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