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