@intlify/message-compiler 9.3.0-beta.8 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1372 +1,1529 @@
1
1
  /*!
2
- * message-compiler v9.3.0-beta.8
3
- * (c) 2022 kazuya kawaguchi
2
+ * message-compiler v9.3.0
3
+ * (c) 2023 kazuya kawaguchi
4
4
  * Released under the MIT License.
5
5
  */
6
- import { format, assign, isString } from '@intlify/shared';
6
+ import { format, assign, join, isString } from '@intlify/shared';
7
7
 
8
- const CompileErrorCodes = {
9
- // tokenizer error codes
10
- EXPECTED_TOKEN: 1,
11
- INVALID_TOKEN_IN_PLACEHOLDER: 2,
12
- UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
13
- UNKNOWN_ESCAPE_SEQUENCE: 4,
14
- INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
15
- UNBALANCED_CLOSING_BRACE: 6,
16
- UNTERMINATED_CLOSING_BRACE: 7,
17
- EMPTY_PLACEHOLDER: 8,
18
- NOT_ALLOW_NEST_PLACEHOLDER: 9,
19
- INVALID_LINKED_FORMAT: 10,
20
- // parser error codes
21
- MUST_HAVE_MESSAGES_IN_PLURAL: 11,
22
- UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
23
- UNEXPECTED_EMPTY_LINKED_KEY: 13,
24
- UNEXPECTED_LEXICAL_ANALYSIS: 14,
25
- // Special value for higher-order compilers to pick up the last code
26
- // to avoid collision of error codes. This should always be kept as the last
27
- // item.
28
- __EXTEND_POINT__: 15
29
- };
30
- /** @internal */
31
- const errorMessages = {
32
- // tokenizer error messages
33
- [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
34
- [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
35
- [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
36
- [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
37
- [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
38
- [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
39
- [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
40
- [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
41
- [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
42
- [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
43
- // parser error messages
44
- [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
45
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
46
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
47
- [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`
48
- };
49
- function createCompileError(code, loc, options = {}) {
50
- const { domain, messages, args } = options;
51
- const msg = (process.env.NODE_ENV !== 'production')
52
- ? format((messages || errorMessages)[code] || '', ...(args || []))
53
- : code;
54
- const error = new SyntaxError(String(msg));
55
- error.code = code;
56
- if (loc) {
57
- error.location = loc;
58
- }
59
- error.domain = domain;
60
- return error;
61
- }
62
- /** @internal */
63
- function defaultOnError(error) {
64
- throw error;
8
+ const LOCATION_STUB = {
9
+ start: { line: 1, column: 1, offset: 0 },
10
+ end: { line: 1, column: 1, offset: 0 }
11
+ };
12
+ function createPosition(line, column, offset) {
13
+ return { line, column, offset };
14
+ }
15
+ function createLocation(start, end, source) {
16
+ const loc = { start, end };
17
+ if (source != null) {
18
+ loc.source = source;
19
+ }
20
+ return loc;
65
21
  }
66
22
 
67
- const LocationStub = {
68
- start: { line: 1, column: 1, offset: 0 },
69
- end: { line: 1, column: 1, offset: 0 }
70
- };
71
- function createPosition(line, column, offset) {
72
- return { line, column, offset };
73
- }
74
- function createLocation(start, end, source) {
75
- const loc = { start, end };
76
- if (source != null) {
77
- loc.source = source;
78
- }
79
- return loc;
23
+ const CompileErrorCodes = {
24
+ // tokenizer error codes
25
+ EXPECTED_TOKEN: 1,
26
+ INVALID_TOKEN_IN_PLACEHOLDER: 2,
27
+ UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
28
+ UNKNOWN_ESCAPE_SEQUENCE: 4,
29
+ INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
30
+ UNBALANCED_CLOSING_BRACE: 6,
31
+ UNTERMINATED_CLOSING_BRACE: 7,
32
+ EMPTY_PLACEHOLDER: 8,
33
+ NOT_ALLOW_NEST_PLACEHOLDER: 9,
34
+ INVALID_LINKED_FORMAT: 10,
35
+ // parser error codes
36
+ MUST_HAVE_MESSAGES_IN_PLURAL: 11,
37
+ UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
38
+ UNEXPECTED_EMPTY_LINKED_KEY: 13,
39
+ UNEXPECTED_LEXICAL_ANALYSIS: 14,
40
+ // generator error codes
41
+ UNHANDLED_CODEGEN_NODE_TYPE: 15,
42
+ // minifier error codes
43
+ UNHANDLED_MINIFIER_NODE_TYPE: 16,
44
+ // Special value for higher-order compilers to pick up the last code
45
+ // to avoid collision of error codes. This should always be kept as the last
46
+ // item.
47
+ __EXTEND_POINT__: 17
48
+ };
49
+ /** @internal */
50
+ const errorMessages = {
51
+ // tokenizer error messages
52
+ [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
53
+ [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
54
+ [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
55
+ [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
56
+ [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
57
+ [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
58
+ [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
59
+ [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
60
+ [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
61
+ [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
62
+ // parser error messages
63
+ [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
64
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
65
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
66
+ [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
67
+ // generator error messages
68
+ [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
69
+ // minimizer error messages
70
+ [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
71
+ };
72
+ function createCompileError(code, loc, options = {}) {
73
+ const { domain, messages, args } = options;
74
+ const msg = (process.env.NODE_ENV !== 'production')
75
+ ? format((messages || errorMessages)[code] || '', ...(args || []))
76
+ : code;
77
+ const error = new SyntaxError(String(msg));
78
+ error.code = code;
79
+ if (loc) {
80
+ error.location = loc;
81
+ }
82
+ error.domain = domain;
83
+ return error;
84
+ }
85
+ /** @internal */
86
+ function defaultOnError(error) {
87
+ throw error;
80
88
  }
81
89
 
82
- const CHAR_SP = ' ';
83
- const CHAR_CR = '\r';
84
- const CHAR_LF = '\n';
85
- const CHAR_LS = String.fromCharCode(0x2028);
86
- const CHAR_PS = String.fromCharCode(0x2029);
87
- function createScanner(str) {
88
- const _buf = str;
89
- let _index = 0;
90
- let _line = 1;
91
- let _column = 1;
92
- let _peekOffset = 0;
93
- const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
94
- const isLF = (index) => _buf[index] === CHAR_LF;
95
- const isPS = (index) => _buf[index] === CHAR_PS;
96
- const isLS = (index) => _buf[index] === CHAR_LS;
97
- const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
98
- const index = () => _index;
99
- const line = () => _line;
100
- const column = () => _column;
101
- const peekOffset = () => _peekOffset;
102
- const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
103
- const currentChar = () => charAt(_index);
104
- const currentPeek = () => charAt(_index + _peekOffset);
105
- function next() {
106
- _peekOffset = 0;
107
- if (isLineEnd(_index)) {
108
- _line++;
109
- _column = 0;
110
- }
111
- if (isCRLF(_index)) {
112
- _index++;
113
- }
114
- _index++;
115
- _column++;
116
- return _buf[_index];
117
- }
118
- function peek() {
119
- if (isCRLF(_index + _peekOffset)) {
120
- _peekOffset++;
121
- }
122
- _peekOffset++;
123
- return _buf[_index + _peekOffset];
124
- }
125
- function reset() {
126
- _index = 0;
127
- _line = 1;
128
- _column = 1;
129
- _peekOffset = 0;
130
- }
131
- function resetPeek(offset = 0) {
132
- _peekOffset = offset;
133
- }
134
- function skipToPeek() {
135
- const target = _index + _peekOffset;
136
- // eslint-disable-next-line no-unmodified-loop-condition
137
- while (target !== _index) {
138
- next();
139
- }
140
- _peekOffset = 0;
141
- }
142
- return {
143
- index,
144
- line,
145
- column,
146
- peekOffset,
147
- charAt,
148
- currentChar,
149
- currentPeek,
150
- next,
151
- peek,
152
- reset,
153
- resetPeek,
154
- skipToPeek
155
- };
90
+ const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
91
+ const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
92
+
93
+ const CHAR_SP = ' ';
94
+ const CHAR_CR = '\r';
95
+ const CHAR_LF = '\n';
96
+ const CHAR_LS = String.fromCharCode(0x2028);
97
+ const CHAR_PS = String.fromCharCode(0x2029);
98
+ function createScanner(str) {
99
+ const _buf = str;
100
+ let _index = 0;
101
+ let _line = 1;
102
+ let _column = 1;
103
+ let _peekOffset = 0;
104
+ const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
105
+ const isLF = (index) => _buf[index] === CHAR_LF;
106
+ const isPS = (index) => _buf[index] === CHAR_PS;
107
+ const isLS = (index) => _buf[index] === CHAR_LS;
108
+ const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
109
+ const index = () => _index;
110
+ const line = () => _line;
111
+ const column = () => _column;
112
+ const peekOffset = () => _peekOffset;
113
+ const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
114
+ const currentChar = () => charAt(_index);
115
+ const currentPeek = () => charAt(_index + _peekOffset);
116
+ function next() {
117
+ _peekOffset = 0;
118
+ if (isLineEnd(_index)) {
119
+ _line++;
120
+ _column = 0;
121
+ }
122
+ if (isCRLF(_index)) {
123
+ _index++;
124
+ }
125
+ _index++;
126
+ _column++;
127
+ return _buf[_index];
128
+ }
129
+ function peek() {
130
+ if (isCRLF(_index + _peekOffset)) {
131
+ _peekOffset++;
132
+ }
133
+ _peekOffset++;
134
+ return _buf[_index + _peekOffset];
135
+ }
136
+ function reset() {
137
+ _index = 0;
138
+ _line = 1;
139
+ _column = 1;
140
+ _peekOffset = 0;
141
+ }
142
+ function resetPeek(offset = 0) {
143
+ _peekOffset = offset;
144
+ }
145
+ function skipToPeek() {
146
+ const target = _index + _peekOffset;
147
+ // eslint-disable-next-line no-unmodified-loop-condition
148
+ while (target !== _index) {
149
+ next();
150
+ }
151
+ _peekOffset = 0;
152
+ }
153
+ return {
154
+ index,
155
+ line,
156
+ column,
157
+ peekOffset,
158
+ charAt,
159
+ currentChar,
160
+ currentPeek,
161
+ next,
162
+ peek,
163
+ reset,
164
+ resetPeek,
165
+ skipToPeek
166
+ };
167
+ }
168
+
169
+ const EOF = undefined;
170
+ const DOT = '.';
171
+ const LITERAL_DELIMITER = "'";
172
+ const ERROR_DOMAIN$3 = 'tokenizer';
173
+ function createTokenizer(source, options = {}) {
174
+ const location = options.location !== false;
175
+ const _scnr = createScanner(source);
176
+ const currentOffset = () => _scnr.index();
177
+ const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
178
+ const _initLoc = currentPosition();
179
+ const _initOffset = currentOffset();
180
+ const _context = {
181
+ currentType: 14 /* TokenTypes.EOF */,
182
+ offset: _initOffset,
183
+ startLoc: _initLoc,
184
+ endLoc: _initLoc,
185
+ lastType: 14 /* TokenTypes.EOF */,
186
+ lastOffset: _initOffset,
187
+ lastStartLoc: _initLoc,
188
+ lastEndLoc: _initLoc,
189
+ braceNest: 0,
190
+ inLinked: false,
191
+ text: ''
192
+ };
193
+ const context = () => _context;
194
+ const { onError } = options;
195
+ function emitError(code, pos, offset, ...args) {
196
+ const ctx = context();
197
+ pos.column += offset;
198
+ pos.offset += offset;
199
+ if (onError) {
200
+ const loc = location ? createLocation(ctx.startLoc, pos) : null;
201
+ const err = createCompileError(code, loc, {
202
+ domain: ERROR_DOMAIN$3,
203
+ args
204
+ });
205
+ onError(err);
206
+ }
207
+ }
208
+ function getToken(context, type, value) {
209
+ context.endLoc = currentPosition();
210
+ context.currentType = type;
211
+ const token = { type };
212
+ if (location) {
213
+ token.loc = createLocation(context.startLoc, context.endLoc);
214
+ }
215
+ if (value != null) {
216
+ token.value = value;
217
+ }
218
+ return token;
219
+ }
220
+ const getEndToken = (context) => getToken(context, 14 /* TokenTypes.EOF */);
221
+ function eat(scnr, ch) {
222
+ if (scnr.currentChar() === ch) {
223
+ scnr.next();
224
+ return ch;
225
+ }
226
+ else {
227
+ emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
228
+ return '';
229
+ }
230
+ }
231
+ function peekSpaces(scnr) {
232
+ let buf = '';
233
+ while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
234
+ buf += scnr.currentPeek();
235
+ scnr.peek();
236
+ }
237
+ return buf;
238
+ }
239
+ function skipSpaces(scnr) {
240
+ const buf = peekSpaces(scnr);
241
+ scnr.skipToPeek();
242
+ return buf;
243
+ }
244
+ function isIdentifierStart(ch) {
245
+ if (ch === EOF) {
246
+ return false;
247
+ }
248
+ const cc = ch.charCodeAt(0);
249
+ return ((cc >= 97 && cc <= 122) || // a-z
250
+ (cc >= 65 && cc <= 90) || // A-Z
251
+ cc === 95 // _
252
+ );
253
+ }
254
+ function isNumberStart(ch) {
255
+ if (ch === EOF) {
256
+ return false;
257
+ }
258
+ const cc = ch.charCodeAt(0);
259
+ return cc >= 48 && cc <= 57; // 0-9
260
+ }
261
+ function isNamedIdentifierStart(scnr, context) {
262
+ const { currentType } = context;
263
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
264
+ return false;
265
+ }
266
+ peekSpaces(scnr);
267
+ const ret = isIdentifierStart(scnr.currentPeek());
268
+ scnr.resetPeek();
269
+ return ret;
270
+ }
271
+ function isListIdentifierStart(scnr, context) {
272
+ const { currentType } = context;
273
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
274
+ return false;
275
+ }
276
+ peekSpaces(scnr);
277
+ const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
278
+ const ret = isNumberStart(ch);
279
+ scnr.resetPeek();
280
+ return ret;
281
+ }
282
+ function isLiteralStart(scnr, context) {
283
+ const { currentType } = context;
284
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
285
+ return false;
286
+ }
287
+ peekSpaces(scnr);
288
+ const ret = scnr.currentPeek() === LITERAL_DELIMITER;
289
+ scnr.resetPeek();
290
+ return ret;
291
+ }
292
+ function isLinkedDotStart(scnr, context) {
293
+ const { currentType } = context;
294
+ if (currentType !== 8 /* TokenTypes.LinkedAlias */) {
295
+ return false;
296
+ }
297
+ peekSpaces(scnr);
298
+ const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
299
+ scnr.resetPeek();
300
+ return ret;
301
+ }
302
+ function isLinkedModifierStart(scnr, context) {
303
+ const { currentType } = context;
304
+ if (currentType !== 9 /* TokenTypes.LinkedDot */) {
305
+ return false;
306
+ }
307
+ peekSpaces(scnr);
308
+ const ret = isIdentifierStart(scnr.currentPeek());
309
+ scnr.resetPeek();
310
+ return ret;
311
+ }
312
+ function isLinkedDelimiterStart(scnr, context) {
313
+ const { currentType } = context;
314
+ if (!(currentType === 8 /* TokenTypes.LinkedAlias */ ||
315
+ currentType === 12 /* TokenTypes.LinkedModifier */)) {
316
+ return false;
317
+ }
318
+ peekSpaces(scnr);
319
+ const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
320
+ scnr.resetPeek();
321
+ return ret;
322
+ }
323
+ function isLinkedReferStart(scnr, context) {
324
+ const { currentType } = context;
325
+ if (currentType !== 10 /* TokenTypes.LinkedDelimiter */) {
326
+ return false;
327
+ }
328
+ const fn = () => {
329
+ const ch = scnr.currentPeek();
330
+ if (ch === "{" /* TokenChars.BraceLeft */) {
331
+ return isIdentifierStart(scnr.peek());
332
+ }
333
+ else if (ch === "@" /* TokenChars.LinkedAlias */ ||
334
+ ch === "%" /* TokenChars.Modulo */ ||
335
+ ch === "|" /* TokenChars.Pipe */ ||
336
+ ch === ":" /* TokenChars.LinkedDelimiter */ ||
337
+ ch === "." /* TokenChars.LinkedDot */ ||
338
+ ch === CHAR_SP ||
339
+ !ch) {
340
+ return false;
341
+ }
342
+ else if (ch === CHAR_LF) {
343
+ scnr.peek();
344
+ return fn();
345
+ }
346
+ else {
347
+ // other characters
348
+ return isIdentifierStart(ch);
349
+ }
350
+ };
351
+ const ret = fn();
352
+ scnr.resetPeek();
353
+ return ret;
354
+ }
355
+ function isPluralStart(scnr) {
356
+ peekSpaces(scnr);
357
+ const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
358
+ scnr.resetPeek();
359
+ return ret;
360
+ }
361
+ function detectModuloStart(scnr) {
362
+ const spaces = peekSpaces(scnr);
363
+ const ret = scnr.currentPeek() === "%" /* TokenChars.Modulo */ &&
364
+ scnr.peek() === "{" /* TokenChars.BraceLeft */;
365
+ scnr.resetPeek();
366
+ return {
367
+ isModulo: ret,
368
+ hasSpace: spaces.length > 0
369
+ };
370
+ }
371
+ function isTextStart(scnr, reset = true) {
372
+ const fn = (hasSpace = false, prev = '', detectModulo = false) => {
373
+ const ch = scnr.currentPeek();
374
+ if (ch === "{" /* TokenChars.BraceLeft */) {
375
+ return prev === "%" /* TokenChars.Modulo */ ? false : hasSpace;
376
+ }
377
+ else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
378
+ return prev === "%" /* TokenChars.Modulo */ ? true : hasSpace;
379
+ }
380
+ else if (ch === "%" /* TokenChars.Modulo */) {
381
+ scnr.peek();
382
+ return fn(hasSpace, "%" /* TokenChars.Modulo */, true);
383
+ }
384
+ else if (ch === "|" /* TokenChars.Pipe */) {
385
+ return prev === "%" /* TokenChars.Modulo */ || detectModulo
386
+ ? true
387
+ : !(prev === CHAR_SP || prev === CHAR_LF);
388
+ }
389
+ else if (ch === CHAR_SP) {
390
+ scnr.peek();
391
+ return fn(true, CHAR_SP, detectModulo);
392
+ }
393
+ else if (ch === CHAR_LF) {
394
+ scnr.peek();
395
+ return fn(true, CHAR_LF, detectModulo);
396
+ }
397
+ else {
398
+ return true;
399
+ }
400
+ };
401
+ const ret = fn();
402
+ reset && scnr.resetPeek();
403
+ return ret;
404
+ }
405
+ function takeChar(scnr, fn) {
406
+ const ch = scnr.currentChar();
407
+ if (ch === EOF) {
408
+ return EOF;
409
+ }
410
+ if (fn(ch)) {
411
+ scnr.next();
412
+ return ch;
413
+ }
414
+ return null;
415
+ }
416
+ function takeIdentifierChar(scnr) {
417
+ const closure = (ch) => {
418
+ const cc = ch.charCodeAt(0);
419
+ return ((cc >= 97 && cc <= 122) || // a-z
420
+ (cc >= 65 && cc <= 90) || // A-Z
421
+ (cc >= 48 && cc <= 57) || // 0-9
422
+ cc === 95 || // _
423
+ cc === 36 // $
424
+ );
425
+ };
426
+ return takeChar(scnr, closure);
427
+ }
428
+ function takeDigit(scnr) {
429
+ const closure = (ch) => {
430
+ const cc = ch.charCodeAt(0);
431
+ return cc >= 48 && cc <= 57; // 0-9
432
+ };
433
+ return takeChar(scnr, closure);
434
+ }
435
+ function takeHexDigit(scnr) {
436
+ const closure = (ch) => {
437
+ const cc = ch.charCodeAt(0);
438
+ return ((cc >= 48 && cc <= 57) || // 0-9
439
+ (cc >= 65 && cc <= 70) || // A-F
440
+ (cc >= 97 && cc <= 102)); // a-f
441
+ };
442
+ return takeChar(scnr, closure);
443
+ }
444
+ function getDigits(scnr) {
445
+ let ch = '';
446
+ let num = '';
447
+ while ((ch = takeDigit(scnr))) {
448
+ num += ch;
449
+ }
450
+ return num;
451
+ }
452
+ function readModulo(scnr) {
453
+ skipSpaces(scnr);
454
+ const ch = scnr.currentChar();
455
+ if (ch !== "%" /* TokenChars.Modulo */) {
456
+ emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
457
+ }
458
+ scnr.next();
459
+ return "%" /* TokenChars.Modulo */;
460
+ }
461
+ function readText(scnr) {
462
+ let buf = '';
463
+ while (true) {
464
+ const ch = scnr.currentChar();
465
+ if (ch === "{" /* TokenChars.BraceLeft */ ||
466
+ ch === "}" /* TokenChars.BraceRight */ ||
467
+ ch === "@" /* TokenChars.LinkedAlias */ ||
468
+ ch === "|" /* TokenChars.Pipe */ ||
469
+ !ch) {
470
+ break;
471
+ }
472
+ else if (ch === "%" /* TokenChars.Modulo */) {
473
+ if (isTextStart(scnr)) {
474
+ buf += ch;
475
+ scnr.next();
476
+ }
477
+ else {
478
+ break;
479
+ }
480
+ }
481
+ else if (ch === CHAR_SP || ch === CHAR_LF) {
482
+ if (isTextStart(scnr)) {
483
+ buf += ch;
484
+ scnr.next();
485
+ }
486
+ else if (isPluralStart(scnr)) {
487
+ break;
488
+ }
489
+ else {
490
+ buf += ch;
491
+ scnr.next();
492
+ }
493
+ }
494
+ else {
495
+ buf += ch;
496
+ scnr.next();
497
+ }
498
+ }
499
+ return buf;
500
+ }
501
+ function readNamedIdentifier(scnr) {
502
+ skipSpaces(scnr);
503
+ let ch = '';
504
+ let name = '';
505
+ while ((ch = takeIdentifierChar(scnr))) {
506
+ name += ch;
507
+ }
508
+ if (scnr.currentChar() === EOF) {
509
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
510
+ }
511
+ return name;
512
+ }
513
+ function readListIdentifier(scnr) {
514
+ skipSpaces(scnr);
515
+ let value = '';
516
+ if (scnr.currentChar() === '-') {
517
+ scnr.next();
518
+ value += `-${getDigits(scnr)}`;
519
+ }
520
+ else {
521
+ value += getDigits(scnr);
522
+ }
523
+ if (scnr.currentChar() === EOF) {
524
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
525
+ }
526
+ return value;
527
+ }
528
+ function readLiteral(scnr) {
529
+ skipSpaces(scnr);
530
+ eat(scnr, `\'`);
531
+ let ch = '';
532
+ let literal = '';
533
+ const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
534
+ while ((ch = takeChar(scnr, fn))) {
535
+ if (ch === '\\') {
536
+ literal += readEscapeSequence(scnr);
537
+ }
538
+ else {
539
+ literal += ch;
540
+ }
541
+ }
542
+ const current = scnr.currentChar();
543
+ if (current === CHAR_LF || current === EOF) {
544
+ emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
545
+ // TODO: Is it correct really?
546
+ if (current === CHAR_LF) {
547
+ scnr.next();
548
+ eat(scnr, `\'`);
549
+ }
550
+ return literal;
551
+ }
552
+ eat(scnr, `\'`);
553
+ return literal;
554
+ }
555
+ function readEscapeSequence(scnr) {
556
+ const ch = scnr.currentChar();
557
+ switch (ch) {
558
+ case '\\':
559
+ case `\'`:
560
+ scnr.next();
561
+ return `\\${ch}`;
562
+ case 'u':
563
+ return readUnicodeEscapeSequence(scnr, ch, 4);
564
+ case 'U':
565
+ return readUnicodeEscapeSequence(scnr, ch, 6);
566
+ default:
567
+ emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
568
+ return '';
569
+ }
570
+ }
571
+ function readUnicodeEscapeSequence(scnr, unicode, digits) {
572
+ eat(scnr, unicode);
573
+ let sequence = '';
574
+ for (let i = 0; i < digits; i++) {
575
+ const ch = takeHexDigit(scnr);
576
+ if (!ch) {
577
+ emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
578
+ break;
579
+ }
580
+ sequence += ch;
581
+ }
582
+ return `\\${unicode}${sequence}`;
583
+ }
584
+ function readInvalidIdentifier(scnr) {
585
+ skipSpaces(scnr);
586
+ let ch = '';
587
+ let identifiers = '';
588
+ const closure = (ch) => ch !== "{" /* TokenChars.BraceLeft */ &&
589
+ ch !== "}" /* TokenChars.BraceRight */ &&
590
+ ch !== CHAR_SP &&
591
+ ch !== CHAR_LF;
592
+ while ((ch = takeChar(scnr, closure))) {
593
+ identifiers += ch;
594
+ }
595
+ return identifiers;
596
+ }
597
+ function readLinkedModifier(scnr) {
598
+ let ch = '';
599
+ let name = '';
600
+ while ((ch = takeIdentifierChar(scnr))) {
601
+ name += ch;
602
+ }
603
+ return name;
604
+ }
605
+ function readLinkedRefer(scnr) {
606
+ const fn = (detect = false, buf) => {
607
+ const ch = scnr.currentChar();
608
+ if (ch === "{" /* TokenChars.BraceLeft */ ||
609
+ ch === "%" /* TokenChars.Modulo */ ||
610
+ ch === "@" /* TokenChars.LinkedAlias */ ||
611
+ ch === "|" /* TokenChars.Pipe */ ||
612
+ !ch) {
613
+ return buf;
614
+ }
615
+ else if (ch === CHAR_SP) {
616
+ return buf;
617
+ }
618
+ else if (ch === CHAR_LF || ch === DOT) {
619
+ buf += ch;
620
+ scnr.next();
621
+ return fn(detect, buf);
622
+ }
623
+ else if (!isIdentifierStart(ch)) {
624
+ return buf;
625
+ }
626
+ else {
627
+ buf += ch;
628
+ scnr.next();
629
+ return fn(true, buf);
630
+ }
631
+ };
632
+ return fn(false, '');
633
+ }
634
+ function readPlural(scnr) {
635
+ skipSpaces(scnr);
636
+ const plural = eat(scnr, "|" /* TokenChars.Pipe */);
637
+ skipSpaces(scnr);
638
+ return plural;
639
+ }
640
+ // TODO: We need refactoring of token parsing ...
641
+ function readTokenInPlaceholder(scnr, context) {
642
+ let token = null;
643
+ const ch = scnr.currentChar();
644
+ switch (ch) {
645
+ case "{" /* TokenChars.BraceLeft */:
646
+ if (context.braceNest >= 1) {
647
+ emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
648
+ }
649
+ scnr.next();
650
+ token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
651
+ skipSpaces(scnr);
652
+ context.braceNest++;
653
+ return token;
654
+ case "}" /* TokenChars.BraceRight */:
655
+ if (context.braceNest > 0 &&
656
+ context.currentType === 2 /* TokenTypes.BraceLeft */) {
657
+ emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
658
+ }
659
+ scnr.next();
660
+ token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
661
+ context.braceNest--;
662
+ context.braceNest > 0 && skipSpaces(scnr);
663
+ if (context.inLinked && context.braceNest === 0) {
664
+ context.inLinked = false;
665
+ }
666
+ return token;
667
+ case "@" /* TokenChars.LinkedAlias */:
668
+ if (context.braceNest > 0) {
669
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
670
+ }
671
+ token = readTokenInLinked(scnr, context) || getEndToken(context);
672
+ context.braceNest = 0;
673
+ return token;
674
+ default:
675
+ let validNamedIdentifier = true;
676
+ let validListIdentifier = true;
677
+ let validLiteral = true;
678
+ if (isPluralStart(scnr)) {
679
+ if (context.braceNest > 0) {
680
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
681
+ }
682
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
683
+ // reset
684
+ context.braceNest = 0;
685
+ context.inLinked = false;
686
+ return token;
687
+ }
688
+ if (context.braceNest > 0 &&
689
+ (context.currentType === 5 /* TokenTypes.Named */ ||
690
+ context.currentType === 6 /* TokenTypes.List */ ||
691
+ context.currentType === 7 /* TokenTypes.Literal */)) {
692
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
693
+ context.braceNest = 0;
694
+ return readToken(scnr, context);
695
+ }
696
+ if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
697
+ token = getToken(context, 5 /* TokenTypes.Named */, readNamedIdentifier(scnr));
698
+ skipSpaces(scnr);
699
+ return token;
700
+ }
701
+ if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
702
+ token = getToken(context, 6 /* TokenTypes.List */, readListIdentifier(scnr));
703
+ skipSpaces(scnr);
704
+ return token;
705
+ }
706
+ if ((validLiteral = isLiteralStart(scnr, context))) {
707
+ token = getToken(context, 7 /* TokenTypes.Literal */, readLiteral(scnr));
708
+ skipSpaces(scnr);
709
+ return token;
710
+ }
711
+ if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
712
+ // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
713
+ token = getToken(context, 13 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
714
+ emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
715
+ skipSpaces(scnr);
716
+ return token;
717
+ }
718
+ break;
719
+ }
720
+ return token;
721
+ }
722
+ // TODO: We need refactoring of token parsing ...
723
+ function readTokenInLinked(scnr, context) {
724
+ const { currentType } = context;
725
+ let token = null;
726
+ const ch = scnr.currentChar();
727
+ if ((currentType === 8 /* TokenTypes.LinkedAlias */ ||
728
+ currentType === 9 /* TokenTypes.LinkedDot */ ||
729
+ currentType === 12 /* TokenTypes.LinkedModifier */ ||
730
+ currentType === 10 /* TokenTypes.LinkedDelimiter */) &&
731
+ (ch === CHAR_LF || ch === CHAR_SP)) {
732
+ emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
733
+ }
734
+ switch (ch) {
735
+ case "@" /* TokenChars.LinkedAlias */:
736
+ scnr.next();
737
+ token = getToken(context, 8 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
738
+ context.inLinked = true;
739
+ return token;
740
+ case "." /* TokenChars.LinkedDot */:
741
+ skipSpaces(scnr);
742
+ scnr.next();
743
+ return getToken(context, 9 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
744
+ case ":" /* TokenChars.LinkedDelimiter */:
745
+ skipSpaces(scnr);
746
+ scnr.next();
747
+ return getToken(context, 10 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
748
+ default:
749
+ if (isPluralStart(scnr)) {
750
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
751
+ // reset
752
+ context.braceNest = 0;
753
+ context.inLinked = false;
754
+ return token;
755
+ }
756
+ if (isLinkedDotStart(scnr, context) ||
757
+ isLinkedDelimiterStart(scnr, context)) {
758
+ skipSpaces(scnr);
759
+ return readTokenInLinked(scnr, context);
760
+ }
761
+ if (isLinkedModifierStart(scnr, context)) {
762
+ skipSpaces(scnr);
763
+ return getToken(context, 12 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
764
+ }
765
+ if (isLinkedReferStart(scnr, context)) {
766
+ skipSpaces(scnr);
767
+ if (ch === "{" /* TokenChars.BraceLeft */) {
768
+ // scan the placeholder
769
+ return readTokenInPlaceholder(scnr, context) || token;
770
+ }
771
+ else {
772
+ return getToken(context, 11 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
773
+ }
774
+ }
775
+ if (currentType === 8 /* TokenTypes.LinkedAlias */) {
776
+ emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
777
+ }
778
+ context.braceNest = 0;
779
+ context.inLinked = false;
780
+ return readToken(scnr, context);
781
+ }
782
+ }
783
+ // TODO: We need refactoring of token parsing ...
784
+ function readToken(scnr, context) {
785
+ let token = { type: 14 /* TokenTypes.EOF */ };
786
+ if (context.braceNest > 0) {
787
+ return readTokenInPlaceholder(scnr, context) || getEndToken(context);
788
+ }
789
+ if (context.inLinked) {
790
+ return readTokenInLinked(scnr, context) || getEndToken(context);
791
+ }
792
+ const ch = scnr.currentChar();
793
+ switch (ch) {
794
+ case "{" /* TokenChars.BraceLeft */:
795
+ return readTokenInPlaceholder(scnr, context) || getEndToken(context);
796
+ case "}" /* TokenChars.BraceRight */:
797
+ emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
798
+ scnr.next();
799
+ return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
800
+ case "@" /* TokenChars.LinkedAlias */:
801
+ return readTokenInLinked(scnr, context) || getEndToken(context);
802
+ default:
803
+ if (isPluralStart(scnr)) {
804
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
805
+ // reset
806
+ context.braceNest = 0;
807
+ context.inLinked = false;
808
+ return token;
809
+ }
810
+ const { isModulo, hasSpace } = detectModuloStart(scnr);
811
+ if (isModulo) {
812
+ return hasSpace
813
+ ? getToken(context, 0 /* TokenTypes.Text */, readText(scnr))
814
+ : getToken(context, 4 /* TokenTypes.Modulo */, readModulo(scnr));
815
+ }
816
+ if (isTextStart(scnr)) {
817
+ return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
818
+ }
819
+ break;
820
+ }
821
+ return token;
822
+ }
823
+ function nextToken() {
824
+ const { currentType, offset, startLoc, endLoc } = _context;
825
+ _context.lastType = currentType;
826
+ _context.lastOffset = offset;
827
+ _context.lastStartLoc = startLoc;
828
+ _context.lastEndLoc = endLoc;
829
+ _context.offset = currentOffset();
830
+ _context.startLoc = currentPosition();
831
+ if (_scnr.currentChar() === EOF) {
832
+ return getToken(_context, 14 /* TokenTypes.EOF */);
833
+ }
834
+ return readToken(_scnr, _context);
835
+ }
836
+ return {
837
+ nextToken,
838
+ currentOffset,
839
+ currentPosition,
840
+ context
841
+ };
842
+ }
843
+
844
+ const ERROR_DOMAIN$2 = 'parser';
845
+ // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
846
+ const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
847
+ function fromEscapeSequence(match, codePoint4, codePoint6) {
848
+ switch (match) {
849
+ case `\\\\`:
850
+ return `\\`;
851
+ case `\\\'`:
852
+ return `\'`;
853
+ default: {
854
+ const codePoint = parseInt(codePoint4 || codePoint6, 16);
855
+ if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
856
+ return String.fromCodePoint(codePoint);
857
+ }
858
+ // invalid ...
859
+ // Replace them with U+FFFD REPLACEMENT CHARACTER.
860
+ return '�';
861
+ }
862
+ }
863
+ }
864
+ function createParser(options = {}) {
865
+ const location = options.location !== false;
866
+ const { onError } = options;
867
+ function emitError(tokenzer, code, start, offset, ...args) {
868
+ const end = tokenzer.currentPosition();
869
+ end.offset += offset;
870
+ end.column += offset;
871
+ if (onError) {
872
+ const loc = location ? createLocation(start, end) : null;
873
+ const err = createCompileError(code, loc, {
874
+ domain: ERROR_DOMAIN$2,
875
+ args
876
+ });
877
+ onError(err);
878
+ }
879
+ }
880
+ function startNode(type, offset, loc) {
881
+ const node = { type };
882
+ if (location) {
883
+ node.start = offset;
884
+ node.end = offset;
885
+ node.loc = { start: loc, end: loc };
886
+ }
887
+ return node;
888
+ }
889
+ function endNode(node, offset, pos, type) {
890
+ if (type) {
891
+ node.type = type;
892
+ }
893
+ if (location) {
894
+ node.end = offset;
895
+ if (node.loc) {
896
+ node.loc.end = pos;
897
+ }
898
+ }
899
+ }
900
+ function parseText(tokenizer, value) {
901
+ const context = tokenizer.context();
902
+ const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
903
+ node.value = value;
904
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
905
+ return node;
906
+ }
907
+ function parseList(tokenizer, index) {
908
+ const context = tokenizer.context();
909
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
910
+ const node = startNode(5 /* NodeTypes.List */, offset, loc);
911
+ node.index = parseInt(index, 10);
912
+ tokenizer.nextToken(); // skip brach right
913
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
914
+ return node;
915
+ }
916
+ function parseNamed(tokenizer, key) {
917
+ const context = tokenizer.context();
918
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
919
+ const node = startNode(4 /* NodeTypes.Named */, offset, loc);
920
+ node.key = key;
921
+ tokenizer.nextToken(); // skip brach right
922
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
923
+ return node;
924
+ }
925
+ function parseLiteral(tokenizer, value) {
926
+ const context = tokenizer.context();
927
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
928
+ const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
929
+ node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
930
+ tokenizer.nextToken(); // skip brach right
931
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
932
+ return node;
933
+ }
934
+ function parseLinkedModifier(tokenizer) {
935
+ const token = tokenizer.nextToken();
936
+ const context = tokenizer.context();
937
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
938
+ const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
939
+ if (token.type !== 12 /* TokenTypes.LinkedModifier */) {
940
+ // empty modifier
941
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
942
+ node.value = '';
943
+ endNode(node, offset, loc);
944
+ return {
945
+ nextConsumeToken: token,
946
+ node
947
+ };
948
+ }
949
+ // check token
950
+ if (token.value == null) {
951
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
952
+ }
953
+ node.value = token.value || '';
954
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
955
+ return {
956
+ node
957
+ };
958
+ }
959
+ function parseLinkedKey(tokenizer, value) {
960
+ const context = tokenizer.context();
961
+ const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
962
+ node.value = value;
963
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
964
+ return node;
965
+ }
966
+ function parseLinked(tokenizer) {
967
+ const context = tokenizer.context();
968
+ const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
969
+ let token = tokenizer.nextToken();
970
+ if (token.type === 9 /* TokenTypes.LinkedDot */) {
971
+ const parsed = parseLinkedModifier(tokenizer);
972
+ linkedNode.modifier = parsed.node;
973
+ token = parsed.nextConsumeToken || tokenizer.nextToken();
974
+ }
975
+ // asset check token
976
+ if (token.type !== 10 /* TokenTypes.LinkedDelimiter */) {
977
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
978
+ }
979
+ token = tokenizer.nextToken();
980
+ // skip brace left
981
+ if (token.type === 2 /* TokenTypes.BraceLeft */) {
982
+ token = tokenizer.nextToken();
983
+ }
984
+ switch (token.type) {
985
+ case 11 /* TokenTypes.LinkedKey */:
986
+ if (token.value == null) {
987
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
988
+ }
989
+ linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
990
+ break;
991
+ case 5 /* TokenTypes.Named */:
992
+ if (token.value == null) {
993
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
994
+ }
995
+ linkedNode.key = parseNamed(tokenizer, token.value || '');
996
+ break;
997
+ case 6 /* TokenTypes.List */:
998
+ if (token.value == null) {
999
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1000
+ }
1001
+ linkedNode.key = parseList(tokenizer, token.value || '');
1002
+ break;
1003
+ case 7 /* TokenTypes.Literal */:
1004
+ if (token.value == null) {
1005
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1006
+ }
1007
+ linkedNode.key = parseLiteral(tokenizer, token.value || '');
1008
+ break;
1009
+ default:
1010
+ // empty key
1011
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
1012
+ const nextContext = tokenizer.context();
1013
+ const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
1014
+ emptyLinkedKeyNode.value = '';
1015
+ endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
1016
+ linkedNode.key = emptyLinkedKeyNode;
1017
+ endNode(linkedNode, nextContext.offset, nextContext.startLoc);
1018
+ return {
1019
+ nextConsumeToken: token,
1020
+ node: linkedNode
1021
+ };
1022
+ }
1023
+ endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
1024
+ return {
1025
+ node: linkedNode
1026
+ };
1027
+ }
1028
+ function parseMessage(tokenizer) {
1029
+ const context = tokenizer.context();
1030
+ const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
1031
+ ? tokenizer.currentOffset()
1032
+ : context.offset;
1033
+ const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
1034
+ ? context.endLoc
1035
+ : context.startLoc;
1036
+ const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
1037
+ node.items = [];
1038
+ let nextToken = null;
1039
+ do {
1040
+ const token = nextToken || tokenizer.nextToken();
1041
+ nextToken = null;
1042
+ switch (token.type) {
1043
+ case 0 /* TokenTypes.Text */:
1044
+ if (token.value == null) {
1045
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1046
+ }
1047
+ node.items.push(parseText(tokenizer, token.value || ''));
1048
+ break;
1049
+ case 6 /* TokenTypes.List */:
1050
+ if (token.value == null) {
1051
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1052
+ }
1053
+ node.items.push(parseList(tokenizer, token.value || ''));
1054
+ break;
1055
+ case 5 /* TokenTypes.Named */:
1056
+ if (token.value == null) {
1057
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1058
+ }
1059
+ node.items.push(parseNamed(tokenizer, token.value || ''));
1060
+ break;
1061
+ case 7 /* TokenTypes.Literal */:
1062
+ if (token.value == null) {
1063
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1064
+ }
1065
+ node.items.push(parseLiteral(tokenizer, token.value || ''));
1066
+ break;
1067
+ case 8 /* TokenTypes.LinkedAlias */:
1068
+ const parsed = parseLinked(tokenizer);
1069
+ node.items.push(parsed.node);
1070
+ nextToken = parsed.nextConsumeToken || null;
1071
+ break;
1072
+ }
1073
+ } while (context.currentType !== 14 /* TokenTypes.EOF */ &&
1074
+ context.currentType !== 1 /* TokenTypes.Pipe */);
1075
+ // adjust message node loc
1076
+ const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
1077
+ ? context.lastOffset
1078
+ : tokenizer.currentOffset();
1079
+ const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
1080
+ ? context.lastEndLoc
1081
+ : tokenizer.currentPosition();
1082
+ endNode(node, endOffset, endLoc);
1083
+ return node;
1084
+ }
1085
+ function parsePlural(tokenizer, offset, loc, msgNode) {
1086
+ const context = tokenizer.context();
1087
+ let hasEmptyMessage = msgNode.items.length === 0;
1088
+ const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
1089
+ node.cases = [];
1090
+ node.cases.push(msgNode);
1091
+ do {
1092
+ const msg = parseMessage(tokenizer);
1093
+ if (!hasEmptyMessage) {
1094
+ hasEmptyMessage = msg.items.length === 0;
1095
+ }
1096
+ node.cases.push(msg);
1097
+ } while (context.currentType !== 14 /* TokenTypes.EOF */);
1098
+ if (hasEmptyMessage) {
1099
+ emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
1100
+ }
1101
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1102
+ return node;
1103
+ }
1104
+ function parseResource(tokenizer) {
1105
+ const context = tokenizer.context();
1106
+ const { offset, startLoc } = context;
1107
+ const msgNode = parseMessage(tokenizer);
1108
+ if (context.currentType === 14 /* TokenTypes.EOF */) {
1109
+ return msgNode;
1110
+ }
1111
+ else {
1112
+ return parsePlural(tokenizer, offset, startLoc, msgNode);
1113
+ }
1114
+ }
1115
+ function parse(source) {
1116
+ const tokenizer = createTokenizer(source, assign({}, options));
1117
+ const context = tokenizer.context();
1118
+ const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
1119
+ if (location && node.loc) {
1120
+ node.loc.source = source;
1121
+ }
1122
+ node.body = parseResource(tokenizer);
1123
+ if (options.onCacheKey) {
1124
+ node.cacheKey = options.onCacheKey(source);
1125
+ }
1126
+ // assert whether achieved to EOF
1127
+ if (context.currentType !== 14 /* TokenTypes.EOF */) {
1128
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
1129
+ }
1130
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1131
+ return node;
1132
+ }
1133
+ return { parse };
1134
+ }
1135
+ function getTokenCaption(token) {
1136
+ if (token.type === 14 /* TokenTypes.EOF */) {
1137
+ return 'EOF';
1138
+ }
1139
+ const name = (token.value || '').replace(/\r?\n/gu, '\\n');
1140
+ return name.length > 10 ? name.slice(0, 9) + '…' : name;
156
1141
  }
157
1142
 
158
- const EOF = undefined;
159
- const LITERAL_DELIMITER = "'";
160
- const ERROR_DOMAIN$1 = 'tokenizer';
161
- function createTokenizer(source, options = {}) {
162
- const location = options.location !== false;
163
- const _scnr = createScanner(source);
164
- const currentOffset = () => _scnr.index();
165
- const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
166
- const _initLoc = currentPosition();
167
- const _initOffset = currentOffset();
168
- const _context = {
169
- currentType: 14 /* EOF */,
170
- offset: _initOffset,
171
- startLoc: _initLoc,
172
- endLoc: _initLoc,
173
- lastType: 14 /* EOF */,
174
- lastOffset: _initOffset,
175
- lastStartLoc: _initLoc,
176
- lastEndLoc: _initLoc,
177
- braceNest: 0,
178
- inLinked: false,
179
- text: ''
180
- };
181
- const context = () => _context;
182
- const { onError } = options;
183
- function emitError(code, pos, offset, ...args) {
184
- const ctx = context();
185
- pos.column += offset;
186
- pos.offset += offset;
187
- if (onError) {
188
- const loc = createLocation(ctx.startLoc, pos);
189
- const err = createCompileError(code, loc, {
190
- domain: ERROR_DOMAIN$1,
191
- args
192
- });
193
- onError(err);
194
- }
195
- }
196
- function getToken(context, type, value) {
197
- context.endLoc = currentPosition();
198
- context.currentType = type;
199
- const token = { type };
200
- if (location) {
201
- token.loc = createLocation(context.startLoc, context.endLoc);
202
- }
203
- if (value != null) {
204
- token.value = value;
205
- }
206
- return token;
207
- }
208
- const getEndToken = (context) => getToken(context, 14 /* EOF */);
209
- function eat(scnr, ch) {
210
- if (scnr.currentChar() === ch) {
211
- scnr.next();
212
- return ch;
213
- }
214
- else {
215
- emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
216
- return '';
217
- }
218
- }
219
- function peekSpaces(scnr) {
220
- let buf = '';
221
- while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
222
- buf += scnr.currentPeek();
223
- scnr.peek();
224
- }
225
- return buf;
226
- }
227
- function skipSpaces(scnr) {
228
- const buf = peekSpaces(scnr);
229
- scnr.skipToPeek();
230
- return buf;
231
- }
232
- function isIdentifierStart(ch) {
233
- if (ch === EOF) {
234
- return false;
235
- }
236
- const cc = ch.charCodeAt(0);
237
- return ((cc >= 97 && cc <= 122) || // a-z
238
- (cc >= 65 && cc <= 90) || // A-Z
239
- cc === 95 // _
240
- );
241
- }
242
- function isNumberStart(ch) {
243
- if (ch === EOF) {
244
- return false;
245
- }
246
- const cc = ch.charCodeAt(0);
247
- return cc >= 48 && cc <= 57; // 0-9
248
- }
249
- function isNamedIdentifierStart(scnr, context) {
250
- const { currentType } = context;
251
- if (currentType !== 2 /* BraceLeft */) {
252
- return false;
253
- }
254
- peekSpaces(scnr);
255
- const ret = isIdentifierStart(scnr.currentPeek());
256
- scnr.resetPeek();
257
- return ret;
258
- }
259
- function isListIdentifierStart(scnr, context) {
260
- const { currentType } = context;
261
- if (currentType !== 2 /* BraceLeft */) {
262
- return false;
263
- }
264
- peekSpaces(scnr);
265
- const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
266
- const ret = isNumberStart(ch);
267
- scnr.resetPeek();
268
- return ret;
269
- }
270
- function isLiteralStart(scnr, context) {
271
- const { currentType } = context;
272
- if (currentType !== 2 /* BraceLeft */) {
273
- return false;
274
- }
275
- peekSpaces(scnr);
276
- const ret = scnr.currentPeek() === LITERAL_DELIMITER;
277
- scnr.resetPeek();
278
- return ret;
279
- }
280
- function isLinkedDotStart(scnr, context) {
281
- const { currentType } = context;
282
- if (currentType !== 8 /* LinkedAlias */) {
283
- return false;
284
- }
285
- peekSpaces(scnr);
286
- const ret = scnr.currentPeek() === "." /* LinkedDot */;
287
- scnr.resetPeek();
288
- return ret;
289
- }
290
- function isLinkedModifierStart(scnr, context) {
291
- const { currentType } = context;
292
- if (currentType !== 9 /* LinkedDot */) {
293
- return false;
294
- }
295
- peekSpaces(scnr);
296
- const ret = isIdentifierStart(scnr.currentPeek());
297
- scnr.resetPeek();
298
- return ret;
299
- }
300
- function isLinkedDelimiterStart(scnr, context) {
301
- const { currentType } = context;
302
- if (!(currentType === 8 /* LinkedAlias */ ||
303
- currentType === 12 /* LinkedModifier */)) {
304
- return false;
305
- }
306
- peekSpaces(scnr);
307
- const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */;
308
- scnr.resetPeek();
309
- return ret;
310
- }
311
- function isLinkedReferStart(scnr, context) {
312
- const { currentType } = context;
313
- if (currentType !== 10 /* LinkedDelimiter */) {
314
- return false;
315
- }
316
- const fn = () => {
317
- const ch = scnr.currentPeek();
318
- if (ch === "{" /* BraceLeft */) {
319
- return isIdentifierStart(scnr.peek());
320
- }
321
- else if (ch === "@" /* LinkedAlias */ ||
322
- ch === "%" /* Modulo */ ||
323
- ch === "|" /* Pipe */ ||
324
- ch === ":" /* LinkedDelimiter */ ||
325
- ch === "." /* LinkedDot */ ||
326
- ch === CHAR_SP ||
327
- !ch) {
328
- return false;
329
- }
330
- else if (ch === CHAR_LF) {
331
- scnr.peek();
332
- return fn();
333
- }
334
- else {
335
- // other characters
336
- return isIdentifierStart(ch);
337
- }
338
- };
339
- const ret = fn();
340
- scnr.resetPeek();
341
- return ret;
342
- }
343
- function isPluralStart(scnr) {
344
- peekSpaces(scnr);
345
- const ret = scnr.currentPeek() === "|" /* Pipe */;
346
- scnr.resetPeek();
347
- return ret;
348
- }
349
- function detectModuloStart(scnr) {
350
- const spaces = peekSpaces(scnr);
351
- const ret = scnr.currentPeek() === "%" /* Modulo */ &&
352
- scnr.peek() === "{" /* BraceLeft */;
353
- scnr.resetPeek();
354
- return {
355
- isModulo: ret,
356
- hasSpace: spaces.length > 0
357
- };
358
- }
359
- function isTextStart(scnr, reset = true) {
360
- const fn = (hasSpace = false, prev = '', detectModulo = false) => {
361
- const ch = scnr.currentPeek();
362
- if (ch === "{" /* BraceLeft */) {
363
- return prev === "%" /* Modulo */ ? false : hasSpace;
364
- }
365
- else if (ch === "@" /* LinkedAlias */ || !ch) {
366
- return prev === "%" /* Modulo */ ? true : hasSpace;
367
- }
368
- else if (ch === "%" /* Modulo */) {
369
- scnr.peek();
370
- return fn(hasSpace, "%" /* Modulo */, true);
371
- }
372
- else if (ch === "|" /* Pipe */) {
373
- return prev === "%" /* Modulo */ || detectModulo
374
- ? true
375
- : !(prev === CHAR_SP || prev === CHAR_LF);
376
- }
377
- else if (ch === CHAR_SP) {
378
- scnr.peek();
379
- return fn(true, CHAR_SP, detectModulo);
380
- }
381
- else if (ch === CHAR_LF) {
382
- scnr.peek();
383
- return fn(true, CHAR_LF, detectModulo);
384
- }
385
- else {
386
- return true;
387
- }
388
- };
389
- const ret = fn();
390
- reset && scnr.resetPeek();
391
- return ret;
392
- }
393
- function takeChar(scnr, fn) {
394
- const ch = scnr.currentChar();
395
- if (ch === EOF) {
396
- return EOF;
397
- }
398
- if (fn(ch)) {
399
- scnr.next();
400
- return ch;
401
- }
402
- return null;
403
- }
404
- function takeIdentifierChar(scnr) {
405
- const closure = (ch) => {
406
- const cc = ch.charCodeAt(0);
407
- return ((cc >= 97 && cc <= 122) || // a-z
408
- (cc >= 65 && cc <= 90) || // A-Z
409
- (cc >= 48 && cc <= 57) || // 0-9
410
- cc === 95 || // _
411
- cc === 36 // $
412
- );
413
- };
414
- return takeChar(scnr, closure);
415
- }
416
- function takeDigit(scnr) {
417
- const closure = (ch) => {
418
- const cc = ch.charCodeAt(0);
419
- return cc >= 48 && cc <= 57; // 0-9
420
- };
421
- return takeChar(scnr, closure);
422
- }
423
- function takeHexDigit(scnr) {
424
- const closure = (ch) => {
425
- const cc = ch.charCodeAt(0);
426
- return ((cc >= 48 && cc <= 57) || // 0-9
427
- (cc >= 65 && cc <= 70) || // A-F
428
- (cc >= 97 && cc <= 102)); // a-f
429
- };
430
- return takeChar(scnr, closure);
431
- }
432
- function getDigits(scnr) {
433
- let ch = '';
434
- let num = '';
435
- while ((ch = takeDigit(scnr))) {
436
- num += ch;
437
- }
438
- return num;
439
- }
440
- function readModulo(scnr) {
441
- skipSpaces(scnr);
442
- const ch = scnr.currentChar();
443
- if (ch !== "%" /* Modulo */) {
444
- emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
445
- }
446
- scnr.next();
447
- return "%" /* Modulo */;
448
- }
449
- function readText(scnr) {
450
- let buf = '';
451
- while (true) {
452
- const ch = scnr.currentChar();
453
- if (ch === "{" /* BraceLeft */ ||
454
- ch === "}" /* BraceRight */ ||
455
- ch === "@" /* LinkedAlias */ ||
456
- ch === "|" /* Pipe */ ||
457
- !ch) {
458
- break;
459
- }
460
- else if (ch === "%" /* Modulo */) {
461
- if (isTextStart(scnr)) {
462
- buf += ch;
463
- scnr.next();
464
- }
465
- else {
466
- break;
467
- }
468
- }
469
- else if (ch === CHAR_SP || ch === CHAR_LF) {
470
- if (isTextStart(scnr)) {
471
- buf += ch;
472
- scnr.next();
473
- }
474
- else if (isPluralStart(scnr)) {
475
- break;
476
- }
477
- else {
478
- buf += ch;
479
- scnr.next();
480
- }
481
- }
482
- else {
483
- buf += ch;
484
- scnr.next();
485
- }
486
- }
487
- return buf;
488
- }
489
- function readNamedIdentifier(scnr) {
490
- skipSpaces(scnr);
491
- let ch = '';
492
- let name = '';
493
- while ((ch = takeIdentifierChar(scnr))) {
494
- name += ch;
495
- }
496
- if (scnr.currentChar() === EOF) {
497
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
498
- }
499
- return name;
500
- }
501
- function readListIdentifier(scnr) {
502
- skipSpaces(scnr);
503
- let value = '';
504
- if (scnr.currentChar() === '-') {
505
- scnr.next();
506
- value += `-${getDigits(scnr)}`;
507
- }
508
- else {
509
- value += getDigits(scnr);
510
- }
511
- if (scnr.currentChar() === EOF) {
512
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
513
- }
514
- return value;
515
- }
516
- function readLiteral(scnr) {
517
- skipSpaces(scnr);
518
- eat(scnr, `\'`);
519
- let ch = '';
520
- let literal = '';
521
- const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
522
- while ((ch = takeChar(scnr, fn))) {
523
- if (ch === '\\') {
524
- literal += readEscapeSequence(scnr);
525
- }
526
- else {
527
- literal += ch;
528
- }
529
- }
530
- const current = scnr.currentChar();
531
- if (current === CHAR_LF || current === EOF) {
532
- emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
533
- // TODO: Is it correct really?
534
- if (current === CHAR_LF) {
535
- scnr.next();
536
- eat(scnr, `\'`);
537
- }
538
- return literal;
539
- }
540
- eat(scnr, `\'`);
541
- return literal;
542
- }
543
- function readEscapeSequence(scnr) {
544
- const ch = scnr.currentChar();
545
- switch (ch) {
546
- case '\\':
547
- case `\'`:
548
- scnr.next();
549
- return `\\${ch}`;
550
- case 'u':
551
- return readUnicodeEscapeSequence(scnr, ch, 4);
552
- case 'U':
553
- return readUnicodeEscapeSequence(scnr, ch, 6);
554
- default:
555
- emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
556
- return '';
557
- }
558
- }
559
- function readUnicodeEscapeSequence(scnr, unicode, digits) {
560
- eat(scnr, unicode);
561
- let sequence = '';
562
- for (let i = 0; i < digits; i++) {
563
- const ch = takeHexDigit(scnr);
564
- if (!ch) {
565
- emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
566
- break;
567
- }
568
- sequence += ch;
569
- }
570
- return `\\${unicode}${sequence}`;
571
- }
572
- function readInvalidIdentifier(scnr) {
573
- skipSpaces(scnr);
574
- let ch = '';
575
- let identifiers = '';
576
- const closure = (ch) => ch !== "{" /* BraceLeft */ &&
577
- ch !== "}" /* BraceRight */ &&
578
- ch !== CHAR_SP &&
579
- ch !== CHAR_LF;
580
- while ((ch = takeChar(scnr, closure))) {
581
- identifiers += ch;
582
- }
583
- return identifiers;
584
- }
585
- function readLinkedModifier(scnr) {
586
- let ch = '';
587
- let name = '';
588
- while ((ch = takeIdentifierChar(scnr))) {
589
- name += ch;
590
- }
591
- return name;
592
- }
593
- function readLinkedRefer(scnr) {
594
- const fn = (detect = false, buf) => {
595
- const ch = scnr.currentChar();
596
- if (ch === "{" /* BraceLeft */ ||
597
- ch === "%" /* Modulo */ ||
598
- ch === "@" /* LinkedAlias */ ||
599
- ch === "|" /* Pipe */ ||
600
- !ch) {
601
- return buf;
602
- }
603
- else if (ch === CHAR_SP) {
604
- return buf;
605
- }
606
- else if (ch === CHAR_LF) {
607
- buf += ch;
608
- scnr.next();
609
- return fn(detect, buf);
610
- }
611
- else {
612
- buf += ch;
613
- scnr.next();
614
- return fn(true, buf);
615
- }
616
- };
617
- return fn(false, '');
618
- }
619
- function readPlural(scnr) {
620
- skipSpaces(scnr);
621
- const plural = eat(scnr, "|" /* Pipe */);
622
- skipSpaces(scnr);
623
- return plural;
624
- }
625
- // TODO: We need refactoring of token parsing ...
626
- function readTokenInPlaceholder(scnr, context) {
627
- let token = null;
628
- const ch = scnr.currentChar();
629
- switch (ch) {
630
- case "{" /* BraceLeft */:
631
- if (context.braceNest >= 1) {
632
- emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
633
- }
634
- scnr.next();
635
- token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */);
636
- skipSpaces(scnr);
637
- context.braceNest++;
638
- return token;
639
- case "}" /* BraceRight */:
640
- if (context.braceNest > 0 &&
641
- context.currentType === 2 /* BraceLeft */) {
642
- emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
643
- }
644
- scnr.next();
645
- token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
646
- context.braceNest--;
647
- context.braceNest > 0 && skipSpaces(scnr);
648
- if (context.inLinked && context.braceNest === 0) {
649
- context.inLinked = false;
650
- }
651
- return token;
652
- case "@" /* LinkedAlias */:
653
- if (context.braceNest > 0) {
654
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
655
- }
656
- token = readTokenInLinked(scnr, context) || getEndToken(context);
657
- context.braceNest = 0;
658
- return token;
659
- default:
660
- let validNamedIdentifier = true;
661
- let validListIdentifier = true;
662
- let validLiteral = true;
663
- if (isPluralStart(scnr)) {
664
- if (context.braceNest > 0) {
665
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
666
- }
667
- token = getToken(context, 1 /* Pipe */, readPlural(scnr));
668
- // reset
669
- context.braceNest = 0;
670
- context.inLinked = false;
671
- return token;
672
- }
673
- if (context.braceNest > 0 &&
674
- (context.currentType === 5 /* Named */ ||
675
- context.currentType === 6 /* List */ ||
676
- context.currentType === 7 /* Literal */)) {
677
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
678
- context.braceNest = 0;
679
- return readToken(scnr, context);
680
- }
681
- if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
682
- token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr));
683
- skipSpaces(scnr);
684
- return token;
685
- }
686
- if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
687
- token = getToken(context, 6 /* List */, readListIdentifier(scnr));
688
- skipSpaces(scnr);
689
- return token;
690
- }
691
- if ((validLiteral = isLiteralStart(scnr, context))) {
692
- token = getToken(context, 7 /* Literal */, readLiteral(scnr));
693
- skipSpaces(scnr);
694
- return token;
695
- }
696
- if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
697
- // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
698
- token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr));
699
- emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
700
- skipSpaces(scnr);
701
- return token;
702
- }
703
- break;
704
- }
705
- return token;
706
- }
707
- // TODO: We need refactoring of token parsing ...
708
- function readTokenInLinked(scnr, context) {
709
- const { currentType } = context;
710
- let token = null;
711
- const ch = scnr.currentChar();
712
- if ((currentType === 8 /* LinkedAlias */ ||
713
- currentType === 9 /* LinkedDot */ ||
714
- currentType === 12 /* LinkedModifier */ ||
715
- currentType === 10 /* LinkedDelimiter */) &&
716
- (ch === CHAR_LF || ch === CHAR_SP)) {
717
- emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
718
- }
719
- switch (ch) {
720
- case "@" /* LinkedAlias */:
721
- scnr.next();
722
- token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */);
723
- context.inLinked = true;
724
- return token;
725
- case "." /* LinkedDot */:
726
- skipSpaces(scnr);
727
- scnr.next();
728
- return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */);
729
- case ":" /* LinkedDelimiter */:
730
- skipSpaces(scnr);
731
- scnr.next();
732
- return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */);
733
- default:
734
- if (isPluralStart(scnr)) {
735
- token = getToken(context, 1 /* Pipe */, readPlural(scnr));
736
- // reset
737
- context.braceNest = 0;
738
- context.inLinked = false;
739
- return token;
740
- }
741
- if (isLinkedDotStart(scnr, context) ||
742
- isLinkedDelimiterStart(scnr, context)) {
743
- skipSpaces(scnr);
744
- return readTokenInLinked(scnr, context);
745
- }
746
- if (isLinkedModifierStart(scnr, context)) {
747
- skipSpaces(scnr);
748
- return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr));
749
- }
750
- if (isLinkedReferStart(scnr, context)) {
751
- skipSpaces(scnr);
752
- if (ch === "{" /* BraceLeft */) {
753
- // scan the placeholder
754
- return readTokenInPlaceholder(scnr, context) || token;
755
- }
756
- else {
757
- return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr));
758
- }
759
- }
760
- if (currentType === 8 /* LinkedAlias */) {
761
- emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
762
- }
763
- context.braceNest = 0;
764
- context.inLinked = false;
765
- return readToken(scnr, context);
766
- }
767
- }
768
- // TODO: We need refactoring of token parsing ...
769
- function readToken(scnr, context) {
770
- let token = { type: 14 /* EOF */ };
771
- if (context.braceNest > 0) {
772
- return readTokenInPlaceholder(scnr, context) || getEndToken(context);
773
- }
774
- if (context.inLinked) {
775
- return readTokenInLinked(scnr, context) || getEndToken(context);
776
- }
777
- const ch = scnr.currentChar();
778
- switch (ch) {
779
- case "{" /* BraceLeft */:
780
- return readTokenInPlaceholder(scnr, context) || getEndToken(context);
781
- case "}" /* BraceRight */:
782
- emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
783
- scnr.next();
784
- return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
785
- case "@" /* LinkedAlias */:
786
- return readTokenInLinked(scnr, context) || getEndToken(context);
787
- default:
788
- if (isPluralStart(scnr)) {
789
- token = getToken(context, 1 /* Pipe */, readPlural(scnr));
790
- // reset
791
- context.braceNest = 0;
792
- context.inLinked = false;
793
- return token;
794
- }
795
- const { isModulo, hasSpace } = detectModuloStart(scnr);
796
- if (isModulo) {
797
- return hasSpace
798
- ? getToken(context, 0 /* Text */, readText(scnr))
799
- : getToken(context, 4 /* Modulo */, readModulo(scnr));
800
- }
801
- if (isTextStart(scnr)) {
802
- return getToken(context, 0 /* Text */, readText(scnr));
803
- }
804
- break;
805
- }
806
- return token;
807
- }
808
- function nextToken() {
809
- const { currentType, offset, startLoc, endLoc } = _context;
810
- _context.lastType = currentType;
811
- _context.lastOffset = offset;
812
- _context.lastStartLoc = startLoc;
813
- _context.lastEndLoc = endLoc;
814
- _context.offset = currentOffset();
815
- _context.startLoc = currentPosition();
816
- if (_scnr.currentChar() === EOF) {
817
- return getToken(_context, 14 /* EOF */);
818
- }
819
- return readToken(_scnr, _context);
820
- }
821
- return {
822
- nextToken,
823
- currentOffset,
824
- currentPosition,
825
- context
826
- };
1143
+ function createTransformer(ast, options = {} // eslint-disable-line
1144
+ ) {
1145
+ const _context = {
1146
+ ast,
1147
+ helpers: new Set()
1148
+ };
1149
+ const context = () => _context;
1150
+ const helper = (name) => {
1151
+ _context.helpers.add(name);
1152
+ return name;
1153
+ };
1154
+ return { context, helper };
1155
+ }
1156
+ function traverseNodes(nodes, transformer) {
1157
+ for (let i = 0; i < nodes.length; i++) {
1158
+ traverseNode(nodes[i], transformer);
1159
+ }
1160
+ }
1161
+ function traverseNode(node, transformer) {
1162
+ // TODO: if we need pre-hook of transform, should be implemented to here
1163
+ switch (node.type) {
1164
+ case 1 /* NodeTypes.Plural */:
1165
+ traverseNodes(node.cases, transformer);
1166
+ transformer.helper("plural" /* HelperNameMap.PLURAL */);
1167
+ break;
1168
+ case 2 /* NodeTypes.Message */:
1169
+ traverseNodes(node.items, transformer);
1170
+ break;
1171
+ case 6 /* NodeTypes.Linked */:
1172
+ const linked = node;
1173
+ traverseNode(linked.key, transformer);
1174
+ transformer.helper("linked" /* HelperNameMap.LINKED */);
1175
+ transformer.helper("type" /* HelperNameMap.TYPE */);
1176
+ break;
1177
+ case 5 /* NodeTypes.List */:
1178
+ transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1179
+ transformer.helper("list" /* HelperNameMap.LIST */);
1180
+ break;
1181
+ case 4 /* NodeTypes.Named */:
1182
+ transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1183
+ transformer.helper("named" /* HelperNameMap.NAMED */);
1184
+ break;
1185
+ }
1186
+ // TODO: if we need post-hook of transform, should be implemented to here
1187
+ }
1188
+ // transform AST
1189
+ function transform(ast, options = {} // eslint-disable-line
1190
+ ) {
1191
+ const transformer = createTransformer(ast);
1192
+ transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
1193
+ // traverse
1194
+ ast.body && traverseNode(ast.body, transformer);
1195
+ // set meta information
1196
+ const context = transformer.context();
1197
+ ast.helpers = Array.from(context.helpers);
827
1198
  }
828
1199
 
829
- const ERROR_DOMAIN = 'parser';
830
- // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
831
- const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
832
- function fromEscapeSequence(match, codePoint4, codePoint6) {
833
- switch (match) {
834
- case `\\\\`:
835
- return `\\`;
836
- case `\\\'`:
837
- return `\'`;
838
- default: {
839
- const codePoint = parseInt(codePoint4 || codePoint6, 16);
840
- if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
841
- return String.fromCodePoint(codePoint);
842
- }
843
- // invalid ...
844
- // Replace them with U+FFFD REPLACEMENT CHARACTER.
845
- return '�';
846
- }
847
- }
848
- }
849
- function createParser(options = {}) {
850
- const location = options.location !== false;
851
- const { onError } = options;
852
- function emitError(tokenzer, code, start, offset, ...args) {
853
- const end = tokenzer.currentPosition();
854
- end.offset += offset;
855
- end.column += offset;
856
- if (onError) {
857
- const loc = createLocation(start, end);
858
- const err = createCompileError(code, loc, {
859
- domain: ERROR_DOMAIN,
860
- args
861
- });
862
- onError(err);
863
- }
864
- }
865
- function startNode(type, offset, loc) {
866
- const node = {
867
- type,
868
- start: offset,
869
- end: offset
870
- };
871
- if (location) {
872
- node.loc = { start: loc, end: loc };
873
- }
874
- return node;
875
- }
876
- function endNode(node, offset, pos, type) {
877
- node.end = offset;
878
- if (type) {
879
- node.type = type;
880
- }
881
- if (location && node.loc) {
882
- node.loc.end = pos;
883
- }
884
- }
885
- function parseText(tokenizer, value) {
886
- const context = tokenizer.context();
887
- const node = startNode(3 /* Text */, context.offset, context.startLoc);
888
- node.value = value;
889
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
890
- return node;
891
- }
892
- function parseList(tokenizer, index) {
893
- const context = tokenizer.context();
894
- const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
895
- const node = startNode(5 /* List */, offset, loc);
896
- node.index = parseInt(index, 10);
897
- tokenizer.nextToken(); // skip brach right
898
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
899
- return node;
900
- }
901
- function parseNamed(tokenizer, key) {
902
- const context = tokenizer.context();
903
- const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
904
- const node = startNode(4 /* Named */, offset, loc);
905
- node.key = key;
906
- tokenizer.nextToken(); // skip brach right
907
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
908
- return node;
909
- }
910
- function parseLiteral(tokenizer, value) {
911
- const context = tokenizer.context();
912
- const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
913
- const node = startNode(9 /* Literal */, offset, loc);
914
- node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
915
- tokenizer.nextToken(); // skip brach right
916
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
917
- return node;
918
- }
919
- function parseLinkedModifier(tokenizer) {
920
- const token = tokenizer.nextToken();
921
- const context = tokenizer.context();
922
- const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
923
- const node = startNode(8 /* LinkedModifier */, offset, loc);
924
- if (token.type !== 12 /* LinkedModifier */) {
925
- // empty modifier
926
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
927
- node.value = '';
928
- endNode(node, offset, loc);
929
- return {
930
- nextConsumeToken: token,
931
- node
932
- };
933
- }
934
- // check token
935
- if (token.value == null) {
936
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
937
- }
938
- node.value = token.value || '';
939
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
940
- return {
941
- node
942
- };
943
- }
944
- function parseLinkedKey(tokenizer, value) {
945
- const context = tokenizer.context();
946
- const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc);
947
- node.value = value;
948
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
949
- return node;
950
- }
951
- function parseLinked(tokenizer) {
952
- const context = tokenizer.context();
953
- const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc);
954
- let token = tokenizer.nextToken();
955
- if (token.type === 9 /* LinkedDot */) {
956
- const parsed = parseLinkedModifier(tokenizer);
957
- linkedNode.modifier = parsed.node;
958
- token = parsed.nextConsumeToken || tokenizer.nextToken();
959
- }
960
- // asset check token
961
- if (token.type !== 10 /* LinkedDelimiter */) {
962
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
963
- }
964
- token = tokenizer.nextToken();
965
- // skip brace left
966
- if (token.type === 2 /* BraceLeft */) {
967
- token = tokenizer.nextToken();
968
- }
969
- switch (token.type) {
970
- case 11 /* LinkedKey */:
971
- if (token.value == null) {
972
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
973
- }
974
- linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
975
- break;
976
- case 5 /* Named */:
977
- if (token.value == null) {
978
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
979
- }
980
- linkedNode.key = parseNamed(tokenizer, token.value || '');
981
- break;
982
- case 6 /* List */:
983
- if (token.value == null) {
984
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
985
- }
986
- linkedNode.key = parseList(tokenizer, token.value || '');
987
- break;
988
- case 7 /* Literal */:
989
- if (token.value == null) {
990
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
991
- }
992
- linkedNode.key = parseLiteral(tokenizer, token.value || '');
993
- break;
994
- default:
995
- // empty key
996
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
997
- const nextContext = tokenizer.context();
998
- const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc);
999
- emptyLinkedKeyNode.value = '';
1000
- endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
1001
- linkedNode.key = emptyLinkedKeyNode;
1002
- endNode(linkedNode, nextContext.offset, nextContext.startLoc);
1003
- return {
1004
- nextConsumeToken: token,
1005
- node: linkedNode
1006
- };
1007
- }
1008
- endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
1009
- return {
1010
- node: linkedNode
1011
- };
1012
- }
1013
- function parseMessage(tokenizer) {
1014
- const context = tokenizer.context();
1015
- const startOffset = context.currentType === 1 /* Pipe */
1016
- ? tokenizer.currentOffset()
1017
- : context.offset;
1018
- const startLoc = context.currentType === 1 /* Pipe */
1019
- ? context.endLoc
1020
- : context.startLoc;
1021
- const node = startNode(2 /* Message */, startOffset, startLoc);
1022
- node.items = [];
1023
- let nextToken = null;
1024
- do {
1025
- const token = nextToken || tokenizer.nextToken();
1026
- nextToken = null;
1027
- switch (token.type) {
1028
- case 0 /* Text */:
1029
- if (token.value == null) {
1030
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1031
- }
1032
- node.items.push(parseText(tokenizer, token.value || ''));
1033
- break;
1034
- case 6 /* List */:
1035
- if (token.value == null) {
1036
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1037
- }
1038
- node.items.push(parseList(tokenizer, token.value || ''));
1039
- break;
1040
- case 5 /* Named */:
1041
- if (token.value == null) {
1042
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1043
- }
1044
- node.items.push(parseNamed(tokenizer, token.value || ''));
1045
- break;
1046
- case 7 /* Literal */:
1047
- if (token.value == null) {
1048
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1049
- }
1050
- node.items.push(parseLiteral(tokenizer, token.value || ''));
1051
- break;
1052
- case 8 /* LinkedAlias */:
1053
- const parsed = parseLinked(tokenizer);
1054
- node.items.push(parsed.node);
1055
- nextToken = parsed.nextConsumeToken || null;
1056
- break;
1057
- }
1058
- } while (context.currentType !== 14 /* EOF */ &&
1059
- context.currentType !== 1 /* Pipe */);
1060
- // adjust message node loc
1061
- const endOffset = context.currentType === 1 /* Pipe */
1062
- ? context.lastOffset
1063
- : tokenizer.currentOffset();
1064
- const endLoc = context.currentType === 1 /* Pipe */
1065
- ? context.lastEndLoc
1066
- : tokenizer.currentPosition();
1067
- endNode(node, endOffset, endLoc);
1068
- return node;
1069
- }
1070
- function parsePlural(tokenizer, offset, loc, msgNode) {
1071
- const context = tokenizer.context();
1072
- let hasEmptyMessage = msgNode.items.length === 0;
1073
- const node = startNode(1 /* Plural */, offset, loc);
1074
- node.cases = [];
1075
- node.cases.push(msgNode);
1076
- do {
1077
- const msg = parseMessage(tokenizer);
1078
- if (!hasEmptyMessage) {
1079
- hasEmptyMessage = msg.items.length === 0;
1080
- }
1081
- node.cases.push(msg);
1082
- } while (context.currentType !== 14 /* EOF */);
1083
- if (hasEmptyMessage) {
1084
- emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
1085
- }
1086
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1087
- return node;
1088
- }
1089
- function parseResource(tokenizer) {
1090
- const context = tokenizer.context();
1091
- const { offset, startLoc } = context;
1092
- const msgNode = parseMessage(tokenizer);
1093
- if (context.currentType === 14 /* EOF */) {
1094
- return msgNode;
1095
- }
1096
- else {
1097
- return parsePlural(tokenizer, offset, startLoc, msgNode);
1098
- }
1099
- }
1100
- function parse(source) {
1101
- const tokenizer = createTokenizer(source, assign({}, options));
1102
- const context = tokenizer.context();
1103
- const node = startNode(0 /* Resource */, context.offset, context.startLoc);
1104
- if (location && node.loc) {
1105
- node.loc.source = source;
1106
- }
1107
- node.body = parseResource(tokenizer);
1108
- // assert whether achieved to EOF
1109
- if (context.currentType !== 14 /* EOF */) {
1110
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
1111
- }
1112
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1113
- return node;
1114
- }
1115
- return { parse };
1116
- }
1117
- function getTokenCaption(token) {
1118
- if (token.type === 14 /* EOF */) {
1119
- return 'EOF';
1120
- }
1121
- const name = (token.value || '').replace(/\r?\n/gu, '\\n');
1122
- return name.length > 10 ? name.slice(0, 9) + '…' : name;
1200
+ function optimize(ast) {
1201
+ const body = ast.body;
1202
+ if (body.type === 2 /* NodeTypes.Message */) {
1203
+ optimizeMessageNode(body);
1204
+ }
1205
+ else {
1206
+ body.cases.forEach(c => optimizeMessageNode(c));
1207
+ }
1208
+ return ast;
1209
+ }
1210
+ function optimizeMessageNode(message) {
1211
+ if (message.items.length === 1) {
1212
+ const item = message.items[0];
1213
+ if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
1214
+ message.static = item.value;
1215
+ delete item.value; // optimization for size
1216
+ }
1217
+ }
1218
+ else {
1219
+ const values = [];
1220
+ for (let i = 0; i < message.items.length; i++) {
1221
+ const item = message.items[i];
1222
+ if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
1223
+ break;
1224
+ }
1225
+ if (item.value == null) {
1226
+ break;
1227
+ }
1228
+ values.push(item.value);
1229
+ }
1230
+ if (values.length === message.items.length) {
1231
+ message.static = join(values);
1232
+ for (let i = 0; i < message.items.length; i++) {
1233
+ const item = message.items[i];
1234
+ if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
1235
+ delete item.value; // optimization for size
1236
+ }
1237
+ }
1238
+ }
1239
+ }
1123
1240
  }
1124
1241
 
1125
- function createTransformer(ast, options = {} // eslint-disable-line
1126
- ) {
1127
- const _context = {
1128
- ast,
1129
- helpers: new Set()
1130
- };
1131
- const context = () => _context;
1132
- const helper = (name) => {
1133
- _context.helpers.add(name);
1134
- return name;
1135
- };
1136
- return { context, helper };
1137
- }
1138
- function traverseNodes(nodes, transformer) {
1139
- for (let i = 0; i < nodes.length; i++) {
1140
- traverseNode(nodes[i], transformer);
1141
- }
1142
- }
1143
- function traverseNode(node, transformer) {
1144
- // TODO: if we need pre-hook of transform, should be implemented to here
1145
- switch (node.type) {
1146
- case 1 /* Plural */:
1147
- traverseNodes(node.cases, transformer);
1148
- transformer.helper("plural" /* PLURAL */);
1149
- break;
1150
- case 2 /* Message */:
1151
- traverseNodes(node.items, transformer);
1152
- break;
1153
- case 6 /* Linked */:
1154
- const linked = node;
1155
- traverseNode(linked.key, transformer);
1156
- transformer.helper("linked" /* LINKED */);
1157
- transformer.helper("type" /* TYPE */);
1158
- break;
1159
- case 5 /* List */:
1160
- transformer.helper("interpolate" /* INTERPOLATE */);
1161
- transformer.helper("list" /* LIST */);
1162
- break;
1163
- case 4 /* Named */:
1164
- transformer.helper("interpolate" /* INTERPOLATE */);
1165
- transformer.helper("named" /* NAMED */);
1166
- break;
1167
- }
1168
- // TODO: if we need post-hook of transform, should be implemented to here
1169
- }
1170
- // transform AST
1171
- function transform(ast, options = {} // eslint-disable-line
1172
- ) {
1173
- const transformer = createTransformer(ast);
1174
- transformer.helper("normalize" /* NORMALIZE */);
1175
- // traverse
1176
- ast.body && traverseNode(ast.body, transformer);
1177
- // set meta information
1178
- const context = transformer.context();
1179
- ast.helpers = Array.from(context.helpers);
1242
+ const ERROR_DOMAIN$1 = 'minifier';
1243
+ /* eslint-disable @typescript-eslint/no-explicit-any */
1244
+ function minify(node) {
1245
+ node.t = node.type;
1246
+ switch (node.type) {
1247
+ case 0 /* NodeTypes.Resource */:
1248
+ const resource = node;
1249
+ minify(resource.body);
1250
+ resource.b = resource.body;
1251
+ delete resource.body;
1252
+ break;
1253
+ case 1 /* NodeTypes.Plural */:
1254
+ const plural = node;
1255
+ const cases = plural.cases;
1256
+ for (let i = 0; i < cases.length; i++) {
1257
+ minify(cases[i]);
1258
+ }
1259
+ plural.c = cases;
1260
+ delete plural.cases;
1261
+ break;
1262
+ case 2 /* NodeTypes.Message */:
1263
+ const message = node;
1264
+ const items = message.items;
1265
+ for (let i = 0; i < items.length; i++) {
1266
+ minify(items[i]);
1267
+ }
1268
+ message.i = items;
1269
+ delete message.items;
1270
+ if (message.static) {
1271
+ message.s = message.static;
1272
+ delete message.static;
1273
+ }
1274
+ break;
1275
+ case 3 /* NodeTypes.Text */:
1276
+ case 9 /* NodeTypes.Literal */:
1277
+ case 8 /* NodeTypes.LinkedModifier */:
1278
+ case 7 /* NodeTypes.LinkedKey */:
1279
+ const valueNode = node;
1280
+ if (valueNode.value) {
1281
+ valueNode.v = valueNode.value;
1282
+ delete valueNode.value;
1283
+ }
1284
+ break;
1285
+ case 6 /* NodeTypes.Linked */:
1286
+ const linked = node;
1287
+ minify(linked.key);
1288
+ linked.k = linked.key;
1289
+ delete linked.key;
1290
+ if (linked.modifier) {
1291
+ minify(linked.modifier);
1292
+ linked.m = linked.modifier;
1293
+ delete linked.modifier;
1294
+ }
1295
+ break;
1296
+ case 5 /* NodeTypes.List */:
1297
+ const list = node;
1298
+ list.i = list.index;
1299
+ delete list.index;
1300
+ break;
1301
+ case 4 /* NodeTypes.Named */:
1302
+ const named = node;
1303
+ named.k = named.key;
1304
+ delete named.key;
1305
+ break;
1306
+ default:
1307
+ if ((process.env.NODE_ENV !== 'production')) {
1308
+ throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {
1309
+ domain: ERROR_DOMAIN$1,
1310
+ args: [node.type]
1311
+ });
1312
+ }
1313
+ }
1314
+ delete node.type;
1180
1315
  }
1316
+ /* eslint-enable @typescript-eslint/no-explicit-any */
1181
1317
 
1182
- function createCodeGenerator(ast, options) {
1183
- const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
1184
- const _context = {
1185
- source: ast.loc.source,
1186
- filename,
1187
- code: '',
1188
- column: 1,
1189
- line: 1,
1190
- offset: 0,
1191
- map: undefined,
1192
- breakLineCode,
1193
- needIndent: _needIndent,
1194
- indentLevel: 0
1195
- };
1196
- const context = () => _context;
1197
- function push(code, node) {
1198
- _context.code += code;
1199
- }
1200
- function _newline(n, withBreakLine = true) {
1201
- const _breakLineCode = withBreakLine ? breakLineCode : '';
1202
- push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
1203
- }
1204
- function indent(withNewLine = true) {
1205
- const level = ++_context.indentLevel;
1206
- withNewLine && _newline(level);
1207
- }
1208
- function deindent(withNewLine = true) {
1209
- const level = --_context.indentLevel;
1210
- withNewLine && _newline(level);
1211
- }
1212
- function newline() {
1213
- _newline(_context.indentLevel);
1214
- }
1215
- const helper = (key) => `_${key}`;
1216
- const needIndent = () => _context.needIndent;
1217
- return {
1218
- context,
1219
- push,
1220
- indent,
1221
- deindent,
1222
- newline,
1223
- helper,
1224
- needIndent
1225
- };
1226
- }
1227
- function generateLinkedNode(generator, node) {
1228
- const { helper } = generator;
1229
- generator.push(`${helper("linked" /* LINKED */)}(`);
1230
- generateNode(generator, node.key);
1231
- if (node.modifier) {
1232
- generator.push(`, `);
1233
- generateNode(generator, node.modifier);
1234
- generator.push(`, _type`);
1235
- }
1236
- else {
1237
- generator.push(`, undefined, _type`);
1238
- }
1239
- generator.push(`)`);
1240
- }
1241
- function generateMessageNode(generator, node) {
1242
- const { helper, needIndent } = generator;
1243
- generator.push(`${helper("normalize" /* NORMALIZE */)}([`);
1244
- generator.indent(needIndent());
1245
- const length = node.items.length;
1246
- for (let i = 0; i < length; i++) {
1247
- generateNode(generator, node.items[i]);
1248
- if (i === length - 1) {
1249
- break;
1250
- }
1251
- generator.push(', ');
1252
- }
1253
- generator.deindent(needIndent());
1254
- generator.push('])');
1255
- }
1256
- function generatePluralNode(generator, node) {
1257
- const { helper, needIndent } = generator;
1258
- if (node.cases.length > 1) {
1259
- generator.push(`${helper("plural" /* PLURAL */)}([`);
1260
- generator.indent(needIndent());
1261
- const length = node.cases.length;
1262
- for (let i = 0; i < length; i++) {
1263
- generateNode(generator, node.cases[i]);
1264
- if (i === length - 1) {
1265
- break;
1266
- }
1267
- generator.push(', ');
1268
- }
1269
- generator.deindent(needIndent());
1270
- generator.push(`])`);
1271
- }
1272
- }
1273
- function generateResource(generator, node) {
1274
- if (node.body) {
1275
- generateNode(generator, node.body);
1276
- }
1277
- else {
1278
- generator.push('null');
1279
- }
1280
- }
1281
- function generateNode(generator, node) {
1282
- const { helper } = generator;
1283
- switch (node.type) {
1284
- case 0 /* Resource */:
1285
- generateResource(generator, node);
1286
- break;
1287
- case 1 /* Plural */:
1288
- generatePluralNode(generator, node);
1289
- break;
1290
- case 2 /* Message */:
1291
- generateMessageNode(generator, node);
1292
- break;
1293
- case 6 /* Linked */:
1294
- generateLinkedNode(generator, node);
1295
- break;
1296
- case 8 /* LinkedModifier */:
1297
- generator.push(JSON.stringify(node.value), node);
1298
- break;
1299
- case 7 /* LinkedKey */:
1300
- generator.push(JSON.stringify(node.value), node);
1301
- break;
1302
- case 5 /* List */:
1303
- generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node);
1304
- break;
1305
- case 4 /* Named */:
1306
- generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node);
1307
- break;
1308
- case 9 /* Literal */:
1309
- generator.push(JSON.stringify(node.value), node);
1310
- break;
1311
- case 3 /* Text */:
1312
- generator.push(JSON.stringify(node.value), node);
1313
- break;
1314
- default:
1315
- if ((process.env.NODE_ENV !== 'production')) {
1316
- throw new Error(`unhandled codegen node type: ${node.type}`);
1317
- }
1318
- }
1319
- }
1320
- // generate code from AST
1321
- const generate = (ast, options = {} // eslint-disable-line
1322
- ) => {
1323
- const mode = isString(options.mode) ? options.mode : 'normal';
1324
- const filename = isString(options.filename)
1325
- ? options.filename
1326
- : 'message.intl';
1327
- const sourceMap = !!options.sourceMap;
1328
- // prettier-ignore
1329
- const breakLineCode = options.breakLineCode != null
1330
- ? options.breakLineCode
1331
- : mode === 'arrow'
1332
- ? ';'
1333
- : '\n';
1334
- const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
1335
- const helpers = ast.helpers || [];
1336
- const generator = createCodeGenerator(ast, {
1337
- mode,
1338
- filename,
1339
- sourceMap,
1340
- breakLineCode,
1341
- needIndent
1342
- });
1343
- generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
1344
- generator.indent(needIndent);
1345
- if (helpers.length > 0) {
1346
- generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`);
1347
- generator.newline();
1348
- }
1349
- generator.push(`return `);
1350
- generateNode(generator, ast);
1351
- generator.deindent(needIndent);
1352
- generator.push(`}`);
1353
- const { code, map } = generator.context();
1354
- return {
1355
- ast,
1356
- code,
1357
- map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
1358
- };
1318
+ const ERROR_DOMAIN = 'parser';
1319
+ function createCodeGenerator(ast, options) {
1320
+ const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
1321
+ const location = options.location !== false;
1322
+ const _context = {
1323
+ filename,
1324
+ code: '',
1325
+ column: 1,
1326
+ line: 1,
1327
+ offset: 0,
1328
+ map: undefined,
1329
+ breakLineCode,
1330
+ needIndent: _needIndent,
1331
+ indentLevel: 0
1332
+ };
1333
+ if (location && ast.loc) {
1334
+ _context.source = ast.loc.source;
1335
+ }
1336
+ const context = () => _context;
1337
+ function push(code, node) {
1338
+ _context.code += code;
1339
+ }
1340
+ function _newline(n, withBreakLine = true) {
1341
+ const _breakLineCode = withBreakLine ? breakLineCode : '';
1342
+ push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
1343
+ }
1344
+ function indent(withNewLine = true) {
1345
+ const level = ++_context.indentLevel;
1346
+ withNewLine && _newline(level);
1347
+ }
1348
+ function deindent(withNewLine = true) {
1349
+ const level = --_context.indentLevel;
1350
+ withNewLine && _newline(level);
1351
+ }
1352
+ function newline() {
1353
+ _newline(_context.indentLevel);
1354
+ }
1355
+ const helper = (key) => `_${key}`;
1356
+ const needIndent = () => _context.needIndent;
1357
+ return {
1358
+ context,
1359
+ push,
1360
+ indent,
1361
+ deindent,
1362
+ newline,
1363
+ helper,
1364
+ needIndent
1365
+ };
1366
+ }
1367
+ function generateLinkedNode(generator, node) {
1368
+ const { helper } = generator;
1369
+ generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
1370
+ generateNode(generator, node.key);
1371
+ if (node.modifier) {
1372
+ generator.push(`, `);
1373
+ generateNode(generator, node.modifier);
1374
+ generator.push(`, _type`);
1375
+ }
1376
+ else {
1377
+ generator.push(`, undefined, _type`);
1378
+ }
1379
+ generator.push(`)`);
1380
+ }
1381
+ function generateMessageNode(generator, node) {
1382
+ const { helper, needIndent } = generator;
1383
+ generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
1384
+ generator.indent(needIndent());
1385
+ const length = node.items.length;
1386
+ for (let i = 0; i < length; i++) {
1387
+ generateNode(generator, node.items[i]);
1388
+ if (i === length - 1) {
1389
+ break;
1390
+ }
1391
+ generator.push(', ');
1392
+ }
1393
+ generator.deindent(needIndent());
1394
+ generator.push('])');
1395
+ }
1396
+ function generatePluralNode(generator, node) {
1397
+ const { helper, needIndent } = generator;
1398
+ if (node.cases.length > 1) {
1399
+ generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
1400
+ generator.indent(needIndent());
1401
+ const length = node.cases.length;
1402
+ for (let i = 0; i < length; i++) {
1403
+ generateNode(generator, node.cases[i]);
1404
+ if (i === length - 1) {
1405
+ break;
1406
+ }
1407
+ generator.push(', ');
1408
+ }
1409
+ generator.deindent(needIndent());
1410
+ generator.push(`])`);
1411
+ }
1412
+ }
1413
+ function generateResource(generator, node) {
1414
+ if (node.body) {
1415
+ generateNode(generator, node.body);
1416
+ }
1417
+ else {
1418
+ generator.push('null');
1419
+ }
1420
+ }
1421
+ function generateNode(generator, node) {
1422
+ const { helper } = generator;
1423
+ switch (node.type) {
1424
+ case 0 /* NodeTypes.Resource */:
1425
+ generateResource(generator, node);
1426
+ break;
1427
+ case 1 /* NodeTypes.Plural */:
1428
+ generatePluralNode(generator, node);
1429
+ break;
1430
+ case 2 /* NodeTypes.Message */:
1431
+ generateMessageNode(generator, node);
1432
+ break;
1433
+ case 6 /* NodeTypes.Linked */:
1434
+ generateLinkedNode(generator, node);
1435
+ break;
1436
+ case 8 /* NodeTypes.LinkedModifier */:
1437
+ generator.push(JSON.stringify(node.value), node);
1438
+ break;
1439
+ case 7 /* NodeTypes.LinkedKey */:
1440
+ generator.push(JSON.stringify(node.value), node);
1441
+ break;
1442
+ case 5 /* NodeTypes.List */:
1443
+ generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
1444
+ break;
1445
+ case 4 /* NodeTypes.Named */:
1446
+ generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
1447
+ break;
1448
+ case 9 /* NodeTypes.Literal */:
1449
+ generator.push(JSON.stringify(node.value), node);
1450
+ break;
1451
+ case 3 /* NodeTypes.Text */:
1452
+ generator.push(JSON.stringify(node.value), node);
1453
+ break;
1454
+ default:
1455
+ if ((process.env.NODE_ENV !== 'production')) {
1456
+ throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {
1457
+ domain: ERROR_DOMAIN,
1458
+ args: [node.type]
1459
+ });
1460
+ }
1461
+ }
1462
+ }
1463
+ // generate code from AST
1464
+ const generate = (ast, options = {} // eslint-disable-line
1465
+ ) => {
1466
+ const mode = isString(options.mode) ? options.mode : 'normal';
1467
+ const filename = isString(options.filename)
1468
+ ? options.filename
1469
+ : 'message.intl';
1470
+ const sourceMap = !!options.sourceMap;
1471
+ // prettier-ignore
1472
+ const breakLineCode = options.breakLineCode != null
1473
+ ? options.breakLineCode
1474
+ : mode === 'arrow'
1475
+ ? ';'
1476
+ : '\n';
1477
+ const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
1478
+ const helpers = ast.helpers || [];
1479
+ const generator = createCodeGenerator(ast, {
1480
+ mode,
1481
+ filename,
1482
+ sourceMap,
1483
+ breakLineCode,
1484
+ needIndent
1485
+ });
1486
+ generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
1487
+ generator.indent(needIndent);
1488
+ if (helpers.length > 0) {
1489
+ generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
1490
+ generator.newline();
1491
+ }
1492
+ generator.push(`return `);
1493
+ generateNode(generator, ast);
1494
+ generator.deindent(needIndent);
1495
+ generator.push(`}`);
1496
+ delete ast.helpers;
1497
+ const { code, map } = generator.context();
1498
+ return {
1499
+ ast,
1500
+ code,
1501
+ map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
1502
+ };
1359
1503
  };
1360
1504
 
1361
- function baseCompile(source, options = {}) {
1362
- const assignedOptions = assign({}, options);
1363
- // parse source codes
1364
- const parser = createParser(assignedOptions);
1365
- const ast = parser.parse(source);
1366
- // transform ASTs
1367
- transform(ast, assignedOptions);
1368
- // generate javascript codes
1369
- return generate(ast, assignedOptions);
1505
+ function baseCompile(source, options = {}) {
1506
+ const assignedOptions = assign({}, options);
1507
+ const jit = !!assignedOptions.jit;
1508
+ const enalbeMinify = !!assignedOptions.minify;
1509
+ const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
1510
+ // parse source codes
1511
+ const parser = createParser(assignedOptions);
1512
+ const ast = parser.parse(source);
1513
+ if (!jit) {
1514
+ // transform ASTs
1515
+ transform(ast, assignedOptions);
1516
+ // generate javascript codes
1517
+ return generate(ast, assignedOptions);
1518
+ }
1519
+ else {
1520
+ // optimize ASTs
1521
+ enambeOptimize && optimize(ast);
1522
+ // minimize ASTs
1523
+ enalbeMinify && minify(ast);
1524
+ // In JIT mode, no ast transform, no code generation.
1525
+ return { ast, code: '' };
1526
+ }
1370
1527
  }
1371
1528
 
1372
- export { CompileErrorCodes, ERROR_DOMAIN, LocationStub, baseCompile, createCompileError, createLocation, createParser, createPosition, defaultOnError, errorMessages };
1529
+ export { CompileErrorCodes, ERROR_DOMAIN$2 as ERROR_DOMAIN, LOCATION_STUB, baseCompile, createCompileError, createLocation, createParser, createPosition, defaultOnError, detectHtmlTag, errorMessages };