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(),
163 ConsumeAnnotationToken();
167 if (Tok.is(tok::annot_template_id)) {
168 // If the current token is an annotated template id, it may already have
169 // a scope specifier. Restore it.
170 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
174 // Has to happen before any "return false"s in this function.
175 bool CheckForDestructor = false;
176 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
177 CheckForDestructor = true;
178 *MayBePseudoDestructor = false;
184 bool HasScopeSpecifier = false;
186 if (Tok.is(tok::coloncolon)) {
187 // ::new and ::delete aren't nested-name-specifiers.
188 tok::TokenKind NextKind = NextToken().getKind();
189 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
192 if (NextKind == tok::l_brace) {
193 // It is invalid to have :: {, consume the scope qualifier and pretend
194 // like we never saw it.
195 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
197 // '::' - Global scope qualifier.
198 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
201 HasScopeSpecifier = true;
205 if (Tok.is(tok::kw___super)) {
206 SourceLocation SuperLoc = ConsumeToken();
207 if (!Tok.is(tok::coloncolon)) {
208 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
212 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
215 if (!HasScopeSpecifier &&
216 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
217 DeclSpec DS(AttrFactory);
218 SourceLocation DeclLoc = Tok.getLocation();
219 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
221 SourceLocation CCLoc;
222 // Work around a standard defect: 'decltype(auto)::' is not a
223 // nested-name-specifier.
224 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
225 !TryConsumeToken(tok::coloncolon, CCLoc)) {
226 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
230 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
231 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
233 HasScopeSpecifier = true;
237 if (HasScopeSpecifier) {
238 // C++ [basic.lookup.classref]p5:
239 // If the qualified-id has the form
241 // ::class-name-or-namespace-name::...
243 // the class-name-or-namespace-name is looked up in global scope as a
244 // class-name or namespace-name.
246 // To implement this, we clear out the object type as soon as we've
247 // seen a leading '::' or part of a nested-name-specifier.
248 ObjectType = nullptr;
250 if (Tok.is(tok::code_completion)) {
251 // Code completion for a nested-name-specifier, where the code
252 // completion token follows the '::'.
253 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
254 // Include code completion token into the range of the scope otherwise
255 // when we try to annotate the scope tokens the dangling code completion
256 // token will cause assertion in
257 // Preprocessor::AnnotatePreviousCachedTokens.
258 SS.setEndLoc(Tok.getLocation());
264 // nested-name-specifier:
265 // nested-name-specifier 'template'[opt] simple-template-id '::'
267 // Parse the optional 'template' keyword, then make sure we have
268 // 'identifier <' after it.
269 if (Tok.is(tok::kw_template)) {
270 // If we don't have a scope specifier or an object type, this isn't a
271 // nested-name-specifier, since they aren't allowed to start with
273 if (!HasScopeSpecifier && !ObjectType)
276 TentativeParsingAction TPA(*this);
277 SourceLocation TemplateKWLoc = ConsumeToken();
279 UnqualifiedId TemplateName;
280 if (Tok.is(tok::identifier)) {
281 // Consume the identifier.
282 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
284 } else if (Tok.is(tok::kw_operator)) {
285 // We don't need to actually parse the unqualified-id in this case,
286 // because a simple-template-id cannot start with 'operator', but
287 // go ahead and parse it anyway for consistency with the case where
288 // we already annotated the template-id.
289 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
295 if (TemplateName.getKind() != 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.
349 ConsumeAnnotationToken();
351 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
352 SourceLocation CCLoc = ConsumeToken();
354 HasScopeSpecifier = true;
356 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
357 TemplateId->NumArgs);
359 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
361 TemplateId->TemplateKWLoc,
362 TemplateId->Template,
363 TemplateId->TemplateNameLoc,
364 TemplateId->LAngleLoc,
366 TemplateId->RAngleLoc,
369 SourceLocation StartLoc
370 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
371 : TemplateId->TemplateNameLoc;
372 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
378 // The rest of the nested-name-specifier possibilities start with
380 if (Tok.isNot(tok::identifier))
383 IdentifierInfo &II = *Tok.getIdentifierInfo();
385 // nested-name-specifier:
387 // namespace-name '::'
388 // nested-name-specifier identifier '::'
389 Token Next = NextToken();
390 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
393 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
394 // and emit a fixit hint for it.
395 if (Next.is(tok::colon) && !ColonIsSacred) {
396 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
398 // If the token after the colon isn't an identifier, it's still an
399 // error, but they probably meant something else strange so don't
400 // recover like this.
401 PP.LookAhead(1).is(tok::identifier)) {
402 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
403 << FixItHint::CreateReplacement(Next.getLocation(), "::");
404 // Recover as if the user wrote '::'.
405 Next.setKind(tok::coloncolon);
409 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
410 // It is invalid to have :: {, consume the scope qualifier and pretend
411 // like we never saw it.
412 Token Identifier = Tok; // Stash away the identifier.
413 ConsumeToken(); // Eat the identifier, current token is now '::'.
414 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
416 UnconsumeToken(Identifier); // Stick the identifier back.
417 Next = NextToken(); // Point Next at the '{' token.
420 if (Next.is(tok::coloncolon)) {
421 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
422 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
423 *MayBePseudoDestructor = true;
428 const Token &Next2 = GetLookAheadToken(2);
429 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
430 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
431 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
433 << FixItHint::CreateReplacement(Next.getLocation(), ":");
436 ColonColon.setKind(tok::colon);
437 PP.EnterToken(ColonColon);
445 // We have an identifier followed by a '::'. Lookup this name
446 // as the name in a nested-name-specifier.
447 Token Identifier = Tok;
448 SourceLocation IdLoc = ConsumeToken();
449 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
450 "NextToken() not working properly!");
451 Token ColonColon = Tok;
452 SourceLocation CCLoc = ConsumeToken();
454 bool IsCorrectedToColon = false;
455 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
456 if (Actions.ActOnCXXNestedNameSpecifier(
457 getCurScope(), IdInfo, EnteringContext, SS, false,
458 CorrectionFlagPtr, OnlyNamespace)) {
459 // Identifier is not recognized as a nested name, but we can have
460 // mistyped '::' instead of ':'.
461 if (CorrectionFlagPtr && IsCorrectedToColon) {
462 ColonColon.setKind(tok::colon);
464 PP.EnterToken(ColonColon);
468 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
470 HasScopeSpecifier = true;
474 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
476 // nested-name-specifier:
478 if (Next.is(tok::less)) {
480 UnqualifiedId TemplateName;
481 TemplateName.setIdentifier(&II, Tok.getLocation());
482 bool MemberOfUnknownSpecialization;
483 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
484 /*hasTemplateKeyword=*/false,
489 MemberOfUnknownSpecialization)) {
490 // We have found a template name, so annotate this token
491 // with a template-id annotation. We do not permit the
492 // template-id to be translated into a type annotation,
493 // because some clients (e.g., the parsing of class template
494 // specializations) still want to see the original template-id
497 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
498 TemplateName, false))
503 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
504 (IsTypename || IsTemplateArgumentList(1))) {
505 // We have something like t::getAs<T>, where getAs is a
506 // member of an unknown specialization. However, this will only
507 // parse correctly as a template, so suggest the keyword 'template'
508 // before 'getAs' and treat this as a dependent template name.
509 unsigned DiagID = diag::err_missing_dependent_template_keyword;
510 if (getLangOpts().MicrosoftExt)
511 DiagID = diag::warn_missing_dependent_template_keyword;
513 Diag(Tok.getLocation(), DiagID)
515 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
517 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
518 getCurScope(), SS, 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.
923 ConsumeAnnotationToken();
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.isInvalid())
970 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
971 if (Init.isUsable()) {
972 // Get the pointer and store it in an lvalue, so we can use it as an
974 Expr *InitExpr = Init.get();
975 // This performs any lvalue-to-rvalue conversions if necessary, which
976 // can affect what gets captured in the containing decl-context.
977 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
978 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
981 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
986 Intro.Range.setEnd(T.getCloseLocation());
990 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
992 /// Returns true if it hit something unexpected.
993 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
995 bool SkippedInits = false;
996 TentativeParsingAction PA1(*this);
998 if (ParseLambdaIntroducer(Intro, &SkippedInits)) {
1003 if (!SkippedInits) {
1011 // Try to parse it again, but this time parse the init-captures too.
1012 Intro = LambdaIntroducer();
1013 TentativeParsingAction PA2(*this);
1015 if (!ParseLambdaIntroducer(Intro)) {
1025 tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1026 SourceLocation &ConstexprLoc,
1027 SourceLocation &DeclEndLoc) {
1028 assert(MutableLoc.isInvalid());
1029 assert(ConstexprLoc.isInvalid());
1030 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1031 // to the final of those locations. Emit an error if we have multiple
1032 // copies of those keywords and recover.
1035 switch (P.getCurToken().getKind()) {
1036 case tok::kw_mutable: {
1037 if (MutableLoc.isValid()) {
1038 P.Diag(P.getCurToken().getLocation(),
1039 diag::err_lambda_decl_specifier_repeated)
1040 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1042 MutableLoc = P.ConsumeToken();
1043 DeclEndLoc = MutableLoc;
1046 case tok::kw_constexpr:
1047 if (ConstexprLoc.isValid()) {
1048 P.Diag(P.getCurToken().getLocation(),
1049 diag::err_lambda_decl_specifier_repeated)
1050 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1052 ConstexprLoc = P.ConsumeToken();
1053 DeclEndLoc = ConstexprLoc;
1062 addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1064 if (ConstexprLoc.isValid()) {
1065 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1066 ? diag::ext_constexpr_on_lambda_cxx17
1067 : diag::warn_cxx14_compat_constexpr_on_lambda);
1068 const char *PrevSpec = nullptr;
1069 unsigned DiagID = 0;
1070 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1071 assert(PrevSpec == nullptr && DiagID == 0 &&
1072 "Constexpr cannot have been set previously!");
1076 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1078 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1079 LambdaIntroducer &Intro) {
1080 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1081 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1083 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1084 "lambda expression parsing");
1088 // FIXME: Call into Actions to add any init-capture declarations to the
1089 // scope while parsing the lambda-declarator and compound-statement.
1091 // Parse lambda-declarator[opt].
1092 DeclSpec DS(AttrFactory);
1093 Declarator D(DS, Declarator::LambdaExprContext);
1094 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1095 Actions.PushLambdaScope();
1097 ParsedAttributes Attr(AttrFactory);
1098 SourceLocation DeclLoc = Tok.getLocation();
1099 if (getLangOpts().CUDA) {
1100 // In CUDA code, GNU attributes are allowed to appear immediately after the
1101 // "[...]", even if there is no "(...)" before the lambda body.
1102 MaybeParseGNUAttributes(D);
1105 // Helper to emit a warning if we see a CUDA host/device/global attribute
1106 // after '(...)'. nvcc doesn't accept this.
1107 auto WarnIfHasCUDATargetAttr = [&] {
1108 if (getLangOpts().CUDA)
1109 for (auto *A = Attr.getList(); A != nullptr; A = A->getNext())
1110 if (A->getKind() == AttributeList::AT_CUDADevice ||
1111 A->getKind() == AttributeList::AT_CUDAHost ||
1112 A->getKind() == AttributeList::AT_CUDAGlobal)
1113 Diag(A->getLoc(), diag::warn_cuda_attr_lambda_position)
1114 << A->getName()->getName();
1117 TypeResult TrailingReturnType;
1118 if (Tok.is(tok::l_paren)) {
1119 ParseScope PrototypeScope(this,
1120 Scope::FunctionPrototypeScope |
1121 Scope::FunctionDeclarationScope |
1124 BalancedDelimiterTracker T(*this, tok::l_paren);
1126 SourceLocation LParenLoc = T.getOpenLocation();
1128 // Parse parameter-declaration-clause.
1129 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1130 SourceLocation EllipsisLoc;
1132 if (Tok.isNot(tok::r_paren)) {
1133 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1134 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1135 // For a generic lambda, each 'auto' within the parameter declaration
1136 // clause creates a template type parameter, so increment the depth.
1137 if (Actions.getCurGenericLambda())
1138 ++CurTemplateDepthTracker;
1141 SourceLocation RParenLoc = T.getCloseLocation();
1142 SourceLocation DeclEndLoc = RParenLoc;
1144 // GNU-style attributes must be parsed before the mutable specifier to be
1145 // compatible with GCC.
1146 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1148 // MSVC-style attributes must be parsed before the mutable specifier to be
1149 // compatible with MSVC.
1150 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1152 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
1153 SourceLocation MutableLoc;
1154 SourceLocation ConstexprLoc;
1155 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1158 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1160 // Parse exception-specification[opt].
1161 ExceptionSpecificationType ESpecType = EST_None;
1162 SourceRange ESpecRange;
1163 SmallVector<ParsedType, 2> DynamicExceptions;
1164 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1165 ExprResult NoexceptExpr;
1166 CachedTokens *ExceptionSpecTokens;
1167 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1170 DynamicExceptionRanges,
1172 ExceptionSpecTokens);
1174 if (ESpecType != EST_None)
1175 DeclEndLoc = ESpecRange.getEnd();
1177 // Parse attribute-specifier[opt].
1178 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1180 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1182 // Parse trailing-return-type[opt].
1183 if (Tok.is(tok::arrow)) {
1184 FunLocalRangeEnd = Tok.getLocation();
1186 TrailingReturnType = ParseTrailingReturnType(Range);
1187 if (Range.getEnd().isValid())
1188 DeclEndLoc = Range.getEnd();
1191 PrototypeScope.Exit();
1193 WarnIfHasCUDATargetAttr();
1195 SourceLocation NoLoc;
1196 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1197 /*isAmbiguous=*/false,
1199 ParamInfo.data(), ParamInfo.size(),
1200 EllipsisLoc, RParenLoc,
1201 DS.getTypeQualifiers(),
1202 /*RefQualifierIsLValueRef=*/true,
1203 /*RefQualifierLoc=*/NoLoc,
1204 /*ConstQualifierLoc=*/NoLoc,
1205 /*VolatileQualifierLoc=*/NoLoc,
1206 /*RestrictQualifierLoc=*/NoLoc,
1208 ESpecType, ESpecRange,
1209 DynamicExceptions.data(),
1210 DynamicExceptionRanges.data(),
1211 DynamicExceptions.size(),
1212 NoexceptExpr.isUsable() ?
1213 NoexceptExpr.get() : nullptr,
1214 /*ExceptionSpecTokens*/nullptr,
1215 /*DeclsInPrototype=*/None,
1216 LParenLoc, FunLocalRangeEnd, D,
1217 TrailingReturnType),
1219 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1220 tok::kw_constexpr) ||
1221 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1222 // It's common to forget that one needs '()' before 'mutable', an attribute
1223 // specifier, or the result type. Deal with this.
1224 unsigned TokKind = 0;
1225 switch (Tok.getKind()) {
1226 case tok::kw_mutable: TokKind = 0; break;
1227 case tok::arrow: TokKind = 1; break;
1228 case tok::kw___attribute:
1229 case tok::l_square: TokKind = 2; break;
1230 case tok::kw_constexpr: TokKind = 3; break;
1231 default: llvm_unreachable("Unknown token kind");
1234 Diag(Tok, diag::err_lambda_missing_parens)
1236 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1237 SourceLocation DeclEndLoc = DeclLoc;
1239 // GNU-style attributes must be parsed before the mutable specifier to be
1240 // compatible with GCC.
1241 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1243 // Parse 'mutable', if it's there.
1244 SourceLocation MutableLoc;
1245 if (Tok.is(tok::kw_mutable)) {
1246 MutableLoc = ConsumeToken();
1247 DeclEndLoc = MutableLoc;
1250 // Parse attribute-specifier[opt].
1251 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1253 // Parse the return type, if there is one.
1254 if (Tok.is(tok::arrow)) {
1256 TrailingReturnType = ParseTrailingReturnType(Range);
1257 if (Range.getEnd().isValid())
1258 DeclEndLoc = Range.getEnd();
1261 WarnIfHasCUDATargetAttr();
1263 SourceLocation NoLoc;
1264 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1265 /*isAmbiguous=*/false,
1266 /*LParenLoc=*/NoLoc,
1269 /*EllipsisLoc=*/NoLoc,
1270 /*RParenLoc=*/NoLoc,
1272 /*RefQualifierIsLValueRef=*/true,
1273 /*RefQualifierLoc=*/NoLoc,
1274 /*ConstQualifierLoc=*/NoLoc,
1275 /*VolatileQualifierLoc=*/NoLoc,
1276 /*RestrictQualifierLoc=*/NoLoc,
1279 /*ESpecRange=*/SourceRange(),
1280 /*Exceptions=*/nullptr,
1281 /*ExceptionRanges=*/nullptr,
1282 /*NumExceptions=*/0,
1283 /*NoexceptExpr=*/nullptr,
1284 /*ExceptionSpecTokens=*/nullptr,
1285 /*DeclsInPrototype=*/None,
1286 DeclLoc, DeclEndLoc, D,
1287 TrailingReturnType),
1291 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1293 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1294 Scope::CompoundStmtScope;
1295 ParseScope BodyScope(this, ScopeFlags);
1297 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1299 // Parse compound-statement.
1300 if (!Tok.is(tok::l_brace)) {
1301 Diag(Tok, diag::err_expected_lambda_body);
1302 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1306 StmtResult Stmt(ParseCompoundStatementBody());
1309 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1310 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1312 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1316 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1319 /// postfix-expression: [C++ 5.2p1]
1320 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1321 /// 'static_cast' '<' type-name '>' '(' expression ')'
1322 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1323 /// 'const_cast' '<' type-name '>' '(' expression ')'
1325 ExprResult Parser::ParseCXXCasts() {
1326 tok::TokenKind Kind = Tok.getKind();
1327 const char *CastName = nullptr; // For error messages
1330 default: llvm_unreachable("Unknown C++ cast!");
1331 case tok::kw_const_cast: CastName = "const_cast"; break;
1332 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1333 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1334 case tok::kw_static_cast: CastName = "static_cast"; break;
1337 SourceLocation OpLoc = ConsumeToken();
1338 SourceLocation LAngleBracketLoc = Tok.getLocation();
1340 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1341 // diagnose error, suggest fix, and recover parsing.
1342 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1343 Token Next = NextToken();
1344 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1345 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1348 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1351 // Parse the common declaration-specifiers piece.
1352 DeclSpec DS(AttrFactory);
1353 ParseSpecifierQualifierList(DS);
1355 // Parse the abstract-declarator, if present.
1356 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1357 ParseDeclarator(DeclaratorInfo);
1359 SourceLocation RAngleBracketLoc = Tok.getLocation();
1361 if (ExpectAndConsume(tok::greater))
1362 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1364 BalancedDelimiterTracker T(*this, tok::l_paren);
1366 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1369 ExprResult Result = ParseExpression();
1374 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1375 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1376 LAngleBracketLoc, DeclaratorInfo,
1378 T.getOpenLocation(), Result.get(),
1379 T.getCloseLocation());
1384 /// ParseCXXTypeid - This handles the C++ typeid expression.
1386 /// postfix-expression: [C++ 5.2p1]
1387 /// 'typeid' '(' expression ')'
1388 /// 'typeid' '(' type-id ')'
1390 ExprResult Parser::ParseCXXTypeid() {
1391 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1393 SourceLocation OpLoc = ConsumeToken();
1394 SourceLocation LParenLoc, RParenLoc;
1395 BalancedDelimiterTracker T(*this, tok::l_paren);
1397 // typeid expressions are always parenthesized.
1398 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1400 LParenLoc = T.getOpenLocation();
1404 // C++0x [expr.typeid]p3:
1405 // When typeid is applied to an expression other than an lvalue of a
1406 // polymorphic class type [...] The expression is an unevaluated
1407 // operand (Clause 5).
1409 // Note that we can't tell whether the expression is an lvalue of a
1410 // polymorphic class type until after we've parsed the expression; we
1411 // speculatively assume the subexpression is unevaluated, and fix it up
1414 // We enter the unevaluated context before trying to determine whether we
1415 // have a type-id, because the tentative parse logic will try to resolve
1416 // names, and must treat them as unevaluated.
1417 EnterExpressionEvaluationContext Unevaluated(
1418 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1419 Sema::ReuseLambdaContextDecl);
1421 if (isTypeIdInParens()) {
1422 TypeResult Ty = ParseTypeName();
1426 RParenLoc = T.getCloseLocation();
1427 if (Ty.isInvalid() || RParenLoc.isInvalid())
1430 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1431 Ty.get().getAsOpaquePtr(), RParenLoc);
1433 Result = ParseExpression();
1436 if (Result.isInvalid())
1437 SkipUntil(tok::r_paren, StopAtSemi);
1440 RParenLoc = T.getCloseLocation();
1441 if (RParenLoc.isInvalid())
1444 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1445 Result.get(), RParenLoc);
1452 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1454 /// '__uuidof' '(' expression ')'
1455 /// '__uuidof' '(' type-id ')'
1457 ExprResult Parser::ParseCXXUuidof() {
1458 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1460 SourceLocation OpLoc = ConsumeToken();
1461 BalancedDelimiterTracker T(*this, tok::l_paren);
1463 // __uuidof expressions are always parenthesized.
1464 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1469 if (isTypeIdInParens()) {
1470 TypeResult Ty = ParseTypeName();
1478 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1479 Ty.get().getAsOpaquePtr(),
1480 T.getCloseLocation());
1482 EnterExpressionEvaluationContext Unevaluated(
1483 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1484 Result = ParseExpression();
1487 if (Result.isInvalid())
1488 SkipUntil(tok::r_paren, StopAtSemi);
1492 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1494 Result.get(), T.getCloseLocation());
1501 /// \brief Parse a C++ pseudo-destructor expression after the base,
1502 /// . or -> operator, and nested-name-specifier have already been
1505 /// postfix-expression: [C++ 5.2]
1506 /// postfix-expression . pseudo-destructor-name
1507 /// postfix-expression -> pseudo-destructor-name
1509 /// pseudo-destructor-name:
1510 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1511 /// ::[opt] nested-name-specifier template simple-template-id ::
1513 /// ::[opt] nested-name-specifier[opt] ~type-name
1516 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1517 tok::TokenKind OpKind,
1519 ParsedType ObjectType) {
1520 // We're parsing either a pseudo-destructor-name or a dependent
1521 // member access that has the same form as a
1522 // pseudo-destructor-name. We parse both in the same way and let
1523 // the action model sort them out.
1525 // Note that the ::[opt] nested-name-specifier[opt] has already
1526 // been parsed, and if there was a simple-template-id, it has
1527 // been coalesced into a template-id annotation token.
1528 UnqualifiedId FirstTypeName;
1529 SourceLocation CCLoc;
1530 if (Tok.is(tok::identifier)) {
1531 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1533 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1534 CCLoc = ConsumeToken();
1535 } else if (Tok.is(tok::annot_template_id)) {
1536 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1537 // store it in the pseudo-dtor node (to be used when instantiating it).
1538 FirstTypeName.setTemplateId(
1539 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1540 ConsumeAnnotationToken();
1541 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1542 CCLoc = ConsumeToken();
1544 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1548 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1549 SourceLocation TildeLoc = ConsumeToken();
1551 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1552 DeclSpec DS(AttrFactory);
1553 ParseDecltypeSpecifier(DS);
1554 if (DS.getTypeSpecType() == TST_error)
1556 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1560 if (!Tok.is(tok::identifier)) {
1561 Diag(Tok, diag::err_destructor_tilde_identifier);
1565 // Parse the second type.
1566 UnqualifiedId SecondTypeName;
1567 IdentifierInfo *Name = Tok.getIdentifierInfo();
1568 SourceLocation NameLoc = ConsumeToken();
1569 SecondTypeName.setIdentifier(Name, NameLoc);
1571 // If there is a '<', the second type name is a template-id. Parse
1573 if (Tok.is(tok::less) &&
1574 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1576 false, ObjectType, SecondTypeName,
1577 /*AssumeTemplateName=*/true))
1580 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1581 SS, FirstTypeName, CCLoc, TildeLoc,
1585 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1587 /// boolean-literal: [C++ 2.13.5]
1590 ExprResult Parser::ParseCXXBoolLiteral() {
1591 tok::TokenKind Kind = Tok.getKind();
1592 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1595 /// ParseThrowExpression - This handles the C++ throw expression.
1597 /// throw-expression: [C++ 15]
1598 /// 'throw' assignment-expression[opt]
1599 ExprResult Parser::ParseThrowExpression() {
1600 assert(Tok.is(tok::kw_throw) && "Not throw!");
1601 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1603 // If the current token isn't the start of an assignment-expression,
1604 // then the expression is not present. This handles things like:
1605 // "C ? throw : (void)42", which is crazy but legal.
1606 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1613 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1616 ExprResult Expr(ParseAssignmentExpression());
1617 if (Expr.isInvalid()) return Expr;
1618 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1622 /// \brief Parse the C++ Coroutines co_yield expression.
1624 /// co_yield-expression:
1625 /// 'co_yield' assignment-expression[opt]
1626 ExprResult Parser::ParseCoyieldExpression() {
1627 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1629 SourceLocation Loc = ConsumeToken();
1630 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1631 : ParseAssignmentExpression();
1632 if (!Expr.isInvalid())
1633 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1637 /// ParseCXXThis - This handles the C++ 'this' pointer.
1639 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1640 /// a non-lvalue expression whose value is the address of the object for which
1641 /// the function is called.
1642 ExprResult Parser::ParseCXXThis() {
1643 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1644 SourceLocation ThisLoc = ConsumeToken();
1645 return Actions.ActOnCXXThis(ThisLoc);
1648 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1649 /// Can be interpreted either as function-style casting ("int(x)")
1650 /// or class type construction ("ClassType(x,y,z)")
1651 /// or creation of a value-initialized type ("int()").
1652 /// See [C++ 5.2.3].
1654 /// postfix-expression: [C++ 5.2p1]
1655 /// simple-type-specifier '(' expression-list[opt] ')'
1656 /// [C++0x] simple-type-specifier braced-init-list
1657 /// typename-specifier '(' expression-list[opt] ')'
1658 /// [C++0x] typename-specifier braced-init-list
1660 /// In C++1z onwards, the type specifier can also be a template-name.
1662 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1663 Declarator DeclaratorInfo(DS, Declarator::FunctionalCastContext);
1664 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1666 assert((Tok.is(tok::l_paren) ||
1667 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1668 && "Expected '(' or '{'!");
1670 if (Tok.is(tok::l_brace)) {
1671 ExprResult Init = ParseBraceInitializer();
1672 if (Init.isInvalid())
1674 Expr *InitList = Init.get();
1675 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1676 MultiExprArg(&InitList, 1),
1679 BalancedDelimiterTracker T(*this, tok::l_paren);
1683 CommaLocsTy CommaLocs;
1685 if (Tok.isNot(tok::r_paren)) {
1686 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1687 Actions.CodeCompleteConstructor(getCurScope(),
1688 TypeRep.get()->getCanonicalTypeInternal(),
1689 DS.getLocEnd(), Exprs);
1691 SkipUntil(tok::r_paren, StopAtSemi);
1699 // TypeRep could be null, if it references an invalid typedef.
1703 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1704 "Unexpected number of commas!");
1705 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1707 T.getCloseLocation());
1711 /// ParseCXXCondition - if/switch/while condition expression.
1715 /// type-specifier-seq declarator '=' assignment-expression
1716 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1717 /// [C++11] type-specifier-seq declarator braced-init-list
1718 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1719 /// brace-or-equal-initializer
1720 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1721 /// '=' assignment-expression
1723 /// In C++1z, a condition may in some contexts be preceded by an
1724 /// optional init-statement. This function will parse that too.
1726 /// \param InitStmt If non-null, an init-statement is permitted, and if present
1727 /// will be parsed and stored here.
1729 /// \param Loc The location of the start of the statement that requires this
1730 /// condition, e.g., the "for" in a for loop.
1732 /// \returns The parsed condition.
1733 Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1735 Sema::ConditionKind CK) {
1736 if (Tok.is(tok::code_completion)) {
1737 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1739 return Sema::ConditionError();
1742 ParsedAttributesWithRange attrs(AttrFactory);
1743 MaybeParseCXX11Attributes(attrs);
1745 // Determine what kind of thing we have.
1746 switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
1747 case ConditionOrInitStatement::Expression: {
1748 ProhibitAttributes(attrs);
1750 // Parse the expression.
1751 ExprResult Expr = ParseExpression(); // expression
1752 if (Expr.isInvalid())
1753 return Sema::ConditionError();
1755 if (InitStmt && Tok.is(tok::semi)) {
1756 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1758 return ParseCXXCondition(nullptr, Loc, CK);
1761 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
1764 case ConditionOrInitStatement::InitStmtDecl: {
1765 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1766 ? diag::warn_cxx14_compat_init_statement
1767 : diag::ext_init_statement)
1768 << (CK == Sema::ConditionKind::Switch);
1769 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1770 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1771 Declarator::InitStmtContext, DeclEnd, attrs, /*RequireSemi=*/true);
1772 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1773 return ParseCXXCondition(nullptr, Loc, CK);
1776 case ConditionOrInitStatement::ConditionDecl:
1777 case ConditionOrInitStatement::Error:
1781 // type-specifier-seq
1782 DeclSpec DS(AttrFactory);
1783 DS.takeAttributesFrom(attrs);
1784 ParseSpecifierQualifierList(DS, AS_none, DSC_condition);
1787 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1788 ParseDeclarator(DeclaratorInfo);
1790 // simple-asm-expr[opt]
1791 if (Tok.is(tok::kw_asm)) {
1793 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1794 if (AsmLabel.isInvalid()) {
1795 SkipUntil(tok::semi, StopAtSemi);
1796 return Sema::ConditionError();
1798 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1799 DeclaratorInfo.SetRangeEnd(Loc);
1802 // If attributes are present, parse them.
1803 MaybeParseGNUAttributes(DeclaratorInfo);
1805 // Type-check the declaration itself.
1806 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1808 if (Dcl.isInvalid())
1809 return Sema::ConditionError();
1810 Decl *DeclOut = Dcl.get();
1812 // '=' assignment-expression
1813 // If a '==' or '+=' is found, suggest a fixit to '='.
1814 bool CopyInitialization = isTokenEqualOrEqualTypo();
1815 if (CopyInitialization)
1818 ExprResult InitExpr = ExprError();
1819 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1820 Diag(Tok.getLocation(),
1821 diag::warn_cxx98_compat_generalized_initializer_lists);
1822 InitExpr = ParseBraceInitializer();
1823 } else if (CopyInitialization) {
1824 InitExpr = ParseAssignmentExpression();
1825 } else if (Tok.is(tok::l_paren)) {
1826 // This was probably an attempt to initialize the variable.
1827 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1828 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1829 RParen = ConsumeParen();
1830 Diag(DeclOut->getLocation(),
1831 diag::err_expected_init_in_condition_lparen)
1832 << SourceRange(LParen, RParen);
1834 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
1837 if (!InitExpr.isInvalid())
1838 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
1840 Actions.ActOnInitializerError(DeclOut);
1842 Actions.FinalizeDeclaration(DeclOut);
1843 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
1846 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1847 /// This should only be called when the current token is known to be part of
1848 /// simple-type-specifier.
1850 /// simple-type-specifier:
1851 /// '::'[opt] nested-name-specifier[opt] type-name
1852 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1864 /// [GNU] typeof-specifier
1865 /// [C++0x] auto [TODO]
1872 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1873 DS.SetRangeStart(Tok.getLocation());
1874 const char *PrevSpec;
1876 SourceLocation Loc = Tok.getLocation();
1877 const clang::PrintingPolicy &Policy =
1878 Actions.getASTContext().getPrintingPolicy();
1880 switch (Tok.getKind()) {
1881 case tok::identifier: // foo::bar
1882 case tok::coloncolon: // ::foo::bar
1883 llvm_unreachable("Annotation token should already be formed!");
1885 llvm_unreachable("Not a simple-type-specifier token!");
1888 case tok::annot_typename: {
1889 if (getTypeAnnotation(Tok))
1890 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1891 getTypeAnnotation(Tok), Policy);
1893 DS.SetTypeSpecError();
1895 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1896 ConsumeAnnotationToken();
1898 DS.Finish(Actions, Policy);
1904 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1907 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1909 case tok::kw___int64:
1910 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1912 case tok::kw_signed:
1913 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1915 case tok::kw_unsigned:
1916 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1919 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1922 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1925 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1927 case tok::kw___int128:
1928 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1931 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1934 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1936 case tok::kw_double:
1937 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1939 case tok::kw__Float16:
1940 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
1942 case tok::kw___float128:
1943 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1945 case tok::kw_wchar_t:
1946 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1948 case tok::kw_char16_t:
1949 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1951 case tok::kw_char32_t:
1952 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1955 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1957 case tok::annot_decltype:
1958 case tok::kw_decltype:
1959 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1960 return DS.Finish(Actions, Policy);
1962 // GNU typeof support.
1963 case tok::kw_typeof:
1964 ParseTypeofSpecifier(DS);
1965 DS.Finish(Actions, Policy);
1969 DS.SetRangeEnd(PrevTokLocation);
1970 DS.Finish(Actions, Policy);
1973 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1974 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1975 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1976 /// by parsing the type-specifier-seq, because these sequences are
1977 /// typically followed by some form of declarator. Returns true and
1978 /// emits diagnostics if this is not a type-specifier-seq, false
1981 /// type-specifier-seq: [C++ 8.1]
1982 /// type-specifier type-specifier-seq[opt]
1984 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1985 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1986 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
1990 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1993 /// This routine is invoked when a '<' is encountered after an identifier or
1994 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1995 /// whether the unqualified-id is actually a template-id. This routine will
1996 /// then parse the template arguments and form the appropriate template-id to
1997 /// return to the caller.
1999 /// \param SS the nested-name-specifier that precedes this template-id, if
2000 /// we're actually parsing a qualified-id.
2002 /// \param Name for constructor and destructor names, this is the actual
2003 /// identifier that may be a template-name.
2005 /// \param NameLoc the location of the class-name in a constructor or
2008 /// \param EnteringContext whether we're entering the scope of the
2009 /// nested-name-specifier.
2011 /// \param ObjectType if this unqualified-id occurs within a member access
2012 /// expression, the type of the base object whose member is being accessed.
2014 /// \param Id as input, describes the template-name or operator-function-id
2015 /// that precedes the '<'. If template arguments were parsed successfully,
2016 /// will be updated with the template-id.
2018 /// \param AssumeTemplateId When true, this routine will assume that the name
2019 /// refers to a template without performing name lookup to verify.
2021 /// \returns true if a parse error occurred, false otherwise.
2022 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2023 SourceLocation TemplateKWLoc,
2024 IdentifierInfo *Name,
2025 SourceLocation NameLoc,
2026 bool EnteringContext,
2027 ParsedType ObjectType,
2029 bool AssumeTemplateId) {
2030 assert((AssumeTemplateId || Tok.is(tok::less)) &&
2031 "Expected '<' to finish parsing a template-id");
2033 TemplateTy Template;
2034 TemplateNameKind TNK = TNK_Non_template;
2035 switch (Id.getKind()) {
2036 case UnqualifiedId::IK_Identifier:
2037 case UnqualifiedId::IK_OperatorFunctionId:
2038 case UnqualifiedId::IK_LiteralOperatorId:
2039 if (AssumeTemplateId) {
2040 // We defer the injected-class-name checks until we've found whether
2041 // this template-id is used to form a nested-name-specifier or not.
2042 TNK = Actions.ActOnDependentTemplateName(
2043 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2044 Template, /*AllowInjectedClassName*/ true);
2045 if (TNK == TNK_Non_template)
2048 bool MemberOfUnknownSpecialization;
2049 TNK = Actions.isTemplateName(getCurScope(), SS,
2050 TemplateKWLoc.isValid(), Id,
2051 ObjectType, EnteringContext, Template,
2052 MemberOfUnknownSpecialization);
2054 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2055 ObjectType && IsTemplateArgumentList()) {
2056 // We have something like t->getAs<T>(), where getAs is a
2057 // member of an unknown specialization. However, this will only
2058 // parse correctly as a template, so suggest the keyword 'template'
2059 // before 'getAs' and treat this as a dependent template name.
2061 if (Id.getKind() == UnqualifiedId::IK_Identifier)
2062 Name = Id.Identifier->getName();
2065 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
2066 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2068 Name += Id.Identifier->getName();
2070 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2072 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2073 TNK = Actions.ActOnDependentTemplateName(
2074 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2075 Template, /*AllowInjectedClassName*/ true);
2076 if (TNK == TNK_Non_template)
2082 case UnqualifiedId::IK_ConstructorName: {
2083 UnqualifiedId TemplateName;
2084 bool MemberOfUnknownSpecialization;
2085 TemplateName.setIdentifier(Name, NameLoc);
2086 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2087 TemplateName, ObjectType,
2088 EnteringContext, Template,
2089 MemberOfUnknownSpecialization);
2093 case UnqualifiedId::IK_DestructorName: {
2094 UnqualifiedId TemplateName;
2095 bool MemberOfUnknownSpecialization;
2096 TemplateName.setIdentifier(Name, NameLoc);
2098 TNK = Actions.ActOnDependentTemplateName(
2099 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2100 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2101 if (TNK == TNK_Non_template)
2104 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2105 TemplateName, ObjectType,
2106 EnteringContext, Template,
2107 MemberOfUnknownSpecialization);
2109 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2110 Diag(NameLoc, diag::err_destructor_template_id)
2111 << Name << SS.getRange();
2122 if (TNK == TNK_Non_template)
2125 // Parse the enclosed template argument list.
2126 SourceLocation LAngleLoc, RAngleLoc;
2127 TemplateArgList TemplateArgs;
2128 if (Tok.is(tok::less) && ParseTemplateIdAfterTemplateName(
2129 true, LAngleLoc, TemplateArgs, RAngleLoc))
2132 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
2133 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2134 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
2135 // Form a parsed representation of the template-id to be stored in the
2138 // FIXME: Store name for literal operator too.
2139 IdentifierInfo *TemplateII =
2140 Id.getKind() == UnqualifiedId::IK_Identifier ? Id.Identifier : nullptr;
2141 OverloadedOperatorKind OpKind = Id.getKind() == UnqualifiedId::IK_Identifier
2143 : Id.OperatorFunctionId.Operator;
2145 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2146 SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2147 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2149 Id.setTemplateId(TemplateId);
2153 // Bundle the template arguments together.
2154 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2156 // Constructor and destructor names.
2158 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2159 Template, Name, NameLoc,
2160 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2161 /*IsCtorOrDtorName=*/true);
2162 if (Type.isInvalid())
2165 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2166 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2168 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2173 /// \brief Parse an operator-function-id or conversion-function-id as part
2174 /// of a C++ unqualified-id.
2176 /// This routine is responsible only for parsing the operator-function-id or
2177 /// conversion-function-id; it does not handle template arguments in any way.
2180 /// operator-function-id: [C++ 13.5]
2181 /// 'operator' operator
2183 /// operator: one of
2184 /// new delete new[] delete[]
2185 /// + - * / % ^ & | ~
2186 /// ! = < > += -= *= /= %=
2187 /// ^= &= |= << >> >>= <<= == !=
2188 /// <= >= && || ++ -- , ->* ->
2191 /// conversion-function-id: [C++ 12.3.2]
2192 /// operator conversion-type-id
2194 /// conversion-type-id:
2195 /// type-specifier-seq conversion-declarator[opt]
2197 /// conversion-declarator:
2198 /// ptr-operator conversion-declarator[opt]
2201 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2202 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2204 /// \param EnteringContext whether we are entering the scope of the
2205 /// nested-name-specifier.
2207 /// \param ObjectType if this unqualified-id occurs within a member access
2208 /// expression, the type of the base object whose member is being accessed.
2210 /// \param Result on a successful parse, contains the parsed unqualified-id.
2212 /// \returns true if parsing fails, false otherwise.
2213 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2214 ParsedType ObjectType,
2215 UnqualifiedId &Result) {
2216 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2218 // Consume the 'operator' keyword.
2219 SourceLocation KeywordLoc = ConsumeToken();
2221 // Determine what kind of operator name we have.
2222 unsigned SymbolIdx = 0;
2223 SourceLocation SymbolLocations[3];
2224 OverloadedOperatorKind Op = OO_None;
2225 switch (Tok.getKind()) {
2227 case tok::kw_delete: {
2228 bool isNew = Tok.getKind() == tok::kw_new;
2229 // Consume the 'new' or 'delete'.
2230 SymbolLocations[SymbolIdx++] = ConsumeToken();
2231 // Check for array new/delete.
2232 if (Tok.is(tok::l_square) &&
2233 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2234 // Consume the '[' and ']'.
2235 BalancedDelimiterTracker T(*this, tok::l_square);
2238 if (T.getCloseLocation().isInvalid())
2241 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2242 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2243 Op = isNew? OO_Array_New : OO_Array_Delete;
2245 Op = isNew? OO_New : OO_Delete;
2250 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2252 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2255 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2256 #include "clang/Basic/OperatorKinds.def"
2258 case tok::l_paren: {
2259 // Consume the '(' and ')'.
2260 BalancedDelimiterTracker T(*this, tok::l_paren);
2263 if (T.getCloseLocation().isInvalid())
2266 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2267 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2272 case tok::l_square: {
2273 // Consume the '[' and ']'.
2274 BalancedDelimiterTracker T(*this, tok::l_square);
2277 if (T.getCloseLocation().isInvalid())
2280 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2281 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2286 case tok::code_completion: {
2287 // Code completion for the operator name.
2288 Actions.CodeCompleteOperatorName(getCurScope());
2290 // Don't try to parse any further.
2298 if (Op != OO_None) {
2299 // We have parsed an operator-function-id.
2300 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2304 // Parse a literal-operator-id.
2306 // literal-operator-id: C++11 [over.literal]
2307 // operator string-literal identifier
2308 // operator user-defined-string-literal
2310 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2311 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2313 SourceLocation DiagLoc;
2314 unsigned DiagId = 0;
2316 // We're past translation phase 6, so perform string literal concatenation
2317 // before checking for "".
2318 SmallVector<Token, 4> Toks;
2319 SmallVector<SourceLocation, 4> TokLocs;
2320 while (isTokenStringLiteral()) {
2321 if (!Tok.is(tok::string_literal) && !DiagId) {
2322 // C++11 [over.literal]p1:
2323 // The string-literal or user-defined-string-literal in a
2324 // literal-operator-id shall have no encoding-prefix [...].
2325 DiagLoc = Tok.getLocation();
2326 DiagId = diag::err_literal_operator_string_prefix;
2328 Toks.push_back(Tok);
2329 TokLocs.push_back(ConsumeStringToken());
2332 StringLiteralParser Literal(Toks, PP);
2333 if (Literal.hadError)
2336 // Grab the literal operator's suffix, which will be either the next token
2337 // or a ud-suffix from the string literal.
2338 IdentifierInfo *II = nullptr;
2339 SourceLocation SuffixLoc;
2340 if (!Literal.getUDSuffix().empty()) {
2341 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2343 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2344 Literal.getUDSuffixOffset(),
2345 PP.getSourceManager(), getLangOpts());
2346 } else if (Tok.is(tok::identifier)) {
2347 II = Tok.getIdentifierInfo();
2348 SuffixLoc = ConsumeToken();
2349 TokLocs.push_back(SuffixLoc);
2351 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2355 // The string literal must be empty.
2356 if (!Literal.GetString().empty() || Literal.Pascal) {
2357 // C++11 [over.literal]p1:
2358 // The string-literal or user-defined-string-literal in a
2359 // literal-operator-id shall [...] contain no characters
2360 // other than the implicit terminating '\0'.
2361 DiagLoc = TokLocs.front();
2362 DiagId = diag::err_literal_operator_string_not_empty;
2366 // This isn't a valid literal-operator-id, but we think we know
2367 // what the user meant. Tell them what they should have written.
2368 SmallString<32> Str;
2370 Str += II->getName();
2371 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2372 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2375 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2377 return Actions.checkLiteralOperatorId(SS, Result);
2380 // Parse a conversion-function-id.
2382 // conversion-function-id: [C++ 12.3.2]
2383 // operator conversion-type-id
2385 // conversion-type-id:
2386 // type-specifier-seq conversion-declarator[opt]
2388 // conversion-declarator:
2389 // ptr-operator conversion-declarator[opt]
2391 // Parse the type-specifier-seq.
2392 DeclSpec DS(AttrFactory);
2393 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2396 // Parse the conversion-declarator, which is merely a sequence of
2398 Declarator D(DS, Declarator::ConversionIdContext);
2399 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2401 // Finish up the type.
2402 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2406 // Note that this is a conversion-function-id.
2407 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2408 D.getSourceRange().getEnd());
2412 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2413 /// name of an entity.
2416 /// unqualified-id: [C++ expr.prim.general]
2418 /// operator-function-id
2419 /// conversion-function-id
2420 /// [C++0x] literal-operator-id [TODO]
2426 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2427 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2429 /// \param EnteringContext whether we are entering the scope of the
2430 /// nested-name-specifier.
2432 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2434 /// \param AllowConstructorName whether we allow parsing a constructor name.
2436 /// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2438 /// \param ObjectType if this unqualified-id occurs within a member access
2439 /// expression, the type of the base object whose member is being accessed.
2441 /// \param Result on a successful parse, contains the parsed unqualified-id.
2443 /// \returns true if parsing fails, false otherwise.
2444 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2445 bool AllowDestructorName,
2446 bool AllowConstructorName,
2447 bool AllowDeductionGuide,
2448 ParsedType ObjectType,
2449 SourceLocation& TemplateKWLoc,
2450 UnqualifiedId &Result) {
2452 // Handle 'A::template B'. This is for template-ids which have not
2453 // already been annotated by ParseOptionalCXXScopeSpecifier().
2454 bool TemplateSpecified = false;
2455 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2456 (ObjectType || SS.isSet())) {
2457 TemplateSpecified = true;
2458 TemplateKWLoc = ConsumeToken();
2463 // template-id (when it hasn't already been annotated)
2464 if (Tok.is(tok::identifier)) {
2465 // Consume the identifier.
2466 IdentifierInfo *Id = Tok.getIdentifierInfo();
2467 SourceLocation IdLoc = ConsumeToken();
2469 if (!getLangOpts().CPlusPlus) {
2470 // If we're not in C++, only identifiers matter. Record the
2471 // identifier and return.
2472 Result.setIdentifier(Id, IdLoc);
2476 ParsedTemplateTy TemplateName;
2477 if (AllowConstructorName &&
2478 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2479 // We have parsed a constructor name.
2480 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, false,
2482 /*IsCtorOrDtorName=*/true,
2483 /*NonTrivialTypeSourceInfo=*/true);
2484 Result.setConstructorName(Ty, IdLoc, IdLoc);
2485 } else if (getLangOpts().CPlusPlus17 &&
2486 AllowDeductionGuide && SS.isEmpty() &&
2487 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2489 // We have parsed a template-name naming a deduction guide.
2490 Result.setDeductionGuideName(TemplateName, IdLoc);
2492 // We have parsed an identifier.
2493 Result.setIdentifier(Id, IdLoc);
2496 // If the next token is a '<', we may have a template.
2497 if (TemplateSpecified || Tok.is(tok::less))
2498 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2499 EnteringContext, ObjectType,
2500 Result, TemplateSpecified);
2506 // template-id (already parsed and annotated)
2507 if (Tok.is(tok::annot_template_id)) {
2508 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2510 // If the template-name names the current class, then this is a constructor
2511 if (AllowConstructorName && TemplateId->Name &&
2512 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2514 // C++ [class.qual]p2 specifies that a qualified template-name
2515 // is taken as the constructor name where a constructor can be
2516 // declared. Thus, the template arguments are extraneous, so
2517 // complain about them and remove them entirely.
2518 Diag(TemplateId->TemplateNameLoc,
2519 diag::err_out_of_line_constructor_template_id)
2521 << FixItHint::CreateRemoval(
2522 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2524 Actions.getTypeName(*TemplateId->Name, TemplateId->TemplateNameLoc,
2525 getCurScope(), &SS, false, false, nullptr,
2526 /*IsCtorOrDtorName=*/true,
2527 /*NontrivialTypeSourceInfo=*/true);
2528 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2529 TemplateId->RAngleLoc);
2530 ConsumeAnnotationToken();
2534 Result.setConstructorTemplateId(TemplateId);
2535 ConsumeAnnotationToken();
2539 // We have already parsed a template-id; consume the annotation token as
2540 // our unqualified-id.
2541 Result.setTemplateId(TemplateId);
2542 TemplateKWLoc = TemplateId->TemplateKWLoc;
2543 ConsumeAnnotationToken();
2548 // operator-function-id
2549 // conversion-function-id
2550 if (Tok.is(tok::kw_operator)) {
2551 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2554 // If we have an operator-function-id or a literal-operator-id and the next
2555 // token is a '<', we may have a
2558 // operator-function-id < template-argument-list[opt] >
2559 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2560 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2561 (TemplateSpecified || Tok.is(tok::less)))
2562 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2563 nullptr, SourceLocation(),
2564 EnteringContext, ObjectType,
2565 Result, TemplateSpecified);
2570 if (getLangOpts().CPlusPlus &&
2571 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2572 // C++ [expr.unary.op]p10:
2573 // There is an ambiguity in the unary-expression ~X(), where X is a
2574 // class-name. The ambiguity is resolved in favor of treating ~ as a
2575 // unary complement rather than treating ~X as referring to a destructor.
2578 SourceLocation TildeLoc = ConsumeToken();
2580 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2581 DeclSpec DS(AttrFactory);
2582 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2583 if (ParsedType Type =
2584 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2585 Result.setDestructorName(TildeLoc, Type, EndLoc);
2591 // Parse the class-name.
2592 if (Tok.isNot(tok::identifier)) {
2593 Diag(Tok, diag::err_destructor_tilde_identifier);
2597 // If the user wrote ~T::T, correct it to T::~T.
2598 DeclaratorScopeObj DeclScopeObj(*this, SS);
2599 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2600 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2601 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2602 // it will confuse this recovery logic.
2603 ColonProtectionRAIIObject ColonRAII(*this, false);
2606 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2609 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2611 if (SS.isNotEmpty())
2612 ObjectType = nullptr;
2613 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2615 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2619 // Recover as if the tilde had been written before the identifier.
2620 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2621 << FixItHint::CreateRemoval(TildeLoc)
2622 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2624 // Temporarily enter the scope for the rest of this function.
2625 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2626 DeclScopeObj.EnterDeclaratorScope();
2629 // Parse the class-name (or template-name in a simple-template-id).
2630 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2631 SourceLocation ClassNameLoc = ConsumeToken();
2633 if (TemplateSpecified || Tok.is(tok::less)) {
2634 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2635 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2636 ClassName, ClassNameLoc,
2637 EnteringContext, ObjectType,
2638 Result, TemplateSpecified);
2641 // Note that this is a destructor name.
2642 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2643 ClassNameLoc, getCurScope(),
2649 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2653 Diag(Tok, diag::err_expected_unqualified_id)
2654 << getLangOpts().CPlusPlus;
2658 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2659 /// memory in a typesafe manner and call constructors.
2661 /// This method is called to parse the new expression after the optional :: has
2662 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2663 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2666 /// '::'[opt] 'new' new-placement[opt] new-type-id
2667 /// new-initializer[opt]
2668 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2669 /// new-initializer[opt]
2672 /// '(' expression-list ')'
2675 /// type-specifier-seq new-declarator[opt]
2676 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2679 /// ptr-operator new-declarator[opt]
2680 /// direct-new-declarator
2682 /// new-initializer:
2683 /// '(' expression-list[opt] ')'
2684 /// [C++0x] braced-init-list
2687 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2688 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2689 ConsumeToken(); // Consume 'new'
2691 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2692 // second form of new-expression. It can't be a new-type-id.
2694 ExprVector PlacementArgs;
2695 SourceLocation PlacementLParen, PlacementRParen;
2697 SourceRange TypeIdParens;
2698 DeclSpec DS(AttrFactory);
2699 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2700 if (Tok.is(tok::l_paren)) {
2701 // If it turns out to be a placement, we change the type location.
2702 BalancedDelimiterTracker T(*this, tok::l_paren);
2704 PlacementLParen = T.getOpenLocation();
2705 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2706 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2711 PlacementRParen = T.getCloseLocation();
2712 if (PlacementRParen.isInvalid()) {
2713 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2717 if (PlacementArgs.empty()) {
2718 // Reset the placement locations. There was no placement.
2719 TypeIdParens = T.getRange();
2720 PlacementLParen = PlacementRParen = SourceLocation();
2722 // We still need the type.
2723 if (Tok.is(tok::l_paren)) {
2724 BalancedDelimiterTracker T(*this, tok::l_paren);
2726 MaybeParseGNUAttributes(DeclaratorInfo);
2727 ParseSpecifierQualifierList(DS);
2728 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2729 ParseDeclarator(DeclaratorInfo);
2731 TypeIdParens = T.getRange();
2733 MaybeParseGNUAttributes(DeclaratorInfo);
2734 if (ParseCXXTypeSpecifierSeq(DS))
2735 DeclaratorInfo.setInvalidType(true);
2737 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2738 ParseDeclaratorInternal(DeclaratorInfo,
2739 &Parser::ParseDirectNewDeclarator);
2744 // A new-type-id is a simplified type-id, where essentially the
2745 // direct-declarator is replaced by a direct-new-declarator.
2746 MaybeParseGNUAttributes(DeclaratorInfo);
2747 if (ParseCXXTypeSpecifierSeq(DS))
2748 DeclaratorInfo.setInvalidType(true);
2750 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2751 ParseDeclaratorInternal(DeclaratorInfo,
2752 &Parser::ParseDirectNewDeclarator);
2755 if (DeclaratorInfo.isInvalidType()) {
2756 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2760 ExprResult Initializer;
2762 if (Tok.is(tok::l_paren)) {
2763 SourceLocation ConstructorLParen, ConstructorRParen;
2764 ExprVector ConstructorArgs;
2765 BalancedDelimiterTracker T(*this, tok::l_paren);
2767 ConstructorLParen = T.getOpenLocation();
2768 if (Tok.isNot(tok::r_paren)) {
2769 CommaLocsTy CommaLocs;
2770 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2771 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2772 DeclaratorInfo).get();
2773 Actions.CodeCompleteConstructor(getCurScope(),
2774 TypeRep.get()->getCanonicalTypeInternal(),
2775 DeclaratorInfo.getLocEnd(),
2778 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2783 ConstructorRParen = T.getCloseLocation();
2784 if (ConstructorRParen.isInvalid()) {
2785 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2788 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2791 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2792 Diag(Tok.getLocation(),
2793 diag::warn_cxx98_compat_generalized_initializer_lists);
2794 Initializer = ParseBraceInitializer();
2796 if (Initializer.isInvalid())
2799 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2800 PlacementArgs, PlacementRParen,
2801 TypeIdParens, DeclaratorInfo, Initializer.get());
2804 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2805 /// passed to ParseDeclaratorInternal.
2807 /// direct-new-declarator:
2808 /// '[' expression ']'
2809 /// direct-new-declarator '[' constant-expression ']'
2811 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2812 // Parse the array dimensions.
2814 while (Tok.is(tok::l_square)) {
2815 // An array-size expression can't start with a lambda.
2816 if (CheckProhibitedCXX11Attribute())
2819 BalancedDelimiterTracker T(*this, tok::l_square);
2822 ExprResult Size(first ? ParseExpression()
2823 : ParseConstantExpression());
2824 if (Size.isInvalid()) {
2826 SkipUntil(tok::r_square, StopAtSemi);
2833 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2834 ParsedAttributes Attrs(AttrFactory);
2835 MaybeParseCXX11Attributes(Attrs);
2837 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2838 /*static=*/false, /*star=*/false,
2840 T.getOpenLocation(),
2841 T.getCloseLocation()),
2842 Attrs, T.getCloseLocation());
2844 if (T.getCloseLocation().isInvalid())
2849 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2850 /// This ambiguity appears in the syntax of the C++ new operator.
2853 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2854 /// new-initializer[opt]
2857 /// '(' expression-list ')'
2859 bool Parser::ParseExpressionListOrTypeId(
2860 SmallVectorImpl<Expr*> &PlacementArgs,
2862 // The '(' was already consumed.
2863 if (isTypeIdInParens()) {
2864 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2865 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2867 return D.isInvalidType();
2870 // It's not a type, it has to be an expression list.
2871 // Discard the comma locations - ActOnCXXNew has enough parameters.
2872 CommaLocsTy CommaLocs;
2873 return ParseExpressionList(PlacementArgs, CommaLocs);
2876 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2877 /// to free memory allocated by new.
2879 /// This method is called to parse the 'delete' expression after the optional
2880 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2881 /// and "Start" is its location. Otherwise, "Start" is the location of the
2884 /// delete-expression:
2885 /// '::'[opt] 'delete' cast-expression
2886 /// '::'[opt] 'delete' '[' ']' cast-expression
2888 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2889 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2890 ConsumeToken(); // Consume 'delete'
2893 bool ArrayDelete = false;
2894 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2895 // C++11 [expr.delete]p1:
2896 // Whenever the delete keyword is followed by empty square brackets, it
2897 // shall be interpreted as [array delete].
2898 // [Footnote: A lambda expression with a lambda-introducer that consists
2899 // of empty square brackets can follow the delete keyword if
2900 // the lambda expression is enclosed in parentheses.]
2901 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2902 // lambda-introducer.
2904 BalancedDelimiterTracker T(*this, tok::l_square);
2908 if (T.getCloseLocation().isInvalid())
2912 ExprResult Operand(ParseCastExpression(false));
2913 if (Operand.isInvalid())
2916 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2919 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2921 default: llvm_unreachable("Not a known type trait");
2922 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2923 case tok::kw_ ## Spelling: return UTT_ ## Name;
2924 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2925 case tok::kw_ ## Spelling: return BTT_ ## Name;
2926 #include "clang/Basic/TokenKinds.def"
2927 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2928 case tok::kw_ ## Spelling: return TT_ ## Name;
2929 #include "clang/Basic/TokenKinds.def"
2933 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2935 default: llvm_unreachable("Not a known binary type trait");
2936 case tok::kw___array_rank: return ATT_ArrayRank;
2937 case tok::kw___array_extent: return ATT_ArrayExtent;
2941 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2943 default: llvm_unreachable("Not a known unary expression trait.");
2944 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2945 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2949 static unsigned TypeTraitArity(tok::TokenKind kind) {
2951 default: llvm_unreachable("Not a known type trait");
2952 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2953 #include "clang/Basic/TokenKinds.def"
2957 /// \brief Parse the built-in type-trait pseudo-functions that allow
2958 /// implementation of the TR1/C++11 type traits templates.
2960 /// primary-expression:
2961 /// unary-type-trait '(' type-id ')'
2962 /// binary-type-trait '(' type-id ',' type-id ')'
2963 /// type-trait '(' type-id-seq ')'
2966 /// type-id ...[opt] type-id-seq[opt]
2968 ExprResult Parser::ParseTypeTrait() {
2969 tok::TokenKind Kind = Tok.getKind();
2970 unsigned Arity = TypeTraitArity(Kind);
2972 SourceLocation Loc = ConsumeToken();
2974 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2975 if (Parens.expectAndConsume())
2978 SmallVector<ParsedType, 2> Args;
2980 // Parse the next type.
2981 TypeResult Ty = ParseTypeName();
2982 if (Ty.isInvalid()) {
2987 // Parse the ellipsis, if present.
2988 if (Tok.is(tok::ellipsis)) {
2989 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2990 if (Ty.isInvalid()) {
2996 // Add this type to the list of arguments.
2997 Args.push_back(Ty.get());
2998 } while (TryConsumeToken(tok::comma));
3000 if (Parens.consumeClose())
3003 SourceLocation EndLoc = Parens.getCloseLocation();
3005 if (Arity && Args.size() != Arity) {
3006 Diag(EndLoc, diag::err_type_trait_arity)
3007 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3011 if (!Arity && Args.empty()) {
3012 Diag(EndLoc, diag::err_type_trait_arity)
3013 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3017 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3020 /// ParseArrayTypeTrait - Parse the built-in array type-trait
3021 /// pseudo-functions.
3023 /// primary-expression:
3024 /// [Embarcadero] '__array_rank' '(' type-id ')'
3025 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3027 ExprResult Parser::ParseArrayTypeTrait() {
3028 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3029 SourceLocation Loc = ConsumeToken();
3031 BalancedDelimiterTracker T(*this, tok::l_paren);
3032 if (T.expectAndConsume())
3035 TypeResult Ty = ParseTypeName();
3036 if (Ty.isInvalid()) {
3037 SkipUntil(tok::comma, StopAtSemi);
3038 SkipUntil(tok::r_paren, StopAtSemi);
3043 case ATT_ArrayRank: {
3045 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3046 T.getCloseLocation());
3048 case ATT_ArrayExtent: {
3049 if (ExpectAndConsume(tok::comma)) {
3050 SkipUntil(tok::r_paren, StopAtSemi);
3054 ExprResult DimExpr = ParseExpression();
3057 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3058 T.getCloseLocation());
3061 llvm_unreachable("Invalid ArrayTypeTrait!");
3064 /// ParseExpressionTrait - Parse built-in expression-trait
3065 /// pseudo-functions like __is_lvalue_expr( xxx ).
3067 /// primary-expression:
3068 /// [Embarcadero] expression-trait '(' expression ')'
3070 ExprResult Parser::ParseExpressionTrait() {
3071 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3072 SourceLocation Loc = ConsumeToken();
3074 BalancedDelimiterTracker T(*this, tok::l_paren);
3075 if (T.expectAndConsume())
3078 ExprResult Expr = ParseExpression();
3082 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3083 T.getCloseLocation());
3087 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3088 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3089 /// based on the context past the parens.
3091 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3093 BalancedDelimiterTracker &Tracker,
3094 ColonProtectionRAIIObject &ColonProt) {
3095 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3096 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3097 assert(isTypeIdInParens() && "Not a type-id!");
3099 ExprResult Result(true);
3102 // We need to disambiguate a very ugly part of the C++ syntax:
3104 // (T())x; - type-id
3105 // (T())*x; - type-id
3106 // (T())/x; - expression
3107 // (T()); - expression
3109 // The bad news is that we cannot use the specialized tentative parser, since
3110 // it can only verify that the thing inside the parens can be parsed as
3111 // type-id, it is not useful for determining the context past the parens.
3113 // The good news is that the parser can disambiguate this part without
3114 // making any unnecessary Action calls.
3116 // It uses a scheme similar to parsing inline methods. The parenthesized
3117 // tokens are cached, the context that follows is determined (possibly by
3118 // parsing a cast-expression), and then we re-introduce the cached tokens
3119 // into the token stream and parse them appropriately.
3121 ParenParseOption ParseAs;
3124 // Store the tokens of the parentheses. We will parse them after we determine
3125 // the context that follows them.
3126 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3127 // We didn't find the ')' we expected.
3128 Tracker.consumeClose();
3132 if (Tok.is(tok::l_brace)) {
3133 ParseAs = CompoundLiteral;
3136 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3139 // Try parsing the cast-expression that may follow.
3140 // If it is not a cast-expression, NotCastExpr will be true and no token
3141 // will be consumed.
3142 ColonProt.restore();
3143 Result = ParseCastExpression(false/*isUnaryExpression*/,
3144 false/*isAddressofOperand*/,
3146 // type-id has priority.
3150 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3152 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3155 // Create a fake EOF to mark end of Toks buffer.
3157 AttrEnd.startToken();
3158 AttrEnd.setKind(tok::eof);
3159 AttrEnd.setLocation(Tok.getLocation());
3160 AttrEnd.setEofData(Toks.data());
3161 Toks.push_back(AttrEnd);
3163 // The current token should go after the cached tokens.
3164 Toks.push_back(Tok);
3165 // Re-enter the stored parenthesized tokens into the token stream, so we may
3167 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
3168 // Drop the current token and bring the first cached one. It's the same token
3169 // as when we entered this function.
3172 if (ParseAs >= CompoundLiteral) {
3173 // Parse the type declarator.
3174 DeclSpec DS(AttrFactory);
3175 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
3177 ColonProtectionRAIIObject InnerColonProtection(*this);
3178 ParseSpecifierQualifierList(DS);
3179 ParseDeclarator(DeclaratorInfo);
3183 Tracker.consumeClose();
3184 ColonProt.restore();
3186 // Consume EOF marker for Toks buffer.
3187 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3190 if (ParseAs == CompoundLiteral) {
3191 ExprType = CompoundLiteral;
3192 if (DeclaratorInfo.isInvalidType())
3195 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3196 return ParseCompoundLiteralExpression(Ty.get(),
3197 Tracker.getOpenLocation(),
3198 Tracker.getCloseLocation());
3201 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3202 assert(ParseAs == CastExpr);
3204 if (DeclaratorInfo.isInvalidType())
3207 // Result is what ParseCastExpression returned earlier.
3208 if (!Result.isInvalid())
3209 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3210 DeclaratorInfo, CastTy,
3211 Tracker.getCloseLocation(), Result.get());
3215 // Not a compound literal, and not followed by a cast-expression.
3216 assert(ParseAs == SimpleExpr);
3218 ExprType = SimpleExpr;
3219 Result = ParseExpression();
3220 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3221 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3222 Tok.getLocation(), Result.get());
3225 if (Result.isInvalid()) {
3226 while (Tok.isNot(tok::eof))
3228 assert(Tok.getEofData() == AttrEnd.getEofData());
3233 Tracker.consumeClose();
3234 // Consume EOF marker for Toks buffer.
3235 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());