1 //===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the tentative parsing portions of the Parser
10 // interfaces, for ambiguity resolution.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/Parse/ParseDiagnostic.h"
16 #include "clang/Sema/ParsedTemplate.h"
17 using namespace clang
;
19 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
20 /// between a declaration or an expression statement, when parsing function
21 /// bodies. Returns true for declaration, false for expression.
23 /// declaration-statement:
26 /// block-declaration:
27 /// simple-declaration
29 /// namespace-alias-definition
32 /// [C++0x] static_assert-declaration
35 /// 'asm' '(' string-literal ')' ';'
37 /// namespace-alias-definition:
38 /// 'namespace' identifier = qualified-namespace-specifier ';'
40 /// using-declaration:
41 /// 'using' typename[opt] '::'[opt] nested-name-specifier
42 /// unqualified-id ';'
43 /// 'using' '::' unqualified-id ;
46 /// 'using' 'namespace' '::'[opt] nested-name-specifier[opt]
47 /// namespace-name ';'
49 bool Parser::isCXXDeclarationStatement(
50 bool DisambiguatingWithExpression
/*=false*/) {
51 assert(getLangOpts().CPlusPlus
&& "Must be called for C++ only.");
53 switch (Tok
.getKind()) {
56 // namespace-alias-definition
57 case tok::kw_namespace
:
61 // static_assert-declaration
62 case tok::kw_static_assert
:
63 case tok::kw__Static_assert
:
66 case tok::identifier
: {
67 if (DisambiguatingWithExpression
) {
68 RevertingTentativeParsingAction
TPA(*this);
69 // Parse the C++ scope specifier.
71 ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
72 /*ObjectHasErrors=*/false,
73 /*EnteringContext=*/true);
75 switch (Tok
.getKind()) {
76 case tok::identifier
: {
77 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
78 bool isDeductionGuide
= Actions
.isDeductionGuideName(
79 getCurScope(), *II
, Tok
.getLocation(), SS
, /*Template=*/nullptr);
80 if (Actions
.isCurrentClassName(*II
, getCurScope(), &SS
) ||
82 if (isConstructorDeclarator(/*Unqualified=*/SS
.isEmpty(),
84 DeclSpec::FriendSpecified::No
))
86 } else if (SS
.isNotEmpty()) {
87 // If the scope is not empty, it could alternatively be something like
88 // a typedef or using declaration. That declaration might be private
89 // in the global context, which would be diagnosed by calling into
90 // isCXXSimpleDeclaration, but may actually be fine in the context of
91 // member functions and static variable definitions. Check if the next
92 // token is also an identifier and assume a declaration.
93 // We cannot check if the scopes match because the declarations could
94 // involve namespaces and friend declarations.
95 if (NextToken().is(tok::identifier
))
100 case tok::kw_operator
:
110 // simple-declaration
112 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
116 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
117 /// between a simple-declaration or an expression-statement.
118 /// If during the disambiguation process a parsing error is encountered,
119 /// the function returns true to let the declaration parsing code handle it.
120 /// Returns false if the statement is disambiguated as expression.
122 /// simple-declaration:
123 /// decl-specifier-seq init-declarator-list[opt] ';'
124 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
125 /// brace-or-equal-initializer ';' [C++17]
127 /// (if AllowForRangeDecl specified)
128 /// for ( for-range-declaration : for-range-initializer ) statement
130 /// for-range-declaration:
131 /// decl-specifier-seq declarator
132 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
134 /// In any of the above cases there can be a preceding attribute-specifier-seq,
135 /// but the caller is expected to handle that.
136 bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl
) {
138 // There is an ambiguity in the grammar involving expression-statements and
139 // declarations: An expression-statement with a function-style explicit type
140 // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
141 // from a declaration where the first declarator starts with a '('. In those
142 // cases the statement is a declaration. [Note: To disambiguate, the whole
143 // statement might have to be examined to determine if it is an
144 // expression-statement or a declaration].
147 // The disambiguation is purely syntactic; that is, the meaning of the names
148 // occurring in such a statement, beyond whether they are type-names or not,
149 // is not generally used in or changed by the disambiguation. Class
150 // templates are instantiated as necessary to determine if a qualified name
151 // is a type-name. Disambiguation precedes parsing, and a statement
152 // disambiguated as a declaration may be an ill-formed declaration.
154 // We don't have to parse all of the decl-specifier-seq part. There's only
155 // an ambiguity if the first decl-specifier is
156 // simple-type-specifier/typename-specifier followed by a '(', which may
157 // indicate a function-style cast expression.
158 // isCXXDeclarationSpecifier will return TPResult::Ambiguous only in such
161 bool InvalidAsDeclaration
= false;
162 TPResult TPR
= isCXXDeclarationSpecifier(
163 ImplicitTypenameContext::No
, TPResult::False
, &InvalidAsDeclaration
);
164 if (TPR
!= TPResult::Ambiguous
)
165 return TPR
!= TPResult::False
; // Returns true for TPResult::True or
168 // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer,
169 // and so gets some cases wrong. We can't carry on if we've already seen
170 // something which makes this statement invalid as a declaration in this case,
171 // since it can cause us to misparse valid code. Revisit this once
172 // TryParseInitDeclaratorList is fixed.
173 if (InvalidAsDeclaration
)
176 // FIXME: Add statistics about the number of ambiguous statements encountered
177 // and how they were resolved (number of declarations+number of expressions).
179 // Ok, we have a simple-type-specifier/typename-specifier followed by a '(',
180 // or an identifier which doesn't resolve as anything. We need tentative
184 RevertingTentativeParsingAction
PA(*this);
185 TPR
= TryParseSimpleDeclaration(AllowForRangeDecl
);
188 // In case of an error, let the declaration parsing code handle it.
189 if (TPR
== TPResult::Error
)
192 // Declarations take precedence over expressions.
193 if (TPR
== TPResult::Ambiguous
)
194 TPR
= TPResult::True
;
196 assert(TPR
== TPResult::True
|| TPR
== TPResult::False
);
197 return TPR
== TPResult::True
;
200 /// Try to consume a token sequence that we've already identified as
201 /// (potentially) starting a decl-specifier.
202 Parser::TPResult
Parser::TryConsumeDeclarationSpecifier() {
203 switch (Tok
.getKind()) {
204 case tok::kw__Atomic
:
205 if (NextToken().isNot(tok::l_paren
)) {
211 case tok::kw___attribute
:
212 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
213 #include "clang/Basic/TransformTypeTraits.def"
216 if (Tok
.isNot(tok::l_paren
))
217 return TPResult::Error
;
219 if (!SkipUntil(tok::r_paren
))
220 return TPResult::Error
;
227 case tok::kw___interface
:
229 // elaborated-type-specifier:
230 // class-key attribute-specifier-seq[opt]
231 // nested-name-specifier[opt] identifier
232 // class-key nested-name-specifier[opt] template[opt] simple-template-id
233 // enum nested-name-specifier[opt] identifier
235 // FIXME: We don't support class-specifiers nor enum-specifiers here.
239 if (!TrySkipAttributes())
240 return TPResult::Error
;
242 if (TryAnnotateOptionalCXXScopeToken())
243 return TPResult::Error
;
244 if (Tok
.is(tok::annot_cxxscope
))
245 ConsumeAnnotationToken();
246 if (Tok
.is(tok::identifier
))
248 else if (Tok
.is(tok::annot_template_id
))
249 ConsumeAnnotationToken();
251 return TPResult::Error
;
254 case tok::annot_cxxscope
:
255 ConsumeAnnotationToken();
260 if (getLangOpts().ObjC
&& Tok
.is(tok::less
))
261 return TryParseProtocolQualifiers();
265 return TPResult::Ambiguous
;
268 /// simple-declaration:
269 /// decl-specifier-seq init-declarator-list[opt] ';'
271 /// (if AllowForRangeDecl specified)
272 /// for ( for-range-declaration : for-range-initializer ) statement
273 /// for-range-declaration:
274 /// attribute-specifier-seqopt type-specifier-seq declarator
276 Parser::TPResult
Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl
) {
277 bool DeclSpecifierIsAuto
= Tok
.is(tok::kw_auto
);
278 if (TryConsumeDeclarationSpecifier() == TPResult::Error
)
279 return TPResult::Error
;
281 // Two decl-specifiers in a row conclusively disambiguate this as being a
282 // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
283 // overwhelmingly common case that the next token is a '('.
284 if (Tok
.isNot(tok::l_paren
)) {
285 TPResult TPR
= isCXXDeclarationSpecifier(ImplicitTypenameContext::No
);
286 if (TPR
== TPResult::Ambiguous
)
287 return TPResult::True
;
288 if (TPR
== TPResult::True
|| TPR
== TPResult::Error
)
290 assert(TPR
== TPResult::False
);
293 TPResult TPR
= TryParseInitDeclaratorList(
294 /*mayHaveTrailingReturnType=*/DeclSpecifierIsAuto
);
295 if (TPR
!= TPResult::Ambiguous
)
298 if (Tok
.isNot(tok::semi
) && (!AllowForRangeDecl
|| Tok
.isNot(tok::colon
)))
299 return TPResult::False
;
301 return TPResult::Ambiguous
;
304 /// Tentatively parse an init-declarator-list in order to disambiguate it from
307 /// init-declarator-list:
309 /// init-declarator-list ',' init-declarator
312 /// declarator initializer[opt]
313 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
316 /// brace-or-equal-initializer
317 /// '(' expression-list ')'
319 /// brace-or-equal-initializer:
320 /// '=' initializer-clause
321 /// [C++11] braced-init-list
323 /// initializer-clause:
324 /// assignment-expression
327 /// braced-init-list:
328 /// '{' initializer-list ','[opt] '}'
332 Parser::TryParseInitDeclaratorList(bool MayHaveTrailingReturnType
) {
335 TPResult TPR
= TryParseDeclarator(
336 /*mayBeAbstract=*/false,
337 /*mayHaveIdentifier=*/true,
338 /*mayHaveDirectInit=*/false,
339 /*mayHaveTrailingReturnType=*/MayHaveTrailingReturnType
);
340 if (TPR
!= TPResult::Ambiguous
)
343 // [GNU] simple-asm-expr[opt] attributes[opt]
344 if (Tok
.isOneOf(tok::kw_asm
, tok::kw___attribute
))
345 return TPResult::True
;
348 if (Tok
.is(tok::l_paren
)) {
349 // Parse through the parens.
351 if (!SkipUntil(tok::r_paren
, StopAtSemi
))
352 return TPResult::Error
;
353 } else if (Tok
.is(tok::l_brace
)) {
354 // A left-brace here is sufficient to disambiguate the parse; an
355 // expression can never be followed directly by a braced-init-list.
356 return TPResult::True
;
357 } else if (Tok
.is(tok::equal
) || isTokIdentifier_in()) {
358 // MSVC and g++ won't examine the rest of declarators if '=' is
359 // encountered; they just conclude that we have a declaration.
360 // EDG parses the initializer completely, which is the proper behavior
363 // At present, Clang follows MSVC and g++, since the parser does not have
364 // the ability to parse an expression fully without recording the
365 // results of that parse.
366 // FIXME: Handle this case correctly.
368 // Also allow 'in' after an Objective-C declaration as in:
369 // for (int (^b)(void) in array). Ideally this should be done in the
370 // context of parsing for-init-statement of a foreach statement only. But,
371 // in any other context 'in' is invalid after a declaration and parser
372 // issues the error regardless of outcome of this decision.
373 // FIXME: Change if above assumption does not hold.
374 return TPResult::True
;
377 if (!TryConsumeToken(tok::comma
))
381 return TPResult::Ambiguous
;
384 struct Parser::ConditionDeclarationOrInitStatementState
{
386 bool CanBeExpression
= true;
387 bool CanBeCondition
= true;
388 bool CanBeInitStatement
;
389 bool CanBeForRangeDecl
;
391 ConditionDeclarationOrInitStatementState(Parser
&P
, bool CanBeInitStatement
,
392 bool CanBeForRangeDecl
)
393 : P(P
), CanBeInitStatement(CanBeInitStatement
),
394 CanBeForRangeDecl(CanBeForRangeDecl
) {}
397 return CanBeExpression
+ CanBeCondition
+ CanBeInitStatement
+
398 CanBeForRangeDecl
< 2;
401 void markNotExpression() {
402 CanBeExpression
= false;
405 // FIXME: Unify the parsing codepaths for condition variables and
406 // simple-declarations so that we don't need to eagerly figure out which
407 // kind we have here. (Just parse init-declarators until we reach a
408 // semicolon or right paren.)
409 RevertingTentativeParsingAction
PA(P
);
410 if (CanBeForRangeDecl
) {
411 // Skip until we hit a ')', ';', or a ':' with no matching '?'.
412 // The final case is a for range declaration, the rest are not.
413 unsigned QuestionColonDepth
= 0;
415 P
.SkipUntil({tok::r_paren
, tok::semi
, tok::question
, tok::colon
},
417 if (P
.Tok
.is(tok::question
))
418 ++QuestionColonDepth
;
419 else if (P
.Tok
.is(tok::colon
)) {
420 if (QuestionColonDepth
)
421 --QuestionColonDepth
;
423 CanBeCondition
= CanBeInitStatement
= false;
427 CanBeForRangeDecl
= false;
433 // Just skip until we hit a ')' or ';'.
434 P
.SkipUntil(tok::r_paren
, tok::semi
, StopBeforeMatch
);
436 if (P
.Tok
.isNot(tok::r_paren
))
437 CanBeCondition
= CanBeForRangeDecl
= false;
438 if (P
.Tok
.isNot(tok::semi
))
439 CanBeInitStatement
= false;
443 bool markNotCondition() {
444 CanBeCondition
= false;
448 bool markNotForRangeDecl() {
449 CanBeForRangeDecl
= false;
453 bool update(TPResult IsDecl
) {
457 assert(resolved() && "can't continue after tentative parsing bails out");
459 case TPResult::False
:
460 CanBeCondition
= CanBeInitStatement
= CanBeForRangeDecl
= false;
462 case TPResult::Ambiguous
:
464 case TPResult::Error
:
465 CanBeExpression
= CanBeCondition
= CanBeInitStatement
=
466 CanBeForRangeDecl
= false;
472 ConditionOrInitStatement
result() const {
473 assert(CanBeExpression
+ CanBeCondition
+ CanBeInitStatement
+
474 CanBeForRangeDecl
< 2 &&
475 "result called but not yet resolved");
477 return ConditionOrInitStatement::Expression
;
479 return ConditionOrInitStatement::ConditionDecl
;
480 if (CanBeInitStatement
)
481 return ConditionOrInitStatement::InitStmtDecl
;
482 if (CanBeForRangeDecl
)
483 return ConditionOrInitStatement::ForRangeDecl
;
484 return ConditionOrInitStatement::Error
;
488 bool Parser::isEnumBase(bool AllowSemi
) {
489 assert(Tok
.is(tok::colon
) && "should be looking at the ':'");
491 RevertingTentativeParsingAction
PA(*this);
495 // type-specifier-seq
496 bool InvalidAsDeclSpec
= false;
497 // FIXME: We could disallow non-type decl-specifiers here, but it makes no
498 // difference: those specifiers are ill-formed regardless of the
500 TPResult R
= isCXXDeclarationSpecifier(ImplicitTypenameContext::No
,
501 /*BracedCastResult=*/TPResult::True
,
503 if (R
== TPResult::Ambiguous
) {
504 // We either have a decl-specifier followed by '(' or an undeclared
506 if (TryConsumeDeclarationSpecifier() == TPResult::Error
)
509 // If we get to the end of the enum-base, we hit either a '{' or a ';'.
510 // Don't bother checking the enumerator-list.
511 if (Tok
.is(tok::l_brace
) || (AllowSemi
&& Tok
.is(tok::semi
)))
514 // A second decl-specifier unambiguously indicatges an enum-base.
515 R
= isCXXDeclarationSpecifier(ImplicitTypenameContext::No
, TPResult::True
,
519 return R
!= TPResult::False
;
522 /// Disambiguates between a declaration in a condition, a
523 /// simple-declaration in an init-statement, and an expression for
524 /// a condition of a if/switch statement.
528 /// type-specifier-seq declarator '=' assignment-expression
529 /// [C++11] type-specifier-seq declarator '=' initializer-clause
530 /// [C++11] type-specifier-seq declarator braced-init-list
531 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
532 /// '=' assignment-expression
533 /// simple-declaration:
534 /// decl-specifier-seq init-declarator-list[opt] ';'
536 /// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
537 /// to the ';' to disambiguate cases like 'int(x))' (an expression) from
538 /// 'int(x);' (a simple-declaration in an init-statement).
539 Parser::ConditionOrInitStatement
540 Parser::isCXXConditionDeclarationOrInitStatement(bool CanBeInitStatement
,
541 bool CanBeForRangeDecl
) {
542 ConditionDeclarationOrInitStatementState
State(*this, CanBeInitStatement
,
545 if (CanBeInitStatement
&& Tok
.is(tok::kw_using
))
546 return ConditionOrInitStatement::InitStmtDecl
;
547 if (State
.update(isCXXDeclarationSpecifier(ImplicitTypenameContext::No
)))
548 return State
.result();
550 // It might be a declaration; we need tentative parsing.
551 RevertingTentativeParsingAction
PA(*this);
553 // FIXME: A tag definition unambiguously tells us this is an init-statement.
554 bool MayHaveTrailingReturnType
= Tok
.is(tok::kw_auto
);
555 if (State
.update(TryConsumeDeclarationSpecifier()))
556 return State
.result();
557 assert(Tok
.is(tok::l_paren
) && "Expected '('");
560 // Consume a declarator.
561 if (State
.update(TryParseDeclarator(
562 /*mayBeAbstract=*/false,
563 /*mayHaveIdentifier=*/true,
564 /*mayHaveDirectInit=*/false,
565 /*mayHaveTrailingReturnType=*/MayHaveTrailingReturnType
)))
566 return State
.result();
568 // Attributes, asm label, or an initializer imply this is not an expression.
569 // FIXME: Disambiguate properly after an = instead of assuming that it's a
570 // valid declaration.
571 if (Tok
.isOneOf(tok::equal
, tok::kw_asm
, tok::kw___attribute
) ||
572 (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
))) {
573 State
.markNotExpression();
574 return State
.result();
577 // A colon here identifies a for-range declaration.
578 if (State
.CanBeForRangeDecl
&& Tok
.is(tok::colon
))
579 return ConditionOrInitStatement::ForRangeDecl
;
581 // At this point, it can't be a condition any more, because a condition
582 // must have a brace-or-equal-initializer.
583 if (State
.markNotCondition())
584 return State
.result();
586 // Likewise, it can't be a for-range declaration any more.
587 if (State
.markNotForRangeDecl())
588 return State
.result();
590 // A parenthesized initializer could be part of an expression or a
591 // simple-declaration.
592 if (Tok
.is(tok::l_paren
)) {
594 SkipUntil(tok::r_paren
, StopAtSemi
);
597 if (!TryConsumeToken(tok::comma
))
601 // We reached the end. If it can now be some kind of decl, then it is.
602 if (State
.CanBeCondition
&& Tok
.is(tok::r_paren
))
603 return ConditionOrInitStatement::ConditionDecl
;
604 else if (State
.CanBeInitStatement
&& Tok
.is(tok::semi
))
605 return ConditionOrInitStatement::InitStmtDecl
;
607 return ConditionOrInitStatement::Expression
;
610 /// Determine whether the next set of tokens contains a type-id.
612 /// The context parameter states what context we're parsing right
613 /// now, which affects how this routine copes with the token
614 /// following the type-id. If the context is TypeIdInParens, we have
615 /// already parsed the '(' and we will cease lookahead when we hit
616 /// the corresponding ')'. If the context is
617 /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
618 /// before this template argument, and will cease lookahead when we
619 /// hit a '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately
620 /// preceding such. Returns true for a type-id and false for an expression.
621 /// If during the disambiguation process a parsing error is encountered,
622 /// the function returns true to let the declaration parsing code handle it.
625 /// type-specifier-seq abstract-declarator[opt]
627 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context
, bool &isAmbiguous
) {
632 // The ambiguity arising from the similarity between a function-style cast and
633 // a type-id can occur in different contexts. The ambiguity appears as a
634 // choice between a function-style cast expression and a declaration of a
635 // type. The resolution is that any construct that could possibly be a type-id
636 // in its syntactic context shall be considered a type-id.
638 TPResult TPR
= isCXXDeclarationSpecifier(ImplicitTypenameContext::No
);
639 if (TPR
!= TPResult::Ambiguous
)
640 return TPR
!= TPResult::False
; // Returns true for TPResult::True or
643 // FIXME: Add statistics about the number of ambiguous statements encountered
644 // and how they were resolved (number of declarations+number of expressions).
646 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
647 // We need tentative parsing...
649 RevertingTentativeParsingAction
PA(*this);
650 bool MayHaveTrailingReturnType
= Tok
.is(tok::kw_auto
);
652 // type-specifier-seq
653 TryConsumeDeclarationSpecifier();
654 assert(Tok
.is(tok::l_paren
) && "Expected '('");
657 TPR
= TryParseDeclarator(true /*mayBeAbstract*/, false /*mayHaveIdentifier*/,
658 /*mayHaveDirectInit=*/false,
659 MayHaveTrailingReturnType
);
661 // In case of an error, let the declaration parsing code handle it.
662 if (TPR
== TPResult::Error
)
663 TPR
= TPResult::True
;
665 if (TPR
== TPResult::Ambiguous
) {
666 // We are supposed to be inside parens, so if after the abstract declarator
667 // we encounter a ')' this is a type-id, otherwise it's an expression.
668 if (Context
== TypeIdInParens
&& Tok
.is(tok::r_paren
)) {
669 TPR
= TPResult::True
;
671 // We are supposed to be inside the first operand to a _Generic selection
672 // expression, so if we find a comma after the declarator, we've found a
673 // type and not an expression.
674 } else if (Context
== TypeIdAsGenericSelectionArgument
&& Tok
.is(tok::comma
)) {
675 TPR
= TPResult::True
;
677 // We are supposed to be inside a template argument, so if after
678 // the abstract declarator we encounter a '>', '>>' (in C++0x), or
679 // ','; or, in C++0x, an ellipsis immediately preceding such, this
680 // is a type-id. Otherwise, it's an expression.
681 } else if (Context
== TypeIdAsTemplateArgument
&&
682 (Tok
.isOneOf(tok::greater
, tok::comma
) ||
683 (getLangOpts().CPlusPlus11
&&
684 (Tok
.isOneOf(tok::greatergreater
,
685 tok::greatergreatergreater
) ||
686 (Tok
.is(tok::ellipsis
) &&
687 NextToken().isOneOf(tok::greater
, tok::greatergreater
,
688 tok::greatergreatergreater
,
690 TPR
= TPResult::True
;
693 } else if (Context
== TypeIdInTrailingReturnType
) {
694 TPR
= TPResult::True
;
697 TPR
= TPResult::False
;
700 assert(TPR
== TPResult::True
|| TPR
== TPResult::False
);
701 return TPR
== TPResult::True
;
704 /// Returns true if this is a C++11 attribute-specifier. Per
705 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
706 /// always introduce an attribute. In Objective-C++11, this rule does not
707 /// apply if either '[' begins a message-send.
709 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
710 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
712 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
713 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
714 /// is not an Obj-C message send.
716 /// C++11 [dcl.attr.grammar]:
718 /// attribute-specifier:
719 /// '[' '[' attribute-list ']' ']'
720 /// alignment-specifier
724 /// attribute-list ',' attribute[opt]
726 /// attribute-list ',' attribute '...'
729 /// attribute-token attribute-argument-clause[opt]
733 /// identifier '::' identifier
735 /// attribute-argument-clause:
736 /// '(' balanced-token-seq ')'
737 Parser::CXX11AttributeKind
738 Parser::isCXX11AttributeSpecifier(bool Disambiguate
,
739 bool OuterMightBeMessageSend
) {
740 if (Tok
.is(tok::kw_alignas
))
741 return CAK_AttributeSpecifier
;
743 if (Tok
.isRegularKeywordAttribute())
744 return CAK_AttributeSpecifier
;
746 if (Tok
.isNot(tok::l_square
) || NextToken().isNot(tok::l_square
))
747 return CAK_NotAttributeSpecifier
;
749 // No tentative parsing if we don't need to look for ']]' or a lambda.
750 if (!Disambiguate
&& !getLangOpts().ObjC
)
751 return CAK_AttributeSpecifier
;
753 // '[[using ns: ...]]' is an attribute.
754 if (GetLookAheadToken(2).is(tok::kw_using
))
755 return CAK_AttributeSpecifier
;
757 RevertingTentativeParsingAction
PA(*this);
759 // Opening brackets were checked for above.
762 if (!getLangOpts().ObjC
) {
765 bool IsAttribute
= SkipUntil(tok::r_square
);
766 IsAttribute
&= Tok
.is(tok::r_square
);
768 return IsAttribute
? CAK_AttributeSpecifier
: CAK_InvalidAttributeSpecifier
;
771 // In Obj-C++11, we need to distinguish four situations:
772 // 1a) int x[[attr]]; C++11 attribute.
773 // 1b) [[attr]]; C++11 statement attribute.
774 // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index.
775 // 3a) int x[[obj get]]; Message send in array size/index.
776 // 3b) [[Class alloc] init]; Message send in message send.
777 // 4) [[obj]{ return self; }() doStuff]; Lambda in message send.
778 // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
780 // Check to see if this is a lambda-expression.
781 // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
782 // into the tentative attribute parse below.
784 RevertingTentativeParsingAction
LambdaTPA(*this);
785 LambdaIntroducer Intro
;
786 LambdaIntroducerTentativeParse Tentative
;
787 if (ParseLambdaIntroducer(Intro
, &Tentative
)) {
788 // We hit a hard error after deciding this was not an attribute.
789 // FIXME: Don't parse and annotate expressions when disambiguating
790 // against an attribute.
791 return CAK_NotAttributeSpecifier
;
795 case LambdaIntroducerTentativeParse::MessageSend
:
796 // Case 3: The inner construct is definitely a message send, so the
797 // outer construct is definitely not an attribute.
798 return CAK_NotAttributeSpecifier
;
800 case LambdaIntroducerTentativeParse::Success
:
801 case LambdaIntroducerTentativeParse::Incomplete
:
802 // This is a lambda-introducer or attribute-specifier.
803 if (Tok
.is(tok::r_square
))
804 // Case 1: C++11 attribute.
805 return CAK_AttributeSpecifier
;
807 if (OuterMightBeMessageSend
)
808 // Case 4: Lambda in message send.
809 return CAK_NotAttributeSpecifier
;
811 // Case 2: Lambda in array size / index.
812 return CAK_InvalidAttributeSpecifier
;
814 case LambdaIntroducerTentativeParse::Invalid
:
815 // No idea what this is; we couldn't parse it as a lambda-introducer.
816 // Might still be an attribute-specifier or a message send.
823 // If we don't have a lambda-introducer, then we have an attribute or a
825 bool IsAttribute
= true;
826 while (Tok
.isNot(tok::r_square
)) {
827 if (Tok
.is(tok::comma
)) {
828 // Case 1: Stray commas can only occur in attributes.
829 return CAK_AttributeSpecifier
;
832 // Parse the attribute-token, if present.
833 // C++11 [dcl.attr.grammar]:
834 // If a keyword or an alternative token that satisfies the syntactic
835 // requirements of an identifier is contained in an attribute-token,
836 // it is considered an identifier.
838 if (!TryParseCXX11AttributeIdentifier(Loc
)) {
842 if (Tok
.is(tok::coloncolon
)) {
844 if (!TryParseCXX11AttributeIdentifier(Loc
)) {
850 // Parse the attribute-argument-clause, if present.
851 if (Tok
.is(tok::l_paren
)) {
853 if (!SkipUntil(tok::r_paren
)) {
859 TryConsumeToken(tok::ellipsis
);
861 if (!TryConsumeToken(tok::comma
))
865 // An attribute must end ']]'.
867 if (Tok
.is(tok::r_square
)) {
869 IsAttribute
= Tok
.is(tok::r_square
);
876 // Case 1: C++11 statement attribute.
877 return CAK_AttributeSpecifier
;
879 // Case 3: Message send.
880 return CAK_NotAttributeSpecifier
;
883 bool Parser::TrySkipAttributes() {
884 while (Tok
.isOneOf(tok::l_square
, tok::kw___attribute
, tok::kw___declspec
,
886 Tok
.isRegularKeywordAttribute()) {
887 if (Tok
.is(tok::l_square
)) {
889 if (Tok
.isNot(tok::l_square
))
892 if (!SkipUntil(tok::r_square
) || Tok
.isNot(tok::r_square
))
894 // Note that explicitly checking for `[[` and `]]` allows to fail as
895 // expected in the case of the Objective-C message send syntax.
897 } else if (Tok
.isRegularKeywordAttribute()) {
901 if (Tok
.isNot(tok::l_paren
))
904 if (!SkipUntil(tok::r_paren
))
912 Parser::TPResult
Parser::TryParsePtrOperatorSeq() {
914 if (TryAnnotateOptionalCXXScopeToken(true))
915 return TPResult::Error
;
917 if (Tok
.isOneOf(tok::star
, tok::amp
, tok::caret
, tok::ampamp
) ||
918 (Tok
.is(tok::annot_cxxscope
) && NextToken().is(tok::star
))) {
923 if (!TrySkipAttributes())
924 return TPResult::Error
;
926 while (Tok
.isOneOf(tok::kw_const
, tok::kw_volatile
, tok::kw_restrict
,
927 tok::kw__Nonnull
, tok::kw__Nullable
,
928 tok::kw__Nullable_result
, tok::kw__Null_unspecified
,
932 return TPResult::True
;
937 /// operator-function-id:
938 /// 'operator' operator
941 /// new delete new[] delete[] + - * / % ^ [...]
943 /// conversion-function-id:
944 /// 'operator' conversion-type-id
946 /// conversion-type-id:
947 /// type-specifier-seq conversion-declarator[opt]
949 /// conversion-declarator:
950 /// ptr-operator conversion-declarator[opt]
952 /// literal-operator-id:
953 /// 'operator' string-literal identifier
954 /// 'operator' user-defined-string-literal
955 Parser::TPResult
Parser::TryParseOperatorId() {
956 assert(Tok
.is(tok::kw_operator
));
959 // Maybe this is an operator-function-id.
960 switch (Tok
.getKind()) {
961 case tok::kw_new
: case tok::kw_delete
:
963 if (Tok
.is(tok::l_square
) && NextToken().is(tok::r_square
)) {
967 return TPResult::True
;
969 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
971 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
972 #include "clang/Basic/OperatorKinds.def"
974 return TPResult::True
;
977 if (NextToken().is(tok::r_square
)) {
980 return TPResult::True
;
985 if (NextToken().is(tok::r_paren
)) {
988 return TPResult::True
;
996 // Maybe this is a literal-operator-id.
997 if (getLangOpts().CPlusPlus11
&& isTokenStringLiteral()) {
998 bool FoundUDSuffix
= false;
1000 FoundUDSuffix
|= Tok
.hasUDSuffix();
1001 ConsumeStringToken();
1002 } while (isTokenStringLiteral());
1004 if (!FoundUDSuffix
) {
1005 if (Tok
.is(tok::identifier
))
1008 return TPResult::Error
;
1010 return TPResult::True
;
1013 // Maybe this is a conversion-function-id.
1014 bool AnyDeclSpecifiers
= false;
1016 TPResult TPR
= isCXXDeclarationSpecifier(ImplicitTypenameContext::No
);
1017 if (TPR
== TPResult::Error
)
1019 if (TPR
== TPResult::False
) {
1020 if (!AnyDeclSpecifiers
)
1021 return TPResult::Error
;
1024 if (TryConsumeDeclarationSpecifier() == TPResult::Error
)
1025 return TPResult::Error
;
1026 AnyDeclSpecifiers
= true;
1028 return TryParsePtrOperatorSeq();
1032 /// direct-declarator
1033 /// ptr-operator declarator
1035 /// direct-declarator:
1037 /// direct-declarator '(' parameter-declaration-clause ')'
1038 /// cv-qualifier-seq[opt] exception-specification[opt]
1039 /// direct-declarator '[' constant-expression[opt] ']'
1040 /// '(' declarator ')'
1041 /// [GNU] '(' attributes declarator ')'
1043 /// abstract-declarator:
1044 /// ptr-operator abstract-declarator[opt]
1045 /// direct-abstract-declarator
1047 /// direct-abstract-declarator:
1048 /// direct-abstract-declarator[opt]
1049 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1050 /// exception-specification[opt]
1051 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
1052 /// '(' abstract-declarator ')'
1056 /// '*' cv-qualifier-seq[opt]
1058 /// [C++0x] '&&' [TODO]
1059 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
1061 /// cv-qualifier-seq:
1062 /// cv-qualifier cv-qualifier-seq[opt]
1069 /// '...'[opt] id-expression
1073 /// qualified-id [TODO]
1077 /// operator-function-id
1078 /// conversion-function-id
1079 /// literal-operator-id
1080 /// '~' class-name [TODO]
1081 /// '~' decltype-specifier [TODO]
1082 /// template-id [TODO]
1084 Parser::TPResult
Parser::TryParseDeclarator(bool mayBeAbstract
,
1085 bool mayHaveIdentifier
,
1086 bool mayHaveDirectInit
,
1087 bool mayHaveTrailingReturnType
) {
1089 // direct-declarator
1090 // ptr-operator declarator
1091 if (TryParsePtrOperatorSeq() == TPResult::Error
)
1092 return TPResult::Error
;
1094 // direct-declarator:
1095 // direct-abstract-declarator:
1096 if (Tok
.is(tok::ellipsis
))
1099 if ((Tok
.isOneOf(tok::identifier
, tok::kw_operator
) ||
1100 (Tok
.is(tok::annot_cxxscope
) && (NextToken().is(tok::identifier
) ||
1101 NextToken().is(tok::kw_operator
)))) &&
1102 mayHaveIdentifier
) {
1104 if (Tok
.is(tok::annot_cxxscope
)) {
1106 Actions
.RestoreNestedNameSpecifierAnnotation(
1107 Tok
.getAnnotationValue(), Tok
.getAnnotationRange(), SS
);
1109 return TPResult::Error
;
1110 ConsumeAnnotationToken();
1111 } else if (Tok
.is(tok::identifier
)) {
1112 TentativelyDeclaredIdentifiers
.push_back(Tok
.getIdentifierInfo());
1114 if (Tok
.is(tok::kw_operator
)) {
1115 if (TryParseOperatorId() == TPResult::Error
)
1116 return TPResult::Error
;
1119 } else if (Tok
.is(tok::l_paren
)) {
1121 if (mayBeAbstract
&&
1122 (Tok
.is(tok::r_paren
) || // 'int()' is a function.
1123 // 'int(...)' is a function.
1124 (Tok
.is(tok::ellipsis
) && NextToken().is(tok::r_paren
)) ||
1125 isDeclarationSpecifier(
1126 ImplicitTypenameContext::No
))) { // 'int(int)' is a function.
1127 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1128 // exception-specification[opt]
1129 TPResult TPR
= TryParseFunctionDeclarator(mayHaveTrailingReturnType
);
1130 if (TPR
!= TPResult::Ambiguous
)
1133 // '(' declarator ')'
1134 // '(' attributes declarator ')'
1135 // '(' abstract-declarator ')'
1136 if (Tok
.isOneOf(tok::kw___attribute
, tok::kw___declspec
, tok::kw___cdecl
,
1137 tok::kw___stdcall
, tok::kw___fastcall
, tok::kw___thiscall
,
1138 tok::kw___regcall
, tok::kw___vectorcall
))
1139 return TPResult::True
; // attributes indicate declaration
1140 TPResult TPR
= TryParseDeclarator(mayBeAbstract
, mayHaveIdentifier
);
1141 if (TPR
!= TPResult::Ambiguous
)
1143 if (Tok
.isNot(tok::r_paren
))
1144 return TPResult::False
;
1147 } else if (!mayBeAbstract
) {
1148 return TPResult::False
;
1151 if (mayHaveDirectInit
)
1152 return TPResult::Ambiguous
;
1155 TPResult
TPR(TPResult::Ambiguous
);
1157 if (Tok
.is(tok::l_paren
)) {
1158 // Check whether we have a function declarator or a possible ctor-style
1159 // initializer that follows the declarator. Note that ctor-style
1160 // initializers are not possible in contexts where abstract declarators
1162 if (!mayBeAbstract
&& !isCXXFunctionDeclarator())
1165 // direct-declarator '(' parameter-declaration-clause ')'
1166 // cv-qualifier-seq[opt] exception-specification[opt]
1168 TPR
= TryParseFunctionDeclarator(mayHaveTrailingReturnType
);
1169 } else if (Tok
.is(tok::l_square
)) {
1170 // direct-declarator '[' constant-expression[opt] ']'
1171 // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
1172 TPR
= TryParseBracketDeclarator();
1173 } else if (Tok
.is(tok::kw_requires
)) {
1174 // declarator requires-clause
1175 // A requires clause indicates a function declaration.
1176 TPR
= TPResult::True
;
1181 if (TPR
!= TPResult::Ambiguous
)
1185 return TPResult::Ambiguous
;
1188 bool Parser::isTentativelyDeclared(IdentifierInfo
*II
) {
1189 return llvm::is_contained(TentativelyDeclaredIdentifiers
, II
);
1193 class TentativeParseCCC final
: public CorrectionCandidateCallback
{
1195 TentativeParseCCC(const Token
&Next
) {
1196 WantRemainingKeywords
= false;
1197 WantTypeSpecifiers
=
1198 Next
.isOneOf(tok::l_paren
, tok::r_paren
, tok::greater
, tok::l_brace
,
1199 tok::identifier
, tok::comma
);
1202 bool ValidateCandidate(const TypoCorrection
&Candidate
) override
{
1203 // Reject any candidate that only resolves to instance members since they
1204 // aren't viable as standalone identifiers instead of member references.
1205 if (Candidate
.isResolved() && !Candidate
.isKeyword() &&
1206 llvm::all_of(Candidate
,
1207 [](NamedDecl
*ND
) { return ND
->isCXXInstanceMember(); }))
1210 return CorrectionCandidateCallback::ValidateCandidate(Candidate
);
1213 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
1214 return std::make_unique
<TentativeParseCCC
>(*this);
1218 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
1219 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
1220 /// be either a decl-specifier or a function-style cast, and TPResult::Error
1221 /// if a parsing error was found and reported.
1223 /// If InvalidAsDeclSpec is not null, some cases that would be ill-formed as
1224 /// declaration specifiers but possibly valid as some other kind of construct
1225 /// return TPResult::Ambiguous instead of TPResult::False. When this happens,
1226 /// the intent is to keep trying to disambiguate, on the basis that we might
1227 /// find a better reason to treat this construct as a declaration later on.
1228 /// When this happens and the name could possibly be valid in some other
1229 /// syntactic context, *InvalidAsDeclSpec is set to 'true'. The current cases
1230 /// that trigger this are:
1232 /// * When parsing X::Y (with no 'typename') where X is dependent
1233 /// * When parsing X<Y> where X is undeclared
1236 /// storage-class-specifier
1238 /// function-specifier
1241 /// [C++11] 'constexpr'
1242 /// [C++20] 'consteval'
1243 /// [GNU] attributes declaration-specifiers[opt]
1245 /// storage-class-specifier:
1251 /// [GNU] '__thread'
1252 /// [C++11] 'thread_local'
1253 /// [C11] '_Thread_local'
1255 /// function-specifier:
1264 /// simple-type-specifier
1267 /// elaborated-type-specifier
1268 /// typename-specifier
1271 /// simple-type-specifier:
1272 /// '::'[opt] nested-name-specifier[opt] type-name
1273 /// '::'[opt] nested-name-specifier 'template'
1274 /// simple-template-id [TODO]
1286 /// [GNU] typeof-specifier
1287 /// [GNU] '_Complex'
1289 /// [GNU] '__auto_type'
1290 /// [C++11] 'decltype' ( expression )
1291 /// [C++1y] 'decltype' ( 'auto' )
1298 /// elaborated-type-specifier:
1299 /// class-key '::'[opt] nested-name-specifier[opt] identifier
1300 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
1301 /// simple-template-id
1302 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
1308 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
1309 /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
1311 /// class-specifier:
1312 /// class-head '{' member-specification[opt] '}'
1315 /// class-key identifier[opt] base-clause[opt]
1316 /// class-key nested-name-specifier identifier base-clause[opt]
1317 /// class-key nested-name-specifier[opt] simple-template-id
1318 /// base-clause[opt]
1331 Parser::isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename
,
1332 Parser::TPResult BracedCastResult
,
1333 bool *InvalidAsDeclSpec
) {
1334 auto IsPlaceholderSpecifier
= [&](TemplateIdAnnotation
*TemplateId
,
1336 // We have a placeholder-constraint (we check for 'auto' or 'decltype' to
1337 // distinguish 'C<int>;' from 'C<int> auto c = 1;')
1338 return TemplateId
->Kind
== TNK_Concept_template
&&
1339 (GetLookAheadToken(Lookahead
+ 1)
1340 .isOneOf(tok::kw_auto
, tok::kw_decltype
,
1341 // If we have an identifier here, the user probably
1342 // forgot the 'auto' in the placeholder constraint,
1343 // e.g. 'C<int> x = 2;' This will be diagnosed nicely
1344 // later, so disambiguate as a declaration.
1346 // CVR qualifierslikely the same situation for the
1347 // user, so let this be diagnosed nicely later. We
1348 // cannot handle references here, as `C<int> & Other`
1349 // and `C<int> && Other` are both legal.
1350 tok::kw_const
, tok::kw_volatile
, tok::kw_restrict
) ||
1351 // While `C<int> && Other` is legal, doing so while not specifying a
1352 // template argument is NOT, so see if we can fix up in that case at
1353 // minimum. Concepts require at least 1 template parameter, so we
1354 // can count on the argument count.
1355 // FIXME: In the future, we migth be able to have SEMA look up the
1356 // declaration for this concept, and see how many template
1357 // parameters it has. If the concept isn't fully specified, it is
1358 // possibly a situation where we want deduction, such as:
1359 // `BinaryConcept<int> auto f = bar();`
1360 (TemplateId
->NumArgs
== 0 &&
1361 GetLookAheadToken(Lookahead
+ 1).isOneOf(tok::amp
, tok::ampamp
)));
1363 switch (Tok
.getKind()) {
1364 case tok::identifier
: {
1365 // Check for need to substitute AltiVec __vector keyword
1366 // for "vector" identifier.
1367 if (TryAltiVecVectorToken())
1368 return TPResult::True
;
1370 const Token
&Next
= NextToken();
1371 // In 'foo bar', 'foo' is always a type name outside of Objective-C.
1372 if (!getLangOpts().ObjC
&& Next
.is(tok::identifier
))
1373 return TPResult::True
;
1375 if (Next
.isNot(tok::coloncolon
) && Next
.isNot(tok::less
)) {
1376 // Determine whether this is a valid expression. If not, we will hit
1377 // a parse error one way or another. In that case, tell the caller that
1378 // this is ambiguous. Typo-correct to type and expression keywords and
1379 // to types and identifiers, in order to try to recover from errors.
1380 TentativeParseCCC
CCC(Next
);
1381 switch (TryAnnotateName(&CCC
)) {
1383 return TPResult::Error
;
1384 case ANK_TentativeDecl
:
1385 return TPResult::False
;
1386 case ANK_TemplateName
:
1387 // In C++17, this could be a type template for class template argument
1388 // deduction. Try to form a type annotation for it. If we're in a
1389 // template template argument, we'll undo this when checking the
1390 // validity of the argument.
1391 if (getLangOpts().CPlusPlus17
) {
1392 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename
))
1393 return TPResult::Error
;
1394 if (Tok
.isNot(tok::identifier
))
1398 // A bare type template-name which can't be a template template
1399 // argument is an error, and was probably intended to be a type.
1400 return GreaterThanIsOperator
? TPResult::True
: TPResult::False
;
1401 case ANK_Unresolved
:
1402 return InvalidAsDeclSpec
? TPResult::Ambiguous
: TPResult::False
;
1406 assert(Tok
.isNot(tok::identifier
) &&
1407 "TryAnnotateName succeeded without producing an annotation");
1409 // This might possibly be a type with a dependent scope specifier and
1410 // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1411 // since it will annotate as a primary expression, and we want to use the
1412 // "missing 'typename'" logic.
1413 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename
))
1414 return TPResult::Error
;
1415 // If annotation failed, assume it's a non-type.
1416 // FIXME: If this happens due to an undeclared identifier, treat it as
1418 if (Tok
.is(tok::identifier
))
1419 return TPResult::False
;
1422 // We annotated this token as something. Recurse to handle whatever we got.
1423 return isCXXDeclarationSpecifier(AllowImplicitTypename
, BracedCastResult
,
1427 case tok::kw_typename
: // typename T::type
1428 // Annotate typenames and C++ scope specifiers. If we get one, just
1429 // recurse to handle whatever we get.
1430 if (TryAnnotateTypeOrScopeToken(ImplicitTypenameContext::Yes
))
1431 return TPResult::Error
;
1432 return isCXXDeclarationSpecifier(ImplicitTypenameContext::Yes
,
1433 BracedCastResult
, InvalidAsDeclSpec
);
1435 case tok::kw_auto
: {
1436 if (!getLangOpts().CPlusPlus23
)
1437 return TPResult::True
;
1438 if (NextToken().is(tok::l_brace
))
1439 return TPResult::False
;
1440 if (NextToken().is(tok::l_paren
))
1441 return TPResult::Ambiguous
;
1442 return TPResult::True
;
1445 case tok::coloncolon
: { // ::foo::bar
1446 const Token
&Next
= NextToken();
1447 if (Next
.isOneOf(tok::kw_new
, // ::new
1448 tok::kw_delete
)) // ::delete
1449 return TPResult::False
;
1452 case tok::kw___super
:
1453 case tok::kw_decltype
:
1454 // Annotate typenames and C++ scope specifiers. If we get one, just
1455 // recurse to handle whatever we get.
1456 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename
))
1457 return TPResult::Error
;
1458 return isCXXDeclarationSpecifier(AllowImplicitTypename
, BracedCastResult
,
1462 // storage-class-specifier
1464 // function-specifier
1468 case tok::kw_friend
:
1469 case tok::kw_typedef
:
1470 case tok::kw_constexpr
:
1471 case tok::kw_consteval
:
1472 case tok::kw_constinit
:
1473 // storage-class-specifier
1474 case tok::kw_register
:
1475 case tok::kw_static
:
1476 case tok::kw_extern
:
1477 case tok::kw_mutable
:
1478 case tok::kw___thread
:
1479 case tok::kw_thread_local
:
1480 case tok::kw__Thread_local
:
1481 // function-specifier
1482 case tok::kw_inline
:
1483 case tok::kw_virtual
:
1484 case tok::kw_explicit
:
1487 case tok::kw___module_private__
:
1490 case tok::kw___unknown_anytype
:
1493 // simple-type-specifier
1496 // elaborated-type-specifier
1497 // typename-specifier
1501 // elaborated-type-specifier
1503 case tok::kw_struct
:
1505 case tok::kw___interface
:
1510 case tok::kw_volatile
:
1511 return TPResult::True
;
1513 // OpenCL address space qualifiers
1514 case tok::kw_private
:
1515 if (!getLangOpts().OpenCL
)
1516 return TPResult::False
;
1518 case tok::kw___private
:
1519 case tok::kw___local
:
1520 case tok::kw___global
:
1521 case tok::kw___constant
:
1522 case tok::kw___generic
:
1523 // OpenCL access qualifiers
1524 case tok::kw___read_only
:
1525 case tok::kw___write_only
:
1526 case tok::kw___read_write
:
1530 // HLSL address space qualifiers
1531 case tok::kw_groupshared
:
1534 case tok::kw_restrict
:
1535 case tok::kw__Complex
:
1536 case tok::kw___attribute
:
1537 case tok::kw___auto_type
:
1538 return TPResult::True
;
1541 case tok::kw___declspec
:
1542 case tok::kw___cdecl
:
1543 case tok::kw___stdcall
:
1544 case tok::kw___fastcall
:
1545 case tok::kw___thiscall
:
1546 case tok::kw___regcall
:
1547 case tok::kw___vectorcall
:
1549 case tok::kw___sptr
:
1550 case tok::kw___uptr
:
1551 case tok::kw___ptr64
:
1552 case tok::kw___ptr32
:
1553 case tok::kw___forceinline
:
1554 case tok::kw___unaligned
:
1555 case tok::kw__Nonnull
:
1556 case tok::kw__Nullable
:
1557 case tok::kw__Nullable_result
:
1558 case tok::kw__Null_unspecified
:
1559 case tok::kw___kindof
:
1560 return TPResult::True
;
1562 // WebAssemblyFuncref
1563 case tok::kw___funcref
:
1564 return TPResult::True
;
1567 case tok::kw___pascal
:
1568 return TPResult::True
;
1571 case tok::kw___vector
:
1572 return TPResult::True
;
1574 case tok::kw_this
: {
1575 // Try to parse a C++23 Explicit Object Parameter
1576 // We do that in all language modes to produce a better diagnostic.
1577 if (getLangOpts().CPlusPlus
) {
1578 RevertingTentativeParsingAction
PA(*this);
1580 return isCXXDeclarationSpecifier(AllowImplicitTypename
, BracedCastResult
,
1583 return TPResult::False
;
1585 case tok::annot_template_id
: {
1586 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
1587 // If lookup for the template-name found nothing, don't assume we have a
1588 // definitive disambiguation result yet.
1589 if ((TemplateId
->hasInvalidName() ||
1590 TemplateId
->Kind
== TNK_Undeclared_template
) &&
1591 InvalidAsDeclSpec
) {
1592 // 'template-id(' can be a valid expression but not a valid decl spec if
1593 // the template-name is not declared, but we don't consider this to be a
1594 // definitive disambiguation. In any other context, it's an error either
1596 *InvalidAsDeclSpec
= NextToken().is(tok::l_paren
);
1597 return TPResult::Ambiguous
;
1599 if (TemplateId
->hasInvalidName())
1600 return TPResult::Error
;
1601 if (IsPlaceholderSpecifier(TemplateId
, /*Lookahead=*/0))
1602 return TPResult::True
;
1603 if (TemplateId
->Kind
!= TNK_Type_template
)
1604 return TPResult::False
;
1606 AnnotateTemplateIdTokenAsType(SS
, AllowImplicitTypename
);
1607 assert(Tok
.is(tok::annot_typename
));
1611 case tok::annot_cxxscope
: // foo::bar or ::foo::bar, but already parsed
1612 // We've already annotated a scope; try to annotate a type.
1613 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename
))
1614 return TPResult::Error
;
1615 if (!Tok
.is(tok::annot_typename
)) {
1616 if (Tok
.is(tok::annot_cxxscope
) &&
1617 NextToken().is(tok::annot_template_id
)) {
1618 TemplateIdAnnotation
*TemplateId
=
1619 takeTemplateIdAnnotation(NextToken());
1620 if (TemplateId
->hasInvalidName()) {
1621 if (InvalidAsDeclSpec
) {
1622 *InvalidAsDeclSpec
= NextToken().is(tok::l_paren
);
1623 return TPResult::Ambiguous
;
1625 return TPResult::Error
;
1627 if (IsPlaceholderSpecifier(TemplateId
, /*Lookahead=*/1))
1628 return TPResult::True
;
1630 // If the next token is an identifier or a type qualifier, then this
1631 // can't possibly be a valid expression either.
1632 if (Tok
.is(tok::annot_cxxscope
) && NextToken().is(tok::identifier
)) {
1634 Actions
.RestoreNestedNameSpecifierAnnotation(Tok
.getAnnotationValue(),
1635 Tok
.getAnnotationRange(),
1637 if (SS
.getScopeRep() && SS
.getScopeRep()->isDependent()) {
1638 RevertingTentativeParsingAction
PA(*this);
1639 ConsumeAnnotationToken();
1641 bool isIdentifier
= Tok
.is(tok::identifier
);
1642 TPResult TPR
= TPResult::False
;
1644 TPR
= isCXXDeclarationSpecifier(
1645 AllowImplicitTypename
, BracedCastResult
, InvalidAsDeclSpec
);
1648 TPR
== TPResult::True
|| TPR
== TPResult::Error
)
1649 return TPResult::Error
;
1651 if (InvalidAsDeclSpec
) {
1652 // We can't tell whether this is a missing 'typename' or a valid
1654 *InvalidAsDeclSpec
= true;
1655 return TPResult::Ambiguous
;
1657 // In MS mode, if InvalidAsDeclSpec is not provided, and the tokens
1658 // are or the form *) or &) *> or &> &&>, this can't be an expression.
1659 // The typename must be missing.
1660 if (getLangOpts().MSVCCompat
) {
1661 if (((Tok
.is(tok::amp
) || Tok
.is(tok::star
)) &&
1662 (NextToken().is(tok::r_paren
) ||
1663 NextToken().is(tok::greater
))) ||
1664 (Tok
.is(tok::ampamp
) && NextToken().is(tok::greater
)))
1665 return TPResult::True
;
1669 // Try to resolve the name. If it doesn't exist, assume it was
1670 // intended to name a type and keep disambiguating.
1671 switch (TryAnnotateName(/*CCC=*/nullptr, AllowImplicitTypename
)) {
1673 return TPResult::Error
;
1674 case ANK_TentativeDecl
:
1675 return TPResult::False
;
1676 case ANK_TemplateName
:
1677 // In C++17, this could be a type template for class template
1678 // argument deduction.
1679 if (getLangOpts().CPlusPlus17
) {
1680 if (TryAnnotateTypeOrScopeToken())
1681 return TPResult::Error
;
1682 // If we annotated then the current token should not still be ::
1683 // FIXME we may want to also check for tok::annot_typename but
1684 // currently don't have a test case.
1685 if (Tok
.isNot(tok::annot_cxxscope
))
1689 // A bare type template-name which can't be a template template
1690 // argument is an error, and was probably intended to be a type.
1691 // In C++17, this could be class template argument deduction.
1692 return (getLangOpts().CPlusPlus17
|| GreaterThanIsOperator
)
1695 case ANK_Unresolved
:
1696 return InvalidAsDeclSpec
? TPResult::Ambiguous
: TPResult::False
;
1701 // Annotated it, check again.
1702 assert(Tok
.isNot(tok::annot_cxxscope
) ||
1703 NextToken().isNot(tok::identifier
));
1704 return isCXXDeclarationSpecifier(AllowImplicitTypename
,
1705 BracedCastResult
, InvalidAsDeclSpec
);
1708 return TPResult::False
;
1710 // If that succeeded, fallthrough into the generic simple-type-id case.
1713 // The ambiguity resides in a simple-type-specifier/typename-specifier
1714 // followed by a '('. The '(' could either be the start of:
1716 // direct-declarator:
1717 // '(' declarator ')'
1719 // direct-abstract-declarator:
1720 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1721 // exception-specification[opt]
1722 // '(' abstract-declarator ')'
1724 // or part of a function-style cast expression:
1726 // simple-type-specifier '(' expression-list[opt] ')'
1729 // simple-type-specifier:
1731 case tok::annot_typename
:
1733 // In Objective-C, we might have a protocol-qualified type.
1734 if (getLangOpts().ObjC
&& NextToken().is(tok::less
)) {
1735 // Tentatively parse the protocol qualifiers.
1736 RevertingTentativeParsingAction
PA(*this);
1737 ConsumeAnyToken(); // The type token
1739 TPResult TPR
= TryParseProtocolQualifiers();
1740 bool isFollowedByParen
= Tok
.is(tok::l_paren
);
1741 bool isFollowedByBrace
= Tok
.is(tok::l_brace
);
1743 if (TPR
== TPResult::Error
)
1744 return TPResult::Error
;
1746 if (isFollowedByParen
)
1747 return TPResult::Ambiguous
;
1749 if (getLangOpts().CPlusPlus11
&& isFollowedByBrace
)
1750 return BracedCastResult
;
1752 return TPResult::True
;
1757 case tok::kw_wchar_t
:
1758 case tok::kw_char8_t
:
1759 case tok::kw_char16_t
:
1760 case tok::kw_char32_t
:
1765 case tok::kw___int64
:
1766 case tok::kw___int128
:
1767 case tok::kw_signed
:
1768 case tok::kw_unsigned
:
1771 case tok::kw_double
:
1772 case tok::kw___bf16
:
1773 case tok::kw__Float16
:
1774 case tok::kw___float128
:
1775 case tok::kw___ibm128
:
1777 case tok::annot_decltype
:
1778 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1779 #include "clang/Basic/OpenCLImageTypes.def"
1780 if (NextToken().is(tok::l_paren
))
1781 return TPResult::Ambiguous
;
1783 // This is a function-style cast in all cases we disambiguate other than
1786 // enum E : int { a = 4 }; // enum
1787 // enum E : int { 4 }; // bit-field
1789 if (getLangOpts().CPlusPlus11
&& NextToken().is(tok::l_brace
))
1790 return BracedCastResult
;
1792 if (isStartOfObjCClassMessageMissingOpenBracket())
1793 return TPResult::False
;
1795 return TPResult::True
;
1797 // GNU typeof support.
1798 case tok::kw_typeof
: {
1799 if (NextToken().isNot(tok::l_paren
))
1800 return TPResult::True
;
1802 RevertingTentativeParsingAction
PA(*this);
1804 TPResult TPR
= TryParseTypeofSpecifier();
1805 bool isFollowedByParen
= Tok
.is(tok::l_paren
);
1806 bool isFollowedByBrace
= Tok
.is(tok::l_brace
);
1808 if (TPR
== TPResult::Error
)
1809 return TPResult::Error
;
1811 if (isFollowedByParen
)
1812 return TPResult::Ambiguous
;
1814 if (getLangOpts().CPlusPlus11
&& isFollowedByBrace
)
1815 return BracedCastResult
;
1817 return TPResult::True
;
1820 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
1821 #include "clang/Basic/TransformTypeTraits.def"
1822 return TPResult::True
;
1825 case tok::kw__Atomic
:
1826 return TPResult::True
;
1828 case tok::kw__BitInt
:
1829 case tok::kw__ExtInt
: {
1830 if (NextToken().isNot(tok::l_paren
))
1831 return TPResult::Error
;
1832 RevertingTentativeParsingAction
PA(*this);
1836 if (!SkipUntil(tok::r_paren
, StopAtSemi
))
1837 return TPResult::Error
;
1839 if (Tok
.is(tok::l_paren
))
1840 return TPResult::Ambiguous
;
1842 if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
))
1843 return BracedCastResult
;
1845 return TPResult::True
;
1848 return TPResult::False
;
1852 bool Parser::isCXXDeclarationSpecifierAType() {
1853 switch (Tok
.getKind()) {
1854 // typename-specifier
1855 case tok::annot_decltype
:
1856 case tok::annot_template_id
:
1857 case tok::annot_typename
:
1858 case tok::kw_typeof
:
1859 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
1860 #include "clang/Basic/TransformTypeTraits.def"
1863 // elaborated-type-specifier
1865 case tok::kw_struct
:
1867 case tok::kw___interface
:
1871 // simple-type-specifier
1873 case tok::kw_wchar_t
:
1874 case tok::kw_char8_t
:
1875 case tok::kw_char16_t
:
1876 case tok::kw_char32_t
:
1880 case tok::kw__ExtInt
:
1881 case tok::kw__BitInt
:
1883 case tok::kw___int64
:
1884 case tok::kw___int128
:
1885 case tok::kw_signed
:
1886 case tok::kw_unsigned
:
1889 case tok::kw_double
:
1890 case tok::kw___bf16
:
1891 case tok::kw__Float16
:
1892 case tok::kw___float128
:
1893 case tok::kw___ibm128
:
1895 case tok::kw___unknown_anytype
:
1896 case tok::kw___auto_type
:
1897 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1898 #include "clang/Basic/OpenCLImageTypes.def"
1902 return getLangOpts().CPlusPlus11
;
1904 case tok::kw__Atomic
:
1906 return NextToken().is(tok::l_paren
);
1913 /// [GNU] typeof-specifier:
1914 /// 'typeof' '(' expressions ')'
1915 /// 'typeof' '(' type-name ')'
1917 Parser::TPResult
Parser::TryParseTypeofSpecifier() {
1918 assert(Tok
.is(tok::kw_typeof
) && "Expected 'typeof'!");
1921 assert(Tok
.is(tok::l_paren
) && "Expected '('");
1922 // Parse through the parens after 'typeof'.
1924 if (!SkipUntil(tok::r_paren
, StopAtSemi
))
1925 return TPResult::Error
;
1927 return TPResult::Ambiguous
;
1930 /// [ObjC] protocol-qualifiers:
1931 //// '<' identifier-list '>'
1932 Parser::TPResult
Parser::TryParseProtocolQualifiers() {
1933 assert(Tok
.is(tok::less
) && "Expected '<' for qualifier list");
1936 if (Tok
.isNot(tok::identifier
))
1937 return TPResult::Error
;
1940 if (Tok
.is(tok::comma
)) {
1945 if (Tok
.is(tok::greater
)) {
1947 return TPResult::Ambiguous
;
1951 return TPResult::Error
;
1954 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1955 /// a constructor-style initializer, when parsing declaration statements.
1956 /// Returns true for function declarator and false for constructor-style
1958 /// If during the disambiguation process a parsing error is encountered,
1959 /// the function returns true to let the declaration parsing code handle it.
1961 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1962 /// exception-specification[opt]
1964 bool Parser::isCXXFunctionDeclarator(
1965 bool *IsAmbiguous
, ImplicitTypenameContext AllowImplicitTypename
) {
1968 // The ambiguity arising from the similarity between a function-style cast and
1969 // a declaration mentioned in 6.8 can also occur in the context of a
1970 // declaration. In that context, the choice is between a function declaration
1971 // with a redundant set of parentheses around a parameter name and an object
1972 // declaration with a function-style cast as the initializer. Just as for the
1973 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1974 // that could possibly be a declaration a declaration.
1976 RevertingTentativeParsingAction
PA(*this);
1979 bool InvalidAsDeclaration
= false;
1980 TPResult TPR
= TryParseParameterDeclarationClause(
1981 &InvalidAsDeclaration
, /*VersusTemplateArgument=*/false,
1982 AllowImplicitTypename
);
1983 if (TPR
== TPResult::Ambiguous
) {
1984 if (Tok
.isNot(tok::r_paren
))
1985 TPR
= TPResult::False
;
1987 const Token
&Next
= NextToken();
1988 if (Next
.isOneOf(tok::amp
, tok::ampamp
, tok::kw_const
, tok::kw_volatile
,
1989 tok::kw_throw
, tok::kw_noexcept
, tok::l_square
,
1990 tok::l_brace
, tok::kw_try
, tok::equal
, tok::arrow
) ||
1991 isCXX11VirtSpecifier(Next
))
1992 // The next token cannot appear after a constructor-style initializer,
1993 // and can appear next in a function definition. This must be a function
1995 TPR
= TPResult::True
;
1996 else if (InvalidAsDeclaration
)
1997 // Use the absence of 'typename' as a tie-breaker.
1998 TPR
= TPResult::False
;
2002 if (IsAmbiguous
&& TPR
== TPResult::Ambiguous
)
2003 *IsAmbiguous
= true;
2005 // In case of an error, let the declaration parsing code handle it.
2006 return TPR
!= TPResult::False
;
2009 /// parameter-declaration-clause:
2010 /// parameter-declaration-list[opt] '...'[opt]
2011 /// parameter-declaration-list ',' '...'
2013 /// parameter-declaration-list:
2014 /// parameter-declaration
2015 /// parameter-declaration-list ',' parameter-declaration
2017 /// parameter-declaration:
2018 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
2019 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
2020 /// '=' assignment-expression
2021 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
2023 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
2024 /// attributes[opt] '=' assignment-expression
2026 Parser::TPResult
Parser::TryParseParameterDeclarationClause(
2027 bool *InvalidAsDeclaration
, bool VersusTemplateArgument
,
2028 ImplicitTypenameContext AllowImplicitTypename
) {
2030 if (Tok
.is(tok::r_paren
))
2031 return TPResult::Ambiguous
;
2033 // parameter-declaration-list[opt] '...'[opt]
2034 // parameter-declaration-list ',' '...'
2036 // parameter-declaration-list:
2037 // parameter-declaration
2038 // parameter-declaration-list ',' parameter-declaration
2042 if (Tok
.is(tok::ellipsis
)) {
2044 if (Tok
.is(tok::r_paren
))
2045 return TPResult::True
; // '...)' is a sign of a function declarator.
2047 return TPResult::False
;
2050 // An attribute-specifier-seq here is a sign of a function declarator.
2051 if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
2052 /*OuterMightBeMessageSend*/true))
2053 return TPResult::True
;
2055 ParsedAttributes
attrs(AttrFactory
);
2056 MaybeParseMicrosoftAttributes(attrs
);
2058 // decl-specifier-seq
2059 // A parameter-declaration's initializer must be preceded by an '=', so
2060 // decl-specifier-seq '{' is not a parameter in C++11.
2061 TPResult TPR
= isCXXDeclarationSpecifier(
2062 AllowImplicitTypename
, TPResult::False
, InvalidAsDeclaration
);
2063 // A declaration-specifier (not followed by '(' or '{') means this can't be
2064 // an expression, but it could still be a template argument.
2065 if (TPR
!= TPResult::Ambiguous
&&
2066 !(VersusTemplateArgument
&& TPR
== TPResult::True
))
2069 bool SeenType
= false;
2070 bool DeclarationSpecifierIsAuto
= Tok
.is(tok::kw_auto
);
2072 SeenType
|= isCXXDeclarationSpecifierAType();
2073 if (TryConsumeDeclarationSpecifier() == TPResult::Error
)
2074 return TPResult::Error
;
2076 // If we see a parameter name, this can't be a template argument.
2077 if (SeenType
&& Tok
.is(tok::identifier
))
2078 return TPResult::True
;
2080 TPR
= isCXXDeclarationSpecifier(AllowImplicitTypename
, TPResult::False
,
2081 InvalidAsDeclaration
);
2082 if (TPR
== TPResult::Error
)
2085 // Two declaration-specifiers means this can't be an expression.
2086 if (TPR
== TPResult::True
&& !VersusTemplateArgument
)
2088 } while (TPR
!= TPResult::False
);
2091 // abstract-declarator[opt]
2092 TPR
= TryParseDeclarator(
2093 /*mayBeAbstract=*/true,
2094 /*mayHaveIdentifier=*/true,
2095 /*mayHaveDirectInit=*/false,
2096 /*mayHaveTrailingReturnType=*/DeclarationSpecifierIsAuto
);
2097 if (TPR
!= TPResult::Ambiguous
)
2100 // [GNU] attributes[opt]
2101 if (Tok
.is(tok::kw___attribute
))
2102 return TPResult::True
;
2104 // If we're disambiguating a template argument in a default argument in
2105 // a class definition versus a parameter declaration, an '=' here
2106 // disambiguates the parse one way or the other.
2107 // If this is a parameter, it must have a default argument because
2108 // (a) the previous parameter did, and
2109 // (b) this must be the first declaration of the function, so we can't
2110 // inherit any default arguments from elsewhere.
2111 // FIXME: If we reach a ')' without consuming any '>'s, then this must
2112 // also be a function parameter (that's missing its default argument).
2113 if (VersusTemplateArgument
)
2114 return Tok
.is(tok::equal
) ? TPResult::True
: TPResult::False
;
2116 if (Tok
.is(tok::equal
)) {
2117 // '=' assignment-expression
2118 // Parse through assignment-expression.
2119 if (!SkipUntil(tok::comma
, tok::r_paren
, StopAtSemi
| StopBeforeMatch
))
2120 return TPResult::Error
;
2123 if (Tok
.is(tok::ellipsis
)) {
2125 if (Tok
.is(tok::r_paren
))
2126 return TPResult::True
; // '...)' is a sign of a function declarator.
2128 return TPResult::False
;
2131 if (!TryConsumeToken(tok::comma
))
2135 return TPResult::Ambiguous
;
2138 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
2139 /// parsing as a function declarator.
2140 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
2141 /// return TPResult::Ambiguous, otherwise it will return either False() or
2144 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
2145 /// exception-specification[opt]
2147 /// exception-specification:
2148 /// 'throw' '(' type-id-list[opt] ')'
2151 Parser::TryParseFunctionDeclarator(bool MayHaveTrailingReturnType
) {
2152 // The '(' is already parsed.
2154 TPResult TPR
= TryParseParameterDeclarationClause();
2155 if (TPR
== TPResult::Ambiguous
&& Tok
.isNot(tok::r_paren
))
2156 TPR
= TPResult::False
;
2158 if (TPR
== TPResult::False
|| TPR
== TPResult::Error
)
2161 // Parse through the parens.
2162 if (!SkipUntil(tok::r_paren
, StopAtSemi
))
2163 return TPResult::Error
;
2166 while (Tok
.isOneOf(tok::kw_const
, tok::kw_volatile
, tok::kw___unaligned
,
2170 // ref-qualifier[opt]
2171 if (Tok
.isOneOf(tok::amp
, tok::ampamp
))
2174 // exception-specification
2175 if (Tok
.is(tok::kw_throw
)) {
2177 if (Tok
.isNot(tok::l_paren
))
2178 return TPResult::Error
;
2180 // Parse through the parens after 'throw'.
2182 if (!SkipUntil(tok::r_paren
, StopAtSemi
))
2183 return TPResult::Error
;
2185 if (Tok
.is(tok::kw_noexcept
)) {
2187 // Possibly an expression as well.
2188 if (Tok
.is(tok::l_paren
)) {
2189 // Find the matching rparen.
2191 if (!SkipUntil(tok::r_paren
, StopAtSemi
))
2192 return TPResult::Error
;
2196 // attribute-specifier-seq
2197 if (!TrySkipAttributes())
2198 return TPResult::Ambiguous
;
2200 // trailing-return-type
2201 if (Tok
.is(tok::arrow
) && MayHaveTrailingReturnType
) {
2202 if (TPR
== TPResult::True
)
2205 if (Tok
.is(tok::identifier
) && NameAfterArrowIsNonType()) {
2206 return TPResult::False
;
2208 if (isCXXTypeId(TentativeCXXTypeIdContext::TypeIdInTrailingReturnType
))
2209 return TPResult::True
;
2212 return TPResult::Ambiguous
;
2215 // When parsing an identifier after an arrow it may be a member expression,
2216 // in which case we should not annotate it as an independant expression
2217 // so we just lookup that name, if it's not a type the construct is not
2218 // a function declaration.
2219 bool Parser::NameAfterArrowIsNonType() {
2220 assert(Tok
.is(tok::identifier
));
2221 Token Next
= NextToken();
2222 if (Next
.is(tok::coloncolon
))
2224 IdentifierInfo
*Name
= Tok
.getIdentifierInfo();
2225 SourceLocation NameLoc
= Tok
.getLocation();
2227 TentativeParseCCC
CCC(Next
);
2228 Sema::NameClassification Classification
=
2229 Actions
.ClassifyName(getCurScope(), SS
, Name
, NameLoc
, Next
, &CCC
);
2230 switch (Classification
.getKind()) {
2231 case Sema::NC_OverloadSet
:
2232 case Sema::NC_NonType
:
2233 case Sema::NC_VarTemplate
:
2234 case Sema::NC_FunctionTemplate
:
2242 /// '[' constant-expression[opt] ']'
2244 Parser::TPResult
Parser::TryParseBracketDeclarator() {
2247 // A constant-expression cannot begin with a '{', but the
2248 // expr-or-braced-init-list of a postfix-expression can.
2249 if (Tok
.is(tok::l_brace
))
2250 return TPResult::False
;
2252 if (!SkipUntil(tok::r_square
, tok::comma
, StopAtSemi
| StopBeforeMatch
))
2253 return TPResult::Error
;
2255 // If we hit a comma before the ']', this is not a constant-expression,
2256 // but might still be the expr-or-braced-init-list of a postfix-expression.
2257 if (Tok
.isNot(tok::r_square
))
2258 return TPResult::False
;
2261 return TPResult::Ambiguous
;
2264 /// Determine whether we might be looking at the '<' template-argument-list '>'
2265 /// of a template-id or simple-template-id, rather than a less-than comparison.
2266 /// This will often fail and produce an ambiguity, but should never be wrong
2267 /// if it returns True or False.
2268 Parser::TPResult
Parser::isTemplateArgumentList(unsigned TokensToSkip
) {
2269 if (!TokensToSkip
) {
2270 if (Tok
.isNot(tok::less
))
2271 return TPResult::False
;
2272 if (NextToken().is(tok::greater
))
2273 return TPResult::True
;
2276 RevertingTentativeParsingAction
PA(*this);
2278 while (TokensToSkip
) {
2283 if (!TryConsumeToken(tok::less
))
2284 return TPResult::False
;
2286 // We can't do much to tell an expression apart from a template-argument,
2287 // but one good distinguishing factor is that a "decl-specifier" not
2288 // followed by '(' or '{' can't appear in an expression.
2289 bool InvalidAsTemplateArgumentList
= false;
2290 if (isCXXDeclarationSpecifier(ImplicitTypenameContext::No
, TPResult::False
,
2291 &InvalidAsTemplateArgumentList
) ==
2293 return TPResult::True
;
2294 if (InvalidAsTemplateArgumentList
)
2295 return TPResult::False
;
2297 // FIXME: In many contexts, X<thing1, Type> can only be a
2298 // template-argument-list. But that's not true in general:
2302 // int a = A<B, b, c = C>D; // OK, declares b, not a template-id.
2304 // X<Y<0, int> // ', int>' might be end of X's template argument list
2306 // We might be able to disambiguate a few more cases if we're careful.
2308 // A template-argument-list must be terminated by a '>'.
2309 if (SkipUntil({tok::greater
, tok::greatergreater
, tok::greatergreatergreater
},
2310 StopAtSemi
| StopBeforeMatch
))
2311 return TPResult::Ambiguous
;
2312 return TPResult::False
;
2315 /// Determine whether we might be looking at the '(' of a C++20 explicit(bool)
2316 /// in an earlier language mode.
2317 Parser::TPResult
Parser::isExplicitBool() {
2318 assert(Tok
.is(tok::l_paren
) && "expected to be looking at a '(' token");
2320 RevertingTentativeParsingAction
PA(*this);
2323 // We can only have 'explicit' on a constructor, conversion function, or
2324 // deduction guide. The declarator of a deduction guide cannot be
2325 // parenthesized, so we know this isn't a deduction guide. So the only
2326 // thing we need to check for is some number of parens followed by either
2327 // the current class name or 'operator'.
2328 while (Tok
.is(tok::l_paren
))
2331 if (TryAnnotateOptionalCXXScopeToken())
2332 return TPResult::Error
;
2334 // Class-scope constructor and conversion function names can't really be
2335 // qualified, but we get better diagnostics if we assume they can be.
2337 if (Tok
.is(tok::annot_cxxscope
)) {
2338 Actions
.RestoreNestedNameSpecifierAnnotation(Tok
.getAnnotationValue(),
2339 Tok
.getAnnotationRange(),
2341 ConsumeAnnotationToken();
2344 // 'explicit(operator' might be explicit(bool) or the declaration of a
2345 // conversion function, but it's probably a conversion function.
2346 if (Tok
.is(tok::kw_operator
))
2347 return TPResult::Ambiguous
;
2349 // If this can't be a constructor name, it can only be explicit(bool).
2350 if (Tok
.isNot(tok::identifier
) && Tok
.isNot(tok::annot_template_id
))
2351 return TPResult::True
;
2352 if (!Actions
.isCurrentClassName(Tok
.is(tok::identifier
)
2353 ? *Tok
.getIdentifierInfo()
2354 : *takeTemplateIdAnnotation(Tok
)->Name
,
2355 getCurScope(), &SS
))
2356 return TPResult::True
;
2357 // Formally, we must have a right-paren after the constructor name to match
2358 // the grammar for a constructor. But clang permits a parenthesized
2359 // constructor declarator, so also allow a constructor declarator to follow
2360 // with no ')' token after the constructor name.
2361 if (!NextToken().is(tok::r_paren
) &&
2362 !isConstructorDeclarator(/*Unqualified=*/SS
.isEmpty(),
2363 /*DeductionGuide=*/false))
2364 return TPResult::True
;
2366 // Might be explicit(bool) or a parenthesized constructor name.
2367 return TPResult::Ambiguous
;