1//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "RAIIObjectsForParser.h"
16#include "clang/Basic/PrettyStackTrace.h"
17#include "clang/Lex/LiteralSupport.h"
18#include "clang/Parse/ParseDiagnostic.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
24using namespace clang;
25
26static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
27  switch (Kind) {
28    case tok::kw_template:         return 0;
29    case tok::kw_const_cast:       return 1;
30    case tok::kw_dynamic_cast:     return 2;
31    case tok::kw_reinterpret_cast: return 3;
32    case tok::kw_static_cast:      return 4;
33    default:
34      llvm_unreachable("Unknown type for digraph error message.");
35  }
36}
37
38// Are the two tokens adjacent in the same source file?
39bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
40  SourceManager &SM = PP.getSourceManager();
41  SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
42  SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
43  return FirstEnd == SM.getSpellingLoc(Second.getLocation());
44}
45
46// Suggest fixit for "<::" after a cast.
47static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
48                       Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
49  // Pull '<:' and ':' off token stream.
50  if (!AtDigraph)
51    PP.Lex(DigraphToken);
52  PP.Lex(ColonToken);
53
54  SourceRange Range;
55  Range.setBegin(DigraphToken.getLocation());
56  Range.setEnd(ColonToken.getLocation());
57  P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
58      << SelectDigraphErrorMessage(Kind)
59      << FixItHint::CreateReplacement(Range, "< ::");
60
61  // Update token information to reflect their change in token type.
62  ColonToken.setKind(tok::coloncolon);
63  ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
64  ColonToken.setLength(2);
65  DigraphToken.setKind(tok::less);
66  DigraphToken.setLength(1);
67
68  // Push new tokens back to token stream.
69  PP.EnterToken(ColonToken);
70  if (!AtDigraph)
71    PP.EnterToken(DigraphToken);
72}
73
74// Check for '<::' which should be '< ::' instead of '[:' when following
75// a template name.
76void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
77                                        bool EnteringContext,
78                                        IdentifierInfo &II, CXXScopeSpec &SS) {
79  if (!Next.is(tok::l_square) || Next.getLength() != 2)
80    return;
81
82  Token SecondToken = GetLookAheadToken(2);
83  if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
84    return;
85
86  TemplateTy Template;
87  UnqualifiedId TemplateName;
88  TemplateName.setIdentifier(&II, Tok.getLocation());
89  bool MemberOfUnknownSpecialization;
90  if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
91                              TemplateName, ObjectType, EnteringContext,
92                              Template, MemberOfUnknownSpecialization))
93    return;
94
95  FixDigraph(*this, PP, Next, SecondToken, tok::kw_template,
96             /*AtDigraph*/false);
97}
98
99/// \brief Emits an error for a left parentheses after a double colon.
100///
101/// When a '(' is found after a '::', emit an error.  Attempt to fix the token
102/// stream by removing the '(', and the matching ')' if found.
103void Parser::CheckForLParenAfterColonColon() {
104  if (!Tok.is(tok::l_paren))
105    return;
106
107  SourceLocation l_parenLoc = ConsumeParen(), r_parenLoc;
108  Token Tok1 = getCurToken();
109  if (!Tok1.is(tok::identifier) && !Tok1.is(tok::star))
110    return;
111
112  if (Tok1.is(tok::identifier)) {
113    Token Tok2 = GetLookAheadToken(1);
114    if (Tok2.is(tok::r_paren)) {
115      ConsumeToken();
116      PP.EnterToken(Tok1);
117      r_parenLoc = ConsumeParen();
118    }
119  } else if (Tok1.is(tok::star)) {
120    Token Tok2 = GetLookAheadToken(1);
121    if (Tok2.is(tok::identifier)) {
122      Token Tok3 = GetLookAheadToken(2);
123      if (Tok3.is(tok::r_paren)) {
124        ConsumeToken();
125        ConsumeToken();
126        PP.EnterToken(Tok2);
127        PP.EnterToken(Tok1);
128        r_parenLoc = ConsumeParen();
129      }
130    }
131  }
132
133  Diag(l_parenLoc, diag::err_paren_after_colon_colon)
134      << FixItHint::CreateRemoval(l_parenLoc)
135      << FixItHint::CreateRemoval(r_parenLoc);
136}
137
138/// \brief Parse global scope or nested-name-specifier if present.
139///
140/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
141/// may be preceded by '::'). Note that this routine will not parse ::new or
142/// ::delete; it will just leave them in the token stream.
143///
144///       '::'[opt] nested-name-specifier
145///       '::'
146///
147///       nested-name-specifier:
148///         type-name '::'
149///         namespace-name '::'
150///         nested-name-specifier identifier '::'
151///         nested-name-specifier 'template'[opt] simple-template-id '::'
152///
153///
154/// \param SS the scope specifier that will be set to the parsed
155/// nested-name-specifier (or empty)
156///
157/// \param ObjectType if this nested-name-specifier is being parsed following
158/// the "." or "->" of a member access expression, this parameter provides the
159/// type of the object whose members are being accessed.
160///
161/// \param EnteringContext whether we will be entering into the context of
162/// the nested-name-specifier after parsing it.
163///
164/// \param MayBePseudoDestructor When non-NULL, points to a flag that
165/// indicates whether this nested-name-specifier may be part of a
166/// pseudo-destructor name. In this case, the flag will be set false
167/// if we don't actually end up parsing a destructor name. Moreorover,
168/// if we do end up determining that we are parsing a destructor name,
169/// the last component of the nested-name-specifier is not parsed as
170/// part of the scope specifier.
171///
172/// \param IsTypename If \c true, this nested-name-specifier is known to be
173/// part of a type name. This is used to improve error recovery.
174///
175/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
176/// filled in with the leading identifier in the last component of the
177/// nested-name-specifier, if any.
178///
179/// \returns true if there was an error parsing a scope specifier
180bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
181                                            ParsedType ObjectType,
182                                            bool EnteringContext,
183                                            bool *MayBePseudoDestructor,
184                                            bool IsTypename,
185                                            IdentifierInfo **LastII) {
186  assert(getLangOpts().CPlusPlus &&
187         "Call sites of this function should be guarded by checking for C++");
188
189  if (Tok.is(tok::annot_cxxscope)) {
190    assert(!LastII && "want last identifier but have already annotated scope");
191    Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
192                                                 Tok.getAnnotationRange(),
193                                                 SS);
194    ConsumeToken();
195    return false;
196  }
197
198  if (Tok.is(tok::annot_template_id)) {
199    // If the current token is an annotated template id, it may already have
200    // a scope specifier. Restore it.
201    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
202    SS = TemplateId->SS;
203  }
204
205  if (LastII)
206    *LastII = 0;
207
208  bool HasScopeSpecifier = false;
209
210  if (Tok.is(tok::coloncolon)) {
211    // ::new and ::delete aren't nested-name-specifiers.
212    tok::TokenKind NextKind = NextToken().getKind();
213    if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
214      return false;
215
216    // '::' - Global scope qualifier.
217    if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
218      return true;
219
220    CheckForLParenAfterColonColon();
221
222    HasScopeSpecifier = true;
223  }
224
225  bool CheckForDestructor = false;
226  if (MayBePseudoDestructor && *MayBePseudoDestructor) {
227    CheckForDestructor = true;
228    *MayBePseudoDestructor = false;
229  }
230
231  if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
232    DeclSpec DS(AttrFactory);
233    SourceLocation DeclLoc = Tok.getLocation();
234    SourceLocation EndLoc  = ParseDecltypeSpecifier(DS);
235    if (Tok.isNot(tok::coloncolon)) {
236      AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
237      return false;
238    }
239
240    SourceLocation CCLoc = ConsumeToken();
241    if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
242      SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
243
244    HasScopeSpecifier = true;
245  }
246
247  while (true) {
248    if (HasScopeSpecifier) {
249      // C++ [basic.lookup.classref]p5:
250      //   If the qualified-id has the form
251      //
252      //       ::class-name-or-namespace-name::...
253      //
254      //   the class-name-or-namespace-name is looked up in global scope as a
255      //   class-name or namespace-name.
256      //
257      // To implement this, we clear out the object type as soon as we've
258      // seen a leading '::' or part of a nested-name-specifier.
259      ObjectType = ParsedType();
260
261      if (Tok.is(tok::code_completion)) {
262        // Code completion for a nested-name-specifier, where the code
263        // code completion token follows the '::'.
264        Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
265        // Include code completion token into the range of the scope otherwise
266        // when we try to annotate the scope tokens the dangling code completion
267        // token will cause assertion in
268        // Preprocessor::AnnotatePreviousCachedTokens.
269        SS.setEndLoc(Tok.getLocation());
270        cutOffParsing();
271        return true;
272      }
273    }
274
275    // nested-name-specifier:
276    //   nested-name-specifier 'template'[opt] simple-template-id '::'
277
278    // Parse the optional 'template' keyword, then make sure we have
279    // 'identifier <' after it.
280    if (Tok.is(tok::kw_template)) {
281      // If we don't have a scope specifier or an object type, this isn't a
282      // nested-name-specifier, since they aren't allowed to start with
283      // 'template'.
284      if (!HasScopeSpecifier && !ObjectType)
285        break;
286
287      TentativeParsingAction TPA(*this);
288      SourceLocation TemplateKWLoc = ConsumeToken();
289
290      UnqualifiedId TemplateName;
291      if (Tok.is(tok::identifier)) {
292        // Consume the identifier.
293        TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
294        ConsumeToken();
295      } else if (Tok.is(tok::kw_operator)) {
296        if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
297                                       TemplateName)) {
298          TPA.Commit();
299          break;
300        }
301
302        if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
303            TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
304          Diag(TemplateName.getSourceRange().getBegin(),
305               diag::err_id_after_template_in_nested_name_spec)
306            << TemplateName.getSourceRange();
307          TPA.Commit();
308          break;
309        }
310      } else {
311        TPA.Revert();
312        break;
313      }
314
315      // If the next token is not '<', we have a qualified-id that refers
316      // to a template name, such as T::template apply, but is not a
317      // template-id.
318      if (Tok.isNot(tok::less)) {
319        TPA.Revert();
320        break;
321      }
322
323      // Commit to parsing the template-id.
324      TPA.Commit();
325      TemplateTy Template;
326      if (TemplateNameKind TNK
327          = Actions.ActOnDependentTemplateName(getCurScope(),
328                                               SS, TemplateKWLoc, TemplateName,
329                                               ObjectType, EnteringContext,
330                                               Template)) {
331        if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
332                                    TemplateName, false))
333          return true;
334      } else
335        return true;
336
337      continue;
338    }
339
340    if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
341      // We have
342      //
343      //   simple-template-id '::'
344      //
345      // So we need to check whether the simple-template-id is of the
346      // right kind (it should name a type or be dependent), and then
347      // convert it into a type within the nested-name-specifier.
348      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
349      if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
350        *MayBePseudoDestructor = true;
351        return false;
352      }
353
354      if (LastII)
355        *LastII = TemplateId->Name;
356
357      // Consume the template-id token.
358      ConsumeToken();
359
360      assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
361      SourceLocation CCLoc = ConsumeToken();
362
363      HasScopeSpecifier = true;
364
365      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
366                                         TemplateId->NumArgs);
367
368      if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
369                                              SS,
370                                              TemplateId->TemplateKWLoc,
371                                              TemplateId->Template,
372                                              TemplateId->TemplateNameLoc,
373                                              TemplateId->LAngleLoc,
374                                              TemplateArgsPtr,
375                                              TemplateId->RAngleLoc,
376                                              CCLoc,
377                                              EnteringContext)) {
378        SourceLocation StartLoc
379          = SS.getBeginLoc().isValid()? SS.getBeginLoc()
380                                      : TemplateId->TemplateNameLoc;
381        SS.SetInvalid(SourceRange(StartLoc, CCLoc));
382      }
383
384      continue;
385    }
386
387
388    // The rest of the nested-name-specifier possibilities start with
389    // tok::identifier.
390    if (Tok.isNot(tok::identifier))
391      break;
392
393    IdentifierInfo &II = *Tok.getIdentifierInfo();
394
395    // nested-name-specifier:
396    //   type-name '::'
397    //   namespace-name '::'
398    //   nested-name-specifier identifier '::'
399    Token Next = NextToken();
400
401    // If we get foo:bar, this is almost certainly a typo for foo::bar.  Recover
402    // and emit a fixit hint for it.
403    if (Next.is(tok::colon) && !ColonIsSacred) {
404      if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
405                                            Tok.getLocation(),
406                                            Next.getLocation(), ObjectType,
407                                            EnteringContext) &&
408          // If the token after the colon isn't an identifier, it's still an
409          // error, but they probably meant something else strange so don't
410          // recover like this.
411          PP.LookAhead(1).is(tok::identifier)) {
412        Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
413          << FixItHint::CreateReplacement(Next.getLocation(), "::");
414
415        // Recover as if the user wrote '::'.
416        Next.setKind(tok::coloncolon);
417      }
418    }
419
420    if (Next.is(tok::coloncolon)) {
421      if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
422          !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
423                                                II, ObjectType)) {
424        *MayBePseudoDestructor = true;
425        return false;
426      }
427
428      if (LastII)
429        *LastII = &II;
430
431      // We have an identifier followed by a '::'. Lookup this name
432      // as the name in a nested-name-specifier.
433      SourceLocation IdLoc = ConsumeToken();
434      assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
435             "NextToken() not working properly!");
436      SourceLocation CCLoc = ConsumeToken();
437
438      CheckForLParenAfterColonColon();
439
440      HasScopeSpecifier = true;
441      if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
442                                              ObjectType, EnteringContext, SS))
443        SS.SetInvalid(SourceRange(IdLoc, CCLoc));
444
445      continue;
446    }
447
448    CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
449
450    // nested-name-specifier:
451    //   type-name '<'
452    if (Next.is(tok::less)) {
453      TemplateTy Template;
454      UnqualifiedId TemplateName;
455      TemplateName.setIdentifier(&II, Tok.getLocation());
456      bool MemberOfUnknownSpecialization;
457      if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
458                                              /*hasTemplateKeyword=*/false,
459                                                        TemplateName,
460                                                        ObjectType,
461                                                        EnteringContext,
462                                                        Template,
463                                              MemberOfUnknownSpecialization)) {
464        // We have found a template name, so annotate this token
465        // with a template-id annotation. We do not permit the
466        // template-id to be translated into a type annotation,
467        // because some clients (e.g., the parsing of class template
468        // specializations) still want to see the original template-id
469        // token.
470        ConsumeToken();
471        if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
472                                    TemplateName, false))
473          return true;
474        continue;
475      }
476
477      if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
478          (IsTypename || IsTemplateArgumentList(1))) {
479        // We have something like t::getAs<T>, where getAs is a
480        // member of an unknown specialization. However, this will only
481        // parse correctly as a template, so suggest the keyword 'template'
482        // before 'getAs' and treat this as a dependent template name.
483        unsigned DiagID = diag::err_missing_dependent_template_keyword;
484        if (getLangOpts().MicrosoftExt)
485          DiagID = diag::warn_missing_dependent_template_keyword;
486
487        Diag(Tok.getLocation(), DiagID)
488          << II.getName()
489          << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
490
491        if (TemplateNameKind TNK
492              = Actions.ActOnDependentTemplateName(getCurScope(),
493                                                   SS, SourceLocation(),
494                                                   TemplateName, ObjectType,
495                                                   EnteringContext, Template)) {
496          // Consume the identifier.
497          ConsumeToken();
498          if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
499                                      TemplateName, false))
500            return true;
501        }
502        else
503          return true;
504
505        continue;
506      }
507    }
508
509    // We don't have any tokens that form the beginning of a
510    // nested-name-specifier, so we're done.
511    break;
512  }
513
514  // Even if we didn't see any pieces of a nested-name-specifier, we
515  // still check whether there is a tilde in this position, which
516  // indicates a potential pseudo-destructor.
517  if (CheckForDestructor && Tok.is(tok::tilde))
518    *MayBePseudoDestructor = true;
519
520  return false;
521}
522
523/// ParseCXXIdExpression - Handle id-expression.
524///
525///       id-expression:
526///         unqualified-id
527///         qualified-id
528///
529///       qualified-id:
530///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
531///         '::' identifier
532///         '::' operator-function-id
533///         '::' template-id
534///
535/// NOTE: The standard specifies that, for qualified-id, the parser does not
536/// expect:
537///
538///   '::' conversion-function-id
539///   '::' '~' class-name
540///
541/// This may cause a slight inconsistency on diagnostics:
542///
543/// class C {};
544/// namespace A {}
545/// void f() {
546///   :: A :: ~ C(); // Some Sema error about using destructor with a
547///                  // namespace.
548///   :: ~ C(); // Some Parser error like 'unexpected ~'.
549/// }
550///
551/// We simplify the parser a bit and make it work like:
552///
553///       qualified-id:
554///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
555///         '::' unqualified-id
556///
557/// That way Sema can handle and report similar errors for namespaces and the
558/// global scope.
559///
560/// The isAddressOfOperand parameter indicates that this id-expression is a
561/// direct operand of the address-of operator. This is, besides member contexts,
562/// the only place where a qualified-id naming a non-static class member may
563/// appear.
564///
565ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
566  // qualified-id:
567  //   '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
568  //   '::' unqualified-id
569  //
570  CXXScopeSpec SS;
571  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
572
573  SourceLocation TemplateKWLoc;
574  UnqualifiedId Name;
575  if (ParseUnqualifiedId(SS,
576                         /*EnteringContext=*/false,
577                         /*AllowDestructorName=*/false,
578                         /*AllowConstructorName=*/false,
579                         /*ObjectType=*/ ParsedType(),
580                         TemplateKWLoc,
581                         Name))
582    return ExprError();
583
584  // This is only the direct operand of an & operator if it is not
585  // followed by a postfix-expression suffix.
586  if (isAddressOfOperand && isPostfixExpressionSuffixStart())
587    isAddressOfOperand = false;
588
589  return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
590                                   Tok.is(tok::l_paren), isAddressOfOperand);
591}
592
593/// ParseLambdaExpression - Parse a C++11 lambda expression.
594///
595///       lambda-expression:
596///         lambda-introducer lambda-declarator[opt] compound-statement
597///
598///       lambda-introducer:
599///         '[' lambda-capture[opt] ']'
600///
601///       lambda-capture:
602///         capture-default
603///         capture-list
604///         capture-default ',' capture-list
605///
606///       capture-default:
607///         '&'
608///         '='
609///
610///       capture-list:
611///         capture
612///         capture-list ',' capture
613///
614///       capture:
615///         simple-capture
616///         init-capture     [C++1y]
617///
618///       simple-capture:
619///         identifier
620///         '&' identifier
621///         'this'
622///
623///       init-capture:      [C++1y]
624///         identifier initializer
625///         '&' identifier initializer
626///
627///       lambda-declarator:
628///         '(' parameter-declaration-clause ')' attribute-specifier[opt]
629///           'mutable'[opt] exception-specification[opt]
630///           trailing-return-type[opt]
631///
632ExprResult Parser::ParseLambdaExpression() {
633  // Parse lambda-introducer.
634  LambdaIntroducer Intro;
635
636  Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
637  if (DiagID) {
638    Diag(Tok, DiagID.getValue());
639    SkipUntil(tok::r_square);
640    SkipUntil(tok::l_brace);
641    SkipUntil(tok::r_brace);
642    return ExprError();
643  }
644
645  return ParseLambdaExpressionAfterIntroducer(Intro);
646}
647
648/// TryParseLambdaExpression - Use lookahead and potentially tentative
649/// parsing to determine if we are looking at a C++0x lambda expression, and parse
650/// it if we are.
651///
652/// If we are not looking at a lambda expression, returns ExprError().
653ExprResult Parser::TryParseLambdaExpression() {
654  assert(getLangOpts().CPlusPlus11
655         && Tok.is(tok::l_square)
656         && "Not at the start of a possible lambda expression.");
657
658  const Token Next = NextToken(), After = GetLookAheadToken(2);
659
660  // If lookahead indicates this is a lambda...
661  if (Next.is(tok::r_square) ||     // []
662      Next.is(tok::equal) ||        // [=
663      (Next.is(tok::amp) &&         // [&] or [&,
664       (After.is(tok::r_square) ||
665        After.is(tok::comma))) ||
666      (Next.is(tok::identifier) &&  // [identifier]
667       After.is(tok::r_square))) {
668    return ParseLambdaExpression();
669  }
670
671  // If lookahead indicates an ObjC message send...
672  // [identifier identifier
673  if (Next.is(tok::identifier) && After.is(tok::identifier)) {
674    return ExprEmpty();
675  }
676
677  // Here, we're stuck: lambda introducers and Objective-C message sends are
678  // unambiguous, but it requires arbitrary lookhead.  [a,b,c,d,e,f,g] is a
679  // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send.  Instead of
680  // writing two routines to parse a lambda introducer, just try to parse
681  // a lambda introducer first, and fall back if that fails.
682  // (TryParseLambdaIntroducer never produces any diagnostic output.)
683  LambdaIntroducer Intro;
684  if (TryParseLambdaIntroducer(Intro))
685    return ExprEmpty();
686  return ParseLambdaExpressionAfterIntroducer(Intro);
687}
688
689/// \brief Parse a lambda introducer.
690/// \param Intro A LambdaIntroducer filled in with information about the
691///        contents of the lambda-introducer.
692/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
693///        message send and a lambda expression. In this mode, we will
694///        sometimes skip the initializers for init-captures and not fully
695///        populate \p Intro. This flag will be set to \c true if we do so.
696/// \return A DiagnosticID if it hit something unexpected. The location for
697///         for the diagnostic is that of the current token.
698Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
699                                                 bool *SkippedInits) {
700  typedef Optional<unsigned> DiagResult;
701
702  assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
703  BalancedDelimiterTracker T(*this, tok::l_square);
704  T.consumeOpen();
705
706  Intro.Range.setBegin(T.getOpenLocation());
707
708  bool first = true;
709
710  // Parse capture-default.
711  if (Tok.is(tok::amp) &&
712      (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
713    Intro.Default = LCD_ByRef;
714    Intro.DefaultLoc = ConsumeToken();
715    first = false;
716  } else if (Tok.is(tok::equal)) {
717    Intro.Default = LCD_ByCopy;
718    Intro.DefaultLoc = ConsumeToken();
719    first = false;
720  }
721
722  while (Tok.isNot(tok::r_square)) {
723    if (!first) {
724      if (Tok.isNot(tok::comma)) {
725        // Provide a completion for a lambda introducer here. Except
726        // in Objective-C, where this is Almost Surely meant to be a message
727        // send. In that case, fail here and let the ObjC message
728        // expression parser perform the completion.
729        if (Tok.is(tok::code_completion) &&
730            !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
731              !Intro.Captures.empty())) {
732          Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
733                                               /*AfterAmpersand=*/false);
734          ConsumeCodeCompletionToken();
735          break;
736        }
737
738        return DiagResult(diag::err_expected_comma_or_rsquare);
739      }
740      ConsumeToken();
741    }
742
743    if (Tok.is(tok::code_completion)) {
744      // If we're in Objective-C++ and we have a bare '[', then this is more
745      // likely to be a message receiver.
746      if (getLangOpts().ObjC1 && first)
747        Actions.CodeCompleteObjCMessageReceiver(getCurScope());
748      else
749        Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
750                                             /*AfterAmpersand=*/false);
751      ConsumeCodeCompletionToken();
752      break;
753    }
754
755    first = false;
756
757    // Parse capture.
758    LambdaCaptureKind Kind = LCK_ByCopy;
759    SourceLocation Loc;
760    IdentifierInfo* Id = 0;
761    SourceLocation EllipsisLoc;
762    ExprResult Init;
763
764    if (Tok.is(tok::kw_this)) {
765      Kind = LCK_This;
766      Loc = ConsumeToken();
767    } else {
768      if (Tok.is(tok::amp)) {
769        Kind = LCK_ByRef;
770        ConsumeToken();
771
772        if (Tok.is(tok::code_completion)) {
773          Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
774                                               /*AfterAmpersand=*/true);
775          ConsumeCodeCompletionToken();
776          break;
777        }
778      }
779
780      if (Tok.is(tok::identifier)) {
781        Id = Tok.getIdentifierInfo();
782        Loc = ConsumeToken();
783      } else if (Tok.is(tok::kw_this)) {
784        // FIXME: If we want to suggest a fixit here, will need to return more
785        // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
786        // Clear()ed to prevent emission in case of tentative parsing?
787        return DiagResult(diag::err_this_captured_by_reference);
788      } else {
789        return DiagResult(diag::err_expected_capture);
790      }
791
792      if (Tok.is(tok::l_paren)) {
793        BalancedDelimiterTracker Parens(*this, tok::l_paren);
794        Parens.consumeOpen();
795
796        ExprVector Exprs;
797        CommaLocsTy Commas;
798        if (SkippedInits) {
799          Parens.skipToEnd();
800          *SkippedInits = true;
801        } else if (ParseExpressionList(Exprs, Commas)) {
802          Parens.skipToEnd();
803          Init = ExprError();
804        } else {
805          Parens.consumeClose();
806          Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
807                                            Parens.getCloseLocation(),
808                                            Exprs);
809        }
810      } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
811        if (Tok.is(tok::equal))
812          ConsumeToken();
813
814        if (!SkippedInits)
815          Init = ParseInitializer();
816        else if (Tok.is(tok::l_brace)) {
817          BalancedDelimiterTracker Braces(*this, tok::l_brace);
818          Braces.consumeOpen();
819          Braces.skipToEnd();
820          *SkippedInits = true;
821        } else {
822          // We're disambiguating this:
823          //
824          //   [..., x = expr
825          //
826          // We need to find the end of the following expression in order to
827          // determine whether this is an Obj-C message send's receiver, or a
828          // lambda init-capture.
829          //
830          // Parse the expression to find where it ends, and annotate it back
831          // onto the tokens. We would have parsed this expression the same way
832          // in either case: both the RHS of an init-capture and the RHS of an
833          // assignment expression are parsed as an initializer-clause, and in
834          // neither case can anything be added to the scope between the '[' and
835          // here.
836          //
837          // FIXME: This is horrible. Adding a mechanism to skip an expression
838          // would be much cleaner.
839          // FIXME: If there is a ',' before the next ']' or ':', we can skip to
840          // that instead. (And if we see a ':' with no matching '?', we can
841          // classify this as an Obj-C message send.)
842          SourceLocation StartLoc = Tok.getLocation();
843          InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
844          Init = ParseInitializer();
845
846          if (Tok.getLocation() != StartLoc) {
847            // Back out the lexing of the token after the initializer.
848            PP.RevertCachedTokens(1);
849
850            // Replace the consumed tokens with an appropriate annotation.
851            Tok.setLocation(StartLoc);
852            Tok.setKind(tok::annot_primary_expr);
853            setExprAnnotation(Tok, Init);
854            Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
855            PP.AnnotateCachedTokens(Tok);
856
857            // Consume the annotated initializer.
858            ConsumeToken();
859          }
860        }
861      } else if (Tok.is(tok::ellipsis))
862        EllipsisLoc = ConsumeToken();
863    }
864
865    Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init);
866  }
867
868  T.consumeClose();
869  Intro.Range.setEnd(T.getCloseLocation());
870
871  return DiagResult();
872}
873
874/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
875///
876/// Returns true if it hit something unexpected.
877bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
878  TentativeParsingAction PA(*this);
879
880  bool SkippedInits = false;
881  Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
882
883  if (DiagID) {
884    PA.Revert();
885    return true;
886  }
887
888  if (SkippedInits) {
889    // Parse it again, but this time parse the init-captures too.
890    PA.Revert();
891    Intro = LambdaIntroducer();
892    DiagID = ParseLambdaIntroducer(Intro);
893    assert(!DiagID && "parsing lambda-introducer failed on reparse");
894    return false;
895  }
896
897  PA.Commit();
898  return false;
899}
900
901/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
902/// expression.
903ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
904                     LambdaIntroducer &Intro) {
905  SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
906  Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
907
908  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
909                                "lambda expression parsing");
910
911  // FIXME: Call into Actions to add any init-capture declarations to the
912  // scope while parsing the lambda-declarator and compound-statement.
913
914  // Parse lambda-declarator[opt].
915  DeclSpec DS(AttrFactory);
916  Declarator D(DS, Declarator::LambdaExprContext);
917
918  if (Tok.is(tok::l_paren)) {
919    ParseScope PrototypeScope(this,
920                              Scope::FunctionPrototypeScope |
921                              Scope::FunctionDeclarationScope |
922                              Scope::DeclScope);
923
924    SourceLocation DeclEndLoc;
925    BalancedDelimiterTracker T(*this, tok::l_paren);
926    T.consumeOpen();
927    SourceLocation LParenLoc = T.getOpenLocation();
928
929    // Parse parameter-declaration-clause.
930    ParsedAttributes Attr(AttrFactory);
931    SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
932    SourceLocation EllipsisLoc;
933
934    if (Tok.isNot(tok::r_paren))
935      ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
936
937    T.consumeClose();
938    SourceLocation RParenLoc = T.getCloseLocation();
939    DeclEndLoc = RParenLoc;
940
941    // Parse 'mutable'[opt].
942    SourceLocation MutableLoc;
943    if (Tok.is(tok::kw_mutable)) {
944      MutableLoc = ConsumeToken();
945      DeclEndLoc = MutableLoc;
946    }
947
948    // Parse exception-specification[opt].
949    ExceptionSpecificationType ESpecType = EST_None;
950    SourceRange ESpecRange;
951    SmallVector<ParsedType, 2> DynamicExceptions;
952    SmallVector<SourceRange, 2> DynamicExceptionRanges;
953    ExprResult NoexceptExpr;
954    ESpecType = tryParseExceptionSpecification(ESpecRange,
955                                               DynamicExceptions,
956                                               DynamicExceptionRanges,
957                                               NoexceptExpr);
958
959    if (ESpecType != EST_None)
960      DeclEndLoc = ESpecRange.getEnd();
961
962    // Parse attribute-specifier[opt].
963    MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
964
965    SourceLocation FunLocalRangeEnd = DeclEndLoc;
966
967    // Parse trailing-return-type[opt].
968    TypeResult TrailingReturnType;
969    if (Tok.is(tok::arrow)) {
970      FunLocalRangeEnd = Tok.getLocation();
971      SourceRange Range;
972      TrailingReturnType = ParseTrailingReturnType(Range);
973      if (Range.getEnd().isValid())
974        DeclEndLoc = Range.getEnd();
975    }
976
977    PrototypeScope.Exit();
978
979    SourceLocation NoLoc;
980    D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
981                                           /*isAmbiguous=*/false,
982                                           LParenLoc,
983                                           ParamInfo.data(), ParamInfo.size(),
984                                           EllipsisLoc, RParenLoc,
985                                           DS.getTypeQualifiers(),
986                                           /*RefQualifierIsLValueRef=*/true,
987                                           /*RefQualifierLoc=*/NoLoc,
988                                           /*ConstQualifierLoc=*/NoLoc,
989                                           /*VolatileQualifierLoc=*/NoLoc,
990                                           MutableLoc,
991                                           ESpecType, ESpecRange.getBegin(),
992                                           DynamicExceptions.data(),
993                                           DynamicExceptionRanges.data(),
994                                           DynamicExceptions.size(),
995                                           NoexceptExpr.isUsable() ?
996                                             NoexceptExpr.get() : 0,
997                                           LParenLoc, FunLocalRangeEnd, D,
998                                           TrailingReturnType),
999                  Attr, DeclEndLoc);
1000  } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) {
1001    // It's common to forget that one needs '()' before 'mutable' or the
1002    // result type. Deal with this.
1003    Diag(Tok, diag::err_lambda_missing_parens)
1004      << Tok.is(tok::arrow)
1005      << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1006    SourceLocation DeclLoc = Tok.getLocation();
1007    SourceLocation DeclEndLoc = DeclLoc;
1008
1009    // Parse 'mutable', if it's there.
1010    SourceLocation MutableLoc;
1011    if (Tok.is(tok::kw_mutable)) {
1012      MutableLoc = ConsumeToken();
1013      DeclEndLoc = MutableLoc;
1014    }
1015
1016    // Parse the return type, if there is one.
1017    TypeResult TrailingReturnType;
1018    if (Tok.is(tok::arrow)) {
1019      SourceRange Range;
1020      TrailingReturnType = ParseTrailingReturnType(Range);
1021      if (Range.getEnd().isValid())
1022        DeclEndLoc = Range.getEnd();
1023    }
1024
1025    ParsedAttributes Attr(AttrFactory);
1026    SourceLocation NoLoc;
1027    D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1028                                               /*isAmbiguous=*/false,
1029                                               /*LParenLoc=*/NoLoc,
1030                                               /*Params=*/0,
1031                                               /*NumParams=*/0,
1032                                               /*EllipsisLoc=*/NoLoc,
1033                                               /*RParenLoc=*/NoLoc,
1034                                               /*TypeQuals=*/0,
1035                                               /*RefQualifierIsLValueRef=*/true,
1036                                               /*RefQualifierLoc=*/NoLoc,
1037                                               /*ConstQualifierLoc=*/NoLoc,
1038                                               /*VolatileQualifierLoc=*/NoLoc,
1039                                               MutableLoc,
1040                                               EST_None,
1041                                               /*ESpecLoc=*/NoLoc,
1042                                               /*Exceptions=*/0,
1043                                               /*ExceptionRanges=*/0,
1044                                               /*NumExceptions=*/0,
1045                                               /*NoexceptExpr=*/0,
1046                                               DeclLoc, DeclEndLoc, D,
1047                                               TrailingReturnType),
1048                  Attr, DeclEndLoc);
1049  }
1050
1051
1052  // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1053  // it.
1054  unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
1055  ParseScope BodyScope(this, ScopeFlags);
1056
1057  Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1058
1059  // Parse compound-statement.
1060  if (!Tok.is(tok::l_brace)) {
1061    Diag(Tok, diag::err_expected_lambda_body);
1062    Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1063    return ExprError();
1064  }
1065
1066  StmtResult Stmt(ParseCompoundStatementBody());
1067  BodyScope.Exit();
1068
1069  if (!Stmt.isInvalid())
1070    return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope());
1071
1072  Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1073  return ExprError();
1074}
1075
1076/// ParseCXXCasts - This handles the various ways to cast expressions to another
1077/// type.
1078///
1079///       postfix-expression: [C++ 5.2p1]
1080///         'dynamic_cast' '<' type-name '>' '(' expression ')'
1081///         'static_cast' '<' type-name '>' '(' expression ')'
1082///         'reinterpret_cast' '<' type-name '>' '(' expression ')'
1083///         'const_cast' '<' type-name '>' '(' expression ')'
1084///
1085ExprResult Parser::ParseCXXCasts() {
1086  tok::TokenKind Kind = Tok.getKind();
1087  const char *CastName = 0;     // For error messages
1088
1089  switch (Kind) {
1090  default: llvm_unreachable("Unknown C++ cast!");
1091  case tok::kw_const_cast:       CastName = "const_cast";       break;
1092  case tok::kw_dynamic_cast:     CastName = "dynamic_cast";     break;
1093  case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1094  case tok::kw_static_cast:      CastName = "static_cast";      break;
1095  }
1096
1097  SourceLocation OpLoc = ConsumeToken();
1098  SourceLocation LAngleBracketLoc = Tok.getLocation();
1099
1100  // Check for "<::" which is parsed as "[:".  If found, fix token stream,
1101  // diagnose error, suggest fix, and recover parsing.
1102  if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1103    Token Next = NextToken();
1104    if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1105      FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1106  }
1107
1108  if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1109    return ExprError();
1110
1111  // Parse the common declaration-specifiers piece.
1112  DeclSpec DS(AttrFactory);
1113  ParseSpecifierQualifierList(DS);
1114
1115  // Parse the abstract-declarator, if present.
1116  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1117  ParseDeclarator(DeclaratorInfo);
1118
1119  SourceLocation RAngleBracketLoc = Tok.getLocation();
1120
1121  if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
1122    return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
1123
1124  SourceLocation LParenLoc, RParenLoc;
1125  BalancedDelimiterTracker T(*this, tok::l_paren);
1126
1127  if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1128    return ExprError();
1129
1130  ExprResult Result = ParseExpression();
1131
1132  // Match the ')'.
1133  T.consumeClose();
1134
1135  if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1136    Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1137                                       LAngleBracketLoc, DeclaratorInfo,
1138                                       RAngleBracketLoc,
1139                                       T.getOpenLocation(), Result.take(),
1140                                       T.getCloseLocation());
1141
1142  return Result;
1143}
1144
1145/// ParseCXXTypeid - This handles the C++ typeid expression.
1146///
1147///       postfix-expression: [C++ 5.2p1]
1148///         'typeid' '(' expression ')'
1149///         'typeid' '(' type-id ')'
1150///
1151ExprResult Parser::ParseCXXTypeid() {
1152  assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1153
1154  SourceLocation OpLoc = ConsumeToken();
1155  SourceLocation LParenLoc, RParenLoc;
1156  BalancedDelimiterTracker T(*this, tok::l_paren);
1157
1158  // typeid expressions are always parenthesized.
1159  if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1160    return ExprError();
1161  LParenLoc = T.getOpenLocation();
1162
1163  ExprResult Result;
1164
1165  // C++0x [expr.typeid]p3:
1166  //   When typeid is applied to an expression other than an lvalue of a
1167  //   polymorphic class type [...] The expression is an unevaluated
1168  //   operand (Clause 5).
1169  //
1170  // Note that we can't tell whether the expression is an lvalue of a
1171  // polymorphic class type until after we've parsed the expression; we
1172  // speculatively assume the subexpression is unevaluated, and fix it up
1173  // later.
1174  //
1175  // We enter the unevaluated context before trying to determine whether we
1176  // have a type-id, because the tentative parse logic will try to resolve
1177  // names, and must treat them as unevaluated.
1178  EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1179                                               Sema::ReuseLambdaContextDecl);
1180
1181  if (isTypeIdInParens()) {
1182    TypeResult Ty = ParseTypeName();
1183
1184    // Match the ')'.
1185    T.consumeClose();
1186    RParenLoc = T.getCloseLocation();
1187    if (Ty.isInvalid() || RParenLoc.isInvalid())
1188      return ExprError();
1189
1190    Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1191                                    Ty.get().getAsOpaquePtr(), RParenLoc);
1192  } else {
1193    Result = ParseExpression();
1194
1195    // Match the ')'.
1196    if (Result.isInvalid())
1197      SkipUntil(tok::r_paren);
1198    else {
1199      T.consumeClose();
1200      RParenLoc = T.getCloseLocation();
1201      if (RParenLoc.isInvalid())
1202        return ExprError();
1203
1204      Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1205                                      Result.release(), RParenLoc);
1206    }
1207  }
1208
1209  return Result;
1210}
1211
1212/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1213///
1214///         '__uuidof' '(' expression ')'
1215///         '__uuidof' '(' type-id ')'
1216///
1217ExprResult Parser::ParseCXXUuidof() {
1218  assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1219
1220  SourceLocation OpLoc = ConsumeToken();
1221  BalancedDelimiterTracker T(*this, tok::l_paren);
1222
1223  // __uuidof expressions are always parenthesized.
1224  if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1225    return ExprError();
1226
1227  ExprResult Result;
1228
1229  if (isTypeIdInParens()) {
1230    TypeResult Ty = ParseTypeName();
1231
1232    // Match the ')'.
1233    T.consumeClose();
1234
1235    if (Ty.isInvalid())
1236      return ExprError();
1237
1238    Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1239                                    Ty.get().getAsOpaquePtr(),
1240                                    T.getCloseLocation());
1241  } else {
1242    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1243    Result = ParseExpression();
1244
1245    // Match the ')'.
1246    if (Result.isInvalid())
1247      SkipUntil(tok::r_paren);
1248    else {
1249      T.consumeClose();
1250
1251      Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1252                                      /*isType=*/false,
1253                                      Result.release(), T.getCloseLocation());
1254    }
1255  }
1256
1257  return Result;
1258}
1259
1260/// \brief Parse a C++ pseudo-destructor expression after the base,
1261/// . or -> operator, and nested-name-specifier have already been
1262/// parsed.
1263///
1264///       postfix-expression: [C++ 5.2]
1265///         postfix-expression . pseudo-destructor-name
1266///         postfix-expression -> pseudo-destructor-name
1267///
1268///       pseudo-destructor-name:
1269///         ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1270///         ::[opt] nested-name-specifier template simple-template-id ::
1271///                 ~type-name
1272///         ::[opt] nested-name-specifier[opt] ~type-name
1273///
1274ExprResult
1275Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1276                                 tok::TokenKind OpKind,
1277                                 CXXScopeSpec &SS,
1278                                 ParsedType ObjectType) {
1279  // We're parsing either a pseudo-destructor-name or a dependent
1280  // member access that has the same form as a
1281  // pseudo-destructor-name. We parse both in the same way and let
1282  // the action model sort them out.
1283  //
1284  // Note that the ::[opt] nested-name-specifier[opt] has already
1285  // been parsed, and if there was a simple-template-id, it has
1286  // been coalesced into a template-id annotation token.
1287  UnqualifiedId FirstTypeName;
1288  SourceLocation CCLoc;
1289  if (Tok.is(tok::identifier)) {
1290    FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1291    ConsumeToken();
1292    assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1293    CCLoc = ConsumeToken();
1294  } else if (Tok.is(tok::annot_template_id)) {
1295    // FIXME: retrieve TemplateKWLoc from template-id annotation and
1296    // store it in the pseudo-dtor node (to be used when instantiating it).
1297    FirstTypeName.setTemplateId(
1298                              (TemplateIdAnnotation *)Tok.getAnnotationValue());
1299    ConsumeToken();
1300    assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1301    CCLoc = ConsumeToken();
1302  } else {
1303    FirstTypeName.setIdentifier(0, SourceLocation());
1304  }
1305
1306  // Parse the tilde.
1307  assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1308  SourceLocation TildeLoc = ConsumeToken();
1309
1310  if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1311    DeclSpec DS(AttrFactory);
1312    ParseDecltypeSpecifier(DS);
1313    if (DS.getTypeSpecType() == TST_error)
1314      return ExprError();
1315    return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1316                                             OpKind, TildeLoc, DS,
1317                                             Tok.is(tok::l_paren));
1318  }
1319
1320  if (!Tok.is(tok::identifier)) {
1321    Diag(Tok, diag::err_destructor_tilde_identifier);
1322    return ExprError();
1323  }
1324
1325  // Parse the second type.
1326  UnqualifiedId SecondTypeName;
1327  IdentifierInfo *Name = Tok.getIdentifierInfo();
1328  SourceLocation NameLoc = ConsumeToken();
1329  SecondTypeName.setIdentifier(Name, NameLoc);
1330
1331  // If there is a '<', the second type name is a template-id. Parse
1332  // it as such.
1333  if (Tok.is(tok::less) &&
1334      ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1335                                   Name, NameLoc,
1336                                   false, ObjectType, SecondTypeName,
1337                                   /*AssumeTemplateName=*/true))
1338    return ExprError();
1339
1340  return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1341                                           OpLoc, OpKind,
1342                                           SS, FirstTypeName, CCLoc,
1343                                           TildeLoc, SecondTypeName,
1344                                           Tok.is(tok::l_paren));
1345}
1346
1347/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1348///
1349///       boolean-literal: [C++ 2.13.5]
1350///         'true'
1351///         'false'
1352ExprResult Parser::ParseCXXBoolLiteral() {
1353  tok::TokenKind Kind = Tok.getKind();
1354  return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1355}
1356
1357/// ParseThrowExpression - This handles the C++ throw expression.
1358///
1359///       throw-expression: [C++ 15]
1360///         'throw' assignment-expression[opt]
1361ExprResult Parser::ParseThrowExpression() {
1362  assert(Tok.is(tok::kw_throw) && "Not throw!");
1363  SourceLocation ThrowLoc = ConsumeToken();           // Eat the throw token.
1364
1365  // If the current token isn't the start of an assignment-expression,
1366  // then the expression is not present.  This handles things like:
1367  //   "C ? throw : (void)42", which is crazy but legal.
1368  switch (Tok.getKind()) {  // FIXME: move this predicate somewhere common.
1369  case tok::semi:
1370  case tok::r_paren:
1371  case tok::r_square:
1372  case tok::r_brace:
1373  case tok::colon:
1374  case tok::comma:
1375    return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
1376
1377  default:
1378    ExprResult Expr(ParseAssignmentExpression());
1379    if (Expr.isInvalid()) return Expr;
1380    return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
1381  }
1382}
1383
1384/// ParseCXXThis - This handles the C++ 'this' pointer.
1385///
1386/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1387/// a non-lvalue expression whose value is the address of the object for which
1388/// the function is called.
1389ExprResult Parser::ParseCXXThis() {
1390  assert(Tok.is(tok::kw_this) && "Not 'this'!");
1391  SourceLocation ThisLoc = ConsumeToken();
1392  return Actions.ActOnCXXThis(ThisLoc);
1393}
1394
1395/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1396/// Can be interpreted either as function-style casting ("int(x)")
1397/// or class type construction ("ClassType(x,y,z)")
1398/// or creation of a value-initialized type ("int()").
1399/// See [C++ 5.2.3].
1400///
1401///       postfix-expression: [C++ 5.2p1]
1402///         simple-type-specifier '(' expression-list[opt] ')'
1403/// [C++0x] simple-type-specifier braced-init-list
1404///         typename-specifier '(' expression-list[opt] ')'
1405/// [C++0x] typename-specifier braced-init-list
1406///
1407ExprResult
1408Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1409  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1410  ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1411
1412  assert((Tok.is(tok::l_paren) ||
1413          (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1414         && "Expected '(' or '{'!");
1415
1416  if (Tok.is(tok::l_brace)) {
1417    ExprResult Init = ParseBraceInitializer();
1418    if (Init.isInvalid())
1419      return Init;
1420    Expr *InitList = Init.take();
1421    return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1422                                             MultiExprArg(&InitList, 1),
1423                                             SourceLocation());
1424  } else {
1425    BalancedDelimiterTracker T(*this, tok::l_paren);
1426    T.consumeOpen();
1427
1428    ExprVector Exprs;
1429    CommaLocsTy CommaLocs;
1430
1431    if (Tok.isNot(tok::r_paren)) {
1432      if (ParseExpressionList(Exprs, CommaLocs)) {
1433        SkipUntil(tok::r_paren);
1434        return ExprError();
1435      }
1436    }
1437
1438    // Match the ')'.
1439    T.consumeClose();
1440
1441    // TypeRep could be null, if it references an invalid typedef.
1442    if (!TypeRep)
1443      return ExprError();
1444
1445    assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1446           "Unexpected number of commas!");
1447    return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1448                                             Exprs,
1449                                             T.getCloseLocation());
1450  }
1451}
1452
1453/// ParseCXXCondition - if/switch/while condition expression.
1454///
1455///       condition:
1456///         expression
1457///         type-specifier-seq declarator '=' assignment-expression
1458/// [C++11] type-specifier-seq declarator '=' initializer-clause
1459/// [C++11] type-specifier-seq declarator braced-init-list
1460/// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1461///             '=' assignment-expression
1462///
1463/// \param ExprOut if the condition was parsed as an expression, the parsed
1464/// expression.
1465///
1466/// \param DeclOut if the condition was parsed as a declaration, the parsed
1467/// declaration.
1468///
1469/// \param Loc The location of the start of the statement that requires this
1470/// condition, e.g., the "for" in a for loop.
1471///
1472/// \param ConvertToBoolean Whether the condition expression should be
1473/// converted to a boolean value.
1474///
1475/// \returns true if there was a parsing, false otherwise.
1476bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1477                               Decl *&DeclOut,
1478                               SourceLocation Loc,
1479                               bool ConvertToBoolean) {
1480  if (Tok.is(tok::code_completion)) {
1481    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1482    cutOffParsing();
1483    return true;
1484  }
1485
1486  ParsedAttributesWithRange attrs(AttrFactory);
1487  MaybeParseCXX11Attributes(attrs);
1488
1489  if (!isCXXConditionDeclaration()) {
1490    ProhibitAttributes(attrs);
1491
1492    // Parse the expression.
1493    ExprOut = ParseExpression(); // expression
1494    DeclOut = 0;
1495    if (ExprOut.isInvalid())
1496      return true;
1497
1498    // If required, convert to a boolean value.
1499    if (ConvertToBoolean)
1500      ExprOut
1501        = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1502    return ExprOut.isInvalid();
1503  }
1504
1505  // type-specifier-seq
1506  DeclSpec DS(AttrFactory);
1507  DS.takeAttributesFrom(attrs);
1508  ParseSpecifierQualifierList(DS);
1509
1510  // declarator
1511  Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1512  ParseDeclarator(DeclaratorInfo);
1513
1514  // simple-asm-expr[opt]
1515  if (Tok.is(tok::kw_asm)) {
1516    SourceLocation Loc;
1517    ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1518    if (AsmLabel.isInvalid()) {
1519      SkipUntil(tok::semi);
1520      return true;
1521    }
1522    DeclaratorInfo.setAsmLabel(AsmLabel.release());
1523    DeclaratorInfo.SetRangeEnd(Loc);
1524  }
1525
1526  // If attributes are present, parse them.
1527  MaybeParseGNUAttributes(DeclaratorInfo);
1528
1529  // Type-check the declaration itself.
1530  DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1531                                                        DeclaratorInfo);
1532  DeclOut = Dcl.get();
1533  ExprOut = ExprError();
1534
1535  // '=' assignment-expression
1536  // If a '==' or '+=' is found, suggest a fixit to '='.
1537  bool CopyInitialization = isTokenEqualOrEqualTypo();
1538  if (CopyInitialization)
1539    ConsumeToken();
1540
1541  ExprResult InitExpr = ExprError();
1542  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1543    Diag(Tok.getLocation(),
1544         diag::warn_cxx98_compat_generalized_initializer_lists);
1545    InitExpr = ParseBraceInitializer();
1546  } else if (CopyInitialization) {
1547    InitExpr = ParseAssignmentExpression();
1548  } else if (Tok.is(tok::l_paren)) {
1549    // This was probably an attempt to initialize the variable.
1550    SourceLocation LParen = ConsumeParen(), RParen = LParen;
1551    if (SkipUntil(tok::r_paren, true, /*DontConsume=*/true))
1552      RParen = ConsumeParen();
1553    Diag(DeclOut ? DeclOut->getLocation() : LParen,
1554         diag::err_expected_init_in_condition_lparen)
1555      << SourceRange(LParen, RParen);
1556  } else {
1557    Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1558         diag::err_expected_init_in_condition);
1559  }
1560
1561  if (!InitExpr.isInvalid())
1562    Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization,
1563                                 DS.containsPlaceholderType());
1564  else
1565    Actions.ActOnInitializerError(DeclOut);
1566
1567  // FIXME: Build a reference to this declaration? Convert it to bool?
1568  // (This is currently handled by Sema).
1569
1570  Actions.FinalizeDeclaration(DeclOut);
1571
1572  return false;
1573}
1574
1575/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1576/// This should only be called when the current token is known to be part of
1577/// simple-type-specifier.
1578///
1579///       simple-type-specifier:
1580///         '::'[opt] nested-name-specifier[opt] type-name
1581///         '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1582///         char
1583///         wchar_t
1584///         bool
1585///         short
1586///         int
1587///         long
1588///         signed
1589///         unsigned
1590///         float
1591///         double
1592///         void
1593/// [GNU]   typeof-specifier
1594/// [C++0x] auto               [TODO]
1595///
1596///       type-name:
1597///         class-name
1598///         enum-name
1599///         typedef-name
1600///
1601void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1602  DS.SetRangeStart(Tok.getLocation());
1603  const char *PrevSpec;
1604  unsigned DiagID;
1605  SourceLocation Loc = Tok.getLocation();
1606
1607  switch (Tok.getKind()) {
1608  case tok::identifier:   // foo::bar
1609  case tok::coloncolon:   // ::foo::bar
1610    llvm_unreachable("Annotation token should already be formed!");
1611  default:
1612    llvm_unreachable("Not a simple-type-specifier token!");
1613
1614  // type-name
1615  case tok::annot_typename: {
1616    if (getTypeAnnotation(Tok))
1617      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1618                         getTypeAnnotation(Tok));
1619    else
1620      DS.SetTypeSpecError();
1621
1622    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1623    ConsumeToken();
1624
1625    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1626    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1627    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1628    // just a normal reference to a typedef name.
1629    if (Tok.is(tok::less) && getLangOpts().ObjC1)
1630      ParseObjCProtocolQualifiers(DS);
1631
1632    DS.Finish(Diags, PP);
1633    return;
1634  }
1635
1636  // builtin types
1637  case tok::kw_short:
1638    DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1639    break;
1640  case tok::kw_long:
1641    DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
1642    break;
1643  case tok::kw___int64:
1644    DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1645    break;
1646  case tok::kw_signed:
1647    DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1648    break;
1649  case tok::kw_unsigned:
1650    DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1651    break;
1652  case tok::kw_void:
1653    DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1654    break;
1655  case tok::kw_char:
1656    DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1657    break;
1658  case tok::kw_int:
1659    DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1660    break;
1661  case tok::kw___int128:
1662    DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID);
1663    break;
1664  case tok::kw_half:
1665    DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
1666    break;
1667  case tok::kw_float:
1668    DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1669    break;
1670  case tok::kw_double:
1671    DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1672    break;
1673  case tok::kw_wchar_t:
1674    DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1675    break;
1676  case tok::kw_char16_t:
1677    DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1678    break;
1679  case tok::kw_char32_t:
1680    DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1681    break;
1682  case tok::kw_bool:
1683    DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1684    break;
1685  case tok::annot_decltype:
1686  case tok::kw_decltype:
1687    DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1688    return DS.Finish(Diags, PP);
1689
1690  // GNU typeof support.
1691  case tok::kw_typeof:
1692    ParseTypeofSpecifier(DS);
1693    DS.Finish(Diags, PP);
1694    return;
1695  }
1696  if (Tok.is(tok::annot_typename))
1697    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1698  else
1699    DS.SetRangeEnd(Tok.getLocation());
1700  ConsumeToken();
1701  DS.Finish(Diags, PP);
1702}
1703
1704/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1705/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1706/// e.g., "const short int". Note that the DeclSpec is *not* finished
1707/// by parsing the type-specifier-seq, because these sequences are
1708/// typically followed by some form of declarator. Returns true and
1709/// emits diagnostics if this is not a type-specifier-seq, false
1710/// otherwise.
1711///
1712///   type-specifier-seq: [C++ 8.1]
1713///     type-specifier type-specifier-seq[opt]
1714///
1715bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1716  ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1717  DS.Finish(Diags, PP);
1718  return false;
1719}
1720
1721/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1722/// some form.
1723///
1724/// This routine is invoked when a '<' is encountered after an identifier or
1725/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1726/// whether the unqualified-id is actually a template-id. This routine will
1727/// then parse the template arguments and form the appropriate template-id to
1728/// return to the caller.
1729///
1730/// \param SS the nested-name-specifier that precedes this template-id, if
1731/// we're actually parsing a qualified-id.
1732///
1733/// \param Name for constructor and destructor names, this is the actual
1734/// identifier that may be a template-name.
1735///
1736/// \param NameLoc the location of the class-name in a constructor or
1737/// destructor.
1738///
1739/// \param EnteringContext whether we're entering the scope of the
1740/// nested-name-specifier.
1741///
1742/// \param ObjectType if this unqualified-id occurs within a member access
1743/// expression, the type of the base object whose member is being accessed.
1744///
1745/// \param Id as input, describes the template-name or operator-function-id
1746/// that precedes the '<'. If template arguments were parsed successfully,
1747/// will be updated with the template-id.
1748///
1749/// \param AssumeTemplateId When true, this routine will assume that the name
1750/// refers to a template without performing name lookup to verify.
1751///
1752/// \returns true if a parse error occurred, false otherwise.
1753bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1754                                          SourceLocation TemplateKWLoc,
1755                                          IdentifierInfo *Name,
1756                                          SourceLocation NameLoc,
1757                                          bool EnteringContext,
1758                                          ParsedType ObjectType,
1759                                          UnqualifiedId &Id,
1760                                          bool AssumeTemplateId) {
1761  assert((AssumeTemplateId || Tok.is(tok::less)) &&
1762         "Expected '<' to finish parsing a template-id");
1763
1764  TemplateTy Template;
1765  TemplateNameKind TNK = TNK_Non_template;
1766  switch (Id.getKind()) {
1767  case UnqualifiedId::IK_Identifier:
1768  case UnqualifiedId::IK_OperatorFunctionId:
1769  case UnqualifiedId::IK_LiteralOperatorId:
1770    if (AssumeTemplateId) {
1771      TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
1772                                               Id, ObjectType, EnteringContext,
1773                                               Template);
1774      if (TNK == TNK_Non_template)
1775        return true;
1776    } else {
1777      bool MemberOfUnknownSpecialization;
1778      TNK = Actions.isTemplateName(getCurScope(), SS,
1779                                   TemplateKWLoc.isValid(), Id,
1780                                   ObjectType, EnteringContext, Template,
1781                                   MemberOfUnknownSpecialization);
1782
1783      if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1784          ObjectType && IsTemplateArgumentList()) {
1785        // We have something like t->getAs<T>(), where getAs is a
1786        // member of an unknown specialization. However, this will only
1787        // parse correctly as a template, so suggest the keyword 'template'
1788        // before 'getAs' and treat this as a dependent template name.
1789        std::string Name;
1790        if (Id.getKind() == UnqualifiedId::IK_Identifier)
1791          Name = Id.Identifier->getName();
1792        else {
1793          Name = "operator ";
1794          if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1795            Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1796          else
1797            Name += Id.Identifier->getName();
1798        }
1799        Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1800          << Name
1801          << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1802        TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1803                                                 SS, TemplateKWLoc, Id,
1804                                                 ObjectType, EnteringContext,
1805                                                 Template);
1806        if (TNK == TNK_Non_template)
1807          return true;
1808      }
1809    }
1810    break;
1811
1812  case UnqualifiedId::IK_ConstructorName: {
1813    UnqualifiedId TemplateName;
1814    bool MemberOfUnknownSpecialization;
1815    TemplateName.setIdentifier(Name, NameLoc);
1816    TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1817                                 TemplateName, ObjectType,
1818                                 EnteringContext, Template,
1819                                 MemberOfUnknownSpecialization);
1820    break;
1821  }
1822
1823  case UnqualifiedId::IK_DestructorName: {
1824    UnqualifiedId TemplateName;
1825    bool MemberOfUnknownSpecialization;
1826    TemplateName.setIdentifier(Name, NameLoc);
1827    if (ObjectType) {
1828      TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1829                                               SS, TemplateKWLoc, TemplateName,
1830                                               ObjectType, EnteringContext,
1831                                               Template);
1832      if (TNK == TNK_Non_template)
1833        return true;
1834    } else {
1835      TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1836                                   TemplateName, ObjectType,
1837                                   EnteringContext, Template,
1838                                   MemberOfUnknownSpecialization);
1839
1840      if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
1841        Diag(NameLoc, diag::err_destructor_template_id)
1842          << Name << SS.getRange();
1843        return true;
1844      }
1845    }
1846    break;
1847  }
1848
1849  default:
1850    return false;
1851  }
1852
1853  if (TNK == TNK_Non_template)
1854    return false;
1855
1856  // Parse the enclosed template argument list.
1857  SourceLocation LAngleLoc, RAngleLoc;
1858  TemplateArgList TemplateArgs;
1859  if (Tok.is(tok::less) &&
1860      ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
1861                                       SS, true, LAngleLoc,
1862                                       TemplateArgs,
1863                                       RAngleLoc))
1864    return true;
1865
1866  if (Id.getKind() == UnqualifiedId::IK_Identifier ||
1867      Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1868      Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
1869    // Form a parsed representation of the template-id to be stored in the
1870    // UnqualifiedId.
1871    TemplateIdAnnotation *TemplateId
1872      = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1873
1874    if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1875      TemplateId->Name = Id.Identifier;
1876      TemplateId->Operator = OO_None;
1877      TemplateId->TemplateNameLoc = Id.StartLocation;
1878    } else {
1879      TemplateId->Name = 0;
1880      TemplateId->Operator = Id.OperatorFunctionId.Operator;
1881      TemplateId->TemplateNameLoc = Id.StartLocation;
1882    }
1883
1884    TemplateId->SS = SS;
1885    TemplateId->TemplateKWLoc = TemplateKWLoc;
1886    TemplateId->Template = Template;
1887    TemplateId->Kind = TNK;
1888    TemplateId->LAngleLoc = LAngleLoc;
1889    TemplateId->RAngleLoc = RAngleLoc;
1890    ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1891    for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
1892         Arg != ArgEnd; ++Arg)
1893      Args[Arg] = TemplateArgs[Arg];
1894
1895    Id.setTemplateId(TemplateId);
1896    return false;
1897  }
1898
1899  // Bundle the template arguments together.
1900  ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1901
1902  // Constructor and destructor names.
1903  TypeResult Type
1904    = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1905                                  Template, NameLoc,
1906                                  LAngleLoc, TemplateArgsPtr, RAngleLoc,
1907                                  /*IsCtorOrDtorName=*/true);
1908  if (Type.isInvalid())
1909    return true;
1910
1911  if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1912    Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1913  else
1914    Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1915
1916  return false;
1917}
1918
1919/// \brief Parse an operator-function-id or conversion-function-id as part
1920/// of a C++ unqualified-id.
1921///
1922/// This routine is responsible only for parsing the operator-function-id or
1923/// conversion-function-id; it does not handle template arguments in any way.
1924///
1925/// \code
1926///       operator-function-id: [C++ 13.5]
1927///         'operator' operator
1928///
1929///       operator: one of
1930///            new   delete  new[]   delete[]
1931///            +     -    *  /    %  ^    &   |   ~
1932///            !     =    <  >    += -=   *=  /=  %=
1933///            ^=    &=   |= <<   >> >>= <<=  ==  !=
1934///            <=    >=   && ||   ++ --   ,   ->* ->
1935///            ()    []
1936///
1937///       conversion-function-id: [C++ 12.3.2]
1938///         operator conversion-type-id
1939///
1940///       conversion-type-id:
1941///         type-specifier-seq conversion-declarator[opt]
1942///
1943///       conversion-declarator:
1944///         ptr-operator conversion-declarator[opt]
1945/// \endcode
1946///
1947/// \param SS The nested-name-specifier that preceded this unqualified-id. If
1948/// non-empty, then we are parsing the unqualified-id of a qualified-id.
1949///
1950/// \param EnteringContext whether we are entering the scope of the
1951/// nested-name-specifier.
1952///
1953/// \param ObjectType if this unqualified-id occurs within a member access
1954/// expression, the type of the base object whose member is being accessed.
1955///
1956/// \param Result on a successful parse, contains the parsed unqualified-id.
1957///
1958/// \returns true if parsing fails, false otherwise.
1959bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
1960                                        ParsedType ObjectType,
1961                                        UnqualifiedId &Result) {
1962  assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
1963
1964  // Consume the 'operator' keyword.
1965  SourceLocation KeywordLoc = ConsumeToken();
1966
1967  // Determine what kind of operator name we have.
1968  unsigned SymbolIdx = 0;
1969  SourceLocation SymbolLocations[3];
1970  OverloadedOperatorKind Op = OO_None;
1971  switch (Tok.getKind()) {
1972    case tok::kw_new:
1973    case tok::kw_delete: {
1974      bool isNew = Tok.getKind() == tok::kw_new;
1975      // Consume the 'new' or 'delete'.
1976      SymbolLocations[SymbolIdx++] = ConsumeToken();
1977      // Check for array new/delete.
1978      if (Tok.is(tok::l_square) &&
1979          (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
1980        // Consume the '[' and ']'.
1981        BalancedDelimiterTracker T(*this, tok::l_square);
1982        T.consumeOpen();
1983        T.consumeClose();
1984        if (T.getCloseLocation().isInvalid())
1985          return true;
1986
1987        SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1988        SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1989        Op = isNew? OO_Array_New : OO_Array_Delete;
1990      } else {
1991        Op = isNew? OO_New : OO_Delete;
1992      }
1993      break;
1994    }
1995
1996#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1997    case tok::Token:                                                     \
1998      SymbolLocations[SymbolIdx++] = ConsumeToken();                     \
1999      Op = OO_##Name;                                                    \
2000      break;
2001#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2002#include "clang/Basic/OperatorKinds.def"
2003
2004    case tok::l_paren: {
2005      // Consume the '(' and ')'.
2006      BalancedDelimiterTracker T(*this, tok::l_paren);
2007      T.consumeOpen();
2008      T.consumeClose();
2009      if (T.getCloseLocation().isInvalid())
2010        return true;
2011
2012      SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2013      SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2014      Op = OO_Call;
2015      break;
2016    }
2017
2018    case tok::l_square: {
2019      // Consume the '[' and ']'.
2020      BalancedDelimiterTracker T(*this, tok::l_square);
2021      T.consumeOpen();
2022      T.consumeClose();
2023      if (T.getCloseLocation().isInvalid())
2024        return true;
2025
2026      SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2027      SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2028      Op = OO_Subscript;
2029      break;
2030    }
2031
2032    case tok::code_completion: {
2033      // Code completion for the operator name.
2034      Actions.CodeCompleteOperatorName(getCurScope());
2035      cutOffParsing();
2036      // Don't try to parse any further.
2037      return true;
2038    }
2039
2040    default:
2041      break;
2042  }
2043
2044  if (Op != OO_None) {
2045    // We have parsed an operator-function-id.
2046    Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2047    return false;
2048  }
2049
2050  // Parse a literal-operator-id.
2051  //
2052  //   literal-operator-id: C++11 [over.literal]
2053  //     operator string-literal identifier
2054  //     operator user-defined-string-literal
2055
2056  if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2057    Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2058
2059    SourceLocation DiagLoc;
2060    unsigned DiagId = 0;
2061
2062    // We're past translation phase 6, so perform string literal concatenation
2063    // before checking for "".
2064    SmallVector<Token, 4> Toks;
2065    SmallVector<SourceLocation, 4> TokLocs;
2066    while (isTokenStringLiteral()) {
2067      if (!Tok.is(tok::string_literal) && !DiagId) {
2068        // C++11 [over.literal]p1:
2069        //   The string-literal or user-defined-string-literal in a
2070        //   literal-operator-id shall have no encoding-prefix [...].
2071        DiagLoc = Tok.getLocation();
2072        DiagId = diag::err_literal_operator_string_prefix;
2073      }
2074      Toks.push_back(Tok);
2075      TokLocs.push_back(ConsumeStringToken());
2076    }
2077
2078    StringLiteralParser Literal(Toks.data(), Toks.size(), PP);
2079    if (Literal.hadError)
2080      return true;
2081
2082    // Grab the literal operator's suffix, which will be either the next token
2083    // or a ud-suffix from the string literal.
2084    IdentifierInfo *II = 0;
2085    SourceLocation SuffixLoc;
2086    if (!Literal.getUDSuffix().empty()) {
2087      II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2088      SuffixLoc =
2089        Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2090                                       Literal.getUDSuffixOffset(),
2091                                       PP.getSourceManager(), getLangOpts());
2092    } else if (Tok.is(tok::identifier)) {
2093      II = Tok.getIdentifierInfo();
2094      SuffixLoc = ConsumeToken();
2095      TokLocs.push_back(SuffixLoc);
2096    } else {
2097      Diag(Tok.getLocation(), diag::err_expected_ident);
2098      return true;
2099    }
2100
2101    // The string literal must be empty.
2102    if (!Literal.GetString().empty() || Literal.Pascal) {
2103      // C++11 [over.literal]p1:
2104      //   The string-literal or user-defined-string-literal in a
2105      //   literal-operator-id shall [...] contain no characters
2106      //   other than the implicit terminating '\0'.
2107      DiagLoc = TokLocs.front();
2108      DiagId = diag::err_literal_operator_string_not_empty;
2109    }
2110
2111    if (DiagId) {
2112      // This isn't a valid literal-operator-id, but we think we know
2113      // what the user meant. Tell them what they should have written.
2114      SmallString<32> Str;
2115      Str += "\"\" ";
2116      Str += II->getName();
2117      Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2118          SourceRange(TokLocs.front(), TokLocs.back()), Str);
2119    }
2120
2121    Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2122    return false;
2123  }
2124
2125  // Parse a conversion-function-id.
2126  //
2127  //   conversion-function-id: [C++ 12.3.2]
2128  //     operator conversion-type-id
2129  //
2130  //   conversion-type-id:
2131  //     type-specifier-seq conversion-declarator[opt]
2132  //
2133  //   conversion-declarator:
2134  //     ptr-operator conversion-declarator[opt]
2135
2136  // Parse the type-specifier-seq.
2137  DeclSpec DS(AttrFactory);
2138  if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2139    return true;
2140
2141  // Parse the conversion-declarator, which is merely a sequence of
2142  // ptr-operators.
2143  Declarator D(DS, Declarator::ConversionIdContext);
2144  ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
2145
2146  // Finish up the type.
2147  TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2148  if (Ty.isInvalid())
2149    return true;
2150
2151  // Note that this is a conversion-function-id.
2152  Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2153                                 D.getSourceRange().getEnd());
2154  return false;
2155}
2156
2157/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2158/// name of an entity.
2159///
2160/// \code
2161///       unqualified-id: [C++ expr.prim.general]
2162///         identifier
2163///         operator-function-id
2164///         conversion-function-id
2165/// [C++0x] literal-operator-id [TODO]
2166///         ~ class-name
2167///         template-id
2168///
2169/// \endcode
2170///
2171/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2172/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2173///
2174/// \param EnteringContext whether we are entering the scope of the
2175/// nested-name-specifier.
2176///
2177/// \param AllowDestructorName whether we allow parsing of a destructor name.
2178///
2179/// \param AllowConstructorName whether we allow parsing a constructor name.
2180///
2181/// \param ObjectType if this unqualified-id occurs within a member access
2182/// expression, the type of the base object whose member is being accessed.
2183///
2184/// \param Result on a successful parse, contains the parsed unqualified-id.
2185///
2186/// \returns true if parsing fails, false otherwise.
2187bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2188                                bool AllowDestructorName,
2189                                bool AllowConstructorName,
2190                                ParsedType ObjectType,
2191                                SourceLocation& TemplateKWLoc,
2192                                UnqualifiedId &Result) {
2193
2194  // Handle 'A::template B'. This is for template-ids which have not
2195  // already been annotated by ParseOptionalCXXScopeSpecifier().
2196  bool TemplateSpecified = false;
2197  if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2198      (ObjectType || SS.isSet())) {
2199    TemplateSpecified = true;
2200    TemplateKWLoc = ConsumeToken();
2201  }
2202
2203  // unqualified-id:
2204  //   identifier
2205  //   template-id (when it hasn't already been annotated)
2206  if (Tok.is(tok::identifier)) {
2207    // Consume the identifier.
2208    IdentifierInfo *Id = Tok.getIdentifierInfo();
2209    SourceLocation IdLoc = ConsumeToken();
2210
2211    if (!getLangOpts().CPlusPlus) {
2212      // If we're not in C++, only identifiers matter. Record the
2213      // identifier and return.
2214      Result.setIdentifier(Id, IdLoc);
2215      return false;
2216    }
2217
2218    if (AllowConstructorName &&
2219        Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2220      // We have parsed a constructor name.
2221      ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2222                                          &SS, false, false,
2223                                          ParsedType(),
2224                                          /*IsCtorOrDtorName=*/true,
2225                                          /*NonTrivialTypeSourceInfo=*/true);
2226      Result.setConstructorName(Ty, IdLoc, IdLoc);
2227    } else {
2228      // We have parsed an identifier.
2229      Result.setIdentifier(Id, IdLoc);
2230    }
2231
2232    // If the next token is a '<', we may have a template.
2233    if (TemplateSpecified || Tok.is(tok::less))
2234      return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2235                                          EnteringContext, ObjectType,
2236                                          Result, TemplateSpecified);
2237
2238    return false;
2239  }
2240
2241  // unqualified-id:
2242  //   template-id (already parsed and annotated)
2243  if (Tok.is(tok::annot_template_id)) {
2244    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2245
2246    // If the template-name names the current class, then this is a constructor
2247    if (AllowConstructorName && TemplateId->Name &&
2248        Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2249      if (SS.isSet()) {
2250        // C++ [class.qual]p2 specifies that a qualified template-name
2251        // is taken as the constructor name where a constructor can be
2252        // declared. Thus, the template arguments are extraneous, so
2253        // complain about them and remove them entirely.
2254        Diag(TemplateId->TemplateNameLoc,
2255             diag::err_out_of_line_constructor_template_id)
2256          << TemplateId->Name
2257          << FixItHint::CreateRemoval(
2258                    SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2259        ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2260                                            TemplateId->TemplateNameLoc,
2261                                            getCurScope(),
2262                                            &SS, false, false,
2263                                            ParsedType(),
2264                                            /*IsCtorOrDtorName=*/true,
2265                                            /*NontrivialTypeSourceInfo=*/true);
2266        Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2267                                  TemplateId->RAngleLoc);
2268        ConsumeToken();
2269        return false;
2270      }
2271
2272      Result.setConstructorTemplateId(TemplateId);
2273      ConsumeToken();
2274      return false;
2275    }
2276
2277    // We have already parsed a template-id; consume the annotation token as
2278    // our unqualified-id.
2279    Result.setTemplateId(TemplateId);
2280    TemplateKWLoc = TemplateId->TemplateKWLoc;
2281    ConsumeToken();
2282    return false;
2283  }
2284
2285  // unqualified-id:
2286  //   operator-function-id
2287  //   conversion-function-id
2288  if (Tok.is(tok::kw_operator)) {
2289    if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2290      return true;
2291
2292    // If we have an operator-function-id or a literal-operator-id and the next
2293    // token is a '<', we may have a
2294    //
2295    //   template-id:
2296    //     operator-function-id < template-argument-list[opt] >
2297    if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2298         Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2299        (TemplateSpecified || Tok.is(tok::less)))
2300      return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2301                                          0, SourceLocation(),
2302                                          EnteringContext, ObjectType,
2303                                          Result, TemplateSpecified);
2304
2305    return false;
2306  }
2307
2308  if (getLangOpts().CPlusPlus &&
2309      (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2310    // C++ [expr.unary.op]p10:
2311    //   There is an ambiguity in the unary-expression ~X(), where X is a
2312    //   class-name. The ambiguity is resolved in favor of treating ~ as a
2313    //    unary complement rather than treating ~X as referring to a destructor.
2314
2315    // Parse the '~'.
2316    SourceLocation TildeLoc = ConsumeToken();
2317
2318    if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2319      DeclSpec DS(AttrFactory);
2320      SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2321      if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2322        Result.setDestructorName(TildeLoc, Type, EndLoc);
2323        return false;
2324      }
2325      return true;
2326    }
2327
2328    // Parse the class-name.
2329    if (Tok.isNot(tok::identifier)) {
2330      Diag(Tok, diag::err_destructor_tilde_identifier);
2331      return true;
2332    }
2333
2334    // Parse the class-name (or template-name in a simple-template-id).
2335    IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2336    SourceLocation ClassNameLoc = ConsumeToken();
2337
2338    if (TemplateSpecified || Tok.is(tok::less)) {
2339      Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
2340      return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2341                                          ClassName, ClassNameLoc,
2342                                          EnteringContext, ObjectType,
2343                                          Result, TemplateSpecified);
2344    }
2345
2346    // Note that this is a destructor name.
2347    ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2348                                              ClassNameLoc, getCurScope(),
2349                                              SS, ObjectType,
2350                                              EnteringContext);
2351    if (!Ty)
2352      return true;
2353
2354    Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2355    return false;
2356  }
2357
2358  Diag(Tok, diag::err_expected_unqualified_id)
2359    << getLangOpts().CPlusPlus;
2360  return true;
2361}
2362
2363/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2364/// memory in a typesafe manner and call constructors.
2365///
2366/// This method is called to parse the new expression after the optional :: has
2367/// been already parsed.  If the :: was present, "UseGlobal" is true and "Start"
2368/// is its location.  Otherwise, "Start" is the location of the 'new' token.
2369///
2370///        new-expression:
2371///                   '::'[opt] 'new' new-placement[opt] new-type-id
2372///                                     new-initializer[opt]
2373///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2374///                                     new-initializer[opt]
2375///
2376///        new-placement:
2377///                   '(' expression-list ')'
2378///
2379///        new-type-id:
2380///                   type-specifier-seq new-declarator[opt]
2381/// [GNU]             attributes type-specifier-seq new-declarator[opt]
2382///
2383///        new-declarator:
2384///                   ptr-operator new-declarator[opt]
2385///                   direct-new-declarator
2386///
2387///        new-initializer:
2388///                   '(' expression-list[opt] ')'
2389/// [C++0x]           braced-init-list
2390///
2391ExprResult
2392Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2393  assert(Tok.is(tok::kw_new) && "expected 'new' token");
2394  ConsumeToken();   // Consume 'new'
2395
2396  // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2397  // second form of new-expression. It can't be a new-type-id.
2398
2399  ExprVector PlacementArgs;
2400  SourceLocation PlacementLParen, PlacementRParen;
2401
2402  SourceRange TypeIdParens;
2403  DeclSpec DS(AttrFactory);
2404  Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2405  if (Tok.is(tok::l_paren)) {
2406    // If it turns out to be a placement, we change the type location.
2407    BalancedDelimiterTracker T(*this, tok::l_paren);
2408    T.consumeOpen();
2409    PlacementLParen = T.getOpenLocation();
2410    if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2411      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2412      return ExprError();
2413    }
2414
2415    T.consumeClose();
2416    PlacementRParen = T.getCloseLocation();
2417    if (PlacementRParen.isInvalid()) {
2418      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2419      return ExprError();
2420    }
2421
2422    if (PlacementArgs.empty()) {
2423      // Reset the placement locations. There was no placement.
2424      TypeIdParens = T.getRange();
2425      PlacementLParen = PlacementRParen = SourceLocation();
2426    } else {
2427      // We still need the type.
2428      if (Tok.is(tok::l_paren)) {
2429        BalancedDelimiterTracker T(*this, tok::l_paren);
2430        T.consumeOpen();
2431        MaybeParseGNUAttributes(DeclaratorInfo);
2432        ParseSpecifierQualifierList(DS);
2433        DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2434        ParseDeclarator(DeclaratorInfo);
2435        T.consumeClose();
2436        TypeIdParens = T.getRange();
2437      } else {
2438        MaybeParseGNUAttributes(DeclaratorInfo);
2439        if (ParseCXXTypeSpecifierSeq(DS))
2440          DeclaratorInfo.setInvalidType(true);
2441        else {
2442          DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2443          ParseDeclaratorInternal(DeclaratorInfo,
2444                                  &Parser::ParseDirectNewDeclarator);
2445        }
2446      }
2447    }
2448  } else {
2449    // A new-type-id is a simplified type-id, where essentially the
2450    // direct-declarator is replaced by a direct-new-declarator.
2451    MaybeParseGNUAttributes(DeclaratorInfo);
2452    if (ParseCXXTypeSpecifierSeq(DS))
2453      DeclaratorInfo.setInvalidType(true);
2454    else {
2455      DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2456      ParseDeclaratorInternal(DeclaratorInfo,
2457                              &Parser::ParseDirectNewDeclarator);
2458    }
2459  }
2460  if (DeclaratorInfo.isInvalidType()) {
2461    SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2462    return ExprError();
2463  }
2464
2465  ExprResult Initializer;
2466
2467  if (Tok.is(tok::l_paren)) {
2468    SourceLocation ConstructorLParen, ConstructorRParen;
2469    ExprVector ConstructorArgs;
2470    BalancedDelimiterTracker T(*this, tok::l_paren);
2471    T.consumeOpen();
2472    ConstructorLParen = T.getOpenLocation();
2473    if (Tok.isNot(tok::r_paren)) {
2474      CommaLocsTy CommaLocs;
2475      if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2476        SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2477        return ExprError();
2478      }
2479    }
2480    T.consumeClose();
2481    ConstructorRParen = T.getCloseLocation();
2482    if (ConstructorRParen.isInvalid()) {
2483      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2484      return ExprError();
2485    }
2486    Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2487                                             ConstructorRParen,
2488                                             ConstructorArgs);
2489  } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2490    Diag(Tok.getLocation(),
2491         diag::warn_cxx98_compat_generalized_initializer_lists);
2492    Initializer = ParseBraceInitializer();
2493  }
2494  if (Initializer.isInvalid())
2495    return Initializer;
2496
2497  return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2498                             PlacementArgs, PlacementRParen,
2499                             TypeIdParens, DeclaratorInfo, Initializer.take());
2500}
2501
2502/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2503/// passed to ParseDeclaratorInternal.
2504///
2505///        direct-new-declarator:
2506///                   '[' expression ']'
2507///                   direct-new-declarator '[' constant-expression ']'
2508///
2509void Parser::ParseDirectNewDeclarator(Declarator &D) {
2510  // Parse the array dimensions.
2511  bool first = true;
2512  while (Tok.is(tok::l_square)) {
2513    // An array-size expression can't start with a lambda.
2514    if (CheckProhibitedCXX11Attribute())
2515      continue;
2516
2517    BalancedDelimiterTracker T(*this, tok::l_square);
2518    T.consumeOpen();
2519
2520    ExprResult Size(first ? ParseExpression()
2521                                : ParseConstantExpression());
2522    if (Size.isInvalid()) {
2523      // Recover
2524      SkipUntil(tok::r_square);
2525      return;
2526    }
2527    first = false;
2528
2529    T.consumeClose();
2530
2531    // Attributes here appertain to the array type. C++11 [expr.new]p5.
2532    ParsedAttributes Attrs(AttrFactory);
2533    MaybeParseCXX11Attributes(Attrs);
2534
2535    D.AddTypeInfo(DeclaratorChunk::getArray(0,
2536                                            /*static=*/false, /*star=*/false,
2537                                            Size.release(),
2538                                            T.getOpenLocation(),
2539                                            T.getCloseLocation()),
2540                  Attrs, T.getCloseLocation());
2541
2542    if (T.getCloseLocation().isInvalid())
2543      return;
2544  }
2545}
2546
2547/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2548/// This ambiguity appears in the syntax of the C++ new operator.
2549///
2550///        new-expression:
2551///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2552///                                     new-initializer[opt]
2553///
2554///        new-placement:
2555///                   '(' expression-list ')'
2556///
2557bool Parser::ParseExpressionListOrTypeId(
2558                                   SmallVectorImpl<Expr*> &PlacementArgs,
2559                                         Declarator &D) {
2560  // The '(' was already consumed.
2561  if (isTypeIdInParens()) {
2562    ParseSpecifierQualifierList(D.getMutableDeclSpec());
2563    D.SetSourceRange(D.getDeclSpec().getSourceRange());
2564    ParseDeclarator(D);
2565    return D.isInvalidType();
2566  }
2567
2568  // It's not a type, it has to be an expression list.
2569  // Discard the comma locations - ActOnCXXNew has enough parameters.
2570  CommaLocsTy CommaLocs;
2571  return ParseExpressionList(PlacementArgs, CommaLocs);
2572}
2573
2574/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2575/// to free memory allocated by new.
2576///
2577/// This method is called to parse the 'delete' expression after the optional
2578/// '::' has been already parsed.  If the '::' was present, "UseGlobal" is true
2579/// and "Start" is its location.  Otherwise, "Start" is the location of the
2580/// 'delete' token.
2581///
2582///        delete-expression:
2583///                   '::'[opt] 'delete' cast-expression
2584///                   '::'[opt] 'delete' '[' ']' cast-expression
2585ExprResult
2586Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2587  assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2588  ConsumeToken(); // Consume 'delete'
2589
2590  // Array delete?
2591  bool ArrayDelete = false;
2592  if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2593    // C++11 [expr.delete]p1:
2594    //   Whenever the delete keyword is followed by empty square brackets, it
2595    //   shall be interpreted as [array delete].
2596    //   [Footnote: A lambda expression with a lambda-introducer that consists
2597    //              of empty square brackets can follow the delete keyword if
2598    //              the lambda expression is enclosed in parentheses.]
2599    // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2600    //        lambda-introducer.
2601    ArrayDelete = true;
2602    BalancedDelimiterTracker T(*this, tok::l_square);
2603
2604    T.consumeOpen();
2605    T.consumeClose();
2606    if (T.getCloseLocation().isInvalid())
2607      return ExprError();
2608  }
2609
2610  ExprResult Operand(ParseCastExpression(false));
2611  if (Operand.isInvalid())
2612    return Operand;
2613
2614  return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
2615}
2616
2617static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
2618  switch(kind) {
2619  default: llvm_unreachable("Not a known unary type trait.");
2620  case tok::kw___has_nothrow_assign:      return UTT_HasNothrowAssign;
2621  case tok::kw___has_nothrow_move_assign: return UTT_HasNothrowMoveAssign;
2622  case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
2623  case tok::kw___has_nothrow_copy:           return UTT_HasNothrowCopy;
2624  case tok::kw___has_trivial_assign:      return UTT_HasTrivialAssign;
2625  case tok::kw___has_trivial_move_assign: return UTT_HasTrivialMoveAssign;
2626  case tok::kw___has_trivial_constructor:
2627                                    return UTT_HasTrivialDefaultConstructor;
2628  case tok::kw___has_trivial_move_constructor:
2629                                    return UTT_HasTrivialMoveConstructor;
2630  case tok::kw___has_trivial_copy:           return UTT_HasTrivialCopy;
2631  case tok::kw___has_trivial_destructor:  return UTT_HasTrivialDestructor;
2632  case tok::kw___has_virtual_destructor:  return UTT_HasVirtualDestructor;
2633  case tok::kw___is_abstract:             return UTT_IsAbstract;
2634  case tok::kw___is_arithmetic:              return UTT_IsArithmetic;
2635  case tok::kw___is_array:                   return UTT_IsArray;
2636  case tok::kw___is_class:                return UTT_IsClass;
2637  case tok::kw___is_complete_type:           return UTT_IsCompleteType;
2638  case tok::kw___is_compound:                return UTT_IsCompound;
2639  case tok::kw___is_const:                   return UTT_IsConst;
2640  case tok::kw___is_empty:                return UTT_IsEmpty;
2641  case tok::kw___is_enum:                 return UTT_IsEnum;
2642  case tok::kw___is_final:                 return UTT_IsFinal;
2643  case tok::kw___is_floating_point:          return UTT_IsFloatingPoint;
2644  case tok::kw___is_function:                return UTT_IsFunction;
2645  case tok::kw___is_fundamental:             return UTT_IsFundamental;
2646  case tok::kw___is_integral:                return UTT_IsIntegral;
2647  case tok::kw___is_interface_class:         return UTT_IsInterfaceClass;
2648  case tok::kw___is_lvalue_reference:        return UTT_IsLvalueReference;
2649  case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer;
2650  case tok::kw___is_member_object_pointer:   return UTT_IsMemberObjectPointer;
2651  case tok::kw___is_member_pointer:          return UTT_IsMemberPointer;
2652  case tok::kw___is_object:                  return UTT_IsObject;
2653  case tok::kw___is_literal:              return UTT_IsLiteral;
2654  case tok::kw___is_literal_type:         return UTT_IsLiteral;
2655  case tok::kw___is_pod:                  return UTT_IsPOD;
2656  case tok::kw___is_pointer:                 return UTT_IsPointer;
2657  case tok::kw___is_polymorphic:          return UTT_IsPolymorphic;
2658  case tok::kw___is_reference:               return UTT_IsReference;
2659  case tok::kw___is_rvalue_reference:        return UTT_IsRvalueReference;
2660  case tok::kw___is_scalar:                  return UTT_IsScalar;
2661  case tok::kw___is_signed:                  return UTT_IsSigned;
2662  case tok::kw___is_standard_layout:         return UTT_IsStandardLayout;
2663  case tok::kw___is_trivial:                 return UTT_IsTrivial;
2664  case tok::kw___is_trivially_copyable:      return UTT_IsTriviallyCopyable;
2665  case tok::kw___is_union:                return UTT_IsUnion;
2666  case tok::kw___is_unsigned:                return UTT_IsUnsigned;
2667  case tok::kw___is_void:                    return UTT_IsVoid;
2668  case tok::kw___is_volatile:                return UTT_IsVolatile;
2669  }
2670}
2671
2672static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) {
2673  switch(kind) {
2674  default: llvm_unreachable("Not a known binary type trait");
2675  case tok::kw___is_base_of:                 return BTT_IsBaseOf;
2676  case tok::kw___is_convertible:             return BTT_IsConvertible;
2677  case tok::kw___is_same:                    return BTT_IsSame;
2678  case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible;
2679  case tok::kw___is_convertible_to:          return BTT_IsConvertibleTo;
2680  case tok::kw___is_trivially_assignable:    return BTT_IsTriviallyAssignable;
2681  }
2682}
2683
2684static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2685  switch (kind) {
2686  default: llvm_unreachable("Not a known type trait");
2687  case tok::kw___is_trivially_constructible:
2688    return TT_IsTriviallyConstructible;
2689  }
2690}
2691
2692static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2693  switch(kind) {
2694  default: llvm_unreachable("Not a known binary type trait");
2695  case tok::kw___array_rank:                 return ATT_ArrayRank;
2696  case tok::kw___array_extent:               return ATT_ArrayExtent;
2697  }
2698}
2699
2700static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2701  switch(kind) {
2702  default: llvm_unreachable("Not a known unary expression trait.");
2703  case tok::kw___is_lvalue_expr:             return ET_IsLValueExpr;
2704  case tok::kw___is_rvalue_expr:             return ET_IsRValueExpr;
2705  }
2706}
2707
2708/// ParseUnaryTypeTrait - Parse the built-in unary type-trait
2709/// pseudo-functions that allow implementation of the TR1/C++0x type traits
2710/// templates.
2711///
2712///       primary-expression:
2713/// [GNU]             unary-type-trait '(' type-id ')'
2714///
2715ExprResult Parser::ParseUnaryTypeTrait() {
2716  UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
2717  SourceLocation Loc = ConsumeToken();
2718
2719  BalancedDelimiterTracker T(*this, tok::l_paren);
2720  if (T.expectAndConsume(diag::err_expected_lparen))
2721    return ExprError();
2722
2723  // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
2724  // there will be cryptic errors about mismatched parentheses and missing
2725  // specifiers.
2726  TypeResult Ty = ParseTypeName();
2727
2728  T.consumeClose();
2729
2730  if (Ty.isInvalid())
2731    return ExprError();
2732
2733  return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), T.getCloseLocation());
2734}
2735
2736/// ParseBinaryTypeTrait - Parse the built-in binary type-trait
2737/// pseudo-functions that allow implementation of the TR1/C++0x type traits
2738/// templates.
2739///
2740///       primary-expression:
2741/// [GNU]             binary-type-trait '(' type-id ',' type-id ')'
2742///
2743ExprResult Parser::ParseBinaryTypeTrait() {
2744  BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind());
2745  SourceLocation Loc = ConsumeToken();
2746
2747  BalancedDelimiterTracker T(*this, tok::l_paren);
2748  if (T.expectAndConsume(diag::err_expected_lparen))
2749    return ExprError();
2750
2751  TypeResult LhsTy = ParseTypeName();
2752  if (LhsTy.isInvalid()) {
2753    SkipUntil(tok::r_paren);
2754    return ExprError();
2755  }
2756
2757  if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2758    SkipUntil(tok::r_paren);
2759    return ExprError();
2760  }
2761
2762  TypeResult RhsTy = ParseTypeName();
2763  if (RhsTy.isInvalid()) {
2764    SkipUntil(tok::r_paren);
2765    return ExprError();
2766  }
2767
2768  T.consumeClose();
2769
2770  return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(),
2771                                      T.getCloseLocation());
2772}
2773
2774/// \brief Parse the built-in type-trait pseudo-functions that allow
2775/// implementation of the TR1/C++11 type traits templates.
2776///
2777///       primary-expression:
2778///          type-trait '(' type-id-seq ')'
2779///
2780///       type-id-seq:
2781///          type-id ...[opt] type-id-seq[opt]
2782///
2783ExprResult Parser::ParseTypeTrait() {
2784  TypeTrait Kind = TypeTraitFromTokKind(Tok.getKind());
2785  SourceLocation Loc = ConsumeToken();
2786
2787  BalancedDelimiterTracker Parens(*this, tok::l_paren);
2788  if (Parens.expectAndConsume(diag::err_expected_lparen))
2789    return ExprError();
2790
2791  SmallVector<ParsedType, 2> Args;
2792  do {
2793    // Parse the next type.
2794    TypeResult Ty = ParseTypeName();
2795    if (Ty.isInvalid()) {
2796      Parens.skipToEnd();
2797      return ExprError();
2798    }
2799
2800    // Parse the ellipsis, if present.
2801    if (Tok.is(tok::ellipsis)) {
2802      Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2803      if (Ty.isInvalid()) {
2804        Parens.skipToEnd();
2805        return ExprError();
2806      }
2807    }
2808
2809    // Add this type to the list of arguments.
2810    Args.push_back(Ty.get());
2811
2812    if (Tok.is(tok::comma)) {
2813      ConsumeToken();
2814      continue;
2815    }
2816
2817    break;
2818  } while (true);
2819
2820  if (Parens.consumeClose())
2821    return ExprError();
2822
2823  return Actions.ActOnTypeTrait(Kind, Loc, Args, Parens.getCloseLocation());
2824}
2825
2826/// ParseArrayTypeTrait - Parse the built-in array type-trait
2827/// pseudo-functions.
2828///
2829///       primary-expression:
2830/// [Embarcadero]     '__array_rank' '(' type-id ')'
2831/// [Embarcadero]     '__array_extent' '(' type-id ',' expression ')'
2832///
2833ExprResult Parser::ParseArrayTypeTrait() {
2834  ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2835  SourceLocation Loc = ConsumeToken();
2836
2837  BalancedDelimiterTracker T(*this, tok::l_paren);
2838  if (T.expectAndConsume(diag::err_expected_lparen))
2839    return ExprError();
2840
2841  TypeResult Ty = ParseTypeName();
2842  if (Ty.isInvalid()) {
2843    SkipUntil(tok::comma);
2844    SkipUntil(tok::r_paren);
2845    return ExprError();
2846  }
2847
2848  switch (ATT) {
2849  case ATT_ArrayRank: {
2850    T.consumeClose();
2851    return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL,
2852                                       T.getCloseLocation());
2853  }
2854  case ATT_ArrayExtent: {
2855    if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2856      SkipUntil(tok::r_paren);
2857      return ExprError();
2858    }
2859
2860    ExprResult DimExpr = ParseExpression();
2861    T.consumeClose();
2862
2863    return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2864                                       T.getCloseLocation());
2865  }
2866  }
2867  llvm_unreachable("Invalid ArrayTypeTrait!");
2868}
2869
2870/// ParseExpressionTrait - Parse built-in expression-trait
2871/// pseudo-functions like __is_lvalue_expr( xxx ).
2872///
2873///       primary-expression:
2874/// [Embarcadero]     expression-trait '(' expression ')'
2875///
2876ExprResult Parser::ParseExpressionTrait() {
2877  ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2878  SourceLocation Loc = ConsumeToken();
2879
2880  BalancedDelimiterTracker T(*this, tok::l_paren);
2881  if (T.expectAndConsume(diag::err_expected_lparen))
2882    return ExprError();
2883
2884  ExprResult Expr = ParseExpression();
2885
2886  T.consumeClose();
2887
2888  return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2889                                      T.getCloseLocation());
2890}
2891
2892
2893/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2894/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2895/// based on the context past the parens.
2896ExprResult
2897Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
2898                                         ParsedType &CastTy,
2899                                         BalancedDelimiterTracker &Tracker) {
2900  assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
2901  assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2902  assert(isTypeIdInParens() && "Not a type-id!");
2903
2904  ExprResult Result(true);
2905  CastTy = ParsedType();
2906
2907  // We need to disambiguate a very ugly part of the C++ syntax:
2908  //
2909  // (T())x;  - type-id
2910  // (T())*x; - type-id
2911  // (T())/x; - expression
2912  // (T());   - expression
2913  //
2914  // The bad news is that we cannot use the specialized tentative parser, since
2915  // it can only verify that the thing inside the parens can be parsed as
2916  // type-id, it is not useful for determining the context past the parens.
2917  //
2918  // The good news is that the parser can disambiguate this part without
2919  // making any unnecessary Action calls.
2920  //
2921  // It uses a scheme similar to parsing inline methods. The parenthesized
2922  // tokens are cached, the context that follows is determined (possibly by
2923  // parsing a cast-expression), and then we re-introduce the cached tokens
2924  // into the token stream and parse them appropriately.
2925
2926  ParenParseOption ParseAs;
2927  CachedTokens Toks;
2928
2929  // Store the tokens of the parentheses. We will parse them after we determine
2930  // the context that follows them.
2931  if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
2932    // We didn't find the ')' we expected.
2933    Tracker.consumeClose();
2934    return ExprError();
2935  }
2936
2937  if (Tok.is(tok::l_brace)) {
2938    ParseAs = CompoundLiteral;
2939  } else {
2940    bool NotCastExpr;
2941    // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2942    if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2943      NotCastExpr = true;
2944    } else {
2945      // Try parsing the cast-expression that may follow.
2946      // If it is not a cast-expression, NotCastExpr will be true and no token
2947      // will be consumed.
2948      Result = ParseCastExpression(false/*isUnaryExpression*/,
2949                                   false/*isAddressofOperand*/,
2950                                   NotCastExpr,
2951                                   // type-id has priority.
2952                                   IsTypeCast);
2953    }
2954
2955    // If we parsed a cast-expression, it's really a type-id, otherwise it's
2956    // an expression.
2957    ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
2958  }
2959
2960  // The current token should go after the cached tokens.
2961  Toks.push_back(Tok);
2962  // Re-enter the stored parenthesized tokens into the token stream, so we may
2963  // parse them now.
2964  PP.EnterTokenStream(Toks.data(), Toks.size(),
2965                      true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2966  // Drop the current token and bring the first cached one. It's the same token
2967  // as when we entered this function.
2968  ConsumeAnyToken();
2969
2970  if (ParseAs >= CompoundLiteral) {
2971    // Parse the type declarator.
2972    DeclSpec DS(AttrFactory);
2973    ParseSpecifierQualifierList(DS);
2974    Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2975    ParseDeclarator(DeclaratorInfo);
2976
2977    // Match the ')'.
2978    Tracker.consumeClose();
2979
2980    if (ParseAs == CompoundLiteral) {
2981      ExprType = CompoundLiteral;
2982      TypeResult Ty = ParseTypeName();
2983       return ParseCompoundLiteralExpression(Ty.get(),
2984                                            Tracker.getOpenLocation(),
2985                                            Tracker.getCloseLocation());
2986    }
2987
2988    // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
2989    assert(ParseAs == CastExpr);
2990
2991    if (DeclaratorInfo.isInvalidType())
2992      return ExprError();
2993
2994    // Result is what ParseCastExpression returned earlier.
2995    if (!Result.isInvalid())
2996      Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
2997                                    DeclaratorInfo, CastTy,
2998                                    Tracker.getCloseLocation(), Result.take());
2999    return Result;
3000  }
3001
3002  // Not a compound literal, and not followed by a cast-expression.
3003  assert(ParseAs == SimpleExpr);
3004
3005  ExprType = SimpleExpr;
3006  Result = ParseExpression();
3007  if (!Result.isInvalid() && Tok.is(tok::r_paren))
3008    Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3009                                    Tok.getLocation(), Result.take());
3010
3011  // Match the ')'.
3012  if (Result.isInvalid()) {
3013    SkipUntil(tok::r_paren);
3014    return ExprError();
3015  }
3016
3017  Tracker.consumeClose();
3018  return Result;
3019}
3020