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
75 changes: 75 additions & 0 deletions Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -988,4 +988,79 @@
Assert.AreEqual(0, exitCode, $"C# rejected the generated source:{Environment.NewLine}{output}{Environment.NewLine}{source}");
});
}

/// <summary>
/// Tests that a private or protected declaration in a position C# forbids the modifier compiles,
/// with a note saying what it was given (#428).
/// </summary>
/// <remarks>
/// A type directly in a namespace may be only public or internal (CS1527), the static class that
/// holds a namespace's members may not have protected ones (CS1057), and a struct may not declare
/// a protected member (CS0666). A protected member of a class is allowed, and stays as it was.
/// </remarks>
[TestMethod]
public void ForbiddenAccessModifiers_Compile()
{
if (ToolchainHarness.FindOnPath("--version", "dotnet") is null)
{
Assert.Inconclusive("No dotnet on the path, so nothing was compiled.");
return;
}

NamespaceDeclaration ns = new("Demo");
ns.Members.Add(new ClassDeclaration("Hidden") { Visibility = Visibility.Private });
ns.Members.Add(new ClassDeclaration("Prot") { Visibility = Visibility.Protected });
ns.Members.Add(new EnumDeclaration("E") { Visibility = Visibility.Private });
ns.Members.Add(new FieldDeclaration("counter", "int") { Visibility = Visibility.Protected });

FunctionDeclaration helper = new("helper") { ReturnType = "int", Visibility = Visibility.Protected };
helper.Body.Add(new ReturnStatement(Literal.Number(1)));
ns.Members.Add(helper);

ClassDeclaration point = new("S") { Kind = TypeDeclarationKind.Struct };
point.Members.Add(new PropertyDeclaration("P", "int") { Visibility = Visibility.Protected, HasSetter = true });
point.Members.Add(new FieldDeclaration("id", "int") { Visibility = Visibility.Protected });
point.Members.Add(new VariableDeclaration("v", "int", Literal.Number(0)) { Visibility = Visibility.Protected });
point.Members.Add(new ClassDeclaration("Nested") { Visibility = Visibility.Protected });
FunctionDeclaration m = new("m") { ReturnType = "int", Visibility = Visibility.Protected };
m.Body.Add(new ReturnStatement(new VariableReference("id")));
point.Members.Add(m);
ns.Members.Add(point);

ClassDeclaration shape = new("Shape") { Visibility = Visibility.Public };
shape.Members.Add(new FieldDeclaration("sides", "int") { Visibility = Visibility.Protected });
ns.Members.Add(shape);

SourceFile file = new("Generated");
file.Members.Add(ns);

string source = new CSharpGenerator().Generate(file);
StringAssert.Contains(source, "internal class Hidden", source);

Check warning on line 1038 in Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.Contains' instead of 'StringAssert.Contains'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaGquksuLvOKsBi_Do5x&open=AaGquksuLvOKsBi_Do5x&pullRequest=455
StringAssert.Contains(source, "internal enum E", source);

Check warning on line 1039 in Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.Contains' instead of 'StringAssert.Contains'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaGquksuLvOKsBi_Do5y&open=AaGquksuLvOKsBi_Do5y&pullRequest=455
StringAssert.Contains(source, "protected int sides", source);

Check warning on line 1040 in Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.Contains' instead of 'StringAssert.Contains'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaGquksuLvOKsBi_Do5z&open=AaGquksuLvOKsBi_Do5z&pullRequest=455
StringAssert.Contains(source, "protected: Prot is internal", source);

Check warning on line 1041 in Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.Contains' instead of 'StringAssert.Contains'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaGquksuLvOKsBi_Do50&open=AaGquksuLvOKsBi_Do50&pullRequest=455
StringAssert.Contains(source, "protected: helper is internal", source);

Check warning on line 1042 in Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.Contains' instead of 'StringAssert.Contains'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaGquksuLvOKsBi_Do51&open=AaGquksuLvOKsBi_Do51&pullRequest=455
StringAssert.Contains(source, "protected: m is private", source);

Check warning on line 1043 in Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.Contains' instead of 'StringAssert.Contains'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaGquksuLvOKsBi_Do52&open=AaGquksuLvOKsBi_Do52&pullRequest=455

ToolchainHarness.InTemporaryDirectory(directory =>
{
File.WriteAllText(Path.Combine(directory, "Generated.csproj"), Project);
File.WriteAllText(
Path.Combine(directory, "AccessDriver.cs"),
"""
public static class AccessDriver
{
public static int Use() =>
global::Demo.Demo.helper()
+ global::Demo.Demo.counter
+ (new global::Demo.Hidden() is null ? 0 : 1)
+ (int)default(global::Demo.E);
}
""");
File.WriteAllText(Path.Combine(directory, "Generated.cs"), source);

(int exitCode, string output) = ToolchainHarness.Run("dotnet", "build -nologo", directory);
Assert.AreEqual(0, exitCode, $"C# rejected the generated source:{Environment.NewLine}{output}{Environment.NewLine}{source}");
});
}
}
123 changes: 117 additions & 6 deletions Coder/Languages/CSharpGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -223,13 +223,13 @@
/// </remarks>
protected override IReadOnlySet<string> ReservedWords { get; } = new HashSet<string>(StringComparer.Ordinal)
{
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const",

Check warning on line 226 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'abstract' 4 times.
"continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit",

Check warning on line 227 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'double' 5 times.
"extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int",

Check warning on line 228 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'float' 5 times.
"interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out",

Check warning on line 229 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'object' 4 times.
"override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed",
"short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try",

Check warning on line 231 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'string' 5 times.
"typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while",

Check warning on line 232 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'ulong' 4 times.
"field",
};

Expand Down Expand Up @@ -739,9 +739,10 @@
// the type makes about itself, then the permission to declare the rest of it elsewhere, then
// what kind of type it is. A record is written before the keyword rather than instead of it,
// which is what makes `record struct` reachable.
WriteForbiddenAccessNote(classDecl, classDecl.Visibility, TypeMemberOwner(classDecl), classDecl.Name ?? "UnnamedClass", code);
string[] modifiers =
[
SpellVisibility(classDecl.Visibility) ?? DefaultVisibility,
SpellAccess(classDecl, classDecl.Visibility, TypeMemberOwner(classDecl)),
.. IsAbstractClass(classDecl) ? (string[])["abstract"] : [],
.. isReadOnlyStruct ? (string[])["readonly"] : [],
.. classDecl.IsPartial ? (string[])["partial"] : [],
Expand Down Expand Up @@ -787,14 +788,17 @@
}
else if (member is not UsingAlias)
{
ClassDeclaration? enclosingOwner = typeMemberOwner;
typeMember = member;
typeMemberOwner = classDecl;
try
{
GenerateInternal(member, code);
}
finally
{
typeMember = null;
typeMemberOwner = enclosingOwner;
}
}
}
Expand Down Expand Up @@ -1481,8 +1485,9 @@
private void GenerateEnum(EnumDeclaration enumDecl, CodeBlocker code)
{
WritePreamble(enumDecl, code, PreambleSite.Enum);
WriteForbiddenAccessNote(enumDecl, enumDecl.Visibility, TypeMemberOwner(enumDecl), enumDecl.Name ?? "UnnamedEnum", code);

code.Write($"{SpellVisibility(enumDecl.Visibility) ?? DefaultVisibility} enum {enumDecl.Name ?? "UnnamedEnum"}");
code.Write($"{SpellAccess(enumDecl, enumDecl.Visibility, TypeMemberOwner(enumDecl))} enum {enumDecl.Name ?? "UnnamedEnum"}");

if (enumDecl.UnderlyingType is TypeReference underlying)
{
Expand Down Expand Up @@ -1522,7 +1527,8 @@
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} {EscapeIdentifier(property.Name ?? "Value")}");
WriteForbiddenAccessNote(property, property.Visibility, TypeMemberOwner(property), property.Name ?? "Value", code);
code.Write($"{SpellAccess(property, property.Visibility, TypeMemberOwner(property))}{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
Expand Down Expand Up @@ -1593,8 +1599,9 @@
private void GenerateField(FieldDeclaration field, CodeBlocker code)
{
WritePreamble(field, code, PreambleSite.Field);
WriteForbiddenAccessNote(field, field.Visibility, TypeMemberOwner(field), field.Name ?? "unnamed", code);

code.Write($"{SpellVisibility(field.Visibility) ?? DefaultVisibility} ");
code.Write($"{SpellAccess(field, field.Visibility, TypeMemberOwner(field))} ");

// static readonly rather than const: const is legal only for the primitives and strings,
// and a generated table is neither. The two mean the same thing to a reader and only one of
Expand Down Expand Up @@ -1868,6 +1875,14 @@
return false;
}

// The access modifier is said where C# allows it, as SpellAccessModifier spells it (#428).
if (!IsOperator(function)
&& function.Kind != FunctionKind.Destructor
&& OverrideObstacle(function, enclosingType) != OverrideObstacleKind.Private)
{
WriteForbiddenAccessNote(function, function.Visibility, enclosingType, name, code);
}

// C++ lets a member operator be private, protected or virtual; a C# operator is public and
// static and nothing else, so what it asked for is written down rather than lost.
if (IsOperator(function))
Expand Down Expand Up @@ -2147,7 +2162,97 @@

return function.Kind == FunctionKind.Destructor
? null
: SpellVisibility(function.Visibility) ?? DefaultVisibility;
: SpellAccess(function, function.Visibility, enclosingType);
}

/// <summary>
/// The type whose members are being written, while one of its members other than a function is.
/// </summary>
/// <remarks>
/// Set beside <see cref="typeMember"/>, and restored rather than cleared, so a member of a nested
/// type is read against the nested type and the members after it against the outer one.
/// </remarks>
private ClassDeclaration? typeMemberOwner;

/// <summary>
/// Reads the type a declaration is a member of, for a declaration that is not a function.
/// </summary>
/// <param name="declaration">The declaration being emitted.</param>
/// <returns>The enclosing type, or null when the declaration is not a member of one.</returns>
private ClassDeclaration? TypeMemberOwner(AstNode declaration) =>
ReferenceEquals(declaration, typeMember) ? typeMemberOwner : null;

/// <summary>
/// Spells the access modifier a declaration is written with, where it stands.
/// </summary>
/// <param name="declaration">The declaration being emitted.</param>
/// <param name="visibility">The visibility it was given.</param>
/// <param name="enclosingType">The type it is a member of, when it is a member of one.</param>
/// <returns>The modifier.</returns>
/// <remarks>
/// What it was given, or public where it was given nothing, unless C# forbids that modifier where
/// the declaration stands; see <see cref="ForbiddenAccess"/>.
/// </remarks>
private string SpellAccess(AstNode declaration, Visibility visibility, ClassDeclaration? enclosingType) =>
ForbiddenAccess(declaration, visibility, enclosingType) is (_, string allowed)
? allowed
: SpellVisibility(visibility) ?? DefaultVisibility;

/// <summary>
/// Writes down an access modifier C# forbids where the declaration stands, and what it is instead.
/// </summary>
/// <param name="declaration">The declaration being emitted.</param>
/// <param name="visibility">The visibility it was given.</param>
/// <param name="enclosingType">The type it is a member of, when it is a member of one.</param>
/// <param name="name">The name it is written under.</param>
/// <param name="code">The writer to emit into.</param>
private void WriteForbiddenAccessNote(AstNode declaration, Visibility visibility, ClassDeclaration? enclosingType, string name, CodeBlocker code)
{
if (ForbiddenAccess(declaration, visibility, enclosingType) is (string reason, string allowed))
{
WriteInexpressible(code, $"{SpellVisibility(visibility)}: {name} is {allowed}, because {reason}");
}
}

/// <summary>
/// Determines whether C# forbids a declaration's access modifier where the declaration stands.
/// </summary>
/// <param name="declaration">The declaration being emitted.</param>
/// <param name="visibility">The visibility it was given.</param>
/// <param name="enclosingType">The type it is a member of, when it is a member of one.</param>
/// <returns>Why the modifier is forbidden and the one written instead, or null when it is allowed.</returns>
/// <remarks>
/// An AST that is valid for C++ can carry a modifier in a position C# refuses (#428):
/// <list type="bullet">
/// <item>A type in a namespace or file may be only public or internal (CS1527). A private or
/// protected one is internal, C#'s closest assembly-local access.</item>
/// <item>A member of a namespace or file is held in a static class, which cannot have protected
/// members (CS1057). It is internal, so the types beside it in the namespace still reach it.</item>
/// <item>A struct cannot be derived from, so a protected member of one (CS0666) is private, which is
/// all protected means where there can be no derived type.</item>
/// </list>
/// Members of classes and interfaces are written as they were given. An operator is public whatever
/// it was given, and says so where it is written.
/// </remarks>
private (string Reason, string Allowed)? ForbiddenAccess(AstNode declaration, Visibility visibility, ClassDeclaration? enclosingType)
{
bool isType = declaration is ClassDeclaration or EnumDeclaration;
if (isType && enclosingType is null && visibility is Visibility.Private or Visibility.Protected)
{
return ("C# declares a type outside a type only public or internal", "internal");
}

if (ReferenceEquals(declaration, heldMember) && visibility == Visibility.Protected)
{
return ("the static class C# holds it in cannot have protected members", "internal");
}

if (enclosingType?.Kind == TypeDeclarationKind.Struct && visibility == Visibility.Protected)
{
return ("a C# struct cannot be derived from", "private");
}

return null;
}

/// <summary>
Expand Down Expand Up @@ -2465,7 +2570,13 @@
WriteInexpressible(code, $"{varDecl.Name}: C# infers no type for a list without one, and nothing here says one");
type = UnknownTypeName;
}
if ((isField ? SpellVisibility(varDecl.Visibility) ?? DefaultVisibility : SpellVisibility(varDecl.Visibility)) is string modifier)

if (isField)
{
WriteForbiddenAccessNote(varDecl, varDecl.Visibility, TypeMemberOwner(varDecl), varDecl.Name, code);
}

if ((isField ? SpellAccess(varDecl, varDecl.Visibility, TypeMemberOwner(varDecl)) : SpellVisibility(varDecl.Visibility)) is string modifier)
{
code.Write($"{modifier} ");
}
Expand Down
Loading