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/ParseDiagnostic.h"
15 #include "clang/Parse/Parser.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/Basic/PrettyStackTrace.h"
18 #include "clang/Lex/LiteralSupport.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/Scope.h"
21 #include "clang/Sema/ParsedTemplate.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 it 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 /// member access expression, e.g., the \p T:: in \p p->T::m.
174 /// \returns true if there was an error parsing a scope specifier
175 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
176 ParsedType ObjectType,
177 bool EnteringContext,
178 bool *MayBePseudoDestructor,
180 assert(getLangOpts().CPlusPlus &&
181 "Call sites of this function should be guarded by checking for C++");
183 if (Tok.is(tok::annot_cxxscope)) {
184 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
185 Tok.getAnnotationRange(),
191 bool HasScopeSpecifier = false;
193 if (Tok.is(tok::coloncolon)) {
194 // ::new and ::delete aren't nested-name-specifiers.
195 tok::TokenKind NextKind = NextToken().getKind();
196 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
199 // '::' - Global scope qualifier.
200 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
203 CheckForLParenAfterColonColon();
205 HasScopeSpecifier = true;
208 bool CheckForDestructor = false;
209 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
210 CheckForDestructor = true;
211 *MayBePseudoDestructor = false;
214 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
215 DeclSpec DS(AttrFactory);
216 SourceLocation DeclLoc = Tok.getLocation();
217 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
218 if (Tok.isNot(tok::coloncolon)) {
219 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
223 SourceLocation CCLoc = ConsumeToken();
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 = ParsedType();
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 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
285 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
286 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
287 Diag(TemplateName.getSourceRange().getBegin(),
288 diag::err_id_after_template_in_nested_name_spec)
289 << TemplateName.getSourceRange();
298 // If the next token is not '<', we have a qualified-id that refers
299 // to a template name, such as T::template apply, but is not a
301 if (Tok.isNot(tok::less)) {
306 // Commit to parsing the template-id.
309 if (TemplateNameKind TNK
310 = Actions.ActOnDependentTemplateName(getCurScope(),
311 SS, TemplateKWLoc, TemplateName,
312 ObjectType, EnteringContext,
314 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
315 TemplateName, false))
323 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
326 // simple-template-id '::'
328 // So we need to check whether the simple-template-id is of the
329 // right kind (it should name a type or be dependent), and then
330 // convert it into a type within the nested-name-specifier.
331 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
332 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
333 *MayBePseudoDestructor = true;
337 // Consume the template-id token.
340 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
341 SourceLocation CCLoc = ConsumeToken();
343 HasScopeSpecifier = true;
345 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
346 TemplateId->NumArgs);
348 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
350 TemplateId->TemplateKWLoc,
351 TemplateId->Template,
352 TemplateId->TemplateNameLoc,
353 TemplateId->LAngleLoc,
355 TemplateId->RAngleLoc,
358 SourceLocation StartLoc
359 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
360 : TemplateId->TemplateNameLoc;
361 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
368 // The rest of the nested-name-specifier possibilities start with
370 if (Tok.isNot(tok::identifier))
373 IdentifierInfo &II = *Tok.getIdentifierInfo();
375 // nested-name-specifier:
377 // namespace-name '::'
378 // nested-name-specifier identifier '::'
379 Token Next = NextToken();
381 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
382 // and emit a fixit hint for it.
383 if (Next.is(tok::colon) && !ColonIsSacred) {
384 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
386 Next.getLocation(), ObjectType,
388 // If the token after the colon isn't an identifier, it's still an
389 // error, but they probably meant something else strange so don't
390 // recover like this.
391 PP.LookAhead(1).is(tok::identifier)) {
392 Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
393 << FixItHint::CreateReplacement(Next.getLocation(), "::");
395 // Recover as if the user wrote '::'.
396 Next.setKind(tok::coloncolon);
400 if (Next.is(tok::coloncolon)) {
401 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
402 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
404 *MayBePseudoDestructor = true;
408 // We have an identifier followed by a '::'. Lookup this name
409 // as the name in a nested-name-specifier.
410 SourceLocation IdLoc = ConsumeToken();
411 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
412 "NextToken() not working properly!");
413 SourceLocation CCLoc = ConsumeToken();
415 CheckForLParenAfterColonColon();
417 HasScopeSpecifier = true;
418 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
419 ObjectType, EnteringContext, SS))
420 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
425 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
427 // nested-name-specifier:
429 if (Next.is(tok::less)) {
431 UnqualifiedId TemplateName;
432 TemplateName.setIdentifier(&II, Tok.getLocation());
433 bool MemberOfUnknownSpecialization;
434 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
435 /*hasTemplateKeyword=*/false,
440 MemberOfUnknownSpecialization)) {
441 // We have found a template name, so annotate this token
442 // with a template-id annotation. We do not permit the
443 // template-id to be translated into a type annotation,
444 // because some clients (e.g., the parsing of class template
445 // specializations) still want to see the original template-id
448 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
449 TemplateName, false))
454 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
455 (IsTypename || IsTemplateArgumentList(1))) {
456 // We have something like t::getAs<T>, where getAs is a
457 // member of an unknown specialization. However, this will only
458 // parse correctly as a template, so suggest the keyword 'template'
459 // before 'getAs' and treat this as a dependent template name.
460 unsigned DiagID = diag::err_missing_dependent_template_keyword;
461 if (getLangOpts().MicrosoftExt)
462 DiagID = diag::warn_missing_dependent_template_keyword;
464 Diag(Tok.getLocation(), DiagID)
466 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
468 if (TemplateNameKind TNK
469 = Actions.ActOnDependentTemplateName(getCurScope(),
470 SS, SourceLocation(),
471 TemplateName, ObjectType,
472 EnteringContext, Template)) {
473 // Consume the identifier.
475 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
476 TemplateName, false))
486 // We don't have any tokens that form the beginning of a
487 // nested-name-specifier, so we're done.
491 // Even if we didn't see any pieces of a nested-name-specifier, we
492 // still check whether there is a tilde in this position, which
493 // indicates a potential pseudo-destructor.
494 if (CheckForDestructor && Tok.is(tok::tilde))
495 *MayBePseudoDestructor = true;
500 /// ParseCXXIdExpression - Handle id-expression.
507 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
509 /// '::' operator-function-id
512 /// NOTE: The standard specifies that, for qualified-id, the parser does not
515 /// '::' conversion-function-id
516 /// '::' '~' class-name
518 /// This may cause a slight inconsistency on diagnostics:
523 /// :: A :: ~ C(); // Some Sema error about using destructor with a
525 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
528 /// We simplify the parser a bit and make it work like:
531 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
532 /// '::' unqualified-id
534 /// That way Sema can handle and report similar errors for namespaces and the
537 /// The isAddressOfOperand parameter indicates that this id-expression is a
538 /// direct operand of the address-of operator. This is, besides member contexts,
539 /// the only place where a qualified-id naming a non-static class member may
542 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
544 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
545 // '::' unqualified-id
548 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
550 SourceLocation TemplateKWLoc;
552 if (ParseUnqualifiedId(SS,
553 /*EnteringContext=*/false,
554 /*AllowDestructorName=*/false,
555 /*AllowConstructorName=*/false,
556 /*ObjectType=*/ ParsedType(),
561 // This is only the direct operand of an & operator if it is not
562 // followed by a postfix-expression suffix.
563 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
564 isAddressOfOperand = false;
566 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
567 Tok.is(tok::l_paren), isAddressOfOperand);
570 /// ParseLambdaExpression - Parse a C++0x lambda expression.
572 /// lambda-expression:
573 /// lambda-introducer lambda-declarator[opt] compound-statement
575 /// lambda-introducer:
576 /// '[' lambda-capture[opt] ']'
581 /// capture-default ',' capture-list
589 /// capture-list ',' capture
596 /// lambda-declarator:
597 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
598 /// 'mutable'[opt] exception-specification[opt]
599 /// trailing-return-type[opt]
601 ExprResult Parser::ParseLambdaExpression() {
602 // Parse lambda-introducer.
603 LambdaIntroducer Intro;
605 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
607 Diag(Tok, DiagID.getValue());
608 SkipUntil(tok::r_square);
609 SkipUntil(tok::l_brace);
610 SkipUntil(tok::r_brace);
614 return ParseLambdaExpressionAfterIntroducer(Intro);
617 /// TryParseLambdaExpression - Use lookahead and potentially tentative
618 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
621 /// If we are not looking at a lambda expression, returns ExprError().
622 ExprResult Parser::TryParseLambdaExpression() {
623 assert(getLangOpts().CPlusPlus0x
624 && Tok.is(tok::l_square)
625 && "Not at the start of a possible lambda expression.");
627 const Token Next = NextToken(), After = GetLookAheadToken(2);
629 // If lookahead indicates this is a lambda...
630 if (Next.is(tok::r_square) || // []
631 Next.is(tok::equal) || // [=
632 (Next.is(tok::amp) && // [&] or [&,
633 (After.is(tok::r_square) ||
634 After.is(tok::comma))) ||
635 (Next.is(tok::identifier) && // [identifier]
636 After.is(tok::r_square))) {
637 return ParseLambdaExpression();
640 // If lookahead indicates an ObjC message send...
641 // [identifier identifier
642 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
646 // Here, we're stuck: lambda introducers and Objective-C message sends are
647 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
648 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
649 // writing two routines to parse a lambda introducer, just try to parse
650 // a lambda introducer first, and fall back if that fails.
651 // (TryParseLambdaIntroducer never produces any diagnostic output.)
652 LambdaIntroducer Intro;
653 if (TryParseLambdaIntroducer(Intro))
655 return ParseLambdaExpressionAfterIntroducer(Intro);
658 /// ParseLambdaExpression - Parse a lambda introducer.
660 /// Returns a DiagnosticID if it hit something unexpected.
661 llvm::Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro){
662 typedef llvm::Optional<unsigned> DiagResult;
664 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
665 BalancedDelimiterTracker T(*this, tok::l_square);
668 Intro.Range.setBegin(T.getOpenLocation());
672 // Parse capture-default.
673 if (Tok.is(tok::amp) &&
674 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
675 Intro.Default = LCD_ByRef;
676 Intro.DefaultLoc = ConsumeToken();
678 } else if (Tok.is(tok::equal)) {
679 Intro.Default = LCD_ByCopy;
680 Intro.DefaultLoc = ConsumeToken();
684 while (Tok.isNot(tok::r_square)) {
686 if (Tok.isNot(tok::comma)) {
687 // Provide a completion for a lambda introducer here. Except
688 // in Objective-C, where this is Almost Surely meant to be a message
689 // send. In that case, fail here and let the ObjC message
690 // expression parser perform the completion.
691 if (Tok.is(tok::code_completion) &&
692 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
693 !Intro.Captures.empty())) {
694 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
695 /*AfterAmpersand=*/false);
696 ConsumeCodeCompletionToken();
700 return DiagResult(diag::err_expected_comma_or_rsquare);
705 if (Tok.is(tok::code_completion)) {
706 // If we're in Objective-C++ and we have a bare '[', then this is more
707 // likely to be a message receiver.
708 if (getLangOpts().ObjC1 && first)
709 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
711 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
712 /*AfterAmpersand=*/false);
713 ConsumeCodeCompletionToken();
720 LambdaCaptureKind Kind = LCK_ByCopy;
722 IdentifierInfo* Id = 0;
723 SourceLocation EllipsisLoc;
725 if (Tok.is(tok::kw_this)) {
727 Loc = ConsumeToken();
729 if (Tok.is(tok::amp)) {
733 if (Tok.is(tok::code_completion)) {
734 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
735 /*AfterAmpersand=*/true);
736 ConsumeCodeCompletionToken();
741 if (Tok.is(tok::identifier)) {
742 Id = Tok.getIdentifierInfo();
743 Loc = ConsumeToken();
745 if (Tok.is(tok::ellipsis))
746 EllipsisLoc = ConsumeToken();
747 } else if (Tok.is(tok::kw_this)) {
748 // FIXME: If we want to suggest a fixit here, will need to return more
749 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
750 // Clear()ed to prevent emission in case of tentative parsing?
751 return DiagResult(diag::err_this_captured_by_reference);
753 return DiagResult(diag::err_expected_capture);
757 Intro.addCapture(Kind, Loc, Id, EllipsisLoc);
761 Intro.Range.setEnd(T.getCloseLocation());
766 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
768 /// Returns true if it hit something unexpected.
769 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
770 TentativeParsingAction PA(*this);
772 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
783 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
785 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
786 LambdaIntroducer &Intro) {
787 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
788 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
790 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
791 "lambda expression parsing");
793 // Parse lambda-declarator[opt].
794 DeclSpec DS(AttrFactory);
795 Declarator D(DS, Declarator::LambdaExprContext);
797 if (Tok.is(tok::l_paren)) {
798 ParseScope PrototypeScope(this,
799 Scope::FunctionPrototypeScope |
802 SourceLocation DeclEndLoc;
803 BalancedDelimiterTracker T(*this, tok::l_paren);
805 SourceLocation LParenLoc = T.getOpenLocation();
807 // Parse parameter-declaration-clause.
808 ParsedAttributes Attr(AttrFactory);
809 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
810 SourceLocation EllipsisLoc;
812 if (Tok.isNot(tok::r_paren))
813 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
816 SourceLocation RParenLoc = T.getCloseLocation();
817 DeclEndLoc = RParenLoc;
819 // Parse 'mutable'[opt].
820 SourceLocation MutableLoc;
821 if (Tok.is(tok::kw_mutable)) {
822 MutableLoc = ConsumeToken();
823 DeclEndLoc = MutableLoc;
826 // Parse exception-specification[opt].
827 ExceptionSpecificationType ESpecType = EST_None;
828 SourceRange ESpecRange;
829 llvm::SmallVector<ParsedType, 2> DynamicExceptions;
830 llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
831 ExprResult NoexceptExpr;
832 ESpecType = tryParseExceptionSpecification(ESpecRange,
834 DynamicExceptionRanges,
837 if (ESpecType != EST_None)
838 DeclEndLoc = ESpecRange.getEnd();
840 // Parse attribute-specifier[opt].
841 MaybeParseCXX0XAttributes(Attr, &DeclEndLoc);
843 SourceLocation FunLocalRangeEnd = DeclEndLoc;
845 // Parse trailing-return-type[opt].
846 TypeResult TrailingReturnType;
847 if (Tok.is(tok::arrow)) {
848 FunLocalRangeEnd = Tok.getLocation();
850 TrailingReturnType = ParseTrailingReturnType(Range);
851 if (Range.getEnd().isValid())
852 DeclEndLoc = Range.getEnd();
855 PrototypeScope.Exit();
857 SourceLocation NoLoc;
858 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
859 /*isAmbiguous=*/false,
861 ParamInfo.data(), ParamInfo.size(),
862 EllipsisLoc, RParenLoc,
863 DS.getTypeQualifiers(),
864 /*RefQualifierIsLValueRef=*/true,
865 /*RefQualifierLoc=*/NoLoc,
866 /*ConstQualifierLoc=*/NoLoc,
867 /*VolatileQualifierLoc=*/NoLoc,
869 ESpecType, ESpecRange.getBegin(),
870 DynamicExceptions.data(),
871 DynamicExceptionRanges.data(),
872 DynamicExceptions.size(),
873 NoexceptExpr.isUsable() ?
874 NoexceptExpr.get() : 0,
875 LParenLoc, FunLocalRangeEnd, D,
878 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) {
879 // It's common to forget that one needs '()' before 'mutable' or the
880 // result type. Deal with this.
881 Diag(Tok, diag::err_lambda_missing_parens)
882 << Tok.is(tok::arrow)
883 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
884 SourceLocation DeclLoc = Tok.getLocation();
885 SourceLocation DeclEndLoc = DeclLoc;
887 // Parse 'mutable', if it's there.
888 SourceLocation MutableLoc;
889 if (Tok.is(tok::kw_mutable)) {
890 MutableLoc = ConsumeToken();
891 DeclEndLoc = MutableLoc;
894 // Parse the return type, if there is one.
895 TypeResult TrailingReturnType;
896 if (Tok.is(tok::arrow)) {
898 TrailingReturnType = ParseTrailingReturnType(Range);
899 if (Range.getEnd().isValid())
900 DeclEndLoc = Range.getEnd();
903 ParsedAttributes Attr(AttrFactory);
904 SourceLocation NoLoc;
905 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
906 /*isAmbiguous=*/false,
910 /*EllipsisLoc=*/NoLoc,
913 /*RefQualifierIsLValueRef=*/true,
914 /*RefQualifierLoc=*/NoLoc,
915 /*ConstQualifierLoc=*/NoLoc,
916 /*VolatileQualifierLoc=*/NoLoc,
921 /*ExceptionRanges=*/0,
924 DeclLoc, DeclEndLoc, D,
930 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
932 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
933 ParseScope BodyScope(this, ScopeFlags);
935 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
937 // Parse compound-statement.
938 if (!Tok.is(tok::l_brace)) {
939 Diag(Tok, diag::err_expected_lambda_body);
940 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
944 StmtResult Stmt(ParseCompoundStatementBody());
947 if (!Stmt.isInvalid())
948 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope());
950 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
954 /// ParseCXXCasts - This handles the various ways to cast expressions to another
957 /// postfix-expression: [C++ 5.2p1]
958 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
959 /// 'static_cast' '<' type-name '>' '(' expression ')'
960 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
961 /// 'const_cast' '<' type-name '>' '(' expression ')'
963 ExprResult Parser::ParseCXXCasts() {
964 tok::TokenKind Kind = Tok.getKind();
965 const char *CastName = 0; // For error messages
968 default: llvm_unreachable("Unknown C++ cast!");
969 case tok::kw_const_cast: CastName = "const_cast"; break;
970 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
971 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
972 case tok::kw_static_cast: CastName = "static_cast"; break;
975 SourceLocation OpLoc = ConsumeToken();
976 SourceLocation LAngleBracketLoc = Tok.getLocation();
978 // Check for "<::" which is parsed as "[:". If found, fix token stream,
979 // diagnose error, suggest fix, and recover parsing.
980 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
981 Token Next = NextToken();
982 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
983 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
986 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
989 // Parse the common declaration-specifiers piece.
990 DeclSpec DS(AttrFactory);
991 ParseSpecifierQualifierList(DS);
993 // Parse the abstract-declarator, if present.
994 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
995 ParseDeclarator(DeclaratorInfo);
997 SourceLocation RAngleBracketLoc = Tok.getLocation();
999 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
1000 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
1002 SourceLocation LParenLoc, RParenLoc;
1003 BalancedDelimiterTracker T(*this, tok::l_paren);
1005 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1008 ExprResult Result = ParseExpression();
1013 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1014 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1015 LAngleBracketLoc, DeclaratorInfo,
1017 T.getOpenLocation(), Result.take(),
1018 T.getCloseLocation());
1023 /// ParseCXXTypeid - This handles the C++ typeid expression.
1025 /// postfix-expression: [C++ 5.2p1]
1026 /// 'typeid' '(' expression ')'
1027 /// 'typeid' '(' type-id ')'
1029 ExprResult Parser::ParseCXXTypeid() {
1030 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1032 SourceLocation OpLoc = ConsumeToken();
1033 SourceLocation LParenLoc, RParenLoc;
1034 BalancedDelimiterTracker T(*this, tok::l_paren);
1036 // typeid expressions are always parenthesized.
1037 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1039 LParenLoc = T.getOpenLocation();
1043 // C++0x [expr.typeid]p3:
1044 // When typeid is applied to an expression other than an lvalue of a
1045 // polymorphic class type [...] The expression is an unevaluated
1046 // operand (Clause 5).
1048 // Note that we can't tell whether the expression is an lvalue of a
1049 // polymorphic class type until after we've parsed the expression; we
1050 // speculatively assume the subexpression is unevaluated, and fix it up
1053 // We enter the unevaluated context before trying to determine whether we
1054 // have a type-id, because the tentative parse logic will try to resolve
1055 // names, and must treat them as unevaluated.
1056 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1057 Sema::ReuseLambdaContextDecl);
1059 if (isTypeIdInParens()) {
1060 TypeResult Ty = ParseTypeName();
1064 RParenLoc = T.getCloseLocation();
1065 if (Ty.isInvalid() || RParenLoc.isInvalid())
1068 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1069 Ty.get().getAsOpaquePtr(), RParenLoc);
1071 Result = ParseExpression();
1074 if (Result.isInvalid())
1075 SkipUntil(tok::r_paren);
1078 RParenLoc = T.getCloseLocation();
1079 if (RParenLoc.isInvalid())
1082 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1083 Result.release(), RParenLoc);
1090 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1092 /// '__uuidof' '(' expression ')'
1093 /// '__uuidof' '(' type-id ')'
1095 ExprResult Parser::ParseCXXUuidof() {
1096 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1098 SourceLocation OpLoc = ConsumeToken();
1099 BalancedDelimiterTracker T(*this, tok::l_paren);
1101 // __uuidof expressions are always parenthesized.
1102 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1107 if (isTypeIdInParens()) {
1108 TypeResult Ty = ParseTypeName();
1116 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1117 Ty.get().getAsOpaquePtr(),
1118 T.getCloseLocation());
1120 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1121 Result = ParseExpression();
1124 if (Result.isInvalid())
1125 SkipUntil(tok::r_paren);
1129 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1131 Result.release(), T.getCloseLocation());
1138 /// \brief Parse a C++ pseudo-destructor expression after the base,
1139 /// . or -> operator, and nested-name-specifier have already been
1142 /// postfix-expression: [C++ 5.2]
1143 /// postfix-expression . pseudo-destructor-name
1144 /// postfix-expression -> pseudo-destructor-name
1146 /// pseudo-destructor-name:
1147 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1148 /// ::[opt] nested-name-specifier template simple-template-id ::
1150 /// ::[opt] nested-name-specifier[opt] ~type-name
1153 Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1154 tok::TokenKind OpKind,
1156 ParsedType ObjectType) {
1157 // We're parsing either a pseudo-destructor-name or a dependent
1158 // member access that has the same form as a
1159 // pseudo-destructor-name. We parse both in the same way and let
1160 // the action model sort them out.
1162 // Note that the ::[opt] nested-name-specifier[opt] has already
1163 // been parsed, and if there was a simple-template-id, it has
1164 // been coalesced into a template-id annotation token.
1165 UnqualifiedId FirstTypeName;
1166 SourceLocation CCLoc;
1167 if (Tok.is(tok::identifier)) {
1168 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1170 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1171 CCLoc = ConsumeToken();
1172 } else if (Tok.is(tok::annot_template_id)) {
1173 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1174 // store it in the pseudo-dtor node (to be used when instantiating it).
1175 FirstTypeName.setTemplateId(
1176 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1178 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1179 CCLoc = ConsumeToken();
1181 FirstTypeName.setIdentifier(0, SourceLocation());
1185 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1186 SourceLocation TildeLoc = ConsumeToken();
1188 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1189 DeclSpec DS(AttrFactory);
1190 ParseDecltypeSpecifier(DS);
1191 if (DS.getTypeSpecType() == TST_error)
1193 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1194 OpKind, TildeLoc, DS,
1195 Tok.is(tok::l_paren));
1198 if (!Tok.is(tok::identifier)) {
1199 Diag(Tok, diag::err_destructor_tilde_identifier);
1203 // Parse the second type.
1204 UnqualifiedId SecondTypeName;
1205 IdentifierInfo *Name = Tok.getIdentifierInfo();
1206 SourceLocation NameLoc = ConsumeToken();
1207 SecondTypeName.setIdentifier(Name, NameLoc);
1209 // If there is a '<', the second type name is a template-id. Parse
1211 if (Tok.is(tok::less) &&
1212 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1214 false, ObjectType, SecondTypeName,
1215 /*AssumeTemplateName=*/true))
1218 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1220 SS, FirstTypeName, CCLoc,
1221 TildeLoc, SecondTypeName,
1222 Tok.is(tok::l_paren));
1225 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1227 /// boolean-literal: [C++ 2.13.5]
1230 ExprResult Parser::ParseCXXBoolLiteral() {
1231 tok::TokenKind Kind = Tok.getKind();
1232 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1235 /// ParseThrowExpression - This handles the C++ throw expression.
1237 /// throw-expression: [C++ 15]
1238 /// 'throw' assignment-expression[opt]
1239 ExprResult Parser::ParseThrowExpression() {
1240 assert(Tok.is(tok::kw_throw) && "Not throw!");
1241 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1243 // If the current token isn't the start of an assignment-expression,
1244 // then the expression is not present. This handles things like:
1245 // "C ? throw : (void)42", which is crazy but legal.
1246 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1253 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
1256 ExprResult Expr(ParseAssignmentExpression());
1257 if (Expr.isInvalid()) return Expr;
1258 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
1262 /// ParseCXXThis - This handles the C++ 'this' pointer.
1264 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1265 /// a non-lvalue expression whose value is the address of the object for which
1266 /// the function is called.
1267 ExprResult Parser::ParseCXXThis() {
1268 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1269 SourceLocation ThisLoc = ConsumeToken();
1270 return Actions.ActOnCXXThis(ThisLoc);
1273 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1274 /// Can be interpreted either as function-style casting ("int(x)")
1275 /// or class type construction ("ClassType(x,y,z)")
1276 /// or creation of a value-initialized type ("int()").
1277 /// See [C++ 5.2.3].
1279 /// postfix-expression: [C++ 5.2p1]
1280 /// simple-type-specifier '(' expression-list[opt] ')'
1281 /// [C++0x] simple-type-specifier braced-init-list
1282 /// typename-specifier '(' expression-list[opt] ')'
1283 /// [C++0x] typename-specifier braced-init-list
1286 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1287 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1288 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1290 assert((Tok.is(tok::l_paren) ||
1291 (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)))
1292 && "Expected '(' or '{'!");
1294 if (Tok.is(tok::l_brace)) {
1295 ExprResult Init = ParseBraceInitializer();
1296 if (Init.isInvalid())
1298 Expr *InitList = Init.take();
1299 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1300 MultiExprArg(&InitList, 1),
1303 BalancedDelimiterTracker T(*this, tok::l_paren);
1307 CommaLocsTy CommaLocs;
1309 if (Tok.isNot(tok::r_paren)) {
1310 if (ParseExpressionList(Exprs, CommaLocs)) {
1311 SkipUntil(tok::r_paren);
1319 // TypeRep could be null, if it references an invalid typedef.
1323 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1324 "Unexpected number of commas!");
1325 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1327 T.getCloseLocation());
1331 /// ParseCXXCondition - if/switch/while condition expression.
1335 /// type-specifier-seq declarator '=' assignment-expression
1336 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1337 /// [C++11] type-specifier-seq declarator braced-init-list
1338 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1339 /// '=' assignment-expression
1341 /// \param ExprOut if the condition was parsed as an expression, the parsed
1344 /// \param DeclOut if the condition was parsed as a declaration, the parsed
1347 /// \param Loc The location of the start of the statement that requires this
1348 /// condition, e.g., the "for" in a for loop.
1350 /// \param ConvertToBoolean Whether the condition expression should be
1351 /// converted to a boolean value.
1353 /// \returns true if there was a parsing, false otherwise.
1354 bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1357 bool ConvertToBoolean) {
1358 if (Tok.is(tok::code_completion)) {
1359 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1364 ParsedAttributesWithRange attrs(AttrFactory);
1365 MaybeParseCXX0XAttributes(attrs);
1367 if (!isCXXConditionDeclaration()) {
1368 ProhibitAttributes(attrs);
1370 // Parse the expression.
1371 ExprOut = ParseExpression(); // expression
1373 if (ExprOut.isInvalid())
1376 // If required, convert to a boolean value.
1377 if (ConvertToBoolean)
1379 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1380 return ExprOut.isInvalid();
1383 // type-specifier-seq
1384 DeclSpec DS(AttrFactory);
1385 ParseSpecifierQualifierList(DS);
1388 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1389 ParseDeclarator(DeclaratorInfo);
1391 // simple-asm-expr[opt]
1392 if (Tok.is(tok::kw_asm)) {
1394 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1395 if (AsmLabel.isInvalid()) {
1396 SkipUntil(tok::semi);
1399 DeclaratorInfo.setAsmLabel(AsmLabel.release());
1400 DeclaratorInfo.SetRangeEnd(Loc);
1403 // If attributes are present, parse them.
1404 MaybeParseGNUAttributes(DeclaratorInfo);
1406 // Type-check the declaration itself.
1407 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1409 DeclOut = Dcl.get();
1410 ExprOut = ExprError();
1412 // '=' assignment-expression
1413 // If a '==' or '+=' is found, suggest a fixit to '='.
1414 bool CopyInitialization = isTokenEqualOrEqualTypo();
1415 if (CopyInitialization)
1418 ExprResult InitExpr = ExprError();
1419 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
1420 Diag(Tok.getLocation(),
1421 diag::warn_cxx98_compat_generalized_initializer_lists);
1422 InitExpr = ParseBraceInitializer();
1423 } else if (CopyInitialization) {
1424 InitExpr = ParseAssignmentExpression();
1425 } else if (Tok.is(tok::l_paren)) {
1426 // This was probably an attempt to initialize the variable.
1427 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1428 if (SkipUntil(tok::r_paren, true, /*DontConsume=*/true))
1429 RParen = ConsumeParen();
1430 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1431 diag::err_expected_init_in_condition_lparen)
1432 << SourceRange(LParen, RParen);
1434 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1435 diag::err_expected_init_in_condition);
1438 if (!InitExpr.isInvalid())
1439 Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization,
1440 DS.getTypeSpecType() == DeclSpec::TST_auto);
1442 // FIXME: Build a reference to this declaration? Convert it to bool?
1443 // (This is currently handled by Sema).
1445 Actions.FinalizeDeclaration(DeclOut);
1450 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1451 /// This should only be called when the current token is known to be part of
1452 /// simple-type-specifier.
1454 /// simple-type-specifier:
1455 /// '::'[opt] nested-name-specifier[opt] type-name
1456 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1468 /// [GNU] typeof-specifier
1469 /// [C++0x] auto [TODO]
1476 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1477 DS.SetRangeStart(Tok.getLocation());
1478 const char *PrevSpec;
1480 SourceLocation Loc = Tok.getLocation();
1482 switch (Tok.getKind()) {
1483 case tok::identifier: // foo::bar
1484 case tok::coloncolon: // ::foo::bar
1485 llvm_unreachable("Annotation token should already be formed!");
1487 llvm_unreachable("Not a simple-type-specifier token!");
1490 case tok::annot_typename: {
1491 if (getTypeAnnotation(Tok))
1492 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1493 getTypeAnnotation(Tok));
1495 DS.SetTypeSpecError();
1497 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1500 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1501 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1502 // Objective-C interface. If we don't have Objective-C or a '<', this is
1503 // just a normal reference to a typedef name.
1504 if (Tok.is(tok::less) && getLangOpts().ObjC1)
1505 ParseObjCProtocolQualifiers(DS);
1507 DS.Finish(Diags, PP);
1513 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1516 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
1518 case tok::kw___int64:
1519 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1521 case tok::kw_signed:
1522 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1524 case tok::kw_unsigned:
1525 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1528 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1531 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1534 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1536 case tok::kw___int128:
1537 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID);
1540 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
1543 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1545 case tok::kw_double:
1546 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1548 case tok::kw_wchar_t:
1549 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1551 case tok::kw_char16_t:
1552 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1554 case tok::kw_char32_t:
1555 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1558 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1560 case tok::annot_decltype:
1561 case tok::kw_decltype:
1562 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1563 return DS.Finish(Diags, PP);
1565 // GNU typeof support.
1566 case tok::kw_typeof:
1567 ParseTypeofSpecifier(DS);
1568 DS.Finish(Diags, PP);
1571 if (Tok.is(tok::annot_typename))
1572 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1574 DS.SetRangeEnd(Tok.getLocation());
1576 DS.Finish(Diags, PP);
1579 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1580 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1581 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1582 /// by parsing the type-specifier-seq, because these sequences are
1583 /// typically followed by some form of declarator. Returns true and
1584 /// emits diagnostics if this is not a type-specifier-seq, false
1587 /// type-specifier-seq: [C++ 8.1]
1588 /// type-specifier type-specifier-seq[opt]
1590 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1591 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1592 DS.Finish(Diags, PP);
1596 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1599 /// This routine is invoked when a '<' is encountered after an identifier or
1600 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1601 /// whether the unqualified-id is actually a template-id. This routine will
1602 /// then parse the template arguments and form the appropriate template-id to
1603 /// return to the caller.
1605 /// \param SS the nested-name-specifier that precedes this template-id, if
1606 /// we're actually parsing a qualified-id.
1608 /// \param Name for constructor and destructor names, this is the actual
1609 /// identifier that may be a template-name.
1611 /// \param NameLoc the location of the class-name in a constructor or
1614 /// \param EnteringContext whether we're entering the scope of the
1615 /// nested-name-specifier.
1617 /// \param ObjectType if this unqualified-id occurs within a member access
1618 /// expression, the type of the base object whose member is being accessed.
1620 /// \param Id as input, describes the template-name or operator-function-id
1621 /// that precedes the '<'. If template arguments were parsed successfully,
1622 /// will be updated with the template-id.
1624 /// \param AssumeTemplateId When true, this routine will assume that the name
1625 /// refers to a template without performing name lookup to verify.
1627 /// \returns true if a parse error occurred, false otherwise.
1628 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1629 SourceLocation TemplateKWLoc,
1630 IdentifierInfo *Name,
1631 SourceLocation NameLoc,
1632 bool EnteringContext,
1633 ParsedType ObjectType,
1635 bool AssumeTemplateId) {
1636 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1637 "Expected '<' to finish parsing a template-id");
1639 TemplateTy Template;
1640 TemplateNameKind TNK = TNK_Non_template;
1641 switch (Id.getKind()) {
1642 case UnqualifiedId::IK_Identifier:
1643 case UnqualifiedId::IK_OperatorFunctionId:
1644 case UnqualifiedId::IK_LiteralOperatorId:
1645 if (AssumeTemplateId) {
1646 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
1647 Id, ObjectType, EnteringContext,
1649 if (TNK == TNK_Non_template)
1652 bool MemberOfUnknownSpecialization;
1653 TNK = Actions.isTemplateName(getCurScope(), SS,
1654 TemplateKWLoc.isValid(), Id,
1655 ObjectType, EnteringContext, Template,
1656 MemberOfUnknownSpecialization);
1658 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1659 ObjectType && IsTemplateArgumentList()) {
1660 // We have something like t->getAs<T>(), where getAs is a
1661 // member of an unknown specialization. However, this will only
1662 // parse correctly as a template, so suggest the keyword 'template'
1663 // before 'getAs' and treat this as a dependent template name.
1665 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1666 Name = Id.Identifier->getName();
1669 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1670 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1672 Name += Id.Identifier->getName();
1674 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1676 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1677 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1678 SS, TemplateKWLoc, Id,
1679 ObjectType, EnteringContext,
1681 if (TNK == TNK_Non_template)
1687 case UnqualifiedId::IK_ConstructorName: {
1688 UnqualifiedId TemplateName;
1689 bool MemberOfUnknownSpecialization;
1690 TemplateName.setIdentifier(Name, NameLoc);
1691 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1692 TemplateName, ObjectType,
1693 EnteringContext, Template,
1694 MemberOfUnknownSpecialization);
1698 case UnqualifiedId::IK_DestructorName: {
1699 UnqualifiedId TemplateName;
1700 bool MemberOfUnknownSpecialization;
1701 TemplateName.setIdentifier(Name, NameLoc);
1703 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1704 SS, TemplateKWLoc, TemplateName,
1705 ObjectType, EnteringContext,
1707 if (TNK == TNK_Non_template)
1710 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1711 TemplateName, ObjectType,
1712 EnteringContext, Template,
1713 MemberOfUnknownSpecialization);
1715 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
1716 Diag(NameLoc, diag::err_destructor_template_id)
1717 << Name << SS.getRange();
1728 if (TNK == TNK_Non_template)
1731 // Parse the enclosed template argument list.
1732 SourceLocation LAngleLoc, RAngleLoc;
1733 TemplateArgList TemplateArgs;
1734 if (Tok.is(tok::less) &&
1735 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
1736 SS, true, LAngleLoc,
1741 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
1742 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1743 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
1744 // Form a parsed representation of the template-id to be stored in the
1746 TemplateIdAnnotation *TemplateId
1747 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1749 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1750 TemplateId->Name = Id.Identifier;
1751 TemplateId->Operator = OO_None;
1752 TemplateId->TemplateNameLoc = Id.StartLocation;
1754 TemplateId->Name = 0;
1755 TemplateId->Operator = Id.OperatorFunctionId.Operator;
1756 TemplateId->TemplateNameLoc = Id.StartLocation;
1759 TemplateId->SS = SS;
1760 TemplateId->TemplateKWLoc = TemplateKWLoc;
1761 TemplateId->Template = Template;
1762 TemplateId->Kind = TNK;
1763 TemplateId->LAngleLoc = LAngleLoc;
1764 TemplateId->RAngleLoc = RAngleLoc;
1765 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1766 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
1767 Arg != ArgEnd; ++Arg)
1768 Args[Arg] = TemplateArgs[Arg];
1770 Id.setTemplateId(TemplateId);
1774 // Bundle the template arguments together.
1775 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1777 // Constructor and destructor names.
1779 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1781 LAngleLoc, TemplateArgsPtr, RAngleLoc,
1782 /*IsCtorOrDtorName=*/true);
1783 if (Type.isInvalid())
1786 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1787 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1789 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1794 /// \brief Parse an operator-function-id or conversion-function-id as part
1795 /// of a C++ unqualified-id.
1797 /// This routine is responsible only for parsing the operator-function-id or
1798 /// conversion-function-id; it does not handle template arguments in any way.
1801 /// operator-function-id: [C++ 13.5]
1802 /// 'operator' operator
1804 /// operator: one of
1805 /// new delete new[] delete[]
1806 /// + - * / % ^ & | ~
1807 /// ! = < > += -= *= /= %=
1808 /// ^= &= |= << >> >>= <<= == !=
1809 /// <= >= && || ++ -- , ->* ->
1812 /// conversion-function-id: [C++ 12.3.2]
1813 /// operator conversion-type-id
1815 /// conversion-type-id:
1816 /// type-specifier-seq conversion-declarator[opt]
1818 /// conversion-declarator:
1819 /// ptr-operator conversion-declarator[opt]
1822 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
1823 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
1825 /// \param EnteringContext whether we are entering the scope of the
1826 /// nested-name-specifier.
1828 /// \param ObjectType if this unqualified-id occurs within a member access
1829 /// expression, the type of the base object whose member is being accessed.
1831 /// \param Result on a successful parse, contains the parsed unqualified-id.
1833 /// \returns true if parsing fails, false otherwise.
1834 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
1835 ParsedType ObjectType,
1836 UnqualifiedId &Result) {
1837 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
1839 // Consume the 'operator' keyword.
1840 SourceLocation KeywordLoc = ConsumeToken();
1842 // Determine what kind of operator name we have.
1843 unsigned SymbolIdx = 0;
1844 SourceLocation SymbolLocations[3];
1845 OverloadedOperatorKind Op = OO_None;
1846 switch (Tok.getKind()) {
1848 case tok::kw_delete: {
1849 bool isNew = Tok.getKind() == tok::kw_new;
1850 // Consume the 'new' or 'delete'.
1851 SymbolLocations[SymbolIdx++] = ConsumeToken();
1852 // Check for array new/delete.
1853 if (Tok.is(tok::l_square) &&
1854 (!getLangOpts().CPlusPlus0x || NextToken().isNot(tok::l_square))) {
1855 // Consume the '[' and ']'.
1856 BalancedDelimiterTracker T(*this, tok::l_square);
1859 if (T.getCloseLocation().isInvalid())
1862 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1863 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1864 Op = isNew? OO_Array_New : OO_Array_Delete;
1866 Op = isNew? OO_New : OO_Delete;
1871 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1873 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
1876 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
1877 #include "clang/Basic/OperatorKinds.def"
1879 case tok::l_paren: {
1880 // Consume the '(' and ')'.
1881 BalancedDelimiterTracker T(*this, tok::l_paren);
1884 if (T.getCloseLocation().isInvalid())
1887 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1888 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1893 case tok::l_square: {
1894 // Consume the '[' and ']'.
1895 BalancedDelimiterTracker T(*this, tok::l_square);
1898 if (T.getCloseLocation().isInvalid())
1901 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1902 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1907 case tok::code_completion: {
1908 // Code completion for the operator name.
1909 Actions.CodeCompleteOperatorName(getCurScope());
1911 // Don't try to parse any further.
1919 if (Op != OO_None) {
1920 // We have parsed an operator-function-id.
1921 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
1925 // Parse a literal-operator-id.
1927 // literal-operator-id: C++11 [over.literal]
1928 // operator string-literal identifier
1929 // operator user-defined-string-literal
1931 if (getLangOpts().CPlusPlus0x && isTokenStringLiteral()) {
1932 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
1934 SourceLocation DiagLoc;
1935 unsigned DiagId = 0;
1937 // We're past translation phase 6, so perform string literal concatenation
1938 // before checking for "".
1939 llvm::SmallVector<Token, 4> Toks;
1940 llvm::SmallVector<SourceLocation, 4> TokLocs;
1941 while (isTokenStringLiteral()) {
1942 if (!Tok.is(tok::string_literal) && !DiagId) {
1943 // C++11 [over.literal]p1:
1944 // The string-literal or user-defined-string-literal in a
1945 // literal-operator-id shall have no encoding-prefix [...].
1946 DiagLoc = Tok.getLocation();
1947 DiagId = diag::err_literal_operator_string_prefix;
1949 Toks.push_back(Tok);
1950 TokLocs.push_back(ConsumeStringToken());
1953 StringLiteralParser Literal(Toks.data(), Toks.size(), PP);
1954 if (Literal.hadError)
1957 // Grab the literal operator's suffix, which will be either the next token
1958 // or a ud-suffix from the string literal.
1959 IdentifierInfo *II = 0;
1960 SourceLocation SuffixLoc;
1961 if (!Literal.getUDSuffix().empty()) {
1962 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
1964 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
1965 Literal.getUDSuffixOffset(),
1966 PP.getSourceManager(), getLangOpts());
1967 } else if (Tok.is(tok::identifier)) {
1968 II = Tok.getIdentifierInfo();
1969 SuffixLoc = ConsumeToken();
1970 TokLocs.push_back(SuffixLoc);
1972 Diag(Tok.getLocation(), diag::err_expected_ident);
1976 // The string literal must be empty.
1977 if (!Literal.GetString().empty() || Literal.Pascal) {
1978 // C++11 [over.literal]p1:
1979 // The string-literal or user-defined-string-literal in a
1980 // literal-operator-id shall [...] contain no characters
1981 // other than the implicit terminating '\0'.
1982 DiagLoc = TokLocs.front();
1983 DiagId = diag::err_literal_operator_string_not_empty;
1987 // This isn't a valid literal-operator-id, but we think we know
1988 // what the user meant. Tell them what they should have written.
1989 llvm::SmallString<32> Str;
1991 Str += II->getName();
1992 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
1993 SourceRange(TokLocs.front(), TokLocs.back()), Str);
1996 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2000 // Parse a conversion-function-id.
2002 // conversion-function-id: [C++ 12.3.2]
2003 // operator conversion-type-id
2005 // conversion-type-id:
2006 // type-specifier-seq conversion-declarator[opt]
2008 // conversion-declarator:
2009 // ptr-operator conversion-declarator[opt]
2011 // Parse the type-specifier-seq.
2012 DeclSpec DS(AttrFactory);
2013 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2016 // Parse the conversion-declarator, which is merely a sequence of
2018 Declarator D(DS, Declarator::TypeNameContext);
2019 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
2021 // Finish up the type.
2022 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2026 // Note that this is a conversion-function-id.
2027 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2028 D.getSourceRange().getEnd());
2032 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2033 /// name of an entity.
2036 /// unqualified-id: [C++ expr.prim.general]
2038 /// operator-function-id
2039 /// conversion-function-id
2040 /// [C++0x] literal-operator-id [TODO]
2046 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2047 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2049 /// \param EnteringContext whether we are entering the scope of the
2050 /// nested-name-specifier.
2052 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2054 /// \param AllowConstructorName whether we allow parsing a constructor name.
2056 /// \param ObjectType if this unqualified-id occurs within a member access
2057 /// expression, the type of the base object whose member is being accessed.
2059 /// \param Result on a successful parse, contains the parsed unqualified-id.
2061 /// \returns true if parsing fails, false otherwise.
2062 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2063 bool AllowDestructorName,
2064 bool AllowConstructorName,
2065 ParsedType ObjectType,
2066 SourceLocation& TemplateKWLoc,
2067 UnqualifiedId &Result) {
2069 // Handle 'A::template B'. This is for template-ids which have not
2070 // already been annotated by ParseOptionalCXXScopeSpecifier().
2071 bool TemplateSpecified = false;
2072 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2073 (ObjectType || SS.isSet())) {
2074 TemplateSpecified = true;
2075 TemplateKWLoc = ConsumeToken();
2080 // template-id (when it hasn't already been annotated)
2081 if (Tok.is(tok::identifier)) {
2082 // Consume the identifier.
2083 IdentifierInfo *Id = Tok.getIdentifierInfo();
2084 SourceLocation IdLoc = ConsumeToken();
2086 if (!getLangOpts().CPlusPlus) {
2087 // If we're not in C++, only identifiers matter. Record the
2088 // identifier and return.
2089 Result.setIdentifier(Id, IdLoc);
2093 if (AllowConstructorName &&
2094 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2095 // We have parsed a constructor name.
2096 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2099 /*IsCtorOrDtorName=*/true,
2100 /*NonTrivialTypeSourceInfo=*/true);
2101 Result.setConstructorName(Ty, IdLoc, IdLoc);
2103 // We have parsed an identifier.
2104 Result.setIdentifier(Id, IdLoc);
2107 // If the next token is a '<', we may have a template.
2108 if (TemplateSpecified || Tok.is(tok::less))
2109 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2110 EnteringContext, ObjectType,
2111 Result, TemplateSpecified);
2117 // template-id (already parsed and annotated)
2118 if (Tok.is(tok::annot_template_id)) {
2119 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2121 // If the template-name names the current class, then this is a constructor
2122 if (AllowConstructorName && TemplateId->Name &&
2123 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2125 // C++ [class.qual]p2 specifies that a qualified template-name
2126 // is taken as the constructor name where a constructor can be
2127 // declared. Thus, the template arguments are extraneous, so
2128 // complain about them and remove them entirely.
2129 Diag(TemplateId->TemplateNameLoc,
2130 diag::err_out_of_line_constructor_template_id)
2132 << FixItHint::CreateRemoval(
2133 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2134 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2135 TemplateId->TemplateNameLoc,
2139 /*IsCtorOrDtorName=*/true,
2140 /*NontrivialTypeSourceInfo=*/true);
2141 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2142 TemplateId->RAngleLoc);
2147 Result.setConstructorTemplateId(TemplateId);
2152 // We have already parsed a template-id; consume the annotation token as
2153 // our unqualified-id.
2154 Result.setTemplateId(TemplateId);
2155 TemplateKWLoc = TemplateId->TemplateKWLoc;
2161 // operator-function-id
2162 // conversion-function-id
2163 if (Tok.is(tok::kw_operator)) {
2164 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2167 // If we have an operator-function-id or a literal-operator-id and the next
2168 // token is a '<', we may have a
2171 // operator-function-id < template-argument-list[opt] >
2172 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2173 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2174 (TemplateSpecified || Tok.is(tok::less)))
2175 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2176 0, SourceLocation(),
2177 EnteringContext, ObjectType,
2178 Result, TemplateSpecified);
2183 if (getLangOpts().CPlusPlus &&
2184 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2185 // C++ [expr.unary.op]p10:
2186 // There is an ambiguity in the unary-expression ~X(), where X is a
2187 // class-name. The ambiguity is resolved in favor of treating ~ as a
2188 // unary complement rather than treating ~X as referring to a destructor.
2191 SourceLocation TildeLoc = ConsumeToken();
2193 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2194 DeclSpec DS(AttrFactory);
2195 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2196 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2197 Result.setDestructorName(TildeLoc, Type, EndLoc);
2203 // Parse the class-name.
2204 if (Tok.isNot(tok::identifier)) {
2205 Diag(Tok, diag::err_destructor_tilde_identifier);
2209 // Parse the class-name (or template-name in a simple-template-id).
2210 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2211 SourceLocation ClassNameLoc = ConsumeToken();
2213 if (TemplateSpecified || Tok.is(tok::less)) {
2214 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
2215 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2216 ClassName, ClassNameLoc,
2217 EnteringContext, ObjectType,
2218 Result, TemplateSpecified);
2221 // Note that this is a destructor name.
2222 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2223 ClassNameLoc, getCurScope(),
2229 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2233 Diag(Tok, diag::err_expected_unqualified_id)
2234 << getLangOpts().CPlusPlus;
2238 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2239 /// memory in a typesafe manner and call constructors.
2241 /// This method is called to parse the new expression after the optional :: has
2242 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2243 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2246 /// '::'[opt] 'new' new-placement[opt] new-type-id
2247 /// new-initializer[opt]
2248 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2249 /// new-initializer[opt]
2252 /// '(' expression-list ')'
2255 /// type-specifier-seq new-declarator[opt]
2256 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2259 /// ptr-operator new-declarator[opt]
2260 /// direct-new-declarator
2262 /// new-initializer:
2263 /// '(' expression-list[opt] ')'
2264 /// [C++0x] braced-init-list
2267 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2268 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2269 ConsumeToken(); // Consume 'new'
2271 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2272 // second form of new-expression. It can't be a new-type-id.
2274 ExprVector PlacementArgs;
2275 SourceLocation PlacementLParen, PlacementRParen;
2277 SourceRange TypeIdParens;
2278 DeclSpec DS(AttrFactory);
2279 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2280 if (Tok.is(tok::l_paren)) {
2281 // If it turns out to be a placement, we change the type location.
2282 BalancedDelimiterTracker T(*this, tok::l_paren);
2284 PlacementLParen = T.getOpenLocation();
2285 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2286 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2291 PlacementRParen = T.getCloseLocation();
2292 if (PlacementRParen.isInvalid()) {
2293 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2297 if (PlacementArgs.empty()) {
2298 // Reset the placement locations. There was no placement.
2299 TypeIdParens = T.getRange();
2300 PlacementLParen = PlacementRParen = SourceLocation();
2302 // We still need the type.
2303 if (Tok.is(tok::l_paren)) {
2304 BalancedDelimiterTracker T(*this, tok::l_paren);
2306 MaybeParseGNUAttributes(DeclaratorInfo);
2307 ParseSpecifierQualifierList(DS);
2308 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2309 ParseDeclarator(DeclaratorInfo);
2311 TypeIdParens = T.getRange();
2313 MaybeParseGNUAttributes(DeclaratorInfo);
2314 if (ParseCXXTypeSpecifierSeq(DS))
2315 DeclaratorInfo.setInvalidType(true);
2317 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2318 ParseDeclaratorInternal(DeclaratorInfo,
2319 &Parser::ParseDirectNewDeclarator);
2324 // A new-type-id is a simplified type-id, where essentially the
2325 // direct-declarator is replaced by a direct-new-declarator.
2326 MaybeParseGNUAttributes(DeclaratorInfo);
2327 if (ParseCXXTypeSpecifierSeq(DS))
2328 DeclaratorInfo.setInvalidType(true);
2330 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2331 ParseDeclaratorInternal(DeclaratorInfo,
2332 &Parser::ParseDirectNewDeclarator);
2335 if (DeclaratorInfo.isInvalidType()) {
2336 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2340 ExprResult Initializer;
2342 if (Tok.is(tok::l_paren)) {
2343 SourceLocation ConstructorLParen, ConstructorRParen;
2344 ExprVector ConstructorArgs;
2345 BalancedDelimiterTracker T(*this, tok::l_paren);
2347 ConstructorLParen = T.getOpenLocation();
2348 if (Tok.isNot(tok::r_paren)) {
2349 CommaLocsTy CommaLocs;
2350 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2351 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2356 ConstructorRParen = T.getCloseLocation();
2357 if (ConstructorRParen.isInvalid()) {
2358 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2361 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2364 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus0x) {
2365 Diag(Tok.getLocation(),
2366 diag::warn_cxx98_compat_generalized_initializer_lists);
2367 Initializer = ParseBraceInitializer();
2369 if (Initializer.isInvalid())
2372 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2373 PlacementArgs, PlacementRParen,
2374 TypeIdParens, DeclaratorInfo, Initializer.take());
2377 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2378 /// passed to ParseDeclaratorInternal.
2380 /// direct-new-declarator:
2381 /// '[' expression ']'
2382 /// direct-new-declarator '[' constant-expression ']'
2384 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2385 // Parse the array dimensions.
2387 while (Tok.is(tok::l_square)) {
2388 // An array-size expression can't start with a lambda.
2389 if (CheckProhibitedCXX11Attribute())
2392 BalancedDelimiterTracker T(*this, tok::l_square);
2395 ExprResult Size(first ? ParseExpression()
2396 : ParseConstantExpression());
2397 if (Size.isInvalid()) {
2399 SkipUntil(tok::r_square);
2406 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2407 ParsedAttributes Attrs(AttrFactory);
2408 MaybeParseCXX0XAttributes(Attrs);
2410 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2411 /*static=*/false, /*star=*/false,
2413 T.getOpenLocation(),
2414 T.getCloseLocation()),
2415 Attrs, T.getCloseLocation());
2417 if (T.getCloseLocation().isInvalid())
2422 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2423 /// This ambiguity appears in the syntax of the C++ new operator.
2426 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2427 /// new-initializer[opt]
2430 /// '(' expression-list ')'
2432 bool Parser::ParseExpressionListOrTypeId(
2433 SmallVectorImpl<Expr*> &PlacementArgs,
2435 // The '(' was already consumed.
2436 if (isTypeIdInParens()) {
2437 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2438 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2440 return D.isInvalidType();
2443 // It's not a type, it has to be an expression list.
2444 // Discard the comma locations - ActOnCXXNew has enough parameters.
2445 CommaLocsTy CommaLocs;
2446 return ParseExpressionList(PlacementArgs, CommaLocs);
2449 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2450 /// to free memory allocated by new.
2452 /// This method is called to parse the 'delete' expression after the optional
2453 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2454 /// and "Start" is its location. Otherwise, "Start" is the location of the
2457 /// delete-expression:
2458 /// '::'[opt] 'delete' cast-expression
2459 /// '::'[opt] 'delete' '[' ']' cast-expression
2461 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2462 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2463 ConsumeToken(); // Consume 'delete'
2466 bool ArrayDelete = false;
2467 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2468 // C++11 [expr.delete]p1:
2469 // Whenever the delete keyword is followed by empty square brackets, it
2470 // shall be interpreted as [array delete].
2471 // [Footnote: A lambda expression with a lambda-introducer that consists
2472 // of empty square brackets can follow the delete keyword if
2473 // the lambda expression is enclosed in parentheses.]
2474 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2475 // lambda-introducer.
2477 BalancedDelimiterTracker T(*this, tok::l_square);
2481 if (T.getCloseLocation().isInvalid())
2485 ExprResult Operand(ParseCastExpression(false));
2486 if (Operand.isInvalid())
2489 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
2492 static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
2494 default: llvm_unreachable("Not a known unary type trait.");
2495 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign;
2496 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
2497 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy;
2498 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign;
2499 case tok::kw___has_trivial_constructor:
2500 return UTT_HasTrivialDefaultConstructor;
2501 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy;
2502 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor;
2503 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor;
2504 case tok::kw___is_abstract: return UTT_IsAbstract;
2505 case tok::kw___is_arithmetic: return UTT_IsArithmetic;
2506 case tok::kw___is_array: return UTT_IsArray;
2507 case tok::kw___is_class: return UTT_IsClass;
2508 case tok::kw___is_complete_type: return UTT_IsCompleteType;
2509 case tok::kw___is_compound: return UTT_IsCompound;
2510 case tok::kw___is_const: return UTT_IsConst;
2511 case tok::kw___is_empty: return UTT_IsEmpty;
2512 case tok::kw___is_enum: return UTT_IsEnum;
2513 case tok::kw___is_final: return UTT_IsFinal;
2514 case tok::kw___is_floating_point: return UTT_IsFloatingPoint;
2515 case tok::kw___is_function: return UTT_IsFunction;
2516 case tok::kw___is_fundamental: return UTT_IsFundamental;
2517 case tok::kw___is_integral: return UTT_IsIntegral;
2518 case tok::kw___is_interface_class: return UTT_IsInterfaceClass;
2519 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference;
2520 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer;
2521 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer;
2522 case tok::kw___is_member_pointer: return UTT_IsMemberPointer;
2523 case tok::kw___is_object: return UTT_IsObject;
2524 case tok::kw___is_literal: return UTT_IsLiteral;
2525 case tok::kw___is_literal_type: return UTT_IsLiteral;
2526 case tok::kw___is_pod: return UTT_IsPOD;
2527 case tok::kw___is_pointer: return UTT_IsPointer;
2528 case tok::kw___is_polymorphic: return UTT_IsPolymorphic;
2529 case tok::kw___is_reference: return UTT_IsReference;
2530 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference;
2531 case tok::kw___is_scalar: return UTT_IsScalar;
2532 case tok::kw___is_signed: return UTT_IsSigned;
2533 case tok::kw___is_standard_layout: return UTT_IsStandardLayout;
2534 case tok::kw___is_trivial: return UTT_IsTrivial;
2535 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable;
2536 case tok::kw___is_union: return UTT_IsUnion;
2537 case tok::kw___is_unsigned: return UTT_IsUnsigned;
2538 case tok::kw___is_void: return UTT_IsVoid;
2539 case tok::kw___is_volatile: return UTT_IsVolatile;
2543 static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) {
2545 default: llvm_unreachable("Not a known binary type trait");
2546 case tok::kw___is_base_of: return BTT_IsBaseOf;
2547 case tok::kw___is_convertible: return BTT_IsConvertible;
2548 case tok::kw___is_same: return BTT_IsSame;
2549 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible;
2550 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo;
2551 case tok::kw___is_trivially_assignable: return BTT_IsTriviallyAssignable;
2555 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2557 default: llvm_unreachable("Not a known type trait");
2558 case tok::kw___is_trivially_constructible:
2559 return TT_IsTriviallyConstructible;
2563 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2565 default: llvm_unreachable("Not a known binary type trait");
2566 case tok::kw___array_rank: return ATT_ArrayRank;
2567 case tok::kw___array_extent: return ATT_ArrayExtent;
2571 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2573 default: llvm_unreachable("Not a known unary expression trait.");
2574 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2575 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2579 /// ParseUnaryTypeTrait - Parse the built-in unary type-trait
2580 /// pseudo-functions that allow implementation of the TR1/C++0x type traits
2583 /// primary-expression:
2584 /// [GNU] unary-type-trait '(' type-id ')'
2586 ExprResult Parser::ParseUnaryTypeTrait() {
2587 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
2588 SourceLocation Loc = ConsumeToken();
2590 BalancedDelimiterTracker T(*this, tok::l_paren);
2591 if (T.expectAndConsume(diag::err_expected_lparen))
2594 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
2595 // there will be cryptic errors about mismatched parentheses and missing
2597 TypeResult Ty = ParseTypeName();
2604 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), T.getCloseLocation());
2607 /// ParseBinaryTypeTrait - Parse the built-in binary type-trait
2608 /// pseudo-functions that allow implementation of the TR1/C++0x type traits
2611 /// primary-expression:
2612 /// [GNU] binary-type-trait '(' type-id ',' type-id ')'
2614 ExprResult Parser::ParseBinaryTypeTrait() {
2615 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind());
2616 SourceLocation Loc = ConsumeToken();
2618 BalancedDelimiterTracker T(*this, tok::l_paren);
2619 if (T.expectAndConsume(diag::err_expected_lparen))
2622 TypeResult LhsTy = ParseTypeName();
2623 if (LhsTy.isInvalid()) {
2624 SkipUntil(tok::r_paren);
2628 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2629 SkipUntil(tok::r_paren);
2633 TypeResult RhsTy = ParseTypeName();
2634 if (RhsTy.isInvalid()) {
2635 SkipUntil(tok::r_paren);
2641 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(),
2642 T.getCloseLocation());
2645 /// \brief Parse the built-in type-trait pseudo-functions that allow
2646 /// implementation of the TR1/C++11 type traits templates.
2648 /// primary-expression:
2649 /// type-trait '(' type-id-seq ')'
2652 /// type-id ...[opt] type-id-seq[opt]
2654 ExprResult Parser::ParseTypeTrait() {
2655 TypeTrait Kind = TypeTraitFromTokKind(Tok.getKind());
2656 SourceLocation Loc = ConsumeToken();
2658 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2659 if (Parens.expectAndConsume(diag::err_expected_lparen))
2662 llvm::SmallVector<ParsedType, 2> Args;
2664 // Parse the next type.
2665 TypeResult Ty = ParseTypeName();
2666 if (Ty.isInvalid()) {
2671 // Parse the ellipsis, if present.
2672 if (Tok.is(tok::ellipsis)) {
2673 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2674 if (Ty.isInvalid()) {
2680 // Add this type to the list of arguments.
2681 Args.push_back(Ty.get());
2683 if (Tok.is(tok::comma)) {
2691 if (Parens.consumeClose())
2694 return Actions.ActOnTypeTrait(Kind, Loc, Args, Parens.getCloseLocation());
2697 /// ParseArrayTypeTrait - Parse the built-in array type-trait
2698 /// pseudo-functions.
2700 /// primary-expression:
2701 /// [Embarcadero] '__array_rank' '(' type-id ')'
2702 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2704 ExprResult Parser::ParseArrayTypeTrait() {
2705 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2706 SourceLocation Loc = ConsumeToken();
2708 BalancedDelimiterTracker T(*this, tok::l_paren);
2709 if (T.expectAndConsume(diag::err_expected_lparen))
2712 TypeResult Ty = ParseTypeName();
2713 if (Ty.isInvalid()) {
2714 SkipUntil(tok::comma);
2715 SkipUntil(tok::r_paren);
2720 case ATT_ArrayRank: {
2722 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL,
2723 T.getCloseLocation());
2725 case ATT_ArrayExtent: {
2726 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2727 SkipUntil(tok::r_paren);
2731 ExprResult DimExpr = ParseExpression();
2734 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2735 T.getCloseLocation());
2738 llvm_unreachable("Invalid ArrayTypeTrait!");
2741 /// ParseExpressionTrait - Parse built-in expression-trait
2742 /// pseudo-functions like __is_lvalue_expr( xxx ).
2744 /// primary-expression:
2745 /// [Embarcadero] expression-trait '(' expression ')'
2747 ExprResult Parser::ParseExpressionTrait() {
2748 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2749 SourceLocation Loc = ConsumeToken();
2751 BalancedDelimiterTracker T(*this, tok::l_paren);
2752 if (T.expectAndConsume(diag::err_expected_lparen))
2755 ExprResult Expr = ParseExpression();
2759 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2760 T.getCloseLocation());
2764 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2765 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2766 /// based on the context past the parens.
2768 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
2770 BalancedDelimiterTracker &Tracker) {
2771 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
2772 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2773 assert(isTypeIdInParens() && "Not a type-id!");
2775 ExprResult Result(true);
2776 CastTy = ParsedType();
2778 // We need to disambiguate a very ugly part of the C++ syntax:
2780 // (T())x; - type-id
2781 // (T())*x; - type-id
2782 // (T())/x; - expression
2783 // (T()); - expression
2785 // The bad news is that we cannot use the specialized tentative parser, since
2786 // it can only verify that the thing inside the parens can be parsed as
2787 // type-id, it is not useful for determining the context past the parens.
2789 // The good news is that the parser can disambiguate this part without
2790 // making any unnecessary Action calls.
2792 // It uses a scheme similar to parsing inline methods. The parenthesized
2793 // tokens are cached, the context that follows is determined (possibly by
2794 // parsing a cast-expression), and then we re-introduce the cached tokens
2795 // into the token stream and parse them appropriately.
2797 ParenParseOption ParseAs;
2800 // Store the tokens of the parentheses. We will parse them after we determine
2801 // the context that follows them.
2802 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
2803 // We didn't find the ')' we expected.
2804 Tracker.consumeClose();
2808 if (Tok.is(tok::l_brace)) {
2809 ParseAs = CompoundLiteral;
2812 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2813 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2816 // Try parsing the cast-expression that may follow.
2817 // If it is not a cast-expression, NotCastExpr will be true and no token
2818 // will be consumed.
2819 Result = ParseCastExpression(false/*isUnaryExpression*/,
2820 false/*isAddressofOperand*/,
2822 // type-id has priority.
2826 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2828 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
2831 // The current token should go after the cached tokens.
2832 Toks.push_back(Tok);
2833 // Re-enter the stored parenthesized tokens into the token stream, so we may
2835 PP.EnterTokenStream(Toks.data(), Toks.size(),
2836 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2837 // Drop the current token and bring the first cached one. It's the same token
2838 // as when we entered this function.
2841 if (ParseAs >= CompoundLiteral) {
2842 // Parse the type declarator.
2843 DeclSpec DS(AttrFactory);
2844 ParseSpecifierQualifierList(DS);
2845 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2846 ParseDeclarator(DeclaratorInfo);
2849 Tracker.consumeClose();
2851 if (ParseAs == CompoundLiteral) {
2852 ExprType = CompoundLiteral;
2853 TypeResult Ty = ParseTypeName();
2854 return ParseCompoundLiteralExpression(Ty.get(),
2855 Tracker.getOpenLocation(),
2856 Tracker.getCloseLocation());
2859 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
2860 assert(ParseAs == CastExpr);
2862 if (DeclaratorInfo.isInvalidType())
2865 // Result is what ParseCastExpression returned earlier.
2866 if (!Result.isInvalid())
2867 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
2868 DeclaratorInfo, CastTy,
2869 Tracker.getCloseLocation(), Result.take());
2873 // Not a compound literal, and not followed by a cast-expression.
2874 assert(ParseAs == SimpleExpr);
2876 ExprType = SimpleExpr;
2877 Result = ParseExpression();
2878 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2879 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
2880 Tok.getLocation(), Result.take());
2883 if (Result.isInvalid()) {
2884 SkipUntil(tok::r_paren);
2888 Tracker.consumeClose();