xref: /freebsd/contrib/llvm-project/clang/lib/Parse/ParseExprCXX.cpp (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expression parsing implementation for C++.
10 //
11 //===----------------------------------------------------------------------===//
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/Basic/DiagnosticParse.h"
17 #include "clang/Basic/PrettyStackTrace.h"
18 #include "clang/Basic/TemplateKinds.h"
19 #include "clang/Basic/TokenKinds.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Parse/Parser.h"
22 #include "clang/Parse/RAIIObjectsForParser.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/EnterExpressionEvaluationContext.h"
25 #include "clang/Sema/ParsedTemplate.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/SemaCodeCompletion.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include <numeric>
31 
32 using namespace clang;
33 
SelectDigraphErrorMessage(tok::TokenKind Kind)34 static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
35   switch (Kind) {
36     // template name
37     case tok::unknown:             return 0;
38     // casts
39     case tok::kw_addrspace_cast:   return 1;
40     case tok::kw_const_cast:       return 2;
41     case tok::kw_dynamic_cast:     return 3;
42     case tok::kw_reinterpret_cast: return 4;
43     case tok::kw_static_cast:      return 5;
44     default:
45       llvm_unreachable("Unknown type for digraph error message.");
46   }
47 }
48 
areTokensAdjacent(const Token & First,const Token & Second)49 bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
50   SourceManager &SM = PP.getSourceManager();
51   SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
52   SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
53   return FirstEnd == SM.getSpellingLoc(Second.getLocation());
54 }
55 
56 // Suggest fixit for "<::" after a cast.
FixDigraph(Parser & P,Preprocessor & PP,Token & DigraphToken,Token & ColonToken,tok::TokenKind Kind,bool AtDigraph)57 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
58                        Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
59   // Pull '<:' and ':' off token stream.
60   if (!AtDigraph)
61     PP.Lex(DigraphToken);
62   PP.Lex(ColonToken);
63 
64   SourceRange Range;
65   Range.setBegin(DigraphToken.getLocation());
66   Range.setEnd(ColonToken.getLocation());
67   P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
68       << SelectDigraphErrorMessage(Kind)
69       << FixItHint::CreateReplacement(Range, "< ::");
70 
71   // Update token information to reflect their change in token type.
72   ColonToken.setKind(tok::coloncolon);
73   ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
74   ColonToken.setLength(2);
75   DigraphToken.setKind(tok::less);
76   DigraphToken.setLength(1);
77 
78   // Push new tokens back to token stream.
79   PP.EnterToken(ColonToken, /*IsReinject*/ true);
80   if (!AtDigraph)
81     PP.EnterToken(DigraphToken, /*IsReinject*/ true);
82 }
83 
CheckForTemplateAndDigraph(Token & Next,ParsedType ObjectType,bool EnteringContext,IdentifierInfo & II,CXXScopeSpec & SS)84 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
85                                         bool EnteringContext,
86                                         IdentifierInfo &II, CXXScopeSpec &SS) {
87   if (!Next.is(tok::l_square) || Next.getLength() != 2)
88     return;
89 
90   Token SecondToken = GetLookAheadToken(2);
91   if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
92     return;
93 
94   TemplateTy Template;
95   UnqualifiedId TemplateName;
96   TemplateName.setIdentifier(&II, Tok.getLocation());
97   bool MemberOfUnknownSpecialization;
98   if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
99                               TemplateName, ObjectType, EnteringContext,
100                               Template, MemberOfUnknownSpecialization))
101     return;
102 
103   FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
104              /*AtDigraph*/false);
105 }
106 
ParseOptionalCXXScopeSpecifier(CXXScopeSpec & SS,ParsedType ObjectType,bool ObjectHadErrors,bool EnteringContext,bool * MayBePseudoDestructor,bool IsTypename,const IdentifierInfo ** LastII,bool OnlyNamespace,bool InUsingDeclaration,bool Disambiguation)107 bool Parser::ParseOptionalCXXScopeSpecifier(
108     CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
109     bool EnteringContext, bool *MayBePseudoDestructor, bool IsTypename,
110     const IdentifierInfo **LastII, bool OnlyNamespace, bool InUsingDeclaration,
111     bool Disambiguation) {
112   assert(getLangOpts().CPlusPlus &&
113          "Call sites of this function should be guarded by checking for C++");
114 
115   if (Tok.is(tok::annot_cxxscope)) {
116     assert(!LastII && "want last identifier but have already annotated scope");
117     assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
118     Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
119                                                  Tok.getAnnotationRange(),
120                                                  SS);
121     ConsumeAnnotationToken();
122     return false;
123   }
124 
125   // Has to happen before any "return false"s in this function.
126   bool CheckForDestructor = false;
127   if (MayBePseudoDestructor && *MayBePseudoDestructor) {
128     CheckForDestructor = true;
129     *MayBePseudoDestructor = false;
130   }
131 
132   if (LastII)
133     *LastII = nullptr;
134 
135   bool HasScopeSpecifier = false;
136 
137   if (Tok.is(tok::coloncolon)) {
138     // ::new and ::delete aren't nested-name-specifiers.
139     tok::TokenKind NextKind = NextToken().getKind();
140     if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
141       return false;
142 
143     if (NextKind == tok::l_brace) {
144       // It is invalid to have :: {, consume the scope qualifier and pretend
145       // like we never saw it.
146       Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
147     } else {
148       // '::' - Global scope qualifier.
149       if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
150         return true;
151 
152       HasScopeSpecifier = true;
153     }
154   }
155 
156   if (Tok.is(tok::kw___super)) {
157     SourceLocation SuperLoc = ConsumeToken();
158     if (!Tok.is(tok::coloncolon)) {
159       Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
160       return true;
161     }
162 
163     return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
164   }
165 
166   if (!HasScopeSpecifier &&
167       Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
168     DeclSpec DS(AttrFactory);
169     SourceLocation DeclLoc = Tok.getLocation();
170     SourceLocation EndLoc  = ParseDecltypeSpecifier(DS);
171 
172     SourceLocation CCLoc;
173     // Work around a standard defect: 'decltype(auto)::' is not a
174     // nested-name-specifier.
175     if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
176         !TryConsumeToken(tok::coloncolon, CCLoc)) {
177       AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
178       return false;
179     }
180 
181     if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
182       SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
183 
184     HasScopeSpecifier = true;
185   }
186 
187   else if (!HasScopeSpecifier && Tok.is(tok::identifier) &&
188            GetLookAheadToken(1).is(tok::ellipsis) &&
189            GetLookAheadToken(2).is(tok::l_square) &&
190            !GetLookAheadToken(3).is(tok::r_square)) {
191     SourceLocation Start = Tok.getLocation();
192     DeclSpec DS(AttrFactory);
193     SourceLocation CCLoc;
194     SourceLocation EndLoc = ParsePackIndexingType(DS);
195     if (DS.getTypeSpecType() == DeclSpec::TST_error)
196       return false;
197 
198     QualType Type = Actions.ActOnPackIndexingType(
199         DS.getRepAsType().get(), DS.getPackIndexingExpr(), DS.getBeginLoc(),
200         DS.getEllipsisLoc());
201 
202     if (Type.isNull())
203       return false;
204 
205     // C++ [cpp23.dcl.dcl-2]:
206     //   Previously, T...[n] would declare a pack of function parameters.
207     //   T...[n] is now a pack-index-specifier. [...] Valid C++ 2023 code that
208     //   declares a pack of parameters without specifying a declarator-id
209     //   becomes ill-formed.
210     //
211     // However, we still treat it as a pack indexing type because the use case
212     // is fairly rare, to ensure semantic consistency given that we have
213     // backported this feature to pre-C++26 modes.
214     if (!Tok.is(tok::coloncolon) && !getLangOpts().CPlusPlus26 &&
215         getCurScope()->isFunctionDeclarationScope())
216       Diag(Start, diag::warn_pre_cxx26_ambiguous_pack_indexing_type) << Type;
217 
218     if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
219       AnnotateExistingIndexedTypeNamePack(ParsedType::make(Type), Start,
220                                           EndLoc);
221       return false;
222     }
223     if (Actions.ActOnCXXNestedNameSpecifierIndexedPack(SS, DS, CCLoc,
224                                                        std::move(Type)))
225       SS.SetInvalid(SourceRange(Start, CCLoc));
226     HasScopeSpecifier = true;
227   }
228 
229   // Preferred type might change when parsing qualifiers, we need the original.
230   auto SavedType = PreferredType;
231   while (true) {
232     if (HasScopeSpecifier) {
233       if (Tok.is(tok::code_completion)) {
234         cutOffParsing();
235         // Code completion for a nested-name-specifier, where the code
236         // completion token follows the '::'.
237         Actions.CodeCompletion().CodeCompleteQualifiedId(
238             getCurScope(), SS, EnteringContext, InUsingDeclaration,
239             ObjectType.get(), SavedType.get(SS.getBeginLoc()));
240         // Include code completion token into the range of the scope otherwise
241         // when we try to annotate the scope tokens the dangling code completion
242         // token will cause assertion in
243         // Preprocessor::AnnotatePreviousCachedTokens.
244         SS.setEndLoc(Tok.getLocation());
245         return true;
246       }
247 
248       // C++ [basic.lookup.classref]p5:
249       //   If the qualified-id has the form
250       //
251       //       ::class-name-or-namespace-name::...
252       //
253       //   the class-name-or-namespace-name is looked up in global scope as a
254       //   class-name or namespace-name.
255       //
256       // To implement this, we clear out the object type as soon as we've
257       // seen a leading '::' or part of a nested-name-specifier.
258       ObjectType = nullptr;
259     }
260 
261     // nested-name-specifier:
262     //   nested-name-specifier 'template'[opt] simple-template-id '::'
263 
264     // Parse the optional 'template' keyword, then make sure we have
265     // 'identifier <' after it.
266     if (Tok.is(tok::kw_template)) {
267       // If we don't have a scope specifier or an object type, this isn't a
268       // nested-name-specifier, since they aren't allowed to start with
269       // 'template'.
270       if (!HasScopeSpecifier && !ObjectType)
271         break;
272 
273       TentativeParsingAction TPA(*this);
274       SourceLocation TemplateKWLoc = ConsumeToken();
275 
276       UnqualifiedId TemplateName;
277       if (Tok.is(tok::identifier)) {
278         // Consume the identifier.
279         TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
280         ConsumeToken();
281       } else if (Tok.is(tok::kw_operator)) {
282         // We don't need to actually parse the unqualified-id in this case,
283         // because a simple-template-id cannot start with 'operator', but
284         // go ahead and parse it anyway for consistency with the case where
285         // we already annotated the template-id.
286         if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
287                                        TemplateName)) {
288           TPA.Commit();
289           break;
290         }
291 
292         if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
293             TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
294           Diag(TemplateName.getSourceRange().getBegin(),
295                diag::err_id_after_template_in_nested_name_spec)
296             << TemplateName.getSourceRange();
297           TPA.Commit();
298           break;
299         }
300       } else {
301         TPA.Revert();
302         break;
303       }
304 
305       // If the next token is not '<', we have a qualified-id that refers
306       // to a template name, such as T::template apply, but is not a
307       // template-id.
308       if (Tok.isNot(tok::less)) {
309         TPA.Revert();
310         break;
311       }
312 
313       // Commit to parsing the template-id.
314       TPA.Commit();
315       TemplateTy Template;
316       TemplateNameKind TNK = Actions.ActOnTemplateName(
317           getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
318           EnteringContext, Template, /*AllowInjectedClassName*/ true);
319       if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
320                                   TemplateName, false))
321         return true;
322 
323       continue;
324     }
325 
326     if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
327       // We have
328       //
329       //   template-id '::'
330       //
331       // So we need to check whether the template-id is a simple-template-id of
332       // the right kind (it should name a type or be dependent), and then
333       // convert it into a type within the nested-name-specifier.
334       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
335       if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
336         *MayBePseudoDestructor = true;
337         return false;
338       }
339 
340       if (LastII)
341         *LastII = TemplateId->Name;
342 
343       // Consume the template-id token.
344       ConsumeAnnotationToken();
345 
346       assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
347       SourceLocation CCLoc = ConsumeToken();
348 
349       HasScopeSpecifier = true;
350 
351       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
352                                          TemplateId->NumArgs);
353 
354       if (TemplateId->isInvalid() ||
355           Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
356                                               SS,
357                                               TemplateId->TemplateKWLoc,
358                                               TemplateId->Template,
359                                               TemplateId->TemplateNameLoc,
360                                               TemplateId->LAngleLoc,
361                                               TemplateArgsPtr,
362                                               TemplateId->RAngleLoc,
363                                               CCLoc,
364                                               EnteringContext)) {
365         SourceLocation StartLoc
366           = SS.getBeginLoc().isValid()? SS.getBeginLoc()
367                                       : TemplateId->TemplateNameLoc;
368         SS.SetInvalid(SourceRange(StartLoc, CCLoc));
369       }
370 
371       continue;
372     }
373 
374     switch (Tok.getKind()) {
375 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
376 #include "clang/Basic/TransformTypeTraits.def"
377       if (!NextToken().is(tok::l_paren)) {
378         Tok.setKind(tok::identifier);
379         Diag(Tok, diag::ext_keyword_as_ident)
380             << Tok.getIdentifierInfo()->getName() << 0;
381         continue;
382       }
383       [[fallthrough]];
384     default:
385       break;
386     }
387 
388     // The rest of the nested-name-specifier possibilities start with
389     // tok::identifier.
390     if (Tok.isNot(tok::identifier))
391       break;
392 
393     IdentifierInfo &II = *Tok.getIdentifierInfo();
394 
395     // nested-name-specifier:
396     //   type-name '::'
397     //   namespace-name '::'
398     //   nested-name-specifier identifier '::'
399     Token Next = NextToken();
400     Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
401                                     ObjectType);
402 
403     // If we get foo:bar, this is almost certainly a typo for foo::bar.  Recover
404     // and emit a fixit hint for it.
405     if (Next.is(tok::colon) && !ColonIsSacred) {
406       if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
407                                             EnteringContext) &&
408           // If the token after the colon isn't an identifier, it's still an
409           // error, but they probably meant something else strange so don't
410           // recover like this.
411           PP.LookAhead(1).is(tok::identifier)) {
412         Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
413           << FixItHint::CreateReplacement(Next.getLocation(), "::");
414         // Recover as if the user wrote '::'.
415         Next.setKind(tok::coloncolon);
416       }
417     }
418 
419     if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
420       // It is invalid to have :: {, consume the scope qualifier and pretend
421       // like we never saw it.
422       Token Identifier = Tok; // Stash away the identifier.
423       ConsumeToken();         // Eat the identifier, current token is now '::'.
424       ConsumeToken();
425       Diag(getEndOfPreviousToken(), diag::err_expected) << tok::identifier;
426       UnconsumeToken(Identifier); // Stick the identifier back.
427       Next = NextToken();         // Point Next at the '{' token.
428     }
429 
430     if (Next.is(tok::coloncolon)) {
431       if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
432         *MayBePseudoDestructor = true;
433         return false;
434       }
435 
436       if (ColonIsSacred) {
437         const Token &Next2 = GetLookAheadToken(2);
438         if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
439             Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
440           Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
441               << Next2.getName()
442               << FixItHint::CreateReplacement(Next.getLocation(), ":");
443           Token ColonColon;
444           PP.Lex(ColonColon);
445           ColonColon.setKind(tok::colon);
446           PP.EnterToken(ColonColon, /*IsReinject*/ true);
447           break;
448         }
449       }
450 
451       if (LastII)
452         *LastII = &II;
453 
454       // We have an identifier followed by a '::'. Lookup this name
455       // as the name in a nested-name-specifier.
456       Token Identifier = Tok;
457       SourceLocation IdLoc = ConsumeToken();
458       assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
459              "NextToken() not working properly!");
460       Token ColonColon = Tok;
461       SourceLocation CCLoc = ConsumeToken();
462 
463       bool IsCorrectedToColon = false;
464       bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
465       if (Actions.ActOnCXXNestedNameSpecifier(
466               getCurScope(), IdInfo, EnteringContext, SS, CorrectionFlagPtr,
467               OnlyNamespace)) {
468         // Identifier is not recognized as a nested name, but we can have
469         // mistyped '::' instead of ':'.
470         if (CorrectionFlagPtr && IsCorrectedToColon) {
471           ColonColon.setKind(tok::colon);
472           PP.EnterToken(Tok, /*IsReinject*/ true);
473           PP.EnterToken(ColonColon, /*IsReinject*/ true);
474           Tok = Identifier;
475           break;
476         }
477         SS.SetInvalid(SourceRange(IdLoc, CCLoc));
478       }
479       HasScopeSpecifier = true;
480       continue;
481     }
482 
483     CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
484 
485     // nested-name-specifier:
486     //   type-name '<'
487     if (Next.is(tok::less)) {
488 
489       TemplateTy Template;
490       UnqualifiedId TemplateName;
491       TemplateName.setIdentifier(&II, Tok.getLocation());
492       bool MemberOfUnknownSpecialization;
493       if (TemplateNameKind TNK = Actions.isTemplateName(
494               getCurScope(), SS,
495               /*hasTemplateKeyword=*/false, TemplateName, ObjectType,
496               EnteringContext, Template, MemberOfUnknownSpecialization,
497               Disambiguation)) {
498         // If lookup didn't find anything, we treat the name as a template-name
499         // anyway. C++20 requires this, and in prior language modes it improves
500         // error recovery. But before we commit to this, check that we actually
501         // have something that looks like a template-argument-list next.
502         if (!IsTypename && TNK == TNK_Undeclared_template &&
503             isTemplateArgumentList(1) == TPResult::False)
504           break;
505 
506         // We have found a template name, so annotate this token
507         // with a template-id annotation. We do not permit the
508         // template-id to be translated into a type annotation,
509         // because some clients (e.g., the parsing of class template
510         // specializations) still want to see the original template-id
511         // token, and it might not be a type at all (e.g. a concept name in a
512         // type-constraint).
513         ConsumeToken();
514         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
515                                     TemplateName, false))
516           return true;
517         continue;
518       }
519 
520       if (MemberOfUnknownSpecialization && !Disambiguation &&
521           (ObjectType || SS.isSet()) &&
522           (IsTypename || isTemplateArgumentList(1) == TPResult::True)) {
523         // If we had errors before, ObjectType can be dependent even without any
524         // templates. Do not report missing template keyword in that case.
525         if (!ObjectHadErrors) {
526           // We have something like t::getAs<T>, where getAs is a
527           // member of an unknown specialization. However, this will only
528           // parse correctly as a template, so suggest the keyword 'template'
529           // before 'getAs' and treat this as a dependent template name.
530           unsigned DiagID = diag::err_missing_dependent_template_keyword;
531           if (getLangOpts().MicrosoftExt)
532             DiagID = diag::warn_missing_dependent_template_keyword;
533 
534           Diag(Tok.getLocation(), DiagID)
535               << II.getName()
536               << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
537         }
538         ConsumeToken();
539 
540         TemplateNameKind TNK = Actions.ActOnTemplateName(
541             getCurScope(), SS, /*TemplateKWLoc=*/SourceLocation(), TemplateName,
542             ObjectType, EnteringContext, Template,
543             /*AllowInjectedClassName=*/true);
544         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
545                                     TemplateName, false))
546           return true;
547 
548         continue;
549       }
550     }
551 
552     // We don't have any tokens that form the beginning of a
553     // nested-name-specifier, so we're done.
554     break;
555   }
556 
557   // Even if we didn't see any pieces of a nested-name-specifier, we
558   // still check whether there is a tilde in this position, which
559   // indicates a potential pseudo-destructor.
560   if (CheckForDestructor && !HasScopeSpecifier && Tok.is(tok::tilde))
561     *MayBePseudoDestructor = true;
562 
563   return false;
564 }
565 
tryParseCXXIdExpression(CXXScopeSpec & SS,bool isAddressOfOperand,Token & Replacement)566 ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS,
567                                            bool isAddressOfOperand,
568                                            Token &Replacement) {
569   ExprResult E;
570 
571   // We may have already annotated this id-expression.
572   switch (Tok.getKind()) {
573   case tok::annot_non_type: {
574     NamedDecl *ND = getNonTypeAnnotation(Tok);
575     SourceLocation Loc = ConsumeAnnotationToken();
576     E = Actions.ActOnNameClassifiedAsNonType(getCurScope(), SS, ND, Loc, Tok);
577     break;
578   }
579 
580   case tok::annot_non_type_dependent: {
581     IdentifierInfo *II = getIdentifierAnnotation(Tok);
582     SourceLocation Loc = ConsumeAnnotationToken();
583 
584     // This is only the direct operand of an & operator if it is not
585     // followed by a postfix-expression suffix.
586     if (isAddressOfOperand && isPostfixExpressionSuffixStart())
587       isAddressOfOperand = false;
588 
589     E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc,
590                                                       isAddressOfOperand);
591     break;
592   }
593 
594   case tok::annot_non_type_undeclared: {
595     assert(SS.isEmpty() &&
596            "undeclared non-type annotation should be unqualified");
597     IdentifierInfo *II = getIdentifierAnnotation(Tok);
598     SourceLocation Loc = ConsumeAnnotationToken();
599     E = Actions.ActOnNameClassifiedAsUndeclaredNonType(II, Loc);
600     break;
601   }
602 
603   default:
604     SourceLocation TemplateKWLoc;
605     UnqualifiedId Name;
606     if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
607                            /*ObjectHadErrors=*/false,
608                            /*EnteringContext=*/false,
609                            /*AllowDestructorName=*/false,
610                            /*AllowConstructorName=*/false,
611                            /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name))
612       return ExprError();
613 
614     // This is only the direct operand of an & operator if it is not
615     // followed by a postfix-expression suffix.
616     if (isAddressOfOperand && isPostfixExpressionSuffixStart())
617       isAddressOfOperand = false;
618 
619     E = Actions.ActOnIdExpression(
620         getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
621         isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
622         &Replacement);
623     break;
624   }
625 
626   // Might be a pack index expression!
627   E = tryParseCXXPackIndexingExpression(E);
628 
629   if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
630     checkPotentialAngleBracket(E);
631   return E;
632 }
633 
ParseCXXPackIndexingExpression(ExprResult PackIdExpression)634 ExprResult Parser::ParseCXXPackIndexingExpression(ExprResult PackIdExpression) {
635   assert(Tok.is(tok::ellipsis) && NextToken().is(tok::l_square) &&
636          "expected ...[");
637   SourceLocation EllipsisLoc = ConsumeToken();
638   BalancedDelimiterTracker T(*this, tok::l_square);
639   T.consumeOpen();
640   ExprResult IndexExpr = ParseConstantExpression();
641   if (T.consumeClose() || IndexExpr.isInvalid())
642     return ExprError();
643   return Actions.ActOnPackIndexingExpr(getCurScope(), PackIdExpression.get(),
644                                        EllipsisLoc, T.getOpenLocation(),
645                                        IndexExpr.get(), T.getCloseLocation());
646 }
647 
648 ExprResult
tryParseCXXPackIndexingExpression(ExprResult PackIdExpression)649 Parser::tryParseCXXPackIndexingExpression(ExprResult PackIdExpression) {
650   ExprResult E = PackIdExpression;
651   if (!PackIdExpression.isInvalid() && !PackIdExpression.isUnset() &&
652       Tok.is(tok::ellipsis) && NextToken().is(tok::l_square)) {
653     E = ParseCXXPackIndexingExpression(E);
654   }
655   return E;
656 }
657 
ParseCXXIdExpression(bool isAddressOfOperand)658 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
659   // qualified-id:
660   //   '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
661   //   '::' unqualified-id
662   //
663   CXXScopeSpec SS;
664   ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
665                                  /*ObjectHasErrors=*/false,
666                                  /*EnteringContext=*/false);
667 
668   Token Replacement;
669   ExprResult Result =
670       tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
671   if (Result.isUnset()) {
672     // If the ExprResult is valid but null, then typo correction suggested a
673     // keyword replacement that needs to be reparsed.
674     UnconsumeToken(Replacement);
675     Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
676   }
677   assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
678                               "for a previous keyword suggestion");
679   return Result;
680 }
681 
ParseLambdaExpression()682 ExprResult Parser::ParseLambdaExpression() {
683   // Parse lambda-introducer.
684   LambdaIntroducer Intro;
685   if (ParseLambdaIntroducer(Intro)) {
686     SkipUntil(tok::r_square, StopAtSemi);
687     SkipUntil(tok::l_brace, StopAtSemi);
688     SkipUntil(tok::r_brace, StopAtSemi);
689     return ExprError();
690   }
691 
692   return ParseLambdaExpressionAfterIntroducer(Intro);
693 }
694 
TryParseLambdaExpression()695 ExprResult Parser::TryParseLambdaExpression() {
696   assert(getLangOpts().CPlusPlus && Tok.is(tok::l_square) &&
697          "Not at the start of a possible lambda expression.");
698 
699   const Token Next = NextToken();
700   if (Next.is(tok::eof)) // Nothing else to lookup here...
701     return ExprEmpty();
702 
703   const Token After = GetLookAheadToken(2);
704   // If lookahead indicates this is a lambda...
705   if (Next.is(tok::r_square) ||     // []
706       Next.is(tok::equal) ||        // [=
707       (Next.is(tok::amp) &&         // [&] or [&,
708        After.isOneOf(tok::r_square, tok::comma)) ||
709       (Next.is(tok::identifier) &&  // [identifier]
710        After.is(tok::r_square)) ||
711       Next.is(tok::ellipsis)) {     // [...
712     return ParseLambdaExpression();
713   }
714 
715   // If lookahead indicates an ObjC message send...
716   // [identifier identifier
717   if (Next.is(tok::identifier) && After.is(tok::identifier))
718     return ExprEmpty();
719 
720   // Here, we're stuck: lambda introducers and Objective-C message sends are
721   // unambiguous, but it requires arbitrary lookhead.  [a,b,c,d,e,f,g] is a
722   // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send.  Instead of
723   // writing two routines to parse a lambda introducer, just try to parse
724   // a lambda introducer first, and fall back if that fails.
725   LambdaIntroducer Intro;
726   {
727     TentativeParsingAction TPA(*this);
728     LambdaIntroducerTentativeParse Tentative;
729     if (ParseLambdaIntroducer(Intro, &Tentative)) {
730       TPA.Commit();
731       return ExprError();
732     }
733 
734     switch (Tentative) {
735     case LambdaIntroducerTentativeParse::Success:
736       TPA.Commit();
737       break;
738 
739     case LambdaIntroducerTentativeParse::Incomplete:
740       // Didn't fully parse the lambda-introducer, try again with a
741       // non-tentative parse.
742       TPA.Revert();
743       Intro = LambdaIntroducer();
744       if (ParseLambdaIntroducer(Intro))
745         return ExprError();
746       break;
747 
748     case LambdaIntroducerTentativeParse::MessageSend:
749     case LambdaIntroducerTentativeParse::Invalid:
750       // Not a lambda-introducer, might be a message send.
751       TPA.Revert();
752       return ExprEmpty();
753     }
754   }
755 
756   return ParseLambdaExpressionAfterIntroducer(Intro);
757 }
758 
ParseLambdaIntroducer(LambdaIntroducer & Intro,LambdaIntroducerTentativeParse * Tentative)759 bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
760                                    LambdaIntroducerTentativeParse *Tentative) {
761   if (Tentative)
762     *Tentative = LambdaIntroducerTentativeParse::Success;
763 
764   assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
765   BalancedDelimiterTracker T(*this, tok::l_square);
766   T.consumeOpen();
767 
768   Intro.Range.setBegin(T.getOpenLocation());
769 
770   bool First = true;
771 
772   // Produce a diagnostic if we're not tentatively parsing; otherwise track
773   // that our parse has failed.
774   auto Invalid = [&](llvm::function_ref<void()> Action) {
775     if (Tentative) {
776       *Tentative = LambdaIntroducerTentativeParse::Invalid;
777       return false;
778     }
779     Action();
780     return true;
781   };
782 
783   // Perform some irreversible action if this is a non-tentative parse;
784   // otherwise note that our actions were incomplete.
785   auto NonTentativeAction = [&](llvm::function_ref<void()> Action) {
786     if (Tentative)
787       *Tentative = LambdaIntroducerTentativeParse::Incomplete;
788     else
789       Action();
790   };
791 
792   // Parse capture-default.
793   if (Tok.is(tok::amp) &&
794       (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
795     Intro.Default = LCD_ByRef;
796     Intro.DefaultLoc = ConsumeToken();
797     First = false;
798     if (!Tok.getIdentifierInfo()) {
799       // This can only be a lambda; no need for tentative parsing any more.
800       // '[[and]]' can still be an attribute, though.
801       Tentative = nullptr;
802     }
803   } else if (Tok.is(tok::equal)) {
804     Intro.Default = LCD_ByCopy;
805     Intro.DefaultLoc = ConsumeToken();
806     First = false;
807     Tentative = nullptr;
808   }
809 
810   while (Tok.isNot(tok::r_square)) {
811     if (!First) {
812       if (Tok.isNot(tok::comma)) {
813         // Provide a completion for a lambda introducer here. Except
814         // in Objective-C, where this is Almost Surely meant to be a message
815         // send. In that case, fail here and let the ObjC message
816         // expression parser perform the completion.
817         if (Tok.is(tok::code_completion) &&
818             !(getLangOpts().ObjC && Tentative)) {
819           cutOffParsing();
820           Actions.CodeCompletion().CodeCompleteLambdaIntroducer(
821               getCurScope(), Intro,
822               /*AfterAmpersand=*/false);
823           break;
824         }
825 
826         return Invalid([&] {
827           Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare);
828         });
829       }
830       ConsumeToken();
831     }
832 
833     if (Tok.is(tok::code_completion)) {
834       cutOffParsing();
835       // If we're in Objective-C++ and we have a bare '[', then this is more
836       // likely to be a message receiver.
837       if (getLangOpts().ObjC && Tentative && First)
838         Actions.CodeCompletion().CodeCompleteObjCMessageReceiver(getCurScope());
839       else
840         Actions.CodeCompletion().CodeCompleteLambdaIntroducer(
841             getCurScope(), Intro,
842             /*AfterAmpersand=*/false);
843       break;
844     }
845 
846     First = false;
847 
848     // Parse capture.
849     LambdaCaptureKind Kind = LCK_ByCopy;
850     LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
851     SourceLocation Loc;
852     IdentifierInfo *Id = nullptr;
853     SourceLocation EllipsisLocs[4];
854     ExprResult Init;
855     SourceLocation LocStart = Tok.getLocation();
856 
857     if (Tok.is(tok::star)) {
858       Loc = ConsumeToken();
859       if (Tok.is(tok::kw_this)) {
860         ConsumeToken();
861         Kind = LCK_StarThis;
862       } else {
863         return Invalid([&] {
864           Diag(Tok.getLocation(), diag::err_expected_star_this_capture);
865         });
866       }
867     } else if (Tok.is(tok::kw_this)) {
868       Kind = LCK_This;
869       Loc = ConsumeToken();
870     } else if (Tok.isOneOf(tok::amp, tok::equal) &&
871                NextToken().isOneOf(tok::comma, tok::r_square) &&
872                Intro.Default == LCD_None) {
873       // We have a lone "&" or "=" which is either a misplaced capture-default
874       // or the start of a capture (in the "&" case) with the rest of the
875       // capture missing. Both are an error but a misplaced capture-default
876       // is more likely if we don't already have a capture default.
877       return Invalid(
878           [&] { Diag(Tok.getLocation(), diag::err_capture_default_first); });
879     } else {
880       TryConsumeToken(tok::ellipsis, EllipsisLocs[0]);
881 
882       if (Tok.is(tok::amp)) {
883         Kind = LCK_ByRef;
884         ConsumeToken();
885 
886         if (Tok.is(tok::code_completion)) {
887           cutOffParsing();
888           Actions.CodeCompletion().CodeCompleteLambdaIntroducer(
889               getCurScope(), Intro,
890               /*AfterAmpersand=*/true);
891           break;
892         }
893       }
894 
895       TryConsumeToken(tok::ellipsis, EllipsisLocs[1]);
896 
897       if (Tok.is(tok::identifier)) {
898         Id = Tok.getIdentifierInfo();
899         Loc = ConsumeToken();
900       } else if (Tok.is(tok::kw_this)) {
901         return Invalid([&] {
902           // FIXME: Suggest a fixit here.
903           Diag(Tok.getLocation(), diag::err_this_captured_by_reference);
904         });
905       } else {
906         return Invalid([&] {
907           Diag(Tok.getLocation(), diag::err_expected_capture);
908         });
909       }
910 
911       TryConsumeToken(tok::ellipsis, EllipsisLocs[2]);
912 
913       if (Tok.is(tok::l_paren)) {
914         BalancedDelimiterTracker Parens(*this, tok::l_paren);
915         Parens.consumeOpen();
916 
917         InitKind = LambdaCaptureInitKind::DirectInit;
918 
919         ExprVector Exprs;
920         if (Tentative) {
921           Parens.skipToEnd();
922           *Tentative = LambdaIntroducerTentativeParse::Incomplete;
923         } else if (ParseExpressionList(Exprs)) {
924           Parens.skipToEnd();
925           Init = ExprError();
926         } else {
927           Parens.consumeClose();
928           Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
929                                             Parens.getCloseLocation(),
930                                             Exprs);
931         }
932       } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
933         // Each lambda init-capture forms its own full expression, which clears
934         // Actions.MaybeODRUseExprs. So create an expression evaluation context
935         // to save the necessary state, and restore it later.
936         EnterExpressionEvaluationContext EC(
937             Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
938 
939         if (TryConsumeToken(tok::equal))
940           InitKind = LambdaCaptureInitKind::CopyInit;
941         else
942           InitKind = LambdaCaptureInitKind::ListInit;
943 
944         if (!Tentative) {
945           Init = ParseInitializer();
946         } else if (Tok.is(tok::l_brace)) {
947           BalancedDelimiterTracker Braces(*this, tok::l_brace);
948           Braces.consumeOpen();
949           Braces.skipToEnd();
950           *Tentative = LambdaIntroducerTentativeParse::Incomplete;
951         } else {
952           // We're disambiguating this:
953           //
954           //   [..., x = expr
955           //
956           // We need to find the end of the following expression in order to
957           // determine whether this is an Obj-C message send's receiver, a
958           // C99 designator, or a lambda init-capture.
959           //
960           // Parse the expression to find where it ends, and annotate it back
961           // onto the tokens. We would have parsed this expression the same way
962           // in either case: both the RHS of an init-capture and the RHS of an
963           // assignment expression are parsed as an initializer-clause, and in
964           // neither case can anything be added to the scope between the '[' and
965           // here.
966           //
967           // FIXME: This is horrible. Adding a mechanism to skip an expression
968           // would be much cleaner.
969           // FIXME: If there is a ',' before the next ']' or ':', we can skip to
970           // that instead. (And if we see a ':' with no matching '?', we can
971           // classify this as an Obj-C message send.)
972           SourceLocation StartLoc = Tok.getLocation();
973           InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
974           Init = ParseInitializer();
975 
976           if (Tok.getLocation() != StartLoc) {
977             // Back out the lexing of the token after the initializer.
978             PP.RevertCachedTokens(1);
979 
980             // Replace the consumed tokens with an appropriate annotation.
981             Tok.setLocation(StartLoc);
982             Tok.setKind(tok::annot_primary_expr);
983             setExprAnnotation(Tok, Init);
984             Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
985             PP.AnnotateCachedTokens(Tok);
986 
987             // Consume the annotated initializer.
988             ConsumeAnnotationToken();
989           }
990         }
991       }
992 
993       TryConsumeToken(tok::ellipsis, EllipsisLocs[3]);
994     }
995 
996     // Check if this is a message send before we act on a possible init-capture.
997     if (Tentative && Tok.is(tok::identifier) &&
998         NextToken().isOneOf(tok::colon, tok::r_square)) {
999       // This can only be a message send. We're done with disambiguation.
1000       *Tentative = LambdaIntroducerTentativeParse::MessageSend;
1001       return false;
1002     }
1003 
1004     // Ensure that any ellipsis was in the right place.
1005     SourceLocation EllipsisLoc;
1006     if (llvm::any_of(EllipsisLocs,
1007                      [](SourceLocation Loc) { return Loc.isValid(); })) {
1008       // The '...' should appear before the identifier in an init-capture, and
1009       // after the identifier otherwise.
1010       bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit;
1011       SourceLocation *ExpectedEllipsisLoc =
1012           !InitCapture      ? &EllipsisLocs[2] :
1013           Kind == LCK_ByRef ? &EllipsisLocs[1] :
1014                               &EllipsisLocs[0];
1015       EllipsisLoc = *ExpectedEllipsisLoc;
1016 
1017       unsigned DiagID = 0;
1018       if (EllipsisLoc.isInvalid()) {
1019         DiagID = diag::err_lambda_capture_misplaced_ellipsis;
1020         for (SourceLocation Loc : EllipsisLocs) {
1021           if (Loc.isValid())
1022             EllipsisLoc = Loc;
1023         }
1024       } else {
1025         unsigned NumEllipses = std::accumulate(
1026             std::begin(EllipsisLocs), std::end(EllipsisLocs), 0,
1027             [](int N, SourceLocation Loc) { return N + Loc.isValid(); });
1028         if (NumEllipses > 1)
1029           DiagID = diag::err_lambda_capture_multiple_ellipses;
1030       }
1031       if (DiagID) {
1032         NonTentativeAction([&] {
1033           // Point the diagnostic at the first misplaced ellipsis.
1034           SourceLocation DiagLoc;
1035           for (SourceLocation &Loc : EllipsisLocs) {
1036             if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) {
1037               DiagLoc = Loc;
1038               break;
1039             }
1040           }
1041           assert(DiagLoc.isValid() && "no location for diagnostic");
1042 
1043           // Issue the diagnostic and produce fixits showing where the ellipsis
1044           // should have been written.
1045           auto &&D = Diag(DiagLoc, DiagID);
1046           if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) {
1047             SourceLocation ExpectedLoc =
1048                 InitCapture ? Loc
1049                             : Lexer::getLocForEndOfToken(
1050                                   Loc, 0, PP.getSourceManager(), getLangOpts());
1051             D << InitCapture << FixItHint::CreateInsertion(ExpectedLoc, "...");
1052           }
1053           for (SourceLocation &Loc : EllipsisLocs) {
1054             if (&Loc != ExpectedEllipsisLoc && Loc.isValid())
1055               D << FixItHint::CreateRemoval(Loc);
1056           }
1057         });
1058       }
1059     }
1060 
1061     // Process the init-capture initializers now rather than delaying until we
1062     // form the lambda-expression so that they can be handled in the context
1063     // enclosing the lambda-expression, rather than in the context of the
1064     // lambda-expression itself.
1065     ParsedType InitCaptureType;
1066     if (Init.isUsable()) {
1067       NonTentativeAction([&] {
1068         // Get the pointer and store it in an lvalue, so we can use it as an
1069         // out argument.
1070         Expr *InitExpr = Init.get();
1071         // This performs any lvalue-to-rvalue conversions if necessary, which
1072         // can affect what gets captured in the containing decl-context.
1073         InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
1074             Loc, Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, InitExpr);
1075         Init = InitExpr;
1076       });
1077     }
1078 
1079     SourceLocation LocEnd = PrevTokLocation;
1080 
1081     Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
1082                      InitCaptureType, SourceRange(LocStart, LocEnd));
1083   }
1084 
1085   T.consumeClose();
1086   Intro.Range.setEnd(T.getCloseLocation());
1087   return false;
1088 }
1089 
tryConsumeLambdaSpecifierToken(Parser & P,SourceLocation & MutableLoc,SourceLocation & StaticLoc,SourceLocation & ConstexprLoc,SourceLocation & ConstevalLoc,SourceLocation & DeclEndLoc)1090 static void tryConsumeLambdaSpecifierToken(Parser &P,
1091                                            SourceLocation &MutableLoc,
1092                                            SourceLocation &StaticLoc,
1093                                            SourceLocation &ConstexprLoc,
1094                                            SourceLocation &ConstevalLoc,
1095                                            SourceLocation &DeclEndLoc) {
1096   assert(MutableLoc.isInvalid());
1097   assert(StaticLoc.isInvalid());
1098   assert(ConstexprLoc.isInvalid());
1099   assert(ConstevalLoc.isInvalid());
1100   // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1101   // to the final of those locations. Emit an error if we have multiple
1102   // copies of those keywords and recover.
1103 
1104   auto ConsumeLocation = [&P, &DeclEndLoc](SourceLocation &SpecifierLoc,
1105                                            int DiagIndex) {
1106     if (SpecifierLoc.isValid()) {
1107       P.Diag(P.getCurToken().getLocation(),
1108              diag::err_lambda_decl_specifier_repeated)
1109           << DiagIndex
1110           << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1111     }
1112     SpecifierLoc = P.ConsumeToken();
1113     DeclEndLoc = SpecifierLoc;
1114   };
1115 
1116   while (true) {
1117     switch (P.getCurToken().getKind()) {
1118     case tok::kw_mutable:
1119       ConsumeLocation(MutableLoc, 0);
1120       break;
1121     case tok::kw_static:
1122       ConsumeLocation(StaticLoc, 1);
1123       break;
1124     case tok::kw_constexpr:
1125       ConsumeLocation(ConstexprLoc, 2);
1126       break;
1127     case tok::kw_consteval:
1128       ConsumeLocation(ConstevalLoc, 3);
1129       break;
1130     default:
1131       return;
1132     }
1133   }
1134 }
1135 
addStaticToLambdaDeclSpecifier(Parser & P,SourceLocation StaticLoc,DeclSpec & DS)1136 static void addStaticToLambdaDeclSpecifier(Parser &P, SourceLocation StaticLoc,
1137                                            DeclSpec &DS) {
1138   if (StaticLoc.isValid()) {
1139     P.Diag(StaticLoc, !P.getLangOpts().CPlusPlus23
1140                           ? diag::err_static_lambda
1141                           : diag::warn_cxx20_compat_static_lambda);
1142     const char *PrevSpec = nullptr;
1143     unsigned DiagID = 0;
1144     DS.SetStorageClassSpec(P.getActions(), DeclSpec::SCS_static, StaticLoc,
1145                            PrevSpec, DiagID,
1146                            P.getActions().getASTContext().getPrintingPolicy());
1147     assert(PrevSpec == nullptr && DiagID == 0 &&
1148            "Static cannot have been set previously!");
1149   }
1150 }
1151 
1152 static void
addConstexprToLambdaDeclSpecifier(Parser & P,SourceLocation ConstexprLoc,DeclSpec & DS)1153 addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1154                                   DeclSpec &DS) {
1155   if (ConstexprLoc.isValid()) {
1156     P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1157                              ? diag::ext_constexpr_on_lambda_cxx17
1158                              : diag::warn_cxx14_compat_constexpr_on_lambda);
1159     const char *PrevSpec = nullptr;
1160     unsigned DiagID = 0;
1161     DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, ConstexprLoc, PrevSpec,
1162                         DiagID);
1163     assert(PrevSpec == nullptr && DiagID == 0 &&
1164            "Constexpr cannot have been set previously!");
1165   }
1166 }
1167 
addConstevalToLambdaDeclSpecifier(Parser & P,SourceLocation ConstevalLoc,DeclSpec & DS)1168 static void addConstevalToLambdaDeclSpecifier(Parser &P,
1169                                               SourceLocation ConstevalLoc,
1170                                               DeclSpec &DS) {
1171   if (ConstevalLoc.isValid()) {
1172     P.Diag(ConstevalLoc, diag::warn_cxx20_compat_consteval);
1173     const char *PrevSpec = nullptr;
1174     unsigned DiagID = 0;
1175     DS.SetConstexprSpec(ConstexprSpecKind::Consteval, ConstevalLoc, PrevSpec,
1176                         DiagID);
1177     if (DiagID != 0)
1178       P.Diag(ConstevalLoc, DiagID) << PrevSpec;
1179   }
1180 }
1181 
DiagnoseStaticSpecifierRestrictions(Parser & P,SourceLocation StaticLoc,SourceLocation MutableLoc,const LambdaIntroducer & Intro)1182 static void DiagnoseStaticSpecifierRestrictions(Parser &P,
1183                                                 SourceLocation StaticLoc,
1184                                                 SourceLocation MutableLoc,
1185                                                 const LambdaIntroducer &Intro) {
1186   if (StaticLoc.isInvalid())
1187     return;
1188 
1189   // [expr.prim.lambda.general] p4
1190   // The lambda-specifier-seq shall not contain both mutable and static.
1191   // If the lambda-specifier-seq contains static, there shall be no
1192   // lambda-capture.
1193   if (MutableLoc.isValid())
1194     P.Diag(StaticLoc, diag::err_static_mutable_lambda);
1195   if (Intro.hasLambdaCapture()) {
1196     P.Diag(StaticLoc, diag::err_static_lambda_captures);
1197   }
1198 }
1199 
ParseLambdaExpressionAfterIntroducer(LambdaIntroducer & Intro)1200 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1201                      LambdaIntroducer &Intro) {
1202   SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1203   if (getLangOpts().HLSL)
1204     Diag(LambdaBeginLoc, diag::ext_hlsl_lambda) << /*HLSL*/ 1;
1205   else
1206     Diag(LambdaBeginLoc, getLangOpts().CPlusPlus11
1207                              ? diag::warn_cxx98_compat_lambda
1208                              : diag::ext_lambda)
1209         << /*C++*/ 0;
1210 
1211   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1212                                 "lambda expression parsing");
1213 
1214   // Parse lambda-declarator[opt].
1215   DeclSpec DS(AttrFactory);
1216   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::LambdaExpr);
1217   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1218 
1219   ParseScope LambdaScope(this, Scope::LambdaScope | Scope::DeclScope |
1220                                    Scope::FunctionDeclarationScope |
1221                                    Scope::FunctionPrototypeScope);
1222 
1223   Actions.PushLambdaScope();
1224   Actions.ActOnLambdaExpressionAfterIntroducer(Intro, getCurScope());
1225 
1226   ParsedAttributes Attributes(AttrFactory);
1227   if (getLangOpts().CUDA) {
1228     // In CUDA code, GNU attributes are allowed to appear immediately after the
1229     // "[...]", even if there is no "(...)" before the lambda body.
1230     //
1231     // Note that we support __noinline__ as a keyword in this mode and thus
1232     // it has to be separately handled.
1233     while (true) {
1234       if (Tok.is(tok::kw___noinline__)) {
1235         IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1236         SourceLocation AttrNameLoc = ConsumeToken();
1237         Attributes.addNew(AttrName, AttrNameLoc, AttributeScopeInfo(),
1238                           /*ArgsUnion=*/nullptr,
1239                           /*numArgs=*/0, tok::kw___noinline__);
1240       } else if (Tok.is(tok::kw___attribute))
1241         ParseGNUAttributes(Attributes, /*LatePArsedAttrList=*/nullptr, &D);
1242       else
1243         break;
1244     }
1245 
1246     D.takeAttributes(Attributes);
1247   }
1248 
1249   MultiParseScope TemplateParamScope(*this);
1250   if (Tok.is(tok::less)) {
1251     Diag(Tok, getLangOpts().CPlusPlus20
1252                   ? diag::warn_cxx17_compat_lambda_template_parameter_list
1253                   : diag::ext_lambda_template_parameter_list);
1254 
1255     SmallVector<NamedDecl*, 4> TemplateParams;
1256     SourceLocation LAngleLoc, RAngleLoc;
1257     if (ParseTemplateParameters(TemplateParamScope,
1258                                 CurTemplateDepthTracker.getDepth(),
1259                                 TemplateParams, LAngleLoc, RAngleLoc)) {
1260       Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1261       return ExprError();
1262     }
1263 
1264     if (TemplateParams.empty()) {
1265       Diag(RAngleLoc,
1266            diag::err_lambda_template_parameter_list_empty);
1267     } else {
1268       // We increase the template depth before recursing into a requires-clause.
1269       //
1270       // This depth is used for setting up a LambdaScopeInfo (in
1271       // Sema::RecordParsingTemplateParameterDepth), which is used later when
1272       // inventing template parameters in InventTemplateParameter.
1273       //
1274       // This way, abbreviated generic lambdas could have different template
1275       // depths, avoiding substitution into the wrong template parameters during
1276       // constraint satisfaction check.
1277       ++CurTemplateDepthTracker;
1278       ExprResult RequiresClause;
1279       if (TryConsumeToken(tok::kw_requires)) {
1280         RequiresClause =
1281             Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
1282                 /*IsTrailingRequiresClause=*/false));
1283         if (RequiresClause.isInvalid())
1284           SkipUntil({tok::l_brace, tok::l_paren}, StopAtSemi | StopBeforeMatch);
1285       }
1286 
1287       Actions.ActOnLambdaExplicitTemplateParameterList(
1288           Intro, LAngleLoc, TemplateParams, RAngleLoc, RequiresClause);
1289     }
1290   }
1291 
1292   // Implement WG21 P2173, which allows attributes immediately before the
1293   // lambda declarator and applies them to the corresponding function operator
1294   // or operator template declaration. We accept this as a conforming extension
1295   // in all language modes that support lambdas.
1296   if (isCXX11AttributeSpecifier() !=
1297       CXX11AttributeKind::NotAttributeSpecifier) {
1298     Diag(Tok, getLangOpts().CPlusPlus23
1299                   ? diag::warn_cxx20_compat_decl_attrs_on_lambda
1300                   : diag::ext_decl_attrs_on_lambda)
1301         << Tok.getIdentifierInfo() << Tok.isRegularKeywordAttribute();
1302     MaybeParseCXX11Attributes(D);
1303   }
1304 
1305   TypeResult TrailingReturnType;
1306   SourceLocation TrailingReturnTypeLoc;
1307   SourceLocation LParenLoc, RParenLoc;
1308   SourceLocation DeclEndLoc;
1309   bool HasParentheses = false;
1310   bool HasSpecifiers = false;
1311   SourceLocation MutableLoc;
1312 
1313   ParseScope Prototype(this, Scope::FunctionPrototypeScope |
1314                                  Scope::FunctionDeclarationScope |
1315                                  Scope::DeclScope);
1316 
1317   // Parse parameter-declaration-clause.
1318   SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1319   SourceLocation EllipsisLoc;
1320 
1321   if (Tok.is(tok::l_paren)) {
1322     BalancedDelimiterTracker T(*this, tok::l_paren);
1323     T.consumeOpen();
1324     LParenLoc = T.getOpenLocation();
1325 
1326     if (Tok.isNot(tok::r_paren)) {
1327       Actions.RecordParsingTemplateParameterDepth(
1328           CurTemplateDepthTracker.getOriginalDepth());
1329 
1330       ParseParameterDeclarationClause(D, Attributes, ParamInfo, EllipsisLoc);
1331       // For a generic lambda, each 'auto' within the parameter declaration
1332       // clause creates a template type parameter, so increment the depth.
1333       // If we've parsed any explicit template parameters, then the depth will
1334       // have already been incremented. So we make sure that at most a single
1335       // depth level is added.
1336       if (Actions.getCurGenericLambda())
1337         CurTemplateDepthTracker.setAddedDepth(1);
1338     }
1339 
1340     T.consumeClose();
1341     DeclEndLoc = RParenLoc = T.getCloseLocation();
1342     HasParentheses = true;
1343   }
1344 
1345   HasSpecifiers =
1346       Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1347                   tok::kw_constexpr, tok::kw_consteval, tok::kw_static,
1348                   tok::kw___private, tok::kw___global, tok::kw___local,
1349                   tok::kw___constant, tok::kw___generic, tok::kw_groupshared,
1350                   tok::kw_requires, tok::kw_noexcept) ||
1351       Tok.isRegularKeywordAttribute() ||
1352       (Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1353 
1354   if (HasSpecifiers && !HasParentheses && !getLangOpts().CPlusPlus23) {
1355     // It's common to forget that one needs '()' before 'mutable', an
1356     // attribute specifier, the result type, or the requires clause. Deal with
1357     // this.
1358     Diag(Tok, diag::ext_lambda_missing_parens)
1359         << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1360   }
1361 
1362   if (HasParentheses || HasSpecifiers) {
1363     // GNU-style attributes must be parsed before the mutable specifier to
1364     // be compatible with GCC. MSVC-style attributes must be parsed before
1365     // the mutable specifier to be compatible with MSVC.
1366     MaybeParseAttributes(PAKM_GNU | PAKM_Declspec, Attributes);
1367     // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update
1368     // the DeclEndLoc.
1369     SourceLocation ConstexprLoc;
1370     SourceLocation ConstevalLoc;
1371     SourceLocation StaticLoc;
1372 
1373     tryConsumeLambdaSpecifierToken(*this, MutableLoc, StaticLoc, ConstexprLoc,
1374                                    ConstevalLoc, DeclEndLoc);
1375 
1376     DiagnoseStaticSpecifierRestrictions(*this, StaticLoc, MutableLoc, Intro);
1377 
1378     addStaticToLambdaDeclSpecifier(*this, StaticLoc, DS);
1379     addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1380     addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS);
1381   }
1382 
1383   Actions.ActOnLambdaClosureParameters(getCurScope(), ParamInfo);
1384 
1385   if (!HasParentheses)
1386     Actions.ActOnLambdaClosureQualifiers(Intro, MutableLoc);
1387 
1388   if (HasSpecifiers || HasParentheses) {
1389     // Parse exception-specification[opt].
1390     ExceptionSpecificationType ESpecType = EST_None;
1391     SourceRange ESpecRange;
1392     SmallVector<ParsedType, 2> DynamicExceptions;
1393     SmallVector<SourceRange, 2> DynamicExceptionRanges;
1394     ExprResult NoexceptExpr;
1395     CachedTokens *ExceptionSpecTokens;
1396 
1397     ESpecType = tryParseExceptionSpecification(
1398         /*Delayed=*/false, ESpecRange, DynamicExceptions,
1399         DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens);
1400 
1401     if (ESpecType != EST_None)
1402       DeclEndLoc = ESpecRange.getEnd();
1403 
1404     // Parse attribute-specifier[opt].
1405     if (MaybeParseCXX11Attributes(Attributes))
1406       DeclEndLoc = Attributes.Range.getEnd();
1407 
1408     // Parse OpenCL addr space attribute.
1409     if (Tok.isOneOf(tok::kw___private, tok::kw___global, tok::kw___local,
1410                     tok::kw___constant, tok::kw___generic)) {
1411       ParseOpenCLQualifiers(DS.getAttributes());
1412       ConsumeToken();
1413     }
1414 
1415     SourceLocation FunLocalRangeEnd = DeclEndLoc;
1416 
1417     // Parse trailing-return-type[opt].
1418     if (Tok.is(tok::arrow)) {
1419       FunLocalRangeEnd = Tok.getLocation();
1420       SourceRange Range;
1421       TrailingReturnType =
1422           ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit=*/false);
1423       TrailingReturnTypeLoc = Range.getBegin();
1424       if (Range.getEnd().isValid())
1425         DeclEndLoc = Range.getEnd();
1426     }
1427 
1428     SourceLocation NoLoc;
1429     D.AddTypeInfo(DeclaratorChunk::getFunction(
1430                       /*HasProto=*/true,
1431                       /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1432                       ParamInfo.size(), EllipsisLoc, RParenLoc,
1433                       /*RefQualifierIsLvalueRef=*/true,
1434                       /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
1435                       ESpecRange, DynamicExceptions.data(),
1436                       DynamicExceptionRanges.data(), DynamicExceptions.size(),
1437                       NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1438                       /*ExceptionSpecTokens*/ nullptr,
1439                       /*DeclsInPrototype=*/{}, LParenLoc, FunLocalRangeEnd, D,
1440                       TrailingReturnType, TrailingReturnTypeLoc, &DS),
1441                   std::move(Attributes), DeclEndLoc);
1442 
1443     // We have called ActOnLambdaClosureQualifiers for parentheses-less cases
1444     // above.
1445     if (HasParentheses)
1446       Actions.ActOnLambdaClosureQualifiers(Intro, MutableLoc);
1447 
1448     if (HasParentheses && Tok.is(tok::kw_requires))
1449       ParseTrailingRequiresClause(D);
1450   }
1451 
1452   // Emit a warning if we see a CUDA host/device/global attribute
1453   // after '(...)'. nvcc doesn't accept this.
1454   if (getLangOpts().CUDA) {
1455     for (const ParsedAttr &A : Attributes)
1456       if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1457           A.getKind() == ParsedAttr::AT_CUDAHost ||
1458           A.getKind() == ParsedAttr::AT_CUDAGlobal)
1459         Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1460             << A.getAttrName()->getName();
1461   }
1462 
1463   Prototype.Exit();
1464 
1465   // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1466   // it.
1467   unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1468                         Scope::CompoundStmtScope;
1469   ParseScope BodyScope(this, ScopeFlags);
1470 
1471   Actions.ActOnStartOfLambdaDefinition(Intro, D, DS);
1472 
1473   // Parse compound-statement.
1474   if (!Tok.is(tok::l_brace)) {
1475     Diag(Tok, diag::err_expected_lambda_body);
1476     Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1477     return ExprError();
1478   }
1479 
1480   StmtResult Stmt(ParseCompoundStatementBody());
1481   BodyScope.Exit();
1482   TemplateParamScope.Exit();
1483   LambdaScope.Exit();
1484 
1485   if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid() &&
1486       !D.isInvalidType())
1487     return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get());
1488 
1489   Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1490   return ExprError();
1491 }
1492 
ParseCXXCasts()1493 ExprResult Parser::ParseCXXCasts() {
1494   tok::TokenKind Kind = Tok.getKind();
1495   const char *CastName = nullptr; // For error messages
1496 
1497   switch (Kind) {
1498   default: llvm_unreachable("Unknown C++ cast!");
1499   case tok::kw_addrspace_cast:   CastName = "addrspace_cast";   break;
1500   case tok::kw_const_cast:       CastName = "const_cast";       break;
1501   case tok::kw_dynamic_cast:     CastName = "dynamic_cast";     break;
1502   case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1503   case tok::kw_static_cast:      CastName = "static_cast";      break;
1504   }
1505 
1506   SourceLocation OpLoc = ConsumeToken();
1507   SourceLocation LAngleBracketLoc = Tok.getLocation();
1508 
1509   // Check for "<::" which is parsed as "[:".  If found, fix token stream,
1510   // diagnose error, suggest fix, and recover parsing.
1511   if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1512     Token Next = NextToken();
1513     if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1514       FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1515   }
1516 
1517   if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1518     return ExprError();
1519 
1520   // Parse the common declaration-specifiers piece.
1521   DeclSpec DS(AttrFactory);
1522   ParseSpecifierQualifierList(DS, /*AccessSpecifier=*/AS_none,
1523                               DeclSpecContext::DSC_type_specifier);
1524 
1525   // Parse the abstract-declarator, if present.
1526   Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1527                             DeclaratorContext::TypeName);
1528   ParseDeclarator(DeclaratorInfo);
1529 
1530   SourceLocation RAngleBracketLoc = Tok.getLocation();
1531 
1532   if (ExpectAndConsume(tok::greater))
1533     return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1534 
1535   BalancedDelimiterTracker T(*this, tok::l_paren);
1536 
1537   if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1538     return ExprError();
1539 
1540   ExprResult Result = ParseExpression();
1541 
1542   // Match the ')'.
1543   T.consumeClose();
1544 
1545   if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1546     Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1547                                        LAngleBracketLoc, DeclaratorInfo,
1548                                        RAngleBracketLoc,
1549                                        T.getOpenLocation(), Result.get(),
1550                                        T.getCloseLocation());
1551 
1552   return Result;
1553 }
1554 
ParseCXXTypeid()1555 ExprResult Parser::ParseCXXTypeid() {
1556   assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1557 
1558   SourceLocation OpLoc = ConsumeToken();
1559   SourceLocation LParenLoc, RParenLoc;
1560   BalancedDelimiterTracker T(*this, tok::l_paren);
1561 
1562   // typeid expressions are always parenthesized.
1563   if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1564     return ExprError();
1565   LParenLoc = T.getOpenLocation();
1566 
1567   ExprResult Result;
1568 
1569   // C++0x [expr.typeid]p3:
1570   //   When typeid is applied to an expression other than an lvalue of a
1571   //   polymorphic class type [...] The expression is an unevaluated
1572   //   operand (Clause 5).
1573   //
1574   // Note that we can't tell whether the expression is an lvalue of a
1575   // polymorphic class type until after we've parsed the expression; we
1576   // speculatively assume the subexpression is unevaluated, and fix it up
1577   // later.
1578   //
1579   // We enter the unevaluated context before trying to determine whether we
1580   // have a type-id, because the tentative parse logic will try to resolve
1581   // names, and must treat them as unevaluated.
1582   EnterExpressionEvaluationContext Unevaluated(
1583       Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1584       Sema::ReuseLambdaContextDecl);
1585 
1586   if (isTypeIdInParens()) {
1587     TypeResult Ty = ParseTypeName();
1588 
1589     // Match the ')'.
1590     T.consumeClose();
1591     RParenLoc = T.getCloseLocation();
1592     if (Ty.isInvalid() || RParenLoc.isInvalid())
1593       return ExprError();
1594 
1595     Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1596                                     Ty.get().getAsOpaquePtr(), RParenLoc);
1597   } else {
1598     Result = ParseExpression();
1599 
1600     // Match the ')'.
1601     if (Result.isInvalid())
1602       SkipUntil(tok::r_paren, StopAtSemi);
1603     else {
1604       T.consumeClose();
1605       RParenLoc = T.getCloseLocation();
1606       if (RParenLoc.isInvalid())
1607         return ExprError();
1608 
1609       Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1610                                       Result.get(), RParenLoc);
1611     }
1612   }
1613 
1614   return Result;
1615 }
1616 
ParseCXXUuidof()1617 ExprResult Parser::ParseCXXUuidof() {
1618   assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1619 
1620   SourceLocation OpLoc = ConsumeToken();
1621   BalancedDelimiterTracker T(*this, tok::l_paren);
1622 
1623   // __uuidof expressions are always parenthesized.
1624   if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1625     return ExprError();
1626 
1627   ExprResult Result;
1628 
1629   if (isTypeIdInParens()) {
1630     TypeResult Ty = ParseTypeName();
1631 
1632     // Match the ')'.
1633     T.consumeClose();
1634 
1635     if (Ty.isInvalid())
1636       return ExprError();
1637 
1638     Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1639                                     Ty.get().getAsOpaquePtr(),
1640                                     T.getCloseLocation());
1641   } else {
1642     EnterExpressionEvaluationContext Unevaluated(
1643         Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1644     Result = ParseExpression();
1645 
1646     // Match the ')'.
1647     if (Result.isInvalid())
1648       SkipUntil(tok::r_paren, StopAtSemi);
1649     else {
1650       T.consumeClose();
1651 
1652       Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1653                                       /*isType=*/false,
1654                                       Result.get(), T.getCloseLocation());
1655     }
1656   }
1657 
1658   return Result;
1659 }
1660 
1661 ExprResult
ParseCXXPseudoDestructor(Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,CXXScopeSpec & SS,ParsedType ObjectType)1662 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1663                                  tok::TokenKind OpKind,
1664                                  CXXScopeSpec &SS,
1665                                  ParsedType ObjectType) {
1666   // If the last component of the (optional) nested-name-specifier is
1667   // template[opt] simple-template-id, it has already been annotated.
1668   UnqualifiedId FirstTypeName;
1669   SourceLocation CCLoc;
1670   if (Tok.is(tok::identifier)) {
1671     FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1672     ConsumeToken();
1673     assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1674     CCLoc = ConsumeToken();
1675   } else if (Tok.is(tok::annot_template_id)) {
1676     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1677     // FIXME: Carry on and build an AST representation for tooling.
1678     if (TemplateId->isInvalid())
1679       return ExprError();
1680     FirstTypeName.setTemplateId(TemplateId);
1681     ConsumeAnnotationToken();
1682     assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1683     CCLoc = ConsumeToken();
1684   } else {
1685     assert(SS.isEmpty() && "missing last component of nested name specifier");
1686     FirstTypeName.setIdentifier(nullptr, SourceLocation());
1687   }
1688 
1689   // Parse the tilde.
1690   assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1691   SourceLocation TildeLoc = ConsumeToken();
1692 
1693   if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid()) {
1694     DeclSpec DS(AttrFactory);
1695     ParseDecltypeSpecifier(DS);
1696     if (DS.getTypeSpecType() == TST_error)
1697       return ExprError();
1698     return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1699                                              TildeLoc, DS);
1700   }
1701 
1702   if (!Tok.is(tok::identifier)) {
1703     Diag(Tok, diag::err_destructor_tilde_identifier);
1704     return ExprError();
1705   }
1706 
1707   // pack-index-specifier
1708   if (GetLookAheadToken(1).is(tok::ellipsis) &&
1709       GetLookAheadToken(2).is(tok::l_square)) {
1710     DeclSpec DS(AttrFactory);
1711     ParsePackIndexingType(DS);
1712     return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1713                                              TildeLoc, DS);
1714   }
1715 
1716   // Parse the second type.
1717   UnqualifiedId SecondTypeName;
1718   IdentifierInfo *Name = Tok.getIdentifierInfo();
1719   SourceLocation NameLoc = ConsumeToken();
1720   SecondTypeName.setIdentifier(Name, NameLoc);
1721 
1722   // If there is a '<', the second type name is a template-id. Parse
1723   // it as such.
1724   //
1725   // FIXME: This is not a context in which a '<' is assumed to start a template
1726   // argument list. This affects examples such as
1727   //   void f(auto *p) { p->~X<int>(); }
1728   // ... but there's no ambiguity, and nowhere to write 'template' in such an
1729   // example, so we accept it anyway.
1730   if (Tok.is(tok::less) &&
1731       ParseUnqualifiedIdTemplateId(
1732           SS, ObjectType, Base && Base->containsErrors(), SourceLocation(),
1733           Name, NameLoc, false, SecondTypeName,
1734           /*AssumeTemplateId=*/true))
1735     return ExprError();
1736 
1737   return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1738                                            SS, FirstTypeName, CCLoc, TildeLoc,
1739                                            SecondTypeName);
1740 }
1741 
ParseCXXBoolLiteral()1742 ExprResult Parser::ParseCXXBoolLiteral() {
1743   tok::TokenKind Kind = Tok.getKind();
1744   return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1745 }
1746 
ParseThrowExpression()1747 ExprResult Parser::ParseThrowExpression() {
1748   assert(Tok.is(tok::kw_throw) && "Not throw!");
1749   SourceLocation ThrowLoc = ConsumeToken();           // Eat the throw token.
1750 
1751   // If the current token isn't the start of an assignment-expression,
1752   // then the expression is not present.  This handles things like:
1753   //   "C ? throw : (void)42", which is crazy but legal.
1754   switch (Tok.getKind()) {  // FIXME: move this predicate somewhere common.
1755   case tok::semi:
1756   case tok::r_paren:
1757   case tok::r_square:
1758   case tok::r_brace:
1759   case tok::colon:
1760   case tok::comma:
1761     return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1762 
1763   default:
1764     ExprResult Expr(ParseAssignmentExpression());
1765     if (Expr.isInvalid()) return Expr;
1766     return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1767   }
1768 }
1769 
ParseCoyieldExpression()1770 ExprResult Parser::ParseCoyieldExpression() {
1771   assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1772 
1773   SourceLocation Loc = ConsumeToken();
1774   ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1775                                          : ParseAssignmentExpression();
1776   if (!Expr.isInvalid())
1777     Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1778   return Expr;
1779 }
1780 
ParseCXXThis()1781 ExprResult Parser::ParseCXXThis() {
1782   assert(Tok.is(tok::kw_this) && "Not 'this'!");
1783   SourceLocation ThisLoc = ConsumeToken();
1784   return Actions.ActOnCXXThis(ThisLoc);
1785 }
1786 
1787 ExprResult
ParseCXXTypeConstructExpression(const DeclSpec & DS)1788 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1789   Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1790                             DeclaratorContext::FunctionalCast);
1791   ParsedType TypeRep = Actions.ActOnTypeName(DeclaratorInfo).get();
1792 
1793   assert((Tok.is(tok::l_paren) ||
1794           (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1795          && "Expected '(' or '{'!");
1796 
1797   if (Tok.is(tok::l_brace)) {
1798     PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1799     ExprResult Init = ParseBraceInitializer();
1800     if (Init.isInvalid())
1801       return Init;
1802     Expr *InitList = Init.get();
1803     return Actions.ActOnCXXTypeConstructExpr(
1804         TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
1805         InitList->getEndLoc(), /*ListInitialization=*/true);
1806   } else {
1807     BalancedDelimiterTracker T(*this, tok::l_paren);
1808     T.consumeOpen();
1809 
1810     PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1811 
1812     ExprVector Exprs;
1813 
1814     auto RunSignatureHelp = [&]() {
1815       QualType PreferredType;
1816       if (TypeRep)
1817         PreferredType =
1818             Actions.CodeCompletion().ProduceConstructorSignatureHelp(
1819                 TypeRep.get()->getCanonicalTypeInternal(), DS.getEndLoc(),
1820                 Exprs, T.getOpenLocation(), /*Braced=*/false);
1821       CalledSignatureHelp = true;
1822       return PreferredType;
1823     };
1824 
1825     if (Tok.isNot(tok::r_paren)) {
1826       if (ParseExpressionList(Exprs, [&] {
1827             PreferredType.enterFunctionArgument(Tok.getLocation(),
1828                                                 RunSignatureHelp);
1829           })) {
1830         if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1831           RunSignatureHelp();
1832         SkipUntil(tok::r_paren, StopAtSemi);
1833         return ExprError();
1834       }
1835     }
1836 
1837     // Match the ')'.
1838     T.consumeClose();
1839 
1840     // TypeRep could be null, if it references an invalid typedef.
1841     if (!TypeRep)
1842       return ExprError();
1843 
1844     return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1845                                              Exprs, T.getCloseLocation(),
1846                                              /*ListInitialization=*/false);
1847   }
1848 }
1849 
1850 Parser::DeclGroupPtrTy
ParseAliasDeclarationInInitStatement(DeclaratorContext Context,ParsedAttributes & Attrs)1851 Parser::ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
1852                                              ParsedAttributes &Attrs) {
1853   assert(Tok.is(tok::kw_using) && "Expected using");
1854   assert((Context == DeclaratorContext::ForInit ||
1855           Context == DeclaratorContext::SelectionInit) &&
1856          "Unexpected Declarator Context");
1857   DeclGroupPtrTy DG;
1858   SourceLocation DeclStart = ConsumeToken(), DeclEnd;
1859 
1860   DG = ParseUsingDeclaration(Context, {}, DeclStart, DeclEnd, Attrs, AS_none);
1861   if (!DG)
1862     return DG;
1863 
1864   Diag(DeclStart, !getLangOpts().CPlusPlus23
1865                       ? diag::ext_alias_in_init_statement
1866                       : diag::warn_cxx20_alias_in_init_statement)
1867       << SourceRange(DeclStart, DeclEnd);
1868 
1869   return DG;
1870 }
1871 
1872 Sema::ConditionResult
ParseCXXCondition(StmtResult * InitStmt,SourceLocation Loc,Sema::ConditionKind CK,bool MissingOK,ForRangeInfo * FRI,bool EnterForConditionScope)1873 Parser::ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc,
1874                           Sema::ConditionKind CK, bool MissingOK,
1875                           ForRangeInfo *FRI, bool EnterForConditionScope) {
1876   // Helper to ensure we always enter a continue/break scope if requested.
1877   struct ForConditionScopeRAII {
1878     Scope *S;
1879     void enter(bool IsConditionVariable) {
1880       if (S) {
1881         S->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1882         S->setIsConditionVarScope(IsConditionVariable);
1883       }
1884     }
1885     ~ForConditionScopeRAII() {
1886       if (S)
1887         S->setIsConditionVarScope(false);
1888     }
1889   } ForConditionScope{EnterForConditionScope ? getCurScope() : nullptr};
1890 
1891   ParenBraceBracketBalancer BalancerRAIIObj(*this);
1892   PreferredType.enterCondition(Actions, Tok.getLocation());
1893 
1894   if (Tok.is(tok::code_completion)) {
1895     cutOffParsing();
1896     Actions.CodeCompletion().CodeCompleteOrdinaryName(
1897         getCurScope(), SemaCodeCompletion::PCC_Condition);
1898     return Sema::ConditionError();
1899   }
1900 
1901   ParsedAttributes attrs(AttrFactory);
1902   MaybeParseCXX11Attributes(attrs);
1903 
1904   const auto WarnOnInit = [this, &CK] {
1905     Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1906                                 ? diag::warn_cxx14_compat_init_statement
1907                                 : diag::ext_init_statement)
1908         << (CK == Sema::ConditionKind::Switch);
1909   };
1910 
1911   // Determine what kind of thing we have.
1912   switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
1913   case ConditionOrInitStatement::Expression: {
1914     // If this is a for loop, we're entering its condition.
1915     ForConditionScope.enter(/*IsConditionVariable=*/false);
1916 
1917     ProhibitAttributes(attrs);
1918 
1919     // We can have an empty expression here.
1920     //   if (; true);
1921     if (InitStmt && Tok.is(tok::semi)) {
1922       WarnOnInit();
1923       SourceLocation SemiLoc = Tok.getLocation();
1924       if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
1925         Diag(SemiLoc, diag::warn_empty_init_statement)
1926             << (CK == Sema::ConditionKind::Switch)
1927             << FixItHint::CreateRemoval(SemiLoc);
1928       }
1929       ConsumeToken();
1930       *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1931       return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
1932     }
1933 
1934     EnterExpressionEvaluationContext Eval(
1935         Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
1936         /*LambdaContextDecl=*/nullptr,
1937         /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_Other,
1938         /*ShouldEnter=*/CK == Sema::ConditionKind::ConstexprIf);
1939 
1940     ExprResult Expr = ParseExpression();
1941 
1942     if (Expr.isInvalid())
1943       return Sema::ConditionError();
1944 
1945     if (InitStmt && Tok.is(tok::semi)) {
1946       WarnOnInit();
1947       *InitStmt = Actions.ActOnExprStmt(Expr.get());
1948       ConsumeToken();
1949       return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
1950     }
1951 
1952     return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK,
1953                                   MissingOK);
1954   }
1955 
1956   case ConditionOrInitStatement::InitStmtDecl: {
1957     WarnOnInit();
1958     DeclGroupPtrTy DG;
1959     SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1960     if (Tok.is(tok::kw_using))
1961       DG = ParseAliasDeclarationInInitStatement(
1962           DeclaratorContext::SelectionInit, attrs);
1963     else {
1964       ParsedAttributes DeclSpecAttrs(AttrFactory);
1965       DG = ParseSimpleDeclaration(DeclaratorContext::SelectionInit, DeclEnd,
1966                                   attrs, DeclSpecAttrs, /*RequireSemi=*/true);
1967     }
1968     *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1969     return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
1970   }
1971 
1972   case ConditionOrInitStatement::ForRangeDecl: {
1973     // This is 'for (init-stmt; for-range-decl : range-expr)'.
1974     // We're not actually in a for loop yet, so 'break' and 'continue' aren't
1975     // permitted here.
1976     assert(FRI && "should not parse a for range declaration here");
1977     SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1978     ParsedAttributes DeclSpecAttrs(AttrFactory);
1979     DeclGroupPtrTy DG = ParseSimpleDeclaration(
1980         DeclaratorContext::ForInit, DeclEnd, attrs, DeclSpecAttrs, false, FRI);
1981     FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1982     return Sema::ConditionResult();
1983   }
1984 
1985   case ConditionOrInitStatement::ConditionDecl:
1986   case ConditionOrInitStatement::Error:
1987     break;
1988   }
1989 
1990   // If this is a for loop, we're entering its condition.
1991   ForConditionScope.enter(/*IsConditionVariable=*/true);
1992 
1993   // type-specifier-seq
1994   DeclSpec DS(AttrFactory);
1995   ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
1996 
1997   // declarator
1998   Declarator DeclaratorInfo(DS, attrs, DeclaratorContext::Condition);
1999   ParseDeclarator(DeclaratorInfo);
2000 
2001   // simple-asm-expr[opt]
2002   if (Tok.is(tok::kw_asm)) {
2003     SourceLocation Loc;
2004     ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2005     if (AsmLabel.isInvalid()) {
2006       SkipUntil(tok::semi, StopAtSemi);
2007       return Sema::ConditionError();
2008     }
2009     DeclaratorInfo.setAsmLabel(AsmLabel.get());
2010     DeclaratorInfo.SetRangeEnd(Loc);
2011   }
2012 
2013   // If attributes are present, parse them.
2014   MaybeParseGNUAttributes(DeclaratorInfo);
2015 
2016   // Type-check the declaration itself.
2017   DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
2018                                                         DeclaratorInfo);
2019   if (Dcl.isInvalid())
2020     return Sema::ConditionError();
2021   Decl *DeclOut = Dcl.get();
2022 
2023   // '=' assignment-expression
2024   // If a '==' or '+=' is found, suggest a fixit to '='.
2025   bool CopyInitialization = isTokenEqualOrEqualTypo();
2026   if (CopyInitialization)
2027     ConsumeToken();
2028 
2029   ExprResult InitExpr = ExprError();
2030   if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2031     Diag(Tok.getLocation(),
2032          diag::warn_cxx98_compat_generalized_initializer_lists);
2033     InitExpr = ParseBraceInitializer();
2034   } else if (CopyInitialization) {
2035     PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
2036     InitExpr = ParseAssignmentExpression();
2037   } else if (Tok.is(tok::l_paren)) {
2038     // This was probably an attempt to initialize the variable.
2039     SourceLocation LParen = ConsumeParen(), RParen = LParen;
2040     if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
2041       RParen = ConsumeParen();
2042     Diag(DeclOut->getLocation(),
2043          diag::err_expected_init_in_condition_lparen)
2044       << SourceRange(LParen, RParen);
2045   } else {
2046     Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
2047   }
2048 
2049   if (!InitExpr.isInvalid())
2050     Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
2051   else
2052     Actions.ActOnInitializerError(DeclOut);
2053 
2054   Actions.FinalizeDeclaration(DeclOut);
2055   return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
2056 }
2057 
ParseCXXSimpleTypeSpecifier(DeclSpec & DS)2058 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
2059   DS.SetRangeStart(Tok.getLocation());
2060   const char *PrevSpec;
2061   unsigned DiagID;
2062   SourceLocation Loc = Tok.getLocation();
2063   const clang::PrintingPolicy &Policy =
2064       Actions.getASTContext().getPrintingPolicy();
2065 
2066   switch (Tok.getKind()) {
2067   case tok::identifier:   // foo::bar
2068   case tok::coloncolon:   // ::foo::bar
2069     llvm_unreachable("Annotation token should already be formed!");
2070   default:
2071     llvm_unreachable("Not a simple-type-specifier token!");
2072 
2073   // type-name
2074   case tok::annot_typename: {
2075     DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
2076                        getTypeAnnotation(Tok), Policy);
2077     DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2078     ConsumeAnnotationToken();
2079     DS.Finish(Actions, Policy);
2080     return;
2081   }
2082 
2083   case tok::kw__ExtInt:
2084   case tok::kw__BitInt: {
2085     DiagnoseBitIntUse(Tok);
2086     ExprResult ER = ParseExtIntegerArgument();
2087     if (ER.isInvalid())
2088       DS.SetTypeSpecError();
2089     else
2090       DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
2091 
2092     // Do this here because we have already consumed the close paren.
2093     DS.SetRangeEnd(PrevTokLocation);
2094     DS.Finish(Actions, Policy);
2095     return;
2096   }
2097 
2098   // builtin types
2099   case tok::kw_short:
2100     DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID,
2101                         Policy);
2102     break;
2103   case tok::kw_long:
2104     DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID,
2105                         Policy);
2106     break;
2107   case tok::kw___int64:
2108     DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc, PrevSpec, DiagID,
2109                         Policy);
2110     break;
2111   case tok::kw_signed:
2112     DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
2113     break;
2114   case tok::kw_unsigned:
2115     DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID);
2116     break;
2117   case tok::kw_void:
2118     DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
2119     break;
2120   case tok::kw_auto:
2121     DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID, Policy);
2122     break;
2123   case tok::kw_char:
2124     DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
2125     break;
2126   case tok::kw_int:
2127     DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
2128     break;
2129   case tok::kw___int128:
2130     DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
2131     break;
2132   case tok::kw___bf16:
2133     DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy);
2134     break;
2135   case tok::kw_half:
2136     DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
2137     break;
2138   case tok::kw_float:
2139     DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
2140     break;
2141   case tok::kw_double:
2142     DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
2143     break;
2144   case tok::kw__Float16:
2145     DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2146     break;
2147   case tok::kw___float128:
2148     DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2149     break;
2150   case tok::kw___ibm128:
2151     DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec, DiagID, Policy);
2152     break;
2153   case tok::kw_wchar_t:
2154     DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
2155     break;
2156   case tok::kw_char8_t:
2157     DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2158     break;
2159   case tok::kw_char16_t:
2160     DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
2161     break;
2162   case tok::kw_char32_t:
2163     DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
2164     break;
2165   case tok::kw_bool:
2166     DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
2167     break;
2168   case tok::kw__Accum:
2169     DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec, DiagID, Policy);
2170     break;
2171   case tok::kw__Fract:
2172     DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec, DiagID, Policy);
2173     break;
2174   case tok::kw__Sat:
2175     DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
2176     break;
2177 #define GENERIC_IMAGE_TYPE(ImgType, Id)                                        \
2178   case tok::kw_##ImgType##_t:                                                  \
2179     DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID,     \
2180                        Policy);                                                \
2181     break;
2182 #include "clang/Basic/OpenCLImageTypes.def"
2183 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId)                            \
2184   case tok::kw_##Name:                                                         \
2185     DS.SetTypeSpecType(DeclSpec::TST_##Name, Loc, PrevSpec, DiagID, Policy);   \
2186     break;
2187 #include "clang/Basic/HLSLIntangibleTypes.def"
2188 
2189   case tok::annot_decltype:
2190   case tok::kw_decltype:
2191     DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2192     return DS.Finish(Actions, Policy);
2193 
2194   case tok::annot_pack_indexing_type:
2195     DS.SetRangeEnd(ParsePackIndexingType(DS));
2196     return DS.Finish(Actions, Policy);
2197 
2198   // GNU typeof support.
2199   case tok::kw_typeof:
2200     ParseTypeofSpecifier(DS);
2201     DS.Finish(Actions, Policy);
2202     return;
2203   }
2204   ConsumeAnyToken();
2205   DS.SetRangeEnd(PrevTokLocation);
2206   DS.Finish(Actions, Policy);
2207 }
2208 
ParseCXXTypeSpecifierSeq(DeclSpec & DS,DeclaratorContext Context)2209 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS, DeclaratorContext Context) {
2210   ParseSpecifierQualifierList(DS, AS_none,
2211                               getDeclSpecContextFromDeclaratorContext(Context));
2212   DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2213   return false;
2214 }
2215 
ParseUnqualifiedIdTemplateId(CXXScopeSpec & SS,ParsedType ObjectType,bool ObjectHadErrors,SourceLocation TemplateKWLoc,IdentifierInfo * Name,SourceLocation NameLoc,bool EnteringContext,UnqualifiedId & Id,bool AssumeTemplateId)2216 bool Parser::ParseUnqualifiedIdTemplateId(
2217     CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
2218     SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc,
2219     bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) {
2220   assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2221 
2222   TemplateTy Template;
2223   TemplateNameKind TNK = TNK_Non_template;
2224   switch (Id.getKind()) {
2225   case UnqualifiedIdKind::IK_Identifier:
2226   case UnqualifiedIdKind::IK_OperatorFunctionId:
2227   case UnqualifiedIdKind::IK_LiteralOperatorId:
2228     if (AssumeTemplateId) {
2229       // We defer the injected-class-name checks until we've found whether
2230       // this template-id is used to form a nested-name-specifier or not.
2231       TNK = Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Id,
2232                                       ObjectType, EnteringContext, Template,
2233                                       /*AllowInjectedClassName*/ true);
2234     } else {
2235       bool MemberOfUnknownSpecialization;
2236       TNK = Actions.isTemplateName(getCurScope(), SS,
2237                                    TemplateKWLoc.isValid(), Id,
2238                                    ObjectType, EnteringContext, Template,
2239                                    MemberOfUnknownSpecialization);
2240       // If lookup found nothing but we're assuming that this is a template
2241       // name, double-check that makes sense syntactically before committing
2242       // to it.
2243       if (TNK == TNK_Undeclared_template &&
2244           isTemplateArgumentList(0) == TPResult::False)
2245         return false;
2246 
2247       if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2248           ObjectType && isTemplateArgumentList(0) == TPResult::True) {
2249         // If we had errors before, ObjectType can be dependent even without any
2250         // templates, do not report missing template keyword in that case.
2251         if (!ObjectHadErrors) {
2252           // We have something like t->getAs<T>(), where getAs is a
2253           // member of an unknown specialization. However, this will only
2254           // parse correctly as a template, so suggest the keyword 'template'
2255           // before 'getAs' and treat this as a dependent template name.
2256           std::string Name;
2257           if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2258             Name = std::string(Id.Identifier->getName());
2259           else {
2260             Name = "operator ";
2261             if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
2262               Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2263             else
2264               Name += Id.Identifier->getName();
2265           }
2266           Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2267               << Name
2268               << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2269         }
2270         TNK = Actions.ActOnTemplateName(
2271             getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2272             Template, /*AllowInjectedClassName*/ true);
2273       } else if (TNK == TNK_Non_template) {
2274         return false;
2275       }
2276     }
2277     break;
2278 
2279   case UnqualifiedIdKind::IK_ConstructorName: {
2280     UnqualifiedId TemplateName;
2281     bool MemberOfUnknownSpecialization;
2282     TemplateName.setIdentifier(Name, NameLoc);
2283     TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2284                                  TemplateName, ObjectType,
2285                                  EnteringContext, Template,
2286                                  MemberOfUnknownSpecialization);
2287     if (TNK == TNK_Non_template)
2288       return false;
2289     break;
2290   }
2291 
2292   case UnqualifiedIdKind::IK_DestructorName: {
2293     UnqualifiedId TemplateName;
2294     bool MemberOfUnknownSpecialization;
2295     TemplateName.setIdentifier(Name, NameLoc);
2296     if (ObjectType) {
2297       TNK = Actions.ActOnTemplateName(
2298           getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2299           EnteringContext, Template, /*AllowInjectedClassName*/ true);
2300     } else {
2301       TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2302                                    TemplateName, ObjectType,
2303                                    EnteringContext, Template,
2304                                    MemberOfUnknownSpecialization);
2305 
2306       if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2307         Diag(NameLoc, diag::err_destructor_template_id)
2308           << Name << SS.getRange();
2309         // Carry on to parse the template arguments before bailing out.
2310       }
2311     }
2312     break;
2313   }
2314 
2315   default:
2316     return false;
2317   }
2318 
2319   // Parse the enclosed template argument list.
2320   SourceLocation LAngleLoc, RAngleLoc;
2321   TemplateArgList TemplateArgs;
2322   if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs, RAngleLoc,
2323                                        Template))
2324     return true;
2325 
2326   // If this is a non-template, we already issued a diagnostic.
2327   if (TNK == TNK_Non_template)
2328     return true;
2329 
2330   if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2331       Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2332       Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
2333     // Form a parsed representation of the template-id to be stored in the
2334     // UnqualifiedId.
2335 
2336     // FIXME: Store name for literal operator too.
2337     const IdentifierInfo *TemplateII =
2338         Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2339                                                          : nullptr;
2340     OverloadedOperatorKind OpKind =
2341         Id.getKind() == UnqualifiedIdKind::IK_Identifier
2342             ? OO_None
2343             : Id.OperatorFunctionId.Operator;
2344 
2345     TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2346         TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2347         LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, TemplateIds);
2348 
2349     Id.setTemplateId(TemplateId);
2350     return false;
2351   }
2352 
2353   // Bundle the template arguments together.
2354   ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2355 
2356   // Constructor and destructor names.
2357   TypeResult Type = Actions.ActOnTemplateIdType(
2358       getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2359       TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
2360   if (Type.isInvalid())
2361     return true;
2362 
2363   if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
2364     Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2365   else
2366     Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2367 
2368   return false;
2369 }
2370 
ParseUnqualifiedIdOperator(CXXScopeSpec & SS,bool EnteringContext,ParsedType ObjectType,UnqualifiedId & Result)2371 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2372                                         ParsedType ObjectType,
2373                                         UnqualifiedId &Result) {
2374   assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2375 
2376   // Consume the 'operator' keyword.
2377   SourceLocation KeywordLoc = ConsumeToken();
2378 
2379   // Determine what kind of operator name we have.
2380   unsigned SymbolIdx = 0;
2381   SourceLocation SymbolLocations[3];
2382   OverloadedOperatorKind Op = OO_None;
2383   switch (Tok.getKind()) {
2384     case tok::kw_new:
2385     case tok::kw_delete: {
2386       bool isNew = Tok.getKind() == tok::kw_new;
2387       // Consume the 'new' or 'delete'.
2388       SymbolLocations[SymbolIdx++] = ConsumeToken();
2389       // Check for array new/delete.
2390       if (Tok.is(tok::l_square) &&
2391           (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2392         // Consume the '[' and ']'.
2393         BalancedDelimiterTracker T(*this, tok::l_square);
2394         T.consumeOpen();
2395         T.consumeClose();
2396         if (T.getCloseLocation().isInvalid())
2397           return true;
2398 
2399         SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2400         SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2401         Op = isNew? OO_Array_New : OO_Array_Delete;
2402       } else {
2403         Op = isNew? OO_New : OO_Delete;
2404       }
2405       break;
2406     }
2407 
2408 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2409     case tok::Token:                                                     \
2410       SymbolLocations[SymbolIdx++] = ConsumeToken();                     \
2411       Op = OO_##Name;                                                    \
2412       break;
2413 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2414 #include "clang/Basic/OperatorKinds.def"
2415 
2416     case tok::l_paren: {
2417       // Consume the '(' and ')'.
2418       BalancedDelimiterTracker T(*this, tok::l_paren);
2419       T.consumeOpen();
2420       T.consumeClose();
2421       if (T.getCloseLocation().isInvalid())
2422         return true;
2423 
2424       SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2425       SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2426       Op = OO_Call;
2427       break;
2428     }
2429 
2430     case tok::l_square: {
2431       // Consume the '[' and ']'.
2432       BalancedDelimiterTracker T(*this, tok::l_square);
2433       T.consumeOpen();
2434       T.consumeClose();
2435       if (T.getCloseLocation().isInvalid())
2436         return true;
2437 
2438       SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2439       SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2440       Op = OO_Subscript;
2441       break;
2442     }
2443 
2444     case tok::code_completion: {
2445       // Don't try to parse any further.
2446       cutOffParsing();
2447       // Code completion for the operator name.
2448       Actions.CodeCompletion().CodeCompleteOperatorName(getCurScope());
2449       return true;
2450     }
2451 
2452     default:
2453       break;
2454   }
2455 
2456   if (Op != OO_None) {
2457     // We have parsed an operator-function-id.
2458     Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2459     return false;
2460   }
2461 
2462   // Parse a literal-operator-id.
2463   //
2464   //   literal-operator-id: C++11 [over.literal]
2465   //     operator string-literal identifier
2466   //     operator user-defined-string-literal
2467 
2468   if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2469     Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2470 
2471     SourceLocation DiagLoc;
2472     unsigned DiagId = 0;
2473 
2474     // We're past translation phase 6, so perform string literal concatenation
2475     // before checking for "".
2476     SmallVector<Token, 4> Toks;
2477     SmallVector<SourceLocation, 4> TokLocs;
2478     while (isTokenStringLiteral()) {
2479       if (!Tok.is(tok::string_literal) && !DiagId) {
2480         // C++11 [over.literal]p1:
2481         //   The string-literal or user-defined-string-literal in a
2482         //   literal-operator-id shall have no encoding-prefix [...].
2483         DiagLoc = Tok.getLocation();
2484         DiagId = diag::err_literal_operator_string_prefix;
2485       }
2486       Toks.push_back(Tok);
2487       TokLocs.push_back(ConsumeStringToken());
2488     }
2489 
2490     StringLiteralParser Literal(Toks, PP);
2491     if (Literal.hadError)
2492       return true;
2493 
2494     // Grab the literal operator's suffix, which will be either the next token
2495     // or a ud-suffix from the string literal.
2496     bool IsUDSuffix = !Literal.getUDSuffix().empty();
2497     IdentifierInfo *II = nullptr;
2498     SourceLocation SuffixLoc;
2499     if (IsUDSuffix) {
2500       II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2501       SuffixLoc =
2502         Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2503                                        Literal.getUDSuffixOffset(),
2504                                        PP.getSourceManager(), getLangOpts());
2505     } else if (Tok.is(tok::identifier)) {
2506       II = Tok.getIdentifierInfo();
2507       SuffixLoc = ConsumeToken();
2508       TokLocs.push_back(SuffixLoc);
2509     } else {
2510       Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2511       return true;
2512     }
2513 
2514     // The string literal must be empty.
2515     if (!Literal.GetString().empty() || Literal.Pascal) {
2516       // C++11 [over.literal]p1:
2517       //   The string-literal or user-defined-string-literal in a
2518       //   literal-operator-id shall [...] contain no characters
2519       //   other than the implicit terminating '\0'.
2520       DiagLoc = TokLocs.front();
2521       DiagId = diag::err_literal_operator_string_not_empty;
2522     }
2523 
2524     if (DiagId) {
2525       // This isn't a valid literal-operator-id, but we think we know
2526       // what the user meant. Tell them what they should have written.
2527       SmallString<32> Str;
2528       Str += "\"\"";
2529       Str += II->getName();
2530       Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2531           SourceRange(TokLocs.front(), TokLocs.back()), Str);
2532     }
2533 
2534     Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2535 
2536     return Actions.checkLiteralOperatorId(SS, Result, IsUDSuffix);
2537   }
2538 
2539   // Parse a conversion-function-id.
2540   //
2541   //   conversion-function-id: [C++ 12.3.2]
2542   //     operator conversion-type-id
2543   //
2544   //   conversion-type-id:
2545   //     type-specifier-seq conversion-declarator[opt]
2546   //
2547   //   conversion-declarator:
2548   //     ptr-operator conversion-declarator[opt]
2549 
2550   // Parse the type-specifier-seq.
2551   DeclSpec DS(AttrFactory);
2552   if (ParseCXXTypeSpecifierSeq(
2553           DS, DeclaratorContext::ConversionId)) // FIXME: ObjectType?
2554     return true;
2555 
2556   // Parse the conversion-declarator, which is merely a sequence of
2557   // ptr-operators.
2558   Declarator D(DS, ParsedAttributesView::none(),
2559                DeclaratorContext::ConversionId);
2560   ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2561 
2562   // Finish up the type.
2563   TypeResult Ty = Actions.ActOnTypeName(D);
2564   if (Ty.isInvalid())
2565     return true;
2566 
2567   // Note that this is a conversion-function-id.
2568   Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2569                                  D.getSourceRange().getEnd());
2570   return false;
2571 }
2572 
ParseUnqualifiedId(CXXScopeSpec & SS,ParsedType ObjectType,bool ObjectHadErrors,bool EnteringContext,bool AllowDestructorName,bool AllowConstructorName,bool AllowDeductionGuide,SourceLocation * TemplateKWLoc,UnqualifiedId & Result)2573 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
2574                                 bool ObjectHadErrors, bool EnteringContext,
2575                                 bool AllowDestructorName,
2576                                 bool AllowConstructorName,
2577                                 bool AllowDeductionGuide,
2578                                 SourceLocation *TemplateKWLoc,
2579                                 UnqualifiedId &Result) {
2580   if (TemplateKWLoc)
2581     *TemplateKWLoc = SourceLocation();
2582 
2583   // Handle 'A::template B'. This is for template-ids which have not
2584   // already been annotated by ParseOptionalCXXScopeSpecifier().
2585   bool TemplateSpecified = false;
2586   if (Tok.is(tok::kw_template)) {
2587     if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2588       TemplateSpecified = true;
2589       *TemplateKWLoc = ConsumeToken();
2590     } else {
2591       SourceLocation TemplateLoc = ConsumeToken();
2592       Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2593         << FixItHint::CreateRemoval(TemplateLoc);
2594     }
2595   }
2596 
2597   // unqualified-id:
2598   //   identifier
2599   //   template-id (when it hasn't already been annotated)
2600   if (Tok.is(tok::identifier)) {
2601   ParseIdentifier:
2602     // Consume the identifier.
2603     IdentifierInfo *Id = Tok.getIdentifierInfo();
2604     SourceLocation IdLoc = ConsumeToken();
2605 
2606     if (!getLangOpts().CPlusPlus) {
2607       // If we're not in C++, only identifiers matter. Record the
2608       // identifier and return.
2609       Result.setIdentifier(Id, IdLoc);
2610       return false;
2611     }
2612 
2613     ParsedTemplateTy TemplateName;
2614     if (AllowConstructorName &&
2615         Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2616       // We have parsed a constructor name.
2617       ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2618                                                  EnteringContext);
2619       if (!Ty)
2620         return true;
2621       Result.setConstructorName(Ty, IdLoc, IdLoc);
2622     } else if (getLangOpts().CPlusPlus17 && AllowDeductionGuide &&
2623                SS.isEmpty() &&
2624                Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc, SS,
2625                                             &TemplateName)) {
2626       // We have parsed a template-name naming a deduction guide.
2627       Result.setDeductionGuideName(TemplateName, IdLoc);
2628     } else {
2629       // We have parsed an identifier.
2630       Result.setIdentifier(Id, IdLoc);
2631     }
2632 
2633     // If the next token is a '<', we may have a template.
2634     TemplateTy Template;
2635     if (Tok.is(tok::less))
2636       return ParseUnqualifiedIdTemplateId(
2637           SS, ObjectType, ObjectHadErrors,
2638           TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2639           EnteringContext, Result, TemplateSpecified);
2640 
2641     if (TemplateSpecified) {
2642       TemplateNameKind TNK =
2643           Actions.ActOnTemplateName(getCurScope(), SS, *TemplateKWLoc, Result,
2644                                     ObjectType, EnteringContext, Template,
2645                                     /*AllowInjectedClassName=*/true);
2646       if (TNK == TNK_Non_template)
2647         return true;
2648 
2649       // C++2c [tem.names]p6
2650       // A name prefixed by the keyword template shall be followed by a template
2651       // argument list or refer to a class template or an alias template.
2652       if ((TNK == TNK_Function_template || TNK == TNK_Dependent_template_name ||
2653            TNK == TNK_Var_template) &&
2654           !Tok.is(tok::less))
2655         Diag(IdLoc, diag::missing_template_arg_list_after_template_kw);
2656     }
2657     return false;
2658   }
2659 
2660   // unqualified-id:
2661   //   template-id (already parsed and annotated)
2662   if (Tok.is(tok::annot_template_id)) {
2663     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2664 
2665     // FIXME: Consider passing invalid template-ids on to callers; they may
2666     // be able to recover better than we can.
2667     if (TemplateId->isInvalid()) {
2668       ConsumeAnnotationToken();
2669       return true;
2670     }
2671 
2672     // If the template-name names the current class, then this is a constructor
2673     if (AllowConstructorName && TemplateId->Name &&
2674         Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2675       if (SS.isSet()) {
2676         // C++ [class.qual]p2 specifies that a qualified template-name
2677         // is taken as the constructor name where a constructor can be
2678         // declared. Thus, the template arguments are extraneous, so
2679         // complain about them and remove them entirely.
2680         Diag(TemplateId->TemplateNameLoc,
2681              diag::err_out_of_line_constructor_template_id)
2682           << TemplateId->Name
2683           << FixItHint::CreateRemoval(
2684                     SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2685         ParsedType Ty = Actions.getConstructorName(
2686             *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2687             EnteringContext);
2688         if (!Ty)
2689           return true;
2690         Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2691                                   TemplateId->RAngleLoc);
2692         ConsumeAnnotationToken();
2693         return false;
2694       }
2695 
2696       Result.setConstructorTemplateId(TemplateId);
2697       ConsumeAnnotationToken();
2698       return false;
2699     }
2700 
2701     // We have already parsed a template-id; consume the annotation token as
2702     // our unqualified-id.
2703     Result.setTemplateId(TemplateId);
2704     SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2705     if (TemplateLoc.isValid()) {
2706       if (TemplateKWLoc && (ObjectType || SS.isSet()))
2707         *TemplateKWLoc = TemplateLoc;
2708       else
2709         Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2710             << FixItHint::CreateRemoval(TemplateLoc);
2711     }
2712     ConsumeAnnotationToken();
2713     return false;
2714   }
2715 
2716   // unqualified-id:
2717   //   operator-function-id
2718   //   conversion-function-id
2719   if (Tok.is(tok::kw_operator)) {
2720     if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2721       return true;
2722 
2723     // If we have an operator-function-id or a literal-operator-id and the next
2724     // token is a '<', we may have a
2725     //
2726     //   template-id:
2727     //     operator-function-id < template-argument-list[opt] >
2728     TemplateTy Template;
2729     if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2730          Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
2731         Tok.is(tok::less))
2732       return ParseUnqualifiedIdTemplateId(
2733           SS, ObjectType, ObjectHadErrors,
2734           TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2735           SourceLocation(), EnteringContext, Result, TemplateSpecified);
2736     else if (TemplateSpecified &&
2737              Actions.ActOnTemplateName(
2738                  getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2739                  EnteringContext, Template,
2740                  /*AllowInjectedClassName*/ true) == TNK_Non_template)
2741       return true;
2742 
2743     return false;
2744   }
2745 
2746   if (getLangOpts().CPlusPlus &&
2747       (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2748     // C++ [expr.unary.op]p10:
2749     //   There is an ambiguity in the unary-expression ~X(), where X is a
2750     //   class-name. The ambiguity is resolved in favor of treating ~ as a
2751     //    unary complement rather than treating ~X as referring to a destructor.
2752 
2753     // Parse the '~'.
2754     SourceLocation TildeLoc = ConsumeToken();
2755 
2756     if (TemplateSpecified) {
2757       // C++ [temp.names]p3:
2758       //   A name prefixed by the keyword template shall be a template-id [...]
2759       //
2760       // A template-id cannot begin with a '~' token. This would never work
2761       // anyway: x.~A<int>() would specify that the destructor is a template,
2762       // not that 'A' is a template.
2763       //
2764       // FIXME: Suggest replacing the attempted destructor name with a correct
2765       // destructor name and recover. (This is not trivial if this would become
2766       // a pseudo-destructor name).
2767       Diag(*TemplateKWLoc, diag::err_unexpected_template_in_destructor_name)
2768         << Tok.getLocation();
2769       return true;
2770     }
2771 
2772     if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2773       DeclSpec DS(AttrFactory);
2774       SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2775       if (ParsedType Type =
2776               Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2777         Result.setDestructorName(TildeLoc, Type, EndLoc);
2778         return false;
2779       }
2780       return true;
2781     }
2782 
2783     // Parse the class-name.
2784     if (Tok.isNot(tok::identifier)) {
2785       Diag(Tok, diag::err_destructor_tilde_identifier);
2786       return true;
2787     }
2788 
2789     // If the user wrote ~T::T, correct it to T::~T.
2790     DeclaratorScopeObj DeclScopeObj(*this, SS);
2791     if (NextToken().is(tok::coloncolon)) {
2792       // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2793       // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2794       // it will confuse this recovery logic.
2795       ColonProtectionRAIIObject ColonRAII(*this, false);
2796 
2797       if (SS.isSet()) {
2798         AnnotateScopeToken(SS, /*NewAnnotation*/true);
2799         SS.clear();
2800       }
2801       if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors,
2802                                          EnteringContext))
2803         return true;
2804       if (SS.isNotEmpty())
2805         ObjectType = nullptr;
2806       if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2807           !SS.isSet()) {
2808         Diag(TildeLoc, diag::err_destructor_tilde_scope);
2809         return true;
2810       }
2811 
2812       // Recover as if the tilde had been written before the identifier.
2813       Diag(TildeLoc, diag::err_destructor_tilde_scope)
2814         << FixItHint::CreateRemoval(TildeLoc)
2815         << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2816 
2817       // Temporarily enter the scope for the rest of this function.
2818       if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2819         DeclScopeObj.EnterDeclaratorScope();
2820     }
2821 
2822     // Parse the class-name (or template-name in a simple-template-id).
2823     IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2824     SourceLocation ClassNameLoc = ConsumeToken();
2825 
2826     if (Tok.is(tok::less)) {
2827       Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2828       return ParseUnqualifiedIdTemplateId(
2829           SS, ObjectType, ObjectHadErrors,
2830           TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2831           ClassNameLoc, EnteringContext, Result, TemplateSpecified);
2832     }
2833 
2834     // Note that this is a destructor name.
2835     ParsedType Ty =
2836         Actions.getDestructorName(*ClassName, ClassNameLoc, getCurScope(), SS,
2837                                   ObjectType, EnteringContext);
2838     if (!Ty)
2839       return true;
2840 
2841     Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2842     return false;
2843   }
2844 
2845   switch (Tok.getKind()) {
2846 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
2847 #include "clang/Basic/TransformTypeTraits.def"
2848     if (!NextToken().is(tok::l_paren)) {
2849       Tok.setKind(tok::identifier);
2850       Diag(Tok, diag::ext_keyword_as_ident)
2851           << Tok.getIdentifierInfo()->getName() << 0;
2852       goto ParseIdentifier;
2853     }
2854     [[fallthrough]];
2855   default:
2856     Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
2857     return true;
2858   }
2859 }
2860 
2861 ExprResult
ParseCXXNewExpression(bool UseGlobal,SourceLocation Start)2862 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2863   assert(Tok.is(tok::kw_new) && "expected 'new' token");
2864   ConsumeToken();   // Consume 'new'
2865 
2866   // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2867   // second form of new-expression. It can't be a new-type-id.
2868 
2869   ExprVector PlacementArgs;
2870   SourceLocation PlacementLParen, PlacementRParen;
2871 
2872   SourceRange TypeIdParens;
2873   DeclSpec DS(AttrFactory);
2874   Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
2875                             DeclaratorContext::CXXNew);
2876   if (Tok.is(tok::l_paren)) {
2877     // If it turns out to be a placement, we change the type location.
2878     BalancedDelimiterTracker T(*this, tok::l_paren);
2879     T.consumeOpen();
2880     PlacementLParen = T.getOpenLocation();
2881     if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2882       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2883       return ExprError();
2884     }
2885 
2886     T.consumeClose();
2887     PlacementRParen = T.getCloseLocation();
2888     if (PlacementRParen.isInvalid()) {
2889       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2890       return ExprError();
2891     }
2892 
2893     if (PlacementArgs.empty()) {
2894       // Reset the placement locations. There was no placement.
2895       TypeIdParens = T.getRange();
2896       PlacementLParen = PlacementRParen = SourceLocation();
2897     } else {
2898       // We still need the type.
2899       if (Tok.is(tok::l_paren)) {
2900         BalancedDelimiterTracker T(*this, tok::l_paren);
2901         T.consumeOpen();
2902         MaybeParseGNUAttributes(DeclaratorInfo);
2903         ParseSpecifierQualifierList(DS);
2904         DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2905         ParseDeclarator(DeclaratorInfo);
2906         T.consumeClose();
2907         TypeIdParens = T.getRange();
2908       } else {
2909         MaybeParseGNUAttributes(DeclaratorInfo);
2910         if (ParseCXXTypeSpecifierSeq(DS))
2911           DeclaratorInfo.setInvalidType(true);
2912         else {
2913           DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2914           ParseDeclaratorInternal(DeclaratorInfo,
2915                                   &Parser::ParseDirectNewDeclarator);
2916         }
2917       }
2918     }
2919   } else {
2920     // A new-type-id is a simplified type-id, where essentially the
2921     // direct-declarator is replaced by a direct-new-declarator.
2922     MaybeParseGNUAttributes(DeclaratorInfo);
2923     if (ParseCXXTypeSpecifierSeq(DS, DeclaratorContext::CXXNew))
2924       DeclaratorInfo.setInvalidType(true);
2925     else {
2926       DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2927       ParseDeclaratorInternal(DeclaratorInfo,
2928                               &Parser::ParseDirectNewDeclarator);
2929     }
2930   }
2931   if (DeclaratorInfo.isInvalidType()) {
2932     SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2933     return ExprError();
2934   }
2935 
2936   ExprResult Initializer;
2937 
2938   if (Tok.is(tok::l_paren)) {
2939     SourceLocation ConstructorLParen, ConstructorRParen;
2940     ExprVector ConstructorArgs;
2941     BalancedDelimiterTracker T(*this, tok::l_paren);
2942     T.consumeOpen();
2943     ConstructorLParen = T.getOpenLocation();
2944     if (Tok.isNot(tok::r_paren)) {
2945       auto RunSignatureHelp = [&]() {
2946         ParsedType TypeRep = Actions.ActOnTypeName(DeclaratorInfo).get();
2947         QualType PreferredType;
2948         // ActOnTypeName might adjust DeclaratorInfo and return a null type even
2949         // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
2950         // `new decltype(invalid) (^)`.
2951         if (TypeRep)
2952           PreferredType =
2953               Actions.CodeCompletion().ProduceConstructorSignatureHelp(
2954                   TypeRep.get()->getCanonicalTypeInternal(),
2955                   DeclaratorInfo.getEndLoc(), ConstructorArgs,
2956                   ConstructorLParen,
2957                   /*Braced=*/false);
2958         CalledSignatureHelp = true;
2959         return PreferredType;
2960       };
2961       if (ParseExpressionList(ConstructorArgs, [&] {
2962             PreferredType.enterFunctionArgument(Tok.getLocation(),
2963                                                 RunSignatureHelp);
2964           })) {
2965         if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
2966           RunSignatureHelp();
2967         SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2968         return ExprError();
2969       }
2970     }
2971     T.consumeClose();
2972     ConstructorRParen = T.getCloseLocation();
2973     if (ConstructorRParen.isInvalid()) {
2974       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2975       return ExprError();
2976     }
2977     Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2978                                              ConstructorRParen,
2979                                              ConstructorArgs);
2980   } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2981     Diag(Tok.getLocation(),
2982          diag::warn_cxx98_compat_generalized_initializer_lists);
2983     Initializer = ParseBraceInitializer();
2984   }
2985   if (Initializer.isInvalid())
2986     return Initializer;
2987 
2988   return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2989                              PlacementArgs, PlacementRParen,
2990                              TypeIdParens, DeclaratorInfo, Initializer.get());
2991 }
2992 
ParseDirectNewDeclarator(Declarator & D)2993 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2994   // Parse the array dimensions.
2995   bool First = true;
2996   while (Tok.is(tok::l_square)) {
2997     // An array-size expression can't start with a lambda.
2998     if (CheckProhibitedCXX11Attribute())
2999       continue;
3000 
3001     BalancedDelimiterTracker T(*this, tok::l_square);
3002     T.consumeOpen();
3003 
3004     ExprResult Size =
3005         First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
3006               : ParseConstantExpression();
3007     if (Size.isInvalid()) {
3008       // Recover
3009       SkipUntil(tok::r_square, StopAtSemi);
3010       return;
3011     }
3012     First = false;
3013 
3014     T.consumeClose();
3015 
3016     // Attributes here appertain to the array type. C++11 [expr.new]p5.
3017     ParsedAttributes Attrs(AttrFactory);
3018     MaybeParseCXX11Attributes(Attrs);
3019 
3020     D.AddTypeInfo(DeclaratorChunk::getArray(0,
3021                                             /*isStatic=*/false, /*isStar=*/false,
3022                                             Size.get(), T.getOpenLocation(),
3023                                             T.getCloseLocation()),
3024                   std::move(Attrs), T.getCloseLocation());
3025 
3026     if (T.getCloseLocation().isInvalid())
3027       return;
3028   }
3029 }
3030 
ParseExpressionListOrTypeId(SmallVectorImpl<Expr * > & PlacementArgs,Declarator & D)3031 bool Parser::ParseExpressionListOrTypeId(
3032                                    SmallVectorImpl<Expr*> &PlacementArgs,
3033                                          Declarator &D) {
3034   // The '(' was already consumed.
3035   if (isTypeIdInParens()) {
3036     ParseSpecifierQualifierList(D.getMutableDeclSpec());
3037     D.SetSourceRange(D.getDeclSpec().getSourceRange());
3038     ParseDeclarator(D);
3039     return D.isInvalidType();
3040   }
3041 
3042   // It's not a type, it has to be an expression list.
3043   return ParseExpressionList(PlacementArgs);
3044 }
3045 
3046 ExprResult
ParseCXXDeleteExpression(bool UseGlobal,SourceLocation Start)3047 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3048   assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
3049   ConsumeToken(); // Consume 'delete'
3050 
3051   // Array delete?
3052   bool ArrayDelete = false;
3053   if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
3054     // C++11 [expr.delete]p1:
3055     //   Whenever the delete keyword is followed by empty square brackets, it
3056     //   shall be interpreted as [array delete].
3057     //   [Footnote: A lambda expression with a lambda-introducer that consists
3058     //              of empty square brackets can follow the delete keyword if
3059     //              the lambda expression is enclosed in parentheses.]
3060 
3061     const Token Next = GetLookAheadToken(2);
3062 
3063     // Basic lookahead to check if we have a lambda expression.
3064     if (Next.isOneOf(tok::l_brace, tok::less) ||
3065         (Next.is(tok::l_paren) &&
3066          (GetLookAheadToken(3).is(tok::r_paren) ||
3067           (GetLookAheadToken(3).is(tok::identifier) &&
3068            GetLookAheadToken(4).is(tok::identifier))))) {
3069       TentativeParsingAction TPA(*this);
3070       SourceLocation LSquareLoc = Tok.getLocation();
3071       SourceLocation RSquareLoc = NextToken().getLocation();
3072 
3073       // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3074       // case.
3075       SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3076       SourceLocation RBraceLoc;
3077       bool EmitFixIt = false;
3078       if (Tok.is(tok::l_brace)) {
3079         ConsumeBrace();
3080         SkipUntil(tok::r_brace, StopBeforeMatch);
3081         RBraceLoc = Tok.getLocation();
3082         EmitFixIt = true;
3083       }
3084 
3085       TPA.Revert();
3086 
3087       if (EmitFixIt)
3088         Diag(Start, diag::err_lambda_after_delete)
3089             << SourceRange(Start, RSquareLoc)
3090             << FixItHint::CreateInsertion(LSquareLoc, "(")
3091             << FixItHint::CreateInsertion(
3092                    Lexer::getLocForEndOfToken(
3093                        RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3094                    ")");
3095       else
3096         Diag(Start, diag::err_lambda_after_delete)
3097             << SourceRange(Start, RSquareLoc);
3098 
3099       // Warn that the non-capturing lambda isn't surrounded by parentheses
3100       // to disambiguate it from 'delete[]'.
3101       ExprResult Lambda = ParseLambdaExpression();
3102       if (Lambda.isInvalid())
3103         return ExprError();
3104 
3105       // Evaluate any postfix expressions used on the lambda.
3106       Lambda = ParsePostfixExpressionSuffix(Lambda);
3107       if (Lambda.isInvalid())
3108         return ExprError();
3109       return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3110                                     Lambda.get());
3111     }
3112 
3113     ArrayDelete = true;
3114     BalancedDelimiterTracker T(*this, tok::l_square);
3115 
3116     T.consumeOpen();
3117     T.consumeClose();
3118     if (T.getCloseLocation().isInvalid())
3119       return ExprError();
3120   }
3121 
3122   ExprResult Operand(ParseCastExpression(CastParseKind::AnyCastExpr));
3123   if (Operand.isInvalid())
3124     return Operand;
3125 
3126   return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
3127 }
3128 
ParseRequiresExpression()3129 ExprResult Parser::ParseRequiresExpression() {
3130   assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword");
3131   SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires'
3132 
3133   llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls;
3134   BalancedDelimiterTracker Parens(*this, tok::l_paren);
3135   if (Tok.is(tok::l_paren)) {
3136     // requirement parameter list is present.
3137     ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope |
3138                                     Scope::DeclScope);
3139     Parens.consumeOpen();
3140     if (!Tok.is(tok::r_paren)) {
3141       ParsedAttributes FirstArgAttrs(getAttrFactory());
3142       SourceLocation EllipsisLoc;
3143       llvm::SmallVector<DeclaratorChunk::ParamInfo, 2> LocalParameters;
3144       ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr,
3145                                       FirstArgAttrs, LocalParameters,
3146                                       EllipsisLoc);
3147       if (EllipsisLoc.isValid())
3148         Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis);
3149       for (auto &ParamInfo : LocalParameters)
3150         LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param));
3151     }
3152     Parens.consumeClose();
3153   }
3154 
3155   BalancedDelimiterTracker Braces(*this, tok::l_brace);
3156   if (Braces.expectAndConsume())
3157     return ExprError();
3158 
3159   // Start of requirement list
3160   llvm::SmallVector<concepts::Requirement *, 2> Requirements;
3161 
3162   // C++2a [expr.prim.req]p2
3163   //   Expressions appearing within a requirement-body are unevaluated operands.
3164   EnterExpressionEvaluationContext Ctx(
3165       Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3166 
3167   ParseScope BodyScope(this, Scope::DeclScope);
3168   // Create a separate diagnostic pool for RequiresExprBodyDecl.
3169   // Dependent diagnostics are attached to this Decl and non-depenedent
3170   // diagnostics are surfaced after this parse.
3171   ParsingDeclRAIIObject ParsingBodyDecl(*this, ParsingDeclRAIIObject::NoParent);
3172   RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr(
3173       RequiresKWLoc, LocalParameterDecls, getCurScope());
3174 
3175   if (Tok.is(tok::r_brace)) {
3176     // Grammar does not allow an empty body.
3177     // requirement-body:
3178     //   { requirement-seq }
3179     // requirement-seq:
3180     //   requirement
3181     //   requirement-seq requirement
3182     Diag(Tok, diag::err_empty_requires_expr);
3183     // Continue anyway and produce a requires expr with no requirements.
3184   } else {
3185     while (!Tok.is(tok::r_brace)) {
3186       switch (Tok.getKind()) {
3187       case tok::l_brace: {
3188         // Compound requirement
3189         // C++ [expr.prim.req.compound]
3190         //     compound-requirement:
3191         //         '{' expression '}' 'noexcept'[opt]
3192         //             return-type-requirement[opt] ';'
3193         //     return-type-requirement:
3194         //         trailing-return-type
3195         //         '->' cv-qualifier-seq[opt] constrained-parameter
3196         //             cv-qualifier-seq[opt] abstract-declarator[opt]
3197         BalancedDelimiterTracker ExprBraces(*this, tok::l_brace);
3198         ExprBraces.consumeOpen();
3199         ExprResult Expression = ParseExpression();
3200         if (!Expression.isUsable()) {
3201           ExprBraces.skipToEnd();
3202           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3203           break;
3204         }
3205         // If there's an error consuming the closing bracket, consumeClose()
3206         // will handle skipping to the nearest recovery point for us.
3207         if (ExprBraces.consumeClose())
3208           break;
3209 
3210         concepts::Requirement *Req = nullptr;
3211         SourceLocation NoexceptLoc;
3212         TryConsumeToken(tok::kw_noexcept, NoexceptLoc);
3213         if (Tok.is(tok::semi)) {
3214           Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc);
3215           if (Req)
3216             Requirements.push_back(Req);
3217           break;
3218         }
3219         if (!TryConsumeToken(tok::arrow))
3220           // User probably forgot the arrow, remind them and try to continue.
3221           Diag(Tok, diag::err_requires_expr_missing_arrow)
3222               << FixItHint::CreateInsertion(Tok.getLocation(), "->");
3223         // Try to parse a 'type-constraint'
3224         if (TryAnnotateTypeConstraint()) {
3225           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3226           break;
3227         }
3228         if (!isTypeConstraintAnnotation()) {
3229           Diag(Tok, diag::err_requires_expr_expected_type_constraint);
3230           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3231           break;
3232         }
3233         CXXScopeSpec SS;
3234         if (Tok.is(tok::annot_cxxscope)) {
3235           Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3236                                                        Tok.getAnnotationRange(),
3237                                                        SS);
3238           ConsumeAnnotationToken();
3239         }
3240 
3241         Req = Actions.ActOnCompoundRequirement(
3242             Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok),
3243             TemplateParameterDepth);
3244         ConsumeAnnotationToken();
3245         if (Req)
3246           Requirements.push_back(Req);
3247         break;
3248       }
3249       default: {
3250         bool PossibleRequiresExprInSimpleRequirement = false;
3251         if (Tok.is(tok::kw_requires)) {
3252           auto IsNestedRequirement = [&] {
3253             RevertingTentativeParsingAction TPA(*this);
3254             ConsumeToken(); // 'requires'
3255             if (Tok.is(tok::l_brace))
3256               // This is a requires expression
3257               // requires (T t) {
3258               //   requires { t++; };
3259               //   ...      ^
3260               // }
3261               return false;
3262             if (Tok.is(tok::l_paren)) {
3263               // This might be the parameter list of a requires expression
3264               ConsumeParen();
3265               auto Res = TryParseParameterDeclarationClause();
3266               if (Res != TPResult::False) {
3267                 // Skip to the closing parenthesis
3268                 unsigned Depth = 1;
3269                 while (Depth != 0) {
3270                   bool FoundParen = SkipUntil(tok::l_paren, tok::r_paren,
3271                                               SkipUntilFlags::StopBeforeMatch);
3272                   if (!FoundParen)
3273                     break;
3274                   if (Tok.is(tok::l_paren))
3275                     Depth++;
3276                   else if (Tok.is(tok::r_paren))
3277                     Depth--;
3278                   ConsumeAnyToken();
3279                 }
3280                 // requires (T t) {
3281                 //   requires () ?
3282                 //   ...         ^
3283                 //   - OR -
3284                 //   requires (int x) ?
3285                 //   ...              ^
3286                 // }
3287                 if (Tok.is(tok::l_brace))
3288                   // requires (...) {
3289                   //                ^ - a requires expression as a
3290                   //                    simple-requirement.
3291                   return false;
3292               }
3293             }
3294             return true;
3295           };
3296           if (IsNestedRequirement()) {
3297             ConsumeToken();
3298             // Nested requirement
3299             // C++ [expr.prim.req.nested]
3300             //     nested-requirement:
3301             //         'requires' constraint-expression ';'
3302             ExprResult ConstraintExpr = ParseConstraintExpression();
3303             if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) {
3304               SkipUntil(tok::semi, tok::r_brace,
3305                         SkipUntilFlags::StopBeforeMatch);
3306               break;
3307             }
3308             if (auto *Req =
3309                     Actions.ActOnNestedRequirement(ConstraintExpr.get()))
3310               Requirements.push_back(Req);
3311             else {
3312               SkipUntil(tok::semi, tok::r_brace,
3313                         SkipUntilFlags::StopBeforeMatch);
3314               break;
3315             }
3316             break;
3317           } else
3318             PossibleRequiresExprInSimpleRequirement = true;
3319         } else if (Tok.is(tok::kw_typename)) {
3320           // This might be 'typename T::value_type;' (a type requirement) or
3321           // 'typename T::value_type{};' (a simple requirement).
3322           TentativeParsingAction TPA(*this);
3323 
3324           // We need to consume the typename to allow 'requires { typename a; }'
3325           SourceLocation TypenameKWLoc = ConsumeToken();
3326           if (TryAnnotateOptionalCXXScopeToken()) {
3327             TPA.Commit();
3328             SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3329             break;
3330           }
3331           CXXScopeSpec SS;
3332           if (Tok.is(tok::annot_cxxscope)) {
3333             Actions.RestoreNestedNameSpecifierAnnotation(
3334                 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3335             ConsumeAnnotationToken();
3336           }
3337 
3338           if (Tok.isOneOf(tok::identifier, tok::annot_template_id) &&
3339               !NextToken().isOneOf(tok::l_brace, tok::l_paren)) {
3340             TPA.Commit();
3341             SourceLocation NameLoc = Tok.getLocation();
3342             IdentifierInfo *II = nullptr;
3343             TemplateIdAnnotation *TemplateId = nullptr;
3344             if (Tok.is(tok::identifier)) {
3345               II = Tok.getIdentifierInfo();
3346               ConsumeToken();
3347             } else {
3348               TemplateId = takeTemplateIdAnnotation(Tok);
3349               ConsumeAnnotationToken();
3350               if (TemplateId->isInvalid())
3351                 break;
3352             }
3353 
3354             if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS,
3355                                                          NameLoc, II,
3356                                                          TemplateId)) {
3357               Requirements.push_back(Req);
3358             }
3359             break;
3360           }
3361           TPA.Revert();
3362         }
3363         // Simple requirement
3364         // C++ [expr.prim.req.simple]
3365         //     simple-requirement:
3366         //         expression ';'
3367         SourceLocation StartLoc = Tok.getLocation();
3368         ExprResult Expression = ParseExpression();
3369         if (!Expression.isUsable()) {
3370           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3371           break;
3372         }
3373         if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement)
3374           Diag(StartLoc, diag::err_requires_expr_in_simple_requirement)
3375               << FixItHint::CreateInsertion(StartLoc, "requires");
3376         if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get()))
3377           Requirements.push_back(Req);
3378         else {
3379           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3380           break;
3381         }
3382         // User may have tried to put some compound requirement stuff here
3383         if (Tok.is(tok::kw_noexcept)) {
3384           Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept)
3385               << FixItHint::CreateInsertion(StartLoc, "{")
3386               << FixItHint::CreateInsertion(Tok.getLocation(), "}");
3387           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3388           break;
3389         }
3390         break;
3391       }
3392       }
3393       if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) {
3394         SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3395         TryConsumeToken(tok::semi);
3396         break;
3397       }
3398     }
3399     if (Requirements.empty()) {
3400       // Don't emit an empty requires expr here to avoid confusing the user with
3401       // other diagnostics quoting an empty requires expression they never
3402       // wrote.
3403       Braces.consumeClose();
3404       Actions.ActOnFinishRequiresExpr();
3405       return ExprError();
3406     }
3407   }
3408   Braces.consumeClose();
3409   Actions.ActOnFinishRequiresExpr();
3410   ParsingBodyDecl.complete(Body);
3411   return Actions.ActOnRequiresExpr(
3412       RequiresKWLoc, Body, Parens.getOpenLocation(), LocalParameterDecls,
3413       Parens.getCloseLocation(), Requirements, Braces.getCloseLocation());
3414 }
3415 
TypeTraitFromTokKind(tok::TokenKind kind)3416 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3417   switch (kind) {
3418   default: llvm_unreachable("Not a known type trait");
3419 #define TYPE_TRAIT_1(Spelling, Name, Key) \
3420 case tok::kw_ ## Spelling: return UTT_ ## Name;
3421 #define TYPE_TRAIT_2(Spelling, Name, Key) \
3422 case tok::kw_ ## Spelling: return BTT_ ## Name;
3423 #include "clang/Basic/TokenKinds.def"
3424 #define TYPE_TRAIT_N(Spelling, Name, Key) \
3425   case tok::kw_ ## Spelling: return TT_ ## Name;
3426 #include "clang/Basic/TokenKinds.def"
3427   }
3428 }
3429 
ArrayTypeTraitFromTokKind(tok::TokenKind kind)3430 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3431   switch (kind) {
3432   default:
3433     llvm_unreachable("Not a known array type trait");
3434 #define ARRAY_TYPE_TRAIT(Spelling, Name, Key)                                  \
3435   case tok::kw_##Spelling:                                                     \
3436     return ATT_##Name;
3437 #include "clang/Basic/TokenKinds.def"
3438   }
3439 }
3440 
ExpressionTraitFromTokKind(tok::TokenKind kind)3441 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3442   switch (kind) {
3443   default:
3444     llvm_unreachable("Not a known unary expression trait.");
3445 #define EXPRESSION_TRAIT(Spelling, Name, Key)                                  \
3446   case tok::kw_##Spelling:                                                     \
3447     return ET_##Name;
3448 #include "clang/Basic/TokenKinds.def"
3449   }
3450 }
3451 
ParseTypeTrait()3452 ExprResult Parser::ParseTypeTrait() {
3453   tok::TokenKind Kind = Tok.getKind();
3454 
3455   SourceLocation Loc = ConsumeToken();
3456 
3457   BalancedDelimiterTracker Parens(*this, tok::l_paren);
3458   if (Parens.expectAndConsume())
3459     return ExprError();
3460 
3461   SmallVector<ParsedType, 2> Args;
3462   do {
3463     // Parse the next type.
3464     TypeResult Ty = ParseTypeName(/*SourceRange=*/nullptr,
3465                                   getLangOpts().CPlusPlus
3466                                       ? DeclaratorContext::TemplateTypeArg
3467                                       : DeclaratorContext::TypeName);
3468     if (Ty.isInvalid()) {
3469       Parens.skipToEnd();
3470       return ExprError();
3471     }
3472 
3473     // Parse the ellipsis, if present.
3474     if (Tok.is(tok::ellipsis)) {
3475       Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3476       if (Ty.isInvalid()) {
3477         Parens.skipToEnd();
3478         return ExprError();
3479       }
3480     }
3481 
3482     // Add this type to the list of arguments.
3483     Args.push_back(Ty.get());
3484   } while (TryConsumeToken(tok::comma));
3485 
3486   if (Parens.consumeClose())
3487     return ExprError();
3488 
3489   SourceLocation EndLoc = Parens.getCloseLocation();
3490 
3491   return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3492 }
3493 
ParseArrayTypeTrait()3494 ExprResult Parser::ParseArrayTypeTrait() {
3495   ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3496   SourceLocation Loc = ConsumeToken();
3497 
3498   BalancedDelimiterTracker T(*this, tok::l_paren);
3499   if (T.expectAndConsume())
3500     return ExprError();
3501 
3502   TypeResult Ty = ParseTypeName(/*SourceRange=*/nullptr,
3503                                 DeclaratorContext::TemplateTypeArg);
3504   if (Ty.isInvalid()) {
3505     SkipUntil(tok::comma, StopAtSemi);
3506     SkipUntil(tok::r_paren, StopAtSemi);
3507     return ExprError();
3508   }
3509 
3510   switch (ATT) {
3511   case ATT_ArrayRank: {
3512     T.consumeClose();
3513     return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3514                                        T.getCloseLocation());
3515   }
3516   case ATT_ArrayExtent: {
3517     if (ExpectAndConsume(tok::comma)) {
3518       SkipUntil(tok::r_paren, StopAtSemi);
3519       return ExprError();
3520     }
3521 
3522     ExprResult DimExpr = ParseExpression();
3523     T.consumeClose();
3524 
3525     if (DimExpr.isInvalid())
3526       return ExprError();
3527 
3528     return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3529                                        T.getCloseLocation());
3530   }
3531   }
3532   llvm_unreachable("Invalid ArrayTypeTrait!");
3533 }
3534 
ParseExpressionTrait()3535 ExprResult Parser::ParseExpressionTrait() {
3536   ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3537   SourceLocation Loc = ConsumeToken();
3538 
3539   BalancedDelimiterTracker T(*this, tok::l_paren);
3540   if (T.expectAndConsume())
3541     return ExprError();
3542 
3543   ExprResult Expr = ParseExpression();
3544 
3545   T.consumeClose();
3546 
3547   return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3548                                       T.getCloseLocation());
3549 }
3550 
3551 ExprResult
ParseCXXAmbiguousParenExpression(ParenParseOption & ExprType,ParsedType & CastTy,BalancedDelimiterTracker & Tracker,ColonProtectionRAIIObject & ColonProt)3552 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3553                                          ParsedType &CastTy,
3554                                          BalancedDelimiterTracker &Tracker,
3555                                          ColonProtectionRAIIObject &ColonProt) {
3556   assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3557   assert(ExprType == ParenParseOption::CastExpr &&
3558          "Compound literals are not ambiguous!");
3559   assert(isTypeIdInParens() && "Not a type-id!");
3560 
3561   ExprResult Result(true);
3562   CastTy = nullptr;
3563 
3564   // We need to disambiguate a very ugly part of the C++ syntax:
3565   //
3566   // (T())x;  - type-id
3567   // (T())*x; - type-id
3568   // (T())/x; - expression
3569   // (T());   - expression
3570   //
3571   // The bad news is that we cannot use the specialized tentative parser, since
3572   // it can only verify that the thing inside the parens can be parsed as
3573   // type-id, it is not useful for determining the context past the parens.
3574   //
3575   // The good news is that the parser can disambiguate this part without
3576   // making any unnecessary Action calls.
3577   //
3578   // It uses a scheme similar to parsing inline methods. The parenthesized
3579   // tokens are cached, the context that follows is determined (possibly by
3580   // parsing a cast-expression), and then we re-introduce the cached tokens
3581   // into the token stream and parse them appropriately.
3582 
3583   ParenParseOption ParseAs;
3584   CachedTokens Toks;
3585 
3586   // Store the tokens of the parentheses. We will parse them after we determine
3587   // the context that follows them.
3588   if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3589     // We didn't find the ')' we expected.
3590     Tracker.consumeClose();
3591     return ExprError();
3592   }
3593 
3594   if (Tok.is(tok::l_brace)) {
3595     ParseAs = ParenParseOption::CompoundLiteral;
3596   } else {
3597     bool NotCastExpr;
3598     if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3599       NotCastExpr = true;
3600     } else {
3601       // Try parsing the cast-expression that may follow.
3602       // If it is not a cast-expression, NotCastExpr will be true and no token
3603       // will be consumed.
3604       ColonProt.restore();
3605       Result = ParseCastExpression(CastParseKind::AnyCastExpr,
3606                                    false /*isAddressofOperand*/, NotCastExpr,
3607                                    // type-id has priority.
3608                                    TypoCorrectionTypeBehavior::AllowTypes);
3609     }
3610 
3611     // If we parsed a cast-expression, it's really a type-id, otherwise it's
3612     // an expression.
3613     ParseAs =
3614         NotCastExpr ? ParenParseOption::SimpleExpr : ParenParseOption::CastExpr;
3615   }
3616 
3617   // Create a fake EOF to mark end of Toks buffer.
3618   Token AttrEnd;
3619   AttrEnd.startToken();
3620   AttrEnd.setKind(tok::eof);
3621   AttrEnd.setLocation(Tok.getLocation());
3622   AttrEnd.setEofData(Toks.data());
3623   Toks.push_back(AttrEnd);
3624 
3625   // The current token should go after the cached tokens.
3626   Toks.push_back(Tok);
3627   // Re-enter the stored parenthesized tokens into the token stream, so we may
3628   // parse them now.
3629   PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
3630                       /*IsReinject*/ true);
3631   // Drop the current token and bring the first cached one. It's the same token
3632   // as when we entered this function.
3633   ConsumeAnyToken();
3634 
3635   if (ParseAs >= ParenParseOption::CompoundLiteral) {
3636     // Parse the type declarator.
3637     DeclSpec DS(AttrFactory);
3638     Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3639                               DeclaratorContext::TypeName);
3640     {
3641       ColonProtectionRAIIObject InnerColonProtection(*this);
3642       ParseSpecifierQualifierList(DS);
3643       ParseDeclarator(DeclaratorInfo);
3644     }
3645 
3646     // Match the ')'.
3647     Tracker.consumeClose();
3648     ColonProt.restore();
3649 
3650     // Consume EOF marker for Toks buffer.
3651     assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3652     ConsumeAnyToken();
3653 
3654     if (ParseAs == ParenParseOption::CompoundLiteral) {
3655       ExprType = ParenParseOption::CompoundLiteral;
3656       if (DeclaratorInfo.isInvalidType())
3657         return ExprError();
3658 
3659       TypeResult Ty = Actions.ActOnTypeName(DeclaratorInfo);
3660       return ParseCompoundLiteralExpression(Ty.get(),
3661                                             Tracker.getOpenLocation(),
3662                                             Tracker.getCloseLocation());
3663     }
3664 
3665     // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3666     assert(ParseAs == ParenParseOption::CastExpr);
3667 
3668     if (DeclaratorInfo.isInvalidType())
3669       return ExprError();
3670 
3671     // Result is what ParseCastExpression returned earlier.
3672     if (!Result.isInvalid())
3673       Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3674                                     DeclaratorInfo, CastTy,
3675                                     Tracker.getCloseLocation(), Result.get());
3676     return Result;
3677   }
3678 
3679   // Not a compound literal, and not followed by a cast-expression.
3680   assert(ParseAs == ParenParseOption::SimpleExpr);
3681 
3682   ExprType = ParenParseOption::SimpleExpr;
3683   Result = ParseExpression();
3684   if (!Result.isInvalid() && Tok.is(tok::r_paren))
3685     Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3686                                     Tok.getLocation(), Result.get());
3687 
3688   // Match the ')'.
3689   if (Result.isInvalid()) {
3690     while (Tok.isNot(tok::eof))
3691       ConsumeAnyToken();
3692     assert(Tok.getEofData() == AttrEnd.getEofData());
3693     ConsumeAnyToken();
3694     return ExprError();
3695   }
3696 
3697   Tracker.consumeClose();
3698   // Consume EOF marker for Toks buffer.
3699   assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3700   ConsumeAnyToken();
3701   return Result;
3702 }
3703 
ParseBuiltinBitCast()3704 ExprResult Parser::ParseBuiltinBitCast() {
3705   SourceLocation KWLoc = ConsumeToken();
3706 
3707   BalancedDelimiterTracker T(*this, tok::l_paren);
3708   if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
3709     return ExprError();
3710 
3711   // Parse the common declaration-specifiers piece.
3712   DeclSpec DS(AttrFactory);
3713   ParseSpecifierQualifierList(DS);
3714 
3715   // Parse the abstract-declarator, if present.
3716   Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3717                             DeclaratorContext::TypeName);
3718   ParseDeclarator(DeclaratorInfo);
3719 
3720   if (ExpectAndConsume(tok::comma)) {
3721     Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
3722     SkipUntil(tok::r_paren, StopAtSemi);
3723     return ExprError();
3724   }
3725 
3726   ExprResult Operand = ParseExpression();
3727 
3728   if (T.consumeClose())
3729     return ExprError();
3730 
3731   if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
3732     return ExprError();
3733 
3734   return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
3735                                          T.getCloseLocation());
3736 }
3737