forked from jeffijoe/messageformat.net
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPluralFormatter.cs
378 lines (313 loc) · 12.2 KB
/
PluralFormatter.cs
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// MessageFormat for .NET
// - PluralFormatter.cs
// Author: Jeff Hansen <[email protected]>
// Copyright (C) Jeff Hansen 2014. All rights reserved.
using Jeffijoe.MessageFormat.Helpers;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Jeffijoe.MessageFormat.Formatting.Formatters
{
/// <summary>
/// Plural Formatter
/// </summary>
public class PluralFormatter : BaseFormatter, IFormatter
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="PluralFormatter" /> class.
/// </summary>
public PluralFormatter()
{
this.Pluralizers = new Dictionary<string, Pluralizer>();
this.AddStandardPluralizers();
}
#endregion
#region Public Properties
/// <summary>
/// Gets the pluralizers dictionary. Key is the locale.
/// </summary>
/// <value>
/// The pluralizers.
/// </value>
public IDictionary<string, Pluralizer> Pluralizers { get; private set; }
#endregion
#region Public Methods and Operators
/// <summary>
/// Determines whether this instance can format a message based on the specified parameters.
/// </summary>
/// <param name="request">
/// The parameters.
/// </param>
/// <returns>
/// The <see cref="bool" />.
/// </returns>
public bool CanFormat(FormatterRequest request)
{
return request.FormatterName == "plural";
}
/// <summary>
/// Using the specified parameters and arguments, a formatted string shall be returned.
/// The <see cref="IMessageFormatter" /> is being provided as well, to enable
/// nested formatting. This is only called if <see cref="CanFormat" /> returns true.
/// The args will always contain the <see cref="FormatterRequest.Variable" />.
/// </summary>
/// <param name="locale">
/// The locale being used. It is up to the formatter what they do with this information.
/// </param>
/// <param name="request">
/// The parameters.
/// </param>
/// <param name="args">
/// The arguments.
/// </param>
/// <param name="value">The value of <see cref="FormatterRequest.Variable"/> from the given args dictionary. Can be null.</param>
/// <param name="messageFormatter">
/// The message formatter.
/// </param>
/// <returns>
/// The <see cref="string" />.
/// </returns>
public string Format(
string locale,
FormatterRequest request,
IDictionary<string, object> args,
object value,
IMessageFormatter messageFormatter)
{
var arguments = this.ParseArguments(request);
double offset = 0;
var offsetExtension = arguments.Extensions.FirstOrDefault(x => x.Extension == "offset");
if (offsetExtension != null)
offset = Convert.ToDouble(offsetExtension.Value);
var operands = PluralizerHelper.ComputePluralOperands(locale, value, offset);
var pluralized = new StringBuilder(this.Pluralize(locale, arguments, operands));
var result = this.ReplaceNumberLiterals(pluralized, operands.ReconstructWithOffset());
var formatted = messageFormatter.FormatMessage(result, args);
return formatted;
}
#endregion
#region Methods
/// <summary>
/// Returns the correct plural block.
/// </summary>
/// <param name="locale">
/// The locale.
/// </param>
/// <param name="arguments">
/// The parsed arguments string.
/// </param>
/// <param name="n">
/// The n.
/// </param>
/// <param name="offset">
/// The offset.
/// </param>
/// <returns>
/// The <see cref="string" />.
/// </returns>
/// <exception cref="MessageFormatterException">
/// The 'other' option was not found in pattern.
/// </exception>
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly",
Justification = "Reviewed. Suppression is OK here.")]
internal string Pluralize(string locale, ParsedArguments arguments, PluralOperands operands)
{
if (!this.Pluralizers.TryGetValue(locale, out Pluralizer pluralizer))
pluralizer = this.Pluralizers["en"];
var pluralForm = pluralizer(operands);
KeyedBlock other = null;
foreach (var keyedBlock in arguments.KeyedBlocks)
{
if (keyedBlock.Key == OtherKey)
{
other = keyedBlock;
}
if (keyedBlock.Key.StartsWith("="))
{
var numberLiteral = Convert.ToDouble(keyedBlock.Key.Substring(1));
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (numberLiteral == operands.originalNumber)
{
return keyedBlock.BlockText;
}
}
if (keyedBlock.Key == pluralForm)
{
return keyedBlock.BlockText;
}
}
if (other == null)
{
throw new MessageFormatterException("'other' option not found in pattern.");
}
return other.BlockText;
}
/// <summary>
/// Replaces the number literals with the actual number.
/// </summary>
/// <param name="pluralized">
/// The pluralized.
/// </param>
/// <param name="n">
/// The n.
/// </param>
/// <returns>
/// The <see cref="string" />.
/// </returns>
internal string ReplaceNumberLiterals(StringBuilder pluralized, string n)
{
// I've done this a few times now..
const char OpenBrace = '{';
const char CloseBrace = '}';
const char Pound = '#';
const char EscapeChar = '\'';
var braceBalance = 0;
var insideEscapeSequence = false;
var sb = new StringBuilder();
for (int i = 0; i < pluralized.Length; i++)
{
var c = pluralized[i];
if (c == EscapeChar)
{
sb.Append(EscapeChar);
if (i == pluralized.Length - 1)
{
// The last char can't open a new escape sequence, it can only close one
if (insideEscapeSequence)
{
insideEscapeSequence = false;
}
continue;
}
var nextChar = pluralized[i + 1];
if (nextChar == EscapeChar)
{
sb.Append(EscapeChar);
++i;
continue;
}
if (insideEscapeSequence)
{
insideEscapeSequence = false;
continue;
}
if (nextChar == '{' || nextChar == '}' || nextChar == '#')
{
sb.Append(nextChar);
insideEscapeSequence = true;
++i;
continue;
}
continue;
}
if (insideEscapeSequence)
{
sb.Append(c);
continue;
}
if (c == OpenBrace)
{
braceBalance++;
}
else if (c == CloseBrace)
{
braceBalance--;
}
else if (c == Pound)
{
if (braceBalance == 0)
{
sb.Append(n);
continue;
}
}
sb.Append(c);
}
return sb.ToString();
}
/// <summary>
/// Adds the standard pluralizers.
/// </summary>
private void AddStandardPluralizers()
{
// Implementations based on https://github.com/unicode-org/cldr/blob/master/common/supplemental/plurals.xml
AddPluralizer(o => "other", "bm bo dz id ig ii in ja jbo jv jw kde kea km ko lkt lo ms my nqo osa root sah ses sg su th to vi wo yo yue zh");
AddPluralizer(o => (o.i == 1 && o.v == 0) ? "one" : "other", "ast ca de en et fi fy gl ia io it ji lij nl pt_PT sc scn sv sw ur yi");
AddPluralizer(o => o.n == 1 ? "one" : "other", "af an asa az bem bez bg brx ce cgg chr ckb dv ee el eo es eu fo fur gsw ha haw hu jgo jmc ka kaj kcg kk kkj kl ks ksb ku ky lb lg mas mgo ml mn mr nah nb nd ne nn nnh no nr ny nyn om or os pap ps rm rof rwk saq sd sdh seh sn so sq ss ssy st syr ta te teo tig tk tn tr ts ug uz ve vo vun wae xh xog");
AddPluralizer(o =>
{
if (o.i == 1 && o.v == 0)
return "one";
if (IsInRange(o.i, 2, 4) && o.v == 0)
return "few";
if (o.v != 0)
return "many";
return "other";
}, "cs sk");
AddPluralizer(o =>
{
if (o.i == 1 && o.v == 0)
return "one";
var mod10 = o.i % 10;
var mod100 = o.i % 100;
if (o.v == 0 && IsInRange(mod10, 2, 4) && !IsInRange(mod100, 12, 14))
return "few";
if ((o.v == 0 && o.i != 1 && IsInRange(mod10, 0, 1))
|| (o.v == 0 && IsInRange(mod10, 5, 9))
|| (o.v == 0 && IsInRange(mod100, 12, 14)))
return "many";
return "other";
}, "pl");
AddPluralizer(o =>
{
if ((o.t == "0" && o.i % 10 == 1 && o.i % 100 != 11) || o.t != "0")
return "one";
return "other";
}, "is");
AddPluralizer(o =>
{
var mod10 = o.i % 10;
var mod100 = o.i % 100;
if (o.v == 0 && mod10 == 1 && mod100 != 11)
return "one";
if (o.v == 0 && IsInRange(mod10, 2, 4) && !IsInRange(mod100, 12, 14))
return "few";
if ((o.v == 0 && mod10 == 0) || (o.v == 0 && IsInRange(mod10, 5, 9)) || (o.v == 0 && IsInRange(mod100, 11, 14)))
return "many";
return "other";
}, "ru uk");
AddPluralizer(o =>
{
if (o.i == 0 || o.i == 1)
return "one";
if (o.e == 0 && o.i != 0 && o.i % 1000000 == 0 && o.v == 0 || !IsInRange(o.e, 0, 5))
return "many";
return "other";
}, "fr");
AddPluralizer(o =>
{
switch(o.n)
{
case 0: return "zero";
case 1: return "one";
case 2: return "two";
case 3: return "few";
case 6: return "many";
default: return "other";
}
}, "cy");
}
static bool IsInRange(int n, int min, int max) => n >= min && n <= max;
void AddPluralizer(Pluralizer pluralizer, string locales)
{
foreach (var locale in locales.Split(' '))
if (!string.IsNullOrWhiteSpace(locale))
this.Pluralizers.Add(locale.Trim(), pluralizer);
}
#endregion
}
}