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