@intlify/message-compiler 9.3.0-beta.2 → 9.3.0-beta.21

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