-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathresolver.ts
More file actions
371 lines (327 loc) · 10.3 KB
/
resolver.ts
File metadata and controls
371 lines (327 loc) · 10.3 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
360
361
362
363
364
365
366
367
368
369
370
371
/**
* The role of the Fluent resolver is to format a `Pattern` to an instance of
* `FluentValue`. For performance reasons, primitive strings are considered
* such instances, too.
*
* Translations can contain references to other messages or variables,
* conditional logic in form of select expressions, traits which describe their
* grammatical features, and can use Fluent builtins which make use of the
* `Intl` formatters to format numbers and dates into the bundle's languages.
* See the documentation of the Fluent syntax for more information.
*
* In case of errors the resolver will try to salvage as much of the
* translation as possible. In rare situations where the resolver didn't know
* how to recover from an error it will return an instance of `FluentNone`.
*
* All expressions resolve to an instance of `FluentValue`. The caller should
* use the `toString` method to convert the instance to a native value.
*
* Functions in this file pass around an instance of the `Scope` class, which
* stores the data required for successful resolution and error recovery.
*/
import {
FluentValue,
FluentType,
FluentNone,
FluentNumber,
FluentDateTime,
FluentVariable,
} from "./types.js";
import { Scope } from "./scope.js";
import {
Variant,
Expression,
NamedArgument,
VariableReference,
MessageReference,
TermReference,
FunctionReference,
SelectExpression,
ComplexPattern,
Pattern,
} from "./ast.js";
/**
* The maximum number of placeables which can be expanded in a single call to
* `formatPattern`. The limit protects against the Billion Laughs and Quadratic
* Blowup attacks. See https://msdn.microsoft.com/en-us/magazine/ee335713.aspx.
*/
const MAX_PLACEABLES = 100;
/** Unicode bidi isolation characters. */
const FSI = "\u2068";
const PDI = "\u2069";
/** Helper: match a variant key to the given selector. */
function match(scope: Scope, selector: FluentValue, key: FluentValue): boolean {
if (key === selector) {
// Both are strings.
return true;
}
// XXX Consider comparing options too, e.g. minimumFractionDigits.
if (
key instanceof FluentNumber &&
selector instanceof FluentNumber &&
key.value === selector.value
) {
return true;
}
if (selector instanceof FluentNumber && typeof key === "string") {
let category = scope
.memoizeIntlObject(
Intl.PluralRules,
selector.opts as Intl.PluralRulesOptions
)
.select(selector.value);
if (key === category) {
return true;
}
}
return false;
}
/** Helper: resolve the default variant from a list of variants. */
function getDefault(
scope: Scope,
variants: Array<Variant>,
star: number
): FluentValue {
if (variants[star]) {
return resolvePattern(scope, variants[star].value);
}
scope.reportError(new RangeError("No default"));
return new FluentNone();
}
interface Arguments {
positional: Array<FluentValue>;
named: Record<string, FluentValue>;
}
/** Helper: resolve arguments to a call expression. */
function getArguments(
scope: Scope,
args: Array<Expression | NamedArgument>
): Arguments {
const positional: Array<FluentValue> = [];
const named = Object.create(null) as Record<string, FluentValue>;
for (const arg of args) {
if (arg.type === "narg") {
named[arg.name] = resolveExpression(scope, arg.value);
} else {
positional.push(resolveExpression(scope, arg));
}
}
return { positional, named };
}
/** Resolve an expression to a Fluent type. */
function resolveExpression(scope: Scope, expr: Expression): FluentValue {
switch (expr.type) {
case "str":
return expr.value;
case "num":
return new FluentNumber(expr.value, {
minimumFractionDigits: expr.precision,
});
case "var":
return resolveVariableReference(scope, expr);
case "mesg":
return resolveMessageReference(scope, expr);
case "term":
return resolveTermReference(scope, expr);
case "func":
return resolveFunctionReference(scope, expr);
case "select":
return resolveSelectExpression(scope, expr);
default:
return new FluentNone();
}
}
/** Resolve a reference to a variable. */
function resolveVariableReference(
scope: Scope,
{ name }: VariableReference
): FluentValue {
let arg: FluentVariable;
if (scope.params) {
// We're inside a TermReference. It's OK to reference undefined parameters.
if (name in scope.params) {
arg = scope.params[name];
} else {
return new FluentNone(`$${name}`);
}
} else if (scope.args && name in scope.args) {
// We're in the top-level Pattern or inside a MessageReference. Missing
// variables references produce ReferenceErrors.
arg = scope.args[name];
} else {
scope.reportError(new ReferenceError(`Unknown variable: $${name}`));
return new FluentNone(`$${name}`);
}
// Return early if the argument already is an instance of FluentType.
if (arg instanceof FluentType) {
return arg;
}
// Convert the argument to a Fluent type.
switch (typeof arg) {
case "string":
return arg;
case "boolean":
return String(arg);
case "number":
return new FluentNumber(arg);
case "object":
if (FluentDateTime.supportsValue(arg)) {
return new FluentDateTime(arg);
}
// eslint-disable-next-line no-fallthrough
default:
scope.reportError(
new TypeError(`Variable type not supported: $${name}, ${typeof arg}`)
);
return new FluentNone(`$${name}`);
}
}
/** Resolve a reference to another message. */
function resolveMessageReference(
scope: Scope,
ref: MessageReference
): FluentValue {
const { name, attr } = ref;
if (scope.dirty.has(ref)) {
scope.reportError(new RangeError("Cyclic reference"));
return new FluentNone(name);
}
scope.dirty.add(ref);
const message = scope.bundle._messages.get(name);
if (!message) {
scope.reportError(new ReferenceError(`Unknown message: ${name}`));
return new FluentNone(name);
}
if (attr) {
const attribute = message.attributes[attr];
if (attribute) {
return resolvePattern(scope, attribute);
}
scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));
return new FluentNone(`${name}.${attr}`);
}
if (message.value) {
return resolvePattern(scope, message.value);
}
scope.reportError(new ReferenceError(`No value: ${name}`));
return new FluentNone(name);
}
/** Resolve a call to a Term with key-value arguments. */
function resolveTermReference(scope: Scope, ref: TermReference): FluentValue {
const { name, attr, args } = ref;
const id = `-${name}`;
if (scope.dirty.has(ref)) {
scope.reportError(new RangeError("Cyclic reference"));
return new FluentNone(id);
}
scope.dirty.add(ref);
const term = scope.bundle._terms.get(id);
if (!term) {
scope.reportError(new ReferenceError(`Unknown term: ${id}`));
return new FluentNone(id);
}
if (attr) {
const attribute = term.attributes[attr];
if (attribute) {
// Every TermReference has its own variables.
scope.params = getArguments(scope, args).named;
const resolved = resolvePattern(scope, attribute);
scope.params = null;
return resolved;
}
scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));
return new FluentNone(`${id}.${attr}`);
}
scope.params = getArguments(scope, args).named;
const resolved = resolvePattern(scope, term.value);
scope.params = null;
return resolved;
}
/** Resolve a call to a Function with positional and key-value arguments. */
function resolveFunctionReference(
scope: Scope,
{ name, args }: FunctionReference
): FluentValue {
// Some functions are built-in. Others may be provided by the runtime via
// the `FluentBundle` constructor.
let func = scope.bundle._functions[name];
if (!func) {
scope.reportError(new ReferenceError(`Unknown function: ${name}()`));
return new FluentNone(`${name}()`);
}
if (typeof func !== "function") {
scope.reportError(new TypeError(`Function ${name}() is not callable`));
return new FluentNone(`${name}()`);
}
try {
let resolved = getArguments(scope, args);
return func(resolved.positional, resolved.named);
} catch (err) {
scope.reportError(err);
return new FluentNone(`${name}()`);
}
}
/** Resolve a select expression to the member object. */
function resolveSelectExpression(
scope: Scope,
{ selector, variants, star }: SelectExpression
): FluentValue {
let sel = resolveExpression(scope, selector);
if (sel instanceof FluentNone) {
return getDefault(scope, variants, star);
}
// Match the selector against keys of each variant, in order.
for (const variant of variants) {
const key = resolveExpression(scope, variant.key);
if (match(scope, sel, key)) {
return resolvePattern(scope, variant.value);
}
}
return getDefault(scope, variants, star);
}
/** Resolve a pattern (a complex string with placeables). */
export function resolveComplexPattern(
scope: Scope,
ptn: ComplexPattern
): FluentValue {
const result = [];
// Wrap interpolations with Directional Isolate Formatting characters
// only when the pattern has more than one element.
const useIsolating = scope.bundle._useIsolating && ptn.length > 1;
for (const elem of ptn) {
if (typeof elem === "string") {
result.push(scope.bundle._transform(elem));
continue;
}
scope.placeables++;
if (scope.placeables > MAX_PLACEABLES) {
// This is a fatal error which causes the resolver to instantly bail out
// on this pattern. The length check protects against excessive memory
// usage, and throwing protects against eating up the CPU when long
// placeables are deeply nested.
throw new RangeError(
`Too many placeables expanded: ${scope.placeables}, ` +
`max allowed is ${MAX_PLACEABLES}`
);
}
if (useIsolating) {
result.push(FSI);
}
result.push(resolveExpression(scope, elem).toString(scope));
if (useIsolating) {
result.push(PDI);
}
}
return result.join("");
}
/**
* Resolve a simple or a complex Pattern to a FluentString
* (which is really the string primitive).
*/
function resolvePattern(scope: Scope, value: Pattern): FluentValue {
// Resolve a simple pattern.
if (typeof value === "string") {
return scope.bundle._transform(value);
}
return resolveComplexPattern(scope, value);
}