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
40 changes: 40 additions & 0 deletions SourceGeneratorToolkit.Test/GeneratorHarnessTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,46 @@
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();

Check warning on line 90 in SourceGeneratorToolkit.Test/GeneratorHarnessTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_SourceGeneratorToolkit&issues=AaHOrSlmNKqA_4jHGYIy&open=AaHOrSlmNKqA_4jHGYIy&pullRequest=79
CSharpCompilation compilation = CompileAsConsumer(tree);
Diagnostic[] errors = [.. compilation.GetDiagnostics().Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)];

Check warning on line 92 in SourceGeneratorToolkit.Test/GeneratorHarnessTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_SourceGeneratorToolkit&issues=AaHOrSlmNKqA_4jHGYIz&open=AaHOrSlmNKqA_4jHGYIz&pullRequest=79

Assert.AreEqual(0, errors.Length, $"{string.Join("\n", errors)}\n{text}");

Check warning on line 94 in SourceGeneratorToolkit.Test/GeneratorHarnessTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.IsEmpty' instead of 'Assert.AreEqual'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_SourceGeneratorToolkit&issues=AaHOrSlmNKqA_4jHGYI1&open=AaHOrSlmNKqA_4jHGYI1&pullRequest=79
Assert.IsTrue(
compilation.Assembly.GetAttributes().Any(attribute => attribute.AttributeClass?.Name == nameof(CLSCompliantAttribute)),
text);
StringAssert.Contains(text, AttributedThingsGenerator.FileComment, text);

Check warning on line 98 in SourceGeneratorToolkit.Test/GeneratorHarnessTests.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_SourceGeneratorToolkit&issues=AaHOrSlmNKqA_4jHGYI0&open=AaHOrSlmNKqA_4jHGYI0&pullRequest=79
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)]
Expand Down
40 changes: 40 additions & 0 deletions SourceGeneratorToolkit.Test/TestGenerators.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,46 @@ protected override void Generate(SourceProductionContext context, ThingsMetadata
}
}

/// <summary>
/// Emits one type per entry in <c>things.json</c> 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.
/// </summary>
internal sealed class AttributedThingsGenerator() : GeneratorBase<ThingsMetadata>("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());
}
}

/// <summary>
/// Reads both metadata files. Exercises <see cref="GeneratorBase"/> directly, which is the shape
/// that used to be reimplemented per generator to get around a single-file base.
Expand Down
31 changes: 29 additions & 2 deletions SourceGeneratorToolkit/GeneratorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -322,21 +322,48 @@ 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)
{
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))
{
Expand Down
Loading