clang 18.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
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.
22///
23/// declaration-statement:
24/// block-declaration
25///
26/// block-declaration:
27/// simple-declaration
28/// asm-definition
29/// namespace-alias-definition
30/// using-declaration
31/// using-directive
32/// [C++0x] static_assert-declaration
33///
34/// asm-definition:
35/// 'asm' '(' string-literal ')' ';'
36///
37/// namespace-alias-definition:
38/// 'namespace' identifier = qualified-namespace-specifier ';'
39///
40/// using-declaration:
41/// 'using' typename[opt] '::'[opt] nested-name-specifier
42/// unqualified-id ';'
43/// 'using' '::' unqualified-id ;
44///
45/// using-directive:
46/// 'using' 'namespace' '::'[opt] nested-name-specifier[opt]
47/// namespace-name ';'
48///
49bool Parser::isCXXDeclarationStatement(
50 bool DisambiguatingWithExpression /*=false*/) {
51 assert(getLangOpts().CPlusPlus && "Must be called for C++ only.");
52
53 switch (Tok.getKind()) {
54 // asm-definition
55 case tok::kw_asm:
56 // namespace-alias-definition
57 case tok::kw_namespace:
58 // using-declaration
59 // using-directive
60 case tok::kw_using:
61 // static_assert-declaration
62 case tok::kw_static_assert:
63 case tok::kw__Static_assert:
64 return true;
65 case tok::coloncolon:
66 case tok::identifier: {
67 if (DisambiguatingWithExpression) {
68 RevertingTentativeParsingAction TPA(*this);
69 // Parse the C++ scope specifier.
70 CXXScopeSpec SS;
71 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
72 /*ObjectHasErrors=*/false,
73 /*EnteringContext=*/true);
74
75 switch (Tok.getKind()) {
76 case tok::identifier: {
78 bool isDeductionGuide = Actions.isDeductionGuideName(
79 getCurScope(), *II, Tok.getLocation(), SS, /*Template=*/nullptr);
80 if (Actions.isCurrentClassName(*II, getCurScope(), &SS) ||
81 isDeductionGuide) {
82 if (isConstructorDeclarator(/*Unqualified=*/SS.isEmpty(),
83 isDeductionGuide,
85 return true;
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))
96 return true;
97 }
98 break;
99 }
100 case tok::kw_operator:
101 return true;
102 case tok::tilde:
103 return true;
104 default:
105 break;
106 }
107 }
108 }
109 [[fallthrough]];
110 // simple-declaration
111 default:
112 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
113 }
114}
115
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.
121///
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]
126///
127/// (if AllowForRangeDecl specified)
128/// for ( for-range-declaration : for-range-initializer ) statement
129///
130/// for-range-declaration:
131/// decl-specifier-seq declarator
132/// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
133///
134/// In any of the above cases there can be a preceding attribute-specifier-seq,
135/// but the caller is expected to handle that.
136bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
137 // C++ 6.8p1:
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].
145
146 // C++ 6.8p3:
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.
153
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
159 // a case.
160
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
166 // TPResult::Error.
167
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)
174 return false;
175
176 // FIXME: Add statistics about the number of ambiguous statements encountered
177 // and how they were resolved (number of declarations+number of expressions).
178
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
181 // parsing...
182
183 {
184 RevertingTentativeParsingAction PA(*this);
185 TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
186 }
187
188 // In case of an error, let the declaration parsing code handle it.
189 if (TPR == TPResult::Error)
190 return true;
191
192 // Declarations take precedence over expressions.
193 if (TPR == TPResult::Ambiguous)
194 TPR = TPResult::True;
195
196 assert(TPR == TPResult::True || TPR == TPResult::False);
197 return TPR == TPResult::True;
198}
199
200/// Try to consume a token sequence that we've already identified as
201/// (potentially) starting a decl-specifier.
202Parser::TPResult Parser::TryConsumeDeclarationSpecifier() {
203 switch (Tok.getKind()) {
204 case tok::kw__Atomic:
205 if (NextToken().isNot(tok::l_paren)) {
206 ConsumeToken();
207 break;
208 }
209 [[fallthrough]];
210 case tok::kw_typeof:
211 case tok::kw___attribute:
212#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
213#include "clang/Basic/TransformTypeTraits.def"
214 {
215 ConsumeToken();
216 if (Tok.isNot(tok::l_paren))
217 return TPResult::Error;
218 ConsumeParen();
219 if (!SkipUntil(tok::r_paren))
220 return TPResult::Error;
221 break;
222 }
223
224 case tok::kw_class:
225 case tok::kw_struct:
226 case tok::kw_union:
227 case tok::kw___interface:
228 case tok::kw_enum:
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
234 //
235 // FIXME: We don't support class-specifiers nor enum-specifiers here.
236 ConsumeToken();
237
238 // Skip attributes.
239 if (!TrySkipAttributes())
240 return TPResult::Error;
241
243 return TPResult::Error;
244 if (Tok.is(tok::annot_cxxscope))
245 ConsumeAnnotationToken();
246 if (Tok.is(tok::identifier))
247 ConsumeToken();
248 else if (Tok.is(tok::annot_template_id))
249 ConsumeAnnotationToken();
250 else
251 return TPResult::Error;
252 break;
253
254 case tok::annot_cxxscope:
255 ConsumeAnnotationToken();
256 [[fallthrough]];
257 default:
259
260 if (getLangOpts().ObjC && Tok.is(tok::less))
261 return TryParseProtocolQualifiers();
262 break;
263 }
264
265 return TPResult::Ambiguous;
266}
267
268/// simple-declaration:
269/// decl-specifier-seq init-declarator-list[opt] ';'
270///
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
275///
276Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
277 bool DeclSpecifierIsAuto = Tok.is(tok::kw_auto);
278 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
279 return TPResult::Error;
280
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)
289 return TPR;
290 assert(TPR == TPResult::False);
291 }
292
293 TPResult TPR = TryParseInitDeclaratorList(
294 /*mayHaveTrailingReturnType=*/DeclSpecifierIsAuto);
295 if (TPR != TPResult::Ambiguous)
296 return TPR;
297
298 if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
299 return TPResult::False;
300
301 return TPResult::Ambiguous;
302}
303
304/// Tentatively parse an init-declarator-list in order to disambiguate it from
305/// an expression.
306///
307/// init-declarator-list:
308/// init-declarator
309/// init-declarator-list ',' init-declarator
310///
311/// init-declarator:
312/// declarator initializer[opt]
313/// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
314///
315/// initializer:
316/// brace-or-equal-initializer
317/// '(' expression-list ')'
318///
319/// brace-or-equal-initializer:
320/// '=' initializer-clause
321/// [C++11] braced-init-list
322///
323/// initializer-clause:
324/// assignment-expression
325/// braced-init-list
326///
327/// braced-init-list:
328/// '{' initializer-list ','[opt] '}'
329/// '{' '}'
330///
331Parser::TPResult
332Parser::TryParseInitDeclaratorList(bool MayHaveTrailingReturnType) {
333 while (true) {
334 // declarator
335 TPResult TPR = TryParseDeclarator(
336 /*mayBeAbstract=*/false,
337 /*mayHaveIdentifier=*/true,
338 /*mayHaveDirectInit=*/false,
339 /*mayHaveTrailingReturnType=*/MayHaveTrailingReturnType);
340 if (TPR != TPResult::Ambiguous)
341 return TPR;
342
343 // [GNU] simple-asm-expr[opt] attributes[opt]
344 if (Tok.isOneOf(tok::kw_asm, tok::kw___attribute))
345 return TPResult::True;
346
347 // initializer[opt]
348 if (Tok.is(tok::l_paren)) {
349 // Parse through the parens.
350 ConsumeParen();
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
361 // for this case.
362 //
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.
367 //
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;
375 }
376
377 if (!TryConsumeToken(tok::comma))
378 break;
379 }
380
381 return TPResult::Ambiguous;
382}
383
386 bool CanBeExpression = true;
387 bool CanBeCondition = true;
390
395
396 bool resolved() {
399 }
400
402 CanBeExpression = false;
403
404 if (!resolved()) {
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;
414 while (true) {
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;
422 else {
424 return;
425 }
426 } else {
427 CanBeForRangeDecl = false;
428 break;
429 }
430 P.ConsumeToken();
431 }
432 } else {
433 // Just skip until we hit a ')' or ';'.
434 P.SkipUntil(tok::r_paren, tok::semi, StopBeforeMatch);
435 }
436 if (P.Tok.isNot(tok::r_paren))
438 if (P.Tok.isNot(tok::semi))
439 CanBeInitStatement = false;
440 }
441 }
442
444 CanBeCondition = false;
445 return resolved();
446 }
447
449 CanBeForRangeDecl = false;
450 return resolved();
451 }
452
453 bool update(TPResult IsDecl) {
454 switch (IsDecl) {
455 case TPResult::True:
457 assert(resolved() && "can't continue after tentative parsing bails out");
458 break;
459 case TPResult::False:
461 break;
462 case TPResult::Ambiguous:
463 break;
464 case TPResult::Error:
466 CanBeForRangeDecl = false;
467 break;
468 }
469 return resolved();
470 }
471
472 ConditionOrInitStatement result() const {
474 CanBeForRangeDecl < 2 &&
475 "result called but not yet resolved");
476 if (CanBeExpression)
477 return ConditionOrInitStatement::Expression;
478 if (CanBeCondition)
479 return ConditionOrInitStatement::ConditionDecl;
481 return ConditionOrInitStatement::InitStmtDecl;
483 return ConditionOrInitStatement::ForRangeDecl;
484 return ConditionOrInitStatement::Error;
485 }
486};
487
488bool Parser::isEnumBase(bool AllowSemi) {
489 assert(Tok.is(tok::colon) && "should be looking at the ':'");
490
491 RevertingTentativeParsingAction PA(*this);
492 // ':'
493 ConsumeToken();
494
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
499 // interpretation.
500 TPResult R = isCXXDeclarationSpecifier(ImplicitTypenameContext::No,
501 /*BracedCastResult=*/TPResult::True,
502 &InvalidAsDeclSpec);
503 if (R == TPResult::Ambiguous) {
504 // We either have a decl-specifier followed by '(' or an undeclared
505 // identifier.
506 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
507 return true;
508
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)))
512 return true;
513
514 // A second decl-specifier unambiguously indicatges an enum-base.
515 R = isCXXDeclarationSpecifier(ImplicitTypenameContext::No, TPResult::True,
516 &InvalidAsDeclSpec);
517 }
518
519 return R != TPResult::False;
520}
521
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.
525///
526/// condition:
527/// expression
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] ';'
535///
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).
539Parser::ConditionOrInitStatement
540Parser::isCXXConditionDeclarationOrInitStatement(bool CanBeInitStatement,
541 bool CanBeForRangeDecl) {
542 ConditionDeclarationOrInitStatementState State(*this, CanBeInitStatement,
543 CanBeForRangeDecl);
544
545 if (CanBeInitStatement && Tok.is(tok::kw_using))
546 return ConditionOrInitStatement::InitStmtDecl;
547 if (State.update(isCXXDeclarationSpecifier(ImplicitTypenameContext::No)))
548 return State.result();
549
550 // It might be a declaration; we need tentative parsing.
551 RevertingTentativeParsingAction PA(*this);
552
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 '('");
558
559 while (true) {
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();
567
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();
575 }
576
577 // A colon here identifies a for-range declaration.
578 if (State.CanBeForRangeDecl && Tok.is(tok::colon))
579 return ConditionOrInitStatement::ForRangeDecl;
580
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();
585
586 // Likewise, it can't be a for-range declaration any more.
587 if (State.markNotForRangeDecl())
588 return State.result();
589
590 // A parenthesized initializer could be part of an expression or a
591 // simple-declaration.
592 if (Tok.is(tok::l_paren)) {
593 ConsumeParen();
594 SkipUntil(tok::r_paren, StopAtSemi);
595 }
596
597 if (!TryConsumeToken(tok::comma))
598 break;
599 }
600
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;
606 else
607 return ConditionOrInitStatement::Expression;
608}
609
610 /// Determine whether the next set of tokens contains a type-id.
611 ///
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.
623 ///
624 /// type-id:
625 /// type-specifier-seq abstract-declarator[opt]
626 ///
627bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
628
629 isAmbiguous = false;
630
631 // C++ 8.2p2:
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.
637
638 TPResult TPR = isCXXDeclarationSpecifier(ImplicitTypenameContext::No);
639 if (TPR != TPResult::Ambiguous)
640 return TPR != TPResult::False; // Returns true for TPResult::True or
641 // TPResult::Error.
642
643 // FIXME: Add statistics about the number of ambiguous statements encountered
644 // and how they were resolved (number of declarations+number of expressions).
645
646 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
647 // We need tentative parsing...
648
649 RevertingTentativeParsingAction PA(*this);
650 bool MayHaveTrailingReturnType = Tok.is(tok::kw_auto);
651
652 // type-specifier-seq
653 TryConsumeDeclarationSpecifier();
654 assert(Tok.is(tok::l_paren) && "Expected '('");
655
656 // declarator
657 TPR = TryParseDeclarator(true /*mayBeAbstract*/, false /*mayHaveIdentifier*/,
658 /*mayHaveDirectInit=*/false,
659 MayHaveTrailingReturnType);
660
661 // In case of an error, let the declaration parsing code handle it.
662 if (TPR == TPResult::Error)
663 TPR = TPResult::True;
664
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;
670 isAmbiguous = 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;
676 isAmbiguous = 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) ||
684 (Tok.isOneOf(tok::greatergreater,
685 tok::greatergreatergreater) ||
686 (Tok.is(tok::ellipsis) &&
687 NextToken().isOneOf(tok::greater, tok::greatergreater,
688 tok::greatergreatergreater,
689 tok::comma)))))) {
690 TPR = TPResult::True;
691 isAmbiguous = true;
692
693 } else if (Context == TypeIdInTrailingReturnType) {
694 TPR = TPResult::True;
695 isAmbiguous = true;
696 } else
697 TPR = TPResult::False;
698 }
699
700 assert(TPR == TPResult::True || TPR == TPResult::False);
701 return TPR == TPResult::True;
702}
703
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.
708///
709/// If Disambiguate is true, we try harder to determine whether a '[[' starts
710/// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
711///
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.
715///
716/// C++11 [dcl.attr.grammar]:
717///
718/// attribute-specifier:
719/// '[' '[' attribute-list ']' ']'
720/// alignment-specifier
721///
722/// attribute-list:
723/// attribute[opt]
724/// attribute-list ',' attribute[opt]
725/// attribute '...'
726/// attribute-list ',' attribute '...'
727///
728/// attribute:
729/// attribute-token attribute-argument-clause[opt]
730///
731/// attribute-token:
732/// identifier
733/// identifier '::' identifier
734///
735/// attribute-argument-clause:
736/// '(' balanced-token-seq ')'
737Parser::CXX11AttributeKind
738Parser::isCXX11AttributeSpecifier(bool Disambiguate,
739 bool OuterMightBeMessageSend) {
740 if (Tok.is(tok::kw_alignas))
741 return CAK_AttributeSpecifier;
742
744 return CAK_AttributeSpecifier;
745
746 if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
747 return CAK_NotAttributeSpecifier;
748
749 // No tentative parsing if we don't need to look for ']]' or a lambda.
750 if (!Disambiguate && !getLangOpts().ObjC)
751 return CAK_AttributeSpecifier;
752
753 // '[[using ns: ...]]' is an attribute.
754 if (GetLookAheadToken(2).is(tok::kw_using))
755 return CAK_AttributeSpecifier;
756
757 RevertingTentativeParsingAction PA(*this);
758
759 // Opening brackets were checked for above.
760 ConsumeBracket();
761
762 if (!getLangOpts().ObjC) {
763 ConsumeBracket();
764
765 bool IsAttribute = SkipUntil(tok::r_square);
766 IsAttribute &= Tok.is(tok::r_square);
767
768 return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
769 }
770
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.
779
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.
783 {
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;
792 }
793
794 switch (Tentative) {
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;
799
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;
806
807 if (OuterMightBeMessageSend)
808 // Case 4: Lambda in message send.
809 return CAK_NotAttributeSpecifier;
810
811 // Case 2: Lambda in array size / index.
812 return CAK_InvalidAttributeSpecifier;
813
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.
817 break;
818 }
819 }
820
821 ConsumeBracket();
822
823 // If we don't have a lambda-introducer, then we have an attribute or a
824 // message-send.
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;
830 }
831
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.
837 SourceLocation Loc;
838 if (!TryParseCXX11AttributeIdentifier(Loc)) {
839 IsAttribute = false;
840 break;
841 }
842 if (Tok.is(tok::coloncolon)) {
843 ConsumeToken();
844 if (!TryParseCXX11AttributeIdentifier(Loc)) {
845 IsAttribute = false;
846 break;
847 }
848 }
849
850 // Parse the attribute-argument-clause, if present.
851 if (Tok.is(tok::l_paren)) {
852 ConsumeParen();
853 if (!SkipUntil(tok::r_paren)) {
854 IsAttribute = false;
855 break;
856 }
857 }
858
859 TryConsumeToken(tok::ellipsis);
860
861 if (!TryConsumeToken(tok::comma))
862 break;
863 }
864
865 // An attribute must end ']]'.
866 if (IsAttribute) {
867 if (Tok.is(tok::r_square)) {
868 ConsumeBracket();
869 IsAttribute = Tok.is(tok::r_square);
870 } else {
871 IsAttribute = false;
872 }
873 }
874
875 if (IsAttribute)
876 // Case 1: C++11 statement attribute.
877 return CAK_AttributeSpecifier;
878
879 // Case 3: Message send.
880 return CAK_NotAttributeSpecifier;
881}
882
883bool Parser::TrySkipAttributes() {
884 while (Tok.isOneOf(tok::l_square, tok::kw___attribute, tok::kw___declspec,
885 tok::kw_alignas) ||
887 if (Tok.is(tok::l_square)) {
888 ConsumeBracket();
889 if (Tok.isNot(tok::l_square))
890 return false;
891 ConsumeBracket();
892 if (!SkipUntil(tok::r_square) || Tok.isNot(tok::r_square))
893 return false;
894 // Note that explicitly checking for `[[` and `]]` allows to fail as
895 // expected in the case of the Objective-C message send syntax.
896 ConsumeBracket();
897 } else if (Tok.isRegularKeywordAttribute()) {
898 ConsumeToken();
899 } else {
900 ConsumeToken();
901 if (Tok.isNot(tok::l_paren))
902 return false;
903 ConsumeParen();
904 if (!SkipUntil(tok::r_paren))
905 return false;
906 }
907 }
908
909 return true;
910}
911
912Parser::TPResult Parser::TryParsePtrOperatorSeq() {
913 while (true) {
915 return TPResult::Error;
916
917 if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) ||
918 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
919 // ptr-operator
921
922 // Skip attributes.
923 if (!TrySkipAttributes())
924 return TPResult::Error;
925
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,
929 tok::kw__Atomic))
930 ConsumeToken();
931 } else {
932 return TPResult::True;
933 }
934 }
935}
936
937/// operator-function-id:
938/// 'operator' operator
939///
940/// operator: one of
941/// new delete new[] delete[] + - * / % ^ [...]
942///
943/// conversion-function-id:
944/// 'operator' conversion-type-id
945///
946/// conversion-type-id:
947/// type-specifier-seq conversion-declarator[opt]
948///
949/// conversion-declarator:
950/// ptr-operator conversion-declarator[opt]
951///
952/// literal-operator-id:
953/// 'operator' string-literal identifier
954/// 'operator' user-defined-string-literal
955Parser::TPResult Parser::TryParseOperatorId() {
956 assert(Tok.is(tok::kw_operator));
957 ConsumeToken();
958
959 // Maybe this is an operator-function-id.
960 switch (Tok.getKind()) {
961 case tok::kw_new: case tok::kw_delete:
962 ConsumeToken();
963 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
964 ConsumeBracket();
965 ConsumeBracket();
966 }
967 return TPResult::True;
968
969#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
970 case tok::Token:
971#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
972#include "clang/Basic/OperatorKinds.def"
973 ConsumeToken();
974 return TPResult::True;
975
976 case tok::l_square:
977 if (NextToken().is(tok::r_square)) {
978 ConsumeBracket();
979 ConsumeBracket();
980 return TPResult::True;
981 }
982 break;
983
984 case tok::l_paren:
985 if (NextToken().is(tok::r_paren)) {
986 ConsumeParen();
987 ConsumeParen();
988 return TPResult::True;
989 }
990 break;
991
992 default:
993 break;
994 }
995
996 // Maybe this is a literal-operator-id.
997 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
998 bool FoundUDSuffix = false;
999 do {
1000 FoundUDSuffix |= Tok.hasUDSuffix();
1001 ConsumeStringToken();
1002 } while (isTokenStringLiteral());
1003
1004 if (!FoundUDSuffix) {
1005 if (Tok.is(tok::identifier))
1006 ConsumeToken();
1007 else
1008 return TPResult::Error;
1009 }
1010 return TPResult::True;
1011 }
1012
1013 // Maybe this is a conversion-function-id.
1014 bool AnyDeclSpecifiers = false;
1015 while (true) {
1016 TPResult TPR = isCXXDeclarationSpecifier(ImplicitTypenameContext::No);
1017 if (TPR == TPResult::Error)
1018 return TPR;
1019 if (TPR == TPResult::False) {
1020 if (!AnyDeclSpecifiers)
1021 return TPResult::Error;
1022 break;
1023 }
1024 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
1025 return TPResult::Error;
1026 AnyDeclSpecifiers = true;
1027 }
1028 return TryParsePtrOperatorSeq();
1029}
1030
1031/// declarator:
1032/// direct-declarator
1033/// ptr-operator declarator
1034///
1035/// direct-declarator:
1036/// declarator-id
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 ')'
1042///
1043/// abstract-declarator:
1044/// ptr-operator abstract-declarator[opt]
1045/// direct-abstract-declarator
1046///
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 ')'
1053/// [C++0x] ...
1054///
1055/// ptr-operator:
1056/// '*' cv-qualifier-seq[opt]
1057/// '&'
1058/// [C++0x] '&&' [TODO]
1059/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
1060///
1061/// cv-qualifier-seq:
1062/// cv-qualifier cv-qualifier-seq[opt]
1063///
1064/// cv-qualifier:
1065/// 'const'
1066/// 'volatile'
1067///
1068/// declarator-id:
1069/// '...'[opt] id-expression
1070///
1071/// id-expression:
1072/// unqualified-id
1073/// qualified-id [TODO]
1074///
1075/// unqualified-id:
1076/// identifier
1077/// operator-function-id
1078/// conversion-function-id
1079/// literal-operator-id
1080/// '~' class-name [TODO]
1081/// '~' decltype-specifier [TODO]
1082/// template-id [TODO]
1083///
1084Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
1085 bool mayHaveIdentifier,
1086 bool mayHaveDirectInit,
1087 bool mayHaveTrailingReturnType) {
1088 // declarator:
1089 // direct-declarator
1090 // ptr-operator declarator
1091 if (TryParsePtrOperatorSeq() == TPResult::Error)
1092 return TPResult::Error;
1093
1094 // direct-declarator:
1095 // direct-abstract-declarator:
1096 if (Tok.is(tok::ellipsis))
1097 ConsumeToken();
1098
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) {
1103 // declarator-id
1104 if (Tok.is(tok::annot_cxxscope)) {
1105 CXXScopeSpec SS;
1107 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
1108 if (SS.isInvalid())
1109 return TPResult::Error;
1110 ConsumeAnnotationToken();
1111 } else if (Tok.is(tok::identifier)) {
1112 TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
1113 }
1114 if (Tok.is(tok::kw_operator)) {
1115 if (TryParseOperatorId() == TPResult::Error)
1116 return TPResult::Error;
1117 } else
1118 ConsumeToken();
1119 } else if (Tok.is(tok::l_paren)) {
1120 ConsumeParen();
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)
1131 return TPR;
1132 } else {
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)
1142 return TPR;
1143 if (Tok.isNot(tok::r_paren))
1144 return TPResult::False;
1145 ConsumeParen();
1146 }
1147 } else if (!mayBeAbstract) {
1148 return TPResult::False;
1149 }
1150
1151 if (mayHaveDirectInit)
1152 return TPResult::Ambiguous;
1153
1154 while (true) {
1155 TPResult TPR(TPResult::Ambiguous);
1156
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
1161 // are allowed.
1162 if (!mayBeAbstract && !isCXXFunctionDeclarator())
1163 break;
1164
1165 // direct-declarator '(' parameter-declaration-clause ')'
1166 // cv-qualifier-seq[opt] exception-specification[opt]
1167 ConsumeParen();
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;
1177 } else {
1178 break;
1179 }
1180
1181 if (TPR != TPResult::Ambiguous)
1182 return TPR;
1183 }
1184
1185 return TPResult::Ambiguous;
1186}
1187
1188bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
1189 return llvm::is_contained(TentativelyDeclaredIdentifiers, II);
1190}
1191
1192namespace {
1193class TentativeParseCCC final : public CorrectionCandidateCallback {
1194public:
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);
1200 }
1201
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(); }))
1208 return false;
1209
1211 }
1212
1213 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1214 return std::make_unique<TentativeParseCCC>(*this);
1215 }
1216};
1217}
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.
1222///
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:
1231///
1232/// * When parsing X::Y (with no 'typename') where X is dependent
1233/// * When parsing X<Y> where X is undeclared
1234///
1235/// decl-specifier:
1236/// storage-class-specifier
1237/// type-specifier
1238/// function-specifier
1239/// 'friend'
1240/// 'typedef'
1241/// [C++11] 'constexpr'
1242/// [C++20] 'consteval'
1243/// [GNU] attributes declaration-specifiers[opt]
1244///
1245/// storage-class-specifier:
1246/// 'register'
1247/// 'static'
1248/// 'extern'
1249/// 'mutable'
1250/// 'auto'
1251/// [GNU] '__thread'
1252/// [C++11] 'thread_local'
1253/// [C11] '_Thread_local'
1254///
1255/// function-specifier:
1256/// 'inline'
1257/// 'virtual'
1258/// 'explicit'
1259///
1260/// typedef-name:
1261/// identifier
1262///
1263/// type-specifier:
1264/// simple-type-specifier
1265/// class-specifier
1266/// enum-specifier
1267/// elaborated-type-specifier
1268/// typename-specifier
1269/// cv-qualifier
1270///
1271/// simple-type-specifier:
1272/// '::'[opt] nested-name-specifier[opt] type-name
1273/// '::'[opt] nested-name-specifier 'template'
1274/// simple-template-id [TODO]
1275/// 'char'
1276/// 'wchar_t'
1277/// 'bool'
1278/// 'short'
1279/// 'int'
1280/// 'long'
1281/// 'signed'
1282/// 'unsigned'
1283/// 'float'
1284/// 'double'
1285/// 'void'
1286/// [GNU] typeof-specifier
1287/// [GNU] '_Complex'
1288/// [C++11] 'auto'
1289/// [GNU] '__auto_type'
1290/// [C++11] 'decltype' ( expression )
1291/// [C++1y] 'decltype' ( 'auto' )
1292///
1293/// type-name:
1294/// class-name
1295/// enum-name
1296/// typedef-name
1297///
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
1303///
1304/// enum-name:
1305/// identifier
1306///
1307/// enum-specifier:
1308/// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
1309/// 'enum' identifier[opt] '{' enumerator-list ',' '}'
1310///
1311/// class-specifier:
1312/// class-head '{' member-specification[opt] '}'
1313///
1314/// class-head:
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]
1319///
1320/// class-key:
1321/// 'class'
1322/// 'struct'
1323/// 'union'
1324///
1325/// cv-qualifier:
1326/// 'const'
1327/// 'volatile'
1328/// [GNU] restrict
1329///
1330Parser::TPResult
1331Parser::isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
1332 Parser::TPResult BracedCastResult,
1333 bool *InvalidAsDeclSpec) {
1334 auto IsPlaceholderSpecifier = [&](TemplateIdAnnotation *TemplateId,
1335 int Lookahead) {
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.
1345 tok::identifier,
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)));
1362 };
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;
1369
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;
1374
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)) {
1382 case ANK_Error:
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))
1395 break;
1396 }
1397
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;
1403 case ANK_Success:
1404 break;
1405 }
1406 assert(Tok.isNot(tok::identifier) &&
1407 "TryAnnotateName succeeded without producing an annotation");
1408 } else {
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
1417 // ambiguous.
1418 if (Tok.is(tok::identifier))
1419 return TPResult::False;
1420 }
1421
1422 // We annotated this token as something. Recurse to handle whatever we got.
1423 return isCXXDeclarationSpecifier(AllowImplicitTypename, BracedCastResult,
1424 InvalidAsDeclSpec);
1425 }
1426
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.
1431 return TPResult::Error;
1432 return isCXXDeclarationSpecifier(ImplicitTypenameContext::Yes,
1433 BracedCastResult, InvalidAsDeclSpec);
1434
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;
1443 }
1444
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;
1450 [[fallthrough]];
1451 }
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,
1459 InvalidAsDeclSpec);
1460
1461 // decl-specifier:
1462 // storage-class-specifier
1463 // type-specifier
1464 // function-specifier
1465 // 'friend'
1466 // 'typedef'
1467 // 'constexpr'
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:
1485
1486 // Modules
1487 case tok::kw___module_private__:
1488
1489 // Debugger support
1490 case tok::kw___unknown_anytype:
1491
1492 // type-specifier:
1493 // simple-type-specifier
1494 // class-specifier
1495 // enum-specifier
1496 // elaborated-type-specifier
1497 // typename-specifier
1498 // cv-qualifier
1499
1500 // class-specifier
1501 // elaborated-type-specifier
1502 case tok::kw_class:
1503 case tok::kw_struct:
1504 case tok::kw_union:
1505 case tok::kw___interface:
1506 // enum-specifier
1507 case tok::kw_enum:
1508 // cv-qualifier
1509 case tok::kw_const:
1510 case tok::kw_volatile:
1511 return TPResult::True;
1512
1513 // OpenCL address space qualifiers
1514 case tok::kw_private:
1515 if (!getLangOpts().OpenCL)
1516 return TPResult::False;
1517 [[fallthrough]];
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:
1527 // OpenCL pipe
1528 case tok::kw_pipe:
1529
1530 // HLSL address space qualifiers
1531 case tok::kw_groupshared:
1532
1533 // GNU
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;
1539
1540 // Microsoft
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:
1548 case tok::kw___w64:
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;
1561
1562 // WebAssemblyFuncref
1563 case tok::kw___funcref:
1564 return TPResult::True;
1565
1566 // Borland
1567 case tok::kw___pascal:
1568 return TPResult::True;
1569
1570 // AltiVec
1571 case tok::kw___vector:
1572 return TPResult::True;
1573
1574 case tok::annot_template_id: {
1575 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1576 // If lookup for the template-name found nothing, don't assume we have a
1577 // definitive disambiguation result yet.
1578 if ((TemplateId->hasInvalidName() ||
1579 TemplateId->Kind == TNK_Undeclared_template) &&
1580 InvalidAsDeclSpec) {
1581 // 'template-id(' can be a valid expression but not a valid decl spec if
1582 // the template-name is not declared, but we don't consider this to be a
1583 // definitive disambiguation. In any other context, it's an error either
1584 // way.
1585 *InvalidAsDeclSpec = NextToken().is(tok::l_paren);
1586 return TPResult::Ambiguous;
1587 }
1588 if (TemplateId->hasInvalidName())
1589 return TPResult::Error;
1590 if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/0))
1591 return TPResult::True;
1592 if (TemplateId->Kind != TNK_Type_template)
1593 return TPResult::False;
1594 CXXScopeSpec SS;
1595 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
1596 assert(Tok.is(tok::annot_typename));
1597 goto case_typename;
1598 }
1599
1600 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1601 // We've already annotated a scope; try to annotate a type.
1602 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
1603 return TPResult::Error;
1604 if (!Tok.is(tok::annot_typename)) {
1605 if (Tok.is(tok::annot_cxxscope) &&
1606 NextToken().is(tok::annot_template_id)) {
1607 TemplateIdAnnotation *TemplateId =
1608 takeTemplateIdAnnotation(NextToken());
1609 if (TemplateId->hasInvalidName()) {
1610 if (InvalidAsDeclSpec) {
1611 *InvalidAsDeclSpec = NextToken().is(tok::l_paren);
1612 return TPResult::Ambiguous;
1613 }
1614 return TPResult::Error;
1615 }
1616 if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/1))
1617 return TPResult::True;
1618 }
1619 // If the next token is an identifier or a type qualifier, then this
1620 // can't possibly be a valid expression either.
1621 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1622 CXXScopeSpec SS;
1624 Tok.getAnnotationRange(),
1625 SS);
1626 if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
1627 RevertingTentativeParsingAction PA(*this);
1628 ConsumeAnnotationToken();
1629 ConsumeToken();
1630 bool isIdentifier = Tok.is(tok::identifier);
1631 TPResult TPR = TPResult::False;
1632 if (!isIdentifier)
1633 TPR = isCXXDeclarationSpecifier(
1634 AllowImplicitTypename, BracedCastResult, InvalidAsDeclSpec);
1635
1636 if (isIdentifier ||
1637 TPR == TPResult::True || TPR == TPResult::Error)
1638 return TPResult::Error;
1639
1640 if (InvalidAsDeclSpec) {
1641 // We can't tell whether this is a missing 'typename' or a valid
1642 // expression.
1643 *InvalidAsDeclSpec = true;
1644 return TPResult::Ambiguous;
1645 } else {
1646 // In MS mode, if InvalidAsDeclSpec is not provided, and the tokens
1647 // are or the form *) or &) *> or &> &&>, this can't be an expression.
1648 // The typename must be missing.
1649 if (getLangOpts().MSVCCompat) {
1650 if (((Tok.is(tok::amp) || Tok.is(tok::star)) &&
1651 (NextToken().is(tok::r_paren) ||
1652 NextToken().is(tok::greater))) ||
1653 (Tok.is(tok::ampamp) && NextToken().is(tok::greater)))
1654 return TPResult::True;
1655 }
1656 }
1657 } else {
1658 // Try to resolve the name. If it doesn't exist, assume it was
1659 // intended to name a type and keep disambiguating.
1660 switch (TryAnnotateName(/*CCC=*/nullptr, AllowImplicitTypename)) {
1661 case ANK_Error:
1662 return TPResult::Error;
1663 case ANK_TentativeDecl:
1664 return TPResult::False;
1665 case ANK_TemplateName:
1666 // In C++17, this could be a type template for class template
1667 // argument deduction.
1668 if (getLangOpts().CPlusPlus17) {
1670 return TPResult::Error;
1671 // If we annotated then the current token should not still be ::
1672 // FIXME we may want to also check for tok::annot_typename but
1673 // currently don't have a test case.
1674 if (Tok.isNot(tok::annot_cxxscope))
1675 break;
1676 }
1677
1678 // A bare type template-name which can't be a template template
1679 // argument is an error, and was probably intended to be a type.
1680 // In C++17, this could be class template argument deduction.
1681 return (getLangOpts().CPlusPlus17 || GreaterThanIsOperator)
1682 ? TPResult::True
1683 : TPResult::False;
1684 case ANK_Unresolved:
1685 return InvalidAsDeclSpec ? TPResult::Ambiguous : TPResult::False;
1686 case ANK_Success:
1687 break;
1688 }
1689
1690 // Annotated it, check again.
1691 assert(Tok.isNot(tok::annot_cxxscope) ||
1692 NextToken().isNot(tok::identifier));
1693 return isCXXDeclarationSpecifier(AllowImplicitTypename,
1694 BracedCastResult, InvalidAsDeclSpec);
1695 }
1696 }
1697 return TPResult::False;
1698 }
1699 // If that succeeded, fallthrough into the generic simple-type-id case.
1700 [[fallthrough]];
1701
1702 // The ambiguity resides in a simple-type-specifier/typename-specifier
1703 // followed by a '('. The '(' could either be the start of:
1704 //
1705 // direct-declarator:
1706 // '(' declarator ')'
1707 //
1708 // direct-abstract-declarator:
1709 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1710 // exception-specification[opt]
1711 // '(' abstract-declarator ')'
1712 //
1713 // or part of a function-style cast expression:
1714 //
1715 // simple-type-specifier '(' expression-list[opt] ')'
1716 //
1717
1718 // simple-type-specifier:
1719
1720 case tok::annot_typename:
1721 case_typename:
1722 // In Objective-C, we might have a protocol-qualified type.
1723 if (getLangOpts().ObjC && NextToken().is(tok::less)) {
1724 // Tentatively parse the protocol qualifiers.
1725 RevertingTentativeParsingAction PA(*this);
1726 ConsumeAnyToken(); // The type token
1727
1728 TPResult TPR = TryParseProtocolQualifiers();
1729 bool isFollowedByParen = Tok.is(tok::l_paren);
1730 bool isFollowedByBrace = Tok.is(tok::l_brace);
1731
1732 if (TPR == TPResult::Error)
1733 return TPResult::Error;
1734
1735 if (isFollowedByParen)
1736 return TPResult::Ambiguous;
1737
1738 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1739 return BracedCastResult;
1740
1741 return TPResult::True;
1742 }
1743 [[fallthrough]];
1744
1745 case tok::kw_char:
1746 case tok::kw_wchar_t:
1747 case tok::kw_char8_t:
1748 case tok::kw_char16_t:
1749 case tok::kw_char32_t:
1750 case tok::kw_bool:
1751 case tok::kw_short:
1752 case tok::kw_int:
1753 case tok::kw_long:
1754 case tok::kw___int64:
1755 case tok::kw___int128:
1756 case tok::kw_signed:
1757 case tok::kw_unsigned:
1758 case tok::kw_half:
1759 case tok::kw_float:
1760 case tok::kw_double:
1761 case tok::kw___bf16:
1762 case tok::kw__Float16:
1763 case tok::kw___float128:
1764 case tok::kw___ibm128:
1765 case tok::kw_void:
1766 case tok::annot_decltype:
1767 case tok::kw__Accum:
1768 case tok::kw__Fract:
1769 case tok::kw__Sat:
1770#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1771#include "clang/Basic/OpenCLImageTypes.def"
1772 if (NextToken().is(tok::l_paren))
1773 return TPResult::Ambiguous;
1774
1775 // This is a function-style cast in all cases we disambiguate other than
1776 // one:
1777 // struct S {
1778 // enum E : int { a = 4 }; // enum
1779 // enum E : int { 4 }; // bit-field
1780 // };
1781 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
1782 return BracedCastResult;
1783
1784 if (isStartOfObjCClassMessageMissingOpenBracket())
1785 return TPResult::False;
1786
1787 return TPResult::True;
1788
1789 // GNU typeof support.
1790 case tok::kw_typeof: {
1791 if (NextToken().isNot(tok::l_paren))
1792 return TPResult::True;
1793
1794 RevertingTentativeParsingAction PA(*this);
1795
1796 TPResult TPR = TryParseTypeofSpecifier();
1797 bool isFollowedByParen = Tok.is(tok::l_paren);
1798 bool isFollowedByBrace = Tok.is(tok::l_brace);
1799
1800 if (TPR == TPResult::Error)
1801 return TPResult::Error;
1802
1803 if (isFollowedByParen)
1804 return TPResult::Ambiguous;
1805
1806 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1807 return BracedCastResult;
1808
1809 return TPResult::True;
1810 }
1811
1812#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
1813#include "clang/Basic/TransformTypeTraits.def"
1814 return TPResult::True;
1815
1816 // C11 _Atomic
1817 case tok::kw__Atomic:
1818 return TPResult::True;
1819
1820 case tok::kw__BitInt:
1821 case tok::kw__ExtInt: {
1822 if (NextToken().isNot(tok::l_paren))
1823 return TPResult::Error;
1824 RevertingTentativeParsingAction PA(*this);
1825 ConsumeToken();
1826 ConsumeParen();
1827
1828 if (!SkipUntil(tok::r_paren, StopAtSemi))
1829 return TPResult::Error;
1830
1831 if (Tok.is(tok::l_paren))
1832 return TPResult::Ambiguous;
1833
1834 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
1835 return BracedCastResult;
1836
1837 return TPResult::True;
1838 }
1839 default:
1840 return TPResult::False;
1841 }
1842}
1843
1844bool Parser::isCXXDeclarationSpecifierAType() {
1845 switch (Tok.getKind()) {
1846 // typename-specifier
1847 case tok::annot_decltype:
1848 case tok::annot_template_id:
1849 case tok::annot_typename:
1850 case tok::kw_typeof:
1851#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
1852#include "clang/Basic/TransformTypeTraits.def"
1853 return true;
1854
1855 // elaborated-type-specifier
1856 case tok::kw_class:
1857 case tok::kw_struct:
1858 case tok::kw_union:
1859 case tok::kw___interface:
1860 case tok::kw_enum:
1861 return true;
1862
1863 // simple-type-specifier
1864 case tok::kw_char:
1865 case tok::kw_wchar_t:
1866 case tok::kw_char8_t:
1867 case tok::kw_char16_t:
1868 case tok::kw_char32_t:
1869 case tok::kw_bool:
1870 case tok::kw_short:
1871 case tok::kw_int:
1872 case tok::kw__ExtInt:
1873 case tok::kw__BitInt:
1874 case tok::kw_long:
1875 case tok::kw___int64:
1876 case tok::kw___int128:
1877 case tok::kw_signed:
1878 case tok::kw_unsigned:
1879 case tok::kw_half:
1880 case tok::kw_float:
1881 case tok::kw_double:
1882 case tok::kw___bf16:
1883 case tok::kw__Float16:
1884 case tok::kw___float128:
1885 case tok::kw___ibm128:
1886 case tok::kw_void:
1887 case tok::kw___unknown_anytype:
1888 case tok::kw___auto_type:
1889 case tok::kw__Accum:
1890 case tok::kw__Fract:
1891 case tok::kw__Sat:
1892#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1893#include "clang/Basic/OpenCLImageTypes.def"
1894 return true;
1895
1896 case tok::kw_auto:
1897 return getLangOpts().CPlusPlus11;
1898
1899 case tok::kw__Atomic:
1900 // "_Atomic foo"
1901 return NextToken().is(tok::l_paren);
1902
1903 default:
1904 return false;
1905 }
1906}
1907
1908/// [GNU] typeof-specifier:
1909/// 'typeof' '(' expressions ')'
1910/// 'typeof' '(' type-name ')'
1911///
1912Parser::TPResult Parser::TryParseTypeofSpecifier() {
1913 assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1914 ConsumeToken();
1915
1916 assert(Tok.is(tok::l_paren) && "Expected '('");
1917 // Parse through the parens after 'typeof'.
1918 ConsumeParen();
1919 if (!SkipUntil(tok::r_paren, StopAtSemi))
1920 return TPResult::Error;
1921
1922 return TPResult::Ambiguous;
1923}
1924
1925/// [ObjC] protocol-qualifiers:
1926//// '<' identifier-list '>'
1927Parser::TPResult Parser::TryParseProtocolQualifiers() {
1928 assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1929 ConsumeToken();
1930 do {
1931 if (Tok.isNot(tok::identifier))
1932 return TPResult::Error;
1933 ConsumeToken();
1934
1935 if (Tok.is(tok::comma)) {
1936 ConsumeToken();
1937 continue;
1938 }
1939
1940 if (Tok.is(tok::greater)) {
1941 ConsumeToken();
1942 return TPResult::Ambiguous;
1943 }
1944 } while (false);
1945
1946 return TPResult::Error;
1947}
1948
1949/// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1950/// a constructor-style initializer, when parsing declaration statements.
1951/// Returns true for function declarator and false for constructor-style
1952/// initializer.
1953/// If during the disambiguation process a parsing error is encountered,
1954/// the function returns true to let the declaration parsing code handle it.
1955///
1956/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1957/// exception-specification[opt]
1958///
1959bool Parser::isCXXFunctionDeclarator(
1960 bool *IsAmbiguous, ImplicitTypenameContext AllowImplicitTypename) {
1961
1962 // C++ 8.2p1:
1963 // The ambiguity arising from the similarity between a function-style cast and
1964 // a declaration mentioned in 6.8 can also occur in the context of a
1965 // declaration. In that context, the choice is between a function declaration
1966 // with a redundant set of parentheses around a parameter name and an object
1967 // declaration with a function-style cast as the initializer. Just as for the
1968 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1969 // that could possibly be a declaration a declaration.
1970
1971 RevertingTentativeParsingAction PA(*this);
1972
1973 ConsumeParen();
1974 bool InvalidAsDeclaration = false;
1975 TPResult TPR = TryParseParameterDeclarationClause(
1976 &InvalidAsDeclaration, /*VersusTemplateArgument=*/false,
1977 AllowImplicitTypename);
1978 if (TPR == TPResult::Ambiguous) {
1979 if (Tok.isNot(tok::r_paren))
1980 TPR = TPResult::False;
1981 else {
1982 const Token &Next = NextToken();
1983 if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile,
1984 tok::kw_throw, tok::kw_noexcept, tok::l_square,
1985 tok::l_brace, tok::kw_try, tok::equal, tok::arrow) ||
1986 isCXX11VirtSpecifier(Next))
1987 // The next token cannot appear after a constructor-style initializer,
1988 // and can appear next in a function definition. This must be a function
1989 // declarator.
1990 TPR = TPResult::True;
1991 else if (InvalidAsDeclaration)
1992 // Use the absence of 'typename' as a tie-breaker.
1993 TPR = TPResult::False;
1994 }
1995 }
1996
1997 if (IsAmbiguous && TPR == TPResult::Ambiguous)
1998 *IsAmbiguous = true;
1999
2000 // In case of an error, let the declaration parsing code handle it.
2001 return TPR != TPResult::False;
2002}
2003
2004/// parameter-declaration-clause:
2005/// parameter-declaration-list[opt] '...'[opt]
2006/// parameter-declaration-list ',' '...'
2007///
2008/// parameter-declaration-list:
2009/// parameter-declaration
2010/// parameter-declaration-list ',' parameter-declaration
2011///
2012/// parameter-declaration:
2013/// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
2014/// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
2015/// '=' assignment-expression
2016/// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
2017/// attributes[opt]
2018/// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
2019/// attributes[opt] '=' assignment-expression
2020///
2021Parser::TPResult Parser::TryParseParameterDeclarationClause(
2022 bool *InvalidAsDeclaration, bool VersusTemplateArgument,
2023 ImplicitTypenameContext AllowImplicitTypename) {
2024
2025 if (Tok.is(tok::r_paren))
2026 return TPResult::Ambiguous;
2027
2028 // parameter-declaration-list[opt] '...'[opt]
2029 // parameter-declaration-list ',' '...'
2030 //
2031 // parameter-declaration-list:
2032 // parameter-declaration
2033 // parameter-declaration-list ',' parameter-declaration
2034 //
2035 while (true) {
2036 // '...'[opt]
2037 if (Tok.is(tok::ellipsis)) {
2038 ConsumeToken();
2039 if (Tok.is(tok::r_paren))
2040 return TPResult::True; // '...)' is a sign of a function declarator.
2041 else
2042 return TPResult::False;
2043 }
2044
2045 // An attribute-specifier-seq here is a sign of a function declarator.
2046 if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
2047 /*OuterMightBeMessageSend*/true))
2048 return TPResult::True;
2049
2050 ParsedAttributes attrs(AttrFactory);
2051 MaybeParseMicrosoftAttributes(attrs);
2052
2053 // decl-specifier-seq
2054 // A parameter-declaration's initializer must be preceded by an '=', so
2055 // decl-specifier-seq '{' is not a parameter in C++11.
2056 TPResult TPR = isCXXDeclarationSpecifier(
2057 AllowImplicitTypename, TPResult::False, InvalidAsDeclaration);
2058 // A declaration-specifier (not followed by '(' or '{') means this can't be
2059 // an expression, but it could still be a template argument.
2060 if (TPR != TPResult::Ambiguous &&
2061 !(VersusTemplateArgument && TPR == TPResult::True))
2062 return TPR;
2063
2064 bool SeenType = false;
2065 bool DeclarationSpecifierIsAuto = Tok.is(tok::kw_auto);
2066 do {
2067 SeenType |= isCXXDeclarationSpecifierAType();
2068 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
2069 return TPResult::Error;
2070
2071 // If we see a parameter name, this can't be a template argument.
2072 if (SeenType && Tok.is(tok::identifier))
2073 return TPResult::True;
2074
2075 TPR = isCXXDeclarationSpecifier(AllowImplicitTypename, TPResult::False,
2076 InvalidAsDeclaration);
2077 if (TPR == TPResult::Error)
2078 return TPR;
2079
2080 // Two declaration-specifiers means this can't be an expression.
2081 if (TPR == TPResult::True && !VersusTemplateArgument)
2082 return TPR;
2083 } while (TPR != TPResult::False);
2084
2085 // declarator
2086 // abstract-declarator[opt]
2087 TPR = TryParseDeclarator(
2088 /*mayBeAbstract=*/true,
2089 /*mayHaveIdentifier=*/true,
2090 /*mayHaveDirectInit=*/false,
2091 /*mayHaveTrailingReturnType=*/DeclarationSpecifierIsAuto);
2092 if (TPR != TPResult::Ambiguous)
2093 return TPR;
2094
2095 // [GNU] attributes[opt]
2096 if (Tok.is(tok::kw___attribute))
2097 return TPResult::True;
2098
2099 // If we're disambiguating a template argument in a default argument in
2100 // a class definition versus a parameter declaration, an '=' here
2101 // disambiguates the parse one way or the other.
2102 // If this is a parameter, it must have a default argument because
2103 // (a) the previous parameter did, and
2104 // (b) this must be the first declaration of the function, so we can't
2105 // inherit any default arguments from elsewhere.
2106 // FIXME: If we reach a ')' without consuming any '>'s, then this must
2107 // also be a function parameter (that's missing its default argument).
2108 if (VersusTemplateArgument)
2109 return Tok.is(tok::equal) ? TPResult::True : TPResult::False;
2110
2111 if (Tok.is(tok::equal)) {
2112 // '=' assignment-expression
2113 // Parse through assignment-expression.
2114 if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
2115 return TPResult::Error;
2116 }
2117
2118 if (Tok.is(tok::ellipsis)) {
2119 ConsumeToken();
2120 if (Tok.is(tok::r_paren))
2121 return TPResult::True; // '...)' is a sign of a function declarator.
2122 else
2123 return TPResult::False;
2124 }
2125
2126 if (!TryConsumeToken(tok::comma))
2127 break;
2128 }
2129
2130 return TPResult::Ambiguous;
2131}
2132
2133/// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
2134/// parsing as a function declarator.
2135/// If TryParseFunctionDeclarator fully parsed the function declarator, it will
2136/// return TPResult::Ambiguous, otherwise it will return either False() or
2137/// Error().
2138///
2139/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
2140/// exception-specification[opt]
2141///
2142/// exception-specification:
2143/// 'throw' '(' type-id-list[opt] ')'
2144///
2145Parser::TPResult
2146Parser::TryParseFunctionDeclarator(bool MayHaveTrailingReturnType) {
2147 // The '(' is already parsed.
2148
2149 TPResult TPR = TryParseParameterDeclarationClause();
2150 if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
2151 TPR = TPResult::False;
2152
2153 if (TPR == TPResult::False || TPR == TPResult::Error)
2154 return TPR;
2155
2156 // Parse through the parens.
2157 if (!SkipUntil(tok::r_paren, StopAtSemi))
2158 return TPResult::Error;
2159
2160 // cv-qualifier-seq
2161 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw___unaligned,
2162 tok::kw_restrict))
2163 ConsumeToken();
2164
2165 // ref-qualifier[opt]
2166 if (Tok.isOneOf(tok::amp, tok::ampamp))
2167 ConsumeToken();
2168
2169 // exception-specification
2170 if (Tok.is(tok::kw_throw)) {
2171 ConsumeToken();
2172 if (Tok.isNot(tok::l_paren))
2173 return TPResult::Error;
2174
2175 // Parse through the parens after 'throw'.
2176 ConsumeParen();
2177 if (!SkipUntil(tok::r_paren, StopAtSemi))
2178 return TPResult::Error;
2179 }
2180 if (Tok.is(tok::kw_noexcept)) {
2181 ConsumeToken();
2182 // Possibly an expression as well.
2183 if (Tok.is(tok::l_paren)) {
2184 // Find the matching rparen.
2185 ConsumeParen();
2186 if (!SkipUntil(tok::r_paren, StopAtSemi))
2187 return TPResult::Error;
2188 }
2189 }
2190
2191 // attribute-specifier-seq
2192 if (!TrySkipAttributes())
2193 return TPResult::Ambiguous;
2194
2195 // trailing-return-type
2196 if (Tok.is(tok::arrow) && MayHaveTrailingReturnType) {
2197 if (TPR == TPResult::True)
2198 return TPR;
2199 ConsumeToken();
2200 if (Tok.is(tok::identifier) && NameAfterArrowIsNonType()) {
2201 return TPResult::False;
2202 }
2203 if (isCXXTypeId(TentativeCXXTypeIdContext::TypeIdInTrailingReturnType))
2204 return TPResult::True;
2205 }
2206
2207 return TPResult::Ambiguous;
2208}
2209
2210// When parsing an identifier after an arrow it may be a member expression,
2211// in which case we should not annotate it as an independant expression
2212// so we just lookup that name, if it's not a type the construct is not
2213// a function declaration.
2214bool Parser::NameAfterArrowIsNonType() {
2215 assert(Tok.is(tok::identifier));
2216 Token Next = NextToken();
2217 if (Next.is(tok::coloncolon))
2218 return false;
2219 IdentifierInfo *Name = Tok.getIdentifierInfo();
2220 SourceLocation NameLoc = Tok.getLocation();
2221 CXXScopeSpec SS;
2222 TentativeParseCCC CCC(Next);
2223 Sema::NameClassification Classification =
2224 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next, &CCC);
2225 switch (Classification.getKind()) {
2227 case Sema::NC_NonType:
2230 return true;
2231 default:
2232 break;
2233 }
2234 return false;
2235}
2236
2237/// '[' constant-expression[opt] ']'
2238///
2239Parser::TPResult Parser::TryParseBracketDeclarator() {
2240 ConsumeBracket();
2241
2242 // A constant-expression cannot begin with a '{', but the
2243 // expr-or-braced-init-list of a postfix-expression can.
2244 if (Tok.is(tok::l_brace))
2245 return TPResult::False;
2246
2247 if (!SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch))
2248 return TPResult::Error;
2249
2250 // If we hit a comma before the ']', this is not a constant-expression,
2251 // but might still be the expr-or-braced-init-list of a postfix-expression.
2252 if (Tok.isNot(tok::r_square))
2253 return TPResult::False;
2254
2255 ConsumeBracket();
2256 return TPResult::Ambiguous;
2257}
2258
2259/// Determine whether we might be looking at the '<' template-argument-list '>'
2260/// of a template-id or simple-template-id, rather than a less-than comparison.
2261/// This will often fail and produce an ambiguity, but should never be wrong
2262/// if it returns True or False.
2263Parser::TPResult Parser::isTemplateArgumentList(unsigned TokensToSkip) {
2264 if (!TokensToSkip) {
2265 if (Tok.isNot(tok::less))
2266 return TPResult::False;
2267 if (NextToken().is(tok::greater))
2268 return TPResult::True;
2269 }
2270
2271 RevertingTentativeParsingAction PA(*this);
2272
2273 while (TokensToSkip) {
2275 --TokensToSkip;
2276 }
2277
2278 if (!TryConsumeToken(tok::less))
2279 return TPResult::False;
2280
2281 // We can't do much to tell an expression apart from a template-argument,
2282 // but one good distinguishing factor is that a "decl-specifier" not
2283 // followed by '(' or '{' can't appear in an expression.
2284 bool InvalidAsTemplateArgumentList = false;
2285 if (isCXXDeclarationSpecifier(ImplicitTypenameContext::No, TPResult::False,
2286 &InvalidAsTemplateArgumentList) ==
2287 TPResult::True)
2288 return TPResult::True;
2289 if (InvalidAsTemplateArgumentList)
2290 return TPResult::False;
2291
2292 // FIXME: In many contexts, X<thing1, Type> can only be a
2293 // template-argument-list. But that's not true in general:
2294 //
2295 // using b = int;
2296 // void f() {
2297 // int a = A<B, b, c = C>D; // OK, declares b, not a template-id.
2298 //
2299 // X<Y<0, int> // ', int>' might be end of X's template argument list
2300 //
2301 // We might be able to disambiguate a few more cases if we're careful.
2302
2303 // A template-argument-list must be terminated by a '>'.
2304 if (SkipUntil({tok::greater, tok::greatergreater, tok::greatergreatergreater},
2306 return TPResult::Ambiguous;
2307 return TPResult::False;
2308}
2309
2310/// Determine whether we might be looking at the '(' of a C++20 explicit(bool)
2311/// in an earlier language mode.
2312Parser::TPResult Parser::isExplicitBool() {
2313 assert(Tok.is(tok::l_paren) && "expected to be looking at a '(' token");
2314
2315 RevertingTentativeParsingAction PA(*this);
2316 ConsumeParen();
2317
2318 // We can only have 'explicit' on a constructor, conversion function, or
2319 // deduction guide. The declarator of a deduction guide cannot be
2320 // parenthesized, so we know this isn't a deduction guide. So the only
2321 // thing we need to check for is some number of parens followed by either
2322 // the current class name or 'operator'.
2323 while (Tok.is(tok::l_paren))
2324 ConsumeParen();
2325
2327 return TPResult::Error;
2328
2329 // Class-scope constructor and conversion function names can't really be
2330 // qualified, but we get better diagnostics if we assume they can be.
2331 CXXScopeSpec SS;
2332 if (Tok.is(tok::annot_cxxscope)) {
2334 Tok.getAnnotationRange(),
2335 SS);
2336 ConsumeAnnotationToken();
2337 }
2338
2339 // 'explicit(operator' might be explicit(bool) or the declaration of a
2340 // conversion function, but it's probably a conversion function.
2341 if (Tok.is(tok::kw_operator))
2342 return TPResult::Ambiguous;
2343
2344 // If this can't be a constructor name, it can only be explicit(bool).
2345 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
2346 return TPResult::True;
2347 if (!Actions.isCurrentClassName(Tok.is(tok::identifier)
2348 ? *Tok.getIdentifierInfo()
2349 : *takeTemplateIdAnnotation(Tok)->Name,
2350 getCurScope(), &SS))
2351 return TPResult::True;
2352 // Formally, we must have a right-paren after the constructor name to match
2353 // the grammar for a constructor. But clang permits a parenthesized
2354 // constructor declarator, so also allow a constructor declarator to follow
2355 // with no ')' token after the constructor name.
2356 if (!NextToken().is(tok::r_paren) &&
2357 !isConstructorDeclarator(/*Unqualified=*/SS.isEmpty(),
2358 /*DeductionGuide=*/false))
2359 return TPResult::True;
2360
2361 // Might be explicit(bool) or a parenthesized constructor name.
2362 return TPResult::Ambiguous;
2363}
static constexpr bool isOneOf()
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:209
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
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.
This represents a decl that may have a name.
Definition: Decl.h:247
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:935
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:53
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition: Parser.h:491
bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext=false)
Definition: Parser.h:875
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition: Parser.h:519
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:499
Scope * getCurScope() const
Definition: Parser.h:445
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:1231
const LangOptions & getLangOpts() const
Definition: Parser.h:438
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1212
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1210
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:1961
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:811
NameClassificationKind getKind() const
Definition: Sema.h:2786
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
@ NC_VarTemplate
The name was classified as a variable template name.
Definition: Sema.h:2703
@ NC_NonType
The name was classified as a specific non-type, non-template declaration.
Definition: Sema.h:2686
@ NC_FunctionTemplate
The name was classified as a function template name.
Definition: Sema.h:2705
@ NC_OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition: Sema.h:2699
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition: SemaDecl.cpp:900
void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS)
Given an annotation pointer for a nested-name-specifier, restore the nested-name-specifier structure.
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
Encodes a location in the source.
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:186
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:131
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:98
void * getAnnotationValue() const
Definition: Token.h:233
tok::TokenKind getKind() const
Definition: Token.h:93
bool isRegularKeywordAttribute() const
Return true if the token is a keyword that is parsed in the same position as a standard attribute,...
Definition: Token.h:125
SourceRange getAnnotationRange() const
SourceRange of the group of tokens that this annotation token represents.
Definition: Token.h:165
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:100
bool isNot(tok::TokenKind K) const
Definition: Token.h:99
bool hasUDSuffix() const
Return true if this token is a string or character literal which has a ud-suffix.
Definition: Token.h:300
Simple class containing the result of Sema::CorrectTypo.
ImplicitTypenameContext
Definition: DeclSpec.h:1833
@ OpenCL
Definition: LangStandard.h:63
@ CPlusPlus23
Definition: LangStandard.h:58
@ CPlusPlus
Definition: LangStandard.h:53
@ CPlusPlus11
Definition: LangStandard.h:54
@ CPlusPlus17
Definition: LangStandard.h:56
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
Definition: TemplateKinds.h:50
ConditionDeclarationOrInitStatementState(Parser &P, bool CanBeInitStatement, bool CanBeForRangeDecl)
Represents a complete lambda introducer.
Definition: DeclSpec.h:2748
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.
unsigned NumArgs
NumArgs - The number of template arguments.