Debian Codegraph @

clang/lib/Parse/ParseTentative.cpp

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