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