Files
StockSharp/Localization.Generator/LocalizedStringsGenerator.cs
T
mika@stocksharp.com e3a115b7b1 Let a language be read while another is being registered
The language registry kept a dictionary of codes to indices beside a list of
translations, and mutated both without synchronisation while every localized
string in the product read them. Removing a language renumbered the rest, so a
reader could take an index under one numbering and read the list under another -
not a torn read but a wrong answer, one language's text returned under another's
code, and an index out of range when the list had shrunk.

A language is now addressed by its code rather than by a position, so there is
nothing left to renumber. Writers build the next map and publish it with a
single assignment under a lock, never touching a map that has been published;
a reader takes one snapshot and reads it to the end, so resolving the active
language and translating against it can no longer disagree. Lookups stay free of
locks and of interlocked operations, which matters on a path every string takes.

The generated properties had the same defect one floor up: each cached its text
in a field that ResetCache set back to null, so a reader that began before a
language changed could write its stale word into the cache afterwards and leave
it there for good. The cache is now an object that is replaced whole, published
after the registry, so a reader that sees the new cache sees the new registry
too.

Four tests were leaving process-wide registrations behind them for whatever ran
next, and two of those ran in the parallel phase.
2026-09-19 14:00:02 +03:00

146 lines
4.3 KiB
C#

namespace StockSharp.Localization;
using System;
using System.Globalization;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
[Generator]
public class LocalizedStringsGenerator : IIncrementalGenerator
{
// Members the emitted class declares on its own, which no resource may take.
private static readonly string[] _ownMembers = ["ResetCache", "_stringsFileName", "Cache", "_cache"];
void IIncrementalGenerator.Initialize(IncrementalGeneratorInitializationContext initContext)
{
//System.Diagnostics.Debugger.Launch();
const string stringsFileName = "strings.json";
var json = initContext
.AdditionalTextsProvider
.Where(static file => Path.GetFileName(file.Path).Equals(stringsFileName, StringComparison.InvariantCultureIgnoreCase))
.Select((text, cancellationToken) => text.GetText(cancellationToken).ToString());
initContext.RegisterSourceOutput(json, static (spc, content) =>
{
var items = new StringBuilder();
var cached = new StringBuilder();
var dict = new Dictionary<string, string>();
using var doc = JsonDocument.Parse(content);
{
foreach (var property in doc.RootElement.EnumerateObject())
{
if (dict.ContainsKey(property.Name))
throw new InvalidOperationException(property.Name);
dict.Add(property.Name, property.Value.GetString());
}
}
var taken = new HashSet<string>(_ownMembers, StringComparer.Ordinal);
foreach (var p in dict)
{
var prop = GetMemberName(p.Key, taken);
var key = SymbolDisplay.FormatLiteral(p.Key, true);
var xmlComment = ToXmlComment(p.Value);
items.AppendLine($@" /// <summary>
{xmlComment}
/// </summary>
public const string {prop}Key = {key};
/// <summary>
{xmlComment}
/// </summary>
public static string {prop} => _cache.{prop} ??= GetString({prop}Key);").AppendLine();
cached.AppendLine($"\t\tpublic string {prop};");
}
spc.AddSource("LocalizedStrings_Items.cs", $@"// <auto-generated />
namespace StockSharp.Localization;
partial class LocalizedStrings
{{
private const string _stringsFileName = ""{stringsFileName}"";
// The text every property has answered with since the language was last chosen. A property computes
// its text before it stores it, and the language can change in between, so the whole cache is
// replaced rather than emptied: a reader that started earlier fills the object it took and can
// leave nothing behind in the one the next reader takes.
private sealed class Cache
{{
{cached}
}}
private static volatile Cache _cache = new();
{items}
/// <summary>
/// Reset cached fields state.
/// </summary>
public static void ResetCache()
=> _cache = new();
}}");
});
}
// A resource key is written by whoever adds the string: it can be a C# keyword, start with a digit
// or carry a dot. The member is named after it as closely as C# allows, and a name already spoken
// for - the key constant of another resource, for one - is numbered so every resource keeps a
// member of its own.
private static string GetMemberName(string key, HashSet<string> taken)
{
var name = new StringBuilder(key.Length);
foreach (var c in key)
name.Append(SyntaxFacts.IsIdentifierPartCharacter(c) ? c : '_');
if (name.Length == 0 || !SyntaxFacts.IsIdentifierStartCharacter(name[0]) || SyntaxFacts.GetKeywordKind(name.ToString()) != SyntaxKind.None)
name.Insert(0, '_');
var baseName = name.ToString();
var candidate = baseName;
for (var i = 2; !IsFree(candidate, taken); i++)
candidate = baseName + "_" + i.ToString(CultureInfo.InvariantCulture);
taken.Add(candidate);
taken.Add($"{candidate}Key");
taken.Add($"_{candidate}");
return candidate;
}
private static bool IsFree(string name, HashSet<string> taken)
=> !taken.Contains(name) && !taken.Contains($"{name}Key") && !taken.Contains($"_{name}");
// The text is copied into the documentation comment, and a line break there would end the comment
// and leave the rest of the sentence standing in the class body as code.
private static string ToXmlComment(string value)
{
var text = (value ?? string.Empty)
.Replace("&", "&amp;")
.Replace("<", "&lt;")
.Replace(">", "&gt;");
return string.Join("\n", text
.Replace("\r\n", "\n")
.Replace('\r', '\n')
.Split('\n')
.Select(line => $"\t/// {line}"));
}
}