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/ASTContext.h"
14 #include "RAIIObjectsForParser.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/Basic/PrettyStackTrace.h"
17 #include "clang/Lex/LiteralSupport.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Parse/Parser.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/ParsedTemplate.h"
22 #include "clang/Sema/Scope.h"
23 #include "llvm/Support/ErrorHandling.h"
26 using namespace clang;
28 static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
31 case tok::unknown: return 0;
33 case tok::kw_const_cast: return 1;
34 case tok::kw_dynamic_cast: return 2;
35 case tok::kw_reinterpret_cast: return 3;
36 case tok::kw_static_cast: return 4;
38 llvm_unreachable("Unknown type for digraph error message.");
42 // Are the two tokens adjacent in the same source file?
43 bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
44 SourceManager &SM = PP.getSourceManager();
45 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
46 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
47 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
50 // Suggest fixit for "<::" after a cast.
51 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
52 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
53 // Pull '<:' and ':' off token stream.
59 Range.setBegin(DigraphToken.getLocation());
60 Range.setEnd(ColonToken.getLocation());
61 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
62 << SelectDigraphErrorMessage(Kind)
63 << FixItHint::CreateReplacement(Range, "< ::");
65 // Update token information to reflect their change in token type.
66 ColonToken.setKind(tok::coloncolon);
67 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
68 ColonToken.setLength(2);
69 DigraphToken.setKind(tok::less);
70 DigraphToken.setLength(1);
72 // Push new tokens back to token stream.
73 PP.EnterToken(ColonToken);
75 PP.EnterToken(DigraphToken);
78 // Check for '<::' which should be '< ::' instead of '[:' when following
80 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
82 IdentifierInfo &II, CXXScopeSpec &SS) {
83 if (!Next.is(tok::l_square) || Next.getLength() != 2)
86 Token SecondToken = GetLookAheadToken(2);
87 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
91 UnqualifiedId TemplateName;
92 TemplateName.setIdentifier(&II, Tok.getLocation());
93 bool MemberOfUnknownSpecialization;
94 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
95 TemplateName, ObjectType, EnteringContext,
96 Template, MemberOfUnknownSpecialization))
99 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
103 /// \brief Emits an error for a left parentheses after a double colon.
105 /// When a '(' is found after a '::', emit an error. Attempt to fix the token
106 /// stream by removing the '(', and the matching ')' if found.
107 void Parser::CheckForLParenAfterColonColon() {
108 if (!Tok.is(tok::l_paren))
111 SourceLocation l_parenLoc = ConsumeParen(), r_parenLoc;
112 Token Tok1 = getCurToken();
113 if (!Tok1.is(tok::identifier) && !Tok1.is(tok::star))
116 if (Tok1.is(tok::identifier)) {
117 Token Tok2 = GetLookAheadToken(1);
118 if (Tok2.is(tok::r_paren)) {
121 r_parenLoc = ConsumeParen();
123 } else if (Tok1.is(tok::star)) {
124 Token Tok2 = GetLookAheadToken(1);
125 if (Tok2.is(tok::identifier)) {
126 Token Tok3 = GetLookAheadToken(2);
127 if (Tok3.is(tok::r_paren)) {
132 r_parenLoc = ConsumeParen();
137 Diag(l_parenLoc, diag::err_paren_after_colon_colon)
138 << FixItHint::CreateRemoval(l_parenLoc)
139 << FixItHint::CreateRemoval(r_parenLoc);
142 /// \brief Parse global scope or nested-name-specifier if present.
144 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
145 /// may be preceded by '::'). Note that this routine will not parse ::new or
146 /// ::delete; it will just leave them in the token stream.
148 /// '::'[opt] nested-name-specifier
151 /// nested-name-specifier:
153 /// namespace-name '::'
154 /// nested-name-specifier identifier '::'
155 /// nested-name-specifier 'template'[opt] simple-template-id '::'
158 /// \param SS the scope specifier that will be set to the parsed
159 /// nested-name-specifier (or empty)
161 /// \param ObjectType if this nested-name-specifier is being parsed following
162 /// the "." or "->" of a member access expression, this parameter provides the
163 /// type of the object whose members are being accessed.
165 /// \param EnteringContext whether we will be entering into the context of
166 /// the nested-name-specifier after parsing it.
168 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
169 /// indicates whether this nested-name-specifier may be part of a
170 /// pseudo-destructor name. In this case, the flag will be set false
171 /// if we don't actually end up parsing a destructor name. Moreorover,
172 /// if we do end up determining that we are parsing a destructor name,
173 /// the last component of the nested-name-specifier is not parsed as
174 /// part of the scope specifier.
176 /// \param IsTypename If \c true, this nested-name-specifier is known to be
177 /// part of a type name. This is used to improve error recovery.
179 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
180 /// filled in with the leading identifier in the last component of the
181 /// nested-name-specifier, if any.
183 /// \returns true if there was an error parsing a scope specifier
184 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
185 ParsedType ObjectType,
186 bool EnteringContext,
187 bool *MayBePseudoDestructor,
189 IdentifierInfo **LastII) {
190 assert(getLangOpts().CPlusPlus &&
191 "Call sites of this function should be guarded by checking for C++");
193 if (Tok.is(tok::annot_cxxscope)) {
194 assert(!LastII && "want last identifier but have already annotated scope");
195 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
196 Tok.getAnnotationRange(),
202 if (Tok.is(tok::annot_template_id)) {
203 // If the current token is an annotated template id, it may already have
204 // a scope specifier. Restore it.
205 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
212 bool HasScopeSpecifier = false;
214 if (Tok.is(tok::coloncolon)) {
215 // ::new and ::delete aren't nested-name-specifiers.
216 tok::TokenKind NextKind = NextToken().getKind();
217 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
220 // '::' - Global scope qualifier.
221 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
224 CheckForLParenAfterColonColon();
226 HasScopeSpecifier = true;
229 bool CheckForDestructor = false;
230 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
231 CheckForDestructor = true;
232 *MayBePseudoDestructor = false;
235 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
236 DeclSpec DS(AttrFactory);
237 SourceLocation DeclLoc = Tok.getLocation();
238 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
240 SourceLocation CCLoc;
241 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
242 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
246 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
247 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
249 HasScopeSpecifier = true;
253 if (HasScopeSpecifier) {
254 // C++ [basic.lookup.classref]p5:
255 // If the qualified-id has the form
257 // ::class-name-or-namespace-name::...
259 // the class-name-or-namespace-name is looked up in global scope as a
260 // class-name or namespace-name.
262 // To implement this, we clear out the object type as soon as we've
263 // seen a leading '::' or part of a nested-name-specifier.
264 ObjectType = ParsedType();
266 if (Tok.is(tok::code_completion)) {
267 // Code completion for a nested-name-specifier, where the code
268 // code completion token follows the '::'.
269 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
270 // Include code completion token into the range of the scope otherwise
271 // when we try to annotate the scope tokens the dangling code completion
272 // token will cause assertion in
273 // Preprocessor::AnnotatePreviousCachedTokens.
274 SS.setEndLoc(Tok.getLocation());
280 // nested-name-specifier:
281 // nested-name-specifier 'template'[opt] simple-template-id '::'
283 // Parse the optional 'template' keyword, then make sure we have
284 // 'identifier <' after it.
285 if (Tok.is(tok::kw_template)) {
286 // If we don't have a scope specifier or an object type, this isn't a
287 // nested-name-specifier, since they aren't allowed to start with
289 if (!HasScopeSpecifier && !ObjectType)
292 TentativeParsingAction TPA(*this);
293 SourceLocation TemplateKWLoc = ConsumeToken();
295 UnqualifiedId TemplateName;
296 if (Tok.is(tok::identifier)) {
297 // Consume the identifier.
298 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
300 } else if (Tok.is(tok::kw_operator)) {
301 // We don't need to actually parse the unqualified-id in this case,
302 // because a simple-template-id cannot start with 'operator', but
303 // go ahead and parse it anyway for consistency with the case where
304 // we already annotated the template-id.
305 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
311 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
312 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
313 Diag(TemplateName.getSourceRange().getBegin(),
314 diag::err_id_after_template_in_nested_name_spec)
315 << TemplateName.getSourceRange();
324 // If the next token is not '<', we have a qualified-id that refers
325 // to a template name, such as T::template apply, but is not a
327 if (Tok.isNot(tok::less)) {
332 // Commit to parsing the template-id.
335 if (TemplateNameKind TNK
336 = Actions.ActOnDependentTemplateName(getCurScope(),
337 SS, TemplateKWLoc, TemplateName,
338 ObjectType, EnteringContext,
340 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
341 TemplateName, false))
349 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
354 // So we need to check whether the template-id is a simple-template-id of
355 // the right kind (it should name a type or be dependent), and then
356 // convert it into a type within the nested-name-specifier.
357 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
358 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
359 *MayBePseudoDestructor = true;
364 *LastII = TemplateId->Name;
366 // Consume the template-id token.
369 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
370 SourceLocation CCLoc = ConsumeToken();
372 HasScopeSpecifier = true;
374 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
375 TemplateId->NumArgs);
377 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
379 TemplateId->TemplateKWLoc,
380 TemplateId->Template,
381 TemplateId->TemplateNameLoc,
382 TemplateId->LAngleLoc,
384 TemplateId->RAngleLoc,
387 SourceLocation StartLoc
388 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
389 : TemplateId->TemplateNameLoc;
390 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
396 // The rest of the nested-name-specifier possibilities start with
398 if (Tok.isNot(tok::identifier))
401 IdentifierInfo &II = *Tok.getIdentifierInfo();
403 // nested-name-specifier:
405 // namespace-name '::'
406 // nested-name-specifier identifier '::'
407 Token Next = NextToken();
409 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
410 // and emit a fixit hint for it.
411 if (Next.is(tok::colon) && !ColonIsSacred) {
412 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
414 Next.getLocation(), ObjectType,
416 // If the token after the colon isn't an identifier, it's still an
417 // error, but they probably meant something else strange so don't
418 // recover like this.
419 PP.LookAhead(1).is(tok::identifier)) {
420 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
421 << FixItHint::CreateReplacement(Next.getLocation(), "::");
422 // Recover as if the user wrote '::'.
423 Next.setKind(tok::coloncolon);
427 if (Next.is(tok::coloncolon)) {
428 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
429 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
431 *MayBePseudoDestructor = true;
436 const Token &Next2 = GetLookAheadToken(2);
437 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
438 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
439 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
441 << FixItHint::CreateReplacement(Next.getLocation(), ":");
444 ColonColon.setKind(tok::colon);
445 PP.EnterToken(ColonColon);
453 // We have an identifier followed by a '::'. Lookup this name
454 // as the name in a nested-name-specifier.
455 Token Identifier = Tok;
456 SourceLocation IdLoc = ConsumeToken();
457 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
458 "NextToken() not working properly!");
459 Token ColonColon = Tok;
460 SourceLocation CCLoc = ConsumeToken();
462 CheckForLParenAfterColonColon();
464 bool IsCorrectedToColon = false;
465 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
466 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
467 ObjectType, EnteringContext, SS,
468 false, CorrectionFlagPtr)) {
469 // Identifier is not recognized as a nested name, but we can have
470 // mistyped '::' instead of ':'.
471 if (CorrectionFlagPtr && IsCorrectedToColon) {
472 ColonColon.setKind(tok::colon);
474 PP.EnterToken(ColonColon);
478 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
480 HasScopeSpecifier = true;
484 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
486 // nested-name-specifier:
488 if (Next.is(tok::less)) {
490 UnqualifiedId TemplateName;
491 TemplateName.setIdentifier(&II, Tok.getLocation());
492 bool MemberOfUnknownSpecialization;
493 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
494 /*hasTemplateKeyword=*/false,
499 MemberOfUnknownSpecialization)) {
500 // We have found a template name, so annotate this token
501 // with a template-id annotation. We do not permit the
502 // template-id to be translated into a type annotation,
503 // because some clients (e.g., the parsing of class template
504 // specializations) still want to see the original template-id
507 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
508 TemplateName, false))
513 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
514 (IsTypename || IsTemplateArgumentList(1))) {
515 // We have something like t::getAs<T>, where getAs is a
516 // member of an unknown specialization. However, this will only
517 // parse correctly as a template, so suggest the keyword 'template'
518 // before 'getAs' and treat this as a dependent template name.
519 unsigned DiagID = diag::err_missing_dependent_template_keyword;
520 if (getLangOpts().MicrosoftExt)
521 DiagID = diag::warn_missing_dependent_template_keyword;
523 Diag(Tok.getLocation(), DiagID)
525 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
527 if (TemplateNameKind TNK
528 = Actions.ActOnDependentTemplateName(getCurScope(),
529 SS, SourceLocation(),
530 TemplateName, ObjectType,
531 EnteringContext, Template)) {
532 // Consume the identifier.
534 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
535 TemplateName, false))
545 // We don't have any tokens that form the beginning of a
546 // nested-name-specifier, so we're done.
550 // Even if we didn't see any pieces of a nested-name-specifier, we
551 // still check whether there is a tilde in this position, which
552 // indicates a potential pseudo-destructor.
553 if (CheckForDestructor && Tok.is(tok::tilde))
554 *MayBePseudoDestructor = true;
559 /// ParseCXXIdExpression - Handle id-expression.
566 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
568 /// '::' operator-function-id
571 /// NOTE: The standard specifies that, for qualified-id, the parser does not
574 /// '::' conversion-function-id
575 /// '::' '~' class-name
577 /// This may cause a slight inconsistency on diagnostics:
582 /// :: A :: ~ C(); // Some Sema error about using destructor with a
584 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
587 /// We simplify the parser a bit and make it work like:
590 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
591 /// '::' unqualified-id
593 /// That way Sema can handle and report similar errors for namespaces and the
596 /// The isAddressOfOperand parameter indicates that this id-expression is a
597 /// direct operand of the address-of operator. This is, besides member contexts,
598 /// the only place where a qualified-id naming a non-static class member may
601 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
603 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
604 // '::' unqualified-id
607 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
609 SourceLocation TemplateKWLoc;
611 if (ParseUnqualifiedId(SS,
612 /*EnteringContext=*/false,
613 /*AllowDestructorName=*/false,
614 /*AllowConstructorName=*/false,
615 /*ObjectType=*/ ParsedType(),
620 // This is only the direct operand of an & operator if it is not
621 // followed by a postfix-expression suffix.
622 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
623 isAddressOfOperand = false;
625 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
626 Tok.is(tok::l_paren), isAddressOfOperand);
629 /// ParseLambdaExpression - Parse a C++11 lambda expression.
631 /// lambda-expression:
632 /// lambda-introducer lambda-declarator[opt] compound-statement
634 /// lambda-introducer:
635 /// '[' lambda-capture[opt] ']'
640 /// capture-default ',' capture-list
648 /// capture-list ',' capture
652 /// init-capture [C++1y]
659 /// init-capture: [C++1y]
660 /// identifier initializer
661 /// '&' identifier initializer
663 /// lambda-declarator:
664 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
665 /// 'mutable'[opt] exception-specification[opt]
666 /// trailing-return-type[opt]
668 ExprResult Parser::ParseLambdaExpression() {
669 // Parse lambda-introducer.
670 LambdaIntroducer Intro;
671 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
673 Diag(Tok, DiagID.getValue());
674 SkipUntil(tok::r_square, StopAtSemi);
675 SkipUntil(tok::l_brace, StopAtSemi);
676 SkipUntil(tok::r_brace, StopAtSemi);
680 return ParseLambdaExpressionAfterIntroducer(Intro);
683 /// TryParseLambdaExpression - Use lookahead and potentially tentative
684 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
687 /// If we are not looking at a lambda expression, returns ExprError().
688 ExprResult Parser::TryParseLambdaExpression() {
689 assert(getLangOpts().CPlusPlus11
690 && Tok.is(tok::l_square)
691 && "Not at the start of a possible lambda expression.");
693 const Token Next = NextToken(), After = GetLookAheadToken(2);
695 // If lookahead indicates this is a lambda...
696 if (Next.is(tok::r_square) || // []
697 Next.is(tok::equal) || // [=
698 (Next.is(tok::amp) && // [&] or [&,
699 (After.is(tok::r_square) ||
700 After.is(tok::comma))) ||
701 (Next.is(tok::identifier) && // [identifier]
702 After.is(tok::r_square))) {
703 return ParseLambdaExpression();
706 // If lookahead indicates an ObjC message send...
707 // [identifier identifier
708 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
712 // Here, we're stuck: lambda introducers and Objective-C message sends are
713 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
714 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
715 // writing two routines to parse a lambda introducer, just try to parse
716 // a lambda introducer first, and fall back if that fails.
717 // (TryParseLambdaIntroducer never produces any diagnostic output.)
718 LambdaIntroducer Intro;
719 if (TryParseLambdaIntroducer(Intro))
722 return ParseLambdaExpressionAfterIntroducer(Intro);
725 /// \brief Parse a lambda introducer.
726 /// \param Intro A LambdaIntroducer filled in with information about the
727 /// contents of the lambda-introducer.
728 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
729 /// message send and a lambda expression. In this mode, we will
730 /// sometimes skip the initializers for init-captures and not fully
731 /// populate \p Intro. This flag will be set to \c true if we do so.
732 /// \return A DiagnosticID if it hit something unexpected. The location for
733 /// for the diagnostic is that of the current token.
734 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
735 bool *SkippedInits) {
736 typedef Optional<unsigned> DiagResult;
738 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
739 BalancedDelimiterTracker T(*this, tok::l_square);
742 Intro.Range.setBegin(T.getOpenLocation());
746 // Parse capture-default.
747 if (Tok.is(tok::amp) &&
748 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
749 Intro.Default = LCD_ByRef;
750 Intro.DefaultLoc = ConsumeToken();
752 } else if (Tok.is(tok::equal)) {
753 Intro.Default = LCD_ByCopy;
754 Intro.DefaultLoc = ConsumeToken();
758 while (Tok.isNot(tok::r_square)) {
760 if (Tok.isNot(tok::comma)) {
761 // Provide a completion for a lambda introducer here. Except
762 // in Objective-C, where this is Almost Surely meant to be a message
763 // send. In that case, fail here and let the ObjC message
764 // expression parser perform the completion.
765 if (Tok.is(tok::code_completion) &&
766 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
767 !Intro.Captures.empty())) {
768 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
769 /*AfterAmpersand=*/false);
774 return DiagResult(diag::err_expected_comma_or_rsquare);
779 if (Tok.is(tok::code_completion)) {
780 // If we're in Objective-C++ and we have a bare '[', then this is more
781 // likely to be a message receiver.
782 if (getLangOpts().ObjC1 && first)
783 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
785 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
786 /*AfterAmpersand=*/false);
794 LambdaCaptureKind Kind = LCK_ByCopy;
796 IdentifierInfo *Id = nullptr;
797 SourceLocation EllipsisLoc;
800 if (Tok.is(tok::kw_this)) {
802 Loc = ConsumeToken();
804 if (Tok.is(tok::amp)) {
808 if (Tok.is(tok::code_completion)) {
809 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
810 /*AfterAmpersand=*/true);
816 if (Tok.is(tok::identifier)) {
817 Id = Tok.getIdentifierInfo();
818 Loc = ConsumeToken();
819 } else if (Tok.is(tok::kw_this)) {
820 // FIXME: If we want to suggest a fixit here, will need to return more
821 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
822 // Clear()ed to prevent emission in case of tentative parsing?
823 return DiagResult(diag::err_this_captured_by_reference);
825 return DiagResult(diag::err_expected_capture);
828 if (Tok.is(tok::l_paren)) {
829 BalancedDelimiterTracker Parens(*this, tok::l_paren);
830 Parens.consumeOpen();
836 *SkippedInits = true;
837 } else if (ParseExpressionList(Exprs, Commas)) {
841 Parens.consumeClose();
842 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
843 Parens.getCloseLocation(),
846 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
847 // Each lambda init-capture forms its own full expression, which clears
848 // Actions.MaybeODRUseExprs. So create an expression evaluation context
849 // to save the necessary state, and restore it later.
850 EnterExpressionEvaluationContext EC(Actions,
851 Sema::PotentiallyEvaluated);
852 TryConsumeToken(tok::equal);
855 Init = ParseInitializer();
856 else if (Tok.is(tok::l_brace)) {
857 BalancedDelimiterTracker Braces(*this, tok::l_brace);
858 Braces.consumeOpen();
860 *SkippedInits = true;
862 // We're disambiguating this:
866 // We need to find the end of the following expression in order to
867 // determine whether this is an Obj-C message send's receiver, a
868 // C99 designator, or a lambda init-capture.
870 // Parse the expression to find where it ends, and annotate it back
871 // onto the tokens. We would have parsed this expression the same way
872 // in either case: both the RHS of an init-capture and the RHS of an
873 // assignment expression are parsed as an initializer-clause, and in
874 // neither case can anything be added to the scope between the '[' and
877 // FIXME: This is horrible. Adding a mechanism to skip an expression
878 // would be much cleaner.
879 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
880 // that instead. (And if we see a ':' with no matching '?', we can
881 // classify this as an Obj-C message send.)
882 SourceLocation StartLoc = Tok.getLocation();
883 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
884 Init = ParseInitializer();
886 if (Tok.getLocation() != StartLoc) {
887 // Back out the lexing of the token after the initializer.
888 PP.RevertCachedTokens(1);
890 // Replace the consumed tokens with an appropriate annotation.
891 Tok.setLocation(StartLoc);
892 Tok.setKind(tok::annot_primary_expr);
893 setExprAnnotation(Tok, Init);
894 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
895 PP.AnnotateCachedTokens(Tok);
897 // Consume the annotated initializer.
902 TryConsumeToken(tok::ellipsis, EllipsisLoc);
904 // If this is an init capture, process the initialization expression
905 // right away. For lambda init-captures such as the following:
907 // auto L = [i = x+1](int a) {
909 // &k = x](char b) { };
911 // keep in mind that each lambda init-capture has to have:
912 // - its initialization expression executed in the context
913 // of the enclosing/parent decl-context.
914 // - but the variable itself has to be 'injected' into the
915 // decl-context of its lambda's call-operator (which has
916 // not yet been created).
917 // Each init-expression is a full-expression that has to get
918 // Sema-analyzed (for capturing etc.) before its lambda's
919 // call-operator's decl-context, scope & scopeinfo are pushed on their
920 // respective stacks. Thus if any variable is odr-used in the init-capture
921 // it will correctly get captured in the enclosing lambda, if one exists.
922 // The init-variables above are created later once the lambdascope and
923 // call-operators decl-context is pushed onto its respective stack.
925 // Since the lambda init-capture's initializer expression occurs in the
926 // context of the enclosing function or lambda, therefore we can not wait
927 // till a lambda scope has been pushed on before deciding whether the
928 // variable needs to be captured. We also need to process all
929 // lvalue-to-rvalue conversions and discarded-value conversions,
930 // so that we can avoid capturing certain constant variables.
934 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
935 // return [y = x](int i) { <-- don't capture by enclosing lambda
939 // If x was not const, the second use would require 'L' to capture, and
940 // that would be an error.
942 ParsedType InitCaptureParsedType;
943 if (Init.isUsable()) {
944 // Get the pointer and store it in an lvalue, so we can use it as an
946 Expr *InitExpr = Init.get();
947 // This performs any lvalue-to-rvalue conversions if necessary, which
948 // can affect what gets captured in the containing decl-context.
949 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
950 Loc, Kind == LCK_ByRef, Id, InitExpr);
952 InitCaptureParsedType.set(InitCaptureType);
954 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
958 Intro.Range.setEnd(T.getCloseLocation());
962 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
964 /// Returns true if it hit something unexpected.
965 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
966 TentativeParsingAction PA(*this);
968 bool SkippedInits = false;
969 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
977 // Parse it again, but this time parse the init-captures too.
979 Intro = LambdaIntroducer();
980 DiagID = ParseLambdaIntroducer(Intro);
981 assert(!DiagID && "parsing lambda-introducer failed on reparse");
989 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
991 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
992 LambdaIntroducer &Intro) {
993 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
994 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
996 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
997 "lambda expression parsing");
1001 // FIXME: Call into Actions to add any init-capture declarations to the
1002 // scope while parsing the lambda-declarator and compound-statement.
1004 // Parse lambda-declarator[opt].
1005 DeclSpec DS(AttrFactory);
1006 Declarator D(DS, Declarator::LambdaExprContext);
1007 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1008 Actions.PushLambdaScope();
1010 if (Tok.is(tok::l_paren)) {
1011 ParseScope PrototypeScope(this,
1012 Scope::FunctionPrototypeScope |
1013 Scope::FunctionDeclarationScope |
1016 SourceLocation DeclEndLoc;
1017 BalancedDelimiterTracker T(*this, tok::l_paren);
1019 SourceLocation LParenLoc = T.getOpenLocation();
1021 // Parse parameter-declaration-clause.
1022 ParsedAttributes Attr(AttrFactory);
1023 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1024 SourceLocation EllipsisLoc;
1026 if (Tok.isNot(tok::r_paren)) {
1027 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1028 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1029 // For a generic lambda, each 'auto' within the parameter declaration
1030 // clause creates a template type parameter, so increment the depth.
1031 if (Actions.getCurGenericLambda())
1032 ++CurTemplateDepthTracker;
1035 SourceLocation RParenLoc = T.getCloseLocation();
1036 DeclEndLoc = RParenLoc;
1038 // GNU-style attributes must be parsed before the mutable specifier to be
1039 // compatible with GCC.
1040 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1042 // Parse 'mutable'[opt].
1043 SourceLocation MutableLoc;
1044 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
1045 DeclEndLoc = MutableLoc;
1047 // Parse exception-specification[opt].
1048 ExceptionSpecificationType ESpecType = EST_None;
1049 SourceRange ESpecRange;
1050 SmallVector<ParsedType, 2> DynamicExceptions;
1051 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1052 ExprResult NoexceptExpr;
1053 ESpecType = tryParseExceptionSpecification(ESpecRange,
1055 DynamicExceptionRanges,
1058 if (ESpecType != EST_None)
1059 DeclEndLoc = ESpecRange.getEnd();
1061 // Parse attribute-specifier[opt].
1062 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1064 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1066 // Parse trailing-return-type[opt].
1067 TypeResult TrailingReturnType;
1068 if (Tok.is(tok::arrow)) {
1069 FunLocalRangeEnd = Tok.getLocation();
1071 TrailingReturnType = ParseTrailingReturnType(Range);
1072 if (Range.getEnd().isValid())
1073 DeclEndLoc = Range.getEnd();
1076 PrototypeScope.Exit();
1078 SourceLocation NoLoc;
1079 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1080 /*isAmbiguous=*/false,
1082 ParamInfo.data(), ParamInfo.size(),
1083 EllipsisLoc, RParenLoc,
1084 DS.getTypeQualifiers(),
1085 /*RefQualifierIsLValueRef=*/true,
1086 /*RefQualifierLoc=*/NoLoc,
1087 /*ConstQualifierLoc=*/NoLoc,
1088 /*VolatileQualifierLoc=*/NoLoc,
1090 ESpecType, ESpecRange.getBegin(),
1091 DynamicExceptions.data(),
1092 DynamicExceptionRanges.data(),
1093 DynamicExceptions.size(),
1094 NoexceptExpr.isUsable() ?
1095 NoexceptExpr.get() : nullptr,
1096 LParenLoc, FunLocalRangeEnd, D,
1097 TrailingReturnType),
1099 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow) ||
1100 Tok.is(tok::kw___attribute) ||
1101 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1102 // It's common to forget that one needs '()' before 'mutable', an attribute
1103 // specifier, or the result type. Deal with this.
1104 unsigned TokKind = 0;
1105 switch (Tok.getKind()) {
1106 case tok::kw_mutable: TokKind = 0; break;
1107 case tok::arrow: TokKind = 1; break;
1108 case tok::kw___attribute:
1109 case tok::l_square: TokKind = 2; break;
1110 default: llvm_unreachable("Unknown token kind");
1113 Diag(Tok, diag::err_lambda_missing_parens)
1115 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1116 SourceLocation DeclLoc = Tok.getLocation();
1117 SourceLocation DeclEndLoc = DeclLoc;
1119 // GNU-style attributes must be parsed before the mutable specifier to be
1120 // compatible with GCC.
1121 ParsedAttributes Attr(AttrFactory);
1122 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1124 // Parse 'mutable', if it's there.
1125 SourceLocation MutableLoc;
1126 if (Tok.is(tok::kw_mutable)) {
1127 MutableLoc = ConsumeToken();
1128 DeclEndLoc = MutableLoc;
1131 // Parse attribute-specifier[opt].
1132 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1134 // Parse the return type, if there is one.
1135 TypeResult TrailingReturnType;
1136 if (Tok.is(tok::arrow)) {
1138 TrailingReturnType = ParseTrailingReturnType(Range);
1139 if (Range.getEnd().isValid())
1140 DeclEndLoc = Range.getEnd();
1143 SourceLocation NoLoc;
1144 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1145 /*isAmbiguous=*/false,
1146 /*LParenLoc=*/NoLoc,
1149 /*EllipsisLoc=*/NoLoc,
1150 /*RParenLoc=*/NoLoc,
1152 /*RefQualifierIsLValueRef=*/true,
1153 /*RefQualifierLoc=*/NoLoc,
1154 /*ConstQualifierLoc=*/NoLoc,
1155 /*VolatileQualifierLoc=*/NoLoc,
1159 /*Exceptions=*/nullptr,
1160 /*ExceptionRanges=*/nullptr,
1161 /*NumExceptions=*/0,
1162 /*NoexceptExpr=*/nullptr,
1163 DeclLoc, DeclEndLoc, D,
1164 TrailingReturnType),
1169 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1171 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
1172 ParseScope BodyScope(this, ScopeFlags);
1174 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1176 // Parse compound-statement.
1177 if (!Tok.is(tok::l_brace)) {
1178 Diag(Tok, diag::err_expected_lambda_body);
1179 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1183 StmtResult Stmt(ParseCompoundStatementBody());
1186 if (!Stmt.isInvalid())
1187 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1189 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1193 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1196 /// postfix-expression: [C++ 5.2p1]
1197 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1198 /// 'static_cast' '<' type-name '>' '(' expression ')'
1199 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1200 /// 'const_cast' '<' type-name '>' '(' expression ')'
1202 ExprResult Parser::ParseCXXCasts() {
1203 tok::TokenKind Kind = Tok.getKind();
1204 const char *CastName = nullptr; // For error messages
1207 default: llvm_unreachable("Unknown C++ cast!");
1208 case tok::kw_const_cast: CastName = "const_cast"; break;
1209 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1210 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1211 case tok::kw_static_cast: CastName = "static_cast"; break;
1214 SourceLocation OpLoc = ConsumeToken();
1215 SourceLocation LAngleBracketLoc = Tok.getLocation();
1217 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1218 // diagnose error, suggest fix, and recover parsing.
1219 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1220 Token Next = NextToken();
1221 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1222 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1225 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1228 // Parse the common declaration-specifiers piece.
1229 DeclSpec DS(AttrFactory);
1230 ParseSpecifierQualifierList(DS);
1232 // Parse the abstract-declarator, if present.
1233 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1234 ParseDeclarator(DeclaratorInfo);
1236 SourceLocation RAngleBracketLoc = Tok.getLocation();
1238 if (ExpectAndConsume(tok::greater))
1239 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1241 SourceLocation LParenLoc, RParenLoc;
1242 BalancedDelimiterTracker T(*this, tok::l_paren);
1244 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1247 ExprResult Result = ParseExpression();
1252 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1253 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1254 LAngleBracketLoc, DeclaratorInfo,
1256 T.getOpenLocation(), Result.get(),
1257 T.getCloseLocation());
1262 /// ParseCXXTypeid - This handles the C++ typeid expression.
1264 /// postfix-expression: [C++ 5.2p1]
1265 /// 'typeid' '(' expression ')'
1266 /// 'typeid' '(' type-id ')'
1268 ExprResult Parser::ParseCXXTypeid() {
1269 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1271 SourceLocation OpLoc = ConsumeToken();
1272 SourceLocation LParenLoc, RParenLoc;
1273 BalancedDelimiterTracker T(*this, tok::l_paren);
1275 // typeid expressions are always parenthesized.
1276 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1278 LParenLoc = T.getOpenLocation();
1282 // C++0x [expr.typeid]p3:
1283 // When typeid is applied to an expression other than an lvalue of a
1284 // polymorphic class type [...] The expression is an unevaluated
1285 // operand (Clause 5).
1287 // Note that we can't tell whether the expression is an lvalue of a
1288 // polymorphic class type until after we've parsed the expression; we
1289 // speculatively assume the subexpression is unevaluated, and fix it up
1292 // We enter the unevaluated context before trying to determine whether we
1293 // have a type-id, because the tentative parse logic will try to resolve
1294 // names, and must treat them as unevaluated.
1295 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1296 Sema::ReuseLambdaContextDecl);
1298 if (isTypeIdInParens()) {
1299 TypeResult Ty = ParseTypeName();
1303 RParenLoc = T.getCloseLocation();
1304 if (Ty.isInvalid() || RParenLoc.isInvalid())
1307 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1308 Ty.get().getAsOpaquePtr(), RParenLoc);
1310 Result = ParseExpression();
1313 if (Result.isInvalid())
1314 SkipUntil(tok::r_paren, StopAtSemi);
1317 RParenLoc = T.getCloseLocation();
1318 if (RParenLoc.isInvalid())
1321 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1322 Result.get(), RParenLoc);
1329 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1331 /// '__uuidof' '(' expression ')'
1332 /// '__uuidof' '(' type-id ')'
1334 ExprResult Parser::ParseCXXUuidof() {
1335 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1337 SourceLocation OpLoc = ConsumeToken();
1338 BalancedDelimiterTracker T(*this, tok::l_paren);
1340 // __uuidof expressions are always parenthesized.
1341 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1346 if (isTypeIdInParens()) {
1347 TypeResult Ty = ParseTypeName();
1355 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1356 Ty.get().getAsOpaquePtr(),
1357 T.getCloseLocation());
1359 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1360 Result = ParseExpression();
1363 if (Result.isInvalid())
1364 SkipUntil(tok::r_paren, StopAtSemi);
1368 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1370 Result.get(), T.getCloseLocation());
1377 /// \brief Parse a C++ pseudo-destructor expression after the base,
1378 /// . or -> operator, and nested-name-specifier have already been
1381 /// postfix-expression: [C++ 5.2]
1382 /// postfix-expression . pseudo-destructor-name
1383 /// postfix-expression -> pseudo-destructor-name
1385 /// pseudo-destructor-name:
1386 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1387 /// ::[opt] nested-name-specifier template simple-template-id ::
1389 /// ::[opt] nested-name-specifier[opt] ~type-name
1392 Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1393 tok::TokenKind OpKind,
1395 ParsedType ObjectType) {
1396 // We're parsing either a pseudo-destructor-name or a dependent
1397 // member access that has the same form as a
1398 // pseudo-destructor-name. We parse both in the same way and let
1399 // the action model sort them out.
1401 // Note that the ::[opt] nested-name-specifier[opt] has already
1402 // been parsed, and if there was a simple-template-id, it has
1403 // been coalesced into a template-id annotation token.
1404 UnqualifiedId FirstTypeName;
1405 SourceLocation CCLoc;
1406 if (Tok.is(tok::identifier)) {
1407 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1409 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1410 CCLoc = ConsumeToken();
1411 } else if (Tok.is(tok::annot_template_id)) {
1412 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1413 // store it in the pseudo-dtor node (to be used when instantiating it).
1414 FirstTypeName.setTemplateId(
1415 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1417 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1418 CCLoc = ConsumeToken();
1420 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1424 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1425 SourceLocation TildeLoc = ConsumeToken();
1427 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1428 DeclSpec DS(AttrFactory);
1429 ParseDecltypeSpecifier(DS);
1430 if (DS.getTypeSpecType() == TST_error)
1432 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1433 OpKind, TildeLoc, DS,
1434 Tok.is(tok::l_paren));
1437 if (!Tok.is(tok::identifier)) {
1438 Diag(Tok, diag::err_destructor_tilde_identifier);
1442 // Parse the second type.
1443 UnqualifiedId SecondTypeName;
1444 IdentifierInfo *Name = Tok.getIdentifierInfo();
1445 SourceLocation NameLoc = ConsumeToken();
1446 SecondTypeName.setIdentifier(Name, NameLoc);
1448 // If there is a '<', the second type name is a template-id. Parse
1450 if (Tok.is(tok::less) &&
1451 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1453 false, ObjectType, SecondTypeName,
1454 /*AssumeTemplateName=*/true))
1457 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1459 SS, FirstTypeName, CCLoc,
1460 TildeLoc, SecondTypeName,
1461 Tok.is(tok::l_paren));
1464 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1466 /// boolean-literal: [C++ 2.13.5]
1469 ExprResult Parser::ParseCXXBoolLiteral() {
1470 tok::TokenKind Kind = Tok.getKind();
1471 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1474 /// ParseThrowExpression - This handles the C++ throw expression.
1476 /// throw-expression: [C++ 15]
1477 /// 'throw' assignment-expression[opt]
1478 ExprResult Parser::ParseThrowExpression() {
1479 assert(Tok.is(tok::kw_throw) && "Not throw!");
1480 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1482 // If the current token isn't the start of an assignment-expression,
1483 // then the expression is not present. This handles things like:
1484 // "C ? throw : (void)42", which is crazy but legal.
1485 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1492 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1495 ExprResult Expr(ParseAssignmentExpression());
1496 if (Expr.isInvalid()) return Expr;
1497 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1501 /// ParseCXXThis - This handles the C++ 'this' pointer.
1503 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1504 /// a non-lvalue expression whose value is the address of the object for which
1505 /// the function is called.
1506 ExprResult Parser::ParseCXXThis() {
1507 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1508 SourceLocation ThisLoc = ConsumeToken();
1509 return Actions.ActOnCXXThis(ThisLoc);
1512 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1513 /// Can be interpreted either as function-style casting ("int(x)")
1514 /// or class type construction ("ClassType(x,y,z)")
1515 /// or creation of a value-initialized type ("int()").
1516 /// See [C++ 5.2.3].
1518 /// postfix-expression: [C++ 5.2p1]
1519 /// simple-type-specifier '(' expression-list[opt] ')'
1520 /// [C++0x] simple-type-specifier braced-init-list
1521 /// typename-specifier '(' expression-list[opt] ')'
1522 /// [C++0x] typename-specifier braced-init-list
1525 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1526 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1527 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1529 assert((Tok.is(tok::l_paren) ||
1530 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1531 && "Expected '(' or '{'!");
1533 if (Tok.is(tok::l_brace)) {
1534 ExprResult Init = ParseBraceInitializer();
1535 if (Init.isInvalid())
1537 Expr *InitList = Init.get();
1538 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1539 MultiExprArg(&InitList, 1),
1542 BalancedDelimiterTracker T(*this, tok::l_paren);
1546 CommaLocsTy CommaLocs;
1548 if (Tok.isNot(tok::r_paren)) {
1549 if (ParseExpressionList(Exprs, CommaLocs)) {
1550 SkipUntil(tok::r_paren, StopAtSemi);
1558 // TypeRep could be null, if it references an invalid typedef.
1562 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1563 "Unexpected number of commas!");
1564 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1566 T.getCloseLocation());
1570 /// ParseCXXCondition - if/switch/while condition expression.
1574 /// type-specifier-seq declarator '=' assignment-expression
1575 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1576 /// [C++11] type-specifier-seq declarator braced-init-list
1577 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1578 /// '=' assignment-expression
1580 /// \param ExprOut if the condition was parsed as an expression, the parsed
1583 /// \param DeclOut if the condition was parsed as a declaration, the parsed
1586 /// \param Loc The location of the start of the statement that requires this
1587 /// condition, e.g., the "for" in a for loop.
1589 /// \param ConvertToBoolean Whether the condition expression should be
1590 /// converted to a boolean value.
1592 /// \returns true if there was a parsing, false otherwise.
1593 bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1596 bool ConvertToBoolean) {
1597 if (Tok.is(tok::code_completion)) {
1598 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1603 ParsedAttributesWithRange attrs(AttrFactory);
1604 MaybeParseCXX11Attributes(attrs);
1606 if (!isCXXConditionDeclaration()) {
1607 ProhibitAttributes(attrs);
1609 // Parse the expression.
1610 ExprOut = ParseExpression(); // expression
1612 if (ExprOut.isInvalid())
1615 // If required, convert to a boolean value.
1616 if (ConvertToBoolean)
1618 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1619 return ExprOut.isInvalid();
1622 // type-specifier-seq
1623 DeclSpec DS(AttrFactory);
1624 DS.takeAttributesFrom(attrs);
1625 ParseSpecifierQualifierList(DS);
1628 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1629 ParseDeclarator(DeclaratorInfo);
1631 // simple-asm-expr[opt]
1632 if (Tok.is(tok::kw_asm)) {
1634 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1635 if (AsmLabel.isInvalid()) {
1636 SkipUntil(tok::semi, StopAtSemi);
1639 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1640 DeclaratorInfo.SetRangeEnd(Loc);
1643 // If attributes are present, parse them.
1644 MaybeParseGNUAttributes(DeclaratorInfo);
1646 // Type-check the declaration itself.
1647 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1649 DeclOut = Dcl.get();
1650 ExprOut = ExprError();
1652 // '=' assignment-expression
1653 // If a '==' or '+=' is found, suggest a fixit to '='.
1654 bool CopyInitialization = isTokenEqualOrEqualTypo();
1655 if (CopyInitialization)
1658 ExprResult InitExpr = ExprError();
1659 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1660 Diag(Tok.getLocation(),
1661 diag::warn_cxx98_compat_generalized_initializer_lists);
1662 InitExpr = ParseBraceInitializer();
1663 } else if (CopyInitialization) {
1664 InitExpr = ParseAssignmentExpression();
1665 } else if (Tok.is(tok::l_paren)) {
1666 // This was probably an attempt to initialize the variable.
1667 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1668 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1669 RParen = ConsumeParen();
1670 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1671 diag::err_expected_init_in_condition_lparen)
1672 << SourceRange(LParen, RParen);
1674 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1675 diag::err_expected_init_in_condition);
1678 if (!InitExpr.isInvalid())
1679 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
1680 DS.containsPlaceholderType());
1682 Actions.ActOnInitializerError(DeclOut);
1684 // FIXME: Build a reference to this declaration? Convert it to bool?
1685 // (This is currently handled by Sema).
1687 Actions.FinalizeDeclaration(DeclOut);
1692 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1693 /// This should only be called when the current token is known to be part of
1694 /// simple-type-specifier.
1696 /// simple-type-specifier:
1697 /// '::'[opt] nested-name-specifier[opt] type-name
1698 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1710 /// [GNU] typeof-specifier
1711 /// [C++0x] auto [TODO]
1718 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1719 DS.SetRangeStart(Tok.getLocation());
1720 const char *PrevSpec;
1722 SourceLocation Loc = Tok.getLocation();
1723 const clang::PrintingPolicy &Policy =
1724 Actions.getASTContext().getPrintingPolicy();
1726 switch (Tok.getKind()) {
1727 case tok::identifier: // foo::bar
1728 case tok::coloncolon: // ::foo::bar
1729 llvm_unreachable("Annotation token should already be formed!");
1731 llvm_unreachable("Not a simple-type-specifier token!");
1734 case tok::annot_typename: {
1735 if (getTypeAnnotation(Tok))
1736 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1737 getTypeAnnotation(Tok), Policy);
1739 DS.SetTypeSpecError();
1741 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1744 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1745 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1746 // Objective-C interface. If we don't have Objective-C or a '<', this is
1747 // just a normal reference to a typedef name.
1748 if (Tok.is(tok::less) && getLangOpts().ObjC1)
1749 ParseObjCProtocolQualifiers(DS);
1751 DS.Finish(Diags, PP, Policy);
1757 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1760 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1762 case tok::kw___int64:
1763 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1765 case tok::kw_signed:
1766 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1768 case tok::kw_unsigned:
1769 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1772 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1775 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1778 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1780 case tok::kw___int128:
1781 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1784 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1787 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1789 case tok::kw_double:
1790 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1792 case tok::kw_wchar_t:
1793 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1795 case tok::kw_char16_t:
1796 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1798 case tok::kw_char32_t:
1799 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1802 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1804 case tok::annot_decltype:
1805 case tok::kw_decltype:
1806 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1807 return DS.Finish(Diags, PP, Policy);
1809 // GNU typeof support.
1810 case tok::kw_typeof:
1811 ParseTypeofSpecifier(DS);
1812 DS.Finish(Diags, PP, Policy);
1815 if (Tok.is(tok::annot_typename))
1816 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1818 DS.SetRangeEnd(Tok.getLocation());
1820 DS.Finish(Diags, PP, Policy);
1823 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1824 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1825 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1826 /// by parsing the type-specifier-seq, because these sequences are
1827 /// typically followed by some form of declarator. Returns true and
1828 /// emits diagnostics if this is not a type-specifier-seq, false
1831 /// type-specifier-seq: [C++ 8.1]
1832 /// type-specifier type-specifier-seq[opt]
1834 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1835 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1836 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
1840 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1843 /// This routine is invoked when a '<' is encountered after an identifier or
1844 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1845 /// whether the unqualified-id is actually a template-id. This routine will
1846 /// then parse the template arguments and form the appropriate template-id to
1847 /// return to the caller.
1849 /// \param SS the nested-name-specifier that precedes this template-id, if
1850 /// we're actually parsing a qualified-id.
1852 /// \param Name for constructor and destructor names, this is the actual
1853 /// identifier that may be a template-name.
1855 /// \param NameLoc the location of the class-name in a constructor or
1858 /// \param EnteringContext whether we're entering the scope of the
1859 /// nested-name-specifier.
1861 /// \param ObjectType if this unqualified-id occurs within a member access
1862 /// expression, the type of the base object whose member is being accessed.
1864 /// \param Id as input, describes the template-name or operator-function-id
1865 /// that precedes the '<'. If template arguments were parsed successfully,
1866 /// will be updated with the template-id.
1868 /// \param AssumeTemplateId When true, this routine will assume that the name
1869 /// refers to a template without performing name lookup to verify.
1871 /// \returns true if a parse error occurred, false otherwise.
1872 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1873 SourceLocation TemplateKWLoc,
1874 IdentifierInfo *Name,
1875 SourceLocation NameLoc,
1876 bool EnteringContext,
1877 ParsedType ObjectType,
1879 bool AssumeTemplateId) {
1880 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1881 "Expected '<' to finish parsing a template-id");
1883 TemplateTy Template;
1884 TemplateNameKind TNK = TNK_Non_template;
1885 switch (Id.getKind()) {
1886 case UnqualifiedId::IK_Identifier:
1887 case UnqualifiedId::IK_OperatorFunctionId:
1888 case UnqualifiedId::IK_LiteralOperatorId:
1889 if (AssumeTemplateId) {
1890 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
1891 Id, ObjectType, EnteringContext,
1893 if (TNK == TNK_Non_template)
1896 bool MemberOfUnknownSpecialization;
1897 TNK = Actions.isTemplateName(getCurScope(), SS,
1898 TemplateKWLoc.isValid(), Id,
1899 ObjectType, EnteringContext, Template,
1900 MemberOfUnknownSpecialization);
1902 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1903 ObjectType && IsTemplateArgumentList()) {
1904 // We have something like t->getAs<T>(), where getAs is a
1905 // member of an unknown specialization. However, this will only
1906 // parse correctly as a template, so suggest the keyword 'template'
1907 // before 'getAs' and treat this as a dependent template name.
1909 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1910 Name = Id.Identifier->getName();
1913 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1914 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1916 Name += Id.Identifier->getName();
1918 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1920 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1921 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1922 SS, TemplateKWLoc, Id,
1923 ObjectType, EnteringContext,
1925 if (TNK == TNK_Non_template)
1931 case UnqualifiedId::IK_ConstructorName: {
1932 UnqualifiedId TemplateName;
1933 bool MemberOfUnknownSpecialization;
1934 TemplateName.setIdentifier(Name, NameLoc);
1935 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1936 TemplateName, ObjectType,
1937 EnteringContext, Template,
1938 MemberOfUnknownSpecialization);
1942 case UnqualifiedId::IK_DestructorName: {
1943 UnqualifiedId TemplateName;
1944 bool MemberOfUnknownSpecialization;
1945 TemplateName.setIdentifier(Name, NameLoc);
1947 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1948 SS, TemplateKWLoc, TemplateName,
1949 ObjectType, EnteringContext,
1951 if (TNK == TNK_Non_template)
1954 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1955 TemplateName, ObjectType,
1956 EnteringContext, Template,
1957 MemberOfUnknownSpecialization);
1959 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
1960 Diag(NameLoc, diag::err_destructor_template_id)
1961 << Name << SS.getRange();
1972 if (TNK == TNK_Non_template)
1975 // Parse the enclosed template argument list.
1976 SourceLocation LAngleLoc, RAngleLoc;
1977 TemplateArgList TemplateArgs;
1978 if (Tok.is(tok::less) &&
1979 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
1980 SS, true, LAngleLoc,
1985 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
1986 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1987 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
1988 // Form a parsed representation of the template-id to be stored in the
1990 TemplateIdAnnotation *TemplateId
1991 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1993 // FIXME: Store name for literal operator too.
1994 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1995 TemplateId->Name = Id.Identifier;
1996 TemplateId->Operator = OO_None;
1997 TemplateId->TemplateNameLoc = Id.StartLocation;
1999 TemplateId->Name = nullptr;
2000 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2001 TemplateId->TemplateNameLoc = Id.StartLocation;
2004 TemplateId->SS = SS;
2005 TemplateId->TemplateKWLoc = TemplateKWLoc;
2006 TemplateId->Template = Template;
2007 TemplateId->Kind = TNK;
2008 TemplateId->LAngleLoc = LAngleLoc;
2009 TemplateId->RAngleLoc = RAngleLoc;
2010 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
2011 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
2012 Arg != ArgEnd; ++Arg)
2013 Args[Arg] = TemplateArgs[Arg];
2015 Id.setTemplateId(TemplateId);
2019 // Bundle the template arguments together.
2020 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2022 // Constructor and destructor names.
2024 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2026 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2027 /*IsCtorOrDtorName=*/true);
2028 if (Type.isInvalid())
2031 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2032 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2034 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2039 /// \brief Parse an operator-function-id or conversion-function-id as part
2040 /// of a C++ unqualified-id.
2042 /// This routine is responsible only for parsing the operator-function-id or
2043 /// conversion-function-id; it does not handle template arguments in any way.
2046 /// operator-function-id: [C++ 13.5]
2047 /// 'operator' operator
2049 /// operator: one of
2050 /// new delete new[] delete[]
2051 /// + - * / % ^ & | ~
2052 /// ! = < > += -= *= /= %=
2053 /// ^= &= |= << >> >>= <<= == !=
2054 /// <= >= && || ++ -- , ->* ->
2057 /// conversion-function-id: [C++ 12.3.2]
2058 /// operator conversion-type-id
2060 /// conversion-type-id:
2061 /// type-specifier-seq conversion-declarator[opt]
2063 /// conversion-declarator:
2064 /// ptr-operator conversion-declarator[opt]
2067 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2068 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2070 /// \param EnteringContext whether we are entering the scope of the
2071 /// nested-name-specifier.
2073 /// \param ObjectType if this unqualified-id occurs within a member access
2074 /// expression, the type of the base object whose member is being accessed.
2076 /// \param Result on a successful parse, contains the parsed unqualified-id.
2078 /// \returns true if parsing fails, false otherwise.
2079 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2080 ParsedType ObjectType,
2081 UnqualifiedId &Result) {
2082 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2084 // Consume the 'operator' keyword.
2085 SourceLocation KeywordLoc = ConsumeToken();
2087 // Determine what kind of operator name we have.
2088 unsigned SymbolIdx = 0;
2089 SourceLocation SymbolLocations[3];
2090 OverloadedOperatorKind Op = OO_None;
2091 switch (Tok.getKind()) {
2093 case tok::kw_delete: {
2094 bool isNew = Tok.getKind() == tok::kw_new;
2095 // Consume the 'new' or 'delete'.
2096 SymbolLocations[SymbolIdx++] = ConsumeToken();
2097 // Check for array new/delete.
2098 if (Tok.is(tok::l_square) &&
2099 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2100 // Consume the '[' and ']'.
2101 BalancedDelimiterTracker T(*this, tok::l_square);
2104 if (T.getCloseLocation().isInvalid())
2107 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2108 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2109 Op = isNew? OO_Array_New : OO_Array_Delete;
2111 Op = isNew? OO_New : OO_Delete;
2116 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2118 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2121 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2122 #include "clang/Basic/OperatorKinds.def"
2124 case tok::l_paren: {
2125 // Consume the '(' and ')'.
2126 BalancedDelimiterTracker T(*this, tok::l_paren);
2129 if (T.getCloseLocation().isInvalid())
2132 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2133 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2138 case tok::l_square: {
2139 // Consume the '[' and ']'.
2140 BalancedDelimiterTracker T(*this, tok::l_square);
2143 if (T.getCloseLocation().isInvalid())
2146 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2147 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2152 case tok::code_completion: {
2153 // Code completion for the operator name.
2154 Actions.CodeCompleteOperatorName(getCurScope());
2156 // Don't try to parse any further.
2164 if (Op != OO_None) {
2165 // We have parsed an operator-function-id.
2166 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2170 // Parse a literal-operator-id.
2172 // literal-operator-id: C++11 [over.literal]
2173 // operator string-literal identifier
2174 // operator user-defined-string-literal
2176 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2177 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2179 SourceLocation DiagLoc;
2180 unsigned DiagId = 0;
2182 // We're past translation phase 6, so perform string literal concatenation
2183 // before checking for "".
2184 SmallVector<Token, 4> Toks;
2185 SmallVector<SourceLocation, 4> TokLocs;
2186 while (isTokenStringLiteral()) {
2187 if (!Tok.is(tok::string_literal) && !DiagId) {
2188 // C++11 [over.literal]p1:
2189 // The string-literal or user-defined-string-literal in a
2190 // literal-operator-id shall have no encoding-prefix [...].
2191 DiagLoc = Tok.getLocation();
2192 DiagId = diag::err_literal_operator_string_prefix;
2194 Toks.push_back(Tok);
2195 TokLocs.push_back(ConsumeStringToken());
2198 StringLiteralParser Literal(Toks, PP);
2199 if (Literal.hadError)
2202 // Grab the literal operator's suffix, which will be either the next token
2203 // or a ud-suffix from the string literal.
2204 IdentifierInfo *II = nullptr;
2205 SourceLocation SuffixLoc;
2206 if (!Literal.getUDSuffix().empty()) {
2207 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2209 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2210 Literal.getUDSuffixOffset(),
2211 PP.getSourceManager(), getLangOpts());
2212 } else if (Tok.is(tok::identifier)) {
2213 II = Tok.getIdentifierInfo();
2214 SuffixLoc = ConsumeToken();
2215 TokLocs.push_back(SuffixLoc);
2217 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2221 // The string literal must be empty.
2222 if (!Literal.GetString().empty() || Literal.Pascal) {
2223 // C++11 [over.literal]p1:
2224 // The string-literal or user-defined-string-literal in a
2225 // literal-operator-id shall [...] contain no characters
2226 // other than the implicit terminating '\0'.
2227 DiagLoc = TokLocs.front();
2228 DiagId = diag::err_literal_operator_string_not_empty;
2232 // This isn't a valid literal-operator-id, but we think we know
2233 // what the user meant. Tell them what they should have written.
2234 SmallString<32> Str;
2236 Str += II->getName();
2237 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2238 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2241 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2243 return Actions.checkLiteralOperatorId(SS, Result);
2246 // Parse a conversion-function-id.
2248 // conversion-function-id: [C++ 12.3.2]
2249 // operator conversion-type-id
2251 // conversion-type-id:
2252 // type-specifier-seq conversion-declarator[opt]
2254 // conversion-declarator:
2255 // ptr-operator conversion-declarator[opt]
2257 // Parse the type-specifier-seq.
2258 DeclSpec DS(AttrFactory);
2259 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2262 // Parse the conversion-declarator, which is merely a sequence of
2264 Declarator D(DS, Declarator::ConversionIdContext);
2265 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2267 // Finish up the type.
2268 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2272 // Note that this is a conversion-function-id.
2273 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2274 D.getSourceRange().getEnd());
2278 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2279 /// name of an entity.
2282 /// unqualified-id: [C++ expr.prim.general]
2284 /// operator-function-id
2285 /// conversion-function-id
2286 /// [C++0x] literal-operator-id [TODO]
2292 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2293 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2295 /// \param EnteringContext whether we are entering the scope of the
2296 /// nested-name-specifier.
2298 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2300 /// \param AllowConstructorName whether we allow parsing a constructor name.
2302 /// \param ObjectType if this unqualified-id occurs within a member access
2303 /// expression, the type of the base object whose member is being accessed.
2305 /// \param Result on a successful parse, contains the parsed unqualified-id.
2307 /// \returns true if parsing fails, false otherwise.
2308 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2309 bool AllowDestructorName,
2310 bool AllowConstructorName,
2311 ParsedType ObjectType,
2312 SourceLocation& TemplateKWLoc,
2313 UnqualifiedId &Result) {
2315 // Handle 'A::template B'. This is for template-ids which have not
2316 // already been annotated by ParseOptionalCXXScopeSpecifier().
2317 bool TemplateSpecified = false;
2318 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2319 (ObjectType || SS.isSet())) {
2320 TemplateSpecified = true;
2321 TemplateKWLoc = ConsumeToken();
2326 // template-id (when it hasn't already been annotated)
2327 if (Tok.is(tok::identifier)) {
2328 // Consume the identifier.
2329 IdentifierInfo *Id = Tok.getIdentifierInfo();
2330 SourceLocation IdLoc = ConsumeToken();
2332 if (!getLangOpts().CPlusPlus) {
2333 // If we're not in C++, only identifiers matter. Record the
2334 // identifier and return.
2335 Result.setIdentifier(Id, IdLoc);
2339 if (AllowConstructorName &&
2340 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2341 // We have parsed a constructor name.
2342 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2345 /*IsCtorOrDtorName=*/true,
2346 /*NonTrivialTypeSourceInfo=*/true);
2347 Result.setConstructorName(Ty, IdLoc, IdLoc);
2349 // We have parsed an identifier.
2350 Result.setIdentifier(Id, IdLoc);
2353 // If the next token is a '<', we may have a template.
2354 if (TemplateSpecified || Tok.is(tok::less))
2355 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2356 EnteringContext, ObjectType,
2357 Result, TemplateSpecified);
2363 // template-id (already parsed and annotated)
2364 if (Tok.is(tok::annot_template_id)) {
2365 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2367 // If the template-name names the current class, then this is a constructor
2368 if (AllowConstructorName && TemplateId->Name &&
2369 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2371 // C++ [class.qual]p2 specifies that a qualified template-name
2372 // is taken as the constructor name where a constructor can be
2373 // declared. Thus, the template arguments are extraneous, so
2374 // complain about them and remove them entirely.
2375 Diag(TemplateId->TemplateNameLoc,
2376 diag::err_out_of_line_constructor_template_id)
2378 << FixItHint::CreateRemoval(
2379 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2380 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2381 TemplateId->TemplateNameLoc,
2385 /*IsCtorOrDtorName=*/true,
2386 /*NontrivialTypeSourceInfo=*/true);
2387 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2388 TemplateId->RAngleLoc);
2393 Result.setConstructorTemplateId(TemplateId);
2398 // We have already parsed a template-id; consume the annotation token as
2399 // our unqualified-id.
2400 Result.setTemplateId(TemplateId);
2401 TemplateKWLoc = TemplateId->TemplateKWLoc;
2407 // operator-function-id
2408 // conversion-function-id
2409 if (Tok.is(tok::kw_operator)) {
2410 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2413 // If we have an operator-function-id or a literal-operator-id and the next
2414 // token is a '<', we may have a
2417 // operator-function-id < template-argument-list[opt] >
2418 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2419 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2420 (TemplateSpecified || Tok.is(tok::less)))
2421 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2422 nullptr, SourceLocation(),
2423 EnteringContext, ObjectType,
2424 Result, TemplateSpecified);
2429 if (getLangOpts().CPlusPlus &&
2430 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2431 // C++ [expr.unary.op]p10:
2432 // There is an ambiguity in the unary-expression ~X(), where X is a
2433 // class-name. The ambiguity is resolved in favor of treating ~ as a
2434 // unary complement rather than treating ~X as referring to a destructor.
2437 SourceLocation TildeLoc = ConsumeToken();
2439 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2440 DeclSpec DS(AttrFactory);
2441 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2442 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2443 Result.setDestructorName(TildeLoc, Type, EndLoc);
2449 // Parse the class-name.
2450 if (Tok.isNot(tok::identifier)) {
2451 Diag(Tok, diag::err_destructor_tilde_identifier);
2455 // Parse the class-name (or template-name in a simple-template-id).
2456 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2457 SourceLocation ClassNameLoc = ConsumeToken();
2459 if (TemplateSpecified || Tok.is(tok::less)) {
2460 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
2461 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2462 ClassName, ClassNameLoc,
2463 EnteringContext, ObjectType,
2464 Result, TemplateSpecified);
2467 // Note that this is a destructor name.
2468 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2469 ClassNameLoc, getCurScope(),
2475 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2479 Diag(Tok, diag::err_expected_unqualified_id)
2480 << getLangOpts().CPlusPlus;
2484 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2485 /// memory in a typesafe manner and call constructors.
2487 /// This method is called to parse the new expression after the optional :: has
2488 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2489 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2492 /// '::'[opt] 'new' new-placement[opt] new-type-id
2493 /// new-initializer[opt]
2494 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2495 /// new-initializer[opt]
2498 /// '(' expression-list ')'
2501 /// type-specifier-seq new-declarator[opt]
2502 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2505 /// ptr-operator new-declarator[opt]
2506 /// direct-new-declarator
2508 /// new-initializer:
2509 /// '(' expression-list[opt] ')'
2510 /// [C++0x] braced-init-list
2513 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2514 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2515 ConsumeToken(); // Consume 'new'
2517 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2518 // second form of new-expression. It can't be a new-type-id.
2520 ExprVector PlacementArgs;
2521 SourceLocation PlacementLParen, PlacementRParen;
2523 SourceRange TypeIdParens;
2524 DeclSpec DS(AttrFactory);
2525 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2526 if (Tok.is(tok::l_paren)) {
2527 // If it turns out to be a placement, we change the type location.
2528 BalancedDelimiterTracker T(*this, tok::l_paren);
2530 PlacementLParen = T.getOpenLocation();
2531 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2532 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2537 PlacementRParen = T.getCloseLocation();
2538 if (PlacementRParen.isInvalid()) {
2539 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2543 if (PlacementArgs.empty()) {
2544 // Reset the placement locations. There was no placement.
2545 TypeIdParens = T.getRange();
2546 PlacementLParen = PlacementRParen = SourceLocation();
2548 // We still need the type.
2549 if (Tok.is(tok::l_paren)) {
2550 BalancedDelimiterTracker T(*this, tok::l_paren);
2552 MaybeParseGNUAttributes(DeclaratorInfo);
2553 ParseSpecifierQualifierList(DS);
2554 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2555 ParseDeclarator(DeclaratorInfo);
2557 TypeIdParens = T.getRange();
2559 MaybeParseGNUAttributes(DeclaratorInfo);
2560 if (ParseCXXTypeSpecifierSeq(DS))
2561 DeclaratorInfo.setInvalidType(true);
2563 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2564 ParseDeclaratorInternal(DeclaratorInfo,
2565 &Parser::ParseDirectNewDeclarator);
2570 // A new-type-id is a simplified type-id, where essentially the
2571 // direct-declarator is replaced by a direct-new-declarator.
2572 MaybeParseGNUAttributes(DeclaratorInfo);
2573 if (ParseCXXTypeSpecifierSeq(DS))
2574 DeclaratorInfo.setInvalidType(true);
2576 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2577 ParseDeclaratorInternal(DeclaratorInfo,
2578 &Parser::ParseDirectNewDeclarator);
2581 if (DeclaratorInfo.isInvalidType()) {
2582 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2586 ExprResult Initializer;
2588 if (Tok.is(tok::l_paren)) {
2589 SourceLocation ConstructorLParen, ConstructorRParen;
2590 ExprVector ConstructorArgs;
2591 BalancedDelimiterTracker T(*this, tok::l_paren);
2593 ConstructorLParen = T.getOpenLocation();
2594 if (Tok.isNot(tok::r_paren)) {
2595 CommaLocsTy CommaLocs;
2596 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2597 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2602 ConstructorRParen = T.getCloseLocation();
2603 if (ConstructorRParen.isInvalid()) {
2604 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2607 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2610 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2611 Diag(Tok.getLocation(),
2612 diag::warn_cxx98_compat_generalized_initializer_lists);
2613 Initializer = ParseBraceInitializer();
2615 if (Initializer.isInvalid())
2618 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2619 PlacementArgs, PlacementRParen,
2620 TypeIdParens, DeclaratorInfo, Initializer.get());
2623 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2624 /// passed to ParseDeclaratorInternal.
2626 /// direct-new-declarator:
2627 /// '[' expression ']'
2628 /// direct-new-declarator '[' constant-expression ']'
2630 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2631 // Parse the array dimensions.
2633 while (Tok.is(tok::l_square)) {
2634 // An array-size expression can't start with a lambda.
2635 if (CheckProhibitedCXX11Attribute())
2638 BalancedDelimiterTracker T(*this, tok::l_square);
2641 ExprResult Size(first ? ParseExpression()
2642 : ParseConstantExpression());
2643 if (Size.isInvalid()) {
2645 SkipUntil(tok::r_square, StopAtSemi);
2652 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2653 ParsedAttributes Attrs(AttrFactory);
2654 MaybeParseCXX11Attributes(Attrs);
2656 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2657 /*static=*/false, /*star=*/false,
2659 T.getOpenLocation(),
2660 T.getCloseLocation()),
2661 Attrs, T.getCloseLocation());
2663 if (T.getCloseLocation().isInvalid())
2668 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2669 /// This ambiguity appears in the syntax of the C++ new operator.
2672 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2673 /// new-initializer[opt]
2676 /// '(' expression-list ')'
2678 bool Parser::ParseExpressionListOrTypeId(
2679 SmallVectorImpl<Expr*> &PlacementArgs,
2681 // The '(' was already consumed.
2682 if (isTypeIdInParens()) {
2683 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2684 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2686 return D.isInvalidType();
2689 // It's not a type, it has to be an expression list.
2690 // Discard the comma locations - ActOnCXXNew has enough parameters.
2691 CommaLocsTy CommaLocs;
2692 return ParseExpressionList(PlacementArgs, CommaLocs);
2695 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2696 /// to free memory allocated by new.
2698 /// This method is called to parse the 'delete' expression after the optional
2699 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2700 /// and "Start" is its location. Otherwise, "Start" is the location of the
2703 /// delete-expression:
2704 /// '::'[opt] 'delete' cast-expression
2705 /// '::'[opt] 'delete' '[' ']' cast-expression
2707 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2708 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2709 ConsumeToken(); // Consume 'delete'
2712 bool ArrayDelete = false;
2713 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2714 // C++11 [expr.delete]p1:
2715 // Whenever the delete keyword is followed by empty square brackets, it
2716 // shall be interpreted as [array delete].
2717 // [Footnote: A lambda expression with a lambda-introducer that consists
2718 // of empty square brackets can follow the delete keyword if
2719 // the lambda expression is enclosed in parentheses.]
2720 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2721 // lambda-introducer.
2723 BalancedDelimiterTracker T(*this, tok::l_square);
2727 if (T.getCloseLocation().isInvalid())
2731 ExprResult Operand(ParseCastExpression(false));
2732 if (Operand.isInvalid())
2735 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2738 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2740 default: llvm_unreachable("Not a known type trait");
2741 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2742 case tok::kw_ ## Spelling: return UTT_ ## Name;
2743 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2744 case tok::kw_ ## Spelling: return BTT_ ## Name;
2745 #include "clang/Basic/TokenKinds.def"
2746 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2747 case tok::kw_ ## Spelling: return TT_ ## Name;
2748 #include "clang/Basic/TokenKinds.def"
2752 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2754 default: llvm_unreachable("Not a known binary type trait");
2755 case tok::kw___array_rank: return ATT_ArrayRank;
2756 case tok::kw___array_extent: return ATT_ArrayExtent;
2760 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2762 default: llvm_unreachable("Not a known unary expression trait.");
2763 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2764 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2768 static unsigned TypeTraitArity(tok::TokenKind kind) {
2770 default: llvm_unreachable("Not a known type trait");
2771 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2772 #include "clang/Basic/TokenKinds.def"
2776 /// \brief Parse the built-in type-trait pseudo-functions that allow
2777 /// implementation of the TR1/C++11 type traits templates.
2779 /// primary-expression:
2780 /// unary-type-trait '(' type-id ')'
2781 /// binary-type-trait '(' type-id ',' type-id ')'
2782 /// type-trait '(' type-id-seq ')'
2785 /// type-id ...[opt] type-id-seq[opt]
2787 ExprResult Parser::ParseTypeTrait() {
2788 tok::TokenKind Kind = Tok.getKind();
2789 unsigned Arity = TypeTraitArity(Kind);
2791 SourceLocation Loc = ConsumeToken();
2793 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2794 if (Parens.expectAndConsume())
2797 SmallVector<ParsedType, 2> Args;
2799 // Parse the next type.
2800 TypeResult Ty = ParseTypeName();
2801 if (Ty.isInvalid()) {
2806 // Parse the ellipsis, if present.
2807 if (Tok.is(tok::ellipsis)) {
2808 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2809 if (Ty.isInvalid()) {
2815 // Add this type to the list of arguments.
2816 Args.push_back(Ty.get());
2817 } while (TryConsumeToken(tok::comma));
2819 if (Parens.consumeClose())
2822 SourceLocation EndLoc = Parens.getCloseLocation();
2824 if (Arity && Args.size() != Arity) {
2825 Diag(EndLoc, diag::err_type_trait_arity)
2826 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2830 if (!Arity && Args.empty()) {
2831 Diag(EndLoc, diag::err_type_trait_arity)
2832 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2836 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
2839 /// ParseArrayTypeTrait - Parse the built-in array type-trait
2840 /// pseudo-functions.
2842 /// primary-expression:
2843 /// [Embarcadero] '__array_rank' '(' type-id ')'
2844 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2846 ExprResult Parser::ParseArrayTypeTrait() {
2847 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2848 SourceLocation Loc = ConsumeToken();
2850 BalancedDelimiterTracker T(*this, tok::l_paren);
2851 if (T.expectAndConsume())
2854 TypeResult Ty = ParseTypeName();
2855 if (Ty.isInvalid()) {
2856 SkipUntil(tok::comma, StopAtSemi);
2857 SkipUntil(tok::r_paren, StopAtSemi);
2862 case ATT_ArrayRank: {
2864 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
2865 T.getCloseLocation());
2867 case ATT_ArrayExtent: {
2868 if (ExpectAndConsume(tok::comma)) {
2869 SkipUntil(tok::r_paren, StopAtSemi);
2873 ExprResult DimExpr = ParseExpression();
2876 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2877 T.getCloseLocation());
2880 llvm_unreachable("Invalid ArrayTypeTrait!");
2883 /// ParseExpressionTrait - Parse built-in expression-trait
2884 /// pseudo-functions like __is_lvalue_expr( xxx ).
2886 /// primary-expression:
2887 /// [Embarcadero] expression-trait '(' expression ')'
2889 ExprResult Parser::ParseExpressionTrait() {
2890 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2891 SourceLocation Loc = ConsumeToken();
2893 BalancedDelimiterTracker T(*this, tok::l_paren);
2894 if (T.expectAndConsume())
2897 ExprResult Expr = ParseExpression();
2901 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2902 T.getCloseLocation());
2906 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2907 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2908 /// based on the context past the parens.
2910 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
2912 BalancedDelimiterTracker &Tracker,
2913 ColonProtectionRAIIObject &ColonProt) {
2914 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
2915 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2916 assert(isTypeIdInParens() && "Not a type-id!");
2918 ExprResult Result(true);
2919 CastTy = ParsedType();
2921 // We need to disambiguate a very ugly part of the C++ syntax:
2923 // (T())x; - type-id
2924 // (T())*x; - type-id
2925 // (T())/x; - expression
2926 // (T()); - expression
2928 // The bad news is that we cannot use the specialized tentative parser, since
2929 // it can only verify that the thing inside the parens can be parsed as
2930 // type-id, it is not useful for determining the context past the parens.
2932 // The good news is that the parser can disambiguate this part without
2933 // making any unnecessary Action calls.
2935 // It uses a scheme similar to parsing inline methods. The parenthesized
2936 // tokens are cached, the context that follows is determined (possibly by
2937 // parsing a cast-expression), and then we re-introduce the cached tokens
2938 // into the token stream and parse them appropriately.
2940 ParenParseOption ParseAs;
2943 // Store the tokens of the parentheses. We will parse them after we determine
2944 // the context that follows them.
2945 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
2946 // We didn't find the ')' we expected.
2947 Tracker.consumeClose();
2951 if (Tok.is(tok::l_brace)) {
2952 ParseAs = CompoundLiteral;
2955 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2958 // Try parsing the cast-expression that may follow.
2959 // If it is not a cast-expression, NotCastExpr will be true and no token
2960 // will be consumed.
2961 ColonProt.restore();
2962 Result = ParseCastExpression(false/*isUnaryExpression*/,
2963 false/*isAddressofOperand*/,
2965 // type-id has priority.
2969 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2971 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
2974 // The current token should go after the cached tokens.
2975 Toks.push_back(Tok);
2976 // Re-enter the stored parenthesized tokens into the token stream, so we may
2978 PP.EnterTokenStream(Toks.data(), Toks.size(),
2979 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2980 // Drop the current token and bring the first cached one. It's the same token
2981 // as when we entered this function.
2984 if (ParseAs >= CompoundLiteral) {
2985 // Parse the type declarator.
2986 DeclSpec DS(AttrFactory);
2987 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2989 ColonProtectionRAIIObject InnerColonProtection(*this);
2990 ParseSpecifierQualifierList(DS);
2991 ParseDeclarator(DeclaratorInfo);
2995 Tracker.consumeClose();
2996 ColonProt.restore();
2998 if (ParseAs == CompoundLiteral) {
2999 ExprType = CompoundLiteral;
3000 if (DeclaratorInfo.isInvalidType())
3003 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3004 return ParseCompoundLiteralExpression(Ty.get(),
3005 Tracker.getOpenLocation(),
3006 Tracker.getCloseLocation());
3009 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3010 assert(ParseAs == CastExpr);
3012 if (DeclaratorInfo.isInvalidType())
3015 // Result is what ParseCastExpression returned earlier.
3016 if (!Result.isInvalid())
3017 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3018 DeclaratorInfo, CastTy,
3019 Tracker.getCloseLocation(), Result.get());
3023 // Not a compound literal, and not followed by a cast-expression.
3024 assert(ParseAs == SimpleExpr);
3026 ExprType = SimpleExpr;
3027 Result = ParseExpression();
3028 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3029 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3030 Tok.getLocation(), Result.get());
3033 if (Result.isInvalid()) {
3034 SkipUntil(tok::r_paren, StopAtSemi);
3038 Tracker.consumeClose();