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
22 changes: 22 additions & 0 deletions src/Nullean.Argh.Generator/CliParserGenerator.ParameterModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1282,6 +1282,18 @@ private static bool ComputeRequired(IParameterSymbol p, BoolSpecialKind bs)
if (v is null)
return p.Type.IsReferenceType ? "null" : "default";

// C# converts only the literal 0 to an enum implicitly, so an enum default names its member, or casts
if (EnumTypeOf(p.Type) is { } enumType)
{
var enumFq = enumType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
foreach (var member in enumType.GetMembers())
{
if (member is IFieldSymbol { HasConstantValue: true } field && Equals(field.ConstantValue, v))
return enumFq + "." + field.Name;
}
return $"({enumFq})({SymbolDisplay.FormatPrimitive(v, quoteStrings: false, useHexadecimalNumbers: false)})";
}

return v switch
{
string s => SymbolDisplay.FormatPrimitive(s, quoteStrings: true, useHexadecimalNumbers: false),
Expand All @@ -1292,6 +1304,16 @@ private static bool ComputeRequired(IParameterSymbol p, BoolSpecialKind bs)
};
}

private static INamedTypeSymbol? EnumTypeOf(ITypeSymbol type) => type switch
{
INamedTypeSymbol { TypeKind: TypeKind.Enum } e => e,
INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T } n when n.TypeArguments[0] is INamedTypeSymbol
{
TypeKind: TypeKind.Enum
} e => e,
_ => null,
};

private static string SafeLocalName(string name)
{
var k = Naming.ToCliLongName(name).Replace("-", "_");
Expand Down
67 changes: 67 additions & 0 deletions tests/Nullean.Argh.Generator.Tests/EnumDefaultTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System.Text;
using AwesomeAssertions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;

namespace Nullean.Argh.Generator.Tests;

/// <summary>
/// A command parameter whose default is an enum member must compile whatever that member's value is: C# converts only
/// the literal <c>0</c> to an enum implicitly (https://github.com/nullean/argh/issues/75).
/// </summary>
public class EnumDefaultTests
{
private static string Source(string parameter) =>
$$"""
using Nullean.Argh;
using Nullean.Argh.Builder;

namespace App
{
public enum OneBased { None = 1, A = 2 }

public static class Handlers
{
public static void Run({{parameter}}) { }
}

public static class CliRegistration
{
public static void Configure(IArghRootBuilder app) => app.Map("run", Handlers.Run);
}
}
""";

private static List<Diagnostic> GeneratedCompilationErrors(string source)
{
var tpaPaths = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator);
var references = tpaPaths.Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList();
references.Add(MetadataReference.CreateFromFile(typeof(Nullean.Argh.Builder.IArghBuilder).Assembly.Location));
references.Add(MetadataReference.CreateFromFile(typeof(Nullean.Argh.ArghApp).Assembly.Location));

var tree = CSharpSyntaxTree.ParseText(SourceText.From(source, Encoding.UTF8), path: "App.cs");
var compilation = CSharpCompilation.Create(
"App",
[tree],
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)
);

var driver = CSharpGeneratorDriver.Create(new CliParserGenerator());
driver.RunGeneratorsAndUpdateCompilation(compilation, out var output, out _);
return output.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToList();
}

[Test]
[Arguments("OneBased level = OneBased.None")]
[Arguments("OneBased level = OneBased.A")]
[Arguments("OneBased? level = OneBased.A")]
[Arguments("OneBased level = (OneBased)7")]
public void Default_of_a_non_zero_enum_member_compiles(string parameter)
{
var errors = GeneratedCompilationErrors(Source(parameter));

errors.Should().BeEmpty(string.Join(Environment.NewLine, errors));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
<ItemGroup>
<ProjectReference Include="..\..\src\Nullean.Argh.Generator\Nullean.Argh.Generator.csproj" />
<ProjectReference Include="..\..\src\Nullean.Argh.Interfaces\Nullean.Argh.Interfaces.csproj" />
<!-- the runtime the generated code calls, so a test can compile it -->
<ProjectReference Include="..\..\src\Nullean.Argh.Core\Nullean.Argh.Core.csproj" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" />
</ItemGroup>

Expand Down
Loading