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 = nullptr;
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=*/nullptr, 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, nullptr, /*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();
743 if (Next.is(tok::eof)) // Nothing else to lookup here...
746 const Token After = GetLookAheadToken(2);
747 // If lookahead indicates this is a lambda...
748 if (Next.is(tok::r_square) || // []
749 Next.is(tok::equal) || // [=
750 (Next.is(tok::amp) && // [&] or [&,
751 (After.is(tok::r_square) ||
752 After.is(tok::comma))) ||
753 (Next.is(tok::identifier) && // [identifier]
754 After.is(tok::r_square))) {
755 return ParseLambdaExpression();
758 // If lookahead indicates an ObjC message send...
759 // [identifier identifier
760 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
764 // Here, we're stuck: lambda introducers and Objective-C message sends are
765 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
766 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
767 // writing two routines to parse a lambda introducer, just try to parse
768 // a lambda introducer first, and fall back if that fails.
769 // (TryParseLambdaIntroducer never produces any diagnostic output.)
770 LambdaIntroducer Intro;
771 if (TryParseLambdaIntroducer(Intro))
774 return ParseLambdaExpressionAfterIntroducer(Intro);
777 /// \brief Parse a lambda introducer.
778 /// \param Intro A LambdaIntroducer filled in with information about the
779 /// contents of the lambda-introducer.
780 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
781 /// message send and a lambda expression. In this mode, we will
782 /// sometimes skip the initializers for init-captures and not fully
783 /// populate \p Intro. This flag will be set to \c true if we do so.
784 /// \return A DiagnosticID if it hit something unexpected. The location for
785 /// for the diagnostic is that of the current token.
786 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
787 bool *SkippedInits) {
788 typedef Optional<unsigned> DiagResult;
790 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
791 BalancedDelimiterTracker T(*this, tok::l_square);
794 Intro.Range.setBegin(T.getOpenLocation());
798 // Parse capture-default.
799 if (Tok.is(tok::amp) &&
800 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
801 Intro.Default = LCD_ByRef;
802 Intro.DefaultLoc = ConsumeToken();
804 } else if (Tok.is(tok::equal)) {
805 Intro.Default = LCD_ByCopy;
806 Intro.DefaultLoc = ConsumeToken();
810 while (Tok.isNot(tok::r_square)) {
812 if (Tok.isNot(tok::comma)) {
813 // Provide a completion for a lambda introducer here. Except
814 // in Objective-C, where this is Almost Surely meant to be a message
815 // send. In that case, fail here and let the ObjC message
816 // expression parser perform the completion.
817 if (Tok.is(tok::code_completion) &&
818 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
819 !Intro.Captures.empty())) {
820 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
821 /*AfterAmpersand=*/false);
826 return DiagResult(diag::err_expected_comma_or_rsquare);
831 if (Tok.is(tok::code_completion)) {
832 // If we're in Objective-C++ and we have a bare '[', then this is more
833 // likely to be a message receiver.
834 if (getLangOpts().ObjC1 && first)
835 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
837 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
838 /*AfterAmpersand=*/false);
846 LambdaCaptureKind Kind = LCK_ByCopy;
847 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
849 IdentifierInfo *Id = nullptr;
850 SourceLocation EllipsisLoc;
853 if (Tok.is(tok::star)) {
854 Loc = ConsumeToken();
855 if (Tok.is(tok::kw_this)) {
859 return DiagResult(diag::err_expected_star_this_capture);
861 } else if (Tok.is(tok::kw_this)) {
863 Loc = ConsumeToken();
865 if (Tok.is(tok::amp)) {
869 if (Tok.is(tok::code_completion)) {
870 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
871 /*AfterAmpersand=*/true);
877 if (Tok.is(tok::identifier)) {
878 Id = Tok.getIdentifierInfo();
879 Loc = ConsumeToken();
880 } else if (Tok.is(tok::kw_this)) {
881 // FIXME: If we want to suggest a fixit here, will need to return more
882 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
883 // Clear()ed to prevent emission in case of tentative parsing?
884 return DiagResult(diag::err_this_captured_by_reference);
886 return DiagResult(diag::err_expected_capture);
889 if (Tok.is(tok::l_paren)) {
890 BalancedDelimiterTracker Parens(*this, tok::l_paren);
891 Parens.consumeOpen();
893 InitKind = LambdaCaptureInitKind::DirectInit;
899 *SkippedInits = true;
900 } else if (ParseExpressionList(Exprs, Commas)) {
904 Parens.consumeClose();
905 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
906 Parens.getCloseLocation(),
909 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
910 // Each lambda init-capture forms its own full expression, which clears
911 // Actions.MaybeODRUseExprs. So create an expression evaluation context
912 // to save the necessary state, and restore it later.
913 EnterExpressionEvaluationContext EC(Actions,
914 Sema::PotentiallyEvaluated);
916 if (TryConsumeToken(tok::equal))
917 InitKind = LambdaCaptureInitKind::CopyInit;
919 InitKind = LambdaCaptureInitKind::ListInit;
922 Init = ParseInitializer();
923 } else if (Tok.is(tok::l_brace)) {
924 BalancedDelimiterTracker Braces(*this, tok::l_brace);
925 Braces.consumeOpen();
927 *SkippedInits = true;
929 // We're disambiguating this:
933 // We need to find the end of the following expression in order to
934 // determine whether this is an Obj-C message send's receiver, a
935 // C99 designator, or a lambda init-capture.
937 // Parse the expression to find where it ends, and annotate it back
938 // onto the tokens. We would have parsed this expression the same way
939 // in either case: both the RHS of an init-capture and the RHS of an
940 // assignment expression are parsed as an initializer-clause, and in
941 // neither case can anything be added to the scope between the '[' and
944 // FIXME: This is horrible. Adding a mechanism to skip an expression
945 // would be much cleaner.
946 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
947 // that instead. (And if we see a ':' with no matching '?', we can
948 // classify this as an Obj-C message send.)
949 SourceLocation StartLoc = Tok.getLocation();
950 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
951 Init = ParseInitializer();
953 if (Tok.getLocation() != StartLoc) {
954 // Back out the lexing of the token after the initializer.
955 PP.RevertCachedTokens(1);
957 // Replace the consumed tokens with an appropriate annotation.
958 Tok.setLocation(StartLoc);
959 Tok.setKind(tok::annot_primary_expr);
960 setExprAnnotation(Tok, Init);
961 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
962 PP.AnnotateCachedTokens(Tok);
964 // Consume the annotated initializer.
969 TryConsumeToken(tok::ellipsis, EllipsisLoc);
971 // If this is an init capture, process the initialization expression
972 // right away. For lambda init-captures such as the following:
974 // auto L = [i = x+1](int a) {
976 // &k = x](char b) { };
978 // keep in mind that each lambda init-capture has to have:
979 // - its initialization expression executed in the context
980 // of the enclosing/parent decl-context.
981 // - but the variable itself has to be 'injected' into the
982 // decl-context of its lambda's call-operator (which has
983 // not yet been created).
984 // Each init-expression is a full-expression that has to get
985 // Sema-analyzed (for capturing etc.) before its lambda's
986 // call-operator's decl-context, scope & scopeinfo are pushed on their
987 // respective stacks. Thus if any variable is odr-used in the init-capture
988 // it will correctly get captured in the enclosing lambda, if one exists.
989 // The init-variables above are created later once the lambdascope and
990 // call-operators decl-context is pushed onto its respective stack.
992 // Since the lambda init-capture's initializer expression occurs in the
993 // context of the enclosing function or lambda, therefore we can not wait
994 // till a lambda scope has been pushed on before deciding whether the
995 // variable needs to be captured. We also need to process all
996 // lvalue-to-rvalue conversions and discarded-value conversions,
997 // so that we can avoid capturing certain constant variables.
1000 // const int x = 10;
1001 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
1002 // return [y = x](int i) { <-- don't capture by enclosing lambda
1006 // If x was not const, the second use would require 'L' to capture, and
1007 // that would be an error.
1009 ParsedType InitCaptureType;
1010 if (Init.isUsable()) {
1011 // Get the pointer and store it in an lvalue, so we can use it as an
1013 Expr *InitExpr = Init.get();
1014 // This performs any lvalue-to-rvalue conversions if necessary, which
1015 // can affect what gets captured in the containing decl-context.
1016 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
1017 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
1020 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
1025 Intro.Range.setEnd(T.getCloseLocation());
1026 return DiagResult();
1029 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
1031 /// Returns true if it hit something unexpected.
1032 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1033 TentativeParsingAction PA(*this);
1035 bool SkippedInits = false;
1036 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
1044 // Parse it again, but this time parse the init-captures too.
1046 Intro = LambdaIntroducer();
1047 DiagID = ParseLambdaIntroducer(Intro);
1048 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1056 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1058 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1059 LambdaIntroducer &Intro) {
1060 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1061 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1063 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1064 "lambda expression parsing");
1068 // FIXME: Call into Actions to add any init-capture declarations to the
1069 // scope while parsing the lambda-declarator and compound-statement.
1071 // Parse lambda-declarator[opt].
1072 DeclSpec DS(AttrFactory);
1073 Declarator D(DS, Declarator::LambdaExprContext);
1074 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1075 Actions.PushLambdaScope();
1077 TypeResult TrailingReturnType;
1078 if (Tok.is(tok::l_paren)) {
1079 ParseScope PrototypeScope(this,
1080 Scope::FunctionPrototypeScope |
1081 Scope::FunctionDeclarationScope |
1084 SourceLocation DeclEndLoc;
1085 BalancedDelimiterTracker T(*this, tok::l_paren);
1087 SourceLocation LParenLoc = T.getOpenLocation();
1089 // Parse parameter-declaration-clause.
1090 ParsedAttributes Attr(AttrFactory);
1091 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1092 SourceLocation EllipsisLoc;
1094 if (Tok.isNot(tok::r_paren)) {
1095 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1096 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1097 // For a generic lambda, each 'auto' within the parameter declaration
1098 // clause creates a template type parameter, so increment the depth.
1099 if (Actions.getCurGenericLambda())
1100 ++CurTemplateDepthTracker;
1103 SourceLocation RParenLoc = T.getCloseLocation();
1104 DeclEndLoc = RParenLoc;
1106 // GNU-style attributes must be parsed before the mutable specifier to be
1107 // compatible with GCC.
1108 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1110 // MSVC-style attributes must be parsed before the mutable specifier to be
1111 // compatible with MSVC.
1112 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1114 // Parse 'mutable'[opt].
1115 SourceLocation MutableLoc;
1116 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
1117 DeclEndLoc = MutableLoc;
1119 // Parse exception-specification[opt].
1120 ExceptionSpecificationType ESpecType = EST_None;
1121 SourceRange ESpecRange;
1122 SmallVector<ParsedType, 2> DynamicExceptions;
1123 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1124 ExprResult NoexceptExpr;
1125 CachedTokens *ExceptionSpecTokens;
1126 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1129 DynamicExceptionRanges,
1131 ExceptionSpecTokens);
1133 if (ESpecType != EST_None)
1134 DeclEndLoc = ESpecRange.getEnd();
1136 // Parse attribute-specifier[opt].
1137 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1139 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1141 // Parse trailing-return-type[opt].
1142 if (Tok.is(tok::arrow)) {
1143 FunLocalRangeEnd = Tok.getLocation();
1145 TrailingReturnType = ParseTrailingReturnType(Range);
1146 if (Range.getEnd().isValid())
1147 DeclEndLoc = Range.getEnd();
1150 PrototypeScope.Exit();
1152 SourceLocation NoLoc;
1153 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1154 /*isAmbiguous=*/false,
1156 ParamInfo.data(), ParamInfo.size(),
1157 EllipsisLoc, RParenLoc,
1158 DS.getTypeQualifiers(),
1159 /*RefQualifierIsLValueRef=*/true,
1160 /*RefQualifierLoc=*/NoLoc,
1161 /*ConstQualifierLoc=*/NoLoc,
1162 /*VolatileQualifierLoc=*/NoLoc,
1163 /*RestrictQualifierLoc=*/NoLoc,
1165 ESpecType, ESpecRange,
1166 DynamicExceptions.data(),
1167 DynamicExceptionRanges.data(),
1168 DynamicExceptions.size(),
1169 NoexceptExpr.isUsable() ?
1170 NoexceptExpr.get() : nullptr,
1171 /*ExceptionSpecTokens*/nullptr,
1172 LParenLoc, FunLocalRangeEnd, D,
1173 TrailingReturnType),
1175 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute) ||
1176 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1177 // It's common to forget that one needs '()' before 'mutable', an attribute
1178 // specifier, or the result type. Deal with this.
1179 unsigned TokKind = 0;
1180 switch (Tok.getKind()) {
1181 case tok::kw_mutable: TokKind = 0; break;
1182 case tok::arrow: TokKind = 1; break;
1183 case tok::kw___attribute:
1184 case tok::l_square: TokKind = 2; break;
1185 default: llvm_unreachable("Unknown token kind");
1188 Diag(Tok, diag::err_lambda_missing_parens)
1190 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1191 SourceLocation DeclLoc = Tok.getLocation();
1192 SourceLocation DeclEndLoc = DeclLoc;
1194 // GNU-style attributes must be parsed before the mutable specifier to be
1195 // compatible with GCC.
1196 ParsedAttributes Attr(AttrFactory);
1197 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1199 // Parse 'mutable', if it's there.
1200 SourceLocation MutableLoc;
1201 if (Tok.is(tok::kw_mutable)) {
1202 MutableLoc = ConsumeToken();
1203 DeclEndLoc = MutableLoc;
1206 // Parse attribute-specifier[opt].
1207 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1209 // Parse the return type, if there is one.
1210 if (Tok.is(tok::arrow)) {
1212 TrailingReturnType = ParseTrailingReturnType(Range);
1213 if (Range.getEnd().isValid())
1214 DeclEndLoc = Range.getEnd();
1217 SourceLocation NoLoc;
1218 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1219 /*isAmbiguous=*/false,
1220 /*LParenLoc=*/NoLoc,
1223 /*EllipsisLoc=*/NoLoc,
1224 /*RParenLoc=*/NoLoc,
1226 /*RefQualifierIsLValueRef=*/true,
1227 /*RefQualifierLoc=*/NoLoc,
1228 /*ConstQualifierLoc=*/NoLoc,
1229 /*VolatileQualifierLoc=*/NoLoc,
1230 /*RestrictQualifierLoc=*/NoLoc,
1233 /*ESpecRange=*/SourceRange(),
1234 /*Exceptions=*/nullptr,
1235 /*ExceptionRanges=*/nullptr,
1236 /*NumExceptions=*/0,
1237 /*NoexceptExpr=*/nullptr,
1238 /*ExceptionSpecTokens=*/nullptr,
1239 DeclLoc, DeclEndLoc, D,
1240 TrailingReturnType),
1245 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1247 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
1248 ParseScope BodyScope(this, ScopeFlags);
1250 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1252 // Parse compound-statement.
1253 if (!Tok.is(tok::l_brace)) {
1254 Diag(Tok, diag::err_expected_lambda_body);
1255 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1259 StmtResult Stmt(ParseCompoundStatementBody());
1262 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1263 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1265 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1269 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1272 /// postfix-expression: [C++ 5.2p1]
1273 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1274 /// 'static_cast' '<' type-name '>' '(' expression ')'
1275 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1276 /// 'const_cast' '<' type-name '>' '(' expression ')'
1278 ExprResult Parser::ParseCXXCasts() {
1279 tok::TokenKind Kind = Tok.getKind();
1280 const char *CastName = nullptr; // For error messages
1283 default: llvm_unreachable("Unknown C++ cast!");
1284 case tok::kw_const_cast: CastName = "const_cast"; break;
1285 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1286 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1287 case tok::kw_static_cast: CastName = "static_cast"; break;
1290 SourceLocation OpLoc = ConsumeToken();
1291 SourceLocation LAngleBracketLoc = Tok.getLocation();
1293 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1294 // diagnose error, suggest fix, and recover parsing.
1295 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1296 Token Next = NextToken();
1297 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1298 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1301 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1304 // Parse the common declaration-specifiers piece.
1305 DeclSpec DS(AttrFactory);
1306 ParseSpecifierQualifierList(DS);
1308 // Parse the abstract-declarator, if present.
1309 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1310 ParseDeclarator(DeclaratorInfo);
1312 SourceLocation RAngleBracketLoc = Tok.getLocation();
1314 if (ExpectAndConsume(tok::greater))
1315 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1317 SourceLocation LParenLoc, RParenLoc;
1318 BalancedDelimiterTracker T(*this, tok::l_paren);
1320 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1323 ExprResult Result = ParseExpression();
1328 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1329 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1330 LAngleBracketLoc, DeclaratorInfo,
1332 T.getOpenLocation(), Result.get(),
1333 T.getCloseLocation());
1338 /// ParseCXXTypeid - This handles the C++ typeid expression.
1340 /// postfix-expression: [C++ 5.2p1]
1341 /// 'typeid' '(' expression ')'
1342 /// 'typeid' '(' type-id ')'
1344 ExprResult Parser::ParseCXXTypeid() {
1345 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1347 SourceLocation OpLoc = ConsumeToken();
1348 SourceLocation LParenLoc, RParenLoc;
1349 BalancedDelimiterTracker T(*this, tok::l_paren);
1351 // typeid expressions are always parenthesized.
1352 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1354 LParenLoc = T.getOpenLocation();
1358 // C++0x [expr.typeid]p3:
1359 // When typeid is applied to an expression other than an lvalue of a
1360 // polymorphic class type [...] The expression is an unevaluated
1361 // operand (Clause 5).
1363 // Note that we can't tell whether the expression is an lvalue of a
1364 // polymorphic class type until after we've parsed the expression; we
1365 // speculatively assume the subexpression is unevaluated, and fix it up
1368 // We enter the unevaluated context before trying to determine whether we
1369 // have a type-id, because the tentative parse logic will try to resolve
1370 // names, and must treat them as unevaluated.
1371 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1372 Sema::ReuseLambdaContextDecl);
1374 if (isTypeIdInParens()) {
1375 TypeResult Ty = ParseTypeName();
1379 RParenLoc = T.getCloseLocation();
1380 if (Ty.isInvalid() || RParenLoc.isInvalid())
1383 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1384 Ty.get().getAsOpaquePtr(), RParenLoc);
1386 Result = ParseExpression();
1389 if (Result.isInvalid())
1390 SkipUntil(tok::r_paren, StopAtSemi);
1393 RParenLoc = T.getCloseLocation();
1394 if (RParenLoc.isInvalid())
1397 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1398 Result.get(), RParenLoc);
1405 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1407 /// '__uuidof' '(' expression ')'
1408 /// '__uuidof' '(' type-id ')'
1410 ExprResult Parser::ParseCXXUuidof() {
1411 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1413 SourceLocation OpLoc = ConsumeToken();
1414 BalancedDelimiterTracker T(*this, tok::l_paren);
1416 // __uuidof expressions are always parenthesized.
1417 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1422 if (isTypeIdInParens()) {
1423 TypeResult Ty = ParseTypeName();
1431 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1432 Ty.get().getAsOpaquePtr(),
1433 T.getCloseLocation());
1435 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1436 Result = ParseExpression();
1439 if (Result.isInvalid())
1440 SkipUntil(tok::r_paren, StopAtSemi);
1444 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1446 Result.get(), T.getCloseLocation());
1453 /// \brief Parse a C++ pseudo-destructor expression after the base,
1454 /// . or -> operator, and nested-name-specifier have already been
1457 /// postfix-expression: [C++ 5.2]
1458 /// postfix-expression . pseudo-destructor-name
1459 /// postfix-expression -> pseudo-destructor-name
1461 /// pseudo-destructor-name:
1462 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1463 /// ::[opt] nested-name-specifier template simple-template-id ::
1465 /// ::[opt] nested-name-specifier[opt] ~type-name
1468 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1469 tok::TokenKind OpKind,
1471 ParsedType ObjectType) {
1472 // We're parsing either a pseudo-destructor-name or a dependent
1473 // member access that has the same form as a
1474 // pseudo-destructor-name. We parse both in the same way and let
1475 // the action model sort them out.
1477 // Note that the ::[opt] nested-name-specifier[opt] has already
1478 // been parsed, and if there was a simple-template-id, it has
1479 // been coalesced into a template-id annotation token.
1480 UnqualifiedId FirstTypeName;
1481 SourceLocation CCLoc;
1482 if (Tok.is(tok::identifier)) {
1483 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1485 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1486 CCLoc = ConsumeToken();
1487 } else if (Tok.is(tok::annot_template_id)) {
1488 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1489 // store it in the pseudo-dtor node (to be used when instantiating it).
1490 FirstTypeName.setTemplateId(
1491 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1493 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1494 CCLoc = ConsumeToken();
1496 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1500 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1501 SourceLocation TildeLoc = ConsumeToken();
1503 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1504 DeclSpec DS(AttrFactory);
1505 ParseDecltypeSpecifier(DS);
1506 if (DS.getTypeSpecType() == TST_error)
1508 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1512 if (!Tok.is(tok::identifier)) {
1513 Diag(Tok, diag::err_destructor_tilde_identifier);
1517 // Parse the second type.
1518 UnqualifiedId SecondTypeName;
1519 IdentifierInfo *Name = Tok.getIdentifierInfo();
1520 SourceLocation NameLoc = ConsumeToken();
1521 SecondTypeName.setIdentifier(Name, NameLoc);
1523 // If there is a '<', the second type name is a template-id. Parse
1525 if (Tok.is(tok::less) &&
1526 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1528 false, ObjectType, SecondTypeName,
1529 /*AssumeTemplateName=*/true))
1532 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1533 SS, FirstTypeName, CCLoc, TildeLoc,
1537 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1539 /// boolean-literal: [C++ 2.13.5]
1542 ExprResult Parser::ParseCXXBoolLiteral() {
1543 tok::TokenKind Kind = Tok.getKind();
1544 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1547 /// ParseThrowExpression - This handles the C++ throw expression.
1549 /// throw-expression: [C++ 15]
1550 /// 'throw' assignment-expression[opt]
1551 ExprResult Parser::ParseThrowExpression() {
1552 assert(Tok.is(tok::kw_throw) && "Not throw!");
1553 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1555 // If the current token isn't the start of an assignment-expression,
1556 // then the expression is not present. This handles things like:
1557 // "C ? throw : (void)42", which is crazy but legal.
1558 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1565 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1568 ExprResult Expr(ParseAssignmentExpression());
1569 if (Expr.isInvalid()) return Expr;
1570 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1574 /// \brief Parse the C++ Coroutines co_yield expression.
1576 /// co_yield-expression:
1577 /// 'co_yield' assignment-expression[opt]
1578 ExprResult Parser::ParseCoyieldExpression() {
1579 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1581 SourceLocation Loc = ConsumeToken();
1582 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1583 : ParseAssignmentExpression();
1584 if (!Expr.isInvalid())
1585 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1589 /// ParseCXXThis - This handles the C++ 'this' pointer.
1591 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1592 /// a non-lvalue expression whose value is the address of the object for which
1593 /// the function is called.
1594 ExprResult Parser::ParseCXXThis() {
1595 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1596 SourceLocation ThisLoc = ConsumeToken();
1597 return Actions.ActOnCXXThis(ThisLoc);
1600 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1601 /// Can be interpreted either as function-style casting ("int(x)")
1602 /// or class type construction ("ClassType(x,y,z)")
1603 /// or creation of a value-initialized type ("int()").
1604 /// See [C++ 5.2.3].
1606 /// postfix-expression: [C++ 5.2p1]
1607 /// simple-type-specifier '(' expression-list[opt] ')'
1608 /// [C++0x] simple-type-specifier braced-init-list
1609 /// typename-specifier '(' expression-list[opt] ')'
1610 /// [C++0x] typename-specifier braced-init-list
1613 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1614 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1615 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1617 assert((Tok.is(tok::l_paren) ||
1618 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1619 && "Expected '(' or '{'!");
1621 if (Tok.is(tok::l_brace)) {
1622 ExprResult Init = ParseBraceInitializer();
1623 if (Init.isInvalid())
1625 Expr *InitList = Init.get();
1626 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1627 MultiExprArg(&InitList, 1),
1630 BalancedDelimiterTracker T(*this, tok::l_paren);
1634 CommaLocsTy CommaLocs;
1636 if (Tok.isNot(tok::r_paren)) {
1637 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1638 Actions.CodeCompleteConstructor(getCurScope(),
1639 TypeRep.get()->getCanonicalTypeInternal(),
1640 DS.getLocEnd(), Exprs);
1642 SkipUntil(tok::r_paren, StopAtSemi);
1650 // TypeRep could be null, if it references an invalid typedef.
1654 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1655 "Unexpected number of commas!");
1656 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1658 T.getCloseLocation());
1662 /// ParseCXXCondition - if/switch/while condition expression.
1666 /// type-specifier-seq declarator '=' assignment-expression
1667 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1668 /// [C++11] type-specifier-seq declarator braced-init-list
1669 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1670 /// '=' assignment-expression
1672 /// In C++1z, a condition may in some contexts be preceded by an
1673 /// optional init-statement. This function will parse that too.
1675 /// \param InitStmt If non-null, an init-statement is permitted, and if present
1676 /// will be parsed and stored here.
1678 /// \param Loc The location of the start of the statement that requires this
1679 /// condition, e.g., the "for" in a for loop.
1681 /// \returns The parsed condition.
1682 Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1684 Sema::ConditionKind CK) {
1685 if (Tok.is(tok::code_completion)) {
1686 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1688 return Sema::ConditionError();
1691 ParsedAttributesWithRange attrs(AttrFactory);
1692 MaybeParseCXX11Attributes(attrs);
1694 // Determine what kind of thing we have.
1695 switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
1696 case ConditionOrInitStatement::Expression: {
1697 ProhibitAttributes(attrs);
1699 // Parse the expression.
1700 ExprResult Expr = ParseExpression(); // expression
1701 if (Expr.isInvalid())
1702 return Sema::ConditionError();
1704 if (InitStmt && Tok.is(tok::semi)) {
1705 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1707 return ParseCXXCondition(nullptr, Loc, CK);
1710 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
1713 case ConditionOrInitStatement::InitStmtDecl: {
1714 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1715 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1716 Declarator::InitStmtContext, DeclEnd, attrs, /*RequireSemi=*/true);
1717 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1718 return ParseCXXCondition(nullptr, Loc, CK);
1721 case ConditionOrInitStatement::ConditionDecl:
1722 case ConditionOrInitStatement::Error:
1726 // type-specifier-seq
1727 DeclSpec DS(AttrFactory);
1728 DS.takeAttributesFrom(attrs);
1729 ParseSpecifierQualifierList(DS, AS_none, DSC_condition);
1732 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1733 ParseDeclarator(DeclaratorInfo);
1735 // simple-asm-expr[opt]
1736 if (Tok.is(tok::kw_asm)) {
1738 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1739 if (AsmLabel.isInvalid()) {
1740 SkipUntil(tok::semi, StopAtSemi);
1741 return Sema::ConditionError();
1743 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1744 DeclaratorInfo.SetRangeEnd(Loc);
1747 // If attributes are present, parse them.
1748 MaybeParseGNUAttributes(DeclaratorInfo);
1750 // Type-check the declaration itself.
1751 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1753 if (Dcl.isInvalid())
1754 return Sema::ConditionError();
1755 Decl *DeclOut = Dcl.get();
1757 // '=' assignment-expression
1758 // If a '==' or '+=' is found, suggest a fixit to '='.
1759 bool CopyInitialization = isTokenEqualOrEqualTypo();
1760 if (CopyInitialization)
1763 ExprResult InitExpr = ExprError();
1764 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1765 Diag(Tok.getLocation(),
1766 diag::warn_cxx98_compat_generalized_initializer_lists);
1767 InitExpr = ParseBraceInitializer();
1768 } else if (CopyInitialization) {
1769 InitExpr = ParseAssignmentExpression();
1770 } else if (Tok.is(tok::l_paren)) {
1771 // This was probably an attempt to initialize the variable.
1772 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1773 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1774 RParen = ConsumeParen();
1775 Diag(DeclOut->getLocation(),
1776 diag::err_expected_init_in_condition_lparen)
1777 << SourceRange(LParen, RParen);
1779 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
1782 if (!InitExpr.isInvalid())
1783 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
1784 DS.containsPlaceholderType());
1786 Actions.ActOnInitializerError(DeclOut);
1788 Actions.FinalizeDeclaration(DeclOut);
1789 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
1792 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1793 /// This should only be called when the current token is known to be part of
1794 /// simple-type-specifier.
1796 /// simple-type-specifier:
1797 /// '::'[opt] nested-name-specifier[opt] type-name
1798 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1810 /// [GNU] typeof-specifier
1811 /// [C++0x] auto [TODO]
1818 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1819 DS.SetRangeStart(Tok.getLocation());
1820 const char *PrevSpec;
1822 SourceLocation Loc = Tok.getLocation();
1823 const clang::PrintingPolicy &Policy =
1824 Actions.getASTContext().getPrintingPolicy();
1826 switch (Tok.getKind()) {
1827 case tok::identifier: // foo::bar
1828 case tok::coloncolon: // ::foo::bar
1829 llvm_unreachable("Annotation token should already be formed!");
1831 llvm_unreachable("Not a simple-type-specifier token!");
1834 case tok::annot_typename: {
1835 if (getTypeAnnotation(Tok))
1836 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1837 getTypeAnnotation(Tok), Policy);
1839 DS.SetTypeSpecError();
1841 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1844 DS.Finish(Actions, Policy);
1850 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1853 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1855 case tok::kw___int64:
1856 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1858 case tok::kw_signed:
1859 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1861 case tok::kw_unsigned:
1862 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1865 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1868 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1871 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1873 case tok::kw___int128:
1874 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1877 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1880 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1882 case tok::kw_double:
1883 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1885 case tok::kw___float128:
1886 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1888 case tok::kw_wchar_t:
1889 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1891 case tok::kw_char16_t:
1892 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1894 case tok::kw_char32_t:
1895 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1898 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1900 case tok::annot_decltype:
1901 case tok::kw_decltype:
1902 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1903 return DS.Finish(Actions, Policy);
1905 // GNU typeof support.
1906 case tok::kw_typeof:
1907 ParseTypeofSpecifier(DS);
1908 DS.Finish(Actions, Policy);
1911 if (Tok.is(tok::annot_typename))
1912 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1914 DS.SetRangeEnd(Tok.getLocation());
1916 DS.Finish(Actions, Policy);
1919 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1920 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1921 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1922 /// by parsing the type-specifier-seq, because these sequences are
1923 /// typically followed by some form of declarator. Returns true and
1924 /// emits diagnostics if this is not a type-specifier-seq, false
1927 /// type-specifier-seq: [C++ 8.1]
1928 /// type-specifier type-specifier-seq[opt]
1930 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1931 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1932 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
1936 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1939 /// This routine is invoked when a '<' is encountered after an identifier or
1940 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1941 /// whether the unqualified-id is actually a template-id. This routine will
1942 /// then parse the template arguments and form the appropriate template-id to
1943 /// return to the caller.
1945 /// \param SS the nested-name-specifier that precedes this template-id, if
1946 /// we're actually parsing a qualified-id.
1948 /// \param Name for constructor and destructor names, this is the actual
1949 /// identifier that may be a template-name.
1951 /// \param NameLoc the location of the class-name in a constructor or
1954 /// \param EnteringContext whether we're entering the scope of the
1955 /// nested-name-specifier.
1957 /// \param ObjectType if this unqualified-id occurs within a member access
1958 /// expression, the type of the base object whose member is being accessed.
1960 /// \param Id as input, describes the template-name or operator-function-id
1961 /// that precedes the '<'. If template arguments were parsed successfully,
1962 /// will be updated with the template-id.
1964 /// \param AssumeTemplateId When true, this routine will assume that the name
1965 /// refers to a template without performing name lookup to verify.
1967 /// \returns true if a parse error occurred, false otherwise.
1968 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1969 SourceLocation TemplateKWLoc,
1970 IdentifierInfo *Name,
1971 SourceLocation NameLoc,
1972 bool EnteringContext,
1973 ParsedType ObjectType,
1975 bool AssumeTemplateId) {
1976 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1977 "Expected '<' to finish parsing a template-id");
1979 TemplateTy Template;
1980 TemplateNameKind TNK = TNK_Non_template;
1981 switch (Id.getKind()) {
1982 case UnqualifiedId::IK_Identifier:
1983 case UnqualifiedId::IK_OperatorFunctionId:
1984 case UnqualifiedId::IK_LiteralOperatorId:
1985 if (AssumeTemplateId) {
1986 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
1987 Id, ObjectType, EnteringContext,
1989 if (TNK == TNK_Non_template)
1992 bool MemberOfUnknownSpecialization;
1993 TNK = Actions.isTemplateName(getCurScope(), SS,
1994 TemplateKWLoc.isValid(), Id,
1995 ObjectType, EnteringContext, Template,
1996 MemberOfUnknownSpecialization);
1998 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1999 ObjectType && IsTemplateArgumentList()) {
2000 // We have something like t->getAs<T>(), where getAs is a
2001 // member of an unknown specialization. However, this will only
2002 // parse correctly as a template, so suggest the keyword 'template'
2003 // before 'getAs' and treat this as a dependent template name.
2005 if (Id.getKind() == UnqualifiedId::IK_Identifier)
2006 Name = Id.Identifier->getName();
2009 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
2010 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2012 Name += Id.Identifier->getName();
2014 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2016 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2017 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2018 SS, TemplateKWLoc, Id,
2019 ObjectType, EnteringContext,
2021 if (TNK == TNK_Non_template)
2027 case UnqualifiedId::IK_ConstructorName: {
2028 UnqualifiedId TemplateName;
2029 bool MemberOfUnknownSpecialization;
2030 TemplateName.setIdentifier(Name, NameLoc);
2031 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2032 TemplateName, ObjectType,
2033 EnteringContext, Template,
2034 MemberOfUnknownSpecialization);
2038 case UnqualifiedId::IK_DestructorName: {
2039 UnqualifiedId TemplateName;
2040 bool MemberOfUnknownSpecialization;
2041 TemplateName.setIdentifier(Name, NameLoc);
2043 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2044 SS, TemplateKWLoc, TemplateName,
2045 ObjectType, EnteringContext,
2047 if (TNK == TNK_Non_template)
2050 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2051 TemplateName, ObjectType,
2052 EnteringContext, Template,
2053 MemberOfUnknownSpecialization);
2055 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2056 Diag(NameLoc, diag::err_destructor_template_id)
2057 << Name << SS.getRange();
2068 if (TNK == TNK_Non_template)
2071 // Parse the enclosed template argument list.
2072 SourceLocation LAngleLoc, RAngleLoc;
2073 TemplateArgList TemplateArgs;
2074 if (Tok.is(tok::less) &&
2075 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
2076 SS, true, LAngleLoc,
2081 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
2082 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2083 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
2084 // Form a parsed representation of the template-id to be stored in the
2086 TemplateIdAnnotation *TemplateId
2087 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
2089 // FIXME: Store name for literal operator too.
2090 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2091 TemplateId->Name = Id.Identifier;
2092 TemplateId->Operator = OO_None;
2093 TemplateId->TemplateNameLoc = Id.StartLocation;
2095 TemplateId->Name = nullptr;
2096 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2097 TemplateId->TemplateNameLoc = Id.StartLocation;
2100 TemplateId->SS = SS;
2101 TemplateId->TemplateKWLoc = TemplateKWLoc;
2102 TemplateId->Template = Template;
2103 TemplateId->Kind = TNK;
2104 TemplateId->LAngleLoc = LAngleLoc;
2105 TemplateId->RAngleLoc = RAngleLoc;
2106 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
2107 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
2108 Arg != ArgEnd; ++Arg)
2109 Args[Arg] = TemplateArgs[Arg];
2111 Id.setTemplateId(TemplateId);
2115 // Bundle the template arguments together.
2116 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2118 // Constructor and destructor names.
2120 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2122 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2123 /*IsCtorOrDtorName=*/true);
2124 if (Type.isInvalid())
2127 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2128 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2130 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2135 /// \brief Parse an operator-function-id or conversion-function-id as part
2136 /// of a C++ unqualified-id.
2138 /// This routine is responsible only for parsing the operator-function-id or
2139 /// conversion-function-id; it does not handle template arguments in any way.
2142 /// operator-function-id: [C++ 13.5]
2143 /// 'operator' operator
2145 /// operator: one of
2146 /// new delete new[] delete[]
2147 /// + - * / % ^ & | ~
2148 /// ! = < > += -= *= /= %=
2149 /// ^= &= |= << >> >>= <<= == !=
2150 /// <= >= && || ++ -- , ->* ->
2153 /// conversion-function-id: [C++ 12.3.2]
2154 /// operator conversion-type-id
2156 /// conversion-type-id:
2157 /// type-specifier-seq conversion-declarator[opt]
2159 /// conversion-declarator:
2160 /// ptr-operator conversion-declarator[opt]
2163 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2164 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2166 /// \param EnteringContext whether we are entering the scope of the
2167 /// nested-name-specifier.
2169 /// \param ObjectType if this unqualified-id occurs within a member access
2170 /// expression, the type of the base object whose member is being accessed.
2172 /// \param Result on a successful parse, contains the parsed unqualified-id.
2174 /// \returns true if parsing fails, false otherwise.
2175 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2176 ParsedType ObjectType,
2177 UnqualifiedId &Result) {
2178 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2180 // Consume the 'operator' keyword.
2181 SourceLocation KeywordLoc = ConsumeToken();
2183 // Determine what kind of operator name we have.
2184 unsigned SymbolIdx = 0;
2185 SourceLocation SymbolLocations[3];
2186 OverloadedOperatorKind Op = OO_None;
2187 switch (Tok.getKind()) {
2189 case tok::kw_delete: {
2190 bool isNew = Tok.getKind() == tok::kw_new;
2191 // Consume the 'new' or 'delete'.
2192 SymbolLocations[SymbolIdx++] = ConsumeToken();
2193 // Check for array new/delete.
2194 if (Tok.is(tok::l_square) &&
2195 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2196 // Consume the '[' and ']'.
2197 BalancedDelimiterTracker T(*this, tok::l_square);
2200 if (T.getCloseLocation().isInvalid())
2203 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2204 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2205 Op = isNew? OO_Array_New : OO_Array_Delete;
2207 Op = isNew? OO_New : OO_Delete;
2212 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2214 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2217 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2218 #include "clang/Basic/OperatorKinds.def"
2220 case tok::l_paren: {
2221 // Consume the '(' and ')'.
2222 BalancedDelimiterTracker T(*this, tok::l_paren);
2225 if (T.getCloseLocation().isInvalid())
2228 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2229 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2234 case tok::l_square: {
2235 // Consume the '[' and ']'.
2236 BalancedDelimiterTracker T(*this, tok::l_square);
2239 if (T.getCloseLocation().isInvalid())
2242 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2243 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2248 case tok::code_completion: {
2249 // Code completion for the operator name.
2250 Actions.CodeCompleteOperatorName(getCurScope());
2252 // Don't try to parse any further.
2260 if (Op != OO_None) {
2261 // We have parsed an operator-function-id.
2262 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2266 // Parse a literal-operator-id.
2268 // literal-operator-id: C++11 [over.literal]
2269 // operator string-literal identifier
2270 // operator user-defined-string-literal
2272 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2273 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2275 SourceLocation DiagLoc;
2276 unsigned DiagId = 0;
2278 // We're past translation phase 6, so perform string literal concatenation
2279 // before checking for "".
2280 SmallVector<Token, 4> Toks;
2281 SmallVector<SourceLocation, 4> TokLocs;
2282 while (isTokenStringLiteral()) {
2283 if (!Tok.is(tok::string_literal) && !DiagId) {
2284 // C++11 [over.literal]p1:
2285 // The string-literal or user-defined-string-literal in a
2286 // literal-operator-id shall have no encoding-prefix [...].
2287 DiagLoc = Tok.getLocation();
2288 DiagId = diag::err_literal_operator_string_prefix;
2290 Toks.push_back(Tok);
2291 TokLocs.push_back(ConsumeStringToken());
2294 StringLiteralParser Literal(Toks, PP);
2295 if (Literal.hadError)
2298 // Grab the literal operator's suffix, which will be either the next token
2299 // or a ud-suffix from the string literal.
2300 IdentifierInfo *II = nullptr;
2301 SourceLocation SuffixLoc;
2302 if (!Literal.getUDSuffix().empty()) {
2303 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2305 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2306 Literal.getUDSuffixOffset(),
2307 PP.getSourceManager(), getLangOpts());
2308 } else if (Tok.is(tok::identifier)) {
2309 II = Tok.getIdentifierInfo();
2310 SuffixLoc = ConsumeToken();
2311 TokLocs.push_back(SuffixLoc);
2313 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2317 // The string literal must be empty.
2318 if (!Literal.GetString().empty() || Literal.Pascal) {
2319 // C++11 [over.literal]p1:
2320 // The string-literal or user-defined-string-literal in a
2321 // literal-operator-id shall [...] contain no characters
2322 // other than the implicit terminating '\0'.
2323 DiagLoc = TokLocs.front();
2324 DiagId = diag::err_literal_operator_string_not_empty;
2328 // This isn't a valid literal-operator-id, but we think we know
2329 // what the user meant. Tell them what they should have written.
2330 SmallString<32> Str;
2332 Str += II->getName();
2333 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2334 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2337 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2339 return Actions.checkLiteralOperatorId(SS, Result);
2342 // Parse a conversion-function-id.
2344 // conversion-function-id: [C++ 12.3.2]
2345 // operator conversion-type-id
2347 // conversion-type-id:
2348 // type-specifier-seq conversion-declarator[opt]
2350 // conversion-declarator:
2351 // ptr-operator conversion-declarator[opt]
2353 // Parse the type-specifier-seq.
2354 DeclSpec DS(AttrFactory);
2355 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2358 // Parse the conversion-declarator, which is merely a sequence of
2360 Declarator D(DS, Declarator::ConversionIdContext);
2361 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2363 // Finish up the type.
2364 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2368 // Note that this is a conversion-function-id.
2369 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2370 D.getSourceRange().getEnd());
2374 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2375 /// name of an entity.
2378 /// unqualified-id: [C++ expr.prim.general]
2380 /// operator-function-id
2381 /// conversion-function-id
2382 /// [C++0x] literal-operator-id [TODO]
2388 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2389 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2391 /// \param EnteringContext whether we are entering the scope of the
2392 /// nested-name-specifier.
2394 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2396 /// \param AllowConstructorName whether we allow parsing a constructor name.
2398 /// \param ObjectType if this unqualified-id occurs within a member access
2399 /// expression, the type of the base object whose member is being accessed.
2401 /// \param Result on a successful parse, contains the parsed unqualified-id.
2403 /// \returns true if parsing fails, false otherwise.
2404 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2405 bool AllowDestructorName,
2406 bool AllowConstructorName,
2407 ParsedType ObjectType,
2408 SourceLocation& TemplateKWLoc,
2409 UnqualifiedId &Result) {
2411 // Handle 'A::template B'. This is for template-ids which have not
2412 // already been annotated by ParseOptionalCXXScopeSpecifier().
2413 bool TemplateSpecified = false;
2414 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2415 (ObjectType || SS.isSet())) {
2416 TemplateSpecified = true;
2417 TemplateKWLoc = ConsumeToken();
2422 // template-id (when it hasn't already been annotated)
2423 if (Tok.is(tok::identifier)) {
2424 // Consume the identifier.
2425 IdentifierInfo *Id = Tok.getIdentifierInfo();
2426 SourceLocation IdLoc = ConsumeToken();
2428 if (!getLangOpts().CPlusPlus) {
2429 // If we're not in C++, only identifiers matter. Record the
2430 // identifier and return.
2431 Result.setIdentifier(Id, IdLoc);
2435 if (AllowConstructorName &&
2436 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2437 // We have parsed a constructor name.
2438 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, false,
2440 /*IsCtorOrDtorName=*/true,
2441 /*NonTrivialTypeSourceInfo=*/true);
2442 Result.setConstructorName(Ty, IdLoc, IdLoc);
2444 // We have parsed an identifier.
2445 Result.setIdentifier(Id, IdLoc);
2448 // If the next token is a '<', we may have a template.
2449 if (TemplateSpecified || Tok.is(tok::less))
2450 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2451 EnteringContext, ObjectType,
2452 Result, TemplateSpecified);
2458 // template-id (already parsed and annotated)
2459 if (Tok.is(tok::annot_template_id)) {
2460 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2462 // If the template-name names the current class, then this is a constructor
2463 if (AllowConstructorName && TemplateId->Name &&
2464 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2466 // C++ [class.qual]p2 specifies that a qualified template-name
2467 // is taken as the constructor name where a constructor can be
2468 // declared. Thus, the template arguments are extraneous, so
2469 // complain about them and remove them entirely.
2470 Diag(TemplateId->TemplateNameLoc,
2471 diag::err_out_of_line_constructor_template_id)
2473 << FixItHint::CreateRemoval(
2474 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2476 Actions.getTypeName(*TemplateId->Name, TemplateId->TemplateNameLoc,
2477 getCurScope(), &SS, false, false, nullptr,
2478 /*IsCtorOrDtorName=*/true,
2479 /*NontrivialTypeSourceInfo=*/true);
2480 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2481 TemplateId->RAngleLoc);
2486 Result.setConstructorTemplateId(TemplateId);
2491 // We have already parsed a template-id; consume the annotation token as
2492 // our unqualified-id.
2493 Result.setTemplateId(TemplateId);
2494 TemplateKWLoc = TemplateId->TemplateKWLoc;
2500 // operator-function-id
2501 // conversion-function-id
2502 if (Tok.is(tok::kw_operator)) {
2503 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2506 // If we have an operator-function-id or a literal-operator-id and the next
2507 // token is a '<', we may have a
2510 // operator-function-id < template-argument-list[opt] >
2511 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2512 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2513 (TemplateSpecified || Tok.is(tok::less)))
2514 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2515 nullptr, SourceLocation(),
2516 EnteringContext, ObjectType,
2517 Result, TemplateSpecified);
2522 if (getLangOpts().CPlusPlus &&
2523 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2524 // C++ [expr.unary.op]p10:
2525 // There is an ambiguity in the unary-expression ~X(), where X is a
2526 // class-name. The ambiguity is resolved in favor of treating ~ as a
2527 // unary complement rather than treating ~X as referring to a destructor.
2530 SourceLocation TildeLoc = ConsumeToken();
2532 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2533 DeclSpec DS(AttrFactory);
2534 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2535 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2536 Result.setDestructorName(TildeLoc, Type, EndLoc);
2542 // Parse the class-name.
2543 if (Tok.isNot(tok::identifier)) {
2544 Diag(Tok, diag::err_destructor_tilde_identifier);
2548 // If the user wrote ~T::T, correct it to T::~T.
2549 DeclaratorScopeObj DeclScopeObj(*this, SS);
2550 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2551 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2552 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2553 // it will confuse this recovery logic.
2554 ColonProtectionRAIIObject ColonRAII(*this, false);
2557 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2560 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2562 if (SS.isNotEmpty())
2563 ObjectType = nullptr;
2564 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2566 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2570 // Recover as if the tilde had been written before the identifier.
2571 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2572 << FixItHint::CreateRemoval(TildeLoc)
2573 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2575 // Temporarily enter the scope for the rest of this function.
2576 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2577 DeclScopeObj.EnterDeclaratorScope();
2580 // Parse the class-name (or template-name in a simple-template-id).
2581 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2582 SourceLocation ClassNameLoc = ConsumeToken();
2584 if (TemplateSpecified || Tok.is(tok::less)) {
2585 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2586 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2587 ClassName, ClassNameLoc,
2588 EnteringContext, ObjectType,
2589 Result, TemplateSpecified);
2592 // Note that this is a destructor name.
2593 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2594 ClassNameLoc, getCurScope(),
2600 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2604 Diag(Tok, diag::err_expected_unqualified_id)
2605 << getLangOpts().CPlusPlus;
2609 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2610 /// memory in a typesafe manner and call constructors.
2612 /// This method is called to parse the new expression after the optional :: has
2613 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2614 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2617 /// '::'[opt] 'new' new-placement[opt] new-type-id
2618 /// new-initializer[opt]
2619 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2620 /// new-initializer[opt]
2623 /// '(' expression-list ')'
2626 /// type-specifier-seq new-declarator[opt]
2627 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2630 /// ptr-operator new-declarator[opt]
2631 /// direct-new-declarator
2633 /// new-initializer:
2634 /// '(' expression-list[opt] ')'
2635 /// [C++0x] braced-init-list
2638 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2639 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2640 ConsumeToken(); // Consume 'new'
2642 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2643 // second form of new-expression. It can't be a new-type-id.
2645 ExprVector PlacementArgs;
2646 SourceLocation PlacementLParen, PlacementRParen;
2648 SourceRange TypeIdParens;
2649 DeclSpec DS(AttrFactory);
2650 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2651 if (Tok.is(tok::l_paren)) {
2652 // If it turns out to be a placement, we change the type location.
2653 BalancedDelimiterTracker T(*this, tok::l_paren);
2655 PlacementLParen = T.getOpenLocation();
2656 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2657 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2662 PlacementRParen = T.getCloseLocation();
2663 if (PlacementRParen.isInvalid()) {
2664 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2668 if (PlacementArgs.empty()) {
2669 // Reset the placement locations. There was no placement.
2670 TypeIdParens = T.getRange();
2671 PlacementLParen = PlacementRParen = SourceLocation();
2673 // We still need the type.
2674 if (Tok.is(tok::l_paren)) {
2675 BalancedDelimiterTracker T(*this, tok::l_paren);
2677 MaybeParseGNUAttributes(DeclaratorInfo);
2678 ParseSpecifierQualifierList(DS);
2679 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2680 ParseDeclarator(DeclaratorInfo);
2682 TypeIdParens = T.getRange();
2684 MaybeParseGNUAttributes(DeclaratorInfo);
2685 if (ParseCXXTypeSpecifierSeq(DS))
2686 DeclaratorInfo.setInvalidType(true);
2688 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2689 ParseDeclaratorInternal(DeclaratorInfo,
2690 &Parser::ParseDirectNewDeclarator);
2695 // A new-type-id is a simplified type-id, where essentially the
2696 // direct-declarator is replaced by a direct-new-declarator.
2697 MaybeParseGNUAttributes(DeclaratorInfo);
2698 if (ParseCXXTypeSpecifierSeq(DS))
2699 DeclaratorInfo.setInvalidType(true);
2701 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2702 ParseDeclaratorInternal(DeclaratorInfo,
2703 &Parser::ParseDirectNewDeclarator);
2706 if (DeclaratorInfo.isInvalidType()) {
2707 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2711 ExprResult Initializer;
2713 if (Tok.is(tok::l_paren)) {
2714 SourceLocation ConstructorLParen, ConstructorRParen;
2715 ExprVector ConstructorArgs;
2716 BalancedDelimiterTracker T(*this, tok::l_paren);
2718 ConstructorLParen = T.getOpenLocation();
2719 if (Tok.isNot(tok::r_paren)) {
2720 CommaLocsTy CommaLocs;
2721 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2722 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2723 DeclaratorInfo).get();
2724 Actions.CodeCompleteConstructor(getCurScope(),
2725 TypeRep.get()->getCanonicalTypeInternal(),
2726 DeclaratorInfo.getLocEnd(),
2729 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2734 ConstructorRParen = T.getCloseLocation();
2735 if (ConstructorRParen.isInvalid()) {
2736 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2739 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2742 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2743 Diag(Tok.getLocation(),
2744 diag::warn_cxx98_compat_generalized_initializer_lists);
2745 Initializer = ParseBraceInitializer();
2747 if (Initializer.isInvalid())
2750 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2751 PlacementArgs, PlacementRParen,
2752 TypeIdParens, DeclaratorInfo, Initializer.get());
2755 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2756 /// passed to ParseDeclaratorInternal.
2758 /// direct-new-declarator:
2759 /// '[' expression ']'
2760 /// direct-new-declarator '[' constant-expression ']'
2762 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2763 // Parse the array dimensions.
2765 while (Tok.is(tok::l_square)) {
2766 // An array-size expression can't start with a lambda.
2767 if (CheckProhibitedCXX11Attribute())
2770 BalancedDelimiterTracker T(*this, tok::l_square);
2773 ExprResult Size(first ? ParseExpression()
2774 : ParseConstantExpression());
2775 if (Size.isInvalid()) {
2777 SkipUntil(tok::r_square, StopAtSemi);
2784 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2785 ParsedAttributes Attrs(AttrFactory);
2786 MaybeParseCXX11Attributes(Attrs);
2788 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2789 /*static=*/false, /*star=*/false,
2791 T.getOpenLocation(),
2792 T.getCloseLocation()),
2793 Attrs, T.getCloseLocation());
2795 if (T.getCloseLocation().isInvalid())
2800 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2801 /// This ambiguity appears in the syntax of the C++ new operator.
2804 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2805 /// new-initializer[opt]
2808 /// '(' expression-list ')'
2810 bool Parser::ParseExpressionListOrTypeId(
2811 SmallVectorImpl<Expr*> &PlacementArgs,
2813 // The '(' was already consumed.
2814 if (isTypeIdInParens()) {
2815 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2816 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2818 return D.isInvalidType();
2821 // It's not a type, it has to be an expression list.
2822 // Discard the comma locations - ActOnCXXNew has enough parameters.
2823 CommaLocsTy CommaLocs;
2824 return ParseExpressionList(PlacementArgs, CommaLocs);
2827 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2828 /// to free memory allocated by new.
2830 /// This method is called to parse the 'delete' expression after the optional
2831 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2832 /// and "Start" is its location. Otherwise, "Start" is the location of the
2835 /// delete-expression:
2836 /// '::'[opt] 'delete' cast-expression
2837 /// '::'[opt] 'delete' '[' ']' cast-expression
2839 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2840 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2841 ConsumeToken(); // Consume 'delete'
2844 bool ArrayDelete = false;
2845 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2846 // C++11 [expr.delete]p1:
2847 // Whenever the delete keyword is followed by empty square brackets, it
2848 // shall be interpreted as [array delete].
2849 // [Footnote: A lambda expression with a lambda-introducer that consists
2850 // of empty square brackets can follow the delete keyword if
2851 // the lambda expression is enclosed in parentheses.]
2852 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2853 // lambda-introducer.
2855 BalancedDelimiterTracker T(*this, tok::l_square);
2859 if (T.getCloseLocation().isInvalid())
2863 ExprResult Operand(ParseCastExpression(false));
2864 if (Operand.isInvalid())
2867 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2870 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2872 default: llvm_unreachable("Not a known type trait");
2873 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2874 case tok::kw_ ## Spelling: return UTT_ ## Name;
2875 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2876 case tok::kw_ ## Spelling: return BTT_ ## Name;
2877 #include "clang/Basic/TokenKinds.def"
2878 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2879 case tok::kw_ ## Spelling: return TT_ ## Name;
2880 #include "clang/Basic/TokenKinds.def"
2884 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2886 default: llvm_unreachable("Not a known binary type trait");
2887 case tok::kw___array_rank: return ATT_ArrayRank;
2888 case tok::kw___array_extent: return ATT_ArrayExtent;
2892 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2894 default: llvm_unreachable("Not a known unary expression trait.");
2895 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2896 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2900 static unsigned TypeTraitArity(tok::TokenKind kind) {
2902 default: llvm_unreachable("Not a known type trait");
2903 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2904 #include "clang/Basic/TokenKinds.def"
2908 /// \brief Parse the built-in type-trait pseudo-functions that allow
2909 /// implementation of the TR1/C++11 type traits templates.
2911 /// primary-expression:
2912 /// unary-type-trait '(' type-id ')'
2913 /// binary-type-trait '(' type-id ',' type-id ')'
2914 /// type-trait '(' type-id-seq ')'
2917 /// type-id ...[opt] type-id-seq[opt]
2919 ExprResult Parser::ParseTypeTrait() {
2920 tok::TokenKind Kind = Tok.getKind();
2921 unsigned Arity = TypeTraitArity(Kind);
2923 SourceLocation Loc = ConsumeToken();
2925 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2926 if (Parens.expectAndConsume())
2929 SmallVector<ParsedType, 2> Args;
2931 // Parse the next type.
2932 TypeResult Ty = ParseTypeName();
2933 if (Ty.isInvalid()) {
2938 // Parse the ellipsis, if present.
2939 if (Tok.is(tok::ellipsis)) {
2940 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2941 if (Ty.isInvalid()) {
2947 // Add this type to the list of arguments.
2948 Args.push_back(Ty.get());
2949 } while (TryConsumeToken(tok::comma));
2951 if (Parens.consumeClose())
2954 SourceLocation EndLoc = Parens.getCloseLocation();
2956 if (Arity && Args.size() != Arity) {
2957 Diag(EndLoc, diag::err_type_trait_arity)
2958 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2962 if (!Arity && Args.empty()) {
2963 Diag(EndLoc, diag::err_type_trait_arity)
2964 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2968 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
2971 /// ParseArrayTypeTrait - Parse the built-in array type-trait
2972 /// pseudo-functions.
2974 /// primary-expression:
2975 /// [Embarcadero] '__array_rank' '(' type-id ')'
2976 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2978 ExprResult Parser::ParseArrayTypeTrait() {
2979 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2980 SourceLocation Loc = ConsumeToken();
2982 BalancedDelimiterTracker T(*this, tok::l_paren);
2983 if (T.expectAndConsume())
2986 TypeResult Ty = ParseTypeName();
2987 if (Ty.isInvalid()) {
2988 SkipUntil(tok::comma, StopAtSemi);
2989 SkipUntil(tok::r_paren, StopAtSemi);
2994 case ATT_ArrayRank: {
2996 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
2997 T.getCloseLocation());
2999 case ATT_ArrayExtent: {
3000 if (ExpectAndConsume(tok::comma)) {
3001 SkipUntil(tok::r_paren, StopAtSemi);
3005 ExprResult DimExpr = ParseExpression();
3008 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3009 T.getCloseLocation());
3012 llvm_unreachable("Invalid ArrayTypeTrait!");
3015 /// ParseExpressionTrait - Parse built-in expression-trait
3016 /// pseudo-functions like __is_lvalue_expr( xxx ).
3018 /// primary-expression:
3019 /// [Embarcadero] expression-trait '(' expression ')'
3021 ExprResult Parser::ParseExpressionTrait() {
3022 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3023 SourceLocation Loc = ConsumeToken();
3025 BalancedDelimiterTracker T(*this, tok::l_paren);
3026 if (T.expectAndConsume())
3029 ExprResult Expr = ParseExpression();
3033 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3034 T.getCloseLocation());
3038 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3039 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3040 /// based on the context past the parens.
3042 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3044 BalancedDelimiterTracker &Tracker,
3045 ColonProtectionRAIIObject &ColonProt) {
3046 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3047 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3048 assert(isTypeIdInParens() && "Not a type-id!");
3050 ExprResult Result(true);
3053 // We need to disambiguate a very ugly part of the C++ syntax:
3055 // (T())x; - type-id
3056 // (T())*x; - type-id
3057 // (T())/x; - expression
3058 // (T()); - expression
3060 // The bad news is that we cannot use the specialized tentative parser, since
3061 // it can only verify that the thing inside the parens can be parsed as
3062 // type-id, it is not useful for determining the context past the parens.
3064 // The good news is that the parser can disambiguate this part without
3065 // making any unnecessary Action calls.
3067 // It uses a scheme similar to parsing inline methods. The parenthesized
3068 // tokens are cached, the context that follows is determined (possibly by
3069 // parsing a cast-expression), and then we re-introduce the cached tokens
3070 // into the token stream and parse them appropriately.
3072 ParenParseOption ParseAs;
3075 // Store the tokens of the parentheses. We will parse them after we determine
3076 // the context that follows them.
3077 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3078 // We didn't find the ')' we expected.
3079 Tracker.consumeClose();
3083 if (Tok.is(tok::l_brace)) {
3084 ParseAs = CompoundLiteral;
3087 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3090 // Try parsing the cast-expression that may follow.
3091 // If it is not a cast-expression, NotCastExpr will be true and no token
3092 // will be consumed.
3093 ColonProt.restore();
3094 Result = ParseCastExpression(false/*isUnaryExpression*/,
3095 false/*isAddressofOperand*/,
3097 // type-id has priority.
3101 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3103 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3106 // Create a fake EOF to mark end of Toks buffer.
3108 AttrEnd.startToken();
3109 AttrEnd.setKind(tok::eof);
3110 AttrEnd.setLocation(Tok.getLocation());
3111 AttrEnd.setEofData(Toks.data());
3112 Toks.push_back(AttrEnd);
3114 // The current token should go after the cached tokens.
3115 Toks.push_back(Tok);
3116 // Re-enter the stored parenthesized tokens into the token stream, so we may
3118 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
3119 // Drop the current token and bring the first cached one. It's the same token
3120 // as when we entered this function.
3123 if (ParseAs >= CompoundLiteral) {
3124 // Parse the type declarator.
3125 DeclSpec DS(AttrFactory);
3126 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
3128 ColonProtectionRAIIObject InnerColonProtection(*this);
3129 ParseSpecifierQualifierList(DS);
3130 ParseDeclarator(DeclaratorInfo);
3134 Tracker.consumeClose();
3135 ColonProt.restore();
3137 // Consume EOF marker for Toks buffer.
3138 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3141 if (ParseAs == CompoundLiteral) {
3142 ExprType = CompoundLiteral;
3143 if (DeclaratorInfo.isInvalidType())
3146 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3147 return ParseCompoundLiteralExpression(Ty.get(),
3148 Tracker.getOpenLocation(),
3149 Tracker.getCloseLocation());
3152 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3153 assert(ParseAs == CastExpr);
3155 if (DeclaratorInfo.isInvalidType())
3158 // Result is what ParseCastExpression returned earlier.
3159 if (!Result.isInvalid())
3160 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3161 DeclaratorInfo, CastTy,
3162 Tracker.getCloseLocation(), Result.get());
3166 // Not a compound literal, and not followed by a cast-expression.
3167 assert(ParseAs == SimpleExpr);
3169 ExprType = SimpleExpr;
3170 Result = ParseExpression();
3171 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3172 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3173 Tok.getLocation(), Result.get());
3176 if (Result.isInvalid()) {
3177 while (Tok.isNot(tok::eof))
3179 assert(Tok.getEofData() == AttrEnd.getEofData());
3184 Tracker.consumeClose();
3185 // Consume EOF marker for Toks buffer.
3186 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());