1 //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Expression parsing implementation for C++.
12 //===----------------------------------------------------------------------===//
13 #include "clang/AST/DeclTemplate.h"
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/Basic/PrettyStackTrace.h"
17 #include "clang/Lex/LiteralSupport.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/ParsedTemplate.h"
21 #include "clang/Sema/Scope.h"
22 #include "llvm/Support/ErrorHandling.h"
25 using namespace clang;
27 static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
29 case tok::kw_template: return 0;
30 case tok::kw_const_cast: return 1;
31 case tok::kw_dynamic_cast: return 2;
32 case tok::kw_reinterpret_cast: return 3;
33 case tok::kw_static_cast: return 4;
35 llvm_unreachable("Unknown type for digraph error message.");
39 // Are the two tokens adjacent in the same source file?
40 bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
41 SourceManager &SM = PP.getSourceManager();
42 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
43 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
44 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
47 // Suggest fixit for "<::" after a cast.
48 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
49 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
50 // Pull '<:' and ':' off token stream.
56 Range.setBegin(DigraphToken.getLocation());
57 Range.setEnd(ColonToken.getLocation());
58 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
59 << SelectDigraphErrorMessage(Kind)
60 << FixItHint::CreateReplacement(Range, "< ::");
62 // Update token information to reflect their change in token type.
63 ColonToken.setKind(tok::coloncolon);
64 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
65 ColonToken.setLength(2);
66 DigraphToken.setKind(tok::less);
67 DigraphToken.setLength(1);
69 // Push new tokens back to token stream.
70 PP.EnterToken(ColonToken);
72 PP.EnterToken(DigraphToken);
75 // Check for '<::' which should be '< ::' instead of '[:' when following
77 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
79 IdentifierInfo &II, CXXScopeSpec &SS) {
80 if (!Next.is(tok::l_square) || Next.getLength() != 2)
83 Token SecondToken = GetLookAheadToken(2);
84 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
88 UnqualifiedId TemplateName;
89 TemplateName.setIdentifier(&II, Tok.getLocation());
90 bool MemberOfUnknownSpecialization;
91 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
92 TemplateName, ObjectType, EnteringContext,
93 Template, MemberOfUnknownSpecialization))
96 FixDigraph(*this, PP, Next, SecondToken, tok::kw_template,
100 /// \brief Emits an error for a left parentheses after a double colon.
102 /// When a '(' is found after a '::', emit an error. Attempt to fix the token
103 /// stream by removing the '(', and the matching ')' if found.
104 void Parser::CheckForLParenAfterColonColon() {
105 if (!Tok.is(tok::l_paren))
108 SourceLocation l_parenLoc = ConsumeParen(), r_parenLoc;
109 Token Tok1 = getCurToken();
110 if (!Tok1.is(tok::identifier) && !Tok1.is(tok::star))
113 if (Tok1.is(tok::identifier)) {
114 Token Tok2 = GetLookAheadToken(1);
115 if (Tok2.is(tok::r_paren)) {
118 r_parenLoc = ConsumeParen();
120 } else if (Tok1.is(tok::star)) {
121 Token Tok2 = GetLookAheadToken(1);
122 if (Tok2.is(tok::identifier)) {
123 Token Tok3 = GetLookAheadToken(2);
124 if (Tok3.is(tok::r_paren)) {
129 r_parenLoc = ConsumeParen();
134 Diag(l_parenLoc, diag::err_paren_after_colon_colon)
135 << FixItHint::CreateRemoval(l_parenLoc)
136 << FixItHint::CreateRemoval(r_parenLoc);
139 /// \brief Parse global scope or nested-name-specifier if present.
141 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
142 /// may be preceded by '::'). Note that this routine will not parse ::new or
143 /// ::delete; it will just leave them in the token stream.
145 /// '::'[opt] nested-name-specifier
148 /// nested-name-specifier:
150 /// namespace-name '::'
151 /// nested-name-specifier identifier '::'
152 /// nested-name-specifier 'template'[opt] simple-template-id '::'
155 /// \param SS the scope specifier that will be set to the parsed
156 /// nested-name-specifier (or empty)
158 /// \param ObjectType if this nested-name-specifier is being parsed following
159 /// the "." or "->" of a member access expression, this parameter provides the
160 /// type of the object whose members are being accessed.
162 /// \param EnteringContext whether we will be entering into the context of
163 /// the nested-name-specifier after parsing it.
165 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
166 /// indicates whether this nested-name-specifier may be part of a
167 /// pseudo-destructor name. In this case, the flag will be set false
168 /// if we don't actually end up parsing a destructor name. Moreorover,
169 /// if we do end up determining that we are parsing a destructor name,
170 /// the last component of the nested-name-specifier is not parsed as
171 /// part of the scope specifier.
173 /// \param IsTypename If \c true, this nested-name-specifier is known to be
174 /// part of a type name. This is used to improve error recovery.
176 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
177 /// filled in with the leading identifier in the last component of the
178 /// nested-name-specifier, if any.
180 /// \returns true if there was an error parsing a scope specifier
181 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
182 ParsedType ObjectType,
183 bool EnteringContext,
184 bool *MayBePseudoDestructor,
186 IdentifierInfo **LastII) {
187 assert(getLangOpts().CPlusPlus &&
188 "Call sites of this function should be guarded by checking for C++");
190 if (Tok.is(tok::annot_cxxscope)) {
191 assert(!LastII && "want last identifier but have already annotated scope");
192 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
193 Tok.getAnnotationRange(),
199 if (Tok.is(tok::annot_template_id)) {
200 // If the current token is an annotated template id, it may already have
201 // a scope specifier. Restore it.
202 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
209 bool HasScopeSpecifier = false;
211 if (Tok.is(tok::coloncolon)) {
212 // ::new and ::delete aren't nested-name-specifiers.
213 tok::TokenKind NextKind = NextToken().getKind();
214 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
217 // '::' - Global scope qualifier.
218 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
221 CheckForLParenAfterColonColon();
223 HasScopeSpecifier = true;
226 bool CheckForDestructor = false;
227 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
228 CheckForDestructor = true;
229 *MayBePseudoDestructor = false;
232 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
233 DeclSpec DS(AttrFactory);
234 SourceLocation DeclLoc = Tok.getLocation();
235 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
236 if (Tok.isNot(tok::coloncolon)) {
237 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
241 SourceLocation CCLoc = ConsumeToken();
242 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
243 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
245 HasScopeSpecifier = true;
249 if (HasScopeSpecifier) {
250 // C++ [basic.lookup.classref]p5:
251 // If the qualified-id has the form
253 // ::class-name-or-namespace-name::...
255 // the class-name-or-namespace-name is looked up in global scope as a
256 // class-name or namespace-name.
258 // To implement this, we clear out the object type as soon as we've
259 // seen a leading '::' or part of a nested-name-specifier.
260 ObjectType = ParsedType();
262 if (Tok.is(tok::code_completion)) {
263 // Code completion for a nested-name-specifier, where the code
264 // code completion token follows the '::'.
265 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
266 // Include code completion token into the range of the scope otherwise
267 // when we try to annotate the scope tokens the dangling code completion
268 // token will cause assertion in
269 // Preprocessor::AnnotatePreviousCachedTokens.
270 SS.setEndLoc(Tok.getLocation());
276 // nested-name-specifier:
277 // nested-name-specifier 'template'[opt] simple-template-id '::'
279 // Parse the optional 'template' keyword, then make sure we have
280 // 'identifier <' after it.
281 if (Tok.is(tok::kw_template)) {
282 // If we don't have a scope specifier or an object type, this isn't a
283 // nested-name-specifier, since they aren't allowed to start with
285 if (!HasScopeSpecifier && !ObjectType)
288 TentativeParsingAction TPA(*this);
289 SourceLocation TemplateKWLoc = ConsumeToken();
291 UnqualifiedId TemplateName;
292 if (Tok.is(tok::identifier)) {
293 // Consume the identifier.
294 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
296 } else if (Tok.is(tok::kw_operator)) {
297 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
303 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
304 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
305 Diag(TemplateName.getSourceRange().getBegin(),
306 diag::err_id_after_template_in_nested_name_spec)
307 << TemplateName.getSourceRange();
316 // If the next token is not '<', we have a qualified-id that refers
317 // to a template name, such as T::template apply, but is not a
319 if (Tok.isNot(tok::less)) {
324 // Commit to parsing the template-id.
327 if (TemplateNameKind TNK
328 = Actions.ActOnDependentTemplateName(getCurScope(),
329 SS, TemplateKWLoc, TemplateName,
330 ObjectType, EnteringContext,
332 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
333 TemplateName, false))
341 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
344 // simple-template-id '::'
346 // So we need to check whether the simple-template-id is of the
347 // right kind (it should name a type or be dependent), and then
348 // convert it into a type within the nested-name-specifier.
349 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
350 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
351 *MayBePseudoDestructor = true;
356 *LastII = TemplateId->Name;
358 // Consume the template-id token.
361 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
362 SourceLocation CCLoc = ConsumeToken();
364 HasScopeSpecifier = true;
366 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
367 TemplateId->NumArgs);
369 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
371 TemplateId->TemplateKWLoc,
372 TemplateId->Template,
373 TemplateId->TemplateNameLoc,
374 TemplateId->LAngleLoc,
376 TemplateId->RAngleLoc,
379 SourceLocation StartLoc
380 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
381 : TemplateId->TemplateNameLoc;
382 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
389 // The rest of the nested-name-specifier possibilities start with
391 if (Tok.isNot(tok::identifier))
394 IdentifierInfo &II = *Tok.getIdentifierInfo();
396 // nested-name-specifier:
398 // namespace-name '::'
399 // nested-name-specifier identifier '::'
400 Token Next = NextToken();
402 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
403 // and emit a fixit hint for it.
404 if (Next.is(tok::colon) && !ColonIsSacred) {
405 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
407 Next.getLocation(), ObjectType,
409 // If the token after the colon isn't an identifier, it's still an
410 // error, but they probably meant something else strange so don't
411 // recover like this.
412 PP.LookAhead(1).is(tok::identifier)) {
413 Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
414 << FixItHint::CreateReplacement(Next.getLocation(), "::");
416 // Recover as if the user wrote '::'.
417 Next.setKind(tok::coloncolon);
421 if (Next.is(tok::coloncolon)) {
422 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
423 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
425 *MayBePseudoDestructor = true;
432 // We have an identifier followed by a '::'. Lookup this name
433 // as the name in a nested-name-specifier.
434 SourceLocation IdLoc = ConsumeToken();
435 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
436 "NextToken() not working properly!");
437 SourceLocation CCLoc = ConsumeToken();
439 CheckForLParenAfterColonColon();
441 HasScopeSpecifier = true;
442 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
443 ObjectType, EnteringContext, SS))
444 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
449 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
451 // nested-name-specifier:
453 if (Next.is(tok::less)) {
455 UnqualifiedId TemplateName;
456 TemplateName.setIdentifier(&II, Tok.getLocation());
457 bool MemberOfUnknownSpecialization;
458 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
459 /*hasTemplateKeyword=*/false,
464 MemberOfUnknownSpecialization)) {
465 // We have found a template name, so annotate this token
466 // with a template-id annotation. We do not permit the
467 // template-id to be translated into a type annotation,
468 // because some clients (e.g., the parsing of class template
469 // specializations) still want to see the original template-id
472 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
473 TemplateName, false))
478 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
479 (IsTypename || IsTemplateArgumentList(1))) {
480 // We have something like t::getAs<T>, where getAs is a
481 // member of an unknown specialization. However, this will only
482 // parse correctly as a template, so suggest the keyword 'template'
483 // before 'getAs' and treat this as a dependent template name.
484 unsigned DiagID = diag::err_missing_dependent_template_keyword;
485 if (getLangOpts().MicrosoftExt)
486 DiagID = diag::warn_missing_dependent_template_keyword;
488 Diag(Tok.getLocation(), DiagID)
490 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
492 if (TemplateNameKind TNK
493 = Actions.ActOnDependentTemplateName(getCurScope(),
494 SS, SourceLocation(),
495 TemplateName, ObjectType,
496 EnteringContext, Template)) {
497 // Consume the identifier.
499 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
500 TemplateName, false))
510 // We don't have any tokens that form the beginning of a
511 // nested-name-specifier, so we're done.
515 // Even if we didn't see any pieces of a nested-name-specifier, we
516 // still check whether there is a tilde in this position, which
517 // indicates a potential pseudo-destructor.
518 if (CheckForDestructor && Tok.is(tok::tilde))
519 *MayBePseudoDestructor = true;
524 /// ParseCXXIdExpression - Handle id-expression.
531 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
533 /// '::' operator-function-id
536 /// NOTE: The standard specifies that, for qualified-id, the parser does not
539 /// '::' conversion-function-id
540 /// '::' '~' class-name
542 /// This may cause a slight inconsistency on diagnostics:
547 /// :: A :: ~ C(); // Some Sema error about using destructor with a
549 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
552 /// We simplify the parser a bit and make it work like:
555 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
556 /// '::' unqualified-id
558 /// That way Sema can handle and report similar errors for namespaces and the
561 /// The isAddressOfOperand parameter indicates that this id-expression is a
562 /// direct operand of the address-of operator. This is, besides member contexts,
563 /// the only place where a qualified-id naming a non-static class member may
566 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
568 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
569 // '::' unqualified-id
572 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
574 SourceLocation TemplateKWLoc;
576 if (ParseUnqualifiedId(SS,
577 /*EnteringContext=*/false,
578 /*AllowDestructorName=*/false,
579 /*AllowConstructorName=*/false,
580 /*ObjectType=*/ ParsedType(),
585 // This is only the direct operand of an & operator if it is not
586 // followed by a postfix-expression suffix.
587 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
588 isAddressOfOperand = false;
590 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
591 Tok.is(tok::l_paren), isAddressOfOperand);
594 /// ParseLambdaExpression - Parse a C++11 lambda expression.
596 /// lambda-expression:
597 /// lambda-introducer lambda-declarator[opt] compound-statement
599 /// lambda-introducer:
600 /// '[' lambda-capture[opt] ']'
605 /// capture-default ',' capture-list
613 /// capture-list ',' capture
617 /// init-capture [C++1y]
624 /// init-capture: [C++1y]
625 /// identifier initializer
626 /// '&' identifier initializer
628 /// lambda-declarator:
629 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
630 /// 'mutable'[opt] exception-specification[opt]
631 /// trailing-return-type[opt]
633 ExprResult Parser::ParseLambdaExpression() {
634 // Parse lambda-introducer.
635 LambdaIntroducer Intro;
636 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
638 Diag(Tok, DiagID.getValue());
639 SkipUntil(tok::r_square, StopAtSemi);
640 SkipUntil(tok::l_brace, StopAtSemi);
641 SkipUntil(tok::r_brace, StopAtSemi);
645 return ParseLambdaExpressionAfterIntroducer(Intro);
648 /// TryParseLambdaExpression - Use lookahead and potentially tentative
649 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
652 /// If we are not looking at a lambda expression, returns ExprError().
653 ExprResult Parser::TryParseLambdaExpression() {
654 assert(getLangOpts().CPlusPlus11
655 && Tok.is(tok::l_square)
656 && "Not at the start of a possible lambda expression.");
658 const Token Next = NextToken(), After = GetLookAheadToken(2);
660 // If lookahead indicates this is a lambda...
661 if (Next.is(tok::r_square) || // []
662 Next.is(tok::equal) || // [=
663 (Next.is(tok::amp) && // [&] or [&,
664 (After.is(tok::r_square) ||
665 After.is(tok::comma))) ||
666 (Next.is(tok::identifier) && // [identifier]
667 After.is(tok::r_square))) {
668 return ParseLambdaExpression();
671 // If lookahead indicates an ObjC message send...
672 // [identifier identifier
673 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
677 // Here, we're stuck: lambda introducers and Objective-C message sends are
678 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
679 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
680 // writing two routines to parse a lambda introducer, just try to parse
681 // a lambda introducer first, and fall back if that fails.
682 // (TryParseLambdaIntroducer never produces any diagnostic output.)
683 LambdaIntroducer Intro;
684 if (TryParseLambdaIntroducer(Intro))
687 return ParseLambdaExpressionAfterIntroducer(Intro);
690 /// \brief Parse a lambda introducer.
691 /// \param Intro A LambdaIntroducer filled in with information about the
692 /// contents of the lambda-introducer.
693 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
694 /// message send and a lambda expression. In this mode, we will
695 /// sometimes skip the initializers for init-captures and not fully
696 /// populate \p Intro. This flag will be set to \c true if we do so.
697 /// \return A DiagnosticID if it hit something unexpected. The location for
698 /// for the diagnostic is that of the current token.
699 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
700 bool *SkippedInits) {
701 typedef Optional<unsigned> DiagResult;
703 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
704 BalancedDelimiterTracker T(*this, tok::l_square);
707 Intro.Range.setBegin(T.getOpenLocation());
711 // Parse capture-default.
712 if (Tok.is(tok::amp) &&
713 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
714 Intro.Default = LCD_ByRef;
715 Intro.DefaultLoc = ConsumeToken();
717 } else if (Tok.is(tok::equal)) {
718 Intro.Default = LCD_ByCopy;
719 Intro.DefaultLoc = ConsumeToken();
723 while (Tok.isNot(tok::r_square)) {
725 if (Tok.isNot(tok::comma)) {
726 // Provide a completion for a lambda introducer here. Except
727 // in Objective-C, where this is Almost Surely meant to be a message
728 // send. In that case, fail here and let the ObjC message
729 // expression parser perform the completion.
730 if (Tok.is(tok::code_completion) &&
731 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
732 !Intro.Captures.empty())) {
733 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
734 /*AfterAmpersand=*/false);
735 ConsumeCodeCompletionToken();
739 return DiagResult(diag::err_expected_comma_or_rsquare);
744 if (Tok.is(tok::code_completion)) {
745 // If we're in Objective-C++ and we have a bare '[', then this is more
746 // likely to be a message receiver.
747 if (getLangOpts().ObjC1 && first)
748 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
750 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
751 /*AfterAmpersand=*/false);
752 ConsumeCodeCompletionToken();
759 LambdaCaptureKind Kind = LCK_ByCopy;
761 IdentifierInfo* Id = 0;
762 SourceLocation EllipsisLoc;
765 if (Tok.is(tok::kw_this)) {
767 Loc = ConsumeToken();
769 if (Tok.is(tok::amp)) {
773 if (Tok.is(tok::code_completion)) {
774 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
775 /*AfterAmpersand=*/true);
776 ConsumeCodeCompletionToken();
781 if (Tok.is(tok::identifier)) {
782 Id = Tok.getIdentifierInfo();
783 Loc = ConsumeToken();
784 } else if (Tok.is(tok::kw_this)) {
785 // FIXME: If we want to suggest a fixit here, will need to return more
786 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
787 // Clear()ed to prevent emission in case of tentative parsing?
788 return DiagResult(diag::err_this_captured_by_reference);
790 return DiagResult(diag::err_expected_capture);
793 if (Tok.is(tok::l_paren)) {
794 BalancedDelimiterTracker Parens(*this, tok::l_paren);
795 Parens.consumeOpen();
801 *SkippedInits = true;
802 } else if (ParseExpressionList(Exprs, Commas)) {
806 Parens.consumeClose();
807 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
808 Parens.getCloseLocation(),
811 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
812 // Each lambda init-capture forms its own full expression, which clears
813 // Actions.MaybeODRUseExprs. So create an expression evaluation context
814 // to save the necessary state, and restore it later.
815 EnterExpressionEvaluationContext EC(Actions,
816 Sema::PotentiallyEvaluated);
817 if (Tok.is(tok::equal))
821 Init = ParseInitializer();
822 else if (Tok.is(tok::l_brace)) {
823 BalancedDelimiterTracker Braces(*this, tok::l_brace);
824 Braces.consumeOpen();
826 *SkippedInits = true;
828 // We're disambiguating this:
832 // We need to find the end of the following expression in order to
833 // determine whether this is an Obj-C message send's receiver, or a
834 // lambda init-capture.
836 // Parse the expression to find where it ends, and annotate it back
837 // onto the tokens. We would have parsed this expression the same way
838 // in either case: both the RHS of an init-capture and the RHS of an
839 // assignment expression are parsed as an initializer-clause, and in
840 // neither case can anything be added to the scope between the '[' and
843 // FIXME: This is horrible. Adding a mechanism to skip an expression
844 // would be much cleaner.
845 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
846 // that instead. (And if we see a ':' with no matching '?', we can
847 // classify this as an Obj-C message send.)
848 SourceLocation StartLoc = Tok.getLocation();
849 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
850 Init = ParseInitializer();
852 if (Tok.getLocation() != StartLoc) {
853 // Back out the lexing of the token after the initializer.
854 PP.RevertCachedTokens(1);
856 // Replace the consumed tokens with an appropriate annotation.
857 Tok.setLocation(StartLoc);
858 Tok.setKind(tok::annot_primary_expr);
859 setExprAnnotation(Tok, Init);
860 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
861 PP.AnnotateCachedTokens(Tok);
863 // Consume the annotated initializer.
867 } else if (Tok.is(tok::ellipsis))
868 EllipsisLoc = ConsumeToken();
870 // If this is an init capture, process the initialization expression
871 // right away. For lambda init-captures such as the following:
873 // auto L = [i = x+1](int a) {
875 // &k = x](char b) { };
877 // keep in mind that each lambda init-capture has to have:
878 // - its initialization expression executed in the context
879 // of the enclosing/parent decl-context.
880 // - but the variable itself has to be 'injected' into the
881 // decl-context of its lambda's call-operator (which has
882 // not yet been created).
883 // Each init-expression is a full-expression that has to get
884 // Sema-analyzed (for capturing etc.) before its lambda's
885 // call-operator's decl-context, scope & scopeinfo are pushed on their
886 // respective stacks. Thus if any variable is odr-used in the init-capture
887 // it will correctly get captured in the enclosing lambda, if one exists.
888 // The init-variables above are created later once the lambdascope and
889 // call-operators decl-context is pushed onto its respective stack.
891 // Since the lambda init-capture's initializer expression occurs in the
892 // context of the enclosing function or lambda, therefore we can not wait
893 // till a lambda scope has been pushed on before deciding whether the
894 // variable needs to be captured. We also need to process all
895 // lvalue-to-rvalue conversions and discarded-value conversions,
896 // so that we can avoid capturing certain constant variables.
900 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
901 // return [y = x](int i) { <-- don't capture by enclosing lambda
905 // If x was not const, the second use would require 'L' to capture, and
906 // that would be an error.
908 ParsedType InitCaptureParsedType;
909 if (Init.isUsable()) {
910 // Get the pointer and store it in an lvalue, so we can use it as an
912 Expr *InitExpr = Init.get();
913 // This performs any lvalue-to-rvalue conversions if necessary, which
914 // can affect what gets captured in the containing decl-context.
915 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
916 Loc, Kind == LCK_ByRef, Id, InitExpr);
918 InitCaptureParsedType.set(InitCaptureType);
920 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
924 Intro.Range.setEnd(T.getCloseLocation());
928 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
930 /// Returns true if it hit something unexpected.
931 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
932 TentativeParsingAction PA(*this);
934 bool SkippedInits = false;
935 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
943 // Parse it again, but this time parse the init-captures too.
945 Intro = LambdaIntroducer();
946 DiagID = ParseLambdaIntroducer(Intro);
947 assert(!DiagID && "parsing lambda-introducer failed on reparse");
955 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
957 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
958 LambdaIntroducer &Intro) {
959 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
960 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
962 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
963 "lambda expression parsing");
967 // FIXME: Call into Actions to add any init-capture declarations to the
968 // scope while parsing the lambda-declarator and compound-statement.
970 // Parse lambda-declarator[opt].
971 DeclSpec DS(AttrFactory);
972 Declarator D(DS, Declarator::LambdaExprContext);
973 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
974 Actions.PushLambdaScope();
976 if (Tok.is(tok::l_paren)) {
977 ParseScope PrototypeScope(this,
978 Scope::FunctionPrototypeScope |
979 Scope::FunctionDeclarationScope |
982 SourceLocation DeclEndLoc;
983 BalancedDelimiterTracker T(*this, tok::l_paren);
985 SourceLocation LParenLoc = T.getOpenLocation();
987 // Parse parameter-declaration-clause.
988 ParsedAttributes Attr(AttrFactory);
989 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
990 SourceLocation EllipsisLoc;
993 if (Tok.isNot(tok::r_paren)) {
994 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
995 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
996 // For a generic lambda, each 'auto' within the parameter declaration
997 // clause creates a template type parameter, so increment the depth.
998 if (Actions.getCurGenericLambda())
999 ++CurTemplateDepthTracker;
1002 SourceLocation RParenLoc = T.getCloseLocation();
1003 DeclEndLoc = RParenLoc;
1005 // Parse 'mutable'[opt].
1006 SourceLocation MutableLoc;
1007 if (Tok.is(tok::kw_mutable)) {
1008 MutableLoc = ConsumeToken();
1009 DeclEndLoc = MutableLoc;
1012 // Parse exception-specification[opt].
1013 ExceptionSpecificationType ESpecType = EST_None;
1014 SourceRange ESpecRange;
1015 SmallVector<ParsedType, 2> DynamicExceptions;
1016 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1017 ExprResult NoexceptExpr;
1018 ESpecType = tryParseExceptionSpecification(ESpecRange,
1020 DynamicExceptionRanges,
1023 if (ESpecType != EST_None)
1024 DeclEndLoc = ESpecRange.getEnd();
1026 // Parse attribute-specifier[opt].
1027 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1029 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1031 // Parse trailing-return-type[opt].
1032 TypeResult TrailingReturnType;
1033 if (Tok.is(tok::arrow)) {
1034 FunLocalRangeEnd = Tok.getLocation();
1036 TrailingReturnType = ParseTrailingReturnType(Range);
1037 if (Range.getEnd().isValid())
1038 DeclEndLoc = Range.getEnd();
1041 PrototypeScope.Exit();
1043 SourceLocation NoLoc;
1044 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1045 /*isAmbiguous=*/false,
1047 ParamInfo.data(), ParamInfo.size(),
1048 EllipsisLoc, RParenLoc,
1049 DS.getTypeQualifiers(),
1050 /*RefQualifierIsLValueRef=*/true,
1051 /*RefQualifierLoc=*/NoLoc,
1052 /*ConstQualifierLoc=*/NoLoc,
1053 /*VolatileQualifierLoc=*/NoLoc,
1055 ESpecType, ESpecRange.getBegin(),
1056 DynamicExceptions.data(),
1057 DynamicExceptionRanges.data(),
1058 DynamicExceptions.size(),
1059 NoexceptExpr.isUsable() ?
1060 NoexceptExpr.get() : 0,
1061 LParenLoc, FunLocalRangeEnd, D,
1062 TrailingReturnType),
1064 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) {
1065 // It's common to forget that one needs '()' before 'mutable' or the
1066 // result type. Deal with this.
1067 Diag(Tok, diag::err_lambda_missing_parens)
1068 << Tok.is(tok::arrow)
1069 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1070 SourceLocation DeclLoc = Tok.getLocation();
1071 SourceLocation DeclEndLoc = DeclLoc;
1073 // Parse 'mutable', if it's there.
1074 SourceLocation MutableLoc;
1075 if (Tok.is(tok::kw_mutable)) {
1076 MutableLoc = ConsumeToken();
1077 DeclEndLoc = MutableLoc;
1080 // Parse the return type, if there is one.
1081 TypeResult TrailingReturnType;
1082 if (Tok.is(tok::arrow)) {
1084 TrailingReturnType = ParseTrailingReturnType(Range);
1085 if (Range.getEnd().isValid())
1086 DeclEndLoc = Range.getEnd();
1089 ParsedAttributes Attr(AttrFactory);
1090 SourceLocation NoLoc;
1091 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1092 /*isAmbiguous=*/false,
1093 /*LParenLoc=*/NoLoc,
1096 /*EllipsisLoc=*/NoLoc,
1097 /*RParenLoc=*/NoLoc,
1099 /*RefQualifierIsLValueRef=*/true,
1100 /*RefQualifierLoc=*/NoLoc,
1101 /*ConstQualifierLoc=*/NoLoc,
1102 /*VolatileQualifierLoc=*/NoLoc,
1107 /*ExceptionRanges=*/0,
1108 /*NumExceptions=*/0,
1110 DeclLoc, DeclEndLoc, D,
1111 TrailingReturnType),
1116 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1118 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
1119 ParseScope BodyScope(this, ScopeFlags);
1121 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1123 // Parse compound-statement.
1124 if (!Tok.is(tok::l_brace)) {
1125 Diag(Tok, diag::err_expected_lambda_body);
1126 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1130 StmtResult Stmt(ParseCompoundStatementBody());
1133 if (!Stmt.isInvalid())
1134 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope());
1136 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1140 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1143 /// postfix-expression: [C++ 5.2p1]
1144 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1145 /// 'static_cast' '<' type-name '>' '(' expression ')'
1146 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1147 /// 'const_cast' '<' type-name '>' '(' expression ')'
1149 ExprResult Parser::ParseCXXCasts() {
1150 tok::TokenKind Kind = Tok.getKind();
1151 const char *CastName = 0; // For error messages
1154 default: llvm_unreachable("Unknown C++ cast!");
1155 case tok::kw_const_cast: CastName = "const_cast"; break;
1156 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1157 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1158 case tok::kw_static_cast: CastName = "static_cast"; break;
1161 SourceLocation OpLoc = ConsumeToken();
1162 SourceLocation LAngleBracketLoc = Tok.getLocation();
1164 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1165 // diagnose error, suggest fix, and recover parsing.
1166 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1167 Token Next = NextToken();
1168 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1169 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1172 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1175 // Parse the common declaration-specifiers piece.
1176 DeclSpec DS(AttrFactory);
1177 ParseSpecifierQualifierList(DS);
1179 // Parse the abstract-declarator, if present.
1180 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1181 ParseDeclarator(DeclaratorInfo);
1183 SourceLocation RAngleBracketLoc = Tok.getLocation();
1185 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
1186 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
1188 SourceLocation LParenLoc, RParenLoc;
1189 BalancedDelimiterTracker T(*this, tok::l_paren);
1191 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1194 ExprResult Result = ParseExpression();
1199 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1200 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1201 LAngleBracketLoc, DeclaratorInfo,
1203 T.getOpenLocation(), Result.take(),
1204 T.getCloseLocation());
1209 /// ParseCXXTypeid - This handles the C++ typeid expression.
1211 /// postfix-expression: [C++ 5.2p1]
1212 /// 'typeid' '(' expression ')'
1213 /// 'typeid' '(' type-id ')'
1215 ExprResult Parser::ParseCXXTypeid() {
1216 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1218 SourceLocation OpLoc = ConsumeToken();
1219 SourceLocation LParenLoc, RParenLoc;
1220 BalancedDelimiterTracker T(*this, tok::l_paren);
1222 // typeid expressions are always parenthesized.
1223 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1225 LParenLoc = T.getOpenLocation();
1229 // C++0x [expr.typeid]p3:
1230 // When typeid is applied to an expression other than an lvalue of a
1231 // polymorphic class type [...] The expression is an unevaluated
1232 // operand (Clause 5).
1234 // Note that we can't tell whether the expression is an lvalue of a
1235 // polymorphic class type until after we've parsed the expression; we
1236 // speculatively assume the subexpression is unevaluated, and fix it up
1239 // We enter the unevaluated context before trying to determine whether we
1240 // have a type-id, because the tentative parse logic will try to resolve
1241 // names, and must treat them as unevaluated.
1242 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1243 Sema::ReuseLambdaContextDecl);
1245 if (isTypeIdInParens()) {
1246 TypeResult Ty = ParseTypeName();
1250 RParenLoc = T.getCloseLocation();
1251 if (Ty.isInvalid() || RParenLoc.isInvalid())
1254 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1255 Ty.get().getAsOpaquePtr(), RParenLoc);
1257 Result = ParseExpression();
1260 if (Result.isInvalid())
1261 SkipUntil(tok::r_paren, StopAtSemi);
1264 RParenLoc = T.getCloseLocation();
1265 if (RParenLoc.isInvalid())
1268 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1269 Result.release(), RParenLoc);
1276 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1278 /// '__uuidof' '(' expression ')'
1279 /// '__uuidof' '(' type-id ')'
1281 ExprResult Parser::ParseCXXUuidof() {
1282 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1284 SourceLocation OpLoc = ConsumeToken();
1285 BalancedDelimiterTracker T(*this, tok::l_paren);
1287 // __uuidof expressions are always parenthesized.
1288 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1293 if (isTypeIdInParens()) {
1294 TypeResult Ty = ParseTypeName();
1302 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1303 Ty.get().getAsOpaquePtr(),
1304 T.getCloseLocation());
1306 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1307 Result = ParseExpression();
1310 if (Result.isInvalid())
1311 SkipUntil(tok::r_paren, StopAtSemi);
1315 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1317 Result.release(), T.getCloseLocation());
1324 /// \brief Parse a C++ pseudo-destructor expression after the base,
1325 /// . or -> operator, and nested-name-specifier have already been
1328 /// postfix-expression: [C++ 5.2]
1329 /// postfix-expression . pseudo-destructor-name
1330 /// postfix-expression -> pseudo-destructor-name
1332 /// pseudo-destructor-name:
1333 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1334 /// ::[opt] nested-name-specifier template simple-template-id ::
1336 /// ::[opt] nested-name-specifier[opt] ~type-name
1339 Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1340 tok::TokenKind OpKind,
1342 ParsedType ObjectType) {
1343 // We're parsing either a pseudo-destructor-name or a dependent
1344 // member access that has the same form as a
1345 // pseudo-destructor-name. We parse both in the same way and let
1346 // the action model sort them out.
1348 // Note that the ::[opt] nested-name-specifier[opt] has already
1349 // been parsed, and if there was a simple-template-id, it has
1350 // been coalesced into a template-id annotation token.
1351 UnqualifiedId FirstTypeName;
1352 SourceLocation CCLoc;
1353 if (Tok.is(tok::identifier)) {
1354 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1356 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1357 CCLoc = ConsumeToken();
1358 } else if (Tok.is(tok::annot_template_id)) {
1359 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1360 // store it in the pseudo-dtor node (to be used when instantiating it).
1361 FirstTypeName.setTemplateId(
1362 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1364 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1365 CCLoc = ConsumeToken();
1367 FirstTypeName.setIdentifier(0, SourceLocation());
1371 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1372 SourceLocation TildeLoc = ConsumeToken();
1374 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1375 DeclSpec DS(AttrFactory);
1376 ParseDecltypeSpecifier(DS);
1377 if (DS.getTypeSpecType() == TST_error)
1379 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1380 OpKind, TildeLoc, DS,
1381 Tok.is(tok::l_paren));
1384 if (!Tok.is(tok::identifier)) {
1385 Diag(Tok, diag::err_destructor_tilde_identifier);
1389 // Parse the second type.
1390 UnqualifiedId SecondTypeName;
1391 IdentifierInfo *Name = Tok.getIdentifierInfo();
1392 SourceLocation NameLoc = ConsumeToken();
1393 SecondTypeName.setIdentifier(Name, NameLoc);
1395 // If there is a '<', the second type name is a template-id. Parse
1397 if (Tok.is(tok::less) &&
1398 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1400 false, ObjectType, SecondTypeName,
1401 /*AssumeTemplateName=*/true))
1404 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1406 SS, FirstTypeName, CCLoc,
1407 TildeLoc, SecondTypeName,
1408 Tok.is(tok::l_paren));
1411 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1413 /// boolean-literal: [C++ 2.13.5]
1416 ExprResult Parser::ParseCXXBoolLiteral() {
1417 tok::TokenKind Kind = Tok.getKind();
1418 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1421 /// ParseThrowExpression - This handles the C++ throw expression.
1423 /// throw-expression: [C++ 15]
1424 /// 'throw' assignment-expression[opt]
1425 ExprResult Parser::ParseThrowExpression() {
1426 assert(Tok.is(tok::kw_throw) && "Not throw!");
1427 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1429 // If the current token isn't the start of an assignment-expression,
1430 // then the expression is not present. This handles things like:
1431 // "C ? throw : (void)42", which is crazy but legal.
1432 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1439 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
1442 ExprResult Expr(ParseAssignmentExpression());
1443 if (Expr.isInvalid()) return Expr;
1444 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
1448 /// ParseCXXThis - This handles the C++ 'this' pointer.
1450 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1451 /// a non-lvalue expression whose value is the address of the object for which
1452 /// the function is called.
1453 ExprResult Parser::ParseCXXThis() {
1454 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1455 SourceLocation ThisLoc = ConsumeToken();
1456 return Actions.ActOnCXXThis(ThisLoc);
1459 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1460 /// Can be interpreted either as function-style casting ("int(x)")
1461 /// or class type construction ("ClassType(x,y,z)")
1462 /// or creation of a value-initialized type ("int()").
1463 /// See [C++ 5.2.3].
1465 /// postfix-expression: [C++ 5.2p1]
1466 /// simple-type-specifier '(' expression-list[opt] ')'
1467 /// [C++0x] simple-type-specifier braced-init-list
1468 /// typename-specifier '(' expression-list[opt] ')'
1469 /// [C++0x] typename-specifier braced-init-list
1472 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1473 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1474 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1476 assert((Tok.is(tok::l_paren) ||
1477 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1478 && "Expected '(' or '{'!");
1480 if (Tok.is(tok::l_brace)) {
1481 ExprResult Init = ParseBraceInitializer();
1482 if (Init.isInvalid())
1484 Expr *InitList = Init.take();
1485 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1486 MultiExprArg(&InitList, 1),
1489 BalancedDelimiterTracker T(*this, tok::l_paren);
1493 CommaLocsTy CommaLocs;
1495 if (Tok.isNot(tok::r_paren)) {
1496 if (ParseExpressionList(Exprs, CommaLocs)) {
1497 SkipUntil(tok::r_paren, StopAtSemi);
1505 // TypeRep could be null, if it references an invalid typedef.
1509 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1510 "Unexpected number of commas!");
1511 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1513 T.getCloseLocation());
1517 /// ParseCXXCondition - if/switch/while condition expression.
1521 /// type-specifier-seq declarator '=' assignment-expression
1522 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1523 /// [C++11] type-specifier-seq declarator braced-init-list
1524 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1525 /// '=' assignment-expression
1527 /// \param ExprOut if the condition was parsed as an expression, the parsed
1530 /// \param DeclOut if the condition was parsed as a declaration, the parsed
1533 /// \param Loc The location of the start of the statement that requires this
1534 /// condition, e.g., the "for" in a for loop.
1536 /// \param ConvertToBoolean Whether the condition expression should be
1537 /// converted to a boolean value.
1539 /// \returns true if there was a parsing, false otherwise.
1540 bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1543 bool ConvertToBoolean) {
1544 if (Tok.is(tok::code_completion)) {
1545 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1550 ParsedAttributesWithRange attrs(AttrFactory);
1551 MaybeParseCXX11Attributes(attrs);
1553 if (!isCXXConditionDeclaration()) {
1554 ProhibitAttributes(attrs);
1556 // Parse the expression.
1557 ExprOut = ParseExpression(); // expression
1559 if (ExprOut.isInvalid())
1562 // If required, convert to a boolean value.
1563 if (ConvertToBoolean)
1565 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1566 return ExprOut.isInvalid();
1569 // type-specifier-seq
1570 DeclSpec DS(AttrFactory);
1571 DS.takeAttributesFrom(attrs);
1572 ParseSpecifierQualifierList(DS);
1575 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1576 ParseDeclarator(DeclaratorInfo);
1578 // simple-asm-expr[opt]
1579 if (Tok.is(tok::kw_asm)) {
1581 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1582 if (AsmLabel.isInvalid()) {
1583 SkipUntil(tok::semi, StopAtSemi);
1586 DeclaratorInfo.setAsmLabel(AsmLabel.release());
1587 DeclaratorInfo.SetRangeEnd(Loc);
1590 // If attributes are present, parse them.
1591 MaybeParseGNUAttributes(DeclaratorInfo);
1593 // Type-check the declaration itself.
1594 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1596 DeclOut = Dcl.get();
1597 ExprOut = ExprError();
1599 // '=' assignment-expression
1600 // If a '==' or '+=' is found, suggest a fixit to '='.
1601 bool CopyInitialization = isTokenEqualOrEqualTypo();
1602 if (CopyInitialization)
1605 ExprResult InitExpr = ExprError();
1606 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1607 Diag(Tok.getLocation(),
1608 diag::warn_cxx98_compat_generalized_initializer_lists);
1609 InitExpr = ParseBraceInitializer();
1610 } else if (CopyInitialization) {
1611 InitExpr = ParseAssignmentExpression();
1612 } else if (Tok.is(tok::l_paren)) {
1613 // This was probably an attempt to initialize the variable.
1614 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1615 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1616 RParen = ConsumeParen();
1617 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1618 diag::err_expected_init_in_condition_lparen)
1619 << SourceRange(LParen, RParen);
1621 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1622 diag::err_expected_init_in_condition);
1625 if (!InitExpr.isInvalid())
1626 Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization,
1627 DS.containsPlaceholderType());
1629 Actions.ActOnInitializerError(DeclOut);
1631 // FIXME: Build a reference to this declaration? Convert it to bool?
1632 // (This is currently handled by Sema).
1634 Actions.FinalizeDeclaration(DeclOut);
1639 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1640 /// This should only be called when the current token is known to be part of
1641 /// simple-type-specifier.
1643 /// simple-type-specifier:
1644 /// '::'[opt] nested-name-specifier[opt] type-name
1645 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1657 /// [GNU] typeof-specifier
1658 /// [C++0x] auto [TODO]
1665 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1666 DS.SetRangeStart(Tok.getLocation());
1667 const char *PrevSpec;
1669 SourceLocation Loc = Tok.getLocation();
1671 switch (Tok.getKind()) {
1672 case tok::identifier: // foo::bar
1673 case tok::coloncolon: // ::foo::bar
1674 llvm_unreachable("Annotation token should already be formed!");
1676 llvm_unreachable("Not a simple-type-specifier token!");
1679 case tok::annot_typename: {
1680 if (getTypeAnnotation(Tok))
1681 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1682 getTypeAnnotation(Tok));
1684 DS.SetTypeSpecError();
1686 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1689 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1690 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1691 // Objective-C interface. If we don't have Objective-C or a '<', this is
1692 // just a normal reference to a typedef name.
1693 if (Tok.is(tok::less) && getLangOpts().ObjC1)
1694 ParseObjCProtocolQualifiers(DS);
1696 DS.Finish(Diags, PP);
1702 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1705 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
1707 case tok::kw___int64:
1708 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1710 case tok::kw_signed:
1711 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1713 case tok::kw_unsigned:
1714 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1717 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1720 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1723 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1725 case tok::kw___int128:
1726 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID);
1729 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
1732 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1734 case tok::kw_double:
1735 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1737 case tok::kw_wchar_t:
1738 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1740 case tok::kw_char16_t:
1741 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1743 case tok::kw_char32_t:
1744 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1747 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1749 case tok::annot_decltype:
1750 case tok::kw_decltype:
1751 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1752 return DS.Finish(Diags, PP);
1754 // GNU typeof support.
1755 case tok::kw_typeof:
1756 ParseTypeofSpecifier(DS);
1757 DS.Finish(Diags, PP);
1760 if (Tok.is(tok::annot_typename))
1761 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1763 DS.SetRangeEnd(Tok.getLocation());
1765 DS.Finish(Diags, PP);
1768 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1769 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1770 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1771 /// by parsing the type-specifier-seq, because these sequences are
1772 /// typically followed by some form of declarator. Returns true and
1773 /// emits diagnostics if this is not a type-specifier-seq, false
1776 /// type-specifier-seq: [C++ 8.1]
1777 /// type-specifier type-specifier-seq[opt]
1779 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1780 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1781 DS.Finish(Diags, PP);
1785 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1788 /// This routine is invoked when a '<' is encountered after an identifier or
1789 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1790 /// whether the unqualified-id is actually a template-id. This routine will
1791 /// then parse the template arguments and form the appropriate template-id to
1792 /// return to the caller.
1794 /// \param SS the nested-name-specifier that precedes this template-id, if
1795 /// we're actually parsing a qualified-id.
1797 /// \param Name for constructor and destructor names, this is the actual
1798 /// identifier that may be a template-name.
1800 /// \param NameLoc the location of the class-name in a constructor or
1803 /// \param EnteringContext whether we're entering the scope of the
1804 /// nested-name-specifier.
1806 /// \param ObjectType if this unqualified-id occurs within a member access
1807 /// expression, the type of the base object whose member is being accessed.
1809 /// \param Id as input, describes the template-name or operator-function-id
1810 /// that precedes the '<'. If template arguments were parsed successfully,
1811 /// will be updated with the template-id.
1813 /// \param AssumeTemplateId When true, this routine will assume that the name
1814 /// refers to a template without performing name lookup to verify.
1816 /// \returns true if a parse error occurred, false otherwise.
1817 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1818 SourceLocation TemplateKWLoc,
1819 IdentifierInfo *Name,
1820 SourceLocation NameLoc,
1821 bool EnteringContext,
1822 ParsedType ObjectType,
1824 bool AssumeTemplateId) {
1825 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1826 "Expected '<' to finish parsing a template-id");
1828 TemplateTy Template;
1829 TemplateNameKind TNK = TNK_Non_template;
1830 switch (Id.getKind()) {
1831 case UnqualifiedId::IK_Identifier:
1832 case UnqualifiedId::IK_OperatorFunctionId:
1833 case UnqualifiedId::IK_LiteralOperatorId:
1834 if (AssumeTemplateId) {
1835 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
1836 Id, ObjectType, EnteringContext,
1838 if (TNK == TNK_Non_template)
1841 bool MemberOfUnknownSpecialization;
1842 TNK = Actions.isTemplateName(getCurScope(), SS,
1843 TemplateKWLoc.isValid(), Id,
1844 ObjectType, EnteringContext, Template,
1845 MemberOfUnknownSpecialization);
1847 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1848 ObjectType && IsTemplateArgumentList()) {
1849 // We have something like t->getAs<T>(), where getAs is a
1850 // member of an unknown specialization. However, this will only
1851 // parse correctly as a template, so suggest the keyword 'template'
1852 // before 'getAs' and treat this as a dependent template name.
1854 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1855 Name = Id.Identifier->getName();
1858 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1859 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1861 Name += Id.Identifier->getName();
1863 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1865 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1866 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1867 SS, TemplateKWLoc, Id,
1868 ObjectType, EnteringContext,
1870 if (TNK == TNK_Non_template)
1876 case UnqualifiedId::IK_ConstructorName: {
1877 UnqualifiedId TemplateName;
1878 bool MemberOfUnknownSpecialization;
1879 TemplateName.setIdentifier(Name, NameLoc);
1880 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1881 TemplateName, ObjectType,
1882 EnteringContext, Template,
1883 MemberOfUnknownSpecialization);
1887 case UnqualifiedId::IK_DestructorName: {
1888 UnqualifiedId TemplateName;
1889 bool MemberOfUnknownSpecialization;
1890 TemplateName.setIdentifier(Name, NameLoc);
1892 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1893 SS, TemplateKWLoc, TemplateName,
1894 ObjectType, EnteringContext,
1896 if (TNK == TNK_Non_template)
1899 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1900 TemplateName, ObjectType,
1901 EnteringContext, Template,
1902 MemberOfUnknownSpecialization);
1904 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
1905 Diag(NameLoc, diag::err_destructor_template_id)
1906 << Name << SS.getRange();
1917 if (TNK == TNK_Non_template)
1920 // Parse the enclosed template argument list.
1921 SourceLocation LAngleLoc, RAngleLoc;
1922 TemplateArgList TemplateArgs;
1923 if (Tok.is(tok::less) &&
1924 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
1925 SS, true, LAngleLoc,
1930 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
1931 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1932 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
1933 // Form a parsed representation of the template-id to be stored in the
1935 TemplateIdAnnotation *TemplateId
1936 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1938 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1939 TemplateId->Name = Id.Identifier;
1940 TemplateId->Operator = OO_None;
1941 TemplateId->TemplateNameLoc = Id.StartLocation;
1943 TemplateId->Name = 0;
1944 TemplateId->Operator = Id.OperatorFunctionId.Operator;
1945 TemplateId->TemplateNameLoc = Id.StartLocation;
1948 TemplateId->SS = SS;
1949 TemplateId->TemplateKWLoc = TemplateKWLoc;
1950 TemplateId->Template = Template;
1951 TemplateId->Kind = TNK;
1952 TemplateId->LAngleLoc = LAngleLoc;
1953 TemplateId->RAngleLoc = RAngleLoc;
1954 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1955 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
1956 Arg != ArgEnd; ++Arg)
1957 Args[Arg] = TemplateArgs[Arg];
1959 Id.setTemplateId(TemplateId);
1963 // Bundle the template arguments together.
1964 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1966 // Constructor and destructor names.
1968 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1970 LAngleLoc, TemplateArgsPtr, RAngleLoc,
1971 /*IsCtorOrDtorName=*/true);
1972 if (Type.isInvalid())
1975 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1976 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1978 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1983 /// \brief Parse an operator-function-id or conversion-function-id as part
1984 /// of a C++ unqualified-id.
1986 /// This routine is responsible only for parsing the operator-function-id or
1987 /// conversion-function-id; it does not handle template arguments in any way.
1990 /// operator-function-id: [C++ 13.5]
1991 /// 'operator' operator
1993 /// operator: one of
1994 /// new delete new[] delete[]
1995 /// + - * / % ^ & | ~
1996 /// ! = < > += -= *= /= %=
1997 /// ^= &= |= << >> >>= <<= == !=
1998 /// <= >= && || ++ -- , ->* ->
2001 /// conversion-function-id: [C++ 12.3.2]
2002 /// operator conversion-type-id
2004 /// conversion-type-id:
2005 /// type-specifier-seq conversion-declarator[opt]
2007 /// conversion-declarator:
2008 /// ptr-operator conversion-declarator[opt]
2011 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2012 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2014 /// \param EnteringContext whether we are entering the scope of the
2015 /// nested-name-specifier.
2017 /// \param ObjectType if this unqualified-id occurs within a member access
2018 /// expression, the type of the base object whose member is being accessed.
2020 /// \param Result on a successful parse, contains the parsed unqualified-id.
2022 /// \returns true if parsing fails, false otherwise.
2023 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2024 ParsedType ObjectType,
2025 UnqualifiedId &Result) {
2026 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2028 // Consume the 'operator' keyword.
2029 SourceLocation KeywordLoc = ConsumeToken();
2031 // Determine what kind of operator name we have.
2032 unsigned SymbolIdx = 0;
2033 SourceLocation SymbolLocations[3];
2034 OverloadedOperatorKind Op = OO_None;
2035 switch (Tok.getKind()) {
2037 case tok::kw_delete: {
2038 bool isNew = Tok.getKind() == tok::kw_new;
2039 // Consume the 'new' or 'delete'.
2040 SymbolLocations[SymbolIdx++] = ConsumeToken();
2041 // Check for array new/delete.
2042 if (Tok.is(tok::l_square) &&
2043 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2044 // Consume the '[' and ']'.
2045 BalancedDelimiterTracker T(*this, tok::l_square);
2048 if (T.getCloseLocation().isInvalid())
2051 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2052 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2053 Op = isNew? OO_Array_New : OO_Array_Delete;
2055 Op = isNew? OO_New : OO_Delete;
2060 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2062 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2065 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2066 #include "clang/Basic/OperatorKinds.def"
2068 case tok::l_paren: {
2069 // Consume the '(' and ')'.
2070 BalancedDelimiterTracker T(*this, tok::l_paren);
2073 if (T.getCloseLocation().isInvalid())
2076 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2077 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2082 case tok::l_square: {
2083 // Consume the '[' and ']'.
2084 BalancedDelimiterTracker T(*this, tok::l_square);
2087 if (T.getCloseLocation().isInvalid())
2090 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2091 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2096 case tok::code_completion: {
2097 // Code completion for the operator name.
2098 Actions.CodeCompleteOperatorName(getCurScope());
2100 // Don't try to parse any further.
2108 if (Op != OO_None) {
2109 // We have parsed an operator-function-id.
2110 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2114 // Parse a literal-operator-id.
2116 // literal-operator-id: C++11 [over.literal]
2117 // operator string-literal identifier
2118 // operator user-defined-string-literal
2120 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2121 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2123 SourceLocation DiagLoc;
2124 unsigned DiagId = 0;
2126 // We're past translation phase 6, so perform string literal concatenation
2127 // before checking for "".
2128 SmallVector<Token, 4> Toks;
2129 SmallVector<SourceLocation, 4> TokLocs;
2130 while (isTokenStringLiteral()) {
2131 if (!Tok.is(tok::string_literal) && !DiagId) {
2132 // C++11 [over.literal]p1:
2133 // The string-literal or user-defined-string-literal in a
2134 // literal-operator-id shall have no encoding-prefix [...].
2135 DiagLoc = Tok.getLocation();
2136 DiagId = diag::err_literal_operator_string_prefix;
2138 Toks.push_back(Tok);
2139 TokLocs.push_back(ConsumeStringToken());
2142 StringLiteralParser Literal(Toks.data(), Toks.size(), PP);
2143 if (Literal.hadError)
2146 // Grab the literal operator's suffix, which will be either the next token
2147 // or a ud-suffix from the string literal.
2148 IdentifierInfo *II = 0;
2149 SourceLocation SuffixLoc;
2150 if (!Literal.getUDSuffix().empty()) {
2151 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2153 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2154 Literal.getUDSuffixOffset(),
2155 PP.getSourceManager(), getLangOpts());
2156 } else if (Tok.is(tok::identifier)) {
2157 II = Tok.getIdentifierInfo();
2158 SuffixLoc = ConsumeToken();
2159 TokLocs.push_back(SuffixLoc);
2161 Diag(Tok.getLocation(), diag::err_expected_ident);
2165 // The string literal must be empty.
2166 if (!Literal.GetString().empty() || Literal.Pascal) {
2167 // C++11 [over.literal]p1:
2168 // The string-literal or user-defined-string-literal in a
2169 // literal-operator-id shall [...] contain no characters
2170 // other than the implicit terminating '\0'.
2171 DiagLoc = TokLocs.front();
2172 DiagId = diag::err_literal_operator_string_not_empty;
2176 // This isn't a valid literal-operator-id, but we think we know
2177 // what the user meant. Tell them what they should have written.
2178 SmallString<32> Str;
2180 Str += II->getName();
2181 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2182 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2185 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2189 // Parse a conversion-function-id.
2191 // conversion-function-id: [C++ 12.3.2]
2192 // operator conversion-type-id
2194 // conversion-type-id:
2195 // type-specifier-seq conversion-declarator[opt]
2197 // conversion-declarator:
2198 // ptr-operator conversion-declarator[opt]
2200 // Parse the type-specifier-seq.
2201 DeclSpec DS(AttrFactory);
2202 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2205 // Parse the conversion-declarator, which is merely a sequence of
2207 Declarator D(DS, Declarator::ConversionIdContext);
2208 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
2210 // Finish up the type.
2211 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2215 // Note that this is a conversion-function-id.
2216 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2217 D.getSourceRange().getEnd());
2221 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2222 /// name of an entity.
2225 /// unqualified-id: [C++ expr.prim.general]
2227 /// operator-function-id
2228 /// conversion-function-id
2229 /// [C++0x] literal-operator-id [TODO]
2235 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2236 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2238 /// \param EnteringContext whether we are entering the scope of the
2239 /// nested-name-specifier.
2241 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2243 /// \param AllowConstructorName whether we allow parsing a constructor name.
2245 /// \param ObjectType if this unqualified-id occurs within a member access
2246 /// expression, the type of the base object whose member is being accessed.
2248 /// \param Result on a successful parse, contains the parsed unqualified-id.
2250 /// \returns true if parsing fails, false otherwise.
2251 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2252 bool AllowDestructorName,
2253 bool AllowConstructorName,
2254 ParsedType ObjectType,
2255 SourceLocation& TemplateKWLoc,
2256 UnqualifiedId &Result) {
2258 // Handle 'A::template B'. This is for template-ids which have not
2259 // already been annotated by ParseOptionalCXXScopeSpecifier().
2260 bool TemplateSpecified = false;
2261 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2262 (ObjectType || SS.isSet())) {
2263 TemplateSpecified = true;
2264 TemplateKWLoc = ConsumeToken();
2269 // template-id (when it hasn't already been annotated)
2270 if (Tok.is(tok::identifier)) {
2271 // Consume the identifier.
2272 IdentifierInfo *Id = Tok.getIdentifierInfo();
2273 SourceLocation IdLoc = ConsumeToken();
2275 if (!getLangOpts().CPlusPlus) {
2276 // If we're not in C++, only identifiers matter. Record the
2277 // identifier and return.
2278 Result.setIdentifier(Id, IdLoc);
2282 if (AllowConstructorName &&
2283 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2284 // We have parsed a constructor name.
2285 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2288 /*IsCtorOrDtorName=*/true,
2289 /*NonTrivialTypeSourceInfo=*/true);
2290 Result.setConstructorName(Ty, IdLoc, IdLoc);
2292 // We have parsed an identifier.
2293 Result.setIdentifier(Id, IdLoc);
2296 // If the next token is a '<', we may have a template.
2297 if (TemplateSpecified || Tok.is(tok::less))
2298 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2299 EnteringContext, ObjectType,
2300 Result, TemplateSpecified);
2306 // template-id (already parsed and annotated)
2307 if (Tok.is(tok::annot_template_id)) {
2308 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2310 // If the template-name names the current class, then this is a constructor
2311 if (AllowConstructorName && TemplateId->Name &&
2312 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2314 // C++ [class.qual]p2 specifies that a qualified template-name
2315 // is taken as the constructor name where a constructor can be
2316 // declared. Thus, the template arguments are extraneous, so
2317 // complain about them and remove them entirely.
2318 Diag(TemplateId->TemplateNameLoc,
2319 diag::err_out_of_line_constructor_template_id)
2321 << FixItHint::CreateRemoval(
2322 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2323 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2324 TemplateId->TemplateNameLoc,
2328 /*IsCtorOrDtorName=*/true,
2329 /*NontrivialTypeSourceInfo=*/true);
2330 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2331 TemplateId->RAngleLoc);
2336 Result.setConstructorTemplateId(TemplateId);
2341 // We have already parsed a template-id; consume the annotation token as
2342 // our unqualified-id.
2343 Result.setTemplateId(TemplateId);
2344 TemplateKWLoc = TemplateId->TemplateKWLoc;
2350 // operator-function-id
2351 // conversion-function-id
2352 if (Tok.is(tok::kw_operator)) {
2353 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2356 // If we have an operator-function-id or a literal-operator-id and the next
2357 // token is a '<', we may have a
2360 // operator-function-id < template-argument-list[opt] >
2361 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2362 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2363 (TemplateSpecified || Tok.is(tok::less)))
2364 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2365 0, SourceLocation(),
2366 EnteringContext, ObjectType,
2367 Result, TemplateSpecified);
2372 if (getLangOpts().CPlusPlus &&
2373 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2374 // C++ [expr.unary.op]p10:
2375 // There is an ambiguity in the unary-expression ~X(), where X is a
2376 // class-name. The ambiguity is resolved in favor of treating ~ as a
2377 // unary complement rather than treating ~X as referring to a destructor.
2380 SourceLocation TildeLoc = ConsumeToken();
2382 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2383 DeclSpec DS(AttrFactory);
2384 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2385 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2386 Result.setDestructorName(TildeLoc, Type, EndLoc);
2392 // Parse the class-name.
2393 if (Tok.isNot(tok::identifier)) {
2394 Diag(Tok, diag::err_destructor_tilde_identifier);
2398 // Parse the class-name (or template-name in a simple-template-id).
2399 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2400 SourceLocation ClassNameLoc = ConsumeToken();
2402 if (TemplateSpecified || Tok.is(tok::less)) {
2403 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
2404 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2405 ClassName, ClassNameLoc,
2406 EnteringContext, ObjectType,
2407 Result, TemplateSpecified);
2410 // Note that this is a destructor name.
2411 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2412 ClassNameLoc, getCurScope(),
2418 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2422 Diag(Tok, diag::err_expected_unqualified_id)
2423 << getLangOpts().CPlusPlus;
2427 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2428 /// memory in a typesafe manner and call constructors.
2430 /// This method is called to parse the new expression after the optional :: has
2431 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2432 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2435 /// '::'[opt] 'new' new-placement[opt] new-type-id
2436 /// new-initializer[opt]
2437 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2438 /// new-initializer[opt]
2441 /// '(' expression-list ')'
2444 /// type-specifier-seq new-declarator[opt]
2445 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2448 /// ptr-operator new-declarator[opt]
2449 /// direct-new-declarator
2451 /// new-initializer:
2452 /// '(' expression-list[opt] ')'
2453 /// [C++0x] braced-init-list
2456 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2457 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2458 ConsumeToken(); // Consume 'new'
2460 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2461 // second form of new-expression. It can't be a new-type-id.
2463 ExprVector PlacementArgs;
2464 SourceLocation PlacementLParen, PlacementRParen;
2466 SourceRange TypeIdParens;
2467 DeclSpec DS(AttrFactory);
2468 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2469 if (Tok.is(tok::l_paren)) {
2470 // If it turns out to be a placement, we change the type location.
2471 BalancedDelimiterTracker T(*this, tok::l_paren);
2473 PlacementLParen = T.getOpenLocation();
2474 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2475 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2480 PlacementRParen = T.getCloseLocation();
2481 if (PlacementRParen.isInvalid()) {
2482 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2486 if (PlacementArgs.empty()) {
2487 // Reset the placement locations. There was no placement.
2488 TypeIdParens = T.getRange();
2489 PlacementLParen = PlacementRParen = SourceLocation();
2491 // We still need the type.
2492 if (Tok.is(tok::l_paren)) {
2493 BalancedDelimiterTracker T(*this, tok::l_paren);
2495 MaybeParseGNUAttributes(DeclaratorInfo);
2496 ParseSpecifierQualifierList(DS);
2497 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2498 ParseDeclarator(DeclaratorInfo);
2500 TypeIdParens = T.getRange();
2502 MaybeParseGNUAttributes(DeclaratorInfo);
2503 if (ParseCXXTypeSpecifierSeq(DS))
2504 DeclaratorInfo.setInvalidType(true);
2506 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2507 ParseDeclaratorInternal(DeclaratorInfo,
2508 &Parser::ParseDirectNewDeclarator);
2513 // A new-type-id is a simplified type-id, where essentially the
2514 // direct-declarator is replaced by a direct-new-declarator.
2515 MaybeParseGNUAttributes(DeclaratorInfo);
2516 if (ParseCXXTypeSpecifierSeq(DS))
2517 DeclaratorInfo.setInvalidType(true);
2519 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2520 ParseDeclaratorInternal(DeclaratorInfo,
2521 &Parser::ParseDirectNewDeclarator);
2524 if (DeclaratorInfo.isInvalidType()) {
2525 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2529 ExprResult Initializer;
2531 if (Tok.is(tok::l_paren)) {
2532 SourceLocation ConstructorLParen, ConstructorRParen;
2533 ExprVector ConstructorArgs;
2534 BalancedDelimiterTracker T(*this, tok::l_paren);
2536 ConstructorLParen = T.getOpenLocation();
2537 if (Tok.isNot(tok::r_paren)) {
2538 CommaLocsTy CommaLocs;
2539 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2540 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2545 ConstructorRParen = T.getCloseLocation();
2546 if (ConstructorRParen.isInvalid()) {
2547 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2550 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2553 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2554 Diag(Tok.getLocation(),
2555 diag::warn_cxx98_compat_generalized_initializer_lists);
2556 Initializer = ParseBraceInitializer();
2558 if (Initializer.isInvalid())
2561 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2562 PlacementArgs, PlacementRParen,
2563 TypeIdParens, DeclaratorInfo, Initializer.take());
2566 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2567 /// passed to ParseDeclaratorInternal.
2569 /// direct-new-declarator:
2570 /// '[' expression ']'
2571 /// direct-new-declarator '[' constant-expression ']'
2573 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2574 // Parse the array dimensions.
2576 while (Tok.is(tok::l_square)) {
2577 // An array-size expression can't start with a lambda.
2578 if (CheckProhibitedCXX11Attribute())
2581 BalancedDelimiterTracker T(*this, tok::l_square);
2584 ExprResult Size(first ? ParseExpression()
2585 : ParseConstantExpression());
2586 if (Size.isInvalid()) {
2588 SkipUntil(tok::r_square, StopAtSemi);
2595 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2596 ParsedAttributes Attrs(AttrFactory);
2597 MaybeParseCXX11Attributes(Attrs);
2599 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2600 /*static=*/false, /*star=*/false,
2602 T.getOpenLocation(),
2603 T.getCloseLocation()),
2604 Attrs, T.getCloseLocation());
2606 if (T.getCloseLocation().isInvalid())
2611 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2612 /// This ambiguity appears in the syntax of the C++ new operator.
2615 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2616 /// new-initializer[opt]
2619 /// '(' expression-list ')'
2621 bool Parser::ParseExpressionListOrTypeId(
2622 SmallVectorImpl<Expr*> &PlacementArgs,
2624 // The '(' was already consumed.
2625 if (isTypeIdInParens()) {
2626 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2627 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2629 return D.isInvalidType();
2632 // It's not a type, it has to be an expression list.
2633 // Discard the comma locations - ActOnCXXNew has enough parameters.
2634 CommaLocsTy CommaLocs;
2635 return ParseExpressionList(PlacementArgs, CommaLocs);
2638 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2639 /// to free memory allocated by new.
2641 /// This method is called to parse the 'delete' expression after the optional
2642 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2643 /// and "Start" is its location. Otherwise, "Start" is the location of the
2646 /// delete-expression:
2647 /// '::'[opt] 'delete' cast-expression
2648 /// '::'[opt] 'delete' '[' ']' cast-expression
2650 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2651 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2652 ConsumeToken(); // Consume 'delete'
2655 bool ArrayDelete = false;
2656 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2657 // C++11 [expr.delete]p1:
2658 // Whenever the delete keyword is followed by empty square brackets, it
2659 // shall be interpreted as [array delete].
2660 // [Footnote: A lambda expression with a lambda-introducer that consists
2661 // of empty square brackets can follow the delete keyword if
2662 // the lambda expression is enclosed in parentheses.]
2663 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2664 // lambda-introducer.
2666 BalancedDelimiterTracker T(*this, tok::l_square);
2670 if (T.getCloseLocation().isInvalid())
2674 ExprResult Operand(ParseCastExpression(false));
2675 if (Operand.isInvalid())
2678 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
2681 static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
2683 default: llvm_unreachable("Not a known unary type trait.");
2684 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign;
2685 case tok::kw___has_nothrow_move_assign: return UTT_HasNothrowMoveAssign;
2686 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
2687 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy;
2688 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign;
2689 case tok::kw___has_trivial_move_assign: return UTT_HasTrivialMoveAssign;
2690 case tok::kw___has_trivial_constructor:
2691 return UTT_HasTrivialDefaultConstructor;
2692 case tok::kw___has_trivial_move_constructor:
2693 return UTT_HasTrivialMoveConstructor;
2694 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy;
2695 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor;
2696 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor;
2697 case tok::kw___is_abstract: return UTT_IsAbstract;
2698 case tok::kw___is_arithmetic: return UTT_IsArithmetic;
2699 case tok::kw___is_array: return UTT_IsArray;
2700 case tok::kw___is_class: return UTT_IsClass;
2701 case tok::kw___is_complete_type: return UTT_IsCompleteType;
2702 case tok::kw___is_compound: return UTT_IsCompound;
2703 case tok::kw___is_const: return UTT_IsConst;
2704 case tok::kw___is_empty: return UTT_IsEmpty;
2705 case tok::kw___is_enum: return UTT_IsEnum;
2706 case tok::kw___is_final: return UTT_IsFinal;
2707 case tok::kw___is_floating_point: return UTT_IsFloatingPoint;
2708 case tok::kw___is_function: return UTT_IsFunction;
2709 case tok::kw___is_fundamental: return UTT_IsFundamental;
2710 case tok::kw___is_integral: return UTT_IsIntegral;
2711 case tok::kw___is_interface_class: return UTT_IsInterfaceClass;
2712 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference;
2713 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer;
2714 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer;
2715 case tok::kw___is_member_pointer: return UTT_IsMemberPointer;
2716 case tok::kw___is_object: return UTT_IsObject;
2717 case tok::kw___is_literal: return UTT_IsLiteral;
2718 case tok::kw___is_literal_type: return UTT_IsLiteral;
2719 case tok::kw___is_pod: return UTT_IsPOD;
2720 case tok::kw___is_pointer: return UTT_IsPointer;
2721 case tok::kw___is_polymorphic: return UTT_IsPolymorphic;
2722 case tok::kw___is_reference: return UTT_IsReference;
2723 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference;
2724 case tok::kw___is_scalar: return UTT_IsScalar;
2725 case tok::kw___is_sealed: return UTT_IsSealed;
2726 case tok::kw___is_signed: return UTT_IsSigned;
2727 case tok::kw___is_standard_layout: return UTT_IsStandardLayout;
2728 case tok::kw___is_trivial: return UTT_IsTrivial;
2729 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable;
2730 case tok::kw___is_union: return UTT_IsUnion;
2731 case tok::kw___is_unsigned: return UTT_IsUnsigned;
2732 case tok::kw___is_void: return UTT_IsVoid;
2733 case tok::kw___is_volatile: return UTT_IsVolatile;
2737 static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) {
2739 default: llvm_unreachable("Not a known binary type trait");
2740 case tok::kw___is_base_of: return BTT_IsBaseOf;
2741 case tok::kw___is_convertible: return BTT_IsConvertible;
2742 case tok::kw___is_same: return BTT_IsSame;
2743 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible;
2744 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo;
2745 case tok::kw___is_trivially_assignable: return BTT_IsTriviallyAssignable;
2749 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2751 default: llvm_unreachable("Not a known type trait");
2752 case tok::kw___is_trivially_constructible:
2753 return TT_IsTriviallyConstructible;
2757 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2759 default: llvm_unreachable("Not a known binary type trait");
2760 case tok::kw___array_rank: return ATT_ArrayRank;
2761 case tok::kw___array_extent: return ATT_ArrayExtent;
2765 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2767 default: llvm_unreachable("Not a known unary expression trait.");
2768 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2769 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2773 /// ParseUnaryTypeTrait - Parse the built-in unary type-trait
2774 /// pseudo-functions that allow implementation of the TR1/C++0x type traits
2777 /// primary-expression:
2778 /// [GNU] unary-type-trait '(' type-id ')'
2780 ExprResult Parser::ParseUnaryTypeTrait() {
2781 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
2782 SourceLocation Loc = ConsumeToken();
2784 BalancedDelimiterTracker T(*this, tok::l_paren);
2785 if (T.expectAndConsume(diag::err_expected_lparen))
2788 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
2789 // there will be cryptic errors about mismatched parentheses and missing
2791 TypeResult Ty = ParseTypeName();
2798 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), T.getCloseLocation());
2801 /// ParseBinaryTypeTrait - Parse the built-in binary type-trait
2802 /// pseudo-functions that allow implementation of the TR1/C++0x type traits
2805 /// primary-expression:
2806 /// [GNU] binary-type-trait '(' type-id ',' type-id ')'
2808 ExprResult Parser::ParseBinaryTypeTrait() {
2809 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind());
2810 SourceLocation Loc = ConsumeToken();
2812 BalancedDelimiterTracker T(*this, tok::l_paren);
2813 if (T.expectAndConsume(diag::err_expected_lparen))
2816 TypeResult LhsTy = ParseTypeName();
2817 if (LhsTy.isInvalid()) {
2818 SkipUntil(tok::r_paren, StopAtSemi);
2822 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2823 SkipUntil(tok::r_paren, StopAtSemi);
2827 TypeResult RhsTy = ParseTypeName();
2828 if (RhsTy.isInvalid()) {
2829 SkipUntil(tok::r_paren, StopAtSemi);
2835 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(),
2836 T.getCloseLocation());
2839 /// \brief Parse the built-in type-trait pseudo-functions that allow
2840 /// implementation of the TR1/C++11 type traits templates.
2842 /// primary-expression:
2843 /// type-trait '(' type-id-seq ')'
2846 /// type-id ...[opt] type-id-seq[opt]
2848 ExprResult Parser::ParseTypeTrait() {
2849 TypeTrait Kind = TypeTraitFromTokKind(Tok.getKind());
2850 SourceLocation Loc = ConsumeToken();
2852 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2853 if (Parens.expectAndConsume(diag::err_expected_lparen))
2856 SmallVector<ParsedType, 2> Args;
2858 // Parse the next type.
2859 TypeResult Ty = ParseTypeName();
2860 if (Ty.isInvalid()) {
2865 // Parse the ellipsis, if present.
2866 if (Tok.is(tok::ellipsis)) {
2867 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2868 if (Ty.isInvalid()) {
2874 // Add this type to the list of arguments.
2875 Args.push_back(Ty.get());
2877 if (Tok.is(tok::comma)) {
2885 if (Parens.consumeClose())
2888 return Actions.ActOnTypeTrait(Kind, Loc, Args, Parens.getCloseLocation());
2891 /// ParseArrayTypeTrait - Parse the built-in array type-trait
2892 /// pseudo-functions.
2894 /// primary-expression:
2895 /// [Embarcadero] '__array_rank' '(' type-id ')'
2896 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2898 ExprResult Parser::ParseArrayTypeTrait() {
2899 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2900 SourceLocation Loc = ConsumeToken();
2902 BalancedDelimiterTracker T(*this, tok::l_paren);
2903 if (T.expectAndConsume(diag::err_expected_lparen))
2906 TypeResult Ty = ParseTypeName();
2907 if (Ty.isInvalid()) {
2908 SkipUntil(tok::comma, StopAtSemi);
2909 SkipUntil(tok::r_paren, StopAtSemi);
2914 case ATT_ArrayRank: {
2916 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL,
2917 T.getCloseLocation());
2919 case ATT_ArrayExtent: {
2920 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2921 SkipUntil(tok::r_paren, StopAtSemi);
2925 ExprResult DimExpr = ParseExpression();
2928 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2929 T.getCloseLocation());
2932 llvm_unreachable("Invalid ArrayTypeTrait!");
2935 /// ParseExpressionTrait - Parse built-in expression-trait
2936 /// pseudo-functions like __is_lvalue_expr( xxx ).
2938 /// primary-expression:
2939 /// [Embarcadero] expression-trait '(' expression ')'
2941 ExprResult Parser::ParseExpressionTrait() {
2942 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2943 SourceLocation Loc = ConsumeToken();
2945 BalancedDelimiterTracker T(*this, tok::l_paren);
2946 if (T.expectAndConsume(diag::err_expected_lparen))
2949 ExprResult Expr = ParseExpression();
2953 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2954 T.getCloseLocation());
2958 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2959 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2960 /// based on the context past the parens.
2962 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
2964 BalancedDelimiterTracker &Tracker) {
2965 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
2966 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2967 assert(isTypeIdInParens() && "Not a type-id!");
2969 ExprResult Result(true);
2970 CastTy = ParsedType();
2972 // We need to disambiguate a very ugly part of the C++ syntax:
2974 // (T())x; - type-id
2975 // (T())*x; - type-id
2976 // (T())/x; - expression
2977 // (T()); - expression
2979 // The bad news is that we cannot use the specialized tentative parser, since
2980 // it can only verify that the thing inside the parens can be parsed as
2981 // type-id, it is not useful for determining the context past the parens.
2983 // The good news is that the parser can disambiguate this part without
2984 // making any unnecessary Action calls.
2986 // It uses a scheme similar to parsing inline methods. The parenthesized
2987 // tokens are cached, the context that follows is determined (possibly by
2988 // parsing a cast-expression), and then we re-introduce the cached tokens
2989 // into the token stream and parse them appropriately.
2991 ParenParseOption ParseAs;
2994 // Store the tokens of the parentheses. We will parse them after we determine
2995 // the context that follows them.
2996 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
2997 // We didn't find the ')' we expected.
2998 Tracker.consumeClose();
3002 if (Tok.is(tok::l_brace)) {
3003 ParseAs = CompoundLiteral;
3006 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
3007 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3010 // Try parsing the cast-expression that may follow.
3011 // If it is not a cast-expression, NotCastExpr will be true and no token
3012 // will be consumed.
3013 Result = ParseCastExpression(false/*isUnaryExpression*/,
3014 false/*isAddressofOperand*/,
3016 // type-id has priority.
3020 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3022 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3025 // The current token should go after the cached tokens.
3026 Toks.push_back(Tok);
3027 // Re-enter the stored parenthesized tokens into the token stream, so we may
3029 PP.EnterTokenStream(Toks.data(), Toks.size(),
3030 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
3031 // Drop the current token and bring the first cached one. It's the same token
3032 // as when we entered this function.
3035 if (ParseAs >= CompoundLiteral) {
3036 // Parse the type declarator.
3037 DeclSpec DS(AttrFactory);
3038 ParseSpecifierQualifierList(DS);
3039 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
3040 ParseDeclarator(DeclaratorInfo);
3043 Tracker.consumeClose();
3045 if (ParseAs == CompoundLiteral) {
3046 ExprType = CompoundLiteral;
3047 TypeResult Ty = ParseTypeName();
3048 return ParseCompoundLiteralExpression(Ty.get(),
3049 Tracker.getOpenLocation(),
3050 Tracker.getCloseLocation());
3053 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3054 assert(ParseAs == CastExpr);
3056 if (DeclaratorInfo.isInvalidType())
3059 // Result is what ParseCastExpression returned earlier.
3060 if (!Result.isInvalid())
3061 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3062 DeclaratorInfo, CastTy,
3063 Tracker.getCloseLocation(), Result.take());
3067 // Not a compound literal, and not followed by a cast-expression.
3068 assert(ParseAs == SimpleExpr);
3070 ExprType = SimpleExpr;
3071 Result = ParseExpression();
3072 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3073 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3074 Tok.getLocation(), Result.take());
3077 if (Result.isInvalid()) {
3078 SkipUntil(tok::r_paren, StopAtSemi);
3082 Tracker.consumeClose();