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