forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSDocParser.java
More file actions
1935 lines (1709 loc) · 56.9 KB
/
JSDocParser.java
File metadata and controls
1935 lines (1709 loc) · 56.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.semmle.js.parser;
import com.semmle.js.ast.Comment;
import com.semmle.js.ast.Position;
import com.semmle.js.ast.SourceLocation;
import com.semmle.js.ast.jsdoc.AllLiteral;
import com.semmle.js.ast.jsdoc.ArrayType;
import com.semmle.js.ast.jsdoc.FieldType;
import com.semmle.js.ast.jsdoc.FunctionType;
import com.semmle.js.ast.jsdoc.JSDocComment;
import com.semmle.js.ast.jsdoc.JSDocTag;
import com.semmle.js.ast.jsdoc.JSDocTypeExpression;
import com.semmle.js.ast.jsdoc.NameExpression;
import com.semmle.js.ast.jsdoc.NonNullableType;
import com.semmle.js.ast.jsdoc.NullLiteral;
import com.semmle.js.ast.jsdoc.NullableLiteral;
import com.semmle.js.ast.jsdoc.NullableType;
import com.semmle.js.ast.jsdoc.OptionalType;
import com.semmle.js.ast.jsdoc.ParameterType;
import com.semmle.js.ast.jsdoc.RecordType;
import com.semmle.js.ast.jsdoc.RestType;
import com.semmle.js.ast.jsdoc.TypeApplication;
import com.semmle.js.ast.jsdoc.UndefinedLiteral;
import com.semmle.js.ast.jsdoc.UnionType;
import com.semmle.js.ast.jsdoc.VoidLiteral;
import com.semmle.util.data.Pair;
import com.semmle.util.exception.Exceptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** A Java port of <a href="https://github.com/Constellation/doctrine">doctrine</a>. */
public class JSDocParser {
private String source;
private int absoluteOffset;
/** Parse the given string as a JSDoc comment. */
public JSDocComment parse(Comment comment) {
source = comment.getText();
JSDocTagParser p = new JSDocTagParser();
Position startPos = comment.getLoc().getStart();
// Get the start of the first line relative to the 'source' string.
// This occurs before the start of 'source', so the lineStart is negative.
int firstLineStart = -(startPos.getColumn() + "/**".length() - 1);
this.absoluteOffset = startPos.getOffset();
Pair<String, List<JSDocTagParser.Tag>> r =
p.new TagParser(null).parseComment(startPos.getLine() - 1, firstLineStart);
List<JSDocTag> tags = new ArrayList<>();
for (JSDocTagParser.Tag tag : r.snd()) {
String title = tag.title;
String description = tag.description;
String name = tag.name;
int startLine = tag.startLine;
int startColumn = tag.startColumn;
JSDocTypeExpression jsdocType = tag.type;
int lineNumber = startLine + 1; // convert to 1-based
SourceLocation loc =
new SourceLocation(
source,
new Position(lineNumber, startColumn, -1),
new Position(lineNumber, startColumn + 1 + title.length(), -1));
tags.add(new JSDocTag(loc, title, description, name, jsdocType, tag.errors));
}
return new JSDocComment(comment, r.fst(), tags);
}
/** Specification of Doctrine AST types for JSDoc type expressions. */
private static final Map<Class<? extends JSDocTypeExpression>, List<String>> spec =
new LinkedHashMap<Class<? extends JSDocTypeExpression>, List<String>>();
static {
spec.put(AllLiteral.class, Arrays.<String>asList());
spec.put(ArrayType.class, Arrays.asList("elements"));
spec.put(FieldType.class, Arrays.asList("key", "value"));
spec.put(FunctionType.class, Arrays.asList("this", "new", "params", "result"));
spec.put(NameExpression.class, Arrays.asList("name"));
spec.put(NonNullableType.class, Arrays.asList("expression", "prefix"));
spec.put(NullableLiteral.class, Arrays.<String>asList());
spec.put(NullLiteral.class, Arrays.<String>asList());
spec.put(NullableType.class, Arrays.asList("expression", "prefix"));
spec.put(OptionalType.class, Arrays.asList("expression"));
spec.put(ParameterType.class, Arrays.asList("name", "expression"));
spec.put(RecordType.class, Arrays.asList("fields"));
spec.put(RestType.class, Arrays.asList("expression"));
spec.put(TypeApplication.class, Arrays.asList("expression", "applications"));
spec.put(UndefinedLiteral.class, Arrays.<String>asList());
spec.put(UnionType.class, Arrays.asList("elements"));
spec.put(VoidLiteral.class, Arrays.<String>asList());
}
private static String sliceSource(String source, int index, int last) {
if (index >= source.length()) return "";
if (last > source.length()) last = source.length();
return source.substring(index, last);
}
private static boolean isLineTerminator(int ch) {
return ch == '\n' || ch == '\r' || ch == '\u2028' || ch == '\u2029';
}
private static boolean isWhiteSpace(char ch) {
return Character.isWhitespace(ch) && !isLineTerminator(ch) || ch == '\u00a0';
}
private static boolean isWhiteSpaceOrLineTerminator(char ch) {
return Character.isWhitespace(ch) || ch == '\u00a0';
}
private static boolean isDecimalDigit(char ch) {
return "0123456789".indexOf(ch) >= 0;
}
private static boolean isHexDigit(char ch) {
return "0123456789abcdefABCDEF".indexOf(ch) >= 0;
}
private static boolean isOctalDigit(char ch) {
return "01234567".indexOf(ch) >= 0;
}
private static boolean isASCIIAlphanumeric(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9');
}
private static boolean isIdentifierStart(char ch) {
return (ch == '\\') || Character.isJavaIdentifierStart(ch);
}
private static boolean isIdentifierPart(char ch) {
return (ch == '\\') || Character.isJavaIdentifierPart(ch);
}
private static boolean isTypeName(char ch) {
return "><(){}[],:*|?!=".indexOf(ch) == -1 && !isWhiteSpace(ch) && !isLineTerminator(ch);
}
private static boolean isParamTitle(String title) {
return title.equals("param") || title.equals("argument") || title.equals("arg");
}
private static boolean isProperty(String title) {
return title.equals("property") || title.equals("prop");
}
private static boolean isNameParameterRequired(String title) {
return isParamTitle(title)
|| isProperty(title)
|| title.equals("alias")
|| title.equals("this")
|| title.equals("mixes")
|| title.equals("requires");
}
private static boolean isAllowedName(String title) {
return isNameParameterRequired(title) || title.equals("const") || title.equals("constant");
}
private static boolean isAllowedNested(String title) {
return isProperty(title) || isParamTitle(title);
}
private static boolean isTypeParameterRequired(String title) {
return isParamTitle(title)
|| title.equals("define")
|| title.equals("enum")
|| title.equals("implements")
|| title.equals("return")
|| title.equals("this")
|| title.equals("type")
|| title.equals("typedef")
|| title.equals("returns")
|| isProperty(title);
}
// Consider deprecation instead using 'isTypeParameterRequired' and 'Rules' declaration to pick
// when a type is optional/required
// This would require changes to 'parseType'
private static boolean isAllowedType(String title) {
return isTypeParameterRequired(title)
|| title.equals("throws")
|| title.equals("const")
|| title.equals("constant")
|| title.equals("namespace")
|| title.equals("member")
|| title.equals("var")
|| title.equals("module")
|| title.equals("constructor")
|| title.equals("class")
|| title.equals("extends")
|| title.equals("augments")
|| title.equals("public")
|| title.equals("private")
|| title.equals("protected");
}
private static <T> T throwError(String message) throws ParseError {
throw new ParseError(message, null);
}
private enum Token {
ILLEGAL, // ILLEGAL
DOT, // .
DOT_LT, // .<
REST, // ...
LT, // <
GT, // >
LPAREN, // (
RPAREN, // )
LBRACE, // {
RBRACE, // }
LBRACK, // [
RBRACK, // ]
COMMA, // ,
COLON, // :
STAR, // *
PIPE, // |
QUESTION, // ?
BANG, // !
EQUAL, // =
NAME, // name token
STRING, // string
NUMBER, // number
EOF
};
private class TypeExpressionParser {
int startIndex;
int endIndex;
int startOfCurToken, endOfPrevToken, index;
Token token;
Object value;
int lineStart;
int lineNumber;
private class Context {
int _startOfCurToken, _endOfPrevToken, _index;
Token _token;
Object _value;
Context(int startOfCurToken, int endOfPrevToken, int index, Token token, Object value) {
this._startOfCurToken = startOfCurToken;
this._endOfPrevToken = endOfPrevToken;
this._index = index;
this._token = token;
this._value = value;
}
void restore() {
startOfCurToken = this._startOfCurToken;
endOfPrevToken = this._endOfPrevToken;
index = this._index;
token = this._token;
value = this._value;
}
}
Context save() {
return new Context(startOfCurToken, endOfPrevToken, index, token, value);
}
private SourceLocation loc() {
return new SourceLocation(pos());
}
/** Returns the absolute position of the start of the current token. */
private Position pos() {
return new Position(
this.lineNumber + 1, startOfCurToken - lineStart, startOfCurToken + absoluteOffset);
}
/**
* Returns the absolute position of the end of the previous token.
*
* <p>This can differ from the start of the current token in case the two tokens are separated
* by whitespace.
*/
private Position endPos() {
return new Position(
this.lineNumber + 1, endOfPrevToken - lineStart, endOfPrevToken + absoluteOffset);
}
private <T extends JSDocTypeExpression> T finishNode(T node) {
SourceLocation loc = node.getLoc();
Position end = endPos();
int relativeStartOffset = loc.getStart().getOffset() - absoluteOffset;
int relativeEndOffset = end.getOffset() - absoluteOffset;
loc.setSource(inputSubstring(relativeStartOffset, relativeEndOffset));
loc.setEnd(end);
return node;
}
private String inputSubstring(int start, int end) {
if (start >= source.length()) return "";
if (end > source.length()) end = source.length();
return source.substring(start, end);
}
private int advance() {
if (index >= source.length()) return -1;
int ch = source.charAt(index);
++index;
if (isLineTerminator(ch)
&& !(ch == '\r' && index < endIndex && source.charAt(index) == '\n')) {
lineNumber += 1;
lineStart = index;
index = skipStars(index, endIndex);
}
return ch;
}
private String scanHexEscape(char prefix) {
int i, len, ch, code = 0;
len = (prefix == 'u') ? 4 : 2;
for (i = 0; i < len; ++i) {
if (index < endIndex && isHexDigit(source.charAt(index))) {
ch = advance();
code = code * 16 + "0123456789abcdef".indexOf(Character.toLowerCase(ch));
} else {
return "";
}
}
return new String(Character.toChars(code));
}
private Token scanString() throws ParseError {
StringBuilder str = new StringBuilder();
int quote, ch, code, restore; // TODO review removal octal = false
String unescaped;
quote = source.charAt(index);
++index;
while (index < endIndex) {
ch = advance();
if (ch == quote) {
quote = -1;
break;
} else if (ch == '\\') {
ch = advance();
if (!isLineTerminator(ch)) {
switch (ch) {
case 'n':
str.append('\n');
break;
case 'r':
str.append('\r');
break;
case 't':
str.append('\t');
break;
case 'u':
case 'x':
restore = index;
unescaped = scanHexEscape((char) ch);
if (!unescaped.isEmpty()) {
str.append(unescaped);
} else {
index = restore;
str.append((char) ch);
}
break;
case 'b':
str.append('\b');
break;
case 'f':
str.append('\f');
break;
case 'v':
str.append('\u000b');
break;
default:
if (isOctalDigit((char) ch)) {
code = "01234567".indexOf(ch);
// \0 is not octal escape sequence
// Deprecating unused code. TODO review removal
// if (code != 0) {
// octal = true;
// }
if (index < endIndex && isOctalDigit(source.charAt(index))) {
// TODO Review Removal octal = true;
code = code * 8 + "01234567".indexOf(advance());
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ("0123".indexOf(ch) >= 0
&& index < endIndex
&& isOctalDigit(source.charAt(index))) {
code = code * 8 + "01234567".indexOf(advance());
}
}
str.append(Character.toChars(code));
} else {
str.append((char) ch);
}
break;
}
} else {
if (ch == '\r' && index < endIndex && source.charAt(index) == '\n') {
++index;
}
}
} else if (isLineTerminator(ch)) {
break;
} else {
str.append((char) ch);
}
}
if (quote != -1) {
throwError("unexpected quote");
}
value = str.toString();
return Token.STRING;
}
private Token scanNumber() throws ParseError {
StringBuilder number = new StringBuilder();
boolean isFloat = false;
char ch = '\0';
if (ch != '.') {
int next = advance();
number.append((char) next);
ch = index < endIndex ? source.charAt(index) : '\0';
if (next == '0') {
if (ch == 'x' || ch == 'X') {
number.append((char) advance());
while (index < endIndex) {
ch = source.charAt(index);
if (!isHexDigit(ch)) {
break;
}
number.append((char) advance());
}
if (number.length() <= 2) {
// only 0x
throwError("unexpected token");
}
if (index < endIndex) {
ch = source.charAt(index);
if (isIdentifierStart(ch)) {
throwError("unexpected token");
}
}
try {
value = Integer.parseInt(number.toString(), 16);
} catch (NumberFormatException nfe) {
Exceptions.ignore(nfe, "Precise exception content is unimportant");
throwError("Invalid hexadecimal constant " + number);
}
return Token.NUMBER;
}
if (isOctalDigit(ch)) {
number.append((char) advance());
while (index < endIndex) {
ch = source.charAt(index);
if (!isOctalDigit(ch)) {
break;
}
number.append((char) advance());
}
if (index < endIndex) {
ch = source.charAt(index);
if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
throwError("unexpected token");
}
}
try {
value = Integer.parseInt(number.toString(), 8);
} catch (NumberFormatException nfe) {
Exceptions.ignore(nfe, "Precise exception content is unimportant");
throwError("Invalid octal constant " + number);
}
return Token.NUMBER;
}
if (isDecimalDigit(ch)) {
throwError("unexpected token");
}
}
while (index < endIndex) {
ch = source.charAt(index);
if (!isDecimalDigit(ch)) {
break;
}
number.append((char) advance());
}
}
if (ch == '.') {
isFloat = true;
number.append((char) advance());
while (index < endIndex) {
ch = source.charAt(index);
if (!isDecimalDigit(ch)) {
break;
}
number.append((char) advance());
}
}
if (ch == 'e' || ch == 'E') {
isFloat = true;
number.append((char) advance());
ch = index < endIndex ? source.charAt(index) : '\0';
if (ch == '+' || ch == '-') {
number.append((char) advance());
}
ch = index < endIndex ? source.charAt(index) : '\0';
if (isDecimalDigit(ch)) {
number.append((char) advance());
while (index < endIndex) {
ch = source.charAt(index);
if (!isDecimalDigit(ch)) {
break;
}
number.append((char) advance());
}
} else {
throwError("unexpected token");
}
}
if (index < endIndex) {
ch = source.charAt(index);
if (isIdentifierStart(ch)) {
throwError("unexpected token");
}
}
String num = number.toString();
try {
if (isFloat) value = Double.parseDouble(num);
else value = Integer.parseInt(num);
} catch (NumberFormatException nfe) {
Exceptions.ignore(nfe, "Precise exception content is unimportant");
throwError("Invalid numeric literal " + num);
}
return Token.NUMBER;
}
private Token scanTypeName() {
char ch, ch2;
StringBuilder sb = new StringBuilder();
sb.append((char)advance());
while (index < endIndex && isTypeName(source.charAt(index))) {
ch = source.charAt(index);
if (ch == '.') {
if ((index + 1) < endIndex) {
ch2 = source.charAt(index + 1);
if (ch2 == '<') {
break;
}
}
}
sb.append((char)advance());
}
value = sb.toString();
return Token.NAME;
}
private Token next() throws ParseError {
char ch;
endOfPrevToken = index;
while (index < endIndex && isWhiteSpaceOrLineTerminator(source.charAt(index))) {
advance();
}
if (index >= endIndex) {
token = Token.EOF;
return token;
}
startOfCurToken = index;
ch = source.charAt(index);
switch (ch) {
case '"':
token = scanString();
return token;
case ':':
advance();
token = Token.COLON;
return token;
case ',':
advance();
token = Token.COMMA;
return token;
case '(':
advance();
token = Token.LPAREN;
return token;
case ')':
advance();
token = Token.RPAREN;
return token;
case '[':
advance();
token = Token.LBRACK;
return token;
case ']':
advance();
token = Token.RBRACK;
return token;
case '{':
advance();
token = Token.LBRACE;
return token;
case '}':
advance();
token = Token.RBRACE;
return token;
case '.':
advance();
if (index < endIndex) {
ch = source.charAt(index);
if (ch == '<') {
advance();
token = Token.DOT_LT;
return token;
}
if (ch == '.' && index + 1 < endIndex && source.charAt(index + 1) == '.') {
advance();
advance();
token = Token.REST;
return token;
}
if (isDecimalDigit(ch)) {
token = scanNumber();
return token;
}
}
token = Token.DOT;
return token;
case '<':
advance();
token = Token.LT;
return token;
case '>':
advance();
token = Token.GT;
return token;
case '*':
advance();
token = Token.STAR;
return token;
case '|':
advance();
token = Token.PIPE;
return token;
case '?':
advance();
token = Token.QUESTION;
return token;
case '!':
advance();
token = Token.BANG;
return token;
case '=':
advance();
token = Token.EQUAL;
return token;
default:
if (isDecimalDigit(ch)) {
token = scanNumber();
return token;
}
// type string permits following case,
//
// namespace.module.MyClass
//
// this reduced 1 token TK_NAME
if (isTypeName(ch)) {
token = scanTypeName();
return token;
}
token = Token.ILLEGAL;
return token;
}
}
private void consume(Token target, String text) throws ParseError {
if (token != target) throwError(text == null ? "consumed token not matched" : text);
next();
}
private void consume(Token target) throws ParseError {
consume(target, null);
}
private void expect(Token target) throws ParseError {
if (token != target) {
throwError("unexpected token");
}
next();
}
// UnionType := '(' TypeUnionList ')'
//
// TypeUnionList :=
// <<empty>>
// | NonemptyTypeUnionList
//
// NonemptyTypeUnionList :=
// TypeExpression
// | TypeExpression '|' NonemptyTypeUnionList
private JSDocTypeExpression parseUnionType() throws ParseError {
SourceLocation loc = loc();
List<JSDocTypeExpression> elements = new ArrayList<>();
consume(Token.LPAREN, "UnionType should start with (");
if (token != Token.RPAREN) {
while (true) {
elements.add(parseTypeExpression());
if (token == Token.RPAREN) {
break;
}
expect(Token.PIPE);
}
}
consume(Token.RPAREN, "UnionType should end with )");
return finishNode(new UnionType(loc, elements));
}
// ArrayType := '[' ElementTypeList ']'
//
// ElementTypeList :=
// <<empty>>
// | TypeExpression
// | '...' TypeExpression
// | TypeExpression ',' ElementTypeList
private JSDocTypeExpression parseArrayType() throws ParseError {
SourceLocation loc = loc();
List<JSDocTypeExpression> elements = new ArrayList<>();
consume(Token.LBRACK, "ArrayType should start with [");
while (token != Token.RBRACK) {
if (token == Token.REST) {
SourceLocation restLoc = loc();
consume(Token.REST);
elements.add(finishNode(new RestType(restLoc, parseTypeExpression())));
break;
} else {
elements.add(parseTypeExpression());
}
if (token != Token.RBRACK) {
expect(Token.COMMA);
}
}
expect(Token.RBRACK);
return finishNode(new ArrayType(loc, elements));
}
private String parseFieldName() throws ParseError {
Object v = value;
if (token == Token.NAME || token == Token.STRING) {
next();
return v.toString();
}
if (token == Token.NUMBER) {
consume(Token.NUMBER);
return v.toString();
}
return throwError("unexpected token");
}
// FieldType :=
// FieldName
// | FieldName ':' TypeExpression
//
// FieldName :=
// NameExpression
// | StringLiteral
// | NumberLiteral
// | ReservedIdentifier
private FieldType parseFieldType() throws ParseError {
String key;
SourceLocation loc = loc();
key = parseFieldName();
if (token == Token.COLON) {
consume(Token.COLON);
return finishNode(new FieldType(loc, key, parseTypeExpression()));
}
return finishNode(new FieldType(loc, key, null));
}
// RecordType := '{' FieldTypeList '}'
//
// FieldTypeList :=
// <<empty>>
// | FieldType
// | FieldType ',' FieldTypeList
private JSDocTypeExpression parseRecordType() throws ParseError {
List<FieldType> fields = new ArrayList<>();
SourceLocation loc = loc();
consume(Token.LBRACE, "RecordType should start with {");
if (token == Token.COMMA) {
consume(Token.COMMA);
} else {
while (token != Token.RBRACE) {
fields.add(parseFieldType());
if (token != Token.RBRACE) {
expect(Token.COMMA);
}
}
}
expect(Token.RBRACE);
return finishNode(new RecordType(loc, fields));
}
private JSDocTypeExpression parseNameExpression() throws ParseError {
Object name = value;
SourceLocation loc = loc();
expect(Token.NAME);
return finishNode(new NameExpression(loc, name.toString()));
}
// TypeExpressionList :=
// TopLevelTypeExpression
// | TopLevelTypeExpression ',' TypeExpressionList
private List<JSDocTypeExpression> parseTypeExpressionList() throws ParseError {
List<JSDocTypeExpression> elements = new ArrayList<>();
elements.add(parseTop());
while (token == Token.COMMA) {
consume(Token.COMMA);
elements.add(parseTop());
}
return elements;
}
// TypeName :=
// NameExpression
// | NameExpression TypeApplication
//
// TypeApplication :=
// '.<' TypeExpressionList '>'
// | '<' TypeExpressionList '>' // this is extension of doctrine
private JSDocTypeExpression parseTypeName() throws ParseError {
JSDocTypeExpression expr;
List<JSDocTypeExpression> applications;
SourceLocation loc = loc();
expr = parseNameExpression();
if (token == Token.DOT_LT || token == Token.LT) {
next();
applications = parseTypeExpressionList();
expect(Token.GT);
return finishNode(new TypeApplication(loc, expr, applications));
}
return expr;
}
// ResultType :=
// <<empty>>
// | ':' void
// | ':' TypeExpression
//
// BNF is above
// but, we remove <<empty>> pattern, so token is always TypeToken::COLON
private JSDocTypeExpression parseResultType() throws ParseError {
consume(Token.COLON, "ResultType should start with :");
SourceLocation loc = loc();
if (token == Token.NAME && value.equals("void")) {
consume(Token.NAME);
return finishNode(new VoidLiteral(loc));
}
return parseTypeExpression();
}
// ParametersType :=
// RestParameterType
// | NonRestParametersType
// | NonRestParametersType ',' RestParameterType
//
// RestParameterType :=
// '...'
// '...' Identifier
//
// NonRestParametersType :=
// ParameterType ',' NonRestParametersType
// | ParameterType
// | OptionalParametersType
//
// OptionalParametersType :=
// OptionalParameterType
// | OptionalParameterType, OptionalParametersType
//
// OptionalParameterType := ParameterType=
//
// ParameterType := TypeExpression | Identifier ':' TypeExpression
//
// Identifier is "new" or "this"
private List<JSDocTypeExpression> parseParametersType() throws ParseError {
List<JSDocTypeExpression> params = new ArrayList<>();
boolean normal = true;
JSDocTypeExpression expr;
boolean rest = false;
while (token != Token.RPAREN) {
if (token == Token.REST) {
// RestParameterType
consume(Token.REST);
rest = true;
}
SourceLocation loc = loc();
expr = parseTypeExpression();
if (expr instanceof NameExpression && token == Token.COLON) {
// Identifier ':' TypeExpression
consume(Token.COLON);
expr =
finishNode(
new ParameterType(
new SourceLocation(loc),
((NameExpression) expr).getName(),
parseTypeExpression()));
}
if (token == Token.EQUAL) {
consume(Token.EQUAL);
expr = finishNode(new OptionalType(new SourceLocation(loc), expr));
normal = false;
} else {
if (!normal) {
throwError("unexpected token");
}
}
if (rest) {
expr = finishNode(new RestType(new SourceLocation(loc), expr));
}
params.add(expr);
if (token != Token.RPAREN) {
expect(Token.COMMA);
}
}
return params;
}
// FunctionType := 'function' FunctionSignatureType
//
// FunctionSignatureType :=
// | TypeParameters '(' ')' ResultType
// | TypeParameters '(' ParametersType ')' ResultType
// | TypeParameters '(' 'this' ':' TypeName ')' ResultType
// | TypeParameters '(' 'this' ':' TypeName ',' ParametersType ')' ResultType
private JSDocTypeExpression parseFunctionType() throws ParseError {
SourceLocation loc = loc();
boolean isNew;
JSDocTypeExpression thisBinding;
List<JSDocTypeExpression> params;
JSDocTypeExpression result;
consume(Token.NAME);
// Google Closure Compiler is not implementing TypeParameters.
// So we do not. if we don't get '(', we see it as error.
expect(Token.LPAREN);
isNew = false;
params = new ArrayList<JSDocTypeExpression>();