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 Parse global scope or nested-name-specifier if present.
105 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
106 /// may be preceded by '::'). Note that this routine will not parse ::new or
107 /// ::delete; it will just leave them in the token stream.
109 /// '::'[opt] nested-name-specifier
112 /// nested-name-specifier:
114 /// namespace-name '::'
115 /// nested-name-specifier identifier '::'
116 /// nested-name-specifier 'template'[opt] simple-template-id '::'
119 /// \param SS the scope specifier that will be set to the parsed
120 /// nested-name-specifier (or empty)
122 /// \param ObjectType if this nested-name-specifier is being parsed following
123 /// the "." or "->" of a member access expression, this parameter provides the
124 /// type of the object whose members are being accessed.
126 /// \param EnteringContext whether we will be entering into the context of
127 /// the nested-name-specifier after parsing it.
129 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
130 /// indicates whether this nested-name-specifier may be part of a
131 /// pseudo-destructor name. In this case, the flag will be set false
132 /// if we don't actually end up parsing a destructor name. Moreorover,
133 /// if we do end up determining that we are parsing a destructor name,
134 /// the last component of the nested-name-specifier is not parsed as
135 /// part of the scope specifier.
137 /// \param IsTypename If \c true, this nested-name-specifier is known to be
138 /// part of a type name. This is used to improve error recovery.
140 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
141 /// filled in with the leading identifier in the last component of the
142 /// nested-name-specifier, if any.
144 /// \returns true if there was an error parsing a scope specifier
145 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
146 ParsedType ObjectType,
147 bool EnteringContext,
148 bool *MayBePseudoDestructor,
150 IdentifierInfo **LastII) {
151 assert(getLangOpts().CPlusPlus &&
152 "Call sites of this function should be guarded by checking for C++");
154 if (Tok.is(tok::annot_cxxscope)) {
155 assert(!LastII && "want last identifier but have already annotated scope");
156 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
157 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
158 Tok.getAnnotationRange(),
164 if (Tok.is(tok::annot_template_id)) {
165 // If the current token is an annotated template id, it may already have
166 // a scope specifier. Restore it.
167 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
171 // Has to happen before any "return false"s in this function.
172 bool CheckForDestructor = false;
173 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
174 CheckForDestructor = true;
175 *MayBePseudoDestructor = false;
181 bool HasScopeSpecifier = false;
183 if (Tok.is(tok::coloncolon)) {
184 // ::new and ::delete aren't nested-name-specifiers.
185 tok::TokenKind NextKind = NextToken().getKind();
186 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
189 if (NextKind == tok::l_brace) {
190 // It is invalid to have :: {, consume the scope qualifier and pretend
191 // like we never saw it.
192 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
194 // '::' - Global scope qualifier.
195 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
198 HasScopeSpecifier = true;
202 if (Tok.is(tok::kw___super)) {
203 SourceLocation SuperLoc = ConsumeToken();
204 if (!Tok.is(tok::coloncolon)) {
205 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
209 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
212 if (!HasScopeSpecifier &&
213 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
214 DeclSpec DS(AttrFactory);
215 SourceLocation DeclLoc = Tok.getLocation();
216 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
218 SourceLocation CCLoc;
219 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
220 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
224 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
225 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
227 HasScopeSpecifier = true;
231 if (HasScopeSpecifier) {
232 // C++ [basic.lookup.classref]p5:
233 // If the qualified-id has the form
235 // ::class-name-or-namespace-name::...
237 // the class-name-or-namespace-name is looked up in global scope as a
238 // class-name or namespace-name.
240 // To implement this, we clear out the object type as soon as we've
241 // seen a leading '::' or part of a nested-name-specifier.
242 ObjectType = nullptr;
244 if (Tok.is(tok::code_completion)) {
245 // Code completion for a nested-name-specifier, where the code
246 // code completion token follows the '::'.
247 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
248 // Include code completion token into the range of the scope otherwise
249 // when we try to annotate the scope tokens the dangling code completion
250 // token will cause assertion in
251 // Preprocessor::AnnotatePreviousCachedTokens.
252 SS.setEndLoc(Tok.getLocation());
258 // nested-name-specifier:
259 // nested-name-specifier 'template'[opt] simple-template-id '::'
261 // Parse the optional 'template' keyword, then make sure we have
262 // 'identifier <' after it.
263 if (Tok.is(tok::kw_template)) {
264 // If we don't have a scope specifier or an object type, this isn't a
265 // nested-name-specifier, since they aren't allowed to start with
267 if (!HasScopeSpecifier && !ObjectType)
270 TentativeParsingAction TPA(*this);
271 SourceLocation TemplateKWLoc = ConsumeToken();
273 UnqualifiedId TemplateName;
274 if (Tok.is(tok::identifier)) {
275 // Consume the identifier.
276 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
278 } else if (Tok.is(tok::kw_operator)) {
279 // We don't need to actually parse the unqualified-id in this case,
280 // because a simple-template-id cannot start with 'operator', but
281 // go ahead and parse it anyway for consistency with the case where
282 // we already annotated the template-id.
283 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
289 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
290 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
291 Diag(TemplateName.getSourceRange().getBegin(),
292 diag::err_id_after_template_in_nested_name_spec)
293 << TemplateName.getSourceRange();
302 // If the next token is not '<', we have a qualified-id that refers
303 // to a template name, such as T::template apply, but is not a
305 if (Tok.isNot(tok::less)) {
310 // Commit to parsing the template-id.
313 if (TemplateNameKind TNK
314 = Actions.ActOnDependentTemplateName(getCurScope(),
315 SS, TemplateKWLoc, TemplateName,
316 ObjectType, EnteringContext,
318 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
319 TemplateName, false))
327 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
332 // So we need to check whether the template-id is a simple-template-id of
333 // the right kind (it should name a type or be dependent), and then
334 // convert it into a type within the nested-name-specifier.
335 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
336 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
337 *MayBePseudoDestructor = true;
342 *LastII = TemplateId->Name;
344 // Consume the template-id token.
347 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
348 SourceLocation CCLoc = ConsumeToken();
350 HasScopeSpecifier = true;
352 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
353 TemplateId->NumArgs);
355 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
357 TemplateId->TemplateKWLoc,
358 TemplateId->Template,
359 TemplateId->TemplateNameLoc,
360 TemplateId->LAngleLoc,
362 TemplateId->RAngleLoc,
365 SourceLocation StartLoc
366 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
367 : TemplateId->TemplateNameLoc;
368 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
374 // The rest of the nested-name-specifier possibilities start with
376 if (Tok.isNot(tok::identifier))
379 IdentifierInfo &II = *Tok.getIdentifierInfo();
381 // nested-name-specifier:
383 // namespace-name '::'
384 // nested-name-specifier identifier '::'
385 Token Next = NextToken();
386 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
389 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
390 // and emit a fixit hint for it.
391 if (Next.is(tok::colon) && !ColonIsSacred) {
392 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
394 // If the token after the colon isn't an identifier, it's still an
395 // error, but they probably meant something else strange so don't
396 // recover like this.
397 PP.LookAhead(1).is(tok::identifier)) {
398 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
399 << FixItHint::CreateReplacement(Next.getLocation(), "::");
400 // Recover as if the user wrote '::'.
401 Next.setKind(tok::coloncolon);
405 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
406 // It is invalid to have :: {, consume the scope qualifier and pretend
407 // like we never saw it.
408 Token Identifier = Tok; // Stash away the identifier.
409 ConsumeToken(); // Eat the identifier, current token is now '::'.
410 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
412 UnconsumeToken(Identifier); // Stick the identifier back.
413 Next = NextToken(); // Point Next at the '{' token.
416 if (Next.is(tok::coloncolon)) {
417 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
418 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
419 *MayBePseudoDestructor = true;
424 const Token &Next2 = GetLookAheadToken(2);
425 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
426 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
427 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
429 << FixItHint::CreateReplacement(Next.getLocation(), ":");
432 ColonColon.setKind(tok::colon);
433 PP.EnterToken(ColonColon);
441 // We have an identifier followed by a '::'. Lookup this name
442 // as the name in a nested-name-specifier.
443 Token Identifier = Tok;
444 SourceLocation IdLoc = ConsumeToken();
445 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
446 "NextToken() not working properly!");
447 Token ColonColon = Tok;
448 SourceLocation CCLoc = ConsumeToken();
450 bool IsCorrectedToColon = false;
451 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
452 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), IdInfo,
454 false, CorrectionFlagPtr)) {
455 // Identifier is not recognized as a nested name, but we can have
456 // mistyped '::' instead of ':'.
457 if (CorrectionFlagPtr && IsCorrectedToColon) {
458 ColonColon.setKind(tok::colon);
460 PP.EnterToken(ColonColon);
464 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
466 HasScopeSpecifier = true;
470 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
472 // nested-name-specifier:
474 if (Next.is(tok::less)) {
476 UnqualifiedId TemplateName;
477 TemplateName.setIdentifier(&II, Tok.getLocation());
478 bool MemberOfUnknownSpecialization;
479 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
480 /*hasTemplateKeyword=*/false,
485 MemberOfUnknownSpecialization)) {
486 // We have found a template name, so annotate this token
487 // with a template-id annotation. We do not permit the
488 // template-id to be translated into a type annotation,
489 // because some clients (e.g., the parsing of class template
490 // specializations) still want to see the original template-id
493 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
494 TemplateName, false))
499 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
500 (IsTypename || IsTemplateArgumentList(1))) {
501 // We have something like t::getAs<T>, where getAs is a
502 // member of an unknown specialization. However, this will only
503 // parse correctly as a template, so suggest the keyword 'template'
504 // before 'getAs' and treat this as a dependent template name.
505 unsigned DiagID = diag::err_missing_dependent_template_keyword;
506 if (getLangOpts().MicrosoftExt)
507 DiagID = diag::warn_missing_dependent_template_keyword;
509 Diag(Tok.getLocation(), DiagID)
511 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
513 if (TemplateNameKind TNK
514 = Actions.ActOnDependentTemplateName(getCurScope(),
515 SS, SourceLocation(),
516 TemplateName, ObjectType,
517 EnteringContext, Template)) {
518 // Consume the identifier.
520 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
521 TemplateName, false))
531 // We don't have any tokens that form the beginning of a
532 // nested-name-specifier, so we're done.
536 // Even if we didn't see any pieces of a nested-name-specifier, we
537 // still check whether there is a tilde in this position, which
538 // indicates a potential pseudo-destructor.
539 if (CheckForDestructor && Tok.is(tok::tilde))
540 *MayBePseudoDestructor = true;
545 ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
546 Token &Replacement) {
547 SourceLocation TemplateKWLoc;
549 if (ParseUnqualifiedId(SS,
550 /*EnteringContext=*/false,
551 /*AllowDestructorName=*/false,
552 /*AllowConstructorName=*/false,
553 /*ObjectType=*/nullptr, TemplateKWLoc, Name))
556 // This is only the direct operand of an & operator if it is not
557 // followed by a postfix-expression suffix.
558 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
559 isAddressOfOperand = false;
561 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
562 Tok.is(tok::l_paren), isAddressOfOperand,
563 nullptr, /*IsInlineAsmIdentifier=*/false,
567 /// ParseCXXIdExpression - Handle id-expression.
574 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
576 /// '::' operator-function-id
579 /// NOTE: The standard specifies that, for qualified-id, the parser does not
582 /// '::' conversion-function-id
583 /// '::' '~' class-name
585 /// This may cause a slight inconsistency on diagnostics:
590 /// :: A :: ~ C(); // Some Sema error about using destructor with a
592 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
595 /// We simplify the parser a bit and make it work like:
598 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
599 /// '::' unqualified-id
601 /// That way Sema can handle and report similar errors for namespaces and the
604 /// The isAddressOfOperand parameter indicates that this id-expression is a
605 /// direct operand of the address-of operator. This is, besides member contexts,
606 /// the only place where a qualified-id naming a non-static class member may
609 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
611 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
612 // '::' unqualified-id
615 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
619 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
620 if (Result.isUnset()) {
621 // If the ExprResult is valid but null, then typo correction suggested a
622 // keyword replacement that needs to be reparsed.
623 UnconsumeToken(Replacement);
624 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
626 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
627 "for a previous keyword suggestion");
631 /// ParseLambdaExpression - Parse a C++11 lambda expression.
633 /// lambda-expression:
634 /// lambda-introducer lambda-declarator[opt] compound-statement
636 /// lambda-introducer:
637 /// '[' lambda-capture[opt] ']'
642 /// capture-default ',' capture-list
650 /// capture-list ',' capture
654 /// init-capture [C++1y]
661 /// init-capture: [C++1y]
662 /// identifier initializer
663 /// '&' identifier initializer
665 /// lambda-declarator:
666 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
667 /// 'mutable'[opt] exception-specification[opt]
668 /// trailing-return-type[opt]
670 ExprResult Parser::ParseLambdaExpression() {
671 // Parse lambda-introducer.
672 LambdaIntroducer Intro;
673 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
675 Diag(Tok, DiagID.getValue());
676 SkipUntil(tok::r_square, StopAtSemi);
677 SkipUntil(tok::l_brace, StopAtSemi);
678 SkipUntil(tok::r_brace, StopAtSemi);
682 return ParseLambdaExpressionAfterIntroducer(Intro);
685 /// TryParseLambdaExpression - Use lookahead and potentially tentative
686 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
689 /// If we are not looking at a lambda expression, returns ExprError().
690 ExprResult Parser::TryParseLambdaExpression() {
691 assert(getLangOpts().CPlusPlus11
692 && Tok.is(tok::l_square)
693 && "Not at the start of a possible lambda expression.");
695 const Token Next = NextToken();
696 if (Next.is(tok::eof)) // Nothing else to lookup here...
699 const Token After = GetLookAheadToken(2);
700 // If lookahead indicates this is a lambda...
701 if (Next.is(tok::r_square) || // []
702 Next.is(tok::equal) || // [=
703 (Next.is(tok::amp) && // [&] or [&,
704 (After.is(tok::r_square) ||
705 After.is(tok::comma))) ||
706 (Next.is(tok::identifier) && // [identifier]
707 After.is(tok::r_square))) {
708 return ParseLambdaExpression();
711 // If lookahead indicates an ObjC message send...
712 // [identifier identifier
713 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
717 // Here, we're stuck: lambda introducers and Objective-C message sends are
718 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
719 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
720 // writing two routines to parse a lambda introducer, just try to parse
721 // a lambda introducer first, and fall back if that fails.
722 // (TryParseLambdaIntroducer never produces any diagnostic output.)
723 LambdaIntroducer Intro;
724 if (TryParseLambdaIntroducer(Intro))
727 return ParseLambdaExpressionAfterIntroducer(Intro);
730 /// \brief Parse a lambda introducer.
731 /// \param Intro A LambdaIntroducer filled in with information about the
732 /// contents of the lambda-introducer.
733 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
734 /// message send and a lambda expression. In this mode, we will
735 /// sometimes skip the initializers for init-captures and not fully
736 /// populate \p Intro. This flag will be set to \c true if we do so.
737 /// \return A DiagnosticID if it hit something unexpected. The location for
738 /// the diagnostic is that of the current token.
739 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
740 bool *SkippedInits) {
741 typedef Optional<unsigned> DiagResult;
743 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
744 BalancedDelimiterTracker T(*this, tok::l_square);
747 Intro.Range.setBegin(T.getOpenLocation());
751 // Parse capture-default.
752 if (Tok.is(tok::amp) &&
753 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
754 Intro.Default = LCD_ByRef;
755 Intro.DefaultLoc = ConsumeToken();
757 } else if (Tok.is(tok::equal)) {
758 Intro.Default = LCD_ByCopy;
759 Intro.DefaultLoc = ConsumeToken();
763 while (Tok.isNot(tok::r_square)) {
765 if (Tok.isNot(tok::comma)) {
766 // Provide a completion for a lambda introducer here. Except
767 // in Objective-C, where this is Almost Surely meant to be a message
768 // send. In that case, fail here and let the ObjC message
769 // expression parser perform the completion.
770 if (Tok.is(tok::code_completion) &&
771 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
772 !Intro.Captures.empty())) {
773 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
774 /*AfterAmpersand=*/false);
779 return DiagResult(diag::err_expected_comma_or_rsquare);
784 if (Tok.is(tok::code_completion)) {
785 // If we're in Objective-C++ and we have a bare '[', then this is more
786 // likely to be a message receiver.
787 if (getLangOpts().ObjC1 && first)
788 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
790 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
791 /*AfterAmpersand=*/false);
799 LambdaCaptureKind Kind = LCK_ByCopy;
800 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
802 IdentifierInfo *Id = nullptr;
803 SourceLocation EllipsisLoc;
806 if (Tok.is(tok::star)) {
807 Loc = ConsumeToken();
808 if (Tok.is(tok::kw_this)) {
812 return DiagResult(diag::err_expected_star_this_capture);
814 } else if (Tok.is(tok::kw_this)) {
816 Loc = ConsumeToken();
818 if (Tok.is(tok::amp)) {
822 if (Tok.is(tok::code_completion)) {
823 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
824 /*AfterAmpersand=*/true);
830 if (Tok.is(tok::identifier)) {
831 Id = Tok.getIdentifierInfo();
832 Loc = ConsumeToken();
833 } else if (Tok.is(tok::kw_this)) {
834 // FIXME: If we want to suggest a fixit here, will need to return more
835 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
836 // Clear()ed to prevent emission in case of tentative parsing?
837 return DiagResult(diag::err_this_captured_by_reference);
839 return DiagResult(diag::err_expected_capture);
842 if (Tok.is(tok::l_paren)) {
843 BalancedDelimiterTracker Parens(*this, tok::l_paren);
844 Parens.consumeOpen();
846 InitKind = LambdaCaptureInitKind::DirectInit;
852 *SkippedInits = true;
853 } else if (ParseExpressionList(Exprs, Commas)) {
857 Parens.consumeClose();
858 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
859 Parens.getCloseLocation(),
862 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
863 // Each lambda init-capture forms its own full expression, which clears
864 // Actions.MaybeODRUseExprs. So create an expression evaluation context
865 // to save the necessary state, and restore it later.
866 EnterExpressionEvaluationContext EC(Actions,
867 Sema::PotentiallyEvaluated);
869 if (TryConsumeToken(tok::equal))
870 InitKind = LambdaCaptureInitKind::CopyInit;
872 InitKind = LambdaCaptureInitKind::ListInit;
875 Init = ParseInitializer();
876 } else if (Tok.is(tok::l_brace)) {
877 BalancedDelimiterTracker Braces(*this, tok::l_brace);
878 Braces.consumeOpen();
880 *SkippedInits = true;
882 // We're disambiguating this:
886 // We need to find the end of the following expression in order to
887 // determine whether this is an Obj-C message send's receiver, a
888 // C99 designator, or a lambda init-capture.
890 // Parse the expression to find where it ends, and annotate it back
891 // onto the tokens. We would have parsed this expression the same way
892 // in either case: both the RHS of an init-capture and the RHS of an
893 // assignment expression are parsed as an initializer-clause, and in
894 // neither case can anything be added to the scope between the '[' and
897 // FIXME: This is horrible. Adding a mechanism to skip an expression
898 // would be much cleaner.
899 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
900 // that instead. (And if we see a ':' with no matching '?', we can
901 // classify this as an Obj-C message send.)
902 SourceLocation StartLoc = Tok.getLocation();
903 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
904 Init = ParseInitializer();
905 if (!Init.isInvalid())
906 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
908 if (Tok.getLocation() != StartLoc) {
909 // Back out the lexing of the token after the initializer.
910 PP.RevertCachedTokens(1);
912 // Replace the consumed tokens with an appropriate annotation.
913 Tok.setLocation(StartLoc);
914 Tok.setKind(tok::annot_primary_expr);
915 setExprAnnotation(Tok, Init);
916 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
917 PP.AnnotateCachedTokens(Tok);
919 // Consume the annotated initializer.
924 TryConsumeToken(tok::ellipsis, EllipsisLoc);
926 // If this is an init capture, process the initialization expression
927 // right away. For lambda init-captures such as the following:
929 // auto L = [i = x+1](int a) {
931 // &k = x](char b) { };
933 // keep in mind that each lambda init-capture has to have:
934 // - its initialization expression executed in the context
935 // of the enclosing/parent decl-context.
936 // - but the variable itself has to be 'injected' into the
937 // decl-context of its lambda's call-operator (which has
938 // not yet been created).
939 // Each init-expression is a full-expression that has to get
940 // Sema-analyzed (for capturing etc.) before its lambda's
941 // call-operator's decl-context, scope & scopeinfo are pushed on their
942 // respective stacks. Thus if any variable is odr-used in the init-capture
943 // it will correctly get captured in the enclosing lambda, if one exists.
944 // The init-variables above are created later once the lambdascope and
945 // call-operators decl-context is pushed onto its respective stack.
947 // Since the lambda init-capture's initializer expression occurs in the
948 // context of the enclosing function or lambda, therefore we can not wait
949 // till a lambda scope has been pushed on before deciding whether the
950 // variable needs to be captured. We also need to process all
951 // lvalue-to-rvalue conversions and discarded-value conversions,
952 // so that we can avoid capturing certain constant variables.
956 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
957 // return [y = x](int i) { <-- don't capture by enclosing lambda
962 // If x was not const, the second use would require 'L' to capture, and
963 // that would be an error.
965 ParsedType InitCaptureType;
966 if (Init.isUsable()) {
967 // Get the pointer and store it in an lvalue, so we can use it as an
969 Expr *InitExpr = Init.get();
970 // This performs any lvalue-to-rvalue conversions if necessary, which
971 // can affect what gets captured in the containing decl-context.
972 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
973 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
976 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
981 Intro.Range.setEnd(T.getCloseLocation());
985 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
987 /// Returns true if it hit something unexpected.
988 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
989 TentativeParsingAction PA(*this);
991 bool SkippedInits = false;
992 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
1000 // Parse it again, but this time parse the init-captures too.
1002 Intro = LambdaIntroducer();
1003 DiagID = ParseLambdaIntroducer(Intro);
1004 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1013 tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1014 SourceLocation &ConstexprLoc,
1015 SourceLocation &DeclEndLoc) {
1016 assert(MutableLoc.isInvalid());
1017 assert(ConstexprLoc.isInvalid());
1018 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1019 // to the final of those locations. Emit an error if we have multiple
1020 // copies of those keywords and recover.
1023 switch (P.getCurToken().getKind()) {
1024 case tok::kw_mutable: {
1025 if (MutableLoc.isValid()) {
1026 P.Diag(P.getCurToken().getLocation(),
1027 diag::err_lambda_decl_specifier_repeated)
1028 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1030 MutableLoc = P.ConsumeToken();
1031 DeclEndLoc = MutableLoc;
1034 case tok::kw_constexpr:
1035 if (ConstexprLoc.isValid()) {
1036 P.Diag(P.getCurToken().getLocation(),
1037 diag::err_lambda_decl_specifier_repeated)
1038 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1040 ConstexprLoc = P.ConsumeToken();
1041 DeclEndLoc = ConstexprLoc;
1050 addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1052 if (ConstexprLoc.isValid()) {
1053 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus1z
1054 ? diag::ext_constexpr_on_lambda_cxx1z
1055 : diag::warn_cxx14_compat_constexpr_on_lambda);
1056 const char *PrevSpec = nullptr;
1057 unsigned DiagID = 0;
1058 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1059 assert(PrevSpec == nullptr && DiagID == 0 &&
1060 "Constexpr cannot have been set previously!");
1064 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1066 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1067 LambdaIntroducer &Intro) {
1068 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1069 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1071 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1072 "lambda expression parsing");
1076 // FIXME: Call into Actions to add any init-capture declarations to the
1077 // scope while parsing the lambda-declarator and compound-statement.
1079 // Parse lambda-declarator[opt].
1080 DeclSpec DS(AttrFactory);
1081 Declarator D(DS, Declarator::LambdaExprContext);
1082 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1083 Actions.PushLambdaScope();
1085 ParsedAttributes Attr(AttrFactory);
1086 SourceLocation DeclLoc = Tok.getLocation();
1087 if (getLangOpts().CUDA) {
1088 // In CUDA code, GNU attributes are allowed to appear immediately after the
1089 // "[...]", even if there is no "(...)" before the lambda body.
1090 MaybeParseGNUAttributes(D);
1093 // Helper to emit a warning if we see a CUDA host/device/global attribute
1094 // after '(...)'. nvcc doesn't accept this.
1095 auto WarnIfHasCUDATargetAttr = [&] {
1096 if (getLangOpts().CUDA)
1097 for (auto *A = Attr.getList(); A != nullptr; A = A->getNext())
1098 if (A->getKind() == AttributeList::AT_CUDADevice ||
1099 A->getKind() == AttributeList::AT_CUDAHost ||
1100 A->getKind() == AttributeList::AT_CUDAGlobal)
1101 Diag(A->getLoc(), diag::warn_cuda_attr_lambda_position)
1102 << A->getName()->getName();
1105 TypeResult TrailingReturnType;
1106 if (Tok.is(tok::l_paren)) {
1107 ParseScope PrototypeScope(this,
1108 Scope::FunctionPrototypeScope |
1109 Scope::FunctionDeclarationScope |
1112 BalancedDelimiterTracker T(*this, tok::l_paren);
1114 SourceLocation LParenLoc = T.getOpenLocation();
1116 // Parse parameter-declaration-clause.
1117 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1118 SourceLocation EllipsisLoc;
1120 if (Tok.isNot(tok::r_paren)) {
1121 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1122 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1123 // For a generic lambda, each 'auto' within the parameter declaration
1124 // clause creates a template type parameter, so increment the depth.
1125 if (Actions.getCurGenericLambda())
1126 ++CurTemplateDepthTracker;
1129 SourceLocation RParenLoc = T.getCloseLocation();
1130 SourceLocation DeclEndLoc = RParenLoc;
1132 // GNU-style attributes must be parsed before the mutable specifier to be
1133 // compatible with GCC.
1134 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1136 // MSVC-style attributes must be parsed before the mutable specifier to be
1137 // compatible with MSVC.
1138 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1140 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
1141 SourceLocation MutableLoc;
1142 SourceLocation ConstexprLoc;
1143 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1146 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1148 // Parse exception-specification[opt].
1149 ExceptionSpecificationType ESpecType = EST_None;
1150 SourceRange ESpecRange;
1151 SmallVector<ParsedType, 2> DynamicExceptions;
1152 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1153 ExprResult NoexceptExpr;
1154 CachedTokens *ExceptionSpecTokens;
1155 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1158 DynamicExceptionRanges,
1160 ExceptionSpecTokens);
1162 if (ESpecType != EST_None)
1163 DeclEndLoc = ESpecRange.getEnd();
1165 // Parse attribute-specifier[opt].
1166 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1168 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1170 // Parse trailing-return-type[opt].
1171 if (Tok.is(tok::arrow)) {
1172 FunLocalRangeEnd = Tok.getLocation();
1174 TrailingReturnType = ParseTrailingReturnType(Range);
1175 if (Range.getEnd().isValid())
1176 DeclEndLoc = Range.getEnd();
1179 PrototypeScope.Exit();
1181 WarnIfHasCUDATargetAttr();
1183 SourceLocation NoLoc;
1184 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1185 /*isAmbiguous=*/false,
1187 ParamInfo.data(), ParamInfo.size(),
1188 EllipsisLoc, RParenLoc,
1189 DS.getTypeQualifiers(),
1190 /*RefQualifierIsLValueRef=*/true,
1191 /*RefQualifierLoc=*/NoLoc,
1192 /*ConstQualifierLoc=*/NoLoc,
1193 /*VolatileQualifierLoc=*/NoLoc,
1194 /*RestrictQualifierLoc=*/NoLoc,
1196 ESpecType, ESpecRange,
1197 DynamicExceptions.data(),
1198 DynamicExceptionRanges.data(),
1199 DynamicExceptions.size(),
1200 NoexceptExpr.isUsable() ?
1201 NoexceptExpr.get() : nullptr,
1202 /*ExceptionSpecTokens*/nullptr,
1203 /*DeclsInPrototype=*/None,
1204 LParenLoc, FunLocalRangeEnd, D,
1205 TrailingReturnType),
1207 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1208 tok::kw_constexpr) ||
1209 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1210 // It's common to forget that one needs '()' before 'mutable', an attribute
1211 // specifier, or the result type. Deal with this.
1212 unsigned TokKind = 0;
1213 switch (Tok.getKind()) {
1214 case tok::kw_mutable: TokKind = 0; break;
1215 case tok::arrow: TokKind = 1; break;
1216 case tok::kw___attribute:
1217 case tok::l_square: TokKind = 2; break;
1218 case tok::kw_constexpr: TokKind = 3; break;
1219 default: llvm_unreachable("Unknown token kind");
1222 Diag(Tok, diag::err_lambda_missing_parens)
1224 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1225 SourceLocation DeclEndLoc = DeclLoc;
1227 // GNU-style attributes must be parsed before the mutable specifier to be
1228 // compatible with GCC.
1229 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1231 // Parse 'mutable', if it's there.
1232 SourceLocation MutableLoc;
1233 if (Tok.is(tok::kw_mutable)) {
1234 MutableLoc = ConsumeToken();
1235 DeclEndLoc = MutableLoc;
1238 // Parse attribute-specifier[opt].
1239 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1241 // Parse the return type, if there is one.
1242 if (Tok.is(tok::arrow)) {
1244 TrailingReturnType = ParseTrailingReturnType(Range);
1245 if (Range.getEnd().isValid())
1246 DeclEndLoc = Range.getEnd();
1249 WarnIfHasCUDATargetAttr();
1251 SourceLocation NoLoc;
1252 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1253 /*isAmbiguous=*/false,
1254 /*LParenLoc=*/NoLoc,
1257 /*EllipsisLoc=*/NoLoc,
1258 /*RParenLoc=*/NoLoc,
1260 /*RefQualifierIsLValueRef=*/true,
1261 /*RefQualifierLoc=*/NoLoc,
1262 /*ConstQualifierLoc=*/NoLoc,
1263 /*VolatileQualifierLoc=*/NoLoc,
1264 /*RestrictQualifierLoc=*/NoLoc,
1267 /*ESpecRange=*/SourceRange(),
1268 /*Exceptions=*/nullptr,
1269 /*ExceptionRanges=*/nullptr,
1270 /*NumExceptions=*/0,
1271 /*NoexceptExpr=*/nullptr,
1272 /*ExceptionSpecTokens=*/nullptr,
1273 /*DeclsInPrototype=*/None,
1274 DeclLoc, DeclEndLoc, D,
1275 TrailingReturnType),
1279 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1281 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
1282 ParseScope BodyScope(this, ScopeFlags);
1284 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1286 // Parse compound-statement.
1287 if (!Tok.is(tok::l_brace)) {
1288 Diag(Tok, diag::err_expected_lambda_body);
1289 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1293 StmtResult Stmt(ParseCompoundStatementBody());
1296 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1297 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1299 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1303 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1306 /// postfix-expression: [C++ 5.2p1]
1307 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1308 /// 'static_cast' '<' type-name '>' '(' expression ')'
1309 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1310 /// 'const_cast' '<' type-name '>' '(' expression ')'
1312 ExprResult Parser::ParseCXXCasts() {
1313 tok::TokenKind Kind = Tok.getKind();
1314 const char *CastName = nullptr; // For error messages
1317 default: llvm_unreachable("Unknown C++ cast!");
1318 case tok::kw_const_cast: CastName = "const_cast"; break;
1319 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1320 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1321 case tok::kw_static_cast: CastName = "static_cast"; break;
1324 SourceLocation OpLoc = ConsumeToken();
1325 SourceLocation LAngleBracketLoc = Tok.getLocation();
1327 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1328 // diagnose error, suggest fix, and recover parsing.
1329 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1330 Token Next = NextToken();
1331 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1332 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1335 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1338 // Parse the common declaration-specifiers piece.
1339 DeclSpec DS(AttrFactory);
1340 ParseSpecifierQualifierList(DS);
1342 // Parse the abstract-declarator, if present.
1343 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1344 ParseDeclarator(DeclaratorInfo);
1346 SourceLocation RAngleBracketLoc = Tok.getLocation();
1348 if (ExpectAndConsume(tok::greater))
1349 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1351 SourceLocation LParenLoc, RParenLoc;
1352 BalancedDelimiterTracker T(*this, tok::l_paren);
1354 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1357 ExprResult Result = ParseExpression();
1362 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1363 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1364 LAngleBracketLoc, DeclaratorInfo,
1366 T.getOpenLocation(), Result.get(),
1367 T.getCloseLocation());
1372 /// ParseCXXTypeid - This handles the C++ typeid expression.
1374 /// postfix-expression: [C++ 5.2p1]
1375 /// 'typeid' '(' expression ')'
1376 /// 'typeid' '(' type-id ')'
1378 ExprResult Parser::ParseCXXTypeid() {
1379 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1381 SourceLocation OpLoc = ConsumeToken();
1382 SourceLocation LParenLoc, RParenLoc;
1383 BalancedDelimiterTracker T(*this, tok::l_paren);
1385 // typeid expressions are always parenthesized.
1386 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1388 LParenLoc = T.getOpenLocation();
1392 // C++0x [expr.typeid]p3:
1393 // When typeid is applied to an expression other than an lvalue of a
1394 // polymorphic class type [...] The expression is an unevaluated
1395 // operand (Clause 5).
1397 // Note that we can't tell whether the expression is an lvalue of a
1398 // polymorphic class type until after we've parsed the expression; we
1399 // speculatively assume the subexpression is unevaluated, and fix it up
1402 // We enter the unevaluated context before trying to determine whether we
1403 // have a type-id, because the tentative parse logic will try to resolve
1404 // names, and must treat them as unevaluated.
1405 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1406 Sema::ReuseLambdaContextDecl);
1408 if (isTypeIdInParens()) {
1409 TypeResult Ty = ParseTypeName();
1413 RParenLoc = T.getCloseLocation();
1414 if (Ty.isInvalid() || RParenLoc.isInvalid())
1417 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1418 Ty.get().getAsOpaquePtr(), RParenLoc);
1420 Result = ParseExpression();
1423 if (Result.isInvalid())
1424 SkipUntil(tok::r_paren, StopAtSemi);
1427 RParenLoc = T.getCloseLocation();
1428 if (RParenLoc.isInvalid())
1431 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1432 Result.get(), RParenLoc);
1439 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1441 /// '__uuidof' '(' expression ')'
1442 /// '__uuidof' '(' type-id ')'
1444 ExprResult Parser::ParseCXXUuidof() {
1445 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1447 SourceLocation OpLoc = ConsumeToken();
1448 BalancedDelimiterTracker T(*this, tok::l_paren);
1450 // __uuidof expressions are always parenthesized.
1451 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1456 if (isTypeIdInParens()) {
1457 TypeResult Ty = ParseTypeName();
1465 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1466 Ty.get().getAsOpaquePtr(),
1467 T.getCloseLocation());
1469 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1470 Result = ParseExpression();
1473 if (Result.isInvalid())
1474 SkipUntil(tok::r_paren, StopAtSemi);
1478 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1480 Result.get(), T.getCloseLocation());
1487 /// \brief Parse a C++ pseudo-destructor expression after the base,
1488 /// . or -> operator, and nested-name-specifier have already been
1491 /// postfix-expression: [C++ 5.2]
1492 /// postfix-expression . pseudo-destructor-name
1493 /// postfix-expression -> pseudo-destructor-name
1495 /// pseudo-destructor-name:
1496 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1497 /// ::[opt] nested-name-specifier template simple-template-id ::
1499 /// ::[opt] nested-name-specifier[opt] ~type-name
1502 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1503 tok::TokenKind OpKind,
1505 ParsedType ObjectType) {
1506 // We're parsing either a pseudo-destructor-name or a dependent
1507 // member access that has the same form as a
1508 // pseudo-destructor-name. We parse both in the same way and let
1509 // the action model sort them out.
1511 // Note that the ::[opt] nested-name-specifier[opt] has already
1512 // been parsed, and if there was a simple-template-id, it has
1513 // been coalesced into a template-id annotation token.
1514 UnqualifiedId FirstTypeName;
1515 SourceLocation CCLoc;
1516 if (Tok.is(tok::identifier)) {
1517 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1519 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1520 CCLoc = ConsumeToken();
1521 } else if (Tok.is(tok::annot_template_id)) {
1522 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1523 // store it in the pseudo-dtor node (to be used when instantiating it).
1524 FirstTypeName.setTemplateId(
1525 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1527 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1528 CCLoc = ConsumeToken();
1530 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1534 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1535 SourceLocation TildeLoc = ConsumeToken();
1537 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1538 DeclSpec DS(AttrFactory);
1539 ParseDecltypeSpecifier(DS);
1540 if (DS.getTypeSpecType() == TST_error)
1542 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1546 if (!Tok.is(tok::identifier)) {
1547 Diag(Tok, diag::err_destructor_tilde_identifier);
1551 // Parse the second type.
1552 UnqualifiedId SecondTypeName;
1553 IdentifierInfo *Name = Tok.getIdentifierInfo();
1554 SourceLocation NameLoc = ConsumeToken();
1555 SecondTypeName.setIdentifier(Name, NameLoc);
1557 // If there is a '<', the second type name is a template-id. Parse
1559 if (Tok.is(tok::less) &&
1560 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1562 false, ObjectType, SecondTypeName,
1563 /*AssumeTemplateName=*/true))
1566 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1567 SS, FirstTypeName, CCLoc, TildeLoc,
1571 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1573 /// boolean-literal: [C++ 2.13.5]
1576 ExprResult Parser::ParseCXXBoolLiteral() {
1577 tok::TokenKind Kind = Tok.getKind();
1578 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1581 /// ParseThrowExpression - This handles the C++ throw expression.
1583 /// throw-expression: [C++ 15]
1584 /// 'throw' assignment-expression[opt]
1585 ExprResult Parser::ParseThrowExpression() {
1586 assert(Tok.is(tok::kw_throw) && "Not throw!");
1587 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1589 // If the current token isn't the start of an assignment-expression,
1590 // then the expression is not present. This handles things like:
1591 // "C ? throw : (void)42", which is crazy but legal.
1592 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1599 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1602 ExprResult Expr(ParseAssignmentExpression());
1603 if (Expr.isInvalid()) return Expr;
1604 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1608 /// \brief Parse the C++ Coroutines co_yield expression.
1610 /// co_yield-expression:
1611 /// 'co_yield' assignment-expression[opt]
1612 ExprResult Parser::ParseCoyieldExpression() {
1613 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1615 SourceLocation Loc = ConsumeToken();
1616 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1617 : ParseAssignmentExpression();
1618 if (!Expr.isInvalid())
1619 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1623 /// ParseCXXThis - This handles the C++ 'this' pointer.
1625 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1626 /// a non-lvalue expression whose value is the address of the object for which
1627 /// the function is called.
1628 ExprResult Parser::ParseCXXThis() {
1629 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1630 SourceLocation ThisLoc = ConsumeToken();
1631 return Actions.ActOnCXXThis(ThisLoc);
1634 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1635 /// Can be interpreted either as function-style casting ("int(x)")
1636 /// or class type construction ("ClassType(x,y,z)")
1637 /// or creation of a value-initialized type ("int()").
1638 /// See [C++ 5.2.3].
1640 /// postfix-expression: [C++ 5.2p1]
1641 /// simple-type-specifier '(' expression-list[opt] ')'
1642 /// [C++0x] simple-type-specifier braced-init-list
1643 /// typename-specifier '(' expression-list[opt] ')'
1644 /// [C++0x] typename-specifier braced-init-list
1647 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1648 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1649 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1651 assert((Tok.is(tok::l_paren) ||
1652 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1653 && "Expected '(' or '{'!");
1655 if (Tok.is(tok::l_brace)) {
1656 ExprResult Init = ParseBraceInitializer();
1657 if (Init.isInvalid())
1659 Expr *InitList = Init.get();
1660 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1661 MultiExprArg(&InitList, 1),
1664 BalancedDelimiterTracker T(*this, tok::l_paren);
1668 CommaLocsTy CommaLocs;
1670 if (Tok.isNot(tok::r_paren)) {
1671 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1672 Actions.CodeCompleteConstructor(getCurScope(),
1673 TypeRep.get()->getCanonicalTypeInternal(),
1674 DS.getLocEnd(), Exprs);
1676 SkipUntil(tok::r_paren, StopAtSemi);
1684 // TypeRep could be null, if it references an invalid typedef.
1688 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1689 "Unexpected number of commas!");
1690 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1692 T.getCloseLocation());
1696 /// ParseCXXCondition - if/switch/while condition expression.
1700 /// type-specifier-seq declarator '=' assignment-expression
1701 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1702 /// [C++11] type-specifier-seq declarator braced-init-list
1703 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1704 /// '=' assignment-expression
1706 /// In C++1z, a condition may in some contexts be preceded by an
1707 /// optional init-statement. This function will parse that too.
1709 /// \param InitStmt If non-null, an init-statement is permitted, and if present
1710 /// will be parsed and stored here.
1712 /// \param Loc The location of the start of the statement that requires this
1713 /// condition, e.g., the "for" in a for loop.
1715 /// \returns The parsed condition.
1716 Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1718 Sema::ConditionKind CK) {
1719 if (Tok.is(tok::code_completion)) {
1720 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1722 return Sema::ConditionError();
1725 ParsedAttributesWithRange attrs(AttrFactory);
1726 MaybeParseCXX11Attributes(attrs);
1728 // Determine what kind of thing we have.
1729 switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
1730 case ConditionOrInitStatement::Expression: {
1731 ProhibitAttributes(attrs);
1733 // Parse the expression.
1734 ExprResult Expr = ParseExpression(); // expression
1735 if (Expr.isInvalid())
1736 return Sema::ConditionError();
1738 if (InitStmt && Tok.is(tok::semi)) {
1739 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1741 return ParseCXXCondition(nullptr, Loc, CK);
1744 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
1747 case ConditionOrInitStatement::InitStmtDecl: {
1748 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
1749 ? diag::warn_cxx14_compat_init_statement
1750 : diag::ext_init_statement)
1751 << (CK == Sema::ConditionKind::Switch);
1752 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1753 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1754 Declarator::InitStmtContext, DeclEnd, attrs, /*RequireSemi=*/true);
1755 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1756 return ParseCXXCondition(nullptr, Loc, CK);
1759 case ConditionOrInitStatement::ConditionDecl:
1760 case ConditionOrInitStatement::Error:
1764 // type-specifier-seq
1765 DeclSpec DS(AttrFactory);
1766 DS.takeAttributesFrom(attrs);
1767 ParseSpecifierQualifierList(DS, AS_none, DSC_condition);
1770 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1771 ParseDeclarator(DeclaratorInfo);
1773 // simple-asm-expr[opt]
1774 if (Tok.is(tok::kw_asm)) {
1776 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1777 if (AsmLabel.isInvalid()) {
1778 SkipUntil(tok::semi, StopAtSemi);
1779 return Sema::ConditionError();
1781 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1782 DeclaratorInfo.SetRangeEnd(Loc);
1785 // If attributes are present, parse them.
1786 MaybeParseGNUAttributes(DeclaratorInfo);
1788 // Type-check the declaration itself.
1789 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1791 if (Dcl.isInvalid())
1792 return Sema::ConditionError();
1793 Decl *DeclOut = Dcl.get();
1795 // '=' assignment-expression
1796 // If a '==' or '+=' is found, suggest a fixit to '='.
1797 bool CopyInitialization = isTokenEqualOrEqualTypo();
1798 if (CopyInitialization)
1801 ExprResult InitExpr = ExprError();
1802 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1803 Diag(Tok.getLocation(),
1804 diag::warn_cxx98_compat_generalized_initializer_lists);
1805 InitExpr = ParseBraceInitializer();
1806 } else if (CopyInitialization) {
1807 InitExpr = ParseAssignmentExpression();
1808 } else if (Tok.is(tok::l_paren)) {
1809 // This was probably an attempt to initialize the variable.
1810 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1811 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1812 RParen = ConsumeParen();
1813 Diag(DeclOut->getLocation(),
1814 diag::err_expected_init_in_condition_lparen)
1815 << SourceRange(LParen, RParen);
1817 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
1820 if (!InitExpr.isInvalid())
1821 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
1823 Actions.ActOnInitializerError(DeclOut);
1825 Actions.FinalizeDeclaration(DeclOut);
1826 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
1829 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1830 /// This should only be called when the current token is known to be part of
1831 /// simple-type-specifier.
1833 /// simple-type-specifier:
1834 /// '::'[opt] nested-name-specifier[opt] type-name
1835 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1847 /// [GNU] typeof-specifier
1848 /// [C++0x] auto [TODO]
1855 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1856 DS.SetRangeStart(Tok.getLocation());
1857 const char *PrevSpec;
1859 SourceLocation Loc = Tok.getLocation();
1860 const clang::PrintingPolicy &Policy =
1861 Actions.getASTContext().getPrintingPolicy();
1863 switch (Tok.getKind()) {
1864 case tok::identifier: // foo::bar
1865 case tok::coloncolon: // ::foo::bar
1866 llvm_unreachable("Annotation token should already be formed!");
1868 llvm_unreachable("Not a simple-type-specifier token!");
1871 case tok::annot_typename: {
1872 if (getTypeAnnotation(Tok))
1873 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1874 getTypeAnnotation(Tok), Policy);
1876 DS.SetTypeSpecError();
1878 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1881 DS.Finish(Actions, Policy);
1887 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1890 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1892 case tok::kw___int64:
1893 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1895 case tok::kw_signed:
1896 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1898 case tok::kw_unsigned:
1899 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1902 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1905 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1908 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1910 case tok::kw___int128:
1911 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1914 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1917 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1919 case tok::kw_double:
1920 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1922 case tok::kw___float128:
1923 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1925 case tok::kw_wchar_t:
1926 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1928 case tok::kw_char16_t:
1929 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1931 case tok::kw_char32_t:
1932 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1935 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1937 case tok::annot_decltype:
1938 case tok::kw_decltype:
1939 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1940 return DS.Finish(Actions, Policy);
1942 // GNU typeof support.
1943 case tok::kw_typeof:
1944 ParseTypeofSpecifier(DS);
1945 DS.Finish(Actions, Policy);
1948 if (Tok.is(tok::annot_typename))
1949 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1951 DS.SetRangeEnd(Tok.getLocation());
1953 DS.Finish(Actions, Policy);
1956 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1957 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1958 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1959 /// by parsing the type-specifier-seq, because these sequences are
1960 /// typically followed by some form of declarator. Returns true and
1961 /// emits diagnostics if this is not a type-specifier-seq, false
1964 /// type-specifier-seq: [C++ 8.1]
1965 /// type-specifier type-specifier-seq[opt]
1967 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1968 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1969 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
1973 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1976 /// This routine is invoked when a '<' is encountered after an identifier or
1977 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1978 /// whether the unqualified-id is actually a template-id. This routine will
1979 /// then parse the template arguments and form the appropriate template-id to
1980 /// return to the caller.
1982 /// \param SS the nested-name-specifier that precedes this template-id, if
1983 /// we're actually parsing a qualified-id.
1985 /// \param Name for constructor and destructor names, this is the actual
1986 /// identifier that may be a template-name.
1988 /// \param NameLoc the location of the class-name in a constructor or
1991 /// \param EnteringContext whether we're entering the scope of the
1992 /// nested-name-specifier.
1994 /// \param ObjectType if this unqualified-id occurs within a member access
1995 /// expression, the type of the base object whose member is being accessed.
1997 /// \param Id as input, describes the template-name or operator-function-id
1998 /// that precedes the '<'. If template arguments were parsed successfully,
1999 /// will be updated with the template-id.
2001 /// \param AssumeTemplateId When true, this routine will assume that the name
2002 /// refers to a template without performing name lookup to verify.
2004 /// \returns true if a parse error occurred, false otherwise.
2005 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2006 SourceLocation TemplateKWLoc,
2007 IdentifierInfo *Name,
2008 SourceLocation NameLoc,
2009 bool EnteringContext,
2010 ParsedType ObjectType,
2012 bool AssumeTemplateId) {
2013 assert((AssumeTemplateId || Tok.is(tok::less)) &&
2014 "Expected '<' to finish parsing a template-id");
2016 TemplateTy Template;
2017 TemplateNameKind TNK = TNK_Non_template;
2018 switch (Id.getKind()) {
2019 case UnqualifiedId::IK_Identifier:
2020 case UnqualifiedId::IK_OperatorFunctionId:
2021 case UnqualifiedId::IK_LiteralOperatorId:
2022 if (AssumeTemplateId) {
2023 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
2024 Id, ObjectType, EnteringContext,
2026 if (TNK == TNK_Non_template)
2029 bool MemberOfUnknownSpecialization;
2030 TNK = Actions.isTemplateName(getCurScope(), SS,
2031 TemplateKWLoc.isValid(), Id,
2032 ObjectType, EnteringContext, Template,
2033 MemberOfUnknownSpecialization);
2035 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2036 ObjectType && IsTemplateArgumentList()) {
2037 // We have something like t->getAs<T>(), where getAs is a
2038 // member of an unknown specialization. However, this will only
2039 // parse correctly as a template, so suggest the keyword 'template'
2040 // before 'getAs' and treat this as a dependent template name.
2042 if (Id.getKind() == UnqualifiedId::IK_Identifier)
2043 Name = Id.Identifier->getName();
2046 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
2047 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2049 Name += Id.Identifier->getName();
2051 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2053 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2054 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2055 SS, TemplateKWLoc, Id,
2056 ObjectType, EnteringContext,
2058 if (TNK == TNK_Non_template)
2064 case UnqualifiedId::IK_ConstructorName: {
2065 UnqualifiedId TemplateName;
2066 bool MemberOfUnknownSpecialization;
2067 TemplateName.setIdentifier(Name, NameLoc);
2068 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2069 TemplateName, ObjectType,
2070 EnteringContext, Template,
2071 MemberOfUnknownSpecialization);
2075 case UnqualifiedId::IK_DestructorName: {
2076 UnqualifiedId TemplateName;
2077 bool MemberOfUnknownSpecialization;
2078 TemplateName.setIdentifier(Name, NameLoc);
2080 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2081 SS, TemplateKWLoc, TemplateName,
2082 ObjectType, EnteringContext,
2084 if (TNK == TNK_Non_template)
2087 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2088 TemplateName, ObjectType,
2089 EnteringContext, Template,
2090 MemberOfUnknownSpecialization);
2092 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2093 Diag(NameLoc, diag::err_destructor_template_id)
2094 << Name << SS.getRange();
2105 if (TNK == TNK_Non_template)
2108 // Parse the enclosed template argument list.
2109 SourceLocation LAngleLoc, RAngleLoc;
2110 TemplateArgList TemplateArgs;
2111 if (Tok.is(tok::less) &&
2112 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
2113 SS, true, LAngleLoc,
2118 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
2119 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2120 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
2121 // Form a parsed representation of the template-id to be stored in the
2123 TemplateIdAnnotation *TemplateId
2124 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
2126 // FIXME: Store name for literal operator too.
2127 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2128 TemplateId->Name = Id.Identifier;
2129 TemplateId->Operator = OO_None;
2130 TemplateId->TemplateNameLoc = Id.StartLocation;
2132 TemplateId->Name = nullptr;
2133 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2134 TemplateId->TemplateNameLoc = Id.StartLocation;
2137 TemplateId->SS = SS;
2138 TemplateId->TemplateKWLoc = TemplateKWLoc;
2139 TemplateId->Template = Template;
2140 TemplateId->Kind = TNK;
2141 TemplateId->LAngleLoc = LAngleLoc;
2142 TemplateId->RAngleLoc = RAngleLoc;
2143 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
2144 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
2145 Arg != ArgEnd; ++Arg)
2146 Args[Arg] = TemplateArgs[Arg];
2148 Id.setTemplateId(TemplateId);
2152 // Bundle the template arguments together.
2153 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2155 // Constructor and destructor names.
2157 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2159 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2160 /*IsCtorOrDtorName=*/true);
2161 if (Type.isInvalid())
2164 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2165 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2167 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2172 /// \brief Parse an operator-function-id or conversion-function-id as part
2173 /// of a C++ unqualified-id.
2175 /// This routine is responsible only for parsing the operator-function-id or
2176 /// conversion-function-id; it does not handle template arguments in any way.
2179 /// operator-function-id: [C++ 13.5]
2180 /// 'operator' operator
2182 /// operator: one of
2183 /// new delete new[] delete[]
2184 /// + - * / % ^ & | ~
2185 /// ! = < > += -= *= /= %=
2186 /// ^= &= |= << >> >>= <<= == !=
2187 /// <= >= && || ++ -- , ->* ->
2190 /// conversion-function-id: [C++ 12.3.2]
2191 /// operator conversion-type-id
2193 /// conversion-type-id:
2194 /// type-specifier-seq conversion-declarator[opt]
2196 /// conversion-declarator:
2197 /// ptr-operator conversion-declarator[opt]
2200 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2201 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2203 /// \param EnteringContext whether we are entering the scope of the
2204 /// nested-name-specifier.
2206 /// \param ObjectType if this unqualified-id occurs within a member access
2207 /// expression, the type of the base object whose member is being accessed.
2209 /// \param Result on a successful parse, contains the parsed unqualified-id.
2211 /// \returns true if parsing fails, false otherwise.
2212 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2213 ParsedType ObjectType,
2214 UnqualifiedId &Result) {
2215 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2217 // Consume the 'operator' keyword.
2218 SourceLocation KeywordLoc = ConsumeToken();
2220 // Determine what kind of operator name we have.
2221 unsigned SymbolIdx = 0;
2222 SourceLocation SymbolLocations[3];
2223 OverloadedOperatorKind Op = OO_None;
2224 switch (Tok.getKind()) {
2226 case tok::kw_delete: {
2227 bool isNew = Tok.getKind() == tok::kw_new;
2228 // Consume the 'new' or 'delete'.
2229 SymbolLocations[SymbolIdx++] = ConsumeToken();
2230 // Check for array new/delete.
2231 if (Tok.is(tok::l_square) &&
2232 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2233 // Consume the '[' and ']'.
2234 BalancedDelimiterTracker T(*this, tok::l_square);
2237 if (T.getCloseLocation().isInvalid())
2240 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2241 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2242 Op = isNew? OO_Array_New : OO_Array_Delete;
2244 Op = isNew? OO_New : OO_Delete;
2249 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2251 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2254 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2255 #include "clang/Basic/OperatorKinds.def"
2257 case tok::l_paren: {
2258 // Consume the '(' and ')'.
2259 BalancedDelimiterTracker T(*this, tok::l_paren);
2262 if (T.getCloseLocation().isInvalid())
2265 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2266 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2271 case tok::l_square: {
2272 // Consume the '[' and ']'.
2273 BalancedDelimiterTracker T(*this, tok::l_square);
2276 if (T.getCloseLocation().isInvalid())
2279 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2280 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2285 case tok::code_completion: {
2286 // Code completion for the operator name.
2287 Actions.CodeCompleteOperatorName(getCurScope());
2289 // Don't try to parse any further.
2297 if (Op != OO_None) {
2298 // We have parsed an operator-function-id.
2299 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2303 // Parse a literal-operator-id.
2305 // literal-operator-id: C++11 [over.literal]
2306 // operator string-literal identifier
2307 // operator user-defined-string-literal
2309 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2310 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2312 SourceLocation DiagLoc;
2313 unsigned DiagId = 0;
2315 // We're past translation phase 6, so perform string literal concatenation
2316 // before checking for "".
2317 SmallVector<Token, 4> Toks;
2318 SmallVector<SourceLocation, 4> TokLocs;
2319 while (isTokenStringLiteral()) {
2320 if (!Tok.is(tok::string_literal) && !DiagId) {
2321 // C++11 [over.literal]p1:
2322 // The string-literal or user-defined-string-literal in a
2323 // literal-operator-id shall have no encoding-prefix [...].
2324 DiagLoc = Tok.getLocation();
2325 DiagId = diag::err_literal_operator_string_prefix;
2327 Toks.push_back(Tok);
2328 TokLocs.push_back(ConsumeStringToken());
2331 StringLiteralParser Literal(Toks, PP);
2332 if (Literal.hadError)
2335 // Grab the literal operator's suffix, which will be either the next token
2336 // or a ud-suffix from the string literal.
2337 IdentifierInfo *II = nullptr;
2338 SourceLocation SuffixLoc;
2339 if (!Literal.getUDSuffix().empty()) {
2340 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2342 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2343 Literal.getUDSuffixOffset(),
2344 PP.getSourceManager(), getLangOpts());
2345 } else if (Tok.is(tok::identifier)) {
2346 II = Tok.getIdentifierInfo();
2347 SuffixLoc = ConsumeToken();
2348 TokLocs.push_back(SuffixLoc);
2350 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2354 // The string literal must be empty.
2355 if (!Literal.GetString().empty() || Literal.Pascal) {
2356 // C++11 [over.literal]p1:
2357 // The string-literal or user-defined-string-literal in a
2358 // literal-operator-id shall [...] contain no characters
2359 // other than the implicit terminating '\0'.
2360 DiagLoc = TokLocs.front();
2361 DiagId = diag::err_literal_operator_string_not_empty;
2365 // This isn't a valid literal-operator-id, but we think we know
2366 // what the user meant. Tell them what they should have written.
2367 SmallString<32> Str;
2369 Str += II->getName();
2370 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2371 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2374 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2376 return Actions.checkLiteralOperatorId(SS, Result);
2379 // Parse a conversion-function-id.
2381 // conversion-function-id: [C++ 12.3.2]
2382 // operator conversion-type-id
2384 // conversion-type-id:
2385 // type-specifier-seq conversion-declarator[opt]
2387 // conversion-declarator:
2388 // ptr-operator conversion-declarator[opt]
2390 // Parse the type-specifier-seq.
2391 DeclSpec DS(AttrFactory);
2392 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2395 // Parse the conversion-declarator, which is merely a sequence of
2397 Declarator D(DS, Declarator::ConversionIdContext);
2398 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2400 // Finish up the type.
2401 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2405 // Note that this is a conversion-function-id.
2406 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2407 D.getSourceRange().getEnd());
2411 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2412 /// name of an entity.
2415 /// unqualified-id: [C++ expr.prim.general]
2417 /// operator-function-id
2418 /// conversion-function-id
2419 /// [C++0x] literal-operator-id [TODO]
2425 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2426 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2428 /// \param EnteringContext whether we are entering the scope of the
2429 /// nested-name-specifier.
2431 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2433 /// \param AllowConstructorName whether we allow parsing a constructor name.
2435 /// \param ObjectType if this unqualified-id occurs within a member access
2436 /// expression, the type of the base object whose member is being accessed.
2438 /// \param Result on a successful parse, contains the parsed unqualified-id.
2440 /// \returns true if parsing fails, false otherwise.
2441 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2442 bool AllowDestructorName,
2443 bool AllowConstructorName,
2444 ParsedType ObjectType,
2445 SourceLocation& TemplateKWLoc,
2446 UnqualifiedId &Result) {
2448 // Handle 'A::template B'. This is for template-ids which have not
2449 // already been annotated by ParseOptionalCXXScopeSpecifier().
2450 bool TemplateSpecified = false;
2451 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2452 (ObjectType || SS.isSet())) {
2453 TemplateSpecified = true;
2454 TemplateKWLoc = ConsumeToken();
2459 // template-id (when it hasn't already been annotated)
2460 if (Tok.is(tok::identifier)) {
2461 // Consume the identifier.
2462 IdentifierInfo *Id = Tok.getIdentifierInfo();
2463 SourceLocation IdLoc = ConsumeToken();
2465 if (!getLangOpts().CPlusPlus) {
2466 // If we're not in C++, only identifiers matter. Record the
2467 // identifier and return.
2468 Result.setIdentifier(Id, IdLoc);
2472 if (AllowConstructorName &&
2473 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2474 // We have parsed a constructor name.
2475 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, false,
2477 /*IsCtorOrDtorName=*/true,
2478 /*NonTrivialTypeSourceInfo=*/true);
2479 Result.setConstructorName(Ty, IdLoc, IdLoc);
2481 // We have parsed an identifier.
2482 Result.setIdentifier(Id, IdLoc);
2485 // If the next token is a '<', we may have a template.
2486 if (TemplateSpecified || Tok.is(tok::less))
2487 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2488 EnteringContext, ObjectType,
2489 Result, TemplateSpecified);
2495 // template-id (already parsed and annotated)
2496 if (Tok.is(tok::annot_template_id)) {
2497 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2499 // If the template-name names the current class, then this is a constructor
2500 if (AllowConstructorName && TemplateId->Name &&
2501 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2503 // C++ [class.qual]p2 specifies that a qualified template-name
2504 // is taken as the constructor name where a constructor can be
2505 // declared. Thus, the template arguments are extraneous, so
2506 // complain about them and remove them entirely.
2507 Diag(TemplateId->TemplateNameLoc,
2508 diag::err_out_of_line_constructor_template_id)
2510 << FixItHint::CreateRemoval(
2511 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2513 Actions.getTypeName(*TemplateId->Name, TemplateId->TemplateNameLoc,
2514 getCurScope(), &SS, false, false, nullptr,
2515 /*IsCtorOrDtorName=*/true,
2516 /*NontrivialTypeSourceInfo=*/true);
2517 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2518 TemplateId->RAngleLoc);
2523 Result.setConstructorTemplateId(TemplateId);
2528 // We have already parsed a template-id; consume the annotation token as
2529 // our unqualified-id.
2530 Result.setTemplateId(TemplateId);
2531 TemplateKWLoc = TemplateId->TemplateKWLoc;
2537 // operator-function-id
2538 // conversion-function-id
2539 if (Tok.is(tok::kw_operator)) {
2540 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2543 // If we have an operator-function-id or a literal-operator-id and the next
2544 // token is a '<', we may have a
2547 // operator-function-id < template-argument-list[opt] >
2548 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2549 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2550 (TemplateSpecified || Tok.is(tok::less)))
2551 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2552 nullptr, SourceLocation(),
2553 EnteringContext, ObjectType,
2554 Result, TemplateSpecified);
2559 if (getLangOpts().CPlusPlus &&
2560 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2561 // C++ [expr.unary.op]p10:
2562 // There is an ambiguity in the unary-expression ~X(), where X is a
2563 // class-name. The ambiguity is resolved in favor of treating ~ as a
2564 // unary complement rather than treating ~X as referring to a destructor.
2567 SourceLocation TildeLoc = ConsumeToken();
2569 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2570 DeclSpec DS(AttrFactory);
2571 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2572 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2573 Result.setDestructorName(TildeLoc, Type, EndLoc);
2579 // Parse the class-name.
2580 if (Tok.isNot(tok::identifier)) {
2581 Diag(Tok, diag::err_destructor_tilde_identifier);
2585 // If the user wrote ~T::T, correct it to T::~T.
2586 DeclaratorScopeObj DeclScopeObj(*this, SS);
2587 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2588 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2589 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2590 // it will confuse this recovery logic.
2591 ColonProtectionRAIIObject ColonRAII(*this, false);
2594 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2597 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2599 if (SS.isNotEmpty())
2600 ObjectType = nullptr;
2601 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2603 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2607 // Recover as if the tilde had been written before the identifier.
2608 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2609 << FixItHint::CreateRemoval(TildeLoc)
2610 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2612 // Temporarily enter the scope for the rest of this function.
2613 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2614 DeclScopeObj.EnterDeclaratorScope();
2617 // Parse the class-name (or template-name in a simple-template-id).
2618 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2619 SourceLocation ClassNameLoc = ConsumeToken();
2621 if (TemplateSpecified || Tok.is(tok::less)) {
2622 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2623 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2624 ClassName, ClassNameLoc,
2625 EnteringContext, ObjectType,
2626 Result, TemplateSpecified);
2629 // Note that this is a destructor name.
2630 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2631 ClassNameLoc, getCurScope(),
2637 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2641 Diag(Tok, diag::err_expected_unqualified_id)
2642 << getLangOpts().CPlusPlus;
2646 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2647 /// memory in a typesafe manner and call constructors.
2649 /// This method is called to parse the new expression after the optional :: has
2650 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2651 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2654 /// '::'[opt] 'new' new-placement[opt] new-type-id
2655 /// new-initializer[opt]
2656 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2657 /// new-initializer[opt]
2660 /// '(' expression-list ')'
2663 /// type-specifier-seq new-declarator[opt]
2664 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2667 /// ptr-operator new-declarator[opt]
2668 /// direct-new-declarator
2670 /// new-initializer:
2671 /// '(' expression-list[opt] ')'
2672 /// [C++0x] braced-init-list
2675 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2676 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2677 ConsumeToken(); // Consume 'new'
2679 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2680 // second form of new-expression. It can't be a new-type-id.
2682 ExprVector PlacementArgs;
2683 SourceLocation PlacementLParen, PlacementRParen;
2685 SourceRange TypeIdParens;
2686 DeclSpec DS(AttrFactory);
2687 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2688 if (Tok.is(tok::l_paren)) {
2689 // If it turns out to be a placement, we change the type location.
2690 BalancedDelimiterTracker T(*this, tok::l_paren);
2692 PlacementLParen = T.getOpenLocation();
2693 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2694 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2699 PlacementRParen = T.getCloseLocation();
2700 if (PlacementRParen.isInvalid()) {
2701 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2705 if (PlacementArgs.empty()) {
2706 // Reset the placement locations. There was no placement.
2707 TypeIdParens = T.getRange();
2708 PlacementLParen = PlacementRParen = SourceLocation();
2710 // We still need the type.
2711 if (Tok.is(tok::l_paren)) {
2712 BalancedDelimiterTracker T(*this, tok::l_paren);
2714 MaybeParseGNUAttributes(DeclaratorInfo);
2715 ParseSpecifierQualifierList(DS);
2716 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2717 ParseDeclarator(DeclaratorInfo);
2719 TypeIdParens = T.getRange();
2721 MaybeParseGNUAttributes(DeclaratorInfo);
2722 if (ParseCXXTypeSpecifierSeq(DS))
2723 DeclaratorInfo.setInvalidType(true);
2725 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2726 ParseDeclaratorInternal(DeclaratorInfo,
2727 &Parser::ParseDirectNewDeclarator);
2732 // A new-type-id is a simplified type-id, where essentially the
2733 // direct-declarator is replaced by a direct-new-declarator.
2734 MaybeParseGNUAttributes(DeclaratorInfo);
2735 if (ParseCXXTypeSpecifierSeq(DS))
2736 DeclaratorInfo.setInvalidType(true);
2738 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2739 ParseDeclaratorInternal(DeclaratorInfo,
2740 &Parser::ParseDirectNewDeclarator);
2743 if (DeclaratorInfo.isInvalidType()) {
2744 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2748 ExprResult Initializer;
2750 if (Tok.is(tok::l_paren)) {
2751 SourceLocation ConstructorLParen, ConstructorRParen;
2752 ExprVector ConstructorArgs;
2753 BalancedDelimiterTracker T(*this, tok::l_paren);
2755 ConstructorLParen = T.getOpenLocation();
2756 if (Tok.isNot(tok::r_paren)) {
2757 CommaLocsTy CommaLocs;
2758 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2759 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2760 DeclaratorInfo).get();
2761 Actions.CodeCompleteConstructor(getCurScope(),
2762 TypeRep.get()->getCanonicalTypeInternal(),
2763 DeclaratorInfo.getLocEnd(),
2766 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2771 ConstructorRParen = T.getCloseLocation();
2772 if (ConstructorRParen.isInvalid()) {
2773 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2776 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2779 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2780 Diag(Tok.getLocation(),
2781 diag::warn_cxx98_compat_generalized_initializer_lists);
2782 Initializer = ParseBraceInitializer();
2784 if (Initializer.isInvalid())
2787 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2788 PlacementArgs, PlacementRParen,
2789 TypeIdParens, DeclaratorInfo, Initializer.get());
2792 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2793 /// passed to ParseDeclaratorInternal.
2795 /// direct-new-declarator:
2796 /// '[' expression ']'
2797 /// direct-new-declarator '[' constant-expression ']'
2799 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2800 // Parse the array dimensions.
2802 while (Tok.is(tok::l_square)) {
2803 // An array-size expression can't start with a lambda.
2804 if (CheckProhibitedCXX11Attribute())
2807 BalancedDelimiterTracker T(*this, tok::l_square);
2810 ExprResult Size(first ? ParseExpression()
2811 : ParseConstantExpression());
2812 if (Size.isInvalid()) {
2814 SkipUntil(tok::r_square, StopAtSemi);
2821 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2822 ParsedAttributes Attrs(AttrFactory);
2823 MaybeParseCXX11Attributes(Attrs);
2825 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2826 /*static=*/false, /*star=*/false,
2828 T.getOpenLocation(),
2829 T.getCloseLocation()),
2830 Attrs, T.getCloseLocation());
2832 if (T.getCloseLocation().isInvalid())
2837 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2838 /// This ambiguity appears in the syntax of the C++ new operator.
2841 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2842 /// new-initializer[opt]
2845 /// '(' expression-list ')'
2847 bool Parser::ParseExpressionListOrTypeId(
2848 SmallVectorImpl<Expr*> &PlacementArgs,
2850 // The '(' was already consumed.
2851 if (isTypeIdInParens()) {
2852 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2853 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2855 return D.isInvalidType();
2858 // It's not a type, it has to be an expression list.
2859 // Discard the comma locations - ActOnCXXNew has enough parameters.
2860 CommaLocsTy CommaLocs;
2861 return ParseExpressionList(PlacementArgs, CommaLocs);
2864 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2865 /// to free memory allocated by new.
2867 /// This method is called to parse the 'delete' expression after the optional
2868 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2869 /// and "Start" is its location. Otherwise, "Start" is the location of the
2872 /// delete-expression:
2873 /// '::'[opt] 'delete' cast-expression
2874 /// '::'[opt] 'delete' '[' ']' cast-expression
2876 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2877 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2878 ConsumeToken(); // Consume 'delete'
2881 bool ArrayDelete = false;
2882 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2883 // C++11 [expr.delete]p1:
2884 // Whenever the delete keyword is followed by empty square brackets, it
2885 // shall be interpreted as [array delete].
2886 // [Footnote: A lambda expression with a lambda-introducer that consists
2887 // of empty square brackets can follow the delete keyword if
2888 // the lambda expression is enclosed in parentheses.]
2889 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2890 // lambda-introducer.
2892 BalancedDelimiterTracker T(*this, tok::l_square);
2896 if (T.getCloseLocation().isInvalid())
2900 ExprResult Operand(ParseCastExpression(false));
2901 if (Operand.isInvalid())
2904 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2907 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2909 default: llvm_unreachable("Not a known type trait");
2910 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2911 case tok::kw_ ## Spelling: return UTT_ ## Name;
2912 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2913 case tok::kw_ ## Spelling: return BTT_ ## Name;
2914 #include "clang/Basic/TokenKinds.def"
2915 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2916 case tok::kw_ ## Spelling: return TT_ ## Name;
2917 #include "clang/Basic/TokenKinds.def"
2921 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2923 default: llvm_unreachable("Not a known binary type trait");
2924 case tok::kw___array_rank: return ATT_ArrayRank;
2925 case tok::kw___array_extent: return ATT_ArrayExtent;
2929 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2931 default: llvm_unreachable("Not a known unary expression trait.");
2932 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2933 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2937 static unsigned TypeTraitArity(tok::TokenKind kind) {
2939 default: llvm_unreachable("Not a known type trait");
2940 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2941 #include "clang/Basic/TokenKinds.def"
2945 /// \brief Parse the built-in type-trait pseudo-functions that allow
2946 /// implementation of the TR1/C++11 type traits templates.
2948 /// primary-expression:
2949 /// unary-type-trait '(' type-id ')'
2950 /// binary-type-trait '(' type-id ',' type-id ')'
2951 /// type-trait '(' type-id-seq ')'
2954 /// type-id ...[opt] type-id-seq[opt]
2956 ExprResult Parser::ParseTypeTrait() {
2957 tok::TokenKind Kind = Tok.getKind();
2958 unsigned Arity = TypeTraitArity(Kind);
2960 SourceLocation Loc = ConsumeToken();
2962 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2963 if (Parens.expectAndConsume())
2966 SmallVector<ParsedType, 2> Args;
2968 // Parse the next type.
2969 TypeResult Ty = ParseTypeName();
2970 if (Ty.isInvalid()) {
2975 // Parse the ellipsis, if present.
2976 if (Tok.is(tok::ellipsis)) {
2977 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2978 if (Ty.isInvalid()) {
2984 // Add this type to the list of arguments.
2985 Args.push_back(Ty.get());
2986 } while (TryConsumeToken(tok::comma));
2988 if (Parens.consumeClose())
2991 SourceLocation EndLoc = Parens.getCloseLocation();
2993 if (Arity && Args.size() != Arity) {
2994 Diag(EndLoc, diag::err_type_trait_arity)
2995 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2999 if (!Arity && Args.empty()) {
3000 Diag(EndLoc, diag::err_type_trait_arity)
3001 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3005 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3008 /// ParseArrayTypeTrait - Parse the built-in array type-trait
3009 /// pseudo-functions.
3011 /// primary-expression:
3012 /// [Embarcadero] '__array_rank' '(' type-id ')'
3013 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3015 ExprResult Parser::ParseArrayTypeTrait() {
3016 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3017 SourceLocation Loc = ConsumeToken();
3019 BalancedDelimiterTracker T(*this, tok::l_paren);
3020 if (T.expectAndConsume())
3023 TypeResult Ty = ParseTypeName();
3024 if (Ty.isInvalid()) {
3025 SkipUntil(tok::comma, StopAtSemi);
3026 SkipUntil(tok::r_paren, StopAtSemi);
3031 case ATT_ArrayRank: {
3033 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3034 T.getCloseLocation());
3036 case ATT_ArrayExtent: {
3037 if (ExpectAndConsume(tok::comma)) {
3038 SkipUntil(tok::r_paren, StopAtSemi);
3042 ExprResult DimExpr = ParseExpression();
3045 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3046 T.getCloseLocation());
3049 llvm_unreachable("Invalid ArrayTypeTrait!");
3052 /// ParseExpressionTrait - Parse built-in expression-trait
3053 /// pseudo-functions like __is_lvalue_expr( xxx ).
3055 /// primary-expression:
3056 /// [Embarcadero] expression-trait '(' expression ')'
3058 ExprResult Parser::ParseExpressionTrait() {
3059 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3060 SourceLocation Loc = ConsumeToken();
3062 BalancedDelimiterTracker T(*this, tok::l_paren);
3063 if (T.expectAndConsume())
3066 ExprResult Expr = ParseExpression();
3070 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3071 T.getCloseLocation());
3075 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3076 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3077 /// based on the context past the parens.
3079 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3081 BalancedDelimiterTracker &Tracker,
3082 ColonProtectionRAIIObject &ColonProt) {
3083 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3084 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3085 assert(isTypeIdInParens() && "Not a type-id!");
3087 ExprResult Result(true);
3090 // We need to disambiguate a very ugly part of the C++ syntax:
3092 // (T())x; - type-id
3093 // (T())*x; - type-id
3094 // (T())/x; - expression
3095 // (T()); - expression
3097 // The bad news is that we cannot use the specialized tentative parser, since
3098 // it can only verify that the thing inside the parens can be parsed as
3099 // type-id, it is not useful for determining the context past the parens.
3101 // The good news is that the parser can disambiguate this part without
3102 // making any unnecessary Action calls.
3104 // It uses a scheme similar to parsing inline methods. The parenthesized
3105 // tokens are cached, the context that follows is determined (possibly by
3106 // parsing a cast-expression), and then we re-introduce the cached tokens
3107 // into the token stream and parse them appropriately.
3109 ParenParseOption ParseAs;
3112 // Store the tokens of the parentheses. We will parse them after we determine
3113 // the context that follows them.
3114 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3115 // We didn't find the ')' we expected.
3116 Tracker.consumeClose();
3120 if (Tok.is(tok::l_brace)) {
3121 ParseAs = CompoundLiteral;
3124 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3127 // Try parsing the cast-expression that may follow.
3128 // If it is not a cast-expression, NotCastExpr will be true and no token
3129 // will be consumed.
3130 ColonProt.restore();
3131 Result = ParseCastExpression(false/*isUnaryExpression*/,
3132 false/*isAddressofOperand*/,
3134 // type-id has priority.
3138 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3140 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3143 // Create a fake EOF to mark end of Toks buffer.
3145 AttrEnd.startToken();
3146 AttrEnd.setKind(tok::eof);
3147 AttrEnd.setLocation(Tok.getLocation());
3148 AttrEnd.setEofData(Toks.data());
3149 Toks.push_back(AttrEnd);
3151 // The current token should go after the cached tokens.
3152 Toks.push_back(Tok);
3153 // Re-enter the stored parenthesized tokens into the token stream, so we may
3155 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
3156 // Drop the current token and bring the first cached one. It's the same token
3157 // as when we entered this function.
3160 if (ParseAs >= CompoundLiteral) {
3161 // Parse the type declarator.
3162 DeclSpec DS(AttrFactory);
3163 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
3165 ColonProtectionRAIIObject InnerColonProtection(*this);
3166 ParseSpecifierQualifierList(DS);
3167 ParseDeclarator(DeclaratorInfo);
3171 Tracker.consumeClose();
3172 ColonProt.restore();
3174 // Consume EOF marker for Toks buffer.
3175 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3178 if (ParseAs == CompoundLiteral) {
3179 ExprType = CompoundLiteral;
3180 if (DeclaratorInfo.isInvalidType())
3183 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3184 return ParseCompoundLiteralExpression(Ty.get(),
3185 Tracker.getOpenLocation(),
3186 Tracker.getCloseLocation());
3189 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3190 assert(ParseAs == CastExpr);
3192 if (DeclaratorInfo.isInvalidType())
3195 // Result is what ParseCastExpression returned earlier.
3196 if (!Result.isInvalid())
3197 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3198 DeclaratorInfo, CastTy,
3199 Tracker.getCloseLocation(), Result.get());
3203 // Not a compound literal, and not followed by a cast-expression.
3204 assert(ParseAs == SimpleExpr);
3206 ExprType = SimpleExpr;
3207 Result = ParseExpression();
3208 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3209 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3210 Tok.getLocation(), Result.get());
3213 if (Result.isInvalid()) {
3214 while (Tok.isNot(tok::eof))
3216 assert(Tok.getEofData() == AttrEnd.getEofData());
3221 Tracker.consumeClose();
3222 // Consume EOF marker for Toks buffer.
3223 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());