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 // C++ [basic.lookup.classref]p5:
239 // If the qualified-id has the form
241 // ::class-name-or-namespace-name::...
243 // the class-name-or-namespace-name is looked up in global scope as a
244 // class-name or namespace-name.
246 // To implement this, we clear out the object type as soon as we've
247 // seen a leading '::' or part of a nested-name-specifier.
248 ObjectType = nullptr;
250 if (Tok.is(tok::code_completion)) {
251 // Code completion for a nested-name-specifier, where the code
252 // completion token follows the '::'.
253 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
254 // Include code completion token into the range of the scope otherwise
255 // when we try to annotate the scope tokens the dangling code completion
256 // token will cause assertion in
257 // Preprocessor::AnnotatePreviousCachedTokens.
258 SS.setEndLoc(Tok.getLocation());
264 // nested-name-specifier:
265 // nested-name-specifier 'template'[opt] simple-template-id '::'
267 // Parse the optional 'template' keyword, then make sure we have
268 // 'identifier <' after it.
269 if (Tok.is(tok::kw_template)) {
270 // If we don't have a scope specifier or an object type, this isn't a
271 // nested-name-specifier, since they aren't allowed to start with
273 if (!HasScopeSpecifier && !ObjectType)
276 TentativeParsingAction TPA(*this);
277 SourceLocation TemplateKWLoc = ConsumeToken();
279 UnqualifiedId TemplateName;
280 if (Tok.is(tok::identifier)) {
281 // Consume the identifier.
282 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
284 } else if (Tok.is(tok::kw_operator)) {
285 // We don't need to actually parse the unqualified-id in this case,
286 // because a simple-template-id cannot start with 'operator', but
287 // go ahead and parse it anyway for consistency with the case where
288 // we already annotated the template-id.
289 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
295 if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
296 TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
297 Diag(TemplateName.getSourceRange().getBegin(),
298 diag::err_id_after_template_in_nested_name_spec)
299 << TemplateName.getSourceRange();
308 // If the next token is not '<', we have a qualified-id that refers
309 // to a template name, such as T::template apply, but is not a
311 if (Tok.isNot(tok::less)) {
316 // Commit to parsing the template-id.
319 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
320 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
321 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
322 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
323 TemplateName, false))
331 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
336 // So we need to check whether the template-id is a simple-template-id of
337 // the right kind (it should name a type or be dependent), and then
338 // convert it into a type within the nested-name-specifier.
339 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
340 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
341 *MayBePseudoDestructor = true;
346 *LastII = TemplateId->Name;
348 // Consume the template-id token.
349 ConsumeAnnotationToken();
351 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
352 SourceLocation CCLoc = ConsumeToken();
354 HasScopeSpecifier = true;
356 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
357 TemplateId->NumArgs);
359 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
361 TemplateId->TemplateKWLoc,
362 TemplateId->Template,
363 TemplateId->TemplateNameLoc,
364 TemplateId->LAngleLoc,
366 TemplateId->RAngleLoc,
369 SourceLocation StartLoc
370 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
371 : TemplateId->TemplateNameLoc;
372 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
378 // The rest of the nested-name-specifier possibilities start with
380 if (Tok.isNot(tok::identifier))
383 IdentifierInfo &II = *Tok.getIdentifierInfo();
385 // nested-name-specifier:
387 // namespace-name '::'
388 // nested-name-specifier identifier '::'
389 Token Next = NextToken();
390 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
393 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
394 // and emit a fixit hint for it.
395 if (Next.is(tok::colon) && !ColonIsSacred) {
396 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
398 // If the token after the colon isn't an identifier, it's still an
399 // error, but they probably meant something else strange so don't
400 // recover like this.
401 PP.LookAhead(1).is(tok::identifier)) {
402 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
403 << FixItHint::CreateReplacement(Next.getLocation(), "::");
404 // Recover as if the user wrote '::'.
405 Next.setKind(tok::coloncolon);
409 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
410 // It is invalid to have :: {, consume the scope qualifier and pretend
411 // like we never saw it.
412 Token Identifier = Tok; // Stash away the identifier.
413 ConsumeToken(); // Eat the identifier, current token is now '::'.
414 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
416 UnconsumeToken(Identifier); // Stick the identifier back.
417 Next = NextToken(); // Point Next at the '{' token.
420 if (Next.is(tok::coloncolon)) {
421 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
422 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
423 *MayBePseudoDestructor = true;
428 const Token &Next2 = GetLookAheadToken(2);
429 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
430 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
431 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
433 << FixItHint::CreateReplacement(Next.getLocation(), ":");
436 ColonColon.setKind(tok::colon);
437 PP.EnterToken(ColonColon);
445 // We have an identifier followed by a '::'. Lookup this name
446 // as the name in a nested-name-specifier.
447 Token Identifier = Tok;
448 SourceLocation IdLoc = ConsumeToken();
449 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
450 "NextToken() not working properly!");
451 Token ColonColon = Tok;
452 SourceLocation CCLoc = ConsumeToken();
454 bool IsCorrectedToColon = false;
455 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
456 if (Actions.ActOnCXXNestedNameSpecifier(
457 getCurScope(), IdInfo, EnteringContext, SS, false,
458 CorrectionFlagPtr, OnlyNamespace)) {
459 // Identifier is not recognized as a nested name, but we can have
460 // mistyped '::' instead of ':'.
461 if (CorrectionFlagPtr && IsCorrectedToColon) {
462 ColonColon.setKind(tok::colon);
464 PP.EnterToken(ColonColon);
468 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
470 HasScopeSpecifier = true;
474 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
476 // nested-name-specifier:
478 if (Next.is(tok::less)) {
480 UnqualifiedId TemplateName;
481 TemplateName.setIdentifier(&II, Tok.getLocation());
482 bool MemberOfUnknownSpecialization;
483 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
484 /*hasTemplateKeyword=*/false,
489 MemberOfUnknownSpecialization)) {
490 // We have found a template name, so annotate this token
491 // with a template-id annotation. We do not permit the
492 // template-id to be translated into a type annotation,
493 // because some clients (e.g., the parsing of class template
494 // specializations) still want to see the original template-id
497 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
498 TemplateName, false))
503 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
504 (IsTypename || IsTemplateArgumentList(1))) {
505 // We have something like t::getAs<T>, where getAs is a
506 // member of an unknown specialization. However, this will only
507 // parse correctly as a template, so suggest the keyword 'template'
508 // before 'getAs' and treat this as a dependent template name.
509 unsigned DiagID = diag::err_missing_dependent_template_keyword;
510 if (getLangOpts().MicrosoftExt)
511 DiagID = diag::warn_missing_dependent_template_keyword;
513 Diag(Tok.getLocation(), DiagID)
515 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
517 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
518 getCurScope(), SS, Tok.getLocation(), TemplateName, ObjectType,
519 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
520 // Consume the identifier.
522 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
523 TemplateName, false))
533 // We don't have any tokens that form the beginning of a
534 // nested-name-specifier, so we're done.
538 // Even if we didn't see any pieces of a nested-name-specifier, we
539 // still check whether there is a tilde in this position, which
540 // indicates a potential pseudo-destructor.
541 if (CheckForDestructor && Tok.is(tok::tilde))
542 *MayBePseudoDestructor = true;
547 ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
548 Token &Replacement) {
549 SourceLocation TemplateKWLoc;
551 if (ParseUnqualifiedId(SS,
552 /*EnteringContext=*/false,
553 /*AllowDestructorName=*/false,
554 /*AllowConstructorName=*/false,
555 /*AllowDeductionGuide=*/false,
556 /*ObjectType=*/nullptr, &TemplateKWLoc, Name))
559 // This is only the direct operand of an & operator if it is not
560 // followed by a postfix-expression suffix.
561 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
562 isAddressOfOperand = false;
564 ExprResult E = Actions.ActOnIdExpression(
565 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
566 isAddressOfOperand, nullptr, /*IsInlineAsmIdentifier=*/false,
568 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
569 checkPotentialAngleBracket(E);
573 /// ParseCXXIdExpression - Handle id-expression.
580 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
582 /// '::' operator-function-id
585 /// NOTE: The standard specifies that, for qualified-id, the parser does not
588 /// '::' conversion-function-id
589 /// '::' '~' class-name
591 /// This may cause a slight inconsistency on diagnostics:
596 /// :: A :: ~ C(); // Some Sema error about using destructor with a
598 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
601 /// We simplify the parser a bit and make it work like:
604 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
605 /// '::' unqualified-id
607 /// That way Sema can handle and report similar errors for namespaces and the
610 /// The isAddressOfOperand parameter indicates that this id-expression is a
611 /// direct operand of the address-of operator. This is, besides member contexts,
612 /// the only place where a qualified-id naming a non-static class member may
615 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
617 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
618 // '::' unqualified-id
621 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
625 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
626 if (Result.isUnset()) {
627 // If the ExprResult is valid but null, then typo correction suggested a
628 // keyword replacement that needs to be reparsed.
629 UnconsumeToken(Replacement);
630 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
632 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
633 "for a previous keyword suggestion");
637 /// ParseLambdaExpression - Parse a C++11 lambda expression.
639 /// lambda-expression:
640 /// lambda-introducer lambda-declarator[opt] compound-statement
642 /// lambda-introducer:
643 /// '[' lambda-capture[opt] ']'
648 /// capture-default ',' capture-list
656 /// capture-list ',' capture
660 /// init-capture [C++1y]
667 /// init-capture: [C++1y]
668 /// identifier initializer
669 /// '&' identifier initializer
671 /// lambda-declarator:
672 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
673 /// 'mutable'[opt] exception-specification[opt]
674 /// trailing-return-type[opt]
676 ExprResult Parser::ParseLambdaExpression() {
677 // Parse lambda-introducer.
678 LambdaIntroducer Intro;
679 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
681 Diag(Tok, DiagID.getValue());
682 SkipUntil(tok::r_square, StopAtSemi);
683 SkipUntil(tok::l_brace, StopAtSemi);
684 SkipUntil(tok::r_brace, StopAtSemi);
688 return ParseLambdaExpressionAfterIntroducer(Intro);
691 /// TryParseLambdaExpression - Use lookahead and potentially tentative
692 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
695 /// If we are not looking at a lambda expression, returns ExprError().
696 ExprResult Parser::TryParseLambdaExpression() {
697 assert(getLangOpts().CPlusPlus11
698 && Tok.is(tok::l_square)
699 && "Not at the start of a possible lambda expression.");
701 const Token Next = NextToken();
702 if (Next.is(tok::eof)) // Nothing else to lookup here...
705 const Token After = GetLookAheadToken(2);
706 // If lookahead indicates this is a lambda...
707 if (Next.is(tok::r_square) || // []
708 Next.is(tok::equal) || // [=
709 (Next.is(tok::amp) && // [&] or [&,
710 (After.is(tok::r_square) ||
711 After.is(tok::comma))) ||
712 (Next.is(tok::identifier) && // [identifier]
713 After.is(tok::r_square))) {
714 return ParseLambdaExpression();
717 // If lookahead indicates an ObjC message send...
718 // [identifier identifier
719 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
723 // Here, we're stuck: lambda introducers and Objective-C message sends are
724 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
725 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
726 // writing two routines to parse a lambda introducer, just try to parse
727 // a lambda introducer first, and fall back if that fails.
728 // (TryParseLambdaIntroducer never produces any diagnostic output.)
729 LambdaIntroducer Intro;
730 if (TryParseLambdaIntroducer(Intro))
733 return ParseLambdaExpressionAfterIntroducer(Intro);
736 /// Parse a lambda introducer.
737 /// \param Intro A LambdaIntroducer filled in with information about the
738 /// contents of the lambda-introducer.
739 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
740 /// message send and a lambda expression. In this mode, we will
741 /// sometimes skip the initializers for init-captures and not fully
742 /// populate \p Intro. This flag will be set to \c true if we do so.
743 /// \return A DiagnosticID if it hit something unexpected. The location for
744 /// the diagnostic is that of the current token.
745 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
746 bool *SkippedInits) {
747 typedef Optional<unsigned> DiagResult;
749 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
750 BalancedDelimiterTracker T(*this, tok::l_square);
753 Intro.Range.setBegin(T.getOpenLocation());
757 // Parse capture-default.
758 if (Tok.is(tok::amp) &&
759 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
760 Intro.Default = LCD_ByRef;
761 Intro.DefaultLoc = ConsumeToken();
763 } else if (Tok.is(tok::equal)) {
764 Intro.Default = LCD_ByCopy;
765 Intro.DefaultLoc = ConsumeToken();
769 while (Tok.isNot(tok::r_square)) {
771 if (Tok.isNot(tok::comma)) {
772 // Provide a completion for a lambda introducer here. Except
773 // in Objective-C, where this is Almost Surely meant to be a message
774 // send. In that case, fail here and let the ObjC message
775 // expression parser perform the completion.
776 if (Tok.is(tok::code_completion) &&
777 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
778 !Intro.Captures.empty())) {
779 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
780 /*AfterAmpersand=*/false);
785 return DiagResult(diag::err_expected_comma_or_rsquare);
790 if (Tok.is(tok::code_completion)) {
791 // If we're in Objective-C++ and we have a bare '[', then this is more
792 // likely to be a message receiver.
793 if (getLangOpts().ObjC1 && first)
794 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
796 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
797 /*AfterAmpersand=*/false);
805 LambdaCaptureKind Kind = LCK_ByCopy;
806 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
808 IdentifierInfo *Id = nullptr;
809 SourceLocation EllipsisLoc;
811 SourceLocation LocStart = Tok.getLocation();
813 if (Tok.is(tok::star)) {
814 Loc = ConsumeToken();
815 if (Tok.is(tok::kw_this)) {
819 return DiagResult(diag::err_expected_star_this_capture);
821 } else if (Tok.is(tok::kw_this)) {
823 Loc = ConsumeToken();
825 if (Tok.is(tok::amp)) {
829 if (Tok.is(tok::code_completion)) {
830 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
831 /*AfterAmpersand=*/true);
837 if (Tok.is(tok::identifier)) {
838 Id = Tok.getIdentifierInfo();
839 Loc = ConsumeToken();
840 } else if (Tok.is(tok::kw_this)) {
841 // FIXME: If we want to suggest a fixit here, will need to return more
842 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
843 // Clear()ed to prevent emission in case of tentative parsing?
844 return DiagResult(diag::err_this_captured_by_reference);
846 return DiagResult(diag::err_expected_capture);
849 if (Tok.is(tok::l_paren)) {
850 BalancedDelimiterTracker Parens(*this, tok::l_paren);
851 Parens.consumeOpen();
853 InitKind = LambdaCaptureInitKind::DirectInit;
859 *SkippedInits = true;
860 } else if (ParseExpressionList(Exprs, Commas)) {
864 Parens.consumeClose();
865 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
866 Parens.getCloseLocation(),
869 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
870 // Each lambda init-capture forms its own full expression, which clears
871 // Actions.MaybeODRUseExprs. So create an expression evaluation context
872 // to save the necessary state, and restore it later.
873 EnterExpressionEvaluationContext EC(
874 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
876 if (TryConsumeToken(tok::equal))
877 InitKind = LambdaCaptureInitKind::CopyInit;
879 InitKind = LambdaCaptureInitKind::ListInit;
882 Init = ParseInitializer();
883 } else if (Tok.is(tok::l_brace)) {
884 BalancedDelimiterTracker Braces(*this, tok::l_brace);
885 Braces.consumeOpen();
887 *SkippedInits = true;
889 // We're disambiguating this:
893 // We need to find the end of the following expression in order to
894 // determine whether this is an Obj-C message send's receiver, a
895 // C99 designator, or a lambda init-capture.
897 // Parse the expression to find where it ends, and annotate it back
898 // onto the tokens. We would have parsed this expression the same way
899 // in either case: both the RHS of an init-capture and the RHS of an
900 // assignment expression are parsed as an initializer-clause, and in
901 // neither case can anything be added to the scope between the '[' and
904 // FIXME: This is horrible. Adding a mechanism to skip an expression
905 // would be much cleaner.
906 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
907 // that instead. (And if we see a ':' with no matching '?', we can
908 // classify this as an Obj-C message send.)
909 SourceLocation StartLoc = Tok.getLocation();
910 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
911 Init = ParseInitializer();
912 if (!Init.isInvalid())
913 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
915 if (Tok.getLocation() != StartLoc) {
916 // Back out the lexing of the token after the initializer.
917 PP.RevertCachedTokens(1);
919 // Replace the consumed tokens with an appropriate annotation.
920 Tok.setLocation(StartLoc);
921 Tok.setKind(tok::annot_primary_expr);
922 setExprAnnotation(Tok, Init);
923 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
924 PP.AnnotateCachedTokens(Tok);
926 // Consume the annotated initializer.
927 ConsumeAnnotationToken();
931 TryConsumeToken(tok::ellipsis, EllipsisLoc);
933 // If this is an init capture, process the initialization expression
934 // right away. For lambda init-captures such as the following:
936 // auto L = [i = x+1](int a) {
938 // &k = x](char b) { };
940 // keep in mind that each lambda init-capture has to have:
941 // - its initialization expression executed in the context
942 // of the enclosing/parent decl-context.
943 // - but the variable itself has to be 'injected' into the
944 // decl-context of its lambda's call-operator (which has
945 // not yet been created).
946 // Each init-expression is a full-expression that has to get
947 // Sema-analyzed (for capturing etc.) before its lambda's
948 // call-operator's decl-context, scope & scopeinfo are pushed on their
949 // respective stacks. Thus if any variable is odr-used in the init-capture
950 // it will correctly get captured in the enclosing lambda, if one exists.
951 // The init-variables above are created later once the lambdascope and
952 // call-operators decl-context is pushed onto its respective stack.
954 // Since the lambda init-capture's initializer expression occurs in the
955 // context of the enclosing function or lambda, therefore we can not wait
956 // till a lambda scope has been pushed on before deciding whether the
957 // variable needs to be captured. We also need to process all
958 // lvalue-to-rvalue conversions and discarded-value conversions,
959 // so that we can avoid capturing certain constant variables.
963 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
964 // return [y = x](int i) { <-- don't capture by enclosing lambda
969 // If x was not const, the second use would require 'L' to capture, and
970 // that would be an error.
972 ParsedType InitCaptureType;
973 if (!Init.isInvalid())
974 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
975 if (Init.isUsable()) {
976 // Get the pointer and store it in an lvalue, so we can use it as an
978 Expr *InitExpr = Init.get();
979 // This performs any lvalue-to-rvalue conversions if necessary, which
980 // can affect what gets captured in the containing decl-context.
981 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
982 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
986 SourceLocation LocEnd = PrevTokLocation;
988 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
989 InitCaptureType, SourceRange(LocStart, LocEnd));
993 Intro.Range.setEnd(T.getCloseLocation());
997 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
999 /// Returns true if it hit something unexpected.
1000 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1002 bool SkippedInits = false;
1003 TentativeParsingAction PA1(*this);
1005 if (ParseLambdaIntroducer(Intro, &SkippedInits)) {
1010 if (!SkippedInits) {
1018 // Try to parse it again, but this time parse the init-captures too.
1019 Intro = LambdaIntroducer();
1020 TentativeParsingAction PA2(*this);
1022 if (!ParseLambdaIntroducer(Intro)) {
1032 tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1033 SourceLocation &ConstexprLoc,
1034 SourceLocation &DeclEndLoc) {
1035 assert(MutableLoc.isInvalid());
1036 assert(ConstexprLoc.isInvalid());
1037 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1038 // to the final of those locations. Emit an error if we have multiple
1039 // copies of those keywords and recover.
1042 switch (P.getCurToken().getKind()) {
1043 case tok::kw_mutable: {
1044 if (MutableLoc.isValid()) {
1045 P.Diag(P.getCurToken().getLocation(),
1046 diag::err_lambda_decl_specifier_repeated)
1047 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1049 MutableLoc = P.ConsumeToken();
1050 DeclEndLoc = MutableLoc;
1053 case tok::kw_constexpr:
1054 if (ConstexprLoc.isValid()) {
1055 P.Diag(P.getCurToken().getLocation(),
1056 diag::err_lambda_decl_specifier_repeated)
1057 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1059 ConstexprLoc = P.ConsumeToken();
1060 DeclEndLoc = ConstexprLoc;
1069 addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1071 if (ConstexprLoc.isValid()) {
1072 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1073 ? diag::ext_constexpr_on_lambda_cxx17
1074 : diag::warn_cxx14_compat_constexpr_on_lambda);
1075 const char *PrevSpec = nullptr;
1076 unsigned DiagID = 0;
1077 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1078 assert(PrevSpec == nullptr && DiagID == 0 &&
1079 "Constexpr cannot have been set previously!");
1083 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1085 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1086 LambdaIntroducer &Intro) {
1087 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1088 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1090 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1091 "lambda expression parsing");
1095 // FIXME: Call into Actions to add any init-capture declarations to the
1096 // scope while parsing the lambda-declarator and compound-statement.
1098 // Parse lambda-declarator[opt].
1099 DeclSpec DS(AttrFactory);
1100 Declarator D(DS, DeclaratorContext::LambdaExprContext);
1101 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1102 Actions.PushLambdaScope();
1104 ParsedAttributes Attr(AttrFactory);
1105 SourceLocation DeclLoc = Tok.getLocation();
1106 if (getLangOpts().CUDA) {
1107 // In CUDA code, GNU attributes are allowed to appear immediately after the
1108 // "[...]", even if there is no "(...)" before the lambda body.
1109 MaybeParseGNUAttributes(D);
1112 // Helper to emit a warning if we see a CUDA host/device/global attribute
1113 // after '(...)'. nvcc doesn't accept this.
1114 auto WarnIfHasCUDATargetAttr = [&] {
1115 if (getLangOpts().CUDA)
1116 for (const ParsedAttr &A : Attr)
1117 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1118 A.getKind() == ParsedAttr::AT_CUDAHost ||
1119 A.getKind() == ParsedAttr::AT_CUDAGlobal)
1120 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1121 << A.getName()->getName();
1124 TypeResult TrailingReturnType;
1125 if (Tok.is(tok::l_paren)) {
1126 ParseScope PrototypeScope(this,
1127 Scope::FunctionPrototypeScope |
1128 Scope::FunctionDeclarationScope |
1131 BalancedDelimiterTracker T(*this, tok::l_paren);
1133 SourceLocation LParenLoc = T.getOpenLocation();
1135 // Parse parameter-declaration-clause.
1136 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1137 SourceLocation EllipsisLoc;
1139 if (Tok.isNot(tok::r_paren)) {
1140 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1141 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1142 // For a generic lambda, each 'auto' within the parameter declaration
1143 // clause creates a template type parameter, so increment the depth.
1144 if (Actions.getCurGenericLambda())
1145 ++CurTemplateDepthTracker;
1148 SourceLocation RParenLoc = T.getCloseLocation();
1149 SourceLocation DeclEndLoc = RParenLoc;
1151 // GNU-style attributes must be parsed before the mutable specifier to be
1152 // compatible with GCC.
1153 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1155 // MSVC-style attributes must be parsed before the mutable specifier to be
1156 // compatible with MSVC.
1157 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1159 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
1160 SourceLocation MutableLoc;
1161 SourceLocation ConstexprLoc;
1162 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1165 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1167 // Parse exception-specification[opt].
1168 ExceptionSpecificationType ESpecType = EST_None;
1169 SourceRange ESpecRange;
1170 SmallVector<ParsedType, 2> DynamicExceptions;
1171 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1172 ExprResult NoexceptExpr;
1173 CachedTokens *ExceptionSpecTokens;
1174 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1177 DynamicExceptionRanges,
1179 ExceptionSpecTokens);
1181 if (ESpecType != EST_None)
1182 DeclEndLoc = ESpecRange.getEnd();
1184 // Parse attribute-specifier[opt].
1185 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1187 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1189 // Parse trailing-return-type[opt].
1190 if (Tok.is(tok::arrow)) {
1191 FunLocalRangeEnd = Tok.getLocation();
1193 TrailingReturnType =
1194 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1195 if (Range.getEnd().isValid())
1196 DeclEndLoc = Range.getEnd();
1199 PrototypeScope.Exit();
1201 WarnIfHasCUDATargetAttr();
1203 SourceLocation NoLoc;
1204 D.AddTypeInfo(DeclaratorChunk::getFunction(
1206 /*isAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1207 ParamInfo.size(), EllipsisLoc, RParenLoc,
1208 DS.getTypeQualifiers(),
1209 /*RefQualifierIsLValueRef=*/true,
1210 /*RefQualifierLoc=*/NoLoc,
1211 /*ConstQualifierLoc=*/NoLoc,
1212 /*VolatileQualifierLoc=*/NoLoc,
1213 /*RestrictQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
1214 ESpecRange, DynamicExceptions.data(),
1215 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1216 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1217 /*ExceptionSpecTokens*/ nullptr,
1218 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1219 TrailingReturnType),
1220 std::move(Attr), DeclEndLoc);
1221 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1222 tok::kw_constexpr) ||
1223 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1224 // It's common to forget that one needs '()' before 'mutable', an attribute
1225 // specifier, or the result type. Deal with this.
1226 unsigned TokKind = 0;
1227 switch (Tok.getKind()) {
1228 case tok::kw_mutable: TokKind = 0; break;
1229 case tok::arrow: TokKind = 1; break;
1230 case tok::kw___attribute:
1231 case tok::l_square: TokKind = 2; break;
1232 case tok::kw_constexpr: TokKind = 3; break;
1233 default: llvm_unreachable("Unknown token kind");
1236 Diag(Tok, diag::err_lambda_missing_parens)
1238 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1239 SourceLocation DeclEndLoc = DeclLoc;
1241 // GNU-style attributes must be parsed before the mutable specifier to be
1242 // compatible with GCC.
1243 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1245 // Parse 'mutable', if it's there.
1246 SourceLocation MutableLoc;
1247 if (Tok.is(tok::kw_mutable)) {
1248 MutableLoc = ConsumeToken();
1249 DeclEndLoc = MutableLoc;
1252 // Parse attribute-specifier[opt].
1253 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1255 // Parse the return type, if there is one.
1256 if (Tok.is(tok::arrow)) {
1258 TrailingReturnType =
1259 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1260 if (Range.getEnd().isValid())
1261 DeclEndLoc = Range.getEnd();
1264 WarnIfHasCUDATargetAttr();
1266 SourceLocation NoLoc;
1267 D.AddTypeInfo(DeclaratorChunk::getFunction(
1269 /*isAmbiguous=*/false,
1270 /*LParenLoc=*/NoLoc,
1273 /*EllipsisLoc=*/NoLoc,
1274 /*RParenLoc=*/NoLoc,
1276 /*RefQualifierIsLValueRef=*/true,
1277 /*RefQualifierLoc=*/NoLoc,
1278 /*ConstQualifierLoc=*/NoLoc,
1279 /*VolatileQualifierLoc=*/NoLoc,
1280 /*RestrictQualifierLoc=*/NoLoc, MutableLoc, EST_None,
1281 /*ESpecRange=*/SourceRange(),
1282 /*Exceptions=*/nullptr,
1283 /*ExceptionRanges=*/nullptr,
1284 /*NumExceptions=*/0,
1285 /*NoexceptExpr=*/nullptr,
1286 /*ExceptionSpecTokens=*/nullptr,
1287 /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1288 TrailingReturnType),
1289 std::move(Attr), DeclEndLoc);
1292 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1294 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1295 Scope::CompoundStmtScope;
1296 ParseScope BodyScope(this, ScopeFlags);
1298 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1300 // Parse compound-statement.
1301 if (!Tok.is(tok::l_brace)) {
1302 Diag(Tok, diag::err_expected_lambda_body);
1303 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1307 StmtResult Stmt(ParseCompoundStatementBody());
1310 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1311 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1313 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1317 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1320 /// postfix-expression: [C++ 5.2p1]
1321 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1322 /// 'static_cast' '<' type-name '>' '(' expression ')'
1323 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1324 /// 'const_cast' '<' type-name '>' '(' expression ')'
1326 ExprResult Parser::ParseCXXCasts() {
1327 tok::TokenKind Kind = Tok.getKind();
1328 const char *CastName = nullptr; // For error messages
1331 default: llvm_unreachable("Unknown C++ cast!");
1332 case tok::kw_const_cast: CastName = "const_cast"; break;
1333 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1334 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1335 case tok::kw_static_cast: CastName = "static_cast"; break;
1338 SourceLocation OpLoc = ConsumeToken();
1339 SourceLocation LAngleBracketLoc = Tok.getLocation();
1341 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1342 // diagnose error, suggest fix, and recover parsing.
1343 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1344 Token Next = NextToken();
1345 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1346 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1349 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1352 // Parse the common declaration-specifiers piece.
1353 DeclSpec DS(AttrFactory);
1354 ParseSpecifierQualifierList(DS);
1356 // Parse the abstract-declarator, if present.
1357 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1358 ParseDeclarator(DeclaratorInfo);
1360 SourceLocation RAngleBracketLoc = Tok.getLocation();
1362 if (ExpectAndConsume(tok::greater))
1363 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1365 BalancedDelimiterTracker T(*this, tok::l_paren);
1367 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1370 ExprResult Result = ParseExpression();
1375 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1376 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1377 LAngleBracketLoc, DeclaratorInfo,
1379 T.getOpenLocation(), Result.get(),
1380 T.getCloseLocation());
1385 /// ParseCXXTypeid - This handles the C++ typeid expression.
1387 /// postfix-expression: [C++ 5.2p1]
1388 /// 'typeid' '(' expression ')'
1389 /// 'typeid' '(' type-id ')'
1391 ExprResult Parser::ParseCXXTypeid() {
1392 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1394 SourceLocation OpLoc = ConsumeToken();
1395 SourceLocation LParenLoc, RParenLoc;
1396 BalancedDelimiterTracker T(*this, tok::l_paren);
1398 // typeid expressions are always parenthesized.
1399 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1401 LParenLoc = T.getOpenLocation();
1405 // C++0x [expr.typeid]p3:
1406 // When typeid is applied to an expression other than an lvalue of a
1407 // polymorphic class type [...] The expression is an unevaluated
1408 // operand (Clause 5).
1410 // Note that we can't tell whether the expression is an lvalue of a
1411 // polymorphic class type until after we've parsed the expression; we
1412 // speculatively assume the subexpression is unevaluated, and fix it up
1415 // We enter the unevaluated context before trying to determine whether we
1416 // have a type-id, because the tentative parse logic will try to resolve
1417 // names, and must treat them as unevaluated.
1418 EnterExpressionEvaluationContext Unevaluated(
1419 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1420 Sema::ReuseLambdaContextDecl);
1422 if (isTypeIdInParens()) {
1423 TypeResult Ty = ParseTypeName();
1427 RParenLoc = T.getCloseLocation();
1428 if (Ty.isInvalid() || RParenLoc.isInvalid())
1431 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1432 Ty.get().getAsOpaquePtr(), RParenLoc);
1434 Result = ParseExpression();
1437 if (Result.isInvalid())
1438 SkipUntil(tok::r_paren, StopAtSemi);
1441 RParenLoc = T.getCloseLocation();
1442 if (RParenLoc.isInvalid())
1445 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1446 Result.get(), RParenLoc);
1453 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1455 /// '__uuidof' '(' expression ')'
1456 /// '__uuidof' '(' type-id ')'
1458 ExprResult Parser::ParseCXXUuidof() {
1459 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1461 SourceLocation OpLoc = ConsumeToken();
1462 BalancedDelimiterTracker T(*this, tok::l_paren);
1464 // __uuidof expressions are always parenthesized.
1465 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1470 if (isTypeIdInParens()) {
1471 TypeResult Ty = ParseTypeName();
1479 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1480 Ty.get().getAsOpaquePtr(),
1481 T.getCloseLocation());
1483 EnterExpressionEvaluationContext Unevaluated(
1484 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1485 Result = ParseExpression();
1488 if (Result.isInvalid())
1489 SkipUntil(tok::r_paren, StopAtSemi);
1493 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1495 Result.get(), T.getCloseLocation());
1502 /// Parse a C++ pseudo-destructor expression after the base,
1503 /// . or -> operator, and nested-name-specifier have already been
1506 /// postfix-expression: [C++ 5.2]
1507 /// postfix-expression . pseudo-destructor-name
1508 /// postfix-expression -> pseudo-destructor-name
1510 /// pseudo-destructor-name:
1511 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1512 /// ::[opt] nested-name-specifier template simple-template-id ::
1514 /// ::[opt] nested-name-specifier[opt] ~type-name
1517 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1518 tok::TokenKind OpKind,
1520 ParsedType ObjectType) {
1521 // We're parsing either a pseudo-destructor-name or a dependent
1522 // member access that has the same form as a
1523 // pseudo-destructor-name. We parse both in the same way and let
1524 // the action model sort them out.
1526 // Note that the ::[opt] nested-name-specifier[opt] has already
1527 // been parsed, and if there was a simple-template-id, it has
1528 // been coalesced into a template-id annotation token.
1529 UnqualifiedId FirstTypeName;
1530 SourceLocation CCLoc;
1531 if (Tok.is(tok::identifier)) {
1532 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1534 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1535 CCLoc = ConsumeToken();
1536 } else if (Tok.is(tok::annot_template_id)) {
1537 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1538 // store it in the pseudo-dtor node (to be used when instantiating it).
1539 FirstTypeName.setTemplateId(
1540 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1541 ConsumeAnnotationToken();
1542 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1543 CCLoc = ConsumeToken();
1545 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1549 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1550 SourceLocation TildeLoc = ConsumeToken();
1552 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1553 DeclSpec DS(AttrFactory);
1554 ParseDecltypeSpecifier(DS);
1555 if (DS.getTypeSpecType() == TST_error)
1557 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1561 if (!Tok.is(tok::identifier)) {
1562 Diag(Tok, diag::err_destructor_tilde_identifier);
1566 // Parse the second type.
1567 UnqualifiedId SecondTypeName;
1568 IdentifierInfo *Name = Tok.getIdentifierInfo();
1569 SourceLocation NameLoc = ConsumeToken();
1570 SecondTypeName.setIdentifier(Name, NameLoc);
1572 // If there is a '<', the second type name is a template-id. Parse
1574 if (Tok.is(tok::less) &&
1575 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1577 false, ObjectType, SecondTypeName,
1578 /*AssumeTemplateName=*/true))
1581 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1582 SS, FirstTypeName, CCLoc, TildeLoc,
1586 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1588 /// boolean-literal: [C++ 2.13.5]
1591 ExprResult Parser::ParseCXXBoolLiteral() {
1592 tok::TokenKind Kind = Tok.getKind();
1593 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1596 /// ParseThrowExpression - This handles the C++ throw expression.
1598 /// throw-expression: [C++ 15]
1599 /// 'throw' assignment-expression[opt]
1600 ExprResult Parser::ParseThrowExpression() {
1601 assert(Tok.is(tok::kw_throw) && "Not throw!");
1602 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1604 // If the current token isn't the start of an assignment-expression,
1605 // then the expression is not present. This handles things like:
1606 // "C ? throw : (void)42", which is crazy but legal.
1607 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1614 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1617 ExprResult Expr(ParseAssignmentExpression());
1618 if (Expr.isInvalid()) return Expr;
1619 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1623 /// Parse the C++ Coroutines co_yield expression.
1625 /// co_yield-expression:
1626 /// 'co_yield' assignment-expression[opt]
1627 ExprResult Parser::ParseCoyieldExpression() {
1628 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1630 SourceLocation Loc = ConsumeToken();
1631 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1632 : ParseAssignmentExpression();
1633 if (!Expr.isInvalid())
1634 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1638 /// ParseCXXThis - This handles the C++ 'this' pointer.
1640 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1641 /// a non-lvalue expression whose value is the address of the object for which
1642 /// the function is called.
1643 ExprResult Parser::ParseCXXThis() {
1644 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1645 SourceLocation ThisLoc = ConsumeToken();
1646 return Actions.ActOnCXXThis(ThisLoc);
1649 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1650 /// Can be interpreted either as function-style casting ("int(x)")
1651 /// or class type construction ("ClassType(x,y,z)")
1652 /// or creation of a value-initialized type ("int()").
1653 /// See [C++ 5.2.3].
1655 /// postfix-expression: [C++ 5.2p1]
1656 /// simple-type-specifier '(' expression-list[opt] ')'
1657 /// [C++0x] simple-type-specifier braced-init-list
1658 /// typename-specifier '(' expression-list[opt] ')'
1659 /// [C++0x] typename-specifier braced-init-list
1661 /// In C++1z onwards, the type specifier can also be a template-name.
1663 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1664 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCastContext);
1665 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1667 assert((Tok.is(tok::l_paren) ||
1668 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1669 && "Expected '(' or '{'!");
1671 if (Tok.is(tok::l_brace)) {
1672 ExprResult Init = ParseBraceInitializer();
1673 if (Init.isInvalid())
1675 Expr *InitList = Init.get();
1676 return Actions.ActOnCXXTypeConstructExpr(
1677 TypeRep, InitList->getLocStart(), MultiExprArg(&InitList, 1),
1678 InitList->getLocEnd(), /*ListInitialization=*/true);
1680 BalancedDelimiterTracker T(*this, tok::l_paren);
1684 CommaLocsTy CommaLocs;
1686 if (Tok.isNot(tok::r_paren)) {
1687 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1688 Actions.CodeCompleteConstructor(getCurScope(),
1689 TypeRep.get()->getCanonicalTypeInternal(),
1690 DS.getLocEnd(), Exprs);
1692 SkipUntil(tok::r_paren, StopAtSemi);
1700 // TypeRep could be null, if it references an invalid typedef.
1704 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1705 "Unexpected number of commas!");
1706 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1707 Exprs, T.getCloseLocation(),
1708 /*ListInitialization=*/false);
1712 /// ParseCXXCondition - if/switch/while condition expression.
1716 /// type-specifier-seq declarator '=' assignment-expression
1717 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1718 /// [C++11] type-specifier-seq declarator braced-init-list
1719 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1720 /// brace-or-equal-initializer
1721 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1722 /// '=' assignment-expression
1724 /// In C++1z, a condition may in some contexts be preceded by an
1725 /// optional init-statement. This function will parse that too.
1727 /// \param InitStmt If non-null, an init-statement is permitted, and if present
1728 /// will be parsed and stored here.
1730 /// \param Loc The location of the start of the statement that requires this
1731 /// condition, e.g., the "for" in a for loop.
1733 /// \returns The parsed condition.
1734 Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1736 Sema::ConditionKind CK) {
1737 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1739 if (Tok.is(tok::code_completion)) {
1740 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1742 return Sema::ConditionError();
1745 ParsedAttributesWithRange attrs(AttrFactory);
1746 MaybeParseCXX11Attributes(attrs);
1748 const auto WarnOnInit = [this, &CK] {
1749 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1750 ? diag::warn_cxx14_compat_init_statement
1751 : diag::ext_init_statement)
1752 << (CK == Sema::ConditionKind::Switch);
1755 // Determine what kind of thing we have.
1756 switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
1757 case ConditionOrInitStatement::Expression: {
1758 ProhibitAttributes(attrs);
1760 // We can have an empty expression here.
1762 if (InitStmt && Tok.is(tok::semi)) {
1764 SourceLocation SemiLoc = ConsumeToken();
1765 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1766 return ParseCXXCondition(nullptr, Loc, CK);
1769 // Parse the expression.
1770 ExprResult Expr = ParseExpression(); // expression
1771 if (Expr.isInvalid())
1772 return Sema::ConditionError();
1774 if (InitStmt && Tok.is(tok::semi)) {
1776 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1778 return ParseCXXCondition(nullptr, Loc, CK);
1781 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
1784 case ConditionOrInitStatement::InitStmtDecl: {
1786 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1788 ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1789 attrs, /*RequireSemi=*/true);
1790 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1791 return ParseCXXCondition(nullptr, Loc, CK);
1794 case ConditionOrInitStatement::ConditionDecl:
1795 case ConditionOrInitStatement::Error:
1799 // type-specifier-seq
1800 DeclSpec DS(AttrFactory);
1801 DS.takeAttributesFrom(attrs);
1802 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
1805 Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
1806 ParseDeclarator(DeclaratorInfo);
1808 // simple-asm-expr[opt]
1809 if (Tok.is(tok::kw_asm)) {
1811 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1812 if (AsmLabel.isInvalid()) {
1813 SkipUntil(tok::semi, StopAtSemi);
1814 return Sema::ConditionError();
1816 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1817 DeclaratorInfo.SetRangeEnd(Loc);
1820 // If attributes are present, parse them.
1821 MaybeParseGNUAttributes(DeclaratorInfo);
1823 // Type-check the declaration itself.
1824 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1826 if (Dcl.isInvalid())
1827 return Sema::ConditionError();
1828 Decl *DeclOut = Dcl.get();
1830 // '=' assignment-expression
1831 // If a '==' or '+=' is found, suggest a fixit to '='.
1832 bool CopyInitialization = isTokenEqualOrEqualTypo();
1833 if (CopyInitialization)
1836 ExprResult InitExpr = ExprError();
1837 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1838 Diag(Tok.getLocation(),
1839 diag::warn_cxx98_compat_generalized_initializer_lists);
1840 InitExpr = ParseBraceInitializer();
1841 } else if (CopyInitialization) {
1842 InitExpr = ParseAssignmentExpression();
1843 } else if (Tok.is(tok::l_paren)) {
1844 // This was probably an attempt to initialize the variable.
1845 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1846 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1847 RParen = ConsumeParen();
1848 Diag(DeclOut->getLocation(),
1849 diag::err_expected_init_in_condition_lparen)
1850 << SourceRange(LParen, RParen);
1852 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
1855 if (!InitExpr.isInvalid())
1856 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
1858 Actions.ActOnInitializerError(DeclOut);
1860 Actions.FinalizeDeclaration(DeclOut);
1861 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
1864 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1865 /// This should only be called when the current token is known to be part of
1866 /// simple-type-specifier.
1868 /// simple-type-specifier:
1869 /// '::'[opt] nested-name-specifier[opt] type-name
1870 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1882 /// [GNU] typeof-specifier
1883 /// [C++0x] auto [TODO]
1890 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1891 DS.SetRangeStart(Tok.getLocation());
1892 const char *PrevSpec;
1894 SourceLocation Loc = Tok.getLocation();
1895 const clang::PrintingPolicy &Policy =
1896 Actions.getASTContext().getPrintingPolicy();
1898 switch (Tok.getKind()) {
1899 case tok::identifier: // foo::bar
1900 case tok::coloncolon: // ::foo::bar
1901 llvm_unreachable("Annotation token should already be formed!");
1903 llvm_unreachable("Not a simple-type-specifier token!");
1906 case tok::annot_typename: {
1907 if (getTypeAnnotation(Tok))
1908 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1909 getTypeAnnotation(Tok), Policy);
1911 DS.SetTypeSpecError();
1913 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1914 ConsumeAnnotationToken();
1916 DS.Finish(Actions, Policy);
1922 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1925 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1927 case tok::kw___int64:
1928 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1930 case tok::kw_signed:
1931 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1933 case tok::kw_unsigned:
1934 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1937 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1940 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1943 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1945 case tok::kw___int128:
1946 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1949 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1952 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1954 case tok::kw_double:
1955 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1957 case tok::kw__Float16:
1958 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
1960 case tok::kw___float128:
1961 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1963 case tok::kw_wchar_t:
1964 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1966 case tok::kw_char8_t:
1967 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
1969 case tok::kw_char16_t:
1970 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1972 case tok::kw_char32_t:
1973 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1976 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1978 case tok::annot_decltype:
1979 case tok::kw_decltype:
1980 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1981 return DS.Finish(Actions, Policy);
1983 // GNU typeof support.
1984 case tok::kw_typeof:
1985 ParseTypeofSpecifier(DS);
1986 DS.Finish(Actions, Policy);
1990 DS.SetRangeEnd(PrevTokLocation);
1991 DS.Finish(Actions, Policy);
1994 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1995 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1996 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1997 /// by parsing the type-specifier-seq, because these sequences are
1998 /// typically followed by some form of declarator. Returns true and
1999 /// emits diagnostics if this is not a type-specifier-seq, false
2002 /// type-specifier-seq: [C++ 8.1]
2003 /// type-specifier type-specifier-seq[opt]
2005 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
2006 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
2007 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2011 /// Finish parsing a C++ unqualified-id that is a template-id of
2014 /// This routine is invoked when a '<' is encountered after an identifier or
2015 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2016 /// whether the unqualified-id is actually a template-id. This routine will
2017 /// then parse the template arguments and form the appropriate template-id to
2018 /// return to the caller.
2020 /// \param SS the nested-name-specifier that precedes this template-id, if
2021 /// we're actually parsing a qualified-id.
2023 /// \param Name for constructor and destructor names, this is the actual
2024 /// identifier that may be a template-name.
2026 /// \param NameLoc the location of the class-name in a constructor or
2029 /// \param EnteringContext whether we're entering the scope of the
2030 /// nested-name-specifier.
2032 /// \param ObjectType if this unqualified-id occurs within a member access
2033 /// expression, the type of the base object whose member is being accessed.
2035 /// \param Id as input, describes the template-name or operator-function-id
2036 /// that precedes the '<'. If template arguments were parsed successfully,
2037 /// will be updated with the template-id.
2039 /// \param AssumeTemplateId When true, this routine will assume that the name
2040 /// refers to a template without performing name lookup to verify.
2042 /// \returns true if a parse error occurred, false otherwise.
2043 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2044 SourceLocation TemplateKWLoc,
2045 IdentifierInfo *Name,
2046 SourceLocation NameLoc,
2047 bool EnteringContext,
2048 ParsedType ObjectType,
2050 bool AssumeTemplateId) {
2051 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2053 TemplateTy Template;
2054 TemplateNameKind TNK = TNK_Non_template;
2055 switch (Id.getKind()) {
2056 case UnqualifiedIdKind::IK_Identifier:
2057 case UnqualifiedIdKind::IK_OperatorFunctionId:
2058 case UnqualifiedIdKind::IK_LiteralOperatorId:
2059 if (AssumeTemplateId) {
2060 // We defer the injected-class-name checks until we've found whether
2061 // this template-id is used to form a nested-name-specifier or not.
2062 TNK = Actions.ActOnDependentTemplateName(
2063 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2064 Template, /*AllowInjectedClassName*/ true);
2065 if (TNK == TNK_Non_template)
2068 bool MemberOfUnknownSpecialization;
2069 TNK = Actions.isTemplateName(getCurScope(), SS,
2070 TemplateKWLoc.isValid(), Id,
2071 ObjectType, EnteringContext, Template,
2072 MemberOfUnknownSpecialization);
2074 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2075 ObjectType && IsTemplateArgumentList()) {
2076 // We have something like t->getAs<T>(), where getAs is a
2077 // member of an unknown specialization. However, this will only
2078 // parse correctly as a template, so suggest the keyword 'template'
2079 // before 'getAs' and treat this as a dependent template name.
2081 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2082 Name = Id.Identifier->getName();
2085 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
2086 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2088 Name += Id.Identifier->getName();
2090 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2092 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2093 TNK = Actions.ActOnDependentTemplateName(
2094 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2095 Template, /*AllowInjectedClassName*/ true);
2096 if (TNK == TNK_Non_template)
2102 case UnqualifiedIdKind::IK_ConstructorName: {
2103 UnqualifiedId TemplateName;
2104 bool MemberOfUnknownSpecialization;
2105 TemplateName.setIdentifier(Name, NameLoc);
2106 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2107 TemplateName, ObjectType,
2108 EnteringContext, Template,
2109 MemberOfUnknownSpecialization);
2113 case UnqualifiedIdKind::IK_DestructorName: {
2114 UnqualifiedId TemplateName;
2115 bool MemberOfUnknownSpecialization;
2116 TemplateName.setIdentifier(Name, NameLoc);
2118 TNK = Actions.ActOnDependentTemplateName(
2119 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2120 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2121 if (TNK == TNK_Non_template)
2124 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2125 TemplateName, ObjectType,
2126 EnteringContext, Template,
2127 MemberOfUnknownSpecialization);
2129 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2130 Diag(NameLoc, diag::err_destructor_template_id)
2131 << Name << SS.getRange();
2142 if (TNK == TNK_Non_template)
2145 // Parse the enclosed template argument list.
2146 SourceLocation LAngleLoc, RAngleLoc;
2147 TemplateArgList TemplateArgs;
2148 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2152 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2153 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2154 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
2155 // Form a parsed representation of the template-id to be stored in the
2158 // FIXME: Store name for literal operator too.
2159 IdentifierInfo *TemplateII =
2160 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2162 OverloadedOperatorKind OpKind =
2163 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2165 : Id.OperatorFunctionId.Operator;
2167 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2168 SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2169 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2171 Id.setTemplateId(TemplateId);
2175 // Bundle the template arguments together.
2176 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2178 // Constructor and destructor names.
2180 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2181 Template, Name, NameLoc,
2182 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2183 /*IsCtorOrDtorName=*/true);
2184 if (Type.isInvalid())
2187 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
2188 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2190 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2195 /// Parse an operator-function-id or conversion-function-id as part
2196 /// of a C++ unqualified-id.
2198 /// This routine is responsible only for parsing the operator-function-id or
2199 /// conversion-function-id; it does not handle template arguments in any way.
2202 /// operator-function-id: [C++ 13.5]
2203 /// 'operator' operator
2205 /// operator: one of
2206 /// new delete new[] delete[]
2207 /// + - * / % ^ & | ~
2208 /// ! = < > += -= *= /= %=
2209 /// ^= &= |= << >> >>= <<= == !=
2210 /// <= >= && || ++ -- , ->* ->
2213 /// conversion-function-id: [C++ 12.3.2]
2214 /// operator conversion-type-id
2216 /// conversion-type-id:
2217 /// type-specifier-seq conversion-declarator[opt]
2219 /// conversion-declarator:
2220 /// ptr-operator conversion-declarator[opt]
2223 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2224 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2226 /// \param EnteringContext whether we are entering the scope of the
2227 /// nested-name-specifier.
2229 /// \param ObjectType if this unqualified-id occurs within a member access
2230 /// expression, the type of the base object whose member is being accessed.
2232 /// \param Result on a successful parse, contains the parsed unqualified-id.
2234 /// \returns true if parsing fails, false otherwise.
2235 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2236 ParsedType ObjectType,
2237 UnqualifiedId &Result) {
2238 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2240 // Consume the 'operator' keyword.
2241 SourceLocation KeywordLoc = ConsumeToken();
2243 // Determine what kind of operator name we have.
2244 unsigned SymbolIdx = 0;
2245 SourceLocation SymbolLocations[3];
2246 OverloadedOperatorKind Op = OO_None;
2247 switch (Tok.getKind()) {
2249 case tok::kw_delete: {
2250 bool isNew = Tok.getKind() == tok::kw_new;
2251 // Consume the 'new' or 'delete'.
2252 SymbolLocations[SymbolIdx++] = ConsumeToken();
2253 // Check for array new/delete.
2254 if (Tok.is(tok::l_square) &&
2255 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2256 // Consume the '[' and ']'.
2257 BalancedDelimiterTracker T(*this, tok::l_square);
2260 if (T.getCloseLocation().isInvalid())
2263 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2264 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2265 Op = isNew? OO_Array_New : OO_Array_Delete;
2267 Op = isNew? OO_New : OO_Delete;
2272 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2274 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2277 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2278 #include "clang/Basic/OperatorKinds.def"
2280 case tok::l_paren: {
2281 // Consume the '(' and ')'.
2282 BalancedDelimiterTracker T(*this, tok::l_paren);
2285 if (T.getCloseLocation().isInvalid())
2288 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2289 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2294 case tok::l_square: {
2295 // Consume the '[' and ']'.
2296 BalancedDelimiterTracker T(*this, tok::l_square);
2299 if (T.getCloseLocation().isInvalid())
2302 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2303 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2308 case tok::code_completion: {
2309 // Code completion for the operator name.
2310 Actions.CodeCompleteOperatorName(getCurScope());
2312 // Don't try to parse any further.
2320 if (Op != OO_None) {
2321 // We have parsed an operator-function-id.
2322 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2326 // Parse a literal-operator-id.
2328 // literal-operator-id: C++11 [over.literal]
2329 // operator string-literal identifier
2330 // operator user-defined-string-literal
2332 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2333 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2335 SourceLocation DiagLoc;
2336 unsigned DiagId = 0;
2338 // We're past translation phase 6, so perform string literal concatenation
2339 // before checking for "".
2340 SmallVector<Token, 4> Toks;
2341 SmallVector<SourceLocation, 4> TokLocs;
2342 while (isTokenStringLiteral()) {
2343 if (!Tok.is(tok::string_literal) && !DiagId) {
2344 // C++11 [over.literal]p1:
2345 // The string-literal or user-defined-string-literal in a
2346 // literal-operator-id shall have no encoding-prefix [...].
2347 DiagLoc = Tok.getLocation();
2348 DiagId = diag::err_literal_operator_string_prefix;
2350 Toks.push_back(Tok);
2351 TokLocs.push_back(ConsumeStringToken());
2354 StringLiteralParser Literal(Toks, PP);
2355 if (Literal.hadError)
2358 // Grab the literal operator's suffix, which will be either the next token
2359 // or a ud-suffix from the string literal.
2360 IdentifierInfo *II = nullptr;
2361 SourceLocation SuffixLoc;
2362 if (!Literal.getUDSuffix().empty()) {
2363 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2365 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2366 Literal.getUDSuffixOffset(),
2367 PP.getSourceManager(), getLangOpts());
2368 } else if (Tok.is(tok::identifier)) {
2369 II = Tok.getIdentifierInfo();
2370 SuffixLoc = ConsumeToken();
2371 TokLocs.push_back(SuffixLoc);
2373 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2377 // The string literal must be empty.
2378 if (!Literal.GetString().empty() || Literal.Pascal) {
2379 // C++11 [over.literal]p1:
2380 // The string-literal or user-defined-string-literal in a
2381 // literal-operator-id shall [...] contain no characters
2382 // other than the implicit terminating '\0'.
2383 DiagLoc = TokLocs.front();
2384 DiagId = diag::err_literal_operator_string_not_empty;
2388 // This isn't a valid literal-operator-id, but we think we know
2389 // what the user meant. Tell them what they should have written.
2390 SmallString<32> Str;
2392 Str += II->getName();
2393 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2394 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2397 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2399 return Actions.checkLiteralOperatorId(SS, Result);
2402 // Parse a conversion-function-id.
2404 // conversion-function-id: [C++ 12.3.2]
2405 // operator conversion-type-id
2407 // conversion-type-id:
2408 // type-specifier-seq conversion-declarator[opt]
2410 // conversion-declarator:
2411 // ptr-operator conversion-declarator[opt]
2413 // Parse the type-specifier-seq.
2414 DeclSpec DS(AttrFactory);
2415 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2418 // Parse the conversion-declarator, which is merely a sequence of
2420 Declarator D(DS, DeclaratorContext::ConversionIdContext);
2421 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2423 // Finish up the type.
2424 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2428 // Note that this is a conversion-function-id.
2429 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2430 D.getSourceRange().getEnd());
2434 /// Parse a C++ unqualified-id (or a C identifier), which describes the
2435 /// name of an entity.
2438 /// unqualified-id: [C++ expr.prim.general]
2440 /// operator-function-id
2441 /// conversion-function-id
2442 /// [C++0x] literal-operator-id [TODO]
2448 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2449 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2451 /// \param EnteringContext whether we are entering the scope of the
2452 /// nested-name-specifier.
2454 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2456 /// \param AllowConstructorName whether we allow parsing a constructor name.
2458 /// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2460 /// \param ObjectType if this unqualified-id occurs within a member access
2461 /// expression, the type of the base object whose member is being accessed.
2463 /// \param Result on a successful parse, contains the parsed unqualified-id.
2465 /// \returns true if parsing fails, false otherwise.
2466 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2467 bool AllowDestructorName,
2468 bool AllowConstructorName,
2469 bool AllowDeductionGuide,
2470 ParsedType ObjectType,
2471 SourceLocation *TemplateKWLoc,
2472 UnqualifiedId &Result) {
2474 *TemplateKWLoc = SourceLocation();
2476 // Handle 'A::template B'. This is for template-ids which have not
2477 // already been annotated by ParseOptionalCXXScopeSpecifier().
2478 bool TemplateSpecified = false;
2479 if (Tok.is(tok::kw_template)) {
2480 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2481 TemplateSpecified = true;
2482 *TemplateKWLoc = ConsumeToken();
2484 SourceLocation TemplateLoc = ConsumeToken();
2485 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2486 << FixItHint::CreateRemoval(TemplateLoc);
2492 // template-id (when it hasn't already been annotated)
2493 if (Tok.is(tok::identifier)) {
2494 // Consume the identifier.
2495 IdentifierInfo *Id = Tok.getIdentifierInfo();
2496 SourceLocation IdLoc = ConsumeToken();
2498 if (!getLangOpts().CPlusPlus) {
2499 // If we're not in C++, only identifiers matter. Record the
2500 // identifier and return.
2501 Result.setIdentifier(Id, IdLoc);
2505 ParsedTemplateTy TemplateName;
2506 if (AllowConstructorName &&
2507 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2508 // We have parsed a constructor name.
2509 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2513 Result.setConstructorName(Ty, IdLoc, IdLoc);
2514 } else if (getLangOpts().CPlusPlus17 &&
2515 AllowDeductionGuide && SS.isEmpty() &&
2516 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2518 // We have parsed a template-name naming a deduction guide.
2519 Result.setDeductionGuideName(TemplateName, IdLoc);
2521 // We have parsed an identifier.
2522 Result.setIdentifier(Id, IdLoc);
2525 // If the next token is a '<', we may have a template.
2526 TemplateTy Template;
2527 if (Tok.is(tok::less))
2528 return ParseUnqualifiedIdTemplateId(
2529 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2530 EnteringContext, ObjectType, Result, TemplateSpecified);
2531 else if (TemplateSpecified &&
2532 Actions.ActOnDependentTemplateName(
2533 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2534 EnteringContext, Template,
2535 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2542 // template-id (already parsed and annotated)
2543 if (Tok.is(tok::annot_template_id)) {
2544 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2546 // If the template-name names the current class, then this is a constructor
2547 if (AllowConstructorName && TemplateId->Name &&
2548 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2550 // C++ [class.qual]p2 specifies that a qualified template-name
2551 // is taken as the constructor name where a constructor can be
2552 // declared. Thus, the template arguments are extraneous, so
2553 // complain about them and remove them entirely.
2554 Diag(TemplateId->TemplateNameLoc,
2555 diag::err_out_of_line_constructor_template_id)
2557 << FixItHint::CreateRemoval(
2558 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2559 ParsedType Ty = Actions.getConstructorName(
2560 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2564 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2565 TemplateId->RAngleLoc);
2566 ConsumeAnnotationToken();
2570 Result.setConstructorTemplateId(TemplateId);
2571 ConsumeAnnotationToken();
2575 // We have already parsed a template-id; consume the annotation token as
2576 // our unqualified-id.
2577 Result.setTemplateId(TemplateId);
2578 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2579 if (TemplateLoc.isValid()) {
2580 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2581 *TemplateKWLoc = TemplateLoc;
2583 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2584 << FixItHint::CreateRemoval(TemplateLoc);
2586 ConsumeAnnotationToken();
2591 // operator-function-id
2592 // conversion-function-id
2593 if (Tok.is(tok::kw_operator)) {
2594 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2597 // If we have an operator-function-id or a literal-operator-id and the next
2598 // token is a '<', we may have a
2601 // operator-function-id < template-argument-list[opt] >
2602 TemplateTy Template;
2603 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2604 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
2606 return ParseUnqualifiedIdTemplateId(
2607 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2608 SourceLocation(), EnteringContext, ObjectType, Result,
2610 else if (TemplateSpecified &&
2611 Actions.ActOnDependentTemplateName(
2612 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2613 EnteringContext, Template,
2614 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2620 if (getLangOpts().CPlusPlus &&
2621 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2622 // C++ [expr.unary.op]p10:
2623 // There is an ambiguity in the unary-expression ~X(), where X is a
2624 // class-name. The ambiguity is resolved in favor of treating ~ as a
2625 // unary complement rather than treating ~X as referring to a destructor.
2628 SourceLocation TildeLoc = ConsumeToken();
2630 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2631 DeclSpec DS(AttrFactory);
2632 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2633 if (ParsedType Type =
2634 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2635 Result.setDestructorName(TildeLoc, Type, EndLoc);
2641 // Parse the class-name.
2642 if (Tok.isNot(tok::identifier)) {
2643 Diag(Tok, diag::err_destructor_tilde_identifier);
2647 // If the user wrote ~T::T, correct it to T::~T.
2648 DeclaratorScopeObj DeclScopeObj(*this, SS);
2649 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2650 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2651 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2652 // it will confuse this recovery logic.
2653 ColonProtectionRAIIObject ColonRAII(*this, false);
2656 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2659 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2661 if (SS.isNotEmpty())
2662 ObjectType = nullptr;
2663 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2665 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2669 // Recover as if the tilde had been written before the identifier.
2670 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2671 << FixItHint::CreateRemoval(TildeLoc)
2672 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2674 // Temporarily enter the scope for the rest of this function.
2675 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2676 DeclScopeObj.EnterDeclaratorScope();
2679 // Parse the class-name (or template-name in a simple-template-id).
2680 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2681 SourceLocation ClassNameLoc = ConsumeToken();
2683 if (Tok.is(tok::less)) {
2684 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2685 return ParseUnqualifiedIdTemplateId(
2686 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2687 ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
2690 // Note that this is a destructor name.
2691 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2692 ClassNameLoc, getCurScope(),
2698 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2702 Diag(Tok, diag::err_expected_unqualified_id)
2703 << getLangOpts().CPlusPlus;
2707 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2708 /// memory in a typesafe manner and call constructors.
2710 /// This method is called to parse the new expression after the optional :: has
2711 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2712 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2715 /// '::'[opt] 'new' new-placement[opt] new-type-id
2716 /// new-initializer[opt]
2717 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2718 /// new-initializer[opt]
2721 /// '(' expression-list ')'
2724 /// type-specifier-seq new-declarator[opt]
2725 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2728 /// ptr-operator new-declarator[opt]
2729 /// direct-new-declarator
2731 /// new-initializer:
2732 /// '(' expression-list[opt] ')'
2733 /// [C++0x] braced-init-list
2736 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2737 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2738 ConsumeToken(); // Consume 'new'
2740 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2741 // second form of new-expression. It can't be a new-type-id.
2743 ExprVector PlacementArgs;
2744 SourceLocation PlacementLParen, PlacementRParen;
2746 SourceRange TypeIdParens;
2747 DeclSpec DS(AttrFactory);
2748 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
2749 if (Tok.is(tok::l_paren)) {
2750 // If it turns out to be a placement, we change the type location.
2751 BalancedDelimiterTracker T(*this, tok::l_paren);
2753 PlacementLParen = T.getOpenLocation();
2754 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2755 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2760 PlacementRParen = T.getCloseLocation();
2761 if (PlacementRParen.isInvalid()) {
2762 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2766 if (PlacementArgs.empty()) {
2767 // Reset the placement locations. There was no placement.
2768 TypeIdParens = T.getRange();
2769 PlacementLParen = PlacementRParen = SourceLocation();
2771 // We still need the type.
2772 if (Tok.is(tok::l_paren)) {
2773 BalancedDelimiterTracker T(*this, tok::l_paren);
2775 MaybeParseGNUAttributes(DeclaratorInfo);
2776 ParseSpecifierQualifierList(DS);
2777 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2778 ParseDeclarator(DeclaratorInfo);
2780 TypeIdParens = T.getRange();
2782 MaybeParseGNUAttributes(DeclaratorInfo);
2783 if (ParseCXXTypeSpecifierSeq(DS))
2784 DeclaratorInfo.setInvalidType(true);
2786 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2787 ParseDeclaratorInternal(DeclaratorInfo,
2788 &Parser::ParseDirectNewDeclarator);
2793 // A new-type-id is a simplified type-id, where essentially the
2794 // direct-declarator is replaced by a direct-new-declarator.
2795 MaybeParseGNUAttributes(DeclaratorInfo);
2796 if (ParseCXXTypeSpecifierSeq(DS))
2797 DeclaratorInfo.setInvalidType(true);
2799 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2800 ParseDeclaratorInternal(DeclaratorInfo,
2801 &Parser::ParseDirectNewDeclarator);
2804 if (DeclaratorInfo.isInvalidType()) {
2805 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2809 ExprResult Initializer;
2811 if (Tok.is(tok::l_paren)) {
2812 SourceLocation ConstructorLParen, ConstructorRParen;
2813 ExprVector ConstructorArgs;
2814 BalancedDelimiterTracker T(*this, tok::l_paren);
2816 ConstructorLParen = T.getOpenLocation();
2817 if (Tok.isNot(tok::r_paren)) {
2818 CommaLocsTy CommaLocs;
2819 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2820 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2821 DeclaratorInfo).get();
2822 Actions.CodeCompleteConstructor(getCurScope(),
2823 TypeRep.get()->getCanonicalTypeInternal(),
2824 DeclaratorInfo.getLocEnd(),
2827 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2832 ConstructorRParen = T.getCloseLocation();
2833 if (ConstructorRParen.isInvalid()) {
2834 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2837 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2840 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2841 Diag(Tok.getLocation(),
2842 diag::warn_cxx98_compat_generalized_initializer_lists);
2843 Initializer = ParseBraceInitializer();
2845 if (Initializer.isInvalid())
2848 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2849 PlacementArgs, PlacementRParen,
2850 TypeIdParens, DeclaratorInfo, Initializer.get());
2853 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2854 /// passed to ParseDeclaratorInternal.
2856 /// direct-new-declarator:
2857 /// '[' expression ']'
2858 /// direct-new-declarator '[' constant-expression ']'
2860 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2861 // Parse the array dimensions.
2863 while (Tok.is(tok::l_square)) {
2864 // An array-size expression can't start with a lambda.
2865 if (CheckProhibitedCXX11Attribute())
2868 BalancedDelimiterTracker T(*this, tok::l_square);
2871 ExprResult Size(first ? ParseExpression()
2872 : ParseConstantExpression());
2873 if (Size.isInvalid()) {
2875 SkipUntil(tok::r_square, StopAtSemi);
2882 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2883 ParsedAttributes Attrs(AttrFactory);
2884 MaybeParseCXX11Attributes(Attrs);
2886 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2887 /*static=*/false, /*star=*/false,
2888 Size.get(), T.getOpenLocation(),
2889 T.getCloseLocation()),
2890 std::move(Attrs), T.getCloseLocation());
2892 if (T.getCloseLocation().isInvalid())
2897 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2898 /// This ambiguity appears in the syntax of the C++ new operator.
2901 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2902 /// new-initializer[opt]
2905 /// '(' expression-list ')'
2907 bool Parser::ParseExpressionListOrTypeId(
2908 SmallVectorImpl<Expr*> &PlacementArgs,
2910 // The '(' was already consumed.
2911 if (isTypeIdInParens()) {
2912 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2913 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2915 return D.isInvalidType();
2918 // It's not a type, it has to be an expression list.
2919 // Discard the comma locations - ActOnCXXNew has enough parameters.
2920 CommaLocsTy CommaLocs;
2921 return ParseExpressionList(PlacementArgs, CommaLocs);
2924 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2925 /// to free memory allocated by new.
2927 /// This method is called to parse the 'delete' expression after the optional
2928 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2929 /// and "Start" is its location. Otherwise, "Start" is the location of the
2932 /// delete-expression:
2933 /// '::'[opt] 'delete' cast-expression
2934 /// '::'[opt] 'delete' '[' ']' cast-expression
2936 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2937 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2938 ConsumeToken(); // Consume 'delete'
2941 bool ArrayDelete = false;
2942 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2943 // C++11 [expr.delete]p1:
2944 // Whenever the delete keyword is followed by empty square brackets, it
2945 // shall be interpreted as [array delete].
2946 // [Footnote: A lambda expression with a lambda-introducer that consists
2947 // of empty square brackets can follow the delete keyword if
2948 // the lambda expression is enclosed in parentheses.]
2949 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2950 // lambda-introducer.
2952 BalancedDelimiterTracker T(*this, tok::l_square);
2956 if (T.getCloseLocation().isInvalid())
2960 ExprResult Operand(ParseCastExpression(false));
2961 if (Operand.isInvalid())
2964 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2967 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2969 default: llvm_unreachable("Not a known type trait");
2970 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2971 case tok::kw_ ## Spelling: return UTT_ ## Name;
2972 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2973 case tok::kw_ ## Spelling: return BTT_ ## Name;
2974 #include "clang/Basic/TokenKinds.def"
2975 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2976 case tok::kw_ ## Spelling: return TT_ ## Name;
2977 #include "clang/Basic/TokenKinds.def"
2981 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2983 default: llvm_unreachable("Not a known binary type trait");
2984 case tok::kw___array_rank: return ATT_ArrayRank;
2985 case tok::kw___array_extent: return ATT_ArrayExtent;
2989 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2991 default: llvm_unreachable("Not a known unary expression trait.");
2992 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2993 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2997 static unsigned TypeTraitArity(tok::TokenKind kind) {
2999 default: llvm_unreachable("Not a known type trait");
3000 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3001 #include "clang/Basic/TokenKinds.def"
3005 /// Parse the built-in type-trait pseudo-functions that allow
3006 /// implementation of the TR1/C++11 type traits templates.
3008 /// primary-expression:
3009 /// unary-type-trait '(' type-id ')'
3010 /// binary-type-trait '(' type-id ',' type-id ')'
3011 /// type-trait '(' type-id-seq ')'
3014 /// type-id ...[opt] type-id-seq[opt]
3016 ExprResult Parser::ParseTypeTrait() {
3017 tok::TokenKind Kind = Tok.getKind();
3018 unsigned Arity = TypeTraitArity(Kind);
3020 SourceLocation Loc = ConsumeToken();
3022 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3023 if (Parens.expectAndConsume())
3026 SmallVector<ParsedType, 2> Args;
3028 // Parse the next type.
3029 TypeResult Ty = ParseTypeName();
3030 if (Ty.isInvalid()) {
3035 // Parse the ellipsis, if present.
3036 if (Tok.is(tok::ellipsis)) {
3037 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3038 if (Ty.isInvalid()) {
3044 // Add this type to the list of arguments.
3045 Args.push_back(Ty.get());
3046 } while (TryConsumeToken(tok::comma));
3048 if (Parens.consumeClose())
3051 SourceLocation EndLoc = Parens.getCloseLocation();
3053 if (Arity && Args.size() != Arity) {
3054 Diag(EndLoc, diag::err_type_trait_arity)
3055 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3059 if (!Arity && Args.empty()) {
3060 Diag(EndLoc, diag::err_type_trait_arity)
3061 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3065 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3068 /// ParseArrayTypeTrait - Parse the built-in array type-trait
3069 /// pseudo-functions.
3071 /// primary-expression:
3072 /// [Embarcadero] '__array_rank' '(' type-id ')'
3073 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3075 ExprResult Parser::ParseArrayTypeTrait() {
3076 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3077 SourceLocation Loc = ConsumeToken();
3079 BalancedDelimiterTracker T(*this, tok::l_paren);
3080 if (T.expectAndConsume())
3083 TypeResult Ty = ParseTypeName();
3084 if (Ty.isInvalid()) {
3085 SkipUntil(tok::comma, StopAtSemi);
3086 SkipUntil(tok::r_paren, StopAtSemi);
3091 case ATT_ArrayRank: {
3093 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3094 T.getCloseLocation());
3096 case ATT_ArrayExtent: {
3097 if (ExpectAndConsume(tok::comma)) {
3098 SkipUntil(tok::r_paren, StopAtSemi);
3102 ExprResult DimExpr = ParseExpression();
3105 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3106 T.getCloseLocation());
3109 llvm_unreachable("Invalid ArrayTypeTrait!");
3112 /// ParseExpressionTrait - Parse built-in expression-trait
3113 /// pseudo-functions like __is_lvalue_expr( xxx ).
3115 /// primary-expression:
3116 /// [Embarcadero] expression-trait '(' expression ')'
3118 ExprResult Parser::ParseExpressionTrait() {
3119 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3120 SourceLocation Loc = ConsumeToken();
3122 BalancedDelimiterTracker T(*this, tok::l_paren);
3123 if (T.expectAndConsume())
3126 ExprResult Expr = ParseExpression();
3130 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3131 T.getCloseLocation());
3135 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3136 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3137 /// based on the context past the parens.
3139 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3141 BalancedDelimiterTracker &Tracker,
3142 ColonProtectionRAIIObject &ColonProt) {
3143 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3144 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3145 assert(isTypeIdInParens() && "Not a type-id!");
3147 ExprResult Result(true);
3150 // We need to disambiguate a very ugly part of the C++ syntax:
3152 // (T())x; - type-id
3153 // (T())*x; - type-id
3154 // (T())/x; - expression
3155 // (T()); - expression
3157 // The bad news is that we cannot use the specialized tentative parser, since
3158 // it can only verify that the thing inside the parens can be parsed as
3159 // type-id, it is not useful for determining the context past the parens.
3161 // The good news is that the parser can disambiguate this part without
3162 // making any unnecessary Action calls.
3164 // It uses a scheme similar to parsing inline methods. The parenthesized
3165 // tokens are cached, the context that follows is determined (possibly by
3166 // parsing a cast-expression), and then we re-introduce the cached tokens
3167 // into the token stream and parse them appropriately.
3169 ParenParseOption ParseAs;
3172 // Store the tokens of the parentheses. We will parse them after we determine
3173 // the context that follows them.
3174 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3175 // We didn't find the ')' we expected.
3176 Tracker.consumeClose();
3180 if (Tok.is(tok::l_brace)) {
3181 ParseAs = CompoundLiteral;
3184 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3187 // Try parsing the cast-expression that may follow.
3188 // If it is not a cast-expression, NotCastExpr will be true and no token
3189 // will be consumed.
3190 ColonProt.restore();
3191 Result = ParseCastExpression(false/*isUnaryExpression*/,
3192 false/*isAddressofOperand*/,
3194 // type-id has priority.
3198 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3200 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3203 // Create a fake EOF to mark end of Toks buffer.
3205 AttrEnd.startToken();
3206 AttrEnd.setKind(tok::eof);
3207 AttrEnd.setLocation(Tok.getLocation());
3208 AttrEnd.setEofData(Toks.data());
3209 Toks.push_back(AttrEnd);
3211 // The current token should go after the cached tokens.
3212 Toks.push_back(Tok);
3213 // Re-enter the stored parenthesized tokens into the token stream, so we may
3215 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
3216 // Drop the current token and bring the first cached one. It's the same token
3217 // as when we entered this function.
3220 if (ParseAs >= CompoundLiteral) {
3221 // Parse the type declarator.
3222 DeclSpec DS(AttrFactory);
3223 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
3225 ColonProtectionRAIIObject InnerColonProtection(*this);
3226 ParseSpecifierQualifierList(DS);
3227 ParseDeclarator(DeclaratorInfo);
3231 Tracker.consumeClose();
3232 ColonProt.restore();
3234 // Consume EOF marker for Toks buffer.
3235 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3238 if (ParseAs == CompoundLiteral) {
3239 ExprType = CompoundLiteral;
3240 if (DeclaratorInfo.isInvalidType())
3243 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3244 return ParseCompoundLiteralExpression(Ty.get(),
3245 Tracker.getOpenLocation(),
3246 Tracker.getCloseLocation());
3249 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3250 assert(ParseAs == CastExpr);
3252 if (DeclaratorInfo.isInvalidType())
3255 // Result is what ParseCastExpression returned earlier.
3256 if (!Result.isInvalid())
3257 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3258 DeclaratorInfo, CastTy,
3259 Tracker.getCloseLocation(), Result.get());
3263 // Not a compound literal, and not followed by a cast-expression.
3264 assert(ParseAs == SimpleExpr);
3266 ExprType = SimpleExpr;
3267 Result = ParseExpression();
3268 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3269 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3270 Tok.getLocation(), Result.get());
3273 if (Result.isInvalid()) {
3274 while (Tok.isNot(tok::eof))
3276 assert(Tok.getEofData() == AttrEnd.getEofData());
3281 Tracker.consumeClose();
3282 // Consume EOF marker for Toks buffer.
3283 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());