Article series
- Code sharing of the future
- Better experience through Roslyn Analyzers and Code Fixes
- Testing Source Generators, Roslyn Analyzers and Code Fixes
- Increasing Performance through Harnessing of the Memoization
- Adapt Code Generation Based on Project Dependencies
- Using 3rd-Party Libraries
- Using Additional Files ⬅
- High-Level API – ForAttributeWithMetadataName
- Reduction of resource consumption in IDE
- Configuration
- Logging
More information about the Smart Enums and the source code can be found on GitHub:
- Smart Enums
- Source Code (see commits starting with message “Part 7”)
I recommend reading part 6 of the series because this article is based on the results of the previous one.
In the previous article the translations were rendered out of hard-coded JSON. This time, the JSON content should come from a file residing along with the production code.
Creation of an "Additional File"
The (content) files of a project are not automatically available in Source Generators. The files must be tagged as an AdditionalFile
to be provided to a Source Generator. An additional file can be anywhere on the file system accessible by the compiler.
The content of previously hard-coded JSON is moved to a new file Translations.json
into the project DemoConsoleApplication
.
{
"ProductCategory": {
"en": "Product category",
"de": "Produktkategorie"
}
}
The JSON file is included into AdditionalFiles
to contribute to code generation.
...
Accessing Additional Files
The additional files are accessible by AdditionalTextsProvider
and provide the same capabilities as the SyntaxProvider
. All performance considerations described in part 4 are applicable here as well. After filtering the files by name, the file contents are combined with enumTypes
and generators
which leads to a change of the signature of the method GenerateCode
.
[Generator]
public class DemoSourceGenerator : IIncrementalGenerator
{
...
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var enumTypes = context.SyntaxProvider
.CreateSyntaxProvider(CouldBeEnumerationAsync, GetEnumInfoOrNull)
.Where(type => type is not null)!
.Collect()
.SelectMany((enumInfos, _) => enumInfos.Distinct());
var translations = context.AdditionalTextsProvider
.Where(text => text.Path.EndsWith("translations.json",
StringComparison.OrdinalIgnoreCase))
.Select((text, token) => text.GetText(token)?.ToString())
.Where(text => text is not null)!
.Collect();
var generators = context.GetMetadataReferencesProvider()
.SelectMany(static (reference, _) => TryGetCodeGenerator(reference, out var factory)
? ImmutableArray.Create(factory)
: ImmutableArray.Empty)
.Collect();
context.RegisterSourceOutput(enumTypes.Combine(translations)
.Combine(generators),
GenerateCode);
}
...
private static void GenerateCode(
SourceProductionContext context,
((DemoEnumInfo, ImmutableArray), ImmutableArray) args)
{
var ((enumInfo, translationsAsJson), generators) = args;
if (generators.IsDefaultOrEmpty)
return;
var translationsByClassName = GetTranslationsByClassName(context, translationsAsJson);
foreach (var generator in generators.Distinct())
{
if (translationsByClassName is null
|| !translationsByClassName.TryGetValue(enumInfo.Name, out var translations))
{
translations = _noTranslations;
}
var ns = enumInfo.Namespace is null ? null : $"{enumInfo.Namespace}.";
var code = generator.Generate(enumInfo, translations);
if (!String.IsNullOrWhiteSpace(code))
context.AddSource($"{ns}{enumInfo.Name}{generator.FileHintSuffix}.g.cs", code);
}
}
...
Parsing of the JSON contents is delegated to a new method GetTranslationsByClassName
. This method is not just parsing the JSON, but makes a few sanity checks and catches potential parsing errors.
private static Dictionary>?
GetTranslationsByClassName(SourceProductionContext context,
ImmutableArray translationsAsJson)
{
if (translationsAsJson.Length <= 0)
return null;
if (translationsAsJson.Length > 1)
{
var error = Diagnostic.Create(DemoDiagnosticsDescriptors.MultipleTranslationsFound,
null);
context.ReportDiagnostic(error);
}
try
{
return JsonConvert.DeserializeObject<
Dictionary>>(translationsAsJson[0]);
}
catch (Exception ex)
{
var error = Diagnostic.Create(DemoDiagnosticsDescriptors.TranslationDeserializationError,
null,
ex.ToString());
context.ReportDiagnostic(error);
return null;
}
}
MultipleTranslationsFound
and TranslationDeserializationError
are defined in DemoDiagnosticsDescriptors
, which is in the same project as the Source Generator.
public static class DemoDiagnosticsDescriptors
{
...
public static readonly DiagnosticDescriptor MultipleTranslationsFound
= new("DEMO002",
"Multiple translations found",
"Multiple translations found",
"DemoSourceGenerator",
DiagnosticSeverity.Error,
true);
public static readonly DiagnosticDescriptor TranslationDeserializationError
= new("DEMO003",
"Translations could not be deserialized",
"Translations could not be deserialized: {0}",
"DemoSourceGenerator",
DiagnosticSeverity.Error,
true);
}
Summary
Additional files are an excellent way to generate code out of (rather static) files, like JSON or XML.
One of the use cases is translation management. Whether the translations come from an external company or are maintained by the developers themselves, a Source Generator can generate constants instead of using magic strings. That way, the translations become virtually type-safe, and there will be no issue with missing translations anymore.