-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathFormatterProfileCatalogInput.cs
More file actions
359 lines (311 loc) · 14.6 KB
/
Copy pathFormatterProfileCatalogInput.cs
File metadata and controls
359 lines (311 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
using System.Collections.Immutable;
using System.Globalization;
using System.Text;
using System.Text.Json;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace Humanizer.SourceGenerators;
public sealed partial class HumanizerSourceGenerator
{
sealed class FormatterProfileCatalogInput(ImmutableArray<FormatterProfileDefinition> profiles)
{
[Flags]
enum TimeUnitMask
{
None = 0,
Millisecond = 1 << 0,
Second = 1 << 1,
Minute = 1 << 2,
Hour = 1 << 3,
Day = 1 << 4,
Week = 1 << 5,
Month = 1 << 6,
Year = 1 << 7,
All = Millisecond | Second | Minute | Hour | Day | Week | Month | Year
}
[Flags]
enum TenseMask
{
None = 0,
Past = 1 << 0,
Future = 1 << 1,
Both = Past | Future
}
readonly ImmutableArray<FormatterProfileDefinition> profiles = profiles;
public ImmutableHashSet<string> DataBackedProfileNames { get; } = profiles
.Select(static profile => profile.ProfileName)
.ToImmutableHashSet(StringComparer.Ordinal);
public static FormatterProfileCatalogInput Create(LocaleCatalogInput localeCatalog)
{
var profiles = ImmutableArray.CreateBuilder<FormatterProfileDefinition>();
var seenProfiles = new HashSet<string>(StringComparer.Ordinal);
foreach (var locale in localeCatalog.Locales)
{
var feature = locale.Formatter;
if (feature is not { UsesGeneratedProfile: true } ||
!seenProfiles.Add(feature.ProfileName!))
{
continue;
}
profiles.Add(new FormatterProfileDefinition(
feature.ProfileName!,
GetRequiredString(feature.ProfileRoot, "engine"),
feature.ProfileRoot.Clone(),
locale.Grammar));
}
return new FormatterProfileCatalogInput(profiles.ToImmutable());
}
public void Emit(SourceProductionContext context)
{
if (profiles.IsDefaultOrEmpty)
{
return;
}
var generatedProfiles = profiles
.OrderBy(static profile => profile.ProfileName, StringComparer.Ordinal)
.ToArray();
var builder = new StringBuilder();
builder.AppendLine("using System;");
builder.AppendLine("using System.Collections.Frozen;");
builder.AppendLine("using System.Collections.Generic;");
builder.AppendLine("using System.Globalization;");
builder.AppendLine();
builder.AppendLine("namespace Humanizer;");
builder.AppendLine();
builder.AppendLine("static partial class FormatterProfileCatalog");
builder.AppendLine("{");
builder.AppendLine(" public static IFormatter Resolve(string kind, CultureInfo culture)");
builder.AppendLine(" {");
builder.AppendLine(" if (Factories.TryGetValue(kind, out var factory))");
builder.AppendLine(" {");
builder.AppendLine(" return factory(culture);");
builder.AppendLine(" }");
builder.AppendLine();
builder.AppendLine(" throw new ArgumentOutOfRangeException(nameof(kind), kind, \"Unknown formatter profile.\");");
builder.AppendLine(" }");
builder.AppendLine();
builder.AppendLine(" static readonly FrozenDictionary<string, Func<CultureInfo, IFormatter>> Factories = new Dictionary<string, Func<CultureInfo, IFormatter>>(StringComparer.Ordinal)");
builder.AppendLine(" {");
foreach (var profile in generatedProfiles)
{
builder.Append(" ");
builder.Append('[');
builder.Append(QuoteLiteral(profile.ProfileName));
builder.Append("] = static culture => new ProfiledFormatter(culture, ");
builder.Append(GetCatalogPropertyName(profile.ProfileName));
builder.AppendLine("),");
}
builder.AppendLine(" }.ToFrozenDictionary(StringComparer.Ordinal);");
builder.AppendLine();
foreach (var profile in generatedProfiles)
{
AppendLazyCachedMember(
builder,
" ",
"static",
"FormatterProfile",
GetCatalogPropertyName(profile.ProfileName),
CreateFormatterProfileExpression(profile));
builder.AppendLine();
}
builder.AppendLine("}");
context.AddSource("FormatterProfileCatalog.g.cs", SourceText.From(builder.ToString(), Encoding.UTF8));
}
static string CreateFormatterProfileExpression(FormatterProfileDefinition profile)
{
if (profile.Engine != "profiled")
{
throw new InvalidOperationException($"Unsupported formatter engine '{profile.Engine}'.");
}
var phraseDetector = GetGrammarScalar(profile.Grammar, "pluralRule") ?? GetOptionalString(profile.Root, "resourceKeyDetector");
var dataUnitDetector = GetGrammarScalar(profile.Grammar, "dataUnitPluralRule") ?? GetOptionalString(profile.Root, "dataUnitDetector");
var dataUnitNonIntegralForm = GetGrammarScalar(profile.Grammar, "dataUnitNonIntegralForm") ?? GetOptionalString(profile.Root, "dataUnitNonIntegralForm");
var prepositionMode = GetGrammarScalar(profile.Grammar, "prepositionMode") ?? GetOptionalString(profile.Root, "prepositionMode");
var secondaryPlaceholderMode = GetGrammarScalar(profile.Grammar, "secondaryPlaceholderMode") ?? GetOptionalString(profile.Root, "secondaryPlaceholderMode");
var fallbackTransform = GetOptionalString(profile.Root, "dataUnitFallbackTransform");
return "new FormatterProfile(" +
CreateFormatterNumberDetectorExpression(phraseDetector) + ", " +
CreateFormatterDateFormRuleArrayExpression(profile.Root, "exactDateForms") + ", " +
CreateFormatterTimeSpanFormRuleArrayExpression(profile.Root, "exactTimeSpanForms") + ", " +
CreateFormatterNumberDetectorExpression(dataUnitDetector) + ", " +
CreateFormatterNumberFormExpression(dataUnitNonIntegralForm) + ", " +
CreateFormatterFallbackTransformExpression(fallbackTransform) + ", " +
CreateFormatterPrepositionModeExpression(prepositionMode) + ", " +
CreateFormatterSecondaryPlaceholderModeExpression(secondaryPlaceholderMode) + ", " +
CreateTimeUnitGenderMapExpression(profile) +
")";
}
static string? GetGrammarScalar(SimpleYamlMapping? grammar, string key) =>
grammar?.GetScalar(key);
static string CreateTimeUnitGenderMapExpression(FormatterProfileDefinition profile)
{
if (profile.Grammar?.TryGetValue("timeUnitGenders", out var grammarValue) == true &&
grammarValue is SimpleYamlMapping grammarMapping)
{
return HumanizerSourceGenerator.CreateTimeUnitGenderMapExpression(
LocaleCatalogInput.ToJsonElement(grammarMapping));
}
return HumanizerSourceGenerator.CreateTimeUnitGenderMapExpression(profile.Root, "timeUnitGenders");
}
static string CreateFormatterDateFormRuleArrayExpression(JsonElement element, string propertyName)
{
if (!element.TryGetProperty(propertyName, out var property) || property.ValueKind != JsonValueKind.Array)
{
return "Array.Empty<FormatterDateFormRule>()";
}
var expressions = new List<string>();
foreach (var item in property.EnumerateArray())
{
var units = ReadTimeUnitMask(item, "units", TimeUnitMask.All);
var tenses = ReadTenseMask(item, "tenses", TenseMask.Both);
if (units == TimeUnitMask.None || tenses == TenseMask.None)
{
continue;
}
expressions.Add(
"new FormatterDateFormRule(" +
checked((int)GetRequiredInt64(item, "number")).ToString(CultureInfo.InvariantCulture) + ", " +
CreateTimeUnitMaskExpression(units) + ", " +
CreateTenseMaskExpression(tenses) + ", " +
CreateFormatterNumberFormExpression(GetRequiredString(item, "form")) +
")");
}
return CreateRuleArrayExpression("FormatterDateFormRule", expressions);
}
static string CreateFormatterTimeSpanFormRuleArrayExpression(JsonElement element, string propertyName)
{
if (!element.TryGetProperty(propertyName, out var property) || property.ValueKind != JsonValueKind.Array)
{
return "Array.Empty<FormatterTimeSpanFormRule>()";
}
var expressions = new List<string>();
foreach (var item in property.EnumerateArray())
{
var units = ReadTimeUnitMask(item, "units", TimeUnitMask.All);
if (units == TimeUnitMask.None)
{
continue;
}
expressions.Add(
"new FormatterTimeSpanFormRule(" +
checked((int)GetRequiredInt64(item, "number")).ToString(CultureInfo.InvariantCulture) + ", " +
CreateTimeUnitMaskExpression(units) + ", " +
CreateFormatterNumberFormExpression(GetRequiredString(item, "form")) +
")");
}
return CreateRuleArrayExpression("FormatterTimeSpanFormRule", expressions);
}
static string CreateRuleArrayExpression(string elementType, List<string> expressions) =>
expressions.Count == 0
? "Array.Empty<" + elementType + ">()"
: "new " + elementType + "[] { " + string.Join(", ", expressions) + " }";
static TimeUnitMask ReadTimeUnitMask(JsonElement item, string propertyName, TimeUnitMask defaultMask)
{
if (!item.TryGetProperty(propertyName, out var property))
{
return defaultMask;
}
var mask = TimeUnitMask.None;
foreach (var value in EnumerateSelectorStrings(property))
{
mask |= value.ToLowerInvariant() switch
{
"all" => TimeUnitMask.All,
"millisecond" or "milliseconds" => TimeUnitMask.Millisecond,
"second" or "seconds" => TimeUnitMask.Second,
"minute" or "minutes" => TimeUnitMask.Minute,
"hour" or "hours" => TimeUnitMask.Hour,
"day" or "days" => TimeUnitMask.Day,
"week" or "weeks" => TimeUnitMask.Week,
"month" or "months" => TimeUnitMask.Month,
"year" or "years" => TimeUnitMask.Year,
_ => TimeUnitMask.None
};
}
return mask;
}
static TenseMask ReadTenseMask(JsonElement item, string propertyName, TenseMask defaultMask)
{
if (!item.TryGetProperty(propertyName, out var property))
{
return defaultMask;
}
var mask = TenseMask.None;
foreach (var value in EnumerateSelectorStrings(property))
{
mask |= value.ToLowerInvariant() switch
{
"all" or "both" => TenseMask.Both,
"past" => TenseMask.Past,
"future" => TenseMask.Future,
_ => TenseMask.None
};
}
return mask;
}
static IEnumerable<string> EnumerateSelectorStrings(JsonElement property)
{
if (property.ValueKind == JsonValueKind.String)
{
yield return property.GetString()!;
yield break;
}
if (property.ValueKind != JsonValueKind.Array)
{
yield break;
}
foreach (var item in property.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.String)
{
yield return item.GetString()!;
}
}
}
static string CreateTimeUnitMaskExpression(TimeUnitMask mask)
{
if (mask == TimeUnitMask.All)
{
return "FormatterTimeUnitMask.All";
}
var parts = new List<string>();
AppendTimeUnitMaskPart(parts, mask, TimeUnitMask.Millisecond, "Millisecond");
AppendTimeUnitMaskPart(parts, mask, TimeUnitMask.Second, "Second");
AppendTimeUnitMaskPart(parts, mask, TimeUnitMask.Minute, "Minute");
AppendTimeUnitMaskPart(parts, mask, TimeUnitMask.Hour, "Hour");
AppendTimeUnitMaskPart(parts, mask, TimeUnitMask.Day, "Day");
AppendTimeUnitMaskPart(parts, mask, TimeUnitMask.Week, "Week");
AppendTimeUnitMaskPart(parts, mask, TimeUnitMask.Month, "Month");
AppendTimeUnitMaskPart(parts, mask, TimeUnitMask.Year, "Year");
return parts.Count == 0
? "FormatterTimeUnitMask.None"
: string.Join(" | ", parts);
}
static string CreateTenseMaskExpression(TenseMask mask)
{
if (mask == TenseMask.Both)
{
return "FormatterTenseMask.Both";
}
var parts = new List<string>();
if ((mask & TenseMask.Past) != 0)
{
parts.Add("FormatterTenseMask.Past");
}
if ((mask & TenseMask.Future) != 0)
{
parts.Add("FormatterTenseMask.Future");
}
return parts.Count == 0
? "FormatterTenseMask.None"
: string.Join(" | ", parts);
}
static void AppendTimeUnitMaskPart(List<string> parts, TimeUnitMask combined, TimeUnitMask flag, string name)
{
if ((combined & flag) != 0)
{
parts.Add("FormatterTimeUnitMask." + name);
}
}
}
}