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