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