// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Immutable;
using System.Text;
namespace Microsoft.DotNet.Cli.Resources.Generator;
/// <summary>
/// Renders a parsed resource file as strongly typed C# source.
/// </summary>
internal static class CSharpResourceRenderer
{
/// <summary>
/// Renders a generated resource class.
/// </summary>
/// <param name="options">The resource naming and generation options.</param>
/// <param name="entries">The validated resource entries to emit.</param>
/// <param name="hasLocalizedSiblings">Whether the resource has localized satellite resources.</param>
/// <param name="features">The features available in the consuming compilation.</param>
/// <returns>The generated C# source.</returns>
internal static string Render(
ResourceGenerationOptions options,
ImmutableArray<ResourceEntry> entries,
bool hasLocalizedSiblings,
CompilationFeatures features)
{
StringBuilder builder = new();
AppendLine(builder, "// <auto-generated/>");
if (features.SupportsNullable)
{
AppendLine(builder, "#nullable enable");
}
AppendLine(builder);
string classIndent = string.Empty;
if (options.NamespaceName is not null)
{
AppendLine(builder, "namespace " + CSharpIdentifier.EscapeNamespace(options.NamespaceName));
AppendLine(builder, "{");
classIndent = " ";
}
string memberIndent = classIndent + " ";
AppendLine(builder, classIndent + "/// <summary>");
AppendLine(builder, classIndent + "/// Provides strongly typed access to string resources.");
AppendLine(builder, classIndent + "/// </summary>");
AppendLine(
builder,
classIndent
+ (ResourceInput.IsTrue(options.Input.Public) ? "public" : "internal")
+ " static partial class "
+ CSharpIdentifier.Escape(options.ClassIdentifier));
AppendLine(builder, classIndent + "{");
RenderCache(builder, memberIndent, entries, features);
AppendLine(builder);
RenderResourceManager(builder, memberIndent, options, hasLocalizedSiblings);
AppendLine(builder);
RenderCulture(builder, memberIndent, features);
AppendLine(builder);
RenderLookupMethods(builder, memberIndent, options, features);
for (int index = 0; index < entries.Length; index++)
{
AppendLine(builder);
RenderProperty(builder, memberIndent, entries[index], index, options, features);
if (ResourceInput.IsTrue(options.Input.EmitFormatMethods)
&& entries[index].EmitFormatMethod
&& entries[index].FormatArguments.HasArguments)
{
AppendLine(builder);
RenderFormatMethod(builder, memberIndent, entries[index], options, features);
}
}
AppendLine(builder, classIndent + "}");
if (options.NamespaceName is not null)
{
AppendLine(builder, "}");
}
return builder.ToString();
}
private static void RenderCache(
StringBuilder builder,
string indent,
ImmutableArray<ResourceEntry> entries,
CompilationFeatures features)
{
string nullableSuffix = features.SupportsNullable ? "?" : string.Empty;
AppendLine(builder, indent + "private sealed class __ResourceCache");
AppendLine(builder, indent + "{");
AppendLine(
builder,
indent
+ " internal __ResourceCache(global::System.Globalization.CultureInfo"
+ nullableSuffix
+ " culture)");
AppendLine(builder, indent + " {");
AppendLine(builder, indent + " Culture = culture;");
AppendLine(builder, indent + " EffectiveCulture = culture ?? global::System.Globalization.CultureInfo.CurrentUICulture;");
AppendLine(builder, indent + " }");
AppendLine(builder);
AppendLine(
builder,
indent
+ " internal global::System.Globalization.CultureInfo"
+ nullableSuffix
+ " Culture { get; }");
AppendLine(builder);
AppendLine(builder, indent + " internal global::System.Globalization.CultureInfo EffectiveCulture { get; }");
for (int index = 0; index < entries.Length; index++)
{
AppendLine(builder);
AppendLine(builder, indent + " internal string" + nullableSuffix + " _value" + index + ";");
}
AppendLine(builder, indent + "}");
}
private static void RenderResourceManager(
StringBuilder builder,
string indent,
ResourceGenerationOptions options,
bool hasLocalizedSiblings)
{
AppendLine(builder, indent + "private static class __ResourceManagerCache");
AppendLine(builder, indent + "{");
AppendLine(builder, indent + " static __ResourceManagerCache()");
AppendLine(builder, indent + " {");
AppendLine(builder, indent + " Instance = CreateResourceManager();");
AppendLine(builder, indent + " }");
AppendLine(builder);
AppendLine(
builder,
indent
+ " internal static global::Microsoft.DotNet.Cli.Resources.StringResourceManager Instance { get; }");
AppendLine(builder, indent + "}");
AppendLine(builder);
AppendLine(
builder,
indent
+ "private static __ResourceCache s_cache = new __ResourceCache(culture: null);");
AppendLine(builder);
AppendLine(builder, indent + "/// <summary>");
AppendLine(builder, indent + "/// Gets the resource manager used by this class.");
AppendLine(builder, indent + "/// </summary>");
AppendLine(
builder,
indent + "public static global::Microsoft.DotNet.Cli.Resources.StringResourceManager ResourceManager =>");
AppendLine(builder, indent + " __ResourceManagerCache.Instance;");
AppendLine(builder);
AppendLine(
builder,
indent + "private static global::Microsoft.DotNet.Cli.Resources.StringResourceManager CreateResourceManager()");
AppendLine(builder, indent + "{");
if (hasLocalizedSiblings)
{
AppendLine(
builder,
indent + " return global::Microsoft.DotNet.Cli.Resources.StringResourceManagerProvider.Create(");
}
else
{
AppendLine(
builder,
indent + " return new global::Microsoft.DotNet.Cli.Resources.StringResourceManager(");
}
AppendLine(builder, indent + " " + ToVerbatimLiteral(options.ResourceName) + ",");
AppendLine(
builder,
indent + " typeof(" + CSharpIdentifier.Escape(options.ClassIdentifier) + ").Assembly);");
AppendLine(builder, indent + "}");
}
private static void RenderCulture(
StringBuilder builder,
string indent,
CompilationFeatures features)
{
string nullableSuffix = features.SupportsNullable ? "?" : string.Empty;
AppendLine(builder, indent + "/// <summary>");
AppendLine(builder, indent + "/// Gets or sets the culture used for resource lookups.");
AppendLine(builder, indent + "/// </summary>");
AppendLine(
builder,
indent
+ "public static global::System.Globalization.CultureInfo"
+ nullableSuffix
+ " Culture");
AppendLine(builder, indent + "{");
AppendLine(builder, indent + " get => global::System.Threading.Volatile.Read(ref s_cache).Culture;");
AppendLine(builder, indent + " set => global::System.Threading.Volatile.Write(ref s_cache, new __ResourceCache(value));");
AppendLine(builder, indent + "}");
AppendLine(builder);
RenderAggressiveInlining(builder, indent, features);
AppendLine(builder, indent + "private static __ResourceCache GetResourceCache()");
AppendLine(builder, indent + "{");
AppendLine(builder, indent + " __ResourceCache cache = global::System.Threading.Volatile.Read(ref s_cache);");
AppendLine(builder, indent + " if (cache.Culture is null && !cache.EffectiveCulture.Equals(global::System.Globalization.CultureInfo.CurrentUICulture))");
AppendLine(builder, indent + " {");
AppendLine(builder, indent + " __ResourceCache replacement = new __ResourceCache(culture: null);");
AppendLine(builder, indent + " global::System.Threading.Interlocked.CompareExchange(ref s_cache, replacement, cache);");
AppendLine(builder, indent + " cache = replacement;");
AppendLine(builder, indent + " }");
AppendLine(builder);
AppendLine(builder, indent + " return cache;");
AppendLine(builder, indent + "}");
}
private static void RenderLookupMethods(
StringBuilder builder,
string indent,
ResourceGenerationOptions options,
CompilationFeatures features)
{
string nullableSuffix = features.SupportsNullable ? "?" : string.Empty;
RenderAggressiveInlining(builder, indent, features);
AppendLine(
builder,
indent
+ "internal static string GetResourceString("
+ "string resourceKey, global::System.Globalization.CultureInfo"
+ nullableSuffix
+ " culture)");
AppendLine(builder, indent + "{");
AppendLine(builder, indent + " string" + nullableSuffix + " value = ResourceManager.GetString(resourceKey, culture);");
AppendLine(builder, indent + " if (value is null)");
AppendLine(builder, indent + " {");
AppendLine(builder, indent + " throw new global::System.Resources.MissingManifestResourceException();");
AppendLine(builder, indent + " }");
AppendLine(builder);
AppendLine(builder, indent + " return value;");
AppendLine(builder, indent + "}");
AppendLine(builder);
RenderAggressiveInlining(builder, indent, features);
if (features.SupportsNullable && features.HasNotNullIfNotNull)
{
AppendLine(
builder,
indent
+ "[return: global::System.Diagnostics.CodeAnalysis.NotNullIfNotNull(\"defaultValue\")]");
}
AppendLine(
builder,
indent
+ "internal static string"
+ nullableSuffix
+ " GetResourceString("
+ "string resourceKey, global::System.Globalization.CultureInfo"
+ nullableSuffix
+ " culture, string"
+ nullableSuffix
+ " defaultValue)");
AppendLine(builder, indent + "{");
AppendLine(builder, indent + " return ResourceManager.GetString(resourceKey, culture) ?? defaultValue;");
AppendLine(builder, indent + "}");
AppendLine(builder);
RenderAggressiveInlining(builder, indent, features);
AppendLine(
builder,
indent
+ "private static string GetCachedResourceString(ref string"
+ nullableSuffix
+ " value, string resourceKey, global::System.Globalization.CultureInfo culture)");
AppendLine(builder, indent + "{");
AppendLine(
builder,
indent + " return value ??= ResourceManager.GetString(resourceKey, culture)");
AppendLine(
builder,
indent + " ?? throw new global::System.Resources.MissingManifestResourceException();");
AppendLine(builder, indent + "}");
if (ResourceInput.IsTrue(options.Input.IncludeDefaultValues))
{
AppendLine(builder);
RenderAggressiveInlining(builder, indent, features);
AppendLine(
builder,
indent
+ "private static string GetCachedResourceString(ref string"
+ nullableSuffix
+ " value, string resourceKey, global::System.Globalization.CultureInfo culture, string defaultValue)");
AppendLine(builder, indent + "{");
AppendLine(
builder,
indent
+ " return value ??= ResourceManager.GetString(resourceKey, culture) ?? defaultValue;");
AppendLine(builder, indent + "}");
}
}
private static void RenderProperty(
StringBuilder builder,
string indent,
ResourceEntry entry,
int index,
ResourceGenerationOptions options,
CompilationFeatures features)
{
RenderSummary(builder, indent, entry.Value);
string escapedIdentifier = CSharpIdentifier.Escape(entry.Identifier);
string resourceKey = entry.Name.Equals(entry.Identifier, StringComparison.Ordinal)
? "nameof(" + escapedIdentifier + ")"
: ToVerbatimLiteral(entry.Name);
bool includeDefaultValues = ResourceInput.IsTrue(options.Input.IncludeDefaultValues);
AppendLine(builder, indent + "public static string " + escapedIdentifier);
AppendLine(builder, indent + "{");
RenderAggressiveInlining(builder, indent + " ", features);
AppendLine(builder, indent + " get");
AppendLine(builder, indent + " {");
AppendLine(builder, indent + " __ResourceCache cache = GetResourceCache();");
AppendLine(builder, indent + " return GetCachedResourceString(");
AppendLine(builder, indent + " ref cache._value" + index + ",");
AppendLine(
builder,
indent
+ " "
+ resourceKey
+ ",");
AppendLine(builder, indent + " cache.EffectiveCulture" + (includeDefaultValues ? "," : ");"));
if (includeDefaultValues)
{
AppendLine(builder, indent + " " + ToVerbatimLiteral(entry.Value) + ");");
}
AppendLine(builder, indent + " }");
AppendLine(builder, indent + "}");
}
private static void RenderFormatMethod(
StringBuilder builder,
string indent,
ResourceEntry entry,
ResourceGenerationOptions options,
CompilationFeatures features)
{
RenderSummary(builder, indent, "Formats " + entry.Name + ".");
using ValueStringBuilder parameters = new(stackalloc char[256]);
using ValueStringBuilder arguments = new(stackalloc char[256]);
for (int index = 0; index < entry.FormatArguments.Arguments.Length; index++)
{
string argument = entry.FormatArguments.Arguments[index];
string parameterName = entry.FormatArguments.UsesNames ? argument : "p" + argument;
if (index > 0)
{
parameters.Append(", ");
arguments.Append(", ");
}
parameters.Append("object");
if (features.SupportsNullable)
{
parameters.Append('?');
}
parameters.Append(' ');
parameters.Append(CSharpIdentifier.Escape(parameterName));
arguments.Append(CSharpIdentifier.Escape(parameterName));
}
string generatedType = GetGlobalTypeName(options);
using ValueStringBuilder propertyExpression = new(stackalloc char[256]);
propertyExpression.Append(generatedType);
propertyExpression.Append('.');
propertyExpression.Append(CSharpIdentifier.Escape(entry.Identifier));
if (entry.FormatArguments.UsesNames)
{
for (int index = 0; index < entry.FormatArguments.Arguments.Length; index++)
{
string argument = entry.FormatArguments.Arguments[index];
propertyExpression.Append(".Replace(");
propertyExpression.Append(ToVerbatimLiteral("{" + argument + "}"));
propertyExpression.Append(", ");
propertyExpression.Append(ToVerbatimLiteral("{" + index + "}"));
propertyExpression.Append(')');
}
}
AppendLine(
builder,
indent
+ "internal static string Format"
+ entry.Identifier
+ "("
+ parameters.ToString()
+ ") =>");
AppendLine(
builder,
indent
+ " global::System.String.Format("
+ generatedType
+ ".Culture, "
+ propertyExpression.ToString()
+ ", "
+ arguments.ToString()
+ ");");
}
private static string GetGlobalTypeName(ResourceGenerationOptions options)
{
return options.NamespaceName is null
? "global::" + CSharpIdentifier.Escape(options.ClassIdentifier)
: "global::"
+ CSharpIdentifier.EscapeNamespace(options.NamespaceName)
+ "."
+ CSharpIdentifier.Escape(options.ClassIdentifier);
}
private static void RenderAggressiveInlining(
StringBuilder builder,
string indent,
CompilationFeatures features)
{
if (features.HasAggressiveInlining)
{
AppendLine(
builder,
indent
+ "[global::System.Runtime.CompilerServices.MethodImpl("
+ "global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]");
}
}
private static void RenderSummary(StringBuilder builder, string indent, string value)
{
AppendLine(builder, indent + "/// <summary>");
AppendLine(builder, indent + "/// " + EscapeXmlComment(NormalizeSummary(value)));
AppendLine(builder, indent + "/// </summary>");
}
private static string NormalizeSummary(string value)
{
using ValueStringBuilder builder = new(stackalloc char[260]);
bool previousWasWhitespace = false;
foreach (char character in value)
{
if (builder.Length >= 256)
{
builder.Append(" ...");
break;
}
if (char.IsWhiteSpace(character))
{
if (!previousWasWhitespace && builder.Length > 0)
{
builder.Append(' ');
}
previousWasWhitespace = true;
continue;
}
if (!char.IsControl(character))
{
builder.Append(character);
previousWasWhitespace = false;
}
}
return builder.ToString().Trim();
}
private static string EscapeXmlComment(string value) =>
value.Replace("&", "&").Replace("<", "<").Replace(">", ">");
private static string ToVerbatimLiteral(string value) =>
"@\"" + value.Replace("\"", "\"\"") + "\"";
private static void AppendLine(StringBuilder builder, string? value = null)
{
if (value is not null)
{
builder.Append(value);
}
builder.Append('\n');
}
}