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/Sema/DeclSpec.h"
18 #include "clang/Sema/ParsedTemplate.h"
19 #include "llvm/Support/ErrorHandling.h"
21 using namespace clang;
23 static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
25 case tok::kw_template: return 0;
26 case tok::kw_const_cast: return 1;
27 case tok::kw_dynamic_cast: return 2;
28 case tok::kw_reinterpret_cast: return 3;
29 case tok::kw_static_cast: return 4;
31 assert(0 && "Unknown type for digraph error message.");
36 // Are the two tokens adjacent in the same source file?
37 static bool AreTokensAdjacent(Preprocessor &PP, Token &First, Token &Second) {
38 SourceManager &SM = PP.getSourceManager();
39 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
40 SourceLocation FirstEnd = FirstLoc.getFileLocWithOffset(First.getLength());
41 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
44 // Suggest fixit for "<::" after a cast.
45 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
46 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
47 // Pull '<:' and ':' off token stream.
53 Range.setBegin(DigraphToken.getLocation());
54 Range.setEnd(ColonToken.getLocation());
55 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
56 << SelectDigraphErrorMessage(Kind)
57 << FixItHint::CreateReplacement(Range, "< ::");
59 // Update token information to reflect their change in token type.
60 ColonToken.setKind(tok::coloncolon);
61 ColonToken.setLocation(ColonToken.getLocation().getFileLocWithOffset(-1));
62 ColonToken.setLength(2);
63 DigraphToken.setKind(tok::less);
64 DigraphToken.setLength(1);
66 // Push new tokens back to token stream.
67 PP.EnterToken(ColonToken);
69 PP.EnterToken(DigraphToken);
72 /// \brief Parse global scope or nested-name-specifier if present.
74 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
75 /// may be preceded by '::'). Note that this routine will not parse ::new or
76 /// ::delete; it will just leave them in the token stream.
78 /// '::'[opt] nested-name-specifier
81 /// nested-name-specifier:
83 /// namespace-name '::'
84 /// nested-name-specifier identifier '::'
85 /// nested-name-specifier 'template'[opt] simple-template-id '::'
88 /// \param SS the scope specifier that will be set to the parsed
89 /// nested-name-specifier (or empty)
91 /// \param ObjectType if this nested-name-specifier is being parsed following
92 /// the "." or "->" of a member access expression, this parameter provides the
93 /// type of the object whose members are being accessed.
95 /// \param EnteringContext whether we will be entering into the context of
96 /// the nested-name-specifier after parsing it.
98 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
99 /// indicates whether this nested-name-specifier may be part of a
100 /// pseudo-destructor name. In this case, the flag will be set false
101 /// if we don't actually end up parsing a destructor name. Moreorover,
102 /// if we do end up determining that we are parsing a destructor name,
103 /// the last component of the nested-name-specifier is not parsed as
104 /// part of the scope specifier.
106 /// member access expression, e.g., the \p T:: in \p p->T::m.
108 /// \returns true if there was an error parsing a scope specifier
109 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
110 ParsedType ObjectType,
111 bool EnteringContext,
112 bool *MayBePseudoDestructor,
114 assert(getLang().CPlusPlus &&
115 "Call sites of this function should be guarded by checking for C++");
117 if (Tok.is(tok::annot_cxxscope)) {
118 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
119 Tok.getAnnotationRange(),
125 bool HasScopeSpecifier = false;
127 if (Tok.is(tok::coloncolon)) {
128 // ::new and ::delete aren't nested-name-specifiers.
129 tok::TokenKind NextKind = NextToken().getKind();
130 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
133 // '::' - Global scope qualifier.
134 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
137 HasScopeSpecifier = true;
140 bool CheckForDestructor = false;
141 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
142 CheckForDestructor = true;
143 *MayBePseudoDestructor = false;
147 if (HasScopeSpecifier) {
148 // C++ [basic.lookup.classref]p5:
149 // If the qualified-id has the form
151 // ::class-name-or-namespace-name::...
153 // the class-name-or-namespace-name is looked up in global scope as a
154 // class-name or namespace-name.
156 // To implement this, we clear out the object type as soon as we've
157 // seen a leading '::' or part of a nested-name-specifier.
158 ObjectType = ParsedType();
160 if (Tok.is(tok::code_completion)) {
161 // Code completion for a nested-name-specifier, where the code
162 // code completion token follows the '::'.
163 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
164 SourceLocation ccLoc = ConsumeCodeCompletionToken();
165 // Include code completion token into the range of the scope otherwise
166 // when we try to annotate the scope tokens the dangling code completion
167 // token will cause assertion in
168 // Preprocessor::AnnotatePreviousCachedTokens.
173 // nested-name-specifier:
174 // nested-name-specifier 'template'[opt] simple-template-id '::'
176 // Parse the optional 'template' keyword, then make sure we have
177 // 'identifier <' after it.
178 if (Tok.is(tok::kw_template)) {
179 // If we don't have a scope specifier or an object type, this isn't a
180 // nested-name-specifier, since they aren't allowed to start with
182 if (!HasScopeSpecifier && !ObjectType)
185 TentativeParsingAction TPA(*this);
186 SourceLocation TemplateKWLoc = ConsumeToken();
188 UnqualifiedId TemplateName;
189 if (Tok.is(tok::identifier)) {
190 // Consume the identifier.
191 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
193 } else if (Tok.is(tok::kw_operator)) {
194 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
200 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
201 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
202 Diag(TemplateName.getSourceRange().getBegin(),
203 diag::err_id_after_template_in_nested_name_spec)
204 << TemplateName.getSourceRange();
213 // If the next token is not '<', we have a qualified-id that refers
214 // to a template name, such as T::template apply, but is not a
216 if (Tok.isNot(tok::less)) {
221 // Commit to parsing the template-id.
224 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(getCurScope(),
231 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,
232 TemplateKWLoc, false))
240 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
243 // simple-template-id '::'
245 // So we need to check whether the simple-template-id is of the
246 // right kind (it should name a type or be dependent), and then
247 // convert it into a type within the nested-name-specifier.
248 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
249 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
250 *MayBePseudoDestructor = true;
254 // Consume the template-id token.
257 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
258 SourceLocation CCLoc = ConsumeToken();
260 if (!HasScopeSpecifier)
261 HasScopeSpecifier = true;
263 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
264 TemplateId->getTemplateArgs(),
265 TemplateId->NumArgs);
267 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
268 /*FIXME:*/SourceLocation(),
270 TemplateId->Template,
271 TemplateId->TemplateNameLoc,
272 TemplateId->LAngleLoc,
274 TemplateId->RAngleLoc,
277 SourceLocation StartLoc
278 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
279 : TemplateId->TemplateNameLoc;
280 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
287 // The rest of the nested-name-specifier possibilities start with
289 if (Tok.isNot(tok::identifier))
292 IdentifierInfo &II = *Tok.getIdentifierInfo();
294 // nested-name-specifier:
296 // namespace-name '::'
297 // nested-name-specifier identifier '::'
298 Token Next = NextToken();
300 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
301 // and emit a fixit hint for it.
302 if (Next.is(tok::colon) && !ColonIsSacred) {
303 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
305 Next.getLocation(), ObjectType,
307 // If the token after the colon isn't an identifier, it's still an
308 // error, but they probably meant something else strange so don't
309 // recover like this.
310 PP.LookAhead(1).is(tok::identifier)) {
311 Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
312 << FixItHint::CreateReplacement(Next.getLocation(), "::");
314 // Recover as if the user wrote '::'.
315 Next.setKind(tok::coloncolon);
319 if (Next.is(tok::coloncolon)) {
320 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
321 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
323 *MayBePseudoDestructor = true;
327 // We have an identifier followed by a '::'. Lookup this name
328 // as the name in a nested-name-specifier.
329 SourceLocation IdLoc = ConsumeToken();
330 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
331 "NextToken() not working properly!");
332 SourceLocation CCLoc = ConsumeToken();
334 HasScopeSpecifier = true;
335 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
336 ObjectType, EnteringContext, SS))
337 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
342 // Check for '<::' which should be '< ::' instead of '[:' when following
344 if (Next.is(tok::l_square) && Next.getLength() == 2) {
345 Token SecondToken = GetLookAheadToken(2);
346 if (SecondToken.is(tok::colon) &&
347 AreTokensAdjacent(PP, Next, SecondToken)) {
349 UnqualifiedId TemplateName;
350 TemplateName.setIdentifier(&II, Tok.getLocation());
351 bool MemberOfUnknownSpecialization;
352 if (Actions.isTemplateName(getCurScope(), SS,
353 /*hasTemplateKeyword=*/false,
358 MemberOfUnknownSpecialization)) {
359 FixDigraph(*this, PP, Next, SecondToken, tok::kw_template,
365 // nested-name-specifier:
367 if (Next.is(tok::less)) {
369 UnqualifiedId TemplateName;
370 TemplateName.setIdentifier(&II, Tok.getLocation());
371 bool MemberOfUnknownSpecialization;
372 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
373 /*hasTemplateKeyword=*/false,
378 MemberOfUnknownSpecialization)) {
379 // We have found a template name, so annotate this this token
380 // with a template-id annotation. We do not permit the
381 // template-id to be translated into a type annotation,
382 // because some clients (e.g., the parsing of class template
383 // specializations) still want to see the original template-id
386 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,
387 SourceLocation(), false))
392 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
393 (IsTypename || IsTemplateArgumentList(1))) {
394 // We have something like t::getAs<T>, where getAs is a
395 // member of an unknown specialization. However, this will only
396 // parse correctly as a template, so suggest the keyword 'template'
397 // before 'getAs' and treat this as a dependent template name.
398 unsigned DiagID = diag::err_missing_dependent_template_keyword;
399 if (getLang().Microsoft)
400 DiagID = diag::warn_missing_dependent_template_keyword;
402 Diag(Tok.getLocation(), DiagID)
404 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
406 if (TemplateNameKind TNK
407 = Actions.ActOnDependentTemplateName(getCurScope(),
408 Tok.getLocation(), SS,
409 TemplateName, ObjectType,
410 EnteringContext, Template)) {
411 // Consume the identifier.
413 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,
414 SourceLocation(), false))
424 // We don't have any tokens that form the beginning of a
425 // nested-name-specifier, so we're done.
429 // Even if we didn't see any pieces of a nested-name-specifier, we
430 // still check whether there is a tilde in this position, which
431 // indicates a potential pseudo-destructor.
432 if (CheckForDestructor && Tok.is(tok::tilde))
433 *MayBePseudoDestructor = true;
438 /// ParseCXXIdExpression - Handle id-expression.
445 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
447 /// '::' operator-function-id
450 /// NOTE: The standard specifies that, for qualified-id, the parser does not
453 /// '::' conversion-function-id
454 /// '::' '~' class-name
456 /// This may cause a slight inconsistency on diagnostics:
461 /// :: A :: ~ C(); // Some Sema error about using destructor with a
463 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
466 /// We simplify the parser a bit and make it work like:
469 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
470 /// '::' unqualified-id
472 /// That way Sema can handle and report similar errors for namespaces and the
475 /// The isAddressOfOperand parameter indicates that this id-expression is a
476 /// direct operand of the address-of operator. This is, besides member contexts,
477 /// the only place where a qualified-id naming a non-static class member may
480 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
482 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
483 // '::' unqualified-id
486 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
489 if (ParseUnqualifiedId(SS,
490 /*EnteringContext=*/false,
491 /*AllowDestructorName=*/false,
492 /*AllowConstructorName=*/false,
493 /*ObjectType=*/ ParsedType(),
497 // This is only the direct operand of an & operator if it is not
498 // followed by a postfix-expression suffix.
499 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
500 isAddressOfOperand = false;
502 return Actions.ActOnIdExpression(getCurScope(), SS, Name, Tok.is(tok::l_paren),
507 /// ParseCXXCasts - This handles the various ways to cast expressions to another
510 /// postfix-expression: [C++ 5.2p1]
511 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
512 /// 'static_cast' '<' type-name '>' '(' expression ')'
513 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
514 /// 'const_cast' '<' type-name '>' '(' expression ')'
516 ExprResult Parser::ParseCXXCasts() {
517 tok::TokenKind Kind = Tok.getKind();
518 const char *CastName = 0; // For error messages
521 default: assert(0 && "Unknown C++ cast!"); abort();
522 case tok::kw_const_cast: CastName = "const_cast"; break;
523 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
524 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
525 case tok::kw_static_cast: CastName = "static_cast"; break;
528 SourceLocation OpLoc = ConsumeToken();
529 SourceLocation LAngleBracketLoc = Tok.getLocation();
531 // Check for "<::" which is parsed as "[:". If found, fix token stream,
532 // diagnose error, suggest fix, and recover parsing.
533 Token Next = NextToken();
534 if (Tok.is(tok::l_square) && Tok.getLength() == 2 && Next.is(tok::colon) &&
535 AreTokensAdjacent(PP, Tok, Next))
536 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
538 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
541 // Parse the common declaration-specifiers piece.
542 DeclSpec DS(AttrFactory);
543 ParseSpecifierQualifierList(DS);
545 // Parse the abstract-declarator, if present.
546 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
547 ParseDeclarator(DeclaratorInfo);
549 SourceLocation RAngleBracketLoc = Tok.getLocation();
551 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
552 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
554 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
556 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, CastName))
559 ExprResult Result = ParseExpression();
562 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
564 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
565 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
566 LAngleBracketLoc, DeclaratorInfo,
568 LParenLoc, Result.take(), RParenLoc);
573 /// ParseCXXTypeid - This handles the C++ typeid expression.
575 /// postfix-expression: [C++ 5.2p1]
576 /// 'typeid' '(' expression ')'
577 /// 'typeid' '(' type-id ')'
579 ExprResult Parser::ParseCXXTypeid() {
580 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
582 SourceLocation OpLoc = ConsumeToken();
583 SourceLocation LParenLoc = Tok.getLocation();
584 SourceLocation RParenLoc;
586 // typeid expressions are always parenthesized.
587 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
593 if (isTypeIdInParens()) {
594 TypeResult Ty = ParseTypeName();
597 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
599 if (Ty.isInvalid() || RParenLoc.isInvalid())
602 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
603 Ty.get().getAsOpaquePtr(), RParenLoc);
605 // C++0x [expr.typeid]p3:
606 // When typeid is applied to an expression other than an lvalue of a
607 // polymorphic class type [...] The expression is an unevaluated
608 // operand (Clause 5).
610 // Note that we can't tell whether the expression is an lvalue of a
611 // polymorphic class type until after we've parsed the expression, so
612 // we the expression is potentially potentially evaluated.
613 EnterExpressionEvaluationContext Unevaluated(Actions,
614 Sema::PotentiallyPotentiallyEvaluated);
615 Result = ParseExpression();
618 if (Result.isInvalid())
619 SkipUntil(tok::r_paren);
621 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
622 if (RParenLoc.isInvalid())
625 // If we are a foo<int> that identifies a single function, resolve it now...
626 Expr* e = Result.get();
627 if (e->getType() == Actions.Context.OverloadTy) {
629 Actions.ResolveAndFixSingleFunctionTemplateSpecialization(e);
631 Result = er.release();
633 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
634 Result.release(), RParenLoc);
641 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
643 /// '__uuidof' '(' expression ')'
644 /// '__uuidof' '(' type-id ')'
646 ExprResult Parser::ParseCXXUuidof() {
647 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
649 SourceLocation OpLoc = ConsumeToken();
650 SourceLocation LParenLoc = Tok.getLocation();
651 SourceLocation RParenLoc;
653 // __uuidof expressions are always parenthesized.
654 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
660 if (isTypeIdInParens()) {
661 TypeResult Ty = ParseTypeName();
664 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
669 Result = Actions.ActOnCXXUuidof(OpLoc, LParenLoc, /*isType=*/true,
670 Ty.get().getAsOpaquePtr(), RParenLoc);
672 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
673 Result = ParseExpression();
676 if (Result.isInvalid())
677 SkipUntil(tok::r_paren);
679 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
681 Result = Actions.ActOnCXXUuidof(OpLoc, LParenLoc, /*isType=*/false,
682 Result.release(), RParenLoc);
689 /// \brief Parse a C++ pseudo-destructor expression after the base,
690 /// . or -> operator, and nested-name-specifier have already been
693 /// postfix-expression: [C++ 5.2]
694 /// postfix-expression . pseudo-destructor-name
695 /// postfix-expression -> pseudo-destructor-name
697 /// pseudo-destructor-name:
698 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
699 /// ::[opt] nested-name-specifier template simple-template-id ::
701 /// ::[opt] nested-name-specifier[opt] ~type-name
704 Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
705 tok::TokenKind OpKind,
707 ParsedType ObjectType) {
708 // We're parsing either a pseudo-destructor-name or a dependent
709 // member access that has the same form as a
710 // pseudo-destructor-name. We parse both in the same way and let
711 // the action model sort them out.
713 // Note that the ::[opt] nested-name-specifier[opt] has already
714 // been parsed, and if there was a simple-template-id, it has
715 // been coalesced into a template-id annotation token.
716 UnqualifiedId FirstTypeName;
717 SourceLocation CCLoc;
718 if (Tok.is(tok::identifier)) {
719 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
721 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
722 CCLoc = ConsumeToken();
723 } else if (Tok.is(tok::annot_template_id)) {
724 FirstTypeName.setTemplateId(
725 (TemplateIdAnnotation *)Tok.getAnnotationValue());
727 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
728 CCLoc = ConsumeToken();
730 FirstTypeName.setIdentifier(0, SourceLocation());
734 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
735 SourceLocation TildeLoc = ConsumeToken();
736 if (!Tok.is(tok::identifier)) {
737 Diag(Tok, diag::err_destructor_tilde_identifier);
741 // Parse the second type.
742 UnqualifiedId SecondTypeName;
743 IdentifierInfo *Name = Tok.getIdentifierInfo();
744 SourceLocation NameLoc = ConsumeToken();
745 SecondTypeName.setIdentifier(Name, NameLoc);
747 // If there is a '<', the second type name is a template-id. Parse
749 if (Tok.is(tok::less) &&
750 ParseUnqualifiedIdTemplateId(SS, Name, NameLoc, false, ObjectType,
751 SecondTypeName, /*AssumeTemplateName=*/true,
752 /*TemplateKWLoc*/SourceLocation()))
755 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
757 SS, FirstTypeName, CCLoc,
758 TildeLoc, SecondTypeName,
759 Tok.is(tok::l_paren));
762 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
764 /// boolean-literal: [C++ 2.13.5]
767 ExprResult Parser::ParseCXXBoolLiteral() {
768 tok::TokenKind Kind = Tok.getKind();
769 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
772 /// ParseThrowExpression - This handles the C++ throw expression.
774 /// throw-expression: [C++ 15]
775 /// 'throw' assignment-expression[opt]
776 ExprResult Parser::ParseThrowExpression() {
777 assert(Tok.is(tok::kw_throw) && "Not throw!");
778 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
780 // If the current token isn't the start of an assignment-expression,
781 // then the expression is not present. This handles things like:
782 // "C ? throw : (void)42", which is crazy but legal.
783 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
790 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
793 ExprResult Expr(ParseAssignmentExpression());
794 if (Expr.isInvalid()) return move(Expr);
795 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
799 /// ParseCXXThis - This handles the C++ 'this' pointer.
801 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
802 /// a non-lvalue expression whose value is the address of the object for which
803 /// the function is called.
804 ExprResult Parser::ParseCXXThis() {
805 assert(Tok.is(tok::kw_this) && "Not 'this'!");
806 SourceLocation ThisLoc = ConsumeToken();
807 return Actions.ActOnCXXThis(ThisLoc);
810 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
811 /// Can be interpreted either as function-style casting ("int(x)")
812 /// or class type construction ("ClassType(x,y,z)")
813 /// or creation of a value-initialized type ("int()").
816 /// postfix-expression: [C++ 5.2p1]
817 /// simple-type-specifier '(' expression-list[opt] ')'
818 /// [C++0x] simple-type-specifier braced-init-list
819 /// typename-specifier '(' expression-list[opt] ')'
820 /// [C++0x] typename-specifier braced-init-list
823 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
824 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
825 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
827 assert((Tok.is(tok::l_paren) ||
828 (getLang().CPlusPlus0x && Tok.is(tok::l_brace)))
829 && "Expected '(' or '{'!");
831 if (Tok.is(tok::l_brace)) {
833 // FIXME: Convert to a proper type construct expression.
834 return ParseBraceInitializer();
837 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true);
839 SourceLocation LParenLoc = ConsumeParen();
841 ExprVector Exprs(Actions);
842 CommaLocsTy CommaLocs;
844 if (Tok.isNot(tok::r_paren)) {
845 if (ParseExpressionList(Exprs, CommaLocs)) {
846 SkipUntil(tok::r_paren);
852 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
854 // TypeRep could be null, if it references an invalid typedef.
858 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
859 "Unexpected number of commas!");
860 return Actions.ActOnCXXTypeConstructExpr(TypeRep, LParenLoc, move_arg(Exprs),
865 /// ParseCXXCondition - if/switch/while condition expression.
869 /// type-specifier-seq declarator '=' assignment-expression
870 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
871 /// '=' assignment-expression
873 /// \param ExprResult if the condition was parsed as an expression, the
874 /// parsed expression.
876 /// \param DeclResult if the condition was parsed as a declaration, the
877 /// parsed declaration.
879 /// \param Loc The location of the start of the statement that requires this
880 /// condition, e.g., the "for" in a for loop.
882 /// \param ConvertToBoolean Whether the condition expression should be
883 /// converted to a boolean value.
885 /// \returns true if there was a parsing, false otherwise.
886 bool Parser::ParseCXXCondition(ExprResult &ExprOut,
889 bool ConvertToBoolean) {
890 if (Tok.is(tok::code_completion)) {
891 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
892 ConsumeCodeCompletionToken();
895 if (!isCXXConditionDeclaration()) {
896 // Parse the expression.
897 ExprOut = ParseExpression(); // expression
899 if (ExprOut.isInvalid())
902 // If required, convert to a boolean value.
903 if (ConvertToBoolean)
905 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
906 return ExprOut.isInvalid();
909 // type-specifier-seq
910 DeclSpec DS(AttrFactory);
911 ParseSpecifierQualifierList(DS);
914 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
915 ParseDeclarator(DeclaratorInfo);
917 // simple-asm-expr[opt]
918 if (Tok.is(tok::kw_asm)) {
920 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
921 if (AsmLabel.isInvalid()) {
922 SkipUntil(tok::semi);
925 DeclaratorInfo.setAsmLabel(AsmLabel.release());
926 DeclaratorInfo.SetRangeEnd(Loc);
929 // If attributes are present, parse them.
930 MaybeParseGNUAttributes(DeclaratorInfo);
932 // Type-check the declaration itself.
933 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
936 ExprOut = ExprError();
938 // '=' assignment-expression
939 if (isTokenEqualOrMistypedEqualEqual(
940 diag::err_invalid_equalequal_after_declarator)) {
942 ExprResult AssignExpr(ParseAssignmentExpression());
943 if (!AssignExpr.isInvalid())
944 Actions.AddInitializerToDecl(DeclOut, AssignExpr.take(), false,
945 DS.getTypeSpecType() == DeclSpec::TST_auto);
947 // FIXME: C++0x allows a braced-init-list
948 Diag(Tok, diag::err_expected_equal_after_declarator);
951 // FIXME: Build a reference to this declaration? Convert it to bool?
952 // (This is currently handled by Sema).
954 Actions.FinalizeDeclaration(DeclOut);
959 /// \brief Determine whether the current token starts a C++
960 /// simple-type-specifier.
961 bool Parser::isCXXSimpleTypeSpecifier() const {
962 switch (Tok.getKind()) {
963 case tok::annot_typename:
966 case tok::kw___int64:
968 case tok::kw_unsigned:
974 case tok::kw_wchar_t:
975 case tok::kw_char16_t:
976 case tok::kw_char32_t:
978 case tok::kw_decltype:
980 case tok::kw___underlying_type:
990 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
991 /// This should only be called when the current token is known to be part of
992 /// simple-type-specifier.
994 /// simple-type-specifier:
995 /// '::'[opt] nested-name-specifier[opt] type-name
996 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1008 /// [GNU] typeof-specifier
1009 /// [C++0x] auto [TODO]
1016 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1017 DS.SetRangeStart(Tok.getLocation());
1018 const char *PrevSpec;
1020 SourceLocation Loc = Tok.getLocation();
1022 switch (Tok.getKind()) {
1023 case tok::identifier: // foo::bar
1024 case tok::coloncolon: // ::foo::bar
1025 assert(0 && "Annotation token should already be formed!");
1027 assert(0 && "Not a simple-type-specifier token!");
1031 case tok::annot_typename: {
1032 if (getTypeAnnotation(Tok))
1033 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1034 getTypeAnnotation(Tok));
1036 DS.SetTypeSpecError();
1038 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1041 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1042 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1043 // Objective-C interface. If we don't have Objective-C or a '<', this is
1044 // just a normal reference to a typedef name.
1045 if (Tok.is(tok::less) && getLang().ObjC1)
1046 ParseObjCProtocolQualifiers(DS);
1048 DS.Finish(Diags, PP);
1054 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1057 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
1059 case tok::kw___int64:
1060 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1062 case tok::kw_signed:
1063 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1065 case tok::kw_unsigned:
1066 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1069 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1072 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1075 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1078 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1080 case tok::kw_double:
1081 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1083 case tok::kw_wchar_t:
1084 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1086 case tok::kw_char16_t:
1087 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1089 case tok::kw_char32_t:
1090 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1093 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1096 // FIXME: C++0x decltype support.
1097 // GNU typeof support.
1098 case tok::kw_typeof:
1099 ParseTypeofSpecifier(DS);
1100 DS.Finish(Diags, PP);
1103 if (Tok.is(tok::annot_typename))
1104 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1106 DS.SetRangeEnd(Tok.getLocation());
1108 DS.Finish(Diags, PP);
1111 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1112 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1113 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1114 /// by parsing the type-specifier-seq, because these sequences are
1115 /// typically followed by some form of declarator. Returns true and
1116 /// emits diagnostics if this is not a type-specifier-seq, false
1119 /// type-specifier-seq: [C++ 8.1]
1120 /// type-specifier type-specifier-seq[opt]
1122 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1123 DS.SetRangeStart(Tok.getLocation());
1124 const char *PrevSpec = 0;
1128 // Parse one or more of the type specifiers.
1129 if (!ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1130 ParsedTemplateInfo(), /*SuppressDeclarations*/true)) {
1131 Diag(Tok, diag::err_expected_type);
1135 while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1136 ParsedTemplateInfo(), /*SuppressDeclarations*/true))
1139 DS.Finish(Diags, PP);
1143 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1146 /// This routine is invoked when a '<' is encountered after an identifier or
1147 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1148 /// whether the unqualified-id is actually a template-id. This routine will
1149 /// then parse the template arguments and form the appropriate template-id to
1150 /// return to the caller.
1152 /// \param SS the nested-name-specifier that precedes this template-id, if
1153 /// we're actually parsing a qualified-id.
1155 /// \param Name for constructor and destructor names, this is the actual
1156 /// identifier that may be a template-name.
1158 /// \param NameLoc the location of the class-name in a constructor or
1161 /// \param EnteringContext whether we're entering the scope of the
1162 /// nested-name-specifier.
1164 /// \param ObjectType if this unqualified-id occurs within a member access
1165 /// expression, the type of the base object whose member is being accessed.
1167 /// \param Id as input, describes the template-name or operator-function-id
1168 /// that precedes the '<'. If template arguments were parsed successfully,
1169 /// will be updated with the template-id.
1171 /// \param AssumeTemplateId When true, this routine will assume that the name
1172 /// refers to a template without performing name lookup to verify.
1174 /// \returns true if a parse error occurred, false otherwise.
1175 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1176 IdentifierInfo *Name,
1177 SourceLocation NameLoc,
1178 bool EnteringContext,
1179 ParsedType ObjectType,
1181 bool AssumeTemplateId,
1182 SourceLocation TemplateKWLoc) {
1183 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1184 "Expected '<' to finish parsing a template-id");
1186 TemplateTy Template;
1187 TemplateNameKind TNK = TNK_Non_template;
1188 switch (Id.getKind()) {
1189 case UnqualifiedId::IK_Identifier:
1190 case UnqualifiedId::IK_OperatorFunctionId:
1191 case UnqualifiedId::IK_LiteralOperatorId:
1192 if (AssumeTemplateId) {
1193 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, SS,
1194 Id, ObjectType, EnteringContext,
1196 if (TNK == TNK_Non_template)
1199 bool MemberOfUnknownSpecialization;
1200 TNK = Actions.isTemplateName(getCurScope(), SS,
1201 TemplateKWLoc.isValid(), Id,
1202 ObjectType, EnteringContext, Template,
1203 MemberOfUnknownSpecialization);
1205 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1206 ObjectType && IsTemplateArgumentList()) {
1207 // We have something like t->getAs<T>(), where getAs is a
1208 // member of an unknown specialization. However, this will only
1209 // parse correctly as a template, so suggest the keyword 'template'
1210 // before 'getAs' and treat this as a dependent template name.
1212 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1213 Name = Id.Identifier->getName();
1216 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1217 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1219 Name += Id.Identifier->getName();
1221 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1223 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1224 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc,
1226 EnteringContext, Template);
1227 if (TNK == TNK_Non_template)
1233 case UnqualifiedId::IK_ConstructorName: {
1234 UnqualifiedId TemplateName;
1235 bool MemberOfUnknownSpecialization;
1236 TemplateName.setIdentifier(Name, NameLoc);
1237 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1238 TemplateName, ObjectType,
1239 EnteringContext, Template,
1240 MemberOfUnknownSpecialization);
1244 case UnqualifiedId::IK_DestructorName: {
1245 UnqualifiedId TemplateName;
1246 bool MemberOfUnknownSpecialization;
1247 TemplateName.setIdentifier(Name, NameLoc);
1249 TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, SS,
1250 TemplateName, ObjectType,
1251 EnteringContext, Template);
1252 if (TNK == TNK_Non_template)
1255 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1256 TemplateName, ObjectType,
1257 EnteringContext, Template,
1258 MemberOfUnknownSpecialization);
1260 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
1261 Diag(NameLoc, diag::err_destructor_template_id)
1262 << Name << SS.getRange();
1273 if (TNK == TNK_Non_template)
1276 // Parse the enclosed template argument list.
1277 SourceLocation LAngleLoc, RAngleLoc;
1278 TemplateArgList TemplateArgs;
1279 if (Tok.is(tok::less) &&
1280 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
1281 SS, true, LAngleLoc,
1286 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
1287 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1288 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
1289 // Form a parsed representation of the template-id to be stored in the
1291 TemplateIdAnnotation *TemplateId
1292 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
1294 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1295 TemplateId->Name = Id.Identifier;
1296 TemplateId->Operator = OO_None;
1297 TemplateId->TemplateNameLoc = Id.StartLocation;
1299 TemplateId->Name = 0;
1300 TemplateId->Operator = Id.OperatorFunctionId.Operator;
1301 TemplateId->TemplateNameLoc = Id.StartLocation;
1304 TemplateId->SS = SS;
1305 TemplateId->Template = Template;
1306 TemplateId->Kind = TNK;
1307 TemplateId->LAngleLoc = LAngleLoc;
1308 TemplateId->RAngleLoc = RAngleLoc;
1309 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1310 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
1311 Arg != ArgEnd; ++Arg)
1312 Args[Arg] = TemplateArgs[Arg];
1314 Id.setTemplateId(TemplateId);
1318 // Bundle the template arguments together.
1319 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
1320 TemplateArgs.size());
1322 // Constructor and destructor names.
1324 = Actions.ActOnTemplateIdType(SS, Template, NameLoc,
1325 LAngleLoc, TemplateArgsPtr,
1327 if (Type.isInvalid())
1330 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1331 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1333 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1338 /// \brief Parse an operator-function-id or conversion-function-id as part
1339 /// of a C++ unqualified-id.
1341 /// This routine is responsible only for parsing the operator-function-id or
1342 /// conversion-function-id; it does not handle template arguments in any way.
1345 /// operator-function-id: [C++ 13.5]
1346 /// 'operator' operator
1348 /// operator: one of
1349 /// new delete new[] delete[]
1350 /// + - * / % ^ & | ~
1351 /// ! = < > += -= *= /= %=
1352 /// ^= &= |= << >> >>= <<= == !=
1353 /// <= >= && || ++ -- , ->* ->
1356 /// conversion-function-id: [C++ 12.3.2]
1357 /// operator conversion-type-id
1359 /// conversion-type-id:
1360 /// type-specifier-seq conversion-declarator[opt]
1362 /// conversion-declarator:
1363 /// ptr-operator conversion-declarator[opt]
1366 /// \param The nested-name-specifier that preceded this unqualified-id. If
1367 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
1369 /// \param EnteringContext whether we are entering the scope of the
1370 /// nested-name-specifier.
1372 /// \param ObjectType if this unqualified-id occurs within a member access
1373 /// expression, the type of the base object whose member is being accessed.
1375 /// \param Result on a successful parse, contains the parsed unqualified-id.
1377 /// \returns true if parsing fails, false otherwise.
1378 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
1379 ParsedType ObjectType,
1380 UnqualifiedId &Result) {
1381 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
1383 // Consume the 'operator' keyword.
1384 SourceLocation KeywordLoc = ConsumeToken();
1386 // Determine what kind of operator name we have.
1387 unsigned SymbolIdx = 0;
1388 SourceLocation SymbolLocations[3];
1389 OverloadedOperatorKind Op = OO_None;
1390 switch (Tok.getKind()) {
1392 case tok::kw_delete: {
1393 bool isNew = Tok.getKind() == tok::kw_new;
1394 // Consume the 'new' or 'delete'.
1395 SymbolLocations[SymbolIdx++] = ConsumeToken();
1396 if (Tok.is(tok::l_square)) {
1398 SourceLocation LBracketLoc = ConsumeBracket();
1400 SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square,
1402 if (RBracketLoc.isInvalid())
1405 SymbolLocations[SymbolIdx++] = LBracketLoc;
1406 SymbolLocations[SymbolIdx++] = RBracketLoc;
1407 Op = isNew? OO_Array_New : OO_Array_Delete;
1409 Op = isNew? OO_New : OO_Delete;
1414 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1416 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
1419 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
1420 #include "clang/Basic/OperatorKinds.def"
1422 case tok::l_paren: {
1424 SourceLocation LParenLoc = ConsumeParen();
1426 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren,
1428 if (RParenLoc.isInvalid())
1431 SymbolLocations[SymbolIdx++] = LParenLoc;
1432 SymbolLocations[SymbolIdx++] = RParenLoc;
1437 case tok::l_square: {
1439 SourceLocation LBracketLoc = ConsumeBracket();
1441 SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square,
1443 if (RBracketLoc.isInvalid())
1446 SymbolLocations[SymbolIdx++] = LBracketLoc;
1447 SymbolLocations[SymbolIdx++] = RBracketLoc;
1452 case tok::code_completion: {
1453 // Code completion for the operator name.
1454 Actions.CodeCompleteOperatorName(getCurScope());
1456 // Consume the operator token.
1457 ConsumeCodeCompletionToken();
1459 // Don't try to parse any further.
1467 if (Op != OO_None) {
1468 // We have parsed an operator-function-id.
1469 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
1473 // Parse a literal-operator-id.
1475 // literal-operator-id: [C++0x 13.5.8]
1476 // operator "" identifier
1478 if (getLang().CPlusPlus0x && Tok.is(tok::string_literal)) {
1479 if (Tok.getLength() != 2)
1480 Diag(Tok.getLocation(), diag::err_operator_string_not_empty);
1481 ConsumeStringToken();
1483 if (Tok.isNot(tok::identifier)) {
1484 Diag(Tok.getLocation(), diag::err_expected_ident);
1488 IdentifierInfo *II = Tok.getIdentifierInfo();
1489 Result.setLiteralOperatorId(II, KeywordLoc, ConsumeToken());
1493 // Parse a conversion-function-id.
1495 // conversion-function-id: [C++ 12.3.2]
1496 // operator conversion-type-id
1498 // conversion-type-id:
1499 // type-specifier-seq conversion-declarator[opt]
1501 // conversion-declarator:
1502 // ptr-operator conversion-declarator[opt]
1504 // Parse the type-specifier-seq.
1505 DeclSpec DS(AttrFactory);
1506 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
1509 // Parse the conversion-declarator, which is merely a sequence of
1511 Declarator D(DS, Declarator::TypeNameContext);
1512 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
1514 // Finish up the type.
1515 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
1519 // Note that this is a conversion-function-id.
1520 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
1521 D.getSourceRange().getEnd());
1525 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
1526 /// name of an entity.
1529 /// unqualified-id: [C++ expr.prim.general]
1531 /// operator-function-id
1532 /// conversion-function-id
1533 /// [C++0x] literal-operator-id [TODO]
1539 /// \param The nested-name-specifier that preceded this unqualified-id. If
1540 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
1542 /// \param EnteringContext whether we are entering the scope of the
1543 /// nested-name-specifier.
1545 /// \param AllowDestructorName whether we allow parsing of a destructor name.
1547 /// \param AllowConstructorName whether we allow parsing a constructor name.
1549 /// \param ObjectType if this unqualified-id occurs within a member access
1550 /// expression, the type of the base object whose member is being accessed.
1552 /// \param Result on a successful parse, contains the parsed unqualified-id.
1554 /// \returns true if parsing fails, false otherwise.
1555 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
1556 bool AllowDestructorName,
1557 bool AllowConstructorName,
1558 ParsedType ObjectType,
1559 UnqualifiedId &Result) {
1561 // Handle 'A::template B'. This is for template-ids which have not
1562 // already been annotated by ParseOptionalCXXScopeSpecifier().
1563 bool TemplateSpecified = false;
1564 SourceLocation TemplateKWLoc;
1565 if (getLang().CPlusPlus && Tok.is(tok::kw_template) &&
1566 (ObjectType || SS.isSet())) {
1567 TemplateSpecified = true;
1568 TemplateKWLoc = ConsumeToken();
1573 // template-id (when it hasn't already been annotated)
1574 if (Tok.is(tok::identifier)) {
1575 // Consume the identifier.
1576 IdentifierInfo *Id = Tok.getIdentifierInfo();
1577 SourceLocation IdLoc = ConsumeToken();
1579 if (!getLang().CPlusPlus) {
1580 // If we're not in C++, only identifiers matter. Record the
1581 // identifier and return.
1582 Result.setIdentifier(Id, IdLoc);
1586 if (AllowConstructorName &&
1587 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
1588 // We have parsed a constructor name.
1589 Result.setConstructorName(Actions.getTypeName(*Id, IdLoc, getCurScope(),
1592 /*NonTrivialTypeSourceInfo=*/true),
1595 // We have parsed an identifier.
1596 Result.setIdentifier(Id, IdLoc);
1599 // If the next token is a '<', we may have a template.
1600 if (TemplateSpecified || Tok.is(tok::less))
1601 return ParseUnqualifiedIdTemplateId(SS, Id, IdLoc, EnteringContext,
1603 TemplateSpecified, TemplateKWLoc);
1609 // template-id (already parsed and annotated)
1610 if (Tok.is(tok::annot_template_id)) {
1611 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1613 // If the template-name names the current class, then this is a constructor
1614 if (AllowConstructorName && TemplateId->Name &&
1615 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
1617 // C++ [class.qual]p2 specifies that a qualified template-name
1618 // is taken as the constructor name where a constructor can be
1619 // declared. Thus, the template arguments are extraneous, so
1620 // complain about them and remove them entirely.
1621 Diag(TemplateId->TemplateNameLoc,
1622 diag::err_out_of_line_constructor_template_id)
1624 << FixItHint::CreateRemoval(
1625 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
1626 Result.setConstructorName(Actions.getTypeName(*TemplateId->Name,
1627 TemplateId->TemplateNameLoc,
1631 /*NontrivialTypeSourceInfo=*/true),
1632 TemplateId->TemplateNameLoc,
1633 TemplateId->RAngleLoc);
1638 Result.setConstructorTemplateId(TemplateId);
1643 // We have already parsed a template-id; consume the annotation token as
1644 // our unqualified-id.
1645 Result.setTemplateId(TemplateId);
1651 // operator-function-id
1652 // conversion-function-id
1653 if (Tok.is(tok::kw_operator)) {
1654 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
1657 // If we have an operator-function-id or a literal-operator-id and the next
1658 // token is a '<', we may have a
1661 // operator-function-id < template-argument-list[opt] >
1662 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1663 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
1664 (TemplateSpecified || Tok.is(tok::less)))
1665 return ParseUnqualifiedIdTemplateId(SS, 0, SourceLocation(),
1666 EnteringContext, ObjectType,
1668 TemplateSpecified, TemplateKWLoc);
1673 if (getLang().CPlusPlus &&
1674 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
1675 // C++ [expr.unary.op]p10:
1676 // There is an ambiguity in the unary-expression ~X(), where X is a
1677 // class-name. The ambiguity is resolved in favor of treating ~ as a
1678 // unary complement rather than treating ~X as referring to a destructor.
1681 SourceLocation TildeLoc = ConsumeToken();
1683 // Parse the class-name.
1684 if (Tok.isNot(tok::identifier)) {
1685 Diag(Tok, diag::err_destructor_tilde_identifier);
1689 // Parse the class-name (or template-name in a simple-template-id).
1690 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
1691 SourceLocation ClassNameLoc = ConsumeToken();
1693 if (TemplateSpecified || Tok.is(tok::less)) {
1694 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
1695 return ParseUnqualifiedIdTemplateId(SS, ClassName, ClassNameLoc,
1696 EnteringContext, ObjectType, Result,
1697 TemplateSpecified, TemplateKWLoc);
1700 // Note that this is a destructor name.
1701 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
1702 ClassNameLoc, getCurScope(),
1708 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
1712 Diag(Tok, diag::err_expected_unqualified_id)
1713 << getLang().CPlusPlus;
1717 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
1718 /// memory in a typesafe manner and call constructors.
1720 /// This method is called to parse the new expression after the optional :: has
1721 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
1722 /// is its location. Otherwise, "Start" is the location of the 'new' token.
1725 /// '::'[opt] 'new' new-placement[opt] new-type-id
1726 /// new-initializer[opt]
1727 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
1728 /// new-initializer[opt]
1731 /// '(' expression-list ')'
1734 /// type-specifier-seq new-declarator[opt]
1735 /// [GNU] attributes type-specifier-seq new-declarator[opt]
1738 /// ptr-operator new-declarator[opt]
1739 /// direct-new-declarator
1741 /// new-initializer:
1742 /// '(' expression-list[opt] ')'
1743 /// [C++0x] braced-init-list
1746 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
1747 assert(Tok.is(tok::kw_new) && "expected 'new' token");
1748 ConsumeToken(); // Consume 'new'
1750 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
1751 // second form of new-expression. It can't be a new-type-id.
1753 ExprVector PlacementArgs(Actions);
1754 SourceLocation PlacementLParen, PlacementRParen;
1756 SourceRange TypeIdParens;
1757 DeclSpec DS(AttrFactory);
1758 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
1759 if (Tok.is(tok::l_paren)) {
1760 // If it turns out to be a placement, we change the type location.
1761 PlacementLParen = ConsumeParen();
1762 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
1763 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1767 PlacementRParen = MatchRHSPunctuation(tok::r_paren, PlacementLParen);
1768 if (PlacementRParen.isInvalid()) {
1769 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1773 if (PlacementArgs.empty()) {
1774 // Reset the placement locations. There was no placement.
1775 TypeIdParens = SourceRange(PlacementLParen, PlacementRParen);
1776 PlacementLParen = PlacementRParen = SourceLocation();
1778 // We still need the type.
1779 if (Tok.is(tok::l_paren)) {
1780 TypeIdParens.setBegin(ConsumeParen());
1781 MaybeParseGNUAttributes(DeclaratorInfo);
1782 ParseSpecifierQualifierList(DS);
1783 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
1784 ParseDeclarator(DeclaratorInfo);
1785 TypeIdParens.setEnd(MatchRHSPunctuation(tok::r_paren,
1786 TypeIdParens.getBegin()));
1788 MaybeParseGNUAttributes(DeclaratorInfo);
1789 if (ParseCXXTypeSpecifierSeq(DS))
1790 DeclaratorInfo.setInvalidType(true);
1792 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
1793 ParseDeclaratorInternal(DeclaratorInfo,
1794 &Parser::ParseDirectNewDeclarator);
1799 // A new-type-id is a simplified type-id, where essentially the
1800 // direct-declarator is replaced by a direct-new-declarator.
1801 MaybeParseGNUAttributes(DeclaratorInfo);
1802 if (ParseCXXTypeSpecifierSeq(DS))
1803 DeclaratorInfo.setInvalidType(true);
1805 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
1806 ParseDeclaratorInternal(DeclaratorInfo,
1807 &Parser::ParseDirectNewDeclarator);
1810 if (DeclaratorInfo.isInvalidType()) {
1811 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1815 ExprVector ConstructorArgs(Actions);
1816 SourceLocation ConstructorLParen, ConstructorRParen;
1818 if (Tok.is(tok::l_paren)) {
1819 ConstructorLParen = ConsumeParen();
1820 if (Tok.isNot(tok::r_paren)) {
1821 CommaLocsTy CommaLocs;
1822 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
1823 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1827 ConstructorRParen = MatchRHSPunctuation(tok::r_paren, ConstructorLParen);
1828 if (ConstructorRParen.isInvalid()) {
1829 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1832 } else if (Tok.is(tok::l_brace)) {
1833 // FIXME: Have to communicate the init-list to ActOnCXXNew.
1834 ParseBraceInitializer();
1837 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
1838 move_arg(PlacementArgs), PlacementRParen,
1839 TypeIdParens, DeclaratorInfo, ConstructorLParen,
1840 move_arg(ConstructorArgs), ConstructorRParen);
1843 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
1844 /// passed to ParseDeclaratorInternal.
1846 /// direct-new-declarator:
1847 /// '[' expression ']'
1848 /// direct-new-declarator '[' constant-expression ']'
1850 void Parser::ParseDirectNewDeclarator(Declarator &D) {
1851 // Parse the array dimensions.
1853 while (Tok.is(tok::l_square)) {
1854 SourceLocation LLoc = ConsumeBracket();
1855 ExprResult Size(first ? ParseExpression()
1856 : ParseConstantExpression());
1857 if (Size.isInvalid()) {
1859 SkipUntil(tok::r_square);
1864 SourceLocation RLoc = MatchRHSPunctuation(tok::r_square, LLoc);
1866 ParsedAttributes attrs(AttrFactory);
1867 D.AddTypeInfo(DeclaratorChunk::getArray(0,
1868 /*static=*/false, /*star=*/false,
1869 Size.release(), LLoc, RLoc),
1872 if (RLoc.isInvalid())
1877 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
1878 /// This ambiguity appears in the syntax of the C++ new operator.
1881 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
1882 /// new-initializer[opt]
1885 /// '(' expression-list ')'
1887 bool Parser::ParseExpressionListOrTypeId(
1888 llvm::SmallVectorImpl<Expr*> &PlacementArgs,
1890 // The '(' was already consumed.
1891 if (isTypeIdInParens()) {
1892 ParseSpecifierQualifierList(D.getMutableDeclSpec());
1893 D.SetSourceRange(D.getDeclSpec().getSourceRange());
1895 return D.isInvalidType();
1898 // It's not a type, it has to be an expression list.
1899 // Discard the comma locations - ActOnCXXNew has enough parameters.
1900 CommaLocsTy CommaLocs;
1901 return ParseExpressionList(PlacementArgs, CommaLocs);
1904 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
1905 /// to free memory allocated by new.
1907 /// This method is called to parse the 'delete' expression after the optional
1908 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
1909 /// and "Start" is its location. Otherwise, "Start" is the location of the
1912 /// delete-expression:
1913 /// '::'[opt] 'delete' cast-expression
1914 /// '::'[opt] 'delete' '[' ']' cast-expression
1916 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
1917 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
1918 ConsumeToken(); // Consume 'delete'
1921 bool ArrayDelete = false;
1922 if (Tok.is(tok::l_square)) {
1924 SourceLocation LHS = ConsumeBracket();
1925 SourceLocation RHS = MatchRHSPunctuation(tok::r_square, LHS);
1926 if (RHS.isInvalid())
1930 ExprResult Operand(ParseCastExpression(false));
1931 if (Operand.isInvalid())
1932 return move(Operand);
1934 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
1937 static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
1939 default: assert(false && "Not a known unary type trait.");
1940 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign;
1941 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
1942 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy;
1943 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign;
1944 case tok::kw___has_trivial_constructor:
1945 return UTT_HasTrivialDefaultConstructor;
1946 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy;
1947 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor;
1948 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor;
1949 case tok::kw___is_abstract: return UTT_IsAbstract;
1950 case tok::kw___is_arithmetic: return UTT_IsArithmetic;
1951 case tok::kw___is_array: return UTT_IsArray;
1952 case tok::kw___is_class: return UTT_IsClass;
1953 case tok::kw___is_complete_type: return UTT_IsCompleteType;
1954 case tok::kw___is_compound: return UTT_IsCompound;
1955 case tok::kw___is_const: return UTT_IsConst;
1956 case tok::kw___is_empty: return UTT_IsEmpty;
1957 case tok::kw___is_enum: return UTT_IsEnum;
1958 case tok::kw___is_floating_point: return UTT_IsFloatingPoint;
1959 case tok::kw___is_function: return UTT_IsFunction;
1960 case tok::kw___is_fundamental: return UTT_IsFundamental;
1961 case tok::kw___is_integral: return UTT_IsIntegral;
1962 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference;
1963 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer;
1964 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer;
1965 case tok::kw___is_member_pointer: return UTT_IsMemberPointer;
1966 case tok::kw___is_object: return UTT_IsObject;
1967 case tok::kw___is_literal: return UTT_IsLiteral;
1968 case tok::kw___is_literal_type: return UTT_IsLiteral;
1969 case tok::kw___is_pod: return UTT_IsPOD;
1970 case tok::kw___is_pointer: return UTT_IsPointer;
1971 case tok::kw___is_polymorphic: return UTT_IsPolymorphic;
1972 case tok::kw___is_reference: return UTT_IsReference;
1973 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference;
1974 case tok::kw___is_scalar: return UTT_IsScalar;
1975 case tok::kw___is_signed: return UTT_IsSigned;
1976 case tok::kw___is_standard_layout: return UTT_IsStandardLayout;
1977 case tok::kw___is_trivial: return UTT_IsTrivial;
1978 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable;
1979 case tok::kw___is_union: return UTT_IsUnion;
1980 case tok::kw___is_unsigned: return UTT_IsUnsigned;
1981 case tok::kw___is_void: return UTT_IsVoid;
1982 case tok::kw___is_volatile: return UTT_IsVolatile;
1986 static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) {
1988 default: llvm_unreachable("Not a known binary type trait");
1989 case tok::kw___is_base_of: return BTT_IsBaseOf;
1990 case tok::kw___is_convertible: return BTT_IsConvertible;
1991 case tok::kw___is_same: return BTT_IsSame;
1992 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible;
1993 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo;
1997 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
1999 default: llvm_unreachable("Not a known binary type trait");
2000 case tok::kw___array_rank: return ATT_ArrayRank;
2001 case tok::kw___array_extent: return ATT_ArrayExtent;
2005 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2007 default: assert(false && "Not a known unary expression trait.");
2008 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2009 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2013 /// ParseUnaryTypeTrait - Parse the built-in unary type-trait
2014 /// pseudo-functions that allow implementation of the TR1/C++0x type traits
2017 /// primary-expression:
2018 /// [GNU] unary-type-trait '(' type-id ')'
2020 ExprResult Parser::ParseUnaryTypeTrait() {
2021 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
2022 SourceLocation Loc = ConsumeToken();
2024 SourceLocation LParen = Tok.getLocation();
2025 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
2028 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
2029 // there will be cryptic errors about mismatched parentheses and missing
2031 TypeResult Ty = ParseTypeName();
2033 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
2038 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), RParen);
2041 /// ParseBinaryTypeTrait - Parse the built-in binary type-trait
2042 /// pseudo-functions that allow implementation of the TR1/C++0x type traits
2045 /// primary-expression:
2046 /// [GNU] binary-type-trait '(' type-id ',' type-id ')'
2048 ExprResult Parser::ParseBinaryTypeTrait() {
2049 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind());
2050 SourceLocation Loc = ConsumeToken();
2052 SourceLocation LParen = Tok.getLocation();
2053 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
2056 TypeResult LhsTy = ParseTypeName();
2057 if (LhsTy.isInvalid()) {
2058 SkipUntil(tok::r_paren);
2062 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2063 SkipUntil(tok::r_paren);
2067 TypeResult RhsTy = ParseTypeName();
2068 if (RhsTy.isInvalid()) {
2069 SkipUntil(tok::r_paren);
2073 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
2075 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(), RParen);
2078 /// ParseArrayTypeTrait - Parse the built-in array type-trait
2079 /// pseudo-functions.
2081 /// primary-expression:
2082 /// [Embarcadero] '__array_rank' '(' type-id ')'
2083 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2085 ExprResult Parser::ParseArrayTypeTrait() {
2086 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2087 SourceLocation Loc = ConsumeToken();
2089 SourceLocation LParen = Tok.getLocation();
2090 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
2093 TypeResult Ty = ParseTypeName();
2094 if (Ty.isInvalid()) {
2095 SkipUntil(tok::comma);
2096 SkipUntil(tok::r_paren);
2101 case ATT_ArrayRank: {
2102 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
2103 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL, RParen);
2105 case ATT_ArrayExtent: {
2106 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2107 SkipUntil(tok::r_paren);
2111 ExprResult DimExpr = ParseExpression();
2112 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
2114 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(), RParen);
2122 /// ParseExpressionTrait - Parse built-in expression-trait
2123 /// pseudo-functions like __is_lvalue_expr( xxx ).
2125 /// primary-expression:
2126 /// [Embarcadero] expression-trait '(' expression ')'
2128 ExprResult Parser::ParseExpressionTrait() {
2129 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2130 SourceLocation Loc = ConsumeToken();
2132 SourceLocation LParen = Tok.getLocation();
2133 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
2136 ExprResult Expr = ParseExpression();
2138 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
2140 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(), RParen);
2144 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2145 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2146 /// based on the context past the parens.
2148 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
2150 SourceLocation LParenLoc,
2151 SourceLocation &RParenLoc) {
2152 assert(getLang().CPlusPlus && "Should only be called for C++!");
2153 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2154 assert(isTypeIdInParens() && "Not a type-id!");
2156 ExprResult Result(true);
2157 CastTy = ParsedType();
2159 // We need to disambiguate a very ugly part of the C++ syntax:
2161 // (T())x; - type-id
2162 // (T())*x; - type-id
2163 // (T())/x; - expression
2164 // (T()); - expression
2166 // The bad news is that we cannot use the specialized tentative parser, since
2167 // it can only verify that the thing inside the parens can be parsed as
2168 // type-id, it is not useful for determining the context past the parens.
2170 // The good news is that the parser can disambiguate this part without
2171 // making any unnecessary Action calls.
2173 // It uses a scheme similar to parsing inline methods. The parenthesized
2174 // tokens are cached, the context that follows is determined (possibly by
2175 // parsing a cast-expression), and then we re-introduce the cached tokens
2176 // into the token stream and parse them appropriately.
2178 ParenParseOption ParseAs;
2181 // Store the tokens of the parentheses. We will parse them after we determine
2182 // the context that follows them.
2183 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
2184 // We didn't find the ')' we expected.
2185 MatchRHSPunctuation(tok::r_paren, LParenLoc);
2189 if (Tok.is(tok::l_brace)) {
2190 ParseAs = CompoundLiteral;
2193 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2194 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2197 // Try parsing the cast-expression that may follow.
2198 // If it is not a cast-expression, NotCastExpr will be true and no token
2199 // will be consumed.
2200 Result = ParseCastExpression(false/*isUnaryExpression*/,
2201 false/*isAddressofOperand*/,
2203 // type-id has priority.
2204 true/*isTypeCast*/);
2207 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2209 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
2212 // The current token should go after the cached tokens.
2213 Toks.push_back(Tok);
2214 // Re-enter the stored parenthesized tokens into the token stream, so we may
2216 PP.EnterTokenStream(Toks.data(), Toks.size(),
2217 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2218 // Drop the current token and bring the first cached one. It's the same token
2219 // as when we entered this function.
2222 if (ParseAs >= CompoundLiteral) {
2223 // Parse the type declarator.
2224 DeclSpec DS(AttrFactory);
2225 ParseSpecifierQualifierList(DS);
2226 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2227 ParseDeclarator(DeclaratorInfo);
2230 if (Tok.is(tok::r_paren))
2231 RParenLoc = ConsumeParen();
2233 MatchRHSPunctuation(tok::r_paren, LParenLoc);
2235 if (ParseAs == CompoundLiteral) {
2236 ExprType = CompoundLiteral;
2237 TypeResult Ty = ParseTypeName();
2238 return ParseCompoundLiteralExpression(Ty.get(), LParenLoc, RParenLoc);
2241 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
2242 assert(ParseAs == CastExpr);
2244 if (DeclaratorInfo.isInvalidType())
2247 // Result is what ParseCastExpression returned earlier.
2248 if (!Result.isInvalid())
2249 Result = Actions.ActOnCastExpr(getCurScope(), LParenLoc,
2250 DeclaratorInfo, CastTy,
2251 RParenLoc, Result.take());
2252 return move(Result);
2255 // Not a compound literal, and not followed by a cast-expression.
2256 assert(ParseAs == SimpleExpr);
2258 ExprType = SimpleExpr;
2259 Result = ParseExpression();
2260 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2261 Result = Actions.ActOnParenExpr(LParenLoc, Tok.getLocation(), Result.take());
2264 if (Result.isInvalid()) {
2265 SkipUntil(tok::r_paren);
2269 if (Tok.is(tok::r_paren))
2270 RParenLoc = ConsumeParen();
2272 MatchRHSPunctuation(tok::r_paren, LParenLoc);
2274 return move(Result);