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