1 //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Expression parsing implementation for C++.
11 //===----------------------------------------------------------------------===//
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/Basic/PrettyStackTrace.h"
17 #include "clang/Basic/TokenKinds.h"
18 #include "clang/Lex/LiteralSupport.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Parse/Parser.h"
21 #include "clang/Parse/RAIIObjectsForParser.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "clang/Sema/ParsedTemplate.h"
24 #include "clang/Sema/Scope.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/ErrorHandling.h"
29 using namespace clang
;
31 static int SelectDigraphErrorMessage(tok::TokenKind Kind
) {
34 case tok::unknown
: return 0;
36 case tok::kw_addrspace_cast
: return 1;
37 case tok::kw_const_cast
: return 2;
38 case tok::kw_dynamic_cast
: return 3;
39 case tok::kw_reinterpret_cast
: return 4;
40 case tok::kw_static_cast
: return 5;
42 llvm_unreachable("Unknown type for digraph error message.");
46 // Are the two tokens adjacent in the same source file?
47 bool Parser::areTokensAdjacent(const Token
&First
, const Token
&Second
) {
48 SourceManager
&SM
= PP
.getSourceManager();
49 SourceLocation FirstLoc
= SM
.getSpellingLoc(First
.getLocation());
50 SourceLocation FirstEnd
= FirstLoc
.getLocWithOffset(First
.getLength());
51 return FirstEnd
== SM
.getSpellingLoc(Second
.getLocation());
54 // Suggest fixit for "<::" after a cast.
55 static void FixDigraph(Parser
&P
, Preprocessor
&PP
, Token
&DigraphToken
,
56 Token
&ColonToken
, tok::TokenKind Kind
, bool AtDigraph
) {
57 // Pull '<:' and ':' off token stream.
63 Range
.setBegin(DigraphToken
.getLocation());
64 Range
.setEnd(ColonToken
.getLocation());
65 P
.Diag(DigraphToken
.getLocation(), diag::err_missing_whitespace_digraph
)
66 << SelectDigraphErrorMessage(Kind
)
67 << FixItHint::CreateReplacement(Range
, "< ::");
69 // Update token information to reflect their change in token type.
70 ColonToken
.setKind(tok::coloncolon
);
71 ColonToken
.setLocation(ColonToken
.getLocation().getLocWithOffset(-1));
72 ColonToken
.setLength(2);
73 DigraphToken
.setKind(tok::less
);
74 DigraphToken
.setLength(1);
76 // Push new tokens back to token stream.
77 PP
.EnterToken(ColonToken
, /*IsReinject*/ true);
79 PP
.EnterToken(DigraphToken
, /*IsReinject*/ true);
82 // Check for '<::' which should be '< ::' instead of '[:' when following
84 void Parser::CheckForTemplateAndDigraph(Token
&Next
, ParsedType ObjectType
,
86 IdentifierInfo
&II
, CXXScopeSpec
&SS
) {
87 if (!Next
.is(tok::l_square
) || Next
.getLength() != 2)
90 Token SecondToken
= GetLookAheadToken(2);
91 if (!SecondToken
.is(tok::colon
) || !areTokensAdjacent(Next
, SecondToken
))
95 UnqualifiedId TemplateName
;
96 TemplateName
.setIdentifier(&II
, Tok
.getLocation());
97 bool MemberOfUnknownSpecialization
;
98 if (!Actions
.isTemplateName(getCurScope(), SS
, /*hasTemplateKeyword=*/false,
99 TemplateName
, ObjectType
, EnteringContext
,
100 Template
, MemberOfUnknownSpecialization
))
103 FixDigraph(*this, PP
, Next
, SecondToken
, tok::unknown
,
107 /// Parse global scope or nested-name-specifier if present.
109 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
110 /// may be preceded by '::'). Note that this routine will not parse ::new or
111 /// ::delete; it will just leave them in the token stream.
113 /// '::'[opt] nested-name-specifier
116 /// nested-name-specifier:
118 /// namespace-name '::'
119 /// nested-name-specifier identifier '::'
120 /// nested-name-specifier 'template'[opt] simple-template-id '::'
123 /// \param SS the scope specifier that will be set to the parsed
124 /// nested-name-specifier (or empty)
126 /// \param ObjectType if this nested-name-specifier is being parsed following
127 /// the "." or "->" of a member access expression, this parameter provides the
128 /// type of the object whose members are being accessed.
130 /// \param ObjectHadErrors if this unqualified-id occurs within a member access
131 /// expression, indicates whether the original subexpressions had any errors.
132 /// When true, diagnostics for missing 'template' keyword will be supressed.
134 /// \param EnteringContext whether we will be entering into the context of
135 /// the nested-name-specifier after parsing it.
137 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
138 /// indicates whether this nested-name-specifier may be part of a
139 /// pseudo-destructor name. In this case, the flag will be set false
140 /// if we don't actually end up parsing a destructor name. Moreover,
141 /// if we do end up determining that we are parsing a destructor name,
142 /// the last component of the nested-name-specifier is not parsed as
143 /// part of the scope specifier.
145 /// \param IsTypename If \c true, this nested-name-specifier is known to be
146 /// part of a type name. This is used to improve error recovery.
148 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
149 /// filled in with the leading identifier in the last component of the
150 /// nested-name-specifier, if any.
152 /// \param OnlyNamespace If true, only considers namespaces in lookup.
155 /// \returns true if there was an error parsing a scope specifier
156 bool Parser::ParseOptionalCXXScopeSpecifier(
157 CXXScopeSpec
&SS
, ParsedType ObjectType
, bool ObjectHadErrors
,
158 bool EnteringContext
, bool *MayBePseudoDestructor
, bool IsTypename
,
159 IdentifierInfo
**LastII
, bool OnlyNamespace
, bool InUsingDeclaration
) {
160 assert(getLangOpts().CPlusPlus
&&
161 "Call sites of this function should be guarded by checking for C++");
163 if (Tok
.is(tok::annot_cxxscope
)) {
164 assert(!LastII
&& "want last identifier but have already annotated scope");
165 assert(!MayBePseudoDestructor
&& "unexpected annot_cxxscope");
166 Actions
.RestoreNestedNameSpecifierAnnotation(Tok
.getAnnotationValue(),
167 Tok
.getAnnotationRange(),
169 ConsumeAnnotationToken();
173 // Has to happen before any "return false"s in this function.
174 bool CheckForDestructor
= false;
175 if (MayBePseudoDestructor
&& *MayBePseudoDestructor
) {
176 CheckForDestructor
= true;
177 *MayBePseudoDestructor
= false;
183 bool HasScopeSpecifier
= false;
185 if (Tok
.is(tok::coloncolon
)) {
186 // ::new and ::delete aren't nested-name-specifiers.
187 tok::TokenKind NextKind
= NextToken().getKind();
188 if (NextKind
== tok::kw_new
|| NextKind
== tok::kw_delete
)
191 if (NextKind
== tok::l_brace
) {
192 // It is invalid to have :: {, consume the scope qualifier and pretend
193 // like we never saw it.
194 Diag(ConsumeToken(), diag::err_expected
) << tok::identifier
;
196 // '::' - Global scope qualifier.
197 if (Actions
.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS
))
200 HasScopeSpecifier
= true;
204 if (Tok
.is(tok::kw___super
)) {
205 SourceLocation SuperLoc
= ConsumeToken();
206 if (!Tok
.is(tok::coloncolon
)) {
207 Diag(Tok
.getLocation(), diag::err_expected_coloncolon_after_super
);
211 return Actions
.ActOnSuperScopeSpecifier(SuperLoc
, ConsumeToken(), SS
);
214 if (!HasScopeSpecifier
&&
215 Tok
.isOneOf(tok::kw_decltype
, tok::annot_decltype
)) {
216 DeclSpec
DS(AttrFactory
);
217 SourceLocation DeclLoc
= Tok
.getLocation();
218 SourceLocation EndLoc
= ParseDecltypeSpecifier(DS
);
220 SourceLocation CCLoc
;
221 // Work around a standard defect: 'decltype(auto)::' is not a
222 // nested-name-specifier.
223 if (DS
.getTypeSpecType() == DeclSpec::TST_decltype_auto
||
224 !TryConsumeToken(tok::coloncolon
, CCLoc
)) {
225 AnnotateExistingDecltypeSpecifier(DS
, DeclLoc
, EndLoc
);
229 if (Actions
.ActOnCXXNestedNameSpecifierDecltype(SS
, DS
, CCLoc
))
230 SS
.SetInvalid(SourceRange(DeclLoc
, CCLoc
));
232 HasScopeSpecifier
= true;
235 // Preferred type might change when parsing qualifiers, we need the original.
236 auto SavedType
= PreferredType
;
238 if (HasScopeSpecifier
) {
239 if (Tok
.is(tok::code_completion
)) {
241 // Code completion for a nested-name-specifier, where the code
242 // completion token follows the '::'.
243 Actions
.CodeCompleteQualifiedId(getCurScope(), SS
, EnteringContext
,
244 InUsingDeclaration
, ObjectType
.get(),
245 SavedType
.get(SS
.getBeginLoc()));
246 // Include code completion token into the range of the scope otherwise
247 // when we try to annotate the scope tokens the dangling code completion
248 // token will cause assertion in
249 // Preprocessor::AnnotatePreviousCachedTokens.
250 SS
.setEndLoc(Tok
.getLocation());
254 // C++ [basic.lookup.classref]p5:
255 // If the qualified-id has the form
257 // ::class-name-or-namespace-name::...
259 // the class-name-or-namespace-name is looked up in global scope as a
260 // class-name or namespace-name.
262 // To implement this, we clear out the object type as soon as we've
263 // seen a leading '::' or part of a nested-name-specifier.
264 ObjectType
= nullptr;
267 // nested-name-specifier:
268 // nested-name-specifier 'template'[opt] simple-template-id '::'
270 // Parse the optional 'template' keyword, then make sure we have
271 // 'identifier <' after it.
272 if (Tok
.is(tok::kw_template
)) {
273 // If we don't have a scope specifier or an object type, this isn't a
274 // nested-name-specifier, since they aren't allowed to start with
276 if (!HasScopeSpecifier
&& !ObjectType
)
279 TentativeParsingAction
TPA(*this);
280 SourceLocation TemplateKWLoc
= ConsumeToken();
282 UnqualifiedId TemplateName
;
283 if (Tok
.is(tok::identifier
)) {
284 // Consume the identifier.
285 TemplateName
.setIdentifier(Tok
.getIdentifierInfo(), Tok
.getLocation());
287 } else if (Tok
.is(tok::kw_operator
)) {
288 // We don't need to actually parse the unqualified-id in this case,
289 // because a simple-template-id cannot start with 'operator', but
290 // go ahead and parse it anyway for consistency with the case where
291 // we already annotated the template-id.
292 if (ParseUnqualifiedIdOperator(SS
, EnteringContext
, ObjectType
,
298 if (TemplateName
.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId
&&
299 TemplateName
.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId
) {
300 Diag(TemplateName
.getSourceRange().getBegin(),
301 diag::err_id_after_template_in_nested_name_spec
)
302 << TemplateName
.getSourceRange();
311 // If the next token is not '<', we have a qualified-id that refers
312 // to a template name, such as T::template apply, but is not a
314 if (Tok
.isNot(tok::less
)) {
319 // Commit to parsing the template-id.
322 TemplateNameKind TNK
= Actions
.ActOnTemplateName(
323 getCurScope(), SS
, TemplateKWLoc
, TemplateName
, ObjectType
,
324 EnteringContext
, Template
, /*AllowInjectedClassName*/ true);
325 if (AnnotateTemplateIdToken(Template
, TNK
, SS
, TemplateKWLoc
,
326 TemplateName
, false))
332 if (Tok
.is(tok::annot_template_id
) && NextToken().is(tok::coloncolon
)) {
337 // So we need to check whether the template-id is a simple-template-id of
338 // the right kind (it should name a type or be dependent), and then
339 // convert it into a type within the nested-name-specifier.
340 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
341 if (CheckForDestructor
&& GetLookAheadToken(2).is(tok::tilde
)) {
342 *MayBePseudoDestructor
= true;
347 *LastII
= TemplateId
->Name
;
349 // Consume the template-id token.
350 ConsumeAnnotationToken();
352 assert(Tok
.is(tok::coloncolon
) && "NextToken() not working properly!");
353 SourceLocation CCLoc
= ConsumeToken();
355 HasScopeSpecifier
= true;
357 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
358 TemplateId
->NumArgs
);
360 if (TemplateId
->isInvalid() ||
361 Actions
.ActOnCXXNestedNameSpecifier(getCurScope(),
363 TemplateId
->TemplateKWLoc
,
364 TemplateId
->Template
,
365 TemplateId
->TemplateNameLoc
,
366 TemplateId
->LAngleLoc
,
368 TemplateId
->RAngleLoc
,
371 SourceLocation StartLoc
372 = SS
.getBeginLoc().isValid()? SS
.getBeginLoc()
373 : TemplateId
->TemplateNameLoc
;
374 SS
.SetInvalid(SourceRange(StartLoc
, CCLoc
));
380 // The rest of the nested-name-specifier possibilities start with
382 if (Tok
.isNot(tok::identifier
))
385 IdentifierInfo
&II
= *Tok
.getIdentifierInfo();
387 // nested-name-specifier:
389 // namespace-name '::'
390 // nested-name-specifier identifier '::'
391 Token Next
= NextToken();
392 Sema::NestedNameSpecInfo
IdInfo(&II
, Tok
.getLocation(), Next
.getLocation(),
395 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
396 // and emit a fixit hint for it.
397 if (Next
.is(tok::colon
) && !ColonIsSacred
) {
398 if (Actions
.IsInvalidUnlessNestedName(getCurScope(), SS
, IdInfo
,
400 // If the token after the colon isn't an identifier, it's still an
401 // error, but they probably meant something else strange so don't
402 // recover like this.
403 PP
.LookAhead(1).is(tok::identifier
)) {
404 Diag(Next
, diag::err_unexpected_colon_in_nested_name_spec
)
405 << FixItHint::CreateReplacement(Next
.getLocation(), "::");
406 // Recover as if the user wrote '::'.
407 Next
.setKind(tok::coloncolon
);
411 if (Next
.is(tok::coloncolon
) && GetLookAheadToken(2).is(tok::l_brace
)) {
412 // It is invalid to have :: {, consume the scope qualifier and pretend
413 // like we never saw it.
414 Token Identifier
= Tok
; // Stash away the identifier.
415 ConsumeToken(); // Eat the identifier, current token is now '::'.
416 Diag(PP
.getLocForEndOfToken(ConsumeToken()), diag::err_expected
)
418 UnconsumeToken(Identifier
); // Stick the identifier back.
419 Next
= NextToken(); // Point Next at the '{' token.
422 if (Next
.is(tok::coloncolon
)) {
423 if (CheckForDestructor
&& GetLookAheadToken(2).is(tok::tilde
)) {
424 *MayBePseudoDestructor
= true;
429 const Token
&Next2
= GetLookAheadToken(2);
430 if (Next2
.is(tok::kw_private
) || Next2
.is(tok::kw_protected
) ||
431 Next2
.is(tok::kw_public
) || Next2
.is(tok::kw_virtual
)) {
432 Diag(Next2
, diag::err_unexpected_token_in_nested_name_spec
)
434 << FixItHint::CreateReplacement(Next
.getLocation(), ":");
437 ColonColon
.setKind(tok::colon
);
438 PP
.EnterToken(ColonColon
, /*IsReinject*/ true);
446 // We have an identifier followed by a '::'. Lookup this name
447 // as the name in a nested-name-specifier.
448 Token Identifier
= Tok
;
449 SourceLocation IdLoc
= ConsumeToken();
450 assert(Tok
.isOneOf(tok::coloncolon
, tok::colon
) &&
451 "NextToken() not working properly!");
452 Token ColonColon
= Tok
;
453 SourceLocation CCLoc
= ConsumeToken();
455 bool IsCorrectedToColon
= false;
456 bool *CorrectionFlagPtr
= ColonIsSacred
? &IsCorrectedToColon
: nullptr;
457 if (Actions
.ActOnCXXNestedNameSpecifier(
458 getCurScope(), IdInfo
, EnteringContext
, SS
, CorrectionFlagPtr
,
460 // Identifier is not recognized as a nested name, but we can have
461 // mistyped '::' instead of ':'.
462 if (CorrectionFlagPtr
&& IsCorrectedToColon
) {
463 ColonColon
.setKind(tok::colon
);
464 PP
.EnterToken(Tok
, /*IsReinject*/ true);
465 PP
.EnterToken(ColonColon
, /*IsReinject*/ true);
469 SS
.SetInvalid(SourceRange(IdLoc
, CCLoc
));
471 HasScopeSpecifier
= true;
475 CheckForTemplateAndDigraph(Next
, ObjectType
, EnteringContext
, II
, SS
);
477 // nested-name-specifier:
479 if (Next
.is(tok::less
)) {
482 UnqualifiedId TemplateName
;
483 TemplateName
.setIdentifier(&II
, Tok
.getLocation());
484 bool MemberOfUnknownSpecialization
;
485 if (TemplateNameKind TNK
= Actions
.isTemplateName(getCurScope(), SS
,
486 /*hasTemplateKeyword=*/false,
491 MemberOfUnknownSpecialization
)) {
492 // If lookup didn't find anything, we treat the name as a template-name
493 // anyway. C++20 requires this, and in prior language modes it improves
494 // error recovery. But before we commit to this, check that we actually
495 // have something that looks like a template-argument-list next.
496 if (!IsTypename
&& TNK
== TNK_Undeclared_template
&&
497 isTemplateArgumentList(1) == TPResult::False
)
500 // We have found a template name, so annotate this token
501 // with a template-id annotation. We do not permit the
502 // template-id to be translated into a type annotation,
503 // because some clients (e.g., the parsing of class template
504 // specializations) still want to see the original template-id
505 // token, and it might not be a type at all (e.g. a concept name in a
508 if (AnnotateTemplateIdToken(Template
, TNK
, SS
, SourceLocation(),
509 TemplateName
, false))
514 if (MemberOfUnknownSpecialization
&& (ObjectType
|| SS
.isSet()) &&
515 (IsTypename
|| isTemplateArgumentList(1) == TPResult::True
)) {
516 // If we had errors before, ObjectType can be dependent even without any
517 // templates. Do not report missing template keyword in that case.
518 if (!ObjectHadErrors
) {
519 // We have something like t::getAs<T>, where getAs is a
520 // member of an unknown specialization. However, this will only
521 // parse correctly as a template, so suggest the keyword 'template'
522 // before 'getAs' and treat this as a dependent template name.
523 unsigned DiagID
= diag::err_missing_dependent_template_keyword
;
524 if (getLangOpts().MicrosoftExt
)
525 DiagID
= diag::warn_missing_dependent_template_keyword
;
527 Diag(Tok
.getLocation(), DiagID
)
529 << FixItHint::CreateInsertion(Tok
.getLocation(), "template ");
532 SourceLocation TemplateNameLoc
= ConsumeToken();
534 TemplateNameKind TNK
= Actions
.ActOnTemplateName(
535 getCurScope(), SS
, TemplateNameLoc
, TemplateName
, ObjectType
,
536 EnteringContext
, Template
, /*AllowInjectedClassName*/ true);
537 if (AnnotateTemplateIdToken(Template
, TNK
, SS
, SourceLocation(),
538 TemplateName
, false))
545 // We don't have any tokens that form the beginning of a
546 // nested-name-specifier, so we're done.
550 // Even if we didn't see any pieces of a nested-name-specifier, we
551 // still check whether there is a tilde in this position, which
552 // indicates a potential pseudo-destructor.
553 if (CheckForDestructor
&& !HasScopeSpecifier
&& Tok
.is(tok::tilde
))
554 *MayBePseudoDestructor
= true;
559 ExprResult
Parser::tryParseCXXIdExpression(CXXScopeSpec
&SS
,
560 bool isAddressOfOperand
,
561 Token
&Replacement
) {
564 // We may have already annotated this id-expression.
565 switch (Tok
.getKind()) {
566 case tok::annot_non_type
: {
567 NamedDecl
*ND
= getNonTypeAnnotation(Tok
);
568 SourceLocation Loc
= ConsumeAnnotationToken();
569 E
= Actions
.ActOnNameClassifiedAsNonType(getCurScope(), SS
, ND
, Loc
, Tok
);
573 case tok::annot_non_type_dependent
: {
574 IdentifierInfo
*II
= getIdentifierAnnotation(Tok
);
575 SourceLocation Loc
= ConsumeAnnotationToken();
577 // This is only the direct operand of an & operator if it is not
578 // followed by a postfix-expression suffix.
579 if (isAddressOfOperand
&& isPostfixExpressionSuffixStart())
580 isAddressOfOperand
= false;
582 E
= Actions
.ActOnNameClassifiedAsDependentNonType(SS
, II
, Loc
,
587 case tok::annot_non_type_undeclared
: {
588 assert(SS
.isEmpty() &&
589 "undeclared non-type annotation should be unqualified");
590 IdentifierInfo
*II
= getIdentifierAnnotation(Tok
);
591 SourceLocation Loc
= ConsumeAnnotationToken();
592 E
= Actions
.ActOnNameClassifiedAsUndeclaredNonType(II
, Loc
);
597 SourceLocation TemplateKWLoc
;
599 if (ParseUnqualifiedId(SS
, /*ObjectType=*/nullptr,
600 /*ObjectHadErrors=*/false,
601 /*EnteringContext=*/false,
602 /*AllowDestructorName=*/false,
603 /*AllowConstructorName=*/false,
604 /*AllowDeductionGuide=*/false, &TemplateKWLoc
, Name
))
607 // This is only the direct operand of an & operator if it is not
608 // followed by a postfix-expression suffix.
609 if (isAddressOfOperand
&& isPostfixExpressionSuffixStart())
610 isAddressOfOperand
= false;
612 E
= Actions
.ActOnIdExpression(
613 getCurScope(), SS
, TemplateKWLoc
, Name
, Tok
.is(tok::l_paren
),
614 isAddressOfOperand
, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
619 if (!E
.isInvalid() && !E
.isUnset() && Tok
.is(tok::less
))
620 checkPotentialAngleBracket(E
);
624 /// ParseCXXIdExpression - Handle id-expression.
631 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
633 /// '::' operator-function-id
636 /// NOTE: The standard specifies that, for qualified-id, the parser does not
639 /// '::' conversion-function-id
640 /// '::' '~' class-name
642 /// This may cause a slight inconsistency on diagnostics:
647 /// :: A :: ~ C(); // Some Sema error about using destructor with a
649 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
652 /// We simplify the parser a bit and make it work like:
655 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
656 /// '::' unqualified-id
658 /// That way Sema can handle and report similar errors for namespaces and the
661 /// The isAddressOfOperand parameter indicates that this id-expression is a
662 /// direct operand of the address-of operator. This is, besides member contexts,
663 /// the only place where a qualified-id naming a non-static class member may
666 ExprResult
Parser::ParseCXXIdExpression(bool isAddressOfOperand
) {
668 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
669 // '::' unqualified-id
672 ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
673 /*ObjectHasErrors=*/false,
674 /*EnteringContext=*/false);
678 tryParseCXXIdExpression(SS
, isAddressOfOperand
, Replacement
);
679 if (Result
.isUnset()) {
680 // If the ExprResult is valid but null, then typo correction suggested a
681 // keyword replacement that needs to be reparsed.
682 UnconsumeToken(Replacement
);
683 Result
= tryParseCXXIdExpression(SS
, isAddressOfOperand
, Replacement
);
685 assert(!Result
.isUnset() && "Typo correction suggested a keyword replacement "
686 "for a previous keyword suggestion");
690 /// ParseLambdaExpression - Parse a C++11 lambda expression.
692 /// lambda-expression:
693 /// lambda-introducer lambda-declarator compound-statement
694 /// lambda-introducer '<' template-parameter-list '>'
695 /// requires-clause[opt] lambda-declarator compound-statement
697 /// lambda-introducer:
698 /// '[' lambda-capture[opt] ']'
703 /// capture-default ',' capture-list
711 /// capture-list ',' capture
715 /// init-capture [C++1y]
722 /// init-capture: [C++1y]
723 /// identifier initializer
724 /// '&' identifier initializer
726 /// lambda-declarator:
727 /// lambda-specifiers [C++2b]
728 /// '(' parameter-declaration-clause ')' lambda-specifiers
729 /// requires-clause[opt]
731 /// lambda-specifiers:
732 /// decl-specifier-seq[opt] noexcept-specifier[opt]
733 /// attribute-specifier-seq[opt] trailing-return-type[opt]
735 ExprResult
Parser::ParseLambdaExpression() {
736 // Parse lambda-introducer.
737 LambdaIntroducer Intro
;
738 if (ParseLambdaIntroducer(Intro
)) {
739 SkipUntil(tok::r_square
, StopAtSemi
);
740 SkipUntil(tok::l_brace
, StopAtSemi
);
741 SkipUntil(tok::r_brace
, StopAtSemi
);
745 return ParseLambdaExpressionAfterIntroducer(Intro
);
748 /// Use lookahead and potentially tentative parsing to determine if we are
749 /// looking at a C++11 lambda expression, and parse it if we are.
751 /// If we are not looking at a lambda expression, returns ExprError().
752 ExprResult
Parser::TryParseLambdaExpression() {
753 assert(getLangOpts().CPlusPlus11
754 && Tok
.is(tok::l_square
)
755 && "Not at the start of a possible lambda expression.");
757 const Token Next
= NextToken();
758 if (Next
.is(tok::eof
)) // Nothing else to lookup here...
761 const Token After
= GetLookAheadToken(2);
762 // If lookahead indicates this is a lambda...
763 if (Next
.is(tok::r_square
) || // []
764 Next
.is(tok::equal
) || // [=
765 (Next
.is(tok::amp
) && // [&] or [&,
766 After
.isOneOf(tok::r_square
, tok::comma
)) ||
767 (Next
.is(tok::identifier
) && // [identifier]
768 After
.is(tok::r_square
)) ||
769 Next
.is(tok::ellipsis
)) { // [...
770 return ParseLambdaExpression();
773 // If lookahead indicates an ObjC message send...
774 // [identifier identifier
775 if (Next
.is(tok::identifier
) && After
.is(tok::identifier
))
778 // Here, we're stuck: lambda introducers and Objective-C message sends are
779 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
780 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
781 // writing two routines to parse a lambda introducer, just try to parse
782 // a lambda introducer first, and fall back if that fails.
783 LambdaIntroducer Intro
;
785 TentativeParsingAction
TPA(*this);
786 LambdaIntroducerTentativeParse Tentative
;
787 if (ParseLambdaIntroducer(Intro
, &Tentative
)) {
793 case LambdaIntroducerTentativeParse::Success
:
797 case LambdaIntroducerTentativeParse::Incomplete
:
798 // Didn't fully parse the lambda-introducer, try again with a
799 // non-tentative parse.
801 Intro
= LambdaIntroducer();
802 if (ParseLambdaIntroducer(Intro
))
806 case LambdaIntroducerTentativeParse::MessageSend
:
807 case LambdaIntroducerTentativeParse::Invalid
:
808 // Not a lambda-introducer, might be a message send.
814 return ParseLambdaExpressionAfterIntroducer(Intro
);
817 /// Parse a lambda introducer.
818 /// \param Intro A LambdaIntroducer filled in with information about the
819 /// contents of the lambda-introducer.
820 /// \param Tentative If non-null, we are disambiguating between a
821 /// lambda-introducer and some other construct. In this mode, we do not
822 /// produce any diagnostics or take any other irreversible action unless
823 /// we're sure that this is a lambda-expression.
824 /// \return \c true if parsing (or disambiguation) failed with a diagnostic and
825 /// the caller should bail out / recover.
826 bool Parser::ParseLambdaIntroducer(LambdaIntroducer
&Intro
,
827 LambdaIntroducerTentativeParse
*Tentative
) {
829 *Tentative
= LambdaIntroducerTentativeParse::Success
;
831 assert(Tok
.is(tok::l_square
) && "Lambda expressions begin with '['.");
832 BalancedDelimiterTracker
T(*this, tok::l_square
);
835 Intro
.Range
.setBegin(T
.getOpenLocation());
839 // Produce a diagnostic if we're not tentatively parsing; otherwise track
840 // that our parse has failed.
841 auto Invalid
= [&](llvm::function_ref
<void()> Action
) {
843 *Tentative
= LambdaIntroducerTentativeParse::Invalid
;
850 // Perform some irreversible action if this is a non-tentative parse;
851 // otherwise note that our actions were incomplete.
852 auto NonTentativeAction
= [&](llvm::function_ref
<void()> Action
) {
854 *Tentative
= LambdaIntroducerTentativeParse::Incomplete
;
859 // Parse capture-default.
860 if (Tok
.is(tok::amp
) &&
861 (NextToken().is(tok::comma
) || NextToken().is(tok::r_square
))) {
862 Intro
.Default
= LCD_ByRef
;
863 Intro
.DefaultLoc
= ConsumeToken();
865 if (!Tok
.getIdentifierInfo()) {
866 // This can only be a lambda; no need for tentative parsing any more.
867 // '[[and]]' can still be an attribute, though.
870 } else if (Tok
.is(tok::equal
)) {
871 Intro
.Default
= LCD_ByCopy
;
872 Intro
.DefaultLoc
= ConsumeToken();
877 while (Tok
.isNot(tok::r_square
)) {
879 if (Tok
.isNot(tok::comma
)) {
880 // Provide a completion for a lambda introducer here. Except
881 // in Objective-C, where this is Almost Surely meant to be a message
882 // send. In that case, fail here and let the ObjC message
883 // expression parser perform the completion.
884 if (Tok
.is(tok::code_completion
) &&
885 !(getLangOpts().ObjC
&& Tentative
)) {
887 Actions
.CodeCompleteLambdaIntroducer(getCurScope(), Intro
,
888 /*AfterAmpersand=*/false);
893 Diag(Tok
.getLocation(), diag::err_expected_comma_or_rsquare
);
899 if (Tok
.is(tok::code_completion
)) {
901 // If we're in Objective-C++ and we have a bare '[', then this is more
902 // likely to be a message receiver.
903 if (getLangOpts().ObjC
&& Tentative
&& First
)
904 Actions
.CodeCompleteObjCMessageReceiver(getCurScope());
906 Actions
.CodeCompleteLambdaIntroducer(getCurScope(), Intro
,
907 /*AfterAmpersand=*/false);
914 LambdaCaptureKind Kind
= LCK_ByCopy
;
915 LambdaCaptureInitKind InitKind
= LambdaCaptureInitKind::NoInit
;
917 IdentifierInfo
*Id
= nullptr;
918 SourceLocation EllipsisLocs
[4];
920 SourceLocation LocStart
= Tok
.getLocation();
922 if (Tok
.is(tok::star
)) {
923 Loc
= ConsumeToken();
924 if (Tok
.is(tok::kw_this
)) {
929 Diag(Tok
.getLocation(), diag::err_expected_star_this_capture
);
932 } else if (Tok
.is(tok::kw_this
)) {
934 Loc
= ConsumeToken();
935 } else if (Tok
.isOneOf(tok::amp
, tok::equal
) &&
936 NextToken().isOneOf(tok::comma
, tok::r_square
) &&
937 Intro
.Default
== LCD_None
) {
938 // We have a lone "&" or "=" which is either a misplaced capture-default
939 // or the start of a capture (in the "&" case) with the rest of the
940 // capture missing. Both are an error but a misplaced capture-default
941 // is more likely if we don't already have a capture default.
943 [&] { Diag(Tok
.getLocation(), diag::err_capture_default_first
); });
945 TryConsumeToken(tok::ellipsis
, EllipsisLocs
[0]);
947 if (Tok
.is(tok::amp
)) {
951 if (Tok
.is(tok::code_completion
)) {
953 Actions
.CodeCompleteLambdaIntroducer(getCurScope(), Intro
,
954 /*AfterAmpersand=*/true);
959 TryConsumeToken(tok::ellipsis
, EllipsisLocs
[1]);
961 if (Tok
.is(tok::identifier
)) {
962 Id
= Tok
.getIdentifierInfo();
963 Loc
= ConsumeToken();
964 } else if (Tok
.is(tok::kw_this
)) {
966 // FIXME: Suggest a fixit here.
967 Diag(Tok
.getLocation(), diag::err_this_captured_by_reference
);
971 Diag(Tok
.getLocation(), diag::err_expected_capture
);
975 TryConsumeToken(tok::ellipsis
, EllipsisLocs
[2]);
977 if (Tok
.is(tok::l_paren
)) {
978 BalancedDelimiterTracker
Parens(*this, tok::l_paren
);
979 Parens
.consumeOpen();
981 InitKind
= LambdaCaptureInitKind::DirectInit
;
986 *Tentative
= LambdaIntroducerTentativeParse::Incomplete
;
987 } else if (ParseExpressionList(Exprs
)) {
991 Parens
.consumeClose();
992 Init
= Actions
.ActOnParenListExpr(Parens
.getOpenLocation(),
993 Parens
.getCloseLocation(),
996 } else if (Tok
.isOneOf(tok::l_brace
, tok::equal
)) {
997 // Each lambda init-capture forms its own full expression, which clears
998 // Actions.MaybeODRUseExprs. So create an expression evaluation context
999 // to save the necessary state, and restore it later.
1000 EnterExpressionEvaluationContext
EC(
1001 Actions
, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
1003 if (TryConsumeToken(tok::equal
))
1004 InitKind
= LambdaCaptureInitKind::CopyInit
;
1006 InitKind
= LambdaCaptureInitKind::ListInit
;
1009 Init
= ParseInitializer();
1010 } else if (Tok
.is(tok::l_brace
)) {
1011 BalancedDelimiterTracker
Braces(*this, tok::l_brace
);
1012 Braces
.consumeOpen();
1014 *Tentative
= LambdaIntroducerTentativeParse::Incomplete
;
1016 // We're disambiguating this:
1020 // We need to find the end of the following expression in order to
1021 // determine whether this is an Obj-C message send's receiver, a
1022 // C99 designator, or a lambda init-capture.
1024 // Parse the expression to find where it ends, and annotate it back
1025 // onto the tokens. We would have parsed this expression the same way
1026 // in either case: both the RHS of an init-capture and the RHS of an
1027 // assignment expression are parsed as an initializer-clause, and in
1028 // neither case can anything be added to the scope between the '[' and
1031 // FIXME: This is horrible. Adding a mechanism to skip an expression
1032 // would be much cleaner.
1033 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
1034 // that instead. (And if we see a ':' with no matching '?', we can
1035 // classify this as an Obj-C message send.)
1036 SourceLocation StartLoc
= Tok
.getLocation();
1037 InMessageExpressionRAIIObject
MaybeInMessageExpression(*this, true);
1038 Init
= ParseInitializer();
1039 if (!Init
.isInvalid())
1040 Init
= Actions
.CorrectDelayedTyposInExpr(Init
.get());
1042 if (Tok
.getLocation() != StartLoc
) {
1043 // Back out the lexing of the token after the initializer.
1044 PP
.RevertCachedTokens(1);
1046 // Replace the consumed tokens with an appropriate annotation.
1047 Tok
.setLocation(StartLoc
);
1048 Tok
.setKind(tok::annot_primary_expr
);
1049 setExprAnnotation(Tok
, Init
);
1050 Tok
.setAnnotationEndLoc(PP
.getLastCachedTokenLocation());
1051 PP
.AnnotateCachedTokens(Tok
);
1053 // Consume the annotated initializer.
1054 ConsumeAnnotationToken();
1059 TryConsumeToken(tok::ellipsis
, EllipsisLocs
[3]);
1062 // Check if this is a message send before we act on a possible init-capture.
1063 if (Tentative
&& Tok
.is(tok::identifier
) &&
1064 NextToken().isOneOf(tok::colon
, tok::r_square
)) {
1065 // This can only be a message send. We're done with disambiguation.
1066 *Tentative
= LambdaIntroducerTentativeParse::MessageSend
;
1070 // Ensure that any ellipsis was in the right place.
1071 SourceLocation EllipsisLoc
;
1072 if (llvm::any_of(EllipsisLocs
,
1073 [](SourceLocation Loc
) { return Loc
.isValid(); })) {
1074 // The '...' should appear before the identifier in an init-capture, and
1075 // after the identifier otherwise.
1076 bool InitCapture
= InitKind
!= LambdaCaptureInitKind::NoInit
;
1077 SourceLocation
*ExpectedEllipsisLoc
=
1078 !InitCapture
? &EllipsisLocs
[2] :
1079 Kind
== LCK_ByRef
? &EllipsisLocs
[1] :
1081 EllipsisLoc
= *ExpectedEllipsisLoc
;
1083 unsigned DiagID
= 0;
1084 if (EllipsisLoc
.isInvalid()) {
1085 DiagID
= diag::err_lambda_capture_misplaced_ellipsis
;
1086 for (SourceLocation Loc
: EllipsisLocs
) {
1091 unsigned NumEllipses
= std::accumulate(
1092 std::begin(EllipsisLocs
), std::end(EllipsisLocs
), 0,
1093 [](int N
, SourceLocation Loc
) { return N
+ Loc
.isValid(); });
1094 if (NumEllipses
> 1)
1095 DiagID
= diag::err_lambda_capture_multiple_ellipses
;
1098 NonTentativeAction([&] {
1099 // Point the diagnostic at the first misplaced ellipsis.
1100 SourceLocation DiagLoc
;
1101 for (SourceLocation
&Loc
: EllipsisLocs
) {
1102 if (&Loc
!= ExpectedEllipsisLoc
&& Loc
.isValid()) {
1107 assert(DiagLoc
.isValid() && "no location for diagnostic");
1109 // Issue the diagnostic and produce fixits showing where the ellipsis
1110 // should have been written.
1111 auto &&D
= Diag(DiagLoc
, DiagID
);
1112 if (DiagID
== diag::err_lambda_capture_misplaced_ellipsis
) {
1113 SourceLocation ExpectedLoc
=
1115 : Lexer::getLocForEndOfToken(
1116 Loc
, 0, PP
.getSourceManager(), getLangOpts());
1117 D
<< InitCapture
<< FixItHint::CreateInsertion(ExpectedLoc
, "...");
1119 for (SourceLocation
&Loc
: EllipsisLocs
) {
1120 if (&Loc
!= ExpectedEllipsisLoc
&& Loc
.isValid())
1121 D
<< FixItHint::CreateRemoval(Loc
);
1127 // Process the init-capture initializers now rather than delaying until we
1128 // form the lambda-expression so that they can be handled in the context
1129 // enclosing the lambda-expression, rather than in the context of the
1130 // lambda-expression itself.
1131 ParsedType InitCaptureType
;
1132 if (Init
.isUsable())
1133 Init
= Actions
.CorrectDelayedTyposInExpr(Init
.get());
1134 if (Init
.isUsable()) {
1135 NonTentativeAction([&] {
1136 // Get the pointer and store it in an lvalue, so we can use it as an
1138 Expr
*InitExpr
= Init
.get();
1139 // This performs any lvalue-to-rvalue conversions if necessary, which
1140 // can affect what gets captured in the containing decl-context.
1141 InitCaptureType
= Actions
.actOnLambdaInitCaptureInitialization(
1142 Loc
, Kind
== LCK_ByRef
, EllipsisLoc
, Id
, InitKind
, InitExpr
);
1147 SourceLocation LocEnd
= PrevTokLocation
;
1149 Intro
.addCapture(Kind
, Loc
, Id
, EllipsisLoc
, InitKind
, Init
,
1150 InitCaptureType
, SourceRange(LocStart
, LocEnd
));
1154 Intro
.Range
.setEnd(T
.getCloseLocation());
1158 static void tryConsumeLambdaSpecifierToken(Parser
&P
,
1159 SourceLocation
&MutableLoc
,
1160 SourceLocation
&StaticLoc
,
1161 SourceLocation
&ConstexprLoc
,
1162 SourceLocation
&ConstevalLoc
,
1163 SourceLocation
&DeclEndLoc
) {
1164 assert(MutableLoc
.isInvalid());
1165 assert(StaticLoc
.isInvalid());
1166 assert(ConstexprLoc
.isInvalid());
1167 assert(ConstevalLoc
.isInvalid());
1168 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1169 // to the final of those locations. Emit an error if we have multiple
1170 // copies of those keywords and recover.
1172 auto ConsumeLocation
= [&P
, &DeclEndLoc
](SourceLocation
&SpecifierLoc
,
1174 if (SpecifierLoc
.isValid()) {
1175 P
.Diag(P
.getCurToken().getLocation(),
1176 diag::err_lambda_decl_specifier_repeated
)
1178 << FixItHint::CreateRemoval(P
.getCurToken().getLocation());
1180 SpecifierLoc
= P
.ConsumeToken();
1181 DeclEndLoc
= SpecifierLoc
;
1185 switch (P
.getCurToken().getKind()) {
1186 case tok::kw_mutable
:
1187 ConsumeLocation(MutableLoc
, 0);
1189 case tok::kw_static
:
1190 ConsumeLocation(StaticLoc
, 1);
1192 case tok::kw_constexpr
:
1193 ConsumeLocation(ConstexprLoc
, 2);
1195 case tok::kw_consteval
:
1196 ConsumeLocation(ConstevalLoc
, 3);
1204 static void addStaticToLambdaDeclSpecifier(Parser
&P
, SourceLocation StaticLoc
,
1206 if (StaticLoc
.isValid()) {
1207 P
.Diag(StaticLoc
, !P
.getLangOpts().CPlusPlus2b
1208 ? diag::err_static_lambda
1209 : diag::warn_cxx20_compat_static_lambda
);
1210 const char *PrevSpec
= nullptr;
1211 unsigned DiagID
= 0;
1212 DS
.SetStorageClassSpec(P
.getActions(), DeclSpec::SCS_static
, StaticLoc
,
1214 P
.getActions().getASTContext().getPrintingPolicy());
1215 assert(PrevSpec
== nullptr && DiagID
== 0 &&
1216 "Static cannot have been set previously!");
1221 addConstexprToLambdaDeclSpecifier(Parser
&P
, SourceLocation ConstexprLoc
,
1223 if (ConstexprLoc
.isValid()) {
1224 P
.Diag(ConstexprLoc
, !P
.getLangOpts().CPlusPlus17
1225 ? diag::ext_constexpr_on_lambda_cxx17
1226 : diag::warn_cxx14_compat_constexpr_on_lambda
);
1227 const char *PrevSpec
= nullptr;
1228 unsigned DiagID
= 0;
1229 DS
.SetConstexprSpec(ConstexprSpecKind::Constexpr
, ConstexprLoc
, PrevSpec
,
1231 assert(PrevSpec
== nullptr && DiagID
== 0 &&
1232 "Constexpr cannot have been set previously!");
1236 static void addConstevalToLambdaDeclSpecifier(Parser
&P
,
1237 SourceLocation ConstevalLoc
,
1239 if (ConstevalLoc
.isValid()) {
1240 P
.Diag(ConstevalLoc
, diag::warn_cxx20_compat_consteval
);
1241 const char *PrevSpec
= nullptr;
1242 unsigned DiagID
= 0;
1243 DS
.SetConstexprSpec(ConstexprSpecKind::Consteval
, ConstevalLoc
, PrevSpec
,
1246 P
.Diag(ConstevalLoc
, DiagID
) << PrevSpec
;
1250 static void DiagnoseStaticSpecifierRestrictions(Parser
&P
,
1251 SourceLocation StaticLoc
,
1252 SourceLocation MutableLoc
,
1253 const LambdaIntroducer
&Intro
) {
1254 if (StaticLoc
.isInvalid())
1257 // [expr.prim.lambda.general] p4
1258 // The lambda-specifier-seq shall not contain both mutable and static.
1259 // If the lambda-specifier-seq contains static, there shall be no
1261 if (MutableLoc
.isValid())
1262 P
.Diag(StaticLoc
, diag::err_static_mutable_lambda
);
1263 if (Intro
.hasLambdaCapture()) {
1264 P
.Diag(StaticLoc
, diag::err_static_lambda_captures
);
1268 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1270 ExprResult
Parser::ParseLambdaExpressionAfterIntroducer(
1271 LambdaIntroducer
&Intro
) {
1272 SourceLocation LambdaBeginLoc
= Intro
.Range
.getBegin();
1273 Diag(LambdaBeginLoc
, diag::warn_cxx98_compat_lambda
);
1275 PrettyStackTraceLoc
CrashInfo(PP
.getSourceManager(), LambdaBeginLoc
,
1276 "lambda expression parsing");
1280 // FIXME: Call into Actions to add any init-capture declarations to the
1281 // scope while parsing the lambda-declarator and compound-statement.
1283 // Parse lambda-declarator[opt].
1284 DeclSpec
DS(AttrFactory
);
1285 Declarator
D(DS
, ParsedAttributesView::none(), DeclaratorContext::LambdaExpr
);
1286 TemplateParameterDepthRAII
CurTemplateDepthTracker(TemplateParameterDepth
);
1287 Actions
.PushLambdaScope();
1289 ParsedAttributes
Attr(AttrFactory
);
1290 if (getLangOpts().CUDA
) {
1291 // In CUDA code, GNU attributes are allowed to appear immediately after the
1292 // "[...]", even if there is no "(...)" before the lambda body.
1294 // Note that we support __noinline__ as a keyword in this mode and thus
1295 // it has to be separately handled.
1297 if (Tok
.is(tok::kw___noinline__
)) {
1298 IdentifierInfo
*AttrName
= Tok
.getIdentifierInfo();
1299 SourceLocation AttrNameLoc
= ConsumeToken();
1300 Attr
.addNew(AttrName
, AttrNameLoc
, nullptr, AttrNameLoc
, nullptr, 0,
1301 ParsedAttr::AS_Keyword
);
1302 } else if (Tok
.is(tok::kw___attribute
))
1303 ParseGNUAttributes(Attr
, nullptr, &D
);
1308 D
.takeAttributes(Attr
);
1311 // Helper to emit a warning if we see a CUDA host/device/global attribute
1312 // after '(...)'. nvcc doesn't accept this.
1313 auto WarnIfHasCUDATargetAttr
= [&] {
1314 if (getLangOpts().CUDA
)
1315 for (const ParsedAttr
&A
: Attr
)
1316 if (A
.getKind() == ParsedAttr::AT_CUDADevice
||
1317 A
.getKind() == ParsedAttr::AT_CUDAHost
||
1318 A
.getKind() == ParsedAttr::AT_CUDAGlobal
)
1319 Diag(A
.getLoc(), diag::warn_cuda_attr_lambda_position
)
1320 << A
.getAttrName()->getName();
1323 MultiParseScope
TemplateParamScope(*this);
1324 if (Tok
.is(tok::less
)) {
1325 Diag(Tok
, getLangOpts().CPlusPlus20
1326 ? diag::warn_cxx17_compat_lambda_template_parameter_list
1327 : diag::ext_lambda_template_parameter_list
);
1329 SmallVector
<NamedDecl
*, 4> TemplateParams
;
1330 SourceLocation LAngleLoc
, RAngleLoc
;
1331 if (ParseTemplateParameters(TemplateParamScope
,
1332 CurTemplateDepthTracker
.getDepth(),
1333 TemplateParams
, LAngleLoc
, RAngleLoc
)) {
1334 Actions
.ActOnLambdaError(LambdaBeginLoc
, getCurScope());
1338 if (TemplateParams
.empty()) {
1340 diag::err_lambda_template_parameter_list_empty
);
1342 ExprResult RequiresClause
;
1343 if (TryConsumeToken(tok::kw_requires
)) {
1345 Actions
.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
1346 /*IsTrailingRequiresClause=*/false));
1347 if (RequiresClause
.isInvalid())
1348 SkipUntil({tok::l_brace
, tok::l_paren
}, StopAtSemi
| StopBeforeMatch
);
1351 Actions
.ActOnLambdaExplicitTemplateParameterList(
1352 LAngleLoc
, TemplateParams
, RAngleLoc
, RequiresClause
);
1353 ++CurTemplateDepthTracker
;
1357 // Implement WG21 P2173, which allows attributes immediately before the
1358 // lambda declarator and applies them to the corresponding function operator
1359 // or operator template declaration. We accept this as a conforming extension
1360 // in all language modes that support lambdas.
1361 if (isCXX11AttributeSpecifier()) {
1362 Diag(Tok
, getLangOpts().CPlusPlus2b
1363 ? diag::warn_cxx20_compat_decl_attrs_on_lambda
1364 : diag::ext_decl_attrs_on_lambda
);
1365 MaybeParseCXX11Attributes(D
);
1368 TypeResult TrailingReturnType
;
1369 SourceLocation TrailingReturnTypeLoc
;
1371 auto ParseLambdaSpecifiers
=
1372 [&](SourceLocation LParenLoc
, SourceLocation RParenLoc
,
1373 MutableArrayRef
<DeclaratorChunk::ParamInfo
> ParamInfo
,
1374 SourceLocation EllipsisLoc
) {
1375 SourceLocation DeclEndLoc
= RParenLoc
;
1377 // GNU-style attributes must be parsed before the mutable specifier to
1378 // be compatible with GCC. MSVC-style attributes must be parsed before
1379 // the mutable specifier to be compatible with MSVC.
1380 MaybeParseAttributes(PAKM_GNU
| PAKM_Declspec
, Attr
);
1382 // Parse lambda specifiers and update the DeclEndLoc.
1383 SourceLocation MutableLoc
;
1384 SourceLocation StaticLoc
;
1385 SourceLocation ConstexprLoc
;
1386 SourceLocation ConstevalLoc
;
1387 tryConsumeLambdaSpecifierToken(*this, MutableLoc
, StaticLoc
,
1388 ConstexprLoc
, ConstevalLoc
, DeclEndLoc
);
1390 DiagnoseStaticSpecifierRestrictions(*this, StaticLoc
, MutableLoc
,
1393 addStaticToLambdaDeclSpecifier(*this, StaticLoc
, DS
);
1394 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc
, DS
);
1395 addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc
, DS
);
1396 // Parse exception-specification[opt].
1397 ExceptionSpecificationType ESpecType
= EST_None
;
1398 SourceRange ESpecRange
;
1399 SmallVector
<ParsedType
, 2> DynamicExceptions
;
1400 SmallVector
<SourceRange
, 2> DynamicExceptionRanges
;
1401 ExprResult NoexceptExpr
;
1402 CachedTokens
*ExceptionSpecTokens
;
1403 ESpecType
= tryParseExceptionSpecification(
1404 /*Delayed=*/false, ESpecRange
, DynamicExceptions
,
1405 DynamicExceptionRanges
, NoexceptExpr
, ExceptionSpecTokens
);
1407 if (ESpecType
!= EST_None
)
1408 DeclEndLoc
= ESpecRange
.getEnd();
1410 // Parse attribute-specifier[opt].
1411 if (MaybeParseCXX11Attributes(Attr
))
1412 DeclEndLoc
= Attr
.Range
.getEnd();
1414 // Parse OpenCL addr space attribute.
1415 if (Tok
.isOneOf(tok::kw___private
, tok::kw___global
, tok::kw___local
,
1416 tok::kw___constant
, tok::kw___generic
)) {
1417 ParseOpenCLQualifiers(DS
.getAttributes());
1421 SourceLocation FunLocalRangeEnd
= DeclEndLoc
;
1423 // Parse trailing-return-type[opt].
1424 if (Tok
.is(tok::arrow
)) {
1425 FunLocalRangeEnd
= Tok
.getLocation();
1427 TrailingReturnType
= ParseTrailingReturnType(
1428 Range
, /*MayBeFollowedByDirectInit*/ false);
1429 TrailingReturnTypeLoc
= Range
.getBegin();
1430 if (Range
.getEnd().isValid())
1431 DeclEndLoc
= Range
.getEnd();
1434 SourceLocation NoLoc
;
1436 DeclaratorChunk::getFunction(
1438 /*IsAmbiguous=*/false, LParenLoc
, ParamInfo
.data(),
1439 ParamInfo
.size(), EllipsisLoc
, RParenLoc
,
1440 /*RefQualifierIsLvalueRef=*/true,
1441 /*RefQualifierLoc=*/NoLoc
, MutableLoc
, ESpecType
, ESpecRange
,
1442 DynamicExceptions
.data(), DynamicExceptionRanges
.data(),
1443 DynamicExceptions
.size(),
1444 NoexceptExpr
.isUsable() ? NoexceptExpr
.get() : nullptr,
1445 /*ExceptionSpecTokens*/ nullptr,
1446 /*DeclsInPrototype=*/std::nullopt
, LParenLoc
, FunLocalRangeEnd
,
1447 D
, TrailingReturnType
, TrailingReturnTypeLoc
, &DS
),
1448 std::move(Attr
), DeclEndLoc
);
1451 if (Tok
.is(tok::l_paren
)) {
1452 ParseScope
PrototypeScope(this, Scope::FunctionPrototypeScope
|
1453 Scope::FunctionDeclarationScope
|
1456 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1458 SourceLocation LParenLoc
= T
.getOpenLocation();
1460 // Parse parameter-declaration-clause.
1461 SmallVector
<DeclaratorChunk::ParamInfo
, 16> ParamInfo
;
1462 SourceLocation EllipsisLoc
;
1464 if (Tok
.isNot(tok::r_paren
)) {
1465 Actions
.RecordParsingTemplateParameterDepth(
1466 CurTemplateDepthTracker
.getOriginalDepth());
1468 ParseParameterDeclarationClause(D
, Attr
, ParamInfo
, EllipsisLoc
);
1469 // For a generic lambda, each 'auto' within the parameter declaration
1470 // clause creates a template type parameter, so increment the depth.
1471 // If we've parsed any explicit template parameters, then the depth will
1472 // have already been incremented. So we make sure that at most a single
1473 // depth level is added.
1474 if (Actions
.getCurGenericLambda())
1475 CurTemplateDepthTracker
.setAddedDepth(1);
1480 // Parse lambda-specifiers.
1481 ParseLambdaSpecifiers(LParenLoc
, /*DeclEndLoc=*/T
.getCloseLocation(),
1482 ParamInfo
, EllipsisLoc
);
1484 // Parse requires-clause[opt].
1485 if (Tok
.is(tok::kw_requires
))
1486 ParseTrailingRequiresClause(D
);
1487 } else if (Tok
.isOneOf(tok::kw_mutable
, tok::arrow
, tok::kw___attribute
,
1488 tok::kw_constexpr
, tok::kw_consteval
, tok::kw_static
,
1489 tok::kw___private
, tok::kw___global
, tok::kw___local
,
1490 tok::kw___constant
, tok::kw___generic
,
1491 tok::kw_groupshared
, tok::kw_requires
,
1492 tok::kw_noexcept
) ||
1493 (Tok
.is(tok::l_square
) && NextToken().is(tok::l_square
))) {
1494 if (!getLangOpts().CPlusPlus2b
)
1495 // It's common to forget that one needs '()' before 'mutable', an
1496 // attribute specifier, the result type, or the requires clause. Deal with
1498 Diag(Tok
, diag::ext_lambda_missing_parens
)
1499 << FixItHint::CreateInsertion(Tok
.getLocation(), "() ");
1501 SourceLocation NoLoc
;
1502 // Parse lambda-specifiers.
1503 std::vector
<DeclaratorChunk::ParamInfo
> EmptyParamInfo
;
1504 ParseLambdaSpecifiers(/*LParenLoc=*/NoLoc
, /*RParenLoc=*/NoLoc
,
1505 EmptyParamInfo
, /*EllipsisLoc=*/NoLoc
);
1508 WarnIfHasCUDATargetAttr();
1510 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1512 unsigned ScopeFlags
= Scope::BlockScope
| Scope::FnScope
| Scope::DeclScope
|
1513 Scope::CompoundStmtScope
;
1514 ParseScope
BodyScope(this, ScopeFlags
);
1516 Actions
.ActOnStartOfLambdaDefinition(Intro
, D
, getCurScope());
1518 // Parse compound-statement.
1519 if (!Tok
.is(tok::l_brace
)) {
1520 Diag(Tok
, diag::err_expected_lambda_body
);
1521 Actions
.ActOnLambdaError(LambdaBeginLoc
, getCurScope());
1525 StmtResult
Stmt(ParseCompoundStatementBody());
1527 TemplateParamScope
.Exit();
1529 if (!Stmt
.isInvalid() && !TrailingReturnType
.isInvalid())
1530 return Actions
.ActOnLambdaExpr(LambdaBeginLoc
, Stmt
.get(), getCurScope());
1532 Actions
.ActOnLambdaError(LambdaBeginLoc
, getCurScope());
1536 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1539 /// postfix-expression: [C++ 5.2p1]
1540 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1541 /// 'static_cast' '<' type-name '>' '(' expression ')'
1542 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1543 /// 'const_cast' '<' type-name '>' '(' expression ')'
1545 /// C++ for OpenCL s2.3.1 adds:
1546 /// 'addrspace_cast' '<' type-name '>' '(' expression ')'
1547 ExprResult
Parser::ParseCXXCasts() {
1548 tok::TokenKind Kind
= Tok
.getKind();
1549 const char *CastName
= nullptr; // For error messages
1552 default: llvm_unreachable("Unknown C++ cast!");
1553 case tok::kw_addrspace_cast
: CastName
= "addrspace_cast"; break;
1554 case tok::kw_const_cast
: CastName
= "const_cast"; break;
1555 case tok::kw_dynamic_cast
: CastName
= "dynamic_cast"; break;
1556 case tok::kw_reinterpret_cast
: CastName
= "reinterpret_cast"; break;
1557 case tok::kw_static_cast
: CastName
= "static_cast"; break;
1560 SourceLocation OpLoc
= ConsumeToken();
1561 SourceLocation LAngleBracketLoc
= Tok
.getLocation();
1563 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1564 // diagnose error, suggest fix, and recover parsing.
1565 if (Tok
.is(tok::l_square
) && Tok
.getLength() == 2) {
1566 Token Next
= NextToken();
1567 if (Next
.is(tok::colon
) && areTokensAdjacent(Tok
, Next
))
1568 FixDigraph(*this, PP
, Tok
, Next
, Kind
, /*AtDigraph*/true);
1571 if (ExpectAndConsume(tok::less
, diag::err_expected_less_after
, CastName
))
1574 // Parse the common declaration-specifiers piece.
1575 DeclSpec
DS(AttrFactory
);
1576 ParseSpecifierQualifierList(DS
, /*AccessSpecifier=*/AS_none
,
1577 DeclSpecContext::DSC_type_specifier
);
1579 // Parse the abstract-declarator, if present.
1580 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
1581 DeclaratorContext::TypeName
);
1582 ParseDeclarator(DeclaratorInfo
);
1584 SourceLocation RAngleBracketLoc
= Tok
.getLocation();
1586 if (ExpectAndConsume(tok::greater
))
1587 return ExprError(Diag(LAngleBracketLoc
, diag::note_matching
) << tok::less
);
1589 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1591 if (T
.expectAndConsume(diag::err_expected_lparen_after
, CastName
))
1594 ExprResult Result
= ParseExpression();
1599 if (!Result
.isInvalid() && !DeclaratorInfo
.isInvalidType())
1600 Result
= Actions
.ActOnCXXNamedCast(OpLoc
, Kind
,
1601 LAngleBracketLoc
, DeclaratorInfo
,
1603 T
.getOpenLocation(), Result
.get(),
1604 T
.getCloseLocation());
1609 /// ParseCXXTypeid - This handles the C++ typeid expression.
1611 /// postfix-expression: [C++ 5.2p1]
1612 /// 'typeid' '(' expression ')'
1613 /// 'typeid' '(' type-id ')'
1615 ExprResult
Parser::ParseCXXTypeid() {
1616 assert(Tok
.is(tok::kw_typeid
) && "Not 'typeid'!");
1618 SourceLocation OpLoc
= ConsumeToken();
1619 SourceLocation LParenLoc
, RParenLoc
;
1620 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1622 // typeid expressions are always parenthesized.
1623 if (T
.expectAndConsume(diag::err_expected_lparen_after
, "typeid"))
1625 LParenLoc
= T
.getOpenLocation();
1629 // C++0x [expr.typeid]p3:
1630 // When typeid is applied to an expression other than an lvalue of a
1631 // polymorphic class type [...] The expression is an unevaluated
1632 // operand (Clause 5).
1634 // Note that we can't tell whether the expression is an lvalue of a
1635 // polymorphic class type until after we've parsed the expression; we
1636 // speculatively assume the subexpression is unevaluated, and fix it up
1639 // We enter the unevaluated context before trying to determine whether we
1640 // have a type-id, because the tentative parse logic will try to resolve
1641 // names, and must treat them as unevaluated.
1642 EnterExpressionEvaluationContext
Unevaluated(
1643 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
,
1644 Sema::ReuseLambdaContextDecl
);
1646 if (isTypeIdInParens()) {
1647 TypeResult Ty
= ParseTypeName();
1651 RParenLoc
= T
.getCloseLocation();
1652 if (Ty
.isInvalid() || RParenLoc
.isInvalid())
1655 Result
= Actions
.ActOnCXXTypeid(OpLoc
, LParenLoc
, /*isType=*/true,
1656 Ty
.get().getAsOpaquePtr(), RParenLoc
);
1658 Result
= ParseExpression();
1661 if (Result
.isInvalid())
1662 SkipUntil(tok::r_paren
, StopAtSemi
);
1665 RParenLoc
= T
.getCloseLocation();
1666 if (RParenLoc
.isInvalid())
1669 Result
= Actions
.ActOnCXXTypeid(OpLoc
, LParenLoc
, /*isType=*/false,
1670 Result
.get(), RParenLoc
);
1677 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1679 /// '__uuidof' '(' expression ')'
1680 /// '__uuidof' '(' type-id ')'
1682 ExprResult
Parser::ParseCXXUuidof() {
1683 assert(Tok
.is(tok::kw___uuidof
) && "Not '__uuidof'!");
1685 SourceLocation OpLoc
= ConsumeToken();
1686 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1688 // __uuidof expressions are always parenthesized.
1689 if (T
.expectAndConsume(diag::err_expected_lparen_after
, "__uuidof"))
1694 if (isTypeIdInParens()) {
1695 TypeResult Ty
= ParseTypeName();
1703 Result
= Actions
.ActOnCXXUuidof(OpLoc
, T
.getOpenLocation(), /*isType=*/true,
1704 Ty
.get().getAsOpaquePtr(),
1705 T
.getCloseLocation());
1707 EnterExpressionEvaluationContext
Unevaluated(
1708 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
);
1709 Result
= ParseExpression();
1712 if (Result
.isInvalid())
1713 SkipUntil(tok::r_paren
, StopAtSemi
);
1717 Result
= Actions
.ActOnCXXUuidof(OpLoc
, T
.getOpenLocation(),
1719 Result
.get(), T
.getCloseLocation());
1726 /// Parse a C++ pseudo-destructor expression after the base,
1727 /// . or -> operator, and nested-name-specifier have already been
1728 /// parsed. We're handling this fragment of the grammar:
1730 /// postfix-expression: [C++2a expr.post]
1731 /// postfix-expression . template[opt] id-expression
1732 /// postfix-expression -> template[opt] id-expression
1739 /// nested-name-specifier template[opt] unqualified-id
1741 /// nested-name-specifier:
1743 /// decltype-specifier :: FIXME: not implemented, but probably only
1744 /// allowed in C++ grammar by accident
1745 /// nested-name-specifier identifier ::
1746 /// nested-name-specifier template[opt] simple-template-id ::
1751 /// ~ decltype-specifier
1754 /// ... where the all but the last component of the nested-name-specifier
1755 /// has already been parsed, and the base expression is not of a non-dependent
1758 Parser::ParseCXXPseudoDestructor(Expr
*Base
, SourceLocation OpLoc
,
1759 tok::TokenKind OpKind
,
1761 ParsedType ObjectType
) {
1762 // If the last component of the (optional) nested-name-specifier is
1763 // template[opt] simple-template-id, it has already been annotated.
1764 UnqualifiedId FirstTypeName
;
1765 SourceLocation CCLoc
;
1766 if (Tok
.is(tok::identifier
)) {
1767 FirstTypeName
.setIdentifier(Tok
.getIdentifierInfo(), Tok
.getLocation());
1769 assert(Tok
.is(tok::coloncolon
) &&"ParseOptionalCXXScopeSpecifier fail");
1770 CCLoc
= ConsumeToken();
1771 } else if (Tok
.is(tok::annot_template_id
)) {
1772 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
1773 // FIXME: Carry on and build an AST representation for tooling.
1774 if (TemplateId
->isInvalid())
1776 FirstTypeName
.setTemplateId(TemplateId
);
1777 ConsumeAnnotationToken();
1778 assert(Tok
.is(tok::coloncolon
) &&"ParseOptionalCXXScopeSpecifier fail");
1779 CCLoc
= ConsumeToken();
1781 assert(SS
.isEmpty() && "missing last component of nested name specifier");
1782 FirstTypeName
.setIdentifier(nullptr, SourceLocation());
1786 assert(Tok
.is(tok::tilde
) && "ParseOptionalCXXScopeSpecifier fail");
1787 SourceLocation TildeLoc
= ConsumeToken();
1789 if (Tok
.is(tok::kw_decltype
) && !FirstTypeName
.isValid()) {
1790 DeclSpec
DS(AttrFactory
);
1791 ParseDecltypeSpecifier(DS
);
1792 if (DS
.getTypeSpecType() == TST_error
)
1794 return Actions
.ActOnPseudoDestructorExpr(getCurScope(), Base
, OpLoc
, OpKind
,
1798 if (!Tok
.is(tok::identifier
)) {
1799 Diag(Tok
, diag::err_destructor_tilde_identifier
);
1803 // Parse the second type.
1804 UnqualifiedId SecondTypeName
;
1805 IdentifierInfo
*Name
= Tok
.getIdentifierInfo();
1806 SourceLocation NameLoc
= ConsumeToken();
1807 SecondTypeName
.setIdentifier(Name
, NameLoc
);
1809 // If there is a '<', the second type name is a template-id. Parse
1812 // FIXME: This is not a context in which a '<' is assumed to start a template
1813 // argument list. This affects examples such as
1814 // void f(auto *p) { p->~X<int>(); }
1815 // ... but there's no ambiguity, and nowhere to write 'template' in such an
1816 // example, so we accept it anyway.
1817 if (Tok
.is(tok::less
) &&
1818 ParseUnqualifiedIdTemplateId(
1819 SS
, ObjectType
, Base
&& Base
->containsErrors(), SourceLocation(),
1820 Name
, NameLoc
, false, SecondTypeName
,
1821 /*AssumeTemplateId=*/true))
1824 return Actions
.ActOnPseudoDestructorExpr(getCurScope(), Base
, OpLoc
, OpKind
,
1825 SS
, FirstTypeName
, CCLoc
, TildeLoc
,
1829 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1831 /// boolean-literal: [C++ 2.13.5]
1834 ExprResult
Parser::ParseCXXBoolLiteral() {
1835 tok::TokenKind Kind
= Tok
.getKind();
1836 return Actions
.ActOnCXXBoolLiteral(ConsumeToken(), Kind
);
1839 /// ParseThrowExpression - This handles the C++ throw expression.
1841 /// throw-expression: [C++ 15]
1842 /// 'throw' assignment-expression[opt]
1843 ExprResult
Parser::ParseThrowExpression() {
1844 assert(Tok
.is(tok::kw_throw
) && "Not throw!");
1845 SourceLocation ThrowLoc
= ConsumeToken(); // Eat the throw token.
1847 // If the current token isn't the start of an assignment-expression,
1848 // then the expression is not present. This handles things like:
1849 // "C ? throw : (void)42", which is crazy but legal.
1850 switch (Tok
.getKind()) { // FIXME: move this predicate somewhere common.
1857 return Actions
.ActOnCXXThrow(getCurScope(), ThrowLoc
, nullptr);
1860 ExprResult
Expr(ParseAssignmentExpression());
1861 if (Expr
.isInvalid()) return Expr
;
1862 return Actions
.ActOnCXXThrow(getCurScope(), ThrowLoc
, Expr
.get());
1866 /// Parse the C++ Coroutines co_yield expression.
1868 /// co_yield-expression:
1869 /// 'co_yield' assignment-expression[opt]
1870 ExprResult
Parser::ParseCoyieldExpression() {
1871 assert(Tok
.is(tok::kw_co_yield
) && "Not co_yield!");
1873 SourceLocation Loc
= ConsumeToken();
1874 ExprResult Expr
= Tok
.is(tok::l_brace
) ? ParseBraceInitializer()
1875 : ParseAssignmentExpression();
1876 if (!Expr
.isInvalid())
1877 Expr
= Actions
.ActOnCoyieldExpr(getCurScope(), Loc
, Expr
.get());
1881 /// ParseCXXThis - This handles the C++ 'this' pointer.
1883 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1884 /// a non-lvalue expression whose value is the address of the object for which
1885 /// the function is called.
1886 ExprResult
Parser::ParseCXXThis() {
1887 assert(Tok
.is(tok::kw_this
) && "Not 'this'!");
1888 SourceLocation ThisLoc
= ConsumeToken();
1889 return Actions
.ActOnCXXThis(ThisLoc
);
1892 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1893 /// Can be interpreted either as function-style casting ("int(x)")
1894 /// or class type construction ("ClassType(x,y,z)")
1895 /// or creation of a value-initialized type ("int()").
1896 /// See [C++ 5.2.3].
1898 /// postfix-expression: [C++ 5.2p1]
1899 /// simple-type-specifier '(' expression-list[opt] ')'
1900 /// [C++0x] simple-type-specifier braced-init-list
1901 /// typename-specifier '(' expression-list[opt] ')'
1902 /// [C++0x] typename-specifier braced-init-list
1904 /// In C++1z onwards, the type specifier can also be a template-name.
1906 Parser::ParseCXXTypeConstructExpression(const DeclSpec
&DS
) {
1907 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
1908 DeclaratorContext::FunctionalCast
);
1909 ParsedType TypeRep
= Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
).get();
1911 assert((Tok
.is(tok::l_paren
) ||
1912 (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
)))
1913 && "Expected '(' or '{'!");
1915 if (Tok
.is(tok::l_brace
)) {
1916 PreferredType
.enterTypeCast(Tok
.getLocation(), TypeRep
.get());
1917 ExprResult Init
= ParseBraceInitializer();
1918 if (Init
.isInvalid())
1920 Expr
*InitList
= Init
.get();
1921 return Actions
.ActOnCXXTypeConstructExpr(
1922 TypeRep
, InitList
->getBeginLoc(), MultiExprArg(&InitList
, 1),
1923 InitList
->getEndLoc(), /*ListInitialization=*/true);
1925 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1928 PreferredType
.enterTypeCast(Tok
.getLocation(), TypeRep
.get());
1932 auto RunSignatureHelp
= [&]() {
1933 QualType PreferredType
;
1935 PreferredType
= Actions
.ProduceConstructorSignatureHelp(
1936 TypeRep
.get()->getCanonicalTypeInternal(), DS
.getEndLoc(), Exprs
,
1937 T
.getOpenLocation(), /*Braced=*/false);
1938 CalledSignatureHelp
= true;
1939 return PreferredType
;
1942 if (Tok
.isNot(tok::r_paren
)) {
1943 if (ParseExpressionList(Exprs
, [&] {
1944 PreferredType
.enterFunctionArgument(Tok
.getLocation(),
1947 if (PP
.isCodeCompletionReached() && !CalledSignatureHelp
)
1949 SkipUntil(tok::r_paren
, StopAtSemi
);
1957 // TypeRep could be null, if it references an invalid typedef.
1961 return Actions
.ActOnCXXTypeConstructExpr(TypeRep
, T
.getOpenLocation(),
1962 Exprs
, T
.getCloseLocation(),
1963 /*ListInitialization=*/false);
1967 Parser::DeclGroupPtrTy
1968 Parser::ParseAliasDeclarationInInitStatement(DeclaratorContext Context
,
1969 ParsedAttributes
&Attrs
) {
1970 assert(Tok
.is(tok::kw_using
) && "Expected using");
1971 assert((Context
== DeclaratorContext::ForInit
||
1972 Context
== DeclaratorContext::SelectionInit
) &&
1973 "Unexpected Declarator Context");
1975 SourceLocation DeclStart
= ConsumeToken(), DeclEnd
;
1977 DG
= ParseUsingDeclaration(Context
, {}, DeclStart
, DeclEnd
, Attrs
, AS_none
);
1981 Diag(DeclStart
, !getLangOpts().CPlusPlus2b
1982 ? diag::ext_alias_in_init_statement
1983 : diag::warn_cxx20_alias_in_init_statement
)
1984 << SourceRange(DeclStart
, DeclEnd
);
1989 /// ParseCXXCondition - if/switch/while condition expression.
1993 /// type-specifier-seq declarator '=' assignment-expression
1994 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1995 /// [C++11] type-specifier-seq declarator braced-init-list
1996 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1997 /// brace-or-equal-initializer
1998 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1999 /// '=' assignment-expression
2001 /// In C++1z, a condition may in some contexts be preceded by an
2002 /// optional init-statement. This function will parse that too.
2004 /// \param InitStmt If non-null, an init-statement is permitted, and if present
2005 /// will be parsed and stored here.
2007 /// \param Loc The location of the start of the statement that requires this
2008 /// condition, e.g., the "for" in a for loop.
2010 /// \param MissingOK Whether an empty condition is acceptable here. Otherwise
2011 /// it is considered an error to be recovered from.
2013 /// \param FRI If non-null, a for range declaration is permitted, and if
2014 /// present will be parsed and stored here, and a null result will be returned.
2016 /// \param EnterForConditionScope If true, enter a continue/break scope at the
2017 /// appropriate moment for a 'for' loop.
2019 /// \returns The parsed condition.
2020 Sema::ConditionResult
2021 Parser::ParseCXXCondition(StmtResult
*InitStmt
, SourceLocation Loc
,
2022 Sema::ConditionKind CK
, bool MissingOK
,
2023 ForRangeInfo
*FRI
, bool EnterForConditionScope
) {
2024 // Helper to ensure we always enter a continue/break scope if requested.
2025 struct ForConditionScopeRAII
{
2027 void enter(bool IsConditionVariable
) {
2029 S
->AddFlags(Scope::BreakScope
| Scope::ContinueScope
);
2030 S
->setIsConditionVarScope(IsConditionVariable
);
2033 ~ForConditionScopeRAII() {
2035 S
->setIsConditionVarScope(false);
2037 } ForConditionScope
{EnterForConditionScope
? getCurScope() : nullptr};
2039 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
2040 PreferredType
.enterCondition(Actions
, Tok
.getLocation());
2042 if (Tok
.is(tok::code_completion
)) {
2044 Actions
.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition
);
2045 return Sema::ConditionError();
2048 ParsedAttributes
attrs(AttrFactory
);
2049 MaybeParseCXX11Attributes(attrs
);
2051 const auto WarnOnInit
= [this, &CK
] {
2052 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus17
2053 ? diag::warn_cxx14_compat_init_statement
2054 : diag::ext_init_statement
)
2055 << (CK
== Sema::ConditionKind::Switch
);
2058 // Determine what kind of thing we have.
2059 switch (isCXXConditionDeclarationOrInitStatement(InitStmt
, FRI
)) {
2060 case ConditionOrInitStatement::Expression
: {
2061 // If this is a for loop, we're entering its condition.
2062 ForConditionScope
.enter(/*IsConditionVariable=*/false);
2064 ProhibitAttributes(attrs
);
2066 // We can have an empty expression here.
2068 if (InitStmt
&& Tok
.is(tok::semi
)) {
2070 SourceLocation SemiLoc
= Tok
.getLocation();
2071 if (!Tok
.hasLeadingEmptyMacro() && !SemiLoc
.isMacroID()) {
2072 Diag(SemiLoc
, diag::warn_empty_init_statement
)
2073 << (CK
== Sema::ConditionKind::Switch
)
2074 << FixItHint::CreateRemoval(SemiLoc
);
2077 *InitStmt
= Actions
.ActOnNullStmt(SemiLoc
);
2078 return ParseCXXCondition(nullptr, Loc
, CK
, MissingOK
);
2081 // Parse the expression.
2082 ExprResult Expr
= ParseExpression(); // expression
2083 if (Expr
.isInvalid())
2084 return Sema::ConditionError();
2086 if (InitStmt
&& Tok
.is(tok::semi
)) {
2088 *InitStmt
= Actions
.ActOnExprStmt(Expr
.get());
2090 return ParseCXXCondition(nullptr, Loc
, CK
, MissingOK
);
2093 return Actions
.ActOnCondition(getCurScope(), Loc
, Expr
.get(), CK
,
2097 case ConditionOrInitStatement::InitStmtDecl
: {
2100 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
2101 if (Tok
.is(tok::kw_using
))
2102 DG
= ParseAliasDeclarationInInitStatement(
2103 DeclaratorContext::SelectionInit
, attrs
);
2105 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
2106 DG
= ParseSimpleDeclaration(DeclaratorContext::SelectionInit
, DeclEnd
,
2107 attrs
, DeclSpecAttrs
, /*RequireSemi=*/true);
2109 *InitStmt
= Actions
.ActOnDeclStmt(DG
, DeclStart
, DeclEnd
);
2110 return ParseCXXCondition(nullptr, Loc
, CK
, MissingOK
);
2113 case ConditionOrInitStatement::ForRangeDecl
: {
2114 // This is 'for (init-stmt; for-range-decl : range-expr)'.
2115 // We're not actually in a for loop yet, so 'break' and 'continue' aren't
2117 assert(FRI
&& "should not parse a for range declaration here");
2118 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
2119 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
2120 DeclGroupPtrTy DG
= ParseSimpleDeclaration(
2121 DeclaratorContext::ForInit
, DeclEnd
, attrs
, DeclSpecAttrs
, false, FRI
);
2122 FRI
->LoopVar
= Actions
.ActOnDeclStmt(DG
, DeclStart
, Tok
.getLocation());
2123 assert((FRI
->ColonLoc
.isValid() || !DG
) &&
2124 "cannot find for range declaration");
2125 return Sema::ConditionResult();
2128 case ConditionOrInitStatement::ConditionDecl
:
2129 case ConditionOrInitStatement::Error
:
2133 // If this is a for loop, we're entering its condition.
2134 ForConditionScope
.enter(/*IsConditionVariable=*/true);
2136 // type-specifier-seq
2137 DeclSpec
DS(AttrFactory
);
2138 ParseSpecifierQualifierList(DS
, AS_none
, DeclSpecContext::DSC_condition
);
2141 Declarator
DeclaratorInfo(DS
, attrs
, DeclaratorContext::Condition
);
2142 ParseDeclarator(DeclaratorInfo
);
2144 // simple-asm-expr[opt]
2145 if (Tok
.is(tok::kw_asm
)) {
2147 ExprResult
AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc
));
2148 if (AsmLabel
.isInvalid()) {
2149 SkipUntil(tok::semi
, StopAtSemi
);
2150 return Sema::ConditionError();
2152 DeclaratorInfo
.setAsmLabel(AsmLabel
.get());
2153 DeclaratorInfo
.SetRangeEnd(Loc
);
2156 // If attributes are present, parse them.
2157 MaybeParseGNUAttributes(DeclaratorInfo
);
2159 // Type-check the declaration itself.
2160 DeclResult Dcl
= Actions
.ActOnCXXConditionDeclaration(getCurScope(),
2162 if (Dcl
.isInvalid())
2163 return Sema::ConditionError();
2164 Decl
*DeclOut
= Dcl
.get();
2166 // '=' assignment-expression
2167 // If a '==' or '+=' is found, suggest a fixit to '='.
2168 bool CopyInitialization
= isTokenEqualOrEqualTypo();
2169 if (CopyInitialization
)
2172 ExprResult InitExpr
= ExprError();
2173 if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
)) {
2174 Diag(Tok
.getLocation(),
2175 diag::warn_cxx98_compat_generalized_initializer_lists
);
2176 InitExpr
= ParseBraceInitializer();
2177 } else if (CopyInitialization
) {
2178 PreferredType
.enterVariableInit(Tok
.getLocation(), DeclOut
);
2179 InitExpr
= ParseAssignmentExpression();
2180 } else if (Tok
.is(tok::l_paren
)) {
2181 // This was probably an attempt to initialize the variable.
2182 SourceLocation LParen
= ConsumeParen(), RParen
= LParen
;
2183 if (SkipUntil(tok::r_paren
, StopAtSemi
| StopBeforeMatch
))
2184 RParen
= ConsumeParen();
2185 Diag(DeclOut
->getLocation(),
2186 diag::err_expected_init_in_condition_lparen
)
2187 << SourceRange(LParen
, RParen
);
2189 Diag(DeclOut
->getLocation(), diag::err_expected_init_in_condition
);
2192 if (!InitExpr
.isInvalid())
2193 Actions
.AddInitializerToDecl(DeclOut
, InitExpr
.get(), !CopyInitialization
);
2195 Actions
.ActOnInitializerError(DeclOut
);
2197 Actions
.FinalizeDeclaration(DeclOut
);
2198 return Actions
.ActOnConditionVariable(DeclOut
, Loc
, CK
);
2201 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2202 /// This should only be called when the current token is known to be part of
2203 /// simple-type-specifier.
2205 /// simple-type-specifier:
2206 /// '::'[opt] nested-name-specifier[opt] type-name
2207 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
2219 /// [GNU] typeof-specifier
2220 /// [C++0x] auto [TODO]
2227 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec
&DS
) {
2228 DS
.SetRangeStart(Tok
.getLocation());
2229 const char *PrevSpec
;
2231 SourceLocation Loc
= Tok
.getLocation();
2232 const clang::PrintingPolicy
&Policy
=
2233 Actions
.getASTContext().getPrintingPolicy();
2235 switch (Tok
.getKind()) {
2236 case tok::identifier
: // foo::bar
2237 case tok::coloncolon
: // ::foo::bar
2238 llvm_unreachable("Annotation token should already be formed!");
2240 llvm_unreachable("Not a simple-type-specifier token!");
2243 case tok::annot_typename
: {
2244 DS
.SetTypeSpecType(DeclSpec::TST_typename
, Loc
, PrevSpec
, DiagID
,
2245 getTypeAnnotation(Tok
), Policy
);
2246 DS
.SetRangeEnd(Tok
.getAnnotationEndLoc());
2247 ConsumeAnnotationToken();
2249 DS
.Finish(Actions
, Policy
);
2253 case tok::kw__ExtInt
:
2254 case tok::kw__BitInt
: {
2255 DiagnoseBitIntUse(Tok
);
2256 ExprResult ER
= ParseExtIntegerArgument();
2258 DS
.SetTypeSpecError();
2260 DS
.SetBitIntType(Loc
, ER
.get(), PrevSpec
, DiagID
, Policy
);
2262 // Do this here because we have already consumed the close paren.
2263 DS
.SetRangeEnd(PrevTokLocation
);
2264 DS
.Finish(Actions
, Policy
);
2270 DS
.SetTypeSpecWidth(TypeSpecifierWidth::Short
, Loc
, PrevSpec
, DiagID
,
2274 DS
.SetTypeSpecWidth(TypeSpecifierWidth::Long
, Loc
, PrevSpec
, DiagID
,
2277 case tok::kw___int64
:
2278 DS
.SetTypeSpecWidth(TypeSpecifierWidth::LongLong
, Loc
, PrevSpec
, DiagID
,
2281 case tok::kw_signed
:
2282 DS
.SetTypeSpecSign(TypeSpecifierSign::Signed
, Loc
, PrevSpec
, DiagID
);
2284 case tok::kw_unsigned
:
2285 DS
.SetTypeSpecSign(TypeSpecifierSign::Unsigned
, Loc
, PrevSpec
, DiagID
);
2288 DS
.SetTypeSpecType(DeclSpec::TST_void
, Loc
, PrevSpec
, DiagID
, Policy
);
2291 DS
.SetTypeSpecType(DeclSpec::TST_auto
, Loc
, PrevSpec
, DiagID
, Policy
);
2294 DS
.SetTypeSpecType(DeclSpec::TST_char
, Loc
, PrevSpec
, DiagID
, Policy
);
2297 DS
.SetTypeSpecType(DeclSpec::TST_int
, Loc
, PrevSpec
, DiagID
, Policy
);
2299 case tok::kw___int128
:
2300 DS
.SetTypeSpecType(DeclSpec::TST_int128
, Loc
, PrevSpec
, DiagID
, Policy
);
2302 case tok::kw___bf16
:
2303 DS
.SetTypeSpecType(DeclSpec::TST_BFloat16
, Loc
, PrevSpec
, DiagID
, Policy
);
2306 DS
.SetTypeSpecType(DeclSpec::TST_half
, Loc
, PrevSpec
, DiagID
, Policy
);
2309 DS
.SetTypeSpecType(DeclSpec::TST_float
, Loc
, PrevSpec
, DiagID
, Policy
);
2311 case tok::kw_double
:
2312 DS
.SetTypeSpecType(DeclSpec::TST_double
, Loc
, PrevSpec
, DiagID
, Policy
);
2314 case tok::kw__Float16
:
2315 DS
.SetTypeSpecType(DeclSpec::TST_float16
, Loc
, PrevSpec
, DiagID
, Policy
);
2317 case tok::kw___float128
:
2318 DS
.SetTypeSpecType(DeclSpec::TST_float128
, Loc
, PrevSpec
, DiagID
, Policy
);
2320 case tok::kw___ibm128
:
2321 DS
.SetTypeSpecType(DeclSpec::TST_ibm128
, Loc
, PrevSpec
, DiagID
, Policy
);
2323 case tok::kw_wchar_t
:
2324 DS
.SetTypeSpecType(DeclSpec::TST_wchar
, Loc
, PrevSpec
, DiagID
, Policy
);
2326 case tok::kw_char8_t
:
2327 DS
.SetTypeSpecType(DeclSpec::TST_char8
, Loc
, PrevSpec
, DiagID
, Policy
);
2329 case tok::kw_char16_t
:
2330 DS
.SetTypeSpecType(DeclSpec::TST_char16
, Loc
, PrevSpec
, DiagID
, Policy
);
2332 case tok::kw_char32_t
:
2333 DS
.SetTypeSpecType(DeclSpec::TST_char32
, Loc
, PrevSpec
, DiagID
, Policy
);
2336 DS
.SetTypeSpecType(DeclSpec::TST_bool
, Loc
, PrevSpec
, DiagID
, Policy
);
2338 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
2339 case tok::kw_##ImgType##_t: \
2340 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2343 #include "clang/Basic/OpenCLImageTypes.def"
2345 case tok::annot_decltype
:
2346 case tok::kw_decltype
:
2347 DS
.SetRangeEnd(ParseDecltypeSpecifier(DS
));
2348 return DS
.Finish(Actions
, Policy
);
2350 // GNU typeof support.
2351 case tok::kw_typeof
:
2352 ParseTypeofSpecifier(DS
);
2353 DS
.Finish(Actions
, Policy
);
2357 DS
.SetRangeEnd(PrevTokLocation
);
2358 DS
.Finish(Actions
, Policy
);
2361 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2362 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
2363 /// e.g., "const short int". Note that the DeclSpec is *not* finished
2364 /// by parsing the type-specifier-seq, because these sequences are
2365 /// typically followed by some form of declarator. Returns true and
2366 /// emits diagnostics if this is not a type-specifier-seq, false
2369 /// type-specifier-seq: [C++ 8.1]
2370 /// type-specifier type-specifier-seq[opt]
2372 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec
&DS
, DeclaratorContext Context
) {
2373 ParseSpecifierQualifierList(DS
, AS_none
,
2374 getDeclSpecContextFromDeclaratorContext(Context
));
2375 DS
.Finish(Actions
, Actions
.getASTContext().getPrintingPolicy());
2379 /// Finish parsing a C++ unqualified-id that is a template-id of
2382 /// This routine is invoked when a '<' is encountered after an identifier or
2383 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2384 /// whether the unqualified-id is actually a template-id. This routine will
2385 /// then parse the template arguments and form the appropriate template-id to
2386 /// return to the caller.
2388 /// \param SS the nested-name-specifier that precedes this template-id, if
2389 /// we're actually parsing a qualified-id.
2391 /// \param ObjectType if this unqualified-id occurs within a member access
2392 /// expression, the type of the base object whose member is being accessed.
2394 /// \param ObjectHadErrors this unqualified-id occurs within a member access
2395 /// expression, indicates whether the original subexpressions had any errors.
2397 /// \param Name for constructor and destructor names, this is the actual
2398 /// identifier that may be a template-name.
2400 /// \param NameLoc the location of the class-name in a constructor or
2403 /// \param EnteringContext whether we're entering the scope of the
2404 /// nested-name-specifier.
2406 /// \param Id as input, describes the template-name or operator-function-id
2407 /// that precedes the '<'. If template arguments were parsed successfully,
2408 /// will be updated with the template-id.
2410 /// \param AssumeTemplateId When true, this routine will assume that the name
2411 /// refers to a template without performing name lookup to verify.
2413 /// \returns true if a parse error occurred, false otherwise.
2414 bool Parser::ParseUnqualifiedIdTemplateId(
2415 CXXScopeSpec
&SS
, ParsedType ObjectType
, bool ObjectHadErrors
,
2416 SourceLocation TemplateKWLoc
, IdentifierInfo
*Name
, SourceLocation NameLoc
,
2417 bool EnteringContext
, UnqualifiedId
&Id
, bool AssumeTemplateId
) {
2418 assert(Tok
.is(tok::less
) && "Expected '<' to finish parsing a template-id");
2420 TemplateTy Template
;
2421 TemplateNameKind TNK
= TNK_Non_template
;
2422 switch (Id
.getKind()) {
2423 case UnqualifiedIdKind::IK_Identifier
:
2424 case UnqualifiedIdKind::IK_OperatorFunctionId
:
2425 case UnqualifiedIdKind::IK_LiteralOperatorId
:
2426 if (AssumeTemplateId
) {
2427 // We defer the injected-class-name checks until we've found whether
2428 // this template-id is used to form a nested-name-specifier or not.
2429 TNK
= Actions
.ActOnTemplateName(getCurScope(), SS
, TemplateKWLoc
, Id
,
2430 ObjectType
, EnteringContext
, Template
,
2431 /*AllowInjectedClassName*/ true);
2433 bool MemberOfUnknownSpecialization
;
2434 TNK
= Actions
.isTemplateName(getCurScope(), SS
,
2435 TemplateKWLoc
.isValid(), Id
,
2436 ObjectType
, EnteringContext
, Template
,
2437 MemberOfUnknownSpecialization
);
2438 // If lookup found nothing but we're assuming that this is a template
2439 // name, double-check that makes sense syntactically before committing
2441 if (TNK
== TNK_Undeclared_template
&&
2442 isTemplateArgumentList(0) == TPResult::False
)
2445 if (TNK
== TNK_Non_template
&& MemberOfUnknownSpecialization
&&
2446 ObjectType
&& isTemplateArgumentList(0) == TPResult::True
) {
2447 // If we had errors before, ObjectType can be dependent even without any
2448 // templates, do not report missing template keyword in that case.
2449 if (!ObjectHadErrors
) {
2450 // We have something like t->getAs<T>(), where getAs is a
2451 // member of an unknown specialization. However, this will only
2452 // parse correctly as a template, so suggest the keyword 'template'
2453 // before 'getAs' and treat this as a dependent template name.
2455 if (Id
.getKind() == UnqualifiedIdKind::IK_Identifier
)
2456 Name
= std::string(Id
.Identifier
->getName());
2459 if (Id
.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId
)
2460 Name
+= getOperatorSpelling(Id
.OperatorFunctionId
.Operator
);
2462 Name
+= Id
.Identifier
->getName();
2464 Diag(Id
.StartLocation
, diag::err_missing_dependent_template_keyword
)
2466 << FixItHint::CreateInsertion(Id
.StartLocation
, "template ");
2468 TNK
= Actions
.ActOnTemplateName(
2469 getCurScope(), SS
, TemplateKWLoc
, Id
, ObjectType
, EnteringContext
,
2470 Template
, /*AllowInjectedClassName*/ true);
2471 } else if (TNK
== TNK_Non_template
) {
2477 case UnqualifiedIdKind::IK_ConstructorName
: {
2478 UnqualifiedId TemplateName
;
2479 bool MemberOfUnknownSpecialization
;
2480 TemplateName
.setIdentifier(Name
, NameLoc
);
2481 TNK
= Actions
.isTemplateName(getCurScope(), SS
, TemplateKWLoc
.isValid(),
2482 TemplateName
, ObjectType
,
2483 EnteringContext
, Template
,
2484 MemberOfUnknownSpecialization
);
2485 if (TNK
== TNK_Non_template
)
2490 case UnqualifiedIdKind::IK_DestructorName
: {
2491 UnqualifiedId TemplateName
;
2492 bool MemberOfUnknownSpecialization
;
2493 TemplateName
.setIdentifier(Name
, NameLoc
);
2495 TNK
= Actions
.ActOnTemplateName(
2496 getCurScope(), SS
, TemplateKWLoc
, TemplateName
, ObjectType
,
2497 EnteringContext
, Template
, /*AllowInjectedClassName*/ true);
2499 TNK
= Actions
.isTemplateName(getCurScope(), SS
, TemplateKWLoc
.isValid(),
2500 TemplateName
, ObjectType
,
2501 EnteringContext
, Template
,
2502 MemberOfUnknownSpecialization
);
2504 if (TNK
== TNK_Non_template
&& !Id
.DestructorName
.get()) {
2505 Diag(NameLoc
, diag::err_destructor_template_id
)
2506 << Name
<< SS
.getRange();
2507 // Carry on to parse the template arguments before bailing out.
2517 // Parse the enclosed template argument list.
2518 SourceLocation LAngleLoc
, RAngleLoc
;
2519 TemplateArgList TemplateArgs
;
2520 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc
, TemplateArgs
, RAngleLoc
,
2524 // If this is a non-template, we already issued a diagnostic.
2525 if (TNK
== TNK_Non_template
)
2528 if (Id
.getKind() == UnqualifiedIdKind::IK_Identifier
||
2529 Id
.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId
||
2530 Id
.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId
) {
2531 // Form a parsed representation of the template-id to be stored in the
2534 // FIXME: Store name for literal operator too.
2535 IdentifierInfo
*TemplateII
=
2536 Id
.getKind() == UnqualifiedIdKind::IK_Identifier
? Id
.Identifier
2538 OverloadedOperatorKind OpKind
=
2539 Id
.getKind() == UnqualifiedIdKind::IK_Identifier
2541 : Id
.OperatorFunctionId
.Operator
;
2543 TemplateIdAnnotation
*TemplateId
= TemplateIdAnnotation::Create(
2544 TemplateKWLoc
, Id
.StartLocation
, TemplateII
, OpKind
, Template
, TNK
,
2545 LAngleLoc
, RAngleLoc
, TemplateArgs
, /*ArgsInvalid*/false, TemplateIds
);
2547 Id
.setTemplateId(TemplateId
);
2551 // Bundle the template arguments together.
2552 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateArgs
);
2554 // Constructor and destructor names.
2555 TypeResult Type
= Actions
.ActOnTemplateIdType(
2556 getCurScope(), SS
, TemplateKWLoc
, Template
, Name
, NameLoc
, LAngleLoc
,
2557 TemplateArgsPtr
, RAngleLoc
, /*IsCtorOrDtorName=*/true);
2558 if (Type
.isInvalid())
2561 if (Id
.getKind() == UnqualifiedIdKind::IK_ConstructorName
)
2562 Id
.setConstructorName(Type
.get(), NameLoc
, RAngleLoc
);
2564 Id
.setDestructorName(Id
.StartLocation
, Type
.get(), RAngleLoc
);
2569 /// Parse an operator-function-id or conversion-function-id as part
2570 /// of a C++ unqualified-id.
2572 /// This routine is responsible only for parsing the operator-function-id or
2573 /// conversion-function-id; it does not handle template arguments in any way.
2576 /// operator-function-id: [C++ 13.5]
2577 /// 'operator' operator
2579 /// operator: one of
2580 /// new delete new[] delete[]
2581 /// + - * / % ^ & | ~
2582 /// ! = < > += -= *= /= %=
2583 /// ^= &= |= << >> >>= <<= == !=
2584 /// <= >= && || ++ -- , ->* ->
2587 /// conversion-function-id: [C++ 12.3.2]
2588 /// operator conversion-type-id
2590 /// conversion-type-id:
2591 /// type-specifier-seq conversion-declarator[opt]
2593 /// conversion-declarator:
2594 /// ptr-operator conversion-declarator[opt]
2597 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2598 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2600 /// \param EnteringContext whether we are entering the scope of the
2601 /// nested-name-specifier.
2603 /// \param ObjectType if this unqualified-id occurs within a member access
2604 /// expression, the type of the base object whose member is being accessed.
2606 /// \param Result on a successful parse, contains the parsed unqualified-id.
2608 /// \returns true if parsing fails, false otherwise.
2609 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec
&SS
, bool EnteringContext
,
2610 ParsedType ObjectType
,
2611 UnqualifiedId
&Result
) {
2612 assert(Tok
.is(tok::kw_operator
) && "Expected 'operator' keyword");
2614 // Consume the 'operator' keyword.
2615 SourceLocation KeywordLoc
= ConsumeToken();
2617 // Determine what kind of operator name we have.
2618 unsigned SymbolIdx
= 0;
2619 SourceLocation SymbolLocations
[3];
2620 OverloadedOperatorKind Op
= OO_None
;
2621 switch (Tok
.getKind()) {
2623 case tok::kw_delete
: {
2624 bool isNew
= Tok
.getKind() == tok::kw_new
;
2625 // Consume the 'new' or 'delete'.
2626 SymbolLocations
[SymbolIdx
++] = ConsumeToken();
2627 // Check for array new/delete.
2628 if (Tok
.is(tok::l_square
) &&
2629 (!getLangOpts().CPlusPlus11
|| NextToken().isNot(tok::l_square
))) {
2630 // Consume the '[' and ']'.
2631 BalancedDelimiterTracker
T(*this, tok::l_square
);
2634 if (T
.getCloseLocation().isInvalid())
2637 SymbolLocations
[SymbolIdx
++] = T
.getOpenLocation();
2638 SymbolLocations
[SymbolIdx
++] = T
.getCloseLocation();
2639 Op
= isNew
? OO_Array_New
: OO_Array_Delete
;
2641 Op
= isNew
? OO_New
: OO_Delete
;
2646 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2648 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2651 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2652 #include "clang/Basic/OperatorKinds.def"
2654 case tok::l_paren
: {
2655 // Consume the '(' and ')'.
2656 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2659 if (T
.getCloseLocation().isInvalid())
2662 SymbolLocations
[SymbolIdx
++] = T
.getOpenLocation();
2663 SymbolLocations
[SymbolIdx
++] = T
.getCloseLocation();
2668 case tok::l_square
: {
2669 // Consume the '[' and ']'.
2670 BalancedDelimiterTracker
T(*this, tok::l_square
);
2673 if (T
.getCloseLocation().isInvalid())
2676 SymbolLocations
[SymbolIdx
++] = T
.getOpenLocation();
2677 SymbolLocations
[SymbolIdx
++] = T
.getCloseLocation();
2682 case tok::code_completion
: {
2683 // Don't try to parse any further.
2685 // Code completion for the operator name.
2686 Actions
.CodeCompleteOperatorName(getCurScope());
2694 if (Op
!= OO_None
) {
2695 // We have parsed an operator-function-id.
2696 Result
.setOperatorFunctionId(KeywordLoc
, Op
, SymbolLocations
);
2700 // Parse a literal-operator-id.
2702 // literal-operator-id: C++11 [over.literal]
2703 // operator string-literal identifier
2704 // operator user-defined-string-literal
2706 if (getLangOpts().CPlusPlus11
&& isTokenStringLiteral()) {
2707 Diag(Tok
.getLocation(), diag::warn_cxx98_compat_literal_operator
);
2709 SourceLocation DiagLoc
;
2710 unsigned DiagId
= 0;
2712 // We're past translation phase 6, so perform string literal concatenation
2713 // before checking for "".
2714 SmallVector
<Token
, 4> Toks
;
2715 SmallVector
<SourceLocation
, 4> TokLocs
;
2716 while (isTokenStringLiteral()) {
2717 if (!Tok
.is(tok::string_literal
) && !DiagId
) {
2718 // C++11 [over.literal]p1:
2719 // The string-literal or user-defined-string-literal in a
2720 // literal-operator-id shall have no encoding-prefix [...].
2721 DiagLoc
= Tok
.getLocation();
2722 DiagId
= diag::err_literal_operator_string_prefix
;
2724 Toks
.push_back(Tok
);
2725 TokLocs
.push_back(ConsumeStringToken());
2728 StringLiteralParser
Literal(Toks
, PP
);
2729 if (Literal
.hadError
)
2732 // Grab the literal operator's suffix, which will be either the next token
2733 // or a ud-suffix from the string literal.
2734 bool IsUDSuffix
= !Literal
.getUDSuffix().empty();
2735 IdentifierInfo
*II
= nullptr;
2736 SourceLocation SuffixLoc
;
2738 II
= &PP
.getIdentifierTable().get(Literal
.getUDSuffix());
2740 Lexer::AdvanceToTokenCharacter(TokLocs
[Literal
.getUDSuffixToken()],
2741 Literal
.getUDSuffixOffset(),
2742 PP
.getSourceManager(), getLangOpts());
2743 } else if (Tok
.is(tok::identifier
)) {
2744 II
= Tok
.getIdentifierInfo();
2745 SuffixLoc
= ConsumeToken();
2746 TokLocs
.push_back(SuffixLoc
);
2748 Diag(Tok
.getLocation(), diag::err_expected
) << tok::identifier
;
2752 // The string literal must be empty.
2753 if (!Literal
.GetString().empty() || Literal
.Pascal
) {
2754 // C++11 [over.literal]p1:
2755 // The string-literal or user-defined-string-literal in a
2756 // literal-operator-id shall [...] contain no characters
2757 // other than the implicit terminating '\0'.
2758 DiagLoc
= TokLocs
.front();
2759 DiagId
= diag::err_literal_operator_string_not_empty
;
2763 // This isn't a valid literal-operator-id, but we think we know
2764 // what the user meant. Tell them what they should have written.
2765 SmallString
<32> Str
;
2767 Str
+= II
->getName();
2768 Diag(DiagLoc
, DiagId
) << FixItHint::CreateReplacement(
2769 SourceRange(TokLocs
.front(), TokLocs
.back()), Str
);
2772 Result
.setLiteralOperatorId(II
, KeywordLoc
, SuffixLoc
);
2774 return Actions
.checkLiteralOperatorId(SS
, Result
, IsUDSuffix
);
2777 // Parse a conversion-function-id.
2779 // conversion-function-id: [C++ 12.3.2]
2780 // operator conversion-type-id
2782 // conversion-type-id:
2783 // type-specifier-seq conversion-declarator[opt]
2785 // conversion-declarator:
2786 // ptr-operator conversion-declarator[opt]
2788 // Parse the type-specifier-seq.
2789 DeclSpec
DS(AttrFactory
);
2790 if (ParseCXXTypeSpecifierSeq(
2791 DS
, DeclaratorContext::ConversionId
)) // FIXME: ObjectType?
2794 // Parse the conversion-declarator, which is merely a sequence of
2796 Declarator
D(DS
, ParsedAttributesView::none(),
2797 DeclaratorContext::ConversionId
);
2798 ParseDeclaratorInternal(D
, /*DirectDeclParser=*/nullptr);
2800 // Finish up the type.
2801 TypeResult Ty
= Actions
.ActOnTypeName(getCurScope(), D
);
2805 // Note that this is a conversion-function-id.
2806 Result
.setConversionFunctionId(KeywordLoc
, Ty
.get(),
2807 D
.getSourceRange().getEnd());
2811 /// Parse a C++ unqualified-id (or a C identifier), which describes the
2812 /// name of an entity.
2815 /// unqualified-id: [C++ expr.prim.general]
2817 /// operator-function-id
2818 /// conversion-function-id
2819 /// [C++0x] literal-operator-id [TODO]
2825 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2826 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2828 /// \param ObjectType if this unqualified-id occurs within a member access
2829 /// expression, the type of the base object whose member is being accessed.
2831 /// \param ObjectHadErrors if this unqualified-id occurs within a member access
2832 /// expression, indicates whether the original subexpressions had any errors.
2833 /// When true, diagnostics for missing 'template' keyword will be supressed.
2835 /// \param EnteringContext whether we are entering the scope of the
2836 /// nested-name-specifier.
2838 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2840 /// \param AllowConstructorName whether we allow parsing a constructor name.
2842 /// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2844 /// \param Result on a successful parse, contains the parsed unqualified-id.
2846 /// \returns true if parsing fails, false otherwise.
2847 bool Parser::ParseUnqualifiedId(CXXScopeSpec
&SS
, ParsedType ObjectType
,
2848 bool ObjectHadErrors
, bool EnteringContext
,
2849 bool AllowDestructorName
,
2850 bool AllowConstructorName
,
2851 bool AllowDeductionGuide
,
2852 SourceLocation
*TemplateKWLoc
,
2853 UnqualifiedId
&Result
) {
2855 *TemplateKWLoc
= SourceLocation();
2857 // Handle 'A::template B'. This is for template-ids which have not
2858 // already been annotated by ParseOptionalCXXScopeSpecifier().
2859 bool TemplateSpecified
= false;
2860 if (Tok
.is(tok::kw_template
)) {
2861 if (TemplateKWLoc
&& (ObjectType
|| SS
.isSet())) {
2862 TemplateSpecified
= true;
2863 *TemplateKWLoc
= ConsumeToken();
2865 SourceLocation TemplateLoc
= ConsumeToken();
2866 Diag(TemplateLoc
, diag::err_unexpected_template_in_unqualified_id
)
2867 << FixItHint::CreateRemoval(TemplateLoc
);
2873 // template-id (when it hasn't already been annotated)
2874 if (Tok
.is(tok::identifier
)) {
2876 // Consume the identifier.
2877 IdentifierInfo
*Id
= Tok
.getIdentifierInfo();
2878 SourceLocation IdLoc
= ConsumeToken();
2880 if (!getLangOpts().CPlusPlus
) {
2881 // If we're not in C++, only identifiers matter. Record the
2882 // identifier and return.
2883 Result
.setIdentifier(Id
, IdLoc
);
2887 ParsedTemplateTy TemplateName
;
2888 if (AllowConstructorName
&&
2889 Actions
.isCurrentClassName(*Id
, getCurScope(), &SS
)) {
2890 // We have parsed a constructor name.
2891 ParsedType Ty
= Actions
.getConstructorName(*Id
, IdLoc
, getCurScope(), SS
,
2895 Result
.setConstructorName(Ty
, IdLoc
, IdLoc
);
2896 } else if (getLangOpts().CPlusPlus17
&&
2897 AllowDeductionGuide
&& SS
.isEmpty() &&
2898 Actions
.isDeductionGuideName(getCurScope(), *Id
, IdLoc
,
2900 // We have parsed a template-name naming a deduction guide.
2901 Result
.setDeductionGuideName(TemplateName
, IdLoc
);
2903 // We have parsed an identifier.
2904 Result
.setIdentifier(Id
, IdLoc
);
2907 // If the next token is a '<', we may have a template.
2908 TemplateTy Template
;
2909 if (Tok
.is(tok::less
))
2910 return ParseUnqualifiedIdTemplateId(
2911 SS
, ObjectType
, ObjectHadErrors
,
2912 TemplateKWLoc
? *TemplateKWLoc
: SourceLocation(), Id
, IdLoc
,
2913 EnteringContext
, Result
, TemplateSpecified
);
2914 else if (TemplateSpecified
&&
2915 Actions
.ActOnTemplateName(
2916 getCurScope(), SS
, *TemplateKWLoc
, Result
, ObjectType
,
2917 EnteringContext
, Template
,
2918 /*AllowInjectedClassName*/ true) == TNK_Non_template
)
2925 // template-id (already parsed and annotated)
2926 if (Tok
.is(tok::annot_template_id
)) {
2927 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
2929 // FIXME: Consider passing invalid template-ids on to callers; they may
2930 // be able to recover better than we can.
2931 if (TemplateId
->isInvalid()) {
2932 ConsumeAnnotationToken();
2936 // If the template-name names the current class, then this is a constructor
2937 if (AllowConstructorName
&& TemplateId
->Name
&&
2938 Actions
.isCurrentClassName(*TemplateId
->Name
, getCurScope(), &SS
)) {
2940 // C++ [class.qual]p2 specifies that a qualified template-name
2941 // is taken as the constructor name where a constructor can be
2942 // declared. Thus, the template arguments are extraneous, so
2943 // complain about them and remove them entirely.
2944 Diag(TemplateId
->TemplateNameLoc
,
2945 diag::err_out_of_line_constructor_template_id
)
2947 << FixItHint::CreateRemoval(
2948 SourceRange(TemplateId
->LAngleLoc
, TemplateId
->RAngleLoc
));
2949 ParsedType Ty
= Actions
.getConstructorName(
2950 *TemplateId
->Name
, TemplateId
->TemplateNameLoc
, getCurScope(), SS
,
2954 Result
.setConstructorName(Ty
, TemplateId
->TemplateNameLoc
,
2955 TemplateId
->RAngleLoc
);
2956 ConsumeAnnotationToken();
2960 Result
.setConstructorTemplateId(TemplateId
);
2961 ConsumeAnnotationToken();
2965 // We have already parsed a template-id; consume the annotation token as
2966 // our unqualified-id.
2967 Result
.setTemplateId(TemplateId
);
2968 SourceLocation TemplateLoc
= TemplateId
->TemplateKWLoc
;
2969 if (TemplateLoc
.isValid()) {
2970 if (TemplateKWLoc
&& (ObjectType
|| SS
.isSet()))
2971 *TemplateKWLoc
= TemplateLoc
;
2973 Diag(TemplateLoc
, diag::err_unexpected_template_in_unqualified_id
)
2974 << FixItHint::CreateRemoval(TemplateLoc
);
2976 ConsumeAnnotationToken();
2981 // operator-function-id
2982 // conversion-function-id
2983 if (Tok
.is(tok::kw_operator
)) {
2984 if (ParseUnqualifiedIdOperator(SS
, EnteringContext
, ObjectType
, Result
))
2987 // If we have an operator-function-id or a literal-operator-id and the next
2988 // token is a '<', we may have a
2991 // operator-function-id < template-argument-list[opt] >
2992 TemplateTy Template
;
2993 if ((Result
.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId
||
2994 Result
.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId
) &&
2996 return ParseUnqualifiedIdTemplateId(
2997 SS
, ObjectType
, ObjectHadErrors
,
2998 TemplateKWLoc
? *TemplateKWLoc
: SourceLocation(), nullptr,
2999 SourceLocation(), EnteringContext
, Result
, TemplateSpecified
);
3000 else if (TemplateSpecified
&&
3001 Actions
.ActOnTemplateName(
3002 getCurScope(), SS
, *TemplateKWLoc
, Result
, ObjectType
,
3003 EnteringContext
, Template
,
3004 /*AllowInjectedClassName*/ true) == TNK_Non_template
)
3010 if (getLangOpts().CPlusPlus
&&
3011 (AllowDestructorName
|| SS
.isSet()) && Tok
.is(tok::tilde
)) {
3012 // C++ [expr.unary.op]p10:
3013 // There is an ambiguity in the unary-expression ~X(), where X is a
3014 // class-name. The ambiguity is resolved in favor of treating ~ as a
3015 // unary complement rather than treating ~X as referring to a destructor.
3018 SourceLocation TildeLoc
= ConsumeToken();
3020 if (TemplateSpecified
) {
3021 // C++ [temp.names]p3:
3022 // A name prefixed by the keyword template shall be a template-id [...]
3024 // A template-id cannot begin with a '~' token. This would never work
3025 // anyway: x.~A<int>() would specify that the destructor is a template,
3026 // not that 'A' is a template.
3028 // FIXME: Suggest replacing the attempted destructor name with a correct
3029 // destructor name and recover. (This is not trivial if this would become
3030 // a pseudo-destructor name).
3031 Diag(*TemplateKWLoc
, diag::err_unexpected_template_in_destructor_name
)
3032 << Tok
.getLocation();
3036 if (SS
.isEmpty() && Tok
.is(tok::kw_decltype
)) {
3037 DeclSpec
DS(AttrFactory
);
3038 SourceLocation EndLoc
= ParseDecltypeSpecifier(DS
);
3039 if (ParsedType Type
=
3040 Actions
.getDestructorTypeForDecltype(DS
, ObjectType
)) {
3041 Result
.setDestructorName(TildeLoc
, Type
, EndLoc
);
3047 // Parse the class-name.
3048 if (Tok
.isNot(tok::identifier
)) {
3049 Diag(Tok
, diag::err_destructor_tilde_identifier
);
3053 // If the user wrote ~T::T, correct it to T::~T.
3054 DeclaratorScopeObj
DeclScopeObj(*this, SS
);
3055 if (NextToken().is(tok::coloncolon
)) {
3056 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
3057 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
3058 // it will confuse this recovery logic.
3059 ColonProtectionRAIIObject
ColonRAII(*this, false);
3062 AnnotateScopeToken(SS
, /*NewAnnotation*/true);
3065 if (ParseOptionalCXXScopeSpecifier(SS
, ObjectType
, ObjectHadErrors
,
3068 if (SS
.isNotEmpty())
3069 ObjectType
= nullptr;
3070 if (Tok
.isNot(tok::identifier
) || NextToken().is(tok::coloncolon
) ||
3072 Diag(TildeLoc
, diag::err_destructor_tilde_scope
);
3076 // Recover as if the tilde had been written before the identifier.
3077 Diag(TildeLoc
, diag::err_destructor_tilde_scope
)
3078 << FixItHint::CreateRemoval(TildeLoc
)
3079 << FixItHint::CreateInsertion(Tok
.getLocation(), "~");
3081 // Temporarily enter the scope for the rest of this function.
3082 if (Actions
.ShouldEnterDeclaratorScope(getCurScope(), SS
))
3083 DeclScopeObj
.EnterDeclaratorScope();
3086 // Parse the class-name (or template-name in a simple-template-id).
3087 IdentifierInfo
*ClassName
= Tok
.getIdentifierInfo();
3088 SourceLocation ClassNameLoc
= ConsumeToken();
3090 if (Tok
.is(tok::less
)) {
3091 Result
.setDestructorName(TildeLoc
, nullptr, ClassNameLoc
);
3092 return ParseUnqualifiedIdTemplateId(
3093 SS
, ObjectType
, ObjectHadErrors
,
3094 TemplateKWLoc
? *TemplateKWLoc
: SourceLocation(), ClassName
,
3095 ClassNameLoc
, EnteringContext
, Result
, TemplateSpecified
);
3098 // Note that this is a destructor name.
3099 ParsedType Ty
= Actions
.getDestructorName(TildeLoc
, *ClassName
,
3100 ClassNameLoc
, getCurScope(),
3106 Result
.setDestructorName(TildeLoc
, Ty
, ClassNameLoc
);
3110 switch (Tok
.getKind()) {
3111 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
3112 #include "clang/Basic/TransformTypeTraits.def"
3113 if (!NextToken().is(tok::l_paren
)) {
3114 Tok
.setKind(tok::identifier
);
3115 Diag(Tok
, diag::ext_keyword_as_ident
)
3116 << Tok
.getIdentifierInfo()->getName() << 0;
3117 goto ParseIdentifier
;
3121 Diag(Tok
, diag::err_expected_unqualified_id
) << getLangOpts().CPlusPlus
;
3126 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
3127 /// memory in a typesafe manner and call constructors.
3129 /// This method is called to parse the new expression after the optional :: has
3130 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
3131 /// is its location. Otherwise, "Start" is the location of the 'new' token.
3134 /// '::'[opt] 'new' new-placement[opt] new-type-id
3135 /// new-initializer[opt]
3136 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3137 /// new-initializer[opt]
3140 /// '(' expression-list ')'
3143 /// type-specifier-seq new-declarator[opt]
3144 /// [GNU] attributes type-specifier-seq new-declarator[opt]
3147 /// ptr-operator new-declarator[opt]
3148 /// direct-new-declarator
3150 /// new-initializer:
3151 /// '(' expression-list[opt] ')'
3152 /// [C++0x] braced-init-list
3155 Parser::ParseCXXNewExpression(bool UseGlobal
, SourceLocation Start
) {
3156 assert(Tok
.is(tok::kw_new
) && "expected 'new' token");
3157 ConsumeToken(); // Consume 'new'
3159 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
3160 // second form of new-expression. It can't be a new-type-id.
3162 ExprVector PlacementArgs
;
3163 SourceLocation PlacementLParen
, PlacementRParen
;
3165 SourceRange TypeIdParens
;
3166 DeclSpec
DS(AttrFactory
);
3167 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
3168 DeclaratorContext::CXXNew
);
3169 if (Tok
.is(tok::l_paren
)) {
3170 // If it turns out to be a placement, we change the type location.
3171 BalancedDelimiterTracker
T(*this, tok::l_paren
);
3173 PlacementLParen
= T
.getOpenLocation();
3174 if (ParseExpressionListOrTypeId(PlacementArgs
, DeclaratorInfo
)) {
3175 SkipUntil(tok::semi
, StopAtSemi
| StopBeforeMatch
);
3180 PlacementRParen
= T
.getCloseLocation();
3181 if (PlacementRParen
.isInvalid()) {
3182 SkipUntil(tok::semi
, StopAtSemi
| StopBeforeMatch
);
3186 if (PlacementArgs
.empty()) {
3187 // Reset the placement locations. There was no placement.
3188 TypeIdParens
= T
.getRange();
3189 PlacementLParen
= PlacementRParen
= SourceLocation();
3191 // We still need the type.
3192 if (Tok
.is(tok::l_paren
)) {
3193 BalancedDelimiterTracker
T(*this, tok::l_paren
);
3195 MaybeParseGNUAttributes(DeclaratorInfo
);
3196 ParseSpecifierQualifierList(DS
);
3197 DeclaratorInfo
.SetSourceRange(DS
.getSourceRange());
3198 ParseDeclarator(DeclaratorInfo
);
3200 TypeIdParens
= T
.getRange();
3202 MaybeParseGNUAttributes(DeclaratorInfo
);
3203 if (ParseCXXTypeSpecifierSeq(DS
))
3204 DeclaratorInfo
.setInvalidType(true);
3206 DeclaratorInfo
.SetSourceRange(DS
.getSourceRange());
3207 ParseDeclaratorInternal(DeclaratorInfo
,
3208 &Parser::ParseDirectNewDeclarator
);
3213 // A new-type-id is a simplified type-id, where essentially the
3214 // direct-declarator is replaced by a direct-new-declarator.
3215 MaybeParseGNUAttributes(DeclaratorInfo
);
3216 if (ParseCXXTypeSpecifierSeq(DS
))
3217 DeclaratorInfo
.setInvalidType(true);
3219 DeclaratorInfo
.SetSourceRange(DS
.getSourceRange());
3220 ParseDeclaratorInternal(DeclaratorInfo
,
3221 &Parser::ParseDirectNewDeclarator
);
3224 if (DeclaratorInfo
.isInvalidType()) {
3225 SkipUntil(tok::semi
, StopAtSemi
| StopBeforeMatch
);
3229 ExprResult Initializer
;
3231 if (Tok
.is(tok::l_paren
)) {
3232 SourceLocation ConstructorLParen
, ConstructorRParen
;
3233 ExprVector ConstructorArgs
;
3234 BalancedDelimiterTracker
T(*this, tok::l_paren
);
3236 ConstructorLParen
= T
.getOpenLocation();
3237 if (Tok
.isNot(tok::r_paren
)) {
3238 auto RunSignatureHelp
= [&]() {
3239 ParsedType TypeRep
=
3240 Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
).get();
3241 QualType PreferredType
;
3242 // ActOnTypeName might adjust DeclaratorInfo and return a null type even
3243 // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
3244 // `new decltype(invalid) (^)`.
3246 PreferredType
= Actions
.ProduceConstructorSignatureHelp(
3247 TypeRep
.get()->getCanonicalTypeInternal(),
3248 DeclaratorInfo
.getEndLoc(), ConstructorArgs
, ConstructorLParen
,
3250 CalledSignatureHelp
= true;
3251 return PreferredType
;
3253 if (ParseExpressionList(ConstructorArgs
, [&] {
3254 PreferredType
.enterFunctionArgument(Tok
.getLocation(),
3257 if (PP
.isCodeCompletionReached() && !CalledSignatureHelp
)
3259 SkipUntil(tok::semi
, StopAtSemi
| StopBeforeMatch
);
3264 ConstructorRParen
= T
.getCloseLocation();
3265 if (ConstructorRParen
.isInvalid()) {
3266 SkipUntil(tok::semi
, StopAtSemi
| StopBeforeMatch
);
3269 Initializer
= Actions
.ActOnParenListExpr(ConstructorLParen
,
3272 } else if (Tok
.is(tok::l_brace
) && getLangOpts().CPlusPlus11
) {
3273 Diag(Tok
.getLocation(),
3274 diag::warn_cxx98_compat_generalized_initializer_lists
);
3275 Initializer
= ParseBraceInitializer();
3277 if (Initializer
.isInvalid())
3280 return Actions
.ActOnCXXNew(Start
, UseGlobal
, PlacementLParen
,
3281 PlacementArgs
, PlacementRParen
,
3282 TypeIdParens
, DeclaratorInfo
, Initializer
.get());
3285 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
3286 /// passed to ParseDeclaratorInternal.
3288 /// direct-new-declarator:
3289 /// '[' expression[opt] ']'
3290 /// direct-new-declarator '[' constant-expression ']'
3292 void Parser::ParseDirectNewDeclarator(Declarator
&D
) {
3293 // Parse the array dimensions.
3295 while (Tok
.is(tok::l_square
)) {
3296 // An array-size expression can't start with a lambda.
3297 if (CheckProhibitedCXX11Attribute())
3300 BalancedDelimiterTracker
T(*this, tok::l_square
);
3304 First
? (Tok
.is(tok::r_square
) ? ExprResult() : ParseExpression())
3305 : ParseConstantExpression();
3306 if (Size
.isInvalid()) {
3308 SkipUntil(tok::r_square
, StopAtSemi
);
3315 // Attributes here appertain to the array type. C++11 [expr.new]p5.
3316 ParsedAttributes
Attrs(AttrFactory
);
3317 MaybeParseCXX11Attributes(Attrs
);
3319 D
.AddTypeInfo(DeclaratorChunk::getArray(0,
3320 /*isStatic=*/false, /*isStar=*/false,
3321 Size
.get(), T
.getOpenLocation(),
3322 T
.getCloseLocation()),
3323 std::move(Attrs
), T
.getCloseLocation());
3325 if (T
.getCloseLocation().isInvalid())
3330 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3331 /// This ambiguity appears in the syntax of the C++ new operator.
3334 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3335 /// new-initializer[opt]
3338 /// '(' expression-list ')'
3340 bool Parser::ParseExpressionListOrTypeId(
3341 SmallVectorImpl
<Expr
*> &PlacementArgs
,
3343 // The '(' was already consumed.
3344 if (isTypeIdInParens()) {
3345 ParseSpecifierQualifierList(D
.getMutableDeclSpec());
3346 D
.SetSourceRange(D
.getDeclSpec().getSourceRange());
3348 return D
.isInvalidType();
3351 // It's not a type, it has to be an expression list.
3352 return ParseExpressionList(PlacementArgs
);
3355 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3356 /// to free memory allocated by new.
3358 /// This method is called to parse the 'delete' expression after the optional
3359 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3360 /// and "Start" is its location. Otherwise, "Start" is the location of the
3363 /// delete-expression:
3364 /// '::'[opt] 'delete' cast-expression
3365 /// '::'[opt] 'delete' '[' ']' cast-expression
3367 Parser::ParseCXXDeleteExpression(bool UseGlobal
, SourceLocation Start
) {
3368 assert(Tok
.is(tok::kw_delete
) && "Expected 'delete' keyword");
3369 ConsumeToken(); // Consume 'delete'
3372 bool ArrayDelete
= false;
3373 if (Tok
.is(tok::l_square
) && NextToken().is(tok::r_square
)) {
3374 // C++11 [expr.delete]p1:
3375 // Whenever the delete keyword is followed by empty square brackets, it
3376 // shall be interpreted as [array delete].
3377 // [Footnote: A lambda expression with a lambda-introducer that consists
3378 // of empty square brackets can follow the delete keyword if
3379 // the lambda expression is enclosed in parentheses.]
3381 const Token Next
= GetLookAheadToken(2);
3383 // Basic lookahead to check if we have a lambda expression.
3384 if (Next
.isOneOf(tok::l_brace
, tok::less
) ||
3385 (Next
.is(tok::l_paren
) &&
3386 (GetLookAheadToken(3).is(tok::r_paren
) ||
3387 (GetLookAheadToken(3).is(tok::identifier
) &&
3388 GetLookAheadToken(4).is(tok::identifier
))))) {
3389 TentativeParsingAction
TPA(*this);
3390 SourceLocation LSquareLoc
= Tok
.getLocation();
3391 SourceLocation RSquareLoc
= NextToken().getLocation();
3393 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3395 SkipUntil({tok::l_brace
, tok::less
}, StopBeforeMatch
);
3396 SourceLocation RBraceLoc
;
3397 bool EmitFixIt
= false;
3398 if (Tok
.is(tok::l_brace
)) {
3400 SkipUntil(tok::r_brace
, StopBeforeMatch
);
3401 RBraceLoc
= Tok
.getLocation();
3408 Diag(Start
, diag::err_lambda_after_delete
)
3409 << SourceRange(Start
, RSquareLoc
)
3410 << FixItHint::CreateInsertion(LSquareLoc
, "(")
3411 << FixItHint::CreateInsertion(
3412 Lexer::getLocForEndOfToken(
3413 RBraceLoc
, 0, Actions
.getSourceManager(), getLangOpts()),
3416 Diag(Start
, diag::err_lambda_after_delete
)
3417 << SourceRange(Start
, RSquareLoc
);
3419 // Warn that the non-capturing lambda isn't surrounded by parentheses
3420 // to disambiguate it from 'delete[]'.
3421 ExprResult Lambda
= ParseLambdaExpression();
3422 if (Lambda
.isInvalid())
3425 // Evaluate any postfix expressions used on the lambda.
3426 Lambda
= ParsePostfixExpressionSuffix(Lambda
);
3427 if (Lambda
.isInvalid())
3429 return Actions
.ActOnCXXDelete(Start
, UseGlobal
, /*ArrayForm=*/false,
3434 BalancedDelimiterTracker
T(*this, tok::l_square
);
3438 if (T
.getCloseLocation().isInvalid())
3442 ExprResult
Operand(ParseCastExpression(AnyCastExpr
));
3443 if (Operand
.isInvalid())
3446 return Actions
.ActOnCXXDelete(Start
, UseGlobal
, ArrayDelete
, Operand
.get());
3449 /// ParseRequiresExpression - Parse a C++2a requires-expression.
3450 /// C++2a [expr.prim.req]p1
3451 /// A requires-expression provides a concise way to express requirements on
3452 /// template arguments. A requirement is one that can be checked by name
3453 /// lookup (6.4) or by checking properties of types and expressions.
3455 /// requires-expression:
3456 /// 'requires' requirement-parameter-list[opt] requirement-body
3458 /// requirement-parameter-list:
3459 /// '(' parameter-declaration-clause[opt] ')'
3461 /// requirement-body:
3462 /// '{' requirement-seq '}'
3464 /// requirement-seq:
3466 /// requirement-seq requirement
3469 /// simple-requirement
3470 /// type-requirement
3471 /// compound-requirement
3472 /// nested-requirement
3473 ExprResult
Parser::ParseRequiresExpression() {
3474 assert(Tok
.is(tok::kw_requires
) && "Expected 'requires' keyword");
3475 SourceLocation RequiresKWLoc
= ConsumeToken(); // Consume 'requires'
3477 llvm::SmallVector
<ParmVarDecl
*, 2> LocalParameterDecls
;
3478 if (Tok
.is(tok::l_paren
)) {
3479 // requirement parameter list is present.
3480 ParseScope
LocalParametersScope(this, Scope::FunctionPrototypeScope
|
3482 BalancedDelimiterTracker
Parens(*this, tok::l_paren
);
3483 Parens
.consumeOpen();
3484 if (!Tok
.is(tok::r_paren
)) {
3485 ParsedAttributes
FirstArgAttrs(getAttrFactory());
3486 SourceLocation EllipsisLoc
;
3487 llvm::SmallVector
<DeclaratorChunk::ParamInfo
, 2> LocalParameters
;
3488 ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr
,
3489 FirstArgAttrs
, LocalParameters
,
3491 if (EllipsisLoc
.isValid())
3492 Diag(EllipsisLoc
, diag::err_requires_expr_parameter_list_ellipsis
);
3493 for (auto &ParamInfo
: LocalParameters
)
3494 LocalParameterDecls
.push_back(cast
<ParmVarDecl
>(ParamInfo
.Param
));
3496 Parens
.consumeClose();
3499 BalancedDelimiterTracker
Braces(*this, tok::l_brace
);
3500 if (Braces
.expectAndConsume())
3503 // Start of requirement list
3504 llvm::SmallVector
<concepts::Requirement
*, 2> Requirements
;
3506 // C++2a [expr.prim.req]p2
3507 // Expressions appearing within a requirement-body are unevaluated operands.
3508 EnterExpressionEvaluationContext
Ctx(
3509 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
);
3511 ParseScope
BodyScope(this, Scope::DeclScope
);
3512 // Create a separate diagnostic pool for RequiresExprBodyDecl.
3513 // Dependent diagnostics are attached to this Decl and non-depenedent
3514 // diagnostics are surfaced after this parse.
3515 ParsingDeclRAIIObject
ParsingBodyDecl(*this, ParsingDeclRAIIObject::NoParent
);
3516 RequiresExprBodyDecl
*Body
= Actions
.ActOnStartRequiresExpr(
3517 RequiresKWLoc
, LocalParameterDecls
, getCurScope());
3519 if (Tok
.is(tok::r_brace
)) {
3520 // Grammar does not allow an empty body.
3521 // requirement-body:
3522 // { requirement-seq }
3525 // requirement-seq requirement
3526 Diag(Tok
, diag::err_empty_requires_expr
);
3527 // Continue anyway and produce a requires expr with no requirements.
3529 while (!Tok
.is(tok::r_brace
)) {
3530 switch (Tok
.getKind()) {
3531 case tok::l_brace
: {
3532 // Compound requirement
3533 // C++ [expr.prim.req.compound]
3534 // compound-requirement:
3535 // '{' expression '}' 'noexcept'[opt]
3536 // return-type-requirement[opt] ';'
3537 // return-type-requirement:
3538 // trailing-return-type
3539 // '->' cv-qualifier-seq[opt] constrained-parameter
3540 // cv-qualifier-seq[opt] abstract-declarator[opt]
3541 BalancedDelimiterTracker
ExprBraces(*this, tok::l_brace
);
3542 ExprBraces
.consumeOpen();
3543 ExprResult Expression
=
3544 Actions
.CorrectDelayedTyposInExpr(ParseExpression());
3545 if (!Expression
.isUsable()) {
3546 ExprBraces
.skipToEnd();
3547 SkipUntil(tok::semi
, tok::r_brace
, SkipUntilFlags::StopBeforeMatch
);
3550 if (ExprBraces
.consumeClose())
3551 ExprBraces
.skipToEnd();
3553 concepts::Requirement
*Req
= nullptr;
3554 SourceLocation NoexceptLoc
;
3555 TryConsumeToken(tok::kw_noexcept
, NoexceptLoc
);
3556 if (Tok
.is(tok::semi
)) {
3557 Req
= Actions
.ActOnCompoundRequirement(Expression
.get(), NoexceptLoc
);
3559 Requirements
.push_back(Req
);
3562 if (!TryConsumeToken(tok::arrow
))
3563 // User probably forgot the arrow, remind them and try to continue.
3564 Diag(Tok
, diag::err_requires_expr_missing_arrow
)
3565 << FixItHint::CreateInsertion(Tok
.getLocation(), "->");
3566 // Try to parse a 'type-constraint'
3567 if (TryAnnotateTypeConstraint()) {
3568 SkipUntil(tok::semi
, tok::r_brace
, SkipUntilFlags::StopBeforeMatch
);
3571 if (!isTypeConstraintAnnotation()) {
3572 Diag(Tok
, diag::err_requires_expr_expected_type_constraint
);
3573 SkipUntil(tok::semi
, tok::r_brace
, SkipUntilFlags::StopBeforeMatch
);
3577 if (Tok
.is(tok::annot_cxxscope
)) {
3578 Actions
.RestoreNestedNameSpecifierAnnotation(Tok
.getAnnotationValue(),
3579 Tok
.getAnnotationRange(),
3581 ConsumeAnnotationToken();
3584 Req
= Actions
.ActOnCompoundRequirement(
3585 Expression
.get(), NoexceptLoc
, SS
, takeTemplateIdAnnotation(Tok
),
3586 TemplateParameterDepth
);
3587 ConsumeAnnotationToken();
3589 Requirements
.push_back(Req
);
3593 bool PossibleRequiresExprInSimpleRequirement
= false;
3594 if (Tok
.is(tok::kw_requires
)) {
3595 auto IsNestedRequirement
= [&] {
3596 RevertingTentativeParsingAction
TPA(*this);
3597 ConsumeToken(); // 'requires'
3598 if (Tok
.is(tok::l_brace
))
3599 // This is a requires expression
3601 // requires { t++; };
3605 if (Tok
.is(tok::l_paren
)) {
3606 // This might be the parameter list of a requires expression
3608 auto Res
= TryParseParameterDeclarationClause();
3609 if (Res
!= TPResult::False
) {
3610 // Skip to the closing parenthesis
3611 // FIXME: Don't traverse these tokens twice (here and in
3612 // TryParseParameterDeclarationClause).
3614 while (Depth
!= 0) {
3615 if (Tok
.is(tok::l_paren
))
3617 else if (Tok
.is(tok::r_paren
))
3625 // requires (int x) ?
3628 if (Tok
.is(tok::l_brace
))
3630 // ^ - a requires expression as a
3631 // simple-requirement.
3637 if (IsNestedRequirement()) {
3639 // Nested requirement
3640 // C++ [expr.prim.req.nested]
3641 // nested-requirement:
3642 // 'requires' constraint-expression ';'
3643 ExprResult ConstraintExpr
=
3644 Actions
.CorrectDelayedTyposInExpr(ParseConstraintExpression());
3645 if (ConstraintExpr
.isInvalid() || !ConstraintExpr
.isUsable()) {
3646 SkipUntil(tok::semi
, tok::r_brace
,
3647 SkipUntilFlags::StopBeforeMatch
);
3651 Actions
.ActOnNestedRequirement(ConstraintExpr
.get()))
3652 Requirements
.push_back(Req
);
3654 SkipUntil(tok::semi
, tok::r_brace
,
3655 SkipUntilFlags::StopBeforeMatch
);
3660 PossibleRequiresExprInSimpleRequirement
= true;
3661 } else if (Tok
.is(tok::kw_typename
)) {
3662 // This might be 'typename T::value_type;' (a type requirement) or
3663 // 'typename T::value_type{};' (a simple requirement).
3664 TentativeParsingAction
TPA(*this);
3666 // We need to consume the typename to allow 'requires { typename a; }'
3667 SourceLocation TypenameKWLoc
= ConsumeToken();
3668 if (TryAnnotateOptionalCXXScopeToken()) {
3670 SkipUntil(tok::semi
, tok::r_brace
, SkipUntilFlags::StopBeforeMatch
);
3674 if (Tok
.is(tok::annot_cxxscope
)) {
3675 Actions
.RestoreNestedNameSpecifierAnnotation(
3676 Tok
.getAnnotationValue(), Tok
.getAnnotationRange(), SS
);
3677 ConsumeAnnotationToken();
3680 if (Tok
.isOneOf(tok::identifier
, tok::annot_template_id
) &&
3681 !NextToken().isOneOf(tok::l_brace
, tok::l_paren
)) {
3683 SourceLocation NameLoc
= Tok
.getLocation();
3684 IdentifierInfo
*II
= nullptr;
3685 TemplateIdAnnotation
*TemplateId
= nullptr;
3686 if (Tok
.is(tok::identifier
)) {
3687 II
= Tok
.getIdentifierInfo();
3690 TemplateId
= takeTemplateIdAnnotation(Tok
);
3691 ConsumeAnnotationToken();
3692 if (TemplateId
->isInvalid())
3696 if (auto *Req
= Actions
.ActOnTypeRequirement(TypenameKWLoc
, SS
,
3699 Requirements
.push_back(Req
);
3705 // Simple requirement
3706 // C++ [expr.prim.req.simple]
3707 // simple-requirement:
3709 SourceLocation StartLoc
= Tok
.getLocation();
3710 ExprResult Expression
=
3711 Actions
.CorrectDelayedTyposInExpr(ParseExpression());
3712 if (!Expression
.isUsable()) {
3713 SkipUntil(tok::semi
, tok::r_brace
, SkipUntilFlags::StopBeforeMatch
);
3716 if (!Expression
.isInvalid() && PossibleRequiresExprInSimpleRequirement
)
3717 Diag(StartLoc
, diag::err_requires_expr_in_simple_requirement
)
3718 << FixItHint::CreateInsertion(StartLoc
, "requires");
3719 if (auto *Req
= Actions
.ActOnSimpleRequirement(Expression
.get()))
3720 Requirements
.push_back(Req
);
3722 SkipUntil(tok::semi
, tok::r_brace
, SkipUntilFlags::StopBeforeMatch
);
3725 // User may have tried to put some compound requirement stuff here
3726 if (Tok
.is(tok::kw_noexcept
)) {
3727 Diag(Tok
, diag::err_requires_expr_simple_requirement_noexcept
)
3728 << FixItHint::CreateInsertion(StartLoc
, "{")
3729 << FixItHint::CreateInsertion(Tok
.getLocation(), "}");
3730 SkipUntil(tok::semi
, tok::r_brace
, SkipUntilFlags::StopBeforeMatch
);
3736 if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement
)) {
3737 SkipUntil(tok::semi
, tok::r_brace
, SkipUntilFlags::StopBeforeMatch
);
3738 TryConsumeToken(tok::semi
);
3742 if (Requirements
.empty()) {
3743 // Don't emit an empty requires expr here to avoid confusing the user with
3744 // other diagnostics quoting an empty requires expression they never
3746 Braces
.consumeClose();
3747 Actions
.ActOnFinishRequiresExpr();
3751 Braces
.consumeClose();
3752 Actions
.ActOnFinishRequiresExpr();
3753 ParsingBodyDecl
.complete(Body
);
3754 return Actions
.ActOnRequiresExpr(RequiresKWLoc
, Body
, LocalParameterDecls
,
3755 Requirements
, Braces
.getCloseLocation());
3758 static TypeTrait
TypeTraitFromTokKind(tok::TokenKind kind
) {
3760 default: llvm_unreachable("Not a known type trait");
3761 #define TYPE_TRAIT_1(Spelling, Name, Key) \
3762 case tok::kw_ ## Spelling: return UTT_ ## Name;
3763 #define TYPE_TRAIT_2(Spelling, Name, Key) \
3764 case tok::kw_ ## Spelling: return BTT_ ## Name;
3765 #include "clang/Basic/TokenKinds.def"
3766 #define TYPE_TRAIT_N(Spelling, Name, Key) \
3767 case tok::kw_ ## Spelling: return TT_ ## Name;
3768 #include "clang/Basic/TokenKinds.def"
3772 static ArrayTypeTrait
ArrayTypeTraitFromTokKind(tok::TokenKind kind
) {
3775 llvm_unreachable("Not a known array type trait");
3776 #define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \
3777 case tok::kw_##Spelling: \
3779 #include "clang/Basic/TokenKinds.def"
3783 static ExpressionTrait
ExpressionTraitFromTokKind(tok::TokenKind kind
) {
3786 llvm_unreachable("Not a known unary expression trait.");
3787 #define EXPRESSION_TRAIT(Spelling, Name, Key) \
3788 case tok::kw_##Spelling: \
3790 #include "clang/Basic/TokenKinds.def"
3794 /// Parse the built-in type-trait pseudo-functions that allow
3795 /// implementation of the TR1/C++11 type traits templates.
3797 /// primary-expression:
3798 /// unary-type-trait '(' type-id ')'
3799 /// binary-type-trait '(' type-id ',' type-id ')'
3800 /// type-trait '(' type-id-seq ')'
3803 /// type-id ...[opt] type-id-seq[opt]
3805 ExprResult
Parser::ParseTypeTrait() {
3806 tok::TokenKind Kind
= Tok
.getKind();
3808 SourceLocation Loc
= ConsumeToken();
3810 BalancedDelimiterTracker
Parens(*this, tok::l_paren
);
3811 if (Parens
.expectAndConsume())
3814 SmallVector
<ParsedType
, 2> Args
;
3816 // Parse the next type.
3817 TypeResult Ty
= ParseTypeName();
3818 if (Ty
.isInvalid()) {
3823 // Parse the ellipsis, if present.
3824 if (Tok
.is(tok::ellipsis
)) {
3825 Ty
= Actions
.ActOnPackExpansion(Ty
.get(), ConsumeToken());
3826 if (Ty
.isInvalid()) {
3832 // Add this type to the list of arguments.
3833 Args
.push_back(Ty
.get());
3834 } while (TryConsumeToken(tok::comma
));
3836 if (Parens
.consumeClose())
3839 SourceLocation EndLoc
= Parens
.getCloseLocation();
3841 return Actions
.ActOnTypeTrait(TypeTraitFromTokKind(Kind
), Loc
, Args
, EndLoc
);
3844 /// ParseArrayTypeTrait - Parse the built-in array type-trait
3845 /// pseudo-functions.
3847 /// primary-expression:
3848 /// [Embarcadero] '__array_rank' '(' type-id ')'
3849 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3851 ExprResult
Parser::ParseArrayTypeTrait() {
3852 ArrayTypeTrait ATT
= ArrayTypeTraitFromTokKind(Tok
.getKind());
3853 SourceLocation Loc
= ConsumeToken();
3855 BalancedDelimiterTracker
T(*this, tok::l_paren
);
3856 if (T
.expectAndConsume())
3859 TypeResult Ty
= ParseTypeName();
3860 if (Ty
.isInvalid()) {
3861 SkipUntil(tok::comma
, StopAtSemi
);
3862 SkipUntil(tok::r_paren
, StopAtSemi
);
3867 case ATT_ArrayRank
: {
3869 return Actions
.ActOnArrayTypeTrait(ATT
, Loc
, Ty
.get(), nullptr,
3870 T
.getCloseLocation());
3872 case ATT_ArrayExtent
: {
3873 if (ExpectAndConsume(tok::comma
)) {
3874 SkipUntil(tok::r_paren
, StopAtSemi
);
3878 ExprResult DimExpr
= ParseExpression();
3881 return Actions
.ActOnArrayTypeTrait(ATT
, Loc
, Ty
.get(), DimExpr
.get(),
3882 T
.getCloseLocation());
3885 llvm_unreachable("Invalid ArrayTypeTrait!");
3888 /// ParseExpressionTrait - Parse built-in expression-trait
3889 /// pseudo-functions like __is_lvalue_expr( xxx ).
3891 /// primary-expression:
3892 /// [Embarcadero] expression-trait '(' expression ')'
3894 ExprResult
Parser::ParseExpressionTrait() {
3895 ExpressionTrait ET
= ExpressionTraitFromTokKind(Tok
.getKind());
3896 SourceLocation Loc
= ConsumeToken();
3898 BalancedDelimiterTracker
T(*this, tok::l_paren
);
3899 if (T
.expectAndConsume())
3902 ExprResult Expr
= ParseExpression();
3906 return Actions
.ActOnExpressionTrait(ET
, Loc
, Expr
.get(),
3907 T
.getCloseLocation());
3911 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3912 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3913 /// based on the context past the parens.
3915 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption
&ExprType
,
3917 BalancedDelimiterTracker
&Tracker
,
3918 ColonProtectionRAIIObject
&ColonProt
) {
3919 assert(getLangOpts().CPlusPlus
&& "Should only be called for C++!");
3920 assert(ExprType
== CastExpr
&& "Compound literals are not ambiguous!");
3921 assert(isTypeIdInParens() && "Not a type-id!");
3923 ExprResult
Result(true);
3926 // We need to disambiguate a very ugly part of the C++ syntax:
3928 // (T())x; - type-id
3929 // (T())*x; - type-id
3930 // (T())/x; - expression
3931 // (T()); - expression
3933 // The bad news is that we cannot use the specialized tentative parser, since
3934 // it can only verify that the thing inside the parens can be parsed as
3935 // type-id, it is not useful for determining the context past the parens.
3937 // The good news is that the parser can disambiguate this part without
3938 // making any unnecessary Action calls.
3940 // It uses a scheme similar to parsing inline methods. The parenthesized
3941 // tokens are cached, the context that follows is determined (possibly by
3942 // parsing a cast-expression), and then we re-introduce the cached tokens
3943 // into the token stream and parse them appropriately.
3945 ParenParseOption ParseAs
;
3948 // Store the tokens of the parentheses. We will parse them after we determine
3949 // the context that follows them.
3950 if (!ConsumeAndStoreUntil(tok::r_paren
, Toks
)) {
3951 // We didn't find the ')' we expected.
3952 Tracker
.consumeClose();
3956 if (Tok
.is(tok::l_brace
)) {
3957 ParseAs
= CompoundLiteral
;
3960 if (Tok
.is(tok::l_paren
) && NextToken().is(tok::r_paren
)) {
3963 // Try parsing the cast-expression that may follow.
3964 // If it is not a cast-expression, NotCastExpr will be true and no token
3965 // will be consumed.
3966 ColonProt
.restore();
3967 Result
= ParseCastExpression(AnyCastExpr
,
3968 false/*isAddressofOperand*/,
3970 // type-id has priority.
3974 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3976 ParseAs
= NotCastExpr
? SimpleExpr
: CastExpr
;
3979 // Create a fake EOF to mark end of Toks buffer.
3981 AttrEnd
.startToken();
3982 AttrEnd
.setKind(tok::eof
);
3983 AttrEnd
.setLocation(Tok
.getLocation());
3984 AttrEnd
.setEofData(Toks
.data());
3985 Toks
.push_back(AttrEnd
);
3987 // The current token should go after the cached tokens.
3988 Toks
.push_back(Tok
);
3989 // Re-enter the stored parenthesized tokens into the token stream, so we may
3991 PP
.EnterTokenStream(Toks
, /*DisableMacroExpansion*/ true,
3992 /*IsReinject*/ true);
3993 // Drop the current token and bring the first cached one. It's the same token
3994 // as when we entered this function.
3997 if (ParseAs
>= CompoundLiteral
) {
3998 // Parse the type declarator.
3999 DeclSpec
DS(AttrFactory
);
4000 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
4001 DeclaratorContext::TypeName
);
4003 ColonProtectionRAIIObject
InnerColonProtection(*this);
4004 ParseSpecifierQualifierList(DS
);
4005 ParseDeclarator(DeclaratorInfo
);
4009 Tracker
.consumeClose();
4010 ColonProt
.restore();
4012 // Consume EOF marker for Toks buffer.
4013 assert(Tok
.is(tok::eof
) && Tok
.getEofData() == AttrEnd
.getEofData());
4016 if (ParseAs
== CompoundLiteral
) {
4017 ExprType
= CompoundLiteral
;
4018 if (DeclaratorInfo
.isInvalidType())
4021 TypeResult Ty
= Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
4022 return ParseCompoundLiteralExpression(Ty
.get(),
4023 Tracker
.getOpenLocation(),
4024 Tracker
.getCloseLocation());
4027 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
4028 assert(ParseAs
== CastExpr
);
4030 if (DeclaratorInfo
.isInvalidType())
4033 // Result is what ParseCastExpression returned earlier.
4034 if (!Result
.isInvalid())
4035 Result
= Actions
.ActOnCastExpr(getCurScope(), Tracker
.getOpenLocation(),
4036 DeclaratorInfo
, CastTy
,
4037 Tracker
.getCloseLocation(), Result
.get());
4041 // Not a compound literal, and not followed by a cast-expression.
4042 assert(ParseAs
== SimpleExpr
);
4044 ExprType
= SimpleExpr
;
4045 Result
= ParseExpression();
4046 if (!Result
.isInvalid() && Tok
.is(tok::r_paren
))
4047 Result
= Actions
.ActOnParenExpr(Tracker
.getOpenLocation(),
4048 Tok
.getLocation(), Result
.get());
4051 if (Result
.isInvalid()) {
4052 while (Tok
.isNot(tok::eof
))
4054 assert(Tok
.getEofData() == AttrEnd
.getEofData());
4059 Tracker
.consumeClose();
4060 // Consume EOF marker for Toks buffer.
4061 assert(Tok
.is(tok::eof
) && Tok
.getEofData() == AttrEnd
.getEofData());
4066 /// Parse a __builtin_bit_cast(T, E).
4067 ExprResult
Parser::ParseBuiltinBitCast() {
4068 SourceLocation KWLoc
= ConsumeToken();
4070 BalancedDelimiterTracker
T(*this, tok::l_paren
);
4071 if (T
.expectAndConsume(diag::err_expected_lparen_after
, "__builtin_bit_cast"))
4074 // Parse the common declaration-specifiers piece.
4075 DeclSpec
DS(AttrFactory
);
4076 ParseSpecifierQualifierList(DS
);
4078 // Parse the abstract-declarator, if present.
4079 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
4080 DeclaratorContext::TypeName
);
4081 ParseDeclarator(DeclaratorInfo
);
4083 if (ExpectAndConsume(tok::comma
)) {
4084 Diag(Tok
.getLocation(), diag::err_expected
) << tok::comma
;
4085 SkipUntil(tok::r_paren
, StopAtSemi
);
4089 ExprResult Operand
= ParseExpression();
4091 if (T
.consumeClose())
4094 if (Operand
.isInvalid() || DeclaratorInfo
.isInvalidType())
4097 return Actions
.ActOnBuiltinBitCastExpr(KWLoc
, DeclaratorInfo
, Operand
,
4098 T
.getCloseLocation());