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
799Parser::TPResult Parser::TryParsePtrOperatorSeq() {
800 while (true) {
802 return TPResult::Error;
803
804 if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) ||
805 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
806 // ptr-operator
808
809 // Skip attributes.
810 if (!TrySkipAttributes())
811 return TPResult::Error;
812
813 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict,
814 tok::kw__Nonnull, tok::kw__Nullable,
815 tok::kw__Nullable_result, tok::kw__Null_unspecified,
816 tok::kw__Atomic))
817 ConsumeToken();
818 } else {
819 return TPResult::True;
820 }
821 }
822}
823
824Parser::TPResult Parser::TryParseOperatorId() {
825 assert(Tok.is(tok::kw_operator));
826 ConsumeToken();
827
828 // Maybe this is an operator-function-id.
829 switch (Tok.getKind()) {
830 case tok::kw_new: case tok::kw_delete:
831 ConsumeToken();
832 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
833 ConsumeBracket();
834 ConsumeBracket();
835 }
836 return TPResult::True;
837
838#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
839 case tok::Token:
840#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
841#include "clang/Basic/OperatorKinds.def"
842 ConsumeToken();
843 return TPResult::True;
844
845 case tok::l_square:
846 if (NextToken().is(tok::r_square)) {
847 ConsumeBracket();
848 ConsumeBracket();
849 return TPResult::True;
850 }
851 break;
852
853 case tok::l_paren:
854 if (NextToken().is(tok::r_paren)) {
855 ConsumeParen();
856 ConsumeParen();
857 return TPResult::True;
858 }
859 break;
860
861 default:
862 break;
863 }
864
865 // Maybe this is a literal-operator-id.
866 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
867 bool FoundUDSuffix = false;
868 do {
869 FoundUDSuffix |= Tok.hasUDSuffix();
870 ConsumeStringToken();
871 } while (isTokenStringLiteral());
872
873 if (!FoundUDSuffix) {
874 if (Tok.is(tok::identifier))
875 ConsumeToken();
876 else
877 return TPResult::Error;
878 }
879 return TPResult::True;
880 }
881
882 // Maybe this is a conversion-function-id.
883 bool AnyDeclSpecifiers = false;
884 while (true) {
885 TPResult TPR = isCXXDeclarationSpecifier(ImplicitTypenameContext::No);
886 if (TPR == TPResult::Error)
887 return TPR;
888 if (TPR == TPResult::False) {
889 if (!AnyDeclSpecifiers)
890 return TPResult::Error;
891 break;
892 }
893 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
894 return TPResult::Error;
895 AnyDeclSpecifiers = true;
896 }
897 return TryParsePtrOperatorSeq();
898}
899
900Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
901 bool mayHaveIdentifier,
902 bool mayHaveDirectInit,
903 bool mayHaveTrailingReturnType) {
904 // declarator:
905 // direct-declarator
906 // ptr-operator declarator
907 if (TryParsePtrOperatorSeq() == TPResult::Error)
908 return TPResult::Error;
909
910 // direct-declarator:
911 // direct-abstract-declarator:
912 if (Tok.is(tok::ellipsis))
913 ConsumeToken();
914
915 if ((Tok.isOneOf(tok::identifier, tok::kw_operator) ||
916 (Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) ||
917 NextToken().is(tok::kw_operator)))) &&
918 mayHaveIdentifier) {
919 // declarator-id
920 if (Tok.is(tok::annot_cxxscope)) {
921 CXXScopeSpec SS;
922 Actions.RestoreNestedNameSpecifierAnnotation(
923 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
924 if (SS.isInvalid())
925 return TPResult::Error;
926 ConsumeAnnotationToken();
927 } else if (Tok.is(tok::identifier)) {
928 TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
929 }
930 if (Tok.is(tok::kw_operator)) {
931 if (TryParseOperatorId() == TPResult::Error)
932 return TPResult::Error;
933 } else
934 ConsumeToken();
935 } else if (Tok.is(tok::l_paren)) {
936 ConsumeParen();
937 if (mayBeAbstract &&
938 (Tok.is(tok::r_paren) || // 'int()' is a function.
939 // 'int(...)' is a function.
940 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
941 isDeclarationSpecifier(
942 ImplicitTypenameContext::No))) { // 'int(int)' is a function.
943 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
944 // exception-specification[opt]
945 TPResult TPR = TryParseFunctionDeclarator(mayHaveTrailingReturnType);
946 if (TPR != TPResult::Ambiguous)
947 return TPR;
948 } else {
949 // '(' declarator ')'
950 // '(' attributes declarator ')'
951 // '(' abstract-declarator ')'
952 if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec, tok::kw___cdecl,
953 tok::kw___stdcall, tok::kw___fastcall, tok::kw___thiscall,
954 tok::kw___regcall, tok::kw___vectorcall))
955 return TPResult::True; // attributes indicate declaration
956 TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
957 if (TPR != TPResult::Ambiguous)
958 return TPR;
959 if (Tok.isNot(tok::r_paren))
960 return TPResult::False;
961 ConsumeParen();
962 }
963 } else if (!mayBeAbstract) {
964 return TPResult::False;
965 }
966
967 if (mayHaveDirectInit)
968 return TPResult::Ambiguous;
969
970 while (true) {
971 TPResult TPR(TPResult::Ambiguous);
972
973 if (Tok.is(tok::l_paren)) {
974 // Check whether we have a function declarator or a possible ctor-style
975 // initializer that follows the declarator. Note that ctor-style
976 // initializers are not possible in contexts where abstract declarators
977 // are allowed.
978 if (!mayBeAbstract && !isCXXFunctionDeclarator())
979 break;
980
981 // direct-declarator '(' parameter-declaration-clause ')'
982 // cv-qualifier-seq[opt] exception-specification[opt]
983 ConsumeParen();
984 TPR = TryParseFunctionDeclarator(mayHaveTrailingReturnType);
985 } else if (Tok.is(tok::l_square)) {
986 // direct-declarator '[' constant-expression[opt] ']'
987 // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
988 TPR = TryParseBracketDeclarator();
989 } else if (Tok.is(tok::kw_requires)) {
990 // declarator requires-clause
991 // A requires clause indicates a function declaration.
992 TPR = TPResult::True;
993 } else {
994 break;
995 }
996
997 if (TPR != TPResult::Ambiguous)
998 return TPR;
999 }
1000
1001 return TPResult::Ambiguous;
1002}
1003
1004bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
1005 return llvm::is_contained(TentativelyDeclaredIdentifiers, II);
1006}
1007
1008namespace {
1009class TentativeParseCCC final : public CorrectionCandidateCallback {
1010public:
1011 TentativeParseCCC(const Token &Next) {
1012 WantRemainingKeywords = false;
1013 WantTypeSpecifiers =
1014 Next.isOneOf(tok::l_paren, tok::r_paren, tok::greater, tok::l_brace,
1015 tok::identifier, tok::comma);
1016 }
1017
1018 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1019 // Reject any candidate that only resolves to instance members since they
1020 // aren't viable as standalone identifiers instead of member references.
1021 if (Candidate.isResolved() && !Candidate.isKeyword() &&
1022 llvm::all_of(Candidate,
1023 [](NamedDecl *ND) { return ND->isCXXInstanceMember(); }))
1024 return false;
1025
1027 }
1028
1029 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1030 return std::make_unique<TentativeParseCCC>(*this);
1031 }
1032};
1033}
1034
1035Parser::TPResult
1036Parser::isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
1037 Parser::TPResult BracedCastResult,
1038 bool *InvalidAsDeclSpec) {
1039 auto IsPlaceholderSpecifier = [&](TemplateIdAnnotation *TemplateId,
1040 int Lookahead) {
1041 // We have a placeholder-constraint (we check for 'auto' or 'decltype' to
1042 // distinguish 'C<int>;' from 'C<int> auto c = 1;')
1043 return TemplateId->Kind == TNK_Concept_template &&
1044 (GetLookAheadToken(Lookahead + 1)
1045 .isOneOf(tok::kw_auto, tok::kw_decltype,
1046 // If we have an identifier here, the user probably
1047 // forgot the 'auto' in the placeholder constraint,
1048 // e.g. 'C<int> x = 2;' This will be diagnosed nicely
1049 // later, so disambiguate as a declaration.
1050 tok::identifier,
1051 // CVR qualifierslikely the same situation for the
1052 // user, so let this be diagnosed nicely later. We
1053 // cannot handle references here, as `C<int> & Other`
1054 // and `C<int> && Other` are both legal.
1055 tok::kw_const, tok::kw_volatile, tok::kw_restrict) ||
1056 // While `C<int> && Other` is legal, doing so while not specifying a
1057 // template argument is NOT, so see if we can fix up in that case at
1058 // minimum. Concepts require at least 1 template parameter, so we
1059 // can count on the argument count.
1060 // FIXME: In the future, we migth be able to have SEMA look up the
1061 // declaration for this concept, and see how many template
1062 // parameters it has. If the concept isn't fully specified, it is
1063 // possibly a situation where we want deduction, such as:
1064 // `BinaryConcept<int> auto f = bar();`
1065 (TemplateId->NumArgs == 0 &&
1066 GetLookAheadToken(Lookahead + 1).isOneOf(tok::amp, tok::ampamp)));
1067 };
1068 switch (Tok.getKind()) {
1069 case tok::identifier: {
1070 if (GetLookAheadToken(1).is(tok::ellipsis) &&
1071 GetLookAheadToken(2).is(tok::l_square)) {
1072
1074 return TPResult::Error;
1075 if (Tok.is(tok::identifier))
1076 return TPResult::False;
1077 return isCXXDeclarationSpecifier(ImplicitTypenameContext::No,
1078 BracedCastResult, InvalidAsDeclSpec);
1079 }
1080
1081 // Check for need to substitute AltiVec __vector keyword
1082 // for "vector" identifier.
1083 if (TryAltiVecVectorToken())
1084 return TPResult::True;
1085
1086 const Token &Next = NextToken();
1087 // In 'foo bar', 'foo' is always a type name outside of Objective-C.
1088 if (!getLangOpts().ObjC && Next.is(tok::identifier))
1089 return TPResult::True;
1090
1091 // If this identifier was reverted from a token ID, and the next token
1092 // is a '(', we assume it to be a use of a type trait, so this
1093 // can never be a type name.
1094 if (Next.is(tok::l_paren) &&
1095 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier() &&
1096 isRevertibleTypeTrait(Tok.getIdentifierInfo())) {
1097 return TPResult::False;
1098 }
1099
1100 if (Next.isNoneOf(tok::coloncolon, tok::less, tok::colon)) {
1101 // Determine whether this is a valid expression. If not, we will hit
1102 // a parse error one way or another. In that case, tell the caller that
1103 // this is ambiguous. Typo-correct to type and expression keywords and
1104 // to types and identifiers, in order to try to recover from errors.
1105 TentativeParseCCC CCC(Next);
1106 switch (TryAnnotateName(&CCC)) {
1108 return TPResult::Error;
1110 return TPResult::False;
1112 // In C++17, this could be a type template for class template argument
1113 // deduction. Try to form a type annotation for it. If we're in a
1114 // template template argument, we'll undo this when checking the
1115 // validity of the argument.
1116 if (getLangOpts().CPlusPlus17) {
1117 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
1118 return TPResult::Error;
1119 if (Tok.isNot(tok::identifier))
1120 break;
1121 }
1122
1123 // A bare type template-name which can't be a template template
1124 // argument is an error, and was probably intended to be a type.
1125 return GreaterThanIsOperator ? TPResult::True : TPResult::False;
1127 return InvalidAsDeclSpec ? TPResult::Ambiguous : TPResult::False;
1129 break;
1130 }
1131 assert(Tok.isNot(tok::identifier) &&
1132 "TryAnnotateName succeeded without producing an annotation");
1133 } else {
1134 // This might possibly be a type with a dependent scope specifier and
1135 // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1136 // since it will annotate as a primary expression, and we want to use the
1137 // "missing 'typename'" logic.
1138 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
1139 return TPResult::Error;
1140 // If annotation failed, assume it's a non-type.
1141 // FIXME: If this happens due to an undeclared identifier, treat it as
1142 // ambiguous.
1143 if (Tok.is(tok::identifier))
1144 return TPResult::False;
1145 }
1146
1147 // We annotated this token as something. Recurse to handle whatever we got.
1148 return isCXXDeclarationSpecifier(AllowImplicitTypename, BracedCastResult,
1149 InvalidAsDeclSpec);
1150 }
1151
1152 case tok::kw_typename: // typename T::type
1153 // Annotate typenames and C++ scope specifiers. If we get one, just
1154 // recurse to handle whatever we get.
1156 return TPResult::Error;
1157 return isCXXDeclarationSpecifier(ImplicitTypenameContext::Yes,
1158 BracedCastResult, InvalidAsDeclSpec);
1159
1160 case tok::kw_auto: {
1161 if (NextToken().is(tok::l_brace))
1162 return TPResult::False;
1163 if (NextToken().is(tok::l_paren))
1164 return TPResult::Ambiguous;
1165 return TPResult::True;
1166 }
1167
1168 case tok::coloncolon: { // ::foo::bar
1169 const Token &Next = NextToken();
1170 if (Next.isOneOf(tok::kw_new, // ::new
1171 tok::kw_delete)) // ::delete
1172 return TPResult::False;
1173 [[fallthrough]];
1174 }
1175 case tok::kw___super:
1176 case tok::kw_decltype:
1177 // Annotate typenames and C++ scope specifiers. If we get one, just
1178 // recurse to handle whatever we get.
1179 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
1180 return TPResult::Error;
1181 return isCXXDeclarationSpecifier(AllowImplicitTypename, BracedCastResult,
1182 InvalidAsDeclSpec);
1183
1184 // decl-specifier:
1185 // storage-class-specifier
1186 // type-specifier
1187 // function-specifier
1188 // 'friend'
1189 // 'typedef'
1190 // 'constexpr'
1191 case tok::kw_friend:
1192 case tok::kw_typedef:
1193 case tok::kw_constexpr:
1194 case tok::kw_consteval:
1195 case tok::kw_constinit:
1196 // storage-class-specifier
1197 case tok::kw_register:
1198 case tok::kw_static:
1199 case tok::kw_extern:
1200 case tok::kw_mutable:
1201 case tok::kw___thread:
1202 case tok::kw_thread_local:
1203 case tok::kw__Thread_local:
1204 // function-specifier
1205 case tok::kw_inline:
1206 case tok::kw_virtual:
1207 case tok::kw_explicit:
1208 case tok::kw__Noreturn:
1209
1210 // Modules
1211 case tok::kw___module_private__:
1212
1213 // Debugger support
1214 case tok::kw___unknown_anytype:
1215
1216 // type-specifier:
1217 // simple-type-specifier
1218 // class-specifier
1219 // enum-specifier
1220 // elaborated-type-specifier
1221 // typename-specifier
1222 // cv-qualifier
1223
1224 // class-specifier
1225 // elaborated-type-specifier
1226 case tok::kw_class:
1227 case tok::kw_struct:
1228 case tok::kw_union:
1229 case tok::kw___interface:
1230 // enum-specifier
1231 case tok::kw_enum:
1232 // cv-qualifier
1233 case tok::kw_const:
1234 case tok::kw_volatile:
1235 return TPResult::True;
1236
1237 // OpenCL address space qualifiers
1238 case tok::kw_private:
1239 if (!getLangOpts().OpenCL)
1240 return TPResult::False;
1241 [[fallthrough]];
1242 case tok::kw___private:
1243 case tok::kw___local:
1244 case tok::kw___global:
1245 case tok::kw___constant:
1246 case tok::kw___generic:
1247 // OpenCL access qualifiers
1248 case tok::kw___read_only:
1249 case tok::kw___write_only:
1250 case tok::kw___read_write:
1251 // OpenCL pipe
1252 case tok::kw_pipe:
1253
1254 // HLSL address space qualifiers
1255 case tok::kw_groupshared:
1256 case tok::kw_in:
1257 case tok::kw_inout:
1258 case tok::kw_out:
1259 // HLSL matrix layout qualifiers
1260 case tok::kw_row_major:
1261 case tok::kw_column_major:
1262
1263 // GNU
1264 case tok::kw_restrict:
1265 case tok::kw__Complex:
1266 case tok::kw__Imaginary:
1267 case tok::kw___attribute:
1268 case tok::kw___auto_type:
1269 return TPResult::True;
1270
1271 // OverflowBehaviorTypes
1272 case tok::kw___ob_wrap:
1273 case tok::kw___ob_trap:
1274 return TPResult::True;
1275
1276 // Microsoft
1277 case tok::kw___declspec:
1278 case tok::kw___cdecl:
1279 case tok::kw___stdcall:
1280 case tok::kw___fastcall:
1281 case tok::kw___thiscall:
1282 case tok::kw___regcall:
1283 case tok::kw___vectorcall:
1284 case tok::kw___w64:
1285 case tok::kw___sptr:
1286 case tok::kw___uptr:
1287 case tok::kw___ptr64:
1288 case tok::kw___ptr32:
1289 case tok::kw___forceinline:
1290 case tok::kw___unaligned:
1291 case tok::kw__Nonnull:
1292 case tok::kw__Nullable:
1293 case tok::kw__Nullable_result:
1294 case tok::kw__Null_unspecified:
1295 case tok::kw___kindof:
1296 return TPResult::True;
1297
1298 // WebAssemblyFuncref
1299 case tok::kw___funcref:
1300 return TPResult::True;
1301
1302 // Borland
1303 case tok::kw___pascal:
1304 return TPResult::True;
1305
1306 // AltiVec
1307 case tok::kw___vector:
1308 return TPResult::True;
1309
1310 case tok::kw_this: {
1311 // Try to parse a C++23 Explicit Object Parameter
1312 // We do that in all language modes to produce a better diagnostic.
1313 if (getLangOpts().CPlusPlus) {
1314 RevertingTentativeParsingAction PA(*this);
1315 ConsumeToken();
1316 return isCXXDeclarationSpecifier(AllowImplicitTypename, BracedCastResult,
1317 InvalidAsDeclSpec);
1318 }
1319 return TPResult::False;
1320 }
1321 case tok::annot_template_id: {
1322 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1323 // If lookup for the template-name found nothing, don't assume we have a
1324 // definitive disambiguation result yet.
1325 if ((TemplateId->hasInvalidName() ||
1326 TemplateId->Kind == TNK_Undeclared_template) &&
1327 InvalidAsDeclSpec) {
1328 // 'template-id(' can be a valid expression but not a valid decl spec if
1329 // the template-name is not declared, but we don't consider this to be a
1330 // definitive disambiguation. In any other context, it's an error either
1331 // way.
1332 *InvalidAsDeclSpec = NextToken().is(tok::l_paren);
1333 return TPResult::Ambiguous;
1334 }
1335 if (TemplateId->hasInvalidName())
1336 return TPResult::Error;
1337 if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/0))
1338 return TPResult::True;
1339 if (TemplateId->Kind != TNK_Type_template)
1340 return TPResult::False;
1341 CXXScopeSpec SS;
1342 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
1343 assert(Tok.is(tok::annot_typename));
1344 goto case_typename;
1345 }
1346
1347 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1348 // We've already annotated a scope; try to annotate a type.
1349 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
1350 return TPResult::Error;
1351 if (!Tok.is(tok::annot_typename)) {
1352 if (Tok.is(tok::annot_cxxscope) &&
1353 NextToken().is(tok::annot_template_id)) {
1354 TemplateIdAnnotation *TemplateId =
1355 takeTemplateIdAnnotation(NextToken());
1356 if (TemplateId->hasInvalidName()) {
1357 if (InvalidAsDeclSpec) {
1358 *InvalidAsDeclSpec = NextToken().is(tok::l_paren);
1359 return TPResult::Ambiguous;
1360 }
1361 return TPResult::Error;
1362 }
1363 if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/1))
1364 return TPResult::True;
1365 }
1366 // If the next token is an identifier or a type qualifier, then this
1367 // can't possibly be a valid expression either.
1368 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1369 CXXScopeSpec SS;
1370 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1371 Tok.getAnnotationRange(),
1372 SS);
1373 if (SS.getScopeRep().isDependent()) {
1374 RevertingTentativeParsingAction PA(*this);
1375 ConsumeAnnotationToken();
1376 ConsumeToken();
1377 bool isIdentifier = Tok.is(tok::identifier);
1378 TPResult TPR = TPResult::False;
1379 if (!isIdentifier)
1380 TPR = isCXXDeclarationSpecifier(
1381 AllowImplicitTypename, BracedCastResult, InvalidAsDeclSpec);
1382
1383 if (isIdentifier ||
1384 TPR == TPResult::True || TPR == TPResult::Error)
1385 return TPResult::Error;
1386
1387 if (InvalidAsDeclSpec) {
1388 // We can't tell whether this is a missing 'typename' or a valid
1389 // expression.
1390 *InvalidAsDeclSpec = true;
1391 return TPResult::Ambiguous;
1392 } else {
1393 // In MS mode, if InvalidAsDeclSpec is not provided, and the tokens
1394 // are or the form *) or &) *> or &> &&>, this can't be an expression.
1395 // The typename must be missing.
1396 if (getLangOpts().MSVCCompat) {
1397 if (((Tok.is(tok::amp) || Tok.is(tok::star)) &&
1398 (NextToken().is(tok::r_paren) ||
1399 NextToken().is(tok::greater))) ||
1400 (Tok.is(tok::ampamp) && NextToken().is(tok::greater)))
1401 return TPResult::True;
1402 }
1403 }
1404 } else {
1405 // Try to resolve the name. If it doesn't exist, assume it was
1406 // intended to name a type and keep disambiguating.
1407 switch (TryAnnotateName(/*CCC=*/nullptr, AllowImplicitTypename)) {
1409 return TPResult::Error;
1411 return TPResult::False;
1413 // In C++17, this could be a type template for class template
1414 // argument deduction.
1415 if (getLangOpts().CPlusPlus17) {
1417 return TPResult::Error;
1418 // If we annotated then the current token should not still be ::
1419 // FIXME we may want to also check for tok::annot_typename but
1420 // currently don't have a test case.
1421 if (Tok.isNot(tok::annot_cxxscope) && Tok.isNot(tok::identifier))
1422 break;
1423 }
1424
1425 // A bare type template-name which can't be a template template
1426 // argument is an error, and was probably intended to be a type.
1427 // In C++17, this could be class template argument deduction.
1428 return (getLangOpts().CPlusPlus17 || GreaterThanIsOperator)
1429 ? TPResult::True
1430 : TPResult::False;
1432 return InvalidAsDeclSpec ? TPResult::Ambiguous : TPResult::False;
1434 break;
1435 }
1436
1437 // Annotated it, check again.
1438 assert(Tok.isNot(tok::annot_cxxscope) ||
1439 NextToken().isNot(tok::identifier));
1440 return isCXXDeclarationSpecifier(AllowImplicitTypename,
1441 BracedCastResult, InvalidAsDeclSpec);
1442 }
1443 }
1444 return TPResult::False;
1445 }
1446 // If that succeeded, fallthrough into the generic simple-type-id case.
1447 [[fallthrough]];
1448
1449 // The ambiguity resides in a simple-type-specifier/typename-specifier
1450 // followed by a '('. The '(' could either be the start of:
1451 //
1452 // direct-declarator:
1453 // '(' declarator ')'
1454 //
1455 // direct-abstract-declarator:
1456 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1457 // exception-specification[opt]
1458 // '(' abstract-declarator ')'
1459 //
1460 // or part of a function-style cast expression:
1461 //
1462 // simple-type-specifier '(' expression-list[opt] ')'
1463 //
1464
1465 // simple-type-specifier:
1466
1467 case tok::annot_typename:
1468 case_typename:
1469 // In Objective-C, we might have a protocol-qualified type.
1470 if (getLangOpts().ObjC && NextToken().is(tok::less)) {
1471 // Tentatively parse the protocol qualifiers.
1472 RevertingTentativeParsingAction PA(*this);
1473 ConsumeAnyToken(); // The type token
1474
1475 TPResult TPR = TryParseProtocolQualifiers();
1476 bool isFollowedByParen = Tok.is(tok::l_paren);
1477 bool isFollowedByBrace = Tok.is(tok::l_brace);
1478
1479 if (TPR == TPResult::Error)
1480 return TPResult::Error;
1481
1482 if (isFollowedByParen)
1483 return TPResult::Ambiguous;
1484
1485 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1486 return BracedCastResult;
1487
1488 return TPResult::True;
1489 }
1490
1491 [[fallthrough]];
1492
1493 case tok::kw_char:
1494 case tok::kw_wchar_t:
1495 case tok::kw_char8_t:
1496 case tok::kw_char16_t:
1497 case tok::kw_char32_t:
1498 case tok::kw_bool:
1499 case tok::kw_short:
1500 case tok::kw_int:
1501 case tok::kw_long:
1502 case tok::kw___int64:
1503 case tok::kw___int128:
1504 case tok::kw_signed:
1505 case tok::kw_unsigned:
1506 case tok::kw_half:
1507 case tok::kw_float:
1508 case tok::kw_double:
1509 case tok::kw___bf16:
1510 case tok::kw__Float16:
1511 case tok::kw___float128:
1512 case tok::kw___ibm128:
1513 case tok::kw_void:
1514 case tok::annot_decltype:
1515 case tok::kw__Accum:
1516 case tok::kw__Fract:
1517 case tok::kw__Sat:
1518 case tok::annot_pack_indexing_type:
1519#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1520#include "clang/Basic/OpenCLImageTypes.def"
1521#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
1522#include "clang/Basic/HLSLIntangibleTypes.def"
1523 if (NextToken().is(tok::l_paren))
1524 return TPResult::Ambiguous;
1525
1526 // This is a function-style cast in all cases we disambiguate other than
1527 // one:
1528 // struct S {
1529 // enum E : int { a = 4 }; // enum
1530 // enum E : int { 4 }; // bit-field
1531 // };
1532 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
1533 return BracedCastResult;
1534
1535 if (isStartOfObjCClassMessageMissingOpenBracket())
1536 return TPResult::False;
1537
1538 return TPResult::True;
1539
1540 // GNU typeof support.
1541 case tok::kw_typeof:
1542 case tok::kw_typeof_unqual: {
1543 if (NextToken().isNot(tok::l_paren))
1544 return TPResult::True;
1545
1546 RevertingTentativeParsingAction PA(*this);
1547
1548 TPResult TPR = TryParseTypeofSpecifier();
1549 bool isFollowedByParen = Tok.is(tok::l_paren);
1550 bool isFollowedByBrace = Tok.is(tok::l_brace);
1551
1552 if (TPR == TPResult::Error)
1553 return TPResult::Error;
1554
1555 if (isFollowedByParen)
1556 return TPResult::Ambiguous;
1557
1558 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1559 return BracedCastResult;
1560
1561 return TPResult::True;
1562 }
1563
1564#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
1565#include "clang/Basic/BuiltinTraits.inc"
1566 return TPResult::True;
1567
1568 // C11 _Alignas
1569 case tok::kw__Alignas:
1570 return TPResult::True;
1571 // C11 _Atomic
1572 case tok::kw__Atomic:
1573 return TPResult::True;
1574
1575 case tok::kw__BitInt:
1576 case tok::kw__ExtInt: {
1577 if (NextToken().isNot(tok::l_paren))
1578 return TPResult::Error;
1579 RevertingTentativeParsingAction PA(*this);
1580 ConsumeToken();
1581 ConsumeParen();
1582
1583 if (!SkipUntil(tok::r_paren, StopAtSemi))
1584 return TPResult::Error;
1585
1586 if (Tok.is(tok::l_paren))
1587 return TPResult::Ambiguous;
1588
1589 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
1590 return BracedCastResult;
1591
1592 return TPResult::True;
1593 }
1594 default:
1595 return TPResult::False;
1596 }
1597}
1598
1599bool Parser::isCXXDeclarationSpecifierAType() {
1600 switch (Tok.getKind()) {
1601 // typename-specifier
1602 case tok::annot_decltype:
1603 case tok::annot_pack_indexing_type:
1604 case tok::annot_template_id:
1605 case tok::annot_typename:
1606 case tok::kw_typeof:
1607 case tok::kw_typeof_unqual:
1608#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
1609#include "clang/Basic/BuiltinTraits.inc"
1610 return true;
1611
1612 // elaborated-type-specifier
1613 case tok::kw_class:
1614 case tok::kw_struct:
1615 case tok::kw_union:
1616 case tok::kw___interface:
1617 case tok::kw_enum:
1618 return true;
1619
1620 // simple-type-specifier
1621 case tok::kw_char:
1622 case tok::kw_wchar_t:
1623 case tok::kw_char8_t:
1624 case tok::kw_char16_t:
1625 case tok::kw_char32_t:
1626 case tok::kw_bool:
1627 case tok::kw_short:
1628 case tok::kw_int:
1629 case tok::kw__ExtInt:
1630 case tok::kw__BitInt:
1631 case tok::kw_long:
1632 case tok::kw___int64:
1633 case tok::kw___int128:
1634 case tok::kw_signed:
1635 case tok::kw_unsigned:
1636 case tok::kw_half:
1637 case tok::kw_float:
1638 case tok::kw_double:
1639 case tok::kw___bf16:
1640 case tok::kw__Float16:
1641 case tok::kw___float128:
1642 case tok::kw___ibm128:
1643 case tok::kw_void:
1644 case tok::kw___unknown_anytype:
1645 case tok::kw___auto_type:
1646 case tok::kw__Accum:
1647 case tok::kw__Fract:
1648 case tok::kw__Sat:
1649#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1650#include "clang/Basic/OpenCLImageTypes.def"
1651#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
1652#include "clang/Basic/HLSLIntangibleTypes.def"
1653 return true;
1654
1655 case tok::kw_auto:
1656 return getLangOpts().CPlusPlus11;
1657
1658 case tok::kw__Atomic:
1659 // "_Atomic foo"
1660 return NextToken().is(tok::l_paren);
1661
1662 default:
1663 return false;
1664 }
1665}
1666
1667Parser::TPResult Parser::TryParseTypeofSpecifier() {
1668 assert(Tok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
1669 "Expected 'typeof' or 'typeof_unqual'!");
1670 ConsumeToken();
1671
1672 assert(Tok.is(tok::l_paren) && "Expected '('");
1673 // Parse through the parens after 'typeof'.
1674 ConsumeParen();
1675 if (!SkipUntil(tok::r_paren, StopAtSemi))
1676 return TPResult::Error;
1677
1678 return TPResult::Ambiguous;
1679}
1680
1681Parser::TPResult Parser::TryParseProtocolQualifiers() {
1682 assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1683 ConsumeToken();
1684 do {
1685 if (Tok.isNot(tok::identifier))
1686 return TPResult::Error;
1687 ConsumeToken();
1688
1689 if (Tok.is(tok::comma)) {
1690 ConsumeToken();
1691 continue;
1692 }
1693
1694 if (Tok.is(tok::greater)) {
1695 ConsumeToken();
1696 return TPResult::Ambiguous;
1697 }
1698 } while (false);
1699
1700 return TPResult::Error;
1701}
1702
1703bool Parser::isCXXFunctionDeclarator(
1704 bool *IsAmbiguous, ImplicitTypenameContext AllowImplicitTypename) {
1705
1706 // C++ 8.2p1:
1707 // The ambiguity arising from the similarity between a function-style cast and
1708 // a declaration mentioned in 6.8 can also occur in the context of a
1709 // declaration. In that context, the choice is between a function declaration
1710 // with a redundant set of parentheses around a parameter name and an object
1711 // declaration with a function-style cast as the initializer. Just as for the
1712 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1713 // that could possibly be a declaration a declaration.
1714
1715 RevertingTentativeParsingAction PA(*this);
1716
1717 ConsumeParen();
1718 bool InvalidAsDeclaration = false;
1719 TPResult TPR = TryParseParameterDeclarationClause(
1720 &InvalidAsDeclaration, /*VersusTemplateArgument=*/false,
1721 AllowImplicitTypename);
1722 if (TPR == TPResult::Ambiguous) {
1723 if (Tok.isNot(tok::r_paren))
1724 TPR = TPResult::False;
1725 else {
1726 const Token &Next = NextToken();
1727 if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile,
1728 tok::kw_throw, tok::kw_noexcept, tok::l_square,
1729 tok::l_brace, tok::kw_try, tok::equal, tok::arrow) ||
1730 isCXX11VirtSpecifier(Next))
1731 // The next token cannot appear after a constructor-style initializer,
1732 // and can appear next in a function definition. This must be a function
1733 // declarator.
1734 TPR = TPResult::True;
1735 else if (InvalidAsDeclaration)
1736 // Use the absence of 'typename' as a tie-breaker.
1737 TPR = TPResult::False;
1738 }
1739 }
1740
1741 if (IsAmbiguous && TPR == TPResult::Ambiguous)
1742 *IsAmbiguous = true;
1743
1744 // In case of an error, let the declaration parsing code handle it.
1745 return TPR != TPResult::False;
1746}
1747
1748Parser::TPResult Parser::TryParseParameterDeclarationClause(
1749 bool *InvalidAsDeclaration, bool VersusTemplateArgument,
1750 ImplicitTypenameContext AllowImplicitTypename) {
1751
1752 if (Tok.is(tok::r_paren))
1753 return TPResult::Ambiguous;
1754
1755 // parameter-declaration-list[opt] '...'[opt]
1756 // parameter-declaration-list ',' '...'
1757 //
1758 // parameter-declaration-list:
1759 // parameter-declaration
1760 // parameter-declaration-list ',' parameter-declaration
1761 //
1762 while (true) {
1763 // '...'[opt]
1764 if (Tok.is(tok::ellipsis)) {
1765 ConsumeToken();
1766 if (Tok.is(tok::r_paren))
1767 return TPResult::True; // '...)' is a sign of a function declarator.
1768 else
1769 return TPResult::False;
1770 }
1771
1772 // An attribute-specifier-seq here is a sign of a function declarator.
1773 if (isCXX11AttributeSpecifier(/*Disambiguate*/ false,
1774 /*OuterMightBeMessageSend*/ true) !=
1776 return TPResult::True;
1777
1778 ParsedAttributes attrs(AttrFactory);
1779 MaybeParseMicrosoftAttributes(attrs);
1780
1781 // decl-specifier-seq
1782 // A parameter-declaration's initializer must be preceded by an '=', so
1783 // decl-specifier-seq '{' is not a parameter in C++11.
1784 TPResult TPR = isCXXDeclarationSpecifier(
1785 AllowImplicitTypename, TPResult::False, InvalidAsDeclaration);
1786 // A declaration-specifier (not followed by '(' or '{') means this can't be
1787 // an expression, but it could still be a template argument.
1788 if (TPR != TPResult::Ambiguous &&
1789 !(VersusTemplateArgument && TPR == TPResult::True))
1790 return TPR;
1791
1792 bool SeenType = false;
1793 bool DeclarationSpecifierIsAuto = Tok.is(tok::kw_auto);
1794 do {
1795 SeenType |= isCXXDeclarationSpecifierAType();
1796 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
1797 return TPResult::Error;
1798
1799 // If we see a parameter name, this can't be a template argument.
1800 if (SeenType && Tok.is(tok::identifier))
1801 return TPResult::True;
1802
1803 TPR = isCXXDeclarationSpecifier(AllowImplicitTypename, TPResult::False,
1804 InvalidAsDeclaration);
1805 if (TPR == TPResult::Error)
1806 return TPR;
1807
1808 // Two declaration-specifiers means this can't be an expression.
1809 if (TPR == TPResult::True && !VersusTemplateArgument)
1810 return TPR;
1811 } while (TPR != TPResult::False);
1812
1813 // declarator
1814 // abstract-declarator[opt]
1815 TPR = TryParseDeclarator(
1816 /*mayBeAbstract=*/true,
1817 /*mayHaveIdentifier=*/true,
1818 /*mayHaveDirectInit=*/false,
1819 /*mayHaveTrailingReturnType=*/DeclarationSpecifierIsAuto);
1820 if (TPR != TPResult::Ambiguous)
1821 return TPR;
1822
1823 // [GNU] attributes[opt]
1824 if (Tok.is(tok::kw___attribute))
1825 return TPResult::True;
1826
1827 // If we're disambiguating a template argument in a default argument in
1828 // a class definition versus a parameter declaration, an '=' here
1829 // disambiguates the parse one way or the other.
1830 // If this is a parameter, it must have a default argument because
1831 // (a) the previous parameter did, and
1832 // (b) this must be the first declaration of the function, so we can't
1833 // inherit any default arguments from elsewhere.
1834 // FIXME: If we reach a ')' without consuming any '>'s, then this must
1835 // also be a function parameter (that's missing its default argument).
1836 if (VersusTemplateArgument)
1837 return Tok.is(tok::equal) ? TPResult::True : TPResult::False;
1838
1839 if (Tok.is(tok::equal)) {
1840 // '=' assignment-expression
1841 // Parse through assignment-expression.
1842 if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
1843 return TPResult::Error;
1844 }
1845
1846 if (Tok.is(tok::ellipsis)) {
1847 ConsumeToken();
1848 if (Tok.is(tok::r_paren))
1849 return TPResult::True; // '...)' is a sign of a function declarator.
1850 else
1851 return TPResult::False;
1852 }
1853
1854 if (!TryConsumeToken(tok::comma))
1855 break;
1856 }
1857
1858 return TPResult::Ambiguous;
1859}
1860
1861Parser::TPResult
1862Parser::TryParseFunctionDeclarator(bool MayHaveTrailingReturnType) {
1863 // The '(' is already parsed.
1864
1865 TPResult TPR = TryParseParameterDeclarationClause();
1866 if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
1867 TPR = TPResult::False;
1868
1869 if (TPR == TPResult::False || TPR == TPResult::Error)
1870 return TPR;
1871
1872 // Parse through the parens.
1873 if (!SkipUntil(tok::r_paren, StopAtSemi))
1874 return TPResult::Error;
1875
1876 // cv-qualifier-seq
1877 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw___unaligned,
1878 tok::kw_restrict))
1879 ConsumeToken();
1880
1881 // ref-qualifier[opt]
1882 if (Tok.isOneOf(tok::amp, tok::ampamp))
1883 ConsumeToken();
1884
1885 // exception-specification
1886 if (Tok.is(tok::kw_throw)) {
1887 ConsumeToken();
1888 if (Tok.isNot(tok::l_paren))
1889 return TPResult::Error;
1890
1891 // Parse through the parens after 'throw'.
1892 ConsumeParen();
1893 if (!SkipUntil(tok::r_paren, StopAtSemi))
1894 return TPResult::Error;
1895 }
1896 if (Tok.is(tok::kw_noexcept)) {
1897 ConsumeToken();
1898 // Possibly an expression as well.
1899 if (Tok.is(tok::l_paren)) {
1900 // Find the matching rparen.
1901 ConsumeParen();
1902 if (!SkipUntil(tok::r_paren, StopAtSemi))
1903 return TPResult::Error;
1904 }
1905 }
1906
1907 // attribute-specifier-seq
1908 if (!TrySkipAttributes())
1909 return TPResult::Ambiguous;
1910
1911 // trailing-return-type
1912 if (Tok.is(tok::arrow) && MayHaveTrailingReturnType) {
1913 if (TPR == TPResult::True)
1914 return TPR;
1915 ConsumeToken();
1916 if (Tok.is(tok::identifier) && NameAfterArrowIsNonType()) {
1917 return TPResult::False;
1918 }
1920 return TPResult::True;
1921 }
1922
1923 return TPResult::Ambiguous;
1924}
1925
1926bool Parser::NameAfterArrowIsNonType() {
1927 assert(Tok.is(tok::identifier));
1928 Token Next = NextToken();
1929 if (Next.is(tok::coloncolon))
1930 return false;
1931 IdentifierInfo *Name = Tok.getIdentifierInfo();
1932 SourceLocation NameLoc = Tok.getLocation();
1933 CXXScopeSpec SS;
1934 TentativeParseCCC CCC(Next);
1935 Sema::NameClassification Classification =
1936 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next, &CCC);
1937 switch (Classification.getKind()) {
1942 return true;
1943 default:
1944 break;
1945 }
1946 return false;
1947}
1948
1949Parser::TPResult Parser::TryParseBracketDeclarator() {
1950 ConsumeBracket();
1951
1952 // A constant-expression cannot begin with a '{', but the
1953 // expr-or-braced-init-list of a postfix-expression can.
1954 if (Tok.is(tok::l_brace))
1955 return TPResult::False;
1956
1957 if (!SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch))
1958 return TPResult::Error;
1959
1960 // If we hit a comma before the ']', this is not a constant-expression,
1961 // but might still be the expr-or-braced-init-list of a postfix-expression.
1962 if (Tok.isNot(tok::r_square))
1963 return TPResult::False;
1964
1965 ConsumeBracket();
1966 return TPResult::Ambiguous;
1967}
1968
1969Parser::TPResult Parser::isTemplateArgumentList(unsigned TokensToSkip) {
1970 if (!TokensToSkip) {
1971 if (Tok.isNot(tok::less))
1972 return TPResult::False;
1973 if (NextToken().is(tok::greater))
1974 return TPResult::True;
1975 }
1976
1977 RevertingTentativeParsingAction PA(*this);
1978
1979 while (TokensToSkip) {
1981 --TokensToSkip;
1982 }
1983
1984 if (!TryConsumeToken(tok::less))
1985 return TPResult::False;
1986
1987 // We can't do much to tell an expression apart from a template-argument,
1988 // but one good distinguishing factor is that a "decl-specifier" not
1989 // followed by '(' or '{' can't appear in an expression.
1990 bool InvalidAsTemplateArgumentList = false;
1991 if (isCXXDeclarationSpecifier(ImplicitTypenameContext::No, TPResult::False,
1992 &InvalidAsTemplateArgumentList) ==
1993 TPResult::True)
1994 return TPResult::True;
1995 if (InvalidAsTemplateArgumentList)
1996 return TPResult::False;
1997
1998 // FIXME: In many contexts, X<thing1, Type> can only be a
1999 // template-argument-list. But that's not true in general:
2000 //
2001 // using b = int;
2002 // void f() {
2003 // int a = A<B, b, c = C>D; // OK, declares b, not a template-id.
2004 //
2005 // X<Y<0, int> // ', int>' might be end of X's template argument list
2006 //
2007 // We might be able to disambiguate a few more cases if we're careful.
2008
2009 // A template-argument-list must be terminated by a '>'.
2010 if (SkipUntil({tok::greater, tok::greatergreater, tok::greatergreatergreater},
2012 return TPResult::Ambiguous;
2013 return TPResult::False;
2014}
2015
2016Parser::TPResult Parser::isExplicitBool() {
2017 assert(Tok.is(tok::l_paren) && "expected to be looking at a '(' token");
2018
2019 RevertingTentativeParsingAction PA(*this);
2020 ConsumeParen();
2021
2022 // We can only have 'explicit' on a constructor, conversion function, or
2023 // deduction guide. The declarator of a deduction guide cannot be
2024 // parenthesized, so we know this isn't a deduction guide. So the only
2025 // thing we need to check for is some number of parens followed by either
2026 // the current class name or 'operator'.
2027 while (Tok.is(tok::l_paren))
2028 ConsumeParen();
2029
2031 return TPResult::Error;
2032
2033 // Class-scope constructor and conversion function names can't really be
2034 // qualified, but we get better diagnostics if we assume they can be.
2035 CXXScopeSpec SS;
2036 if (Tok.is(tok::annot_cxxscope)) {
2037 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2038 Tok.getAnnotationRange(),
2039 SS);
2040 ConsumeAnnotationToken();
2041 }
2042
2043 // 'explicit(operator' might be explicit(bool) or the declaration of a
2044 // conversion function, but it's probably a conversion function.
2045 if (Tok.is(tok::kw_operator))
2046 return TPResult::Ambiguous;
2047
2048 // If this can't be a constructor name, it can only be explicit(bool).
2049 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
2050 return TPResult::True;
2051 if (!Actions.isCurrentClassName(Tok.is(tok::identifier)
2052 ? *Tok.getIdentifierInfo()
2053 : *takeTemplateIdAnnotation(Tok)->Name,
2054 getCurScope(), &SS))
2055 return TPResult::True;
2056 // Formally, we must have a right-paren after the constructor name to match
2057 // the grammar for a constructor. But clang permits a parenthesized
2058 // constructor declarator, so also allow a constructor declarator to follow
2059 // with no ')' token after the constructor name.
2060 if (!NextToken().is(tok::r_paren) &&
2061 !isConstructorDeclarator(/*Unqualified=*/SS.isEmpty(),
2062 /*DeductionGuide=*/false))
2063 return TPResult::True;
2064
2065 // Might be explicit(bool) or a parenthesized constructor name.
2066 return TPResult::Ambiguous;
2067}
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:1872
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition Parser.h:347
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
Definition Parser.cpp:59
bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext=false)
Definition Parser.h:479
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition Parser.h:375
const Token & GetLookAheadToken(unsigned N)
GetLookAheadToken - This peeks ahead N tokens and returns that token without consuming any tokens.
Definition Parser.h:401
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:355
Scope * getCurScope() const
Definition Parser.h:296
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition Parser.h:591
const LangOptions & getLangOpts() const
Definition Parser.h:289
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition Parser.h:572
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:570
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:409
NameClassificationKind getKind() const
Definition Sema.h:3792
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.