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))
112 Token NextTok = GetLookAheadToken(1);
113 Token StarTok = NextTok;
114 // Check for (identifier or (*identifier
115 Token IdentifierTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : StarTok;
116 if (IdentifierTok.isNot(tok::identifier))
121 // Do we have a ')' ?
122 NextTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : GetLookAheadToken(1);
123 if (NextTok.is(tok::r_paren)) {
125 // Eat the '*' if it is present.
126 if (StarTok.is(tok::star))
128 // Eat the identifier.
130 // Add the identifier token back.
131 PP.EnterToken(IdentifierTok);
132 // Add the '*' back if it was present.
133 if (StarTok.is(tok::star))
134 PP.EnterToken(StarTok);
139 Diag(LParen.getLocation(), diag::err_paren_after_colon_colon)
140 << FixItHint::CreateRemoval(LParen.getLocation())
141 << FixItHint::CreateRemoval(RParen.getLocation());
144 /// \brief Parse global scope or nested-name-specifier if present.
146 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
147 /// may be preceded by '::'). Note that this routine will not parse ::new or
148 /// ::delete; it will just leave them in the token stream.
150 /// '::'[opt] nested-name-specifier
153 /// nested-name-specifier:
155 /// namespace-name '::'
156 /// nested-name-specifier identifier '::'
157 /// nested-name-specifier 'template'[opt] simple-template-id '::'
160 /// \param SS the scope specifier that will be set to the parsed
161 /// nested-name-specifier (or empty)
163 /// \param ObjectType if this nested-name-specifier is being parsed following
164 /// the "." or "->" of a member access expression, this parameter provides the
165 /// type of the object whose members are being accessed.
167 /// \param EnteringContext whether we will be entering into the context of
168 /// the nested-name-specifier after parsing it.
170 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
171 /// indicates whether this nested-name-specifier may be part of a
172 /// pseudo-destructor name. In this case, the flag will be set false
173 /// if we don't actually end up parsing a destructor name. Moreorover,
174 /// if we do end up determining that we are parsing a destructor name,
175 /// the last component of the nested-name-specifier is not parsed as
176 /// part of the scope specifier.
178 /// \param IsTypename If \c true, this nested-name-specifier is known to be
179 /// part of a type name. This is used to improve error recovery.
181 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
182 /// filled in with the leading identifier in the last component of the
183 /// nested-name-specifier, if any.
185 /// \returns true if there was an error parsing a scope specifier
186 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
187 ParsedType ObjectType,
188 bool EnteringContext,
189 bool *MayBePseudoDestructor,
191 IdentifierInfo **LastII) {
192 assert(getLangOpts().CPlusPlus &&
193 "Call sites of this function should be guarded by checking for C++");
195 if (Tok.is(tok::annot_cxxscope)) {
196 assert(!LastII && "want last identifier but have already annotated scope");
197 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
198 Tok.getAnnotationRange(),
204 if (Tok.is(tok::annot_template_id)) {
205 // If the current token is an annotated template id, it may already have
206 // a scope specifier. Restore it.
207 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
214 bool HasScopeSpecifier = false;
216 if (Tok.is(tok::coloncolon)) {
217 // ::new and ::delete aren't nested-name-specifiers.
218 tok::TokenKind NextKind = NextToken().getKind();
219 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
222 if (NextKind == tok::l_brace) {
223 // It is invalid to have :: {, consume the scope qualifier and pretend
224 // like we never saw it.
225 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
227 // '::' - Global scope qualifier.
228 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
231 CheckForLParenAfterColonColon();
233 HasScopeSpecifier = true;
237 if (Tok.is(tok::kw___super)) {
238 SourceLocation SuperLoc = ConsumeToken();
239 if (!Tok.is(tok::coloncolon)) {
240 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
244 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
247 bool CheckForDestructor = false;
248 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
249 CheckForDestructor = true;
250 *MayBePseudoDestructor = false;
253 if (!HasScopeSpecifier &&
254 (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))) {
255 DeclSpec DS(AttrFactory);
256 SourceLocation DeclLoc = Tok.getLocation();
257 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
259 SourceLocation CCLoc;
260 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
261 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
265 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
266 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
268 HasScopeSpecifier = true;
272 if (HasScopeSpecifier) {
273 // C++ [basic.lookup.classref]p5:
274 // If the qualified-id has the form
276 // ::class-name-or-namespace-name::...
278 // the class-name-or-namespace-name is looked up in global scope as a
279 // class-name or namespace-name.
281 // To implement this, we clear out the object type as soon as we've
282 // seen a leading '::' or part of a nested-name-specifier.
283 ObjectType = ParsedType();
285 if (Tok.is(tok::code_completion)) {
286 // Code completion for a nested-name-specifier, where the code
287 // code completion token follows the '::'.
288 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
289 // Include code completion token into the range of the scope otherwise
290 // when we try to annotate the scope tokens the dangling code completion
291 // token will cause assertion in
292 // Preprocessor::AnnotatePreviousCachedTokens.
293 SS.setEndLoc(Tok.getLocation());
299 // nested-name-specifier:
300 // nested-name-specifier 'template'[opt] simple-template-id '::'
302 // Parse the optional 'template' keyword, then make sure we have
303 // 'identifier <' after it.
304 if (Tok.is(tok::kw_template)) {
305 // If we don't have a scope specifier or an object type, this isn't a
306 // nested-name-specifier, since they aren't allowed to start with
308 if (!HasScopeSpecifier && !ObjectType)
311 TentativeParsingAction TPA(*this);
312 SourceLocation TemplateKWLoc = ConsumeToken();
314 UnqualifiedId TemplateName;
315 if (Tok.is(tok::identifier)) {
316 // Consume the identifier.
317 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
319 } else if (Tok.is(tok::kw_operator)) {
320 // We don't need to actually parse the unqualified-id in this case,
321 // because a simple-template-id cannot start with 'operator', but
322 // go ahead and parse it anyway for consistency with the case where
323 // we already annotated the template-id.
324 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
330 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
331 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
332 Diag(TemplateName.getSourceRange().getBegin(),
333 diag::err_id_after_template_in_nested_name_spec)
334 << TemplateName.getSourceRange();
343 // If the next token is not '<', we have a qualified-id that refers
344 // to a template name, such as T::template apply, but is not a
346 if (Tok.isNot(tok::less)) {
351 // Commit to parsing the template-id.
354 if (TemplateNameKind TNK
355 = Actions.ActOnDependentTemplateName(getCurScope(),
356 SS, TemplateKWLoc, TemplateName,
357 ObjectType, EnteringContext,
359 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
360 TemplateName, false))
368 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
373 // So we need to check whether the template-id is a simple-template-id of
374 // the right kind (it should name a type or be dependent), and then
375 // convert it into a type within the nested-name-specifier.
376 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
377 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
378 *MayBePseudoDestructor = true;
383 *LastII = TemplateId->Name;
385 // Consume the template-id token.
388 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
389 SourceLocation CCLoc = ConsumeToken();
391 HasScopeSpecifier = true;
393 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
394 TemplateId->NumArgs);
396 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
398 TemplateId->TemplateKWLoc,
399 TemplateId->Template,
400 TemplateId->TemplateNameLoc,
401 TemplateId->LAngleLoc,
403 TemplateId->RAngleLoc,
406 SourceLocation StartLoc
407 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
408 : TemplateId->TemplateNameLoc;
409 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
415 // The rest of the nested-name-specifier possibilities start with
417 if (Tok.isNot(tok::identifier))
420 IdentifierInfo &II = *Tok.getIdentifierInfo();
422 // nested-name-specifier:
424 // namespace-name '::'
425 // nested-name-specifier identifier '::'
426 Token Next = NextToken();
428 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
429 // and emit a fixit hint for it.
430 if (Next.is(tok::colon) && !ColonIsSacred) {
431 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
433 Next.getLocation(), ObjectType,
435 // If the token after the colon isn't an identifier, it's still an
436 // error, but they probably meant something else strange so don't
437 // recover like this.
438 PP.LookAhead(1).is(tok::identifier)) {
439 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
440 << FixItHint::CreateReplacement(Next.getLocation(), "::");
441 // Recover as if the user wrote '::'.
442 Next.setKind(tok::coloncolon);
446 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
447 // It is invalid to have :: {, consume the scope qualifier and pretend
448 // like we never saw it.
449 Token Identifier = Tok; // Stash away the identifier.
450 ConsumeToken(); // Eat the identifier, current token is now '::'.
451 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
453 UnconsumeToken(Identifier); // Stick the identifier back.
454 Next = NextToken(); // Point Next at the '{' token.
457 if (Next.is(tok::coloncolon)) {
458 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
459 !Actions.isNonTypeNestedNameSpecifier(
460 getCurScope(), SS, Tok.getLocation(), II, ObjectType)) {
461 *MayBePseudoDestructor = true;
466 const Token &Next2 = GetLookAheadToken(2);
467 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
468 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
469 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
471 << FixItHint::CreateReplacement(Next.getLocation(), ":");
474 ColonColon.setKind(tok::colon);
475 PP.EnterToken(ColonColon);
483 // We have an identifier followed by a '::'. Lookup this name
484 // as the name in a nested-name-specifier.
485 Token Identifier = Tok;
486 SourceLocation IdLoc = ConsumeToken();
487 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
488 "NextToken() not working properly!");
489 Token ColonColon = Tok;
490 SourceLocation CCLoc = ConsumeToken();
492 CheckForLParenAfterColonColon();
494 bool IsCorrectedToColon = false;
495 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
496 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
497 ObjectType, EnteringContext, SS,
498 false, CorrectionFlagPtr)) {
499 // Identifier is not recognized as a nested name, but we can have
500 // mistyped '::' instead of ':'.
501 if (CorrectionFlagPtr && IsCorrectedToColon) {
502 ColonColon.setKind(tok::colon);
504 PP.EnterToken(ColonColon);
508 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
510 HasScopeSpecifier = true;
514 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
516 // nested-name-specifier:
518 if (Next.is(tok::less)) {
520 UnqualifiedId TemplateName;
521 TemplateName.setIdentifier(&II, Tok.getLocation());
522 bool MemberOfUnknownSpecialization;
523 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
524 /*hasTemplateKeyword=*/false,
529 MemberOfUnknownSpecialization)) {
530 // We have found a template name, so annotate this token
531 // with a template-id annotation. We do not permit the
532 // template-id to be translated into a type annotation,
533 // because some clients (e.g., the parsing of class template
534 // specializations) still want to see the original template-id
537 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
538 TemplateName, false))
543 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
544 (IsTypename || IsTemplateArgumentList(1))) {
545 // We have something like t::getAs<T>, where getAs is a
546 // member of an unknown specialization. However, this will only
547 // parse correctly as a template, so suggest the keyword 'template'
548 // before 'getAs' and treat this as a dependent template name.
549 unsigned DiagID = diag::err_missing_dependent_template_keyword;
550 if (getLangOpts().MicrosoftExt)
551 DiagID = diag::warn_missing_dependent_template_keyword;
553 Diag(Tok.getLocation(), DiagID)
555 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
557 if (TemplateNameKind TNK
558 = Actions.ActOnDependentTemplateName(getCurScope(),
559 SS, SourceLocation(),
560 TemplateName, ObjectType,
561 EnteringContext, Template)) {
562 // Consume the identifier.
564 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
565 TemplateName, false))
575 // We don't have any tokens that form the beginning of a
576 // nested-name-specifier, so we're done.
580 // Even if we didn't see any pieces of a nested-name-specifier, we
581 // still check whether there is a tilde in this position, which
582 // indicates a potential pseudo-destructor.
583 if (CheckForDestructor && Tok.is(tok::tilde))
584 *MayBePseudoDestructor = true;
589 ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
590 Token &Replacement) {
591 SourceLocation TemplateKWLoc;
593 if (ParseUnqualifiedId(SS,
594 /*EnteringContext=*/false,
595 /*AllowDestructorName=*/false,
596 /*AllowConstructorName=*/false,
597 /*ObjectType=*/ParsedType(), TemplateKWLoc, Name))
600 // This is only the direct operand of an & operator if it is not
601 // followed by a postfix-expression suffix.
602 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
603 isAddressOfOperand = false;
605 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
606 Tok.is(tok::l_paren), isAddressOfOperand,
607 nullptr, /*IsInlineAsmIdentifier=*/false,
611 /// ParseCXXIdExpression - Handle id-expression.
618 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
620 /// '::' operator-function-id
623 /// NOTE: The standard specifies that, for qualified-id, the parser does not
626 /// '::' conversion-function-id
627 /// '::' '~' class-name
629 /// This may cause a slight inconsistency on diagnostics:
634 /// :: A :: ~ C(); // Some Sema error about using destructor with a
636 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
639 /// We simplify the parser a bit and make it work like:
642 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
643 /// '::' unqualified-id
645 /// That way Sema can handle and report similar errors for namespaces and the
648 /// The isAddressOfOperand parameter indicates that this id-expression is a
649 /// direct operand of the address-of operator. This is, besides member contexts,
650 /// the only place where a qualified-id naming a non-static class member may
653 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
655 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
656 // '::' unqualified-id
659 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
662 ExprResult Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
663 if (Result.isUnset()) {
664 // If the ExprResult is valid but null, then typo correction suggested a
665 // keyword replacement that needs to be reparsed.
666 UnconsumeToken(Replacement);
667 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
669 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
670 "for a previous keyword suggestion");
674 /// ParseLambdaExpression - Parse a C++11 lambda expression.
676 /// lambda-expression:
677 /// lambda-introducer lambda-declarator[opt] compound-statement
679 /// lambda-introducer:
680 /// '[' lambda-capture[opt] ']'
685 /// capture-default ',' capture-list
693 /// capture-list ',' capture
697 /// init-capture [C++1y]
704 /// init-capture: [C++1y]
705 /// identifier initializer
706 /// '&' identifier initializer
708 /// lambda-declarator:
709 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
710 /// 'mutable'[opt] exception-specification[opt]
711 /// trailing-return-type[opt]
713 ExprResult Parser::ParseLambdaExpression() {
714 // Parse lambda-introducer.
715 LambdaIntroducer Intro;
716 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
718 Diag(Tok, DiagID.getValue());
719 SkipUntil(tok::r_square, StopAtSemi);
720 SkipUntil(tok::l_brace, StopAtSemi);
721 SkipUntil(tok::r_brace, StopAtSemi);
725 return ParseLambdaExpressionAfterIntroducer(Intro);
728 /// TryParseLambdaExpression - Use lookahead and potentially tentative
729 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
732 /// If we are not looking at a lambda expression, returns ExprError().
733 ExprResult Parser::TryParseLambdaExpression() {
734 assert(getLangOpts().CPlusPlus11
735 && Tok.is(tok::l_square)
736 && "Not at the start of a possible lambda expression.");
738 const Token Next = NextToken(), After = GetLookAheadToken(2);
740 // If lookahead indicates this is a lambda...
741 if (Next.is(tok::r_square) || // []
742 Next.is(tok::equal) || // [=
743 (Next.is(tok::amp) && // [&] or [&,
744 (After.is(tok::r_square) ||
745 After.is(tok::comma))) ||
746 (Next.is(tok::identifier) && // [identifier]
747 After.is(tok::r_square))) {
748 return ParseLambdaExpression();
751 // If lookahead indicates an ObjC message send...
752 // [identifier identifier
753 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
757 // Here, we're stuck: lambda introducers and Objective-C message sends are
758 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
759 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
760 // writing two routines to parse a lambda introducer, just try to parse
761 // a lambda introducer first, and fall back if that fails.
762 // (TryParseLambdaIntroducer never produces any diagnostic output.)
763 LambdaIntroducer Intro;
764 if (TryParseLambdaIntroducer(Intro))
767 return ParseLambdaExpressionAfterIntroducer(Intro);
770 /// \brief Parse a lambda introducer.
771 /// \param Intro A LambdaIntroducer filled in with information about the
772 /// contents of the lambda-introducer.
773 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
774 /// message send and a lambda expression. In this mode, we will
775 /// sometimes skip the initializers for init-captures and not fully
776 /// populate \p Intro. This flag will be set to \c true if we do so.
777 /// \return A DiagnosticID if it hit something unexpected. The location for
778 /// for the diagnostic is that of the current token.
779 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
780 bool *SkippedInits) {
781 typedef Optional<unsigned> DiagResult;
783 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
784 BalancedDelimiterTracker T(*this, tok::l_square);
787 Intro.Range.setBegin(T.getOpenLocation());
791 // Parse capture-default.
792 if (Tok.is(tok::amp) &&
793 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
794 Intro.Default = LCD_ByRef;
795 Intro.DefaultLoc = ConsumeToken();
797 } else if (Tok.is(tok::equal)) {
798 Intro.Default = LCD_ByCopy;
799 Intro.DefaultLoc = ConsumeToken();
803 while (Tok.isNot(tok::r_square)) {
805 if (Tok.isNot(tok::comma)) {
806 // Provide a completion for a lambda introducer here. Except
807 // in Objective-C, where this is Almost Surely meant to be a message
808 // send. In that case, fail here and let the ObjC message
809 // expression parser perform the completion.
810 if (Tok.is(tok::code_completion) &&
811 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
812 !Intro.Captures.empty())) {
813 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
814 /*AfterAmpersand=*/false);
819 return DiagResult(diag::err_expected_comma_or_rsquare);
824 if (Tok.is(tok::code_completion)) {
825 // If we're in Objective-C++ and we have a bare '[', then this is more
826 // likely to be a message receiver.
827 if (getLangOpts().ObjC1 && first)
828 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
830 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
831 /*AfterAmpersand=*/false);
839 LambdaCaptureKind Kind = LCK_ByCopy;
841 IdentifierInfo *Id = nullptr;
842 SourceLocation EllipsisLoc;
845 if (Tok.is(tok::kw_this)) {
847 Loc = ConsumeToken();
849 if (Tok.is(tok::amp)) {
853 if (Tok.is(tok::code_completion)) {
854 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
855 /*AfterAmpersand=*/true);
861 if (Tok.is(tok::identifier)) {
862 Id = Tok.getIdentifierInfo();
863 Loc = ConsumeToken();
864 } else if (Tok.is(tok::kw_this)) {
865 // FIXME: If we want to suggest a fixit here, will need to return more
866 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
867 // Clear()ed to prevent emission in case of tentative parsing?
868 return DiagResult(diag::err_this_captured_by_reference);
870 return DiagResult(diag::err_expected_capture);
873 if (Tok.is(tok::l_paren)) {
874 BalancedDelimiterTracker Parens(*this, tok::l_paren);
875 Parens.consumeOpen();
881 *SkippedInits = true;
882 } else if (ParseExpressionList(Exprs, Commas)) {
886 Parens.consumeClose();
887 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
888 Parens.getCloseLocation(),
891 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
892 // Each lambda init-capture forms its own full expression, which clears
893 // Actions.MaybeODRUseExprs. So create an expression evaluation context
894 // to save the necessary state, and restore it later.
895 EnterExpressionEvaluationContext EC(Actions,
896 Sema::PotentiallyEvaluated);
897 bool HadEquals = TryConsumeToken(tok::equal);
900 // Warn on constructs that will change meaning when we implement N3922
901 if (!HadEquals && Tok.is(tok::l_brace)) {
902 Diag(Tok, diag::warn_init_capture_direct_list_init)
903 << FixItHint::CreateInsertion(Tok.getLocation(), "=");
905 Init = ParseInitializer();
906 } else if (Tok.is(tok::l_brace)) {
907 BalancedDelimiterTracker Braces(*this, tok::l_brace);
908 Braces.consumeOpen();
910 *SkippedInits = true;
912 // We're disambiguating this:
916 // We need to find the end of the following expression in order to
917 // determine whether this is an Obj-C message send's receiver, a
918 // C99 designator, or a lambda init-capture.
920 // Parse the expression to find where it ends, and annotate it back
921 // onto the tokens. We would have parsed this expression the same way
922 // in either case: both the RHS of an init-capture and the RHS of an
923 // assignment expression are parsed as an initializer-clause, and in
924 // neither case can anything be added to the scope between the '[' and
927 // FIXME: This is horrible. Adding a mechanism to skip an expression
928 // would be much cleaner.
929 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
930 // that instead. (And if we see a ':' with no matching '?', we can
931 // classify this as an Obj-C message send.)
932 SourceLocation StartLoc = Tok.getLocation();
933 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
934 Init = ParseInitializer();
936 if (Tok.getLocation() != StartLoc) {
937 // Back out the lexing of the token after the initializer.
938 PP.RevertCachedTokens(1);
940 // Replace the consumed tokens with an appropriate annotation.
941 Tok.setLocation(StartLoc);
942 Tok.setKind(tok::annot_primary_expr);
943 setExprAnnotation(Tok, Init);
944 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
945 PP.AnnotateCachedTokens(Tok);
947 // Consume the annotated initializer.
952 TryConsumeToken(tok::ellipsis, EllipsisLoc);
954 // If this is an init capture, process the initialization expression
955 // right away. For lambda init-captures such as the following:
957 // auto L = [i = x+1](int a) {
959 // &k = x](char b) { };
961 // keep in mind that each lambda init-capture has to have:
962 // - its initialization expression executed in the context
963 // of the enclosing/parent decl-context.
964 // - but the variable itself has to be 'injected' into the
965 // decl-context of its lambda's call-operator (which has
966 // not yet been created).
967 // Each init-expression is a full-expression that has to get
968 // Sema-analyzed (for capturing etc.) before its lambda's
969 // call-operator's decl-context, scope & scopeinfo are pushed on their
970 // respective stacks. Thus if any variable is odr-used in the init-capture
971 // it will correctly get captured in the enclosing lambda, if one exists.
972 // The init-variables above are created later once the lambdascope and
973 // call-operators decl-context is pushed onto its respective stack.
975 // Since the lambda init-capture's initializer expression occurs in the
976 // context of the enclosing function or lambda, therefore we can not wait
977 // till a lambda scope has been pushed on before deciding whether the
978 // variable needs to be captured. We also need to process all
979 // lvalue-to-rvalue conversions and discarded-value conversions,
980 // so that we can avoid capturing certain constant variables.
984 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
985 // return [y = x](int i) { <-- don't capture by enclosing lambda
989 // If x was not const, the second use would require 'L' to capture, and
990 // that would be an error.
992 ParsedType InitCaptureParsedType;
993 if (Init.isUsable()) {
994 // Get the pointer and store it in an lvalue, so we can use it as an
996 Expr *InitExpr = Init.get();
997 // This performs any lvalue-to-rvalue conversions if necessary, which
998 // can affect what gets captured in the containing decl-context.
999 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
1000 Loc, Kind == LCK_ByRef, Id, InitExpr);
1002 InitCaptureParsedType.set(InitCaptureType);
1004 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
1008 Intro.Range.setEnd(T.getCloseLocation());
1009 return DiagResult();
1012 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
1014 /// Returns true if it hit something unexpected.
1015 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1016 TentativeParsingAction PA(*this);
1018 bool SkippedInits = false;
1019 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
1027 // Parse it again, but this time parse the init-captures too.
1029 Intro = LambdaIntroducer();
1030 DiagID = ParseLambdaIntroducer(Intro);
1031 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1039 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1041 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1042 LambdaIntroducer &Intro) {
1043 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1044 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1046 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1047 "lambda expression parsing");
1051 // FIXME: Call into Actions to add any init-capture declarations to the
1052 // scope while parsing the lambda-declarator and compound-statement.
1054 // Parse lambda-declarator[opt].
1055 DeclSpec DS(AttrFactory);
1056 Declarator D(DS, Declarator::LambdaExprContext);
1057 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1058 Actions.PushLambdaScope();
1060 TypeResult TrailingReturnType;
1061 if (Tok.is(tok::l_paren)) {
1062 ParseScope PrototypeScope(this,
1063 Scope::FunctionPrototypeScope |
1064 Scope::FunctionDeclarationScope |
1067 SourceLocation DeclEndLoc;
1068 BalancedDelimiterTracker T(*this, tok::l_paren);
1070 SourceLocation LParenLoc = T.getOpenLocation();
1072 // Parse parameter-declaration-clause.
1073 ParsedAttributes Attr(AttrFactory);
1074 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1075 SourceLocation EllipsisLoc;
1077 if (Tok.isNot(tok::r_paren)) {
1078 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1079 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1080 // For a generic lambda, each 'auto' within the parameter declaration
1081 // clause creates a template type parameter, so increment the depth.
1082 if (Actions.getCurGenericLambda())
1083 ++CurTemplateDepthTracker;
1086 SourceLocation RParenLoc = T.getCloseLocation();
1087 DeclEndLoc = RParenLoc;
1089 // GNU-style attributes must be parsed before the mutable specifier to be
1090 // compatible with GCC.
1091 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1093 // Parse 'mutable'[opt].
1094 SourceLocation MutableLoc;
1095 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
1096 DeclEndLoc = MutableLoc;
1098 // Parse exception-specification[opt].
1099 ExceptionSpecificationType ESpecType = EST_None;
1100 SourceRange ESpecRange;
1101 SmallVector<ParsedType, 2> DynamicExceptions;
1102 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1103 ExprResult NoexceptExpr;
1104 CachedTokens *ExceptionSpecTokens;
1105 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1108 DynamicExceptionRanges,
1110 ExceptionSpecTokens);
1112 if (ESpecType != EST_None)
1113 DeclEndLoc = ESpecRange.getEnd();
1115 // Parse attribute-specifier[opt].
1116 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1118 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1120 // Parse trailing-return-type[opt].
1121 if (Tok.is(tok::arrow)) {
1122 FunLocalRangeEnd = Tok.getLocation();
1124 TrailingReturnType = ParseTrailingReturnType(Range);
1125 if (Range.getEnd().isValid())
1126 DeclEndLoc = Range.getEnd();
1129 PrototypeScope.Exit();
1131 SourceLocation NoLoc;
1132 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1133 /*isAmbiguous=*/false,
1135 ParamInfo.data(), ParamInfo.size(),
1136 EllipsisLoc, RParenLoc,
1137 DS.getTypeQualifiers(),
1138 /*RefQualifierIsLValueRef=*/true,
1139 /*RefQualifierLoc=*/NoLoc,
1140 /*ConstQualifierLoc=*/NoLoc,
1141 /*VolatileQualifierLoc=*/NoLoc,
1142 /*RestrictQualifierLoc=*/NoLoc,
1144 ESpecType, ESpecRange.getBegin(),
1145 DynamicExceptions.data(),
1146 DynamicExceptionRanges.data(),
1147 DynamicExceptions.size(),
1148 NoexceptExpr.isUsable() ?
1149 NoexceptExpr.get() : nullptr,
1150 /*ExceptionSpecTokens*/nullptr,
1151 LParenLoc, FunLocalRangeEnd, D,
1152 TrailingReturnType),
1154 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow) ||
1155 Tok.is(tok::kw___attribute) ||
1156 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1157 // It's common to forget that one needs '()' before 'mutable', an attribute
1158 // specifier, or the result type. Deal with this.
1159 unsigned TokKind = 0;
1160 switch (Tok.getKind()) {
1161 case tok::kw_mutable: TokKind = 0; break;
1162 case tok::arrow: TokKind = 1; break;
1163 case tok::kw___attribute:
1164 case tok::l_square: TokKind = 2; break;
1165 default: llvm_unreachable("Unknown token kind");
1168 Diag(Tok, diag::err_lambda_missing_parens)
1170 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1171 SourceLocation DeclLoc = Tok.getLocation();
1172 SourceLocation DeclEndLoc = DeclLoc;
1174 // GNU-style attributes must be parsed before the mutable specifier to be
1175 // compatible with GCC.
1176 ParsedAttributes Attr(AttrFactory);
1177 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1179 // Parse 'mutable', if it's there.
1180 SourceLocation MutableLoc;
1181 if (Tok.is(tok::kw_mutable)) {
1182 MutableLoc = ConsumeToken();
1183 DeclEndLoc = MutableLoc;
1186 // Parse attribute-specifier[opt].
1187 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1189 // Parse the return type, if there is one.
1190 if (Tok.is(tok::arrow)) {
1192 TrailingReturnType = ParseTrailingReturnType(Range);
1193 if (Range.getEnd().isValid())
1194 DeclEndLoc = Range.getEnd();
1197 SourceLocation NoLoc;
1198 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1199 /*isAmbiguous=*/false,
1200 /*LParenLoc=*/NoLoc,
1203 /*EllipsisLoc=*/NoLoc,
1204 /*RParenLoc=*/NoLoc,
1206 /*RefQualifierIsLValueRef=*/true,
1207 /*RefQualifierLoc=*/NoLoc,
1208 /*ConstQualifierLoc=*/NoLoc,
1209 /*VolatileQualifierLoc=*/NoLoc,
1210 /*RestrictQualifierLoc=*/NoLoc,
1214 /*Exceptions=*/nullptr,
1215 /*ExceptionRanges=*/nullptr,
1216 /*NumExceptions=*/0,
1217 /*NoexceptExpr=*/nullptr,
1218 /*ExceptionSpecTokens=*/nullptr,
1219 DeclLoc, DeclEndLoc, D,
1220 TrailingReturnType),
1225 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1227 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
1228 ParseScope BodyScope(this, ScopeFlags);
1230 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1232 // Parse compound-statement.
1233 if (!Tok.is(tok::l_brace)) {
1234 Diag(Tok, diag::err_expected_lambda_body);
1235 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1239 StmtResult Stmt(ParseCompoundStatementBody());
1242 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1243 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1245 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1249 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1252 /// postfix-expression: [C++ 5.2p1]
1253 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1254 /// 'static_cast' '<' type-name '>' '(' expression ')'
1255 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1256 /// 'const_cast' '<' type-name '>' '(' expression ')'
1258 ExprResult Parser::ParseCXXCasts() {
1259 tok::TokenKind Kind = Tok.getKind();
1260 const char *CastName = nullptr; // For error messages
1263 default: llvm_unreachable("Unknown C++ cast!");
1264 case tok::kw_const_cast: CastName = "const_cast"; break;
1265 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1266 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1267 case tok::kw_static_cast: CastName = "static_cast"; break;
1270 SourceLocation OpLoc = ConsumeToken();
1271 SourceLocation LAngleBracketLoc = Tok.getLocation();
1273 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1274 // diagnose error, suggest fix, and recover parsing.
1275 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1276 Token Next = NextToken();
1277 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1278 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1281 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1284 // Parse the common declaration-specifiers piece.
1285 DeclSpec DS(AttrFactory);
1286 ParseSpecifierQualifierList(DS);
1288 // Parse the abstract-declarator, if present.
1289 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1290 ParseDeclarator(DeclaratorInfo);
1292 SourceLocation RAngleBracketLoc = Tok.getLocation();
1294 if (ExpectAndConsume(tok::greater))
1295 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1297 SourceLocation LParenLoc, RParenLoc;
1298 BalancedDelimiterTracker T(*this, tok::l_paren);
1300 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1303 ExprResult Result = ParseExpression();
1308 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1309 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1310 LAngleBracketLoc, DeclaratorInfo,
1312 T.getOpenLocation(), Result.get(),
1313 T.getCloseLocation());
1318 /// ParseCXXTypeid - This handles the C++ typeid expression.
1320 /// postfix-expression: [C++ 5.2p1]
1321 /// 'typeid' '(' expression ')'
1322 /// 'typeid' '(' type-id ')'
1324 ExprResult Parser::ParseCXXTypeid() {
1325 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1327 SourceLocation OpLoc = ConsumeToken();
1328 SourceLocation LParenLoc, RParenLoc;
1329 BalancedDelimiterTracker T(*this, tok::l_paren);
1331 // typeid expressions are always parenthesized.
1332 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1334 LParenLoc = T.getOpenLocation();
1338 // C++0x [expr.typeid]p3:
1339 // When typeid is applied to an expression other than an lvalue of a
1340 // polymorphic class type [...] The expression is an unevaluated
1341 // operand (Clause 5).
1343 // Note that we can't tell whether the expression is an lvalue of a
1344 // polymorphic class type until after we've parsed the expression; we
1345 // speculatively assume the subexpression is unevaluated, and fix it up
1348 // We enter the unevaluated context before trying to determine whether we
1349 // have a type-id, because the tentative parse logic will try to resolve
1350 // names, and must treat them as unevaluated.
1351 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1352 Sema::ReuseLambdaContextDecl);
1354 if (isTypeIdInParens()) {
1355 TypeResult Ty = ParseTypeName();
1359 RParenLoc = T.getCloseLocation();
1360 if (Ty.isInvalid() || RParenLoc.isInvalid())
1363 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1364 Ty.get().getAsOpaquePtr(), RParenLoc);
1366 Result = ParseExpression();
1369 if (Result.isInvalid())
1370 SkipUntil(tok::r_paren, StopAtSemi);
1373 RParenLoc = T.getCloseLocation();
1374 if (RParenLoc.isInvalid())
1377 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1378 Result.get(), RParenLoc);
1385 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1387 /// '__uuidof' '(' expression ')'
1388 /// '__uuidof' '(' type-id ')'
1390 ExprResult Parser::ParseCXXUuidof() {
1391 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1393 SourceLocation OpLoc = ConsumeToken();
1394 BalancedDelimiterTracker T(*this, tok::l_paren);
1396 // __uuidof expressions are always parenthesized.
1397 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1402 if (isTypeIdInParens()) {
1403 TypeResult Ty = ParseTypeName();
1411 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1412 Ty.get().getAsOpaquePtr(),
1413 T.getCloseLocation());
1415 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1416 Result = ParseExpression();
1419 if (Result.isInvalid())
1420 SkipUntil(tok::r_paren, StopAtSemi);
1424 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1426 Result.get(), T.getCloseLocation());
1433 /// \brief Parse a C++ pseudo-destructor expression after the base,
1434 /// . or -> operator, and nested-name-specifier have already been
1437 /// postfix-expression: [C++ 5.2]
1438 /// postfix-expression . pseudo-destructor-name
1439 /// postfix-expression -> pseudo-destructor-name
1441 /// pseudo-destructor-name:
1442 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1443 /// ::[opt] nested-name-specifier template simple-template-id ::
1445 /// ::[opt] nested-name-specifier[opt] ~type-name
1448 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1449 tok::TokenKind OpKind,
1451 ParsedType ObjectType) {
1452 // We're parsing either a pseudo-destructor-name or a dependent
1453 // member access that has the same form as a
1454 // pseudo-destructor-name. We parse both in the same way and let
1455 // the action model sort them out.
1457 // Note that the ::[opt] nested-name-specifier[opt] has already
1458 // been parsed, and if there was a simple-template-id, it has
1459 // been coalesced into a template-id annotation token.
1460 UnqualifiedId FirstTypeName;
1461 SourceLocation CCLoc;
1462 if (Tok.is(tok::identifier)) {
1463 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1465 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1466 CCLoc = ConsumeToken();
1467 } else if (Tok.is(tok::annot_template_id)) {
1468 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1469 // store it in the pseudo-dtor node (to be used when instantiating it).
1470 FirstTypeName.setTemplateId(
1471 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1473 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1474 CCLoc = ConsumeToken();
1476 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1480 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1481 SourceLocation TildeLoc = ConsumeToken();
1483 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1484 DeclSpec DS(AttrFactory);
1485 ParseDecltypeSpecifier(DS);
1486 if (DS.getTypeSpecType() == TST_error)
1488 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1489 OpKind, TildeLoc, DS,
1490 Tok.is(tok::l_paren));
1493 if (!Tok.is(tok::identifier)) {
1494 Diag(Tok, diag::err_destructor_tilde_identifier);
1498 // Parse the second type.
1499 UnqualifiedId SecondTypeName;
1500 IdentifierInfo *Name = Tok.getIdentifierInfo();
1501 SourceLocation NameLoc = ConsumeToken();
1502 SecondTypeName.setIdentifier(Name, NameLoc);
1504 // If there is a '<', the second type name is a template-id. Parse
1506 if (Tok.is(tok::less) &&
1507 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1509 false, ObjectType, SecondTypeName,
1510 /*AssumeTemplateName=*/true))
1513 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1515 SS, FirstTypeName, CCLoc,
1516 TildeLoc, SecondTypeName,
1517 Tok.is(tok::l_paren));
1520 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1522 /// boolean-literal: [C++ 2.13.5]
1525 ExprResult Parser::ParseCXXBoolLiteral() {
1526 tok::TokenKind Kind = Tok.getKind();
1527 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1530 /// ParseThrowExpression - This handles the C++ throw expression.
1532 /// throw-expression: [C++ 15]
1533 /// 'throw' assignment-expression[opt]
1534 ExprResult Parser::ParseThrowExpression() {
1535 assert(Tok.is(tok::kw_throw) && "Not throw!");
1536 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1538 // If the current token isn't the start of an assignment-expression,
1539 // then the expression is not present. This handles things like:
1540 // "C ? throw : (void)42", which is crazy but legal.
1541 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1548 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1551 ExprResult Expr(ParseAssignmentExpression());
1552 if (Expr.isInvalid()) return Expr;
1553 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1557 /// ParseCXXThis - This handles the C++ 'this' pointer.
1559 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1560 /// a non-lvalue expression whose value is the address of the object for which
1561 /// the function is called.
1562 ExprResult Parser::ParseCXXThis() {
1563 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1564 SourceLocation ThisLoc = ConsumeToken();
1565 return Actions.ActOnCXXThis(ThisLoc);
1568 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1569 /// Can be interpreted either as function-style casting ("int(x)")
1570 /// or class type construction ("ClassType(x,y,z)")
1571 /// or creation of a value-initialized type ("int()").
1572 /// See [C++ 5.2.3].
1574 /// postfix-expression: [C++ 5.2p1]
1575 /// simple-type-specifier '(' expression-list[opt] ')'
1576 /// [C++0x] simple-type-specifier braced-init-list
1577 /// typename-specifier '(' expression-list[opt] ')'
1578 /// [C++0x] typename-specifier braced-init-list
1581 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1582 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1583 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1585 assert((Tok.is(tok::l_paren) ||
1586 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1587 && "Expected '(' or '{'!");
1589 if (Tok.is(tok::l_brace)) {
1590 ExprResult Init = ParseBraceInitializer();
1591 if (Init.isInvalid())
1593 Expr *InitList = Init.get();
1594 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1595 MultiExprArg(&InitList, 1),
1598 BalancedDelimiterTracker T(*this, tok::l_paren);
1602 CommaLocsTy CommaLocs;
1604 if (Tok.isNot(tok::r_paren)) {
1605 if (ParseExpressionList(Exprs, CommaLocs)) {
1606 SkipUntil(tok::r_paren, StopAtSemi);
1614 // TypeRep could be null, if it references an invalid typedef.
1618 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1619 "Unexpected number of commas!");
1620 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1622 T.getCloseLocation());
1626 /// ParseCXXCondition - if/switch/while condition expression.
1630 /// type-specifier-seq declarator '=' assignment-expression
1631 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1632 /// [C++11] type-specifier-seq declarator braced-init-list
1633 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1634 /// '=' assignment-expression
1636 /// \param ExprOut if the condition was parsed as an expression, the parsed
1639 /// \param DeclOut if the condition was parsed as a declaration, the parsed
1642 /// \param Loc The location of the start of the statement that requires this
1643 /// condition, e.g., the "for" in a for loop.
1645 /// \param ConvertToBoolean Whether the condition expression should be
1646 /// converted to a boolean value.
1648 /// \returns true if there was a parsing, false otherwise.
1649 bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1652 bool ConvertToBoolean) {
1653 if (Tok.is(tok::code_completion)) {
1654 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1659 ParsedAttributesWithRange attrs(AttrFactory);
1660 MaybeParseCXX11Attributes(attrs);
1662 if (!isCXXConditionDeclaration()) {
1663 ProhibitAttributes(attrs);
1665 // Parse the expression.
1666 ExprOut = ParseExpression(); // expression
1668 if (ExprOut.isInvalid())
1671 // If required, convert to a boolean value.
1672 if (ConvertToBoolean)
1674 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1675 return ExprOut.isInvalid();
1678 // type-specifier-seq
1679 DeclSpec DS(AttrFactory);
1680 DS.takeAttributesFrom(attrs);
1681 ParseSpecifierQualifierList(DS);
1684 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1685 ParseDeclarator(DeclaratorInfo);
1687 // simple-asm-expr[opt]
1688 if (Tok.is(tok::kw_asm)) {
1690 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1691 if (AsmLabel.isInvalid()) {
1692 SkipUntil(tok::semi, StopAtSemi);
1695 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1696 DeclaratorInfo.SetRangeEnd(Loc);
1699 // If attributes are present, parse them.
1700 MaybeParseGNUAttributes(DeclaratorInfo);
1702 // Type-check the declaration itself.
1703 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1705 DeclOut = Dcl.get();
1706 ExprOut = ExprError();
1708 // '=' assignment-expression
1709 // If a '==' or '+=' is found, suggest a fixit to '='.
1710 bool CopyInitialization = isTokenEqualOrEqualTypo();
1711 if (CopyInitialization)
1714 ExprResult InitExpr = ExprError();
1715 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1716 Diag(Tok.getLocation(),
1717 diag::warn_cxx98_compat_generalized_initializer_lists);
1718 InitExpr = ParseBraceInitializer();
1719 } else if (CopyInitialization) {
1720 InitExpr = ParseAssignmentExpression();
1721 } else if (Tok.is(tok::l_paren)) {
1722 // This was probably an attempt to initialize the variable.
1723 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1724 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1725 RParen = ConsumeParen();
1726 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1727 diag::err_expected_init_in_condition_lparen)
1728 << SourceRange(LParen, RParen);
1730 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1731 diag::err_expected_init_in_condition);
1734 if (!InitExpr.isInvalid())
1735 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
1736 DS.containsPlaceholderType());
1738 Actions.ActOnInitializerError(DeclOut);
1740 // FIXME: Build a reference to this declaration? Convert it to bool?
1741 // (This is currently handled by Sema).
1743 Actions.FinalizeDeclaration(DeclOut);
1748 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1749 /// This should only be called when the current token is known to be part of
1750 /// simple-type-specifier.
1752 /// simple-type-specifier:
1753 /// '::'[opt] nested-name-specifier[opt] type-name
1754 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1766 /// [GNU] typeof-specifier
1767 /// [C++0x] auto [TODO]
1774 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1775 DS.SetRangeStart(Tok.getLocation());
1776 const char *PrevSpec;
1778 SourceLocation Loc = Tok.getLocation();
1779 const clang::PrintingPolicy &Policy =
1780 Actions.getASTContext().getPrintingPolicy();
1782 switch (Tok.getKind()) {
1783 case tok::identifier: // foo::bar
1784 case tok::coloncolon: // ::foo::bar
1785 llvm_unreachable("Annotation token should already be formed!");
1787 llvm_unreachable("Not a simple-type-specifier token!");
1790 case tok::annot_typename: {
1791 if (getTypeAnnotation(Tok))
1792 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1793 getTypeAnnotation(Tok), Policy);
1795 DS.SetTypeSpecError();
1797 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1800 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1801 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1802 // Objective-C interface. If we don't have Objective-C or a '<', this is
1803 // just a normal reference to a typedef name.
1804 if (Tok.is(tok::less) && getLangOpts().ObjC1)
1805 ParseObjCProtocolQualifiers(DS);
1807 DS.Finish(Diags, PP, Policy);
1813 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1816 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1818 case tok::kw___int64:
1819 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1821 case tok::kw_signed:
1822 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1824 case tok::kw_unsigned:
1825 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1828 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1831 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1834 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1836 case tok::kw___int128:
1837 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1840 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1843 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1845 case tok::kw_double:
1846 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1848 case tok::kw_wchar_t:
1849 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1851 case tok::kw_char16_t:
1852 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1854 case tok::kw_char32_t:
1855 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1858 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1860 case tok::annot_decltype:
1861 case tok::kw_decltype:
1862 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1863 return DS.Finish(Diags, PP, Policy);
1865 // GNU typeof support.
1866 case tok::kw_typeof:
1867 ParseTypeofSpecifier(DS);
1868 DS.Finish(Diags, PP, Policy);
1871 if (Tok.is(tok::annot_typename))
1872 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1874 DS.SetRangeEnd(Tok.getLocation());
1876 DS.Finish(Diags, PP, Policy);
1879 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1880 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1881 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1882 /// by parsing the type-specifier-seq, because these sequences are
1883 /// typically followed by some form of declarator. Returns true and
1884 /// emits diagnostics if this is not a type-specifier-seq, false
1887 /// type-specifier-seq: [C++ 8.1]
1888 /// type-specifier type-specifier-seq[opt]
1890 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1891 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1892 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
1896 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1899 /// This routine is invoked when a '<' is encountered after an identifier or
1900 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1901 /// whether the unqualified-id is actually a template-id. This routine will
1902 /// then parse the template arguments and form the appropriate template-id to
1903 /// return to the caller.
1905 /// \param SS the nested-name-specifier that precedes this template-id, if
1906 /// we're actually parsing a qualified-id.
1908 /// \param Name for constructor and destructor names, this is the actual
1909 /// identifier that may be a template-name.
1911 /// \param NameLoc the location of the class-name in a constructor or
1914 /// \param EnteringContext whether we're entering the scope of the
1915 /// nested-name-specifier.
1917 /// \param ObjectType if this unqualified-id occurs within a member access
1918 /// expression, the type of the base object whose member is being accessed.
1920 /// \param Id as input, describes the template-name or operator-function-id
1921 /// that precedes the '<'. If template arguments were parsed successfully,
1922 /// will be updated with the template-id.
1924 /// \param AssumeTemplateId When true, this routine will assume that the name
1925 /// refers to a template without performing name lookup to verify.
1927 /// \returns true if a parse error occurred, false otherwise.
1928 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1929 SourceLocation TemplateKWLoc,
1930 IdentifierInfo *Name,
1931 SourceLocation NameLoc,
1932 bool EnteringContext,
1933 ParsedType ObjectType,
1935 bool AssumeTemplateId) {
1936 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1937 "Expected '<' to finish parsing a template-id");
1939 TemplateTy Template;
1940 TemplateNameKind TNK = TNK_Non_template;
1941 switch (Id.getKind()) {
1942 case UnqualifiedId::IK_Identifier:
1943 case UnqualifiedId::IK_OperatorFunctionId:
1944 case UnqualifiedId::IK_LiteralOperatorId:
1945 if (AssumeTemplateId) {
1946 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
1947 Id, ObjectType, EnteringContext,
1949 if (TNK == TNK_Non_template)
1952 bool MemberOfUnknownSpecialization;
1953 TNK = Actions.isTemplateName(getCurScope(), SS,
1954 TemplateKWLoc.isValid(), Id,
1955 ObjectType, EnteringContext, Template,
1956 MemberOfUnknownSpecialization);
1958 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1959 ObjectType && IsTemplateArgumentList()) {
1960 // We have something like t->getAs<T>(), where getAs is a
1961 // member of an unknown specialization. However, this will only
1962 // parse correctly as a template, so suggest the keyword 'template'
1963 // before 'getAs' and treat this as a dependent template name.
1965 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1966 Name = Id.Identifier->getName();
1969 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1970 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1972 Name += Id.Identifier->getName();
1974 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1976 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1977 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1978 SS, TemplateKWLoc, Id,
1979 ObjectType, EnteringContext,
1981 if (TNK == TNK_Non_template)
1987 case UnqualifiedId::IK_ConstructorName: {
1988 UnqualifiedId TemplateName;
1989 bool MemberOfUnknownSpecialization;
1990 TemplateName.setIdentifier(Name, NameLoc);
1991 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1992 TemplateName, ObjectType,
1993 EnteringContext, Template,
1994 MemberOfUnknownSpecialization);
1998 case UnqualifiedId::IK_DestructorName: {
1999 UnqualifiedId TemplateName;
2000 bool MemberOfUnknownSpecialization;
2001 TemplateName.setIdentifier(Name, NameLoc);
2003 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2004 SS, TemplateKWLoc, TemplateName,
2005 ObjectType, EnteringContext,
2007 if (TNK == TNK_Non_template)
2010 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2011 TemplateName, ObjectType,
2012 EnteringContext, Template,
2013 MemberOfUnknownSpecialization);
2015 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2016 Diag(NameLoc, diag::err_destructor_template_id)
2017 << Name << SS.getRange();
2028 if (TNK == TNK_Non_template)
2031 // Parse the enclosed template argument list.
2032 SourceLocation LAngleLoc, RAngleLoc;
2033 TemplateArgList TemplateArgs;
2034 if (Tok.is(tok::less) &&
2035 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
2036 SS, true, LAngleLoc,
2041 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
2042 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2043 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
2044 // Form a parsed representation of the template-id to be stored in the
2046 TemplateIdAnnotation *TemplateId
2047 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
2049 // FIXME: Store name for literal operator too.
2050 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2051 TemplateId->Name = Id.Identifier;
2052 TemplateId->Operator = OO_None;
2053 TemplateId->TemplateNameLoc = Id.StartLocation;
2055 TemplateId->Name = nullptr;
2056 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2057 TemplateId->TemplateNameLoc = Id.StartLocation;
2060 TemplateId->SS = SS;
2061 TemplateId->TemplateKWLoc = TemplateKWLoc;
2062 TemplateId->Template = Template;
2063 TemplateId->Kind = TNK;
2064 TemplateId->LAngleLoc = LAngleLoc;
2065 TemplateId->RAngleLoc = RAngleLoc;
2066 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
2067 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
2068 Arg != ArgEnd; ++Arg)
2069 Args[Arg] = TemplateArgs[Arg];
2071 Id.setTemplateId(TemplateId);
2075 // Bundle the template arguments together.
2076 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2078 // Constructor and destructor names.
2080 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2082 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2083 /*IsCtorOrDtorName=*/true);
2084 if (Type.isInvalid())
2087 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2088 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2090 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2095 /// \brief Parse an operator-function-id or conversion-function-id as part
2096 /// of a C++ unqualified-id.
2098 /// This routine is responsible only for parsing the operator-function-id or
2099 /// conversion-function-id; it does not handle template arguments in any way.
2102 /// operator-function-id: [C++ 13.5]
2103 /// 'operator' operator
2105 /// operator: one of
2106 /// new delete new[] delete[]
2107 /// + - * / % ^ & | ~
2108 /// ! = < > += -= *= /= %=
2109 /// ^= &= |= << >> >>= <<= == !=
2110 /// <= >= && || ++ -- , ->* ->
2113 /// conversion-function-id: [C++ 12.3.2]
2114 /// operator conversion-type-id
2116 /// conversion-type-id:
2117 /// type-specifier-seq conversion-declarator[opt]
2119 /// conversion-declarator:
2120 /// ptr-operator conversion-declarator[opt]
2123 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2124 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2126 /// \param EnteringContext whether we are entering the scope of the
2127 /// nested-name-specifier.
2129 /// \param ObjectType if this unqualified-id occurs within a member access
2130 /// expression, the type of the base object whose member is being accessed.
2132 /// \param Result on a successful parse, contains the parsed unqualified-id.
2134 /// \returns true if parsing fails, false otherwise.
2135 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2136 ParsedType ObjectType,
2137 UnqualifiedId &Result) {
2138 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2140 // Consume the 'operator' keyword.
2141 SourceLocation KeywordLoc = ConsumeToken();
2143 // Determine what kind of operator name we have.
2144 unsigned SymbolIdx = 0;
2145 SourceLocation SymbolLocations[3];
2146 OverloadedOperatorKind Op = OO_None;
2147 switch (Tok.getKind()) {
2149 case tok::kw_delete: {
2150 bool isNew = Tok.getKind() == tok::kw_new;
2151 // Consume the 'new' or 'delete'.
2152 SymbolLocations[SymbolIdx++] = ConsumeToken();
2153 // Check for array new/delete.
2154 if (Tok.is(tok::l_square) &&
2155 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2156 // Consume the '[' and ']'.
2157 BalancedDelimiterTracker T(*this, tok::l_square);
2160 if (T.getCloseLocation().isInvalid())
2163 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2164 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2165 Op = isNew? OO_Array_New : OO_Array_Delete;
2167 Op = isNew? OO_New : OO_Delete;
2172 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2174 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2177 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2178 #include "clang/Basic/OperatorKinds.def"
2180 case tok::l_paren: {
2181 // Consume the '(' and ')'.
2182 BalancedDelimiterTracker T(*this, tok::l_paren);
2185 if (T.getCloseLocation().isInvalid())
2188 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2189 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2194 case tok::l_square: {
2195 // Consume the '[' and ']'.
2196 BalancedDelimiterTracker T(*this, tok::l_square);
2199 if (T.getCloseLocation().isInvalid())
2202 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2203 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2208 case tok::code_completion: {
2209 // Code completion for the operator name.
2210 Actions.CodeCompleteOperatorName(getCurScope());
2212 // Don't try to parse any further.
2220 if (Op != OO_None) {
2221 // We have parsed an operator-function-id.
2222 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2226 // Parse a literal-operator-id.
2228 // literal-operator-id: C++11 [over.literal]
2229 // operator string-literal identifier
2230 // operator user-defined-string-literal
2232 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2233 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2235 SourceLocation DiagLoc;
2236 unsigned DiagId = 0;
2238 // We're past translation phase 6, so perform string literal concatenation
2239 // before checking for "".
2240 SmallVector<Token, 4> Toks;
2241 SmallVector<SourceLocation, 4> TokLocs;
2242 while (isTokenStringLiteral()) {
2243 if (!Tok.is(tok::string_literal) && !DiagId) {
2244 // C++11 [over.literal]p1:
2245 // The string-literal or user-defined-string-literal in a
2246 // literal-operator-id shall have no encoding-prefix [...].
2247 DiagLoc = Tok.getLocation();
2248 DiagId = diag::err_literal_operator_string_prefix;
2250 Toks.push_back(Tok);
2251 TokLocs.push_back(ConsumeStringToken());
2254 StringLiteralParser Literal(Toks, PP);
2255 if (Literal.hadError)
2258 // Grab the literal operator's suffix, which will be either the next token
2259 // or a ud-suffix from the string literal.
2260 IdentifierInfo *II = nullptr;
2261 SourceLocation SuffixLoc;
2262 if (!Literal.getUDSuffix().empty()) {
2263 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2265 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2266 Literal.getUDSuffixOffset(),
2267 PP.getSourceManager(), getLangOpts());
2268 } else if (Tok.is(tok::identifier)) {
2269 II = Tok.getIdentifierInfo();
2270 SuffixLoc = ConsumeToken();
2271 TokLocs.push_back(SuffixLoc);
2273 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2277 // The string literal must be empty.
2278 if (!Literal.GetString().empty() || Literal.Pascal) {
2279 // C++11 [over.literal]p1:
2280 // The string-literal or user-defined-string-literal in a
2281 // literal-operator-id shall [...] contain no characters
2282 // other than the implicit terminating '\0'.
2283 DiagLoc = TokLocs.front();
2284 DiagId = diag::err_literal_operator_string_not_empty;
2288 // This isn't a valid literal-operator-id, but we think we know
2289 // what the user meant. Tell them what they should have written.
2290 SmallString<32> Str;
2292 Str += II->getName();
2293 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2294 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2297 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2299 return Actions.checkLiteralOperatorId(SS, Result);
2302 // Parse a conversion-function-id.
2304 // conversion-function-id: [C++ 12.3.2]
2305 // operator conversion-type-id
2307 // conversion-type-id:
2308 // type-specifier-seq conversion-declarator[opt]
2310 // conversion-declarator:
2311 // ptr-operator conversion-declarator[opt]
2313 // Parse the type-specifier-seq.
2314 DeclSpec DS(AttrFactory);
2315 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2318 // Parse the conversion-declarator, which is merely a sequence of
2320 Declarator D(DS, Declarator::ConversionIdContext);
2321 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2323 // Finish up the type.
2324 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2328 // Note that this is a conversion-function-id.
2329 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2330 D.getSourceRange().getEnd());
2334 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2335 /// name of an entity.
2338 /// unqualified-id: [C++ expr.prim.general]
2340 /// operator-function-id
2341 /// conversion-function-id
2342 /// [C++0x] literal-operator-id [TODO]
2348 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2349 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2351 /// \param EnteringContext whether we are entering the scope of the
2352 /// nested-name-specifier.
2354 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2356 /// \param AllowConstructorName whether we allow parsing a constructor name.
2358 /// \param ObjectType if this unqualified-id occurs within a member access
2359 /// expression, the type of the base object whose member is being accessed.
2361 /// \param Result on a successful parse, contains the parsed unqualified-id.
2363 /// \returns true if parsing fails, false otherwise.
2364 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2365 bool AllowDestructorName,
2366 bool AllowConstructorName,
2367 ParsedType ObjectType,
2368 SourceLocation& TemplateKWLoc,
2369 UnqualifiedId &Result) {
2371 // Handle 'A::template B'. This is for template-ids which have not
2372 // already been annotated by ParseOptionalCXXScopeSpecifier().
2373 bool TemplateSpecified = false;
2374 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2375 (ObjectType || SS.isSet())) {
2376 TemplateSpecified = true;
2377 TemplateKWLoc = ConsumeToken();
2382 // template-id (when it hasn't already been annotated)
2383 if (Tok.is(tok::identifier)) {
2384 // Consume the identifier.
2385 IdentifierInfo *Id = Tok.getIdentifierInfo();
2386 SourceLocation IdLoc = ConsumeToken();
2388 if (!getLangOpts().CPlusPlus) {
2389 // If we're not in C++, only identifiers matter. Record the
2390 // identifier and return.
2391 Result.setIdentifier(Id, IdLoc);
2395 if (AllowConstructorName &&
2396 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2397 // We have parsed a constructor name.
2398 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2401 /*IsCtorOrDtorName=*/true,
2402 /*NonTrivialTypeSourceInfo=*/true);
2403 Result.setConstructorName(Ty, IdLoc, IdLoc);
2405 // We have parsed an identifier.
2406 Result.setIdentifier(Id, IdLoc);
2409 // If the next token is a '<', we may have a template.
2410 if (TemplateSpecified || Tok.is(tok::less))
2411 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2412 EnteringContext, ObjectType,
2413 Result, TemplateSpecified);
2419 // template-id (already parsed and annotated)
2420 if (Tok.is(tok::annot_template_id)) {
2421 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2423 // If the template-name names the current class, then this is a constructor
2424 if (AllowConstructorName && TemplateId->Name &&
2425 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2427 // C++ [class.qual]p2 specifies that a qualified template-name
2428 // is taken as the constructor name where a constructor can be
2429 // declared. Thus, the template arguments are extraneous, so
2430 // complain about them and remove them entirely.
2431 Diag(TemplateId->TemplateNameLoc,
2432 diag::err_out_of_line_constructor_template_id)
2434 << FixItHint::CreateRemoval(
2435 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2436 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2437 TemplateId->TemplateNameLoc,
2441 /*IsCtorOrDtorName=*/true,
2442 /*NontrivialTypeSourceInfo=*/true);
2443 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2444 TemplateId->RAngleLoc);
2449 Result.setConstructorTemplateId(TemplateId);
2454 // We have already parsed a template-id; consume the annotation token as
2455 // our unqualified-id.
2456 Result.setTemplateId(TemplateId);
2457 TemplateKWLoc = TemplateId->TemplateKWLoc;
2463 // operator-function-id
2464 // conversion-function-id
2465 if (Tok.is(tok::kw_operator)) {
2466 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2469 // If we have an operator-function-id or a literal-operator-id and the next
2470 // token is a '<', we may have a
2473 // operator-function-id < template-argument-list[opt] >
2474 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2475 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2476 (TemplateSpecified || Tok.is(tok::less)))
2477 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2478 nullptr, SourceLocation(),
2479 EnteringContext, ObjectType,
2480 Result, TemplateSpecified);
2485 if (getLangOpts().CPlusPlus &&
2486 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2487 // C++ [expr.unary.op]p10:
2488 // There is an ambiguity in the unary-expression ~X(), where X is a
2489 // class-name. The ambiguity is resolved in favor of treating ~ as a
2490 // unary complement rather than treating ~X as referring to a destructor.
2493 SourceLocation TildeLoc = ConsumeToken();
2495 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2496 DeclSpec DS(AttrFactory);
2497 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2498 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2499 Result.setDestructorName(TildeLoc, Type, EndLoc);
2505 // Parse the class-name.
2506 if (Tok.isNot(tok::identifier)) {
2507 Diag(Tok, diag::err_destructor_tilde_identifier);
2511 // If the user wrote ~T::T, correct it to T::~T.
2512 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2514 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2517 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2519 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon)) {
2520 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2524 // Recover as if the tilde had been written before the identifier.
2525 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2526 << FixItHint::CreateRemoval(TildeLoc)
2527 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2530 // Parse the class-name (or template-name in a simple-template-id).
2531 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2532 SourceLocation ClassNameLoc = ConsumeToken();
2534 if (TemplateSpecified || Tok.is(tok::less)) {
2535 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
2536 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2537 ClassName, ClassNameLoc,
2538 EnteringContext, ObjectType,
2539 Result, TemplateSpecified);
2542 // Note that this is a destructor name.
2543 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2544 ClassNameLoc, getCurScope(),
2550 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2554 Diag(Tok, diag::err_expected_unqualified_id)
2555 << getLangOpts().CPlusPlus;
2559 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2560 /// memory in a typesafe manner and call constructors.
2562 /// This method is called to parse the new expression after the optional :: has
2563 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2564 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2567 /// '::'[opt] 'new' new-placement[opt] new-type-id
2568 /// new-initializer[opt]
2569 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2570 /// new-initializer[opt]
2573 /// '(' expression-list ')'
2576 /// type-specifier-seq new-declarator[opt]
2577 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2580 /// ptr-operator new-declarator[opt]
2581 /// direct-new-declarator
2583 /// new-initializer:
2584 /// '(' expression-list[opt] ')'
2585 /// [C++0x] braced-init-list
2588 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2589 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2590 ConsumeToken(); // Consume 'new'
2592 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2593 // second form of new-expression. It can't be a new-type-id.
2595 ExprVector PlacementArgs;
2596 SourceLocation PlacementLParen, PlacementRParen;
2598 SourceRange TypeIdParens;
2599 DeclSpec DS(AttrFactory);
2600 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2601 if (Tok.is(tok::l_paren)) {
2602 // If it turns out to be a placement, we change the type location.
2603 BalancedDelimiterTracker T(*this, tok::l_paren);
2605 PlacementLParen = T.getOpenLocation();
2606 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2607 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2612 PlacementRParen = T.getCloseLocation();
2613 if (PlacementRParen.isInvalid()) {
2614 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2618 if (PlacementArgs.empty()) {
2619 // Reset the placement locations. There was no placement.
2620 TypeIdParens = T.getRange();
2621 PlacementLParen = PlacementRParen = SourceLocation();
2623 // We still need the type.
2624 if (Tok.is(tok::l_paren)) {
2625 BalancedDelimiterTracker T(*this, tok::l_paren);
2627 MaybeParseGNUAttributes(DeclaratorInfo);
2628 ParseSpecifierQualifierList(DS);
2629 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2630 ParseDeclarator(DeclaratorInfo);
2632 TypeIdParens = T.getRange();
2634 MaybeParseGNUAttributes(DeclaratorInfo);
2635 if (ParseCXXTypeSpecifierSeq(DS))
2636 DeclaratorInfo.setInvalidType(true);
2638 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2639 ParseDeclaratorInternal(DeclaratorInfo,
2640 &Parser::ParseDirectNewDeclarator);
2645 // A new-type-id is a simplified type-id, where essentially the
2646 // direct-declarator is replaced by a direct-new-declarator.
2647 MaybeParseGNUAttributes(DeclaratorInfo);
2648 if (ParseCXXTypeSpecifierSeq(DS))
2649 DeclaratorInfo.setInvalidType(true);
2651 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2652 ParseDeclaratorInternal(DeclaratorInfo,
2653 &Parser::ParseDirectNewDeclarator);
2656 if (DeclaratorInfo.isInvalidType()) {
2657 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2661 ExprResult Initializer;
2663 if (Tok.is(tok::l_paren)) {
2664 SourceLocation ConstructorLParen, ConstructorRParen;
2665 ExprVector ConstructorArgs;
2666 BalancedDelimiterTracker T(*this, tok::l_paren);
2668 ConstructorLParen = T.getOpenLocation();
2669 if (Tok.isNot(tok::r_paren)) {
2670 CommaLocsTy CommaLocs;
2671 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2672 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2677 ConstructorRParen = T.getCloseLocation();
2678 if (ConstructorRParen.isInvalid()) {
2679 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2682 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2685 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2686 Diag(Tok.getLocation(),
2687 diag::warn_cxx98_compat_generalized_initializer_lists);
2688 Initializer = ParseBraceInitializer();
2690 if (Initializer.isInvalid())
2693 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2694 PlacementArgs, PlacementRParen,
2695 TypeIdParens, DeclaratorInfo, Initializer.get());
2698 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2699 /// passed to ParseDeclaratorInternal.
2701 /// direct-new-declarator:
2702 /// '[' expression ']'
2703 /// direct-new-declarator '[' constant-expression ']'
2705 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2706 // Parse the array dimensions.
2708 while (Tok.is(tok::l_square)) {
2709 // An array-size expression can't start with a lambda.
2710 if (CheckProhibitedCXX11Attribute())
2713 BalancedDelimiterTracker T(*this, tok::l_square);
2716 ExprResult Size(first ? ParseExpression()
2717 : ParseConstantExpression());
2718 if (Size.isInvalid()) {
2720 SkipUntil(tok::r_square, StopAtSemi);
2727 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2728 ParsedAttributes Attrs(AttrFactory);
2729 MaybeParseCXX11Attributes(Attrs);
2731 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2732 /*static=*/false, /*star=*/false,
2734 T.getOpenLocation(),
2735 T.getCloseLocation()),
2736 Attrs, T.getCloseLocation());
2738 if (T.getCloseLocation().isInvalid())
2743 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2744 /// This ambiguity appears in the syntax of the C++ new operator.
2747 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2748 /// new-initializer[opt]
2751 /// '(' expression-list ')'
2753 bool Parser::ParseExpressionListOrTypeId(
2754 SmallVectorImpl<Expr*> &PlacementArgs,
2756 // The '(' was already consumed.
2757 if (isTypeIdInParens()) {
2758 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2759 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2761 return D.isInvalidType();
2764 // It's not a type, it has to be an expression list.
2765 // Discard the comma locations - ActOnCXXNew has enough parameters.
2766 CommaLocsTy CommaLocs;
2767 return ParseExpressionList(PlacementArgs, CommaLocs);
2770 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2771 /// to free memory allocated by new.
2773 /// This method is called to parse the 'delete' expression after the optional
2774 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2775 /// and "Start" is its location. Otherwise, "Start" is the location of the
2778 /// delete-expression:
2779 /// '::'[opt] 'delete' cast-expression
2780 /// '::'[opt] 'delete' '[' ']' cast-expression
2782 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2783 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2784 ConsumeToken(); // Consume 'delete'
2787 bool ArrayDelete = false;
2788 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2789 // C++11 [expr.delete]p1:
2790 // Whenever the delete keyword is followed by empty square brackets, it
2791 // shall be interpreted as [array delete].
2792 // [Footnote: A lambda expression with a lambda-introducer that consists
2793 // of empty square brackets can follow the delete keyword if
2794 // the lambda expression is enclosed in parentheses.]
2795 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2796 // lambda-introducer.
2798 BalancedDelimiterTracker T(*this, tok::l_square);
2802 if (T.getCloseLocation().isInvalid())
2806 ExprResult Operand(ParseCastExpression(false));
2807 if (Operand.isInvalid())
2810 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2813 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2815 default: llvm_unreachable("Not a known type trait");
2816 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2817 case tok::kw_ ## Spelling: return UTT_ ## Name;
2818 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2819 case tok::kw_ ## Spelling: return BTT_ ## Name;
2820 #include "clang/Basic/TokenKinds.def"
2821 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2822 case tok::kw_ ## Spelling: return TT_ ## Name;
2823 #include "clang/Basic/TokenKinds.def"
2827 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2829 default: llvm_unreachable("Not a known binary type trait");
2830 case tok::kw___array_rank: return ATT_ArrayRank;
2831 case tok::kw___array_extent: return ATT_ArrayExtent;
2835 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2837 default: llvm_unreachable("Not a known unary expression trait.");
2838 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2839 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2843 static unsigned TypeTraitArity(tok::TokenKind kind) {
2845 default: llvm_unreachable("Not a known type trait");
2846 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2847 #include "clang/Basic/TokenKinds.def"
2851 /// \brief Parse the built-in type-trait pseudo-functions that allow
2852 /// implementation of the TR1/C++11 type traits templates.
2854 /// primary-expression:
2855 /// unary-type-trait '(' type-id ')'
2856 /// binary-type-trait '(' type-id ',' type-id ')'
2857 /// type-trait '(' type-id-seq ')'
2860 /// type-id ...[opt] type-id-seq[opt]
2862 ExprResult Parser::ParseTypeTrait() {
2863 tok::TokenKind Kind = Tok.getKind();
2864 unsigned Arity = TypeTraitArity(Kind);
2866 SourceLocation Loc = ConsumeToken();
2868 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2869 if (Parens.expectAndConsume())
2872 SmallVector<ParsedType, 2> Args;
2874 // Parse the next type.
2875 TypeResult Ty = ParseTypeName();
2876 if (Ty.isInvalid()) {
2881 // Parse the ellipsis, if present.
2882 if (Tok.is(tok::ellipsis)) {
2883 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2884 if (Ty.isInvalid()) {
2890 // Add this type to the list of arguments.
2891 Args.push_back(Ty.get());
2892 } while (TryConsumeToken(tok::comma));
2894 if (Parens.consumeClose())
2897 SourceLocation EndLoc = Parens.getCloseLocation();
2899 if (Arity && Args.size() != Arity) {
2900 Diag(EndLoc, diag::err_type_trait_arity)
2901 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2905 if (!Arity && Args.empty()) {
2906 Diag(EndLoc, diag::err_type_trait_arity)
2907 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2911 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
2914 /// ParseArrayTypeTrait - Parse the built-in array type-trait
2915 /// pseudo-functions.
2917 /// primary-expression:
2918 /// [Embarcadero] '__array_rank' '(' type-id ')'
2919 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2921 ExprResult Parser::ParseArrayTypeTrait() {
2922 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2923 SourceLocation Loc = ConsumeToken();
2925 BalancedDelimiterTracker T(*this, tok::l_paren);
2926 if (T.expectAndConsume())
2929 TypeResult Ty = ParseTypeName();
2930 if (Ty.isInvalid()) {
2931 SkipUntil(tok::comma, StopAtSemi);
2932 SkipUntil(tok::r_paren, StopAtSemi);
2937 case ATT_ArrayRank: {
2939 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
2940 T.getCloseLocation());
2942 case ATT_ArrayExtent: {
2943 if (ExpectAndConsume(tok::comma)) {
2944 SkipUntil(tok::r_paren, StopAtSemi);
2948 ExprResult DimExpr = ParseExpression();
2951 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2952 T.getCloseLocation());
2955 llvm_unreachable("Invalid ArrayTypeTrait!");
2958 /// ParseExpressionTrait - Parse built-in expression-trait
2959 /// pseudo-functions like __is_lvalue_expr( xxx ).
2961 /// primary-expression:
2962 /// [Embarcadero] expression-trait '(' expression ')'
2964 ExprResult Parser::ParseExpressionTrait() {
2965 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2966 SourceLocation Loc = ConsumeToken();
2968 BalancedDelimiterTracker T(*this, tok::l_paren);
2969 if (T.expectAndConsume())
2972 ExprResult Expr = ParseExpression();
2976 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2977 T.getCloseLocation());
2981 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2982 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2983 /// based on the context past the parens.
2985 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
2987 BalancedDelimiterTracker &Tracker,
2988 ColonProtectionRAIIObject &ColonProt) {
2989 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
2990 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2991 assert(isTypeIdInParens() && "Not a type-id!");
2993 ExprResult Result(true);
2994 CastTy = ParsedType();
2996 // We need to disambiguate a very ugly part of the C++ syntax:
2998 // (T())x; - type-id
2999 // (T())*x; - type-id
3000 // (T())/x; - expression
3001 // (T()); - expression
3003 // The bad news is that we cannot use the specialized tentative parser, since
3004 // it can only verify that the thing inside the parens can be parsed as
3005 // type-id, it is not useful for determining the context past the parens.
3007 // The good news is that the parser can disambiguate this part without
3008 // making any unnecessary Action calls.
3010 // It uses a scheme similar to parsing inline methods. The parenthesized
3011 // tokens are cached, the context that follows is determined (possibly by
3012 // parsing a cast-expression), and then we re-introduce the cached tokens
3013 // into the token stream and parse them appropriately.
3015 ParenParseOption ParseAs;
3018 // Store the tokens of the parentheses. We will parse them after we determine
3019 // the context that follows them.
3020 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3021 // We didn't find the ')' we expected.
3022 Tracker.consumeClose();
3026 if (Tok.is(tok::l_brace)) {
3027 ParseAs = CompoundLiteral;
3030 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3033 // Try parsing the cast-expression that may follow.
3034 // If it is not a cast-expression, NotCastExpr will be true and no token
3035 // will be consumed.
3036 ColonProt.restore();
3037 Result = ParseCastExpression(false/*isUnaryExpression*/,
3038 false/*isAddressofOperand*/,
3040 // type-id has priority.
3044 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3046 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3049 // The current token should go after the cached tokens.
3050 Toks.push_back(Tok);
3051 // Re-enter the stored parenthesized tokens into the token stream, so we may
3053 PP.EnterTokenStream(Toks.data(), Toks.size(),
3054 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
3055 // Drop the current token and bring the first cached one. It's the same token
3056 // as when we entered this function.
3059 if (ParseAs >= CompoundLiteral) {
3060 // Parse the type declarator.
3061 DeclSpec DS(AttrFactory);
3062 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
3064 ColonProtectionRAIIObject InnerColonProtection(*this);
3065 ParseSpecifierQualifierList(DS);
3066 ParseDeclarator(DeclaratorInfo);
3070 Tracker.consumeClose();
3071 ColonProt.restore();
3073 if (ParseAs == CompoundLiteral) {
3074 ExprType = CompoundLiteral;
3075 if (DeclaratorInfo.isInvalidType())
3078 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3079 return ParseCompoundLiteralExpression(Ty.get(),
3080 Tracker.getOpenLocation(),
3081 Tracker.getCloseLocation());
3084 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3085 assert(ParseAs == CastExpr);
3087 if (DeclaratorInfo.isInvalidType())
3090 // Result is what ParseCastExpression returned earlier.
3091 if (!Result.isInvalid())
3092 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3093 DeclaratorInfo, CastTy,
3094 Tracker.getCloseLocation(), Result.get());
3098 // Not a compound literal, and not followed by a cast-expression.
3099 assert(ParseAs == SimpleExpr);
3101 ExprType = SimpleExpr;
3102 Result = ParseExpression();
3103 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3104 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3105 Tok.getLocation(), Result.get());
3108 if (Result.isInvalid()) {
3109 SkipUntil(tok::r_paren, StopAtSemi);
3113 Tracker.consumeClose();