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 address space qualifiers
1290 case tok::kw_groupshared:
1291 case tok::kw_in:
1292 case tok::kw_inout:
1293 case tok::kw_out:
1294 // HLSL matrix layout qualifiers
1295 case tok::kw_row_major:
1296 case tok::kw_column_major:
1297
1298 // GNU
1299 case tok::kw_restrict:
1300 case tok::kw__Complex:
1301 case tok::kw__Imaginary:
1302 case tok::kw___attribute:
1303 case tok::kw___auto_type:
1304 return TPResult::True;
1305
1306 // OverflowBehaviorTypes
1307 case tok::kw___ob_wrap:
1308 case tok::kw___ob_trap:
1309 return TPResult::True;
1310
1311 // Microsoft
1312 case tok::kw___declspec:
1313 case tok::kw___cdecl:
1314 case tok::kw___stdcall:
1315 case tok::kw___fastcall:
1316 case tok::kw___thiscall:
1317 case tok::kw___regcall:
1318 case tok::kw___vectorcall:
1319 case tok::kw___w64:
1320 case tok::kw___sptr:
1321 case tok::kw___uptr:
1322 case tok::kw___ptr64:
1323 case tok::kw___ptr32:
1324 case tok::kw___forceinline:
1325 case tok::kw___unaligned:
1326 case tok::kw__Nonnull:
1327 case tok::kw__Nullable:
1328 case tok::kw__Nullable_result:
1329 case tok::kw__Null_unspecified:
1330 case tok::kw___kindof:
1331 return TPResult::True;
1332
1333 // WebAssemblyFuncref
1334 case tok::kw___funcref:
1335 return TPResult::True;
1336
1337 // Borland
1338 case tok::kw___pascal:
1339 return TPResult::True;
1340
1341 // AltiVec
1342 case tok::kw___vector:
1343 return TPResult::True;
1344
1345 case tok::kw_this: {
1346 // Try to parse a C++23 Explicit Object Parameter
1347 // We do that in all language modes to produce a better diagnostic.
1348 if (getLangOpts().CPlusPlus) {
1349 RevertingTentativeParsingAction PA(*this);
1350 ConsumeToken();
1351 return isCXXDeclarationSpecifier(AllowImplicitTypename, BracedCastResult,
1352 InvalidAsDeclSpec);
1353 }
1354 return TPResult::False;
1355 }
1356 case tok::annot_template_id: {
1357 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1358 // If lookup for the template-name found nothing, don't assume we have a
1359 // definitive disambiguation result yet.
1360 if ((TemplateId->hasInvalidName() ||
1361 TemplateId->Kind == TNK_Undeclared_template) &&
1362 InvalidAsDeclSpec) {
1363 // 'template-id(' can be a valid expression but not a valid decl spec if
1364 // the template-name is not declared, but we don't consider this to be a
1365 // definitive disambiguation. In any other context, it's an error either
1366 // way.
1367 *InvalidAsDeclSpec = NextToken().is(tok::l_paren);
1368 return TPResult::Ambiguous;
1369 }
1370 if (TemplateId->hasInvalidName())
1371 return TPResult::Error;
1372 if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/0))
1373 return TPResult::True;
1374 if (TemplateId->Kind != TNK_Type_template)
1375 return TPResult::False;
1376 CXXScopeSpec SS;
1377 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
1378 assert(Tok.is(tok::annot_typename));
1379 goto case_typename;
1380 }
1381
1382 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1383 // We've already annotated a scope; try to annotate a type.
1384 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
1385 return TPResult::Error;
1386 if (!Tok.is(tok::annot_typename)) {
1387 if (Tok.is(tok::annot_cxxscope) &&
1388 NextToken().is(tok::annot_template_id)) {
1389 TemplateIdAnnotation *TemplateId =
1390 takeTemplateIdAnnotation(NextToken());
1391 if (TemplateId->hasInvalidName()) {
1392 if (InvalidAsDeclSpec) {
1393 *InvalidAsDeclSpec = NextToken().is(tok::l_paren);
1394 return TPResult::Ambiguous;
1395 }
1396 return TPResult::Error;
1397 }
1398 if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/1))
1399 return TPResult::True;
1400 }
1401 // If the next token is an identifier or a type qualifier, then this
1402 // can't possibly be a valid expression either.
1403 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1404 CXXScopeSpec SS;
1405 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1406 Tok.getAnnotationRange(),
1407 SS);
1408 if (SS.getScopeRep().isDependent()) {
1409 RevertingTentativeParsingAction PA(*this);
1410 ConsumeAnnotationToken();
1411 ConsumeToken();
1412 bool isIdentifier = Tok.is(tok::identifier);
1413 TPResult TPR = TPResult::False;
1414 if (!isIdentifier)
1415 TPR = isCXXDeclarationSpecifier(
1416 AllowImplicitTypename, BracedCastResult, InvalidAsDeclSpec);
1417
1418 if (isIdentifier ||
1419 TPR == TPResult::True || TPR == TPResult::Error)
1420 return TPResult::Error;
1421
1422 if (InvalidAsDeclSpec) {
1423 // We can't tell whether this is a missing 'typename' or a valid
1424 // expression.
1425 *InvalidAsDeclSpec = true;
1426 return TPResult::Ambiguous;
1427 } else {
1428 // In MS mode, if InvalidAsDeclSpec is not provided, and the tokens
1429 // are or the form *) or &) *> or &> &&>, this can't be an expression.
1430 // The typename must be missing.
1431 if (getLangOpts().MSVCCompat) {
1432 if (((Tok.is(tok::amp) || Tok.is(tok::star)) &&
1433 (NextToken().is(tok::r_paren) ||
1434 NextToken().is(tok::greater))) ||
1435 (Tok.is(tok::ampamp) && NextToken().is(tok::greater)))
1436 return TPResult::True;
1437 }
1438 }
1439 } else {
1440 // Try to resolve the name. If it doesn't exist, assume it was
1441 // intended to name a type and keep disambiguating.
1442 switch (TryAnnotateName(/*CCC=*/nullptr, AllowImplicitTypename)) {
1444 return TPResult::Error;
1446 return TPResult::False;
1448 // In C++17, this could be a type template for class template
1449 // argument deduction.
1450 if (getLangOpts().CPlusPlus17) {
1452 return TPResult::Error;
1453 // If we annotated then the current token should not still be ::
1454 // FIXME we may want to also check for tok::annot_typename but
1455 // currently don't have a test case.
1456 if (Tok.isNot(tok::annot_cxxscope) && Tok.isNot(tok::identifier))
1457 break;
1458 }
1459
1460 // A bare type template-name which can't be a template template
1461 // argument is an error, and was probably intended to be a type.
1462 // In C++17, this could be class template argument deduction.
1463 return (getLangOpts().CPlusPlus17 || GreaterThanIsOperator)
1464 ? TPResult::True
1465 : TPResult::False;
1467 return InvalidAsDeclSpec ? TPResult::Ambiguous : TPResult::False;
1469 break;
1470 }
1471
1472 // Annotated it, check again.
1473 assert(Tok.isNot(tok::annot_cxxscope) ||
1474 NextToken().isNot(tok::identifier));
1475 return isCXXDeclarationSpecifier(AllowImplicitTypename,
1476 BracedCastResult, InvalidAsDeclSpec);
1477 }
1478 }
1479 return TPResult::False;
1480 }
1481 // If that succeeded, fallthrough into the generic simple-type-id case.
1482 [[fallthrough]];
1483
1484 // The ambiguity resides in a simple-type-specifier/typename-specifier
1485 // followed by a '('. The '(' could either be the start of:
1486 //
1487 // direct-declarator:
1488 // '(' declarator ')'
1489 //
1490 // direct-abstract-declarator:
1491 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1492 // exception-specification[opt]
1493 // '(' abstract-declarator ')'
1494 //
1495 // or part of a function-style cast expression:
1496 //
1497 // simple-type-specifier '(' expression-list[opt] ')'
1498 //
1499
1500 // simple-type-specifier:
1501
1502 case tok::annot_typename:
1503 case_typename:
1504 // In Objective-C, we might have a protocol-qualified type.
1505 if (getLangOpts().ObjC && NextToken().is(tok::less)) {
1506 // Tentatively parse the protocol qualifiers.
1507 RevertingTentativeParsingAction PA(*this);
1508 ConsumeAnyToken(); // The type token
1509
1510 TPResult TPR = TryParseProtocolQualifiers();
1511 bool isFollowedByParen = Tok.is(tok::l_paren);
1512 bool isFollowedByBrace = Tok.is(tok::l_brace);
1513
1514 if (TPR == TPResult::Error)
1515 return TPResult::Error;
1516
1517 if (isFollowedByParen)
1518 return TPResult::Ambiguous;
1519
1520 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1521 return BracedCastResult;
1522
1523 return TPResult::True;
1524 }
1525
1526 [[fallthrough]];
1527
1528 case tok::kw_char:
1529 case tok::kw_wchar_t:
1530 case tok::kw_char8_t:
1531 case tok::kw_char16_t:
1532 case tok::kw_char32_t:
1533 case tok::kw_bool:
1534 case tok::kw_short:
1535 case tok::kw_int:
1536 case tok::kw_long:
1537 case tok::kw___int64:
1538 case tok::kw___int128:
1539 case tok::kw_signed:
1540 case tok::kw_unsigned:
1541 case tok::kw_half:
1542 case tok::kw_float:
1543 case tok::kw_double:
1544 case tok::kw___bf16:
1545 case tok::kw__Float16:
1546 case tok::kw___float128:
1547 case tok::kw___ibm128:
1548 case tok::kw_void:
1549 case tok::annot_decltype:
1550 case tok::kw__Accum:
1551 case tok::kw__Fract:
1552 case tok::kw__Sat:
1553 case tok::annot_pack_indexing_type:
1554#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1555#include "clang/Basic/OpenCLImageTypes.def"
1556#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
1557#include "clang/Basic/HLSLIntangibleTypes.def"
1558 if (NextToken().is(tok::l_paren))
1559 return TPResult::Ambiguous;
1560
1561 // This is a function-style cast in all cases we disambiguate other than
1562 // one:
1563 // struct S {
1564 // enum E : int { a = 4 }; // enum
1565 // enum E : int { 4 }; // bit-field
1566 // };
1567 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
1568 return BracedCastResult;
1569
1570 if (isStartOfObjCClassMessageMissingOpenBracket())
1571 return TPResult::False;
1572
1573 return TPResult::True;
1574
1575 // GNU typeof support.
1576 case tok::kw_typeof:
1577 case tok::kw_typeof_unqual: {
1578 if (NextToken().isNot(tok::l_paren))
1579 return TPResult::True;
1580
1581 RevertingTentativeParsingAction PA(*this);
1582
1583 TPResult TPR = TryParseTypeofSpecifier();
1584 bool isFollowedByParen = Tok.is(tok::l_paren);
1585 bool isFollowedByBrace = Tok.is(tok::l_brace);
1586
1587 if (TPR == TPResult::Error)
1588 return TPResult::Error;
1589
1590 if (isFollowedByParen)
1591 return TPResult::Ambiguous;
1592
1593 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1594 return BracedCastResult;
1595
1596 return TPResult::True;
1597 }
1598
1599#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
1600#include "clang/Basic/BuiltinTraits.inc"
1601 return TPResult::True;
1602
1603 // C11 _Alignas
1604 case tok::kw__Alignas:
1605 return TPResult::True;
1606 // C11 _Atomic
1607 case tok::kw__Atomic:
1608 return TPResult::True;
1609
1610 case tok::kw__BitInt:
1611 case tok::kw__ExtInt: {
1612 if (NextToken().isNot(tok::l_paren))
1613 return TPResult::Error;
1614 RevertingTentativeParsingAction PA(*this);
1615 ConsumeToken();
1616 ConsumeParen();
1617
1618 if (!SkipUntil(tok::r_paren, StopAtSemi))
1619 return TPResult::Error;
1620
1621 if (Tok.is(tok::l_paren))
1622 return TPResult::Ambiguous;
1623
1624 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
1625 return BracedCastResult;
1626
1627 return TPResult::True;
1628 }
1629 default:
1630 return TPResult::False;
1631 }
1632}
1633
1634bool Parser::isCXXDeclarationSpecifierAType() {
1635 switch (Tok.getKind()) {
1636 // typename-specifier
1637 case tok::annot_decltype:
1638 case tok::annot_pack_indexing_type:
1639 case tok::annot_template_id:
1640 case tok::annot_typename:
1641 case tok::kw_typeof:
1642 case tok::kw_typeof_unqual:
1643#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
1644#include "clang/Basic/BuiltinTraits.inc"
1645 return true;
1646
1647 // elaborated-type-specifier
1648 case tok::kw_class:
1649 case tok::kw_struct:
1650 case tok::kw_union:
1651 case tok::kw___interface:
1652 case tok::kw_enum:
1653 return true;
1654
1655 // simple-type-specifier
1656 case tok::kw_char:
1657 case tok::kw_wchar_t:
1658 case tok::kw_char8_t:
1659 case tok::kw_char16_t:
1660 case tok::kw_char32_t:
1661 case tok::kw_bool:
1662 case tok::kw_short:
1663 case tok::kw_int:
1664 case tok::kw__ExtInt:
1665 case tok::kw__BitInt:
1666 case tok::kw_long:
1667 case tok::kw___int64:
1668 case tok::kw___int128:
1669 case tok::kw_signed:
1670 case tok::kw_unsigned:
1671 case tok::kw_half:
1672 case tok::kw_float:
1673 case tok::kw_double:
1674 case tok::kw___bf16:
1675 case tok::kw__Float16:
1676 case tok::kw___float128:
1677 case tok::kw___ibm128:
1678 case tok::kw_void:
1679 case tok::kw___unknown_anytype:
1680 case tok::kw___auto_type:
1681 case tok::kw__Accum:
1682 case tok::kw__Fract:
1683 case tok::kw__Sat:
1684#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1685#include "clang/Basic/OpenCLImageTypes.def"
1686#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
1687#include "clang/Basic/HLSLIntangibleTypes.def"
1688 return true;
1689
1690 case tok::kw_auto:
1691 return getLangOpts().CPlusPlus11;
1692
1693 case tok::kw__Atomic:
1694 // "_Atomic foo"
1695 return NextToken().is(tok::l_paren);
1696
1697 default:
1698 return false;
1699 }
1700}
1701
1702Parser::TPResult Parser::TryParseTypeofSpecifier() {
1703 assert(Tok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
1704 "Expected 'typeof' or 'typeof_unqual'!");
1705 ConsumeToken();
1706
1707 assert(Tok.is(tok::l_paren) && "Expected '('");
1708 // Parse through the parens after 'typeof'.
1709 ConsumeParen();
1710 if (!SkipUntil(tok::r_paren, StopAtSemi))
1711 return TPResult::Error;
1712
1713 return TPResult::Ambiguous;
1714}
1715
1716Parser::TPResult Parser::TryParseProtocolQualifiers() {
1717 assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1718 ConsumeToken();
1719 do {
1720 if (Tok.isNot(tok::identifier))
1721 return TPResult::Error;
1722 ConsumeToken();
1723
1724 if (Tok.is(tok::comma)) {
1725 ConsumeToken();
1726 continue;
1727 }
1728
1729 if (Tok.is(tok::greater)) {
1730 ConsumeToken();
1731 return TPResult::Ambiguous;
1732 }
1733 } while (false);
1734
1735 return TPResult::Error;
1736}
1737
1738bool Parser::isCXXFunctionDeclarator(
1739 bool *IsAmbiguous, ImplicitTypenameContext AllowImplicitTypename) {
1740
1741 // C++ 8.2p1:
1742 // The ambiguity arising from the similarity between a function-style cast and
1743 // a declaration mentioned in 6.8 can also occur in the context of a
1744 // declaration. In that context, the choice is between a function declaration
1745 // with a redundant set of parentheses around a parameter name and an object
1746 // declaration with a function-style cast as the initializer. Just as for the
1747 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1748 // that could possibly be a declaration a declaration.
1749
1750 RevertingTentativeParsingAction PA(*this);
1751
1752 ConsumeParen();
1753 bool InvalidAsDeclaration = false;
1754 TPResult TPR = TryParseParameterDeclarationClause(
1755 &InvalidAsDeclaration, /*VersusTemplateArgument=*/false,
1756 AllowImplicitTypename);
1757 if (TPR == TPResult::Ambiguous) {
1758 if (Tok.isNot(tok::r_paren))
1759 TPR = TPResult::False;
1760 else {
1761 const Token &Next = NextToken();
1762 if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile,
1763 tok::kw_throw, tok::kw_noexcept, tok::l_square,
1764 tok::l_brace, tok::kw_try, tok::equal, tok::arrow) ||
1765 isCXX11VirtSpecifier(Next))
1766 // The next token cannot appear after a constructor-style initializer,
1767 // and can appear next in a function definition. This must be a function
1768 // declarator.
1769 TPR = TPResult::True;
1770 else if (InvalidAsDeclaration)
1771 // Use the absence of 'typename' as a tie-breaker.
1772 TPR = TPResult::False;
1773 }
1774 }
1775
1776 if (IsAmbiguous && TPR == TPResult::Ambiguous)
1777 *IsAmbiguous = true;
1778
1779 // In case of an error, let the declaration parsing code handle it.
1780 return TPR != TPResult::False;
1781}
1782
1783Parser::TPResult Parser::TryParseParameterDeclarationClause(
1784 bool *InvalidAsDeclaration, bool VersusTemplateArgument,
1785 ImplicitTypenameContext AllowImplicitTypename) {
1786
1787 if (Tok.is(tok::r_paren))
1788 return TPResult::Ambiguous;
1789
1790 // parameter-declaration-list[opt] '...'[opt]
1791 // parameter-declaration-list ',' '...'
1792 //
1793 // parameter-declaration-list:
1794 // parameter-declaration
1795 // parameter-declaration-list ',' parameter-declaration
1796 //
1797 while (true) {
1798 // '...'[opt]
1799 if (Tok.is(tok::ellipsis)) {
1800 ConsumeToken();
1801 if (Tok.is(tok::r_paren))
1802 return TPResult::True; // '...)' is a sign of a function declarator.
1803 else
1804 return TPResult::False;
1805 }
1806
1807 // An attribute-specifier-seq here is a sign of a function declarator.
1808 if (isCXX11AttributeSpecifier(/*Disambiguate*/ false,
1809 /*OuterMightBeMessageSend*/ true) !=
1811 return TPResult::True;
1812
1813 if ((getLangOpts().MicrosoftExt || getLangOpts().HLSL) &&
1814 Tok.is(tok::l_square) && hasLambdaLikeContinuation())
1815 return TPResult::False;
1816
1817 ParsedAttributes attrs(AttrFactory);
1818 MaybeParseMicrosoftAttributes(attrs);
1819
1820 // decl-specifier-seq
1821 // A parameter-declaration's initializer must be preceded by an '=', so
1822 // decl-specifier-seq '{' is not a parameter in C++11.
1823 TPResult TPR = isCXXDeclarationSpecifier(
1824 AllowImplicitTypename, TPResult::False, InvalidAsDeclaration);
1825 // A declaration-specifier (not followed by '(' or '{') means this can't be
1826 // an expression, but it could still be a template argument.
1827 if (TPR != TPResult::Ambiguous &&
1828 !(VersusTemplateArgument && TPR == TPResult::True))
1829 return TPR;
1830
1831 bool SeenType = false;
1832 bool DeclarationSpecifierIsAuto = Tok.is(tok::kw_auto);
1833 do {
1834 SeenType |= isCXXDeclarationSpecifierAType();
1835 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
1836 return TPResult::Error;
1837
1838 // If we see a parameter name, this can't be a template argument.
1839 if (SeenType && Tok.is(tok::identifier))
1840 return TPResult::True;
1841
1842 TPR = isCXXDeclarationSpecifier(AllowImplicitTypename, TPResult::False,
1843 InvalidAsDeclaration);
1844 if (TPR == TPResult::Error)
1845 return TPR;
1846
1847 // Two declaration-specifiers means this can't be an expression.
1848 if (TPR == TPResult::True && !VersusTemplateArgument)
1849 return TPR;
1850 } while (TPR != TPResult::False);
1851
1852 // declarator
1853 // abstract-declarator[opt]
1854 TPR = TryParseDeclarator(
1855 /*mayBeAbstract=*/true,
1856 /*mayHaveIdentifier=*/true,
1857 /*mayHaveDirectInit=*/false,
1858 /*mayHaveTrailingReturnType=*/DeclarationSpecifierIsAuto);
1859 if (TPR != TPResult::Ambiguous)
1860 return TPR;
1861
1862 // [GNU] attributes[opt]
1863 if (Tok.is(tok::kw___attribute))
1864 return TPResult::True;
1865
1866 // If we're disambiguating a template argument in a default argument in
1867 // a class definition versus a parameter declaration, an '=' here
1868 // disambiguates the parse one way or the other.
1869 // If this is a parameter, it must have a default argument because
1870 // (a) the previous parameter did, and
1871 // (b) this must be the first declaration of the function, so we can't
1872 // inherit any default arguments from elsewhere.
1873 // FIXME: If we reach a ')' without consuming any '>'s, then this must
1874 // also be a function parameter (that's missing its default argument).
1875 if (VersusTemplateArgument)
1876 return Tok.is(tok::equal) ? TPResult::True : TPResult::False;
1877
1878 if (Tok.is(tok::equal)) {
1879 // '=' assignment-expression
1880 // Parse through assignment-expression.
1881 if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
1882 return TPResult::Error;
1883 }
1884
1885 if (Tok.is(tok::ellipsis)) {
1886 ConsumeToken();
1887 if (Tok.is(tok::r_paren))
1888 return TPResult::True; // '...)' is a sign of a function declarator.
1889 else
1890 return TPResult::False;
1891 }
1892
1893 if (!TryConsumeToken(tok::comma))
1894 break;
1895 }
1896
1897 return TPResult::Ambiguous;
1898}
1899
1900Parser::TPResult
1901Parser::TryParseFunctionDeclarator(bool MayHaveTrailingReturnType) {
1902 // The '(' is already parsed.
1903
1904 TPResult TPR = TryParseParameterDeclarationClause();
1905 if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
1906 TPR = TPResult::False;
1907
1908 if (TPR == TPResult::False || TPR == TPResult::Error)
1909 return TPR;
1910
1911 // Parse through the parens.
1912 if (!SkipUntil(tok::r_paren, StopAtSemi))
1913 return TPResult::Error;
1914
1915 // cv-qualifier-seq
1916 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw___unaligned,
1917 tok::kw_restrict))
1918 ConsumeToken();
1919
1920 // ref-qualifier[opt]
1921 if (Tok.isOneOf(tok::amp, tok::ampamp))
1922 ConsumeToken();
1923
1924 // exception-specification
1925 if (Tok.is(tok::kw_throw)) {
1926 ConsumeToken();
1927 if (Tok.isNot(tok::l_paren))
1928 return TPResult::Error;
1929
1930 // Parse through the parens after 'throw'.
1931 ConsumeParen();
1932 if (!SkipUntil(tok::r_paren, StopAtSemi))
1933 return TPResult::Error;
1934 }
1935 if (Tok.is(tok::kw_noexcept)) {
1936 ConsumeToken();
1937 // Possibly an expression as well.
1938 if (Tok.is(tok::l_paren)) {
1939 // Find the matching rparen.
1940 ConsumeParen();
1941 if (!SkipUntil(tok::r_paren, StopAtSemi))
1942 return TPResult::Error;
1943 }
1944 }
1945
1946 // attribute-specifier-seq
1947 if (!TrySkipAttributes())
1948 return TPResult::Ambiguous;
1949
1950 // trailing-return-type
1951 if (Tok.is(tok::arrow) && MayHaveTrailingReturnType) {
1952 if (TPR == TPResult::True)
1953 return TPR;
1954 ConsumeToken();
1955 if (Tok.is(tok::identifier) && NameAfterArrowIsNonType()) {
1956 return TPResult::False;
1957 }
1959 return TPResult::True;
1960 }
1961
1962 return TPResult::Ambiguous;
1963}
1964
1965bool Parser::NameAfterArrowIsNonType() {
1966 assert(Tok.is(tok::identifier));
1967 Token Next = NextToken();
1968 if (Next.is(tok::coloncolon))
1969 return false;
1970 IdentifierInfo *Name = Tok.getIdentifierInfo();
1971 SourceLocation NameLoc = Tok.getLocation();
1972 CXXScopeSpec SS;
1973 TentativeParseCCC CCC(Next);
1974 Sema::NameClassification Classification =
1975 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next, &CCC);
1976 switch (Classification.getKind()) {
1981 return true;
1982 default:
1983 break;
1984 }
1985 return false;
1986}
1987
1988Parser::TPResult Parser::TryParseBracketDeclarator() {
1989 ConsumeBracket();
1990
1991 // A constant-expression cannot begin with a '{', but the
1992 // expr-or-braced-init-list of a postfix-expression can.
1993 if (Tok.is(tok::l_brace))
1994 return TPResult::False;
1995
1996 if (!SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch))
1997 return TPResult::Error;
1998
1999 // If we hit a comma before the ']', this is not a constant-expression,
2000 // but might still be the expr-or-braced-init-list of a postfix-expression.
2001 if (Tok.isNot(tok::r_square))
2002 return TPResult::False;
2003
2004 ConsumeBracket();
2005 return TPResult::Ambiguous;
2006}
2007
2008Parser::TPResult Parser::isTemplateArgumentList(unsigned TokensToSkip) {
2009 if (!TokensToSkip) {
2010 if (Tok.isNot(tok::less))
2011 return TPResult::False;
2012 if (NextToken().is(tok::greater))
2013 return TPResult::True;
2014 }
2015
2016 RevertingTentativeParsingAction PA(*this);
2017
2018 while (TokensToSkip) {
2020 --TokensToSkip;
2021 }
2022
2023 if (!TryConsumeToken(tok::less))
2024 return TPResult::False;
2025
2026 // We can't do much to tell an expression apart from a template-argument,
2027 // but one good distinguishing factor is that a "decl-specifier" not
2028 // followed by '(' or '{' can't appear in an expression.
2029 bool InvalidAsTemplateArgumentList = false;
2030 if (isCXXDeclarationSpecifier(ImplicitTypenameContext::No, TPResult::False,
2031 &InvalidAsTemplateArgumentList) ==
2032 TPResult::True)
2033 return TPResult::True;
2034 if (InvalidAsTemplateArgumentList)
2035 return TPResult::False;
2036
2037 // FIXME: In many contexts, X<thing1, Type> can only be a
2038 // template-argument-list. But that's not true in general:
2039 //
2040 // using b = int;
2041 // void f() {
2042 // int a = A<B, b, c = C>D; // OK, declares b, not a template-id.
2043 //
2044 // X<Y<0, int> // ', int>' might be end of X's template argument list
2045 //
2046 // We might be able to disambiguate a few more cases if we're careful.
2047
2048 // A template-argument-list must be terminated by a '>'.
2049 if (SkipUntil({tok::greater, tok::greatergreater, tok::greatergreatergreater},
2051 return TPResult::Ambiguous;
2052 return TPResult::False;
2053}
2054
2055Parser::TPResult Parser::isExplicitBool() {
2056 assert(Tok.is(tok::l_paren) && "expected to be looking at a '(' token");
2057
2058 RevertingTentativeParsingAction PA(*this);
2059 ConsumeParen();
2060
2061 // We can only have 'explicit' on a constructor, conversion function, or
2062 // deduction guide. The declarator of a deduction guide cannot be
2063 // parenthesized, so we know this isn't a deduction guide. So the only
2064 // thing we need to check for is some number of parens followed by either
2065 // the current class name or 'operator'.
2066 while (Tok.is(tok::l_paren))
2067 ConsumeParen();
2068
2070 return TPResult::Error;
2071
2072 // Class-scope constructor and conversion function names can't really be
2073 // qualified, but we get better diagnostics if we assume they can be.
2074 CXXScopeSpec SS;
2075 if (Tok.is(tok::annot_cxxscope)) {
2076 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2077 Tok.getAnnotationRange(),
2078 SS);
2079 ConsumeAnnotationToken();
2080 }
2081
2082 // 'explicit(operator' might be explicit(bool) or the declaration of a
2083 // conversion function, but it's probably a conversion function.
2084 if (Tok.is(tok::kw_operator))
2085 return TPResult::Ambiguous;
2086
2087 // If this can't be a constructor name, it can only be explicit(bool).
2088 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
2089 return TPResult::True;
2090 if (!Actions.isCurrentClassName(Tok.is(tok::identifier)
2091 ? *Tok.getIdentifierInfo()
2092 : *takeTemplateIdAnnotation(Tok)->Name,
2093 getCurScope(), &SS))
2094 return TPResult::True;
2095 // Formally, we must have a right-paren after the constructor name to match
2096 // the grammar for a constructor. But clang permits a parenthesized
2097 // constructor declarator, so also allow a constructor declarator to follow
2098 // with no ')' token after the constructor name.
2099 if (!NextToken().is(tok::r_paren) &&
2100 !isConstructorDeclarator(/*Unqualified=*/SS.isEmpty(),
2101 /*DeductionGuide=*/false))
2102 return TPResult::True;
2103
2104 // Might be explicit(bool) or a parenthesized constructor name.
2105 return TPResult::Ambiguous;
2106}
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:1885
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:72
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
@ StopAtCodeCompletion
Stop at code completion.
Definition Parser.h:573
@ 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:3794
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: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.