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