-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathparser.js
811 lines (629 loc) · 16.6 KB
/
parser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
/* eslint no-magic-numbers: [0] */
import * as AST from "./ast";
import { FTLParserStream } from "./ftlstream";
import { ParseError } from "./errors";
const trailingWSRe = /[ \t\n\r]+$/;
function withSpan(fn) {
return function(ps, ...args) {
if (!this.withSpans) {
return fn.call(this, ps, ...args);
}
let start = ps.getIndex();
const node = fn.call(this, ps, ...args);
// Don't re-add the span if the node already has it. This may happen when
// one decorated function calls another decorated function.
if (node.span) {
return node;
}
// Spans of Messages should include the attached Comment.
if (node.type === "Message") {
if (node.comment !== null) {
start = node.comment.span.start;
}
}
const end = ps.getIndex();
node.addSpan(start, end);
return node;
};
}
export default class FluentParser {
constructor({
withSpans = true,
} = {}) {
this.withSpans = withSpans;
// Poor man's decorators.
[
"getComment", "getMessage", "getTerm", "getAttribute", "getIdentifier",
"getTermIdentifier", "getVariant", "getVariantName", "getNumber",
"getValue", "getPattern", "getVariantList", "getTextElement",
"getPlaceable", "getExpression", "getSelectorExpression", "getCallArg",
"getString", "getLiteral", "getVariantList"
].forEach(
name => this[name] = withSpan(this[name])
);
}
parse(source) {
const ps = new FTLParserStream(source);
ps.skipBlankLines();
const entries = [];
let lastComment = null;
while (ps.current()) {
const entry = this.getEntryOrJunk(ps);
const blankLines = ps.skipBlankLines();
// Regular Comments require special logic. Comments may be attached to
// Messages or Terms if they are followed immediately by them. However
// they should parse as standalone when they're followed by Junk.
// Consequently, we only attach Comments once we know that the Message
// or the Term parsed successfully.
if (entry.type === "Comment" && blankLines === 0 && ps.current()) {
// Stash the comment and decide what to do with it in the next pass.
lastComment = entry;
continue;
}
if (lastComment) {
if (entry.type === "Message" || entry.type === "Term") {
entry.comment = lastComment;
} else {
entries.push(lastComment);
}
// In either case, the stashed comment has been dealt with; clear it.
lastComment = null;
}
// No special logic for other types of entries.
entries.push(entry);
}
const res = new AST.Resource(entries);
if (this.withSpans) {
res.addSpan(0, ps.getIndex());
}
return res;
}
/*
* Parse the first Message or Term in `source`.
*
* Skip all encountered comments and start parsing at the first Message or
* Term start. Return Junk if the parsing is not successful.
*
* Preceding comments are ignored unless they contain syntax errors
* themselves, in which case Junk for the invalid comment is returned.
*/
parseEntry(source) {
const ps = new FTLParserStream(source);
ps.skipBlankLines();
while (ps.currentIs("#")) {
const skipped = this.getEntryOrJunk(ps);
if (skipped.type === "Junk") {
// Don't skip Junk comments.
return skipped;
}
ps.skipBlankLines();
}
return this.getEntryOrJunk(ps);
}
getEntryOrJunk(ps) {
const entryStartPos = ps.getIndex();
try {
return this.getEntry(ps);
} catch (err) {
if (!(err instanceof ParseError)) {
throw err;
}
const errorIndex = ps.getIndex();
ps.skipToNextEntryStart();
const nextEntryStart = ps.getIndex();
// Create a Junk instance
const slice = ps.getSlice(entryStartPos, nextEntryStart);
const junk = new AST.Junk(slice);
if (this.withSpans) {
junk.addSpan(entryStartPos, nextEntryStart);
}
const annot = new AST.Annotation(err.code, err.args, err.message);
annot.addSpan(errorIndex, errorIndex);
junk.addAnnotation(annot);
return junk;
}
}
getEntry(ps) {
if (ps.currentIs("#")) {
return this.getComment(ps);
}
if (ps.currentIs("-")) {
return this.getTerm(ps);
}
if (ps.isIdentifierStart()) {
return this.getMessage(ps);
}
throw new ParseError("E0002");
}
getComment(ps) {
// 0 - comment
// 1 - group comment
// 2 - resource comment
let level = -1;
let content = "";
while (true) {
let i = -1;
while (ps.currentIs("#") && (i < (level === -1 ? 2 : level))) {
ps.next();
i++;
}
if (level === -1) {
level = i;
}
if (!ps.currentIs("\n")) {
ps.expectChar(" ");
let ch;
while ((ch = ps.takeChar(x => x !== "\n"))) {
content += ch;
}
}
if (!ps.currentIs(undefined)) {
content += "\n";
} else {
break;
}
if (ps.isPeekNextLineComment(level, false)) {
ps.next();
} else {
break;
}
}
let Comment;
switch (level) {
case 0:
Comment = AST.Comment;
break;
case 1:
Comment = AST.GroupComment;
break;
case 2:
Comment = AST.ResourceComment;
break;
}
return new Comment(content);
}
getMessage(ps) {
const id = this.getIdentifier(ps);
ps.skipInlineWS();
ps.expectChar("=");
if (ps.isPeekValueStart()) {
ps.skipIndent();
var pattern = this.getPattern(ps);
} else {
ps.skipInlineWS();
}
if (ps.isPeekNextLineAttributeStart()) {
var attrs = this.getAttributes(ps);
}
if (pattern === undefined && attrs === undefined) {
throw new ParseError("E0005", id.name);
}
return new AST.Message(id, pattern, attrs);
}
getTerm(ps) {
const id = this.getTermIdentifier(ps);
ps.skipInlineWS();
ps.expectChar("=");
if (ps.isPeekValueStart()) {
ps.skipIndent();
var pattern = this.getValue(ps);
} else {
throw new ParseError("E0006", id.name);
}
if (ps.isPeekNextLineAttributeStart()) {
var attrs = this.getAttributes(ps);
}
return new AST.Term(id, pattern, attrs);
}
getAttribute(ps) {
ps.expectChar(".");
const key = this.getIdentifier(ps);
ps.skipInlineWS();
ps.expectChar("=");
if (ps.isPeekValueStart()) {
ps.skipIndent();
const value = this.getPattern(ps);
return new AST.Attribute(key, value);
}
throw new ParseError("E0012");
}
getAttributes(ps) {
const attrs = [];
while (true) {
const lineStart = ps.getIndex() + 1;
ps.expectIndent();
try {
const attr = this.getAttribute(ps);
attrs.push(attr);
} catch (err) {
ps.setIndex(lineStart);
return attrs;
}
if (!ps.isPeekNextLineAttributeStart()) {
break;
}
}
return attrs;
}
getIdentifier(ps) {
let name = ps.takeIDStart();
let ch;
while ((ch = ps.takeIDChar())) {
name += ch;
}
return new AST.Identifier(name);
}
getVariantKey(ps) {
const ch = ps.current();
if (!ch) {
throw new ParseError("E0013");
}
const cc = ch.charCodeAt(0);
if ((cc >= 48 && cc <= 57) || cc === 45) { // 0-9, -
return this.getNumber(ps);
}
return this.getVariantName(ps);
}
getVariant(ps, hasDefault) {
let defaultIndex = false;
if (ps.currentIs("*")) {
if (hasDefault) {
throw new ParseError("E0015");
}
ps.next();
defaultIndex = true;
hasDefault = true;
}
ps.expectChar("[");
const key = this.getVariantKey(ps);
ps.expectChar("]");
if (ps.isPeekValueStart()) {
ps.skipIndent();
const value = this.getValue(ps);
return new AST.Variant(key, value, defaultIndex);
}
throw new ParseError("E0012");
}
getVariants(ps) {
const variants = [];
let hasDefault = false;
while (true) {
ps.expectIndent();
const variant = this.getVariant(ps, hasDefault);
if (variant.default) {
hasDefault = true;
}
variants.push(variant);
if (!ps.isPeekNextLineVariantStart()) {
break;
}
}
if (!hasDefault) {
throw new ParseError("E0010");
}
return variants;
}
getVariantName(ps) {
let name = ps.takeIDStart();
while (true) {
const ch = ps.takeVariantNameChar();
if (ch) {
name += ch;
} else {
break;
}
}
return new AST.VariantName(name.replace(trailingWSRe, ""));
}
getDigits(ps) {
let num = "";
let ch;
while ((ch = ps.takeDigit())) {
num += ch;
}
if (num.length === 0) {
throw new ParseError("E0004", "0-9");
}
return num;
}
getNumber(ps) {
let num = "";
if (ps.currentIs("-")) {
num += "-";
ps.next();
}
num = `${num}${this.getDigits(ps)}`;
if (ps.currentIs(".")) {
num += ".";
ps.next();
num = `${num}${this.getDigits(ps)}`;
}
return new AST.NumberLiteral(num);
}
getValue(ps) {
if (ps.currentIs("{")) {
ps.peek();
ps.peekInlineWS();
if (ps.isPeekNextLineVariantStart()) {
return this.getVariantList(ps);
}
}
return this.getPattern(ps);
}
getVariantList(ps) {
ps.expectChar("{");
ps.skipInlineWS();
const variants = this.getVariants(ps);
ps.expectIndent();
ps.expectChar("}");
return new AST.VariantList(variants);
}
getPattern(ps) {
const elements = [];
ps.skipInlineWS();
let ch;
while ((ch = ps.current())) {
// The end condition for getPattern's while loop is a newline
// which is not followed by a valid pattern continuation.
if (ch === "\n" && !ps.isPeekNextLineValue()) {
break;
}
if (ch === "{") {
const element = this.getPlaceable(ps);
elements.push(element);
} else {
const element = this.getTextElement(ps);
elements.push(element);
}
}
// Trim trailing whitespace.
const lastElement = elements[elements.length - 1];
if (lastElement.type === "TextElement") {
lastElement.value = lastElement.value.replace(trailingWSRe, "");
}
return new AST.Pattern(elements);
}
getTextElement(ps) {
let buffer = "";
let ch;
while ((ch = ps.current())) {
if (ch === "{") {
return new AST.TextElement(buffer);
}
if (ch === "\n") {
if (!ps.isPeekNextLineValue()) {
return new AST.TextElement(buffer);
}
ps.next();
ps.skipInlineWS();
// Add the new line to the buffer
buffer += ch;
continue;
}
if (ch === "\\") {
ps.next();
buffer += this.getEscapeSequence(ps);
} else {
buffer += ch;
ps.next();
}
}
return new AST.TextElement(buffer);
}
getEscapeSequence(ps, specials = ["{", "\\"]) {
const next = ps.current();
if (specials.includes(next)) {
ps.next();
return `\\${next}`;
}
if (next === "u") {
let sequence = "";
ps.next();
for (let i = 0; i < 4; i++) {
const ch = ps.takeHexDigit();
if (ch === undefined) {
throw new ParseError("E0026", sequence + ps.current());
}
sequence += ch;
}
return `\\u${sequence}`;
}
throw new ParseError("E0025", next);
}
getPlaceable(ps) {
ps.expectChar("{");
const expression = this.getExpression(ps);
ps.expectChar("}");
return new AST.Placeable(expression);
}
getExpression(ps) {
ps.skipInlineWS();
const selector = this.getSelectorExpression(ps);
ps.skipInlineWS();
if (ps.currentIs("-")) {
ps.peek();
if (!ps.currentPeekIs(">")) {
ps.resetPeek();
return selector;
}
if (selector.type === "MessageReference") {
throw new ParseError("E0016");
}
if (selector.type === "AttributeExpression" &&
selector.ref.type === "MessageReference") {
throw new ParseError("E0018");
}
if (selector.type === "VariantExpression") {
throw new ParseError("E0017");
}
ps.next();
ps.next();
ps.skipInlineWS();
const variants = this.getVariants(ps);
if (variants.length === 0) {
throw new ParseError("E0011");
}
// VariantLists are only allowed in other VariantLists.
if (variants.some(v => v.value.type === "VariantList")) {
throw new ParseError("E0023");
}
ps.expectIndent();
return new AST.SelectExpression(selector, variants);
} else if (selector.type === "AttributeExpression" &&
selector.ref.type === "TermReference") {
throw new ParseError("E0019");
}
return selector;
}
getSelectorExpression(ps) {
if (ps.currentIs("{")) {
return this.getPlaceable(ps);
}
const literal = this.getLiteral(ps);
if (literal.type !== "MessageReference"
&& literal.type !== "TermReference") {
return literal;
}
const ch = ps.current();
if (ch === ".") {
ps.next();
const attr = this.getIdentifier(ps);
return new AST.AttributeExpression(literal, attr);
}
if (ch === "[") {
ps.next();
if (literal.type === "MessageReference") {
throw new ParseError("E0024");
}
const key = this.getVariantKey(ps);
ps.expectChar("]");
return new AST.VariantExpression(literal, key);
}
if (ch === "(") {
ps.next();
if (!/^[A-Z][A-Z_?-]*$/.test(literal.id.name)) {
throw new ParseError("E0008");
}
const args = this.getCallArgs(ps);
ps.expectChar(")");
const func = new AST.Function(literal.id.name);
if (this.withSpans) {
func.addSpan(literal.span.start, literal.span.end);
}
return new AST.CallExpression(
func,
args.positional,
args.named,
);
}
return literal;
}
getCallArg(ps) {
const exp = this.getSelectorExpression(ps);
ps.skipInlineWS();
if (ps.current() !== ":") {
return exp;
}
if (exp.type !== "MessageReference") {
throw new ParseError("E0009");
}
ps.next();
ps.skipInlineWS();
const val = this.getArgVal(ps);
return new AST.NamedArgument(exp.id, val);
}
getCallArgs(ps) {
const positional = [];
const named = [];
const argumentNames = new Set();
ps.skipInlineWS();
ps.skipIndent();
while (true) {
if (ps.current() === ")") {
break;
}
const arg = this.getCallArg(ps);
if (arg.type === "NamedArgument") {
if (argumentNames.has(arg.name.name)) {
throw new ParseError("E0022");
}
named.push(arg);
argumentNames.add(arg.name.name);
} else if (argumentNames.size > 0) {
throw new ParseError("E0021");
} else {
positional.push(arg);
}
ps.skipInlineWS();
ps.skipIndent();
if (ps.current() === ",") {
ps.next();
ps.skipInlineWS();
ps.skipIndent();
continue;
} else {
break;
}
}
return {
positional,
named
};
}
getArgVal(ps) {
if (ps.isNumberStart()) {
return this.getNumber(ps);
} else if (ps.currentIs('"')) {
return this.getString(ps);
}
throw new ParseError("E0012");
}
getString(ps) {
let val = "";
ps.expectChar('"');
let ch;
while ((ch = ps.takeChar(x => x !== '"' && x !== "\n"))) {
if (ch === "\\") {
val += this.getEscapeSequence(ps, ["{", "\\", "\""]);
} else {
val += ch;
}
}
if (ps.currentIs("\n")) {
throw new ParseError("E0020");
}
ps.next();
return new AST.StringLiteral(val);
}
getLiteral(ps) {
const ch = ps.current();
if (!ch) {
throw new ParseError("E0014");
}
if (ch === "$") {
ps.next();
const id = this.getIdentifier(ps);
return new AST.VariableReference(id);
}
if (ps.isIdentifierStart()) {
const id = this.getIdentifier(ps);
return new AST.MessageReference(id);
}
if (ps.isNumberStart()) {
return this.getNumber(ps);
}
if (ch === "-") {
const id = this.getTermIdentifier(ps);
return new AST.TermReference(id);
}
if (ch === '"') {
return this.getString(ps);
}
throw new ParseError("E0014");
}
getTermIdentifier(ps) {
ps.expectChar("-");
const id = this.getIdentifier(ps);
return new AST.Identifier(`-${id.name}`);
}
}