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