Debian Codegraph @

src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java

raw symbols SCIP
1 /*
2 * Copyright 2007 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp.parsing;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Splitter;
21 import com.google.common.collect.ImmutableSet;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Sets;
24 import com.google.javascript.jscomp.parsing.Config.LanguageMode;
25 import com.google.javascript.rhino.IR;
26 import com.google.javascript.rhino.JSDocInfo;
27 import com.google.javascript.rhino.JSDocInfo.Visibility;
28 import com.google.javascript.rhino.JSDocInfoBuilder;
29 import com.google.javascript.rhino.JSTypeExpression;
30 import com.google.javascript.rhino.Node;
31 import com.google.javascript.rhino.ScriptRuntime;
32 import com.google.javascript.rhino.Token;
33 import com.google.javascript.rhino.head.ErrorReporter;
34 import com.google.javascript.rhino.head.ast.Comment;
35 import com.google.javascript.rhino.jstype.StaticSourceFile;
36
37 import java.util.HashSet;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Set;
41
42 /**
43 * A parser for JSDoc comments.
44 *
45 */
46 // TODO(nicksantos): Unify all the JSDocInfo stuff into one package, instead of
47 // spreading it across multiple packages.
48 public final class JsDocInfoParser {
49
50 private final JsDocTokenStream stream;
51 private final JSDocInfoBuilder jsdocBuilder;
52 private final StaticSourceFile sourceFile;
53 private final Node associatedNode;
54 private final ErrorReporter errorReporter;
55 private final ErrorReporterParser parser = new ErrorReporterParser();
56
57 // Use a template node for properties set on all nodes to minimize the
58 // memory footprint associated with these (similar to IRFactory).
59 private final Node templateNode;
60
61 private class ErrorReporterParser {
62 void addParserWarning(String messageId, String messageArg, int lineno,
63 int charno) {
64 errorReporter.warning(ScriptRuntime.getMessage1(messageId, messageArg),
65 getSourceName(), lineno, null, charno);
66 }
67
68 void addParserWarning(String messageId, int lineno, int charno) {
69 errorReporter.warning(ScriptRuntime.getMessage0(messageId),
70 getSourceName(), lineno, null, charno);
71 }
72
73 void addTypeWarning(String messageId, String messageArg, int lineno,
74 int charno) {
75 errorReporter.warning(
76 "Bad type annotation. " +
77 ScriptRuntime.getMessage1(messageId, messageArg),
78 getSourceName(), lineno, null, charno);
79 }
80
81 void addTypeWarning(String messageId, int lineno, int charno) {
82 errorReporter.warning(
83 "Bad type annotation. " +
84 ScriptRuntime.getMessage0(messageId),
85 getSourceName(), lineno, null, charno);
86 }
87 }
88
89 // The DocInfo with the fileoverview tag for the whole file.
90 private JSDocInfo fileOverviewJSDocInfo = null;
91 private State state;
92
93 private final Map<String, Annotation> annotationNames;
94 private final Set<String> suppressionNames;
95 static private final Set<String> modifiesAnnotationKeywords =
96 ImmutableSet.<String>of("this", "arguments");
97
98 private Node.FileLevelJsDocBuilder fileLevelJsDocBuilder;
99
100 /**
101 * Sets the JsDocBuilder for the file-level (root) node of this parse. The
102 * parser uses the builder to append any preserve annotations it encounters
103 * in JsDoc comments.
104 *
105 * @param fileLevelJsDocBuilder
106 */
107 void setFileLevelJsDocBuilder(
108 Node.FileLevelJsDocBuilder fileLevelJsDocBuilder) {
109 this.fileLevelJsDocBuilder = fileLevelJsDocBuilder;
110 }
111
112 /**
113 * Sets the file overview JSDocInfo, in order to warn about multiple uses of
114 * the @fileoverview tag in a file.
115 */
116 void setFileOverviewJSDocInfo(JSDocInfo fileOverviewJSDocInfo) {
117 this.fileOverviewJSDocInfo = fileOverviewJSDocInfo;
118 }
119
120 private enum State {
121 SEARCHING_ANNOTATION,
122 SEARCHING_NEWLINE,
123 NEXT_IS_ANNOTATION
124 }
125
126 JsDocInfoParser(JsDocTokenStream stream,
127 Comment commentNode,
128 Node associatedNode,
129 Config config,
130 ErrorReporter errorReporter) {
131 this.stream = stream;
132 this.associatedNode = associatedNode;
133
134 // Sometimes this will be null in tests.
135 this.sourceFile = associatedNode == null
136 ? null : associatedNode.getStaticSourceFile();
137
138 this.jsdocBuilder = new JSDocInfoBuilder(config.parseJsDocDocumentation);
139 if (commentNode != null) {
140 this.jsdocBuilder.recordOriginalCommentString(commentNode.getValue());
141 }
142 this.annotationNames = config.annotationNames;
143 this.suppressionNames = config.suppressionNames;
144
145 this.errorReporter = errorReporter;
146 this.templateNode = this.createTemplateNode();
147 }
148
149 private String getSourceName() {
150 return sourceFile == null ? null : sourceFile.getName();
151 }
152
153 /**
154 * Parse a description as a {@code @type}.
155 */
156 public JSDocInfo parseInlineTypeDoc() {
157 skipEOLs();
158
159 Node typeAst = parseAndRecordTypeNode(next());
160 JSTypeExpression expr = createJSTypeExpression(typeAst);
161 if (expr != null) {
162 jsdocBuilder.recordType(expr);
163 return retrieveAndResetParsedJSDocInfo();
164 }
165 return null;
166 }
167
168 /**
169 * Parses a string containing a JsDoc type declaration, returning the
170 * type if the parsing succeeded or {@code null} if it failed.
171 */
172 public static Node parseTypeString(String typeString) {
173 Config config = new Config(
174 Sets.<String>newHashSet(),
175 Sets.<String>newHashSet(),
176 false,
177 LanguageMode.ECMASCRIPT3,
178 false);
179 JsDocInfoParser parser = new JsDocInfoParser(
180 new JsDocTokenStream(typeString),
181 null,
182 null,
183 config,
184 NullErrorReporter.forNewRhino());
185
186 return parser.parseTopLevelTypeExpression(parser.next());
187 }
188
189 /**
190 * Parses a {@link JSDocInfo} object. This parsing method reads all tokens
191 * returned by the {@link JsDocTokenStream#getJsDocToken()} method until the
192 * {@link JsDocToken#EOC} is returned.
193 *
194 * @return {@code true} if JSDoc information was correctly parsed,
195 * {@code false} otherwise
196 */
197 boolean parse() {
198 state = State.SEARCHING_ANNOTATION;
199 skipEOLs();
200
201 JsDocToken token = next();
202
203 // Always record that we have a comment.
204 if (jsdocBuilder.shouldParseDocumentation()) {
205 ExtractionInfo blockInfo = extractBlockComment(token);
206 token = blockInfo.token;
207 if (!blockInfo.string.isEmpty()) {
208 jsdocBuilder.recordBlockDescription(blockInfo.string);
209 }
210 } else {
211 if (token != JsDocToken.ANNOTATION &&
212 token != JsDocToken.EOC) {
213 // Mark that there was a description, but don't bother marking
214 // what it was.
215 jsdocBuilder.recordBlockDescription("");
216 }
217 }
218
219 return parseHelperLoop(token, Lists.<ExtendedTypeInfo>newArrayList());
220 }
221
222 private boolean parseHelperLoop(JsDocToken token,
223 List<ExtendedTypeInfo> extendedTypes) {
224 while (true) {
225 switch (token) {
226 case ANNOTATION:
227 if (state == State.SEARCHING_ANNOTATION) {
228 state = State.SEARCHING_NEWLINE;
229 token = parseAnnotation(token, extendedTypes);
230 } else {
231 token = next();
232 }
233 break;
234
235 case EOC:
236 if (hasParsedFileOverviewDocInfo()) {
237 fileOverviewJSDocInfo = retrieveAndResetParsedJSDocInfo();
238 }
239 checkExtendedTypes(extendedTypes);
240 return true;
241
242 case EOF:
243 // discard any accumulated information
244 jsdocBuilder.build(null);
245 parser.addParserWarning("msg.unexpected.eof",
246 stream.getLineno(), stream.getCharno());
247 checkExtendedTypes(extendedTypes);
248 return false;
249
250 case EOL:
251 if (state == State.SEARCHING_NEWLINE) {
252 state = State.SEARCHING_ANNOTATION;
253 }
254 token = next();
255 break;
256
257 default:
258 if (token == JsDocToken.STAR && state == State.SEARCHING_ANNOTATION) {
259 token = next();
260 } else {
261 state = State.SEARCHING_NEWLINE;
262 token = eatTokensUntilEOL();
263 }
264 break;
265 }
266 }
267 }
268
269 private JsDocToken parseAnnotation(JsDocToken token,
270 List<ExtendedTypeInfo> extendedTypes) {
271 // JSTypes are represented as Rhino AST nodes, and then resolved later.
272 JSTypeExpression type;
273 int lineno = stream.getLineno();
274 int charno = stream.getCharno();
275
276 String annotationName = stream.getString();
277 Annotation annotation = annotationNames.get(annotationName);
278 if (annotation == null) {
279 parser.addParserWarning("msg.bad.jsdoc.tag", annotationName,
280 stream.getLineno(), stream.getCharno());
281 } else {
282 // Mark the beginning of the annotation.
283 jsdocBuilder.markAnnotation(annotationName, lineno, charno);
284
285 switch (annotation) {
286 case NG_INJECT:
287 if (jsdocBuilder.isNgInjectRecorded()) {
288 parser.addParserWarning("msg.jsdoc.nginject.extra",
289 stream.getLineno(), stream.getCharno());
290 } else {
291 jsdocBuilder.recordNgInject(true);
292 }
293 return eatTokensUntilEOL();
294
295 case AUTHOR:
296 if (jsdocBuilder.shouldParseDocumentation()) {
297 ExtractionInfo authorInfo = extractSingleLineBlock();
298 String author = authorInfo.string;
299
300 if (author.length() == 0) {
301 parser.addParserWarning("msg.jsdoc.authormissing",
302 stream.getLineno(), stream.getCharno());
303 } else {
304 jsdocBuilder.addAuthor(author);
305 }
306 token = authorInfo.token;
307 } else {
308 token = eatTokensUntilEOL(token);
309 }
310 return token;
311
312 case CONSISTENTIDGENERATOR:
313 if (!jsdocBuilder.recordConsistentIdGenerator()) {
314 parser.addParserWarning("msg.jsdoc.consistidgen",
315 stream.getLineno(), stream.getCharno());
316 }
317 return eatTokensUntilEOL();
318
319 case STRUCT:
320 if (!jsdocBuilder.recordStruct()) {
321 parser.addTypeWarning("msg.jsdoc.incompat.type",
322 stream.getLineno(),
323 stream.getCharno());
324 }
325 return eatTokensUntilEOL();
326
327 case DICT:
328 if (!jsdocBuilder.recordDict()) {
329 parser.addTypeWarning("msg.jsdoc.incompat.type",
330 stream.getLineno(),
331 stream.getCharno());
332 }
333 return eatTokensUntilEOL();
334
335 case CONSTRUCTOR:
336 if (!jsdocBuilder.recordConstructor()) {
337 if (jsdocBuilder.isInterfaceRecorded()) {
338 parser.addTypeWarning("msg.jsdoc.interface.constructor",
339 stream.getLineno(), stream.getCharno());
340 } else {
341 parser.addTypeWarning("msg.jsdoc.incompat.type",
342 stream.getLineno(), stream.getCharno());
343 }
344 }
345 return eatTokensUntilEOL();
346
347 case DEPRECATED:
348 if (!jsdocBuilder.recordDeprecated()) {
349 parser.addParserWarning("msg.jsdoc.deprecated",
350 stream.getLineno(), stream.getCharno());
351 }
352
353 // Find the reason/description, if any.
354 ExtractionInfo reasonInfo =
355 extractMultilineTextualBlock(token);
356
357 String reason = reasonInfo.string;
358
359 if (reason.length() > 0) {
360 jsdocBuilder.recordDeprecationReason(reason);
361 }
362
363 token = reasonInfo.token;
364 return token;
365
366 case INTERFACE:
367 if (!jsdocBuilder.recordInterface()) {
368 if (jsdocBuilder.isConstructorRecorded()) {
369 parser.addTypeWarning("msg.jsdoc.interface.constructor",
370 stream.getLineno(), stream.getCharno());
371 } else {
372 parser.addTypeWarning("msg.jsdoc.incompat.type",
373 stream.getLineno(), stream.getCharno());
374 }
375 }
376 return eatTokensUntilEOL();
377
378 case DESC:
379 if (jsdocBuilder.isDescriptionRecorded()) {
380 parser.addParserWarning("msg.jsdoc.desc.extra",
381 stream.getLineno(), stream.getCharno());
382 return eatTokensUntilEOL();
383 } else {
384 ExtractionInfo descriptionInfo =
385 extractMultilineTextualBlock(token);
386
387 String description = descriptionInfo.string;
388
389 jsdocBuilder.recordDescription(description);
390 token = descriptionInfo.token;
391 return token;
392 }
393
394 case FILE_OVERVIEW:
395 String fileOverview = "";
396 if (jsdocBuilder.shouldParseDocumentation()) {
397 ExtractionInfo fileOverviewInfo =
398 extractMultilineTextualBlock(token,
399 WhitespaceOption.TRIM);
400
401 fileOverview = fileOverviewInfo.string;
402
403 token = fileOverviewInfo.token;
404 } else {
405 token = eatTokensUntilEOL(token);
406 }
407
408 if (!jsdocBuilder.recordFileOverview(fileOverview)) {
409 parser.addParserWarning("msg.jsdoc.fileoverview.extra",
410 stream.getLineno(), stream.getCharno());
411 }
412 return token;
413
414 case LICENSE:
415 case PRESERVE:
416 ExtractionInfo preserveInfo =
417 extractMultilineTextualBlock(token,
418 WhitespaceOption.PRESERVE);
419
420 String preserve = preserveInfo.string;
421
422 if (preserve.length() > 0) {
423 if (fileLevelJsDocBuilder != null) {
424 fileLevelJsDocBuilder.append(preserve);
425 }
426 }
427
428 token = preserveInfo.token;
429 return token;
430
431 case ENUM:
432 token = next();
433 lineno = stream.getLineno();
434 charno = stream.getCharno();
435
436 type = null;
437 if (token != JsDocToken.EOL && token != JsDocToken.EOC) {
438 type = createJSTypeExpression(
439 parseAndRecordTypeNode(token));
440 }
441
442 if (type == null) {
443 type = createJSTypeExpression(newStringNode("number"));
444 }
445 if (!jsdocBuilder.recordEnumParameterType(type)) {
446 parser.addTypeWarning(
447 "msg.jsdoc.incompat.type", lineno, charno);
448 }
449 token = eatTokensUntilEOL(token);
450 return token;
451
452 case EXPORT:
453 if (!jsdocBuilder.recordExport()) {
454 parser.addParserWarning("msg.jsdoc.export",
455 stream.getLineno(), stream.getCharno());
456 }
457 return eatTokensUntilEOL();
458
459 case EXPOSE:
460 if (!jsdocBuilder.recordExpose()) {
461 parser.addParserWarning("msg.jsdoc.expose",
462 stream.getLineno(), stream.getCharno());
463 }
464 return eatTokensUntilEOL();
465
466 case EXTERNS:
467 if (!jsdocBuilder.recordExterns()) {
468 parser.addParserWarning("msg.jsdoc.externs",
469 stream.getLineno(), stream.getCharno());
470 }
471 return eatTokensUntilEOL();
472
473 case JAVA_DISPATCH:
474 if (!jsdocBuilder.recordJavaDispatch()) {
475 parser.addParserWarning("msg.jsdoc.javadispatch",
476 stream.getLineno(), stream.getCharno());
477 }
478 return eatTokensUntilEOL();
479
480 case EXTENDS:
481 case IMPLEMENTS:
482 skipEOLs();
483 token = next();
484 lineno = stream.getLineno();
485 charno = stream.getCharno();
486 boolean matchingRc = false;
487
488 if (token == JsDocToken.LC) {
489 token = next();
490 matchingRc = true;
491 }
492
493 if (token == JsDocToken.STRING) {
494 Node typeNode = parseAndRecordTypeNameNode(
495 token, lineno, charno, matchingRc);
496
497 lineno = stream.getLineno();
498 charno = stream.getCharno();
499
500 typeNode = wrapNode(Token.BANG, typeNode);
501 type = createJSTypeExpression(typeNode);
502
503 if (annotation == Annotation.EXTENDS) {
504 // record the extended type, check later
505 extendedTypes.add(new ExtendedTypeInfo(
506 type, stream.getLineno(), stream.getCharno()));
507 } else {
508 Preconditions.checkState(
509 annotation == Annotation.IMPLEMENTS);
510 if (!jsdocBuilder.recordImplementedInterface(type)) {
511 parser.addTypeWarning("msg.jsdoc.implements.duplicate",
512 lineno, charno);
513 }
514 }
515 token = next();
516 if (matchingRc) {
517 if (token != JsDocToken.RC) {
518 parser.addTypeWarning("msg.jsdoc.missing.rc",
519 stream.getLineno(), stream.getCharno());
520 }
521 } else if (token != JsDocToken.EOL &&
522 token != JsDocToken.EOF && token != JsDocToken.EOC) {
523 parser.addTypeWarning("msg.end.annotation.expected",
524 stream.getLineno(), stream.getCharno());
525 }
526 } else {
527 parser.addTypeWarning("msg.no.type.name", lineno, charno);
528 }
529 token = eatTokensUntilEOL(token);
530 return token;
531
532 case HIDDEN:
533 if (!jsdocBuilder.recordHiddenness()) {
534 parser.addParserWarning("msg.jsdoc.hidden",
535 stream.getLineno(), stream.getCharno());
536 }
537 return eatTokensUntilEOL();
538
539 case LENDS:
540 skipEOLs();
541
542 matchingRc = false;
543 if (match(JsDocToken.LC)) {
544 token = next();
545 matchingRc = true;
546 }
547
548 if (match(JsDocToken.STRING)) {
549 token = next();
550 if (!jsdocBuilder.recordLends(stream.getString())) {
551 parser.addTypeWarning("msg.jsdoc.lends.incompatible",
552 stream.getLineno(), stream.getCharno());
553 }
554 } else {
555 parser.addTypeWarning("msg.jsdoc.lends.missing",
556 stream.getLineno(), stream.getCharno());
557 }
558
559 if (matchingRc && !match(JsDocToken.RC)) {
560 parser.addTypeWarning("msg.jsdoc.missing.rc",
561 stream.getLineno(), stream.getCharno());
562 }
563 return eatTokensUntilEOL();
564
565 case MEANING:
566 ExtractionInfo meaningInfo =
567 extractMultilineTextualBlock(token);
568 String meaning = meaningInfo.string;
569 token = meaningInfo.token;
570 if (!jsdocBuilder.recordMeaning(meaning)) {
571 parser.addParserWarning("msg.jsdoc.meaning.extra",
572 stream.getLineno(), stream.getCharno());
573 }
574 return token;
575
576 case NO_ALIAS:
577 if (!jsdocBuilder.recordNoAlias()) {
578 parser.addParserWarning("msg.jsdoc.noalias",
579 stream.getLineno(), stream.getCharno());
580 }
581 return eatTokensUntilEOL();
582
583 case NO_COMPILE:
584 if (!jsdocBuilder.recordNoCompile()) {
585 parser.addParserWarning("msg.jsdoc.nocompile",
586 stream.getLineno(), stream.getCharno());
587 }
588 return eatTokensUntilEOL();
589
590 case NO_TYPE_CHECK:
591 if (!jsdocBuilder.recordNoTypeCheck()) {
592 parser.addParserWarning("msg.jsdoc.nocheck",
593 stream.getLineno(), stream.getCharno());
594 }
595 return eatTokensUntilEOL();
596
597 case NOT_IMPLEMENTED:
598 return eatTokensUntilEOL();
599
600 case INHERIT_DOC:
601 case OVERRIDE:
602 if (!jsdocBuilder.recordOverride()) {
603 parser.addTypeWarning("msg.jsdoc.override",
604 stream.getLineno(), stream.getCharno());
605 }
606 return eatTokensUntilEOL();
607
608 case THROWS:
609 skipEOLs();
610 token = next();
611 lineno = stream.getLineno();
612 charno = stream.getCharno();
613 type = null;
614
615 if (token == JsDocToken.LC) {
616 type = createJSTypeExpression(
617 parseAndRecordTypeNode(token));
618
619 if (type == null) {
620 // parsing error reported during recursive descent
621 // recovering parsing
622 return eatTokensUntilEOL();
623 }
624 }
625
626 // *Update* the token to that after the type annotation.
627 token = current();
628
629 // Save the throw type.
630 jsdocBuilder.recordThrowType(type);
631
632 // Find the throw's description (if applicable).
633 if (jsdocBuilder.shouldParseDocumentation()) {
634 ExtractionInfo descriptionInfo =
635 extractMultilineTextualBlock(token);
636
637 String description = descriptionInfo.string;
638
639 if (description.length() > 0) {
640 jsdocBuilder.recordThrowDescription(type, description);
641 }
642
643 token = descriptionInfo.token;
644 } else {
645 token = eatTokensUntilEOL(token);
646 }
647 return token;
648
649 case PARAM:
650 skipEOLs();
651 token = next();
652 lineno = stream.getLineno();
653 charno = stream.getCharno();
654 type = null;
655
656 if (token == JsDocToken.LC) {
657 type = createJSTypeExpression(
658 parseAndRecordParamTypeNode(token));
659
660 if (type == null) {
661 // parsing error reported during recursive descent
662 // recovering parsing
663 return eatTokensUntilEOL();
664 }
665 skipEOLs();
666 token = next();
667 lineno = stream.getLineno();
668 charno = stream.getCharno();
669 }
670
671 String name = null;
672 boolean isBracketedParam = JsDocToken.LB == token;
673 if (isBracketedParam) {
674 token = next();
675 }
676
677 if (JsDocToken.STRING != token) {
678 parser.addTypeWarning("msg.missing.variable.name",
679 lineno, charno);
680 } else {
681 name = stream.getString();
682
683 if (isBracketedParam) {
684 token = next();
685
686 // Throw out JsDocToolkit's "default" parameter
687 // annotation. It makes no sense under our type
688 // system.
689 if (JsDocToken.EQUALS == token) {
690 token = next();
691 if (JsDocToken.STRING == token) {
692 token = next();
693 }
694 }
695
696 if (JsDocToken.RB != token) {
697 reportTypeSyntaxWarning("msg.jsdoc.missing.rb");
698 } else if (type != null) {
699 // Make the type expression optional, if it isn't
700 // already.
701 type = JSTypeExpression.makeOptionalArg(type);
702 }
703 }
704
705 // If the param name has a DOT in it, just throw it out
706 // quietly. We do not handle the JsDocToolkit method
707 // for handling properties of params.
708 if (name.indexOf('.') > -1) {
709 name = null;
710 } else if (!jsdocBuilder.recordParameter(name, type)) {
711 if (jsdocBuilder.hasParameter(name)) {
712 parser.addTypeWarning("msg.dup.variable.name", name,
713 lineno, charno);
714 } else {
715 parser.addTypeWarning("msg.jsdoc.incompat.type", name,
716 lineno, charno);
717 }
718 }
719 }
720
721 if (name == null) {
722 token = eatTokensUntilEOL(token);
723 return token;
724 }
725
726 jsdocBuilder.markName(name, sourceFile, lineno, charno);
727
728 // Find the parameter's description (if applicable).
729 if (jsdocBuilder.shouldParseDocumentation()) {
730 ExtractionInfo paramDescriptionInfo =
731 extractMultilineTextualBlock(token);
732
733 String paramDescription = paramDescriptionInfo.string;
734
735 if (paramDescription.length() > 0) {
736 jsdocBuilder.recordParameterDescription(name,
737 paramDescription);
738 }
739
740 token = paramDescriptionInfo.token;
741 } else {
742 token = eatTokensUntilEOL(token);
743 }
744 return token;
745
746 case PRESERVE_TRY:
747 if (!jsdocBuilder.recordPreserveTry()) {
748 parser.addParserWarning("msg.jsdoc.preservertry",
749 stream.getLineno(), stream.getCharno());
750 }
751 return eatTokensUntilEOL();
752
753 case NO_SHADOW:
754 if (!jsdocBuilder.recordNoShadow()) {
755 parser.addParserWarning("msg.jsdoc.noshadow",
756 stream.getLineno(), stream.getCharno());
757 }
758 return eatTokensUntilEOL();
759
760 case NO_SIDE_EFFECTS:
761 if (!jsdocBuilder.recordNoSideEffects()) {
762 parser.addParserWarning("msg.jsdoc.nosideeffects",
763 stream.getLineno(), stream.getCharno());
764 }
765 return eatTokensUntilEOL();
766
767 case MODIFIES:
768 token = parseModifiesTag(next());
769 return token;
770
771 case IMPLICIT_CAST:
772 if (!jsdocBuilder.recordImplicitCast()) {
773 parser.addTypeWarning("msg.jsdoc.implicitcast",
774 stream.getLineno(), stream.getCharno());
775 }
776 return eatTokensUntilEOL();
777
778 case SEE:
779 if (jsdocBuilder.shouldParseDocumentation()) {
780 ExtractionInfo referenceInfo = extractSingleLineBlock();
781 String reference = referenceInfo.string;
782
783 if (reference.length() == 0) {
784 parser.addParserWarning("msg.jsdoc.seemissing",
785 stream.getLineno(), stream.getCharno());
786 } else {
787 jsdocBuilder.addReference(reference);
788 }
789
790 token = referenceInfo.token;
791 } else {
792 token = eatTokensUntilEOL(token);
793 }
794 return token;
795
796 case STABLEIDGENERATOR:
797 if (!jsdocBuilder.recordStableIdGenerator()) {
798 parser.addParserWarning("msg.jsdoc.stableidgen",
799 stream.getLineno(), stream.getCharno());
800 }
801 return eatTokensUntilEOL();
802
803 case SUPPRESS:
804 token = parseSuppressTag(next());
805 return token;
806
807 case TEMPLATE: {
808 ExtractionInfo templateInfo = extractSingleLineBlock();
809 List<String> names = Lists.newArrayList(
810 Splitter.on(',')
811 .trimResults()
812 .split(templateInfo.string));
813
814 if (names.size() == 0 || names.get(0).length() == 0) {
815 parser.addTypeWarning("msg.jsdoc.templatemissing",
816 stream.getLineno(), stream.getCharno());
817 } else if (!jsdocBuilder.recordTemplateTypeNames(names)) {
818 parser.addTypeWarning("msg.jsdoc.template.at.most.once",
819 stream.getLineno(), stream.getCharno());
820 }
821
822 token = templateInfo.token;
823 return token;
824 }
825
826 case CLASS_TEMPLATE: {
827 ExtractionInfo classTemplateInfo = extractSingleLineBlock();
828 List<String> names = Lists.newArrayList(
829 Splitter.on(',')
830 .trimResults()
831 .split(classTemplateInfo.string));
832
833 if (names.size() == 0 || names.get(0).length() == 0) {
834 parser.addTypeWarning(
835 "msg.jsdoc.classtemplate.missing.type.name",
836 stream.getLineno(), stream.getCharno());
837 } else if (!jsdocBuilder.recordClassTemplateTypeNames(names)) {
838 parser.addTypeWarning(
839 "msg.jsdoc.classtemplate.at.most.once",
840 stream.getLineno(), stream.getCharno());
841 }
842
843 token = classTemplateInfo.token;
844 return token;
845 }
846
847 case IDGENERATOR:
848 if (!jsdocBuilder.recordIdGenerator()) {
849 parser.addParserWarning("msg.jsdoc.idgen",
850 stream.getLineno(), stream.getCharno());
851 }
852 return eatTokensUntilEOL();
853
854 case VERSION:
855 ExtractionInfo versionInfo = extractSingleLineBlock();
856 String version = versionInfo.string;
857
858 if (version.length() == 0) {
859 parser.addParserWarning("msg.jsdoc.versionmissing",
860 stream.getLineno(), stream.getCharno());
861 } else {
862 if (!jsdocBuilder.recordVersion(version)) {
863 parser.addParserWarning("msg.jsdoc.extraversion",
864 stream.getLineno(), stream.getCharno());
865 }
866 }
867
868 token = versionInfo.token;
869 return token;
870
871 case CONSTANT:
872 case DEFINE:
873 case RETURN:
874 case PRIVATE:
875 case PROTECTED:
876 case PUBLIC:
877 case THIS:
878 case TYPE:
879 case TYPEDEF:
880 lineno = stream.getLineno();
881 charno = stream.getCharno();
882
883 Node typeNode = null;
884 boolean hasType = lookAheadForTypeAnnotation();
885 boolean isAlternateTypeAnnotation =
886 (annotation == Annotation.PRIVATE ||
887 annotation == Annotation.PROTECTED ||
888 annotation == Annotation.PUBLIC ||
889 annotation == Annotation.CONSTANT);
890 boolean canSkipTypeAnnotation =
891 (isAlternateTypeAnnotation ||
892 annotation == Annotation.RETURN);
893 type = null;
894 if (hasType || !canSkipTypeAnnotation) {
895 skipEOLs();
896 token = next();
897 typeNode = parseAndRecordTypeNode(token);
898
899 if (annotation == Annotation.THIS) {
900 typeNode = wrapNode(Token.BANG, typeNode);
901 }
902 type = createJSTypeExpression(typeNode);
903 }
904
905 // The error was reported during recursive descent
906 // recovering parsing
907 boolean hasError = type == null && !canSkipTypeAnnotation;
908 if (!hasError) {
909 // Record types for @type.
910 // If the @private, @protected, or @public annotations
911 // have a type attached, pretend that they actually wrote:
912 // @type {type}\n@private
913 // This will have some weird behavior in some cases
914 // (for example, @private can now be used as a type-cast),
915 // but should be mostly OK.
916 if ((type != null && isAlternateTypeAnnotation)
917 || annotation == Annotation.TYPE) {
918 if (!jsdocBuilder.recordType(type)) {
919 parser.addTypeWarning(
920 "msg.jsdoc.incompat.type", lineno, charno);
921 }
922 }
923
924 switch (annotation) {
925 case CONSTANT:
926 if (!jsdocBuilder.recordConstancy()) {
927 parser.addParserWarning("msg.jsdoc.const",
928 stream.getLineno(), stream.getCharno());
929 }
930 break;
931
932 case DEFINE:
933 if (!jsdocBuilder.recordDefineType(type)) {
934 parser.addParserWarning("msg.jsdoc.define",
935 lineno, charno);
936 }
937 break;
938
939 case PRIVATE:
940 if (!jsdocBuilder.recordVisibility(Visibility.PRIVATE)) {
941 parser.addParserWarning(
942 "msg.jsdoc.visibility.private",
943 lineno, charno);
944 }
945 break;
946
947 case PROTECTED:
948 if (!jsdocBuilder.recordVisibility(Visibility.PROTECTED)) {
949 parser.addParserWarning(
950 "msg.jsdoc.visibility.protected",
951 lineno, charno);
952 }
953 break;
954
955 case PUBLIC:
956 if (!jsdocBuilder.recordVisibility(Visibility.PUBLIC)) {
957 parser.addParserWarning(
958 "msg.jsdoc.visibility.public",
959 lineno, charno);
960 }
961 break;
962
963 case RETURN:
964 if (type == null) {
965 type = createJSTypeExpression(newNode(Token.QMARK));
966 }
967
968 if (!jsdocBuilder.recordReturnType(type)) {
969 parser.addTypeWarning(
970 "msg.jsdoc.incompat.type", lineno, charno);
971 break;
972 }
973
974 // Find the return's description (if applicable).
975 if (jsdocBuilder.shouldParseDocumentation()) {
976 ExtractionInfo returnDescriptionInfo =
977 extractMultilineTextualBlock(token);
978
979 String returnDescription =
980 returnDescriptionInfo.string;
981
982 if (returnDescription.length() > 0) {
983 jsdocBuilder.recordReturnDescription(
984 returnDescription);
985 }
986
987 token = returnDescriptionInfo.token;
988 } else {
989 token = eatTokensUntilEOL(token);
990 }
991 return token;
992
993 case THIS:
994 if (!jsdocBuilder.recordThisType(type)) {
995 parser.addTypeWarning(
996 "msg.jsdoc.incompat.type", lineno, charno);
997 }
998 break;
999
1000 case TYPEDEF:
1001 if (!jsdocBuilder.recordTypedef(type)) {
1002 parser.addTypeWarning(
1003 "msg.jsdoc.incompat.type", lineno, charno);
1004 }
1005 break;
1006 }
1007 }
1008
1009 return eatTokensUntilEOL();
1010 }
1011 }
1012
1013 return next();
1014 }
1015
1016 private void checkExtendedTypes(List<ExtendedTypeInfo> extendedTypes) {
1017 for (ExtendedTypeInfo typeInfo : extendedTypes) {
1018 // If interface, record the multiple extended interfaces
1019 if (jsdocBuilder.isInterfaceRecorded()) {
1020 if (!jsdocBuilder.recordExtendedInterface(typeInfo.type)) {
1021 parser.addParserWarning("msg.jsdoc.extends.duplicate",
1022 typeInfo.lineno, typeInfo.charno);
1023 }
1024 } else {
1025 if (!jsdocBuilder.recordBaseType(typeInfo.type)) {
1026 parser.addTypeWarning("msg.jsdoc.incompat.type",
1027 typeInfo.lineno, typeInfo.charno);
1028 }
1029 }
1030 }
1031 }
1032
1033 /**
1034 * Parse a {@code @suppress} tag of the form
1035 * {@code @suppress&#123;warning1|warning2&#125;}.
1036 *
1037 * @param token The current token.
1038 */
1039 private JsDocToken parseSuppressTag(JsDocToken token) {
1040 if (token == JsDocToken.LC) {
1041 Set<String> suppressions = new HashSet<String>();
1042 while (true) {
1043 if (match(JsDocToken.STRING)) {
1044 String name = stream.getString();
1045 if (!suppressionNames.contains(name)) {
1046 parser.addParserWarning("msg.jsdoc.suppress.unknown", name,
1047 stream.getLineno(), stream.getCharno());
1048 }
1049
1050 suppressions.add(stream.getString());
1051 token = next();
1052 } else {
1053 parser.addParserWarning("msg.jsdoc.suppress",
1054 stream.getLineno(), stream.getCharno());
1055 return token;
1056 }
1057
1058 if (match(JsDocToken.PIPE, JsDocToken.COMMA)) {
1059 token = next();
1060 } else {
1061 break;
1062 }
1063 }
1064
1065 if (!match(JsDocToken.RC)) {
1066 parser.addParserWarning("msg.jsdoc.suppress",
1067 stream.getLineno(), stream.getCharno());
1068 } else {
1069 token = next();
1070 if (!jsdocBuilder.recordSuppressions(suppressions)) {
1071 parser.addParserWarning("msg.jsdoc.suppress.duplicate",
1072 stream.getLineno(), stream.getCharno());
1073 }
1074 }
1075 }
1076 return token;
1077 }
1078
1079 /**
1080 * Parse a {@code @modifies} tag of the form
1081 * {@code @modifies&#123;this|arguments|param&#125;}.
1082 *
1083 * @param token The current token.
1084 */
1085 private JsDocToken parseModifiesTag(JsDocToken token) {
1086 if (token == JsDocToken.LC) {
1087 Set<String> modifies = new HashSet<String>();
1088 while (true) {
1089 if (match(JsDocToken.STRING)) {
1090 String name = stream.getString();
1091 if (!modifiesAnnotationKeywords.contains(name)
1092 && !jsdocBuilder.hasParameter(name)) {
1093 parser.addParserWarning("msg.jsdoc.modifies.unknown", name,
1094 stream.getLineno(), stream.getCharno());
1095 }
1096
1097 modifies.add(stream.getString());
1098 token = next();
1099 } else {
1100 parser.addParserWarning("msg.jsdoc.modifies",
1101 stream.getLineno(), stream.getCharno());
1102 return token;
1103 }
1104
1105 if (match(JsDocToken.PIPE)) {
1106 token = next();
1107 } else {
1108 break;
1109 }
1110 }
1111
1112 if (!match(JsDocToken.RC)) {
1113 parser.addParserWarning("msg.jsdoc.modifies",
1114 stream.getLineno(), stream.getCharno());
1115 } else {
1116 token = next();
1117 if (!jsdocBuilder.recordModifies(modifies)) {
1118 parser.addParserWarning("msg.jsdoc.modifies.duplicate",
1119 stream.getLineno(), stream.getCharno());
1120 }
1121 }
1122 }
1123 return token;
1124 }
1125
1126 /**
1127 * Looks for a type expression at the current token and if found,
1128 * returns it. Note that this method consumes input.
1129 *
1130 * @param token The current token.
1131 * @return The type expression found or null if none.
1132 */
1133 Node parseAndRecordTypeNode(JsDocToken token) {
1134 return parseAndRecordTypeNode(token, token == JsDocToken.LC);
1135 }
1136
1137 /**
1138 * Looks for a type expression at the current token and if found,
1139 * returns it. Note that this method consumes input.
1140 *
1141 * @param token The current token.
1142 * @param matchingLC Whether the type expression starts with a "{".
1143 * @return The type expression found or null if none.
1144 */
1145 private Node parseAndRecordTypeNode(JsDocToken token, boolean matchingLC) {
1146 return parseAndRecordTypeNode(token, stream.getLineno(), stream.getCharno(),
1147 matchingLC, false);
1148 }
1149
1150 /**
1151 * Looks for a type expression at the current token and if found,
1152 * returns it. Note that this method consumes input.
1153 *
1154 * @param token The current token.
1155 * @param lineno The line of the type expression.
1156 * @param startCharno The starting character position of the type expression.
1157 * @param matchingLC Whether the type expression starts with a "{".
1158 * @return The type expression found or null if none.
1159 */
1160 private Node parseAndRecordTypeNameNode(JsDocToken token, int lineno,
1161 int startCharno, boolean matchingLC) {
1162 return parseAndRecordTypeNode(token, lineno, startCharno, matchingLC, true);
1163 }
1164
1165 /**
1166 * Looks for a type expression at the current token and if found,
1167 * returns it. Note that this method consumes input.
1168 *
1169 * Parameter type expressions are special for two reasons:
1170 * <ol>
1171 * <li>They must begin with '{', to distinguish type names from param names.
1172 * <li>They may end in '=', to denote optionality.
1173 * </ol>
1174 *
1175 * @param token The current token.
1176 * @return The type expression found or null if none.
1177 */
1178 private Node parseAndRecordParamTypeNode(JsDocToken token) {
1179 Preconditions.checkArgument(token == JsDocToken.LC);
1180 int lineno = stream.getLineno();
1181 int startCharno = stream.getCharno();
1182
1183 Node typeNode = parseParamTypeExpressionAnnotation(token);
1184 if (typeNode != null) {
1185 int endLineno = stream.getLineno();
1186 int endCharno = stream.getCharno();
1187
1188 jsdocBuilder.markTypeNode(typeNode, lineno, startCharno,
1189 endLineno, endCharno, true);
1190 }
1191 return typeNode;
1192 }
1193
1194 /**
1195 * Looks for a parameter type expression at the current token and if found,
1196 * returns it. Note that this method consumes input.
1197 *
1198 * @param token The current token.
1199 * @param lineno The line of the type expression.
1200 * @param startCharno The starting character position of the type expression.
1201 * @param matchingLC Whether the type expression starts with a "{".
1202 * @param onlyParseSimpleNames If true, only simple type names are parsed
1203 * (via a call to parseTypeNameAnnotation instead of
1204 * parseTypeExpressionAnnotation).
1205 * @return The type expression found or null if none.
1206 */
1207 private Node parseAndRecordTypeNode(JsDocToken token, int lineno,
1208 int startCharno,
1209 boolean matchingLC,
1210 boolean onlyParseSimpleNames) {
1211 Node typeNode = null;
1212
1213 if (onlyParseSimpleNames) {
1214 typeNode = parseTypeNameAnnotation(token);
1215 } else {
1216 typeNode = parseTypeExpressionAnnotation(token);
1217 }
1218
1219 if (typeNode != null) {
1220 int endLineno = stream.getLineno();
1221 int endCharno = stream.getCharno();
1222
1223 jsdocBuilder.markTypeNode(
1224 typeNode, lineno, startCharno, endLineno, endCharno, matchingLC);
1225 }
1226
1227 return typeNode;
1228 }
1229
1230 /**
1231 * Converts a JSDoc token to its string representation.
1232 */
1233 private String toString(JsDocToken token) {
1234 switch (token) {
1235 case ANNOTATION:
1236 return "@" + stream.getString();
1237
1238 case BANG:
1239 return "!";
1240
1241 case COMMA:
1242 return ",";
1243
1244 case COLON:
1245 return ":";
1246
1247 case GT:
1248 return ">";
1249
1250 case LB:
1251 return "[";
1252
1253 case LC:
1254 return "{";
1255
1256 case LP:
1257 return "(";
1258
1259 case LT:
1260 return ".<";
1261
1262 case QMARK:
1263 return "?";
1264
1265 case PIPE:
1266 return "|";
1267
1268 case RB:
1269 return "]";
1270
1271 case RC:
1272 return "}";
1273
1274 case RP:
1275 return ")";
1276
1277 case STAR:
1278 return "*";
1279
1280 case ELLIPSIS:
1281 return "...";
1282
1283 case EQUALS:
1284 return "=";
1285
1286 case STRING:
1287 return stream.getString();
1288
1289 default:
1290 throw new IllegalStateException(token.toString());
1291 }
1292 }
1293
1294 /**
1295 * Constructs a new {@code JSTypeExpression}.
1296 * @param n A node. May be null.
1297 */
1298 JSTypeExpression createJSTypeExpression(Node n) {
1299 return n == null ? null :
1300 new JSTypeExpression(n, getSourceName());
1301 }
1302
1303 /**
1304 * Tuple for returning both the string extracted and the
1305 * new token following a call to any of the extract*Block
1306 * methods.
1307 */
1308 private static class ExtractionInfo {
1309 private final String string;
1310 private final JsDocToken token;
1311
1312 public ExtractionInfo(String string, JsDocToken token) {
1313 this.string = string;
1314 this.token = token;
1315 }
1316 }
1317
1318 /**
1319 * Tuple for recording extended types
1320 */
1321 private static class ExtendedTypeInfo {
1322 final JSTypeExpression type;
1323 final int lineno;
1324 final int charno;
1325
1326 public ExtendedTypeInfo(JSTypeExpression type, int lineno, int charno) {
1327 this.type = type;
1328 this.lineno = lineno;
1329 this.charno = charno;
1330 }
1331 }
1332
1333 /**
1334 * Extracts the text found on the current line starting at token. Note that
1335 * token = token.info; should be called after this method is used to update
1336 * the token properly in the parser.
1337 *
1338 * @return The extraction information.
1339 */
1340 private ExtractionInfo extractSingleLineBlock() {
1341
1342 // Get the current starting point.
1343 stream.update();
1344 int lineno = stream.getLineno();
1345 int charno = stream.getCharno() + 1;
1346
1347 String line = getRemainingJSDocLine().trim();
1348
1349 // Record the textual description.
1350 if (line.length() > 0) {
1351 jsdocBuilder.markText(line, lineno, charno, lineno,
1352 charno + line.length());
1353 }
1354
1355 return new ExtractionInfo(line, next());
1356 }
1357
1358 private ExtractionInfo extractMultilineTextualBlock(JsDocToken token) {
1359 return extractMultilineTextualBlock(token, WhitespaceOption.SINGLE_LINE);
1360 }
1361
1362 private enum WhitespaceOption {
1363 /**
1364 * Preserves all whitespace and formatting. Needed for licenses and
1365 * purposely formatted text.
1366 */
1367 PRESERVE,
1368
1369 /** Preserves newlines but trims the output. */
1370 TRIM,
1371
1372 /** Removes newlines and turns the output into a single line string. */
1373 SINGLE_LINE
1374 }
1375
1376 /**
1377 * Extracts the text found on the current line and all subsequent
1378 * until either an annotation, end of comment or end of file is reached.
1379 * Note that if this method detects an end of line as the first token, it
1380 * will quit immediately (indicating that there is no text where it was
1381 * expected). Note that token = info.token; should be called after this
1382 * method is used to update the token properly in the parser.
1383 *
1384 * @param token The start token.
1385 * @param option How to handle whitespace.
1386 *
1387 * @return The extraction information.
1388 */
1389 @SuppressWarnings("fallthrough")
1390 private ExtractionInfo extractMultilineTextualBlock(JsDocToken token,
1391 WhitespaceOption option) {
1392
1393 if (token == JsDocToken.EOC || token == JsDocToken.EOL ||
1394 token == JsDocToken.EOF) {
1395 return new ExtractionInfo("", token);
1396 }
1397
1398 stream.update();
1399 int startLineno = stream.getLineno();
1400 int startCharno = stream.getCharno() + 1;
1401
1402 // Read the content from the first line.
1403 String line = getRemainingJSDocLine();
1404 if (option != WhitespaceOption.PRESERVE) {
1405 line = line.trim();
1406 }
1407
1408 StringBuilder builder = new StringBuilder();
1409 builder.append(line);
1410
1411 state = State.SEARCHING_ANNOTATION;
1412 token = next();
1413
1414 boolean ignoreStar = false;
1415
1416 // Track the start of the line to count whitespace that
1417 // the tokenizer skipped. Because this case is rare, it's easier
1418 // to do this here than in the tokenizer.
1419 int lineStartChar = -1;
1420
1421 do {
1422 switch (token) {
1423 case STAR:
1424 if (ignoreStar) {
1425 // Mark the position after the star as the new start of the line.
1426 lineStartChar = stream.getCharno() + 1;
1427 } else {
1428 // The star is part of the comment.
1429 if (builder.length() > 0) {
1430 builder.append(' ');
1431 }
1432
1433 builder.append('*');
1434 }
1435
1436 token = next();
1437 continue;
1438
1439 case EOL:
1440 if (option != WhitespaceOption.SINGLE_LINE) {
1441 builder.append("\n");
1442 }
1443
1444 ignoreStar = true;
1445 lineStartChar = 0;
1446 token = next();
1447 continue;
1448
1449 default:
1450 ignoreStar = false;
1451 state = State.SEARCHING_ANNOTATION;
1452
1453 boolean isEOC = token == JsDocToken.EOC;
1454 if (!isEOC) {
1455 if (lineStartChar != -1 && option == WhitespaceOption.PRESERVE) {
1456 int numSpaces = stream.getCharno() - lineStartChar;
1457 for (int i = 0; i < numSpaces; i++) {
1458 builder.append(' ');
1459 }
1460 lineStartChar = -1;
1461 } else if (builder.length() > 0) {
1462 // All tokens must be separated by a space.
1463 builder.append(' ');
1464 }
1465 }
1466
1467 if (token == JsDocToken.EOC ||
1468 token == JsDocToken.EOF ||
1469 // When we're capturing a license block, annotations
1470 // in the block are OK.
1471 (token == JsDocToken.ANNOTATION &&
1472 option != WhitespaceOption.PRESERVE)) {
1473 String multilineText = builder.toString();
1474
1475 if (option != WhitespaceOption.PRESERVE) {
1476 multilineText = multilineText.trim();
1477 }
1478
1479 int endLineno = stream.getLineno();
1480 int endCharno = stream.getCharno();
1481
1482 if (multilineText.length() > 0) {
1483 jsdocBuilder.markText(multilineText, startLineno, startCharno,
1484 endLineno, endCharno);
1485 }
1486
1487 return new ExtractionInfo(multilineText, token);
1488 }
1489
1490 builder.append(toString(token));
1491
1492 line = getRemainingJSDocLine();
1493
1494 if (option != WhitespaceOption.PRESERVE) {
1495 line = trimEnd(line);
1496 }
1497
1498 builder.append(line);
1499 token = next();
1500 }
1501 } while (true);
1502 }
1503
1504
1505 /**
1506 * Extracts the top-level block comment from the JsDoc comment, if any.
1507 * This method differs from the extractMultilineTextualBlock in that it
1508 * terminates under different conditions (it doesn't have the same
1509 * prechecks), it does not first read in the remaining of the current
1510 * line and its conditions for ignoring the "*" (STAR) are different.
1511 *
1512 * @param token The starting token.
1513 *
1514 * @return The extraction information.
1515 */
1516 private ExtractionInfo extractBlockComment(JsDocToken token) {
1517 StringBuilder builder = new StringBuilder();
1518
1519 boolean ignoreStar = true;
1520
1521 do {
1522 switch (token) {
1523 case ANNOTATION:
1524 case EOC:
1525 case EOF:
1526 return new ExtractionInfo(builder.toString().trim(), token);
1527
1528 case STAR:
1529 if (!ignoreStar) {
1530 if (builder.length() > 0) {
1531 builder.append(' ');
1532 }
1533
1534 builder.append('*');
1535 }
1536
1537 token = next();
1538 continue;
1539
1540 case EOL:
1541 ignoreStar = true;
1542 builder.append('\n');
1543 token = next();
1544 continue;
1545
1546 default:
1547 if (!ignoreStar && builder.length() > 0) {
1548 builder.append(' ');
1549 }
1550
1551 ignoreStar = false;
1552
1553 builder.append(toString(token));
1554
1555 String line = getRemainingJSDocLine();
1556 line = trimEnd(line);
1557 builder.append(line);
1558 token = next();
1559 }
1560 } while (true);
1561 }
1562
1563 /**
1564 * Trim characters from only the end of a string.
1565 * This method will remove all whitespace characters
1566 * (defined by Character.isWhitespace(char), in addition to the characters
1567 * provided, from the end of the provided string.
1568 *
1569 * @param s String to be trimmed
1570 * @return String with whitespace and characters in extraChars removed
1571 * from the end.
1572 */
1573 private static String trimEnd(String s) {
1574 int trimCount = 0;
1575 while (trimCount < s.length()) {
1576 char ch = s.charAt(s.length() - trimCount - 1);
1577 if (Character.isWhitespace(ch)) {
1578 trimCount++;
1579 } else {
1580 break;
1581 }
1582 }
1583
1584 if (trimCount == 0) {
1585 return s;
1586 }
1587 return s.substring(0, s.length() - trimCount);
1588 }
1589
1590 // Based on ES4 grammar proposed on July 10, 2008.
1591 // http://wiki.ecmascript.org/doku.php?id=spec:spec
1592 // Deliberately written to line up with the actual grammar rules,
1593 // for maximum flexibility.
1594
1595 // TODO(nicksantos): The current implementation tries to maintain backwards
1596 // compatibility with previous versions of the spec whenever we can.
1597 // We should try to gradually withdraw support for these.
1598
1599 /**
1600 * TypeExpressionAnnotation := TypeExpression |
1601 * '{' TopLevelTypeExpression '}'
1602 */
1603 private Node parseTypeExpressionAnnotation(JsDocToken token) {
1604 if (token == JsDocToken.LC) {
1605 skipEOLs();
1606 Node typeNode = parseTopLevelTypeExpression(next());
1607 if (typeNode != null) {
1608 skipEOLs();
1609 if (!match(JsDocToken.RC)) {
1610 reportTypeSyntaxWarning("msg.jsdoc.missing.rc");
1611 } else {
1612 next();
1613 }
1614 }
1615
1616 return typeNode;
1617 } else {
1618 return parseTypeExpression(token);
1619 }
1620 }
1621
1622 /**
1623 * ParamTypeExpressionAnnotation :=
1624 * '{' OptionalParameterType '}' |
1625 * '{' TopLevelTypeExpression '}' |
1626 * '{' '...' TopLevelTypeExpression '}'
1627 *
1628 * OptionalParameterType :=
1629 * TopLevelTypeExpression '='
1630 */
1631 private Node parseParamTypeExpressionAnnotation(JsDocToken token) {
1632 Preconditions.checkArgument(token == JsDocToken.LC);
1633
1634 skipEOLs();
1635
1636 boolean restArg = false;
1637 token = next();
1638 if (token == JsDocToken.ELLIPSIS) {
1639 token = next();
1640 if (token == JsDocToken.RC) {
1641 // EMPTY represents the UNKNOWN type in the Type AST.
1642 return wrapNode(Token.ELLIPSIS, IR.empty());
1643 }
1644 restArg = true;
1645 }
1646
1647 Node typeNode = parseTopLevelTypeExpression(token);
1648 if (typeNode != null) {
1649 skipEOLs();
1650 if (restArg) {
1651 typeNode = wrapNode(Token.ELLIPSIS, typeNode);
1652 } else if (match(JsDocToken.EQUALS)) {
1653 next();
1654 skipEOLs();
1655 typeNode = wrapNode(Token.EQUALS, typeNode);
1656 }
1657
1658 if (!match(JsDocToken.RC)) {
1659 reportTypeSyntaxWarning("msg.jsdoc.missing.rc");
1660 } else {
1661 next();
1662 }
1663 }
1664
1665 return typeNode;
1666 }
1667
1668 /**
1669 * TypeNameAnnotation := TypeName | '{' TypeName '}'
1670 */
1671 private Node parseTypeNameAnnotation(JsDocToken token) {
1672 if (token == JsDocToken.LC) {
1673 skipEOLs();
1674 Node typeNode = parseTypeName(next());
1675 if (typeNode != null) {
1676 skipEOLs();
1677 if (!match(JsDocToken.RC)) {
1678 reportTypeSyntaxWarning("msg.jsdoc.missing.rc");
1679 } else {
1680 next();
1681 }
1682 }
1683
1684 return typeNode;
1685 } else {
1686 return parseTypeName(token);
1687 }
1688 }
1689
1690 /**
1691 * TopLevelTypeExpression := TypeExpression
1692 * | TypeUnionList
1693 *
1694 * We made this rule up, for the sake of backwards compatibility.
1695 */
1696 private Node parseTopLevelTypeExpression(JsDocToken token) {
1697 Node typeExpr = parseTypeExpression(token);
1698 if (typeExpr != null) {
1699 // top-level unions are allowed
1700 if (match(JsDocToken.PIPE)) {
1701 next();
1702 if (match(JsDocToken.PIPE)) {
1703 // We support double pipes for backwards-compatibility.
1704 next();
1705 }
1706 skipEOLs();
1707 token = next();
1708 return parseUnionTypeWithAlternate(token, typeExpr);
1709 }
1710 }
1711 return typeExpr;
1712 }
1713
1714 /**
1715 * TypeExpressionList := TopLevelTypeExpression
1716 * | TopLevelTypeExpression ',' TypeExpressionList
1717 */
1718 private Node parseTypeExpressionList(JsDocToken token) {
1719 Node typeExpr = parseTopLevelTypeExpression(token);
1720 if (typeExpr == null) {
1721 return null;
1722 }
1723 Node typeList = IR.block();
1724 typeList.addChildToBack(typeExpr);
1725 while (match(JsDocToken.COMMA)) {
1726 next();
1727 skipEOLs();
1728 typeExpr = parseTopLevelTypeExpression(next());
1729 if (typeExpr == null) {
1730 return null;
1731 }
1732 typeList.addChildToBack(typeExpr);
1733 }
1734 return typeList;
1735 }
1736
1737 /**
1738 * TypeExpression := BasicTypeExpression
1739 * | '?' BasicTypeExpression
1740 * | '!' BasicTypeExpression
1741 * | BasicTypeExpression '?'
1742 * | BasicTypeExpression '!'
1743 * | '?'
1744 */
1745 private Node parseTypeExpression(JsDocToken token) {
1746 if (token == JsDocToken.QMARK) {
1747 // A QMARK could mean that a type is nullable, or that it's unknown.
1748 // We use look-ahead 1 to determine whether it's unknown. Otherwise,
1749 // we assume it means nullable. There are 5 cases:
1750 // {?} - right curly
1751 // {?=} - equals
1752 // {function(?, number)} - comma
1753 // {function(number, ?)} - right paren
1754 // {function(number, ...[?])} - right bracket
1755 // {function(): ?|number} - pipe
1756 // {Array.<?>} - greater than
1757 // I'm not a big fan of using look-ahead for this, but it makes
1758 // the type language a lot nicer.
1759 token = next();
1760 if (token == JsDocToken.COMMA ||
1761 token == JsDocToken.EQUALS ||
1762 token == JsDocToken.RB ||
1763 token == JsDocToken.RC ||
1764 token == JsDocToken.RP ||
1765 token == JsDocToken.PIPE ||
1766 token == JsDocToken.GT) {
1767 restoreLookAhead(token);
1768 return newNode(Token.QMARK);
1769 }
1770
1771 return wrapNode(Token.QMARK, parseBasicTypeExpression(token));
1772 } else if (token == JsDocToken.BANG) {
1773 return wrapNode(Token.BANG, parseBasicTypeExpression(next()));
1774 } else {
1775 Node basicTypeExpr = parseBasicTypeExpression(token);
1776 if (basicTypeExpr != null) {
1777 if (match(JsDocToken.QMARK)) {
1778 next();
1779 return wrapNode(Token.QMARK, basicTypeExpr);
1780 } else if (match(JsDocToken.BANG)) {
1781 next();
1782 return wrapNode(Token.BANG, basicTypeExpr);
1783 }
1784 }
1785
1786 return basicTypeExpr;
1787 }
1788 }
1789
1790 /**
1791 * BasicTypeExpression := '*' | 'null' | 'undefined' | TypeName
1792 * | FunctionType | UnionType | RecordType | ArrayType
1793 */
1794 private Node parseBasicTypeExpression(JsDocToken token) {
1795 if (token == JsDocToken.STAR) {
1796 return newNode(Token.STAR);
1797 } else if (token == JsDocToken.LB) {
1798 skipEOLs();
1799 return parseArrayType(next());
1800 } else if (token == JsDocToken.LC) {
1801 skipEOLs();
1802 return parseRecordType(next());
1803 } else if (token == JsDocToken.LP) {
1804 skipEOLs();
1805 return parseUnionType(next());
1806 } else if (token == JsDocToken.STRING) {
1807 String string = stream.getString();
1808 if ("function".equals(string)) {
1809 skipEOLs();
1810 return parseFunctionType(next());
1811 } else if ("null".equals(string) || "undefined".equals(string)) {
1812 return newStringNode(string);
1813 } else {
1814 return parseTypeName(token);
1815 }
1816 }
1817
1818 restoreLookAhead(token);
1819 return reportGenericTypeSyntaxWarning();
1820 }
1821
1822 /**
1823 * TypeName := NameExpression | NameExpression TypeApplication
1824 * TypeApplication := '.<' TypeExpressionList '>'
1825 */
1826 private Node parseTypeName(JsDocToken token) {
1827 if (token != JsDocToken.STRING) {
1828 return reportGenericTypeSyntaxWarning();
1829 }
1830
1831 String typeName = stream.getString();
1832 int lineno = stream.getLineno();
1833 int charno = stream.getCharno();
1834 while (match(JsDocToken.EOL) &&
1835 typeName.charAt(typeName.length() - 1) == '.') {
1836 skipEOLs();
1837 if (match(JsDocToken.STRING)) {
1838 next();
1839 typeName += stream.getString();
1840 }
1841 }
1842
1843 Node typeNameNode = newStringNode(typeName, lineno, charno);
1844
1845 if (match(JsDocToken.LT)) {
1846 next();
1847 skipEOLs();
1848 Node memberType = parseTypeExpressionList(next());
1849 if (memberType != null) {
1850 typeNameNode.addChildToFront(memberType);
1851
1852 skipEOLs();
1853 if (!match(JsDocToken.GT)) {
1854 return reportTypeSyntaxWarning("msg.jsdoc.missing.gt");
1855 }
1856
1857 next();
1858 }
1859 }
1860 return typeNameNode;
1861 }
1862
1863 /**
1864 * FunctionType := 'function' FunctionSignatureType
1865 * FunctionSignatureType :=
1866 * TypeParameters '(' 'this' ':' TypeName, ParametersType ')' ResultType
1867 */
1868 private Node parseFunctionType(JsDocToken token) {
1869 // NOTE(nicksantos): We're not implementing generics at the moment, so
1870 // just throw out TypeParameters.
1871 if (token != JsDocToken.LP) {
1872 restoreLookAhead(token);
1873 return reportTypeSyntaxWarning("msg.jsdoc.missing.lp");
1874 }
1875
1876 Node functionType = newNode(Token.FUNCTION);
1877 Node parameters = null;
1878 skipEOLs();
1879 if (!match(JsDocToken.RP)) {
1880 token = next();
1881
1882 boolean hasParams = true;
1883 if (token == JsDocToken.STRING) {
1884 String tokenStr = stream.getString();
1885 boolean isThis = "this".equals(tokenStr);
1886 boolean isNew = "new".equals(tokenStr);
1887 if (isThis || isNew) {
1888 if (match(JsDocToken.COLON)) {
1889 next();
1890 skipEOLs();
1891 Node contextType = wrapNode(
1892 isThis ? Token.THIS : Token.NEW,
1893 parseTypeName(next()));
1894 if (contextType == null) {
1895 return null;
1896 }
1897
1898 functionType.addChildToFront(contextType);
1899 } else {
1900 return reportTypeSyntaxWarning("msg.jsdoc.missing.colon");
1901 }
1902
1903 if (match(JsDocToken.COMMA)) {
1904 next();
1905 skipEOLs();
1906 token = next();
1907 } else {
1908 hasParams = false;
1909 }
1910 }
1911 }
1912
1913 if (hasParams) {
1914 parameters = parseParametersType(token);
1915 if (parameters == null) {
1916 return null;
1917 }
1918 }
1919 }
1920
1921 if (parameters != null) {
1922 functionType.addChildToBack(parameters);
1923 }
1924
1925 skipEOLs();
1926 if (!match(JsDocToken.RP)) {
1927 return reportTypeSyntaxWarning("msg.jsdoc.missing.rp");
1928 }
1929
1930 skipEOLs();
1931 Node resultType = parseResultType(next());
1932 if (resultType == null) {
1933 return null;
1934 } else {
1935 functionType.addChildToBack(resultType);
1936 }
1937 return functionType;
1938 }
1939
1940 /**
1941 * ParametersType := RestParameterType | NonRestParametersType
1942 * | NonRestParametersType ',' RestParameterType
1943 * RestParameterType := '...' Identifier
1944 * NonRestParametersType := ParameterType ',' NonRestParametersType
1945 * | ParameterType
1946 * | OptionalParametersType
1947 * OptionalParametersType := OptionalParameterType
1948 * | OptionalParameterType, OptionalParametersType
1949 * OptionalParameterType := ParameterType=
1950 * ParameterType := TypeExpression | Identifier ':' TypeExpression
1951 */
1952 // NOTE(nicksantos): The official ES4 grammar forces optional and rest
1953 // arguments to come after the required arguments. Our parser does not
1954 // enforce this. Instead we allow them anywhere in the function at parse-time,
1955 // and then warn about them during type resolution.
1956 //
1957 // In theory, it might be mathematically nicer to do the order-checking here.
1958 // But in practice, the order-checking for structural functions is exactly
1959 // the same as the order-checking for @param annotations. And the latter
1960 // has to happen during type resolution. Rather than duplicate the
1961 // order-checking in two places, we just do all of it in type resolution.
1962 private Node parseParametersType(JsDocToken token) {
1963 Node paramsType = newNode(Token.PARAM_LIST);
1964 boolean isVarArgs = false;
1965 Node paramType = null;
1966 if (token != JsDocToken.RP) {
1967 do {
1968 if (paramType != null) {
1969 // skip past the comma
1970 next();
1971 skipEOLs();
1972 token = next();
1973 }
1974
1975 if (token == JsDocToken.ELLIPSIS) {
1976 // In the latest ES4 proposal, there are no type constraints allowed
1977 // on variable arguments. We support the old syntax for backwards
1978 // compatibility, but we should gradually tear it out.
1979 skipEOLs();
1980 if (match(JsDocToken.RP)) {
1981 paramType = newNode(Token.ELLIPSIS);
1982 } else {
1983 skipEOLs();
1984 if (!match(JsDocToken.LB)) {
1985 return reportTypeSyntaxWarning("msg.jsdoc.missing.lb");
1986 }
1987
1988 next();
1989 skipEOLs();
1990 paramType = wrapNode(Token.ELLIPSIS, parseTypeExpression(next()));
1991 skipEOLs();
1992 if (!match(JsDocToken.RB)) {
1993 return reportTypeSyntaxWarning("msg.jsdoc.missing.rb");
1994 }
1995 skipEOLs();
1996 next();
1997 }
1998
1999 isVarArgs = true;
2000 } else {
2001 paramType = parseTypeExpression(token);
2002 if (match(JsDocToken.EQUALS)) {
2003 skipEOLs();
2004 next();
2005 paramType = wrapNode(Token.EQUALS, paramType);
2006 }
2007 }
2008
2009 if (paramType == null) {
2010 return null;
2011 }
2012 paramsType.addChildToBack(paramType);
2013 if (isVarArgs) {
2014 break;
2015 }
2016 } while (match(JsDocToken.COMMA));
2017 }
2018
2019 if (isVarArgs && match(JsDocToken.COMMA)) {
2020 return reportTypeSyntaxWarning("msg.jsdoc.function.varargs");
2021 }
2022
2023 // The right paren will be checked by parseFunctionType
2024
2025 return paramsType;
2026 }
2027
2028 /**
2029 * ResultType := <empty> | ':' void | ':' TypeExpression
2030 */
2031 private Node parseResultType(JsDocToken token) {
2032 skipEOLs();
2033 if (!match(JsDocToken.COLON)) {
2034 return newNode(Token.EMPTY);
2035 }
2036
2037 token = next();
2038 skipEOLs();
2039 if (match(JsDocToken.STRING) && "void".equals(stream.getString())) {
2040 next();
2041 return newNode(Token.VOID);
2042 } else {
2043 return parseTypeExpression(next());
2044 }
2045 }
2046
2047 /**
2048 * UnionType := '(' TypeUnionList ')'
2049 * TypeUnionList := TypeExpression | TypeExpression '|' TypeUnionList
2050 *
2051 * We've removed the empty union type.
2052 */
2053 private Node parseUnionType(JsDocToken token) {
2054 return parseUnionTypeWithAlternate(token, null);
2055 }
2056
2057 /**
2058 * Create a new union type, with an alternate that has already been
2059 * parsed. The alternate may be null.
2060 */
2061 private Node parseUnionTypeWithAlternate(JsDocToken token, Node alternate) {
2062 Node union = newNode(Token.PIPE);
2063 if (alternate != null) {
2064 union.addChildToBack(alternate);
2065 }
2066
2067 Node expr = null;
2068 do {
2069 if (expr != null) {
2070 skipEOLs();
2071 token = next();
2072 Preconditions.checkState(
2073 token == JsDocToken.PIPE || token == JsDocToken.COMMA);
2074
2075 boolean isPipe = token == JsDocToken.PIPE;
2076 if (isPipe && match(JsDocToken.PIPE)) {
2077 // We support double pipes for backwards compatibility.
2078 next();
2079 }
2080 skipEOLs();
2081 token = next();
2082 }
2083 expr = parseTypeExpression(token);
2084 if (expr == null) {
2085 return null;
2086 }
2087
2088 union.addChildToBack(expr);
2089 // We support commas for backwards compatibility.
2090 } while (match(JsDocToken.PIPE, JsDocToken.COMMA));
2091
2092 if (alternate == null) {
2093 skipEOLs();
2094 if (!match(JsDocToken.RP)) {
2095 return reportTypeSyntaxWarning("msg.jsdoc.missing.rp");
2096 }
2097 next();
2098 }
2099 return union;
2100 }
2101
2102 /**
2103 * ArrayType := '[' ElementTypeList ']'
2104 * ElementTypeList := <empty> | TypeExpression | '...' TypeExpression
2105 * | TypeExpression ',' ElementTypeList
2106 */
2107 private Node parseArrayType(JsDocToken token) {
2108 Node array = newNode(Token.LB);
2109 Node arg = null;
2110 boolean hasVarArgs = false;
2111
2112 do {
2113 if (arg != null) {
2114 next();
2115 skipEOLs();
2116 token = next();
2117 }
2118 if (token == JsDocToken.ELLIPSIS) {
2119 arg = wrapNode(Token.ELLIPSIS, parseTypeExpression(next()));
2120 hasVarArgs = true;
2121 } else {
2122 arg = parseTypeExpression(token);
2123 }
2124
2125 if (arg == null) {
2126 return null;
2127 }
2128
2129 array.addChildToBack(arg);
2130 if (hasVarArgs) {
2131 break;
2132 }
2133 skipEOLs();
2134 } while (match(JsDocToken.COMMA));
2135
2136 if (!match(JsDocToken.RB)) {
2137 return reportTypeSyntaxWarning("msg.jsdoc.missing.rb");
2138 }
2139 next();
2140 return array;
2141 }
2142
2143 /**
2144 * RecordType := '{' FieldTypeList '}'
2145 */
2146 private Node parseRecordType(JsDocToken token) {
2147 Node recordType = newNode(Token.LC);
2148 Node fieldTypeList = parseFieldTypeList(token);
2149
2150 if (fieldTypeList == null) {
2151 return reportGenericTypeSyntaxWarning();
2152 }
2153
2154 skipEOLs();
2155 if (!match(JsDocToken.RC)) {
2156 return reportTypeSyntaxWarning("msg.jsdoc.missing.rc");
2157 }
2158
2159 next();
2160
2161 recordType.addChildToBack(fieldTypeList);
2162 return recordType;
2163 }
2164
2165 /**
2166 * FieldTypeList := FieldType | FieldType ',' FieldTypeList
2167 */
2168 private Node parseFieldTypeList(JsDocToken token) {
2169 Node fieldTypeList = newNode(Token.LB);
2170
2171 do {
2172 Node fieldType = parseFieldType(token);
2173
2174 if (fieldType == null) {
2175 return null;
2176 }
2177
2178 fieldTypeList.addChildToBack(fieldType);
2179
2180 skipEOLs();
2181 if (!match(JsDocToken.COMMA)) {
2182 break;
2183 }
2184
2185 // Move to the comma token.
2186 next();
2187
2188 // Move to the token passed the comma.
2189 skipEOLs();
2190 token = next();
2191 } while (true);
2192
2193 return fieldTypeList;
2194 }
2195
2196 /**
2197 * FieldType := FieldName | FieldName ':' TypeExpression
2198 */
2199 private Node parseFieldType(JsDocToken token) {
2200 Node fieldName = parseFieldName(token);
2201
2202 if (fieldName == null) {
2203 return null;
2204 }
2205
2206 skipEOLs();
2207 if (!match(JsDocToken.COLON)) {
2208 return fieldName;
2209 }
2210
2211 // Move to the colon.
2212 next();
2213
2214 // Move to the token after the colon and parse
2215 // the type expression.
2216 skipEOLs();
2217 Node typeExpression = parseTypeExpression(next());
2218
2219 if (typeExpression == null) {
2220 return null;
2221 }
2222
2223 Node fieldType = newNode(Token.COLON);
2224 fieldType.addChildToBack(fieldName);
2225 fieldType.addChildToBack(typeExpression);
2226 return fieldType;
2227 }
2228
2229 /**
2230 * FieldName := NameExpression | StringLiteral | NumberLiteral |
2231 * ReservedIdentifier
2232 */
2233 private Node parseFieldName(JsDocToken token) {
2234 switch (token) {
2235 case STRING:
2236 String string = stream.getString();
2237 return newStringNode(string);
2238
2239 default:
2240 return null;
2241 }
2242 }
2243
2244 private Node wrapNode(int type, Node n) {
2245 return n == null ? null :
2246 new Node(type, n, stream.getLineno(),
2247 stream.getCharno()).clonePropsFrom(templateNode);
2248 }
2249
2250 private Node newNode(int type) {
2251 return new Node(type, stream.getLineno(),
2252 stream.getCharno()).clonePropsFrom(templateNode);
2253 }
2254
2255 private Node newStringNode(String s) {
2256 return newStringNode(s, stream.getLineno(), stream.getCharno());
2257 }
2258
2259 private Node newStringNode(String s, int lineno, int charno) {
2260 Node n = Node.newString(s, lineno, charno).clonePropsFrom(templateNode);
2261 n.setLength(s.length());
2262 return n;
2263 }
2264
2265 // This is similar to IRFactory.createTemplateNode to share common props
2266 // e.g., source-name, between all nodes.
2267 private Node createTemplateNode() {
2268 // The Node type choice is arbitrary.
2269 Node templateNode = IR.script();
2270 templateNode.setStaticSourceFile(
2271 this.associatedNode != null ?
2272 this.associatedNode.getStaticSourceFile() :
2273 null);
2274 return templateNode;
2275 }
2276
2277 private Node reportTypeSyntaxWarning(String warning) {
2278 parser.addTypeWarning(warning, stream.getLineno(), stream.getCharno());
2279 return null;
2280 }
2281
2282 private Node reportGenericTypeSyntaxWarning() {
2283 return reportTypeSyntaxWarning("msg.jsdoc.type.syntax");
2284 }
2285
2286 /**
2287 * Eats tokens until {@link JsDocToken#EOL} included, and switches back the
2288 * state to {@link State#SEARCHING_ANNOTATION}.
2289 */
2290 private JsDocToken eatTokensUntilEOL() {
2291 return eatTokensUntilEOL(next());
2292 }
2293
2294 /**
2295 * Eats tokens until {@link JsDocToken#EOL} included, and switches back the
2296 * state to {@link State#SEARCHING_ANNOTATION}.
2297 */
2298 private JsDocToken eatTokensUntilEOL(JsDocToken token) {
2299 do {
2300 if (token == JsDocToken.EOL || token == JsDocToken.EOC ||
2301 token == JsDocToken.EOF) {
2302 state = State.SEARCHING_ANNOTATION;
2303 return token;
2304 }
2305 token = next();
2306 } while (true);
2307 }
2308
2309 /**
2310 * Specific value indicating that the {@link #unreadToken} contains no token.
2311 */
2312 private static final JsDocToken NO_UNREAD_TOKEN = null;
2313
2314 /**
2315 * One token buffer.
2316 */
2317 private JsDocToken unreadToken = NO_UNREAD_TOKEN;
2318
2319 /** Restores the lookahead token to the token stream */
2320 private void restoreLookAhead(JsDocToken token) {
2321 unreadToken = token;
2322 }
2323
2324 /**
2325 * Tests whether the next symbol of the token stream matches the specific
2326 * token.
2327 */
2328 private boolean match(JsDocToken token) {
2329 unreadToken = next();
2330 return unreadToken == token;
2331 }
2332
2333 /**
2334 * Tests that the next symbol of the token stream matches one of the specified
2335 * tokens.
2336 */
2337 private boolean match(JsDocToken token1, JsDocToken token2) {
2338 unreadToken = next();
2339 return unreadToken == token1 || unreadToken == token2;
2340 }
2341
2342 /**
2343 * Gets the next token of the token stream or the buffered token if a matching
2344 * was previously made.
2345 */
2346 private JsDocToken next() {
2347 if (unreadToken == NO_UNREAD_TOKEN) {
2348 return stream.getJsDocToken();
2349 } else {
2350 return current();
2351 }
2352 }
2353
2354 /**
2355 * Gets the current token, invalidating it in the process.
2356 */
2357 private JsDocToken current() {
2358 JsDocToken t = unreadToken;
2359 unreadToken = NO_UNREAD_TOKEN;
2360 return t;
2361 }
2362
2363 /**
2364 * Skips all EOLs and all empty lines in the JSDoc. Call this method if you
2365 * want the JSDoc entry to span multiple lines.
2366 */
2367 private void skipEOLs() {
2368 while (match(JsDocToken.EOL)) {
2369 next();
2370 if (match(JsDocToken.STAR)) {
2371 next();
2372 }
2373 }
2374 }
2375
2376 /**
2377 * Returns the remainder of the line.
2378 */
2379 private String getRemainingJSDocLine() {
2380 String result = stream.getRemainingJSDocLine();
2381 unreadToken = NO_UNREAD_TOKEN;
2382 return result;
2383 }
2384
2385 /**
2386 * Determines whether the parser has been populated with docinfo with a
2387 * fileoverview tag.
2388 */
2389 private boolean hasParsedFileOverviewDocInfo() {
2390 return jsdocBuilder.isPopulatedWithFileOverview();
2391 }
2392
2393 boolean hasParsedJSDocInfo() {
2394 return jsdocBuilder.isPopulated();
2395 }
2396
2397 JSDocInfo retrieveAndResetParsedJSDocInfo() {
2398 return jsdocBuilder.build(associatedNode);
2399 }
2400
2401 /**
2402 * Gets the fileoverview JSDocInfo, if any.
2403 */
2404 JSDocInfo getFileOverviewJSDocInfo() {
2405 return fileOverviewJSDocInfo;
2406 }
2407
2408 /**
2409 * Look ahead for a type annotation by advancing the character stream.
2410 * Does not modify the token stream.
2411 * This is kind of a hack, and is only necessary because we use the token
2412 * stream to parse types, but need the underlying character stream to get
2413 * JsDoc descriptions.
2414 * @return Whether we found a type annotation.
2415 */
2416 private boolean lookAheadForTypeAnnotation() {
2417 boolean matchedLc = false;
2418 int c;
2419 while (true) {
2420 c = stream.getChar();
2421 if (c == ' ') {
2422 continue;
2423 } else if (c == '{') {
2424 matchedLc = true;
2425 break;
2426 } else {
2427 break;
2428 }
2429 }
2430 stream.ungetChar(c);
2431 return matchedLc;
2432 }
2433 }