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 static bool AreTokensAdjacent(Preprocessor &PP, Token &First, 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(PP, 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 Parse global scope or nested-name-specifier if present.
101 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
102 /// may be preceded by '::'). Note that this routine will not parse ::new or
103 /// ::delete; it will just leave them in the token stream.
105 /// '::'[opt] nested-name-specifier
108 /// nested-name-specifier:
110 /// namespace-name '::'
111 /// nested-name-specifier identifier '::'
112 /// nested-name-specifier 'template'[opt] simple-template-id '::'
115 /// \param SS the scope specifier that will be set to the parsed
116 /// nested-name-specifier (or empty)
118 /// \param ObjectType if this nested-name-specifier is being parsed following
119 /// the "." or "->" of a member access expression, this parameter provides the
120 /// type of the object whose members are being accessed.
122 /// \param EnteringContext whether we will be entering into the context of
123 /// the nested-name-specifier after parsing it.
125 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
126 /// indicates whether this nested-name-specifier may be part of a
127 /// pseudo-destructor name. In this case, the flag will be set false
128 /// if we don't actually end up parsing a destructor name. Moreorover,
129 /// if we do end up determining that we are parsing a destructor name,
130 /// the last component of the nested-name-specifier is not parsed as
131 /// part of the scope specifier.
133 /// member access expression, e.g., the \p T:: in \p p->T::m.
135 /// \returns true if there was an error parsing a scope specifier
136 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
137 ParsedType ObjectType,
138 bool EnteringContext,
139 bool *MayBePseudoDestructor,
141 assert(getLangOpts().CPlusPlus &&
142 "Call sites of this function should be guarded by checking for C++");
144 if (Tok.is(tok::annot_cxxscope)) {
145 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
146 Tok.getAnnotationRange(),
152 bool HasScopeSpecifier = false;
154 if (Tok.is(tok::coloncolon)) {
155 // ::new and ::delete aren't nested-name-specifiers.
156 tok::TokenKind NextKind = NextToken().getKind();
157 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
160 // '::' - Global scope qualifier.
161 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
164 HasScopeSpecifier = true;
167 bool CheckForDestructor = false;
168 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
169 CheckForDestructor = true;
170 *MayBePseudoDestructor = false;
173 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
174 DeclSpec DS(AttrFactory);
175 SourceLocation DeclLoc = Tok.getLocation();
176 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
177 if (Tok.isNot(tok::coloncolon)) {
178 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
182 SourceLocation CCLoc = ConsumeToken();
183 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
184 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
186 HasScopeSpecifier = true;
190 if (HasScopeSpecifier) {
191 // C++ [basic.lookup.classref]p5:
192 // If the qualified-id has the form
194 // ::class-name-or-namespace-name::...
196 // the class-name-or-namespace-name is looked up in global scope as a
197 // class-name or namespace-name.
199 // To implement this, we clear out the object type as soon as we've
200 // seen a leading '::' or part of a nested-name-specifier.
201 ObjectType = ParsedType();
203 if (Tok.is(tok::code_completion)) {
204 // Code completion for a nested-name-specifier, where the code
205 // code completion token follows the '::'.
206 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
207 // Include code completion token into the range of the scope otherwise
208 // when we try to annotate the scope tokens the dangling code completion
209 // token will cause assertion in
210 // Preprocessor::AnnotatePreviousCachedTokens.
211 SS.setEndLoc(Tok.getLocation());
217 // nested-name-specifier:
218 // nested-name-specifier 'template'[opt] simple-template-id '::'
220 // Parse the optional 'template' keyword, then make sure we have
221 // 'identifier <' after it.
222 if (Tok.is(tok::kw_template)) {
223 // If we don't have a scope specifier or an object type, this isn't a
224 // nested-name-specifier, since they aren't allowed to start with
226 if (!HasScopeSpecifier && !ObjectType)
229 TentativeParsingAction TPA(*this);
230 SourceLocation TemplateKWLoc = ConsumeToken();
232 UnqualifiedId TemplateName;
233 if (Tok.is(tok::identifier)) {
234 // Consume the identifier.
235 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
237 } else if (Tok.is(tok::kw_operator)) {
238 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
244 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
245 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
246 Diag(TemplateName.getSourceRange().getBegin(),
247 diag::err_id_after_template_in_nested_name_spec)
248 << TemplateName.getSourceRange();
257 // If the next token is not '<', we have a qualified-id that refers
258 // to a template name, such as T::template apply, but is not a
260 if (Tok.isNot(tok::less)) {
265 // Commit to parsing the template-id.
268 if (TemplateNameKind TNK
269 = Actions.ActOnDependentTemplateName(getCurScope(),
270 SS, TemplateKWLoc, TemplateName,
271 ObjectType, EnteringContext,
273 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
274 TemplateName, false))
282 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
285 // simple-template-id '::'
287 // So we need to check whether the simple-template-id is of the
288 // right kind (it should name a type or be dependent), and then
289 // convert it into a type within the nested-name-specifier.
290 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
291 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
292 *MayBePseudoDestructor = true;
296 // Consume the template-id token.
299 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
300 SourceLocation CCLoc = ConsumeToken();
302 HasScopeSpecifier = true;
304 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
305 TemplateId->getTemplateArgs(),
306 TemplateId->NumArgs);
308 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
310 TemplateId->TemplateKWLoc,
311 TemplateId->Template,
312 TemplateId->TemplateNameLoc,
313 TemplateId->LAngleLoc,
315 TemplateId->RAngleLoc,
318 SourceLocation StartLoc
319 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
320 : TemplateId->TemplateNameLoc;
321 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
328 // The rest of the nested-name-specifier possibilities start with
330 if (Tok.isNot(tok::identifier))
333 IdentifierInfo &II = *Tok.getIdentifierInfo();
335 // nested-name-specifier:
337 // namespace-name '::'
338 // nested-name-specifier identifier '::'
339 Token Next = NextToken();
341 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
342 // and emit a fixit hint for it.
343 if (Next.is(tok::colon) && !ColonIsSacred) {
344 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
346 Next.getLocation(), ObjectType,
348 // If the token after the colon isn't an identifier, it's still an
349 // error, but they probably meant something else strange so don't
350 // recover like this.
351 PP.LookAhead(1).is(tok::identifier)) {
352 Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
353 << FixItHint::CreateReplacement(Next.getLocation(), "::");
355 // Recover as if the user wrote '::'.
356 Next.setKind(tok::coloncolon);
360 if (Next.is(tok::coloncolon)) {
361 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
362 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
364 *MayBePseudoDestructor = true;
368 // We have an identifier followed by a '::'. Lookup this name
369 // as the name in a nested-name-specifier.
370 SourceLocation IdLoc = ConsumeToken();
371 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
372 "NextToken() not working properly!");
373 SourceLocation CCLoc = ConsumeToken();
375 HasScopeSpecifier = true;
376 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
377 ObjectType, EnteringContext, SS))
378 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
383 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
385 // nested-name-specifier:
387 if (Next.is(tok::less)) {
389 UnqualifiedId TemplateName;
390 TemplateName.setIdentifier(&II, Tok.getLocation());
391 bool MemberOfUnknownSpecialization;
392 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
393 /*hasTemplateKeyword=*/false,
398 MemberOfUnknownSpecialization)) {
399 // We have found a template name, so annotate this token
400 // with a template-id annotation. We do not permit the
401 // template-id to be translated into a type annotation,
402 // because some clients (e.g., the parsing of class template
403 // specializations) still want to see the original template-id
406 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
407 TemplateName, false))
412 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
413 (IsTypename || IsTemplateArgumentList(1))) {
414 // We have something like t::getAs<T>, where getAs is a
415 // member of an unknown specialization. However, this will only
416 // parse correctly as a template, so suggest the keyword 'template'
417 // before 'getAs' and treat this as a dependent template name.
418 unsigned DiagID = diag::err_missing_dependent_template_keyword;
419 if (getLangOpts().MicrosoftExt)
420 DiagID = diag::warn_missing_dependent_template_keyword;
422 Diag(Tok.getLocation(), DiagID)
424 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
426 if (TemplateNameKind TNK
427 = Actions.ActOnDependentTemplateName(getCurScope(),
428 SS, SourceLocation(),
429 TemplateName, ObjectType,
430 EnteringContext, Template)) {
431 // Consume the identifier.
433 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
434 TemplateName, false))
444 // We don't have any tokens that form the beginning of a
445 // nested-name-specifier, so we're done.
449 // Even if we didn't see any pieces of a nested-name-specifier, we
450 // still check whether there is a tilde in this position, which
451 // indicates a potential pseudo-destructor.
452 if (CheckForDestructor && Tok.is(tok::tilde))
453 *MayBePseudoDestructor = true;
458 /// ParseCXXIdExpression - Handle id-expression.
465 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
467 /// '::' operator-function-id
470 /// NOTE: The standard specifies that, for qualified-id, the parser does not
473 /// '::' conversion-function-id
474 /// '::' '~' class-name
476 /// This may cause a slight inconsistency on diagnostics:
481 /// :: A :: ~ C(); // Some Sema error about using destructor with a
483 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
486 /// We simplify the parser a bit and make it work like:
489 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
490 /// '::' unqualified-id
492 /// That way Sema can handle and report similar errors for namespaces and the
495 /// The isAddressOfOperand parameter indicates that this id-expression is a
496 /// direct operand of the address-of operator. This is, besides member contexts,
497 /// the only place where a qualified-id naming a non-static class member may
500 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
502 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
503 // '::' unqualified-id
506 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
508 SourceLocation TemplateKWLoc;
510 if (ParseUnqualifiedId(SS,
511 /*EnteringContext=*/false,
512 /*AllowDestructorName=*/false,
513 /*AllowConstructorName=*/false,
514 /*ObjectType=*/ ParsedType(),
519 // This is only the direct operand of an & operator if it is not
520 // followed by a postfix-expression suffix.
521 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
522 isAddressOfOperand = false;
524 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
525 Tok.is(tok::l_paren), isAddressOfOperand);
528 /// ParseLambdaExpression - Parse a C++0x lambda expression.
530 /// lambda-expression:
531 /// lambda-introducer lambda-declarator[opt] compound-statement
533 /// lambda-introducer:
534 /// '[' lambda-capture[opt] ']'
539 /// capture-default ',' capture-list
547 /// capture-list ',' capture
554 /// lambda-declarator:
555 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
556 /// 'mutable'[opt] exception-specification[opt]
557 /// trailing-return-type[opt]
559 ExprResult Parser::ParseLambdaExpression() {
560 // Parse lambda-introducer.
561 LambdaIntroducer Intro;
563 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
565 Diag(Tok, DiagID.getValue());
566 SkipUntil(tok::r_square);
567 SkipUntil(tok::l_brace);
568 SkipUntil(tok::r_brace);
572 return ParseLambdaExpressionAfterIntroducer(Intro);
575 /// TryParseLambdaExpression - Use lookahead and potentially tentative
576 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
579 /// If we are not looking at a lambda expression, returns ExprError().
580 ExprResult Parser::TryParseLambdaExpression() {
581 assert(getLangOpts().CPlusPlus0x
582 && Tok.is(tok::l_square)
583 && "Not at the start of a possible lambda expression.");
585 const Token Next = NextToken(), After = GetLookAheadToken(2);
587 // If lookahead indicates this is a lambda...
588 if (Next.is(tok::r_square) || // []
589 Next.is(tok::equal) || // [=
590 (Next.is(tok::amp) && // [&] or [&,
591 (After.is(tok::r_square) ||
592 After.is(tok::comma))) ||
593 (Next.is(tok::identifier) && // [identifier]
594 After.is(tok::r_square))) {
595 return ParseLambdaExpression();
598 // If lookahead indicates an ObjC message send...
599 // [identifier identifier
600 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
604 // Here, we're stuck: lambda introducers and Objective-C message sends are
605 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
606 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
607 // writing two routines to parse a lambda introducer, just try to parse
608 // a lambda introducer first, and fall back if that fails.
609 // (TryParseLambdaIntroducer never produces any diagnostic output.)
610 LambdaIntroducer Intro;
611 if (TryParseLambdaIntroducer(Intro))
613 return ParseLambdaExpressionAfterIntroducer(Intro);
616 /// ParseLambdaExpression - Parse a lambda introducer.
618 /// Returns a DiagnosticID if it hit something unexpected.
619 llvm::Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro){
620 typedef llvm::Optional<unsigned> DiagResult;
622 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
623 BalancedDelimiterTracker T(*this, tok::l_square);
626 Intro.Range.setBegin(T.getOpenLocation());
630 // Parse capture-default.
631 if (Tok.is(tok::amp) &&
632 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
633 Intro.Default = LCD_ByRef;
634 Intro.DefaultLoc = ConsumeToken();
636 } else if (Tok.is(tok::equal)) {
637 Intro.Default = LCD_ByCopy;
638 Intro.DefaultLoc = ConsumeToken();
642 while (Tok.isNot(tok::r_square)) {
644 if (Tok.isNot(tok::comma)) {
645 if (Tok.is(tok::code_completion)) {
646 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
647 /*AfterAmpersand=*/false);
648 ConsumeCodeCompletionToken();
652 return DiagResult(diag::err_expected_comma_or_rsquare);
657 if (Tok.is(tok::code_completion)) {
658 // If we're in Objective-C++ and we have a bare '[', then this is more
659 // likely to be a message receiver.
660 if (getLangOpts().ObjC1 && first)
661 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
663 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
664 /*AfterAmpersand=*/false);
665 ConsumeCodeCompletionToken();
672 LambdaCaptureKind Kind = LCK_ByCopy;
674 IdentifierInfo* Id = 0;
675 SourceLocation EllipsisLoc;
677 if (Tok.is(tok::kw_this)) {
679 Loc = ConsumeToken();
681 if (Tok.is(tok::amp)) {
685 if (Tok.is(tok::code_completion)) {
686 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
687 /*AfterAmpersand=*/true);
688 ConsumeCodeCompletionToken();
693 if (Tok.is(tok::identifier)) {
694 Id = Tok.getIdentifierInfo();
695 Loc = ConsumeToken();
697 if (Tok.is(tok::ellipsis))
698 EllipsisLoc = ConsumeToken();
699 } else if (Tok.is(tok::kw_this)) {
700 // FIXME: If we want to suggest a fixit here, will need to return more
701 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
702 // Clear()ed to prevent emission in case of tentative parsing?
703 return DiagResult(diag::err_this_captured_by_reference);
705 return DiagResult(diag::err_expected_capture);
709 Intro.addCapture(Kind, Loc, Id, EllipsisLoc);
713 Intro.Range.setEnd(T.getCloseLocation());
718 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
720 /// Returns true if it hit something unexpected.
721 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
722 TentativeParsingAction PA(*this);
724 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
735 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
737 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
738 LambdaIntroducer &Intro) {
739 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
740 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
742 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
743 "lambda expression parsing");
745 // Parse lambda-declarator[opt].
746 DeclSpec DS(AttrFactory);
747 Declarator D(DS, Declarator::LambdaExprContext);
749 if (Tok.is(tok::l_paren)) {
750 ParseScope PrototypeScope(this,
751 Scope::FunctionPrototypeScope |
754 SourceLocation DeclLoc, DeclEndLoc;
755 BalancedDelimiterTracker T(*this, tok::l_paren);
757 DeclLoc = T.getOpenLocation();
759 // Parse parameter-declaration-clause.
760 ParsedAttributes Attr(AttrFactory);
761 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
762 SourceLocation EllipsisLoc;
764 if (Tok.isNot(tok::r_paren))
765 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
768 DeclEndLoc = T.getCloseLocation();
770 // Parse 'mutable'[opt].
771 SourceLocation MutableLoc;
772 if (Tok.is(tok::kw_mutable)) {
773 MutableLoc = ConsumeToken();
774 DeclEndLoc = MutableLoc;
777 // Parse exception-specification[opt].
778 ExceptionSpecificationType ESpecType = EST_None;
779 SourceRange ESpecRange;
780 llvm::SmallVector<ParsedType, 2> DynamicExceptions;
781 llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
782 ExprResult NoexceptExpr;
783 CachedTokens *ExceptionSpecTokens;
784 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
787 DynamicExceptionRanges,
789 ExceptionSpecTokens);
791 if (ESpecType != EST_None)
792 DeclEndLoc = ESpecRange.getEnd();
794 // Parse attribute-specifier[opt].
795 MaybeParseCXX0XAttributes(Attr, &DeclEndLoc);
797 // Parse trailing-return-type[opt].
798 ParsedType TrailingReturnType;
799 if (Tok.is(tok::arrow)) {
801 TrailingReturnType = ParseTrailingReturnType(Range).get();
802 if (Range.getEnd().isValid())
803 DeclEndLoc = Range.getEnd();
806 PrototypeScope.Exit();
808 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
809 /*isVariadic=*/EllipsisLoc.isValid(),
811 ParamInfo.data(), ParamInfo.size(),
812 DS.getTypeQualifiers(),
813 /*RefQualifierIsLValueRef=*/true,
814 /*RefQualifierLoc=*/SourceLocation(),
815 /*ConstQualifierLoc=*/SourceLocation(),
816 /*VolatileQualifierLoc=*/SourceLocation(),
818 ESpecType, ESpecRange.getBegin(),
819 DynamicExceptions.data(),
820 DynamicExceptionRanges.data(),
821 DynamicExceptions.size(),
822 NoexceptExpr.isUsable() ?
823 NoexceptExpr.get() : 0,
825 DeclLoc, DeclEndLoc, D,
828 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) {
829 // It's common to forget that one needs '()' before 'mutable' or the
830 // result type. Deal with this.
831 Diag(Tok, diag::err_lambda_missing_parens)
832 << Tok.is(tok::arrow)
833 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
834 SourceLocation DeclLoc = Tok.getLocation();
835 SourceLocation DeclEndLoc = DeclLoc;
837 // Parse 'mutable', if it's there.
838 SourceLocation MutableLoc;
839 if (Tok.is(tok::kw_mutable)) {
840 MutableLoc = ConsumeToken();
841 DeclEndLoc = MutableLoc;
844 // Parse the return type, if there is one.
845 ParsedType TrailingReturnType;
846 if (Tok.is(tok::arrow)) {
848 TrailingReturnType = ParseTrailingReturnType(Range).get();
849 if (Range.getEnd().isValid())
850 DeclEndLoc = Range.getEnd();
853 ParsedAttributes Attr(AttrFactory);
854 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
855 /*isVariadic=*/false,
856 /*EllipsisLoc=*/SourceLocation(),
857 /*Params=*/0, /*NumParams=*/0,
859 /*RefQualifierIsLValueRef=*/true,
860 /*RefQualifierLoc=*/SourceLocation(),
861 /*ConstQualifierLoc=*/SourceLocation(),
862 /*VolatileQualifierLoc=*/SourceLocation(),
865 /*ESpecLoc=*/SourceLocation(),
867 /*ExceptionRanges=*/0,
870 /*ExceptionSpecTokens=*/0,
871 DeclLoc, DeclEndLoc, D,
877 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
879 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
880 ParseScope BodyScope(this, ScopeFlags);
882 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
884 // Parse compound-statement.
885 if (!Tok.is(tok::l_brace)) {
886 Diag(Tok, diag::err_expected_lambda_body);
887 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
891 StmtResult Stmt(ParseCompoundStatementBody());
894 if (!Stmt.isInvalid())
895 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope());
897 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
901 /// ParseCXXCasts - This handles the various ways to cast expressions to another
904 /// postfix-expression: [C++ 5.2p1]
905 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
906 /// 'static_cast' '<' type-name '>' '(' expression ')'
907 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
908 /// 'const_cast' '<' type-name '>' '(' expression ')'
910 ExprResult Parser::ParseCXXCasts() {
911 tok::TokenKind Kind = Tok.getKind();
912 const char *CastName = 0; // For error messages
915 default: llvm_unreachable("Unknown C++ cast!");
916 case tok::kw_const_cast: CastName = "const_cast"; break;
917 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
918 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
919 case tok::kw_static_cast: CastName = "static_cast"; break;
922 SourceLocation OpLoc = ConsumeToken();
923 SourceLocation LAngleBracketLoc = Tok.getLocation();
925 // Check for "<::" which is parsed as "[:". If found, fix token stream,
926 // diagnose error, suggest fix, and recover parsing.
927 Token Next = NextToken();
928 if (Tok.is(tok::l_square) && Tok.getLength() == 2 && Next.is(tok::colon) &&
929 AreTokensAdjacent(PP, Tok, Next))
930 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
932 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
935 // Parse the common declaration-specifiers piece.
936 DeclSpec DS(AttrFactory);
937 ParseSpecifierQualifierList(DS);
939 // Parse the abstract-declarator, if present.
940 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
941 ParseDeclarator(DeclaratorInfo);
943 SourceLocation RAngleBracketLoc = Tok.getLocation();
945 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
946 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
948 SourceLocation LParenLoc, RParenLoc;
949 BalancedDelimiterTracker T(*this, tok::l_paren);
951 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
954 ExprResult Result = ParseExpression();
959 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
960 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
961 LAngleBracketLoc, DeclaratorInfo,
963 T.getOpenLocation(), Result.take(),
964 T.getCloseLocation());
969 /// ParseCXXTypeid - This handles the C++ typeid expression.
971 /// postfix-expression: [C++ 5.2p1]
972 /// 'typeid' '(' expression ')'
973 /// 'typeid' '(' type-id ')'
975 ExprResult Parser::ParseCXXTypeid() {
976 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
978 SourceLocation OpLoc = ConsumeToken();
979 SourceLocation LParenLoc, RParenLoc;
980 BalancedDelimiterTracker T(*this, tok::l_paren);
982 // typeid expressions are always parenthesized.
983 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
985 LParenLoc = T.getOpenLocation();
989 if (isTypeIdInParens()) {
990 TypeResult Ty = ParseTypeName();
994 RParenLoc = T.getCloseLocation();
995 if (Ty.isInvalid() || RParenLoc.isInvalid())
998 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
999 Ty.get().getAsOpaquePtr(), RParenLoc);
1001 // C++0x [expr.typeid]p3:
1002 // When typeid is applied to an expression other than an lvalue of a
1003 // polymorphic class type [...] The expression is an unevaluated
1004 // operand (Clause 5).
1006 // Note that we can't tell whether the expression is an lvalue of a
1007 // polymorphic class type until after we've parsed the expression; we
1008 // speculatively assume the subexpression is unevaluated, and fix it up
1010 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1011 Result = ParseExpression();
1014 if (Result.isInvalid())
1015 SkipUntil(tok::r_paren);
1018 RParenLoc = T.getCloseLocation();
1019 if (RParenLoc.isInvalid())
1022 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1023 Result.release(), RParenLoc);
1027 return move(Result);
1030 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1032 /// '__uuidof' '(' expression ')'
1033 /// '__uuidof' '(' type-id ')'
1035 ExprResult Parser::ParseCXXUuidof() {
1036 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1038 SourceLocation OpLoc = ConsumeToken();
1039 BalancedDelimiterTracker T(*this, tok::l_paren);
1041 // __uuidof expressions are always parenthesized.
1042 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1047 if (isTypeIdInParens()) {
1048 TypeResult Ty = ParseTypeName();
1056 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1057 Ty.get().getAsOpaquePtr(),
1058 T.getCloseLocation());
1060 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1061 Result = ParseExpression();
1064 if (Result.isInvalid())
1065 SkipUntil(tok::r_paren);
1069 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1071 Result.release(), T.getCloseLocation());
1075 return move(Result);
1078 /// \brief Parse a C++ pseudo-destructor expression after the base,
1079 /// . or -> operator, and nested-name-specifier have already been
1082 /// postfix-expression: [C++ 5.2]
1083 /// postfix-expression . pseudo-destructor-name
1084 /// postfix-expression -> pseudo-destructor-name
1086 /// pseudo-destructor-name:
1087 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1088 /// ::[opt] nested-name-specifier template simple-template-id ::
1090 /// ::[opt] nested-name-specifier[opt] ~type-name
1093 Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1094 tok::TokenKind OpKind,
1096 ParsedType ObjectType) {
1097 // We're parsing either a pseudo-destructor-name or a dependent
1098 // member access that has the same form as a
1099 // pseudo-destructor-name. We parse both in the same way and let
1100 // the action model sort them out.
1102 // Note that the ::[opt] nested-name-specifier[opt] has already
1103 // been parsed, and if there was a simple-template-id, it has
1104 // been coalesced into a template-id annotation token.
1105 UnqualifiedId FirstTypeName;
1106 SourceLocation CCLoc;
1107 if (Tok.is(tok::identifier)) {
1108 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1110 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1111 CCLoc = ConsumeToken();
1112 } else if (Tok.is(tok::annot_template_id)) {
1113 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1114 // store it in the pseudo-dtor node (to be used when instantiating it).
1115 FirstTypeName.setTemplateId(
1116 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1118 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1119 CCLoc = ConsumeToken();
1121 FirstTypeName.setIdentifier(0, SourceLocation());
1125 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1126 SourceLocation TildeLoc = ConsumeToken();
1128 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1129 DeclSpec DS(AttrFactory);
1130 ParseDecltypeSpecifier(DS);
1131 if (DS.getTypeSpecType() == TST_error)
1133 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1134 OpKind, TildeLoc, DS,
1135 Tok.is(tok::l_paren));
1138 if (!Tok.is(tok::identifier)) {
1139 Diag(Tok, diag::err_destructor_tilde_identifier);
1143 // Parse the second type.
1144 UnqualifiedId SecondTypeName;
1145 IdentifierInfo *Name = Tok.getIdentifierInfo();
1146 SourceLocation NameLoc = ConsumeToken();
1147 SecondTypeName.setIdentifier(Name, NameLoc);
1149 // If there is a '<', the second type name is a template-id. Parse
1151 if (Tok.is(tok::less) &&
1152 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1154 false, ObjectType, SecondTypeName,
1155 /*AssumeTemplateName=*/true))
1158 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1160 SS, FirstTypeName, CCLoc,
1161 TildeLoc, SecondTypeName,
1162 Tok.is(tok::l_paren));
1165 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1167 /// boolean-literal: [C++ 2.13.5]
1170 ExprResult Parser::ParseCXXBoolLiteral() {
1171 tok::TokenKind Kind = Tok.getKind();
1172 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1175 /// ParseThrowExpression - This handles the C++ throw expression.
1177 /// throw-expression: [C++ 15]
1178 /// 'throw' assignment-expression[opt]
1179 ExprResult Parser::ParseThrowExpression() {
1180 assert(Tok.is(tok::kw_throw) && "Not throw!");
1181 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1183 // If the current token isn't the start of an assignment-expression,
1184 // then the expression is not present. This handles things like:
1185 // "C ? throw : (void)42", which is crazy but legal.
1186 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1193 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
1196 ExprResult Expr(ParseAssignmentExpression());
1197 if (Expr.isInvalid()) return move(Expr);
1198 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
1202 /// ParseCXXThis - This handles the C++ 'this' pointer.
1204 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1205 /// a non-lvalue expression whose value is the address of the object for which
1206 /// the function is called.
1207 ExprResult Parser::ParseCXXThis() {
1208 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1209 SourceLocation ThisLoc = ConsumeToken();
1210 return Actions.ActOnCXXThis(ThisLoc);
1213 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1214 /// Can be interpreted either as function-style casting ("int(x)")
1215 /// or class type construction ("ClassType(x,y,z)")
1216 /// or creation of a value-initialized type ("int()").
1217 /// See [C++ 5.2.3].
1219 /// postfix-expression: [C++ 5.2p1]
1220 /// simple-type-specifier '(' expression-list[opt] ')'
1221 /// [C++0x] simple-type-specifier braced-init-list
1222 /// typename-specifier '(' expression-list[opt] ')'
1223 /// [C++0x] typename-specifier braced-init-list
1226 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1227 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1228 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1230 assert((Tok.is(tok::l_paren) ||
1231 (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)))
1232 && "Expected '(' or '{'!");
1234 if (Tok.is(tok::l_brace)) {
1235 ExprResult Init = ParseBraceInitializer();
1236 if (Init.isInvalid())
1238 Expr *InitList = Init.take();
1239 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1240 MultiExprArg(&InitList, 1),
1243 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true);
1245 BalancedDelimiterTracker T(*this, tok::l_paren);
1248 ExprVector Exprs(Actions);
1249 CommaLocsTy CommaLocs;
1251 if (Tok.isNot(tok::r_paren)) {
1252 if (ParseExpressionList(Exprs, CommaLocs)) {
1253 SkipUntil(tok::r_paren);
1261 // TypeRep could be null, if it references an invalid typedef.
1265 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1266 "Unexpected number of commas!");
1267 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1269 T.getCloseLocation());
1273 /// ParseCXXCondition - if/switch/while condition expression.
1277 /// type-specifier-seq declarator '=' assignment-expression
1278 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1279 /// [C++11] type-specifier-seq declarator braced-init-list
1280 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1281 /// '=' assignment-expression
1283 /// \param ExprResult if the condition was parsed as an expression, the
1284 /// parsed expression.
1286 /// \param DeclResult if the condition was parsed as a declaration, the
1287 /// parsed declaration.
1289 /// \param Loc The location of the start of the statement that requires this
1290 /// condition, e.g., the "for" in a for loop.
1292 /// \param ConvertToBoolean Whether the condition expression should be
1293 /// converted to a boolean value.
1295 /// \returns true if there was a parsing, false otherwise.
1296 bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1299 bool ConvertToBoolean) {
1300 if (Tok.is(tok::code_completion)) {
1301 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1306 if (!isCXXConditionDeclaration()) {
1307 // Parse the expression.
1308 ExprOut = ParseExpression(); // expression
1310 if (ExprOut.isInvalid())
1313 // If required, convert to a boolean value.
1314 if (ConvertToBoolean)
1316 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1317 return ExprOut.isInvalid();
1320 // type-specifier-seq
1321 DeclSpec DS(AttrFactory);
1322 ParseSpecifierQualifierList(DS);
1325 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1326 ParseDeclarator(DeclaratorInfo);
1328 // simple-asm-expr[opt]
1329 if (Tok.is(tok::kw_asm)) {
1331 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1332 if (AsmLabel.isInvalid()) {
1333 SkipUntil(tok::semi);
1336 DeclaratorInfo.setAsmLabel(AsmLabel.release());
1337 DeclaratorInfo.SetRangeEnd(Loc);
1340 // If attributes are present, parse them.
1341 MaybeParseGNUAttributes(DeclaratorInfo);
1343 // Type-check the declaration itself.
1344 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1346 DeclOut = Dcl.get();
1347 ExprOut = ExprError();
1349 // '=' assignment-expression
1350 // If a '==' or '+=' is found, suggest a fixit to '='.
1351 bool CopyInitialization = isTokenEqualOrEqualTypo();
1352 if (CopyInitialization)
1355 ExprResult InitExpr = ExprError();
1356 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
1357 Diag(Tok.getLocation(),
1358 diag::warn_cxx98_compat_generalized_initializer_lists);
1359 InitExpr = ParseBraceInitializer();
1360 } else if (CopyInitialization) {
1361 InitExpr = ParseAssignmentExpression();
1362 } else if (Tok.is(tok::l_paren)) {
1363 // This was probably an attempt to initialize the variable.
1364 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1365 if (SkipUntil(tok::r_paren, true, /*DontConsume=*/true))
1366 RParen = ConsumeParen();
1367 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1368 diag::err_expected_init_in_condition_lparen)
1369 << SourceRange(LParen, RParen);
1371 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1372 diag::err_expected_init_in_condition);
1375 if (!InitExpr.isInvalid())
1376 Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization,
1377 DS.getTypeSpecType() == DeclSpec::TST_auto);
1379 // FIXME: Build a reference to this declaration? Convert it to bool?
1380 // (This is currently handled by Sema).
1382 Actions.FinalizeDeclaration(DeclOut);
1387 /// \brief Determine whether the current token starts a C++
1388 /// simple-type-specifier.
1389 bool Parser::isCXXSimpleTypeSpecifier() const {
1390 switch (Tok.getKind()) {
1391 case tok::annot_typename:
1394 case tok::kw___int64:
1395 case tok::kw___int128:
1396 case tok::kw_signed:
1397 case tok::kw_unsigned:
1403 case tok::kw_double:
1404 case tok::kw_wchar_t:
1405 case tok::kw_char16_t:
1406 case tok::kw_char32_t:
1408 case tok::kw_decltype:
1409 case tok::kw_typeof:
1410 case tok::kw___underlying_type:
1420 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1421 /// This should only be called when the current token is known to be part of
1422 /// simple-type-specifier.
1424 /// simple-type-specifier:
1425 /// '::'[opt] nested-name-specifier[opt] type-name
1426 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1438 /// [GNU] typeof-specifier
1439 /// [C++0x] auto [TODO]
1446 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1447 DS.SetRangeStart(Tok.getLocation());
1448 const char *PrevSpec;
1450 SourceLocation Loc = Tok.getLocation();
1452 switch (Tok.getKind()) {
1453 case tok::identifier: // foo::bar
1454 case tok::coloncolon: // ::foo::bar
1455 llvm_unreachable("Annotation token should already be formed!");
1457 llvm_unreachable("Not a simple-type-specifier token!");
1460 case tok::annot_typename: {
1461 if (getTypeAnnotation(Tok))
1462 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1463 getTypeAnnotation(Tok));
1465 DS.SetTypeSpecError();
1467 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1470 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1471 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1472 // Objective-C interface. If we don't have Objective-C or a '<', this is
1473 // just a normal reference to a typedef name.
1474 if (Tok.is(tok::less) && getLangOpts().ObjC1)
1475 ParseObjCProtocolQualifiers(DS);
1477 DS.Finish(Diags, PP);
1483 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1486 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
1488 case tok::kw___int64:
1489 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1491 case tok::kw_signed:
1492 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1494 case tok::kw_unsigned:
1495 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1498 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1501 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1504 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1506 case tok::kw___int128:
1507 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID);
1510 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
1513 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1515 case tok::kw_double:
1516 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1518 case tok::kw_wchar_t:
1519 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1521 case tok::kw_char16_t:
1522 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1524 case tok::kw_char32_t:
1525 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1528 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1530 case tok::annot_decltype:
1531 case tok::kw_decltype:
1532 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1533 return DS.Finish(Diags, PP);
1535 // GNU typeof support.
1536 case tok::kw_typeof:
1537 ParseTypeofSpecifier(DS);
1538 DS.Finish(Diags, PP);
1541 if (Tok.is(tok::annot_typename))
1542 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1544 DS.SetRangeEnd(Tok.getLocation());
1546 DS.Finish(Diags, PP);
1549 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1550 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1551 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1552 /// by parsing the type-specifier-seq, because these sequences are
1553 /// typically followed by some form of declarator. Returns true and
1554 /// emits diagnostics if this is not a type-specifier-seq, false
1557 /// type-specifier-seq: [C++ 8.1]
1558 /// type-specifier type-specifier-seq[opt]
1560 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1561 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1562 DS.Finish(Diags, PP);
1566 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1569 /// This routine is invoked when a '<' is encountered after an identifier or
1570 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1571 /// whether the unqualified-id is actually a template-id. This routine will
1572 /// then parse the template arguments and form the appropriate template-id to
1573 /// return to the caller.
1575 /// \param SS the nested-name-specifier that precedes this template-id, if
1576 /// we're actually parsing a qualified-id.
1578 /// \param Name for constructor and destructor names, this is the actual
1579 /// identifier that may be a template-name.
1581 /// \param NameLoc the location of the class-name in a constructor or
1584 /// \param EnteringContext whether we're entering the scope of the
1585 /// nested-name-specifier.
1587 /// \param ObjectType if this unqualified-id occurs within a member access
1588 /// expression, the type of the base object whose member is being accessed.
1590 /// \param Id as input, describes the template-name or operator-function-id
1591 /// that precedes the '<'. If template arguments were parsed successfully,
1592 /// will be updated with the template-id.
1594 /// \param AssumeTemplateId When true, this routine will assume that the name
1595 /// refers to a template without performing name lookup to verify.
1597 /// \returns true if a parse error occurred, false otherwise.
1598 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1599 SourceLocation TemplateKWLoc,
1600 IdentifierInfo *Name,
1601 SourceLocation NameLoc,
1602 bool EnteringContext,
1603 ParsedType ObjectType,
1605 bool AssumeTemplateId) {
1606 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1607 "Expected '<' to finish parsing a template-id");
1609 TemplateTy Template;
1610 TemplateNameKind TNK = TNK_Non_template;
1611 switch (Id.getKind()) {
1612 case UnqualifiedId::IK_Identifier:
1613 case UnqualifiedId::IK_OperatorFunctionId:
1614 case UnqualifiedId::IK_LiteralOperatorId:
1615 if (AssumeTemplateId) {
1616 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
1617 Id, ObjectType, EnteringContext,
1619 if (TNK == TNK_Non_template)
1622 bool MemberOfUnknownSpecialization;
1623 TNK = Actions.isTemplateName(getCurScope(), SS,
1624 TemplateKWLoc.isValid(), Id,
1625 ObjectType, EnteringContext, Template,
1626 MemberOfUnknownSpecialization);
1628 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1629 ObjectType && IsTemplateArgumentList()) {
1630 // We have something like t->getAs<T>(), where getAs is a
1631 // member of an unknown specialization. However, this will only
1632 // parse correctly as a template, so suggest the keyword 'template'
1633 // before 'getAs' and treat this as a dependent template name.
1635 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1636 Name = Id.Identifier->getName();
1639 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1640 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1642 Name += Id.Identifier->getName();
1644 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1646 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1647 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1648 SS, TemplateKWLoc, Id,
1649 ObjectType, EnteringContext,
1651 if (TNK == TNK_Non_template)
1657 case UnqualifiedId::IK_ConstructorName: {
1658 UnqualifiedId TemplateName;
1659 bool MemberOfUnknownSpecialization;
1660 TemplateName.setIdentifier(Name, NameLoc);
1661 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1662 TemplateName, ObjectType,
1663 EnteringContext, Template,
1664 MemberOfUnknownSpecialization);
1668 case UnqualifiedId::IK_DestructorName: {
1669 UnqualifiedId TemplateName;
1670 bool MemberOfUnknownSpecialization;
1671 TemplateName.setIdentifier(Name, NameLoc);
1673 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1674 SS, TemplateKWLoc, TemplateName,
1675 ObjectType, EnteringContext,
1677 if (TNK == TNK_Non_template)
1680 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1681 TemplateName, ObjectType,
1682 EnteringContext, Template,
1683 MemberOfUnknownSpecialization);
1685 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
1686 Diag(NameLoc, diag::err_destructor_template_id)
1687 << Name << SS.getRange();
1698 if (TNK == TNK_Non_template)
1701 // Parse the enclosed template argument list.
1702 SourceLocation LAngleLoc, RAngleLoc;
1703 TemplateArgList TemplateArgs;
1704 if (Tok.is(tok::less) &&
1705 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
1706 SS, true, LAngleLoc,
1711 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
1712 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1713 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
1714 // Form a parsed representation of the template-id to be stored in the
1716 TemplateIdAnnotation *TemplateId
1717 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1719 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1720 TemplateId->Name = Id.Identifier;
1721 TemplateId->Operator = OO_None;
1722 TemplateId->TemplateNameLoc = Id.StartLocation;
1724 TemplateId->Name = 0;
1725 TemplateId->Operator = Id.OperatorFunctionId.Operator;
1726 TemplateId->TemplateNameLoc = Id.StartLocation;
1729 TemplateId->SS = SS;
1730 TemplateId->TemplateKWLoc = TemplateKWLoc;
1731 TemplateId->Template = Template;
1732 TemplateId->Kind = TNK;
1733 TemplateId->LAngleLoc = LAngleLoc;
1734 TemplateId->RAngleLoc = RAngleLoc;
1735 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1736 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
1737 Arg != ArgEnd; ++Arg)
1738 Args[Arg] = TemplateArgs[Arg];
1740 Id.setTemplateId(TemplateId);
1744 // Bundle the template arguments together.
1745 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
1746 TemplateArgs.size());
1748 // Constructor and destructor names.
1750 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1752 LAngleLoc, TemplateArgsPtr, RAngleLoc,
1753 /*IsCtorOrDtorName=*/true);
1754 if (Type.isInvalid())
1757 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1758 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1760 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1765 /// \brief Parse an operator-function-id or conversion-function-id as part
1766 /// of a C++ unqualified-id.
1768 /// This routine is responsible only for parsing the operator-function-id or
1769 /// conversion-function-id; it does not handle template arguments in any way.
1772 /// operator-function-id: [C++ 13.5]
1773 /// 'operator' operator
1775 /// operator: one of
1776 /// new delete new[] delete[]
1777 /// + - * / % ^ & | ~
1778 /// ! = < > += -= *= /= %=
1779 /// ^= &= |= << >> >>= <<= == !=
1780 /// <= >= && || ++ -- , ->* ->
1783 /// conversion-function-id: [C++ 12.3.2]
1784 /// operator conversion-type-id
1786 /// conversion-type-id:
1787 /// type-specifier-seq conversion-declarator[opt]
1789 /// conversion-declarator:
1790 /// ptr-operator conversion-declarator[opt]
1793 /// \param The nested-name-specifier that preceded this unqualified-id. If
1794 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
1796 /// \param EnteringContext whether we are entering the scope of the
1797 /// nested-name-specifier.
1799 /// \param ObjectType if this unqualified-id occurs within a member access
1800 /// expression, the type of the base object whose member is being accessed.
1802 /// \param Result on a successful parse, contains the parsed unqualified-id.
1804 /// \returns true if parsing fails, false otherwise.
1805 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
1806 ParsedType ObjectType,
1807 UnqualifiedId &Result) {
1808 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
1810 // Consume the 'operator' keyword.
1811 SourceLocation KeywordLoc = ConsumeToken();
1813 // Determine what kind of operator name we have.
1814 unsigned SymbolIdx = 0;
1815 SourceLocation SymbolLocations[3];
1816 OverloadedOperatorKind Op = OO_None;
1817 switch (Tok.getKind()) {
1819 case tok::kw_delete: {
1820 bool isNew = Tok.getKind() == tok::kw_new;
1821 // Consume the 'new' or 'delete'.
1822 SymbolLocations[SymbolIdx++] = ConsumeToken();
1823 // Check for array new/delete.
1824 if (Tok.is(tok::l_square) &&
1825 (!getLangOpts().CPlusPlus0x || NextToken().isNot(tok::l_square))) {
1826 // Consume the '[' and ']'.
1827 BalancedDelimiterTracker T(*this, tok::l_square);
1830 if (T.getCloseLocation().isInvalid())
1833 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1834 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1835 Op = isNew? OO_Array_New : OO_Array_Delete;
1837 Op = isNew? OO_New : OO_Delete;
1842 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1844 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
1847 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
1848 #include "clang/Basic/OperatorKinds.def"
1850 case tok::l_paren: {
1851 // Consume the '(' and ')'.
1852 BalancedDelimiterTracker T(*this, tok::l_paren);
1855 if (T.getCloseLocation().isInvalid())
1858 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1859 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1864 case tok::l_square: {
1865 // Consume the '[' and ']'.
1866 BalancedDelimiterTracker T(*this, tok::l_square);
1869 if (T.getCloseLocation().isInvalid())
1872 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1873 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1878 case tok::code_completion: {
1879 // Code completion for the operator name.
1880 Actions.CodeCompleteOperatorName(getCurScope());
1882 // Don't try to parse any further.
1890 if (Op != OO_None) {
1891 // We have parsed an operator-function-id.
1892 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
1896 // Parse a literal-operator-id.
1898 // literal-operator-id: [C++0x 13.5.8]
1899 // operator "" identifier
1901 if (getLangOpts().CPlusPlus0x && isTokenStringLiteral()) {
1902 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
1904 SourceLocation DiagLoc;
1905 unsigned DiagId = 0;
1907 // We're past translation phase 6, so perform string literal concatenation
1908 // before checking for "".
1909 llvm::SmallVector<Token, 4> Toks;
1910 llvm::SmallVector<SourceLocation, 4> TokLocs;
1911 while (isTokenStringLiteral()) {
1912 if (!Tok.is(tok::string_literal) && !DiagId) {
1913 DiagLoc = Tok.getLocation();
1914 DiagId = diag::err_literal_operator_string_prefix;
1916 Toks.push_back(Tok);
1917 TokLocs.push_back(ConsumeStringToken());
1920 StringLiteralParser Literal(Toks.data(), Toks.size(), PP);
1921 if (Literal.hadError)
1924 // Grab the literal operator's suffix, which will be either the next token
1925 // or a ud-suffix from the string literal.
1926 IdentifierInfo *II = 0;
1927 SourceLocation SuffixLoc;
1928 if (!Literal.getUDSuffix().empty()) {
1929 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
1931 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
1932 Literal.getUDSuffixOffset(),
1933 PP.getSourceManager(), getLangOpts());
1934 // This form is not permitted by the standard (yet).
1935 DiagLoc = SuffixLoc;
1936 DiagId = diag::err_literal_operator_missing_space;
1937 } else if (Tok.is(tok::identifier)) {
1938 II = Tok.getIdentifierInfo();
1939 SuffixLoc = ConsumeToken();
1940 TokLocs.push_back(SuffixLoc);
1942 Diag(Tok.getLocation(), diag::err_expected_ident);
1946 // The string literal must be empty.
1947 if (!Literal.GetString().empty() || Literal.Pascal) {
1948 DiagLoc = TokLocs.front();
1949 DiagId = diag::err_literal_operator_string_not_empty;
1953 // This isn't a valid literal-operator-id, but we think we know
1954 // what the user meant. Tell them what they should have written.
1955 llvm::SmallString<32> Str;
1957 Str += II->getName();
1958 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
1959 SourceRange(TokLocs.front(), TokLocs.back()), Str);
1962 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
1966 // Parse a conversion-function-id.
1968 // conversion-function-id: [C++ 12.3.2]
1969 // operator conversion-type-id
1971 // conversion-type-id:
1972 // type-specifier-seq conversion-declarator[opt]
1974 // conversion-declarator:
1975 // ptr-operator conversion-declarator[opt]
1977 // Parse the type-specifier-seq.
1978 DeclSpec DS(AttrFactory);
1979 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
1982 // Parse the conversion-declarator, which is merely a sequence of
1984 Declarator D(DS, Declarator::TypeNameContext);
1985 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
1987 // Finish up the type.
1988 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
1992 // Note that this is a conversion-function-id.
1993 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
1994 D.getSourceRange().getEnd());
1998 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
1999 /// name of an entity.
2002 /// unqualified-id: [C++ expr.prim.general]
2004 /// operator-function-id
2005 /// conversion-function-id
2006 /// [C++0x] literal-operator-id [TODO]
2012 /// \param The nested-name-specifier that preceded this unqualified-id. If
2013 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2015 /// \param EnteringContext whether we are entering the scope of the
2016 /// nested-name-specifier.
2018 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2020 /// \param AllowConstructorName whether we allow parsing a constructor name.
2022 /// \param ObjectType if this unqualified-id occurs within a member access
2023 /// expression, the type of the base object whose member is being accessed.
2025 /// \param Result on a successful parse, contains the parsed unqualified-id.
2027 /// \returns true if parsing fails, false otherwise.
2028 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2029 bool AllowDestructorName,
2030 bool AllowConstructorName,
2031 ParsedType ObjectType,
2032 SourceLocation& TemplateKWLoc,
2033 UnqualifiedId &Result) {
2035 // Handle 'A::template B'. This is for template-ids which have not
2036 // already been annotated by ParseOptionalCXXScopeSpecifier().
2037 bool TemplateSpecified = false;
2038 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2039 (ObjectType || SS.isSet())) {
2040 TemplateSpecified = true;
2041 TemplateKWLoc = ConsumeToken();
2046 // template-id (when it hasn't already been annotated)
2047 if (Tok.is(tok::identifier)) {
2048 // Consume the identifier.
2049 IdentifierInfo *Id = Tok.getIdentifierInfo();
2050 SourceLocation IdLoc = ConsumeToken();
2052 if (!getLangOpts().CPlusPlus) {
2053 // If we're not in C++, only identifiers matter. Record the
2054 // identifier and return.
2055 Result.setIdentifier(Id, IdLoc);
2059 if (AllowConstructorName &&
2060 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2061 // We have parsed a constructor name.
2062 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2065 /*IsCtorOrDtorName=*/true,
2066 /*NonTrivialTypeSourceInfo=*/true);
2067 Result.setConstructorName(Ty, IdLoc, IdLoc);
2069 // We have parsed an identifier.
2070 Result.setIdentifier(Id, IdLoc);
2073 // If the next token is a '<', we may have a template.
2074 if (TemplateSpecified || Tok.is(tok::less))
2075 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2076 EnteringContext, ObjectType,
2077 Result, TemplateSpecified);
2083 // template-id (already parsed and annotated)
2084 if (Tok.is(tok::annot_template_id)) {
2085 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2087 // If the template-name names the current class, then this is a constructor
2088 if (AllowConstructorName && TemplateId->Name &&
2089 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2091 // C++ [class.qual]p2 specifies that a qualified template-name
2092 // is taken as the constructor name where a constructor can be
2093 // declared. Thus, the template arguments are extraneous, so
2094 // complain about them and remove them entirely.
2095 Diag(TemplateId->TemplateNameLoc,
2096 diag::err_out_of_line_constructor_template_id)
2098 << FixItHint::CreateRemoval(
2099 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2100 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2101 TemplateId->TemplateNameLoc,
2105 /*IsCtorOrDtorName=*/true,
2106 /*NontrivialTypeSourceInfo=*/true);
2107 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2108 TemplateId->RAngleLoc);
2113 Result.setConstructorTemplateId(TemplateId);
2118 // We have already parsed a template-id; consume the annotation token as
2119 // our unqualified-id.
2120 Result.setTemplateId(TemplateId);
2121 TemplateKWLoc = TemplateId->TemplateKWLoc;
2127 // operator-function-id
2128 // conversion-function-id
2129 if (Tok.is(tok::kw_operator)) {
2130 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2133 // If we have an operator-function-id or a literal-operator-id and the next
2134 // token is a '<', we may have a
2137 // operator-function-id < template-argument-list[opt] >
2138 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2139 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2140 (TemplateSpecified || Tok.is(tok::less)))
2141 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2142 0, SourceLocation(),
2143 EnteringContext, ObjectType,
2144 Result, TemplateSpecified);
2149 if (getLangOpts().CPlusPlus &&
2150 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2151 // C++ [expr.unary.op]p10:
2152 // There is an ambiguity in the unary-expression ~X(), where X is a
2153 // class-name. The ambiguity is resolved in favor of treating ~ as a
2154 // unary complement rather than treating ~X as referring to a destructor.
2157 SourceLocation TildeLoc = ConsumeToken();
2159 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2160 DeclSpec DS(AttrFactory);
2161 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2162 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2163 Result.setDestructorName(TildeLoc, Type, EndLoc);
2169 // Parse the class-name.
2170 if (Tok.isNot(tok::identifier)) {
2171 Diag(Tok, diag::err_destructor_tilde_identifier);
2175 // Parse the class-name (or template-name in a simple-template-id).
2176 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2177 SourceLocation ClassNameLoc = ConsumeToken();
2179 if (TemplateSpecified || Tok.is(tok::less)) {
2180 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
2181 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2182 ClassName, ClassNameLoc,
2183 EnteringContext, ObjectType,
2184 Result, TemplateSpecified);
2187 // Note that this is a destructor name.
2188 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2189 ClassNameLoc, getCurScope(),
2195 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2199 Diag(Tok, diag::err_expected_unqualified_id)
2200 << getLangOpts().CPlusPlus;
2204 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2205 /// memory in a typesafe manner and call constructors.
2207 /// This method is called to parse the new expression after the optional :: has
2208 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2209 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2212 /// '::'[opt] 'new' new-placement[opt] new-type-id
2213 /// new-initializer[opt]
2214 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2215 /// new-initializer[opt]
2218 /// '(' expression-list ')'
2221 /// type-specifier-seq new-declarator[opt]
2222 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2225 /// ptr-operator new-declarator[opt]
2226 /// direct-new-declarator
2228 /// new-initializer:
2229 /// '(' expression-list[opt] ')'
2230 /// [C++0x] braced-init-list
2233 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2234 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2235 ConsumeToken(); // Consume 'new'
2237 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2238 // second form of new-expression. It can't be a new-type-id.
2240 ExprVector PlacementArgs(Actions);
2241 SourceLocation PlacementLParen, PlacementRParen;
2243 SourceRange TypeIdParens;
2244 DeclSpec DS(AttrFactory);
2245 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2246 if (Tok.is(tok::l_paren)) {
2247 // If it turns out to be a placement, we change the type location.
2248 BalancedDelimiterTracker T(*this, tok::l_paren);
2250 PlacementLParen = T.getOpenLocation();
2251 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2252 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2257 PlacementRParen = T.getCloseLocation();
2258 if (PlacementRParen.isInvalid()) {
2259 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2263 if (PlacementArgs.empty()) {
2264 // Reset the placement locations. There was no placement.
2265 TypeIdParens = T.getRange();
2266 PlacementLParen = PlacementRParen = SourceLocation();
2268 // We still need the type.
2269 if (Tok.is(tok::l_paren)) {
2270 BalancedDelimiterTracker T(*this, tok::l_paren);
2272 MaybeParseGNUAttributes(DeclaratorInfo);
2273 ParseSpecifierQualifierList(DS);
2274 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2275 ParseDeclarator(DeclaratorInfo);
2277 TypeIdParens = T.getRange();
2279 MaybeParseGNUAttributes(DeclaratorInfo);
2280 if (ParseCXXTypeSpecifierSeq(DS))
2281 DeclaratorInfo.setInvalidType(true);
2283 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2284 ParseDeclaratorInternal(DeclaratorInfo,
2285 &Parser::ParseDirectNewDeclarator);
2290 // A new-type-id is a simplified type-id, where essentially the
2291 // direct-declarator is replaced by a direct-new-declarator.
2292 MaybeParseGNUAttributes(DeclaratorInfo);
2293 if (ParseCXXTypeSpecifierSeq(DS))
2294 DeclaratorInfo.setInvalidType(true);
2296 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2297 ParseDeclaratorInternal(DeclaratorInfo,
2298 &Parser::ParseDirectNewDeclarator);
2301 if (DeclaratorInfo.isInvalidType()) {
2302 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2306 ExprResult Initializer;
2308 if (Tok.is(tok::l_paren)) {
2309 SourceLocation ConstructorLParen, ConstructorRParen;
2310 ExprVector ConstructorArgs(Actions);
2311 BalancedDelimiterTracker T(*this, tok::l_paren);
2313 ConstructorLParen = T.getOpenLocation();
2314 if (Tok.isNot(tok::r_paren)) {
2315 CommaLocsTy CommaLocs;
2316 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2317 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2322 ConstructorRParen = T.getCloseLocation();
2323 if (ConstructorRParen.isInvalid()) {
2324 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2327 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2329 move_arg(ConstructorArgs));
2330 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus0x) {
2331 Diag(Tok.getLocation(),
2332 diag::warn_cxx98_compat_generalized_initializer_lists);
2333 Initializer = ParseBraceInitializer();
2335 if (Initializer.isInvalid())
2338 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2339 move_arg(PlacementArgs), PlacementRParen,
2340 TypeIdParens, DeclaratorInfo, Initializer.take());
2343 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2344 /// passed to ParseDeclaratorInternal.
2346 /// direct-new-declarator:
2347 /// '[' expression ']'
2348 /// direct-new-declarator '[' constant-expression ']'
2350 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2351 // Parse the array dimensions.
2353 while (Tok.is(tok::l_square)) {
2354 // An array-size expression can't start with a lambda.
2355 if (CheckProhibitedCXX11Attribute())
2358 BalancedDelimiterTracker T(*this, tok::l_square);
2361 ExprResult Size(first ? ParseExpression()
2362 : ParseConstantExpression());
2363 if (Size.isInvalid()) {
2365 SkipUntil(tok::r_square);
2372 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2373 ParsedAttributes Attrs(AttrFactory);
2374 MaybeParseCXX0XAttributes(Attrs);
2376 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2377 /*static=*/false, /*star=*/false,
2379 T.getOpenLocation(),
2380 T.getCloseLocation()),
2381 Attrs, T.getCloseLocation());
2383 if (T.getCloseLocation().isInvalid())
2388 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2389 /// This ambiguity appears in the syntax of the C++ new operator.
2392 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2393 /// new-initializer[opt]
2396 /// '(' expression-list ')'
2398 bool Parser::ParseExpressionListOrTypeId(
2399 SmallVectorImpl<Expr*> &PlacementArgs,
2401 // The '(' was already consumed.
2402 if (isTypeIdInParens()) {
2403 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2404 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2406 return D.isInvalidType();
2409 // It's not a type, it has to be an expression list.
2410 // Discard the comma locations - ActOnCXXNew has enough parameters.
2411 CommaLocsTy CommaLocs;
2412 return ParseExpressionList(PlacementArgs, CommaLocs);
2415 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2416 /// to free memory allocated by new.
2418 /// This method is called to parse the 'delete' expression after the optional
2419 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2420 /// and "Start" is its location. Otherwise, "Start" is the location of the
2423 /// delete-expression:
2424 /// '::'[opt] 'delete' cast-expression
2425 /// '::'[opt] 'delete' '[' ']' cast-expression
2427 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2428 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2429 ConsumeToken(); // Consume 'delete'
2432 bool ArrayDelete = false;
2433 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2434 // FIXME: This could be the start of a lambda-expression. We should
2435 // disambiguate this, but that will require arbitrary lookahead if
2436 // the next token is '(':
2437 // delete [](int*){ /* ... */
2439 BalancedDelimiterTracker T(*this, tok::l_square);
2443 if (T.getCloseLocation().isInvalid())
2447 ExprResult Operand(ParseCastExpression(false));
2448 if (Operand.isInvalid())
2449 return move(Operand);
2451 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
2454 static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
2456 default: llvm_unreachable("Not a known unary type trait.");
2457 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign;
2458 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
2459 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy;
2460 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign;
2461 case tok::kw___has_trivial_constructor:
2462 return UTT_HasTrivialDefaultConstructor;
2463 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy;
2464 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor;
2465 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor;
2466 case tok::kw___is_abstract: return UTT_IsAbstract;
2467 case tok::kw___is_arithmetic: return UTT_IsArithmetic;
2468 case tok::kw___is_array: return UTT_IsArray;
2469 case tok::kw___is_class: return UTT_IsClass;
2470 case tok::kw___is_complete_type: return UTT_IsCompleteType;
2471 case tok::kw___is_compound: return UTT_IsCompound;
2472 case tok::kw___is_const: return UTT_IsConst;
2473 case tok::kw___is_empty: return UTT_IsEmpty;
2474 case tok::kw___is_enum: return UTT_IsEnum;
2475 case tok::kw___is_final: return UTT_IsFinal;
2476 case tok::kw___is_floating_point: return UTT_IsFloatingPoint;
2477 case tok::kw___is_function: return UTT_IsFunction;
2478 case tok::kw___is_fundamental: return UTT_IsFundamental;
2479 case tok::kw___is_integral: return UTT_IsIntegral;
2480 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference;
2481 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer;
2482 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer;
2483 case tok::kw___is_member_pointer: return UTT_IsMemberPointer;
2484 case tok::kw___is_object: return UTT_IsObject;
2485 case tok::kw___is_literal: return UTT_IsLiteral;
2486 case tok::kw___is_literal_type: return UTT_IsLiteral;
2487 case tok::kw___is_pod: return UTT_IsPOD;
2488 case tok::kw___is_pointer: return UTT_IsPointer;
2489 case tok::kw___is_polymorphic: return UTT_IsPolymorphic;
2490 case tok::kw___is_reference: return UTT_IsReference;
2491 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference;
2492 case tok::kw___is_scalar: return UTT_IsScalar;
2493 case tok::kw___is_signed: return UTT_IsSigned;
2494 case tok::kw___is_standard_layout: return UTT_IsStandardLayout;
2495 case tok::kw___is_trivial: return UTT_IsTrivial;
2496 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable;
2497 case tok::kw___is_union: return UTT_IsUnion;
2498 case tok::kw___is_unsigned: return UTT_IsUnsigned;
2499 case tok::kw___is_void: return UTT_IsVoid;
2500 case tok::kw___is_volatile: return UTT_IsVolatile;
2504 static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) {
2506 default: llvm_unreachable("Not a known binary type trait");
2507 case tok::kw___is_base_of: return BTT_IsBaseOf;
2508 case tok::kw___is_convertible: return BTT_IsConvertible;
2509 case tok::kw___is_same: return BTT_IsSame;
2510 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible;
2511 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo;
2512 case tok::kw___is_trivially_assignable: return BTT_IsTriviallyAssignable;
2516 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2518 default: llvm_unreachable("Not a known type trait");
2519 case tok::kw___is_trivially_constructible:
2520 return TT_IsTriviallyConstructible;
2524 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2526 default: llvm_unreachable("Not a known binary type trait");
2527 case tok::kw___array_rank: return ATT_ArrayRank;
2528 case tok::kw___array_extent: return ATT_ArrayExtent;
2532 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2534 default: llvm_unreachable("Not a known unary expression trait.");
2535 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2536 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2540 /// ParseUnaryTypeTrait - Parse the built-in unary type-trait
2541 /// pseudo-functions that allow implementation of the TR1/C++0x type traits
2544 /// primary-expression:
2545 /// [GNU] unary-type-trait '(' type-id ')'
2547 ExprResult Parser::ParseUnaryTypeTrait() {
2548 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
2549 SourceLocation Loc = ConsumeToken();
2551 BalancedDelimiterTracker T(*this, tok::l_paren);
2552 if (T.expectAndConsume(diag::err_expected_lparen))
2555 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
2556 // there will be cryptic errors about mismatched parentheses and missing
2558 TypeResult Ty = ParseTypeName();
2565 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), T.getCloseLocation());
2568 /// ParseBinaryTypeTrait - Parse the built-in binary type-trait
2569 /// pseudo-functions that allow implementation of the TR1/C++0x type traits
2572 /// primary-expression:
2573 /// [GNU] binary-type-trait '(' type-id ',' type-id ')'
2575 ExprResult Parser::ParseBinaryTypeTrait() {
2576 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind());
2577 SourceLocation Loc = ConsumeToken();
2579 BalancedDelimiterTracker T(*this, tok::l_paren);
2580 if (T.expectAndConsume(diag::err_expected_lparen))
2583 TypeResult LhsTy = ParseTypeName();
2584 if (LhsTy.isInvalid()) {
2585 SkipUntil(tok::r_paren);
2589 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2590 SkipUntil(tok::r_paren);
2594 TypeResult RhsTy = ParseTypeName();
2595 if (RhsTy.isInvalid()) {
2596 SkipUntil(tok::r_paren);
2602 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(),
2603 T.getCloseLocation());
2606 /// \brief Parse the built-in type-trait pseudo-functions that allow
2607 /// implementation of the TR1/C++11 type traits templates.
2609 /// primary-expression:
2610 /// type-trait '(' type-id-seq ')'
2613 /// type-id ...[opt] type-id-seq[opt]
2615 ExprResult Parser::ParseTypeTrait() {
2616 TypeTrait Kind = TypeTraitFromTokKind(Tok.getKind());
2617 SourceLocation Loc = ConsumeToken();
2619 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2620 if (Parens.expectAndConsume(diag::err_expected_lparen))
2623 llvm::SmallVector<ParsedType, 2> Args;
2625 // Parse the next type.
2626 TypeResult Ty = ParseTypeName();
2627 if (Ty.isInvalid()) {
2632 // Parse the ellipsis, if present.
2633 if (Tok.is(tok::ellipsis)) {
2634 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2635 if (Ty.isInvalid()) {
2641 // Add this type to the list of arguments.
2642 Args.push_back(Ty.get());
2644 if (Tok.is(tok::comma)) {
2652 if (Parens.consumeClose())
2655 return Actions.ActOnTypeTrait(Kind, Loc, Args, Parens.getCloseLocation());
2658 /// ParseArrayTypeTrait - Parse the built-in array type-trait
2659 /// pseudo-functions.
2661 /// primary-expression:
2662 /// [Embarcadero] '__array_rank' '(' type-id ')'
2663 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2665 ExprResult Parser::ParseArrayTypeTrait() {
2666 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2667 SourceLocation Loc = ConsumeToken();
2669 BalancedDelimiterTracker T(*this, tok::l_paren);
2670 if (T.expectAndConsume(diag::err_expected_lparen))
2673 TypeResult Ty = ParseTypeName();
2674 if (Ty.isInvalid()) {
2675 SkipUntil(tok::comma);
2676 SkipUntil(tok::r_paren);
2681 case ATT_ArrayRank: {
2683 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL,
2684 T.getCloseLocation());
2686 case ATT_ArrayExtent: {
2687 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2688 SkipUntil(tok::r_paren);
2692 ExprResult DimExpr = ParseExpression();
2695 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2696 T.getCloseLocation());
2699 llvm_unreachable("Invalid ArrayTypeTrait!");
2702 /// ParseExpressionTrait - Parse built-in expression-trait
2703 /// pseudo-functions like __is_lvalue_expr( xxx ).
2705 /// primary-expression:
2706 /// [Embarcadero] expression-trait '(' expression ')'
2708 ExprResult Parser::ParseExpressionTrait() {
2709 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2710 SourceLocation Loc = ConsumeToken();
2712 BalancedDelimiterTracker T(*this, tok::l_paren);
2713 if (T.expectAndConsume(diag::err_expected_lparen))
2716 ExprResult Expr = ParseExpression();
2720 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2721 T.getCloseLocation());
2725 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2726 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2727 /// based on the context past the parens.
2729 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
2731 BalancedDelimiterTracker &Tracker) {
2732 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
2733 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2734 assert(isTypeIdInParens() && "Not a type-id!");
2736 ExprResult Result(true);
2737 CastTy = ParsedType();
2739 // We need to disambiguate a very ugly part of the C++ syntax:
2741 // (T())x; - type-id
2742 // (T())*x; - type-id
2743 // (T())/x; - expression
2744 // (T()); - expression
2746 // The bad news is that we cannot use the specialized tentative parser, since
2747 // it can only verify that the thing inside the parens can be parsed as
2748 // type-id, it is not useful for determining the context past the parens.
2750 // The good news is that the parser can disambiguate this part without
2751 // making any unnecessary Action calls.
2753 // It uses a scheme similar to parsing inline methods. The parenthesized
2754 // tokens are cached, the context that follows is determined (possibly by
2755 // parsing a cast-expression), and then we re-introduce the cached tokens
2756 // into the token stream and parse them appropriately.
2758 ParenParseOption ParseAs;
2761 // Store the tokens of the parentheses. We will parse them after we determine
2762 // the context that follows them.
2763 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
2764 // We didn't find the ')' we expected.
2765 Tracker.consumeClose();
2769 if (Tok.is(tok::l_brace)) {
2770 ParseAs = CompoundLiteral;
2773 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2774 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2777 // Try parsing the cast-expression that may follow.
2778 // If it is not a cast-expression, NotCastExpr will be true and no token
2779 // will be consumed.
2780 Result = ParseCastExpression(false/*isUnaryExpression*/,
2781 false/*isAddressofOperand*/,
2783 // type-id has priority.
2787 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2789 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
2792 // The current token should go after the cached tokens.
2793 Toks.push_back(Tok);
2794 // Re-enter the stored parenthesized tokens into the token stream, so we may
2796 PP.EnterTokenStream(Toks.data(), Toks.size(),
2797 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2798 // Drop the current token and bring the first cached one. It's the same token
2799 // as when we entered this function.
2802 if (ParseAs >= CompoundLiteral) {
2803 // Parse the type declarator.
2804 DeclSpec DS(AttrFactory);
2805 ParseSpecifierQualifierList(DS);
2806 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2807 ParseDeclarator(DeclaratorInfo);
2810 Tracker.consumeClose();
2812 if (ParseAs == CompoundLiteral) {
2813 ExprType = CompoundLiteral;
2814 TypeResult Ty = ParseTypeName();
2815 return ParseCompoundLiteralExpression(Ty.get(),
2816 Tracker.getOpenLocation(),
2817 Tracker.getCloseLocation());
2820 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
2821 assert(ParseAs == CastExpr);
2823 if (DeclaratorInfo.isInvalidType())
2826 // Result is what ParseCastExpression returned earlier.
2827 if (!Result.isInvalid())
2828 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
2829 DeclaratorInfo, CastTy,
2830 Tracker.getCloseLocation(), Result.take());
2831 return move(Result);
2834 // Not a compound literal, and not followed by a cast-expression.
2835 assert(ParseAs == SimpleExpr);
2837 ExprType = SimpleExpr;
2838 Result = ParseExpression();
2839 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2840 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
2841 Tok.getLocation(), Result.take());
2844 if (Result.isInvalid()) {
2845 SkipUntil(tok::r_paren);
2849 Tracker.consumeClose();
2850 return move(Result);