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