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