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