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/AST/ASTContext.h"
14 #include "RAIIObjectsForParser.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/Parser.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 Emits an error for a left parentheses after a double colon.
105 /// When a '(' is found after a '::', emit an error. Attempt to fix the token
106 /// stream by removing the '(', and the matching ')' if found.
107 void Parser::CheckForLParenAfterColonColon() {
108 if (!Tok.is(tok::l_paren))
112 Token NextTok = GetLookAheadToken(1);
113 Token StarTok = NextTok;
114 // Check for (identifier or (*identifier
115 Token IdentifierTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : StarTok;
116 if (IdentifierTok.isNot(tok::identifier))
121 RParen.setLocation(SourceLocation());
122 // Do we have a ')' ?
123 NextTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : GetLookAheadToken(1);
124 if (NextTok.is(tok::r_paren)) {
126 // Eat the '*' if it is present.
127 if (StarTok.is(tok::star))
129 // Eat the identifier.
131 // Add the identifier token back.
132 PP.EnterToken(IdentifierTok);
133 // Add the '*' back if it was present.
134 if (StarTok.is(tok::star))
135 PP.EnterToken(StarTok);
140 Diag(LParen.getLocation(), diag::err_paren_after_colon_colon)
141 << FixItHint::CreateRemoval(LParen.getLocation())
142 << FixItHint::CreateRemoval(RParen.getLocation());
145 /// \brief Parse global scope or nested-name-specifier if present.
147 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
148 /// may be preceded by '::'). Note that this routine will not parse ::new or
149 /// ::delete; it will just leave them in the token stream.
151 /// '::'[opt] nested-name-specifier
154 /// nested-name-specifier:
156 /// namespace-name '::'
157 /// nested-name-specifier identifier '::'
158 /// nested-name-specifier 'template'[opt] simple-template-id '::'
161 /// \param SS the scope specifier that will be set to the parsed
162 /// nested-name-specifier (or empty)
164 /// \param ObjectType if this nested-name-specifier is being parsed following
165 /// the "." or "->" of a member access expression, this parameter provides the
166 /// type of the object whose members are being accessed.
168 /// \param EnteringContext whether we will be entering into the context of
169 /// the nested-name-specifier after parsing it.
171 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
172 /// indicates whether this nested-name-specifier may be part of a
173 /// pseudo-destructor name. In this case, the flag will be set false
174 /// if we don't actually end up parsing a destructor name. Moreorover,
175 /// if we do end up determining that we are parsing a destructor name,
176 /// the last component of the nested-name-specifier is not parsed as
177 /// part of the scope specifier.
179 /// \param IsTypename If \c true, this nested-name-specifier is known to be
180 /// part of a type name. This is used to improve error recovery.
182 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
183 /// filled in with the leading identifier in the last component of the
184 /// nested-name-specifier, if any.
186 /// \returns true if there was an error parsing a scope specifier
187 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
188 ParsedType ObjectType,
189 bool EnteringContext,
190 bool *MayBePseudoDestructor,
192 IdentifierInfo **LastII) {
193 assert(getLangOpts().CPlusPlus &&
194 "Call sites of this function should be guarded by checking for C++");
196 if (Tok.is(tok::annot_cxxscope)) {
197 assert(!LastII && "want last identifier but have already annotated scope");
198 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
199 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
200 Tok.getAnnotationRange(),
206 if (Tok.is(tok::annot_template_id)) {
207 // If the current token is an annotated template id, it may already have
208 // a scope specifier. Restore it.
209 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
213 // Has to happen before any "return false"s in this function.
214 bool CheckForDestructor = false;
215 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
216 CheckForDestructor = true;
217 *MayBePseudoDestructor = false;
223 bool HasScopeSpecifier = false;
225 if (Tok.is(tok::coloncolon)) {
226 // ::new and ::delete aren't nested-name-specifiers.
227 tok::TokenKind NextKind = NextToken().getKind();
228 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
231 if (NextKind == tok::l_brace) {
232 // It is invalid to have :: {, consume the scope qualifier and pretend
233 // like we never saw it.
234 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
236 // '::' - Global scope qualifier.
237 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
240 CheckForLParenAfterColonColon();
242 HasScopeSpecifier = true;
246 if (Tok.is(tok::kw___super)) {
247 SourceLocation SuperLoc = ConsumeToken();
248 if (!Tok.is(tok::coloncolon)) {
249 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
253 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
256 if (!HasScopeSpecifier &&
257 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
258 DeclSpec DS(AttrFactory);
259 SourceLocation DeclLoc = Tok.getLocation();
260 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
262 SourceLocation CCLoc;
263 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
264 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
268 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
269 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
271 HasScopeSpecifier = true;
275 if (HasScopeSpecifier) {
276 // C++ [basic.lookup.classref]p5:
277 // If the qualified-id has the form
279 // ::class-name-or-namespace-name::...
281 // the class-name-or-namespace-name is looked up in global scope as a
282 // class-name or namespace-name.
284 // To implement this, we clear out the object type as soon as we've
285 // seen a leading '::' or part of a nested-name-specifier.
286 ObjectType = ParsedType();
288 if (Tok.is(tok::code_completion)) {
289 // Code completion for a nested-name-specifier, where the code
290 // code completion token follows the '::'.
291 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
292 // Include code completion token into the range of the scope otherwise
293 // when we try to annotate the scope tokens the dangling code completion
294 // token will cause assertion in
295 // Preprocessor::AnnotatePreviousCachedTokens.
296 SS.setEndLoc(Tok.getLocation());
302 // nested-name-specifier:
303 // nested-name-specifier 'template'[opt] simple-template-id '::'
305 // Parse the optional 'template' keyword, then make sure we have
306 // 'identifier <' after it.
307 if (Tok.is(tok::kw_template)) {
308 // If we don't have a scope specifier or an object type, this isn't a
309 // nested-name-specifier, since they aren't allowed to start with
311 if (!HasScopeSpecifier && !ObjectType)
314 TentativeParsingAction TPA(*this);
315 SourceLocation TemplateKWLoc = ConsumeToken();
317 UnqualifiedId TemplateName;
318 if (Tok.is(tok::identifier)) {
319 // Consume the identifier.
320 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
322 } else if (Tok.is(tok::kw_operator)) {
323 // We don't need to actually parse the unqualified-id in this case,
324 // because a simple-template-id cannot start with 'operator', but
325 // go ahead and parse it anyway for consistency with the case where
326 // we already annotated the template-id.
327 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
333 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
334 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
335 Diag(TemplateName.getSourceRange().getBegin(),
336 diag::err_id_after_template_in_nested_name_spec)
337 << TemplateName.getSourceRange();
346 // If the next token is not '<', we have a qualified-id that refers
347 // to a template name, such as T::template apply, but is not a
349 if (Tok.isNot(tok::less)) {
354 // Commit to parsing the template-id.
357 if (TemplateNameKind TNK
358 = Actions.ActOnDependentTemplateName(getCurScope(),
359 SS, TemplateKWLoc, TemplateName,
360 ObjectType, EnteringContext,
362 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
363 TemplateName, false))
371 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
376 // So we need to check whether the template-id is a simple-template-id of
377 // the right kind (it should name a type or be dependent), and then
378 // convert it into a type within the nested-name-specifier.
379 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
380 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
381 *MayBePseudoDestructor = true;
386 *LastII = TemplateId->Name;
388 // Consume the template-id token.
391 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
392 SourceLocation CCLoc = ConsumeToken();
394 HasScopeSpecifier = true;
396 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
397 TemplateId->NumArgs);
399 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
401 TemplateId->TemplateKWLoc,
402 TemplateId->Template,
403 TemplateId->TemplateNameLoc,
404 TemplateId->LAngleLoc,
406 TemplateId->RAngleLoc,
409 SourceLocation StartLoc
410 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
411 : TemplateId->TemplateNameLoc;
412 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
418 // The rest of the nested-name-specifier possibilities start with
420 if (Tok.isNot(tok::identifier))
423 IdentifierInfo &II = *Tok.getIdentifierInfo();
425 // nested-name-specifier:
427 // namespace-name '::'
428 // nested-name-specifier identifier '::'
429 Token Next = NextToken();
431 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
432 // and emit a fixit hint for it.
433 if (Next.is(tok::colon) && !ColonIsSacred) {
434 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
436 Next.getLocation(), ObjectType,
438 // If the token after the colon isn't an identifier, it's still an
439 // error, but they probably meant something else strange so don't
440 // recover like this.
441 PP.LookAhead(1).is(tok::identifier)) {
442 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
443 << FixItHint::CreateReplacement(Next.getLocation(), "::");
444 // Recover as if the user wrote '::'.
445 Next.setKind(tok::coloncolon);
449 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
450 // It is invalid to have :: {, consume the scope qualifier and pretend
451 // like we never saw it.
452 Token Identifier = Tok; // Stash away the identifier.
453 ConsumeToken(); // Eat the identifier, current token is now '::'.
454 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
456 UnconsumeToken(Identifier); // Stick the identifier back.
457 Next = NextToken(); // Point Next at the '{' token.
460 if (Next.is(tok::coloncolon)) {
461 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
462 !Actions.isNonTypeNestedNameSpecifier(
463 getCurScope(), SS, Tok.getLocation(), II, ObjectType)) {
464 *MayBePseudoDestructor = true;
469 const Token &Next2 = GetLookAheadToken(2);
470 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
471 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
472 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
474 << FixItHint::CreateReplacement(Next.getLocation(), ":");
477 ColonColon.setKind(tok::colon);
478 PP.EnterToken(ColonColon);
486 // We have an identifier followed by a '::'. Lookup this name
487 // as the name in a nested-name-specifier.
488 Token Identifier = Tok;
489 SourceLocation IdLoc = ConsumeToken();
490 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
491 "NextToken() not working properly!");
492 Token ColonColon = Tok;
493 SourceLocation CCLoc = ConsumeToken();
495 CheckForLParenAfterColonColon();
497 bool IsCorrectedToColon = false;
498 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
499 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
500 ObjectType, EnteringContext, SS,
501 false, CorrectionFlagPtr)) {
502 // Identifier is not recognized as a nested name, but we can have
503 // mistyped '::' instead of ':'.
504 if (CorrectionFlagPtr && IsCorrectedToColon) {
505 ColonColon.setKind(tok::colon);
507 PP.EnterToken(ColonColon);
511 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
513 HasScopeSpecifier = true;
517 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
519 // nested-name-specifier:
521 if (Next.is(tok::less)) {
523 UnqualifiedId TemplateName;
524 TemplateName.setIdentifier(&II, Tok.getLocation());
525 bool MemberOfUnknownSpecialization;
526 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
527 /*hasTemplateKeyword=*/false,
532 MemberOfUnknownSpecialization)) {
533 // We have found a template name, so annotate this token
534 // with a template-id annotation. We do not permit the
535 // template-id to be translated into a type annotation,
536 // because some clients (e.g., the parsing of class template
537 // specializations) still want to see the original template-id
540 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
541 TemplateName, false))
546 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
547 (IsTypename || IsTemplateArgumentList(1))) {
548 // We have something like t::getAs<T>, where getAs is a
549 // member of an unknown specialization. However, this will only
550 // parse correctly as a template, so suggest the keyword 'template'
551 // before 'getAs' and treat this as a dependent template name.
552 unsigned DiagID = diag::err_missing_dependent_template_keyword;
553 if (getLangOpts().MicrosoftExt)
554 DiagID = diag::warn_missing_dependent_template_keyword;
556 Diag(Tok.getLocation(), DiagID)
558 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
560 if (TemplateNameKind TNK
561 = Actions.ActOnDependentTemplateName(getCurScope(),
562 SS, SourceLocation(),
563 TemplateName, ObjectType,
564 EnteringContext, Template)) {
565 // Consume the identifier.
567 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
568 TemplateName, false))
578 // We don't have any tokens that form the beginning of a
579 // nested-name-specifier, so we're done.
583 // Even if we didn't see any pieces of a nested-name-specifier, we
584 // still check whether there is a tilde in this position, which
585 // indicates a potential pseudo-destructor.
586 if (CheckForDestructor && Tok.is(tok::tilde))
587 *MayBePseudoDestructor = true;
592 ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
593 Token &Replacement) {
594 SourceLocation TemplateKWLoc;
596 if (ParseUnqualifiedId(SS,
597 /*EnteringContext=*/false,
598 /*AllowDestructorName=*/false,
599 /*AllowConstructorName=*/false,
600 /*ObjectType=*/ParsedType(), TemplateKWLoc, Name))
603 // This is only the direct operand of an & operator if it is not
604 // followed by a postfix-expression suffix.
605 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
606 isAddressOfOperand = false;
608 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
609 Tok.is(tok::l_paren), isAddressOfOperand,
610 nullptr, /*IsInlineAsmIdentifier=*/false,
614 /// ParseCXXIdExpression - Handle id-expression.
621 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
623 /// '::' operator-function-id
626 /// NOTE: The standard specifies that, for qualified-id, the parser does not
629 /// '::' conversion-function-id
630 /// '::' '~' class-name
632 /// This may cause a slight inconsistency on diagnostics:
637 /// :: A :: ~ C(); // Some Sema error about using destructor with a
639 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
642 /// We simplify the parser a bit and make it work like:
645 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
646 /// '::' unqualified-id
648 /// That way Sema can handle and report similar errors for namespaces and the
651 /// The isAddressOfOperand parameter indicates that this id-expression is a
652 /// direct operand of the address-of operator. This is, besides member contexts,
653 /// the only place where a qualified-id naming a non-static class member may
656 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
658 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
659 // '::' unqualified-id
662 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
666 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
667 if (Result.isUnset()) {
668 // If the ExprResult is valid but null, then typo correction suggested a
669 // keyword replacement that needs to be reparsed.
670 UnconsumeToken(Replacement);
671 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
673 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
674 "for a previous keyword suggestion");
678 /// ParseLambdaExpression - Parse a C++11 lambda expression.
680 /// lambda-expression:
681 /// lambda-introducer lambda-declarator[opt] compound-statement
683 /// lambda-introducer:
684 /// '[' lambda-capture[opt] ']'
689 /// capture-default ',' capture-list
697 /// capture-list ',' capture
701 /// init-capture [C++1y]
708 /// init-capture: [C++1y]
709 /// identifier initializer
710 /// '&' identifier initializer
712 /// lambda-declarator:
713 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
714 /// 'mutable'[opt] exception-specification[opt]
715 /// trailing-return-type[opt]
717 ExprResult Parser::ParseLambdaExpression() {
718 // Parse lambda-introducer.
719 LambdaIntroducer Intro;
720 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
722 Diag(Tok, DiagID.getValue());
723 SkipUntil(tok::r_square, StopAtSemi);
724 SkipUntil(tok::l_brace, StopAtSemi);
725 SkipUntil(tok::r_brace, StopAtSemi);
729 return ParseLambdaExpressionAfterIntroducer(Intro);
732 /// TryParseLambdaExpression - Use lookahead and potentially tentative
733 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
736 /// If we are not looking at a lambda expression, returns ExprError().
737 ExprResult Parser::TryParseLambdaExpression() {
738 assert(getLangOpts().CPlusPlus11
739 && Tok.is(tok::l_square)
740 && "Not at the start of a possible lambda expression.");
742 const Token Next = NextToken(), After = GetLookAheadToken(2);
744 // If lookahead indicates this is a lambda...
745 if (Next.is(tok::r_square) || // []
746 Next.is(tok::equal) || // [=
747 (Next.is(tok::amp) && // [&] or [&,
748 (After.is(tok::r_square) ||
749 After.is(tok::comma))) ||
750 (Next.is(tok::identifier) && // [identifier]
751 After.is(tok::r_square))) {
752 return ParseLambdaExpression();
755 // If lookahead indicates an ObjC message send...
756 // [identifier identifier
757 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
761 // Here, we're stuck: lambda introducers and Objective-C message sends are
762 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
763 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
764 // writing two routines to parse a lambda introducer, just try to parse
765 // a lambda introducer first, and fall back if that fails.
766 // (TryParseLambdaIntroducer never produces any diagnostic output.)
767 LambdaIntroducer Intro;
768 if (TryParseLambdaIntroducer(Intro))
771 return ParseLambdaExpressionAfterIntroducer(Intro);
774 /// \brief Parse a lambda introducer.
775 /// \param Intro A LambdaIntroducer filled in with information about the
776 /// contents of the lambda-introducer.
777 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
778 /// message send and a lambda expression. In this mode, we will
779 /// sometimes skip the initializers for init-captures and not fully
780 /// populate \p Intro. This flag will be set to \c true if we do so.
781 /// \return A DiagnosticID if it hit something unexpected. The location for
782 /// for the diagnostic is that of the current token.
783 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
784 bool *SkippedInits) {
785 typedef Optional<unsigned> DiagResult;
787 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
788 BalancedDelimiterTracker T(*this, tok::l_square);
791 Intro.Range.setBegin(T.getOpenLocation());
795 // Parse capture-default.
796 if (Tok.is(tok::amp) &&
797 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
798 Intro.Default = LCD_ByRef;
799 Intro.DefaultLoc = ConsumeToken();
801 } else if (Tok.is(tok::equal)) {
802 Intro.Default = LCD_ByCopy;
803 Intro.DefaultLoc = ConsumeToken();
807 while (Tok.isNot(tok::r_square)) {
809 if (Tok.isNot(tok::comma)) {
810 // Provide a completion for a lambda introducer here. Except
811 // in Objective-C, where this is Almost Surely meant to be a message
812 // send. In that case, fail here and let the ObjC message
813 // expression parser perform the completion.
814 if (Tok.is(tok::code_completion) &&
815 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
816 !Intro.Captures.empty())) {
817 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
818 /*AfterAmpersand=*/false);
823 return DiagResult(diag::err_expected_comma_or_rsquare);
828 if (Tok.is(tok::code_completion)) {
829 // If we're in Objective-C++ and we have a bare '[', then this is more
830 // likely to be a message receiver.
831 if (getLangOpts().ObjC1 && first)
832 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
834 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
835 /*AfterAmpersand=*/false);
843 LambdaCaptureKind Kind = LCK_ByCopy;
845 IdentifierInfo *Id = nullptr;
846 SourceLocation EllipsisLoc;
849 if (Tok.is(tok::kw_this)) {
851 Loc = ConsumeToken();
853 if (Tok.is(tok::amp)) {
857 if (Tok.is(tok::code_completion)) {
858 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
859 /*AfterAmpersand=*/true);
865 if (Tok.is(tok::identifier)) {
866 Id = Tok.getIdentifierInfo();
867 Loc = ConsumeToken();
868 } else if (Tok.is(tok::kw_this)) {
869 // FIXME: If we want to suggest a fixit here, will need to return more
870 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
871 // Clear()ed to prevent emission in case of tentative parsing?
872 return DiagResult(diag::err_this_captured_by_reference);
874 return DiagResult(diag::err_expected_capture);
877 if (Tok.is(tok::l_paren)) {
878 BalancedDelimiterTracker Parens(*this, tok::l_paren);
879 Parens.consumeOpen();
885 *SkippedInits = true;
886 } else if (ParseExpressionList(Exprs, Commas)) {
890 Parens.consumeClose();
891 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
892 Parens.getCloseLocation(),
895 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
896 // Each lambda init-capture forms its own full expression, which clears
897 // Actions.MaybeODRUseExprs. So create an expression evaluation context
898 // to save the necessary state, and restore it later.
899 EnterExpressionEvaluationContext EC(Actions,
900 Sema::PotentiallyEvaluated);
901 bool HadEquals = TryConsumeToken(tok::equal);
904 // Warn on constructs that will change meaning when we implement N3922
905 if (!HadEquals && Tok.is(tok::l_brace)) {
906 Diag(Tok, diag::warn_init_capture_direct_list_init)
907 << FixItHint::CreateInsertion(Tok.getLocation(), "=");
909 Init = ParseInitializer();
910 } else if (Tok.is(tok::l_brace)) {
911 BalancedDelimiterTracker Braces(*this, tok::l_brace);
912 Braces.consumeOpen();
914 *SkippedInits = true;
916 // We're disambiguating this:
920 // We need to find the end of the following expression in order to
921 // determine whether this is an Obj-C message send's receiver, a
922 // C99 designator, or a lambda init-capture.
924 // Parse the expression to find where it ends, and annotate it back
925 // onto the tokens. We would have parsed this expression the same way
926 // in either case: both the RHS of an init-capture and the RHS of an
927 // assignment expression are parsed as an initializer-clause, and in
928 // neither case can anything be added to the scope between the '[' and
931 // FIXME: This is horrible. Adding a mechanism to skip an expression
932 // would be much cleaner.
933 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
934 // that instead. (And if we see a ':' with no matching '?', we can
935 // classify this as an Obj-C message send.)
936 SourceLocation StartLoc = Tok.getLocation();
937 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
938 Init = ParseInitializer();
940 if (Tok.getLocation() != StartLoc) {
941 // Back out the lexing of the token after the initializer.
942 PP.RevertCachedTokens(1);
944 // Replace the consumed tokens with an appropriate annotation.
945 Tok.setLocation(StartLoc);
946 Tok.setKind(tok::annot_primary_expr);
947 setExprAnnotation(Tok, Init);
948 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
949 PP.AnnotateCachedTokens(Tok);
951 // Consume the annotated initializer.
956 TryConsumeToken(tok::ellipsis, EllipsisLoc);
958 // If this is an init capture, process the initialization expression
959 // right away. For lambda init-captures such as the following:
961 // auto L = [i = x+1](int a) {
963 // &k = x](char b) { };
965 // keep in mind that each lambda init-capture has to have:
966 // - its initialization expression executed in the context
967 // of the enclosing/parent decl-context.
968 // - but the variable itself has to be 'injected' into the
969 // decl-context of its lambda's call-operator (which has
970 // not yet been created).
971 // Each init-expression is a full-expression that has to get
972 // Sema-analyzed (for capturing etc.) before its lambda's
973 // call-operator's decl-context, scope & scopeinfo are pushed on their
974 // respective stacks. Thus if any variable is odr-used in the init-capture
975 // it will correctly get captured in the enclosing lambda, if one exists.
976 // The init-variables above are created later once the lambdascope and
977 // call-operators decl-context is pushed onto its respective stack.
979 // Since the lambda init-capture's initializer expression occurs in the
980 // context of the enclosing function or lambda, therefore we can not wait
981 // till a lambda scope has been pushed on before deciding whether the
982 // variable needs to be captured. We also need to process all
983 // lvalue-to-rvalue conversions and discarded-value conversions,
984 // so that we can avoid capturing certain constant variables.
988 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
989 // return [y = x](int i) { <-- don't capture by enclosing lambda
993 // If x was not const, the second use would require 'L' to capture, and
994 // that would be an error.
996 ParsedType InitCaptureParsedType;
997 if (Init.isUsable()) {
998 // Get the pointer and store it in an lvalue, so we can use it as an
1000 Expr *InitExpr = Init.get();
1001 // This performs any lvalue-to-rvalue conversions if necessary, which
1002 // can affect what gets captured in the containing decl-context.
1003 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
1004 Loc, Kind == LCK_ByRef, Id, InitExpr);
1006 InitCaptureParsedType.set(InitCaptureType);
1008 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
1012 Intro.Range.setEnd(T.getCloseLocation());
1013 return DiagResult();
1016 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
1018 /// Returns true if it hit something unexpected.
1019 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1020 TentativeParsingAction PA(*this);
1022 bool SkippedInits = false;
1023 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
1031 // Parse it again, but this time parse the init-captures too.
1033 Intro = LambdaIntroducer();
1034 DiagID = ParseLambdaIntroducer(Intro);
1035 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1043 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1045 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1046 LambdaIntroducer &Intro) {
1047 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1048 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1050 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1051 "lambda expression parsing");
1055 // FIXME: Call into Actions to add any init-capture declarations to the
1056 // scope while parsing the lambda-declarator and compound-statement.
1058 // Parse lambda-declarator[opt].
1059 DeclSpec DS(AttrFactory);
1060 Declarator D(DS, Declarator::LambdaExprContext);
1061 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1062 Actions.PushLambdaScope();
1064 TypeResult TrailingReturnType;
1065 if (Tok.is(tok::l_paren)) {
1066 ParseScope PrototypeScope(this,
1067 Scope::FunctionPrototypeScope |
1068 Scope::FunctionDeclarationScope |
1071 SourceLocation DeclEndLoc;
1072 BalancedDelimiterTracker T(*this, tok::l_paren);
1074 SourceLocation LParenLoc = T.getOpenLocation();
1076 // Parse parameter-declaration-clause.
1077 ParsedAttributes Attr(AttrFactory);
1078 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1079 SourceLocation EllipsisLoc;
1081 if (Tok.isNot(tok::r_paren)) {
1082 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1083 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1084 // For a generic lambda, each 'auto' within the parameter declaration
1085 // clause creates a template type parameter, so increment the depth.
1086 if (Actions.getCurGenericLambda())
1087 ++CurTemplateDepthTracker;
1090 SourceLocation RParenLoc = T.getCloseLocation();
1091 DeclEndLoc = RParenLoc;
1093 // GNU-style attributes must be parsed before the mutable specifier to be
1094 // compatible with GCC.
1095 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1097 // MSVC-style attributes must be parsed before the mutable specifier to be
1098 // compatible with MSVC.
1099 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1101 // Parse 'mutable'[opt].
1102 SourceLocation MutableLoc;
1103 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
1104 DeclEndLoc = MutableLoc;
1106 // Parse exception-specification[opt].
1107 ExceptionSpecificationType ESpecType = EST_None;
1108 SourceRange ESpecRange;
1109 SmallVector<ParsedType, 2> DynamicExceptions;
1110 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1111 ExprResult NoexceptExpr;
1112 CachedTokens *ExceptionSpecTokens;
1113 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1116 DynamicExceptionRanges,
1118 ExceptionSpecTokens);
1120 if (ESpecType != EST_None)
1121 DeclEndLoc = ESpecRange.getEnd();
1123 // Parse attribute-specifier[opt].
1124 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1126 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1128 // Parse trailing-return-type[opt].
1129 if (Tok.is(tok::arrow)) {
1130 FunLocalRangeEnd = Tok.getLocation();
1132 TrailingReturnType = ParseTrailingReturnType(Range);
1133 if (Range.getEnd().isValid())
1134 DeclEndLoc = Range.getEnd();
1137 PrototypeScope.Exit();
1139 SourceLocation NoLoc;
1140 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1141 /*isAmbiguous=*/false,
1143 ParamInfo.data(), ParamInfo.size(),
1144 EllipsisLoc, RParenLoc,
1145 DS.getTypeQualifiers(),
1146 /*RefQualifierIsLValueRef=*/true,
1147 /*RefQualifierLoc=*/NoLoc,
1148 /*ConstQualifierLoc=*/NoLoc,
1149 /*VolatileQualifierLoc=*/NoLoc,
1150 /*RestrictQualifierLoc=*/NoLoc,
1152 ESpecType, ESpecRange.getBegin(),
1153 DynamicExceptions.data(),
1154 DynamicExceptionRanges.data(),
1155 DynamicExceptions.size(),
1156 NoexceptExpr.isUsable() ?
1157 NoexceptExpr.get() : nullptr,
1158 /*ExceptionSpecTokens*/nullptr,
1159 LParenLoc, FunLocalRangeEnd, D,
1160 TrailingReturnType),
1162 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute) ||
1163 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1164 // It's common to forget that one needs '()' before 'mutable', an attribute
1165 // specifier, or the result type. Deal with this.
1166 unsigned TokKind = 0;
1167 switch (Tok.getKind()) {
1168 case tok::kw_mutable: TokKind = 0; break;
1169 case tok::arrow: TokKind = 1; break;
1170 case tok::kw___attribute:
1171 case tok::l_square: TokKind = 2; break;
1172 default: llvm_unreachable("Unknown token kind");
1175 Diag(Tok, diag::err_lambda_missing_parens)
1177 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1178 SourceLocation DeclLoc = Tok.getLocation();
1179 SourceLocation DeclEndLoc = DeclLoc;
1181 // GNU-style attributes must be parsed before the mutable specifier to be
1182 // compatible with GCC.
1183 ParsedAttributes Attr(AttrFactory);
1184 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1186 // Parse 'mutable', if it's there.
1187 SourceLocation MutableLoc;
1188 if (Tok.is(tok::kw_mutable)) {
1189 MutableLoc = ConsumeToken();
1190 DeclEndLoc = MutableLoc;
1193 // Parse attribute-specifier[opt].
1194 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1196 // Parse the return type, if there is one.
1197 if (Tok.is(tok::arrow)) {
1199 TrailingReturnType = ParseTrailingReturnType(Range);
1200 if (Range.getEnd().isValid())
1201 DeclEndLoc = Range.getEnd();
1204 SourceLocation NoLoc;
1205 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1206 /*isAmbiguous=*/false,
1207 /*LParenLoc=*/NoLoc,
1210 /*EllipsisLoc=*/NoLoc,
1211 /*RParenLoc=*/NoLoc,
1213 /*RefQualifierIsLValueRef=*/true,
1214 /*RefQualifierLoc=*/NoLoc,
1215 /*ConstQualifierLoc=*/NoLoc,
1216 /*VolatileQualifierLoc=*/NoLoc,
1217 /*RestrictQualifierLoc=*/NoLoc,
1221 /*Exceptions=*/nullptr,
1222 /*ExceptionRanges=*/nullptr,
1223 /*NumExceptions=*/0,
1224 /*NoexceptExpr=*/nullptr,
1225 /*ExceptionSpecTokens=*/nullptr,
1226 DeclLoc, DeclEndLoc, D,
1227 TrailingReturnType),
1232 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1234 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
1235 ParseScope BodyScope(this, ScopeFlags);
1237 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1239 // Parse compound-statement.
1240 if (!Tok.is(tok::l_brace)) {
1241 Diag(Tok, diag::err_expected_lambda_body);
1242 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1246 StmtResult Stmt(ParseCompoundStatementBody());
1249 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1250 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1252 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1256 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1259 /// postfix-expression: [C++ 5.2p1]
1260 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1261 /// 'static_cast' '<' type-name '>' '(' expression ')'
1262 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1263 /// 'const_cast' '<' type-name '>' '(' expression ')'
1265 ExprResult Parser::ParseCXXCasts() {
1266 tok::TokenKind Kind = Tok.getKind();
1267 const char *CastName = nullptr; // For error messages
1270 default: llvm_unreachable("Unknown C++ cast!");
1271 case tok::kw_const_cast: CastName = "const_cast"; break;
1272 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1273 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1274 case tok::kw_static_cast: CastName = "static_cast"; break;
1277 SourceLocation OpLoc = ConsumeToken();
1278 SourceLocation LAngleBracketLoc = Tok.getLocation();
1280 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1281 // diagnose error, suggest fix, and recover parsing.
1282 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1283 Token Next = NextToken();
1284 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1285 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1288 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1291 // Parse the common declaration-specifiers piece.
1292 DeclSpec DS(AttrFactory);
1293 ParseSpecifierQualifierList(DS);
1295 // Parse the abstract-declarator, if present.
1296 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1297 ParseDeclarator(DeclaratorInfo);
1299 SourceLocation RAngleBracketLoc = Tok.getLocation();
1301 if (ExpectAndConsume(tok::greater))
1302 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1304 SourceLocation LParenLoc, RParenLoc;
1305 BalancedDelimiterTracker T(*this, tok::l_paren);
1307 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1310 ExprResult Result = ParseExpression();
1315 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1316 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1317 LAngleBracketLoc, DeclaratorInfo,
1319 T.getOpenLocation(), Result.get(),
1320 T.getCloseLocation());
1325 /// ParseCXXTypeid - This handles the C++ typeid expression.
1327 /// postfix-expression: [C++ 5.2p1]
1328 /// 'typeid' '(' expression ')'
1329 /// 'typeid' '(' type-id ')'
1331 ExprResult Parser::ParseCXXTypeid() {
1332 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1334 SourceLocation OpLoc = ConsumeToken();
1335 SourceLocation LParenLoc, RParenLoc;
1336 BalancedDelimiterTracker T(*this, tok::l_paren);
1338 // typeid expressions are always parenthesized.
1339 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1341 LParenLoc = T.getOpenLocation();
1345 // C++0x [expr.typeid]p3:
1346 // When typeid is applied to an expression other than an lvalue of a
1347 // polymorphic class type [...] The expression is an unevaluated
1348 // operand (Clause 5).
1350 // Note that we can't tell whether the expression is an lvalue of a
1351 // polymorphic class type until after we've parsed the expression; we
1352 // speculatively assume the subexpression is unevaluated, and fix it up
1355 // We enter the unevaluated context before trying to determine whether we
1356 // have a type-id, because the tentative parse logic will try to resolve
1357 // names, and must treat them as unevaluated.
1358 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1359 Sema::ReuseLambdaContextDecl);
1361 if (isTypeIdInParens()) {
1362 TypeResult Ty = ParseTypeName();
1366 RParenLoc = T.getCloseLocation();
1367 if (Ty.isInvalid() || RParenLoc.isInvalid())
1370 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1371 Ty.get().getAsOpaquePtr(), RParenLoc);
1373 Result = ParseExpression();
1376 if (Result.isInvalid())
1377 SkipUntil(tok::r_paren, StopAtSemi);
1380 RParenLoc = T.getCloseLocation();
1381 if (RParenLoc.isInvalid())
1384 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1385 Result.get(), RParenLoc);
1392 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1394 /// '__uuidof' '(' expression ')'
1395 /// '__uuidof' '(' type-id ')'
1397 ExprResult Parser::ParseCXXUuidof() {
1398 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1400 SourceLocation OpLoc = ConsumeToken();
1401 BalancedDelimiterTracker T(*this, tok::l_paren);
1403 // __uuidof expressions are always parenthesized.
1404 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1409 if (isTypeIdInParens()) {
1410 TypeResult Ty = ParseTypeName();
1418 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1419 Ty.get().getAsOpaquePtr(),
1420 T.getCloseLocation());
1422 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1423 Result = ParseExpression();
1426 if (Result.isInvalid())
1427 SkipUntil(tok::r_paren, StopAtSemi);
1431 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1433 Result.get(), T.getCloseLocation());
1440 /// \brief Parse a C++ pseudo-destructor expression after the base,
1441 /// . or -> operator, and nested-name-specifier have already been
1444 /// postfix-expression: [C++ 5.2]
1445 /// postfix-expression . pseudo-destructor-name
1446 /// postfix-expression -> pseudo-destructor-name
1448 /// pseudo-destructor-name:
1449 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1450 /// ::[opt] nested-name-specifier template simple-template-id ::
1452 /// ::[opt] nested-name-specifier[opt] ~type-name
1455 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1456 tok::TokenKind OpKind,
1458 ParsedType ObjectType) {
1459 // We're parsing either a pseudo-destructor-name or a dependent
1460 // member access that has the same form as a
1461 // pseudo-destructor-name. We parse both in the same way and let
1462 // the action model sort them out.
1464 // Note that the ::[opt] nested-name-specifier[opt] has already
1465 // been parsed, and if there was a simple-template-id, it has
1466 // been coalesced into a template-id annotation token.
1467 UnqualifiedId FirstTypeName;
1468 SourceLocation CCLoc;
1469 if (Tok.is(tok::identifier)) {
1470 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1472 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1473 CCLoc = ConsumeToken();
1474 } else if (Tok.is(tok::annot_template_id)) {
1475 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1476 // store it in the pseudo-dtor node (to be used when instantiating it).
1477 FirstTypeName.setTemplateId(
1478 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1480 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1481 CCLoc = ConsumeToken();
1483 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1487 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1488 SourceLocation TildeLoc = ConsumeToken();
1490 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1491 DeclSpec DS(AttrFactory);
1492 ParseDecltypeSpecifier(DS);
1493 if (DS.getTypeSpecType() == TST_error)
1495 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1499 if (!Tok.is(tok::identifier)) {
1500 Diag(Tok, diag::err_destructor_tilde_identifier);
1504 // Parse the second type.
1505 UnqualifiedId SecondTypeName;
1506 IdentifierInfo *Name = Tok.getIdentifierInfo();
1507 SourceLocation NameLoc = ConsumeToken();
1508 SecondTypeName.setIdentifier(Name, NameLoc);
1510 // If there is a '<', the second type name is a template-id. Parse
1512 if (Tok.is(tok::less) &&
1513 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1515 false, ObjectType, SecondTypeName,
1516 /*AssumeTemplateName=*/true))
1519 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1520 SS, FirstTypeName, CCLoc, TildeLoc,
1524 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1526 /// boolean-literal: [C++ 2.13.5]
1529 ExprResult Parser::ParseCXXBoolLiteral() {
1530 tok::TokenKind Kind = Tok.getKind();
1531 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1534 /// ParseThrowExpression - This handles the C++ throw expression.
1536 /// throw-expression: [C++ 15]
1537 /// 'throw' assignment-expression[opt]
1538 ExprResult Parser::ParseThrowExpression() {
1539 assert(Tok.is(tok::kw_throw) && "Not throw!");
1540 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1542 // If the current token isn't the start of an assignment-expression,
1543 // then the expression is not present. This handles things like:
1544 // "C ? throw : (void)42", which is crazy but legal.
1545 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1552 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1555 ExprResult Expr(ParseAssignmentExpression());
1556 if (Expr.isInvalid()) return Expr;
1557 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1561 /// ParseCXXThis - This handles the C++ 'this' pointer.
1563 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1564 /// a non-lvalue expression whose value is the address of the object for which
1565 /// the function is called.
1566 ExprResult Parser::ParseCXXThis() {
1567 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1568 SourceLocation ThisLoc = ConsumeToken();
1569 return Actions.ActOnCXXThis(ThisLoc);
1572 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1573 /// Can be interpreted either as function-style casting ("int(x)")
1574 /// or class type construction ("ClassType(x,y,z)")
1575 /// or creation of a value-initialized type ("int()").
1576 /// See [C++ 5.2.3].
1578 /// postfix-expression: [C++ 5.2p1]
1579 /// simple-type-specifier '(' expression-list[opt] ')'
1580 /// [C++0x] simple-type-specifier braced-init-list
1581 /// typename-specifier '(' expression-list[opt] ')'
1582 /// [C++0x] typename-specifier braced-init-list
1585 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1586 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1587 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1589 assert((Tok.is(tok::l_paren) ||
1590 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1591 && "Expected '(' or '{'!");
1593 if (Tok.is(tok::l_brace)) {
1594 ExprResult Init = ParseBraceInitializer();
1595 if (Init.isInvalid())
1597 Expr *InitList = Init.get();
1598 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1599 MultiExprArg(&InitList, 1),
1602 BalancedDelimiterTracker T(*this, tok::l_paren);
1606 CommaLocsTy CommaLocs;
1608 if (Tok.isNot(tok::r_paren)) {
1609 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1610 Actions.CodeCompleteConstructor(getCurScope(),
1611 TypeRep.get()->getCanonicalTypeInternal(),
1612 DS.getLocEnd(), Exprs);
1614 SkipUntil(tok::r_paren, StopAtSemi);
1622 // TypeRep could be null, if it references an invalid typedef.
1626 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1627 "Unexpected number of commas!");
1628 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1630 T.getCloseLocation());
1634 /// ParseCXXCondition - if/switch/while condition expression.
1638 /// type-specifier-seq declarator '=' assignment-expression
1639 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1640 /// [C++11] type-specifier-seq declarator braced-init-list
1641 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1642 /// '=' assignment-expression
1644 /// \param ExprOut if the condition was parsed as an expression, the parsed
1647 /// \param DeclOut if the condition was parsed as a declaration, the parsed
1650 /// \param Loc The location of the start of the statement that requires this
1651 /// condition, e.g., the "for" in a for loop.
1653 /// \param ConvertToBoolean Whether the condition expression should be
1654 /// converted to a boolean value.
1656 /// \returns true if there was a parsing, false otherwise.
1657 bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1660 bool ConvertToBoolean) {
1661 if (Tok.is(tok::code_completion)) {
1662 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1667 ParsedAttributesWithRange attrs(AttrFactory);
1668 MaybeParseCXX11Attributes(attrs);
1670 if (!isCXXConditionDeclaration()) {
1671 ProhibitAttributes(attrs);
1673 // Parse the expression.
1674 ExprOut = ParseExpression(); // expression
1676 if (ExprOut.isInvalid())
1679 // If required, convert to a boolean value.
1680 if (ConvertToBoolean)
1682 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1683 return ExprOut.isInvalid();
1686 // type-specifier-seq
1687 DeclSpec DS(AttrFactory);
1688 DS.takeAttributesFrom(attrs);
1689 ParseSpecifierQualifierList(DS, AS_none, DSC_condition);
1692 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1693 ParseDeclarator(DeclaratorInfo);
1695 // simple-asm-expr[opt]
1696 if (Tok.is(tok::kw_asm)) {
1698 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1699 if (AsmLabel.isInvalid()) {
1700 SkipUntil(tok::semi, StopAtSemi);
1703 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1704 DeclaratorInfo.SetRangeEnd(Loc);
1707 // If attributes are present, parse them.
1708 MaybeParseGNUAttributes(DeclaratorInfo);
1710 // Type-check the declaration itself.
1711 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1713 DeclOut = Dcl.get();
1714 ExprOut = ExprError();
1716 // '=' assignment-expression
1717 // If a '==' or '+=' is found, suggest a fixit to '='.
1718 bool CopyInitialization = isTokenEqualOrEqualTypo();
1719 if (CopyInitialization)
1722 ExprResult InitExpr = ExprError();
1723 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1724 Diag(Tok.getLocation(),
1725 diag::warn_cxx98_compat_generalized_initializer_lists);
1726 InitExpr = ParseBraceInitializer();
1727 } else if (CopyInitialization) {
1728 InitExpr = ParseAssignmentExpression();
1729 } else if (Tok.is(tok::l_paren)) {
1730 // This was probably an attempt to initialize the variable.
1731 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1732 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1733 RParen = ConsumeParen();
1734 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1735 diag::err_expected_init_in_condition_lparen)
1736 << SourceRange(LParen, RParen);
1738 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1739 diag::err_expected_init_in_condition);
1742 if (!InitExpr.isInvalid())
1743 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
1744 DS.containsPlaceholderType());
1746 Actions.ActOnInitializerError(DeclOut);
1748 // FIXME: Build a reference to this declaration? Convert it to bool?
1749 // (This is currently handled by Sema).
1751 Actions.FinalizeDeclaration(DeclOut);
1756 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1757 /// This should only be called when the current token is known to be part of
1758 /// simple-type-specifier.
1760 /// simple-type-specifier:
1761 /// '::'[opt] nested-name-specifier[opt] type-name
1762 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1774 /// [GNU] typeof-specifier
1775 /// [C++0x] auto [TODO]
1782 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1783 DS.SetRangeStart(Tok.getLocation());
1784 const char *PrevSpec;
1786 SourceLocation Loc = Tok.getLocation();
1787 const clang::PrintingPolicy &Policy =
1788 Actions.getASTContext().getPrintingPolicy();
1790 switch (Tok.getKind()) {
1791 case tok::identifier: // foo::bar
1792 case tok::coloncolon: // ::foo::bar
1793 llvm_unreachable("Annotation token should already be formed!");
1795 llvm_unreachable("Not a simple-type-specifier token!");
1798 case tok::annot_typename: {
1799 if (getTypeAnnotation(Tok))
1800 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1801 getTypeAnnotation(Tok), Policy);
1803 DS.SetTypeSpecError();
1805 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1808 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1809 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1810 // Objective-C interface. If we don't have Objective-C or a '<', this is
1811 // just a normal reference to a typedef name.
1812 if (Tok.is(tok::less) && getLangOpts().ObjC1)
1813 ParseObjCProtocolQualifiers(DS);
1815 DS.Finish(Diags, PP, Policy);
1821 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1824 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1826 case tok::kw___int64:
1827 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1829 case tok::kw_signed:
1830 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1832 case tok::kw_unsigned:
1833 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1836 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1839 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1842 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1844 case tok::kw___int128:
1845 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1848 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1851 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1853 case tok::kw_double:
1854 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1856 case tok::kw_wchar_t:
1857 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1859 case tok::kw_char16_t:
1860 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1862 case tok::kw_char32_t:
1863 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1866 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1868 case tok::annot_decltype:
1869 case tok::kw_decltype:
1870 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1871 return DS.Finish(Diags, PP, Policy);
1873 // GNU typeof support.
1874 case tok::kw_typeof:
1875 ParseTypeofSpecifier(DS);
1876 DS.Finish(Diags, PP, Policy);
1879 if (Tok.is(tok::annot_typename))
1880 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1882 DS.SetRangeEnd(Tok.getLocation());
1884 DS.Finish(Diags, PP, Policy);
1887 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1888 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1889 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1890 /// by parsing the type-specifier-seq, because these sequences are
1891 /// typically followed by some form of declarator. Returns true and
1892 /// emits diagnostics if this is not a type-specifier-seq, false
1895 /// type-specifier-seq: [C++ 8.1]
1896 /// type-specifier type-specifier-seq[opt]
1898 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1899 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1900 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
1904 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1907 /// This routine is invoked when a '<' is encountered after an identifier or
1908 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1909 /// whether the unqualified-id is actually a template-id. This routine will
1910 /// then parse the template arguments and form the appropriate template-id to
1911 /// return to the caller.
1913 /// \param SS the nested-name-specifier that precedes this template-id, if
1914 /// we're actually parsing a qualified-id.
1916 /// \param Name for constructor and destructor names, this is the actual
1917 /// identifier that may be a template-name.
1919 /// \param NameLoc the location of the class-name in a constructor or
1922 /// \param EnteringContext whether we're entering the scope of the
1923 /// nested-name-specifier.
1925 /// \param ObjectType if this unqualified-id occurs within a member access
1926 /// expression, the type of the base object whose member is being accessed.
1928 /// \param Id as input, describes the template-name or operator-function-id
1929 /// that precedes the '<'. If template arguments were parsed successfully,
1930 /// will be updated with the template-id.
1932 /// \param AssumeTemplateId When true, this routine will assume that the name
1933 /// refers to a template without performing name lookup to verify.
1935 /// \returns true if a parse error occurred, false otherwise.
1936 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1937 SourceLocation TemplateKWLoc,
1938 IdentifierInfo *Name,
1939 SourceLocation NameLoc,
1940 bool EnteringContext,
1941 ParsedType ObjectType,
1943 bool AssumeTemplateId) {
1944 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1945 "Expected '<' to finish parsing a template-id");
1947 TemplateTy Template;
1948 TemplateNameKind TNK = TNK_Non_template;
1949 switch (Id.getKind()) {
1950 case UnqualifiedId::IK_Identifier:
1951 case UnqualifiedId::IK_OperatorFunctionId:
1952 case UnqualifiedId::IK_LiteralOperatorId:
1953 if (AssumeTemplateId) {
1954 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
1955 Id, ObjectType, EnteringContext,
1957 if (TNK == TNK_Non_template)
1960 bool MemberOfUnknownSpecialization;
1961 TNK = Actions.isTemplateName(getCurScope(), SS,
1962 TemplateKWLoc.isValid(), Id,
1963 ObjectType, EnteringContext, Template,
1964 MemberOfUnknownSpecialization);
1966 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1967 ObjectType && IsTemplateArgumentList()) {
1968 // We have something like t->getAs<T>(), where getAs is a
1969 // member of an unknown specialization. However, this will only
1970 // parse correctly as a template, so suggest the keyword 'template'
1971 // before 'getAs' and treat this as a dependent template name.
1973 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1974 Name = Id.Identifier->getName();
1977 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1978 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1980 Name += Id.Identifier->getName();
1982 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1984 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1985 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1986 SS, TemplateKWLoc, Id,
1987 ObjectType, EnteringContext,
1989 if (TNK == TNK_Non_template)
1995 case UnqualifiedId::IK_ConstructorName: {
1996 UnqualifiedId TemplateName;
1997 bool MemberOfUnknownSpecialization;
1998 TemplateName.setIdentifier(Name, NameLoc);
1999 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2000 TemplateName, ObjectType,
2001 EnteringContext, Template,
2002 MemberOfUnknownSpecialization);
2006 case UnqualifiedId::IK_DestructorName: {
2007 UnqualifiedId TemplateName;
2008 bool MemberOfUnknownSpecialization;
2009 TemplateName.setIdentifier(Name, NameLoc);
2011 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2012 SS, TemplateKWLoc, TemplateName,
2013 ObjectType, EnteringContext,
2015 if (TNK == TNK_Non_template)
2018 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2019 TemplateName, ObjectType,
2020 EnteringContext, Template,
2021 MemberOfUnknownSpecialization);
2023 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2024 Diag(NameLoc, diag::err_destructor_template_id)
2025 << Name << SS.getRange();
2036 if (TNK == TNK_Non_template)
2039 // Parse the enclosed template argument list.
2040 SourceLocation LAngleLoc, RAngleLoc;
2041 TemplateArgList TemplateArgs;
2042 if (Tok.is(tok::less) &&
2043 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
2044 SS, true, LAngleLoc,
2049 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
2050 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2051 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
2052 // Form a parsed representation of the template-id to be stored in the
2054 TemplateIdAnnotation *TemplateId
2055 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
2057 // FIXME: Store name for literal operator too.
2058 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2059 TemplateId->Name = Id.Identifier;
2060 TemplateId->Operator = OO_None;
2061 TemplateId->TemplateNameLoc = Id.StartLocation;
2063 TemplateId->Name = nullptr;
2064 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2065 TemplateId->TemplateNameLoc = Id.StartLocation;
2068 TemplateId->SS = SS;
2069 TemplateId->TemplateKWLoc = TemplateKWLoc;
2070 TemplateId->Template = Template;
2071 TemplateId->Kind = TNK;
2072 TemplateId->LAngleLoc = LAngleLoc;
2073 TemplateId->RAngleLoc = RAngleLoc;
2074 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
2075 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
2076 Arg != ArgEnd; ++Arg)
2077 Args[Arg] = TemplateArgs[Arg];
2079 Id.setTemplateId(TemplateId);
2083 // Bundle the template arguments together.
2084 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2086 // Constructor and destructor names.
2088 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2090 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2091 /*IsCtorOrDtorName=*/true);
2092 if (Type.isInvalid())
2095 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2096 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2098 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2103 /// \brief Parse an operator-function-id or conversion-function-id as part
2104 /// of a C++ unqualified-id.
2106 /// This routine is responsible only for parsing the operator-function-id or
2107 /// conversion-function-id; it does not handle template arguments in any way.
2110 /// operator-function-id: [C++ 13.5]
2111 /// 'operator' operator
2113 /// operator: one of
2114 /// new delete new[] delete[]
2115 /// + - * / % ^ & | ~
2116 /// ! = < > += -= *= /= %=
2117 /// ^= &= |= << >> >>= <<= == !=
2118 /// <= >= && || ++ -- , ->* ->
2121 /// conversion-function-id: [C++ 12.3.2]
2122 /// operator conversion-type-id
2124 /// conversion-type-id:
2125 /// type-specifier-seq conversion-declarator[opt]
2127 /// conversion-declarator:
2128 /// ptr-operator conversion-declarator[opt]
2131 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2132 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2134 /// \param EnteringContext whether we are entering the scope of the
2135 /// nested-name-specifier.
2137 /// \param ObjectType if this unqualified-id occurs within a member access
2138 /// expression, the type of the base object whose member is being accessed.
2140 /// \param Result on a successful parse, contains the parsed unqualified-id.
2142 /// \returns true if parsing fails, false otherwise.
2143 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2144 ParsedType ObjectType,
2145 UnqualifiedId &Result) {
2146 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2148 // Consume the 'operator' keyword.
2149 SourceLocation KeywordLoc = ConsumeToken();
2151 // Determine what kind of operator name we have.
2152 unsigned SymbolIdx = 0;
2153 SourceLocation SymbolLocations[3];
2154 OverloadedOperatorKind Op = OO_None;
2155 switch (Tok.getKind()) {
2157 case tok::kw_delete: {
2158 bool isNew = Tok.getKind() == tok::kw_new;
2159 // Consume the 'new' or 'delete'.
2160 SymbolLocations[SymbolIdx++] = ConsumeToken();
2161 // Check for array new/delete.
2162 if (Tok.is(tok::l_square) &&
2163 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2164 // Consume the '[' and ']'.
2165 BalancedDelimiterTracker T(*this, tok::l_square);
2168 if (T.getCloseLocation().isInvalid())
2171 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2172 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2173 Op = isNew? OO_Array_New : OO_Array_Delete;
2175 Op = isNew? OO_New : OO_Delete;
2180 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2182 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2185 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2186 #include "clang/Basic/OperatorKinds.def"
2188 case tok::l_paren: {
2189 // Consume the '(' and ')'.
2190 BalancedDelimiterTracker T(*this, tok::l_paren);
2193 if (T.getCloseLocation().isInvalid())
2196 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2197 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2202 case tok::l_square: {
2203 // Consume the '[' and ']'.
2204 BalancedDelimiterTracker T(*this, tok::l_square);
2207 if (T.getCloseLocation().isInvalid())
2210 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2211 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2216 case tok::code_completion: {
2217 // Code completion for the operator name.
2218 Actions.CodeCompleteOperatorName(getCurScope());
2220 // Don't try to parse any further.
2228 if (Op != OO_None) {
2229 // We have parsed an operator-function-id.
2230 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2234 // Parse a literal-operator-id.
2236 // literal-operator-id: C++11 [over.literal]
2237 // operator string-literal identifier
2238 // operator user-defined-string-literal
2240 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2241 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2243 SourceLocation DiagLoc;
2244 unsigned DiagId = 0;
2246 // We're past translation phase 6, so perform string literal concatenation
2247 // before checking for "".
2248 SmallVector<Token, 4> Toks;
2249 SmallVector<SourceLocation, 4> TokLocs;
2250 while (isTokenStringLiteral()) {
2251 if (!Tok.is(tok::string_literal) && !DiagId) {
2252 // C++11 [over.literal]p1:
2253 // The string-literal or user-defined-string-literal in a
2254 // literal-operator-id shall have no encoding-prefix [...].
2255 DiagLoc = Tok.getLocation();
2256 DiagId = diag::err_literal_operator_string_prefix;
2258 Toks.push_back(Tok);
2259 TokLocs.push_back(ConsumeStringToken());
2262 StringLiteralParser Literal(Toks, PP);
2263 if (Literal.hadError)
2266 // Grab the literal operator's suffix, which will be either the next token
2267 // or a ud-suffix from the string literal.
2268 IdentifierInfo *II = nullptr;
2269 SourceLocation SuffixLoc;
2270 if (!Literal.getUDSuffix().empty()) {
2271 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2273 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2274 Literal.getUDSuffixOffset(),
2275 PP.getSourceManager(), getLangOpts());
2276 } else if (Tok.is(tok::identifier)) {
2277 II = Tok.getIdentifierInfo();
2278 SuffixLoc = ConsumeToken();
2279 TokLocs.push_back(SuffixLoc);
2281 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2285 // The string literal must be empty.
2286 if (!Literal.GetString().empty() || Literal.Pascal) {
2287 // C++11 [over.literal]p1:
2288 // The string-literal or user-defined-string-literal in a
2289 // literal-operator-id shall [...] contain no characters
2290 // other than the implicit terminating '\0'.
2291 DiagLoc = TokLocs.front();
2292 DiagId = diag::err_literal_operator_string_not_empty;
2296 // This isn't a valid literal-operator-id, but we think we know
2297 // what the user meant. Tell them what they should have written.
2298 SmallString<32> Str;
2300 Str += II->getName();
2301 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2302 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2305 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2307 return Actions.checkLiteralOperatorId(SS, Result);
2310 // Parse a conversion-function-id.
2312 // conversion-function-id: [C++ 12.3.2]
2313 // operator conversion-type-id
2315 // conversion-type-id:
2316 // type-specifier-seq conversion-declarator[opt]
2318 // conversion-declarator:
2319 // ptr-operator conversion-declarator[opt]
2321 // Parse the type-specifier-seq.
2322 DeclSpec DS(AttrFactory);
2323 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2326 // Parse the conversion-declarator, which is merely a sequence of
2328 Declarator D(DS, Declarator::ConversionIdContext);
2329 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2331 // Finish up the type.
2332 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2336 // Note that this is a conversion-function-id.
2337 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2338 D.getSourceRange().getEnd());
2342 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2343 /// name of an entity.
2346 /// unqualified-id: [C++ expr.prim.general]
2348 /// operator-function-id
2349 /// conversion-function-id
2350 /// [C++0x] literal-operator-id [TODO]
2356 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2357 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2359 /// \param EnteringContext whether we are entering the scope of the
2360 /// nested-name-specifier.
2362 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2364 /// \param AllowConstructorName whether we allow parsing a constructor name.
2366 /// \param ObjectType if this unqualified-id occurs within a member access
2367 /// expression, the type of the base object whose member is being accessed.
2369 /// \param Result on a successful parse, contains the parsed unqualified-id.
2371 /// \returns true if parsing fails, false otherwise.
2372 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2373 bool AllowDestructorName,
2374 bool AllowConstructorName,
2375 ParsedType ObjectType,
2376 SourceLocation& TemplateKWLoc,
2377 UnqualifiedId &Result) {
2379 // Handle 'A::template B'. This is for template-ids which have not
2380 // already been annotated by ParseOptionalCXXScopeSpecifier().
2381 bool TemplateSpecified = false;
2382 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2383 (ObjectType || SS.isSet())) {
2384 TemplateSpecified = true;
2385 TemplateKWLoc = ConsumeToken();
2390 // template-id (when it hasn't already been annotated)
2391 if (Tok.is(tok::identifier)) {
2392 // Consume the identifier.
2393 IdentifierInfo *Id = Tok.getIdentifierInfo();
2394 SourceLocation IdLoc = ConsumeToken();
2396 if (!getLangOpts().CPlusPlus) {
2397 // If we're not in C++, only identifiers matter. Record the
2398 // identifier and return.
2399 Result.setIdentifier(Id, IdLoc);
2403 if (AllowConstructorName &&
2404 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2405 // We have parsed a constructor name.
2406 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2409 /*IsCtorOrDtorName=*/true,
2410 /*NonTrivialTypeSourceInfo=*/true);
2411 Result.setConstructorName(Ty, IdLoc, IdLoc);
2413 // We have parsed an identifier.
2414 Result.setIdentifier(Id, IdLoc);
2417 // If the next token is a '<', we may have a template.
2418 if (TemplateSpecified || Tok.is(tok::less))
2419 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2420 EnteringContext, ObjectType,
2421 Result, TemplateSpecified);
2427 // template-id (already parsed and annotated)
2428 if (Tok.is(tok::annot_template_id)) {
2429 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2431 // If the template-name names the current class, then this is a constructor
2432 if (AllowConstructorName && TemplateId->Name &&
2433 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2435 // C++ [class.qual]p2 specifies that a qualified template-name
2436 // is taken as the constructor name where a constructor can be
2437 // declared. Thus, the template arguments are extraneous, so
2438 // complain about them and remove them entirely.
2439 Diag(TemplateId->TemplateNameLoc,
2440 diag::err_out_of_line_constructor_template_id)
2442 << FixItHint::CreateRemoval(
2443 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2444 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2445 TemplateId->TemplateNameLoc,
2449 /*IsCtorOrDtorName=*/true,
2450 /*NontrivialTypeSourceInfo=*/true);
2451 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2452 TemplateId->RAngleLoc);
2457 Result.setConstructorTemplateId(TemplateId);
2462 // We have already parsed a template-id; consume the annotation token as
2463 // our unqualified-id.
2464 Result.setTemplateId(TemplateId);
2465 TemplateKWLoc = TemplateId->TemplateKWLoc;
2471 // operator-function-id
2472 // conversion-function-id
2473 if (Tok.is(tok::kw_operator)) {
2474 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2477 // If we have an operator-function-id or a literal-operator-id and the next
2478 // token is a '<', we may have a
2481 // operator-function-id < template-argument-list[opt] >
2482 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2483 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2484 (TemplateSpecified || Tok.is(tok::less)))
2485 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2486 nullptr, SourceLocation(),
2487 EnteringContext, ObjectType,
2488 Result, TemplateSpecified);
2493 if (getLangOpts().CPlusPlus &&
2494 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2495 // C++ [expr.unary.op]p10:
2496 // There is an ambiguity in the unary-expression ~X(), where X is a
2497 // class-name. The ambiguity is resolved in favor of treating ~ as a
2498 // unary complement rather than treating ~X as referring to a destructor.
2501 SourceLocation TildeLoc = ConsumeToken();
2503 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2504 DeclSpec DS(AttrFactory);
2505 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2506 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2507 Result.setDestructorName(TildeLoc, Type, EndLoc);
2513 // Parse the class-name.
2514 if (Tok.isNot(tok::identifier)) {
2515 Diag(Tok, diag::err_destructor_tilde_identifier);
2519 // If the user wrote ~T::T, correct it to T::~T.
2520 DeclaratorScopeObj DeclScopeObj(*this, SS);
2521 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2522 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2523 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2524 // it will confuse this recovery logic.
2525 ColonProtectionRAIIObject ColonRAII(*this, false);
2528 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2531 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2533 if (SS.isNotEmpty())
2534 ObjectType = ParsedType();
2535 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2537 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2541 // Recover as if the tilde had been written before the identifier.
2542 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2543 << FixItHint::CreateRemoval(TildeLoc)
2544 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2546 // Temporarily enter the scope for the rest of this function.
2547 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2548 DeclScopeObj.EnterDeclaratorScope();
2551 // Parse the class-name (or template-name in a simple-template-id).
2552 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2553 SourceLocation ClassNameLoc = ConsumeToken();
2555 if (TemplateSpecified || Tok.is(tok::less)) {
2556 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
2557 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2558 ClassName, ClassNameLoc,
2559 EnteringContext, ObjectType,
2560 Result, TemplateSpecified);
2563 // Note that this is a destructor name.
2564 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2565 ClassNameLoc, getCurScope(),
2571 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2575 Diag(Tok, diag::err_expected_unqualified_id)
2576 << getLangOpts().CPlusPlus;
2580 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2581 /// memory in a typesafe manner and call constructors.
2583 /// This method is called to parse the new expression after the optional :: has
2584 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2585 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2588 /// '::'[opt] 'new' new-placement[opt] new-type-id
2589 /// new-initializer[opt]
2590 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2591 /// new-initializer[opt]
2594 /// '(' expression-list ')'
2597 /// type-specifier-seq new-declarator[opt]
2598 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2601 /// ptr-operator new-declarator[opt]
2602 /// direct-new-declarator
2604 /// new-initializer:
2605 /// '(' expression-list[opt] ')'
2606 /// [C++0x] braced-init-list
2609 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2610 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2611 ConsumeToken(); // Consume 'new'
2613 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2614 // second form of new-expression. It can't be a new-type-id.
2616 ExprVector PlacementArgs;
2617 SourceLocation PlacementLParen, PlacementRParen;
2619 SourceRange TypeIdParens;
2620 DeclSpec DS(AttrFactory);
2621 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2622 if (Tok.is(tok::l_paren)) {
2623 // If it turns out to be a placement, we change the type location.
2624 BalancedDelimiterTracker T(*this, tok::l_paren);
2626 PlacementLParen = T.getOpenLocation();
2627 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2628 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2633 PlacementRParen = T.getCloseLocation();
2634 if (PlacementRParen.isInvalid()) {
2635 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2639 if (PlacementArgs.empty()) {
2640 // Reset the placement locations. There was no placement.
2641 TypeIdParens = T.getRange();
2642 PlacementLParen = PlacementRParen = SourceLocation();
2644 // We still need the type.
2645 if (Tok.is(tok::l_paren)) {
2646 BalancedDelimiterTracker T(*this, tok::l_paren);
2648 MaybeParseGNUAttributes(DeclaratorInfo);
2649 ParseSpecifierQualifierList(DS);
2650 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2651 ParseDeclarator(DeclaratorInfo);
2653 TypeIdParens = T.getRange();
2655 MaybeParseGNUAttributes(DeclaratorInfo);
2656 if (ParseCXXTypeSpecifierSeq(DS))
2657 DeclaratorInfo.setInvalidType(true);
2659 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2660 ParseDeclaratorInternal(DeclaratorInfo,
2661 &Parser::ParseDirectNewDeclarator);
2666 // A new-type-id is a simplified type-id, where essentially the
2667 // direct-declarator is replaced by a direct-new-declarator.
2668 MaybeParseGNUAttributes(DeclaratorInfo);
2669 if (ParseCXXTypeSpecifierSeq(DS))
2670 DeclaratorInfo.setInvalidType(true);
2672 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2673 ParseDeclaratorInternal(DeclaratorInfo,
2674 &Parser::ParseDirectNewDeclarator);
2677 if (DeclaratorInfo.isInvalidType()) {
2678 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2682 ExprResult Initializer;
2684 if (Tok.is(tok::l_paren)) {
2685 SourceLocation ConstructorLParen, ConstructorRParen;
2686 ExprVector ConstructorArgs;
2687 BalancedDelimiterTracker T(*this, tok::l_paren);
2689 ConstructorLParen = T.getOpenLocation();
2690 if (Tok.isNot(tok::r_paren)) {
2691 CommaLocsTy CommaLocs;
2692 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2693 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2694 DeclaratorInfo).get();
2695 Actions.CodeCompleteConstructor(getCurScope(),
2696 TypeRep.get()->getCanonicalTypeInternal(),
2697 DeclaratorInfo.getLocEnd(),
2700 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2705 ConstructorRParen = T.getCloseLocation();
2706 if (ConstructorRParen.isInvalid()) {
2707 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2710 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2713 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2714 Diag(Tok.getLocation(),
2715 diag::warn_cxx98_compat_generalized_initializer_lists);
2716 Initializer = ParseBraceInitializer();
2718 if (Initializer.isInvalid())
2721 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2722 PlacementArgs, PlacementRParen,
2723 TypeIdParens, DeclaratorInfo, Initializer.get());
2726 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2727 /// passed to ParseDeclaratorInternal.
2729 /// direct-new-declarator:
2730 /// '[' expression ']'
2731 /// direct-new-declarator '[' constant-expression ']'
2733 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2734 // Parse the array dimensions.
2736 while (Tok.is(tok::l_square)) {
2737 // An array-size expression can't start with a lambda.
2738 if (CheckProhibitedCXX11Attribute())
2741 BalancedDelimiterTracker T(*this, tok::l_square);
2744 ExprResult Size(first ? ParseExpression()
2745 : ParseConstantExpression());
2746 if (Size.isInvalid()) {
2748 SkipUntil(tok::r_square, StopAtSemi);
2755 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2756 ParsedAttributes Attrs(AttrFactory);
2757 MaybeParseCXX11Attributes(Attrs);
2759 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2760 /*static=*/false, /*star=*/false,
2762 T.getOpenLocation(),
2763 T.getCloseLocation()),
2764 Attrs, T.getCloseLocation());
2766 if (T.getCloseLocation().isInvalid())
2771 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2772 /// This ambiguity appears in the syntax of the C++ new operator.
2775 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2776 /// new-initializer[opt]
2779 /// '(' expression-list ')'
2781 bool Parser::ParseExpressionListOrTypeId(
2782 SmallVectorImpl<Expr*> &PlacementArgs,
2784 // The '(' was already consumed.
2785 if (isTypeIdInParens()) {
2786 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2787 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2789 return D.isInvalidType();
2792 // It's not a type, it has to be an expression list.
2793 // Discard the comma locations - ActOnCXXNew has enough parameters.
2794 CommaLocsTy CommaLocs;
2795 return ParseExpressionList(PlacementArgs, CommaLocs);
2798 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2799 /// to free memory allocated by new.
2801 /// This method is called to parse the 'delete' expression after the optional
2802 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2803 /// and "Start" is its location. Otherwise, "Start" is the location of the
2806 /// delete-expression:
2807 /// '::'[opt] 'delete' cast-expression
2808 /// '::'[opt] 'delete' '[' ']' cast-expression
2810 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2811 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2812 ConsumeToken(); // Consume 'delete'
2815 bool ArrayDelete = false;
2816 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2817 // C++11 [expr.delete]p1:
2818 // Whenever the delete keyword is followed by empty square brackets, it
2819 // shall be interpreted as [array delete].
2820 // [Footnote: A lambda expression with a lambda-introducer that consists
2821 // of empty square brackets can follow the delete keyword if
2822 // the lambda expression is enclosed in parentheses.]
2823 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2824 // lambda-introducer.
2826 BalancedDelimiterTracker T(*this, tok::l_square);
2830 if (T.getCloseLocation().isInvalid())
2834 ExprResult Operand(ParseCastExpression(false));
2835 if (Operand.isInvalid())
2838 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2841 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2843 default: llvm_unreachable("Not a known type trait");
2844 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2845 case tok::kw_ ## Spelling: return UTT_ ## Name;
2846 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2847 case tok::kw_ ## Spelling: return BTT_ ## Name;
2848 #include "clang/Basic/TokenKinds.def"
2849 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2850 case tok::kw_ ## Spelling: return TT_ ## Name;
2851 #include "clang/Basic/TokenKinds.def"
2855 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2857 default: llvm_unreachable("Not a known binary type trait");
2858 case tok::kw___array_rank: return ATT_ArrayRank;
2859 case tok::kw___array_extent: return ATT_ArrayExtent;
2863 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2865 default: llvm_unreachable("Not a known unary expression trait.");
2866 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2867 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2871 static unsigned TypeTraitArity(tok::TokenKind kind) {
2873 default: llvm_unreachable("Not a known type trait");
2874 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2875 #include "clang/Basic/TokenKinds.def"
2879 /// \brief Parse the built-in type-trait pseudo-functions that allow
2880 /// implementation of the TR1/C++11 type traits templates.
2882 /// primary-expression:
2883 /// unary-type-trait '(' type-id ')'
2884 /// binary-type-trait '(' type-id ',' type-id ')'
2885 /// type-trait '(' type-id-seq ')'
2888 /// type-id ...[opt] type-id-seq[opt]
2890 ExprResult Parser::ParseTypeTrait() {
2891 tok::TokenKind Kind = Tok.getKind();
2892 unsigned Arity = TypeTraitArity(Kind);
2894 SourceLocation Loc = ConsumeToken();
2896 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2897 if (Parens.expectAndConsume())
2900 SmallVector<ParsedType, 2> Args;
2902 // Parse the next type.
2903 TypeResult Ty = ParseTypeName();
2904 if (Ty.isInvalid()) {
2909 // Parse the ellipsis, if present.
2910 if (Tok.is(tok::ellipsis)) {
2911 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2912 if (Ty.isInvalid()) {
2918 // Add this type to the list of arguments.
2919 Args.push_back(Ty.get());
2920 } while (TryConsumeToken(tok::comma));
2922 if (Parens.consumeClose())
2925 SourceLocation EndLoc = Parens.getCloseLocation();
2927 if (Arity && Args.size() != Arity) {
2928 Diag(EndLoc, diag::err_type_trait_arity)
2929 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2933 if (!Arity && Args.empty()) {
2934 Diag(EndLoc, diag::err_type_trait_arity)
2935 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2939 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
2942 /// ParseArrayTypeTrait - Parse the built-in array type-trait
2943 /// pseudo-functions.
2945 /// primary-expression:
2946 /// [Embarcadero] '__array_rank' '(' type-id ')'
2947 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2949 ExprResult Parser::ParseArrayTypeTrait() {
2950 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2951 SourceLocation Loc = ConsumeToken();
2953 BalancedDelimiterTracker T(*this, tok::l_paren);
2954 if (T.expectAndConsume())
2957 TypeResult Ty = ParseTypeName();
2958 if (Ty.isInvalid()) {
2959 SkipUntil(tok::comma, StopAtSemi);
2960 SkipUntil(tok::r_paren, StopAtSemi);
2965 case ATT_ArrayRank: {
2967 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
2968 T.getCloseLocation());
2970 case ATT_ArrayExtent: {
2971 if (ExpectAndConsume(tok::comma)) {
2972 SkipUntil(tok::r_paren, StopAtSemi);
2976 ExprResult DimExpr = ParseExpression();
2979 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2980 T.getCloseLocation());
2983 llvm_unreachable("Invalid ArrayTypeTrait!");
2986 /// ParseExpressionTrait - Parse built-in expression-trait
2987 /// pseudo-functions like __is_lvalue_expr( xxx ).
2989 /// primary-expression:
2990 /// [Embarcadero] expression-trait '(' expression ')'
2992 ExprResult Parser::ParseExpressionTrait() {
2993 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2994 SourceLocation Loc = ConsumeToken();
2996 BalancedDelimiterTracker T(*this, tok::l_paren);
2997 if (T.expectAndConsume())
3000 ExprResult Expr = ParseExpression();
3004 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3005 T.getCloseLocation());
3009 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3010 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3011 /// based on the context past the parens.
3013 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3015 BalancedDelimiterTracker &Tracker,
3016 ColonProtectionRAIIObject &ColonProt) {
3017 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3018 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3019 assert(isTypeIdInParens() && "Not a type-id!");
3021 ExprResult Result(true);
3022 CastTy = ParsedType();
3024 // We need to disambiguate a very ugly part of the C++ syntax:
3026 // (T())x; - type-id
3027 // (T())*x; - type-id
3028 // (T())/x; - expression
3029 // (T()); - expression
3031 // The bad news is that we cannot use the specialized tentative parser, since
3032 // it can only verify that the thing inside the parens can be parsed as
3033 // type-id, it is not useful for determining the context past the parens.
3035 // The good news is that the parser can disambiguate this part without
3036 // making any unnecessary Action calls.
3038 // It uses a scheme similar to parsing inline methods. The parenthesized
3039 // tokens are cached, the context that follows is determined (possibly by
3040 // parsing a cast-expression), and then we re-introduce the cached tokens
3041 // into the token stream and parse them appropriately.
3043 ParenParseOption ParseAs;
3046 // Store the tokens of the parentheses. We will parse them after we determine
3047 // the context that follows them.
3048 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3049 // We didn't find the ')' we expected.
3050 Tracker.consumeClose();
3054 if (Tok.is(tok::l_brace)) {
3055 ParseAs = CompoundLiteral;
3058 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3061 // Try parsing the cast-expression that may follow.
3062 // If it is not a cast-expression, NotCastExpr will be true and no token
3063 // will be consumed.
3064 ColonProt.restore();
3065 Result = ParseCastExpression(false/*isUnaryExpression*/,
3066 false/*isAddressofOperand*/,
3068 // type-id has priority.
3072 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3074 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3077 // The current token should go after the cached tokens.
3078 Toks.push_back(Tok);
3079 // Re-enter the stored parenthesized tokens into the token stream, so we may
3081 PP.EnterTokenStream(Toks.data(), Toks.size(),
3082 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
3083 // Drop the current token and bring the first cached one. It's the same token
3084 // as when we entered this function.
3087 if (ParseAs >= CompoundLiteral) {
3088 // Parse the type declarator.
3089 DeclSpec DS(AttrFactory);
3090 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
3092 ColonProtectionRAIIObject InnerColonProtection(*this);
3093 ParseSpecifierQualifierList(DS);
3094 ParseDeclarator(DeclaratorInfo);
3098 Tracker.consumeClose();
3099 ColonProt.restore();
3101 if (ParseAs == CompoundLiteral) {
3102 ExprType = CompoundLiteral;
3103 if (DeclaratorInfo.isInvalidType())
3106 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3107 return ParseCompoundLiteralExpression(Ty.get(),
3108 Tracker.getOpenLocation(),
3109 Tracker.getCloseLocation());
3112 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3113 assert(ParseAs == CastExpr);
3115 if (DeclaratorInfo.isInvalidType())
3118 // Result is what ParseCastExpression returned earlier.
3119 if (!Result.isInvalid())
3120 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3121 DeclaratorInfo, CastTy,
3122 Tracker.getCloseLocation(), Result.get());
3126 // Not a compound literal, and not followed by a cast-expression.
3127 assert(ParseAs == SimpleExpr);
3129 ExprType = SimpleExpr;
3130 Result = ParseExpression();
3131 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3132 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3133 Tok.getLocation(), Result.get());
3136 if (Result.isInvalid()) {
3137 SkipUntil(tok::r_paren, StopAtSemi);
3141 Tracker.consumeClose();