1 //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Expression parsing implementation for C++.
12 //===----------------------------------------------------------------------===//
13 #include "clang/Parse/Parser.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/Basic/PrettyStackTrace.h"
17 #include "clang/Lex/LiteralSupport.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Parse/RAIIObjectsForParser.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/ParsedTemplate.h"
22 #include "clang/Sema/Scope.h"
23 #include "llvm/Support/ErrorHandling.h"
26 using namespace clang;
28 static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
31 case tok::unknown: return 0;
33 case tok::kw_const_cast: return 1;
34 case tok::kw_dynamic_cast: return 2;
35 case tok::kw_reinterpret_cast: return 3;
36 case tok::kw_static_cast: return 4;
38 llvm_unreachable("Unknown type for digraph error message.");
42 // Are the two tokens adjacent in the same source file?
43 bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
44 SourceManager &SM = PP.getSourceManager();
45 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
46 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
47 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
50 // Suggest fixit for "<::" after a cast.
51 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
52 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
53 // Pull '<:' and ':' off token stream.
59 Range.setBegin(DigraphToken.getLocation());
60 Range.setEnd(ColonToken.getLocation());
61 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
62 << SelectDigraphErrorMessage(Kind)
63 << FixItHint::CreateReplacement(Range, "< ::");
65 // Update token information to reflect their change in token type.
66 ColonToken.setKind(tok::coloncolon);
67 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
68 ColonToken.setLength(2);
69 DigraphToken.setKind(tok::less);
70 DigraphToken.setLength(1);
72 // Push new tokens back to token stream.
73 PP.EnterToken(ColonToken);
75 PP.EnterToken(DigraphToken);
78 // Check for '<::' which should be '< ::' instead of '[:' when following
80 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
82 IdentifierInfo &II, CXXScopeSpec &SS) {
83 if (!Next.is(tok::l_square) || Next.getLength() != 2)
86 Token SecondToken = GetLookAheadToken(2);
87 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
91 UnqualifiedId TemplateName;
92 TemplateName.setIdentifier(&II, Tok.getLocation());
93 bool MemberOfUnknownSpecialization;
94 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
95 TemplateName, ObjectType, EnteringContext,
96 Template, MemberOfUnknownSpecialization))
99 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
103 /// Parse global scope or nested-name-specifier if present.
105 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
106 /// may be preceded by '::'). Note that this routine will not parse ::new or
107 /// ::delete; it will just leave them in the token stream.
109 /// '::'[opt] nested-name-specifier
112 /// nested-name-specifier:
114 /// namespace-name '::'
115 /// nested-name-specifier identifier '::'
116 /// nested-name-specifier 'template'[opt] simple-template-id '::'
119 /// \param SS the scope specifier that will be set to the parsed
120 /// nested-name-specifier (or empty)
122 /// \param ObjectType if this nested-name-specifier is being parsed following
123 /// the "." or "->" of a member access expression, this parameter provides the
124 /// type of the object whose members are being accessed.
126 /// \param EnteringContext whether we will be entering into the context of
127 /// the nested-name-specifier after parsing it.
129 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
130 /// indicates whether this nested-name-specifier may be part of a
131 /// pseudo-destructor name. In this case, the flag will be set false
132 /// if we don't actually end up parsing a destructor name. Moreorover,
133 /// if we do end up determining that we are parsing a destructor name,
134 /// the last component of the nested-name-specifier is not parsed as
135 /// part of the scope specifier.
137 /// \param IsTypename If \c true, this nested-name-specifier is known to be
138 /// part of a type name. This is used to improve error recovery.
140 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
141 /// filled in with the leading identifier in the last component of the
142 /// nested-name-specifier, if any.
144 /// \param OnlyNamespace If true, only considers namespaces in lookup.
146 /// \returns true if there was an error parsing a scope specifier
147 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
148 ParsedType ObjectType,
149 bool EnteringContext,
150 bool *MayBePseudoDestructor,
152 IdentifierInfo **LastII,
153 bool OnlyNamespace) {
154 assert(getLangOpts().CPlusPlus &&
155 "Call sites of this function should be guarded by checking for C++");
157 if (Tok.is(tok::annot_cxxscope)) {
158 assert(!LastII && "want last identifier but have already annotated scope");
159 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
160 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
161 Tok.getAnnotationRange(),
163 ConsumeAnnotationToken();
167 if (Tok.is(tok::annot_template_id)) {
168 // If the current token is an annotated template id, it may already have
169 // a scope specifier. Restore it.
170 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
174 // Has to happen before any "return false"s in this function.
175 bool CheckForDestructor = false;
176 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
177 CheckForDestructor = true;
178 *MayBePseudoDestructor = false;
184 bool HasScopeSpecifier = false;
186 if (Tok.is(tok::coloncolon)) {
187 // ::new and ::delete aren't nested-name-specifiers.
188 tok::TokenKind NextKind = NextToken().getKind();
189 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
192 if (NextKind == tok::l_brace) {
193 // It is invalid to have :: {, consume the scope qualifier and pretend
194 // like we never saw it.
195 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
197 // '::' - Global scope qualifier.
198 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
201 HasScopeSpecifier = true;
205 if (Tok.is(tok::kw___super)) {
206 SourceLocation SuperLoc = ConsumeToken();
207 if (!Tok.is(tok::coloncolon)) {
208 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
212 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
215 if (!HasScopeSpecifier &&
216 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
217 DeclSpec DS(AttrFactory);
218 SourceLocation DeclLoc = Tok.getLocation();
219 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
221 SourceLocation CCLoc;
222 // Work around a standard defect: 'decltype(auto)::' is not a
223 // nested-name-specifier.
224 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
225 !TryConsumeToken(tok::coloncolon, CCLoc)) {
226 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
230 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
231 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
233 HasScopeSpecifier = true;
237 if (HasScopeSpecifier) {
238 if (Tok.is(tok::code_completion)) {
239 // Code completion for a nested-name-specifier, where the code
240 // completion token follows the '::'.
241 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext,
243 // Include code completion token into the range of the scope otherwise
244 // when we try to annotate the scope tokens the dangling code completion
245 // token will cause assertion in
246 // Preprocessor::AnnotatePreviousCachedTokens.
247 SS.setEndLoc(Tok.getLocation());
252 // C++ [basic.lookup.classref]p5:
253 // If the qualified-id has the form
255 // ::class-name-or-namespace-name::...
257 // the class-name-or-namespace-name is looked up in global scope as a
258 // class-name or namespace-name.
260 // To implement this, we clear out the object type as soon as we've
261 // seen a leading '::' or part of a nested-name-specifier.
262 ObjectType = nullptr;
265 // nested-name-specifier:
266 // nested-name-specifier 'template'[opt] simple-template-id '::'
268 // Parse the optional 'template' keyword, then make sure we have
269 // 'identifier <' after it.
270 if (Tok.is(tok::kw_template)) {
271 // If we don't have a scope specifier or an object type, this isn't a
272 // nested-name-specifier, since they aren't allowed to start with
274 if (!HasScopeSpecifier && !ObjectType)
277 TentativeParsingAction TPA(*this);
278 SourceLocation TemplateKWLoc = ConsumeToken();
280 UnqualifiedId TemplateName;
281 if (Tok.is(tok::identifier)) {
282 // Consume the identifier.
283 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
285 } else if (Tok.is(tok::kw_operator)) {
286 // We don't need to actually parse the unqualified-id in this case,
287 // because a simple-template-id cannot start with 'operator', but
288 // go ahead and parse it anyway for consistency with the case where
289 // we already annotated the template-id.
290 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
296 if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
297 TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
298 Diag(TemplateName.getSourceRange().getBegin(),
299 diag::err_id_after_template_in_nested_name_spec)
300 << TemplateName.getSourceRange();
309 // If the next token is not '<', we have a qualified-id that refers
310 // to a template name, such as T::template apply, but is not a
312 if (Tok.isNot(tok::less)) {
317 // Commit to parsing the template-id.
320 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
321 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
322 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
323 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
324 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 (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
362 TemplateId->TemplateKWLoc,
363 TemplateId->Template,
364 TemplateId->TemplateNameLoc,
365 TemplateId->LAngleLoc,
367 TemplateId->RAngleLoc,
370 SourceLocation StartLoc
371 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
372 : TemplateId->TemplateNameLoc;
373 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
379 // The rest of the nested-name-specifier possibilities start with
381 if (Tok.isNot(tok::identifier))
384 IdentifierInfo &II = *Tok.getIdentifierInfo();
386 // nested-name-specifier:
388 // namespace-name '::'
389 // nested-name-specifier identifier '::'
390 Token Next = NextToken();
391 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
394 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
395 // and emit a fixit hint for it.
396 if (Next.is(tok::colon) && !ColonIsSacred) {
397 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
399 // If the token after the colon isn't an identifier, it's still an
400 // error, but they probably meant something else strange so don't
401 // recover like this.
402 PP.LookAhead(1).is(tok::identifier)) {
403 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
404 << FixItHint::CreateReplacement(Next.getLocation(), "::");
405 // Recover as if the user wrote '::'.
406 Next.setKind(tok::coloncolon);
410 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
411 // It is invalid to have :: {, consume the scope qualifier and pretend
412 // like we never saw it.
413 Token Identifier = Tok; // Stash away the identifier.
414 ConsumeToken(); // Eat the identifier, current token is now '::'.
415 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
417 UnconsumeToken(Identifier); // Stick the identifier back.
418 Next = NextToken(); // Point Next at the '{' token.
421 if (Next.is(tok::coloncolon)) {
422 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
423 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
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);
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, false,
459 CorrectionFlagPtr, OnlyNamespace)) {
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);
465 PP.EnterToken(ColonColon);
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)) {
481 UnqualifiedId TemplateName;
482 TemplateName.setIdentifier(&II, Tok.getLocation());
483 bool MemberOfUnknownSpecialization;
484 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
485 /*hasTemplateKeyword=*/false,
490 MemberOfUnknownSpecialization)) {
491 // We have found a template name, so annotate this token
492 // with a template-id annotation. We do not permit the
493 // template-id to be translated into a type annotation,
494 // because some clients (e.g., the parsing of class template
495 // specializations) still want to see the original template-id
498 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
499 TemplateName, false))
504 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
505 (IsTypename || IsTemplateArgumentList(1))) {
506 // We have something like t::getAs<T>, where getAs is a
507 // member of an unknown specialization. However, this will only
508 // parse correctly as a template, so suggest the keyword 'template'
509 // before 'getAs' and treat this as a dependent template name.
510 unsigned DiagID = diag::err_missing_dependent_template_keyword;
511 if (getLangOpts().MicrosoftExt)
512 DiagID = diag::warn_missing_dependent_template_keyword;
514 Diag(Tok.getLocation(), DiagID)
516 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
518 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
519 getCurScope(), SS, Tok.getLocation(), TemplateName, ObjectType,
520 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
521 // Consume the identifier.
523 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
524 TemplateName, false))
534 // We don't have any tokens that form the beginning of a
535 // nested-name-specifier, so we're done.
539 // Even if we didn't see any pieces of a nested-name-specifier, we
540 // still check whether there is a tilde in this position, which
541 // indicates a potential pseudo-destructor.
542 if (CheckForDestructor && Tok.is(tok::tilde))
543 *MayBePseudoDestructor = true;
548 ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
549 Token &Replacement) {
550 SourceLocation TemplateKWLoc;
552 if (ParseUnqualifiedId(SS,
553 /*EnteringContext=*/false,
554 /*AllowDestructorName=*/false,
555 /*AllowConstructorName=*/false,
556 /*AllowDeductionGuide=*/false,
557 /*ObjectType=*/nullptr, &TemplateKWLoc, Name))
560 // This is only the direct operand of an & operator if it is not
561 // followed by a postfix-expression suffix.
562 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
563 isAddressOfOperand = false;
565 ExprResult E = Actions.ActOnIdExpression(
566 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
567 isAddressOfOperand, nullptr, /*IsInlineAsmIdentifier=*/false,
569 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
570 checkPotentialAngleBracket(E);
574 /// ParseCXXIdExpression - Handle id-expression.
581 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
583 /// '::' operator-function-id
586 /// NOTE: The standard specifies that, for qualified-id, the parser does not
589 /// '::' conversion-function-id
590 /// '::' '~' class-name
592 /// This may cause a slight inconsistency on diagnostics:
597 /// :: A :: ~ C(); // Some Sema error about using destructor with a
599 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
602 /// We simplify the parser a bit and make it work like:
605 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
606 /// '::' unqualified-id
608 /// That way Sema can handle and report similar errors for namespaces and the
611 /// The isAddressOfOperand parameter indicates that this id-expression is a
612 /// direct operand of the address-of operator. This is, besides member contexts,
613 /// the only place where a qualified-id naming a non-static class member may
616 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
618 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
619 // '::' unqualified-id
622 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
626 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
627 if (Result.isUnset()) {
628 // If the ExprResult is valid but null, then typo correction suggested a
629 // keyword replacement that needs to be reparsed.
630 UnconsumeToken(Replacement);
631 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
633 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
634 "for a previous keyword suggestion");
638 /// ParseLambdaExpression - Parse a C++11 lambda expression.
640 /// lambda-expression:
641 /// lambda-introducer lambda-declarator[opt] compound-statement
643 /// lambda-introducer:
644 /// '[' lambda-capture[opt] ']'
649 /// capture-default ',' capture-list
657 /// capture-list ',' capture
661 /// init-capture [C++1y]
668 /// init-capture: [C++1y]
669 /// identifier initializer
670 /// '&' identifier initializer
672 /// lambda-declarator:
673 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
674 /// 'mutable'[opt] exception-specification[opt]
675 /// trailing-return-type[opt]
677 ExprResult Parser::ParseLambdaExpression() {
678 // Parse lambda-introducer.
679 LambdaIntroducer Intro;
680 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
682 Diag(Tok, DiagID.getValue());
683 SkipUntil(tok::r_square, StopAtSemi);
684 SkipUntil(tok::l_brace, StopAtSemi);
685 SkipUntil(tok::r_brace, StopAtSemi);
689 return ParseLambdaExpressionAfterIntroducer(Intro);
692 /// TryParseLambdaExpression - Use lookahead and potentially tentative
693 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
696 /// If we are not looking at a lambda expression, returns ExprError().
697 ExprResult Parser::TryParseLambdaExpression() {
698 assert(getLangOpts().CPlusPlus11
699 && Tok.is(tok::l_square)
700 && "Not at the start of a possible lambda expression.");
702 const Token Next = NextToken();
703 if (Next.is(tok::eof)) // Nothing else to lookup here...
706 const Token After = GetLookAheadToken(2);
707 // If lookahead indicates this is a lambda...
708 if (Next.is(tok::r_square) || // []
709 Next.is(tok::equal) || // [=
710 (Next.is(tok::amp) && // [&] or [&,
711 (After.is(tok::r_square) ||
712 After.is(tok::comma))) ||
713 (Next.is(tok::identifier) && // [identifier]
714 After.is(tok::r_square))) {
715 return ParseLambdaExpression();
718 // If lookahead indicates an ObjC message send...
719 // [identifier identifier
720 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
724 // Here, we're stuck: lambda introducers and Objective-C message sends are
725 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
726 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
727 // writing two routines to parse a lambda introducer, just try to parse
728 // a lambda introducer first, and fall back if that fails.
729 // (TryParseLambdaIntroducer never produces any diagnostic output.)
730 LambdaIntroducer Intro;
731 if (TryParseLambdaIntroducer(Intro))
734 return ParseLambdaExpressionAfterIntroducer(Intro);
737 /// Parse a lambda introducer.
738 /// \param Intro A LambdaIntroducer filled in with information about the
739 /// contents of the lambda-introducer.
740 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
741 /// message send and a lambda expression. In this mode, we will
742 /// sometimes skip the initializers for init-captures and not fully
743 /// populate \p Intro. This flag will be set to \c true if we do so.
744 /// \return A DiagnosticID if it hit something unexpected. The location for
745 /// the diagnostic is that of the current token.
746 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
747 bool *SkippedInits) {
748 typedef Optional<unsigned> DiagResult;
750 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
751 BalancedDelimiterTracker T(*this, tok::l_square);
754 Intro.Range.setBegin(T.getOpenLocation());
758 // Parse capture-default.
759 if (Tok.is(tok::amp) &&
760 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
761 Intro.Default = LCD_ByRef;
762 Intro.DefaultLoc = ConsumeToken();
764 } else if (Tok.is(tok::equal)) {
765 Intro.Default = LCD_ByCopy;
766 Intro.DefaultLoc = ConsumeToken();
770 while (Tok.isNot(tok::r_square)) {
772 if (Tok.isNot(tok::comma)) {
773 // Provide a completion for a lambda introducer here. Except
774 // in Objective-C, where this is Almost Surely meant to be a message
775 // send. In that case, fail here and let the ObjC message
776 // expression parser perform the completion.
777 if (Tok.is(tok::code_completion) &&
778 !(getLangOpts().ObjC && Intro.Default == LCD_None &&
779 !Intro.Captures.empty())) {
780 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
781 /*AfterAmpersand=*/false);
786 return DiagResult(diag::err_expected_comma_or_rsquare);
791 if (Tok.is(tok::code_completion)) {
792 // If we're in Objective-C++ and we have a bare '[', then this is more
793 // likely to be a message receiver.
794 if (getLangOpts().ObjC && first)
795 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
797 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
798 /*AfterAmpersand=*/false);
806 LambdaCaptureKind Kind = LCK_ByCopy;
807 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
809 IdentifierInfo *Id = nullptr;
810 SourceLocation EllipsisLoc;
812 SourceLocation LocStart = Tok.getLocation();
814 if (Tok.is(tok::star)) {
815 Loc = ConsumeToken();
816 if (Tok.is(tok::kw_this)) {
820 return DiagResult(diag::err_expected_star_this_capture);
822 } else if (Tok.is(tok::kw_this)) {
824 Loc = ConsumeToken();
826 if (Tok.is(tok::amp)) {
830 if (Tok.is(tok::code_completion)) {
831 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
832 /*AfterAmpersand=*/true);
838 if (Tok.is(tok::identifier)) {
839 Id = Tok.getIdentifierInfo();
840 Loc = ConsumeToken();
841 } else if (Tok.is(tok::kw_this)) {
842 // FIXME: If we want to suggest a fixit here, will need to return more
843 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
844 // Clear()ed to prevent emission in case of tentative parsing?
845 return DiagResult(diag::err_this_captured_by_reference);
847 return DiagResult(diag::err_expected_capture);
850 if (Tok.is(tok::l_paren)) {
851 BalancedDelimiterTracker Parens(*this, tok::l_paren);
852 Parens.consumeOpen();
854 InitKind = LambdaCaptureInitKind::DirectInit;
860 *SkippedInits = true;
861 } else if (ParseExpressionList(Exprs, Commas)) {
865 Parens.consumeClose();
866 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
867 Parens.getCloseLocation(),
870 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
871 // Each lambda init-capture forms its own full expression, which clears
872 // Actions.MaybeODRUseExprs. So create an expression evaluation context
873 // to save the necessary state, and restore it later.
874 EnterExpressionEvaluationContext EC(
875 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
877 if (TryConsumeToken(tok::equal))
878 InitKind = LambdaCaptureInitKind::CopyInit;
880 InitKind = LambdaCaptureInitKind::ListInit;
883 Init = ParseInitializer();
884 } else if (Tok.is(tok::l_brace)) {
885 BalancedDelimiterTracker Braces(*this, tok::l_brace);
886 Braces.consumeOpen();
888 *SkippedInits = true;
890 // We're disambiguating this:
894 // We need to find the end of the following expression in order to
895 // determine whether this is an Obj-C message send's receiver, a
896 // C99 designator, or a lambda init-capture.
898 // Parse the expression to find where it ends, and annotate it back
899 // onto the tokens. We would have parsed this expression the same way
900 // in either case: both the RHS of an init-capture and the RHS of an
901 // assignment expression are parsed as an initializer-clause, and in
902 // neither case can anything be added to the scope between the '[' and
905 // FIXME: This is horrible. Adding a mechanism to skip an expression
906 // would be much cleaner.
907 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
908 // that instead. (And if we see a ':' with no matching '?', we can
909 // classify this as an Obj-C message send.)
910 SourceLocation StartLoc = Tok.getLocation();
911 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
912 Init = ParseInitializer();
913 if (!Init.isInvalid())
914 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
916 if (Tok.getLocation() != StartLoc) {
917 // Back out the lexing of the token after the initializer.
918 PP.RevertCachedTokens(1);
920 // Replace the consumed tokens with an appropriate annotation.
921 Tok.setLocation(StartLoc);
922 Tok.setKind(tok::annot_primary_expr);
923 setExprAnnotation(Tok, Init);
924 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
925 PP.AnnotateCachedTokens(Tok);
927 // Consume the annotated initializer.
928 ConsumeAnnotationToken();
932 TryConsumeToken(tok::ellipsis, EllipsisLoc);
934 // If this is an init capture, process the initialization expression
935 // right away. For lambda init-captures such as the following:
937 // auto L = [i = x+1](int a) {
939 // &k = x](char b) { };
941 // keep in mind that each lambda init-capture has to have:
942 // - its initialization expression executed in the context
943 // of the enclosing/parent decl-context.
944 // - but the variable itself has to be 'injected' into the
945 // decl-context of its lambda's call-operator (which has
946 // not yet been created).
947 // Each init-expression is a full-expression that has to get
948 // Sema-analyzed (for capturing etc.) before its lambda's
949 // call-operator's decl-context, scope & scopeinfo are pushed on their
950 // respective stacks. Thus if any variable is odr-used in the init-capture
951 // it will correctly get captured in the enclosing lambda, if one exists.
952 // The init-variables above are created later once the lambdascope and
953 // call-operators decl-context is pushed onto its respective stack.
955 // Since the lambda init-capture's initializer expression occurs in the
956 // context of the enclosing function or lambda, therefore we can not wait
957 // till a lambda scope has been pushed on before deciding whether the
958 // variable needs to be captured. We also need to process all
959 // lvalue-to-rvalue conversions and discarded-value conversions,
960 // so that we can avoid capturing certain constant variables.
964 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
965 // return [y = x](int i) { <-- don't capture by enclosing lambda
970 // If x was not const, the second use would require 'L' to capture, and
971 // that would be an error.
973 ParsedType InitCaptureType;
974 if (!Init.isInvalid())
975 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
976 if (Init.isUsable()) {
977 // Get the pointer and store it in an lvalue, so we can use it as an
979 Expr *InitExpr = Init.get();
980 // This performs any lvalue-to-rvalue conversions if necessary, which
981 // can affect what gets captured in the containing decl-context.
982 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
983 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
987 SourceLocation LocEnd = PrevTokLocation;
989 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
990 InitCaptureType, SourceRange(LocStart, LocEnd));
994 Intro.Range.setEnd(T.getCloseLocation());
998 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
1000 /// Returns true if it hit something unexpected.
1001 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1003 bool SkippedInits = false;
1004 TentativeParsingAction PA1(*this);
1006 if (ParseLambdaIntroducer(Intro, &SkippedInits)) {
1011 if (!SkippedInits) {
1019 // Try to parse it again, but this time parse the init-captures too.
1020 Intro = LambdaIntroducer();
1021 TentativeParsingAction PA2(*this);
1023 if (!ParseLambdaIntroducer(Intro)) {
1033 tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1034 SourceLocation &ConstexprLoc,
1035 SourceLocation &DeclEndLoc) {
1036 assert(MutableLoc.isInvalid());
1037 assert(ConstexprLoc.isInvalid());
1038 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1039 // to the final of those locations. Emit an error if we have multiple
1040 // copies of those keywords and recover.
1043 switch (P.getCurToken().getKind()) {
1044 case tok::kw_mutable: {
1045 if (MutableLoc.isValid()) {
1046 P.Diag(P.getCurToken().getLocation(),
1047 diag::err_lambda_decl_specifier_repeated)
1048 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1050 MutableLoc = P.ConsumeToken();
1051 DeclEndLoc = MutableLoc;
1054 case tok::kw_constexpr:
1055 if (ConstexprLoc.isValid()) {
1056 P.Diag(P.getCurToken().getLocation(),
1057 diag::err_lambda_decl_specifier_repeated)
1058 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1060 ConstexprLoc = P.ConsumeToken();
1061 DeclEndLoc = ConstexprLoc;
1070 addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1072 if (ConstexprLoc.isValid()) {
1073 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1074 ? diag::ext_constexpr_on_lambda_cxx17
1075 : diag::warn_cxx14_compat_constexpr_on_lambda);
1076 const char *PrevSpec = nullptr;
1077 unsigned DiagID = 0;
1078 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1079 assert(PrevSpec == nullptr && DiagID == 0 &&
1080 "Constexpr cannot have been set previously!");
1084 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1086 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1087 LambdaIntroducer &Intro) {
1088 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1089 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1091 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1092 "lambda expression parsing");
1096 // FIXME: Call into Actions to add any init-capture declarations to the
1097 // scope while parsing the lambda-declarator and compound-statement.
1099 // Parse lambda-declarator[opt].
1100 DeclSpec DS(AttrFactory);
1101 Declarator D(DS, DeclaratorContext::LambdaExprContext);
1102 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1103 Actions.PushLambdaScope();
1105 ParsedAttributes Attr(AttrFactory);
1106 SourceLocation DeclLoc = Tok.getLocation();
1107 if (getLangOpts().CUDA) {
1108 // In CUDA code, GNU attributes are allowed to appear immediately after the
1109 // "[...]", even if there is no "(...)" before the lambda body.
1110 MaybeParseGNUAttributes(D);
1113 // Helper to emit a warning if we see a CUDA host/device/global attribute
1114 // after '(...)'. nvcc doesn't accept this.
1115 auto WarnIfHasCUDATargetAttr = [&] {
1116 if (getLangOpts().CUDA)
1117 for (const ParsedAttr &A : Attr)
1118 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1119 A.getKind() == ParsedAttr::AT_CUDAHost ||
1120 A.getKind() == ParsedAttr::AT_CUDAGlobal)
1121 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1122 << A.getName()->getName();
1125 TypeResult TrailingReturnType;
1126 if (Tok.is(tok::l_paren)) {
1127 ParseScope PrototypeScope(this,
1128 Scope::FunctionPrototypeScope |
1129 Scope::FunctionDeclarationScope |
1132 BalancedDelimiterTracker T(*this, tok::l_paren);
1134 SourceLocation LParenLoc = T.getOpenLocation();
1136 // Parse parameter-declaration-clause.
1137 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1138 SourceLocation EllipsisLoc;
1140 if (Tok.isNot(tok::r_paren)) {
1141 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1142 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1143 // For a generic lambda, each 'auto' within the parameter declaration
1144 // clause creates a template type parameter, so increment the depth.
1145 if (Actions.getCurGenericLambda())
1146 ++CurTemplateDepthTracker;
1149 SourceLocation RParenLoc = T.getCloseLocation();
1150 SourceLocation DeclEndLoc = RParenLoc;
1152 // GNU-style attributes must be parsed before the mutable specifier to be
1153 // compatible with GCC.
1154 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1156 // MSVC-style attributes must be parsed before the mutable specifier to be
1157 // compatible with MSVC.
1158 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1160 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
1161 SourceLocation MutableLoc;
1162 SourceLocation ConstexprLoc;
1163 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1166 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1168 // Parse exception-specification[opt].
1169 ExceptionSpecificationType ESpecType = EST_None;
1170 SourceRange ESpecRange;
1171 SmallVector<ParsedType, 2> DynamicExceptions;
1172 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1173 ExprResult NoexceptExpr;
1174 CachedTokens *ExceptionSpecTokens;
1175 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1178 DynamicExceptionRanges,
1180 ExceptionSpecTokens);
1182 if (ESpecType != EST_None)
1183 DeclEndLoc = ESpecRange.getEnd();
1185 // Parse attribute-specifier[opt].
1186 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1188 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1190 // Parse trailing-return-type[opt].
1191 if (Tok.is(tok::arrow)) {
1192 FunLocalRangeEnd = Tok.getLocation();
1194 TrailingReturnType =
1195 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1196 if (Range.getEnd().isValid())
1197 DeclEndLoc = Range.getEnd();
1200 PrototypeScope.Exit();
1202 WarnIfHasCUDATargetAttr();
1204 SourceLocation NoLoc;
1205 D.AddTypeInfo(DeclaratorChunk::getFunction(
1207 /*isAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1208 ParamInfo.size(), EllipsisLoc, RParenLoc,
1209 /*RefQualifierIsLValueRef=*/true,
1210 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
1211 ESpecRange, DynamicExceptions.data(),
1212 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1213 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1214 /*ExceptionSpecTokens*/ nullptr,
1215 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1216 TrailingReturnType),
1217 std::move(Attr), DeclEndLoc);
1218 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1219 tok::kw_constexpr) ||
1220 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1221 // It's common to forget that one needs '()' before 'mutable', an attribute
1222 // specifier, or the result type. Deal with this.
1223 unsigned TokKind = 0;
1224 switch (Tok.getKind()) {
1225 case tok::kw_mutable: TokKind = 0; break;
1226 case tok::arrow: TokKind = 1; break;
1227 case tok::kw___attribute:
1228 case tok::l_square: TokKind = 2; break;
1229 case tok::kw_constexpr: TokKind = 3; break;
1230 default: llvm_unreachable("Unknown token kind");
1233 Diag(Tok, diag::err_lambda_missing_parens)
1235 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1236 SourceLocation DeclEndLoc = DeclLoc;
1238 // GNU-style attributes must be parsed before the mutable specifier to be
1239 // compatible with GCC.
1240 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1242 // Parse 'mutable', if it's there.
1243 SourceLocation MutableLoc;
1244 if (Tok.is(tok::kw_mutable)) {
1245 MutableLoc = ConsumeToken();
1246 DeclEndLoc = MutableLoc;
1249 // Parse attribute-specifier[opt].
1250 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1252 // Parse the return type, if there is one.
1253 if (Tok.is(tok::arrow)) {
1255 TrailingReturnType =
1256 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1257 if (Range.getEnd().isValid())
1258 DeclEndLoc = Range.getEnd();
1261 WarnIfHasCUDATargetAttr();
1263 SourceLocation NoLoc;
1264 D.AddTypeInfo(DeclaratorChunk::getFunction(
1266 /*isAmbiguous=*/false,
1267 /*LParenLoc=*/NoLoc,
1270 /*EllipsisLoc=*/NoLoc,
1271 /*RParenLoc=*/NoLoc,
1272 /*RefQualifierIsLValueRef=*/true,
1273 /*RefQualifierLoc=*/NoLoc, MutableLoc, EST_None,
1274 /*ESpecRange=*/SourceRange(),
1275 /*Exceptions=*/nullptr,
1276 /*ExceptionRanges=*/nullptr,
1277 /*NumExceptions=*/0,
1278 /*NoexceptExpr=*/nullptr,
1279 /*ExceptionSpecTokens=*/nullptr,
1280 /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1281 TrailingReturnType),
1282 std::move(Attr), DeclEndLoc);
1285 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1287 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1288 Scope::CompoundStmtScope;
1289 ParseScope BodyScope(this, ScopeFlags);
1291 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1293 // Parse compound-statement.
1294 if (!Tok.is(tok::l_brace)) {
1295 Diag(Tok, diag::err_expected_lambda_body);
1296 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1300 StmtResult Stmt(ParseCompoundStatementBody());
1303 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1304 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1306 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1310 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1313 /// postfix-expression: [C++ 5.2p1]
1314 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1315 /// 'static_cast' '<' type-name '>' '(' expression ')'
1316 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1317 /// 'const_cast' '<' type-name '>' '(' expression ')'
1319 ExprResult Parser::ParseCXXCasts() {
1320 tok::TokenKind Kind = Tok.getKind();
1321 const char *CastName = nullptr; // For error messages
1324 default: llvm_unreachable("Unknown C++ cast!");
1325 case tok::kw_const_cast: CastName = "const_cast"; break;
1326 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1327 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1328 case tok::kw_static_cast: CastName = "static_cast"; break;
1331 SourceLocation OpLoc = ConsumeToken();
1332 SourceLocation LAngleBracketLoc = Tok.getLocation();
1334 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1335 // diagnose error, suggest fix, and recover parsing.
1336 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1337 Token Next = NextToken();
1338 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1339 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1342 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1345 // Parse the common declaration-specifiers piece.
1346 DeclSpec DS(AttrFactory);
1347 ParseSpecifierQualifierList(DS);
1349 // Parse the abstract-declarator, if present.
1350 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1351 ParseDeclarator(DeclaratorInfo);
1353 SourceLocation RAngleBracketLoc = Tok.getLocation();
1355 if (ExpectAndConsume(tok::greater))
1356 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1358 BalancedDelimiterTracker T(*this, tok::l_paren);
1360 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1363 ExprResult Result = ParseExpression();
1368 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1369 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1370 LAngleBracketLoc, DeclaratorInfo,
1372 T.getOpenLocation(), Result.get(),
1373 T.getCloseLocation());
1378 /// ParseCXXTypeid - This handles the C++ typeid expression.
1380 /// postfix-expression: [C++ 5.2p1]
1381 /// 'typeid' '(' expression ')'
1382 /// 'typeid' '(' type-id ')'
1384 ExprResult Parser::ParseCXXTypeid() {
1385 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1387 SourceLocation OpLoc = ConsumeToken();
1388 SourceLocation LParenLoc, RParenLoc;
1389 BalancedDelimiterTracker T(*this, tok::l_paren);
1391 // typeid expressions are always parenthesized.
1392 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1394 LParenLoc = T.getOpenLocation();
1398 // C++0x [expr.typeid]p3:
1399 // When typeid is applied to an expression other than an lvalue of a
1400 // polymorphic class type [...] The expression is an unevaluated
1401 // operand (Clause 5).
1403 // Note that we can't tell whether the expression is an lvalue of a
1404 // polymorphic class type until after we've parsed the expression; we
1405 // speculatively assume the subexpression is unevaluated, and fix it up
1408 // We enter the unevaluated context before trying to determine whether we
1409 // have a type-id, because the tentative parse logic will try to resolve
1410 // names, and must treat them as unevaluated.
1411 EnterExpressionEvaluationContext Unevaluated(
1412 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1413 Sema::ReuseLambdaContextDecl);
1415 if (isTypeIdInParens()) {
1416 TypeResult Ty = ParseTypeName();
1420 RParenLoc = T.getCloseLocation();
1421 if (Ty.isInvalid() || RParenLoc.isInvalid())
1424 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1425 Ty.get().getAsOpaquePtr(), RParenLoc);
1427 Result = ParseExpression();
1430 if (Result.isInvalid())
1431 SkipUntil(tok::r_paren, StopAtSemi);
1434 RParenLoc = T.getCloseLocation();
1435 if (RParenLoc.isInvalid())
1438 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1439 Result.get(), RParenLoc);
1446 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1448 /// '__uuidof' '(' expression ')'
1449 /// '__uuidof' '(' type-id ')'
1451 ExprResult Parser::ParseCXXUuidof() {
1452 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1454 SourceLocation OpLoc = ConsumeToken();
1455 BalancedDelimiterTracker T(*this, tok::l_paren);
1457 // __uuidof expressions are always parenthesized.
1458 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1463 if (isTypeIdInParens()) {
1464 TypeResult Ty = ParseTypeName();
1472 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1473 Ty.get().getAsOpaquePtr(),
1474 T.getCloseLocation());
1476 EnterExpressionEvaluationContext Unevaluated(
1477 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1478 Result = ParseExpression();
1481 if (Result.isInvalid())
1482 SkipUntil(tok::r_paren, StopAtSemi);
1486 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1488 Result.get(), T.getCloseLocation());
1495 /// Parse a C++ pseudo-destructor expression after the base,
1496 /// . or -> operator, and nested-name-specifier have already been
1499 /// postfix-expression: [C++ 5.2]
1500 /// postfix-expression . pseudo-destructor-name
1501 /// postfix-expression -> pseudo-destructor-name
1503 /// pseudo-destructor-name:
1504 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1505 /// ::[opt] nested-name-specifier template simple-template-id ::
1507 /// ::[opt] nested-name-specifier[opt] ~type-name
1510 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1511 tok::TokenKind OpKind,
1513 ParsedType ObjectType) {
1514 // We're parsing either a pseudo-destructor-name or a dependent
1515 // member access that has the same form as a
1516 // pseudo-destructor-name. We parse both in the same way and let
1517 // the action model sort them out.
1519 // Note that the ::[opt] nested-name-specifier[opt] has already
1520 // been parsed, and if there was a simple-template-id, it has
1521 // been coalesced into a template-id annotation token.
1522 UnqualifiedId FirstTypeName;
1523 SourceLocation CCLoc;
1524 if (Tok.is(tok::identifier)) {
1525 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1527 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1528 CCLoc = ConsumeToken();
1529 } else if (Tok.is(tok::annot_template_id)) {
1530 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1531 // store it in the pseudo-dtor node (to be used when instantiating it).
1532 FirstTypeName.setTemplateId(
1533 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1534 ConsumeAnnotationToken();
1535 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1536 CCLoc = ConsumeToken();
1538 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1542 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1543 SourceLocation TildeLoc = ConsumeToken();
1545 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1546 DeclSpec DS(AttrFactory);
1547 ParseDecltypeSpecifier(DS);
1548 if (DS.getTypeSpecType() == TST_error)
1550 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1554 if (!Tok.is(tok::identifier)) {
1555 Diag(Tok, diag::err_destructor_tilde_identifier);
1559 // Parse the second type.
1560 UnqualifiedId SecondTypeName;
1561 IdentifierInfo *Name = Tok.getIdentifierInfo();
1562 SourceLocation NameLoc = ConsumeToken();
1563 SecondTypeName.setIdentifier(Name, NameLoc);
1565 // If there is a '<', the second type name is a template-id. Parse
1567 if (Tok.is(tok::less) &&
1568 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1570 false, ObjectType, SecondTypeName,
1571 /*AssumeTemplateName=*/true))
1574 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1575 SS, FirstTypeName, CCLoc, TildeLoc,
1579 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1581 /// boolean-literal: [C++ 2.13.5]
1584 ExprResult Parser::ParseCXXBoolLiteral() {
1585 tok::TokenKind Kind = Tok.getKind();
1586 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1589 /// ParseThrowExpression - This handles the C++ throw expression.
1591 /// throw-expression: [C++ 15]
1592 /// 'throw' assignment-expression[opt]
1593 ExprResult Parser::ParseThrowExpression() {
1594 assert(Tok.is(tok::kw_throw) && "Not throw!");
1595 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1597 // If the current token isn't the start of an assignment-expression,
1598 // then the expression is not present. This handles things like:
1599 // "C ? throw : (void)42", which is crazy but legal.
1600 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1607 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1610 ExprResult Expr(ParseAssignmentExpression());
1611 if (Expr.isInvalid()) return Expr;
1612 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1616 /// Parse the C++ Coroutines co_yield expression.
1618 /// co_yield-expression:
1619 /// 'co_yield' assignment-expression[opt]
1620 ExprResult Parser::ParseCoyieldExpression() {
1621 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1623 SourceLocation Loc = ConsumeToken();
1624 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1625 : ParseAssignmentExpression();
1626 if (!Expr.isInvalid())
1627 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1631 /// ParseCXXThis - This handles the C++ 'this' pointer.
1633 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1634 /// a non-lvalue expression whose value is the address of the object for which
1635 /// the function is called.
1636 ExprResult Parser::ParseCXXThis() {
1637 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1638 SourceLocation ThisLoc = ConsumeToken();
1639 return Actions.ActOnCXXThis(ThisLoc);
1642 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1643 /// Can be interpreted either as function-style casting ("int(x)")
1644 /// or class type construction ("ClassType(x,y,z)")
1645 /// or creation of a value-initialized type ("int()").
1646 /// See [C++ 5.2.3].
1648 /// postfix-expression: [C++ 5.2p1]
1649 /// simple-type-specifier '(' expression-list[opt] ')'
1650 /// [C++0x] simple-type-specifier braced-init-list
1651 /// typename-specifier '(' expression-list[opt] ')'
1652 /// [C++0x] typename-specifier braced-init-list
1654 /// In C++1z onwards, the type specifier can also be a template-name.
1656 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1657 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCastContext);
1658 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1660 assert((Tok.is(tok::l_paren) ||
1661 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1662 && "Expected '(' or '{'!");
1664 if (Tok.is(tok::l_brace)) {
1665 ExprResult Init = ParseBraceInitializer();
1666 if (Init.isInvalid())
1668 Expr *InitList = Init.get();
1669 return Actions.ActOnCXXTypeConstructExpr(
1670 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
1671 InitList->getEndLoc(), /*ListInitialization=*/true);
1673 BalancedDelimiterTracker T(*this, tok::l_paren);
1677 CommaLocsTy CommaLocs;
1679 if (Tok.isNot(tok::r_paren)) {
1680 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1681 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
1682 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1683 DS.getEndLoc(), Exprs, T.getOpenLocation());
1684 CalledSignatureHelp = true;
1685 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
1687 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) {
1688 Actions.ProduceConstructorSignatureHelp(
1689 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1690 DS.getEndLoc(), Exprs, T.getOpenLocation());
1691 CalledSignatureHelp = true;
1693 SkipUntil(tok::r_paren, StopAtSemi);
1701 // TypeRep could be null, if it references an invalid typedef.
1705 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1706 "Unexpected number of commas!");
1707 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1708 Exprs, T.getCloseLocation(),
1709 /*ListInitialization=*/false);
1713 /// ParseCXXCondition - if/switch/while condition expression.
1717 /// type-specifier-seq declarator '=' assignment-expression
1718 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1719 /// [C++11] type-specifier-seq declarator braced-init-list
1720 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1721 /// brace-or-equal-initializer
1722 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1723 /// '=' assignment-expression
1725 /// In C++1z, a condition may in some contexts be preceded by an
1726 /// optional init-statement. This function will parse that too.
1728 /// \param InitStmt If non-null, an init-statement is permitted, and if present
1729 /// will be parsed and stored here.
1731 /// \param Loc The location of the start of the statement that requires this
1732 /// condition, e.g., the "for" in a for loop.
1734 /// \param FRI If non-null, a for range declaration is permitted, and if
1735 /// present will be parsed and stored here, and a null result will be returned.
1737 /// \returns The parsed condition.
1738 Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1740 Sema::ConditionKind CK,
1741 ForRangeInfo *FRI) {
1742 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1744 if (Tok.is(tok::code_completion)) {
1745 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1747 return Sema::ConditionError();
1750 ParsedAttributesWithRange attrs(AttrFactory);
1751 MaybeParseCXX11Attributes(attrs);
1753 const auto WarnOnInit = [this, &CK] {
1754 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1755 ? diag::warn_cxx14_compat_init_statement
1756 : diag::ext_init_statement)
1757 << (CK == Sema::ConditionKind::Switch);
1760 // Determine what kind of thing we have.
1761 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
1762 case ConditionOrInitStatement::Expression: {
1763 ProhibitAttributes(attrs);
1765 // We can have an empty expression here.
1767 if (InitStmt && Tok.is(tok::semi)) {
1769 SourceLocation SemiLoc = Tok.getLocation();
1770 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
1771 Diag(SemiLoc, diag::warn_empty_init_statement)
1772 << (CK == Sema::ConditionKind::Switch)
1773 << FixItHint::CreateRemoval(SemiLoc);
1776 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1777 return ParseCXXCondition(nullptr, Loc, CK);
1780 // Parse the expression.
1781 ExprResult Expr = ParseExpression(); // expression
1782 if (Expr.isInvalid())
1783 return Sema::ConditionError();
1785 if (InitStmt && Tok.is(tok::semi)) {
1787 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1789 return ParseCXXCondition(nullptr, Loc, CK);
1792 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
1795 case ConditionOrInitStatement::InitStmtDecl: {
1797 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1799 ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1800 attrs, /*RequireSemi=*/true);
1801 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1802 return ParseCXXCondition(nullptr, Loc, CK);
1805 case ConditionOrInitStatement::ForRangeDecl: {
1806 assert(FRI && "should not parse a for range declaration here");
1807 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1808 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1809 DeclaratorContext::ForContext, DeclEnd, attrs, false, FRI);
1810 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1811 return Sema::ConditionResult();
1814 case ConditionOrInitStatement::ConditionDecl:
1815 case ConditionOrInitStatement::Error:
1819 // type-specifier-seq
1820 DeclSpec DS(AttrFactory);
1821 DS.takeAttributesFrom(attrs);
1822 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
1825 Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
1826 ParseDeclarator(DeclaratorInfo);
1828 // simple-asm-expr[opt]
1829 if (Tok.is(tok::kw_asm)) {
1831 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1832 if (AsmLabel.isInvalid()) {
1833 SkipUntil(tok::semi, StopAtSemi);
1834 return Sema::ConditionError();
1836 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1837 DeclaratorInfo.SetRangeEnd(Loc);
1840 // If attributes are present, parse them.
1841 MaybeParseGNUAttributes(DeclaratorInfo);
1843 // Type-check the declaration itself.
1844 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1846 if (Dcl.isInvalid())
1847 return Sema::ConditionError();
1848 Decl *DeclOut = Dcl.get();
1850 // '=' assignment-expression
1851 // If a '==' or '+=' is found, suggest a fixit to '='.
1852 bool CopyInitialization = isTokenEqualOrEqualTypo();
1853 if (CopyInitialization)
1856 ExprResult InitExpr = ExprError();
1857 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1858 Diag(Tok.getLocation(),
1859 diag::warn_cxx98_compat_generalized_initializer_lists);
1860 InitExpr = ParseBraceInitializer();
1861 } else if (CopyInitialization) {
1862 InitExpr = ParseAssignmentExpression();
1863 } else if (Tok.is(tok::l_paren)) {
1864 // This was probably an attempt to initialize the variable.
1865 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1866 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1867 RParen = ConsumeParen();
1868 Diag(DeclOut->getLocation(),
1869 diag::err_expected_init_in_condition_lparen)
1870 << SourceRange(LParen, RParen);
1872 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
1875 if (!InitExpr.isInvalid())
1876 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
1878 Actions.ActOnInitializerError(DeclOut);
1880 Actions.FinalizeDeclaration(DeclOut);
1881 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
1884 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1885 /// This should only be called when the current token is known to be part of
1886 /// simple-type-specifier.
1888 /// simple-type-specifier:
1889 /// '::'[opt] nested-name-specifier[opt] type-name
1890 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1902 /// [GNU] typeof-specifier
1903 /// [C++0x] auto [TODO]
1910 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1911 DS.SetRangeStart(Tok.getLocation());
1912 const char *PrevSpec;
1914 SourceLocation Loc = Tok.getLocation();
1915 const clang::PrintingPolicy &Policy =
1916 Actions.getASTContext().getPrintingPolicy();
1918 switch (Tok.getKind()) {
1919 case tok::identifier: // foo::bar
1920 case tok::coloncolon: // ::foo::bar
1921 llvm_unreachable("Annotation token should already be formed!");
1923 llvm_unreachable("Not a simple-type-specifier token!");
1926 case tok::annot_typename: {
1927 if (getTypeAnnotation(Tok))
1928 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1929 getTypeAnnotation(Tok), Policy);
1931 DS.SetTypeSpecError();
1933 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1934 ConsumeAnnotationToken();
1936 DS.Finish(Actions, Policy);
1942 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1945 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1947 case tok::kw___int64:
1948 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1950 case tok::kw_signed:
1951 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1953 case tok::kw_unsigned:
1954 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1957 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1960 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1963 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1965 case tok::kw___int128:
1966 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1969 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1972 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1974 case tok::kw_double:
1975 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1977 case tok::kw__Float16:
1978 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
1980 case tok::kw___float128:
1981 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1983 case tok::kw_wchar_t:
1984 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1986 case tok::kw_char8_t:
1987 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
1989 case tok::kw_char16_t:
1990 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1992 case tok::kw_char32_t:
1993 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1996 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1998 case tok::annot_decltype:
1999 case tok::kw_decltype:
2000 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2001 return DS.Finish(Actions, Policy);
2003 // GNU typeof support.
2004 case tok::kw_typeof:
2005 ParseTypeofSpecifier(DS);
2006 DS.Finish(Actions, Policy);
2010 DS.SetRangeEnd(PrevTokLocation);
2011 DS.Finish(Actions, Policy);
2014 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2015 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
2016 /// e.g., "const short int". Note that the DeclSpec is *not* finished
2017 /// by parsing the type-specifier-seq, because these sequences are
2018 /// typically followed by some form of declarator. Returns true and
2019 /// emits diagnostics if this is not a type-specifier-seq, false
2022 /// type-specifier-seq: [C++ 8.1]
2023 /// type-specifier type-specifier-seq[opt]
2025 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
2026 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
2027 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2031 /// Finish parsing a C++ unqualified-id that is a template-id of
2034 /// This routine is invoked when a '<' is encountered after an identifier or
2035 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2036 /// whether the unqualified-id is actually a template-id. This routine will
2037 /// then parse the template arguments and form the appropriate template-id to
2038 /// return to the caller.
2040 /// \param SS the nested-name-specifier that precedes this template-id, if
2041 /// we're actually parsing a qualified-id.
2043 /// \param Name for constructor and destructor names, this is the actual
2044 /// identifier that may be a template-name.
2046 /// \param NameLoc the location of the class-name in a constructor or
2049 /// \param EnteringContext whether we're entering the scope of the
2050 /// nested-name-specifier.
2052 /// \param ObjectType if this unqualified-id occurs within a member access
2053 /// expression, the type of the base object whose member is being accessed.
2055 /// \param Id as input, describes the template-name or operator-function-id
2056 /// that precedes the '<'. If template arguments were parsed successfully,
2057 /// will be updated with the template-id.
2059 /// \param AssumeTemplateId When true, this routine will assume that the name
2060 /// refers to a template without performing name lookup to verify.
2062 /// \returns true if a parse error occurred, false otherwise.
2063 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2064 SourceLocation TemplateKWLoc,
2065 IdentifierInfo *Name,
2066 SourceLocation NameLoc,
2067 bool EnteringContext,
2068 ParsedType ObjectType,
2070 bool AssumeTemplateId) {
2071 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2073 TemplateTy Template;
2074 TemplateNameKind TNK = TNK_Non_template;
2075 switch (Id.getKind()) {
2076 case UnqualifiedIdKind::IK_Identifier:
2077 case UnqualifiedIdKind::IK_OperatorFunctionId:
2078 case UnqualifiedIdKind::IK_LiteralOperatorId:
2079 if (AssumeTemplateId) {
2080 // We defer the injected-class-name checks until we've found whether
2081 // this template-id is used to form a nested-name-specifier or not.
2082 TNK = Actions.ActOnDependentTemplateName(
2083 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2084 Template, /*AllowInjectedClassName*/ true);
2085 if (TNK == TNK_Non_template)
2088 bool MemberOfUnknownSpecialization;
2089 TNK = Actions.isTemplateName(getCurScope(), SS,
2090 TemplateKWLoc.isValid(), Id,
2091 ObjectType, EnteringContext, Template,
2092 MemberOfUnknownSpecialization);
2094 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2095 ObjectType && IsTemplateArgumentList()) {
2096 // We have something like t->getAs<T>(), where getAs is a
2097 // member of an unknown specialization. However, this will only
2098 // parse correctly as a template, so suggest the keyword 'template'
2099 // before 'getAs' and treat this as a dependent template name.
2101 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2102 Name = Id.Identifier->getName();
2105 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
2106 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2108 Name += Id.Identifier->getName();
2110 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2112 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2113 TNK = Actions.ActOnDependentTemplateName(
2114 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2115 Template, /*AllowInjectedClassName*/ true);
2116 if (TNK == TNK_Non_template)
2122 case UnqualifiedIdKind::IK_ConstructorName: {
2123 UnqualifiedId TemplateName;
2124 bool MemberOfUnknownSpecialization;
2125 TemplateName.setIdentifier(Name, NameLoc);
2126 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2127 TemplateName, ObjectType,
2128 EnteringContext, Template,
2129 MemberOfUnknownSpecialization);
2133 case UnqualifiedIdKind::IK_DestructorName: {
2134 UnqualifiedId TemplateName;
2135 bool MemberOfUnknownSpecialization;
2136 TemplateName.setIdentifier(Name, NameLoc);
2138 TNK = Actions.ActOnDependentTemplateName(
2139 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2140 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2141 if (TNK == TNK_Non_template)
2144 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2145 TemplateName, ObjectType,
2146 EnteringContext, Template,
2147 MemberOfUnknownSpecialization);
2149 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2150 Diag(NameLoc, diag::err_destructor_template_id)
2151 << Name << SS.getRange();
2162 if (TNK == TNK_Non_template)
2165 // Parse the enclosed template argument list.
2166 SourceLocation LAngleLoc, RAngleLoc;
2167 TemplateArgList TemplateArgs;
2168 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2172 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2173 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2174 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
2175 // Form a parsed representation of the template-id to be stored in the
2178 // FIXME: Store name for literal operator too.
2179 IdentifierInfo *TemplateII =
2180 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2182 OverloadedOperatorKind OpKind =
2183 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2185 : Id.OperatorFunctionId.Operator;
2187 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2188 SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2189 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2191 Id.setTemplateId(TemplateId);
2195 // Bundle the template arguments together.
2196 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2198 // Constructor and destructor names.
2200 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2201 Template, Name, NameLoc,
2202 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2203 /*IsCtorOrDtorName=*/true);
2204 if (Type.isInvalid())
2207 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
2208 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2210 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2215 /// Parse an operator-function-id or conversion-function-id as part
2216 /// of a C++ unqualified-id.
2218 /// This routine is responsible only for parsing the operator-function-id or
2219 /// conversion-function-id; it does not handle template arguments in any way.
2222 /// operator-function-id: [C++ 13.5]
2223 /// 'operator' operator
2225 /// operator: one of
2226 /// new delete new[] delete[]
2227 /// + - * / % ^ & | ~
2228 /// ! = < > += -= *= /= %=
2229 /// ^= &= |= << >> >>= <<= == !=
2230 /// <= >= && || ++ -- , ->* ->
2233 /// conversion-function-id: [C++ 12.3.2]
2234 /// operator conversion-type-id
2236 /// conversion-type-id:
2237 /// type-specifier-seq conversion-declarator[opt]
2239 /// conversion-declarator:
2240 /// ptr-operator conversion-declarator[opt]
2243 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2244 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2246 /// \param EnteringContext whether we are entering the scope of the
2247 /// nested-name-specifier.
2249 /// \param ObjectType if this unqualified-id occurs within a member access
2250 /// expression, the type of the base object whose member is being accessed.
2252 /// \param Result on a successful parse, contains the parsed unqualified-id.
2254 /// \returns true if parsing fails, false otherwise.
2255 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2256 ParsedType ObjectType,
2257 UnqualifiedId &Result) {
2258 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2260 // Consume the 'operator' keyword.
2261 SourceLocation KeywordLoc = ConsumeToken();
2263 // Determine what kind of operator name we have.
2264 unsigned SymbolIdx = 0;
2265 SourceLocation SymbolLocations[3];
2266 OverloadedOperatorKind Op = OO_None;
2267 switch (Tok.getKind()) {
2269 case tok::kw_delete: {
2270 bool isNew = Tok.getKind() == tok::kw_new;
2271 // Consume the 'new' or 'delete'.
2272 SymbolLocations[SymbolIdx++] = ConsumeToken();
2273 // Check for array new/delete.
2274 if (Tok.is(tok::l_square) &&
2275 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2276 // Consume the '[' and ']'.
2277 BalancedDelimiterTracker T(*this, tok::l_square);
2280 if (T.getCloseLocation().isInvalid())
2283 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2284 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2285 Op = isNew? OO_Array_New : OO_Array_Delete;
2287 Op = isNew? OO_New : OO_Delete;
2292 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2294 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2297 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2298 #include "clang/Basic/OperatorKinds.def"
2300 case tok::l_paren: {
2301 // Consume the '(' and ')'.
2302 BalancedDelimiterTracker T(*this, tok::l_paren);
2305 if (T.getCloseLocation().isInvalid())
2308 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2309 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2314 case tok::l_square: {
2315 // Consume the '[' and ']'.
2316 BalancedDelimiterTracker T(*this, tok::l_square);
2319 if (T.getCloseLocation().isInvalid())
2322 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2323 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2328 case tok::code_completion: {
2329 // Code completion for the operator name.
2330 Actions.CodeCompleteOperatorName(getCurScope());
2332 // Don't try to parse any further.
2340 if (Op != OO_None) {
2341 // We have parsed an operator-function-id.
2342 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2346 // Parse a literal-operator-id.
2348 // literal-operator-id: C++11 [over.literal]
2349 // operator string-literal identifier
2350 // operator user-defined-string-literal
2352 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2353 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2355 SourceLocation DiagLoc;
2356 unsigned DiagId = 0;
2358 // We're past translation phase 6, so perform string literal concatenation
2359 // before checking for "".
2360 SmallVector<Token, 4> Toks;
2361 SmallVector<SourceLocation, 4> TokLocs;
2362 while (isTokenStringLiteral()) {
2363 if (!Tok.is(tok::string_literal) && !DiagId) {
2364 // C++11 [over.literal]p1:
2365 // The string-literal or user-defined-string-literal in a
2366 // literal-operator-id shall have no encoding-prefix [...].
2367 DiagLoc = Tok.getLocation();
2368 DiagId = diag::err_literal_operator_string_prefix;
2370 Toks.push_back(Tok);
2371 TokLocs.push_back(ConsumeStringToken());
2374 StringLiteralParser Literal(Toks, PP);
2375 if (Literal.hadError)
2378 // Grab the literal operator's suffix, which will be either the next token
2379 // or a ud-suffix from the string literal.
2380 IdentifierInfo *II = nullptr;
2381 SourceLocation SuffixLoc;
2382 if (!Literal.getUDSuffix().empty()) {
2383 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2385 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2386 Literal.getUDSuffixOffset(),
2387 PP.getSourceManager(), getLangOpts());
2388 } else if (Tok.is(tok::identifier)) {
2389 II = Tok.getIdentifierInfo();
2390 SuffixLoc = ConsumeToken();
2391 TokLocs.push_back(SuffixLoc);
2393 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2397 // The string literal must be empty.
2398 if (!Literal.GetString().empty() || Literal.Pascal) {
2399 // C++11 [over.literal]p1:
2400 // The string-literal or user-defined-string-literal in a
2401 // literal-operator-id shall [...] contain no characters
2402 // other than the implicit terminating '\0'.
2403 DiagLoc = TokLocs.front();
2404 DiagId = diag::err_literal_operator_string_not_empty;
2408 // This isn't a valid literal-operator-id, but we think we know
2409 // what the user meant. Tell them what they should have written.
2410 SmallString<32> Str;
2412 Str += II->getName();
2413 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2414 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2417 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2419 return Actions.checkLiteralOperatorId(SS, Result);
2422 // Parse a conversion-function-id.
2424 // conversion-function-id: [C++ 12.3.2]
2425 // operator conversion-type-id
2427 // conversion-type-id:
2428 // type-specifier-seq conversion-declarator[opt]
2430 // conversion-declarator:
2431 // ptr-operator conversion-declarator[opt]
2433 // Parse the type-specifier-seq.
2434 DeclSpec DS(AttrFactory);
2435 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2438 // Parse the conversion-declarator, which is merely a sequence of
2440 Declarator D(DS, DeclaratorContext::ConversionIdContext);
2441 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2443 // Finish up the type.
2444 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2448 // Note that this is a conversion-function-id.
2449 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2450 D.getSourceRange().getEnd());
2454 /// Parse a C++ unqualified-id (or a C identifier), which describes the
2455 /// name of an entity.
2458 /// unqualified-id: [C++ expr.prim.general]
2460 /// operator-function-id
2461 /// conversion-function-id
2462 /// [C++0x] literal-operator-id [TODO]
2468 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2469 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2471 /// \param EnteringContext whether we are entering the scope of the
2472 /// nested-name-specifier.
2474 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2476 /// \param AllowConstructorName whether we allow parsing a constructor name.
2478 /// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2480 /// \param ObjectType if this unqualified-id occurs within a member access
2481 /// expression, the type of the base object whose member is being accessed.
2483 /// \param Result on a successful parse, contains the parsed unqualified-id.
2485 /// \returns true if parsing fails, false otherwise.
2486 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2487 bool AllowDestructorName,
2488 bool AllowConstructorName,
2489 bool AllowDeductionGuide,
2490 ParsedType ObjectType,
2491 SourceLocation *TemplateKWLoc,
2492 UnqualifiedId &Result) {
2494 *TemplateKWLoc = SourceLocation();
2496 // Handle 'A::template B'. This is for template-ids which have not
2497 // already been annotated by ParseOptionalCXXScopeSpecifier().
2498 bool TemplateSpecified = false;
2499 if (Tok.is(tok::kw_template)) {
2500 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2501 TemplateSpecified = true;
2502 *TemplateKWLoc = ConsumeToken();
2504 SourceLocation TemplateLoc = ConsumeToken();
2505 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2506 << FixItHint::CreateRemoval(TemplateLoc);
2512 // template-id (when it hasn't already been annotated)
2513 if (Tok.is(tok::identifier)) {
2514 // Consume the identifier.
2515 IdentifierInfo *Id = Tok.getIdentifierInfo();
2516 SourceLocation IdLoc = ConsumeToken();
2518 if (!getLangOpts().CPlusPlus) {
2519 // If we're not in C++, only identifiers matter. Record the
2520 // identifier and return.
2521 Result.setIdentifier(Id, IdLoc);
2525 ParsedTemplateTy TemplateName;
2526 if (AllowConstructorName &&
2527 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2528 // We have parsed a constructor name.
2529 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2533 Result.setConstructorName(Ty, IdLoc, IdLoc);
2534 } else if (getLangOpts().CPlusPlus17 &&
2535 AllowDeductionGuide && SS.isEmpty() &&
2536 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2538 // We have parsed a template-name naming a deduction guide.
2539 Result.setDeductionGuideName(TemplateName, IdLoc);
2541 // We have parsed an identifier.
2542 Result.setIdentifier(Id, IdLoc);
2545 // If the next token is a '<', we may have a template.
2546 TemplateTy Template;
2547 if (Tok.is(tok::less))
2548 return ParseUnqualifiedIdTemplateId(
2549 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2550 EnteringContext, ObjectType, Result, TemplateSpecified);
2551 else if (TemplateSpecified &&
2552 Actions.ActOnDependentTemplateName(
2553 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2554 EnteringContext, Template,
2555 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2562 // template-id (already parsed and annotated)
2563 if (Tok.is(tok::annot_template_id)) {
2564 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2566 // If the template-name names the current class, then this is a constructor
2567 if (AllowConstructorName && TemplateId->Name &&
2568 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2570 // C++ [class.qual]p2 specifies that a qualified template-name
2571 // is taken as the constructor name where a constructor can be
2572 // declared. Thus, the template arguments are extraneous, so
2573 // complain about them and remove them entirely.
2574 Diag(TemplateId->TemplateNameLoc,
2575 diag::err_out_of_line_constructor_template_id)
2577 << FixItHint::CreateRemoval(
2578 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2579 ParsedType Ty = Actions.getConstructorName(
2580 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2584 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2585 TemplateId->RAngleLoc);
2586 ConsumeAnnotationToken();
2590 Result.setConstructorTemplateId(TemplateId);
2591 ConsumeAnnotationToken();
2595 // We have already parsed a template-id; consume the annotation token as
2596 // our unqualified-id.
2597 Result.setTemplateId(TemplateId);
2598 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2599 if (TemplateLoc.isValid()) {
2600 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2601 *TemplateKWLoc = TemplateLoc;
2603 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2604 << FixItHint::CreateRemoval(TemplateLoc);
2606 ConsumeAnnotationToken();
2611 // operator-function-id
2612 // conversion-function-id
2613 if (Tok.is(tok::kw_operator)) {
2614 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2617 // If we have an operator-function-id or a literal-operator-id and the next
2618 // token is a '<', we may have a
2621 // operator-function-id < template-argument-list[opt] >
2622 TemplateTy Template;
2623 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2624 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
2626 return ParseUnqualifiedIdTemplateId(
2627 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2628 SourceLocation(), EnteringContext, ObjectType, Result,
2630 else if (TemplateSpecified &&
2631 Actions.ActOnDependentTemplateName(
2632 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2633 EnteringContext, Template,
2634 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2640 if (getLangOpts().CPlusPlus &&
2641 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2642 // C++ [expr.unary.op]p10:
2643 // There is an ambiguity in the unary-expression ~X(), where X is a
2644 // class-name. The ambiguity is resolved in favor of treating ~ as a
2645 // unary complement rather than treating ~X as referring to a destructor.
2648 SourceLocation TildeLoc = ConsumeToken();
2650 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2651 DeclSpec DS(AttrFactory);
2652 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2653 if (ParsedType Type =
2654 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2655 Result.setDestructorName(TildeLoc, Type, EndLoc);
2661 // Parse the class-name.
2662 if (Tok.isNot(tok::identifier)) {
2663 Diag(Tok, diag::err_destructor_tilde_identifier);
2667 // If the user wrote ~T::T, correct it to T::~T.
2668 DeclaratorScopeObj DeclScopeObj(*this, SS);
2669 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2670 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2671 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2672 // it will confuse this recovery logic.
2673 ColonProtectionRAIIObject ColonRAII(*this, false);
2676 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2679 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2681 if (SS.isNotEmpty())
2682 ObjectType = nullptr;
2683 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2685 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2689 // Recover as if the tilde had been written before the identifier.
2690 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2691 << FixItHint::CreateRemoval(TildeLoc)
2692 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2694 // Temporarily enter the scope for the rest of this function.
2695 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2696 DeclScopeObj.EnterDeclaratorScope();
2699 // Parse the class-name (or template-name in a simple-template-id).
2700 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2701 SourceLocation ClassNameLoc = ConsumeToken();
2703 if (Tok.is(tok::less)) {
2704 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2705 return ParseUnqualifiedIdTemplateId(
2706 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2707 ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
2710 // Note that this is a destructor name.
2711 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2712 ClassNameLoc, getCurScope(),
2718 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2722 Diag(Tok, diag::err_expected_unqualified_id)
2723 << getLangOpts().CPlusPlus;
2727 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2728 /// memory in a typesafe manner and call constructors.
2730 /// This method is called to parse the new expression after the optional :: has
2731 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2732 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2735 /// '::'[opt] 'new' new-placement[opt] new-type-id
2736 /// new-initializer[opt]
2737 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2738 /// new-initializer[opt]
2741 /// '(' expression-list ')'
2744 /// type-specifier-seq new-declarator[opt]
2745 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2748 /// ptr-operator new-declarator[opt]
2749 /// direct-new-declarator
2751 /// new-initializer:
2752 /// '(' expression-list[opt] ')'
2753 /// [C++0x] braced-init-list
2756 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2757 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2758 ConsumeToken(); // Consume 'new'
2760 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2761 // second form of new-expression. It can't be a new-type-id.
2763 ExprVector PlacementArgs;
2764 SourceLocation PlacementLParen, PlacementRParen;
2766 SourceRange TypeIdParens;
2767 DeclSpec DS(AttrFactory);
2768 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
2769 if (Tok.is(tok::l_paren)) {
2770 // If it turns out to be a placement, we change the type location.
2771 BalancedDelimiterTracker T(*this, tok::l_paren);
2773 PlacementLParen = T.getOpenLocation();
2774 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2775 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2780 PlacementRParen = T.getCloseLocation();
2781 if (PlacementRParen.isInvalid()) {
2782 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2786 if (PlacementArgs.empty()) {
2787 // Reset the placement locations. There was no placement.
2788 TypeIdParens = T.getRange();
2789 PlacementLParen = PlacementRParen = SourceLocation();
2791 // We still need the type.
2792 if (Tok.is(tok::l_paren)) {
2793 BalancedDelimiterTracker T(*this, tok::l_paren);
2795 MaybeParseGNUAttributes(DeclaratorInfo);
2796 ParseSpecifierQualifierList(DS);
2797 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2798 ParseDeclarator(DeclaratorInfo);
2800 TypeIdParens = T.getRange();
2802 MaybeParseGNUAttributes(DeclaratorInfo);
2803 if (ParseCXXTypeSpecifierSeq(DS))
2804 DeclaratorInfo.setInvalidType(true);
2806 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2807 ParseDeclaratorInternal(DeclaratorInfo,
2808 &Parser::ParseDirectNewDeclarator);
2813 // A new-type-id is a simplified type-id, where essentially the
2814 // direct-declarator is replaced by a direct-new-declarator.
2815 MaybeParseGNUAttributes(DeclaratorInfo);
2816 if (ParseCXXTypeSpecifierSeq(DS))
2817 DeclaratorInfo.setInvalidType(true);
2819 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2820 ParseDeclaratorInternal(DeclaratorInfo,
2821 &Parser::ParseDirectNewDeclarator);
2824 if (DeclaratorInfo.isInvalidType()) {
2825 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2829 ExprResult Initializer;
2831 if (Tok.is(tok::l_paren)) {
2832 SourceLocation ConstructorLParen, ConstructorRParen;
2833 ExprVector ConstructorArgs;
2834 BalancedDelimiterTracker T(*this, tok::l_paren);
2836 ConstructorLParen = T.getOpenLocation();
2837 if (Tok.isNot(tok::r_paren)) {
2838 CommaLocsTy CommaLocs;
2839 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2840 ParsedType TypeRep =
2841 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
2842 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2843 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
2844 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
2845 CalledSignatureHelp = true;
2846 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
2848 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2849 ParsedType TypeRep =
2850 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
2851 Actions.ProduceConstructorSignatureHelp(
2852 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
2853 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
2854 CalledSignatureHelp = true;
2856 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2861 ConstructorRParen = T.getCloseLocation();
2862 if (ConstructorRParen.isInvalid()) {
2863 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2866 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2869 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2870 Diag(Tok.getLocation(),
2871 diag::warn_cxx98_compat_generalized_initializer_lists);
2872 Initializer = ParseBraceInitializer();
2874 if (Initializer.isInvalid())
2877 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2878 PlacementArgs, PlacementRParen,
2879 TypeIdParens, DeclaratorInfo, Initializer.get());
2882 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2883 /// passed to ParseDeclaratorInternal.
2885 /// direct-new-declarator:
2886 /// '[' expression ']'
2887 /// direct-new-declarator '[' constant-expression ']'
2889 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2890 // Parse the array dimensions.
2892 while (Tok.is(tok::l_square)) {
2893 // An array-size expression can't start with a lambda.
2894 if (CheckProhibitedCXX11Attribute())
2897 BalancedDelimiterTracker T(*this, tok::l_square);
2900 ExprResult Size(first ? ParseExpression()
2901 : ParseConstantExpression());
2902 if (Size.isInvalid()) {
2904 SkipUntil(tok::r_square, StopAtSemi);
2911 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2912 ParsedAttributes Attrs(AttrFactory);
2913 MaybeParseCXX11Attributes(Attrs);
2915 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2916 /*static=*/false, /*star=*/false,
2917 Size.get(), T.getOpenLocation(),
2918 T.getCloseLocation()),
2919 std::move(Attrs), T.getCloseLocation());
2921 if (T.getCloseLocation().isInvalid())
2926 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2927 /// This ambiguity appears in the syntax of the C++ new operator.
2930 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2931 /// new-initializer[opt]
2934 /// '(' expression-list ')'
2936 bool Parser::ParseExpressionListOrTypeId(
2937 SmallVectorImpl<Expr*> &PlacementArgs,
2939 // The '(' was already consumed.
2940 if (isTypeIdInParens()) {
2941 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2942 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2944 return D.isInvalidType();
2947 // It's not a type, it has to be an expression list.
2948 // Discard the comma locations - ActOnCXXNew has enough parameters.
2949 CommaLocsTy CommaLocs;
2950 return ParseExpressionList(PlacementArgs, CommaLocs);
2953 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2954 /// to free memory allocated by new.
2956 /// This method is called to parse the 'delete' expression after the optional
2957 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2958 /// and "Start" is its location. Otherwise, "Start" is the location of the
2961 /// delete-expression:
2962 /// '::'[opt] 'delete' cast-expression
2963 /// '::'[opt] 'delete' '[' ']' cast-expression
2965 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2966 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2967 ConsumeToken(); // Consume 'delete'
2970 bool ArrayDelete = false;
2971 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2972 // C++11 [expr.delete]p1:
2973 // Whenever the delete keyword is followed by empty square brackets, it
2974 // shall be interpreted as [array delete].
2975 // [Footnote: A lambda expression with a lambda-introducer that consists
2976 // of empty square brackets can follow the delete keyword if
2977 // the lambda expression is enclosed in parentheses.]
2978 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2979 // lambda-introducer.
2981 BalancedDelimiterTracker T(*this, tok::l_square);
2985 if (T.getCloseLocation().isInvalid())
2989 ExprResult Operand(ParseCastExpression(false));
2990 if (Operand.isInvalid())
2993 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2996 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2998 default: llvm_unreachable("Not a known type trait");
2999 #define TYPE_TRAIT_1(Spelling, Name, Key) \
3000 case tok::kw_ ## Spelling: return UTT_ ## Name;
3001 #define TYPE_TRAIT_2(Spelling, Name, Key) \
3002 case tok::kw_ ## Spelling: return BTT_ ## Name;
3003 #include "clang/Basic/TokenKinds.def"
3004 #define TYPE_TRAIT_N(Spelling, Name, Key) \
3005 case tok::kw_ ## Spelling: return TT_ ## Name;
3006 #include "clang/Basic/TokenKinds.def"
3010 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3012 default: llvm_unreachable("Not a known binary type trait");
3013 case tok::kw___array_rank: return ATT_ArrayRank;
3014 case tok::kw___array_extent: return ATT_ArrayExtent;
3018 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3020 default: llvm_unreachable("Not a known unary expression trait.");
3021 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
3022 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
3026 static unsigned TypeTraitArity(tok::TokenKind kind) {
3028 default: llvm_unreachable("Not a known type trait");
3029 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3030 #include "clang/Basic/TokenKinds.def"
3034 /// Parse the built-in type-trait pseudo-functions that allow
3035 /// implementation of the TR1/C++11 type traits templates.
3037 /// primary-expression:
3038 /// unary-type-trait '(' type-id ')'
3039 /// binary-type-trait '(' type-id ',' type-id ')'
3040 /// type-trait '(' type-id-seq ')'
3043 /// type-id ...[opt] type-id-seq[opt]
3045 ExprResult Parser::ParseTypeTrait() {
3046 tok::TokenKind Kind = Tok.getKind();
3047 unsigned Arity = TypeTraitArity(Kind);
3049 SourceLocation Loc = ConsumeToken();
3051 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3052 if (Parens.expectAndConsume())
3055 SmallVector<ParsedType, 2> Args;
3057 // Parse the next type.
3058 TypeResult Ty = ParseTypeName();
3059 if (Ty.isInvalid()) {
3064 // Parse the ellipsis, if present.
3065 if (Tok.is(tok::ellipsis)) {
3066 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3067 if (Ty.isInvalid()) {
3073 // Add this type to the list of arguments.
3074 Args.push_back(Ty.get());
3075 } while (TryConsumeToken(tok::comma));
3077 if (Parens.consumeClose())
3080 SourceLocation EndLoc = Parens.getCloseLocation();
3082 if (Arity && Args.size() != Arity) {
3083 Diag(EndLoc, diag::err_type_trait_arity)
3084 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3088 if (!Arity && Args.empty()) {
3089 Diag(EndLoc, diag::err_type_trait_arity)
3090 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3094 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3097 /// ParseArrayTypeTrait - Parse the built-in array type-trait
3098 /// pseudo-functions.
3100 /// primary-expression:
3101 /// [Embarcadero] '__array_rank' '(' type-id ')'
3102 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3104 ExprResult Parser::ParseArrayTypeTrait() {
3105 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3106 SourceLocation Loc = ConsumeToken();
3108 BalancedDelimiterTracker T(*this, tok::l_paren);
3109 if (T.expectAndConsume())
3112 TypeResult Ty = ParseTypeName();
3113 if (Ty.isInvalid()) {
3114 SkipUntil(tok::comma, StopAtSemi);
3115 SkipUntil(tok::r_paren, StopAtSemi);
3120 case ATT_ArrayRank: {
3122 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3123 T.getCloseLocation());
3125 case ATT_ArrayExtent: {
3126 if (ExpectAndConsume(tok::comma)) {
3127 SkipUntil(tok::r_paren, StopAtSemi);
3131 ExprResult DimExpr = ParseExpression();
3134 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3135 T.getCloseLocation());
3138 llvm_unreachable("Invalid ArrayTypeTrait!");
3141 /// ParseExpressionTrait - Parse built-in expression-trait
3142 /// pseudo-functions like __is_lvalue_expr( xxx ).
3144 /// primary-expression:
3145 /// [Embarcadero] expression-trait '(' expression ')'
3147 ExprResult Parser::ParseExpressionTrait() {
3148 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3149 SourceLocation Loc = ConsumeToken();
3151 BalancedDelimiterTracker T(*this, tok::l_paren);
3152 if (T.expectAndConsume())
3155 ExprResult Expr = ParseExpression();
3159 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3160 T.getCloseLocation());
3164 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3165 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3166 /// based on the context past the parens.
3168 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3170 BalancedDelimiterTracker &Tracker,
3171 ColonProtectionRAIIObject &ColonProt) {
3172 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3173 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3174 assert(isTypeIdInParens() && "Not a type-id!");
3176 ExprResult Result(true);
3179 // We need to disambiguate a very ugly part of the C++ syntax:
3181 // (T())x; - type-id
3182 // (T())*x; - type-id
3183 // (T())/x; - expression
3184 // (T()); - expression
3186 // The bad news is that we cannot use the specialized tentative parser, since
3187 // it can only verify that the thing inside the parens can be parsed as
3188 // type-id, it is not useful for determining the context past the parens.
3190 // The good news is that the parser can disambiguate this part without
3191 // making any unnecessary Action calls.
3193 // It uses a scheme similar to parsing inline methods. The parenthesized
3194 // tokens are cached, the context that follows is determined (possibly by
3195 // parsing a cast-expression), and then we re-introduce the cached tokens
3196 // into the token stream and parse them appropriately.
3198 ParenParseOption ParseAs;
3201 // Store the tokens of the parentheses. We will parse them after we determine
3202 // the context that follows them.
3203 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3204 // We didn't find the ')' we expected.
3205 Tracker.consumeClose();
3209 if (Tok.is(tok::l_brace)) {
3210 ParseAs = CompoundLiteral;
3213 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3216 // Try parsing the cast-expression that may follow.
3217 // If it is not a cast-expression, NotCastExpr will be true and no token
3218 // will be consumed.
3219 ColonProt.restore();
3220 Result = ParseCastExpression(false/*isUnaryExpression*/,
3221 false/*isAddressofOperand*/,
3223 // type-id has priority.
3227 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3229 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3232 // Create a fake EOF to mark end of Toks buffer.
3234 AttrEnd.startToken();
3235 AttrEnd.setKind(tok::eof);
3236 AttrEnd.setLocation(Tok.getLocation());
3237 AttrEnd.setEofData(Toks.data());
3238 Toks.push_back(AttrEnd);
3240 // The current token should go after the cached tokens.
3241 Toks.push_back(Tok);
3242 // Re-enter the stored parenthesized tokens into the token stream, so we may
3244 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
3245 // Drop the current token and bring the first cached one. It's the same token
3246 // as when we entered this function.
3249 if (ParseAs >= CompoundLiteral) {
3250 // Parse the type declarator.
3251 DeclSpec DS(AttrFactory);
3252 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
3254 ColonProtectionRAIIObject InnerColonProtection(*this);
3255 ParseSpecifierQualifierList(DS);
3256 ParseDeclarator(DeclaratorInfo);
3260 Tracker.consumeClose();
3261 ColonProt.restore();
3263 // Consume EOF marker for Toks buffer.
3264 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3267 if (ParseAs == CompoundLiteral) {
3268 ExprType = CompoundLiteral;
3269 if (DeclaratorInfo.isInvalidType())
3272 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3273 return ParseCompoundLiteralExpression(Ty.get(),
3274 Tracker.getOpenLocation(),
3275 Tracker.getCloseLocation());
3278 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3279 assert(ParseAs == CastExpr);
3281 if (DeclaratorInfo.isInvalidType())
3284 // Result is what ParseCastExpression returned earlier.
3285 if (!Result.isInvalid())
3286 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3287 DeclaratorInfo, CastTy,
3288 Tracker.getCloseLocation(), Result.get());
3292 // Not a compound literal, and not followed by a cast-expression.
3293 assert(ParseAs == SimpleExpr);
3295 ExprType = SimpleExpr;
3296 Result = ParseExpression();
3297 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3298 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3299 Tok.getLocation(), Result.get());
3302 if (Result.isInvalid()) {
3303 while (Tok.isNot(tok::eof))
3305 assert(Tok.getEofData() == AttrEnd.getEofData());
3310 Tracker.consumeClose();
3311 // Consume EOF marker for Toks buffer.
3312 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());