1 //===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the tentative parsing portions of the Parser
11 //  interfaces, for ambiguity resolution.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Parse/Parser.h"
16 #include "clang/Parse/ParseDiagnostic.h"
17 #include "clang/Sema/ParsedTemplate.h"
18 using namespace clang;
19 
20 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
21 /// between a declaration or an expression statement, when parsing function
22 /// bodies. Returns true for declaration, false for expression.
23 ///
24 ///         declaration-statement:
25 ///           block-declaration
26 ///
27 ///         block-declaration:
28 ///           simple-declaration
29 ///           asm-definition
30 ///           namespace-alias-definition
31 ///           using-declaration
32 ///           using-directive
33 /// [C++0x]   static_assert-declaration
34 ///
35 ///         asm-definition:
36 ///           'asm' '(' string-literal ')' ';'
37 ///
38 ///         namespace-alias-definition:
39 ///           'namespace' identifier = qualified-namespace-specifier ';'
40 ///
41 ///         using-declaration:
42 ///           'using' typename[opt] '::'[opt] nested-name-specifier
43 ///                 unqualified-id ';'
44 ///           'using' '::' unqualified-id ;
45 ///
46 ///         using-directive:
47 ///           'using' 'namespace' '::'[opt] nested-name-specifier[opt]
48 ///                 namespace-name ';'
49 ///
isCXXDeclarationStatement()50 bool Parser::isCXXDeclarationStatement() {
51   switch (Tok.getKind()) {
52     // asm-definition
53   case tok::kw_asm:
54     // namespace-alias-definition
55   case tok::kw_namespace:
56     // using-declaration
57     // using-directive
58   case tok::kw_using:
59     // static_assert-declaration
60   case tok::kw_static_assert:
61   case tok::kw__Static_assert:
62     return true;
63     // simple-declaration
64   default:
65     return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
66   }
67 }
68 
69 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
70 /// between a simple-declaration or an expression-statement.
71 /// If during the disambiguation process a parsing error is encountered,
72 /// the function returns true to let the declaration parsing code handle it.
73 /// Returns false if the statement is disambiguated as expression.
74 ///
75 /// simple-declaration:
76 ///   decl-specifier-seq init-declarator-list[opt] ';'
77 ///   decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
78 ///                      brace-or-equal-initializer ';'    [C++17]
79 ///
80 /// (if AllowForRangeDecl specified)
81 /// for ( for-range-declaration : for-range-initializer ) statement
82 ///
83 /// for-range-declaration:
84 ///    decl-specifier-seq declarator
85 ///    decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
86 ///
87 /// In any of the above cases there can be a preceding attribute-specifier-seq,
88 /// but the caller is expected to handle that.
isCXXSimpleDeclaration(bool AllowForRangeDecl)89 bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
90   // C++ 6.8p1:
91   // There is an ambiguity in the grammar involving expression-statements and
92   // declarations: An expression-statement with a function-style explicit type
93   // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
94   // from a declaration where the first declarator starts with a '('. In those
95   // cases the statement is a declaration. [Note: To disambiguate, the whole
96   // statement might have to be examined to determine if it is an
97   // expression-statement or a declaration].
98 
99   // C++ 6.8p3:
100   // The disambiguation is purely syntactic; that is, the meaning of the names
101   // occurring in such a statement, beyond whether they are type-names or not,
102   // is not generally used in or changed by the disambiguation. Class
103   // templates are instantiated as necessary to determine if a qualified name
104   // is a type-name. Disambiguation precedes parsing, and a statement
105   // disambiguated as a declaration may be an ill-formed declaration.
106 
107   // We don't have to parse all of the decl-specifier-seq part. There's only
108   // an ambiguity if the first decl-specifier is
109   // simple-type-specifier/typename-specifier followed by a '(', which may
110   // indicate a function-style cast expression.
111   // isCXXDeclarationSpecifier will return TPResult::Ambiguous only in such
112   // a case.
113 
114   bool InvalidAsDeclaration = false;
115   TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
116                                            &InvalidAsDeclaration);
117   if (TPR != TPResult::Ambiguous)
118     return TPR != TPResult::False; // Returns true for TPResult::True or
119                                    // TPResult::Error.
120 
121   // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer,
122   // and so gets some cases wrong. We can't carry on if we've already seen
123   // something which makes this statement invalid as a declaration in this case,
124   // since it can cause us to misparse valid code. Revisit this once
125   // TryParseInitDeclaratorList is fixed.
126   if (InvalidAsDeclaration)
127     return false;
128 
129   // FIXME: Add statistics about the number of ambiguous statements encountered
130   // and how they were resolved (number of declarations+number of expressions).
131 
132   // Ok, we have a simple-type-specifier/typename-specifier followed by a '(',
133   // or an identifier which doesn't resolve as anything. We need tentative
134   // parsing...
135 
136   {
137     RevertingTentativeParsingAction PA(*this);
138     TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
139   }
140 
141   // In case of an error, let the declaration parsing code handle it.
142   if (TPR == TPResult::Error)
143     return true;
144 
145   // Declarations take precedence over expressions.
146   if (TPR == TPResult::Ambiguous)
147     TPR = TPResult::True;
148 
149   assert(TPR == TPResult::True || TPR == TPResult::False);
150   return TPR == TPResult::True;
151 }
152 
153 /// Try to consume a token sequence that we've already identified as
154 /// (potentially) starting a decl-specifier.
TryConsumeDeclarationSpecifier()155 Parser::TPResult Parser::TryConsumeDeclarationSpecifier() {
156   switch (Tok.getKind()) {
157   case tok::kw__Atomic:
158     if (NextToken().isNot(tok::l_paren)) {
159       ConsumeToken();
160       break;
161     }
162     LLVM_FALLTHROUGH;
163   case tok::kw_typeof:
164   case tok::kw___attribute:
165   case tok::kw___underlying_type: {
166     ConsumeToken();
167     if (Tok.isNot(tok::l_paren))
168       return TPResult::Error;
169     ConsumeParen();
170     if (!SkipUntil(tok::r_paren))
171       return TPResult::Error;
172     break;
173   }
174 
175   case tok::kw_class:
176   case tok::kw_struct:
177   case tok::kw_union:
178   case tok::kw___interface:
179   case tok::kw_enum:
180     // elaborated-type-specifier:
181     //     class-key attribute-specifier-seq[opt]
182     //         nested-name-specifier[opt] identifier
183     //     class-key nested-name-specifier[opt] template[opt] simple-template-id
184     //     enum nested-name-specifier[opt] identifier
185     //
186     // FIXME: We don't support class-specifiers nor enum-specifiers here.
187     ConsumeToken();
188 
189     // Skip attributes.
190     while (Tok.isOneOf(tok::l_square, tok::kw___attribute, tok::kw___declspec,
191                        tok::kw_alignas)) {
192       if (Tok.is(tok::l_square)) {
193         ConsumeBracket();
194         if (!SkipUntil(tok::r_square))
195           return TPResult::Error;
196       } else {
197         ConsumeToken();
198         if (Tok.isNot(tok::l_paren))
199           return TPResult::Error;
200         ConsumeParen();
201         if (!SkipUntil(tok::r_paren))
202           return TPResult::Error;
203       }
204     }
205 
206     if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
207                     tok::annot_template_id) &&
208         TryAnnotateCXXScopeToken())
209       return TPResult::Error;
210     if (Tok.is(tok::annot_cxxscope))
211       ConsumeAnnotationToken();
212     if (Tok.is(tok::identifier))
213       ConsumeToken();
214     else if (Tok.is(tok::annot_template_id))
215       ConsumeAnnotationToken();
216     else
217       return TPResult::Error;
218     break;
219 
220   case tok::annot_cxxscope:
221     ConsumeAnnotationToken();
222     LLVM_FALLTHROUGH;
223   default:
224     ConsumeAnyToken();
225 
226     if (getLangOpts().ObjC && Tok.is(tok::less))
227       return TryParseProtocolQualifiers();
228     break;
229   }
230 
231   return TPResult::Ambiguous;
232 }
233 
234 /// simple-declaration:
235 ///   decl-specifier-seq init-declarator-list[opt] ';'
236 ///
237 /// (if AllowForRangeDecl specified)
238 /// for ( for-range-declaration : for-range-initializer ) statement
239 /// for-range-declaration:
240 ///    attribute-specifier-seqopt type-specifier-seq declarator
241 ///
TryParseSimpleDeclaration(bool AllowForRangeDecl)242 Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
243   if (TryConsumeDeclarationSpecifier() == TPResult::Error)
244     return TPResult::Error;
245 
246   // Two decl-specifiers in a row conclusively disambiguate this as being a
247   // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
248   // overwhelmingly common case that the next token is a '('.
249   if (Tok.isNot(tok::l_paren)) {
250     TPResult TPR = isCXXDeclarationSpecifier();
251     if (TPR == TPResult::Ambiguous)
252       return TPResult::True;
253     if (TPR == TPResult::True || TPR == TPResult::Error)
254       return TPR;
255     assert(TPR == TPResult::False);
256   }
257 
258   TPResult TPR = TryParseInitDeclaratorList();
259   if (TPR != TPResult::Ambiguous)
260     return TPR;
261 
262   if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
263     return TPResult::False;
264 
265   return TPResult::Ambiguous;
266 }
267 
268 /// Tentatively parse an init-declarator-list in order to disambiguate it from
269 /// an expression.
270 ///
271 ///       init-declarator-list:
272 ///         init-declarator
273 ///         init-declarator-list ',' init-declarator
274 ///
275 ///       init-declarator:
276 ///         declarator initializer[opt]
277 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
278 ///
279 ///       initializer:
280 ///         brace-or-equal-initializer
281 ///         '(' expression-list ')'
282 ///
283 ///       brace-or-equal-initializer:
284 ///         '=' initializer-clause
285 /// [C++11] braced-init-list
286 ///
287 ///       initializer-clause:
288 ///         assignment-expression
289 ///         braced-init-list
290 ///
291 ///       braced-init-list:
292 ///         '{' initializer-list ','[opt] '}'
293 ///         '{' '}'
294 ///
TryParseInitDeclaratorList()295 Parser::TPResult Parser::TryParseInitDeclaratorList() {
296   while (1) {
297     // declarator
298     TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
299     if (TPR != TPResult::Ambiguous)
300       return TPR;
301 
302     // [GNU] simple-asm-expr[opt] attributes[opt]
303     if (Tok.isOneOf(tok::kw_asm, tok::kw___attribute))
304       return TPResult::True;
305 
306     // initializer[opt]
307     if (Tok.is(tok::l_paren)) {
308       // Parse through the parens.
309       ConsumeParen();
310       if (!SkipUntil(tok::r_paren, StopAtSemi))
311         return TPResult::Error;
312     } else if (Tok.is(tok::l_brace)) {
313       // A left-brace here is sufficient to disambiguate the parse; an
314       // expression can never be followed directly by a braced-init-list.
315       return TPResult::True;
316     } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
317       // MSVC and g++ won't examine the rest of declarators if '=' is
318       // encountered; they just conclude that we have a declaration.
319       // EDG parses the initializer completely, which is the proper behavior
320       // for this case.
321       //
322       // At present, Clang follows MSVC and g++, since the parser does not have
323       // the ability to parse an expression fully without recording the
324       // results of that parse.
325       // FIXME: Handle this case correctly.
326       //
327       // Also allow 'in' after an Objective-C declaration as in:
328       // for (int (^b)(void) in array). Ideally this should be done in the
329       // context of parsing for-init-statement of a foreach statement only. But,
330       // in any other context 'in' is invalid after a declaration and parser
331       // issues the error regardless of outcome of this decision.
332       // FIXME: Change if above assumption does not hold.
333       return TPResult::True;
334     }
335 
336     if (!TryConsumeToken(tok::comma))
337       break;
338   }
339 
340   return TPResult::Ambiguous;
341 }
342 
343 struct Parser::ConditionDeclarationOrInitStatementState {
344   Parser &P;
345   bool CanBeExpression = true;
346   bool CanBeCondition = true;
347   bool CanBeInitStatement;
348   bool CanBeForRangeDecl;
349 
ConditionDeclarationOrInitStatementStateParser::ConditionDeclarationOrInitStatementState350   ConditionDeclarationOrInitStatementState(Parser &P, bool CanBeInitStatement,
351                                            bool CanBeForRangeDecl)
352       : P(P), CanBeInitStatement(CanBeInitStatement),
353         CanBeForRangeDecl(CanBeForRangeDecl) {}
354 
resolvedParser::ConditionDeclarationOrInitStatementState355   bool resolved() {
356     return CanBeExpression + CanBeCondition + CanBeInitStatement +
357                CanBeForRangeDecl < 2;
358   }
359 
markNotExpressionParser::ConditionDeclarationOrInitStatementState360   void markNotExpression() {
361     CanBeExpression = false;
362 
363     if (!resolved()) {
364       // FIXME: Unify the parsing codepaths for condition variables and
365       // simple-declarations so that we don't need to eagerly figure out which
366       // kind we have here. (Just parse init-declarators until we reach a
367       // semicolon or right paren.)
368       RevertingTentativeParsingAction PA(P);
369       if (CanBeForRangeDecl) {
370         // Skip until we hit a ')', ';', or a ':' with no matching '?'.
371         // The final case is a for range declaration, the rest are not.
372         while (true) {
373           unsigned QuestionColonDepth = 0;
374           P.SkipUntil({tok::r_paren, tok::semi, tok::question, tok::colon},
375                       StopBeforeMatch);
376           if (P.Tok.is(tok::question))
377             ++QuestionColonDepth;
378           else if (P.Tok.is(tok::colon)) {
379             if (QuestionColonDepth)
380               --QuestionColonDepth;
381             else {
382               CanBeCondition = CanBeInitStatement = false;
383               return;
384             }
385           } else {
386             CanBeForRangeDecl = false;
387             break;
388           }
389           P.ConsumeToken();
390         }
391       } else {
392         // Just skip until we hit a ')' or ';'.
393         P.SkipUntil(tok::r_paren, tok::semi, StopBeforeMatch);
394       }
395       if (P.Tok.isNot(tok::r_paren))
396         CanBeCondition = CanBeForRangeDecl = false;
397       if (P.Tok.isNot(tok::semi))
398         CanBeInitStatement = false;
399     }
400   }
401 
markNotConditionParser::ConditionDeclarationOrInitStatementState402   bool markNotCondition() {
403     CanBeCondition = false;
404     return resolved();
405   }
406 
markNotForRangeDeclParser::ConditionDeclarationOrInitStatementState407   bool markNotForRangeDecl() {
408     CanBeForRangeDecl = false;
409     return resolved();
410   }
411 
updateParser::ConditionDeclarationOrInitStatementState412   bool update(TPResult IsDecl) {
413     switch (IsDecl) {
414     case TPResult::True:
415       markNotExpression();
416       assert(resolved() && "can't continue after tentative parsing bails out");
417       break;
418     case TPResult::False:
419       CanBeCondition = CanBeInitStatement = CanBeForRangeDecl = false;
420       break;
421     case TPResult::Ambiguous:
422       break;
423     case TPResult::Error:
424       CanBeExpression = CanBeCondition = CanBeInitStatement =
425           CanBeForRangeDecl = false;
426       break;
427     }
428     return resolved();
429   }
430 
resultParser::ConditionDeclarationOrInitStatementState431   ConditionOrInitStatement result() const {
432     assert(CanBeExpression + CanBeCondition + CanBeInitStatement +
433                    CanBeForRangeDecl < 2 &&
434            "result called but not yet resolved");
435     if (CanBeExpression)
436       return ConditionOrInitStatement::Expression;
437     if (CanBeCondition)
438       return ConditionOrInitStatement::ConditionDecl;
439     if (CanBeInitStatement)
440       return ConditionOrInitStatement::InitStmtDecl;
441     if (CanBeForRangeDecl)
442       return ConditionOrInitStatement::ForRangeDecl;
443     return ConditionOrInitStatement::Error;
444   }
445 };
446 
447 /// Disambiguates between a declaration in a condition, a
448 /// simple-declaration in an init-statement, and an expression for
449 /// a condition of a if/switch statement.
450 ///
451 ///       condition:
452 ///         expression
453 ///         type-specifier-seq declarator '=' assignment-expression
454 /// [C++11] type-specifier-seq declarator '=' initializer-clause
455 /// [C++11] type-specifier-seq declarator braced-init-list
456 /// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
457 ///             '=' assignment-expression
458 ///       simple-declaration:
459 ///         decl-specifier-seq init-declarator-list[opt] ';'
460 ///
461 /// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
462 /// to the ';' to disambiguate cases like 'int(x))' (an expression) from
463 /// 'int(x);' (a simple-declaration in an init-statement).
464 Parser::ConditionOrInitStatement
isCXXConditionDeclarationOrInitStatement(bool CanBeInitStatement,bool CanBeForRangeDecl)465 Parser::isCXXConditionDeclarationOrInitStatement(bool CanBeInitStatement,
466                                                  bool CanBeForRangeDecl) {
467   ConditionDeclarationOrInitStatementState State(*this, CanBeInitStatement,
468                                                  CanBeForRangeDecl);
469 
470   if (State.update(isCXXDeclarationSpecifier()))
471     return State.result();
472 
473   // It might be a declaration; we need tentative parsing.
474   RevertingTentativeParsingAction PA(*this);
475 
476   // FIXME: A tag definition unambiguously tells us this is an init-statement.
477   if (State.update(TryConsumeDeclarationSpecifier()))
478     return State.result();
479   assert(Tok.is(tok::l_paren) && "Expected '('");
480 
481   while (true) {
482     // Consume a declarator.
483     if (State.update(TryParseDeclarator(false/*mayBeAbstract*/)))
484       return State.result();
485 
486     // Attributes, asm label, or an initializer imply this is not an expression.
487     // FIXME: Disambiguate properly after an = instead of assuming that it's a
488     // valid declaration.
489     if (Tok.isOneOf(tok::equal, tok::kw_asm, tok::kw___attribute) ||
490         (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) {
491       State.markNotExpression();
492       return State.result();
493     }
494 
495     // A colon here identifies a for-range declaration.
496     if (State.CanBeForRangeDecl && Tok.is(tok::colon))
497       return ConditionOrInitStatement::ForRangeDecl;
498 
499     // At this point, it can't be a condition any more, because a condition
500     // must have a brace-or-equal-initializer.
501     if (State.markNotCondition())
502       return State.result();
503 
504     // Likewise, it can't be a for-range declaration any more.
505     if (State.markNotForRangeDecl())
506       return State.result();
507 
508     // A parenthesized initializer could be part of an expression or a
509     // simple-declaration.
510     if (Tok.is(tok::l_paren)) {
511       ConsumeParen();
512       SkipUntil(tok::r_paren, StopAtSemi);
513     }
514 
515     if (!TryConsumeToken(tok::comma))
516       break;
517   }
518 
519   // We reached the end. If it can now be some kind of decl, then it is.
520   if (State.CanBeCondition && Tok.is(tok::r_paren))
521     return ConditionOrInitStatement::ConditionDecl;
522   else if (State.CanBeInitStatement && Tok.is(tok::semi))
523     return ConditionOrInitStatement::InitStmtDecl;
524   else
525     return ConditionOrInitStatement::Expression;
526 }
527 
528   /// Determine whether the next set of tokens contains a type-id.
529   ///
530   /// The context parameter states what context we're parsing right
531   /// now, which affects how this routine copes with the token
532   /// following the type-id. If the context is TypeIdInParens, we have
533   /// already parsed the '(' and we will cease lookahead when we hit
534   /// the corresponding ')'. If the context is
535   /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
536   /// before this template argument, and will cease lookahead when we
537   /// hit a '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately
538   /// preceding such. Returns true for a type-id and false for an expression.
539   /// If during the disambiguation process a parsing error is encountered,
540   /// the function returns true to let the declaration parsing code handle it.
541   ///
542   /// type-id:
543   ///   type-specifier-seq abstract-declarator[opt]
544   ///
isCXXTypeId(TentativeCXXTypeIdContext Context,bool & isAmbiguous)545 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
546 
547   isAmbiguous = false;
548 
549   // C++ 8.2p2:
550   // The ambiguity arising from the similarity between a function-style cast and
551   // a type-id can occur in different contexts. The ambiguity appears as a
552   // choice between a function-style cast expression and a declaration of a
553   // type. The resolution is that any construct that could possibly be a type-id
554   // in its syntactic context shall be considered a type-id.
555 
556   TPResult TPR = isCXXDeclarationSpecifier();
557   if (TPR != TPResult::Ambiguous)
558     return TPR != TPResult::False; // Returns true for TPResult::True or
559                                      // TPResult::Error.
560 
561   // FIXME: Add statistics about the number of ambiguous statements encountered
562   // and how they were resolved (number of declarations+number of expressions).
563 
564   // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
565   // We need tentative parsing...
566 
567   RevertingTentativeParsingAction PA(*this);
568 
569   // type-specifier-seq
570   TryConsumeDeclarationSpecifier();
571   assert(Tok.is(tok::l_paren) && "Expected '('");
572 
573   // declarator
574   TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
575 
576   // In case of an error, let the declaration parsing code handle it.
577   if (TPR == TPResult::Error)
578     TPR = TPResult::True;
579 
580   if (TPR == TPResult::Ambiguous) {
581     // We are supposed to be inside parens, so if after the abstract declarator
582     // we encounter a ')' this is a type-id, otherwise it's an expression.
583     if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
584       TPR = TPResult::True;
585       isAmbiguous = true;
586 
587     // We are supposed to be inside a template argument, so if after
588     // the abstract declarator we encounter a '>', '>>' (in C++0x), or
589     // ','; or, in C++0x, an ellipsis immediately preceding such, this
590     // is a type-id. Otherwise, it's an expression.
591     } else if (Context == TypeIdAsTemplateArgument &&
592                (Tok.isOneOf(tok::greater, tok::comma) ||
593                 (getLangOpts().CPlusPlus11 &&
594                  (Tok.is(tok::greatergreater) ||
595                   (Tok.is(tok::ellipsis) &&
596                    NextToken().isOneOf(tok::greater, tok::greatergreater,
597                                        tok::comma)))))) {
598       TPR = TPResult::True;
599       isAmbiguous = true;
600 
601     } else
602       TPR = TPResult::False;
603   }
604 
605   assert(TPR == TPResult::True || TPR == TPResult::False);
606   return TPR == TPResult::True;
607 }
608 
609 /// Returns true if this is a C++11 attribute-specifier. Per
610 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
611 /// always introduce an attribute. In Objective-C++11, this rule does not
612 /// apply if either '[' begins a message-send.
613 ///
614 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
615 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
616 ///
617 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
618 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
619 /// is not an Obj-C message send.
620 ///
621 /// C++11 [dcl.attr.grammar]:
622 ///
623 ///     attribute-specifier:
624 ///         '[' '[' attribute-list ']' ']'
625 ///         alignment-specifier
626 ///
627 ///     attribute-list:
628 ///         attribute[opt]
629 ///         attribute-list ',' attribute[opt]
630 ///         attribute '...'
631 ///         attribute-list ',' attribute '...'
632 ///
633 ///     attribute:
634 ///         attribute-token attribute-argument-clause[opt]
635 ///
636 ///     attribute-token:
637 ///         identifier
638 ///         identifier '::' identifier
639 ///
640 ///     attribute-argument-clause:
641 ///         '(' balanced-token-seq ')'
642 Parser::CXX11AttributeKind
isCXX11AttributeSpecifier(bool Disambiguate,bool OuterMightBeMessageSend)643 Parser::isCXX11AttributeSpecifier(bool Disambiguate,
644                                   bool OuterMightBeMessageSend) {
645   if (Tok.is(tok::kw_alignas))
646     return CAK_AttributeSpecifier;
647 
648   if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
649     return CAK_NotAttributeSpecifier;
650 
651   // No tentative parsing if we don't need to look for ']]' or a lambda.
652   if (!Disambiguate && !getLangOpts().ObjC)
653     return CAK_AttributeSpecifier;
654 
655   RevertingTentativeParsingAction PA(*this);
656 
657   // Opening brackets were checked for above.
658   ConsumeBracket();
659 
660   // Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
661   if (!getLangOpts().ObjC) {
662     ConsumeBracket();
663 
664     bool IsAttribute = SkipUntil(tok::r_square);
665     IsAttribute &= Tok.is(tok::r_square);
666 
667     return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
668   }
669 
670   // In Obj-C++11, we need to distinguish four situations:
671   //  1a) int x[[attr]];                     C++11 attribute.
672   //  1b) [[attr]];                          C++11 statement attribute.
673   //   2) int x[[obj](){ return 1; }()];     Lambda in array size/index.
674   //  3a) int x[[obj get]];                  Message send in array size/index.
675   //  3b) [[Class alloc] init];              Message send in message send.
676   //   4) [[obj]{ return self; }() doStuff]; Lambda in message send.
677   // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
678 
679   // If we have a lambda-introducer, then this is definitely not a message send.
680   // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
681   // into the tentative attribute parse below.
682   LambdaIntroducer Intro;
683   if (!TryParseLambdaIntroducer(Intro)) {
684     // A lambda cannot end with ']]', and an attribute must.
685     bool IsAttribute = Tok.is(tok::r_square);
686 
687     if (IsAttribute)
688       // Case 1: C++11 attribute.
689       return CAK_AttributeSpecifier;
690 
691     if (OuterMightBeMessageSend)
692       // Case 4: Lambda in message send.
693       return CAK_NotAttributeSpecifier;
694 
695     // Case 2: Lambda in array size / index.
696     return CAK_InvalidAttributeSpecifier;
697   }
698 
699   ConsumeBracket();
700 
701   // If we don't have a lambda-introducer, then we have an attribute or a
702   // message-send.
703   bool IsAttribute = true;
704   while (Tok.isNot(tok::r_square)) {
705     if (Tok.is(tok::comma)) {
706       // Case 1: Stray commas can only occur in attributes.
707       return CAK_AttributeSpecifier;
708     }
709 
710     // Parse the attribute-token, if present.
711     // C++11 [dcl.attr.grammar]:
712     //   If a keyword or an alternative token that satisfies the syntactic
713     //   requirements of an identifier is contained in an attribute-token,
714     //   it is considered an identifier.
715     SourceLocation Loc;
716     if (!TryParseCXX11AttributeIdentifier(Loc)) {
717       IsAttribute = false;
718       break;
719     }
720     if (Tok.is(tok::coloncolon)) {
721       ConsumeToken();
722       if (!TryParseCXX11AttributeIdentifier(Loc)) {
723         IsAttribute = false;
724         break;
725       }
726     }
727 
728     // Parse the attribute-argument-clause, if present.
729     if (Tok.is(tok::l_paren)) {
730       ConsumeParen();
731       if (!SkipUntil(tok::r_paren)) {
732         IsAttribute = false;
733         break;
734       }
735     }
736 
737     TryConsumeToken(tok::ellipsis);
738 
739     if (!TryConsumeToken(tok::comma))
740       break;
741   }
742 
743   // An attribute must end ']]'.
744   if (IsAttribute) {
745     if (Tok.is(tok::r_square)) {
746       ConsumeBracket();
747       IsAttribute = Tok.is(tok::r_square);
748     } else {
749       IsAttribute = false;
750     }
751   }
752 
753   if (IsAttribute)
754     // Case 1: C++11 statement attribute.
755     return CAK_AttributeSpecifier;
756 
757   // Case 3: Message send.
758   return CAK_NotAttributeSpecifier;
759 }
760 
TryParsePtrOperatorSeq()761 Parser::TPResult Parser::TryParsePtrOperatorSeq() {
762   while (true) {
763     if (Tok.isOneOf(tok::coloncolon, tok::identifier))
764       if (TryAnnotateCXXScopeToken(true))
765         return TPResult::Error;
766 
767     if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) ||
768         (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
769       // ptr-operator
770       ConsumeAnyToken();
771       while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict,
772                          tok::kw__Nonnull, tok::kw__Nullable,
773                          tok::kw__Null_unspecified))
774         ConsumeToken();
775     } else {
776       return TPResult::True;
777     }
778   }
779 }
780 
781 ///         operator-function-id:
782 ///           'operator' operator
783 ///
784 ///         operator: one of
785 ///           new  delete  new[]  delete[]  +  -  *  /  %  ^  [...]
786 ///
787 ///         conversion-function-id:
788 ///           'operator' conversion-type-id
789 ///
790 ///         conversion-type-id:
791 ///           type-specifier-seq conversion-declarator[opt]
792 ///
793 ///         conversion-declarator:
794 ///           ptr-operator conversion-declarator[opt]
795 ///
796 ///         literal-operator-id:
797 ///           'operator' string-literal identifier
798 ///           'operator' user-defined-string-literal
TryParseOperatorId()799 Parser::TPResult Parser::TryParseOperatorId() {
800   assert(Tok.is(tok::kw_operator));
801   ConsumeToken();
802 
803   // Maybe this is an operator-function-id.
804   switch (Tok.getKind()) {
805   case tok::kw_new: case tok::kw_delete:
806     ConsumeToken();
807     if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
808       ConsumeBracket();
809       ConsumeBracket();
810     }
811     return TPResult::True;
812 
813 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
814   case tok::Token:
815 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
816 #include "clang/Basic/OperatorKinds.def"
817     ConsumeToken();
818     return TPResult::True;
819 
820   case tok::l_square:
821     if (NextToken().is(tok::r_square)) {
822       ConsumeBracket();
823       ConsumeBracket();
824       return TPResult::True;
825     }
826     break;
827 
828   case tok::l_paren:
829     if (NextToken().is(tok::r_paren)) {
830       ConsumeParen();
831       ConsumeParen();
832       return TPResult::True;
833     }
834     break;
835 
836   default:
837     break;
838   }
839 
840   // Maybe this is a literal-operator-id.
841   if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
842     bool FoundUDSuffix = false;
843     do {
844       FoundUDSuffix |= Tok.hasUDSuffix();
845       ConsumeStringToken();
846     } while (isTokenStringLiteral());
847 
848     if (!FoundUDSuffix) {
849       if (Tok.is(tok::identifier))
850         ConsumeToken();
851       else
852         return TPResult::Error;
853     }
854     return TPResult::True;
855   }
856 
857   // Maybe this is a conversion-function-id.
858   bool AnyDeclSpecifiers = false;
859   while (true) {
860     TPResult TPR = isCXXDeclarationSpecifier();
861     if (TPR == TPResult::Error)
862       return TPR;
863     if (TPR == TPResult::False) {
864       if (!AnyDeclSpecifiers)
865         return TPResult::Error;
866       break;
867     }
868     if (TryConsumeDeclarationSpecifier() == TPResult::Error)
869       return TPResult::Error;
870     AnyDeclSpecifiers = true;
871   }
872   return TryParsePtrOperatorSeq();
873 }
874 
875 ///         declarator:
876 ///           direct-declarator
877 ///           ptr-operator declarator
878 ///
879 ///         direct-declarator:
880 ///           declarator-id
881 ///           direct-declarator '(' parameter-declaration-clause ')'
882 ///                 cv-qualifier-seq[opt] exception-specification[opt]
883 ///           direct-declarator '[' constant-expression[opt] ']'
884 ///           '(' declarator ')'
885 /// [GNU]     '(' attributes declarator ')'
886 ///
887 ///         abstract-declarator:
888 ///           ptr-operator abstract-declarator[opt]
889 ///           direct-abstract-declarator
890 ///
891 ///         direct-abstract-declarator:
892 ///           direct-abstract-declarator[opt]
893 ///                 '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
894 ///                 exception-specification[opt]
895 ///           direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
896 ///           '(' abstract-declarator ')'
897 /// [C++0x]   ...
898 ///
899 ///         ptr-operator:
900 ///           '*' cv-qualifier-seq[opt]
901 ///           '&'
902 /// [C++0x]   '&&'                                                        [TODO]
903 ///           '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
904 ///
905 ///         cv-qualifier-seq:
906 ///           cv-qualifier cv-qualifier-seq[opt]
907 ///
908 ///         cv-qualifier:
909 ///           'const'
910 ///           'volatile'
911 ///
912 ///         declarator-id:
913 ///           '...'[opt] id-expression
914 ///
915 ///         id-expression:
916 ///           unqualified-id
917 ///           qualified-id                                                [TODO]
918 ///
919 ///         unqualified-id:
920 ///           identifier
921 ///           operator-function-id
922 ///           conversion-function-id
923 ///           literal-operator-id
924 ///           '~' class-name                                              [TODO]
925 ///           '~' decltype-specifier                                      [TODO]
926 ///           template-id                                                 [TODO]
927 ///
TryParseDeclarator(bool mayBeAbstract,bool mayHaveIdentifier,bool mayHaveDirectInit)928 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
929                                             bool mayHaveIdentifier,
930                                             bool mayHaveDirectInit) {
931   // declarator:
932   //   direct-declarator
933   //   ptr-operator declarator
934   if (TryParsePtrOperatorSeq() == TPResult::Error)
935     return TPResult::Error;
936 
937   // direct-declarator:
938   // direct-abstract-declarator:
939   if (Tok.is(tok::ellipsis))
940     ConsumeToken();
941 
942   if ((Tok.isOneOf(tok::identifier, tok::kw_operator) ||
943        (Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) ||
944                                         NextToken().is(tok::kw_operator)))) &&
945       mayHaveIdentifier) {
946     // declarator-id
947     if (Tok.is(tok::annot_cxxscope))
948       ConsumeAnnotationToken();
949     else if (Tok.is(tok::identifier))
950       TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
951     if (Tok.is(tok::kw_operator)) {
952       if (TryParseOperatorId() == TPResult::Error)
953         return TPResult::Error;
954     } else
955       ConsumeToken();
956   } else if (Tok.is(tok::l_paren)) {
957     ConsumeParen();
958     if (mayBeAbstract &&
959         (Tok.is(tok::r_paren) ||       // 'int()' is a function.
960          // 'int(...)' is a function.
961          (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
962          isDeclarationSpecifier())) {   // 'int(int)' is a function.
963       // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
964       //        exception-specification[opt]
965       TPResult TPR = TryParseFunctionDeclarator();
966       if (TPR != TPResult::Ambiguous)
967         return TPR;
968     } else {
969       // '(' declarator ')'
970       // '(' attributes declarator ')'
971       // '(' abstract-declarator ')'
972       if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec, tok::kw___cdecl,
973                       tok::kw___stdcall, tok::kw___fastcall, tok::kw___thiscall,
974                       tok::kw___regcall, tok::kw___vectorcall))
975         return TPResult::True; // attributes indicate declaration
976       TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
977       if (TPR != TPResult::Ambiguous)
978         return TPR;
979       if (Tok.isNot(tok::r_paren))
980         return TPResult::False;
981       ConsumeParen();
982     }
983   } else if (!mayBeAbstract) {
984     return TPResult::False;
985   }
986 
987   if (mayHaveDirectInit)
988     return TPResult::Ambiguous;
989 
990   while (1) {
991     TPResult TPR(TPResult::Ambiguous);
992 
993     if (Tok.is(tok::l_paren)) {
994       // Check whether we have a function declarator or a possible ctor-style
995       // initializer that follows the declarator. Note that ctor-style
996       // initializers are not possible in contexts where abstract declarators
997       // are allowed.
998       if (!mayBeAbstract && !isCXXFunctionDeclarator())
999         break;
1000 
1001       // direct-declarator '(' parameter-declaration-clause ')'
1002       //        cv-qualifier-seq[opt] exception-specification[opt]
1003       ConsumeParen();
1004       TPR = TryParseFunctionDeclarator();
1005     } else if (Tok.is(tok::l_square)) {
1006       // direct-declarator '[' constant-expression[opt] ']'
1007       // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
1008       TPR = TryParseBracketDeclarator();
1009     } else {
1010       break;
1011     }
1012 
1013     if (TPR != TPResult::Ambiguous)
1014       return TPR;
1015   }
1016 
1017   return TPResult::Ambiguous;
1018 }
1019 
1020 Parser::TPResult
isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind)1021 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
1022   switch (Kind) {
1023   // Obviously starts an expression.
1024   case tok::numeric_constant:
1025   case tok::char_constant:
1026   case tok::wide_char_constant:
1027   case tok::utf8_char_constant:
1028   case tok::utf16_char_constant:
1029   case tok::utf32_char_constant:
1030   case tok::string_literal:
1031   case tok::wide_string_literal:
1032   case tok::utf8_string_literal:
1033   case tok::utf16_string_literal:
1034   case tok::utf32_string_literal:
1035   case tok::l_square:
1036   case tok::l_paren:
1037   case tok::amp:
1038   case tok::ampamp:
1039   case tok::star:
1040   case tok::plus:
1041   case tok::plusplus:
1042   case tok::minus:
1043   case tok::minusminus:
1044   case tok::tilde:
1045   case tok::exclaim:
1046   case tok::kw_sizeof:
1047   case tok::kw___func__:
1048   case tok::kw_const_cast:
1049   case tok::kw_delete:
1050   case tok::kw_dynamic_cast:
1051   case tok::kw_false:
1052   case tok::kw_new:
1053   case tok::kw_operator:
1054   case tok::kw_reinterpret_cast:
1055   case tok::kw_static_cast:
1056   case tok::kw_this:
1057   case tok::kw_throw:
1058   case tok::kw_true:
1059   case tok::kw_typeid:
1060   case tok::kw_alignof:
1061   case tok::kw_noexcept:
1062   case tok::kw_nullptr:
1063   case tok::kw__Alignof:
1064   case tok::kw___null:
1065   case tok::kw___alignof:
1066   case tok::kw___builtin_choose_expr:
1067   case tok::kw___builtin_offsetof:
1068   case tok::kw___builtin_va_arg:
1069   case tok::kw___imag:
1070   case tok::kw___real:
1071   case tok::kw___FUNCTION__:
1072   case tok::kw___FUNCDNAME__:
1073   case tok::kw___FUNCSIG__:
1074   case tok::kw_L__FUNCTION__:
1075   case tok::kw_L__FUNCSIG__:
1076   case tok::kw___PRETTY_FUNCTION__:
1077   case tok::kw___uuidof:
1078 #define TYPE_TRAIT(N,Spelling,K) \
1079   case tok::kw_##Spelling:
1080 #include "clang/Basic/TokenKinds.def"
1081     return TPResult::True;
1082 
1083   // Obviously starts a type-specifier-seq:
1084   case tok::kw_char:
1085   case tok::kw_const:
1086   case tok::kw_double:
1087   case tok::kw__Float16:
1088   case tok::kw___float128:
1089   case tok::kw_enum:
1090   case tok::kw_half:
1091   case tok::kw_float:
1092   case tok::kw_int:
1093   case tok::kw_long:
1094   case tok::kw___int64:
1095   case tok::kw___int128:
1096   case tok::kw_restrict:
1097   case tok::kw_short:
1098   case tok::kw_signed:
1099   case tok::kw_struct:
1100   case tok::kw_union:
1101   case tok::kw_unsigned:
1102   case tok::kw_void:
1103   case tok::kw_volatile:
1104   case tok::kw__Bool:
1105   case tok::kw__Complex:
1106   case tok::kw_class:
1107   case tok::kw_typename:
1108   case tok::kw_wchar_t:
1109   case tok::kw_char8_t:
1110   case tok::kw_char16_t:
1111   case tok::kw_char32_t:
1112   case tok::kw__Decimal32:
1113   case tok::kw__Decimal64:
1114   case tok::kw__Decimal128:
1115   case tok::kw___interface:
1116   case tok::kw___thread:
1117   case tok::kw_thread_local:
1118   case tok::kw__Thread_local:
1119   case tok::kw_typeof:
1120   case tok::kw___underlying_type:
1121   case tok::kw___cdecl:
1122   case tok::kw___stdcall:
1123   case tok::kw___fastcall:
1124   case tok::kw___thiscall:
1125   case tok::kw___regcall:
1126   case tok::kw___vectorcall:
1127   case tok::kw___unaligned:
1128   case tok::kw___vector:
1129   case tok::kw___pixel:
1130   case tok::kw___bool:
1131   case tok::kw__Atomic:
1132 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1133 #include "clang/Basic/OpenCLImageTypes.def"
1134   case tok::kw___unknown_anytype:
1135     return TPResult::False;
1136 
1137   default:
1138     break;
1139   }
1140 
1141   return TPResult::Ambiguous;
1142 }
1143 
isTentativelyDeclared(IdentifierInfo * II)1144 bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
1145   return std::find(TentativelyDeclaredIdentifiers.begin(),
1146                    TentativelyDeclaredIdentifiers.end(), II)
1147       != TentativelyDeclaredIdentifiers.end();
1148 }
1149 
1150 namespace {
1151 class TentativeParseCCC : public CorrectionCandidateCallback {
1152 public:
TentativeParseCCC(const Token & Next)1153   TentativeParseCCC(const Token &Next) {
1154     WantRemainingKeywords = false;
1155     WantTypeSpecifiers = Next.isOneOf(tok::l_paren, tok::r_paren, tok::greater,
1156                                       tok::l_brace, tok::identifier);
1157   }
1158 
ValidateCandidate(const TypoCorrection & Candidate)1159   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1160     // Reject any candidate that only resolves to instance members since they
1161     // aren't viable as standalone identifiers instead of member references.
1162     if (Candidate.isResolved() && !Candidate.isKeyword() &&
1163         llvm::all_of(Candidate,
1164                      [](NamedDecl *ND) { return ND->isCXXInstanceMember(); }))
1165       return false;
1166 
1167     return CorrectionCandidateCallback::ValidateCandidate(Candidate);
1168   }
1169 };
1170 }
1171 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
1172 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
1173 /// be either a decl-specifier or a function-style cast, and TPResult::Error
1174 /// if a parsing error was found and reported.
1175 ///
1176 /// If HasMissingTypename is provided, a name with a dependent scope specifier
1177 /// will be treated as ambiguous if the 'typename' keyword is missing. If this
1178 /// happens, *HasMissingTypename will be set to 'true'. This will also be used
1179 /// as an indicator that undeclared identifiers (which will trigger a later
1180 /// parse error) should be treated as types. Returns TPResult::Ambiguous in
1181 /// such cases.
1182 ///
1183 ///         decl-specifier:
1184 ///           storage-class-specifier
1185 ///           type-specifier
1186 ///           function-specifier
1187 ///           'friend'
1188 ///           'typedef'
1189 /// [C++11]   'constexpr'
1190 /// [GNU]     attributes declaration-specifiers[opt]
1191 ///
1192 ///         storage-class-specifier:
1193 ///           'register'
1194 ///           'static'
1195 ///           'extern'
1196 ///           'mutable'
1197 ///           'auto'
1198 /// [GNU]     '__thread'
1199 /// [C++11]   'thread_local'
1200 /// [C11]     '_Thread_local'
1201 ///
1202 ///         function-specifier:
1203 ///           'inline'
1204 ///           'virtual'
1205 ///           'explicit'
1206 ///
1207 ///         typedef-name:
1208 ///           identifier
1209 ///
1210 ///         type-specifier:
1211 ///           simple-type-specifier
1212 ///           class-specifier
1213 ///           enum-specifier
1214 ///           elaborated-type-specifier
1215 ///           typename-specifier
1216 ///           cv-qualifier
1217 ///
1218 ///         simple-type-specifier:
1219 ///           '::'[opt] nested-name-specifier[opt] type-name
1220 ///           '::'[opt] nested-name-specifier 'template'
1221 ///                 simple-template-id                              [TODO]
1222 ///           'char'
1223 ///           'wchar_t'
1224 ///           'bool'
1225 ///           'short'
1226 ///           'int'
1227 ///           'long'
1228 ///           'signed'
1229 ///           'unsigned'
1230 ///           'float'
1231 ///           'double'
1232 ///           'void'
1233 /// [GNU]     typeof-specifier
1234 /// [GNU]     '_Complex'
1235 /// [C++11]   'auto'
1236 /// [GNU]     '__auto_type'
1237 /// [C++11]   'decltype' ( expression )
1238 /// [C++1y]   'decltype' ( 'auto' )
1239 ///
1240 ///         type-name:
1241 ///           class-name
1242 ///           enum-name
1243 ///           typedef-name
1244 ///
1245 ///         elaborated-type-specifier:
1246 ///           class-key '::'[opt] nested-name-specifier[opt] identifier
1247 ///           class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
1248 ///               simple-template-id
1249 ///           'enum' '::'[opt] nested-name-specifier[opt] identifier
1250 ///
1251 ///         enum-name:
1252 ///           identifier
1253 ///
1254 ///         enum-specifier:
1255 ///           'enum' identifier[opt] '{' enumerator-list[opt] '}'
1256 ///           'enum' identifier[opt] '{' enumerator-list ',' '}'
1257 ///
1258 ///         class-specifier:
1259 ///           class-head '{' member-specification[opt] '}'
1260 ///
1261 ///         class-head:
1262 ///           class-key identifier[opt] base-clause[opt]
1263 ///           class-key nested-name-specifier identifier base-clause[opt]
1264 ///           class-key nested-name-specifier[opt] simple-template-id
1265 ///               base-clause[opt]
1266 ///
1267 ///         class-key:
1268 ///           'class'
1269 ///           'struct'
1270 ///           'union'
1271 ///
1272 ///         cv-qualifier:
1273 ///           'const'
1274 ///           'volatile'
1275 /// [GNU]     restrict
1276 ///
1277 Parser::TPResult
isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,bool * HasMissingTypename)1278 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
1279                                   bool *HasMissingTypename) {
1280   switch (Tok.getKind()) {
1281   case tok::identifier: {
1282     // Check for need to substitute AltiVec __vector keyword
1283     // for "vector" identifier.
1284     if (TryAltiVecVectorToken())
1285       return TPResult::True;
1286 
1287     const Token &Next = NextToken();
1288     // In 'foo bar', 'foo' is always a type name outside of Objective-C.
1289     if (!getLangOpts().ObjC && Next.is(tok::identifier))
1290       return TPResult::True;
1291 
1292     if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
1293       // Determine whether this is a valid expression. If not, we will hit
1294       // a parse error one way or another. In that case, tell the caller that
1295       // this is ambiguous. Typo-correct to type and expression keywords and
1296       // to types and identifiers, in order to try to recover from errors.
1297       switch (TryAnnotateName(false /* no nested name specifier */,
1298                               llvm::make_unique<TentativeParseCCC>(Next))) {
1299       case ANK_Error:
1300         return TPResult::Error;
1301       case ANK_TentativeDecl:
1302         return TPResult::False;
1303       case ANK_TemplateName:
1304         // In C++17, this could be a type template for class template argument
1305         // deduction. Try to form a type annotation for it. If we're in a
1306         // template template argument, we'll undo this when checking the
1307         // validity of the argument.
1308         if (getLangOpts().CPlusPlus17) {
1309           if (TryAnnotateTypeOrScopeToken())
1310             return TPResult::Error;
1311           if (Tok.isNot(tok::identifier))
1312             break;
1313         }
1314 
1315         // A bare type template-name which can't be a template template
1316         // argument is an error, and was probably intended to be a type.
1317         return GreaterThanIsOperator ? TPResult::True : TPResult::False;
1318       case ANK_Unresolved:
1319         return HasMissingTypename ? TPResult::Ambiguous : TPResult::False;
1320       case ANK_Success:
1321         break;
1322       }
1323       assert(Tok.isNot(tok::identifier) &&
1324              "TryAnnotateName succeeded without producing an annotation");
1325     } else {
1326       // This might possibly be a type with a dependent scope specifier and
1327       // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1328       // since it will annotate as a primary expression, and we want to use the
1329       // "missing 'typename'" logic.
1330       if (TryAnnotateTypeOrScopeToken())
1331         return TPResult::Error;
1332       // If annotation failed, assume it's a non-type.
1333       // FIXME: If this happens due to an undeclared identifier, treat it as
1334       // ambiguous.
1335       if (Tok.is(tok::identifier))
1336         return TPResult::False;
1337     }
1338 
1339     // We annotated this token as something. Recurse to handle whatever we got.
1340     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1341   }
1342 
1343   case tok::kw_typename:  // typename T::type
1344     // Annotate typenames and C++ scope specifiers.  If we get one, just
1345     // recurse to handle whatever we get.
1346     if (TryAnnotateTypeOrScopeToken())
1347       return TPResult::Error;
1348     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1349 
1350   case tok::coloncolon: {    // ::foo::bar
1351     const Token &Next = NextToken();
1352     if (Next.isOneOf(tok::kw_new,       // ::new
1353                      tok::kw_delete))   // ::delete
1354       return TPResult::False;
1355     LLVM_FALLTHROUGH;
1356   }
1357   case tok::kw___super:
1358   case tok::kw_decltype:
1359     // Annotate typenames and C++ scope specifiers.  If we get one, just
1360     // recurse to handle whatever we get.
1361     if (TryAnnotateTypeOrScopeToken())
1362       return TPResult::Error;
1363     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1364 
1365     // decl-specifier:
1366     //   storage-class-specifier
1367     //   type-specifier
1368     //   function-specifier
1369     //   'friend'
1370     //   'typedef'
1371     //   'constexpr'
1372   case tok::kw_friend:
1373   case tok::kw_typedef:
1374   case tok::kw_constexpr:
1375     // storage-class-specifier
1376   case tok::kw_register:
1377   case tok::kw_static:
1378   case tok::kw_extern:
1379   case tok::kw_mutable:
1380   case tok::kw_auto:
1381   case tok::kw___thread:
1382   case tok::kw_thread_local:
1383   case tok::kw__Thread_local:
1384     // function-specifier
1385   case tok::kw_inline:
1386   case tok::kw_virtual:
1387   case tok::kw_explicit:
1388 
1389     // Modules
1390   case tok::kw___module_private__:
1391 
1392     // Debugger support
1393   case tok::kw___unknown_anytype:
1394 
1395     // type-specifier:
1396     //   simple-type-specifier
1397     //   class-specifier
1398     //   enum-specifier
1399     //   elaborated-type-specifier
1400     //   typename-specifier
1401     //   cv-qualifier
1402 
1403     // class-specifier
1404     // elaborated-type-specifier
1405   case tok::kw_class:
1406   case tok::kw_struct:
1407   case tok::kw_union:
1408   case tok::kw___interface:
1409     // enum-specifier
1410   case tok::kw_enum:
1411     // cv-qualifier
1412   case tok::kw_const:
1413   case tok::kw_volatile:
1414   case tok::kw___private:
1415   case tok::kw___local:
1416   case tok::kw___global:
1417   case tok::kw___constant:
1418   case tok::kw___generic:
1419 
1420     // GNU
1421   case tok::kw_restrict:
1422   case tok::kw__Complex:
1423   case tok::kw___attribute:
1424   case tok::kw___auto_type:
1425     return TPResult::True;
1426 
1427     // Microsoft
1428   case tok::kw___declspec:
1429   case tok::kw___cdecl:
1430   case tok::kw___stdcall:
1431   case tok::kw___fastcall:
1432   case tok::kw___thiscall:
1433   case tok::kw___regcall:
1434   case tok::kw___vectorcall:
1435   case tok::kw___w64:
1436   case tok::kw___sptr:
1437   case tok::kw___uptr:
1438   case tok::kw___ptr64:
1439   case tok::kw___ptr32:
1440   case tok::kw___forceinline:
1441   case tok::kw___unaligned:
1442   case tok::kw__Nonnull:
1443   case tok::kw__Nullable:
1444   case tok::kw__Null_unspecified:
1445   case tok::kw___kindof:
1446     return TPResult::True;
1447 
1448     // Borland
1449   case tok::kw___pascal:
1450     return TPResult::True;
1451 
1452     // AltiVec
1453   case tok::kw___vector:
1454     return TPResult::True;
1455 
1456   case tok::annot_template_id: {
1457     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1458     if (TemplateId->Kind != TNK_Type_template)
1459       return TPResult::False;
1460     CXXScopeSpec SS;
1461     AnnotateTemplateIdTokenAsType();
1462     assert(Tok.is(tok::annot_typename));
1463     goto case_typename;
1464   }
1465 
1466   case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1467     // We've already annotated a scope; try to annotate a type.
1468     if (TryAnnotateTypeOrScopeToken())
1469       return TPResult::Error;
1470     if (!Tok.is(tok::annot_typename)) {
1471       // If the next token is an identifier or a type qualifier, then this
1472       // can't possibly be a valid expression either.
1473       if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1474         CXXScopeSpec SS;
1475         Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1476                                                      Tok.getAnnotationRange(),
1477                                                      SS);
1478         if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
1479           RevertingTentativeParsingAction PA(*this);
1480           ConsumeAnnotationToken();
1481           ConsumeToken();
1482           bool isIdentifier = Tok.is(tok::identifier);
1483           TPResult TPR = TPResult::False;
1484           if (!isIdentifier)
1485             TPR = isCXXDeclarationSpecifier(BracedCastResult,
1486                                             HasMissingTypename);
1487 
1488           if (isIdentifier ||
1489               TPR == TPResult::True || TPR == TPResult::Error)
1490             return TPResult::Error;
1491 
1492           if (HasMissingTypename) {
1493             // We can't tell whether this is a missing 'typename' or a valid
1494             // expression.
1495             *HasMissingTypename = true;
1496             return TPResult::Ambiguous;
1497           }
1498         } else {
1499           // Try to resolve the name. If it doesn't exist, assume it was
1500           // intended to name a type and keep disambiguating.
1501           switch (TryAnnotateName(false /* SS is not dependent */)) {
1502           case ANK_Error:
1503             return TPResult::Error;
1504           case ANK_TentativeDecl:
1505             return TPResult::False;
1506           case ANK_TemplateName:
1507             // In C++17, this could be a type template for class template
1508             // argument deduction.
1509             if (getLangOpts().CPlusPlus17) {
1510               if (TryAnnotateTypeOrScopeToken())
1511                 return TPResult::Error;
1512               if (Tok.isNot(tok::identifier))
1513                 break;
1514             }
1515 
1516             // A bare type template-name which can't be a template template
1517             // argument is an error, and was probably intended to be a type.
1518             // In C++17, this could be class template argument deduction.
1519             return (getLangOpts().CPlusPlus17 || GreaterThanIsOperator)
1520                        ? TPResult::True
1521                        : TPResult::False;
1522           case ANK_Unresolved:
1523             return HasMissingTypename ? TPResult::Ambiguous
1524                                       : TPResult::False;
1525           case ANK_Success:
1526             break;
1527           }
1528 
1529           // Annotated it, check again.
1530           assert(Tok.isNot(tok::annot_cxxscope) ||
1531                  NextToken().isNot(tok::identifier));
1532           return isCXXDeclarationSpecifier(BracedCastResult,
1533                                            HasMissingTypename);
1534         }
1535       }
1536       return TPResult::False;
1537     }
1538     // If that succeeded, fallthrough into the generic simple-type-id case.
1539     LLVM_FALLTHROUGH;
1540 
1541     // The ambiguity resides in a simple-type-specifier/typename-specifier
1542     // followed by a '('. The '(' could either be the start of:
1543     //
1544     //   direct-declarator:
1545     //     '(' declarator ')'
1546     //
1547     //   direct-abstract-declarator:
1548     //     '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1549     //              exception-specification[opt]
1550     //     '(' abstract-declarator ')'
1551     //
1552     // or part of a function-style cast expression:
1553     //
1554     //     simple-type-specifier '(' expression-list[opt] ')'
1555     //
1556 
1557     // simple-type-specifier:
1558 
1559   case tok::annot_typename:
1560   case_typename:
1561     // In Objective-C, we might have a protocol-qualified type.
1562     if (getLangOpts().ObjC && NextToken().is(tok::less)) {
1563       // Tentatively parse the protocol qualifiers.
1564       RevertingTentativeParsingAction PA(*this);
1565       ConsumeAnyToken(); // The type token
1566 
1567       TPResult TPR = TryParseProtocolQualifiers();
1568       bool isFollowedByParen = Tok.is(tok::l_paren);
1569       bool isFollowedByBrace = Tok.is(tok::l_brace);
1570 
1571       if (TPR == TPResult::Error)
1572         return TPResult::Error;
1573 
1574       if (isFollowedByParen)
1575         return TPResult::Ambiguous;
1576 
1577       if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1578         return BracedCastResult;
1579 
1580       return TPResult::True;
1581     }
1582     LLVM_FALLTHROUGH;
1583 
1584   case tok::kw_char:
1585   case tok::kw_wchar_t:
1586   case tok::kw_char8_t:
1587   case tok::kw_char16_t:
1588   case tok::kw_char32_t:
1589   case tok::kw_bool:
1590   case tok::kw_short:
1591   case tok::kw_int:
1592   case tok::kw_long:
1593   case tok::kw___int64:
1594   case tok::kw___int128:
1595   case tok::kw_signed:
1596   case tok::kw_unsigned:
1597   case tok::kw_half:
1598   case tok::kw_float:
1599   case tok::kw_double:
1600   case tok::kw__Float16:
1601   case tok::kw___float128:
1602   case tok::kw_void:
1603   case tok::annot_decltype:
1604     if (NextToken().is(tok::l_paren))
1605       return TPResult::Ambiguous;
1606 
1607     // This is a function-style cast in all cases we disambiguate other than
1608     // one:
1609     //   struct S {
1610     //     enum E : int { a = 4 }; // enum
1611     //     enum E : int { 4 };     // bit-field
1612     //   };
1613     if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
1614       return BracedCastResult;
1615 
1616     if (isStartOfObjCClassMessageMissingOpenBracket())
1617       return TPResult::False;
1618 
1619     return TPResult::True;
1620 
1621   // GNU typeof support.
1622   case tok::kw_typeof: {
1623     if (NextToken().isNot(tok::l_paren))
1624       return TPResult::True;
1625 
1626     RevertingTentativeParsingAction PA(*this);
1627 
1628     TPResult TPR = TryParseTypeofSpecifier();
1629     bool isFollowedByParen = Tok.is(tok::l_paren);
1630     bool isFollowedByBrace = Tok.is(tok::l_brace);
1631 
1632     if (TPR == TPResult::Error)
1633       return TPResult::Error;
1634 
1635     if (isFollowedByParen)
1636       return TPResult::Ambiguous;
1637 
1638     if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1639       return BracedCastResult;
1640 
1641     return TPResult::True;
1642   }
1643 
1644   // C++0x type traits support
1645   case tok::kw___underlying_type:
1646     return TPResult::True;
1647 
1648   // C11 _Atomic
1649   case tok::kw__Atomic:
1650     return TPResult::True;
1651 
1652   default:
1653     return TPResult::False;
1654   }
1655 }
1656 
isCXXDeclarationSpecifierAType()1657 bool Parser::isCXXDeclarationSpecifierAType() {
1658   switch (Tok.getKind()) {
1659     // typename-specifier
1660   case tok::annot_decltype:
1661   case tok::annot_template_id:
1662   case tok::annot_typename:
1663   case tok::kw_typeof:
1664   case tok::kw___underlying_type:
1665     return true;
1666 
1667     // elaborated-type-specifier
1668   case tok::kw_class:
1669   case tok::kw_struct:
1670   case tok::kw_union:
1671   case tok::kw___interface:
1672   case tok::kw_enum:
1673     return true;
1674 
1675     // simple-type-specifier
1676   case tok::kw_char:
1677   case tok::kw_wchar_t:
1678   case tok::kw_char8_t:
1679   case tok::kw_char16_t:
1680   case tok::kw_char32_t:
1681   case tok::kw_bool:
1682   case tok::kw_short:
1683   case tok::kw_int:
1684   case tok::kw_long:
1685   case tok::kw___int64:
1686   case tok::kw___int128:
1687   case tok::kw_signed:
1688   case tok::kw_unsigned:
1689   case tok::kw_half:
1690   case tok::kw_float:
1691   case tok::kw_double:
1692   case tok::kw__Float16:
1693   case tok::kw___float128:
1694   case tok::kw_void:
1695   case tok::kw___unknown_anytype:
1696   case tok::kw___auto_type:
1697     return true;
1698 
1699   case tok::kw_auto:
1700     return getLangOpts().CPlusPlus11;
1701 
1702   case tok::kw__Atomic:
1703     // "_Atomic foo"
1704     return NextToken().is(tok::l_paren);
1705 
1706   default:
1707     return false;
1708   }
1709 }
1710 
1711 /// [GNU] typeof-specifier:
1712 ///         'typeof' '(' expressions ')'
1713 ///         'typeof' '(' type-name ')'
1714 ///
TryParseTypeofSpecifier()1715 Parser::TPResult Parser::TryParseTypeofSpecifier() {
1716   assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1717   ConsumeToken();
1718 
1719   assert(Tok.is(tok::l_paren) && "Expected '('");
1720   // Parse through the parens after 'typeof'.
1721   ConsumeParen();
1722   if (!SkipUntil(tok::r_paren, StopAtSemi))
1723     return TPResult::Error;
1724 
1725   return TPResult::Ambiguous;
1726 }
1727 
1728 /// [ObjC] protocol-qualifiers:
1729 ////         '<' identifier-list '>'
TryParseProtocolQualifiers()1730 Parser::TPResult Parser::TryParseProtocolQualifiers() {
1731   assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1732   ConsumeToken();
1733   do {
1734     if (Tok.isNot(tok::identifier))
1735       return TPResult::Error;
1736     ConsumeToken();
1737 
1738     if (Tok.is(tok::comma)) {
1739       ConsumeToken();
1740       continue;
1741     }
1742 
1743     if (Tok.is(tok::greater)) {
1744       ConsumeToken();
1745       return TPResult::Ambiguous;
1746     }
1747   } while (false);
1748 
1749   return TPResult::Error;
1750 }
1751 
1752 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1753 /// a constructor-style initializer, when parsing declaration statements.
1754 /// Returns true for function declarator and false for constructor-style
1755 /// initializer.
1756 /// If during the disambiguation process a parsing error is encountered,
1757 /// the function returns true to let the declaration parsing code handle it.
1758 ///
1759 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1760 ///         exception-specification[opt]
1761 ///
isCXXFunctionDeclarator(bool * IsAmbiguous)1762 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
1763 
1764   // C++ 8.2p1:
1765   // The ambiguity arising from the similarity between a function-style cast and
1766   // a declaration mentioned in 6.8 can also occur in the context of a
1767   // declaration. In that context, the choice is between a function declaration
1768   // with a redundant set of parentheses around a parameter name and an object
1769   // declaration with a function-style cast as the initializer. Just as for the
1770   // ambiguities mentioned in 6.8, the resolution is to consider any construct
1771   // that could possibly be a declaration a declaration.
1772 
1773   RevertingTentativeParsingAction PA(*this);
1774 
1775   ConsumeParen();
1776   bool InvalidAsDeclaration = false;
1777   TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
1778   if (TPR == TPResult::Ambiguous) {
1779     if (Tok.isNot(tok::r_paren))
1780       TPR = TPResult::False;
1781     else {
1782       const Token &Next = NextToken();
1783       if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile,
1784                        tok::kw_throw, tok::kw_noexcept, tok::l_square,
1785                        tok::l_brace, tok::kw_try, tok::equal, tok::arrow) ||
1786           isCXX11VirtSpecifier(Next))
1787         // The next token cannot appear after a constructor-style initializer,
1788         // and can appear next in a function definition. This must be a function
1789         // declarator.
1790         TPR = TPResult::True;
1791       else if (InvalidAsDeclaration)
1792         // Use the absence of 'typename' as a tie-breaker.
1793         TPR = TPResult::False;
1794     }
1795   }
1796 
1797   if (IsAmbiguous && TPR == TPResult::Ambiguous)
1798     *IsAmbiguous = true;
1799 
1800   // In case of an error, let the declaration parsing code handle it.
1801   return TPR != TPResult::False;
1802 }
1803 
1804 /// parameter-declaration-clause:
1805 ///   parameter-declaration-list[opt] '...'[opt]
1806 ///   parameter-declaration-list ',' '...'
1807 ///
1808 /// parameter-declaration-list:
1809 ///   parameter-declaration
1810 ///   parameter-declaration-list ',' parameter-declaration
1811 ///
1812 /// parameter-declaration:
1813 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1814 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1815 ///     '=' assignment-expression
1816 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1817 ///     attributes[opt]
1818 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1819 ///     attributes[opt] '=' assignment-expression
1820 ///
1821 Parser::TPResult
TryParseParameterDeclarationClause(bool * InvalidAsDeclaration,bool VersusTemplateArgument)1822 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration,
1823                                            bool VersusTemplateArgument) {
1824 
1825   if (Tok.is(tok::r_paren))
1826     return TPResult::Ambiguous;
1827 
1828   //   parameter-declaration-list[opt] '...'[opt]
1829   //   parameter-declaration-list ',' '...'
1830   //
1831   // parameter-declaration-list:
1832   //   parameter-declaration
1833   //   parameter-declaration-list ',' parameter-declaration
1834   //
1835   while (1) {
1836     // '...'[opt]
1837     if (Tok.is(tok::ellipsis)) {
1838       ConsumeToken();
1839       if (Tok.is(tok::r_paren))
1840         return TPResult::True; // '...)' is a sign of a function declarator.
1841       else
1842         return TPResult::False;
1843     }
1844 
1845     // An attribute-specifier-seq here is a sign of a function declarator.
1846     if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
1847                                   /*OuterMightBeMessageSend*/true))
1848       return TPResult::True;
1849 
1850     ParsedAttributes attrs(AttrFactory);
1851     MaybeParseMicrosoftAttributes(attrs);
1852 
1853     // decl-specifier-seq
1854     // A parameter-declaration's initializer must be preceded by an '=', so
1855     // decl-specifier-seq '{' is not a parameter in C++11.
1856     TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
1857                                              InvalidAsDeclaration);
1858 
1859     if (VersusTemplateArgument && TPR == TPResult::True) {
1860       // Consume the decl-specifier-seq. We have to look past it, since a
1861       // type-id might appear here in a template argument.
1862       bool SeenType = false;
1863       do {
1864         SeenType |= isCXXDeclarationSpecifierAType();
1865         if (TryConsumeDeclarationSpecifier() == TPResult::Error)
1866           return TPResult::Error;
1867 
1868         // If we see a parameter name, this can't be a template argument.
1869         if (SeenType && Tok.is(tok::identifier))
1870           return TPResult::True;
1871 
1872         TPR = isCXXDeclarationSpecifier(TPResult::False,
1873                                         InvalidAsDeclaration);
1874         if (TPR == TPResult::Error)
1875           return TPR;
1876       } while (TPR != TPResult::False);
1877     } else if (TPR == TPResult::Ambiguous) {
1878       // Disambiguate what follows the decl-specifier.
1879       if (TryConsumeDeclarationSpecifier() == TPResult::Error)
1880         return TPResult::Error;
1881     } else
1882       return TPR;
1883 
1884     // declarator
1885     // abstract-declarator[opt]
1886     TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1887     if (TPR != TPResult::Ambiguous)
1888       return TPR;
1889 
1890     // [GNU] attributes[opt]
1891     if (Tok.is(tok::kw___attribute))
1892       return TPResult::True;
1893 
1894     // If we're disambiguating a template argument in a default argument in
1895     // a class definition versus a parameter declaration, an '=' here
1896     // disambiguates the parse one way or the other.
1897     // If this is a parameter, it must have a default argument because
1898     //   (a) the previous parameter did, and
1899     //   (b) this must be the first declaration of the function, so we can't
1900     //       inherit any default arguments from elsewhere.
1901     // If we see an ')', then we've reached the end of a
1902     // parameter-declaration-clause, and the last param is missing its default
1903     // argument.
1904     if (VersusTemplateArgument)
1905       return Tok.isOneOf(tok::equal, tok::r_paren) ? TPResult::True
1906                                                    : TPResult::False;
1907 
1908     if (Tok.is(tok::equal)) {
1909       // '=' assignment-expression
1910       // Parse through assignment-expression.
1911       // FIXME: assignment-expression may contain an unparenthesized comma.
1912       if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
1913         return TPResult::Error;
1914     }
1915 
1916     if (Tok.is(tok::ellipsis)) {
1917       ConsumeToken();
1918       if (Tok.is(tok::r_paren))
1919         return TPResult::True; // '...)' is a sign of a function declarator.
1920       else
1921         return TPResult::False;
1922     }
1923 
1924     if (!TryConsumeToken(tok::comma))
1925       break;
1926   }
1927 
1928   return TPResult::Ambiguous;
1929 }
1930 
1931 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
1932 /// parsing as a function declarator.
1933 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
1934 /// return TPResult::Ambiguous, otherwise it will return either False() or
1935 /// Error().
1936 ///
1937 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1938 ///         exception-specification[opt]
1939 ///
1940 /// exception-specification:
1941 ///   'throw' '(' type-id-list[opt] ')'
1942 ///
TryParseFunctionDeclarator()1943 Parser::TPResult Parser::TryParseFunctionDeclarator() {
1944 
1945   // The '(' is already parsed.
1946 
1947   TPResult TPR = TryParseParameterDeclarationClause();
1948   if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
1949     TPR = TPResult::False;
1950 
1951   if (TPR == TPResult::False || TPR == TPResult::Error)
1952     return TPR;
1953 
1954   // Parse through the parens.
1955   if (!SkipUntil(tok::r_paren, StopAtSemi))
1956     return TPResult::Error;
1957 
1958   // cv-qualifier-seq
1959   while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw___unaligned,
1960                      tok::kw_restrict))
1961     ConsumeToken();
1962 
1963   // ref-qualifier[opt]
1964   if (Tok.isOneOf(tok::amp, tok::ampamp))
1965     ConsumeToken();
1966 
1967   // exception-specification
1968   if (Tok.is(tok::kw_throw)) {
1969     ConsumeToken();
1970     if (Tok.isNot(tok::l_paren))
1971       return TPResult::Error;
1972 
1973     // Parse through the parens after 'throw'.
1974     ConsumeParen();
1975     if (!SkipUntil(tok::r_paren, StopAtSemi))
1976       return TPResult::Error;
1977   }
1978   if (Tok.is(tok::kw_noexcept)) {
1979     ConsumeToken();
1980     // Possibly an expression as well.
1981     if (Tok.is(tok::l_paren)) {
1982       // Find the matching rparen.
1983       ConsumeParen();
1984       if (!SkipUntil(tok::r_paren, StopAtSemi))
1985         return TPResult::Error;
1986     }
1987   }
1988 
1989   return TPResult::Ambiguous;
1990 }
1991 
1992 /// '[' constant-expression[opt] ']'
1993 ///
TryParseBracketDeclarator()1994 Parser::TPResult Parser::TryParseBracketDeclarator() {
1995   ConsumeBracket();
1996   if (!SkipUntil(tok::r_square, StopAtSemi))
1997     return TPResult::Error;
1998 
1999   return TPResult::Ambiguous;
2000 }
2001