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 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/Basic/PrettyStackTrace.h"
17 #include "clang/Lex/LiteralSupport.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/ParsedTemplate.h"
21 #include "clang/Sema/Scope.h"
22 #include "llvm/Support/ErrorHandling.h"
24 using namespace clang;
26 static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
28 case tok::kw_template: return 0;
29 case tok::kw_const_cast: return 1;
30 case tok::kw_dynamic_cast: return 2;
31 case tok::kw_reinterpret_cast: return 3;
32 case tok::kw_static_cast: return 4;
34 llvm_unreachable("Unknown type for digraph error message.");
38 // Are the two tokens adjacent in the same source file?
39 bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
40 SourceManager &SM = PP.getSourceManager();
41 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
42 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
43 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
46 // Suggest fixit for "<::" after a cast.
47 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
48 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
49 // Pull '<:' and ':' off token stream.
55 Range.setBegin(DigraphToken.getLocation());
56 Range.setEnd(ColonToken.getLocation());
57 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
58 << SelectDigraphErrorMessage(Kind)
59 << FixItHint::CreateReplacement(Range, "< ::");
61 // Update token information to reflect their change in token type.
62 ColonToken.setKind(tok::coloncolon);
63 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
64 ColonToken.setLength(2);
65 DigraphToken.setKind(tok::less);
66 DigraphToken.setLength(1);
68 // Push new tokens back to token stream.
69 PP.EnterToken(ColonToken);
71 PP.EnterToken(DigraphToken);
74 // Check for '<::' which should be '< ::' instead of '[:' when following
76 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
78 IdentifierInfo &II, CXXScopeSpec &SS) {
79 if (!Next.is(tok::l_square) || Next.getLength() != 2)
82 Token SecondToken = GetLookAheadToken(2);
83 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
87 UnqualifiedId TemplateName;
88 TemplateName.setIdentifier(&II, Tok.getLocation());
89 bool MemberOfUnknownSpecialization;
90 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
91 TemplateName, ObjectType, EnteringContext,
92 Template, MemberOfUnknownSpecialization))
95 FixDigraph(*this, PP, Next, SecondToken, tok::kw_template,
99 /// \brief Emits an error for a left parentheses after a double colon.
101 /// When a '(' is found after a '::', emit an error. Attempt to fix the token
102 /// stream by removing the '(', and the matching ')' if found.
103 void Parser::CheckForLParenAfterColonColon() {
104 if (!Tok.is(tok::l_paren))
107 SourceLocation l_parenLoc = ConsumeParen(), r_parenLoc;
108 Token Tok1 = getCurToken();
109 if (!Tok1.is(tok::identifier) && !Tok1.is(tok::star))
112 if (Tok1.is(tok::identifier)) {
113 Token Tok2 = GetLookAheadToken(1);
114 if (Tok2.is(tok::r_paren)) {
117 r_parenLoc = ConsumeParen();
119 } else if (Tok1.is(tok::star)) {
120 Token Tok2 = GetLookAheadToken(1);
121 if (Tok2.is(tok::identifier)) {
122 Token Tok3 = GetLookAheadToken(2);
123 if (Tok3.is(tok::r_paren)) {
128 r_parenLoc = ConsumeParen();
133 Diag(l_parenLoc, diag::err_paren_after_colon_colon)
134 << FixItHint::CreateRemoval(l_parenLoc)
135 << FixItHint::CreateRemoval(r_parenLoc);
138 /// \brief Parse global scope or nested-name-specifier if present.
140 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
141 /// may be preceded by '::'). Note that this routine will not parse ::new or
142 /// ::delete; it will just leave them in the token stream.
144 /// '::'[opt] nested-name-specifier
147 /// nested-name-specifier:
149 /// namespace-name '::'
150 /// nested-name-specifier identifier '::'
151 /// nested-name-specifier 'template'[opt] simple-template-id '::'
154 /// \param SS the scope specifier that will be set to the parsed
155 /// nested-name-specifier (or empty)
157 /// \param ObjectType if this nested-name-specifier is being parsed following
158 /// the "." or "->" of a member access expression, this parameter provides the
159 /// type of the object whose members are being accessed.
161 /// \param EnteringContext whether we will be entering into the context of
162 /// the nested-name-specifier after parsing it.
164 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
165 /// indicates whether this nested-name-specifier may be part of a
166 /// pseudo-destructor name. In this case, the flag will be set false
167 /// if we don't actually end up parsing a destructor name. Moreorover,
168 /// if we do end up determining that we are parsing a destructor name,
169 /// the last component of the nested-name-specifier is not parsed as
170 /// part of the scope specifier.
172 /// \param IsTypename If \c true, this nested-name-specifier is known to be
173 /// part of a type name. This is used to improve error recovery.
175 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
176 /// filled in with the leading identifier in the last component of the
177 /// nested-name-specifier, if any.
179 /// \returns true if there was an error parsing a scope specifier
180 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
181 ParsedType ObjectType,
182 bool EnteringContext,
183 bool *MayBePseudoDestructor,
185 IdentifierInfo **LastII) {
186 assert(getLangOpts().CPlusPlus &&
187 "Call sites of this function should be guarded by checking for C++");
189 if (Tok.is(tok::annot_cxxscope)) {
190 assert(!LastII && "want last identifier but have already annotated scope");
191 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
192 Tok.getAnnotationRange(),
201 bool HasScopeSpecifier = false;
203 if (Tok.is(tok::coloncolon)) {
204 // ::new and ::delete aren't nested-name-specifiers.
205 tok::TokenKind NextKind = NextToken().getKind();
206 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
209 // '::' - Global scope qualifier.
210 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
213 CheckForLParenAfterColonColon();
215 HasScopeSpecifier = true;
218 bool CheckForDestructor = false;
219 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
220 CheckForDestructor = true;
221 *MayBePseudoDestructor = false;
224 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
225 DeclSpec DS(AttrFactory);
226 SourceLocation DeclLoc = Tok.getLocation();
227 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
228 if (Tok.isNot(tok::coloncolon)) {
229 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
233 SourceLocation CCLoc = ConsumeToken();
234 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
235 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
237 HasScopeSpecifier = true;
241 if (HasScopeSpecifier) {
242 // C++ [basic.lookup.classref]p5:
243 // If the qualified-id has the form
245 // ::class-name-or-namespace-name::...
247 // the class-name-or-namespace-name is looked up in global scope as a
248 // class-name or namespace-name.
250 // To implement this, we clear out the object type as soon as we've
251 // seen a leading '::' or part of a nested-name-specifier.
252 ObjectType = ParsedType();
254 if (Tok.is(tok::code_completion)) {
255 // Code completion for a nested-name-specifier, where the code
256 // code completion token follows the '::'.
257 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
258 // Include code completion token into the range of the scope otherwise
259 // when we try to annotate the scope tokens the dangling code completion
260 // token will cause assertion in
261 // Preprocessor::AnnotatePreviousCachedTokens.
262 SS.setEndLoc(Tok.getLocation());
268 // nested-name-specifier:
269 // nested-name-specifier 'template'[opt] simple-template-id '::'
271 // Parse the optional 'template' keyword, then make sure we have
272 // 'identifier <' after it.
273 if (Tok.is(tok::kw_template)) {
274 // If we don't have a scope specifier or an object type, this isn't a
275 // nested-name-specifier, since they aren't allowed to start with
277 if (!HasScopeSpecifier && !ObjectType)
280 TentativeParsingAction TPA(*this);
281 SourceLocation TemplateKWLoc = ConsumeToken();
283 UnqualifiedId TemplateName;
284 if (Tok.is(tok::identifier)) {
285 // Consume the identifier.
286 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
288 } else if (Tok.is(tok::kw_operator)) {
289 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
295 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
296 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
297 Diag(TemplateName.getSourceRange().getBegin(),
298 diag::err_id_after_template_in_nested_name_spec)
299 << TemplateName.getSourceRange();
308 // If the next token is not '<', we have a qualified-id that refers
309 // to a template name, such as T::template apply, but is not a
311 if (Tok.isNot(tok::less)) {
316 // Commit to parsing the template-id.
319 if (TemplateNameKind TNK
320 = Actions.ActOnDependentTemplateName(getCurScope(),
321 SS, TemplateKWLoc, TemplateName,
322 ObjectType, EnteringContext,
324 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
325 TemplateName, false))
333 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
336 // simple-template-id '::'
338 // So we need to check whether the simple-template-id is of the
339 // right kind (it should name a type or be dependent), and then
340 // convert it into a type within the nested-name-specifier.
341 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
342 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
343 *MayBePseudoDestructor = true;
348 *LastII = TemplateId->Name;
350 // Consume the template-id token.
353 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
354 SourceLocation CCLoc = ConsumeToken();
356 HasScopeSpecifier = true;
358 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
359 TemplateId->NumArgs);
361 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
363 TemplateId->TemplateKWLoc,
364 TemplateId->Template,
365 TemplateId->TemplateNameLoc,
366 TemplateId->LAngleLoc,
368 TemplateId->RAngleLoc,
371 SourceLocation StartLoc
372 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
373 : TemplateId->TemplateNameLoc;
374 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
381 // The rest of the nested-name-specifier possibilities start with
383 if (Tok.isNot(tok::identifier))
386 IdentifierInfo &II = *Tok.getIdentifierInfo();
388 // nested-name-specifier:
390 // namespace-name '::'
391 // nested-name-specifier identifier '::'
392 Token Next = NextToken();
394 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
395 // and emit a fixit hint for it.
396 if (Next.is(tok::colon) && !ColonIsSacred) {
397 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
399 Next.getLocation(), ObjectType,
401 // If the token after the colon isn't an identifier, it's still an
402 // error, but they probably meant something else strange so don't
403 // recover like this.
404 PP.LookAhead(1).is(tok::identifier)) {
405 Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
406 << FixItHint::CreateReplacement(Next.getLocation(), "::");
408 // Recover as if the user wrote '::'.
409 Next.setKind(tok::coloncolon);
413 if (Next.is(tok::coloncolon)) {
414 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
415 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
417 *MayBePseudoDestructor = true;
424 // We have an identifier followed by a '::'. Lookup this name
425 // as the name in a nested-name-specifier.
426 SourceLocation IdLoc = ConsumeToken();
427 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
428 "NextToken() not working properly!");
429 SourceLocation CCLoc = ConsumeToken();
431 CheckForLParenAfterColonColon();
433 HasScopeSpecifier = true;
434 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
435 ObjectType, EnteringContext, SS))
436 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
441 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
443 // nested-name-specifier:
445 if (Next.is(tok::less)) {
447 UnqualifiedId TemplateName;
448 TemplateName.setIdentifier(&II, Tok.getLocation());
449 bool MemberOfUnknownSpecialization;
450 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
451 /*hasTemplateKeyword=*/false,
456 MemberOfUnknownSpecialization)) {
457 // We have found a template name, so annotate this token
458 // with a template-id annotation. We do not permit the
459 // template-id to be translated into a type annotation,
460 // because some clients (e.g., the parsing of class template
461 // specializations) still want to see the original template-id
464 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
465 TemplateName, false))
470 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
471 (IsTypename || IsTemplateArgumentList(1))) {
472 // We have something like t::getAs<T>, where getAs is a
473 // member of an unknown specialization. However, this will only
474 // parse correctly as a template, so suggest the keyword 'template'
475 // before 'getAs' and treat this as a dependent template name.
476 unsigned DiagID = diag::err_missing_dependent_template_keyword;
477 if (getLangOpts().MicrosoftExt)
478 DiagID = diag::warn_missing_dependent_template_keyword;
480 Diag(Tok.getLocation(), DiagID)
482 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
484 if (TemplateNameKind TNK
485 = Actions.ActOnDependentTemplateName(getCurScope(),
486 SS, SourceLocation(),
487 TemplateName, ObjectType,
488 EnteringContext, Template)) {
489 // Consume the identifier.
491 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
492 TemplateName, false))
502 // We don't have any tokens that form the beginning of a
503 // nested-name-specifier, so we're done.
507 // Even if we didn't see any pieces of a nested-name-specifier, we
508 // still check whether there is a tilde in this position, which
509 // indicates a potential pseudo-destructor.
510 if (CheckForDestructor && Tok.is(tok::tilde))
511 *MayBePseudoDestructor = true;
516 /// ParseCXXIdExpression - Handle id-expression.
523 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
525 /// '::' operator-function-id
528 /// NOTE: The standard specifies that, for qualified-id, the parser does not
531 /// '::' conversion-function-id
532 /// '::' '~' class-name
534 /// This may cause a slight inconsistency on diagnostics:
539 /// :: A :: ~ C(); // Some Sema error about using destructor with a
541 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
544 /// We simplify the parser a bit and make it work like:
547 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
548 /// '::' unqualified-id
550 /// That way Sema can handle and report similar errors for namespaces and the
553 /// The isAddressOfOperand parameter indicates that this id-expression is a
554 /// direct operand of the address-of operator. This is, besides member contexts,
555 /// the only place where a qualified-id naming a non-static class member may
558 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
560 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
561 // '::' unqualified-id
564 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
566 SourceLocation TemplateKWLoc;
568 if (ParseUnqualifiedId(SS,
569 /*EnteringContext=*/false,
570 /*AllowDestructorName=*/false,
571 /*AllowConstructorName=*/false,
572 /*ObjectType=*/ ParsedType(),
577 // This is only the direct operand of an & operator if it is not
578 // followed by a postfix-expression suffix.
579 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
580 isAddressOfOperand = false;
582 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
583 Tok.is(tok::l_paren), isAddressOfOperand);
586 /// ParseLambdaExpression - Parse a C++0x lambda expression.
588 /// lambda-expression:
589 /// lambda-introducer lambda-declarator[opt] compound-statement
591 /// lambda-introducer:
592 /// '[' lambda-capture[opt] ']'
597 /// capture-default ',' capture-list
605 /// capture-list ',' capture
612 /// lambda-declarator:
613 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
614 /// 'mutable'[opt] exception-specification[opt]
615 /// trailing-return-type[opt]
617 ExprResult Parser::ParseLambdaExpression() {
618 // Parse lambda-introducer.
619 LambdaIntroducer Intro;
621 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
623 Diag(Tok, DiagID.getValue());
624 SkipUntil(tok::r_square);
625 SkipUntil(tok::l_brace);
626 SkipUntil(tok::r_brace);
630 return ParseLambdaExpressionAfterIntroducer(Intro);
633 /// TryParseLambdaExpression - Use lookahead and potentially tentative
634 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
637 /// If we are not looking at a lambda expression, returns ExprError().
638 ExprResult Parser::TryParseLambdaExpression() {
639 assert(getLangOpts().CPlusPlus11
640 && Tok.is(tok::l_square)
641 && "Not at the start of a possible lambda expression.");
643 const Token Next = NextToken(), After = GetLookAheadToken(2);
645 // If lookahead indicates this is a lambda...
646 if (Next.is(tok::r_square) || // []
647 Next.is(tok::equal) || // [=
648 (Next.is(tok::amp) && // [&] or [&,
649 (After.is(tok::r_square) ||
650 After.is(tok::comma))) ||
651 (Next.is(tok::identifier) && // [identifier]
652 After.is(tok::r_square))) {
653 return ParseLambdaExpression();
656 // If lookahead indicates an ObjC message send...
657 // [identifier identifier
658 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
662 // Here, we're stuck: lambda introducers and Objective-C message sends are
663 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
664 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
665 // writing two routines to parse a lambda introducer, just try to parse
666 // a lambda introducer first, and fall back if that fails.
667 // (TryParseLambdaIntroducer never produces any diagnostic output.)
668 LambdaIntroducer Intro;
669 if (TryParseLambdaIntroducer(Intro))
671 return ParseLambdaExpressionAfterIntroducer(Intro);
674 /// ParseLambdaExpression - Parse a lambda introducer.
676 /// Returns a DiagnosticID if it hit something unexpected.
677 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro) {
678 typedef Optional<unsigned> DiagResult;
680 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
681 BalancedDelimiterTracker T(*this, tok::l_square);
684 Intro.Range.setBegin(T.getOpenLocation());
688 // Parse capture-default.
689 if (Tok.is(tok::amp) &&
690 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
691 Intro.Default = LCD_ByRef;
692 Intro.DefaultLoc = ConsumeToken();
694 } else if (Tok.is(tok::equal)) {
695 Intro.Default = LCD_ByCopy;
696 Intro.DefaultLoc = ConsumeToken();
700 while (Tok.isNot(tok::r_square)) {
702 if (Tok.isNot(tok::comma)) {
703 // Provide a completion for a lambda introducer here. Except
704 // in Objective-C, where this is Almost Surely meant to be a message
705 // send. In that case, fail here and let the ObjC message
706 // expression parser perform the completion.
707 if (Tok.is(tok::code_completion) &&
708 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
709 !Intro.Captures.empty())) {
710 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
711 /*AfterAmpersand=*/false);
712 ConsumeCodeCompletionToken();
716 return DiagResult(diag::err_expected_comma_or_rsquare);
721 if (Tok.is(tok::code_completion)) {
722 // If we're in Objective-C++ and we have a bare '[', then this is more
723 // likely to be a message receiver.
724 if (getLangOpts().ObjC1 && first)
725 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
727 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
728 /*AfterAmpersand=*/false);
729 ConsumeCodeCompletionToken();
736 LambdaCaptureKind Kind = LCK_ByCopy;
738 IdentifierInfo* Id = 0;
739 SourceLocation EllipsisLoc;
741 if (Tok.is(tok::kw_this)) {
743 Loc = ConsumeToken();
745 if (Tok.is(tok::amp)) {
749 if (Tok.is(tok::code_completion)) {
750 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
751 /*AfterAmpersand=*/true);
752 ConsumeCodeCompletionToken();
757 if (Tok.is(tok::identifier)) {
758 Id = Tok.getIdentifierInfo();
759 Loc = ConsumeToken();
761 if (Tok.is(tok::ellipsis))
762 EllipsisLoc = ConsumeToken();
763 } else if (Tok.is(tok::kw_this)) {
764 // FIXME: If we want to suggest a fixit here, will need to return more
765 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
766 // Clear()ed to prevent emission in case of tentative parsing?
767 return DiagResult(diag::err_this_captured_by_reference);
769 return DiagResult(diag::err_expected_capture);
773 Intro.addCapture(Kind, Loc, Id, EllipsisLoc);
777 Intro.Range.setEnd(T.getCloseLocation());
782 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
784 /// Returns true if it hit something unexpected.
785 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
786 TentativeParsingAction PA(*this);
788 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
799 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
801 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
802 LambdaIntroducer &Intro) {
803 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
804 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
806 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
807 "lambda expression parsing");
809 // Parse lambda-declarator[opt].
810 DeclSpec DS(AttrFactory);
811 Declarator D(DS, Declarator::LambdaExprContext);
813 if (Tok.is(tok::l_paren)) {
814 ParseScope PrototypeScope(this,
815 Scope::FunctionPrototypeScope |
816 Scope::FunctionDeclarationScope |
819 SourceLocation DeclEndLoc;
820 BalancedDelimiterTracker T(*this, tok::l_paren);
822 SourceLocation LParenLoc = T.getOpenLocation();
824 // Parse parameter-declaration-clause.
825 ParsedAttributes Attr(AttrFactory);
826 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
827 SourceLocation EllipsisLoc;
829 if (Tok.isNot(tok::r_paren))
830 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
833 SourceLocation RParenLoc = T.getCloseLocation();
834 DeclEndLoc = RParenLoc;
836 // Parse 'mutable'[opt].
837 SourceLocation MutableLoc;
838 if (Tok.is(tok::kw_mutable)) {
839 MutableLoc = ConsumeToken();
840 DeclEndLoc = MutableLoc;
843 // Parse exception-specification[opt].
844 ExceptionSpecificationType ESpecType = EST_None;
845 SourceRange ESpecRange;
846 SmallVector<ParsedType, 2> DynamicExceptions;
847 SmallVector<SourceRange, 2> DynamicExceptionRanges;
848 ExprResult NoexceptExpr;
849 ESpecType = tryParseExceptionSpecification(ESpecRange,
851 DynamicExceptionRanges,
854 if (ESpecType != EST_None)
855 DeclEndLoc = ESpecRange.getEnd();
857 // Parse attribute-specifier[opt].
858 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
860 SourceLocation FunLocalRangeEnd = DeclEndLoc;
862 // Parse trailing-return-type[opt].
863 TypeResult TrailingReturnType;
864 if (Tok.is(tok::arrow)) {
865 FunLocalRangeEnd = Tok.getLocation();
867 TrailingReturnType = ParseTrailingReturnType(Range);
868 if (Range.getEnd().isValid())
869 DeclEndLoc = Range.getEnd();
872 PrototypeScope.Exit();
874 SourceLocation NoLoc;
875 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
876 /*isAmbiguous=*/false,
878 ParamInfo.data(), ParamInfo.size(),
879 EllipsisLoc, RParenLoc,
880 DS.getTypeQualifiers(),
881 /*RefQualifierIsLValueRef=*/true,
882 /*RefQualifierLoc=*/NoLoc,
883 /*ConstQualifierLoc=*/NoLoc,
884 /*VolatileQualifierLoc=*/NoLoc,
886 ESpecType, ESpecRange.getBegin(),
887 DynamicExceptions.data(),
888 DynamicExceptionRanges.data(),
889 DynamicExceptions.size(),
890 NoexceptExpr.isUsable() ?
891 NoexceptExpr.get() : 0,
892 LParenLoc, FunLocalRangeEnd, D,
895 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) {
896 // It's common to forget that one needs '()' before 'mutable' or the
897 // result type. Deal with this.
898 Diag(Tok, diag::err_lambda_missing_parens)
899 << Tok.is(tok::arrow)
900 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
901 SourceLocation DeclLoc = Tok.getLocation();
902 SourceLocation DeclEndLoc = DeclLoc;
904 // Parse 'mutable', if it's there.
905 SourceLocation MutableLoc;
906 if (Tok.is(tok::kw_mutable)) {
907 MutableLoc = ConsumeToken();
908 DeclEndLoc = MutableLoc;
911 // Parse the return type, if there is one.
912 TypeResult TrailingReturnType;
913 if (Tok.is(tok::arrow)) {
915 TrailingReturnType = ParseTrailingReturnType(Range);
916 if (Range.getEnd().isValid())
917 DeclEndLoc = Range.getEnd();
920 ParsedAttributes Attr(AttrFactory);
921 SourceLocation NoLoc;
922 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
923 /*isAmbiguous=*/false,
927 /*EllipsisLoc=*/NoLoc,
930 /*RefQualifierIsLValueRef=*/true,
931 /*RefQualifierLoc=*/NoLoc,
932 /*ConstQualifierLoc=*/NoLoc,
933 /*VolatileQualifierLoc=*/NoLoc,
938 /*ExceptionRanges=*/0,
941 DeclLoc, DeclEndLoc, D,
947 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
949 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
950 ParseScope BodyScope(this, ScopeFlags);
952 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
954 // Parse compound-statement.
955 if (!Tok.is(tok::l_brace)) {
956 Diag(Tok, diag::err_expected_lambda_body);
957 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
961 StmtResult Stmt(ParseCompoundStatementBody());
964 if (!Stmt.isInvalid())
965 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope());
967 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
971 /// ParseCXXCasts - This handles the various ways to cast expressions to another
974 /// postfix-expression: [C++ 5.2p1]
975 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
976 /// 'static_cast' '<' type-name '>' '(' expression ')'
977 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
978 /// 'const_cast' '<' type-name '>' '(' expression ')'
980 ExprResult Parser::ParseCXXCasts() {
981 tok::TokenKind Kind = Tok.getKind();
982 const char *CastName = 0; // For error messages
985 default: llvm_unreachable("Unknown C++ cast!");
986 case tok::kw_const_cast: CastName = "const_cast"; break;
987 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
988 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
989 case tok::kw_static_cast: CastName = "static_cast"; break;
992 SourceLocation OpLoc = ConsumeToken();
993 SourceLocation LAngleBracketLoc = Tok.getLocation();
995 // Check for "<::" which is parsed as "[:". If found, fix token stream,
996 // diagnose error, suggest fix, and recover parsing.
997 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
998 Token Next = NextToken();
999 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1000 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1003 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1006 // Parse the common declaration-specifiers piece.
1007 DeclSpec DS(AttrFactory);
1008 ParseSpecifierQualifierList(DS);
1010 // Parse the abstract-declarator, if present.
1011 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1012 ParseDeclarator(DeclaratorInfo);
1014 SourceLocation RAngleBracketLoc = Tok.getLocation();
1016 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
1017 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
1019 SourceLocation LParenLoc, RParenLoc;
1020 BalancedDelimiterTracker T(*this, tok::l_paren);
1022 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1025 ExprResult Result = ParseExpression();
1030 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1031 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1032 LAngleBracketLoc, DeclaratorInfo,
1034 T.getOpenLocation(), Result.take(),
1035 T.getCloseLocation());
1040 /// ParseCXXTypeid - This handles the C++ typeid expression.
1042 /// postfix-expression: [C++ 5.2p1]
1043 /// 'typeid' '(' expression ')'
1044 /// 'typeid' '(' type-id ')'
1046 ExprResult Parser::ParseCXXTypeid() {
1047 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1049 SourceLocation OpLoc = ConsumeToken();
1050 SourceLocation LParenLoc, RParenLoc;
1051 BalancedDelimiterTracker T(*this, tok::l_paren);
1053 // typeid expressions are always parenthesized.
1054 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1056 LParenLoc = T.getOpenLocation();
1060 // C++0x [expr.typeid]p3:
1061 // When typeid is applied to an expression other than an lvalue of a
1062 // polymorphic class type [...] The expression is an unevaluated
1063 // operand (Clause 5).
1065 // Note that we can't tell whether the expression is an lvalue of a
1066 // polymorphic class type until after we've parsed the expression; we
1067 // speculatively assume the subexpression is unevaluated, and fix it up
1070 // We enter the unevaluated context before trying to determine whether we
1071 // have a type-id, because the tentative parse logic will try to resolve
1072 // names, and must treat them as unevaluated.
1073 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1074 Sema::ReuseLambdaContextDecl);
1076 if (isTypeIdInParens()) {
1077 TypeResult Ty = ParseTypeName();
1081 RParenLoc = T.getCloseLocation();
1082 if (Ty.isInvalid() || RParenLoc.isInvalid())
1085 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1086 Ty.get().getAsOpaquePtr(), RParenLoc);
1088 Result = ParseExpression();
1091 if (Result.isInvalid())
1092 SkipUntil(tok::r_paren);
1095 RParenLoc = T.getCloseLocation();
1096 if (RParenLoc.isInvalid())
1099 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1100 Result.release(), RParenLoc);
1107 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1109 /// '__uuidof' '(' expression ')'
1110 /// '__uuidof' '(' type-id ')'
1112 ExprResult Parser::ParseCXXUuidof() {
1113 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1115 SourceLocation OpLoc = ConsumeToken();
1116 BalancedDelimiterTracker T(*this, tok::l_paren);
1118 // __uuidof expressions are always parenthesized.
1119 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1124 if (isTypeIdInParens()) {
1125 TypeResult Ty = ParseTypeName();
1133 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1134 Ty.get().getAsOpaquePtr(),
1135 T.getCloseLocation());
1137 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1138 Result = ParseExpression();
1141 if (Result.isInvalid())
1142 SkipUntil(tok::r_paren);
1146 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1148 Result.release(), T.getCloseLocation());
1155 /// \brief Parse a C++ pseudo-destructor expression after the base,
1156 /// . or -> operator, and nested-name-specifier have already been
1159 /// postfix-expression: [C++ 5.2]
1160 /// postfix-expression . pseudo-destructor-name
1161 /// postfix-expression -> pseudo-destructor-name
1163 /// pseudo-destructor-name:
1164 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1165 /// ::[opt] nested-name-specifier template simple-template-id ::
1167 /// ::[opt] nested-name-specifier[opt] ~type-name
1170 Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1171 tok::TokenKind OpKind,
1173 ParsedType ObjectType) {
1174 // We're parsing either a pseudo-destructor-name or a dependent
1175 // member access that has the same form as a
1176 // pseudo-destructor-name. We parse both in the same way and let
1177 // the action model sort them out.
1179 // Note that the ::[opt] nested-name-specifier[opt] has already
1180 // been parsed, and if there was a simple-template-id, it has
1181 // been coalesced into a template-id annotation token.
1182 UnqualifiedId FirstTypeName;
1183 SourceLocation CCLoc;
1184 if (Tok.is(tok::identifier)) {
1185 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1187 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1188 CCLoc = ConsumeToken();
1189 } else if (Tok.is(tok::annot_template_id)) {
1190 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1191 // store it in the pseudo-dtor node (to be used when instantiating it).
1192 FirstTypeName.setTemplateId(
1193 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1195 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1196 CCLoc = ConsumeToken();
1198 FirstTypeName.setIdentifier(0, SourceLocation());
1202 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1203 SourceLocation TildeLoc = ConsumeToken();
1205 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1206 DeclSpec DS(AttrFactory);
1207 ParseDecltypeSpecifier(DS);
1208 if (DS.getTypeSpecType() == TST_error)
1210 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1211 OpKind, TildeLoc, DS,
1212 Tok.is(tok::l_paren));
1215 if (!Tok.is(tok::identifier)) {
1216 Diag(Tok, diag::err_destructor_tilde_identifier);
1220 // Parse the second type.
1221 UnqualifiedId SecondTypeName;
1222 IdentifierInfo *Name = Tok.getIdentifierInfo();
1223 SourceLocation NameLoc = ConsumeToken();
1224 SecondTypeName.setIdentifier(Name, NameLoc);
1226 // If there is a '<', the second type name is a template-id. Parse
1228 if (Tok.is(tok::less) &&
1229 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1231 false, ObjectType, SecondTypeName,
1232 /*AssumeTemplateName=*/true))
1235 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1237 SS, FirstTypeName, CCLoc,
1238 TildeLoc, SecondTypeName,
1239 Tok.is(tok::l_paren));
1242 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1244 /// boolean-literal: [C++ 2.13.5]
1247 ExprResult Parser::ParseCXXBoolLiteral() {
1248 tok::TokenKind Kind = Tok.getKind();
1249 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1252 /// ParseThrowExpression - This handles the C++ throw expression.
1254 /// throw-expression: [C++ 15]
1255 /// 'throw' assignment-expression[opt]
1256 ExprResult Parser::ParseThrowExpression() {
1257 assert(Tok.is(tok::kw_throw) && "Not throw!");
1258 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1260 // If the current token isn't the start of an assignment-expression,
1261 // then the expression is not present. This handles things like:
1262 // "C ? throw : (void)42", which is crazy but legal.
1263 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1270 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
1273 ExprResult Expr(ParseAssignmentExpression());
1274 if (Expr.isInvalid()) return Expr;
1275 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
1279 /// ParseCXXThis - This handles the C++ 'this' pointer.
1281 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1282 /// a non-lvalue expression whose value is the address of the object for which
1283 /// the function is called.
1284 ExprResult Parser::ParseCXXThis() {
1285 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1286 SourceLocation ThisLoc = ConsumeToken();
1287 return Actions.ActOnCXXThis(ThisLoc);
1290 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1291 /// Can be interpreted either as function-style casting ("int(x)")
1292 /// or class type construction ("ClassType(x,y,z)")
1293 /// or creation of a value-initialized type ("int()").
1294 /// See [C++ 5.2.3].
1296 /// postfix-expression: [C++ 5.2p1]
1297 /// simple-type-specifier '(' expression-list[opt] ')'
1298 /// [C++0x] simple-type-specifier braced-init-list
1299 /// typename-specifier '(' expression-list[opt] ')'
1300 /// [C++0x] typename-specifier braced-init-list
1303 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1304 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1305 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1307 assert((Tok.is(tok::l_paren) ||
1308 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1309 && "Expected '(' or '{'!");
1311 if (Tok.is(tok::l_brace)) {
1312 ExprResult Init = ParseBraceInitializer();
1313 if (Init.isInvalid())
1315 Expr *InitList = Init.take();
1316 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1317 MultiExprArg(&InitList, 1),
1320 BalancedDelimiterTracker T(*this, tok::l_paren);
1324 CommaLocsTy CommaLocs;
1326 if (Tok.isNot(tok::r_paren)) {
1327 if (ParseExpressionList(Exprs, CommaLocs)) {
1328 SkipUntil(tok::r_paren);
1336 // TypeRep could be null, if it references an invalid typedef.
1340 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1341 "Unexpected number of commas!");
1342 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1344 T.getCloseLocation());
1348 /// ParseCXXCondition - if/switch/while condition expression.
1352 /// type-specifier-seq declarator '=' assignment-expression
1353 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1354 /// [C++11] type-specifier-seq declarator braced-init-list
1355 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1356 /// '=' assignment-expression
1358 /// \param ExprOut if the condition was parsed as an expression, the parsed
1361 /// \param DeclOut if the condition was parsed as a declaration, the parsed
1364 /// \param Loc The location of the start of the statement that requires this
1365 /// condition, e.g., the "for" in a for loop.
1367 /// \param ConvertToBoolean Whether the condition expression should be
1368 /// converted to a boolean value.
1370 /// \returns true if there was a parsing, false otherwise.
1371 bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1374 bool ConvertToBoolean) {
1375 if (Tok.is(tok::code_completion)) {
1376 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1381 ParsedAttributesWithRange attrs(AttrFactory);
1382 MaybeParseCXX11Attributes(attrs);
1384 if (!isCXXConditionDeclaration()) {
1385 ProhibitAttributes(attrs);
1387 // Parse the expression.
1388 ExprOut = ParseExpression(); // expression
1390 if (ExprOut.isInvalid())
1393 // If required, convert to a boolean value.
1394 if (ConvertToBoolean)
1396 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1397 return ExprOut.isInvalid();
1400 // type-specifier-seq
1401 DeclSpec DS(AttrFactory);
1402 DS.takeAttributesFrom(attrs);
1403 ParseSpecifierQualifierList(DS);
1406 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1407 ParseDeclarator(DeclaratorInfo);
1409 // simple-asm-expr[opt]
1410 if (Tok.is(tok::kw_asm)) {
1412 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1413 if (AsmLabel.isInvalid()) {
1414 SkipUntil(tok::semi);
1417 DeclaratorInfo.setAsmLabel(AsmLabel.release());
1418 DeclaratorInfo.SetRangeEnd(Loc);
1421 // If attributes are present, parse them.
1422 MaybeParseGNUAttributes(DeclaratorInfo);
1424 // Type-check the declaration itself.
1425 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1427 DeclOut = Dcl.get();
1428 ExprOut = ExprError();
1430 // '=' assignment-expression
1431 // If a '==' or '+=' is found, suggest a fixit to '='.
1432 bool CopyInitialization = isTokenEqualOrEqualTypo();
1433 if (CopyInitialization)
1436 ExprResult InitExpr = ExprError();
1437 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1438 Diag(Tok.getLocation(),
1439 diag::warn_cxx98_compat_generalized_initializer_lists);
1440 InitExpr = ParseBraceInitializer();
1441 } else if (CopyInitialization) {
1442 InitExpr = ParseAssignmentExpression();
1443 } else if (Tok.is(tok::l_paren)) {
1444 // This was probably an attempt to initialize the variable.
1445 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1446 if (SkipUntil(tok::r_paren, true, /*DontConsume=*/true))
1447 RParen = ConsumeParen();
1448 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1449 diag::err_expected_init_in_condition_lparen)
1450 << SourceRange(LParen, RParen);
1452 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1453 diag::err_expected_init_in_condition);
1456 if (!InitExpr.isInvalid())
1457 Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization,
1458 DS.containsPlaceholderType());
1460 Actions.ActOnInitializerError(DeclOut);
1462 // FIXME: Build a reference to this declaration? Convert it to bool?
1463 // (This is currently handled by Sema).
1465 Actions.FinalizeDeclaration(DeclOut);
1470 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1471 /// This should only be called when the current token is known to be part of
1472 /// simple-type-specifier.
1474 /// simple-type-specifier:
1475 /// '::'[opt] nested-name-specifier[opt] type-name
1476 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1488 /// [GNU] typeof-specifier
1489 /// [C++0x] auto [TODO]
1496 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1497 DS.SetRangeStart(Tok.getLocation());
1498 const char *PrevSpec;
1500 SourceLocation Loc = Tok.getLocation();
1502 switch (Tok.getKind()) {
1503 case tok::identifier: // foo::bar
1504 case tok::coloncolon: // ::foo::bar
1505 llvm_unreachable("Annotation token should already be formed!");
1507 llvm_unreachable("Not a simple-type-specifier token!");
1510 case tok::annot_typename: {
1511 if (getTypeAnnotation(Tok))
1512 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1513 getTypeAnnotation(Tok));
1515 DS.SetTypeSpecError();
1517 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1520 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1521 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1522 // Objective-C interface. If we don't have Objective-C or a '<', this is
1523 // just a normal reference to a typedef name.
1524 if (Tok.is(tok::less) && getLangOpts().ObjC1)
1525 ParseObjCProtocolQualifiers(DS);
1527 DS.Finish(Diags, PP);
1533 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1536 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
1538 case tok::kw___int64:
1539 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1541 case tok::kw_signed:
1542 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1544 case tok::kw_unsigned:
1545 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1548 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1551 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1554 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1556 case tok::kw___int128:
1557 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID);
1560 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
1563 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1565 case tok::kw_double:
1566 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1568 case tok::kw_wchar_t:
1569 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1571 case tok::kw_char16_t:
1572 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1574 case tok::kw_char32_t:
1575 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1578 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1580 case tok::annot_decltype:
1581 case tok::kw_decltype:
1582 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1583 return DS.Finish(Diags, PP);
1585 // GNU typeof support.
1586 case tok::kw_typeof:
1587 ParseTypeofSpecifier(DS);
1588 DS.Finish(Diags, PP);
1591 if (Tok.is(tok::annot_typename))
1592 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1594 DS.SetRangeEnd(Tok.getLocation());
1596 DS.Finish(Diags, PP);
1599 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1600 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1601 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1602 /// by parsing the type-specifier-seq, because these sequences are
1603 /// typically followed by some form of declarator. Returns true and
1604 /// emits diagnostics if this is not a type-specifier-seq, false
1607 /// type-specifier-seq: [C++ 8.1]
1608 /// type-specifier type-specifier-seq[opt]
1610 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1611 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1612 DS.Finish(Diags, PP);
1616 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1619 /// This routine is invoked when a '<' is encountered after an identifier or
1620 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1621 /// whether the unqualified-id is actually a template-id. This routine will
1622 /// then parse the template arguments and form the appropriate template-id to
1623 /// return to the caller.
1625 /// \param SS the nested-name-specifier that precedes this template-id, if
1626 /// we're actually parsing a qualified-id.
1628 /// \param Name for constructor and destructor names, this is the actual
1629 /// identifier that may be a template-name.
1631 /// \param NameLoc the location of the class-name in a constructor or
1634 /// \param EnteringContext whether we're entering the scope of the
1635 /// nested-name-specifier.
1637 /// \param ObjectType if this unqualified-id occurs within a member access
1638 /// expression, the type of the base object whose member is being accessed.
1640 /// \param Id as input, describes the template-name or operator-function-id
1641 /// that precedes the '<'. If template arguments were parsed successfully,
1642 /// will be updated with the template-id.
1644 /// \param AssumeTemplateId When true, this routine will assume that the name
1645 /// refers to a template without performing name lookup to verify.
1647 /// \returns true if a parse error occurred, false otherwise.
1648 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1649 SourceLocation TemplateKWLoc,
1650 IdentifierInfo *Name,
1651 SourceLocation NameLoc,
1652 bool EnteringContext,
1653 ParsedType ObjectType,
1655 bool AssumeTemplateId) {
1656 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1657 "Expected '<' to finish parsing a template-id");
1659 TemplateTy Template;
1660 TemplateNameKind TNK = TNK_Non_template;
1661 switch (Id.getKind()) {
1662 case UnqualifiedId::IK_Identifier:
1663 case UnqualifiedId::IK_OperatorFunctionId:
1664 case UnqualifiedId::IK_LiteralOperatorId:
1665 if (AssumeTemplateId) {
1666 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
1667 Id, ObjectType, EnteringContext,
1669 if (TNK == TNK_Non_template)
1672 bool MemberOfUnknownSpecialization;
1673 TNK = Actions.isTemplateName(getCurScope(), SS,
1674 TemplateKWLoc.isValid(), Id,
1675 ObjectType, EnteringContext, Template,
1676 MemberOfUnknownSpecialization);
1678 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1679 ObjectType && IsTemplateArgumentList()) {
1680 // We have something like t->getAs<T>(), where getAs is a
1681 // member of an unknown specialization. However, this will only
1682 // parse correctly as a template, so suggest the keyword 'template'
1683 // before 'getAs' and treat this as a dependent template name.
1685 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1686 Name = Id.Identifier->getName();
1689 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1690 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1692 Name += Id.Identifier->getName();
1694 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1696 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1697 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1698 SS, TemplateKWLoc, Id,
1699 ObjectType, EnteringContext,
1701 if (TNK == TNK_Non_template)
1707 case UnqualifiedId::IK_ConstructorName: {
1708 UnqualifiedId TemplateName;
1709 bool MemberOfUnknownSpecialization;
1710 TemplateName.setIdentifier(Name, NameLoc);
1711 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1712 TemplateName, ObjectType,
1713 EnteringContext, Template,
1714 MemberOfUnknownSpecialization);
1718 case UnqualifiedId::IK_DestructorName: {
1719 UnqualifiedId TemplateName;
1720 bool MemberOfUnknownSpecialization;
1721 TemplateName.setIdentifier(Name, NameLoc);
1723 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1724 SS, TemplateKWLoc, TemplateName,
1725 ObjectType, EnteringContext,
1727 if (TNK == TNK_Non_template)
1730 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1731 TemplateName, ObjectType,
1732 EnteringContext, Template,
1733 MemberOfUnknownSpecialization);
1735 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
1736 Diag(NameLoc, diag::err_destructor_template_id)
1737 << Name << SS.getRange();
1748 if (TNK == TNK_Non_template)
1751 // Parse the enclosed template argument list.
1752 SourceLocation LAngleLoc, RAngleLoc;
1753 TemplateArgList TemplateArgs;
1754 if (Tok.is(tok::less) &&
1755 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
1756 SS, true, LAngleLoc,
1761 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
1762 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1763 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
1764 // Form a parsed representation of the template-id to be stored in the
1766 TemplateIdAnnotation *TemplateId
1767 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1769 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1770 TemplateId->Name = Id.Identifier;
1771 TemplateId->Operator = OO_None;
1772 TemplateId->TemplateNameLoc = Id.StartLocation;
1774 TemplateId->Name = 0;
1775 TemplateId->Operator = Id.OperatorFunctionId.Operator;
1776 TemplateId->TemplateNameLoc = Id.StartLocation;
1779 TemplateId->SS = SS;
1780 TemplateId->TemplateKWLoc = TemplateKWLoc;
1781 TemplateId->Template = Template;
1782 TemplateId->Kind = TNK;
1783 TemplateId->LAngleLoc = LAngleLoc;
1784 TemplateId->RAngleLoc = RAngleLoc;
1785 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1786 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
1787 Arg != ArgEnd; ++Arg)
1788 Args[Arg] = TemplateArgs[Arg];
1790 Id.setTemplateId(TemplateId);
1794 // Bundle the template arguments together.
1795 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1797 // Constructor and destructor names.
1799 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1801 LAngleLoc, TemplateArgsPtr, RAngleLoc,
1802 /*IsCtorOrDtorName=*/true);
1803 if (Type.isInvalid())
1806 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1807 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1809 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1814 /// \brief Parse an operator-function-id or conversion-function-id as part
1815 /// of a C++ unqualified-id.
1817 /// This routine is responsible only for parsing the operator-function-id or
1818 /// conversion-function-id; it does not handle template arguments in any way.
1821 /// operator-function-id: [C++ 13.5]
1822 /// 'operator' operator
1824 /// operator: one of
1825 /// new delete new[] delete[]
1826 /// + - * / % ^ & | ~
1827 /// ! = < > += -= *= /= %=
1828 /// ^= &= |= << >> >>= <<= == !=
1829 /// <= >= && || ++ -- , ->* ->
1832 /// conversion-function-id: [C++ 12.3.2]
1833 /// operator conversion-type-id
1835 /// conversion-type-id:
1836 /// type-specifier-seq conversion-declarator[opt]
1838 /// conversion-declarator:
1839 /// ptr-operator conversion-declarator[opt]
1842 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
1843 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
1845 /// \param EnteringContext whether we are entering the scope of the
1846 /// nested-name-specifier.
1848 /// \param ObjectType if this unqualified-id occurs within a member access
1849 /// expression, the type of the base object whose member is being accessed.
1851 /// \param Result on a successful parse, contains the parsed unqualified-id.
1853 /// \returns true if parsing fails, false otherwise.
1854 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
1855 ParsedType ObjectType,
1856 UnqualifiedId &Result) {
1857 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
1859 // Consume the 'operator' keyword.
1860 SourceLocation KeywordLoc = ConsumeToken();
1862 // Determine what kind of operator name we have.
1863 unsigned SymbolIdx = 0;
1864 SourceLocation SymbolLocations[3];
1865 OverloadedOperatorKind Op = OO_None;
1866 switch (Tok.getKind()) {
1868 case tok::kw_delete: {
1869 bool isNew = Tok.getKind() == tok::kw_new;
1870 // Consume the 'new' or 'delete'.
1871 SymbolLocations[SymbolIdx++] = ConsumeToken();
1872 // Check for array new/delete.
1873 if (Tok.is(tok::l_square) &&
1874 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
1875 // Consume the '[' and ']'.
1876 BalancedDelimiterTracker T(*this, tok::l_square);
1879 if (T.getCloseLocation().isInvalid())
1882 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1883 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1884 Op = isNew? OO_Array_New : OO_Array_Delete;
1886 Op = isNew? OO_New : OO_Delete;
1891 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1893 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
1896 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
1897 #include "clang/Basic/OperatorKinds.def"
1899 case tok::l_paren: {
1900 // Consume the '(' and ')'.
1901 BalancedDelimiterTracker T(*this, tok::l_paren);
1904 if (T.getCloseLocation().isInvalid())
1907 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1908 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1913 case tok::l_square: {
1914 // Consume the '[' and ']'.
1915 BalancedDelimiterTracker T(*this, tok::l_square);
1918 if (T.getCloseLocation().isInvalid())
1921 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1922 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1927 case tok::code_completion: {
1928 // Code completion for the operator name.
1929 Actions.CodeCompleteOperatorName(getCurScope());
1931 // Don't try to parse any further.
1939 if (Op != OO_None) {
1940 // We have parsed an operator-function-id.
1941 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
1945 // Parse a literal-operator-id.
1947 // literal-operator-id: C++11 [over.literal]
1948 // operator string-literal identifier
1949 // operator user-defined-string-literal
1951 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
1952 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
1954 SourceLocation DiagLoc;
1955 unsigned DiagId = 0;
1957 // We're past translation phase 6, so perform string literal concatenation
1958 // before checking for "".
1959 SmallVector<Token, 4> Toks;
1960 SmallVector<SourceLocation, 4> TokLocs;
1961 while (isTokenStringLiteral()) {
1962 if (!Tok.is(tok::string_literal) && !DiagId) {
1963 // C++11 [over.literal]p1:
1964 // The string-literal or user-defined-string-literal in a
1965 // literal-operator-id shall have no encoding-prefix [...].
1966 DiagLoc = Tok.getLocation();
1967 DiagId = diag::err_literal_operator_string_prefix;
1969 Toks.push_back(Tok);
1970 TokLocs.push_back(ConsumeStringToken());
1973 StringLiteralParser Literal(Toks.data(), Toks.size(), PP);
1974 if (Literal.hadError)
1977 // Grab the literal operator's suffix, which will be either the next token
1978 // or a ud-suffix from the string literal.
1979 IdentifierInfo *II = 0;
1980 SourceLocation SuffixLoc;
1981 if (!Literal.getUDSuffix().empty()) {
1982 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
1984 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
1985 Literal.getUDSuffixOffset(),
1986 PP.getSourceManager(), getLangOpts());
1987 } else if (Tok.is(tok::identifier)) {
1988 II = Tok.getIdentifierInfo();
1989 SuffixLoc = ConsumeToken();
1990 TokLocs.push_back(SuffixLoc);
1992 Diag(Tok.getLocation(), diag::err_expected_ident);
1996 // The string literal must be empty.
1997 if (!Literal.GetString().empty() || Literal.Pascal) {
1998 // C++11 [over.literal]p1:
1999 // The string-literal or user-defined-string-literal in a
2000 // literal-operator-id shall [...] contain no characters
2001 // other than the implicit terminating '\0'.
2002 DiagLoc = TokLocs.front();
2003 DiagId = diag::err_literal_operator_string_not_empty;
2007 // This isn't a valid literal-operator-id, but we think we know
2008 // what the user meant. Tell them what they should have written.
2009 SmallString<32> Str;
2011 Str += II->getName();
2012 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2013 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2016 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2020 // Parse a conversion-function-id.
2022 // conversion-function-id: [C++ 12.3.2]
2023 // operator conversion-type-id
2025 // conversion-type-id:
2026 // type-specifier-seq conversion-declarator[opt]
2028 // conversion-declarator:
2029 // ptr-operator conversion-declarator[opt]
2031 // Parse the type-specifier-seq.
2032 DeclSpec DS(AttrFactory);
2033 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2036 // Parse the conversion-declarator, which is merely a sequence of
2038 Declarator D(DS, Declarator::ConversionIdContext);
2039 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
2041 // Finish up the type.
2042 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2046 // Note that this is a conversion-function-id.
2047 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2048 D.getSourceRange().getEnd());
2052 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2053 /// name of an entity.
2056 /// unqualified-id: [C++ expr.prim.general]
2058 /// operator-function-id
2059 /// conversion-function-id
2060 /// [C++0x] literal-operator-id [TODO]
2066 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2067 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2069 /// \param EnteringContext whether we are entering the scope of the
2070 /// nested-name-specifier.
2072 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2074 /// \param AllowConstructorName whether we allow parsing a constructor name.
2076 /// \param ObjectType if this unqualified-id occurs within a member access
2077 /// expression, the type of the base object whose member is being accessed.
2079 /// \param Result on a successful parse, contains the parsed unqualified-id.
2081 /// \returns true if parsing fails, false otherwise.
2082 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2083 bool AllowDestructorName,
2084 bool AllowConstructorName,
2085 ParsedType ObjectType,
2086 SourceLocation& TemplateKWLoc,
2087 UnqualifiedId &Result) {
2089 // Handle 'A::template B'. This is for template-ids which have not
2090 // already been annotated by ParseOptionalCXXScopeSpecifier().
2091 bool TemplateSpecified = false;
2092 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2093 (ObjectType || SS.isSet())) {
2094 TemplateSpecified = true;
2095 TemplateKWLoc = ConsumeToken();
2100 // template-id (when it hasn't already been annotated)
2101 if (Tok.is(tok::identifier)) {
2102 // Consume the identifier.
2103 IdentifierInfo *Id = Tok.getIdentifierInfo();
2104 SourceLocation IdLoc = ConsumeToken();
2106 if (!getLangOpts().CPlusPlus) {
2107 // If we're not in C++, only identifiers matter. Record the
2108 // identifier and return.
2109 Result.setIdentifier(Id, IdLoc);
2113 if (AllowConstructorName &&
2114 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2115 // We have parsed a constructor name.
2116 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2119 /*IsCtorOrDtorName=*/true,
2120 /*NonTrivialTypeSourceInfo=*/true);
2121 Result.setConstructorName(Ty, IdLoc, IdLoc);
2123 // We have parsed an identifier.
2124 Result.setIdentifier(Id, IdLoc);
2127 // If the next token is a '<', we may have a template.
2128 if (TemplateSpecified || Tok.is(tok::less))
2129 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2130 EnteringContext, ObjectType,
2131 Result, TemplateSpecified);
2137 // template-id (already parsed and annotated)
2138 if (Tok.is(tok::annot_template_id)) {
2139 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2141 // If the template-name names the current class, then this is a constructor
2142 if (AllowConstructorName && TemplateId->Name &&
2143 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2145 // C++ [class.qual]p2 specifies that a qualified template-name
2146 // is taken as the constructor name where a constructor can be
2147 // declared. Thus, the template arguments are extraneous, so
2148 // complain about them and remove them entirely.
2149 Diag(TemplateId->TemplateNameLoc,
2150 diag::err_out_of_line_constructor_template_id)
2152 << FixItHint::CreateRemoval(
2153 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2154 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2155 TemplateId->TemplateNameLoc,
2159 /*IsCtorOrDtorName=*/true,
2160 /*NontrivialTypeSourceInfo=*/true);
2161 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2162 TemplateId->RAngleLoc);
2167 Result.setConstructorTemplateId(TemplateId);
2172 // We have already parsed a template-id; consume the annotation token as
2173 // our unqualified-id.
2174 Result.setTemplateId(TemplateId);
2175 TemplateKWLoc = TemplateId->TemplateKWLoc;
2181 // operator-function-id
2182 // conversion-function-id
2183 if (Tok.is(tok::kw_operator)) {
2184 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2187 // If we have an operator-function-id or a literal-operator-id and the next
2188 // token is a '<', we may have a
2191 // operator-function-id < template-argument-list[opt] >
2192 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2193 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2194 (TemplateSpecified || Tok.is(tok::less)))
2195 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2196 0, SourceLocation(),
2197 EnteringContext, ObjectType,
2198 Result, TemplateSpecified);
2203 if (getLangOpts().CPlusPlus &&
2204 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2205 // C++ [expr.unary.op]p10:
2206 // There is an ambiguity in the unary-expression ~X(), where X is a
2207 // class-name. The ambiguity is resolved in favor of treating ~ as a
2208 // unary complement rather than treating ~X as referring to a destructor.
2211 SourceLocation TildeLoc = ConsumeToken();
2213 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2214 DeclSpec DS(AttrFactory);
2215 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2216 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2217 Result.setDestructorName(TildeLoc, Type, EndLoc);
2223 // Parse the class-name.
2224 if (Tok.isNot(tok::identifier)) {
2225 Diag(Tok, diag::err_destructor_tilde_identifier);
2229 // Parse the class-name (or template-name in a simple-template-id).
2230 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2231 SourceLocation ClassNameLoc = ConsumeToken();
2233 if (TemplateSpecified || Tok.is(tok::less)) {
2234 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
2235 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2236 ClassName, ClassNameLoc,
2237 EnteringContext, ObjectType,
2238 Result, TemplateSpecified);
2241 // Note that this is a destructor name.
2242 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2243 ClassNameLoc, getCurScope(),
2249 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2253 Diag(Tok, diag::err_expected_unqualified_id)
2254 << getLangOpts().CPlusPlus;
2258 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2259 /// memory in a typesafe manner and call constructors.
2261 /// This method is called to parse the new expression after the optional :: has
2262 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2263 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2266 /// '::'[opt] 'new' new-placement[opt] new-type-id
2267 /// new-initializer[opt]
2268 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2269 /// new-initializer[opt]
2272 /// '(' expression-list ')'
2275 /// type-specifier-seq new-declarator[opt]
2276 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2279 /// ptr-operator new-declarator[opt]
2280 /// direct-new-declarator
2282 /// new-initializer:
2283 /// '(' expression-list[opt] ')'
2284 /// [C++0x] braced-init-list
2287 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2288 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2289 ConsumeToken(); // Consume 'new'
2291 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2292 // second form of new-expression. It can't be a new-type-id.
2294 ExprVector PlacementArgs;
2295 SourceLocation PlacementLParen, PlacementRParen;
2297 SourceRange TypeIdParens;
2298 DeclSpec DS(AttrFactory);
2299 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2300 if (Tok.is(tok::l_paren)) {
2301 // If it turns out to be a placement, we change the type location.
2302 BalancedDelimiterTracker T(*this, tok::l_paren);
2304 PlacementLParen = T.getOpenLocation();
2305 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2306 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2311 PlacementRParen = T.getCloseLocation();
2312 if (PlacementRParen.isInvalid()) {
2313 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2317 if (PlacementArgs.empty()) {
2318 // Reset the placement locations. There was no placement.
2319 TypeIdParens = T.getRange();
2320 PlacementLParen = PlacementRParen = SourceLocation();
2322 // We still need the type.
2323 if (Tok.is(tok::l_paren)) {
2324 BalancedDelimiterTracker T(*this, tok::l_paren);
2326 MaybeParseGNUAttributes(DeclaratorInfo);
2327 ParseSpecifierQualifierList(DS);
2328 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2329 ParseDeclarator(DeclaratorInfo);
2331 TypeIdParens = T.getRange();
2333 MaybeParseGNUAttributes(DeclaratorInfo);
2334 if (ParseCXXTypeSpecifierSeq(DS))
2335 DeclaratorInfo.setInvalidType(true);
2337 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2338 ParseDeclaratorInternal(DeclaratorInfo,
2339 &Parser::ParseDirectNewDeclarator);
2344 // A new-type-id is a simplified type-id, where essentially the
2345 // direct-declarator is replaced by a direct-new-declarator.
2346 MaybeParseGNUAttributes(DeclaratorInfo);
2347 if (ParseCXXTypeSpecifierSeq(DS))
2348 DeclaratorInfo.setInvalidType(true);
2350 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2351 ParseDeclaratorInternal(DeclaratorInfo,
2352 &Parser::ParseDirectNewDeclarator);
2355 if (DeclaratorInfo.isInvalidType()) {
2356 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2360 ExprResult Initializer;
2362 if (Tok.is(tok::l_paren)) {
2363 SourceLocation ConstructorLParen, ConstructorRParen;
2364 ExprVector ConstructorArgs;
2365 BalancedDelimiterTracker T(*this, tok::l_paren);
2367 ConstructorLParen = T.getOpenLocation();
2368 if (Tok.isNot(tok::r_paren)) {
2369 CommaLocsTy CommaLocs;
2370 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2371 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2376 ConstructorRParen = T.getCloseLocation();
2377 if (ConstructorRParen.isInvalid()) {
2378 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2381 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2384 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2385 Diag(Tok.getLocation(),
2386 diag::warn_cxx98_compat_generalized_initializer_lists);
2387 Initializer = ParseBraceInitializer();
2389 if (Initializer.isInvalid())
2392 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2393 PlacementArgs, PlacementRParen,
2394 TypeIdParens, DeclaratorInfo, Initializer.take());
2397 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2398 /// passed to ParseDeclaratorInternal.
2400 /// direct-new-declarator:
2401 /// '[' expression ']'
2402 /// direct-new-declarator '[' constant-expression ']'
2404 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2405 // Parse the array dimensions.
2407 while (Tok.is(tok::l_square)) {
2408 // An array-size expression can't start with a lambda.
2409 if (CheckProhibitedCXX11Attribute())
2412 BalancedDelimiterTracker T(*this, tok::l_square);
2415 ExprResult Size(first ? ParseExpression()
2416 : ParseConstantExpression());
2417 if (Size.isInvalid()) {
2419 SkipUntil(tok::r_square);
2426 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2427 ParsedAttributes Attrs(AttrFactory);
2428 MaybeParseCXX11Attributes(Attrs);
2430 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2431 /*static=*/false, /*star=*/false,
2433 T.getOpenLocation(),
2434 T.getCloseLocation()),
2435 Attrs, T.getCloseLocation());
2437 if (T.getCloseLocation().isInvalid())
2442 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2443 /// This ambiguity appears in the syntax of the C++ new operator.
2446 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2447 /// new-initializer[opt]
2450 /// '(' expression-list ')'
2452 bool Parser::ParseExpressionListOrTypeId(
2453 SmallVectorImpl<Expr*> &PlacementArgs,
2455 // The '(' was already consumed.
2456 if (isTypeIdInParens()) {
2457 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2458 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2460 return D.isInvalidType();
2463 // It's not a type, it has to be an expression list.
2464 // Discard the comma locations - ActOnCXXNew has enough parameters.
2465 CommaLocsTy CommaLocs;
2466 return ParseExpressionList(PlacementArgs, CommaLocs);
2469 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2470 /// to free memory allocated by new.
2472 /// This method is called to parse the 'delete' expression after the optional
2473 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2474 /// and "Start" is its location. Otherwise, "Start" is the location of the
2477 /// delete-expression:
2478 /// '::'[opt] 'delete' cast-expression
2479 /// '::'[opt] 'delete' '[' ']' cast-expression
2481 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2482 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2483 ConsumeToken(); // Consume 'delete'
2486 bool ArrayDelete = false;
2487 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2488 // C++11 [expr.delete]p1:
2489 // Whenever the delete keyword is followed by empty square brackets, it
2490 // shall be interpreted as [array delete].
2491 // [Footnote: A lambda expression with a lambda-introducer that consists
2492 // of empty square brackets can follow the delete keyword if
2493 // the lambda expression is enclosed in parentheses.]
2494 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2495 // lambda-introducer.
2497 BalancedDelimiterTracker T(*this, tok::l_square);
2501 if (T.getCloseLocation().isInvalid())
2505 ExprResult Operand(ParseCastExpression(false));
2506 if (Operand.isInvalid())
2509 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
2512 static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
2514 default: llvm_unreachable("Not a known unary type trait.");
2515 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign;
2516 case tok::kw___has_nothrow_move_assign: return UTT_HasNothrowMoveAssign;
2517 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
2518 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy;
2519 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign;
2520 case tok::kw___has_trivial_move_assign: return UTT_HasTrivialMoveAssign;
2521 case tok::kw___has_trivial_constructor:
2522 return UTT_HasTrivialDefaultConstructor;
2523 case tok::kw___has_trivial_move_constructor:
2524 return UTT_HasTrivialMoveConstructor;
2525 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy;
2526 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor;
2527 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor;
2528 case tok::kw___is_abstract: return UTT_IsAbstract;
2529 case tok::kw___is_arithmetic: return UTT_IsArithmetic;
2530 case tok::kw___is_array: return UTT_IsArray;
2531 case tok::kw___is_class: return UTT_IsClass;
2532 case tok::kw___is_complete_type: return UTT_IsCompleteType;
2533 case tok::kw___is_compound: return UTT_IsCompound;
2534 case tok::kw___is_const: return UTT_IsConst;
2535 case tok::kw___is_empty: return UTT_IsEmpty;
2536 case tok::kw___is_enum: return UTT_IsEnum;
2537 case tok::kw___is_final: return UTT_IsFinal;
2538 case tok::kw___is_floating_point: return UTT_IsFloatingPoint;
2539 case tok::kw___is_function: return UTT_IsFunction;
2540 case tok::kw___is_fundamental: return UTT_IsFundamental;
2541 case tok::kw___is_integral: return UTT_IsIntegral;
2542 case tok::kw___is_interface_class: return UTT_IsInterfaceClass;
2543 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference;
2544 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer;
2545 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer;
2546 case tok::kw___is_member_pointer: return UTT_IsMemberPointer;
2547 case tok::kw___is_object: return UTT_IsObject;
2548 case tok::kw___is_literal: return UTT_IsLiteral;
2549 case tok::kw___is_literal_type: return UTT_IsLiteral;
2550 case tok::kw___is_pod: return UTT_IsPOD;
2551 case tok::kw___is_pointer: return UTT_IsPointer;
2552 case tok::kw___is_polymorphic: return UTT_IsPolymorphic;
2553 case tok::kw___is_reference: return UTT_IsReference;
2554 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference;
2555 case tok::kw___is_scalar: return UTT_IsScalar;
2556 case tok::kw___is_signed: return UTT_IsSigned;
2557 case tok::kw___is_standard_layout: return UTT_IsStandardLayout;
2558 case tok::kw___is_trivial: return UTT_IsTrivial;
2559 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable;
2560 case tok::kw___is_union: return UTT_IsUnion;
2561 case tok::kw___is_unsigned: return UTT_IsUnsigned;
2562 case tok::kw___is_void: return UTT_IsVoid;
2563 case tok::kw___is_volatile: return UTT_IsVolatile;
2567 static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) {
2569 default: llvm_unreachable("Not a known binary type trait");
2570 case tok::kw___is_base_of: return BTT_IsBaseOf;
2571 case tok::kw___is_convertible: return BTT_IsConvertible;
2572 case tok::kw___is_same: return BTT_IsSame;
2573 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible;
2574 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo;
2575 case tok::kw___is_trivially_assignable: return BTT_IsTriviallyAssignable;
2579 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2581 default: llvm_unreachable("Not a known type trait");
2582 case tok::kw___is_trivially_constructible:
2583 return TT_IsTriviallyConstructible;
2587 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2589 default: llvm_unreachable("Not a known binary type trait");
2590 case tok::kw___array_rank: return ATT_ArrayRank;
2591 case tok::kw___array_extent: return ATT_ArrayExtent;
2595 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2597 default: llvm_unreachable("Not a known unary expression trait.");
2598 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2599 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2603 /// ParseUnaryTypeTrait - Parse the built-in unary type-trait
2604 /// pseudo-functions that allow implementation of the TR1/C++0x type traits
2607 /// primary-expression:
2608 /// [GNU] unary-type-trait '(' type-id ')'
2610 ExprResult Parser::ParseUnaryTypeTrait() {
2611 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
2612 SourceLocation Loc = ConsumeToken();
2614 BalancedDelimiterTracker T(*this, tok::l_paren);
2615 if (T.expectAndConsume(diag::err_expected_lparen))
2618 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
2619 // there will be cryptic errors about mismatched parentheses and missing
2621 TypeResult Ty = ParseTypeName();
2628 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), T.getCloseLocation());
2631 /// ParseBinaryTypeTrait - Parse the built-in binary type-trait
2632 /// pseudo-functions that allow implementation of the TR1/C++0x type traits
2635 /// primary-expression:
2636 /// [GNU] binary-type-trait '(' type-id ',' type-id ')'
2638 ExprResult Parser::ParseBinaryTypeTrait() {
2639 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind());
2640 SourceLocation Loc = ConsumeToken();
2642 BalancedDelimiterTracker T(*this, tok::l_paren);
2643 if (T.expectAndConsume(diag::err_expected_lparen))
2646 TypeResult LhsTy = ParseTypeName();
2647 if (LhsTy.isInvalid()) {
2648 SkipUntil(tok::r_paren);
2652 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2653 SkipUntil(tok::r_paren);
2657 TypeResult RhsTy = ParseTypeName();
2658 if (RhsTy.isInvalid()) {
2659 SkipUntil(tok::r_paren);
2665 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(),
2666 T.getCloseLocation());
2669 /// \brief Parse the built-in type-trait pseudo-functions that allow
2670 /// implementation of the TR1/C++11 type traits templates.
2672 /// primary-expression:
2673 /// type-trait '(' type-id-seq ')'
2676 /// type-id ...[opt] type-id-seq[opt]
2678 ExprResult Parser::ParseTypeTrait() {
2679 TypeTrait Kind = TypeTraitFromTokKind(Tok.getKind());
2680 SourceLocation Loc = ConsumeToken();
2682 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2683 if (Parens.expectAndConsume(diag::err_expected_lparen))
2686 SmallVector<ParsedType, 2> Args;
2688 // Parse the next type.
2689 TypeResult Ty = ParseTypeName();
2690 if (Ty.isInvalid()) {
2695 // Parse the ellipsis, if present.
2696 if (Tok.is(tok::ellipsis)) {
2697 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2698 if (Ty.isInvalid()) {
2704 // Add this type to the list of arguments.
2705 Args.push_back(Ty.get());
2707 if (Tok.is(tok::comma)) {
2715 if (Parens.consumeClose())
2718 return Actions.ActOnTypeTrait(Kind, Loc, Args, Parens.getCloseLocation());
2721 /// ParseArrayTypeTrait - Parse the built-in array type-trait
2722 /// pseudo-functions.
2724 /// primary-expression:
2725 /// [Embarcadero] '__array_rank' '(' type-id ')'
2726 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2728 ExprResult Parser::ParseArrayTypeTrait() {
2729 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2730 SourceLocation Loc = ConsumeToken();
2732 BalancedDelimiterTracker T(*this, tok::l_paren);
2733 if (T.expectAndConsume(diag::err_expected_lparen))
2736 TypeResult Ty = ParseTypeName();
2737 if (Ty.isInvalid()) {
2738 SkipUntil(tok::comma);
2739 SkipUntil(tok::r_paren);
2744 case ATT_ArrayRank: {
2746 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL,
2747 T.getCloseLocation());
2749 case ATT_ArrayExtent: {
2750 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2751 SkipUntil(tok::r_paren);
2755 ExprResult DimExpr = ParseExpression();
2758 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2759 T.getCloseLocation());
2762 llvm_unreachable("Invalid ArrayTypeTrait!");
2765 /// ParseExpressionTrait - Parse built-in expression-trait
2766 /// pseudo-functions like __is_lvalue_expr( xxx ).
2768 /// primary-expression:
2769 /// [Embarcadero] expression-trait '(' expression ')'
2771 ExprResult Parser::ParseExpressionTrait() {
2772 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2773 SourceLocation Loc = ConsumeToken();
2775 BalancedDelimiterTracker T(*this, tok::l_paren);
2776 if (T.expectAndConsume(diag::err_expected_lparen))
2779 ExprResult Expr = ParseExpression();
2783 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2784 T.getCloseLocation());
2788 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2789 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2790 /// based on the context past the parens.
2792 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
2794 BalancedDelimiterTracker &Tracker) {
2795 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
2796 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2797 assert(isTypeIdInParens() && "Not a type-id!");
2799 ExprResult Result(true);
2800 CastTy = ParsedType();
2802 // We need to disambiguate a very ugly part of the C++ syntax:
2804 // (T())x; - type-id
2805 // (T())*x; - type-id
2806 // (T())/x; - expression
2807 // (T()); - expression
2809 // The bad news is that we cannot use the specialized tentative parser, since
2810 // it can only verify that the thing inside the parens can be parsed as
2811 // type-id, it is not useful for determining the context past the parens.
2813 // The good news is that the parser can disambiguate this part without
2814 // making any unnecessary Action calls.
2816 // It uses a scheme similar to parsing inline methods. The parenthesized
2817 // tokens are cached, the context that follows is determined (possibly by
2818 // parsing a cast-expression), and then we re-introduce the cached tokens
2819 // into the token stream and parse them appropriately.
2821 ParenParseOption ParseAs;
2824 // Store the tokens of the parentheses. We will parse them after we determine
2825 // the context that follows them.
2826 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
2827 // We didn't find the ')' we expected.
2828 Tracker.consumeClose();
2832 if (Tok.is(tok::l_brace)) {
2833 ParseAs = CompoundLiteral;
2836 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2837 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2840 // Try parsing the cast-expression that may follow.
2841 // If it is not a cast-expression, NotCastExpr will be true and no token
2842 // will be consumed.
2843 Result = ParseCastExpression(false/*isUnaryExpression*/,
2844 false/*isAddressofOperand*/,
2846 // type-id has priority.
2850 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2852 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
2855 // The current token should go after the cached tokens.
2856 Toks.push_back(Tok);
2857 // Re-enter the stored parenthesized tokens into the token stream, so we may
2859 PP.EnterTokenStream(Toks.data(), Toks.size(),
2860 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2861 // Drop the current token and bring the first cached one. It's the same token
2862 // as when we entered this function.
2865 if (ParseAs >= CompoundLiteral) {
2866 // Parse the type declarator.
2867 DeclSpec DS(AttrFactory);
2868 ParseSpecifierQualifierList(DS);
2869 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2870 ParseDeclarator(DeclaratorInfo);
2873 Tracker.consumeClose();
2875 if (ParseAs == CompoundLiteral) {
2876 ExprType = CompoundLiteral;
2877 TypeResult Ty = ParseTypeName();
2878 return ParseCompoundLiteralExpression(Ty.get(),
2879 Tracker.getOpenLocation(),
2880 Tracker.getCloseLocation());
2883 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
2884 assert(ParseAs == CastExpr);
2886 if (DeclaratorInfo.isInvalidType())
2889 // Result is what ParseCastExpression returned earlier.
2890 if (!Result.isInvalid())
2891 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
2892 DeclaratorInfo, CastTy,
2893 Tracker.getCloseLocation(), Result.take());
2897 // Not a compound literal, and not followed by a cast-expression.
2898 assert(ParseAs == SimpleExpr);
2900 ExprType = SimpleExpr;
2901 Result = ParseExpression();
2902 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2903 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
2904 Tok.getLocation(), Result.take());
2907 if (Result.isInvalid()) {
2908 SkipUntil(tok::r_paren);
2912 Tracker.consumeClose();