diff --git a/Coder.Test/Languages/ReservedWordIdentifierTests.cs b/Coder.Test/Languages/ReservedWordIdentifierTests.cs index b6af904..7ae8f81 100644 --- a/Coder.Test/Languages/ReservedWordIdentifierTests.cs +++ b/Coder.Test/Languages/ReservedWordIdentifierTests.cs @@ -7,7 +7,7 @@ namespace ktsu.Coder.Test.Languages; using Microsoft.VisualStudio.TestTools.UnitTesting; /// -/// Compiles and runs what the Rust, C++ and Python generators write for names that are keywords of +/// Compiles and runs what the Rust, C++, Python and C# generators write for names that are keywords of /// the target: a property called Type or Default, which are ordinary C# names, fields, /// parameters and locals called where, virtual, match, delete, /// loop and new, and, for Python, an enumeration member called None. Each name has to come out escaped where it is declared and spelled the @@ -184,6 +184,95 @@ public void Python_ReferenceKeepsTheLiteralWordsAndEscapesTheMember() Assert.DoesNotContain("None_", source, StringComparison.Ordinal, source); } + /// + /// The project the generated C# is built as: a program, so the driver can check what it reads back. + /// + private const string CSharpProject = """ + + + Exe + net10.0 + disable + disable + + + """; + + /// + /// The C# driver. @ is how a C# caller names a keyword, so it reads the escaped names back + /// exactly as a user of the generated type would. + /// + private const string CSharpDriver = """ + public static class Program + { + public static int Main() + { + Holder holder = Holder.make(); + if (holder.@class != 9 || holder.@event != 4) { return 1; } + if (holder.@default != 1) { return 2; } + if (holder.total(5, 6) != 20) { return 3; } + if ((int)Flag.@null != 0 || (int)Flag.All != 1) { return 4; } + if (Globals.@return(7) != 7) { return 5; } + if (Globals.widest() != int.MaxValue) { return 6; } + return 0; + } + } + """; + + /// + /// Tests that C# writes a keyword-named field, property, parameter, local, enumeration member, + /// function and designated member as a verbatim identifier, at their declarations and where they + /// are used, and keeps a built-in type's keyword leading a member access as written. + /// + [TestMethod] + public void CSharp_KeywordNamesCompileAndResolve() + { + if (ToolchainHarness.FindOnPath("--version", "dotnet") is null) + { + Assert.Inconclusive("No dotnet on the path, so nothing was compiled."); + return; + } + + ToolchainHarness.InTemporaryDirectory(directory => + { + string source = new CSharpGenerator().Generate(CSharpTypes()); + File.WriteAllText(Path.Combine(directory, "Holder.csproj"), CSharpProject); + File.WriteAllText(Path.Combine(directory, "Program.cs"), CSharpDriver); + File.WriteAllText(Path.Combine(directory, "Holder.cs"), source); + + (int ran, string output) = ToolchainHarness.Run("dotnet", "run -nologo", directory); + Assert.AreEqual(0, ran, $"C# rejected the generated source, or a keyword-named member read back wrongly (driver check {ran}):{Environment.NewLine}{output}{Environment.NewLine}{source}"); + }); + } + + /// + /// Tests that a C# reference keeps the receiver and the literal words as written while escaping + /// a keyword that names a member. + /// + [TestMethod] + public void CSharp_ReferenceKeepsTheReceiverAndLiteralsAndEscapesTheMember() + { + FunctionDeclaration read = new("read") { ReturnType = "int" }; + read.Body.Add(new VariableDeclaration("unused", "object", new VariableReference("null"))); + read.Body.Add(new VariableDeclaration("empty", "string", new VariableReference("string.Empty"))); + read.Body.Add(new ReturnStatement(new VariableReference("this.base"))); + ClassDeclaration holder = new("Holder"); + holder.Members.Add(new VariableDeclaration("base", "int")); + holder.Members.Add(read); + SourceFile file = new("holder"); + file.Members.Add(holder); + + string source = new CSharpGenerator().Generate(file); + + Assert.Contains("int @base", source, StringComparison.Ordinal, source); + Assert.Contains("return this.@base;", source, StringComparison.Ordinal, source); + Assert.Contains("= null;", source, StringComparison.Ordinal, source); + Assert.Contains("= string.Empty;", source, StringComparison.Ordinal, source); + Assert.DoesNotContain("@this", source, StringComparison.Ordinal, source); + Assert.DoesNotContain("@null", source, StringComparison.Ordinal, source); + Assert.DoesNotContain("@string", source, StringComparison.Ordinal, source); + } + /// /// Tests that a reference keeps a receiver as written and escapes only the plain names after it. /// @@ -266,6 +355,59 @@ private static SourceFile PythonTypes() return file; } + /// + /// Builds a class, an enumeration and functions whose names are C# keywords. + /// + /// The file to generate. + private static SourceFile CSharpTypes() + { + ClassDeclaration holder = new("Holder"); + holder.Members.Add(new VariableDeclaration("class", "int", new LiteralExpression(3)) { Visibility = Visibility.Public }); + holder.Members.Add(new VariableDeclaration("event", "int", new LiteralExpression(4)) { Visibility = Visibility.Public }); + holder.Members.Add(new PropertyDeclaration("default", "int") + { + GetterBody = { new ReturnStatement(new LiteralExpression(1)) }, + }); + + ConstructionExpression built = new(new TypeReference("Holder")); + built.Arguments.Add(new MemberInitialiser("class", new LiteralExpression(9))); + FunctionDeclaration make = new("make") { ReturnType = "Holder", IsStatic = true }; + make.Body.Add(new ReturnStatement(built)); + holder.Members.Add(make); + + FunctionDeclaration total = new("total") { ReturnType = "int" }; + total.Parameters.Add(new Parameter("in", "int")); + total.Parameters.Add(new Parameter("out", "int")); + total.Body.Add(new VariableDeclaration( + "lock", + "int", + new BinaryExpression(new VariableReference("in"), BinaryOperator.Add, new VariableReference("out")))); + total.Body.Add(new VariableDeclaration( + "fixed", + "int", + new BinaryExpression(new VariableReference("lock"), BinaryOperator.Add, new VariableReference("this.class")))); + total.Body.Add(new ReturnStatement(new VariableReference("fixed"))); + holder.Members.Add(total); + + EnumDeclaration flag = new("Flag"); + flag.Members.Add(new EnumMember("null")); + flag.Members.Add(new EnumMember("All")); + + FunctionDeclaration identity = new("return") { ReturnType = "int" }; + identity.Parameters.Add(new Parameter("params", "int")); + identity.Body.Add(new ReturnStatement(new VariableReference("params"))); + + FunctionDeclaration widest = new("widest") { ReturnType = "int" }; + widest.Body.Add(new ReturnStatement(new VariableReference("int.MaxValue"))); + + SourceFile file = new("holder"); + file.Members.Add(holder); + file.Members.Add(flag); + file.Members.Add(identity); + file.Members.Add(widest); + return file; + } + /// /// Builds a struct whose members are all named after a keyword of one target or the other. /// diff --git a/Coder/Languages/CSharpGenerator.cs b/Coder/Languages/CSharpGenerator.cs index febb6cb..5900f04 100644 --- a/Coder/Languages/CSharpGenerator.cs +++ b/Coder/Languages/CSharpGenerator.cs @@ -111,7 +111,7 @@ private void GenerateExpressionOrLeaf(AstNode node, CodeBlocker code) switch (node) { case VariableReference varRef: - code.Write(varRef.Name); + code.Write(SpellReference(varRef.Name)); break; case LiteralExpression stringLit: code.Write($"\"{EscapeString(stringLit.Value ?? string.Empty)}\""); @@ -205,6 +205,68 @@ private void GenerateBinary(BinaryExpression binary, CodeBlocker code) code.Write(")"); } + /// + /// + /// The reserved keywords. The contextual ones — var, value, where, + /// record, nameof and the rest — are keywords only where the grammar expects one + /// and are legal names everywhere else, so they are left alone. + /// + protected override IReadOnlySet ReservedWords { get; } = new HashSet(StringComparer.Ordinal) + { + "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", + "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", + "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", + "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", + "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", + "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", + "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while", + }; + + /// + /// + /// C# has a real escape, the verbatim identifier, so nothing is renamed: default is + /// declared and used as @default, and a caller written in C# names it that way too. + /// + protected override string EscapeIdentifier(string name) + { + Ensure.NotNull(name); + return ReservedWords.Contains(name) ? $"@{name}" : name; + } + + /// + /// + /// this and base name the receiver, and true, false and null + /// are the literals a reference written as text means by them. + /// + protected override bool IsReceiverWord(string word) => word is "this" or "base" or "true" or "false" or "null"; + + /// + /// Spells a reference, escaping its keyword-named segments as their declarations were. + /// + /// The reference's text. + /// The reference as C# writes it. + /// + /// A built-in type's keyword leading a member access — int.MaxValue, + /// string.Empty — names the type, so it is kept as written. On its own it can only be a + /// declared name, and is escaped like one. + /// + private string SpellReference(string reference) + { + int dot = reference.IndexOf('.', StringComparison.Ordinal); + return dot > 0 && BuiltInTypeKeywords.Contains(reference[..dot]) + ? $"{reference[..dot]}.{EscapeReference(reference[(dot + 1)..])}" + : EscapeReference(reference); + } + + /// + /// The keywords that are also the names of built-in types. + /// + private static readonly HashSet BuiltInTypeKeywords = new(StringComparer.Ordinal) + { + "bool", "byte", "char", "decimal", "double", "float", "int", "long", "object", "sbyte", "short", "string", + "uint", "ulong", "ushort", + }; + /// /// /// <<= and >>= take an int count for the same reason a shift does, so their @@ -1024,7 +1086,7 @@ private void WriteListElement(AstNode argument, CodeBlocker code) { if (argument is MemberInitialiser designated) { - code.Write($"{designated.Name} = "); + code.Write($"{EscapeIdentifier(designated.Name ?? string.Empty)} = "); GenerateInternal(designated.Value!, code); return; } @@ -1058,7 +1120,7 @@ private void GenerateEnum(EnumDeclaration enumDecl, CodeBlocker code) using Scope members = new(code); foreach (EnumMember member in enumDecl.Members) { - code.Write(member.Name ?? "Unnamed"); + code.Write(EscapeIdentifier(member.Name ?? "Unnamed")); if (member.Value is not null) { @@ -1086,7 +1148,7 @@ private void GenerateProperty(PropertyDeclaration property, CodeBlocker code) string type = property.Type is TypeReference declared ? MapToCSType(declared) : "object"; string modifiers = property.IsStatic ? " static" : string.Empty; - code.Write($"{SpellVisibility(property.Visibility) ?? DefaultVisibility}{modifiers} {type} {property.Name ?? "Value"}"); + code.Write($"{SpellVisibility(property.Visibility) ?? DefaultVisibility}{modifiers} {type} {EscapeIdentifier(property.Name ?? "Value")}"); // init rather than set where the declaration asked for it: the two differ only in when the // call is legal, and nothing else here has a word for the difference. A readonly struct asks @@ -1175,7 +1237,7 @@ private void GenerateField(FieldDeclaration field, CodeBlocker code) code.Write("readonly "); } - code.Write($"{MapToCSType(field.Type ?? new TypeReference(UnknownTypeName))} {field.Name}"); + code.Write($"{MapToCSType(field.Type ?? new TypeReference(UnknownTypeName))} {EscapeIdentifier(field.Name ?? string.Empty)}"); if (field.InitialValue is not null) { @@ -1375,7 +1437,7 @@ private void WriteInitialisers(FunctionDeclaration function, CodeBlocker code) // value value-initialises the member, as C++'s `x()` does, and `default` is C#'s spelling. foreach (MemberInitialiser initialiser in function.Initialisers) { - code.Write($"this.{initialiser.Name} = "); + code.Write($"this.{EscapeIdentifier(initialiser.Name ?? string.Empty)} = "); if (initialiser.Value is not null) { @@ -1632,7 +1694,7 @@ private static bool IsAbstractClass(ClassDeclaration classDecl) => /// The declaration being emitted. /// The name of the type it belongs to, when it belongs to one. /// The name as C# writes it. - private static string SpellFunctionName(FunctionDeclaration function, string? enclosingType) + private string SpellFunctionName(FunctionDeclaration function, string? enclosingType) { string typeName = enclosingType ?? function.Name ?? "UnnamedType"; @@ -1643,13 +1705,13 @@ private static string SpellFunctionName(FunctionDeclaration function, string? en FunctionKind.Operator => $"operator {function.Name}", FunctionKind.ConversionOperator => $"{(function.IsExplicit ? "explicit" : "implicit")} operator {MapToCSType(function.ReturnType ?? new TypeReference(UnknownTypeName))}", - _ => function.Name ?? "UnnamedFunction", + _ => EscapeIdentifier(function.Name ?? "UnnamedFunction"), }; } private void GenerateParameter(Parameter parameter, CodeBlocker code) { - code.Write($"{MapToCSType(parameter.Type ?? new TypeReference(UnknownTypeName))} {parameter.Name}"); + code.Write($"{MapToCSType(parameter.Type ?? new TypeReference(UnknownTypeName))} {EscapeIdentifier(parameter.Name ?? string.Empty)}"); if (parameter.IsOptional && parameter.DefaultValue is Expression value) { @@ -1864,7 +1926,7 @@ private void GenerateVariableDeclaration(VariableDeclaration varDecl, CodeBlocke code.Write("static "); } - code.Write($"{type} {varDecl.Name}"); + code.Write($"{type} {EscapeIdentifier(varDecl.Name)}"); if (varDecl.InitialValue != null) {