From f8ed6af13d28cb060dffdffe20179dadb4972170 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 07:25:59 +0000 Subject: [PATCH] Keep a file's assembly attributes and comments below C# 10 [patch] The block-scoped namespace path copied only the usings and classes into the template it wrote inside the block, so a file's assembly:/module: attributes, comments and documentation vanished for C# 7.3-9 consumers with no diagnostic. Write them before the namespace block, with the usings too when there are attributes so the attributes can be named through them, as CodeBlocker does for a file-scoped namespace. Fixes #77 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017vfJW5chbrSDfDAQ2U7T5G --- .../GeneratorHarnessTests.cs | 40 +++++++++++++++++++ SourceGeneratorToolkit.Test/TestGenerators.cs | 40 +++++++++++++++++++ SourceGeneratorToolkit/GeneratorBase.cs | 31 +++++++++++++- 3 files changed, 109 insertions(+), 2 deletions(-) diff --git a/SourceGeneratorToolkit.Test/GeneratorHarnessTests.cs b/SourceGeneratorToolkit.Test/GeneratorHarnessTests.cs index ab3f893..fcad62e 100644 --- a/SourceGeneratorToolkit.Test/GeneratorHarnessTests.cs +++ b/SourceGeneratorToolkit.Test/GeneratorHarnessTests.cs @@ -77,6 +77,46 @@ public void ANamespacedSourceFileForAConsumerBeforeCSharp10IsBlockScoped(Languag Assert.IsFalse(text.Contains("namespace Generated;", StringComparison.Ordinal), text); } + [TestMethod] + [DataRow(LanguageVersion.CSharp7_3)] + [DataRow(LanguageVersion.CSharp9)] + [DataRow(LanguageVersion.CSharp10)] + [DataRow(LanguageVersion.Latest)] + public void AFilesAssemblyAttributesAndCommentsAreKeptAtEveryLanguageVersion(LanguageVersion languageVersion) + { + GeneratorHarness harness = new(MetadataDirectory) { LanguageVersion = languageVersion }; + + SyntaxTree tree = harness.Run(new AttributedThingsGenerator()).GeneratedSources[0].SyntaxTree; + string text = tree.GetText().ToString(); + CSharpCompilation compilation = CompileAsConsumer(tree); + Diagnostic[] errors = [.. compilation.GetDiagnostics().Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)]; + + Assert.AreEqual(0, errors.Length, $"{string.Join("\n", errors)}\n{text}"); + Assert.IsTrue( + compilation.Assembly.GetAttributes().Any(attribute => attribute.AttributeClass?.Name == nameof(CLSCompliantAttribute)), + text); + StringAssert.Contains(text, AttributedThingsGenerator.FileComment, text); + Assert.IsNotNull(compilation.GetTypeByMetadataName("Generated.Alpha"), text); + } + + [TestMethod] + [DataRow(LanguageVersion.CSharp7_3)] + [DataRow(LanguageVersion.CSharp9)] + public void AFilesAssemblyAttributesAndCommentsPrecedeABlockScopedNamespace(LanguageVersion languageVersion) + { + GeneratorHarness harness = new(MetadataDirectory) { LanguageVersion = languageVersion }; + + string text = harness.Run(new AttributedThingsGenerator()).GeneratedSources[0].SourceText.ToString(); + int namespaceAt = text.IndexOf("namespace Generated\n{\n", StringComparison.Ordinal); + + Assert.IsGreaterThan(-1, namespaceAt, text); + foreach (string beforeNamespace in new[] { AttributedThingsGenerator.FileComment, "using System;", "[assembly: CLSCompliant(true)]" }) + { + int at = text.IndexOf(beforeNamespace, StringComparison.Ordinal); + Assert.IsTrue(at >= 0 && at < namespaceAt, $"'{beforeNamespace}' should be written before the namespace block.\n{text}"); + } + } + [TestMethod] [DataRow(LanguageVersion.CSharp10)] [DataRow(LanguageVersion.Default)] diff --git a/SourceGeneratorToolkit.Test/TestGenerators.cs b/SourceGeneratorToolkit.Test/TestGenerators.cs index ff5be45..f558105 100644 --- a/SourceGeneratorToolkit.Test/TestGenerators.cs +++ b/SourceGeneratorToolkit.Test/TestGenerators.cs @@ -146,6 +146,46 @@ protected override void Generate(SourceProductionContext context, ThingsMetadata } } +/// +/// Emits one type per entry in things.json into a file that also carries a using, an assembly +/// attribute named through that using, and a file comment: the parts that have to stay outside a +/// block-scoped namespace. +/// +internal sealed class AttributedThingsGenerator() : GeneratorBase("things.json") +{ + internal const string FileComment = "// Generated from things.json"; + + protected override DiagnosticCatalog Diagnostics => TestDiagnostics.Catalog; + + protected override DiagnosticDescriptor MetadataFileMissing => TestDiagnostics.MetadataFileMissing; + + protected override DiagnosticDescriptor MetadataParseFailed => TestDiagnostics.MetadataParseFailed; + + protected override void Generate(SourceProductionContext context, ThingsMetadata metadata, CodeBlocker codeBlocker) + { + SourceFileTemplate file = new() + { + Namespace = "Generated", + Usings = { "System" }, + Attributes = { "assembly: CLSCompliant(true)" }, + Comments = { FileComment }, + }; + + foreach (ThingDefinition thing in metadata.Things) + { + file.Classes.Add(new ClassTemplate + { + Name = thing.Name, + Kind = ktsu.CodeBlocker.Templates.TypeKind.Class, + Keywords = { CSharpKeywords.Public }, + }); + } + + WriteSourceFile(codeBlocker, file, TestDiagnostics.Copyright); + context.AddSource("AttributedThings.g.cs", codeBlocker.ToString()); + } +} + /// /// Reads both metadata files. Exercises directly, which is the shape /// that used to be reimplemented per generator to get around a single-file base. diff --git a/SourceGeneratorToolkit/GeneratorBase.cs b/SourceGeneratorToolkit/GeneratorBase.cs index 11aec34..49db3f6 100644 --- a/SourceGeneratorToolkit/GeneratorBase.cs +++ b/SourceGeneratorToolkit/GeneratorBase.cs @@ -322,14 +322,36 @@ protected static void WriteSourceFile(CodeBlocker codeBlocker, SourceFileTemplat } // ktsu.CodeBlocker only writes file-scoped namespaces, so the block is written here around a - // copy of the template without one. Usings are legal inside a namespace block. + // copy of the template without one. What can't live inside a namespace block is written first, + // from a copy holding nothing else: the file's documentation and comments, and its global + // (assembly:/module:) attributes, which C# only accepts after every using and before the + // namespace. A file with attributes writes its usings there too, so the attributes can be named + // through them, as CodeBlocker does for a file-scoped namespace; otherwise the usings stay + // inside the block. + bool hasAttributes = sourceFileTemplate.Attributes.Count > 0; + SourceFileTemplate outsideNamespace = new() + { + FileName = sourceFileTemplate.FileName, + Documentation = sourceFileTemplate.Documentation, + }; SourceFileTemplate withoutNamespace = new() { FileName = sourceFileTemplate.FileName, }; + + foreach (string comment in sourceFileTemplate.Comments) + { + outsideNamespace.Comments.Add(comment); + } + + foreach (string attribute in sourceFileTemplate.Attributes) + { + outsideNamespace.Attributes.Add(attribute); + } + foreach (string usingDirective in sourceFileTemplate.Usings) { - withoutNamespace.Usings.Add(usingDirective); + (hasAttributes ? outsideNamespace : withoutNamespace).Usings.Add(usingDirective); } foreach (ClassTemplate classTemplate in sourceFileTemplate.Classes) @@ -337,6 +359,11 @@ protected static void WriteSourceFile(CodeBlocker codeBlocker, SourceFileTemplat withoutNamespace.Classes.Add(classTemplate); } + if (hasAttributes || outsideNamespace.Comments.Count > 0 || outsideNamespace.Documentation is not null) + { + codeBlocker.AddSourceFile(outsideNamespace); + } + codeBlocker.WriteLine($"namespace {sourceFileTemplate.Namespace}"); using (new Scope(codeBlocker)) {