1 //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Expression parsing implementation for C++.
11 //===----------------------------------------------------------------------===//
12 #include "clang/Parse/Parser.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/Basic/PrettyStackTrace.h"
16 #include "clang/Lex/LiteralSupport.h"
17 #include "clang/Parse/ParseDiagnostic.h"
18 #include "clang/Parse/RAIIObjectsForParser.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/ParsedTemplate.h"
21 #include "clang/Sema/Scope.h"
22 #include "llvm/Support/ErrorHandling.h"
25 using namespace clang;
27 static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
30 case tok::unknown: return 0;
32 case tok::kw_const_cast: return 1;
33 case tok::kw_dynamic_cast: return 2;
34 case tok::kw_reinterpret_cast: return 3;
35 case tok::kw_static_cast: return 4;
37 llvm_unreachable("Unknown type for digraph error message.");
41 // Are the two tokens adjacent in the same source file?
42 bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
43 SourceManager &SM = PP.getSourceManager();
44 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
45 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
46 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
49 // Suggest fixit for "<::" after a cast.
50 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
51 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
52 // Pull '<:' and ':' off token stream.
58 Range.setBegin(DigraphToken.getLocation());
59 Range.setEnd(ColonToken.getLocation());
60 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
61 << SelectDigraphErrorMessage(Kind)
62 << FixItHint::CreateReplacement(Range, "< ::");
64 // Update token information to reflect their change in token type.
65 ColonToken.setKind(tok::coloncolon);
66 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
67 ColonToken.setLength(2);
68 DigraphToken.setKind(tok::less);
69 DigraphToken.setLength(1);
71 // Push new tokens back to token stream.
72 PP.EnterToken(ColonToken, /*IsReinject*/ true);
74 PP.EnterToken(DigraphToken, /*IsReinject*/ true);
77 // Check for '<::' which should be '< ::' instead of '[:' when following
79 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
81 IdentifierInfo &II, CXXScopeSpec &SS) {
82 if (!Next.is(tok::l_square) || Next.getLength() != 2)
85 Token SecondToken = GetLookAheadToken(2);
86 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
90 UnqualifiedId TemplateName;
91 TemplateName.setIdentifier(&II, Tok.getLocation());
92 bool MemberOfUnknownSpecialization;
93 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
94 TemplateName, ObjectType, EnteringContext,
95 Template, MemberOfUnknownSpecialization))
98 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
102 /// Parse global scope or nested-name-specifier if present.
104 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
105 /// may be preceded by '::'). Note that this routine will not parse ::new or
106 /// ::delete; it will just leave them in the token stream.
108 /// '::'[opt] nested-name-specifier
111 /// nested-name-specifier:
113 /// namespace-name '::'
114 /// nested-name-specifier identifier '::'
115 /// nested-name-specifier 'template'[opt] simple-template-id '::'
118 /// \param SS the scope specifier that will be set to the parsed
119 /// nested-name-specifier (or empty)
121 /// \param ObjectType if this nested-name-specifier is being parsed following
122 /// the "." or "->" of a member access expression, this parameter provides the
123 /// type of the object whose members are being accessed.
125 /// \param EnteringContext whether we will be entering into the context of
126 /// the nested-name-specifier after parsing it.
128 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
129 /// indicates whether this nested-name-specifier may be part of a
130 /// pseudo-destructor name. In this case, the flag will be set false
131 /// if we don't actually end up parsing a destructor name. Moreorover,
132 /// if we do end up determining that we are parsing a destructor name,
133 /// the last component of the nested-name-specifier is not parsed as
134 /// part of the scope specifier.
136 /// \param IsTypename If \c true, this nested-name-specifier is known to be
137 /// part of a type name. This is used to improve error recovery.
139 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
140 /// filled in with the leading identifier in the last component of the
141 /// nested-name-specifier, if any.
143 /// \param OnlyNamespace If true, only considers namespaces in lookup.
145 /// \returns true if there was an error parsing a scope specifier
146 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
147 ParsedType ObjectType,
148 bool EnteringContext,
149 bool *MayBePseudoDestructor,
151 IdentifierInfo **LastII,
152 bool OnlyNamespace) {
153 assert(getLangOpts().CPlusPlus &&
154 "Call sites of this function should be guarded by checking for C++");
156 if (Tok.is(tok::annot_cxxscope)) {
157 assert(!LastII && "want last identifier but have already annotated scope");
158 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
159 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
160 Tok.getAnnotationRange(),
162 ConsumeAnnotationToken();
166 if (Tok.is(tok::annot_template_id)) {
167 // If the current token is an annotated template id, it may already have
168 // a scope specifier. Restore it.
169 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
173 // Has to happen before any "return false"s in this function.
174 bool CheckForDestructor = false;
175 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
176 CheckForDestructor = true;
177 *MayBePseudoDestructor = false;
183 bool HasScopeSpecifier = false;
185 if (Tok.is(tok::coloncolon)) {
186 // ::new and ::delete aren't nested-name-specifiers.
187 tok::TokenKind NextKind = NextToken().getKind();
188 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
191 if (NextKind == tok::l_brace) {
192 // It is invalid to have :: {, consume the scope qualifier and pretend
193 // like we never saw it.
194 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
196 // '::' - Global scope qualifier.
197 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
200 HasScopeSpecifier = true;
204 if (Tok.is(tok::kw___super)) {
205 SourceLocation SuperLoc = ConsumeToken();
206 if (!Tok.is(tok::coloncolon)) {
207 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
211 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
214 if (!HasScopeSpecifier &&
215 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
216 DeclSpec DS(AttrFactory);
217 SourceLocation DeclLoc = Tok.getLocation();
218 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
220 SourceLocation CCLoc;
221 // Work around a standard defect: 'decltype(auto)::' is not a
222 // nested-name-specifier.
223 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
224 !TryConsumeToken(tok::coloncolon, CCLoc)) {
225 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
229 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
230 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
232 HasScopeSpecifier = true;
235 // Preferred type might change when parsing qualifiers, we need the original.
236 auto SavedType = PreferredType;
238 if (HasScopeSpecifier) {
239 if (Tok.is(tok::code_completion)) {
240 // Code completion for a nested-name-specifier, where the code
241 // completion token follows the '::'.
242 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext,
244 SavedType.get(SS.getBeginLoc()));
245 // Include code completion token into the range of the scope otherwise
246 // when we try to annotate the scope tokens the dangling code completion
247 // token will cause assertion in
248 // Preprocessor::AnnotatePreviousCachedTokens.
249 SS.setEndLoc(Tok.getLocation());
254 // C++ [basic.lookup.classref]p5:
255 // If the qualified-id has the form
257 // ::class-name-or-namespace-name::...
259 // the class-name-or-namespace-name is looked up in global scope as a
260 // class-name or namespace-name.
262 // To implement this, we clear out the object type as soon as we've
263 // seen a leading '::' or part of a nested-name-specifier.
264 ObjectType = nullptr;
267 // nested-name-specifier:
268 // nested-name-specifier 'template'[opt] simple-template-id '::'
270 // Parse the optional 'template' keyword, then make sure we have
271 // 'identifier <' after it.
272 if (Tok.is(tok::kw_template)) {
273 // If we don't have a scope specifier or an object type, this isn't a
274 // nested-name-specifier, since they aren't allowed to start with
276 if (!HasScopeSpecifier && !ObjectType)
279 TentativeParsingAction TPA(*this);
280 SourceLocation TemplateKWLoc = ConsumeToken();
282 UnqualifiedId TemplateName;
283 if (Tok.is(tok::identifier)) {
284 // Consume the identifier.
285 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
287 } else if (Tok.is(tok::kw_operator)) {
288 // We don't need to actually parse the unqualified-id in this case,
289 // because a simple-template-id cannot start with 'operator', but
290 // go ahead and parse it anyway for consistency with the case where
291 // we already annotated the template-id.
292 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
298 if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
299 TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
300 Diag(TemplateName.getSourceRange().getBegin(),
301 diag::err_id_after_template_in_nested_name_spec)
302 << TemplateName.getSourceRange();
311 // If the next token is not '<', we have a qualified-id that refers
312 // to a template name, such as T::template apply, but is not a
314 if (Tok.isNot(tok::less)) {
319 // Commit to parsing the template-id.
322 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
323 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
324 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
325 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
326 TemplateName, false))
334 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
339 // So we need to check whether the template-id is a simple-template-id of
340 // the right kind (it should name a type or be dependent), and then
341 // convert it into a type within the nested-name-specifier.
342 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
343 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
344 *MayBePseudoDestructor = true;
349 *LastII = TemplateId->Name;
351 // Consume the template-id token.
352 ConsumeAnnotationToken();
354 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
355 SourceLocation CCLoc = ConsumeToken();
357 HasScopeSpecifier = true;
359 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
360 TemplateId->NumArgs);
362 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
364 TemplateId->TemplateKWLoc,
365 TemplateId->Template,
366 TemplateId->TemplateNameLoc,
367 TemplateId->LAngleLoc,
369 TemplateId->RAngleLoc,
372 SourceLocation StartLoc
373 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
374 : TemplateId->TemplateNameLoc;
375 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
381 // The rest of the nested-name-specifier possibilities start with
383 if (Tok.isNot(tok::identifier))
386 IdentifierInfo &II = *Tok.getIdentifierInfo();
388 // nested-name-specifier:
390 // namespace-name '::'
391 // nested-name-specifier identifier '::'
392 Token Next = NextToken();
393 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
396 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
397 // and emit a fixit hint for it.
398 if (Next.is(tok::colon) && !ColonIsSacred) {
399 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
401 // If the token after the colon isn't an identifier, it's still an
402 // error, but they probably meant something else strange so don't
403 // recover like this.
404 PP.LookAhead(1).is(tok::identifier)) {
405 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
406 << FixItHint::CreateReplacement(Next.getLocation(), "::");
407 // Recover as if the user wrote '::'.
408 Next.setKind(tok::coloncolon);
412 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
413 // It is invalid to have :: {, consume the scope qualifier and pretend
414 // like we never saw it.
415 Token Identifier = Tok; // Stash away the identifier.
416 ConsumeToken(); // Eat the identifier, current token is now '::'.
417 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
419 UnconsumeToken(Identifier); // Stick the identifier back.
420 Next = NextToken(); // Point Next at the '{' token.
423 if (Next.is(tok::coloncolon)) {
424 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
425 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
426 *MayBePseudoDestructor = true;
431 const Token &Next2 = GetLookAheadToken(2);
432 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
433 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
434 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
436 << FixItHint::CreateReplacement(Next.getLocation(), ":");
439 ColonColon.setKind(tok::colon);
440 PP.EnterToken(ColonColon, /*IsReinject*/ true);
448 // We have an identifier followed by a '::'. Lookup this name
449 // as the name in a nested-name-specifier.
450 Token Identifier = Tok;
451 SourceLocation IdLoc = ConsumeToken();
452 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
453 "NextToken() not working properly!");
454 Token ColonColon = Tok;
455 SourceLocation CCLoc = ConsumeToken();
457 bool IsCorrectedToColon = false;
458 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
459 if (Actions.ActOnCXXNestedNameSpecifier(
460 getCurScope(), IdInfo, EnteringContext, SS, false,
461 CorrectionFlagPtr, OnlyNamespace)) {
462 // Identifier is not recognized as a nested name, but we can have
463 // mistyped '::' instead of ':'.
464 if (CorrectionFlagPtr && IsCorrectedToColon) {
465 ColonColon.setKind(tok::colon);
466 PP.EnterToken(Tok, /*IsReinject*/ true);
467 PP.EnterToken(ColonColon, /*IsReinject*/ true);
471 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
473 HasScopeSpecifier = true;
477 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
479 // nested-name-specifier:
481 if (Next.is(tok::less)) {
483 UnqualifiedId TemplateName;
484 TemplateName.setIdentifier(&II, Tok.getLocation());
485 bool MemberOfUnknownSpecialization;
486 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
487 /*hasTemplateKeyword=*/false,
492 MemberOfUnknownSpecialization)) {
493 // If lookup didn't find anything, we treat the name as a template-name
494 // anyway. C++20 requires this, and in prior language modes it improves
495 // error recovery. But before we commit to this, check that we actually
496 // have something that looks like a template-argument-list next.
497 if (!IsTypename && TNK == TNK_Undeclared_template &&
498 isTemplateArgumentList(1) == TPResult::False)
501 // We have found a template name, so annotate this token
502 // with a template-id annotation. We do not permit the
503 // template-id to be translated into a type annotation,
504 // because some clients (e.g., the parsing of class template
505 // specializations) still want to see the original template-id
508 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
509 TemplateName, false))
514 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
515 (IsTypename || isTemplateArgumentList(1) == TPResult::True)) {
516 // We have something like t::getAs<T>, where getAs is a
517 // member of an unknown specialization. However, this will only
518 // parse correctly as a template, so suggest the keyword 'template'
519 // before 'getAs' and treat this as a dependent template name.
520 unsigned DiagID = diag::err_missing_dependent_template_keyword;
521 if (getLangOpts().MicrosoftExt)
522 DiagID = diag::warn_missing_dependent_template_keyword;
524 Diag(Tok.getLocation(), DiagID)
526 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
528 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
529 getCurScope(), SS, Tok.getLocation(), TemplateName, ObjectType,
530 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
531 // Consume the identifier.
533 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
534 TemplateName, false))
544 // We don't have any tokens that form the beginning of a
545 // nested-name-specifier, so we're done.
549 // Even if we didn't see any pieces of a nested-name-specifier, we
550 // still check whether there is a tilde in this position, which
551 // indicates a potential pseudo-destructor.
552 if (CheckForDestructor && Tok.is(tok::tilde))
553 *MayBePseudoDestructor = true;
558 ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
559 Token &Replacement) {
560 SourceLocation TemplateKWLoc;
562 if (ParseUnqualifiedId(SS,
563 /*EnteringContext=*/false,
564 /*AllowDestructorName=*/false,
565 /*AllowConstructorName=*/false,
566 /*AllowDeductionGuide=*/false,
567 /*ObjectType=*/nullptr, &TemplateKWLoc, Name))
570 // This is only the direct operand of an & operator if it is not
571 // followed by a postfix-expression suffix.
572 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
573 isAddressOfOperand = false;
575 ExprResult E = Actions.ActOnIdExpression(
576 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
577 isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
579 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
580 checkPotentialAngleBracket(E);
584 /// ParseCXXIdExpression - Handle id-expression.
591 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
593 /// '::' operator-function-id
596 /// NOTE: The standard specifies that, for qualified-id, the parser does not
599 /// '::' conversion-function-id
600 /// '::' '~' class-name
602 /// This may cause a slight inconsistency on diagnostics:
607 /// :: A :: ~ C(); // Some Sema error about using destructor with a
609 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
612 /// We simplify the parser a bit and make it work like:
615 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
616 /// '::' unqualified-id
618 /// That way Sema can handle and report similar errors for namespaces and the
621 /// The isAddressOfOperand parameter indicates that this id-expression is a
622 /// direct operand of the address-of operator. This is, besides member contexts,
623 /// the only place where a qualified-id naming a non-static class member may
626 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
628 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
629 // '::' unqualified-id
632 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
636 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
637 if (Result.isUnset()) {
638 // If the ExprResult is valid but null, then typo correction suggested a
639 // keyword replacement that needs to be reparsed.
640 UnconsumeToken(Replacement);
641 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
643 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
644 "for a previous keyword suggestion");
648 /// ParseLambdaExpression - Parse a C++11 lambda expression.
650 /// lambda-expression:
651 /// lambda-introducer lambda-declarator[opt] compound-statement
652 /// lambda-introducer '<' template-parameter-list '>'
653 /// lambda-declarator[opt] compound-statement
655 /// lambda-introducer:
656 /// '[' lambda-capture[opt] ']'
661 /// capture-default ',' capture-list
669 /// capture-list ',' capture
673 /// init-capture [C++1y]
680 /// init-capture: [C++1y]
681 /// identifier initializer
682 /// '&' identifier initializer
684 /// lambda-declarator:
685 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
686 /// 'mutable'[opt] exception-specification[opt]
687 /// trailing-return-type[opt]
689 ExprResult Parser::ParseLambdaExpression() {
690 // Parse lambda-introducer.
691 LambdaIntroducer Intro;
692 if (ParseLambdaIntroducer(Intro)) {
693 SkipUntil(tok::r_square, StopAtSemi);
694 SkipUntil(tok::l_brace, StopAtSemi);
695 SkipUntil(tok::r_brace, StopAtSemi);
699 return ParseLambdaExpressionAfterIntroducer(Intro);
702 /// Use lookahead and potentially tentative parsing to determine if we are
703 /// looking at a C++11 lambda expression, and parse it if we are.
705 /// If we are not looking at a lambda expression, returns ExprError().
706 ExprResult Parser::TryParseLambdaExpression() {
707 assert(getLangOpts().CPlusPlus11
708 && Tok.is(tok::l_square)
709 && "Not at the start of a possible lambda expression.");
711 const Token Next = NextToken();
712 if (Next.is(tok::eof)) // Nothing else to lookup here...
715 const Token After = GetLookAheadToken(2);
716 // If lookahead indicates this is a lambda...
717 if (Next.is(tok::r_square) || // []
718 Next.is(tok::equal) || // [=
719 (Next.is(tok::amp) && // [&] or [&,
720 After.isOneOf(tok::r_square, tok::comma)) ||
721 (Next.is(tok::identifier) && // [identifier]
722 After.is(tok::r_square)) ||
723 Next.is(tok::ellipsis)) { // [...
724 return ParseLambdaExpression();
727 // If lookahead indicates an ObjC message send...
728 // [identifier identifier
729 if (Next.is(tok::identifier) && After.is(tok::identifier))
732 // Here, we're stuck: lambda introducers and Objective-C message sends are
733 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
734 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
735 // writing two routines to parse a lambda introducer, just try to parse
736 // a lambda introducer first, and fall back if that fails.
737 LambdaIntroducer Intro;
739 TentativeParsingAction TPA(*this);
740 LambdaIntroducerTentativeParse Tentative;
741 if (ParseLambdaIntroducer(Intro, &Tentative)) {
747 case LambdaIntroducerTentativeParse::Success:
751 case LambdaIntroducerTentativeParse::Incomplete:
752 // Didn't fully parse the lambda-introducer, try again with a
753 // non-tentative parse.
755 Intro = LambdaIntroducer();
756 if (ParseLambdaIntroducer(Intro))
760 case LambdaIntroducerTentativeParse::MessageSend:
761 case LambdaIntroducerTentativeParse::Invalid:
762 // Not a lambda-introducer, might be a message send.
768 return ParseLambdaExpressionAfterIntroducer(Intro);
771 /// Parse a lambda introducer.
772 /// \param Intro A LambdaIntroducer filled in with information about the
773 /// contents of the lambda-introducer.
774 /// \param Tentative If non-null, we are disambiguating between a
775 /// lambda-introducer and some other construct. In this mode, we do not
776 /// produce any diagnostics or take any other irreversible action unless
777 /// we're sure that this is a lambda-expression.
778 /// \return \c true if parsing (or disambiguation) failed with a diagnostic and
779 /// the caller should bail out / recover.
780 bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
781 LambdaIntroducerTentativeParse *Tentative) {
783 *Tentative = LambdaIntroducerTentativeParse::Success;
785 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
786 BalancedDelimiterTracker T(*this, tok::l_square);
789 Intro.Range.setBegin(T.getOpenLocation());
793 // Produce a diagnostic if we're not tentatively parsing; otherwise track
794 // that our parse has failed.
795 auto Invalid = [&](llvm::function_ref<void()> Action) {
797 *Tentative = LambdaIntroducerTentativeParse::Invalid;
804 // Perform some irreversible action if this is a non-tentative parse;
805 // otherwise note that our actions were incomplete.
806 auto NonTentativeAction = [&](llvm::function_ref<void()> Action) {
808 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
813 // Parse capture-default.
814 if (Tok.is(tok::amp) &&
815 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
816 Intro.Default = LCD_ByRef;
817 Intro.DefaultLoc = ConsumeToken();
819 if (!Tok.getIdentifierInfo()) {
820 // This can only be a lambda; no need for tentative parsing any more.
821 // '[[and]]' can still be an attribute, though.
824 } else if (Tok.is(tok::equal)) {
825 Intro.Default = LCD_ByCopy;
826 Intro.DefaultLoc = ConsumeToken();
831 while (Tok.isNot(tok::r_square)) {
833 if (Tok.isNot(tok::comma)) {
834 // Provide a completion for a lambda introducer here. Except
835 // in Objective-C, where this is Almost Surely meant to be a message
836 // send. In that case, fail here and let the ObjC message
837 // expression parser perform the completion.
838 if (Tok.is(tok::code_completion) &&
839 !(getLangOpts().ObjC && Tentative)) {
840 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
841 /*AfterAmpersand=*/false);
847 Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare);
853 if (Tok.is(tok::code_completion)) {
854 // If we're in Objective-C++ and we have a bare '[', then this is more
855 // likely to be a message receiver.
856 if (getLangOpts().ObjC && Tentative && First)
857 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
859 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
860 /*AfterAmpersand=*/false);
868 LambdaCaptureKind Kind = LCK_ByCopy;
869 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
871 IdentifierInfo *Id = nullptr;
872 SourceLocation EllipsisLocs[4];
874 SourceLocation LocStart = Tok.getLocation();
876 if (Tok.is(tok::star)) {
877 Loc = ConsumeToken();
878 if (Tok.is(tok::kw_this)) {
883 Diag(Tok.getLocation(), diag::err_expected_star_this_capture);
886 } else if (Tok.is(tok::kw_this)) {
888 Loc = ConsumeToken();
890 TryConsumeToken(tok::ellipsis, EllipsisLocs[0]);
892 if (Tok.is(tok::amp)) {
896 if (Tok.is(tok::code_completion)) {
897 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
898 /*AfterAmpersand=*/true);
904 TryConsumeToken(tok::ellipsis, EllipsisLocs[1]);
906 if (Tok.is(tok::identifier)) {
907 Id = Tok.getIdentifierInfo();
908 Loc = ConsumeToken();
909 } else if (Tok.is(tok::kw_this)) {
911 // FIXME: Suggest a fixit here.
912 Diag(Tok.getLocation(), diag::err_this_captured_by_reference);
916 Diag(Tok.getLocation(), diag::err_expected_capture);
920 TryConsumeToken(tok::ellipsis, EllipsisLocs[2]);
922 if (Tok.is(tok::l_paren)) {
923 BalancedDelimiterTracker Parens(*this, tok::l_paren);
924 Parens.consumeOpen();
926 InitKind = LambdaCaptureInitKind::DirectInit;
932 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
933 } else if (ParseExpressionList(Exprs, Commas)) {
937 Parens.consumeClose();
938 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
939 Parens.getCloseLocation(),
942 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
943 // Each lambda init-capture forms its own full expression, which clears
944 // Actions.MaybeODRUseExprs. So create an expression evaluation context
945 // to save the necessary state, and restore it later.
946 EnterExpressionEvaluationContext EC(
947 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
949 if (TryConsumeToken(tok::equal))
950 InitKind = LambdaCaptureInitKind::CopyInit;
952 InitKind = LambdaCaptureInitKind::ListInit;
955 Init = ParseInitializer();
956 } else if (Tok.is(tok::l_brace)) {
957 BalancedDelimiterTracker Braces(*this, tok::l_brace);
958 Braces.consumeOpen();
960 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
962 // We're disambiguating this:
966 // We need to find the end of the following expression in order to
967 // determine whether this is an Obj-C message send's receiver, a
968 // C99 designator, or a lambda init-capture.
970 // Parse the expression to find where it ends, and annotate it back
971 // onto the tokens. We would have parsed this expression the same way
972 // in either case: both the RHS of an init-capture and the RHS of an
973 // assignment expression are parsed as an initializer-clause, and in
974 // neither case can anything be added to the scope between the '[' and
977 // FIXME: This is horrible. Adding a mechanism to skip an expression
978 // would be much cleaner.
979 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
980 // that instead. (And if we see a ':' with no matching '?', we can
981 // classify this as an Obj-C message send.)
982 SourceLocation StartLoc = Tok.getLocation();
983 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
984 Init = ParseInitializer();
985 if (!Init.isInvalid())
986 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
988 if (Tok.getLocation() != StartLoc) {
989 // Back out the lexing of the token after the initializer.
990 PP.RevertCachedTokens(1);
992 // Replace the consumed tokens with an appropriate annotation.
993 Tok.setLocation(StartLoc);
994 Tok.setKind(tok::annot_primary_expr);
995 setExprAnnotation(Tok, Init);
996 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
997 PP.AnnotateCachedTokens(Tok);
999 // Consume the annotated initializer.
1000 ConsumeAnnotationToken();
1005 TryConsumeToken(tok::ellipsis, EllipsisLocs[3]);
1008 // Check if this is a message send before we act on a possible init-capture.
1009 if (Tentative && Tok.is(tok::identifier) &&
1010 NextToken().isOneOf(tok::colon, tok::r_square)) {
1011 // This can only be a message send. We're done with disambiguation.
1012 *Tentative = LambdaIntroducerTentativeParse::MessageSend;
1016 // Ensure that any ellipsis was in the right place.
1017 SourceLocation EllipsisLoc;
1018 if (std::any_of(std::begin(EllipsisLocs), std::end(EllipsisLocs),
1019 [](SourceLocation Loc) { return Loc.isValid(); })) {
1020 // The '...' should appear before the identifier in an init-capture, and
1021 // after the identifier otherwise.
1022 bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit;
1023 SourceLocation *ExpectedEllipsisLoc =
1024 !InitCapture ? &EllipsisLocs[2] :
1025 Kind == LCK_ByRef ? &EllipsisLocs[1] :
1027 EllipsisLoc = *ExpectedEllipsisLoc;
1029 unsigned DiagID = 0;
1030 if (EllipsisLoc.isInvalid()) {
1031 DiagID = diag::err_lambda_capture_misplaced_ellipsis;
1032 for (SourceLocation Loc : EllipsisLocs) {
1037 unsigned NumEllipses = std::accumulate(
1038 std::begin(EllipsisLocs), std::end(EllipsisLocs), 0,
1039 [](int N, SourceLocation Loc) { return N + Loc.isValid(); });
1040 if (NumEllipses > 1)
1041 DiagID = diag::err_lambda_capture_multiple_ellipses;
1044 NonTentativeAction([&] {
1045 // Point the diagnostic at the first misplaced ellipsis.
1046 SourceLocation DiagLoc;
1047 for (SourceLocation &Loc : EllipsisLocs) {
1048 if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) {
1053 assert(DiagLoc.isValid() && "no location for diagnostic");
1055 // Issue the diagnostic and produce fixits showing where the ellipsis
1056 // should have been written.
1057 auto &&D = Diag(DiagLoc, DiagID);
1058 if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) {
1059 SourceLocation ExpectedLoc =
1061 : Lexer::getLocForEndOfToken(
1062 Loc, 0, PP.getSourceManager(), getLangOpts());
1063 D << InitCapture << FixItHint::CreateInsertion(ExpectedLoc, "...");
1065 for (SourceLocation &Loc : EllipsisLocs) {
1066 if (&Loc != ExpectedEllipsisLoc && Loc.isValid())
1067 D << FixItHint::CreateRemoval(Loc);
1073 // Process the init-capture initializers now rather than delaying until we
1074 // form the lambda-expression so that they can be handled in the context
1075 // enclosing the lambda-expression, rather than in the context of the
1076 // lambda-expression itself.
1077 ParsedType InitCaptureType;
1078 if (Init.isUsable())
1079 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
1080 if (Init.isUsable()) {
1081 NonTentativeAction([&] {
1082 // Get the pointer and store it in an lvalue, so we can use it as an
1084 Expr *InitExpr = Init.get();
1085 // This performs any lvalue-to-rvalue conversions if necessary, which
1086 // can affect what gets captured in the containing decl-context.
1087 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
1088 Loc, Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, InitExpr);
1093 SourceLocation LocEnd = PrevTokLocation;
1095 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
1096 InitCaptureType, SourceRange(LocStart, LocEnd));
1100 Intro.Range.setEnd(T.getCloseLocation());
1104 static void tryConsumeLambdaSpecifierToken(Parser &P,
1105 SourceLocation &MutableLoc,
1106 SourceLocation &ConstexprLoc,
1107 SourceLocation &ConstevalLoc,
1108 SourceLocation &DeclEndLoc) {
1109 assert(MutableLoc.isInvalid());
1110 assert(ConstexprLoc.isInvalid());
1111 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1112 // to the final of those locations. Emit an error if we have multiple
1113 // copies of those keywords and recover.
1116 switch (P.getCurToken().getKind()) {
1117 case tok::kw_mutable: {
1118 if (MutableLoc.isValid()) {
1119 P.Diag(P.getCurToken().getLocation(),
1120 diag::err_lambda_decl_specifier_repeated)
1121 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1123 MutableLoc = P.ConsumeToken();
1124 DeclEndLoc = MutableLoc;
1127 case tok::kw_constexpr:
1128 if (ConstexprLoc.isValid()) {
1129 P.Diag(P.getCurToken().getLocation(),
1130 diag::err_lambda_decl_specifier_repeated)
1131 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1133 ConstexprLoc = P.ConsumeToken();
1134 DeclEndLoc = ConstexprLoc;
1136 case tok::kw_consteval:
1137 if (ConstevalLoc.isValid()) {
1138 P.Diag(P.getCurToken().getLocation(),
1139 diag::err_lambda_decl_specifier_repeated)
1140 << 2 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1142 ConstevalLoc = P.ConsumeToken();
1143 DeclEndLoc = ConstevalLoc;
1152 addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1154 if (ConstexprLoc.isValid()) {
1155 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1156 ? diag::ext_constexpr_on_lambda_cxx17
1157 : diag::warn_cxx14_compat_constexpr_on_lambda);
1158 const char *PrevSpec = nullptr;
1159 unsigned DiagID = 0;
1160 DS.SetConstexprSpec(CSK_constexpr, ConstexprLoc, PrevSpec, DiagID);
1161 assert(PrevSpec == nullptr && DiagID == 0 &&
1162 "Constexpr cannot have been set previously!");
1166 static void addConstevalToLambdaDeclSpecifier(Parser &P,
1167 SourceLocation ConstevalLoc,
1169 if (ConstevalLoc.isValid()) {
1170 P.Diag(ConstevalLoc, diag::warn_cxx20_compat_consteval);
1171 const char *PrevSpec = nullptr;
1172 unsigned DiagID = 0;
1173 DS.SetConstexprSpec(CSK_consteval, ConstevalLoc, PrevSpec, DiagID);
1175 P.Diag(ConstevalLoc, DiagID) << PrevSpec;
1179 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1181 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1182 LambdaIntroducer &Intro) {
1183 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1184 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1186 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1187 "lambda expression parsing");
1191 // FIXME: Call into Actions to add any init-capture declarations to the
1192 // scope while parsing the lambda-declarator and compound-statement.
1194 // Parse lambda-declarator[opt].
1195 DeclSpec DS(AttrFactory);
1196 Declarator D(DS, DeclaratorContext::LambdaExprContext);
1197 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1198 Actions.PushLambdaScope();
1200 ParsedAttributes Attr(AttrFactory);
1201 SourceLocation DeclLoc = Tok.getLocation();
1202 if (getLangOpts().CUDA) {
1203 // In CUDA code, GNU attributes are allowed to appear immediately after the
1204 // "[...]", even if there is no "(...)" before the lambda body.
1205 MaybeParseGNUAttributes(D);
1208 // Helper to emit a warning if we see a CUDA host/device/global attribute
1209 // after '(...)'. nvcc doesn't accept this.
1210 auto WarnIfHasCUDATargetAttr = [&] {
1211 if (getLangOpts().CUDA)
1212 for (const ParsedAttr &A : Attr)
1213 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1214 A.getKind() == ParsedAttr::AT_CUDAHost ||
1215 A.getKind() == ParsedAttr::AT_CUDAGlobal)
1216 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1217 << A.getName()->getName();
1220 // FIXME: Consider allowing this as an extension for GCC compatibiblity.
1221 const bool HasExplicitTemplateParams = Tok.is(tok::less);
1222 ParseScope TemplateParamScope(this, Scope::TemplateParamScope,
1223 /*EnteredScope=*/HasExplicitTemplateParams);
1224 if (HasExplicitTemplateParams) {
1225 Diag(Tok, getLangOpts().CPlusPlus2a
1226 ? diag::warn_cxx17_compat_lambda_template_parameter_list
1227 : diag::ext_lambda_template_parameter_list);
1229 SmallVector<NamedDecl*, 4> TemplateParams;
1230 SourceLocation LAngleLoc, RAngleLoc;
1231 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
1232 TemplateParams, LAngleLoc, RAngleLoc)) {
1233 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1237 if (TemplateParams.empty()) {
1239 diag::err_lambda_template_parameter_list_empty);
1241 Actions.ActOnLambdaExplicitTemplateParameterList(
1242 LAngleLoc, TemplateParams, RAngleLoc);
1243 ++CurTemplateDepthTracker;
1247 TypeResult TrailingReturnType;
1248 if (Tok.is(tok::l_paren)) {
1249 ParseScope PrototypeScope(this,
1250 Scope::FunctionPrototypeScope |
1251 Scope::FunctionDeclarationScope |
1254 BalancedDelimiterTracker T(*this, tok::l_paren);
1256 SourceLocation LParenLoc = T.getOpenLocation();
1258 // Parse parameter-declaration-clause.
1259 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1260 SourceLocation EllipsisLoc;
1262 if (Tok.isNot(tok::r_paren)) {
1263 Actions.RecordParsingTemplateParameterDepth(
1264 CurTemplateDepthTracker.getOriginalDepth());
1266 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1268 // For a generic lambda, each 'auto' within the parameter declaration
1269 // clause creates a template type parameter, so increment the depth.
1270 // If we've parsed any explicit template parameters, then the depth will
1271 // have already been incremented. So we make sure that at most a single
1272 // depth level is added.
1273 if (Actions.getCurGenericLambda())
1274 CurTemplateDepthTracker.setAddedDepth(1);
1278 SourceLocation RParenLoc = T.getCloseLocation();
1279 SourceLocation DeclEndLoc = RParenLoc;
1281 // GNU-style attributes must be parsed before the mutable specifier to be
1282 // compatible with GCC.
1283 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1285 // MSVC-style attributes must be parsed before the mutable specifier to be
1286 // compatible with MSVC.
1287 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1289 // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update the
1291 SourceLocation MutableLoc;
1292 SourceLocation ConstexprLoc;
1293 SourceLocation ConstevalLoc;
1294 tryConsumeLambdaSpecifierToken(*this, MutableLoc, ConstexprLoc,
1295 ConstevalLoc, DeclEndLoc);
1297 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1298 addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS);
1299 // Parse exception-specification[opt].
1300 ExceptionSpecificationType ESpecType = EST_None;
1301 SourceRange ESpecRange;
1302 SmallVector<ParsedType, 2> DynamicExceptions;
1303 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1304 ExprResult NoexceptExpr;
1305 CachedTokens *ExceptionSpecTokens;
1306 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1309 DynamicExceptionRanges,
1311 ExceptionSpecTokens);
1313 if (ESpecType != EST_None)
1314 DeclEndLoc = ESpecRange.getEnd();
1316 // Parse attribute-specifier[opt].
1317 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1319 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1321 // Parse trailing-return-type[opt].
1322 if (Tok.is(tok::arrow)) {
1323 FunLocalRangeEnd = Tok.getLocation();
1325 TrailingReturnType =
1326 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1327 if (Range.getEnd().isValid())
1328 DeclEndLoc = Range.getEnd();
1331 PrototypeScope.Exit();
1333 WarnIfHasCUDATargetAttr();
1335 SourceLocation NoLoc;
1336 D.AddTypeInfo(DeclaratorChunk::getFunction(
1338 /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1339 ParamInfo.size(), EllipsisLoc, RParenLoc,
1340 /*RefQualifierIsLvalueRef=*/true,
1341 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
1342 ESpecRange, DynamicExceptions.data(),
1343 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1344 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1345 /*ExceptionSpecTokens*/ nullptr,
1346 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1347 TrailingReturnType),
1348 std::move(Attr), DeclEndLoc);
1349 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1350 tok::kw_constexpr, tok::kw_consteval) ||
1351 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1352 // It's common to forget that one needs '()' before 'mutable', an attribute
1353 // specifier, or the result type. Deal with this.
1354 unsigned TokKind = 0;
1355 switch (Tok.getKind()) {
1356 case tok::kw_mutable: TokKind = 0; break;
1357 case tok::arrow: TokKind = 1; break;
1358 case tok::kw___attribute:
1359 case tok::l_square: TokKind = 2; break;
1360 case tok::kw_constexpr: TokKind = 3; break;
1361 case tok::kw_consteval: TokKind = 4; break;
1362 default: llvm_unreachable("Unknown token kind");
1365 Diag(Tok, diag::err_lambda_missing_parens)
1367 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1368 SourceLocation DeclEndLoc = DeclLoc;
1370 // GNU-style attributes must be parsed before the mutable specifier to be
1371 // compatible with GCC.
1372 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1374 // Parse 'mutable', if it's there.
1375 SourceLocation MutableLoc;
1376 if (Tok.is(tok::kw_mutable)) {
1377 MutableLoc = ConsumeToken();
1378 DeclEndLoc = MutableLoc;
1381 // Parse attribute-specifier[opt].
1382 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1384 // Parse the return type, if there is one.
1385 if (Tok.is(tok::arrow)) {
1387 TrailingReturnType =
1388 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1389 if (Range.getEnd().isValid())
1390 DeclEndLoc = Range.getEnd();
1393 WarnIfHasCUDATargetAttr();
1395 SourceLocation NoLoc;
1396 D.AddTypeInfo(DeclaratorChunk::getFunction(
1398 /*IsAmbiguous=*/false,
1399 /*LParenLoc=*/NoLoc,
1402 /*EllipsisLoc=*/NoLoc,
1403 /*RParenLoc=*/NoLoc,
1404 /*RefQualifierIsLvalueRef=*/true,
1405 /*RefQualifierLoc=*/NoLoc, MutableLoc, EST_None,
1406 /*ESpecRange=*/SourceRange(),
1407 /*Exceptions=*/nullptr,
1408 /*ExceptionRanges=*/nullptr,
1409 /*NumExceptions=*/0,
1410 /*NoexceptExpr=*/nullptr,
1411 /*ExceptionSpecTokens=*/nullptr,
1412 /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1413 TrailingReturnType),
1414 std::move(Attr), DeclEndLoc);
1417 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1419 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1420 Scope::CompoundStmtScope;
1421 ParseScope BodyScope(this, ScopeFlags);
1423 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1425 // Parse compound-statement.
1426 if (!Tok.is(tok::l_brace)) {
1427 Diag(Tok, diag::err_expected_lambda_body);
1428 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1432 StmtResult Stmt(ParseCompoundStatementBody());
1434 TemplateParamScope.Exit();
1436 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1437 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1439 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1443 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1446 /// postfix-expression: [C++ 5.2p1]
1447 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1448 /// 'static_cast' '<' type-name '>' '(' expression ')'
1449 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1450 /// 'const_cast' '<' type-name '>' '(' expression ')'
1452 ExprResult Parser::ParseCXXCasts() {
1453 tok::TokenKind Kind = Tok.getKind();
1454 const char *CastName = nullptr; // For error messages
1457 default: llvm_unreachable("Unknown C++ cast!");
1458 case tok::kw_const_cast: CastName = "const_cast"; break;
1459 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1460 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1461 case tok::kw_static_cast: CastName = "static_cast"; break;
1464 SourceLocation OpLoc = ConsumeToken();
1465 SourceLocation LAngleBracketLoc = Tok.getLocation();
1467 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1468 // diagnose error, suggest fix, and recover parsing.
1469 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1470 Token Next = NextToken();
1471 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1472 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1475 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1478 // Parse the common declaration-specifiers piece.
1479 DeclSpec DS(AttrFactory);
1480 ParseSpecifierQualifierList(DS);
1482 // Parse the abstract-declarator, if present.
1483 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1484 ParseDeclarator(DeclaratorInfo);
1486 SourceLocation RAngleBracketLoc = Tok.getLocation();
1488 if (ExpectAndConsume(tok::greater))
1489 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1491 BalancedDelimiterTracker T(*this, tok::l_paren);
1493 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1496 ExprResult Result = ParseExpression();
1501 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1502 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1503 LAngleBracketLoc, DeclaratorInfo,
1505 T.getOpenLocation(), Result.get(),
1506 T.getCloseLocation());
1511 /// ParseCXXTypeid - This handles the C++ typeid expression.
1513 /// postfix-expression: [C++ 5.2p1]
1514 /// 'typeid' '(' expression ')'
1515 /// 'typeid' '(' type-id ')'
1517 ExprResult Parser::ParseCXXTypeid() {
1518 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1520 SourceLocation OpLoc = ConsumeToken();
1521 SourceLocation LParenLoc, RParenLoc;
1522 BalancedDelimiterTracker T(*this, tok::l_paren);
1524 // typeid expressions are always parenthesized.
1525 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1527 LParenLoc = T.getOpenLocation();
1531 // C++0x [expr.typeid]p3:
1532 // When typeid is applied to an expression other than an lvalue of a
1533 // polymorphic class type [...] The expression is an unevaluated
1534 // operand (Clause 5).
1536 // Note that we can't tell whether the expression is an lvalue of a
1537 // polymorphic class type until after we've parsed the expression; we
1538 // speculatively assume the subexpression is unevaluated, and fix it up
1541 // We enter the unevaluated context before trying to determine whether we
1542 // have a type-id, because the tentative parse logic will try to resolve
1543 // names, and must treat them as unevaluated.
1544 EnterExpressionEvaluationContext Unevaluated(
1545 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1546 Sema::ReuseLambdaContextDecl);
1548 if (isTypeIdInParens()) {
1549 TypeResult Ty = ParseTypeName();
1553 RParenLoc = T.getCloseLocation();
1554 if (Ty.isInvalid() || RParenLoc.isInvalid())
1557 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1558 Ty.get().getAsOpaquePtr(), RParenLoc);
1560 Result = ParseExpression();
1563 if (Result.isInvalid())
1564 SkipUntil(tok::r_paren, StopAtSemi);
1567 RParenLoc = T.getCloseLocation();
1568 if (RParenLoc.isInvalid())
1571 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1572 Result.get(), RParenLoc);
1579 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1581 /// '__uuidof' '(' expression ')'
1582 /// '__uuidof' '(' type-id ')'
1584 ExprResult Parser::ParseCXXUuidof() {
1585 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1587 SourceLocation OpLoc = ConsumeToken();
1588 BalancedDelimiterTracker T(*this, tok::l_paren);
1590 // __uuidof expressions are always parenthesized.
1591 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1596 if (isTypeIdInParens()) {
1597 TypeResult Ty = ParseTypeName();
1605 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1606 Ty.get().getAsOpaquePtr(),
1607 T.getCloseLocation());
1609 EnterExpressionEvaluationContext Unevaluated(
1610 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1611 Result = ParseExpression();
1614 if (Result.isInvalid())
1615 SkipUntil(tok::r_paren, StopAtSemi);
1619 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1621 Result.get(), T.getCloseLocation());
1628 /// Parse a C++ pseudo-destructor expression after the base,
1629 /// . or -> operator, and nested-name-specifier have already been
1632 /// postfix-expression: [C++ 5.2]
1633 /// postfix-expression . pseudo-destructor-name
1634 /// postfix-expression -> pseudo-destructor-name
1636 /// pseudo-destructor-name:
1637 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1638 /// ::[opt] nested-name-specifier template simple-template-id ::
1640 /// ::[opt] nested-name-specifier[opt] ~type-name
1643 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1644 tok::TokenKind OpKind,
1646 ParsedType ObjectType) {
1647 // We're parsing either a pseudo-destructor-name or a dependent
1648 // member access that has the same form as a
1649 // pseudo-destructor-name. We parse both in the same way and let
1650 // the action model sort them out.
1652 // Note that the ::[opt] nested-name-specifier[opt] has already
1653 // been parsed, and if there was a simple-template-id, it has
1654 // been coalesced into a template-id annotation token.
1655 UnqualifiedId FirstTypeName;
1656 SourceLocation CCLoc;
1657 if (Tok.is(tok::identifier)) {
1658 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1660 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1661 CCLoc = ConsumeToken();
1662 } else if (Tok.is(tok::annot_template_id)) {
1663 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1664 // store it in the pseudo-dtor node (to be used when instantiating it).
1665 FirstTypeName.setTemplateId(
1666 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1667 ConsumeAnnotationToken();
1668 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1669 CCLoc = ConsumeToken();
1671 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1675 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1676 SourceLocation TildeLoc = ConsumeToken();
1678 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1679 DeclSpec DS(AttrFactory);
1680 ParseDecltypeSpecifier(DS);
1681 if (DS.getTypeSpecType() == TST_error)
1683 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1687 if (!Tok.is(tok::identifier)) {
1688 Diag(Tok, diag::err_destructor_tilde_identifier);
1692 // Parse the second type.
1693 UnqualifiedId SecondTypeName;
1694 IdentifierInfo *Name = Tok.getIdentifierInfo();
1695 SourceLocation NameLoc = ConsumeToken();
1696 SecondTypeName.setIdentifier(Name, NameLoc);
1698 // If there is a '<', the second type name is a template-id. Parse
1700 if (Tok.is(tok::less) &&
1701 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1703 false, ObjectType, SecondTypeName,
1704 /*AssumeTemplateId=*/true))
1707 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1708 SS, FirstTypeName, CCLoc, TildeLoc,
1712 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1714 /// boolean-literal: [C++ 2.13.5]
1717 ExprResult Parser::ParseCXXBoolLiteral() {
1718 tok::TokenKind Kind = Tok.getKind();
1719 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1722 /// ParseThrowExpression - This handles the C++ throw expression.
1724 /// throw-expression: [C++ 15]
1725 /// 'throw' assignment-expression[opt]
1726 ExprResult Parser::ParseThrowExpression() {
1727 assert(Tok.is(tok::kw_throw) && "Not throw!");
1728 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1730 // If the current token isn't the start of an assignment-expression,
1731 // then the expression is not present. This handles things like:
1732 // "C ? throw : (void)42", which is crazy but legal.
1733 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1740 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1743 ExprResult Expr(ParseAssignmentExpression());
1744 if (Expr.isInvalid()) return Expr;
1745 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1749 /// Parse the C++ Coroutines co_yield expression.
1751 /// co_yield-expression:
1752 /// 'co_yield' assignment-expression[opt]
1753 ExprResult Parser::ParseCoyieldExpression() {
1754 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1756 SourceLocation Loc = ConsumeToken();
1757 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1758 : ParseAssignmentExpression();
1759 if (!Expr.isInvalid())
1760 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1764 /// ParseCXXThis - This handles the C++ 'this' pointer.
1766 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1767 /// a non-lvalue expression whose value is the address of the object for which
1768 /// the function is called.
1769 ExprResult Parser::ParseCXXThis() {
1770 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1771 SourceLocation ThisLoc = ConsumeToken();
1772 return Actions.ActOnCXXThis(ThisLoc);
1775 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1776 /// Can be interpreted either as function-style casting ("int(x)")
1777 /// or class type construction ("ClassType(x,y,z)")
1778 /// or creation of a value-initialized type ("int()").
1779 /// See [C++ 5.2.3].
1781 /// postfix-expression: [C++ 5.2p1]
1782 /// simple-type-specifier '(' expression-list[opt] ')'
1783 /// [C++0x] simple-type-specifier braced-init-list
1784 /// typename-specifier '(' expression-list[opt] ')'
1785 /// [C++0x] typename-specifier braced-init-list
1787 /// In C++1z onwards, the type specifier can also be a template-name.
1789 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1790 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCastContext);
1791 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1793 assert((Tok.is(tok::l_paren) ||
1794 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1795 && "Expected '(' or '{'!");
1797 if (Tok.is(tok::l_brace)) {
1798 ExprResult Init = ParseBraceInitializer();
1799 if (Init.isInvalid())
1801 Expr *InitList = Init.get();
1802 return Actions.ActOnCXXTypeConstructExpr(
1803 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
1804 InitList->getEndLoc(), /*ListInitialization=*/true);
1806 BalancedDelimiterTracker T(*this, tok::l_paren);
1809 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1812 CommaLocsTy CommaLocs;
1814 auto RunSignatureHelp = [&]() {
1815 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
1816 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1817 DS.getEndLoc(), Exprs, T.getOpenLocation());
1818 CalledSignatureHelp = true;
1819 return PreferredType;
1822 if (Tok.isNot(tok::r_paren)) {
1823 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1824 PreferredType.enterFunctionArgument(Tok.getLocation(),
1827 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1829 SkipUntil(tok::r_paren, StopAtSemi);
1837 // TypeRep could be null, if it references an invalid typedef.
1841 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1842 "Unexpected number of commas!");
1843 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1844 Exprs, T.getCloseLocation(),
1845 /*ListInitialization=*/false);
1849 /// ParseCXXCondition - if/switch/while condition expression.
1853 /// type-specifier-seq declarator '=' assignment-expression
1854 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1855 /// [C++11] type-specifier-seq declarator braced-init-list
1856 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1857 /// brace-or-equal-initializer
1858 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1859 /// '=' assignment-expression
1861 /// In C++1z, a condition may in some contexts be preceded by an
1862 /// optional init-statement. This function will parse that too.
1864 /// \param InitStmt If non-null, an init-statement is permitted, and if present
1865 /// will be parsed and stored here.
1867 /// \param Loc The location of the start of the statement that requires this
1868 /// condition, e.g., the "for" in a for loop.
1870 /// \param FRI If non-null, a for range declaration is permitted, and if
1871 /// present will be parsed and stored here, and a null result will be returned.
1873 /// \returns The parsed condition.
1874 Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1876 Sema::ConditionKind CK,
1877 ForRangeInfo *FRI) {
1878 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1879 PreferredType.enterCondition(Actions, Tok.getLocation());
1881 if (Tok.is(tok::code_completion)) {
1882 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1884 return Sema::ConditionError();
1887 ParsedAttributesWithRange attrs(AttrFactory);
1888 MaybeParseCXX11Attributes(attrs);
1890 const auto WarnOnInit = [this, &CK] {
1891 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1892 ? diag::warn_cxx14_compat_init_statement
1893 : diag::ext_init_statement)
1894 << (CK == Sema::ConditionKind::Switch);
1897 // Determine what kind of thing we have.
1898 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
1899 case ConditionOrInitStatement::Expression: {
1900 ProhibitAttributes(attrs);
1902 // We can have an empty expression here.
1904 if (InitStmt && Tok.is(tok::semi)) {
1906 SourceLocation SemiLoc = Tok.getLocation();
1907 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
1908 Diag(SemiLoc, diag::warn_empty_init_statement)
1909 << (CK == Sema::ConditionKind::Switch)
1910 << FixItHint::CreateRemoval(SemiLoc);
1913 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1914 return ParseCXXCondition(nullptr, Loc, CK);
1917 // Parse the expression.
1918 ExprResult Expr = ParseExpression(); // expression
1919 if (Expr.isInvalid())
1920 return Sema::ConditionError();
1922 if (InitStmt && Tok.is(tok::semi)) {
1924 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1926 return ParseCXXCondition(nullptr, Loc, CK);
1929 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
1932 case ConditionOrInitStatement::InitStmtDecl: {
1934 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1936 ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1937 attrs, /*RequireSemi=*/true);
1938 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1939 return ParseCXXCondition(nullptr, Loc, CK);
1942 case ConditionOrInitStatement::ForRangeDecl: {
1943 assert(FRI && "should not parse a for range declaration here");
1944 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1945 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1946 DeclaratorContext::ForContext, DeclEnd, attrs, false, FRI);
1947 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1948 return Sema::ConditionResult();
1951 case ConditionOrInitStatement::ConditionDecl:
1952 case ConditionOrInitStatement::Error:
1956 // type-specifier-seq
1957 DeclSpec DS(AttrFactory);
1958 DS.takeAttributesFrom(attrs);
1959 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
1962 Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
1963 ParseDeclarator(DeclaratorInfo);
1965 // simple-asm-expr[opt]
1966 if (Tok.is(tok::kw_asm)) {
1968 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1969 if (AsmLabel.isInvalid()) {
1970 SkipUntil(tok::semi, StopAtSemi);
1971 return Sema::ConditionError();
1973 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1974 DeclaratorInfo.SetRangeEnd(Loc);
1977 // If attributes are present, parse them.
1978 MaybeParseGNUAttributes(DeclaratorInfo);
1980 // Type-check the declaration itself.
1981 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1983 if (Dcl.isInvalid())
1984 return Sema::ConditionError();
1985 Decl *DeclOut = Dcl.get();
1987 // '=' assignment-expression
1988 // If a '==' or '+=' is found, suggest a fixit to '='.
1989 bool CopyInitialization = isTokenEqualOrEqualTypo();
1990 if (CopyInitialization)
1993 ExprResult InitExpr = ExprError();
1994 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1995 Diag(Tok.getLocation(),
1996 diag::warn_cxx98_compat_generalized_initializer_lists);
1997 InitExpr = ParseBraceInitializer();
1998 } else if (CopyInitialization) {
1999 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
2000 InitExpr = ParseAssignmentExpression();
2001 } else if (Tok.is(tok::l_paren)) {
2002 // This was probably an attempt to initialize the variable.
2003 SourceLocation LParen = ConsumeParen(), RParen = LParen;
2004 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
2005 RParen = ConsumeParen();
2006 Diag(DeclOut->getLocation(),
2007 diag::err_expected_init_in_condition_lparen)
2008 << SourceRange(LParen, RParen);
2010 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
2013 if (!InitExpr.isInvalid())
2014 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
2016 Actions.ActOnInitializerError(DeclOut);
2018 Actions.FinalizeDeclaration(DeclOut);
2019 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
2022 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2023 /// This should only be called when the current token is known to be part of
2024 /// simple-type-specifier.
2026 /// simple-type-specifier:
2027 /// '::'[opt] nested-name-specifier[opt] type-name
2028 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
2040 /// [GNU] typeof-specifier
2041 /// [C++0x] auto [TODO]
2048 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
2049 DS.SetRangeStart(Tok.getLocation());
2050 const char *PrevSpec;
2052 SourceLocation Loc = Tok.getLocation();
2053 const clang::PrintingPolicy &Policy =
2054 Actions.getASTContext().getPrintingPolicy();
2056 switch (Tok.getKind()) {
2057 case tok::identifier: // foo::bar
2058 case tok::coloncolon: // ::foo::bar
2059 llvm_unreachable("Annotation token should already be formed!");
2061 llvm_unreachable("Not a simple-type-specifier token!");
2064 case tok::annot_typename: {
2065 if (getTypeAnnotation(Tok))
2066 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
2067 getTypeAnnotation(Tok), Policy);
2069 DS.SetTypeSpecError();
2071 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2072 ConsumeAnnotationToken();
2074 DS.Finish(Actions, Policy);
2080 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
2083 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
2085 case tok::kw___int64:
2086 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
2088 case tok::kw_signed:
2089 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
2091 case tok::kw_unsigned:
2092 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
2095 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
2098 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
2101 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
2103 case tok::kw___int128:
2104 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
2107 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
2110 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
2112 case tok::kw_double:
2113 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
2115 case tok::kw__Float16:
2116 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2118 case tok::kw___float128:
2119 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2121 case tok::kw_wchar_t:
2122 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
2124 case tok::kw_char8_t:
2125 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2127 case tok::kw_char16_t:
2128 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
2130 case tok::kw_char32_t:
2131 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
2134 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
2136 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
2137 case tok::kw_##ImgType##_t: \
2138 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2141 #include "clang/Basic/OpenCLImageTypes.def"
2143 case tok::annot_decltype:
2144 case tok::kw_decltype:
2145 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2146 return DS.Finish(Actions, Policy);
2148 // GNU typeof support.
2149 case tok::kw_typeof:
2150 ParseTypeofSpecifier(DS);
2151 DS.Finish(Actions, Policy);
2155 DS.SetRangeEnd(PrevTokLocation);
2156 DS.Finish(Actions, Policy);
2159 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2160 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
2161 /// e.g., "const short int". Note that the DeclSpec is *not* finished
2162 /// by parsing the type-specifier-seq, because these sequences are
2163 /// typically followed by some form of declarator. Returns true and
2164 /// emits diagnostics if this is not a type-specifier-seq, false
2167 /// type-specifier-seq: [C++ 8.1]
2168 /// type-specifier type-specifier-seq[opt]
2170 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
2171 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
2172 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2176 /// Finish parsing a C++ unqualified-id that is a template-id of
2179 /// This routine is invoked when a '<' is encountered after an identifier or
2180 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2181 /// whether the unqualified-id is actually a template-id. This routine will
2182 /// then parse the template arguments and form the appropriate template-id to
2183 /// return to the caller.
2185 /// \param SS the nested-name-specifier that precedes this template-id, if
2186 /// we're actually parsing a qualified-id.
2188 /// \param Name for constructor and destructor names, this is the actual
2189 /// identifier that may be a template-name.
2191 /// \param NameLoc the location of the class-name in a constructor or
2194 /// \param EnteringContext whether we're entering the scope of the
2195 /// nested-name-specifier.
2197 /// \param ObjectType if this unqualified-id occurs within a member access
2198 /// expression, the type of the base object whose member is being accessed.
2200 /// \param Id as input, describes the template-name or operator-function-id
2201 /// that precedes the '<'. If template arguments were parsed successfully,
2202 /// will be updated with the template-id.
2204 /// \param AssumeTemplateId When true, this routine will assume that the name
2205 /// refers to a template without performing name lookup to verify.
2207 /// \returns true if a parse error occurred, false otherwise.
2208 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2209 SourceLocation TemplateKWLoc,
2210 IdentifierInfo *Name,
2211 SourceLocation NameLoc,
2212 bool EnteringContext,
2213 ParsedType ObjectType,
2215 bool AssumeTemplateId) {
2216 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2218 TemplateTy Template;
2219 TemplateNameKind TNK = TNK_Non_template;
2220 switch (Id.getKind()) {
2221 case UnqualifiedIdKind::IK_Identifier:
2222 case UnqualifiedIdKind::IK_OperatorFunctionId:
2223 case UnqualifiedIdKind::IK_LiteralOperatorId:
2224 if (AssumeTemplateId) {
2225 // We defer the injected-class-name checks until we've found whether
2226 // this template-id is used to form a nested-name-specifier or not.
2227 TNK = Actions.ActOnDependentTemplateName(
2228 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2229 Template, /*AllowInjectedClassName*/ true);
2230 if (TNK == TNK_Non_template)
2233 bool MemberOfUnknownSpecialization;
2234 TNK = Actions.isTemplateName(getCurScope(), SS,
2235 TemplateKWLoc.isValid(), Id,
2236 ObjectType, EnteringContext, Template,
2237 MemberOfUnknownSpecialization);
2238 // If lookup found nothing but we're assuming that this is a template
2239 // name, double-check that makes sense syntactically before committing
2241 if (TNK == TNK_Undeclared_template &&
2242 isTemplateArgumentList(0) == TPResult::False)
2245 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2246 ObjectType && isTemplateArgumentList(0) == TPResult::True) {
2247 // We have something like t->getAs<T>(), where getAs is a
2248 // member of an unknown specialization. However, this will only
2249 // parse correctly as a template, so suggest the keyword 'template'
2250 // before 'getAs' and treat this as a dependent template name.
2252 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2253 Name = Id.Identifier->getName();
2256 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
2257 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2259 Name += Id.Identifier->getName();
2261 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2263 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2264 TNK = Actions.ActOnDependentTemplateName(
2265 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2266 Template, /*AllowInjectedClassName*/ true);
2267 if (TNK == TNK_Non_template)
2273 case UnqualifiedIdKind::IK_ConstructorName: {
2274 UnqualifiedId TemplateName;
2275 bool MemberOfUnknownSpecialization;
2276 TemplateName.setIdentifier(Name, NameLoc);
2277 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2278 TemplateName, ObjectType,
2279 EnteringContext, Template,
2280 MemberOfUnknownSpecialization);
2284 case UnqualifiedIdKind::IK_DestructorName: {
2285 UnqualifiedId TemplateName;
2286 bool MemberOfUnknownSpecialization;
2287 TemplateName.setIdentifier(Name, NameLoc);
2289 TNK = Actions.ActOnDependentTemplateName(
2290 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2291 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2292 if (TNK == TNK_Non_template)
2295 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2296 TemplateName, ObjectType,
2297 EnteringContext, Template,
2298 MemberOfUnknownSpecialization);
2300 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2301 Diag(NameLoc, diag::err_destructor_template_id)
2302 << Name << SS.getRange();
2313 if (TNK == TNK_Non_template)
2316 // Parse the enclosed template argument list.
2317 SourceLocation LAngleLoc, RAngleLoc;
2318 TemplateArgList TemplateArgs;
2319 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2323 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2324 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2325 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
2326 // Form a parsed representation of the template-id to be stored in the
2329 // FIXME: Store name for literal operator too.
2330 IdentifierInfo *TemplateII =
2331 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2333 OverloadedOperatorKind OpKind =
2334 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2336 : Id.OperatorFunctionId.Operator;
2338 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2339 SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2340 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2342 Id.setTemplateId(TemplateId);
2346 // Bundle the template arguments together.
2347 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2349 // Constructor and destructor names.
2350 TypeResult Type = Actions.ActOnTemplateIdType(
2351 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2352 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
2353 if (Type.isInvalid())
2356 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
2357 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2359 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2364 /// Parse an operator-function-id or conversion-function-id as part
2365 /// of a C++ unqualified-id.
2367 /// This routine is responsible only for parsing the operator-function-id or
2368 /// conversion-function-id; it does not handle template arguments in any way.
2371 /// operator-function-id: [C++ 13.5]
2372 /// 'operator' operator
2374 /// operator: one of
2375 /// new delete new[] delete[]
2376 /// + - * / % ^ & | ~
2377 /// ! = < > += -= *= /= %=
2378 /// ^= &= |= << >> >>= <<= == !=
2379 /// <= >= && || ++ -- , ->* ->
2382 /// conversion-function-id: [C++ 12.3.2]
2383 /// operator conversion-type-id
2385 /// conversion-type-id:
2386 /// type-specifier-seq conversion-declarator[opt]
2388 /// conversion-declarator:
2389 /// ptr-operator conversion-declarator[opt]
2392 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2393 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2395 /// \param EnteringContext whether we are entering the scope of the
2396 /// nested-name-specifier.
2398 /// \param ObjectType if this unqualified-id occurs within a member access
2399 /// expression, the type of the base object whose member is being accessed.
2401 /// \param Result on a successful parse, contains the parsed unqualified-id.
2403 /// \returns true if parsing fails, false otherwise.
2404 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2405 ParsedType ObjectType,
2406 UnqualifiedId &Result) {
2407 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2409 // Consume the 'operator' keyword.
2410 SourceLocation KeywordLoc = ConsumeToken();
2412 // Determine what kind of operator name we have.
2413 unsigned SymbolIdx = 0;
2414 SourceLocation SymbolLocations[3];
2415 OverloadedOperatorKind Op = OO_None;
2416 switch (Tok.getKind()) {
2418 case tok::kw_delete: {
2419 bool isNew = Tok.getKind() == tok::kw_new;
2420 // Consume the 'new' or 'delete'.
2421 SymbolLocations[SymbolIdx++] = ConsumeToken();
2422 // Check for array new/delete.
2423 if (Tok.is(tok::l_square) &&
2424 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2425 // Consume the '[' and ']'.
2426 BalancedDelimiterTracker T(*this, tok::l_square);
2429 if (T.getCloseLocation().isInvalid())
2432 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2433 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2434 Op = isNew? OO_Array_New : OO_Array_Delete;
2436 Op = isNew? OO_New : OO_Delete;
2441 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2443 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2446 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2447 #include "clang/Basic/OperatorKinds.def"
2449 case tok::l_paren: {
2450 // Consume the '(' and ')'.
2451 BalancedDelimiterTracker T(*this, tok::l_paren);
2454 if (T.getCloseLocation().isInvalid())
2457 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2458 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2463 case tok::l_square: {
2464 // Consume the '[' and ']'.
2465 BalancedDelimiterTracker T(*this, tok::l_square);
2468 if (T.getCloseLocation().isInvalid())
2471 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2472 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2477 case tok::code_completion: {
2478 // Code completion for the operator name.
2479 Actions.CodeCompleteOperatorName(getCurScope());
2481 // Don't try to parse any further.
2489 if (Op != OO_None) {
2490 // We have parsed an operator-function-id.
2491 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2495 // Parse a literal-operator-id.
2497 // literal-operator-id: C++11 [over.literal]
2498 // operator string-literal identifier
2499 // operator user-defined-string-literal
2501 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2502 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2504 SourceLocation DiagLoc;
2505 unsigned DiagId = 0;
2507 // We're past translation phase 6, so perform string literal concatenation
2508 // before checking for "".
2509 SmallVector<Token, 4> Toks;
2510 SmallVector<SourceLocation, 4> TokLocs;
2511 while (isTokenStringLiteral()) {
2512 if (!Tok.is(tok::string_literal) && !DiagId) {
2513 // C++11 [over.literal]p1:
2514 // The string-literal or user-defined-string-literal in a
2515 // literal-operator-id shall have no encoding-prefix [...].
2516 DiagLoc = Tok.getLocation();
2517 DiagId = diag::err_literal_operator_string_prefix;
2519 Toks.push_back(Tok);
2520 TokLocs.push_back(ConsumeStringToken());
2523 StringLiteralParser Literal(Toks, PP);
2524 if (Literal.hadError)
2527 // Grab the literal operator's suffix, which will be either the next token
2528 // or a ud-suffix from the string literal.
2529 IdentifierInfo *II = nullptr;
2530 SourceLocation SuffixLoc;
2531 if (!Literal.getUDSuffix().empty()) {
2532 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2534 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2535 Literal.getUDSuffixOffset(),
2536 PP.getSourceManager(), getLangOpts());
2537 } else if (Tok.is(tok::identifier)) {
2538 II = Tok.getIdentifierInfo();
2539 SuffixLoc = ConsumeToken();
2540 TokLocs.push_back(SuffixLoc);
2542 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2546 // The string literal must be empty.
2547 if (!Literal.GetString().empty() || Literal.Pascal) {
2548 // C++11 [over.literal]p1:
2549 // The string-literal or user-defined-string-literal in a
2550 // literal-operator-id shall [...] contain no characters
2551 // other than the implicit terminating '\0'.
2552 DiagLoc = TokLocs.front();
2553 DiagId = diag::err_literal_operator_string_not_empty;
2557 // This isn't a valid literal-operator-id, but we think we know
2558 // what the user meant. Tell them what they should have written.
2559 SmallString<32> Str;
2561 Str += II->getName();
2562 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2563 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2566 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2568 return Actions.checkLiteralOperatorId(SS, Result);
2571 // Parse a conversion-function-id.
2573 // conversion-function-id: [C++ 12.3.2]
2574 // operator conversion-type-id
2576 // conversion-type-id:
2577 // type-specifier-seq conversion-declarator[opt]
2579 // conversion-declarator:
2580 // ptr-operator conversion-declarator[opt]
2582 // Parse the type-specifier-seq.
2583 DeclSpec DS(AttrFactory);
2584 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2587 // Parse the conversion-declarator, which is merely a sequence of
2589 Declarator D(DS, DeclaratorContext::ConversionIdContext);
2590 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2592 // Finish up the type.
2593 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2597 // Note that this is a conversion-function-id.
2598 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2599 D.getSourceRange().getEnd());
2603 /// Parse a C++ unqualified-id (or a C identifier), which describes the
2604 /// name of an entity.
2607 /// unqualified-id: [C++ expr.prim.general]
2609 /// operator-function-id
2610 /// conversion-function-id
2611 /// [C++0x] literal-operator-id [TODO]
2617 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2618 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2620 /// \param EnteringContext whether we are entering the scope of the
2621 /// nested-name-specifier.
2623 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2625 /// \param AllowConstructorName whether we allow parsing a constructor name.
2627 /// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2629 /// \param ObjectType if this unqualified-id occurs within a member access
2630 /// expression, the type of the base object whose member is being accessed.
2632 /// \param Result on a successful parse, contains the parsed unqualified-id.
2634 /// \returns true if parsing fails, false otherwise.
2635 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2636 bool AllowDestructorName,
2637 bool AllowConstructorName,
2638 bool AllowDeductionGuide,
2639 ParsedType ObjectType,
2640 SourceLocation *TemplateKWLoc,
2641 UnqualifiedId &Result) {
2643 *TemplateKWLoc = SourceLocation();
2645 // Handle 'A::template B'. This is for template-ids which have not
2646 // already been annotated by ParseOptionalCXXScopeSpecifier().
2647 bool TemplateSpecified = false;
2648 if (Tok.is(tok::kw_template)) {
2649 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2650 TemplateSpecified = true;
2651 *TemplateKWLoc = ConsumeToken();
2653 SourceLocation TemplateLoc = ConsumeToken();
2654 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2655 << FixItHint::CreateRemoval(TemplateLoc);
2661 // template-id (when it hasn't already been annotated)
2662 if (Tok.is(tok::identifier)) {
2663 // Consume the identifier.
2664 IdentifierInfo *Id = Tok.getIdentifierInfo();
2665 SourceLocation IdLoc = ConsumeToken();
2667 if (!getLangOpts().CPlusPlus) {
2668 // If we're not in C++, only identifiers matter. Record the
2669 // identifier and return.
2670 Result.setIdentifier(Id, IdLoc);
2674 ParsedTemplateTy TemplateName;
2675 if (AllowConstructorName &&
2676 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2677 // We have parsed a constructor name.
2678 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2682 Result.setConstructorName(Ty, IdLoc, IdLoc);
2683 } else if (getLangOpts().CPlusPlus17 &&
2684 AllowDeductionGuide && SS.isEmpty() &&
2685 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2687 // We have parsed a template-name naming a deduction guide.
2688 Result.setDeductionGuideName(TemplateName, IdLoc);
2690 // We have parsed an identifier.
2691 Result.setIdentifier(Id, IdLoc);
2694 // If the next token is a '<', we may have a template.
2695 TemplateTy Template;
2696 if (Tok.is(tok::less))
2697 return ParseUnqualifiedIdTemplateId(
2698 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2699 EnteringContext, ObjectType, Result, TemplateSpecified);
2700 else if (TemplateSpecified &&
2701 Actions.ActOnDependentTemplateName(
2702 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2703 EnteringContext, Template,
2704 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2711 // template-id (already parsed and annotated)
2712 if (Tok.is(tok::annot_template_id)) {
2713 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2715 // If the template-name names the current class, then this is a constructor
2716 if (AllowConstructorName && TemplateId->Name &&
2717 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2719 // C++ [class.qual]p2 specifies that a qualified template-name
2720 // is taken as the constructor name where a constructor can be
2721 // declared. Thus, the template arguments are extraneous, so
2722 // complain about them and remove them entirely.
2723 Diag(TemplateId->TemplateNameLoc,
2724 diag::err_out_of_line_constructor_template_id)
2726 << FixItHint::CreateRemoval(
2727 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2728 ParsedType Ty = Actions.getConstructorName(
2729 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2733 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2734 TemplateId->RAngleLoc);
2735 ConsumeAnnotationToken();
2739 Result.setConstructorTemplateId(TemplateId);
2740 ConsumeAnnotationToken();
2744 // We have already parsed a template-id; consume the annotation token as
2745 // our unqualified-id.
2746 Result.setTemplateId(TemplateId);
2747 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2748 if (TemplateLoc.isValid()) {
2749 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2750 *TemplateKWLoc = TemplateLoc;
2752 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2753 << FixItHint::CreateRemoval(TemplateLoc);
2755 ConsumeAnnotationToken();
2760 // operator-function-id
2761 // conversion-function-id
2762 if (Tok.is(tok::kw_operator)) {
2763 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2766 // If we have an operator-function-id or a literal-operator-id and the next
2767 // token is a '<', we may have a
2770 // operator-function-id < template-argument-list[opt] >
2771 TemplateTy Template;
2772 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2773 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
2775 return ParseUnqualifiedIdTemplateId(
2776 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2777 SourceLocation(), EnteringContext, ObjectType, Result,
2779 else if (TemplateSpecified &&
2780 Actions.ActOnDependentTemplateName(
2781 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2782 EnteringContext, Template,
2783 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2789 if (getLangOpts().CPlusPlus &&
2790 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2791 // C++ [expr.unary.op]p10:
2792 // There is an ambiguity in the unary-expression ~X(), where X is a
2793 // class-name. The ambiguity is resolved in favor of treating ~ as a
2794 // unary complement rather than treating ~X as referring to a destructor.
2797 SourceLocation TildeLoc = ConsumeToken();
2799 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2800 DeclSpec DS(AttrFactory);
2801 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2802 if (ParsedType Type =
2803 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2804 Result.setDestructorName(TildeLoc, Type, EndLoc);
2810 // Parse the class-name.
2811 if (Tok.isNot(tok::identifier)) {
2812 Diag(Tok, diag::err_destructor_tilde_identifier);
2816 // If the user wrote ~T::T, correct it to T::~T.
2817 DeclaratorScopeObj DeclScopeObj(*this, SS);
2818 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2819 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2820 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2821 // it will confuse this recovery logic.
2822 ColonProtectionRAIIObject ColonRAII(*this, false);
2825 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2828 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2830 if (SS.isNotEmpty())
2831 ObjectType = nullptr;
2832 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2834 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2838 // Recover as if the tilde had been written before the identifier.
2839 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2840 << FixItHint::CreateRemoval(TildeLoc)
2841 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2843 // Temporarily enter the scope for the rest of this function.
2844 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2845 DeclScopeObj.EnterDeclaratorScope();
2848 // Parse the class-name (or template-name in a simple-template-id).
2849 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2850 SourceLocation ClassNameLoc = ConsumeToken();
2852 if (Tok.is(tok::less)) {
2853 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2854 return ParseUnqualifiedIdTemplateId(
2855 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2856 ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
2859 // Note that this is a destructor name.
2860 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2861 ClassNameLoc, getCurScope(),
2867 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2871 Diag(Tok, diag::err_expected_unqualified_id)
2872 << getLangOpts().CPlusPlus;
2876 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2877 /// memory in a typesafe manner and call constructors.
2879 /// This method is called to parse the new expression after the optional :: has
2880 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2881 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2884 /// '::'[opt] 'new' new-placement[opt] new-type-id
2885 /// new-initializer[opt]
2886 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2887 /// new-initializer[opt]
2890 /// '(' expression-list ')'
2893 /// type-specifier-seq new-declarator[opt]
2894 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2897 /// ptr-operator new-declarator[opt]
2898 /// direct-new-declarator
2900 /// new-initializer:
2901 /// '(' expression-list[opt] ')'
2902 /// [C++0x] braced-init-list
2905 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2906 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2907 ConsumeToken(); // Consume 'new'
2909 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2910 // second form of new-expression. It can't be a new-type-id.
2912 ExprVector PlacementArgs;
2913 SourceLocation PlacementLParen, PlacementRParen;
2915 SourceRange TypeIdParens;
2916 DeclSpec DS(AttrFactory);
2917 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
2918 if (Tok.is(tok::l_paren)) {
2919 // If it turns out to be a placement, we change the type location.
2920 BalancedDelimiterTracker T(*this, tok::l_paren);
2922 PlacementLParen = T.getOpenLocation();
2923 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2924 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2929 PlacementRParen = T.getCloseLocation();
2930 if (PlacementRParen.isInvalid()) {
2931 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2935 if (PlacementArgs.empty()) {
2936 // Reset the placement locations. There was no placement.
2937 TypeIdParens = T.getRange();
2938 PlacementLParen = PlacementRParen = SourceLocation();
2940 // We still need the type.
2941 if (Tok.is(tok::l_paren)) {
2942 BalancedDelimiterTracker T(*this, tok::l_paren);
2944 MaybeParseGNUAttributes(DeclaratorInfo);
2945 ParseSpecifierQualifierList(DS);
2946 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2947 ParseDeclarator(DeclaratorInfo);
2949 TypeIdParens = T.getRange();
2951 MaybeParseGNUAttributes(DeclaratorInfo);
2952 if (ParseCXXTypeSpecifierSeq(DS))
2953 DeclaratorInfo.setInvalidType(true);
2955 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2956 ParseDeclaratorInternal(DeclaratorInfo,
2957 &Parser::ParseDirectNewDeclarator);
2962 // A new-type-id is a simplified type-id, where essentially the
2963 // direct-declarator is replaced by a direct-new-declarator.
2964 MaybeParseGNUAttributes(DeclaratorInfo);
2965 if (ParseCXXTypeSpecifierSeq(DS))
2966 DeclaratorInfo.setInvalidType(true);
2968 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2969 ParseDeclaratorInternal(DeclaratorInfo,
2970 &Parser::ParseDirectNewDeclarator);
2973 if (DeclaratorInfo.isInvalidType()) {
2974 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2978 ExprResult Initializer;
2980 if (Tok.is(tok::l_paren)) {
2981 SourceLocation ConstructorLParen, ConstructorRParen;
2982 ExprVector ConstructorArgs;
2983 BalancedDelimiterTracker T(*this, tok::l_paren);
2985 ConstructorLParen = T.getOpenLocation();
2986 if (Tok.isNot(tok::r_paren)) {
2987 CommaLocsTy CommaLocs;
2988 auto RunSignatureHelp = [&]() {
2989 ParsedType TypeRep =
2990 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
2991 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2992 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
2993 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
2994 CalledSignatureHelp = true;
2995 return PreferredType;
2997 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2998 PreferredType.enterFunctionArgument(Tok.getLocation(),
3001 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3003 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3008 ConstructorRParen = T.getCloseLocation();
3009 if (ConstructorRParen.isInvalid()) {
3010 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3013 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
3016 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
3017 Diag(Tok.getLocation(),
3018 diag::warn_cxx98_compat_generalized_initializer_lists);
3019 Initializer = ParseBraceInitializer();
3021 if (Initializer.isInvalid())
3024 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
3025 PlacementArgs, PlacementRParen,
3026 TypeIdParens, DeclaratorInfo, Initializer.get());
3029 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
3030 /// passed to ParseDeclaratorInternal.
3032 /// direct-new-declarator:
3033 /// '[' expression[opt] ']'
3034 /// direct-new-declarator '[' constant-expression ']'
3036 void Parser::ParseDirectNewDeclarator(Declarator &D) {
3037 // Parse the array dimensions.
3039 while (Tok.is(tok::l_square)) {
3040 // An array-size expression can't start with a lambda.
3041 if (CheckProhibitedCXX11Attribute())
3044 BalancedDelimiterTracker T(*this, tok::l_square);
3048 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
3049 : ParseConstantExpression();
3050 if (Size.isInvalid()) {
3052 SkipUntil(tok::r_square, StopAtSemi);
3059 // Attributes here appertain to the array type. C++11 [expr.new]p5.
3060 ParsedAttributes Attrs(AttrFactory);
3061 MaybeParseCXX11Attributes(Attrs);
3063 D.AddTypeInfo(DeclaratorChunk::getArray(0,
3064 /*isStatic=*/false, /*isStar=*/false,
3065 Size.get(), T.getOpenLocation(),
3066 T.getCloseLocation()),
3067 std::move(Attrs), T.getCloseLocation());
3069 if (T.getCloseLocation().isInvalid())
3074 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3075 /// This ambiguity appears in the syntax of the C++ new operator.
3078 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3079 /// new-initializer[opt]
3082 /// '(' expression-list ')'
3084 bool Parser::ParseExpressionListOrTypeId(
3085 SmallVectorImpl<Expr*> &PlacementArgs,
3087 // The '(' was already consumed.
3088 if (isTypeIdInParens()) {
3089 ParseSpecifierQualifierList(D.getMutableDeclSpec());
3090 D.SetSourceRange(D.getDeclSpec().getSourceRange());
3092 return D.isInvalidType();
3095 // It's not a type, it has to be an expression list.
3096 // Discard the comma locations - ActOnCXXNew has enough parameters.
3097 CommaLocsTy CommaLocs;
3098 return ParseExpressionList(PlacementArgs, CommaLocs);
3101 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3102 /// to free memory allocated by new.
3104 /// This method is called to parse the 'delete' expression after the optional
3105 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3106 /// and "Start" is its location. Otherwise, "Start" is the location of the
3109 /// delete-expression:
3110 /// '::'[opt] 'delete' cast-expression
3111 /// '::'[opt] 'delete' '[' ']' cast-expression
3113 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3114 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
3115 ConsumeToken(); // Consume 'delete'
3118 bool ArrayDelete = false;
3119 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
3120 // C++11 [expr.delete]p1:
3121 // Whenever the delete keyword is followed by empty square brackets, it
3122 // shall be interpreted as [array delete].
3123 // [Footnote: A lambda expression with a lambda-introducer that consists
3124 // of empty square brackets can follow the delete keyword if
3125 // the lambda expression is enclosed in parentheses.]
3127 const Token Next = GetLookAheadToken(2);
3129 // Basic lookahead to check if we have a lambda expression.
3130 if (Next.isOneOf(tok::l_brace, tok::less) ||
3131 (Next.is(tok::l_paren) &&
3132 (GetLookAheadToken(3).is(tok::r_paren) ||
3133 (GetLookAheadToken(3).is(tok::identifier) &&
3134 GetLookAheadToken(4).is(tok::identifier))))) {
3135 TentativeParsingAction TPA(*this);
3136 SourceLocation LSquareLoc = Tok.getLocation();
3137 SourceLocation RSquareLoc = NextToken().getLocation();
3139 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3141 SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3142 SourceLocation RBraceLoc;
3143 bool EmitFixIt = false;
3144 if (Tok.is(tok::l_brace)) {
3146 SkipUntil(tok::r_brace, StopBeforeMatch);
3147 RBraceLoc = Tok.getLocation();
3154 Diag(Start, diag::err_lambda_after_delete)
3155 << SourceRange(Start, RSquareLoc)
3156 << FixItHint::CreateInsertion(LSquareLoc, "(")
3157 << FixItHint::CreateInsertion(
3158 Lexer::getLocForEndOfToken(
3159 RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3162 Diag(Start, diag::err_lambda_after_delete)
3163 << SourceRange(Start, RSquareLoc);
3165 // Warn that the non-capturing lambda isn't surrounded by parentheses
3166 // to disambiguate it from 'delete[]'.
3167 ExprResult Lambda = ParseLambdaExpression();
3168 if (Lambda.isInvalid())
3171 // Evaluate any postfix expressions used on the lambda.
3172 Lambda = ParsePostfixExpressionSuffix(Lambda);
3173 if (Lambda.isInvalid())
3175 return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3180 BalancedDelimiterTracker T(*this, tok::l_square);
3184 if (T.getCloseLocation().isInvalid())
3188 ExprResult Operand(ParseCastExpression(false));
3189 if (Operand.isInvalid())
3192 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
3195 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3197 default: llvm_unreachable("Not a known type trait");
3198 #define TYPE_TRAIT_1(Spelling, Name, Key) \
3199 case tok::kw_ ## Spelling: return UTT_ ## Name;
3200 #define TYPE_TRAIT_2(Spelling, Name, Key) \
3201 case tok::kw_ ## Spelling: return BTT_ ## Name;
3202 #include "clang/Basic/TokenKinds.def"
3203 #define TYPE_TRAIT_N(Spelling, Name, Key) \
3204 case tok::kw_ ## Spelling: return TT_ ## Name;
3205 #include "clang/Basic/TokenKinds.def"
3209 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3211 default: llvm_unreachable("Not a known binary type trait");
3212 case tok::kw___array_rank: return ATT_ArrayRank;
3213 case tok::kw___array_extent: return ATT_ArrayExtent;
3217 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3219 default: llvm_unreachable("Not a known unary expression trait.");
3220 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
3221 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
3225 static unsigned TypeTraitArity(tok::TokenKind kind) {
3227 default: llvm_unreachable("Not a known type trait");
3228 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3229 #include "clang/Basic/TokenKinds.def"
3233 /// Parse the built-in type-trait pseudo-functions that allow
3234 /// implementation of the TR1/C++11 type traits templates.
3236 /// primary-expression:
3237 /// unary-type-trait '(' type-id ')'
3238 /// binary-type-trait '(' type-id ',' type-id ')'
3239 /// type-trait '(' type-id-seq ')'
3242 /// type-id ...[opt] type-id-seq[opt]
3244 ExprResult Parser::ParseTypeTrait() {
3245 tok::TokenKind Kind = Tok.getKind();
3246 unsigned Arity = TypeTraitArity(Kind);
3248 SourceLocation Loc = ConsumeToken();
3250 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3251 if (Parens.expectAndConsume())
3254 SmallVector<ParsedType, 2> Args;
3256 // Parse the next type.
3257 TypeResult Ty = ParseTypeName();
3258 if (Ty.isInvalid()) {
3263 // Parse the ellipsis, if present.
3264 if (Tok.is(tok::ellipsis)) {
3265 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3266 if (Ty.isInvalid()) {
3272 // Add this type to the list of arguments.
3273 Args.push_back(Ty.get());
3274 } while (TryConsumeToken(tok::comma));
3276 if (Parens.consumeClose())
3279 SourceLocation EndLoc = Parens.getCloseLocation();
3281 if (Arity && Args.size() != Arity) {
3282 Diag(EndLoc, diag::err_type_trait_arity)
3283 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3287 if (!Arity && Args.empty()) {
3288 Diag(EndLoc, diag::err_type_trait_arity)
3289 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3293 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3296 /// ParseArrayTypeTrait - Parse the built-in array type-trait
3297 /// pseudo-functions.
3299 /// primary-expression:
3300 /// [Embarcadero] '__array_rank' '(' type-id ')'
3301 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3303 ExprResult Parser::ParseArrayTypeTrait() {
3304 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3305 SourceLocation Loc = ConsumeToken();
3307 BalancedDelimiterTracker T(*this, tok::l_paren);
3308 if (T.expectAndConsume())
3311 TypeResult Ty = ParseTypeName();
3312 if (Ty.isInvalid()) {
3313 SkipUntil(tok::comma, StopAtSemi);
3314 SkipUntil(tok::r_paren, StopAtSemi);
3319 case ATT_ArrayRank: {
3321 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3322 T.getCloseLocation());
3324 case ATT_ArrayExtent: {
3325 if (ExpectAndConsume(tok::comma)) {
3326 SkipUntil(tok::r_paren, StopAtSemi);
3330 ExprResult DimExpr = ParseExpression();
3333 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3334 T.getCloseLocation());
3337 llvm_unreachable("Invalid ArrayTypeTrait!");
3340 /// ParseExpressionTrait - Parse built-in expression-trait
3341 /// pseudo-functions like __is_lvalue_expr( xxx ).
3343 /// primary-expression:
3344 /// [Embarcadero] expression-trait '(' expression ')'
3346 ExprResult Parser::ParseExpressionTrait() {
3347 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3348 SourceLocation Loc = ConsumeToken();
3350 BalancedDelimiterTracker T(*this, tok::l_paren);
3351 if (T.expectAndConsume())
3354 ExprResult Expr = ParseExpression();
3358 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3359 T.getCloseLocation());
3363 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3364 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3365 /// based on the context past the parens.
3367 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3369 BalancedDelimiterTracker &Tracker,
3370 ColonProtectionRAIIObject &ColonProt) {
3371 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3372 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3373 assert(isTypeIdInParens() && "Not a type-id!");
3375 ExprResult Result(true);
3378 // We need to disambiguate a very ugly part of the C++ syntax:
3380 // (T())x; - type-id
3381 // (T())*x; - type-id
3382 // (T())/x; - expression
3383 // (T()); - expression
3385 // The bad news is that we cannot use the specialized tentative parser, since
3386 // it can only verify that the thing inside the parens can be parsed as
3387 // type-id, it is not useful for determining the context past the parens.
3389 // The good news is that the parser can disambiguate this part without
3390 // making any unnecessary Action calls.
3392 // It uses a scheme similar to parsing inline methods. The parenthesized
3393 // tokens are cached, the context that follows is determined (possibly by
3394 // parsing a cast-expression), and then we re-introduce the cached tokens
3395 // into the token stream and parse them appropriately.
3397 ParenParseOption ParseAs;
3400 // Store the tokens of the parentheses. We will parse them after we determine
3401 // the context that follows them.
3402 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3403 // We didn't find the ')' we expected.
3404 Tracker.consumeClose();
3408 if (Tok.is(tok::l_brace)) {
3409 ParseAs = CompoundLiteral;
3412 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3415 // Try parsing the cast-expression that may follow.
3416 // If it is not a cast-expression, NotCastExpr will be true and no token
3417 // will be consumed.
3418 ColonProt.restore();
3419 Result = ParseCastExpression(false/*isUnaryExpression*/,
3420 false/*isAddressofOperand*/,
3422 // type-id has priority.
3426 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3428 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3431 // Create a fake EOF to mark end of Toks buffer.
3433 AttrEnd.startToken();
3434 AttrEnd.setKind(tok::eof);
3435 AttrEnd.setLocation(Tok.getLocation());
3436 AttrEnd.setEofData(Toks.data());
3437 Toks.push_back(AttrEnd);
3439 // The current token should go after the cached tokens.
3440 Toks.push_back(Tok);
3441 // Re-enter the stored parenthesized tokens into the token stream, so we may
3443 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
3444 /*IsReinject*/ true);
3445 // Drop the current token and bring the first cached one. It's the same token
3446 // as when we entered this function.
3449 if (ParseAs >= CompoundLiteral) {
3450 // Parse the type declarator.
3451 DeclSpec DS(AttrFactory);
3452 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
3454 ColonProtectionRAIIObject InnerColonProtection(*this);
3455 ParseSpecifierQualifierList(DS);
3456 ParseDeclarator(DeclaratorInfo);
3460 Tracker.consumeClose();
3461 ColonProt.restore();
3463 // Consume EOF marker for Toks buffer.
3464 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3467 if (ParseAs == CompoundLiteral) {
3468 ExprType = CompoundLiteral;
3469 if (DeclaratorInfo.isInvalidType())
3472 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3473 return ParseCompoundLiteralExpression(Ty.get(),
3474 Tracker.getOpenLocation(),
3475 Tracker.getCloseLocation());
3478 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3479 assert(ParseAs == CastExpr);
3481 if (DeclaratorInfo.isInvalidType())
3484 // Result is what ParseCastExpression returned earlier.
3485 if (!Result.isInvalid())
3486 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3487 DeclaratorInfo, CastTy,
3488 Tracker.getCloseLocation(), Result.get());
3492 // Not a compound literal, and not followed by a cast-expression.
3493 assert(ParseAs == SimpleExpr);
3495 ExprType = SimpleExpr;
3496 Result = ParseExpression();
3497 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3498 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3499 Tok.getLocation(), Result.get());
3502 if (Result.isInvalid()) {
3503 while (Tok.isNot(tok::eof))
3505 assert(Tok.getEofData() == AttrEnd.getEofData());
3510 Tracker.consumeClose();
3511 // Consume EOF marker for Toks buffer.
3512 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3517 /// Parse a __builtin_bit_cast(T, E).
3518 ExprResult Parser::ParseBuiltinBitCast() {
3519 SourceLocation KWLoc = ConsumeToken();
3521 BalancedDelimiterTracker T(*this, tok::l_paren);
3522 if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
3525 // Parse the common declaration-specifiers piece.
3526 DeclSpec DS(AttrFactory);
3527 ParseSpecifierQualifierList(DS);
3529 // Parse the abstract-declarator, if present.
3530 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
3531 ParseDeclarator(DeclaratorInfo);
3533 if (ExpectAndConsume(tok::comma)) {
3534 Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
3535 SkipUntil(tok::r_paren, StopAtSemi);
3539 ExprResult Operand = ParseExpression();
3541 if (T.consumeClose())
3544 if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
3547 return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
3548 T.getCloseLocation());