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 /// \brief 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(),
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 // code 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() != UnqualifiedId::IK_OperatorFunctionId &&
296 TemplateName.getKind() != UnqualifiedId::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.
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, SourceLocation(), 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 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
565 Tok.is(tok::l_paren), isAddressOfOperand,
566 nullptr, /*IsInlineAsmIdentifier=*/false,
570 /// ParseCXXIdExpression - Handle id-expression.
577 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
579 /// '::' operator-function-id
582 /// NOTE: The standard specifies that, for qualified-id, the parser does not
585 /// '::' conversion-function-id
586 /// '::' '~' class-name
588 /// This may cause a slight inconsistency on diagnostics:
593 /// :: A :: ~ C(); // Some Sema error about using destructor with a
595 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
598 /// We simplify the parser a bit and make it work like:
601 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
602 /// '::' unqualified-id
604 /// That way Sema can handle and report similar errors for namespaces and the
607 /// The isAddressOfOperand parameter indicates that this id-expression is a
608 /// direct operand of the address-of operator. This is, besides member contexts,
609 /// the only place where a qualified-id naming a non-static class member may
612 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
614 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
615 // '::' unqualified-id
618 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
622 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
623 if (Result.isUnset()) {
624 // If the ExprResult is valid but null, then typo correction suggested a
625 // keyword replacement that needs to be reparsed.
626 UnconsumeToken(Replacement);
627 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
629 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
630 "for a previous keyword suggestion");
634 /// ParseLambdaExpression - Parse a C++11 lambda expression.
636 /// lambda-expression:
637 /// lambda-introducer lambda-declarator[opt] compound-statement
639 /// lambda-introducer:
640 /// '[' lambda-capture[opt] ']'
645 /// capture-default ',' capture-list
653 /// capture-list ',' capture
657 /// init-capture [C++1y]
664 /// init-capture: [C++1y]
665 /// identifier initializer
666 /// '&' identifier initializer
668 /// lambda-declarator:
669 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
670 /// 'mutable'[opt] exception-specification[opt]
671 /// trailing-return-type[opt]
673 ExprResult Parser::ParseLambdaExpression() {
674 // Parse lambda-introducer.
675 LambdaIntroducer Intro;
676 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
678 Diag(Tok, DiagID.getValue());
679 SkipUntil(tok::r_square, StopAtSemi);
680 SkipUntil(tok::l_brace, StopAtSemi);
681 SkipUntil(tok::r_brace, StopAtSemi);
685 return ParseLambdaExpressionAfterIntroducer(Intro);
688 /// TryParseLambdaExpression - Use lookahead and potentially tentative
689 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
692 /// If we are not looking at a lambda expression, returns ExprError().
693 ExprResult Parser::TryParseLambdaExpression() {
694 assert(getLangOpts().CPlusPlus11
695 && Tok.is(tok::l_square)
696 && "Not at the start of a possible lambda expression.");
698 const Token Next = NextToken();
699 if (Next.is(tok::eof)) // Nothing else to lookup here...
702 const Token After = GetLookAheadToken(2);
703 // If lookahead indicates this is a lambda...
704 if (Next.is(tok::r_square) || // []
705 Next.is(tok::equal) || // [=
706 (Next.is(tok::amp) && // [&] or [&,
707 (After.is(tok::r_square) ||
708 After.is(tok::comma))) ||
709 (Next.is(tok::identifier) && // [identifier]
710 After.is(tok::r_square))) {
711 return ParseLambdaExpression();
714 // If lookahead indicates an ObjC message send...
715 // [identifier identifier
716 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
720 // Here, we're stuck: lambda introducers and Objective-C message sends are
721 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
722 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
723 // writing two routines to parse a lambda introducer, just try to parse
724 // a lambda introducer first, and fall back if that fails.
725 // (TryParseLambdaIntroducer never produces any diagnostic output.)
726 LambdaIntroducer Intro;
727 if (TryParseLambdaIntroducer(Intro))
730 return ParseLambdaExpressionAfterIntroducer(Intro);
733 /// \brief Parse a lambda introducer.
734 /// \param Intro A LambdaIntroducer filled in with information about the
735 /// contents of the lambda-introducer.
736 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
737 /// message send and a lambda expression. In this mode, we will
738 /// sometimes skip the initializers for init-captures and not fully
739 /// populate \p Intro. This flag will be set to \c true if we do so.
740 /// \return A DiagnosticID if it hit something unexpected. The location for
741 /// the diagnostic is that of the current token.
742 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
743 bool *SkippedInits) {
744 typedef Optional<unsigned> DiagResult;
746 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
747 BalancedDelimiterTracker T(*this, tok::l_square);
750 Intro.Range.setBegin(T.getOpenLocation());
754 // Parse capture-default.
755 if (Tok.is(tok::amp) &&
756 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
757 Intro.Default = LCD_ByRef;
758 Intro.DefaultLoc = ConsumeToken();
760 } else if (Tok.is(tok::equal)) {
761 Intro.Default = LCD_ByCopy;
762 Intro.DefaultLoc = ConsumeToken();
766 while (Tok.isNot(tok::r_square)) {
768 if (Tok.isNot(tok::comma)) {
769 // Provide a completion for a lambda introducer here. Except
770 // in Objective-C, where this is Almost Surely meant to be a message
771 // send. In that case, fail here and let the ObjC message
772 // expression parser perform the completion.
773 if (Tok.is(tok::code_completion) &&
774 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
775 !Intro.Captures.empty())) {
776 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
777 /*AfterAmpersand=*/false);
782 return DiagResult(diag::err_expected_comma_or_rsquare);
787 if (Tok.is(tok::code_completion)) {
788 // If we're in Objective-C++ and we have a bare '[', then this is more
789 // likely to be a message receiver.
790 if (getLangOpts().ObjC1 && first)
791 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
793 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
794 /*AfterAmpersand=*/false);
802 LambdaCaptureKind Kind = LCK_ByCopy;
803 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
805 IdentifierInfo *Id = nullptr;
806 SourceLocation EllipsisLoc;
809 if (Tok.is(tok::star)) {
810 Loc = ConsumeToken();
811 if (Tok.is(tok::kw_this)) {
815 return DiagResult(diag::err_expected_star_this_capture);
817 } else if (Tok.is(tok::kw_this)) {
819 Loc = ConsumeToken();
821 if (Tok.is(tok::amp)) {
825 if (Tok.is(tok::code_completion)) {
826 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
827 /*AfterAmpersand=*/true);
833 if (Tok.is(tok::identifier)) {
834 Id = Tok.getIdentifierInfo();
835 Loc = ConsumeToken();
836 } else if (Tok.is(tok::kw_this)) {
837 // FIXME: If we want to suggest a fixit here, will need to return more
838 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
839 // Clear()ed to prevent emission in case of tentative parsing?
840 return DiagResult(diag::err_this_captured_by_reference);
842 return DiagResult(diag::err_expected_capture);
845 if (Tok.is(tok::l_paren)) {
846 BalancedDelimiterTracker Parens(*this, tok::l_paren);
847 Parens.consumeOpen();
849 InitKind = LambdaCaptureInitKind::DirectInit;
855 *SkippedInits = true;
856 } else if (ParseExpressionList(Exprs, Commas)) {
860 Parens.consumeClose();
861 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
862 Parens.getCloseLocation(),
865 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
866 // Each lambda init-capture forms its own full expression, which clears
867 // Actions.MaybeODRUseExprs. So create an expression evaluation context
868 // to save the necessary state, and restore it later.
869 EnterExpressionEvaluationContext EC(
870 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
872 if (TryConsumeToken(tok::equal))
873 InitKind = LambdaCaptureInitKind::CopyInit;
875 InitKind = LambdaCaptureInitKind::ListInit;
878 Init = ParseInitializer();
879 } else if (Tok.is(tok::l_brace)) {
880 BalancedDelimiterTracker Braces(*this, tok::l_brace);
881 Braces.consumeOpen();
883 *SkippedInits = true;
885 // We're disambiguating this:
889 // We need to find the end of the following expression in order to
890 // determine whether this is an Obj-C message send's receiver, a
891 // C99 designator, or a lambda init-capture.
893 // Parse the expression to find where it ends, and annotate it back
894 // onto the tokens. We would have parsed this expression the same way
895 // in either case: both the RHS of an init-capture and the RHS of an
896 // assignment expression are parsed as an initializer-clause, and in
897 // neither case can anything be added to the scope between the '[' and
900 // FIXME: This is horrible. Adding a mechanism to skip an expression
901 // would be much cleaner.
902 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
903 // that instead. (And if we see a ':' with no matching '?', we can
904 // classify this as an Obj-C message send.)
905 SourceLocation StartLoc = Tok.getLocation();
906 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
907 Init = ParseInitializer();
908 if (!Init.isInvalid())
909 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
911 if (Tok.getLocation() != StartLoc) {
912 // Back out the lexing of the token after the initializer.
913 PP.RevertCachedTokens(1);
915 // Replace the consumed tokens with an appropriate annotation.
916 Tok.setLocation(StartLoc);
917 Tok.setKind(tok::annot_primary_expr);
918 setExprAnnotation(Tok, Init);
919 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
920 PP.AnnotateCachedTokens(Tok);
922 // Consume the annotated initializer.
927 TryConsumeToken(tok::ellipsis, EllipsisLoc);
929 // If this is an init capture, process the initialization expression
930 // right away. For lambda init-captures such as the following:
932 // auto L = [i = x+1](int a) {
934 // &k = x](char b) { };
936 // keep in mind that each lambda init-capture has to have:
937 // - its initialization expression executed in the context
938 // of the enclosing/parent decl-context.
939 // - but the variable itself has to be 'injected' into the
940 // decl-context of its lambda's call-operator (which has
941 // not yet been created).
942 // Each init-expression is a full-expression that has to get
943 // Sema-analyzed (for capturing etc.) before its lambda's
944 // call-operator's decl-context, scope & scopeinfo are pushed on their
945 // respective stacks. Thus if any variable is odr-used in the init-capture
946 // it will correctly get captured in the enclosing lambda, if one exists.
947 // The init-variables above are created later once the lambdascope and
948 // call-operators decl-context is pushed onto its respective stack.
950 // Since the lambda init-capture's initializer expression occurs in the
951 // context of the enclosing function or lambda, therefore we can not wait
952 // till a lambda scope has been pushed on before deciding whether the
953 // variable needs to be captured. We also need to process all
954 // lvalue-to-rvalue conversions and discarded-value conversions,
955 // so that we can avoid capturing certain constant variables.
959 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
960 // return [y = x](int i) { <-- don't capture by enclosing lambda
965 // If x was not const, the second use would require 'L' to capture, and
966 // that would be an error.
968 ParsedType InitCaptureType;
969 if (Init.isUsable()) {
970 // Get the pointer and store it in an lvalue, so we can use it as an
972 Expr *InitExpr = Init.get();
973 // This performs any lvalue-to-rvalue conversions if necessary, which
974 // can affect what gets captured in the containing decl-context.
975 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
976 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
979 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
984 Intro.Range.setEnd(T.getCloseLocation());
988 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
990 /// Returns true if it hit something unexpected.
991 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
992 TentativeParsingAction PA(*this);
994 bool SkippedInits = false;
995 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
1003 // Parse it again, but this time parse the init-captures too.
1005 Intro = LambdaIntroducer();
1006 DiagID = ParseLambdaIntroducer(Intro);
1007 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1016 tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1017 SourceLocation &ConstexprLoc,
1018 SourceLocation &DeclEndLoc) {
1019 assert(MutableLoc.isInvalid());
1020 assert(ConstexprLoc.isInvalid());
1021 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1022 // to the final of those locations. Emit an error if we have multiple
1023 // copies of those keywords and recover.
1026 switch (P.getCurToken().getKind()) {
1027 case tok::kw_mutable: {
1028 if (MutableLoc.isValid()) {
1029 P.Diag(P.getCurToken().getLocation(),
1030 diag::err_lambda_decl_specifier_repeated)
1031 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1033 MutableLoc = P.ConsumeToken();
1034 DeclEndLoc = MutableLoc;
1037 case tok::kw_constexpr:
1038 if (ConstexprLoc.isValid()) {
1039 P.Diag(P.getCurToken().getLocation(),
1040 diag::err_lambda_decl_specifier_repeated)
1041 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1043 ConstexprLoc = P.ConsumeToken();
1044 DeclEndLoc = ConstexprLoc;
1053 addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1055 if (ConstexprLoc.isValid()) {
1056 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus1z
1057 ? diag::ext_constexpr_on_lambda_cxx1z
1058 : diag::warn_cxx14_compat_constexpr_on_lambda);
1059 const char *PrevSpec = nullptr;
1060 unsigned DiagID = 0;
1061 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1062 assert(PrevSpec == nullptr && DiagID == 0 &&
1063 "Constexpr cannot have been set previously!");
1067 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1069 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1070 LambdaIntroducer &Intro) {
1071 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1072 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1074 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1075 "lambda expression parsing");
1079 // FIXME: Call into Actions to add any init-capture declarations to the
1080 // scope while parsing the lambda-declarator and compound-statement.
1082 // Parse lambda-declarator[opt].
1083 DeclSpec DS(AttrFactory);
1084 Declarator D(DS, Declarator::LambdaExprContext);
1085 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1086 Actions.PushLambdaScope();
1088 ParsedAttributes Attr(AttrFactory);
1089 SourceLocation DeclLoc = Tok.getLocation();
1090 if (getLangOpts().CUDA) {
1091 // In CUDA code, GNU attributes are allowed to appear immediately after the
1092 // "[...]", even if there is no "(...)" before the lambda body.
1093 MaybeParseGNUAttributes(D);
1096 // Helper to emit a warning if we see a CUDA host/device/global attribute
1097 // after '(...)'. nvcc doesn't accept this.
1098 auto WarnIfHasCUDATargetAttr = [&] {
1099 if (getLangOpts().CUDA)
1100 for (auto *A = Attr.getList(); A != nullptr; A = A->getNext())
1101 if (A->getKind() == AttributeList::AT_CUDADevice ||
1102 A->getKind() == AttributeList::AT_CUDAHost ||
1103 A->getKind() == AttributeList::AT_CUDAGlobal)
1104 Diag(A->getLoc(), diag::warn_cuda_attr_lambda_position)
1105 << A->getName()->getName();
1108 TypeResult TrailingReturnType;
1109 if (Tok.is(tok::l_paren)) {
1110 ParseScope PrototypeScope(this,
1111 Scope::FunctionPrototypeScope |
1112 Scope::FunctionDeclarationScope |
1115 BalancedDelimiterTracker T(*this, tok::l_paren);
1117 SourceLocation LParenLoc = T.getOpenLocation();
1119 // Parse parameter-declaration-clause.
1120 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1121 SourceLocation EllipsisLoc;
1123 if (Tok.isNot(tok::r_paren)) {
1124 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1125 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1126 // For a generic lambda, each 'auto' within the parameter declaration
1127 // clause creates a template type parameter, so increment the depth.
1128 if (Actions.getCurGenericLambda())
1129 ++CurTemplateDepthTracker;
1132 SourceLocation RParenLoc = T.getCloseLocation();
1133 SourceLocation DeclEndLoc = RParenLoc;
1135 // GNU-style attributes must be parsed before the mutable specifier to be
1136 // compatible with GCC.
1137 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1139 // MSVC-style attributes must be parsed before the mutable specifier to be
1140 // compatible with MSVC.
1141 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1143 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
1144 SourceLocation MutableLoc;
1145 SourceLocation ConstexprLoc;
1146 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1149 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1151 // Parse exception-specification[opt].
1152 ExceptionSpecificationType ESpecType = EST_None;
1153 SourceRange ESpecRange;
1154 SmallVector<ParsedType, 2> DynamicExceptions;
1155 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1156 ExprResult NoexceptExpr;
1157 CachedTokens *ExceptionSpecTokens;
1158 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1161 DynamicExceptionRanges,
1163 ExceptionSpecTokens);
1165 if (ESpecType != EST_None)
1166 DeclEndLoc = ESpecRange.getEnd();
1168 // Parse attribute-specifier[opt].
1169 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1171 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1173 // Parse trailing-return-type[opt].
1174 if (Tok.is(tok::arrow)) {
1175 FunLocalRangeEnd = Tok.getLocation();
1177 TrailingReturnType = ParseTrailingReturnType(Range);
1178 if (Range.getEnd().isValid())
1179 DeclEndLoc = Range.getEnd();
1182 PrototypeScope.Exit();
1184 WarnIfHasCUDATargetAttr();
1186 SourceLocation NoLoc;
1187 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1188 /*isAmbiguous=*/false,
1190 ParamInfo.data(), ParamInfo.size(),
1191 EllipsisLoc, RParenLoc,
1192 DS.getTypeQualifiers(),
1193 /*RefQualifierIsLValueRef=*/true,
1194 /*RefQualifierLoc=*/NoLoc,
1195 /*ConstQualifierLoc=*/NoLoc,
1196 /*VolatileQualifierLoc=*/NoLoc,
1197 /*RestrictQualifierLoc=*/NoLoc,
1199 ESpecType, ESpecRange,
1200 DynamicExceptions.data(),
1201 DynamicExceptionRanges.data(),
1202 DynamicExceptions.size(),
1203 NoexceptExpr.isUsable() ?
1204 NoexceptExpr.get() : nullptr,
1205 /*ExceptionSpecTokens*/nullptr,
1206 /*DeclsInPrototype=*/None,
1207 LParenLoc, FunLocalRangeEnd, D,
1208 TrailingReturnType),
1210 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1211 tok::kw_constexpr) ||
1212 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1213 // It's common to forget that one needs '()' before 'mutable', an attribute
1214 // specifier, or the result type. Deal with this.
1215 unsigned TokKind = 0;
1216 switch (Tok.getKind()) {
1217 case tok::kw_mutable: TokKind = 0; break;
1218 case tok::arrow: TokKind = 1; break;
1219 case tok::kw___attribute:
1220 case tok::l_square: TokKind = 2; break;
1221 case tok::kw_constexpr: TokKind = 3; break;
1222 default: llvm_unreachable("Unknown token kind");
1225 Diag(Tok, diag::err_lambda_missing_parens)
1227 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1228 SourceLocation DeclEndLoc = DeclLoc;
1230 // GNU-style attributes must be parsed before the mutable specifier to be
1231 // compatible with GCC.
1232 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1234 // Parse 'mutable', if it's there.
1235 SourceLocation MutableLoc;
1236 if (Tok.is(tok::kw_mutable)) {
1237 MutableLoc = ConsumeToken();
1238 DeclEndLoc = MutableLoc;
1241 // Parse attribute-specifier[opt].
1242 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1244 // Parse the return type, if there is one.
1245 if (Tok.is(tok::arrow)) {
1247 TrailingReturnType = ParseTrailingReturnType(Range);
1248 if (Range.getEnd().isValid())
1249 DeclEndLoc = Range.getEnd();
1252 WarnIfHasCUDATargetAttr();
1254 SourceLocation NoLoc;
1255 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1256 /*isAmbiguous=*/false,
1257 /*LParenLoc=*/NoLoc,
1260 /*EllipsisLoc=*/NoLoc,
1261 /*RParenLoc=*/NoLoc,
1263 /*RefQualifierIsLValueRef=*/true,
1264 /*RefQualifierLoc=*/NoLoc,
1265 /*ConstQualifierLoc=*/NoLoc,
1266 /*VolatileQualifierLoc=*/NoLoc,
1267 /*RestrictQualifierLoc=*/NoLoc,
1270 /*ESpecRange=*/SourceRange(),
1271 /*Exceptions=*/nullptr,
1272 /*ExceptionRanges=*/nullptr,
1273 /*NumExceptions=*/0,
1274 /*NoexceptExpr=*/nullptr,
1275 /*ExceptionSpecTokens=*/nullptr,
1276 /*DeclsInPrototype=*/None,
1277 DeclLoc, DeclEndLoc, D,
1278 TrailingReturnType),
1282 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1284 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
1285 ParseScope BodyScope(this, ScopeFlags);
1287 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1289 // Parse compound-statement.
1290 if (!Tok.is(tok::l_brace)) {
1291 Diag(Tok, diag::err_expected_lambda_body);
1292 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1296 StmtResult Stmt(ParseCompoundStatementBody());
1299 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1300 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1302 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1306 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1309 /// postfix-expression: [C++ 5.2p1]
1310 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1311 /// 'static_cast' '<' type-name '>' '(' expression ')'
1312 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1313 /// 'const_cast' '<' type-name '>' '(' expression ')'
1315 ExprResult Parser::ParseCXXCasts() {
1316 tok::TokenKind Kind = Tok.getKind();
1317 const char *CastName = nullptr; // For error messages
1320 default: llvm_unreachable("Unknown C++ cast!");
1321 case tok::kw_const_cast: CastName = "const_cast"; break;
1322 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1323 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1324 case tok::kw_static_cast: CastName = "static_cast"; break;
1327 SourceLocation OpLoc = ConsumeToken();
1328 SourceLocation LAngleBracketLoc = Tok.getLocation();
1330 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1331 // diagnose error, suggest fix, and recover parsing.
1332 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1333 Token Next = NextToken();
1334 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1335 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1338 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1341 // Parse the common declaration-specifiers piece.
1342 DeclSpec DS(AttrFactory);
1343 ParseSpecifierQualifierList(DS);
1345 // Parse the abstract-declarator, if present.
1346 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1347 ParseDeclarator(DeclaratorInfo);
1349 SourceLocation RAngleBracketLoc = Tok.getLocation();
1351 if (ExpectAndConsume(tok::greater))
1352 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1354 SourceLocation LParenLoc, RParenLoc;
1355 BalancedDelimiterTracker T(*this, tok::l_paren);
1357 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1360 ExprResult Result = ParseExpression();
1365 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1366 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1367 LAngleBracketLoc, DeclaratorInfo,
1369 T.getOpenLocation(), Result.get(),
1370 T.getCloseLocation());
1375 /// ParseCXXTypeid - This handles the C++ typeid expression.
1377 /// postfix-expression: [C++ 5.2p1]
1378 /// 'typeid' '(' expression ')'
1379 /// 'typeid' '(' type-id ')'
1381 ExprResult Parser::ParseCXXTypeid() {
1382 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1384 SourceLocation OpLoc = ConsumeToken();
1385 SourceLocation LParenLoc, RParenLoc;
1386 BalancedDelimiterTracker T(*this, tok::l_paren);
1388 // typeid expressions are always parenthesized.
1389 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1391 LParenLoc = T.getOpenLocation();
1395 // C++0x [expr.typeid]p3:
1396 // When typeid is applied to an expression other than an lvalue of a
1397 // polymorphic class type [...] The expression is an unevaluated
1398 // operand (Clause 5).
1400 // Note that we can't tell whether the expression is an lvalue of a
1401 // polymorphic class type until after we've parsed the expression; we
1402 // speculatively assume the subexpression is unevaluated, and fix it up
1405 // We enter the unevaluated context before trying to determine whether we
1406 // have a type-id, because the tentative parse logic will try to resolve
1407 // names, and must treat them as unevaluated.
1408 EnterExpressionEvaluationContext Unevaluated(
1409 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1410 Sema::ReuseLambdaContextDecl);
1412 if (isTypeIdInParens()) {
1413 TypeResult Ty = ParseTypeName();
1417 RParenLoc = T.getCloseLocation();
1418 if (Ty.isInvalid() || RParenLoc.isInvalid())
1421 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1422 Ty.get().getAsOpaquePtr(), RParenLoc);
1424 Result = ParseExpression();
1427 if (Result.isInvalid())
1428 SkipUntil(tok::r_paren, StopAtSemi);
1431 RParenLoc = T.getCloseLocation();
1432 if (RParenLoc.isInvalid())
1435 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1436 Result.get(), RParenLoc);
1443 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1445 /// '__uuidof' '(' expression ')'
1446 /// '__uuidof' '(' type-id ')'
1448 ExprResult Parser::ParseCXXUuidof() {
1449 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1451 SourceLocation OpLoc = ConsumeToken();
1452 BalancedDelimiterTracker T(*this, tok::l_paren);
1454 // __uuidof expressions are always parenthesized.
1455 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1460 if (isTypeIdInParens()) {
1461 TypeResult Ty = ParseTypeName();
1469 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1470 Ty.get().getAsOpaquePtr(),
1471 T.getCloseLocation());
1473 EnterExpressionEvaluationContext Unevaluated(
1474 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1475 Result = ParseExpression();
1478 if (Result.isInvalid())
1479 SkipUntil(tok::r_paren, StopAtSemi);
1483 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1485 Result.get(), T.getCloseLocation());
1492 /// \brief Parse a C++ pseudo-destructor expression after the base,
1493 /// . or -> operator, and nested-name-specifier have already been
1496 /// postfix-expression: [C++ 5.2]
1497 /// postfix-expression . pseudo-destructor-name
1498 /// postfix-expression -> pseudo-destructor-name
1500 /// pseudo-destructor-name:
1501 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1502 /// ::[opt] nested-name-specifier template simple-template-id ::
1504 /// ::[opt] nested-name-specifier[opt] ~type-name
1507 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1508 tok::TokenKind OpKind,
1510 ParsedType ObjectType) {
1511 // We're parsing either a pseudo-destructor-name or a dependent
1512 // member access that has the same form as a
1513 // pseudo-destructor-name. We parse both in the same way and let
1514 // the action model sort them out.
1516 // Note that the ::[opt] nested-name-specifier[opt] has already
1517 // been parsed, and if there was a simple-template-id, it has
1518 // been coalesced into a template-id annotation token.
1519 UnqualifiedId FirstTypeName;
1520 SourceLocation CCLoc;
1521 if (Tok.is(tok::identifier)) {
1522 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1524 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1525 CCLoc = ConsumeToken();
1526 } else if (Tok.is(tok::annot_template_id)) {
1527 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1528 // store it in the pseudo-dtor node (to be used when instantiating it).
1529 FirstTypeName.setTemplateId(
1530 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1532 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1533 CCLoc = ConsumeToken();
1535 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1539 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1540 SourceLocation TildeLoc = ConsumeToken();
1542 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1543 DeclSpec DS(AttrFactory);
1544 ParseDecltypeSpecifier(DS);
1545 if (DS.getTypeSpecType() == TST_error)
1547 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1551 if (!Tok.is(tok::identifier)) {
1552 Diag(Tok, diag::err_destructor_tilde_identifier);
1556 // Parse the second type.
1557 UnqualifiedId SecondTypeName;
1558 IdentifierInfo *Name = Tok.getIdentifierInfo();
1559 SourceLocation NameLoc = ConsumeToken();
1560 SecondTypeName.setIdentifier(Name, NameLoc);
1562 // If there is a '<', the second type name is a template-id. Parse
1564 if (Tok.is(tok::less) &&
1565 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1567 false, ObjectType, SecondTypeName,
1568 /*AssumeTemplateName=*/true))
1571 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1572 SS, FirstTypeName, CCLoc, TildeLoc,
1576 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1578 /// boolean-literal: [C++ 2.13.5]
1581 ExprResult Parser::ParseCXXBoolLiteral() {
1582 tok::TokenKind Kind = Tok.getKind();
1583 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1586 /// ParseThrowExpression - This handles the C++ throw expression.
1588 /// throw-expression: [C++ 15]
1589 /// 'throw' assignment-expression[opt]
1590 ExprResult Parser::ParseThrowExpression() {
1591 assert(Tok.is(tok::kw_throw) && "Not throw!");
1592 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1594 // If the current token isn't the start of an assignment-expression,
1595 // then the expression is not present. This handles things like:
1596 // "C ? throw : (void)42", which is crazy but legal.
1597 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1604 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1607 ExprResult Expr(ParseAssignmentExpression());
1608 if (Expr.isInvalid()) return Expr;
1609 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1613 /// \brief Parse the C++ Coroutines co_yield expression.
1615 /// co_yield-expression:
1616 /// 'co_yield' assignment-expression[opt]
1617 ExprResult Parser::ParseCoyieldExpression() {
1618 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1620 SourceLocation Loc = ConsumeToken();
1621 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1622 : ParseAssignmentExpression();
1623 if (!Expr.isInvalid())
1624 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1628 /// ParseCXXThis - This handles the C++ 'this' pointer.
1630 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1631 /// a non-lvalue expression whose value is the address of the object for which
1632 /// the function is called.
1633 ExprResult Parser::ParseCXXThis() {
1634 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1635 SourceLocation ThisLoc = ConsumeToken();
1636 return Actions.ActOnCXXThis(ThisLoc);
1639 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1640 /// Can be interpreted either as function-style casting ("int(x)")
1641 /// or class type construction ("ClassType(x,y,z)")
1642 /// or creation of a value-initialized type ("int()").
1643 /// See [C++ 5.2.3].
1645 /// postfix-expression: [C++ 5.2p1]
1646 /// simple-type-specifier '(' expression-list[opt] ')'
1647 /// [C++0x] simple-type-specifier braced-init-list
1648 /// typename-specifier '(' expression-list[opt] ')'
1649 /// [C++0x] typename-specifier braced-init-list
1651 /// In C++1z onwards, the type specifier can also be a template-name.
1653 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1654 Declarator DeclaratorInfo(DS, Declarator::FunctionalCastContext);
1655 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1657 assert((Tok.is(tok::l_paren) ||
1658 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1659 && "Expected '(' or '{'!");
1661 if (Tok.is(tok::l_brace)) {
1662 ExprResult Init = ParseBraceInitializer();
1663 if (Init.isInvalid())
1665 Expr *InitList = Init.get();
1666 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1667 MultiExprArg(&InitList, 1),
1670 BalancedDelimiterTracker T(*this, tok::l_paren);
1674 CommaLocsTy CommaLocs;
1676 if (Tok.isNot(tok::r_paren)) {
1677 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1678 Actions.CodeCompleteConstructor(getCurScope(),
1679 TypeRep.get()->getCanonicalTypeInternal(),
1680 DS.getLocEnd(), Exprs);
1682 SkipUntil(tok::r_paren, StopAtSemi);
1690 // TypeRep could be null, if it references an invalid typedef.
1694 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1695 "Unexpected number of commas!");
1696 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1698 T.getCloseLocation());
1702 /// ParseCXXCondition - if/switch/while condition expression.
1706 /// type-specifier-seq declarator '=' assignment-expression
1707 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1708 /// [C++11] type-specifier-seq declarator braced-init-list
1709 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1710 /// '=' assignment-expression
1712 /// In C++1z, a condition may in some contexts be preceded by an
1713 /// optional init-statement. This function will parse that too.
1715 /// \param InitStmt If non-null, an init-statement is permitted, and if present
1716 /// will be parsed and stored here.
1718 /// \param Loc The location of the start of the statement that requires this
1719 /// condition, e.g., the "for" in a for loop.
1721 /// \returns The parsed condition.
1722 Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1724 Sema::ConditionKind CK) {
1725 if (Tok.is(tok::code_completion)) {
1726 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1728 return Sema::ConditionError();
1731 ParsedAttributesWithRange attrs(AttrFactory);
1732 MaybeParseCXX11Attributes(attrs);
1734 // Determine what kind of thing we have.
1735 switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
1736 case ConditionOrInitStatement::Expression: {
1737 ProhibitAttributes(attrs);
1739 // Parse the expression.
1740 ExprResult Expr = ParseExpression(); // expression
1741 if (Expr.isInvalid())
1742 return Sema::ConditionError();
1744 if (InitStmt && Tok.is(tok::semi)) {
1745 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1747 return ParseCXXCondition(nullptr, Loc, CK);
1750 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
1753 case ConditionOrInitStatement::InitStmtDecl: {
1754 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
1755 ? diag::warn_cxx14_compat_init_statement
1756 : diag::ext_init_statement)
1757 << (CK == Sema::ConditionKind::Switch);
1758 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1759 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1760 Declarator::InitStmtContext, DeclEnd, attrs, /*RequireSemi=*/true);
1761 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1762 return ParseCXXCondition(nullptr, Loc, CK);
1765 case ConditionOrInitStatement::ConditionDecl:
1766 case ConditionOrInitStatement::Error:
1770 // type-specifier-seq
1771 DeclSpec DS(AttrFactory);
1772 DS.takeAttributesFrom(attrs);
1773 ParseSpecifierQualifierList(DS, AS_none, DSC_condition);
1776 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1777 ParseDeclarator(DeclaratorInfo);
1779 // simple-asm-expr[opt]
1780 if (Tok.is(tok::kw_asm)) {
1782 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1783 if (AsmLabel.isInvalid()) {
1784 SkipUntil(tok::semi, StopAtSemi);
1785 return Sema::ConditionError();
1787 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1788 DeclaratorInfo.SetRangeEnd(Loc);
1791 // If attributes are present, parse them.
1792 MaybeParseGNUAttributes(DeclaratorInfo);
1794 // Type-check the declaration itself.
1795 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1797 if (Dcl.isInvalid())
1798 return Sema::ConditionError();
1799 Decl *DeclOut = Dcl.get();
1801 // '=' assignment-expression
1802 // If a '==' or '+=' is found, suggest a fixit to '='.
1803 bool CopyInitialization = isTokenEqualOrEqualTypo();
1804 if (CopyInitialization)
1807 ExprResult InitExpr = ExprError();
1808 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1809 Diag(Tok.getLocation(),
1810 diag::warn_cxx98_compat_generalized_initializer_lists);
1811 InitExpr = ParseBraceInitializer();
1812 } else if (CopyInitialization) {
1813 InitExpr = ParseAssignmentExpression();
1814 } else if (Tok.is(tok::l_paren)) {
1815 // This was probably an attempt to initialize the variable.
1816 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1817 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1818 RParen = ConsumeParen();
1819 Diag(DeclOut->getLocation(),
1820 diag::err_expected_init_in_condition_lparen)
1821 << SourceRange(LParen, RParen);
1823 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
1826 if (!InitExpr.isInvalid())
1827 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
1829 Actions.ActOnInitializerError(DeclOut);
1831 Actions.FinalizeDeclaration(DeclOut);
1832 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
1835 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1836 /// This should only be called when the current token is known to be part of
1837 /// simple-type-specifier.
1839 /// simple-type-specifier:
1840 /// '::'[opt] nested-name-specifier[opt] type-name
1841 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1853 /// [GNU] typeof-specifier
1854 /// [C++0x] auto [TODO]
1861 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1862 DS.SetRangeStart(Tok.getLocation());
1863 const char *PrevSpec;
1865 SourceLocation Loc = Tok.getLocation();
1866 const clang::PrintingPolicy &Policy =
1867 Actions.getASTContext().getPrintingPolicy();
1869 switch (Tok.getKind()) {
1870 case tok::identifier: // foo::bar
1871 case tok::coloncolon: // ::foo::bar
1872 llvm_unreachable("Annotation token should already be formed!");
1874 llvm_unreachable("Not a simple-type-specifier token!");
1877 case tok::annot_typename: {
1878 if (getTypeAnnotation(Tok))
1879 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1880 getTypeAnnotation(Tok), Policy);
1882 DS.SetTypeSpecError();
1884 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1887 DS.Finish(Actions, Policy);
1893 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1896 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1898 case tok::kw___int64:
1899 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1901 case tok::kw_signed:
1902 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1904 case tok::kw_unsigned:
1905 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1908 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1911 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1914 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1916 case tok::kw___int128:
1917 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1920 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1923 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1925 case tok::kw_double:
1926 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1928 case tok::kw___float128:
1929 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1931 case tok::kw_wchar_t:
1932 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1934 case tok::kw_char16_t:
1935 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1937 case tok::kw_char32_t:
1938 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1941 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1943 case tok::annot_decltype:
1944 case tok::kw_decltype:
1945 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1946 return DS.Finish(Actions, Policy);
1948 // GNU typeof support.
1949 case tok::kw_typeof:
1950 ParseTypeofSpecifier(DS);
1951 DS.Finish(Actions, Policy);
1954 if (Tok.is(tok::annot_typename))
1955 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1957 DS.SetRangeEnd(Tok.getLocation());
1959 DS.Finish(Actions, Policy);
1962 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1963 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1964 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1965 /// by parsing the type-specifier-seq, because these sequences are
1966 /// typically followed by some form of declarator. Returns true and
1967 /// emits diagnostics if this is not a type-specifier-seq, false
1970 /// type-specifier-seq: [C++ 8.1]
1971 /// type-specifier type-specifier-seq[opt]
1973 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1974 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1975 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
1979 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1982 /// This routine is invoked when a '<' is encountered after an identifier or
1983 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1984 /// whether the unqualified-id is actually a template-id. This routine will
1985 /// then parse the template arguments and form the appropriate template-id to
1986 /// return to the caller.
1988 /// \param SS the nested-name-specifier that precedes this template-id, if
1989 /// we're actually parsing a qualified-id.
1991 /// \param Name for constructor and destructor names, this is the actual
1992 /// identifier that may be a template-name.
1994 /// \param NameLoc the location of the class-name in a constructor or
1997 /// \param EnteringContext whether we're entering the scope of the
1998 /// nested-name-specifier.
2000 /// \param ObjectType if this unqualified-id occurs within a member access
2001 /// expression, the type of the base object whose member is being accessed.
2003 /// \param Id as input, describes the template-name or operator-function-id
2004 /// that precedes the '<'. If template arguments were parsed successfully,
2005 /// will be updated with the template-id.
2007 /// \param AssumeTemplateId When true, this routine will assume that the name
2008 /// refers to a template without performing name lookup to verify.
2010 /// \returns true if a parse error occurred, false otherwise.
2011 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2012 SourceLocation TemplateKWLoc,
2013 IdentifierInfo *Name,
2014 SourceLocation NameLoc,
2015 bool EnteringContext,
2016 ParsedType ObjectType,
2018 bool AssumeTemplateId) {
2019 assert((AssumeTemplateId || Tok.is(tok::less)) &&
2020 "Expected '<' to finish parsing a template-id");
2022 TemplateTy Template;
2023 TemplateNameKind TNK = TNK_Non_template;
2024 switch (Id.getKind()) {
2025 case UnqualifiedId::IK_Identifier:
2026 case UnqualifiedId::IK_OperatorFunctionId:
2027 case UnqualifiedId::IK_LiteralOperatorId:
2028 if (AssumeTemplateId) {
2029 // We defer the injected-class-name checks until we've found whether
2030 // this template-id is used to form a nested-name-specifier or not.
2031 TNK = Actions.ActOnDependentTemplateName(
2032 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2033 Template, /*AllowInjectedClassName*/ true);
2034 if (TNK == TNK_Non_template)
2037 bool MemberOfUnknownSpecialization;
2038 TNK = Actions.isTemplateName(getCurScope(), SS,
2039 TemplateKWLoc.isValid(), Id,
2040 ObjectType, EnteringContext, Template,
2041 MemberOfUnknownSpecialization);
2043 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2044 ObjectType && IsTemplateArgumentList()) {
2045 // We have something like t->getAs<T>(), where getAs is a
2046 // member of an unknown specialization. However, this will only
2047 // parse correctly as a template, so suggest the keyword 'template'
2048 // before 'getAs' and treat this as a dependent template name.
2050 if (Id.getKind() == UnqualifiedId::IK_Identifier)
2051 Name = Id.Identifier->getName();
2054 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
2055 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2057 Name += Id.Identifier->getName();
2059 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2061 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2062 TNK = Actions.ActOnDependentTemplateName(
2063 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2064 Template, /*AllowInjectedClassName*/ true);
2065 if (TNK == TNK_Non_template)
2071 case UnqualifiedId::IK_ConstructorName: {
2072 UnqualifiedId TemplateName;
2073 bool MemberOfUnknownSpecialization;
2074 TemplateName.setIdentifier(Name, NameLoc);
2075 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2076 TemplateName, ObjectType,
2077 EnteringContext, Template,
2078 MemberOfUnknownSpecialization);
2082 case UnqualifiedId::IK_DestructorName: {
2083 UnqualifiedId TemplateName;
2084 bool MemberOfUnknownSpecialization;
2085 TemplateName.setIdentifier(Name, NameLoc);
2087 TNK = Actions.ActOnDependentTemplateName(
2088 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2089 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2090 if (TNK == TNK_Non_template)
2093 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2094 TemplateName, ObjectType,
2095 EnteringContext, Template,
2096 MemberOfUnknownSpecialization);
2098 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2099 Diag(NameLoc, diag::err_destructor_template_id)
2100 << Name << SS.getRange();
2111 if (TNK == TNK_Non_template)
2114 // Parse the enclosed template argument list.
2115 SourceLocation LAngleLoc, RAngleLoc;
2116 TemplateArgList TemplateArgs;
2117 if (Tok.is(tok::less) && ParseTemplateIdAfterTemplateName(
2118 true, LAngleLoc, TemplateArgs, RAngleLoc))
2121 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
2122 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2123 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
2124 // Form a parsed representation of the template-id to be stored in the
2126 TemplateIdAnnotation *TemplateId
2127 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
2129 // FIXME: Store name for literal operator too.
2130 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2131 TemplateId->Name = Id.Identifier;
2132 TemplateId->Operator = OO_None;
2133 TemplateId->TemplateNameLoc = Id.StartLocation;
2135 TemplateId->Name = nullptr;
2136 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2137 TemplateId->TemplateNameLoc = Id.StartLocation;
2140 TemplateId->SS = SS;
2141 TemplateId->TemplateKWLoc = TemplateKWLoc;
2142 TemplateId->Template = Template;
2143 TemplateId->Kind = TNK;
2144 TemplateId->LAngleLoc = LAngleLoc;
2145 TemplateId->RAngleLoc = RAngleLoc;
2146 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
2147 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
2148 Arg != ArgEnd; ++Arg)
2149 Args[Arg] = TemplateArgs[Arg];
2151 Id.setTemplateId(TemplateId);
2155 // Bundle the template arguments together.
2156 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2158 // Constructor and destructor names.
2160 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2161 Template, Name, NameLoc,
2162 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2163 /*IsCtorOrDtorName=*/true);
2164 if (Type.isInvalid())
2167 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2168 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2170 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2175 /// \brief Parse an operator-function-id or conversion-function-id as part
2176 /// of a C++ unqualified-id.
2178 /// This routine is responsible only for parsing the operator-function-id or
2179 /// conversion-function-id; it does not handle template arguments in any way.
2182 /// operator-function-id: [C++ 13.5]
2183 /// 'operator' operator
2185 /// operator: one of
2186 /// new delete new[] delete[]
2187 /// + - * / % ^ & | ~
2188 /// ! = < > += -= *= /= %=
2189 /// ^= &= |= << >> >>= <<= == !=
2190 /// <= >= && || ++ -- , ->* ->
2193 /// conversion-function-id: [C++ 12.3.2]
2194 /// operator conversion-type-id
2196 /// conversion-type-id:
2197 /// type-specifier-seq conversion-declarator[opt]
2199 /// conversion-declarator:
2200 /// ptr-operator conversion-declarator[opt]
2203 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2204 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2206 /// \param EnteringContext whether we are entering the scope of the
2207 /// nested-name-specifier.
2209 /// \param ObjectType if this unqualified-id occurs within a member access
2210 /// expression, the type of the base object whose member is being accessed.
2212 /// \param Result on a successful parse, contains the parsed unqualified-id.
2214 /// \returns true if parsing fails, false otherwise.
2215 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2216 ParsedType ObjectType,
2217 UnqualifiedId &Result) {
2218 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2220 // Consume the 'operator' keyword.
2221 SourceLocation KeywordLoc = ConsumeToken();
2223 // Determine what kind of operator name we have.
2224 unsigned SymbolIdx = 0;
2225 SourceLocation SymbolLocations[3];
2226 OverloadedOperatorKind Op = OO_None;
2227 switch (Tok.getKind()) {
2229 case tok::kw_delete: {
2230 bool isNew = Tok.getKind() == tok::kw_new;
2231 // Consume the 'new' or 'delete'.
2232 SymbolLocations[SymbolIdx++] = ConsumeToken();
2233 // Check for array new/delete.
2234 if (Tok.is(tok::l_square) &&
2235 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2236 // Consume the '[' and ']'.
2237 BalancedDelimiterTracker T(*this, tok::l_square);
2240 if (T.getCloseLocation().isInvalid())
2243 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2244 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2245 Op = isNew? OO_Array_New : OO_Array_Delete;
2247 Op = isNew? OO_New : OO_Delete;
2252 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2254 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2257 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2258 #include "clang/Basic/OperatorKinds.def"
2260 case tok::l_paren: {
2261 // Consume the '(' and ')'.
2262 BalancedDelimiterTracker T(*this, tok::l_paren);
2265 if (T.getCloseLocation().isInvalid())
2268 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2269 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2274 case tok::l_square: {
2275 // Consume the '[' and ']'.
2276 BalancedDelimiterTracker T(*this, tok::l_square);
2279 if (T.getCloseLocation().isInvalid())
2282 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2283 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2288 case tok::code_completion: {
2289 // Code completion for the operator name.
2290 Actions.CodeCompleteOperatorName(getCurScope());
2292 // Don't try to parse any further.
2300 if (Op != OO_None) {
2301 // We have parsed an operator-function-id.
2302 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2306 // Parse a literal-operator-id.
2308 // literal-operator-id: C++11 [over.literal]
2309 // operator string-literal identifier
2310 // operator user-defined-string-literal
2312 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2313 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2315 SourceLocation DiagLoc;
2316 unsigned DiagId = 0;
2318 // We're past translation phase 6, so perform string literal concatenation
2319 // before checking for "".
2320 SmallVector<Token, 4> Toks;
2321 SmallVector<SourceLocation, 4> TokLocs;
2322 while (isTokenStringLiteral()) {
2323 if (!Tok.is(tok::string_literal) && !DiagId) {
2324 // C++11 [over.literal]p1:
2325 // The string-literal or user-defined-string-literal in a
2326 // literal-operator-id shall have no encoding-prefix [...].
2327 DiagLoc = Tok.getLocation();
2328 DiagId = diag::err_literal_operator_string_prefix;
2330 Toks.push_back(Tok);
2331 TokLocs.push_back(ConsumeStringToken());
2334 StringLiteralParser Literal(Toks, PP);
2335 if (Literal.hadError)
2338 // Grab the literal operator's suffix, which will be either the next token
2339 // or a ud-suffix from the string literal.
2340 IdentifierInfo *II = nullptr;
2341 SourceLocation SuffixLoc;
2342 if (!Literal.getUDSuffix().empty()) {
2343 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2345 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2346 Literal.getUDSuffixOffset(),
2347 PP.getSourceManager(), getLangOpts());
2348 } else if (Tok.is(tok::identifier)) {
2349 II = Tok.getIdentifierInfo();
2350 SuffixLoc = ConsumeToken();
2351 TokLocs.push_back(SuffixLoc);
2353 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2357 // The string literal must be empty.
2358 if (!Literal.GetString().empty() || Literal.Pascal) {
2359 // C++11 [over.literal]p1:
2360 // The string-literal or user-defined-string-literal in a
2361 // literal-operator-id shall [...] contain no characters
2362 // other than the implicit terminating '\0'.
2363 DiagLoc = TokLocs.front();
2364 DiagId = diag::err_literal_operator_string_not_empty;
2368 // This isn't a valid literal-operator-id, but we think we know
2369 // what the user meant. Tell them what they should have written.
2370 SmallString<32> Str;
2372 Str += II->getName();
2373 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2374 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2377 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2379 return Actions.checkLiteralOperatorId(SS, Result);
2382 // Parse a conversion-function-id.
2384 // conversion-function-id: [C++ 12.3.2]
2385 // operator conversion-type-id
2387 // conversion-type-id:
2388 // type-specifier-seq conversion-declarator[opt]
2390 // conversion-declarator:
2391 // ptr-operator conversion-declarator[opt]
2393 // Parse the type-specifier-seq.
2394 DeclSpec DS(AttrFactory);
2395 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2398 // Parse the conversion-declarator, which is merely a sequence of
2400 Declarator D(DS, Declarator::ConversionIdContext);
2401 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2403 // Finish up the type.
2404 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2408 // Note that this is a conversion-function-id.
2409 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2410 D.getSourceRange().getEnd());
2414 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2415 /// name of an entity.
2418 /// unqualified-id: [C++ expr.prim.general]
2420 /// operator-function-id
2421 /// conversion-function-id
2422 /// [C++0x] literal-operator-id [TODO]
2428 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2429 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2431 /// \param EnteringContext whether we are entering the scope of the
2432 /// nested-name-specifier.
2434 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2436 /// \param AllowConstructorName whether we allow parsing a constructor name.
2438 /// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2440 /// \param ObjectType if this unqualified-id occurs within a member access
2441 /// expression, the type of the base object whose member is being accessed.
2443 /// \param Result on a successful parse, contains the parsed unqualified-id.
2445 /// \returns true if parsing fails, false otherwise.
2446 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2447 bool AllowDestructorName,
2448 bool AllowConstructorName,
2449 bool AllowDeductionGuide,
2450 ParsedType ObjectType,
2451 SourceLocation& TemplateKWLoc,
2452 UnqualifiedId &Result) {
2454 // Handle 'A::template B'. This is for template-ids which have not
2455 // already been annotated by ParseOptionalCXXScopeSpecifier().
2456 bool TemplateSpecified = false;
2457 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2458 (ObjectType || SS.isSet())) {
2459 TemplateSpecified = true;
2460 TemplateKWLoc = ConsumeToken();
2465 // template-id (when it hasn't already been annotated)
2466 if (Tok.is(tok::identifier)) {
2467 // Consume the identifier.
2468 IdentifierInfo *Id = Tok.getIdentifierInfo();
2469 SourceLocation IdLoc = ConsumeToken();
2471 if (!getLangOpts().CPlusPlus) {
2472 // If we're not in C++, only identifiers matter. Record the
2473 // identifier and return.
2474 Result.setIdentifier(Id, IdLoc);
2478 ParsedTemplateTy TemplateName;
2479 if (AllowConstructorName &&
2480 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2481 // We have parsed a constructor name.
2482 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, false,
2484 /*IsCtorOrDtorName=*/true,
2485 /*NonTrivialTypeSourceInfo=*/true);
2486 Result.setConstructorName(Ty, IdLoc, IdLoc);
2487 } else if (getLangOpts().CPlusPlus1z &&
2488 AllowDeductionGuide && SS.isEmpty() &&
2489 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2491 // We have parsed a template-name naming a deduction guide.
2492 Result.setDeductionGuideName(TemplateName, IdLoc);
2494 // We have parsed an identifier.
2495 Result.setIdentifier(Id, IdLoc);
2498 // If the next token is a '<', we may have a template.
2499 if (TemplateSpecified || Tok.is(tok::less))
2500 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2501 EnteringContext, ObjectType,
2502 Result, TemplateSpecified);
2508 // template-id (already parsed and annotated)
2509 if (Tok.is(tok::annot_template_id)) {
2510 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2512 // If the template-name names the current class, then this is a constructor
2513 if (AllowConstructorName && TemplateId->Name &&
2514 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2516 // C++ [class.qual]p2 specifies that a qualified template-name
2517 // is taken as the constructor name where a constructor can be
2518 // declared. Thus, the template arguments are extraneous, so
2519 // complain about them and remove them entirely.
2520 Diag(TemplateId->TemplateNameLoc,
2521 diag::err_out_of_line_constructor_template_id)
2523 << FixItHint::CreateRemoval(
2524 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2526 Actions.getTypeName(*TemplateId->Name, TemplateId->TemplateNameLoc,
2527 getCurScope(), &SS, false, false, nullptr,
2528 /*IsCtorOrDtorName=*/true,
2529 /*NontrivialTypeSourceInfo=*/true);
2530 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2531 TemplateId->RAngleLoc);
2536 Result.setConstructorTemplateId(TemplateId);
2541 // We have already parsed a template-id; consume the annotation token as
2542 // our unqualified-id.
2543 Result.setTemplateId(TemplateId);
2544 TemplateKWLoc = TemplateId->TemplateKWLoc;
2550 // operator-function-id
2551 // conversion-function-id
2552 if (Tok.is(tok::kw_operator)) {
2553 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2556 // If we have an operator-function-id or a literal-operator-id and the next
2557 // token is a '<', we may have a
2560 // operator-function-id < template-argument-list[opt] >
2561 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2562 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2563 (TemplateSpecified || Tok.is(tok::less)))
2564 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2565 nullptr, SourceLocation(),
2566 EnteringContext, ObjectType,
2567 Result, TemplateSpecified);
2572 if (getLangOpts().CPlusPlus &&
2573 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2574 // C++ [expr.unary.op]p10:
2575 // There is an ambiguity in the unary-expression ~X(), where X is a
2576 // class-name. The ambiguity is resolved in favor of treating ~ as a
2577 // unary complement rather than treating ~X as referring to a destructor.
2580 SourceLocation TildeLoc = ConsumeToken();
2582 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2583 DeclSpec DS(AttrFactory);
2584 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2585 if (ParsedType Type =
2586 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2587 Result.setDestructorName(TildeLoc, Type, EndLoc);
2593 // Parse the class-name.
2594 if (Tok.isNot(tok::identifier)) {
2595 Diag(Tok, diag::err_destructor_tilde_identifier);
2599 // If the user wrote ~T::T, correct it to T::~T.
2600 DeclaratorScopeObj DeclScopeObj(*this, SS);
2601 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2602 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2603 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2604 // it will confuse this recovery logic.
2605 ColonProtectionRAIIObject ColonRAII(*this, false);
2608 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2611 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2613 if (SS.isNotEmpty())
2614 ObjectType = nullptr;
2615 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2617 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2621 // Recover as if the tilde had been written before the identifier.
2622 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2623 << FixItHint::CreateRemoval(TildeLoc)
2624 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2626 // Temporarily enter the scope for the rest of this function.
2627 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2628 DeclScopeObj.EnterDeclaratorScope();
2631 // Parse the class-name (or template-name in a simple-template-id).
2632 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2633 SourceLocation ClassNameLoc = ConsumeToken();
2635 if (TemplateSpecified || Tok.is(tok::less)) {
2636 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2637 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2638 ClassName, ClassNameLoc,
2639 EnteringContext, ObjectType,
2640 Result, TemplateSpecified);
2643 // Note that this is a destructor name.
2644 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2645 ClassNameLoc, getCurScope(),
2651 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2655 Diag(Tok, diag::err_expected_unqualified_id)
2656 << getLangOpts().CPlusPlus;
2660 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2661 /// memory in a typesafe manner and call constructors.
2663 /// This method is called to parse the new expression after the optional :: has
2664 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2665 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2668 /// '::'[opt] 'new' new-placement[opt] new-type-id
2669 /// new-initializer[opt]
2670 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2671 /// new-initializer[opt]
2674 /// '(' expression-list ')'
2677 /// type-specifier-seq new-declarator[opt]
2678 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2681 /// ptr-operator new-declarator[opt]
2682 /// direct-new-declarator
2684 /// new-initializer:
2685 /// '(' expression-list[opt] ')'
2686 /// [C++0x] braced-init-list
2689 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2690 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2691 ConsumeToken(); // Consume 'new'
2693 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2694 // second form of new-expression. It can't be a new-type-id.
2696 ExprVector PlacementArgs;
2697 SourceLocation PlacementLParen, PlacementRParen;
2699 SourceRange TypeIdParens;
2700 DeclSpec DS(AttrFactory);
2701 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2702 if (Tok.is(tok::l_paren)) {
2703 // If it turns out to be a placement, we change the type location.
2704 BalancedDelimiterTracker T(*this, tok::l_paren);
2706 PlacementLParen = T.getOpenLocation();
2707 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2708 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2713 PlacementRParen = T.getCloseLocation();
2714 if (PlacementRParen.isInvalid()) {
2715 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2719 if (PlacementArgs.empty()) {
2720 // Reset the placement locations. There was no placement.
2721 TypeIdParens = T.getRange();
2722 PlacementLParen = PlacementRParen = SourceLocation();
2724 // We still need the type.
2725 if (Tok.is(tok::l_paren)) {
2726 BalancedDelimiterTracker T(*this, tok::l_paren);
2728 MaybeParseGNUAttributes(DeclaratorInfo);
2729 ParseSpecifierQualifierList(DS);
2730 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2731 ParseDeclarator(DeclaratorInfo);
2733 TypeIdParens = T.getRange();
2735 MaybeParseGNUAttributes(DeclaratorInfo);
2736 if (ParseCXXTypeSpecifierSeq(DS))
2737 DeclaratorInfo.setInvalidType(true);
2739 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2740 ParseDeclaratorInternal(DeclaratorInfo,
2741 &Parser::ParseDirectNewDeclarator);
2746 // A new-type-id is a simplified type-id, where essentially the
2747 // direct-declarator is replaced by a direct-new-declarator.
2748 MaybeParseGNUAttributes(DeclaratorInfo);
2749 if (ParseCXXTypeSpecifierSeq(DS))
2750 DeclaratorInfo.setInvalidType(true);
2752 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2753 ParseDeclaratorInternal(DeclaratorInfo,
2754 &Parser::ParseDirectNewDeclarator);
2757 if (DeclaratorInfo.isInvalidType()) {
2758 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2762 ExprResult Initializer;
2764 if (Tok.is(tok::l_paren)) {
2765 SourceLocation ConstructorLParen, ConstructorRParen;
2766 ExprVector ConstructorArgs;
2767 BalancedDelimiterTracker T(*this, tok::l_paren);
2769 ConstructorLParen = T.getOpenLocation();
2770 if (Tok.isNot(tok::r_paren)) {
2771 CommaLocsTy CommaLocs;
2772 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2773 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2774 DeclaratorInfo).get();
2775 Actions.CodeCompleteConstructor(getCurScope(),
2776 TypeRep.get()->getCanonicalTypeInternal(),
2777 DeclaratorInfo.getLocEnd(),
2780 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2785 ConstructorRParen = T.getCloseLocation();
2786 if (ConstructorRParen.isInvalid()) {
2787 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2790 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2793 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2794 Diag(Tok.getLocation(),
2795 diag::warn_cxx98_compat_generalized_initializer_lists);
2796 Initializer = ParseBraceInitializer();
2798 if (Initializer.isInvalid())
2801 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2802 PlacementArgs, PlacementRParen,
2803 TypeIdParens, DeclaratorInfo, Initializer.get());
2806 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2807 /// passed to ParseDeclaratorInternal.
2809 /// direct-new-declarator:
2810 /// '[' expression ']'
2811 /// direct-new-declarator '[' constant-expression ']'
2813 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2814 // Parse the array dimensions.
2816 while (Tok.is(tok::l_square)) {
2817 // An array-size expression can't start with a lambda.
2818 if (CheckProhibitedCXX11Attribute())
2821 BalancedDelimiterTracker T(*this, tok::l_square);
2824 ExprResult Size(first ? ParseExpression()
2825 : ParseConstantExpression());
2826 if (Size.isInvalid()) {
2828 SkipUntil(tok::r_square, StopAtSemi);
2835 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2836 ParsedAttributes Attrs(AttrFactory);
2837 MaybeParseCXX11Attributes(Attrs);
2839 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2840 /*static=*/false, /*star=*/false,
2842 T.getOpenLocation(),
2843 T.getCloseLocation()),
2844 Attrs, T.getCloseLocation());
2846 if (T.getCloseLocation().isInvalid())
2851 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2852 /// This ambiguity appears in the syntax of the C++ new operator.
2855 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2856 /// new-initializer[opt]
2859 /// '(' expression-list ')'
2861 bool Parser::ParseExpressionListOrTypeId(
2862 SmallVectorImpl<Expr*> &PlacementArgs,
2864 // The '(' was already consumed.
2865 if (isTypeIdInParens()) {
2866 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2867 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2869 return D.isInvalidType();
2872 // It's not a type, it has to be an expression list.
2873 // Discard the comma locations - ActOnCXXNew has enough parameters.
2874 CommaLocsTy CommaLocs;
2875 return ParseExpressionList(PlacementArgs, CommaLocs);
2878 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2879 /// to free memory allocated by new.
2881 /// This method is called to parse the 'delete' expression after the optional
2882 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2883 /// and "Start" is its location. Otherwise, "Start" is the location of the
2886 /// delete-expression:
2887 /// '::'[opt] 'delete' cast-expression
2888 /// '::'[opt] 'delete' '[' ']' cast-expression
2890 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2891 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2892 ConsumeToken(); // Consume 'delete'
2895 bool ArrayDelete = false;
2896 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2897 // C++11 [expr.delete]p1:
2898 // Whenever the delete keyword is followed by empty square brackets, it
2899 // shall be interpreted as [array delete].
2900 // [Footnote: A lambda expression with a lambda-introducer that consists
2901 // of empty square brackets can follow the delete keyword if
2902 // the lambda expression is enclosed in parentheses.]
2903 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2904 // lambda-introducer.
2906 BalancedDelimiterTracker T(*this, tok::l_square);
2910 if (T.getCloseLocation().isInvalid())
2914 ExprResult Operand(ParseCastExpression(false));
2915 if (Operand.isInvalid())
2918 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2921 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2923 default: llvm_unreachable("Not a known type trait");
2924 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2925 case tok::kw_ ## Spelling: return UTT_ ## Name;
2926 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2927 case tok::kw_ ## Spelling: return BTT_ ## Name;
2928 #include "clang/Basic/TokenKinds.def"
2929 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2930 case tok::kw_ ## Spelling: return TT_ ## Name;
2931 #include "clang/Basic/TokenKinds.def"
2935 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2937 default: llvm_unreachable("Not a known binary type trait");
2938 case tok::kw___array_rank: return ATT_ArrayRank;
2939 case tok::kw___array_extent: return ATT_ArrayExtent;
2943 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2945 default: llvm_unreachable("Not a known unary expression trait.");
2946 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2947 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2951 static unsigned TypeTraitArity(tok::TokenKind kind) {
2953 default: llvm_unreachable("Not a known type trait");
2954 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2955 #include "clang/Basic/TokenKinds.def"
2959 /// \brief Parse the built-in type-trait pseudo-functions that allow
2960 /// implementation of the TR1/C++11 type traits templates.
2962 /// primary-expression:
2963 /// unary-type-trait '(' type-id ')'
2964 /// binary-type-trait '(' type-id ',' type-id ')'
2965 /// type-trait '(' type-id-seq ')'
2968 /// type-id ...[opt] type-id-seq[opt]
2970 ExprResult Parser::ParseTypeTrait() {
2971 tok::TokenKind Kind = Tok.getKind();
2972 unsigned Arity = TypeTraitArity(Kind);
2974 SourceLocation Loc = ConsumeToken();
2976 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2977 if (Parens.expectAndConsume())
2980 SmallVector<ParsedType, 2> Args;
2982 // Parse the next type.
2983 TypeResult Ty = ParseTypeName();
2984 if (Ty.isInvalid()) {
2989 // Parse the ellipsis, if present.
2990 if (Tok.is(tok::ellipsis)) {
2991 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2992 if (Ty.isInvalid()) {
2998 // Add this type to the list of arguments.
2999 Args.push_back(Ty.get());
3000 } while (TryConsumeToken(tok::comma));
3002 if (Parens.consumeClose())
3005 SourceLocation EndLoc = Parens.getCloseLocation();
3007 if (Arity && Args.size() != Arity) {
3008 Diag(EndLoc, diag::err_type_trait_arity)
3009 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3013 if (!Arity && Args.empty()) {
3014 Diag(EndLoc, diag::err_type_trait_arity)
3015 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3019 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3022 /// ParseArrayTypeTrait - Parse the built-in array type-trait
3023 /// pseudo-functions.
3025 /// primary-expression:
3026 /// [Embarcadero] '__array_rank' '(' type-id ')'
3027 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3029 ExprResult Parser::ParseArrayTypeTrait() {
3030 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3031 SourceLocation Loc = ConsumeToken();
3033 BalancedDelimiterTracker T(*this, tok::l_paren);
3034 if (T.expectAndConsume())
3037 TypeResult Ty = ParseTypeName();
3038 if (Ty.isInvalid()) {
3039 SkipUntil(tok::comma, StopAtSemi);
3040 SkipUntil(tok::r_paren, StopAtSemi);
3045 case ATT_ArrayRank: {
3047 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3048 T.getCloseLocation());
3050 case ATT_ArrayExtent: {
3051 if (ExpectAndConsume(tok::comma)) {
3052 SkipUntil(tok::r_paren, StopAtSemi);
3056 ExprResult DimExpr = ParseExpression();
3059 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3060 T.getCloseLocation());
3063 llvm_unreachable("Invalid ArrayTypeTrait!");
3066 /// ParseExpressionTrait - Parse built-in expression-trait
3067 /// pseudo-functions like __is_lvalue_expr( xxx ).
3069 /// primary-expression:
3070 /// [Embarcadero] expression-trait '(' expression ')'
3072 ExprResult Parser::ParseExpressionTrait() {
3073 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3074 SourceLocation Loc = ConsumeToken();
3076 BalancedDelimiterTracker T(*this, tok::l_paren);
3077 if (T.expectAndConsume())
3080 ExprResult Expr = ParseExpression();
3084 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3085 T.getCloseLocation());
3089 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3090 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3091 /// based on the context past the parens.
3093 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3095 BalancedDelimiterTracker &Tracker,
3096 ColonProtectionRAIIObject &ColonProt) {
3097 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3098 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3099 assert(isTypeIdInParens() && "Not a type-id!");
3101 ExprResult Result(true);
3104 // We need to disambiguate a very ugly part of the C++ syntax:
3106 // (T())x; - type-id
3107 // (T())*x; - type-id
3108 // (T())/x; - expression
3109 // (T()); - expression
3111 // The bad news is that we cannot use the specialized tentative parser, since
3112 // it can only verify that the thing inside the parens can be parsed as
3113 // type-id, it is not useful for determining the context past the parens.
3115 // The good news is that the parser can disambiguate this part without
3116 // making any unnecessary Action calls.
3118 // It uses a scheme similar to parsing inline methods. The parenthesized
3119 // tokens are cached, the context that follows is determined (possibly by
3120 // parsing a cast-expression), and then we re-introduce the cached tokens
3121 // into the token stream and parse them appropriately.
3123 ParenParseOption ParseAs;
3126 // Store the tokens of the parentheses. We will parse them after we determine
3127 // the context that follows them.
3128 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3129 // We didn't find the ')' we expected.
3130 Tracker.consumeClose();
3134 if (Tok.is(tok::l_brace)) {
3135 ParseAs = CompoundLiteral;
3138 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3141 // Try parsing the cast-expression that may follow.
3142 // If it is not a cast-expression, NotCastExpr will be true and no token
3143 // will be consumed.
3144 ColonProt.restore();
3145 Result = ParseCastExpression(false/*isUnaryExpression*/,
3146 false/*isAddressofOperand*/,
3148 // type-id has priority.
3152 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3154 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3157 // Create a fake EOF to mark end of Toks buffer.
3159 AttrEnd.startToken();
3160 AttrEnd.setKind(tok::eof);
3161 AttrEnd.setLocation(Tok.getLocation());
3162 AttrEnd.setEofData(Toks.data());
3163 Toks.push_back(AttrEnd);
3165 // The current token should go after the cached tokens.
3166 Toks.push_back(Tok);
3167 // Re-enter the stored parenthesized tokens into the token stream, so we may
3169 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
3170 // Drop the current token and bring the first cached one. It's the same token
3171 // as when we entered this function.
3174 if (ParseAs >= CompoundLiteral) {
3175 // Parse the type declarator.
3176 DeclSpec DS(AttrFactory);
3177 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
3179 ColonProtectionRAIIObject InnerColonProtection(*this);
3180 ParseSpecifierQualifierList(DS);
3181 ParseDeclarator(DeclaratorInfo);
3185 Tracker.consumeClose();
3186 ColonProt.restore();
3188 // Consume EOF marker for Toks buffer.
3189 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3192 if (ParseAs == CompoundLiteral) {
3193 ExprType = CompoundLiteral;
3194 if (DeclaratorInfo.isInvalidType())
3197 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3198 return ParseCompoundLiteralExpression(Ty.get(),
3199 Tracker.getOpenLocation(),
3200 Tracker.getCloseLocation());
3203 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3204 assert(ParseAs == CastExpr);
3206 if (DeclaratorInfo.isInvalidType())
3209 // Result is what ParseCastExpression returned earlier.
3210 if (!Result.isInvalid())
3211 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3212 DeclaratorInfo, CastTy,
3213 Tracker.getCloseLocation(), Result.get());
3217 // Not a compound literal, and not followed by a cast-expression.
3218 assert(ParseAs == SimpleExpr);
3220 ExprType = SimpleExpr;
3221 Result = ParseExpression();
3222 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3223 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3224 Tok.getLocation(), Result.get());
3227 if (Result.isInvalid()) {
3228 while (Tok.isNot(tok::eof))
3230 assert(Tok.getEofData() == AttrEnd.getEofData());
3235 Tracker.consumeClose();
3236 // Consume EOF marker for Toks buffer.
3237 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());