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