diff --git a/Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs b/Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs
index 9575727..67d862d 100644
--- a/Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs
+++ b/Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs
@@ -988,4 +988,79 @@ public static int Use() =>
Assert.AreEqual(0, exitCode, $"C# rejected the generated source:{Environment.NewLine}{output}{Environment.NewLine}{source}");
});
}
+
+ ///
+ /// Tests that a private or protected declaration in a position C# forbids the modifier compiles,
+ /// with a note saying what it was given (#428).
+ ///
+ ///
+ /// 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.
+ ///
+ [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);
+ StringAssert.Contains(source, "internal enum E", source);
+ StringAssert.Contains(source, "protected int sides", source);
+ StringAssert.Contains(source, "protected: Prot is internal", source);
+ StringAssert.Contains(source, "protected: helper is internal", source);
+ StringAssert.Contains(source, "protected: m is private", source);
+
+ 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}");
+ });
+ }
}
diff --git a/Coder/Languages/CSharpGenerator.cs b/Coder/Languages/CSharpGenerator.cs
index bd1d387..ab5ccf7 100644
--- a/Coder/Languages/CSharpGenerator.cs
+++ b/Coder/Languages/CSharpGenerator.cs
@@ -739,9 +739,10 @@ private void GenerateClass(ClassDeclaration classDecl, CodeBlocker code)
// 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"] : [],
@@ -787,7 +788,9 @@ .. classDecl.Interfaces.Select(MapToCSType),
}
else if (member is not UsingAlias)
{
+ ClassDeclaration? enclosingOwner = typeMemberOwner;
typeMember = member;
+ typeMemberOwner = classDecl;
try
{
GenerateInternal(member, code);
@@ -795,6 +798,7 @@ .. classDecl.Interfaces.Select(MapToCSType),
finally
{
typeMember = null;
+ typeMemberOwner = enclosingOwner;
}
}
}
@@ -1481,8 +1485,9 @@ private void WriteListElement(AstNode argument, TypeReference? listType, CodeBlo
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)
{
@@ -1522,7 +1527,8 @@ 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} {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
@@ -1593,8 +1599,9 @@ private void WriteAccessorBody(Collection body, CodeBlocker code, TypeR
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
@@ -1868,6 +1875,14 @@ private bool WriteMemberNotes(FunctionDeclaration function, string name, ClassDe
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))
@@ -2147,7 +2162,97 @@ private void WriteFunctionModifiers(FunctionDeclaration function, CodeBlocker co
return function.Kind == FunctionKind.Destructor
? null
- : SpellVisibility(function.Visibility) ?? DefaultVisibility;
+ : SpellAccess(function, function.Visibility, enclosingType);
+ }
+
+ ///
+ /// The type whose members are being written, while one of its members other than a function is.
+ ///
+ ///
+ /// Set beside , 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.
+ ///
+ private ClassDeclaration? typeMemberOwner;
+
+ ///
+ /// Reads the type a declaration is a member of, for a declaration that is not a function.
+ ///
+ /// The declaration being emitted.
+ /// The enclosing type, or null when the declaration is not a member of one.
+ private ClassDeclaration? TypeMemberOwner(AstNode declaration) =>
+ ReferenceEquals(declaration, typeMember) ? typeMemberOwner : null;
+
+ ///
+ /// Spells the access modifier a declaration is written with, where it stands.
+ ///
+ /// The declaration being emitted.
+ /// The visibility it was given.
+ /// The type it is a member of, when it is a member of one.
+ /// The modifier.
+ ///
+ /// What it was given, or public where it was given nothing, unless C# forbids that modifier where
+ /// the declaration stands; see .
+ ///
+ private string SpellAccess(AstNode declaration, Visibility visibility, ClassDeclaration? enclosingType) =>
+ ForbiddenAccess(declaration, visibility, enclosingType) is (_, string allowed)
+ ? allowed
+ : SpellVisibility(visibility) ?? DefaultVisibility;
+
+ ///
+ /// Writes down an access modifier C# forbids where the declaration stands, and what it is instead.
+ ///
+ /// The declaration being emitted.
+ /// The visibility it was given.
+ /// The type it is a member of, when it is a member of one.
+ /// The name it is written under.
+ /// The writer to emit into.
+ 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}");
+ }
+ }
+
+ ///
+ /// Determines whether C# forbids a declaration's access modifier where the declaration stands.
+ ///
+ /// The declaration being emitted.
+ /// The visibility it was given.
+ /// The type it is a member of, when it is a member of one.
+ /// Why the modifier is forbidden and the one written instead, or null when it is allowed.
+ ///
+ /// An AST that is valid for C++ can carry a modifier in a position C# refuses (#428):
+ ///
+ /// - 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.
+ /// - 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.
+ /// - 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.
+ ///
+ /// 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.
+ ///
+ 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;
}
///
@@ -2465,7 +2570,13 @@ private void GenerateVariableDeclaration(VariableDeclaration varDecl, CodeBlocke
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} ");
}