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 TryConsumeToken(tok::equal);
900 Init = ParseInitializer();
901 else if (Tok.is(tok::l_brace)) {
902 BalancedDelimiterTracker Braces(*this, tok::l_brace);
903 Braces.consumeOpen();
905 *SkippedInits = true;
907 // We're disambiguating this:
911 // We need to find the end of the following expression in order to
912 // determine whether this is an Obj-C message send's receiver, a
913 // C99 designator, or a lambda init-capture.
915 // Parse the expression to find where it ends, and annotate it back
916 // onto the tokens. We would have parsed this expression the same way
917 // in either case: both the RHS of an init-capture and the RHS of an
918 // assignment expression are parsed as an initializer-clause, and in
919 // neither case can anything be added to the scope between the '[' and
922 // FIXME: This is horrible. Adding a mechanism to skip an expression
923 // would be much cleaner.
924 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
925 // that instead. (And if we see a ':' with no matching '?', we can
926 // classify this as an Obj-C message send.)
927 SourceLocation StartLoc = Tok.getLocation();
928 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
929 Init = ParseInitializer();
931 if (Tok.getLocation() != StartLoc) {
932 // Back out the lexing of the token after the initializer.
933 PP.RevertCachedTokens(1);
935 // Replace the consumed tokens with an appropriate annotation.
936 Tok.setLocation(StartLoc);
937 Tok.setKind(tok::annot_primary_expr);
938 setExprAnnotation(Tok, Init);
939 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
940 PP.AnnotateCachedTokens(Tok);
942 // Consume the annotated initializer.
947 TryConsumeToken(tok::ellipsis, EllipsisLoc);
949 // If this is an init capture, process the initialization expression
950 // right away. For lambda init-captures such as the following:
952 // auto L = [i = x+1](int a) {
954 // &k = x](char b) { };
956 // keep in mind that each lambda init-capture has to have:
957 // - its initialization expression executed in the context
958 // of the enclosing/parent decl-context.
959 // - but the variable itself has to be 'injected' into the
960 // decl-context of its lambda's call-operator (which has
961 // not yet been created).
962 // Each init-expression is a full-expression that has to get
963 // Sema-analyzed (for capturing etc.) before its lambda's
964 // call-operator's decl-context, scope & scopeinfo are pushed on their
965 // respective stacks. Thus if any variable is odr-used in the init-capture
966 // it will correctly get captured in the enclosing lambda, if one exists.
967 // The init-variables above are created later once the lambdascope and
968 // call-operators decl-context is pushed onto its respective stack.
970 // Since the lambda init-capture's initializer expression occurs in the
971 // context of the enclosing function or lambda, therefore we can not wait
972 // till a lambda scope has been pushed on before deciding whether the
973 // variable needs to be captured. We also need to process all
974 // lvalue-to-rvalue conversions and discarded-value conversions,
975 // so that we can avoid capturing certain constant variables.
979 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
980 // return [y = x](int i) { <-- don't capture by enclosing lambda
984 // If x was not const, the second use would require 'L' to capture, and
985 // that would be an error.
987 ParsedType InitCaptureParsedType;
988 if (Init.isUsable()) {
989 // Get the pointer and store it in an lvalue, so we can use it as an
991 Expr *InitExpr = Init.get();
992 // This performs any lvalue-to-rvalue conversions if necessary, which
993 // can affect what gets captured in the containing decl-context.
994 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
995 Loc, Kind == LCK_ByRef, Id, InitExpr);
997 InitCaptureParsedType.set(InitCaptureType);
999 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
1003 Intro.Range.setEnd(T.getCloseLocation());
1004 return DiagResult();
1007 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
1009 /// Returns true if it hit something unexpected.
1010 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1011 TentativeParsingAction PA(*this);
1013 bool SkippedInits = false;
1014 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
1022 // Parse it again, but this time parse the init-captures too.
1024 Intro = LambdaIntroducer();
1025 DiagID = ParseLambdaIntroducer(Intro);
1026 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1034 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1036 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1037 LambdaIntroducer &Intro) {
1038 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1039 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1041 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1042 "lambda expression parsing");
1046 // FIXME: Call into Actions to add any init-capture declarations to the
1047 // scope while parsing the lambda-declarator and compound-statement.
1049 // Parse lambda-declarator[opt].
1050 DeclSpec DS(AttrFactory);
1051 Declarator D(DS, Declarator::LambdaExprContext);
1052 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1053 Actions.PushLambdaScope();
1055 TypeResult TrailingReturnType;
1056 if (Tok.is(tok::l_paren)) {
1057 ParseScope PrototypeScope(this,
1058 Scope::FunctionPrototypeScope |
1059 Scope::FunctionDeclarationScope |
1062 SourceLocation DeclEndLoc;
1063 BalancedDelimiterTracker T(*this, tok::l_paren);
1065 SourceLocation LParenLoc = T.getOpenLocation();
1067 // Parse parameter-declaration-clause.
1068 ParsedAttributes Attr(AttrFactory);
1069 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1070 SourceLocation EllipsisLoc;
1072 if (Tok.isNot(tok::r_paren)) {
1073 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1074 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1075 // For a generic lambda, each 'auto' within the parameter declaration
1076 // clause creates a template type parameter, so increment the depth.
1077 if (Actions.getCurGenericLambda())
1078 ++CurTemplateDepthTracker;
1081 SourceLocation RParenLoc = T.getCloseLocation();
1082 DeclEndLoc = RParenLoc;
1084 // GNU-style attributes must be parsed before the mutable specifier to be
1085 // compatible with GCC.
1086 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1088 // Parse 'mutable'[opt].
1089 SourceLocation MutableLoc;
1090 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
1091 DeclEndLoc = MutableLoc;
1093 // Parse exception-specification[opt].
1094 ExceptionSpecificationType ESpecType = EST_None;
1095 SourceRange ESpecRange;
1096 SmallVector<ParsedType, 2> DynamicExceptions;
1097 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1098 ExprResult NoexceptExpr;
1099 CachedTokens *ExceptionSpecTokens;
1100 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1103 DynamicExceptionRanges,
1105 ExceptionSpecTokens);
1107 if (ESpecType != EST_None)
1108 DeclEndLoc = ESpecRange.getEnd();
1110 // Parse attribute-specifier[opt].
1111 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1113 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1115 // Parse trailing-return-type[opt].
1116 if (Tok.is(tok::arrow)) {
1117 FunLocalRangeEnd = Tok.getLocation();
1119 TrailingReturnType = ParseTrailingReturnType(Range);
1120 if (Range.getEnd().isValid())
1121 DeclEndLoc = Range.getEnd();
1124 PrototypeScope.Exit();
1126 SourceLocation NoLoc;
1127 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1128 /*isAmbiguous=*/false,
1130 ParamInfo.data(), ParamInfo.size(),
1131 EllipsisLoc, RParenLoc,
1132 DS.getTypeQualifiers(),
1133 /*RefQualifierIsLValueRef=*/true,
1134 /*RefQualifierLoc=*/NoLoc,
1135 /*ConstQualifierLoc=*/NoLoc,
1136 /*VolatileQualifierLoc=*/NoLoc,
1137 /*RestrictQualifierLoc=*/NoLoc,
1139 ESpecType, ESpecRange.getBegin(),
1140 DynamicExceptions.data(),
1141 DynamicExceptionRanges.data(),
1142 DynamicExceptions.size(),
1143 NoexceptExpr.isUsable() ?
1144 NoexceptExpr.get() : nullptr,
1145 /*ExceptionSpecTokens*/nullptr,
1146 LParenLoc, FunLocalRangeEnd, D,
1147 TrailingReturnType),
1149 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow) ||
1150 Tok.is(tok::kw___attribute) ||
1151 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1152 // It's common to forget that one needs '()' before 'mutable', an attribute
1153 // specifier, or the result type. Deal with this.
1154 unsigned TokKind = 0;
1155 switch (Tok.getKind()) {
1156 case tok::kw_mutable: TokKind = 0; break;
1157 case tok::arrow: TokKind = 1; break;
1158 case tok::kw___attribute:
1159 case tok::l_square: TokKind = 2; break;
1160 default: llvm_unreachable("Unknown token kind");
1163 Diag(Tok, diag::err_lambda_missing_parens)
1165 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1166 SourceLocation DeclLoc = Tok.getLocation();
1167 SourceLocation DeclEndLoc = DeclLoc;
1169 // GNU-style attributes must be parsed before the mutable specifier to be
1170 // compatible with GCC.
1171 ParsedAttributes Attr(AttrFactory);
1172 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1174 // Parse 'mutable', if it's there.
1175 SourceLocation MutableLoc;
1176 if (Tok.is(tok::kw_mutable)) {
1177 MutableLoc = ConsumeToken();
1178 DeclEndLoc = MutableLoc;
1181 // Parse attribute-specifier[opt].
1182 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1184 // Parse the return type, if there is one.
1185 if (Tok.is(tok::arrow)) {
1187 TrailingReturnType = ParseTrailingReturnType(Range);
1188 if (Range.getEnd().isValid())
1189 DeclEndLoc = Range.getEnd();
1192 SourceLocation NoLoc;
1193 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1194 /*isAmbiguous=*/false,
1195 /*LParenLoc=*/NoLoc,
1198 /*EllipsisLoc=*/NoLoc,
1199 /*RParenLoc=*/NoLoc,
1201 /*RefQualifierIsLValueRef=*/true,
1202 /*RefQualifierLoc=*/NoLoc,
1203 /*ConstQualifierLoc=*/NoLoc,
1204 /*VolatileQualifierLoc=*/NoLoc,
1205 /*RestrictQualifierLoc=*/NoLoc,
1209 /*Exceptions=*/nullptr,
1210 /*ExceptionRanges=*/nullptr,
1211 /*NumExceptions=*/0,
1212 /*NoexceptExpr=*/nullptr,
1213 /*ExceptionSpecTokens=*/nullptr,
1214 DeclLoc, DeclEndLoc, D,
1215 TrailingReturnType),
1220 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1222 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
1223 ParseScope BodyScope(this, ScopeFlags);
1225 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1227 // Parse compound-statement.
1228 if (!Tok.is(tok::l_brace)) {
1229 Diag(Tok, diag::err_expected_lambda_body);
1230 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1234 StmtResult Stmt(ParseCompoundStatementBody());
1237 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1238 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1240 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1244 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1247 /// postfix-expression: [C++ 5.2p1]
1248 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1249 /// 'static_cast' '<' type-name '>' '(' expression ')'
1250 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1251 /// 'const_cast' '<' type-name '>' '(' expression ')'
1253 ExprResult Parser::ParseCXXCasts() {
1254 tok::TokenKind Kind = Tok.getKind();
1255 const char *CastName = nullptr; // For error messages
1258 default: llvm_unreachable("Unknown C++ cast!");
1259 case tok::kw_const_cast: CastName = "const_cast"; break;
1260 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1261 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1262 case tok::kw_static_cast: CastName = "static_cast"; break;
1265 SourceLocation OpLoc = ConsumeToken();
1266 SourceLocation LAngleBracketLoc = Tok.getLocation();
1268 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1269 // diagnose error, suggest fix, and recover parsing.
1270 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1271 Token Next = NextToken();
1272 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1273 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1276 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1279 // Parse the common declaration-specifiers piece.
1280 DeclSpec DS(AttrFactory);
1281 ParseSpecifierQualifierList(DS);
1283 // Parse the abstract-declarator, if present.
1284 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1285 ParseDeclarator(DeclaratorInfo);
1287 SourceLocation RAngleBracketLoc = Tok.getLocation();
1289 if (ExpectAndConsume(tok::greater))
1290 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1292 SourceLocation LParenLoc, RParenLoc;
1293 BalancedDelimiterTracker T(*this, tok::l_paren);
1295 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1298 ExprResult Result = ParseExpression();
1303 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1304 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1305 LAngleBracketLoc, DeclaratorInfo,
1307 T.getOpenLocation(), Result.get(),
1308 T.getCloseLocation());
1313 /// ParseCXXTypeid - This handles the C++ typeid expression.
1315 /// postfix-expression: [C++ 5.2p1]
1316 /// 'typeid' '(' expression ')'
1317 /// 'typeid' '(' type-id ')'
1319 ExprResult Parser::ParseCXXTypeid() {
1320 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1322 SourceLocation OpLoc = ConsumeToken();
1323 SourceLocation LParenLoc, RParenLoc;
1324 BalancedDelimiterTracker T(*this, tok::l_paren);
1326 // typeid expressions are always parenthesized.
1327 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1329 LParenLoc = T.getOpenLocation();
1333 // C++0x [expr.typeid]p3:
1334 // When typeid is applied to an expression other than an lvalue of a
1335 // polymorphic class type [...] The expression is an unevaluated
1336 // operand (Clause 5).
1338 // Note that we can't tell whether the expression is an lvalue of a
1339 // polymorphic class type until after we've parsed the expression; we
1340 // speculatively assume the subexpression is unevaluated, and fix it up
1343 // We enter the unevaluated context before trying to determine whether we
1344 // have a type-id, because the tentative parse logic will try to resolve
1345 // names, and must treat them as unevaluated.
1346 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1347 Sema::ReuseLambdaContextDecl);
1349 if (isTypeIdInParens()) {
1350 TypeResult Ty = ParseTypeName();
1354 RParenLoc = T.getCloseLocation();
1355 if (Ty.isInvalid() || RParenLoc.isInvalid())
1358 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1359 Ty.get().getAsOpaquePtr(), RParenLoc);
1361 Result = ParseExpression();
1364 if (Result.isInvalid())
1365 SkipUntil(tok::r_paren, StopAtSemi);
1368 RParenLoc = T.getCloseLocation();
1369 if (RParenLoc.isInvalid())
1372 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1373 Result.get(), RParenLoc);
1380 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1382 /// '__uuidof' '(' expression ')'
1383 /// '__uuidof' '(' type-id ')'
1385 ExprResult Parser::ParseCXXUuidof() {
1386 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1388 SourceLocation OpLoc = ConsumeToken();
1389 BalancedDelimiterTracker T(*this, tok::l_paren);
1391 // __uuidof expressions are always parenthesized.
1392 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1397 if (isTypeIdInParens()) {
1398 TypeResult Ty = ParseTypeName();
1406 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1407 Ty.get().getAsOpaquePtr(),
1408 T.getCloseLocation());
1410 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1411 Result = ParseExpression();
1414 if (Result.isInvalid())
1415 SkipUntil(tok::r_paren, StopAtSemi);
1419 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1421 Result.get(), T.getCloseLocation());
1428 /// \brief Parse a C++ pseudo-destructor expression after the base,
1429 /// . or -> operator, and nested-name-specifier have already been
1432 /// postfix-expression: [C++ 5.2]
1433 /// postfix-expression . pseudo-destructor-name
1434 /// postfix-expression -> pseudo-destructor-name
1436 /// pseudo-destructor-name:
1437 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1438 /// ::[opt] nested-name-specifier template simple-template-id ::
1440 /// ::[opt] nested-name-specifier[opt] ~type-name
1443 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1444 tok::TokenKind OpKind,
1446 ParsedType ObjectType) {
1447 // We're parsing either a pseudo-destructor-name or a dependent
1448 // member access that has the same form as a
1449 // pseudo-destructor-name. We parse both in the same way and let
1450 // the action model sort them out.
1452 // Note that the ::[opt] nested-name-specifier[opt] has already
1453 // been parsed, and if there was a simple-template-id, it has
1454 // been coalesced into a template-id annotation token.
1455 UnqualifiedId FirstTypeName;
1456 SourceLocation CCLoc;
1457 if (Tok.is(tok::identifier)) {
1458 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1460 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1461 CCLoc = ConsumeToken();
1462 } else if (Tok.is(tok::annot_template_id)) {
1463 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1464 // store it in the pseudo-dtor node (to be used when instantiating it).
1465 FirstTypeName.setTemplateId(
1466 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1468 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1469 CCLoc = ConsumeToken();
1471 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1475 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1476 SourceLocation TildeLoc = ConsumeToken();
1478 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1479 DeclSpec DS(AttrFactory);
1480 ParseDecltypeSpecifier(DS);
1481 if (DS.getTypeSpecType() == TST_error)
1483 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1484 OpKind, TildeLoc, DS,
1485 Tok.is(tok::l_paren));
1488 if (!Tok.is(tok::identifier)) {
1489 Diag(Tok, diag::err_destructor_tilde_identifier);
1493 // Parse the second type.
1494 UnqualifiedId SecondTypeName;
1495 IdentifierInfo *Name = Tok.getIdentifierInfo();
1496 SourceLocation NameLoc = ConsumeToken();
1497 SecondTypeName.setIdentifier(Name, NameLoc);
1499 // If there is a '<', the second type name is a template-id. Parse
1501 if (Tok.is(tok::less) &&
1502 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1504 false, ObjectType, SecondTypeName,
1505 /*AssumeTemplateName=*/true))
1508 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1510 SS, FirstTypeName, CCLoc,
1511 TildeLoc, SecondTypeName,
1512 Tok.is(tok::l_paren));
1515 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1517 /// boolean-literal: [C++ 2.13.5]
1520 ExprResult Parser::ParseCXXBoolLiteral() {
1521 tok::TokenKind Kind = Tok.getKind();
1522 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1525 /// ParseThrowExpression - This handles the C++ throw expression.
1527 /// throw-expression: [C++ 15]
1528 /// 'throw' assignment-expression[opt]
1529 ExprResult Parser::ParseThrowExpression() {
1530 assert(Tok.is(tok::kw_throw) && "Not throw!");
1531 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1533 // If the current token isn't the start of an assignment-expression,
1534 // then the expression is not present. This handles things like:
1535 // "C ? throw : (void)42", which is crazy but legal.
1536 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1543 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1546 ExprResult Expr(ParseAssignmentExpression());
1547 if (Expr.isInvalid()) return Expr;
1548 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1552 /// ParseCXXThis - This handles the C++ 'this' pointer.
1554 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1555 /// a non-lvalue expression whose value is the address of the object for which
1556 /// the function is called.
1557 ExprResult Parser::ParseCXXThis() {
1558 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1559 SourceLocation ThisLoc = ConsumeToken();
1560 return Actions.ActOnCXXThis(ThisLoc);
1563 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1564 /// Can be interpreted either as function-style casting ("int(x)")
1565 /// or class type construction ("ClassType(x,y,z)")
1566 /// or creation of a value-initialized type ("int()").
1567 /// See [C++ 5.2.3].
1569 /// postfix-expression: [C++ 5.2p1]
1570 /// simple-type-specifier '(' expression-list[opt] ')'
1571 /// [C++0x] simple-type-specifier braced-init-list
1572 /// typename-specifier '(' expression-list[opt] ')'
1573 /// [C++0x] typename-specifier braced-init-list
1576 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1577 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1578 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1580 assert((Tok.is(tok::l_paren) ||
1581 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1582 && "Expected '(' or '{'!");
1584 if (Tok.is(tok::l_brace)) {
1585 ExprResult Init = ParseBraceInitializer();
1586 if (Init.isInvalid())
1588 Expr *InitList = Init.get();
1589 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1590 MultiExprArg(&InitList, 1),
1593 BalancedDelimiterTracker T(*this, tok::l_paren);
1597 CommaLocsTy CommaLocs;
1599 if (Tok.isNot(tok::r_paren)) {
1600 if (ParseExpressionList(Exprs, CommaLocs)) {
1601 SkipUntil(tok::r_paren, StopAtSemi);
1609 // TypeRep could be null, if it references an invalid typedef.
1613 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1614 "Unexpected number of commas!");
1615 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1617 T.getCloseLocation());
1621 /// ParseCXXCondition - if/switch/while condition expression.
1625 /// type-specifier-seq declarator '=' assignment-expression
1626 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1627 /// [C++11] type-specifier-seq declarator braced-init-list
1628 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1629 /// '=' assignment-expression
1631 /// \param ExprOut if the condition was parsed as an expression, the parsed
1634 /// \param DeclOut if the condition was parsed as a declaration, the parsed
1637 /// \param Loc The location of the start of the statement that requires this
1638 /// condition, e.g., the "for" in a for loop.
1640 /// \param ConvertToBoolean Whether the condition expression should be
1641 /// converted to a boolean value.
1643 /// \returns true if there was a parsing, false otherwise.
1644 bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1647 bool ConvertToBoolean) {
1648 if (Tok.is(tok::code_completion)) {
1649 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1654 ParsedAttributesWithRange attrs(AttrFactory);
1655 MaybeParseCXX11Attributes(attrs);
1657 if (!isCXXConditionDeclaration()) {
1658 ProhibitAttributes(attrs);
1660 // Parse the expression.
1661 ExprOut = ParseExpression(); // expression
1663 if (ExprOut.isInvalid())
1666 // If required, convert to a boolean value.
1667 if (ConvertToBoolean)
1669 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1670 return ExprOut.isInvalid();
1673 // type-specifier-seq
1674 DeclSpec DS(AttrFactory);
1675 DS.takeAttributesFrom(attrs);
1676 ParseSpecifierQualifierList(DS);
1679 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1680 ParseDeclarator(DeclaratorInfo);
1682 // simple-asm-expr[opt]
1683 if (Tok.is(tok::kw_asm)) {
1685 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1686 if (AsmLabel.isInvalid()) {
1687 SkipUntil(tok::semi, StopAtSemi);
1690 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1691 DeclaratorInfo.SetRangeEnd(Loc);
1694 // If attributes are present, parse them.
1695 MaybeParseGNUAttributes(DeclaratorInfo);
1697 // Type-check the declaration itself.
1698 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1700 DeclOut = Dcl.get();
1701 ExprOut = ExprError();
1703 // '=' assignment-expression
1704 // If a '==' or '+=' is found, suggest a fixit to '='.
1705 bool CopyInitialization = isTokenEqualOrEqualTypo();
1706 if (CopyInitialization)
1709 ExprResult InitExpr = ExprError();
1710 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1711 Diag(Tok.getLocation(),
1712 diag::warn_cxx98_compat_generalized_initializer_lists);
1713 InitExpr = ParseBraceInitializer();
1714 } else if (CopyInitialization) {
1715 InitExpr = ParseAssignmentExpression();
1716 } else if (Tok.is(tok::l_paren)) {
1717 // This was probably an attempt to initialize the variable.
1718 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1719 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1720 RParen = ConsumeParen();
1721 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1722 diag::err_expected_init_in_condition_lparen)
1723 << SourceRange(LParen, RParen);
1725 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1726 diag::err_expected_init_in_condition);
1729 if (!InitExpr.isInvalid())
1730 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
1731 DS.containsPlaceholderType());
1733 Actions.ActOnInitializerError(DeclOut);
1735 // FIXME: Build a reference to this declaration? Convert it to bool?
1736 // (This is currently handled by Sema).
1738 Actions.FinalizeDeclaration(DeclOut);
1743 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1744 /// This should only be called when the current token is known to be part of
1745 /// simple-type-specifier.
1747 /// simple-type-specifier:
1748 /// '::'[opt] nested-name-specifier[opt] type-name
1749 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1761 /// [GNU] typeof-specifier
1762 /// [C++0x] auto [TODO]
1769 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1770 DS.SetRangeStart(Tok.getLocation());
1771 const char *PrevSpec;
1773 SourceLocation Loc = Tok.getLocation();
1774 const clang::PrintingPolicy &Policy =
1775 Actions.getASTContext().getPrintingPolicy();
1777 switch (Tok.getKind()) {
1778 case tok::identifier: // foo::bar
1779 case tok::coloncolon: // ::foo::bar
1780 llvm_unreachable("Annotation token should already be formed!");
1782 llvm_unreachable("Not a simple-type-specifier token!");
1785 case tok::annot_typename: {
1786 if (getTypeAnnotation(Tok))
1787 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1788 getTypeAnnotation(Tok), Policy);
1790 DS.SetTypeSpecError();
1792 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1795 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1796 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1797 // Objective-C interface. If we don't have Objective-C or a '<', this is
1798 // just a normal reference to a typedef name.
1799 if (Tok.is(tok::less) && getLangOpts().ObjC1)
1800 ParseObjCProtocolQualifiers(DS);
1802 DS.Finish(Diags, PP, Policy);
1808 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1811 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1813 case tok::kw___int64:
1814 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1816 case tok::kw_signed:
1817 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1819 case tok::kw_unsigned:
1820 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1823 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1826 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1829 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1831 case tok::kw___int128:
1832 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1835 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1838 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1840 case tok::kw_double:
1841 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1843 case tok::kw_wchar_t:
1844 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1846 case tok::kw_char16_t:
1847 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1849 case tok::kw_char32_t:
1850 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1853 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1855 case tok::annot_decltype:
1856 case tok::kw_decltype:
1857 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1858 return DS.Finish(Diags, PP, Policy);
1860 // GNU typeof support.
1861 case tok::kw_typeof:
1862 ParseTypeofSpecifier(DS);
1863 DS.Finish(Diags, PP, Policy);
1866 if (Tok.is(tok::annot_typename))
1867 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1869 DS.SetRangeEnd(Tok.getLocation());
1871 DS.Finish(Diags, PP, Policy);
1874 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1875 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1876 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1877 /// by parsing the type-specifier-seq, because these sequences are
1878 /// typically followed by some form of declarator. Returns true and
1879 /// emits diagnostics if this is not a type-specifier-seq, false
1882 /// type-specifier-seq: [C++ 8.1]
1883 /// type-specifier type-specifier-seq[opt]
1885 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1886 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1887 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
1891 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1894 /// This routine is invoked when a '<' is encountered after an identifier or
1895 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1896 /// whether the unqualified-id is actually a template-id. This routine will
1897 /// then parse the template arguments and form the appropriate template-id to
1898 /// return to the caller.
1900 /// \param SS the nested-name-specifier that precedes this template-id, if
1901 /// we're actually parsing a qualified-id.
1903 /// \param Name for constructor and destructor names, this is the actual
1904 /// identifier that may be a template-name.
1906 /// \param NameLoc the location of the class-name in a constructor or
1909 /// \param EnteringContext whether we're entering the scope of the
1910 /// nested-name-specifier.
1912 /// \param ObjectType if this unqualified-id occurs within a member access
1913 /// expression, the type of the base object whose member is being accessed.
1915 /// \param Id as input, describes the template-name or operator-function-id
1916 /// that precedes the '<'. If template arguments were parsed successfully,
1917 /// will be updated with the template-id.
1919 /// \param AssumeTemplateId When true, this routine will assume that the name
1920 /// refers to a template without performing name lookup to verify.
1922 /// \returns true if a parse error occurred, false otherwise.
1923 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1924 SourceLocation TemplateKWLoc,
1925 IdentifierInfo *Name,
1926 SourceLocation NameLoc,
1927 bool EnteringContext,
1928 ParsedType ObjectType,
1930 bool AssumeTemplateId) {
1931 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1932 "Expected '<' to finish parsing a template-id");
1934 TemplateTy Template;
1935 TemplateNameKind TNK = TNK_Non_template;
1936 switch (Id.getKind()) {
1937 case UnqualifiedId::IK_Identifier:
1938 case UnqualifiedId::IK_OperatorFunctionId:
1939 case UnqualifiedId::IK_LiteralOperatorId:
1940 if (AssumeTemplateId) {
1941 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
1942 Id, ObjectType, EnteringContext,
1944 if (TNK == TNK_Non_template)
1947 bool MemberOfUnknownSpecialization;
1948 TNK = Actions.isTemplateName(getCurScope(), SS,
1949 TemplateKWLoc.isValid(), Id,
1950 ObjectType, EnteringContext, Template,
1951 MemberOfUnknownSpecialization);
1953 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1954 ObjectType && IsTemplateArgumentList()) {
1955 // We have something like t->getAs<T>(), where getAs is a
1956 // member of an unknown specialization. However, this will only
1957 // parse correctly as a template, so suggest the keyword 'template'
1958 // before 'getAs' and treat this as a dependent template name.
1960 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1961 Name = Id.Identifier->getName();
1964 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1965 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1967 Name += Id.Identifier->getName();
1969 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1971 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1972 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1973 SS, TemplateKWLoc, Id,
1974 ObjectType, EnteringContext,
1976 if (TNK == TNK_Non_template)
1982 case UnqualifiedId::IK_ConstructorName: {
1983 UnqualifiedId TemplateName;
1984 bool MemberOfUnknownSpecialization;
1985 TemplateName.setIdentifier(Name, NameLoc);
1986 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1987 TemplateName, ObjectType,
1988 EnteringContext, Template,
1989 MemberOfUnknownSpecialization);
1993 case UnqualifiedId::IK_DestructorName: {
1994 UnqualifiedId TemplateName;
1995 bool MemberOfUnknownSpecialization;
1996 TemplateName.setIdentifier(Name, NameLoc);
1998 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1999 SS, TemplateKWLoc, TemplateName,
2000 ObjectType, EnteringContext,
2002 if (TNK == TNK_Non_template)
2005 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2006 TemplateName, ObjectType,
2007 EnteringContext, Template,
2008 MemberOfUnknownSpecialization);
2010 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2011 Diag(NameLoc, diag::err_destructor_template_id)
2012 << Name << SS.getRange();
2023 if (TNK == TNK_Non_template)
2026 // Parse the enclosed template argument list.
2027 SourceLocation LAngleLoc, RAngleLoc;
2028 TemplateArgList TemplateArgs;
2029 if (Tok.is(tok::less) &&
2030 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
2031 SS, true, LAngleLoc,
2036 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
2037 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2038 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
2039 // Form a parsed representation of the template-id to be stored in the
2041 TemplateIdAnnotation *TemplateId
2042 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
2044 // FIXME: Store name for literal operator too.
2045 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2046 TemplateId->Name = Id.Identifier;
2047 TemplateId->Operator = OO_None;
2048 TemplateId->TemplateNameLoc = Id.StartLocation;
2050 TemplateId->Name = nullptr;
2051 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2052 TemplateId->TemplateNameLoc = Id.StartLocation;
2055 TemplateId->SS = SS;
2056 TemplateId->TemplateKWLoc = TemplateKWLoc;
2057 TemplateId->Template = Template;
2058 TemplateId->Kind = TNK;
2059 TemplateId->LAngleLoc = LAngleLoc;
2060 TemplateId->RAngleLoc = RAngleLoc;
2061 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
2062 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
2063 Arg != ArgEnd; ++Arg)
2064 Args[Arg] = TemplateArgs[Arg];
2066 Id.setTemplateId(TemplateId);
2070 // Bundle the template arguments together.
2071 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2073 // Constructor and destructor names.
2075 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2077 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2078 /*IsCtorOrDtorName=*/true);
2079 if (Type.isInvalid())
2082 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2083 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2085 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2090 /// \brief Parse an operator-function-id or conversion-function-id as part
2091 /// of a C++ unqualified-id.
2093 /// This routine is responsible only for parsing the operator-function-id or
2094 /// conversion-function-id; it does not handle template arguments in any way.
2097 /// operator-function-id: [C++ 13.5]
2098 /// 'operator' operator
2100 /// operator: one of
2101 /// new delete new[] delete[]
2102 /// + - * / % ^ & | ~
2103 /// ! = < > += -= *= /= %=
2104 /// ^= &= |= << >> >>= <<= == !=
2105 /// <= >= && || ++ -- , ->* ->
2108 /// conversion-function-id: [C++ 12.3.2]
2109 /// operator conversion-type-id
2111 /// conversion-type-id:
2112 /// type-specifier-seq conversion-declarator[opt]
2114 /// conversion-declarator:
2115 /// ptr-operator conversion-declarator[opt]
2118 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2119 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2121 /// \param EnteringContext whether we are entering the scope of the
2122 /// nested-name-specifier.
2124 /// \param ObjectType if this unqualified-id occurs within a member access
2125 /// expression, the type of the base object whose member is being accessed.
2127 /// \param Result on a successful parse, contains the parsed unqualified-id.
2129 /// \returns true if parsing fails, false otherwise.
2130 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2131 ParsedType ObjectType,
2132 UnqualifiedId &Result) {
2133 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2135 // Consume the 'operator' keyword.
2136 SourceLocation KeywordLoc = ConsumeToken();
2138 // Determine what kind of operator name we have.
2139 unsigned SymbolIdx = 0;
2140 SourceLocation SymbolLocations[3];
2141 OverloadedOperatorKind Op = OO_None;
2142 switch (Tok.getKind()) {
2144 case tok::kw_delete: {
2145 bool isNew = Tok.getKind() == tok::kw_new;
2146 // Consume the 'new' or 'delete'.
2147 SymbolLocations[SymbolIdx++] = ConsumeToken();
2148 // Check for array new/delete.
2149 if (Tok.is(tok::l_square) &&
2150 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2151 // Consume the '[' and ']'.
2152 BalancedDelimiterTracker T(*this, tok::l_square);
2155 if (T.getCloseLocation().isInvalid())
2158 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2159 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2160 Op = isNew? OO_Array_New : OO_Array_Delete;
2162 Op = isNew? OO_New : OO_Delete;
2167 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2169 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2172 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2173 #include "clang/Basic/OperatorKinds.def"
2175 case tok::l_paren: {
2176 // Consume the '(' and ')'.
2177 BalancedDelimiterTracker T(*this, tok::l_paren);
2180 if (T.getCloseLocation().isInvalid())
2183 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2184 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2189 case tok::l_square: {
2190 // Consume the '[' and ']'.
2191 BalancedDelimiterTracker T(*this, tok::l_square);
2194 if (T.getCloseLocation().isInvalid())
2197 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2198 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2203 case tok::code_completion: {
2204 // Code completion for the operator name.
2205 Actions.CodeCompleteOperatorName(getCurScope());
2207 // Don't try to parse any further.
2215 if (Op != OO_None) {
2216 // We have parsed an operator-function-id.
2217 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2221 // Parse a literal-operator-id.
2223 // literal-operator-id: C++11 [over.literal]
2224 // operator string-literal identifier
2225 // operator user-defined-string-literal
2227 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2228 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2230 SourceLocation DiagLoc;
2231 unsigned DiagId = 0;
2233 // We're past translation phase 6, so perform string literal concatenation
2234 // before checking for "".
2235 SmallVector<Token, 4> Toks;
2236 SmallVector<SourceLocation, 4> TokLocs;
2237 while (isTokenStringLiteral()) {
2238 if (!Tok.is(tok::string_literal) && !DiagId) {
2239 // C++11 [over.literal]p1:
2240 // The string-literal or user-defined-string-literal in a
2241 // literal-operator-id shall have no encoding-prefix [...].
2242 DiagLoc = Tok.getLocation();
2243 DiagId = diag::err_literal_operator_string_prefix;
2245 Toks.push_back(Tok);
2246 TokLocs.push_back(ConsumeStringToken());
2249 StringLiteralParser Literal(Toks, PP);
2250 if (Literal.hadError)
2253 // Grab the literal operator's suffix, which will be either the next token
2254 // or a ud-suffix from the string literal.
2255 IdentifierInfo *II = nullptr;
2256 SourceLocation SuffixLoc;
2257 if (!Literal.getUDSuffix().empty()) {
2258 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2260 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2261 Literal.getUDSuffixOffset(),
2262 PP.getSourceManager(), getLangOpts());
2263 } else if (Tok.is(tok::identifier)) {
2264 II = Tok.getIdentifierInfo();
2265 SuffixLoc = ConsumeToken();
2266 TokLocs.push_back(SuffixLoc);
2268 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2272 // The string literal must be empty.
2273 if (!Literal.GetString().empty() || Literal.Pascal) {
2274 // C++11 [over.literal]p1:
2275 // The string-literal or user-defined-string-literal in a
2276 // literal-operator-id shall [...] contain no characters
2277 // other than the implicit terminating '\0'.
2278 DiagLoc = TokLocs.front();
2279 DiagId = diag::err_literal_operator_string_not_empty;
2283 // This isn't a valid literal-operator-id, but we think we know
2284 // what the user meant. Tell them what they should have written.
2285 SmallString<32> Str;
2287 Str += II->getName();
2288 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2289 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2292 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2294 return Actions.checkLiteralOperatorId(SS, Result);
2297 // Parse a conversion-function-id.
2299 // conversion-function-id: [C++ 12.3.2]
2300 // operator conversion-type-id
2302 // conversion-type-id:
2303 // type-specifier-seq conversion-declarator[opt]
2305 // conversion-declarator:
2306 // ptr-operator conversion-declarator[opt]
2308 // Parse the type-specifier-seq.
2309 DeclSpec DS(AttrFactory);
2310 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2313 // Parse the conversion-declarator, which is merely a sequence of
2315 Declarator D(DS, Declarator::ConversionIdContext);
2316 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2318 // Finish up the type.
2319 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2323 // Note that this is a conversion-function-id.
2324 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2325 D.getSourceRange().getEnd());
2329 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2330 /// name of an entity.
2333 /// unqualified-id: [C++ expr.prim.general]
2335 /// operator-function-id
2336 /// conversion-function-id
2337 /// [C++0x] literal-operator-id [TODO]
2343 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2344 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2346 /// \param EnteringContext whether we are entering the scope of the
2347 /// nested-name-specifier.
2349 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2351 /// \param AllowConstructorName whether we allow parsing a constructor name.
2353 /// \param ObjectType if this unqualified-id occurs within a member access
2354 /// expression, the type of the base object whose member is being accessed.
2356 /// \param Result on a successful parse, contains the parsed unqualified-id.
2358 /// \returns true if parsing fails, false otherwise.
2359 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2360 bool AllowDestructorName,
2361 bool AllowConstructorName,
2362 ParsedType ObjectType,
2363 SourceLocation& TemplateKWLoc,
2364 UnqualifiedId &Result) {
2366 // Handle 'A::template B'. This is for template-ids which have not
2367 // already been annotated by ParseOptionalCXXScopeSpecifier().
2368 bool TemplateSpecified = false;
2369 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2370 (ObjectType || SS.isSet())) {
2371 TemplateSpecified = true;
2372 TemplateKWLoc = ConsumeToken();
2377 // template-id (when it hasn't already been annotated)
2378 if (Tok.is(tok::identifier)) {
2379 // Consume the identifier.
2380 IdentifierInfo *Id = Tok.getIdentifierInfo();
2381 SourceLocation IdLoc = ConsumeToken();
2383 if (!getLangOpts().CPlusPlus) {
2384 // If we're not in C++, only identifiers matter. Record the
2385 // identifier and return.
2386 Result.setIdentifier(Id, IdLoc);
2390 if (AllowConstructorName &&
2391 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2392 // We have parsed a constructor name.
2393 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2396 /*IsCtorOrDtorName=*/true,
2397 /*NonTrivialTypeSourceInfo=*/true);
2398 Result.setConstructorName(Ty, IdLoc, IdLoc);
2400 // We have parsed an identifier.
2401 Result.setIdentifier(Id, IdLoc);
2404 // If the next token is a '<', we may have a template.
2405 if (TemplateSpecified || Tok.is(tok::less))
2406 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2407 EnteringContext, ObjectType,
2408 Result, TemplateSpecified);
2414 // template-id (already parsed and annotated)
2415 if (Tok.is(tok::annot_template_id)) {
2416 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2418 // If the template-name names the current class, then this is a constructor
2419 if (AllowConstructorName && TemplateId->Name &&
2420 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2422 // C++ [class.qual]p2 specifies that a qualified template-name
2423 // is taken as the constructor name where a constructor can be
2424 // declared. Thus, the template arguments are extraneous, so
2425 // complain about them and remove them entirely.
2426 Diag(TemplateId->TemplateNameLoc,
2427 diag::err_out_of_line_constructor_template_id)
2429 << FixItHint::CreateRemoval(
2430 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2431 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2432 TemplateId->TemplateNameLoc,
2436 /*IsCtorOrDtorName=*/true,
2437 /*NontrivialTypeSourceInfo=*/true);
2438 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2439 TemplateId->RAngleLoc);
2444 Result.setConstructorTemplateId(TemplateId);
2449 // We have already parsed a template-id; consume the annotation token as
2450 // our unqualified-id.
2451 Result.setTemplateId(TemplateId);
2452 TemplateKWLoc = TemplateId->TemplateKWLoc;
2458 // operator-function-id
2459 // conversion-function-id
2460 if (Tok.is(tok::kw_operator)) {
2461 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2464 // If we have an operator-function-id or a literal-operator-id and the next
2465 // token is a '<', we may have a
2468 // operator-function-id < template-argument-list[opt] >
2469 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2470 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2471 (TemplateSpecified || Tok.is(tok::less)))
2472 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2473 nullptr, SourceLocation(),
2474 EnteringContext, ObjectType,
2475 Result, TemplateSpecified);
2480 if (getLangOpts().CPlusPlus &&
2481 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2482 // C++ [expr.unary.op]p10:
2483 // There is an ambiguity in the unary-expression ~X(), where X is a
2484 // class-name. The ambiguity is resolved in favor of treating ~ as a
2485 // unary complement rather than treating ~X as referring to a destructor.
2488 SourceLocation TildeLoc = ConsumeToken();
2490 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2491 DeclSpec DS(AttrFactory);
2492 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2493 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2494 Result.setDestructorName(TildeLoc, Type, EndLoc);
2500 // Parse the class-name.
2501 if (Tok.isNot(tok::identifier)) {
2502 Diag(Tok, diag::err_destructor_tilde_identifier);
2506 // If the user wrote ~T::T, correct it to T::~T.
2507 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2509 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2512 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2514 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon)) {
2515 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2519 // Recover as if the tilde had been written before the identifier.
2520 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2521 << FixItHint::CreateRemoval(TildeLoc)
2522 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2525 // Parse the class-name (or template-name in a simple-template-id).
2526 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2527 SourceLocation ClassNameLoc = ConsumeToken();
2529 if (TemplateSpecified || Tok.is(tok::less)) {
2530 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
2531 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2532 ClassName, ClassNameLoc,
2533 EnteringContext, ObjectType,
2534 Result, TemplateSpecified);
2537 // Note that this is a destructor name.
2538 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2539 ClassNameLoc, getCurScope(),
2545 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2549 Diag(Tok, diag::err_expected_unqualified_id)
2550 << getLangOpts().CPlusPlus;
2554 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2555 /// memory in a typesafe manner and call constructors.
2557 /// This method is called to parse the new expression after the optional :: has
2558 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2559 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2562 /// '::'[opt] 'new' new-placement[opt] new-type-id
2563 /// new-initializer[opt]
2564 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2565 /// new-initializer[opt]
2568 /// '(' expression-list ')'
2571 /// type-specifier-seq new-declarator[opt]
2572 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2575 /// ptr-operator new-declarator[opt]
2576 /// direct-new-declarator
2578 /// new-initializer:
2579 /// '(' expression-list[opt] ')'
2580 /// [C++0x] braced-init-list
2583 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2584 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2585 ConsumeToken(); // Consume 'new'
2587 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2588 // second form of new-expression. It can't be a new-type-id.
2590 ExprVector PlacementArgs;
2591 SourceLocation PlacementLParen, PlacementRParen;
2593 SourceRange TypeIdParens;
2594 DeclSpec DS(AttrFactory);
2595 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2596 if (Tok.is(tok::l_paren)) {
2597 // If it turns out to be a placement, we change the type location.
2598 BalancedDelimiterTracker T(*this, tok::l_paren);
2600 PlacementLParen = T.getOpenLocation();
2601 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2602 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2607 PlacementRParen = T.getCloseLocation();
2608 if (PlacementRParen.isInvalid()) {
2609 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2613 if (PlacementArgs.empty()) {
2614 // Reset the placement locations. There was no placement.
2615 TypeIdParens = T.getRange();
2616 PlacementLParen = PlacementRParen = SourceLocation();
2618 // We still need the type.
2619 if (Tok.is(tok::l_paren)) {
2620 BalancedDelimiterTracker T(*this, tok::l_paren);
2622 MaybeParseGNUAttributes(DeclaratorInfo);
2623 ParseSpecifierQualifierList(DS);
2624 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2625 ParseDeclarator(DeclaratorInfo);
2627 TypeIdParens = T.getRange();
2629 MaybeParseGNUAttributes(DeclaratorInfo);
2630 if (ParseCXXTypeSpecifierSeq(DS))
2631 DeclaratorInfo.setInvalidType(true);
2633 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2634 ParseDeclaratorInternal(DeclaratorInfo,
2635 &Parser::ParseDirectNewDeclarator);
2640 // A new-type-id is a simplified type-id, where essentially the
2641 // direct-declarator is replaced by a direct-new-declarator.
2642 MaybeParseGNUAttributes(DeclaratorInfo);
2643 if (ParseCXXTypeSpecifierSeq(DS))
2644 DeclaratorInfo.setInvalidType(true);
2646 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2647 ParseDeclaratorInternal(DeclaratorInfo,
2648 &Parser::ParseDirectNewDeclarator);
2651 if (DeclaratorInfo.isInvalidType()) {
2652 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2656 ExprResult Initializer;
2658 if (Tok.is(tok::l_paren)) {
2659 SourceLocation ConstructorLParen, ConstructorRParen;
2660 ExprVector ConstructorArgs;
2661 BalancedDelimiterTracker T(*this, tok::l_paren);
2663 ConstructorLParen = T.getOpenLocation();
2664 if (Tok.isNot(tok::r_paren)) {
2665 CommaLocsTy CommaLocs;
2666 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2667 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2672 ConstructorRParen = T.getCloseLocation();
2673 if (ConstructorRParen.isInvalid()) {
2674 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2677 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2680 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2681 Diag(Tok.getLocation(),
2682 diag::warn_cxx98_compat_generalized_initializer_lists);
2683 Initializer = ParseBraceInitializer();
2685 if (Initializer.isInvalid())
2688 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2689 PlacementArgs, PlacementRParen,
2690 TypeIdParens, DeclaratorInfo, Initializer.get());
2693 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2694 /// passed to ParseDeclaratorInternal.
2696 /// direct-new-declarator:
2697 /// '[' expression ']'
2698 /// direct-new-declarator '[' constant-expression ']'
2700 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2701 // Parse the array dimensions.
2703 while (Tok.is(tok::l_square)) {
2704 // An array-size expression can't start with a lambda.
2705 if (CheckProhibitedCXX11Attribute())
2708 BalancedDelimiterTracker T(*this, tok::l_square);
2711 ExprResult Size(first ? ParseExpression()
2712 : ParseConstantExpression());
2713 if (Size.isInvalid()) {
2715 SkipUntil(tok::r_square, StopAtSemi);
2722 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2723 ParsedAttributes Attrs(AttrFactory);
2724 MaybeParseCXX11Attributes(Attrs);
2726 D.AddTypeInfo(DeclaratorChunk::getArray(0,
2727 /*static=*/false, /*star=*/false,
2729 T.getOpenLocation(),
2730 T.getCloseLocation()),
2731 Attrs, T.getCloseLocation());
2733 if (T.getCloseLocation().isInvalid())
2738 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2739 /// This ambiguity appears in the syntax of the C++ new operator.
2742 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2743 /// new-initializer[opt]
2746 /// '(' expression-list ')'
2748 bool Parser::ParseExpressionListOrTypeId(
2749 SmallVectorImpl<Expr*> &PlacementArgs,
2751 // The '(' was already consumed.
2752 if (isTypeIdInParens()) {
2753 ParseSpecifierQualifierList(D.getMutableDeclSpec());
2754 D.SetSourceRange(D.getDeclSpec().getSourceRange());
2756 return D.isInvalidType();
2759 // It's not a type, it has to be an expression list.
2760 // Discard the comma locations - ActOnCXXNew has enough parameters.
2761 CommaLocsTy CommaLocs;
2762 return ParseExpressionList(PlacementArgs, CommaLocs);
2765 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2766 /// to free memory allocated by new.
2768 /// This method is called to parse the 'delete' expression after the optional
2769 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2770 /// and "Start" is its location. Otherwise, "Start" is the location of the
2773 /// delete-expression:
2774 /// '::'[opt] 'delete' cast-expression
2775 /// '::'[opt] 'delete' '[' ']' cast-expression
2777 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2778 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2779 ConsumeToken(); // Consume 'delete'
2782 bool ArrayDelete = false;
2783 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2784 // C++11 [expr.delete]p1:
2785 // Whenever the delete keyword is followed by empty square brackets, it
2786 // shall be interpreted as [array delete].
2787 // [Footnote: A lambda expression with a lambda-introducer that consists
2788 // of empty square brackets can follow the delete keyword if
2789 // the lambda expression is enclosed in parentheses.]
2790 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2791 // lambda-introducer.
2793 BalancedDelimiterTracker T(*this, tok::l_square);
2797 if (T.getCloseLocation().isInvalid())
2801 ExprResult Operand(ParseCastExpression(false));
2802 if (Operand.isInvalid())
2805 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2808 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2810 default: llvm_unreachable("Not a known type trait");
2811 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2812 case tok::kw_ ## Spelling: return UTT_ ## Name;
2813 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2814 case tok::kw_ ## Spelling: return BTT_ ## Name;
2815 #include "clang/Basic/TokenKinds.def"
2816 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2817 case tok::kw_ ## Spelling: return TT_ ## Name;
2818 #include "clang/Basic/TokenKinds.def"
2822 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2824 default: llvm_unreachable("Not a known binary type trait");
2825 case tok::kw___array_rank: return ATT_ArrayRank;
2826 case tok::kw___array_extent: return ATT_ArrayExtent;
2830 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2832 default: llvm_unreachable("Not a known unary expression trait.");
2833 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2834 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2838 static unsigned TypeTraitArity(tok::TokenKind kind) {
2840 default: llvm_unreachable("Not a known type trait");
2841 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2842 #include "clang/Basic/TokenKinds.def"
2846 /// \brief Parse the built-in type-trait pseudo-functions that allow
2847 /// implementation of the TR1/C++11 type traits templates.
2849 /// primary-expression:
2850 /// unary-type-trait '(' type-id ')'
2851 /// binary-type-trait '(' type-id ',' type-id ')'
2852 /// type-trait '(' type-id-seq ')'
2855 /// type-id ...[opt] type-id-seq[opt]
2857 ExprResult Parser::ParseTypeTrait() {
2858 tok::TokenKind Kind = Tok.getKind();
2859 unsigned Arity = TypeTraitArity(Kind);
2861 SourceLocation Loc = ConsumeToken();
2863 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2864 if (Parens.expectAndConsume())
2867 SmallVector<ParsedType, 2> Args;
2869 // Parse the next type.
2870 TypeResult Ty = ParseTypeName();
2871 if (Ty.isInvalid()) {
2876 // Parse the ellipsis, if present.
2877 if (Tok.is(tok::ellipsis)) {
2878 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2879 if (Ty.isInvalid()) {
2885 // Add this type to the list of arguments.
2886 Args.push_back(Ty.get());
2887 } while (TryConsumeToken(tok::comma));
2889 if (Parens.consumeClose())
2892 SourceLocation EndLoc = Parens.getCloseLocation();
2894 if (Arity && Args.size() != Arity) {
2895 Diag(EndLoc, diag::err_type_trait_arity)
2896 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2900 if (!Arity && Args.empty()) {
2901 Diag(EndLoc, diag::err_type_trait_arity)
2902 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2906 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
2909 /// ParseArrayTypeTrait - Parse the built-in array type-trait
2910 /// pseudo-functions.
2912 /// primary-expression:
2913 /// [Embarcadero] '__array_rank' '(' type-id ')'
2914 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2916 ExprResult Parser::ParseArrayTypeTrait() {
2917 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2918 SourceLocation Loc = ConsumeToken();
2920 BalancedDelimiterTracker T(*this, tok::l_paren);
2921 if (T.expectAndConsume())
2924 TypeResult Ty = ParseTypeName();
2925 if (Ty.isInvalid()) {
2926 SkipUntil(tok::comma, StopAtSemi);
2927 SkipUntil(tok::r_paren, StopAtSemi);
2932 case ATT_ArrayRank: {
2934 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
2935 T.getCloseLocation());
2937 case ATT_ArrayExtent: {
2938 if (ExpectAndConsume(tok::comma)) {
2939 SkipUntil(tok::r_paren, StopAtSemi);
2943 ExprResult DimExpr = ParseExpression();
2946 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2947 T.getCloseLocation());
2950 llvm_unreachable("Invalid ArrayTypeTrait!");
2953 /// ParseExpressionTrait - Parse built-in expression-trait
2954 /// pseudo-functions like __is_lvalue_expr( xxx ).
2956 /// primary-expression:
2957 /// [Embarcadero] expression-trait '(' expression ')'
2959 ExprResult Parser::ParseExpressionTrait() {
2960 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2961 SourceLocation Loc = ConsumeToken();
2963 BalancedDelimiterTracker T(*this, tok::l_paren);
2964 if (T.expectAndConsume())
2967 ExprResult Expr = ParseExpression();
2971 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2972 T.getCloseLocation());
2976 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2977 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2978 /// based on the context past the parens.
2980 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
2982 BalancedDelimiterTracker &Tracker,
2983 ColonProtectionRAIIObject &ColonProt) {
2984 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
2985 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2986 assert(isTypeIdInParens() && "Not a type-id!");
2988 ExprResult Result(true);
2989 CastTy = ParsedType();
2991 // We need to disambiguate a very ugly part of the C++ syntax:
2993 // (T())x; - type-id
2994 // (T())*x; - type-id
2995 // (T())/x; - expression
2996 // (T()); - expression
2998 // The bad news is that we cannot use the specialized tentative parser, since
2999 // it can only verify that the thing inside the parens can be parsed as
3000 // type-id, it is not useful for determining the context past the parens.
3002 // The good news is that the parser can disambiguate this part without
3003 // making any unnecessary Action calls.
3005 // It uses a scheme similar to parsing inline methods. The parenthesized
3006 // tokens are cached, the context that follows is determined (possibly by
3007 // parsing a cast-expression), and then we re-introduce the cached tokens
3008 // into the token stream and parse them appropriately.
3010 ParenParseOption ParseAs;
3013 // Store the tokens of the parentheses. We will parse them after we determine
3014 // the context that follows them.
3015 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3016 // We didn't find the ')' we expected.
3017 Tracker.consumeClose();
3021 if (Tok.is(tok::l_brace)) {
3022 ParseAs = CompoundLiteral;
3025 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3028 // Try parsing the cast-expression that may follow.
3029 // If it is not a cast-expression, NotCastExpr will be true and no token
3030 // will be consumed.
3031 ColonProt.restore();
3032 Result = ParseCastExpression(false/*isUnaryExpression*/,
3033 false/*isAddressofOperand*/,
3035 // type-id has priority.
3039 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3041 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3044 // The current token should go after the cached tokens.
3045 Toks.push_back(Tok);
3046 // Re-enter the stored parenthesized tokens into the token stream, so we may
3048 PP.EnterTokenStream(Toks.data(), Toks.size(),
3049 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
3050 // Drop the current token and bring the first cached one. It's the same token
3051 // as when we entered this function.
3054 if (ParseAs >= CompoundLiteral) {
3055 // Parse the type declarator.
3056 DeclSpec DS(AttrFactory);
3057 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
3059 ColonProtectionRAIIObject InnerColonProtection(*this);
3060 ParseSpecifierQualifierList(DS);
3061 ParseDeclarator(DeclaratorInfo);
3065 Tracker.consumeClose();
3066 ColonProt.restore();
3068 if (ParseAs == CompoundLiteral) {
3069 ExprType = CompoundLiteral;
3070 if (DeclaratorInfo.isInvalidType())
3073 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3074 return ParseCompoundLiteralExpression(Ty.get(),
3075 Tracker.getOpenLocation(),
3076 Tracker.getCloseLocation());
3079 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3080 assert(ParseAs == CastExpr);
3082 if (DeclaratorInfo.isInvalidType())
3085 // Result is what ParseCastExpression returned earlier.
3086 if (!Result.isInvalid())
3087 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3088 DeclaratorInfo, CastTy,
3089 Tracker.getCloseLocation(), Result.get());
3093 // Not a compound literal, and not followed by a cast-expression.
3094 assert(ParseAs == SimpleExpr);
3096 ExprType = SimpleExpr;
3097 Result = ParseExpression();
3098 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3099 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3100 Tok.getLocation(), Result.get());
3103 if (Result.isInvalid()) {
3104 SkipUntil(tok::r_paren, StopAtSemi);
3108 Tracker.consumeClose();