Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
- name: Build
run: dotnet build --configuration Release --no-restore
- name: Test
run: dotnet test --configuration Release --no-build --logger trx --results-directory TestResults --collect:"XPlat Code Coverage"
run: dotnet test --configuration Release --no-build --report-trx --results-directory TestResults --coverage
- name: Upload test results
uses: actions/upload-artifact@v4
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
- name: Build
run: dotnet build --configuration Release --no-restore
- name: Test
run: dotnet test --configuration Release --no-build --logger trx --results-directory TestResults --collect:"XPlat Code Coverage"
run: dotnet test --configuration Release --no-build --report-trx --results-directory TestResults --coverage
- name: Upload test results
uses: actions/upload-artifact@v4
with:
Expand Down
23 changes: 9 additions & 14 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ItemGroup>
<PackageVersion Include="coverlet.collector" Version="6.0.2" />
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="8.0.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.11.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.11.0" />
<PackageVersion Include="MSTest.TestAdapter" Version="3.5.2" />
<PackageVersion Include="MSTest.TestFramework" Version="3.5.2" />
<PackageVersion Include="System.IO.Pipelines" Version="8.0.0" />
<PackageVersion Include="System.IO.Ports" Version="8.0.0" />
<PackageVersion Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
<PackageVersion Include="System.Text.Encodings.Web" Version="8.0.0" />
<PackageVersion Include="System.Text.Json" Version="8.0.4" />
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="10.0.2" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="5.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.2" />
<PackageVersion Include="System.IO.Ports" Version="10.0.2" />
<PackageVersion Include="System.Runtime.CompilerServices.Unsafe" Version="6.1.2" />
<PackageVersion Include="System.Text.Encodings.Web" Version="10.0.2" />
<PackageVersion Include="System.Text.Json" Version="10.0.2" />
</ItemGroup>
<ItemGroup>
<GlobalPackageReference Include="Nerdbank.GitVersioning" Version="3.6.143" />
<GlobalPackageReference Include="Nerdbank.GitVersioning" Version="3.9.50" />
</ItemGroup>
</Project>
5 changes: 3 additions & 2 deletions ZWave.NET.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.31911.260
# Visual Studio Version 18
VisualStudioVersion = 18.4.11426.133
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{DDBF7DBF-FA50-4311-A52A-8AC978CD417A}"
EndProject
Expand All @@ -15,6 +15,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
.gitignore = .gitignore
Directory.Build.props = Directory.Build.props
Directory.Build.rsp = Directory.Build.rsp
Directory.Packages.props = Directory.Packages.props
global.json = global.json
LICENSE = LICENSE
NuGet.config = NuGet.config
Expand Down
14 changes: 10 additions & 4 deletions global.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
{
"sdk": {
"version": "8.0.201",
"rollForward": "latestFeature"
}
"sdk": {
"version": "10.0.102",
"rollForward": "latestFeature"
},
"msbuild-sdks": {
"MSTest.Sdk": "4.0.2"
},
"test": {
"runner": "Microsoft.Testing.Platform"
}
}
154 changes: 68 additions & 86 deletions src/ZWave.BuildTools/CommandClassFactoryGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
using System.Text;
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace ZWave.BuildTools;

[Generator]
public sealed class CommandClassFactoryGenerator : ISourceGenerator
public sealed class CommandClassFactoryGenerator : IIncrementalGenerator
{
private static readonly DiagnosticDescriptor DuplicateCommandClassId = new DiagnosticDescriptor(
id: "ZWAVE001",
Expand All @@ -15,9 +16,7 @@ public sealed class CommandClassFactoryGenerator : ISourceGenerator
DiagnosticSeverity.Error,
isEnabledByDefault: true);

public void Initialize(GeneratorInitializationContext context)
{
const string attributeSource = @"
private const string AttributeSource = @"
namespace ZWave.CommandClasses;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
Expand All @@ -29,21 +28,71 @@ public CommandClassAttribute(CommandClassId id)
=> (Id) = (id);
}
";
context.RegisterForPostInitialization((pi) => pi.AddSource("CommandClassAttribute.generated.cs", attributeSource));
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
}

public void Execute(GeneratorExecutionContext context)
public void Initialize(IncrementalGeneratorInitializationContext context)
{
SyntaxReceiver syntaxReceiver = (SyntaxReceiver)context.SyntaxReceiver!;
context.RegisterPostInitializationOutput(static ctx =>
ctx.AddSource("CommandClassAttribute.generated.cs", AttributeSource));

// Find all classes with [CommandClass] and extract (CommandClassId, ClassName)
IncrementalValuesProvider<(string CommandClassId, string ClassName)> commandClasses = context.SyntaxProvider
.ForAttributeWithMetadataName(
"ZWave.CommandClasses.CommandClassAttribute",
predicate: static (node, _) => node is ClassDeclarationSyntax,
transform: static (ctx, _) =>
{
string className = ((ClassDeclarationSyntax)ctx.TargetNode).Identifier.ToString();

// Get the attribute argument as "CommandClassId.EnumMemberName"
foreach (AttributeData attr in ctx.Attributes)
{
if (attr.ConstructorArguments.Length > 0)
{
TypedConstant arg = attr.ConstructorArguments[0];
if (arg.Type?.TypeKind == TypeKind.Enum)
{
// Get enum member name from the constant value
string? memberName = arg.Type.GetMembers()
.OfType<IFieldSymbol>()
.FirstOrDefault(f => f.HasConstantValue && Equals(f.ConstantValue, arg.Value))
?.Name;

foreach (Diagnostic diagnostic in syntaxReceiver.DiagnosticsToReport)
if (memberName != null)
{
return ($"CommandClassId.{memberName}", className);
}
}
}
}

return default;
})
.Where(static x => x.Item1 != null!);

IncrementalValueProvider<ImmutableArray<(string CommandClassId, string ClassName)>> collected = commandClasses.Collect();

context.RegisterSourceOutput(collected, static (spc, items) =>
{
context.ReportDiagnostic(diagnostic);
}
var idToType = new Dictionary<string, string>(StringComparer.Ordinal);

foreach ((string commandClassId, string className) in items)
{
if (idToType.ContainsKey(commandClassId))
{
spc.ReportDiagnostic(Diagnostic.Create(DuplicateCommandClassId, Location.None, commandClassId));
}
else
{
idToType.Add(commandClassId, className);
}
}

Dictionary<string, string> commandClassIdToType = syntaxReceiver.CommandClassIdToType;
spc.AddSource("CommandClassFactory.generated.cs", GenerateSource(idToType));
});
}

private static string GenerateSource(Dictionary<string, string> idToType)
{
var sb = new StringBuilder();
sb.Append(@"
#nullable enable
Expand All @@ -56,18 +105,9 @@ internal static class CommandClassFactory
{
");

foreach (KeyValuePair<string, string> pair in commandClassIdToType)
foreach (KeyValuePair<string, string> pair in idToType)
{
string commandClassId = pair.Key;
string commandClassType = pair.Value;

// { CommandClassId.Basic, (info, driver, node) => new BasicCommandClass(info, driver, node) },
sb.Append(" { ");
sb.Append(commandClassId);
sb.Append(", (info, driver, node) => new ");
sb.Append(commandClassType);
sb.Append("(info, driver, node) },");
sb.AppendLine();
sb.AppendLine($" {{ {pair.Key}, (info, driver, node) => new {pair.Value}(info, driver, node) }},");
}

sb.Append(@" };
Expand All @@ -76,18 +116,9 @@ internal static class CommandClassFactory
{
");

foreach (KeyValuePair<string, string> pair in commandClassIdToType)
foreach (KeyValuePair<string, string> pair in idToType)
{
string commandClassId = pair.Key;
string commandClassType = pair.Value;

// { typeof(BasicCommandClass), CommandClassId.Basic },
sb.Append(" { typeof(");
sb.Append(commandClassType);
sb.Append("), ");
sb.Append(commandClassId);
sb.Append(" },");
sb.AppendLine();
sb.AppendLine($" {{ typeof({pair.Value}), {pair.Key} }},");
}

sb.Append(@" };
Expand All @@ -102,55 +133,6 @@ public static CommandClassId GetCommandClassId<TCommandClass>()
=> TypeToIdMap[typeof(TCommandClass)];
}
");

context.AddSource("CommandClassFactory.generated.cs", sb.ToString());
return sb.ToString();
}

private sealed class SyntaxReceiver : ISyntaxReceiver
{
public Dictionary<string, string> CommandClassIdToType { get; } = new Dictionary<string, string>(StringComparer.Ordinal);

public List<Diagnostic> DiagnosticsToReport { get; } = new List<Diagnostic>();

public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is ClassDeclarationSyntax classDeclarationSyntax)
{
foreach (AttributeListSyntax attributeListSyntax in classDeclarationSyntax.AttributeLists)
{
foreach (AttributeSyntax attributeSyntax in attributeListSyntax.Attributes)
{
var attributeName = attributeSyntax.Name.ToString();
if (attributeName == "CommandClass"
|| attributeName == "CommandClassAttribute")
{
if (attributeSyntax.ArgumentList != null
&& attributeSyntax.ArgumentList.Arguments.Count > 0)
{
AttributeArgumentSyntax attributeArgumentSyntax = attributeSyntax.ArgumentList.Arguments[0];
string attributeArgumentValue = attributeArgumentSyntax.ToString();
if (attributeArgumentValue.StartsWith("CommandClassId."))
{
if (CommandClassIdToType.ContainsKey(attributeArgumentValue))
{
var diagnostic = Diagnostic.Create(
DuplicateCommandClassId,
attributeSyntax.GetLocation(),
attributeArgumentValue);
DiagnosticsToReport.Add(diagnostic);
}
else
{
CommandClassIdToType.Add(attributeArgumentValue, classDeclarationSyntax.Identifier.ToString());
}
}
}
}
}
}
}
}
}

private record struct CommandClassMetadata(string CommandClassId, string CommandClassType);
}
Loading