ParseExprCXX.cpp revision c0012d65f8a63b0ad0cd5053780322c44a65af3f
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/ParseDiagnostic.h"
15#include "clang/Parse/Parser.h"
16#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Template.h"
18#include "llvm/Support/ErrorHandling.h"
19
20using namespace clang;
21
22/// \brief Parse global scope or nested-name-specifier if present.
23///
24/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
25/// may be preceded by '::'). Note that this routine will not parse ::new or
26/// ::delete; it will just leave them in the token stream.
27///
28///       '::'[opt] nested-name-specifier
29///       '::'
30///
31///       nested-name-specifier:
32///         type-name '::'
33///         namespace-name '::'
34///         nested-name-specifier identifier '::'
35///         nested-name-specifier 'template'[opt] simple-template-id '::'
36///
37///
38/// \param SS the scope specifier that will be set to the parsed
39/// nested-name-specifier (or empty)
40///
41/// \param ObjectType if this nested-name-specifier is being parsed following
42/// the "." or "->" of a member access expression, this parameter provides the
43/// type of the object whose members are being accessed.
44///
45/// \param EnteringContext whether we will be entering into the context of
46/// the nested-name-specifier after parsing it.
47///
48/// \param MayBePseudoDestructor When non-NULL, points to a flag that
49/// indicates whether this nested-name-specifier may be part of a
50/// pseudo-destructor name. In this case, the flag will be set false
51/// if we don't actually end up parsing a destructor name. Moreorover,
52/// if we do end up determining that we are parsing a destructor name,
53/// the last component of the nested-name-specifier is not parsed as
54/// part of the scope specifier.
55
56/// member access expression, e.g., the \p T:: in \p p->T::m.
57///
58/// \returns true if there was an error parsing a scope specifier
59bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
60                                            Action::TypeTy *ObjectType,
61                                            bool EnteringContext,
62                                            bool *MayBePseudoDestructor) {
63  assert(getLang().CPlusPlus &&
64         "Call sites of this function should be guarded by checking for C++");
65
66  if (Tok.is(tok::annot_cxxscope)) {
67    SS.setScopeRep(Tok.getAnnotationValue());
68    SS.setRange(Tok.getAnnotationRange());
69    ConsumeToken();
70    return false;
71  }
72
73  bool HasScopeSpecifier = false;
74
75  if (Tok.is(tok::coloncolon)) {
76    // ::new and ::delete aren't nested-name-specifiers.
77    tok::TokenKind NextKind = NextToken().getKind();
78    if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
79      return false;
80
81    // '::' - Global scope qualifier.
82    SourceLocation CCLoc = ConsumeToken();
83    SS.setBeginLoc(CCLoc);
84    SS.setScopeRep(Actions.ActOnCXXGlobalScopeSpecifier(CurScope, CCLoc));
85    SS.setEndLoc(CCLoc);
86    HasScopeSpecifier = true;
87  }
88
89  bool CheckForDestructor = false;
90  if (MayBePseudoDestructor && *MayBePseudoDestructor) {
91    CheckForDestructor = true;
92    *MayBePseudoDestructor = false;
93  }
94
95  while (true) {
96    if (HasScopeSpecifier) {
97      // C++ [basic.lookup.classref]p5:
98      //   If the qualified-id has the form
99      //
100      //       ::class-name-or-namespace-name::...
101      //
102      //   the class-name-or-namespace-name is looked up in global scope as a
103      //   class-name or namespace-name.
104      //
105      // To implement this, we clear out the object type as soon as we've
106      // seen a leading '::' or part of a nested-name-specifier.
107      ObjectType = 0;
108
109      if (Tok.is(tok::code_completion)) {
110        // Code completion for a nested-name-specifier, where the code
111        // code completion token follows the '::'.
112        Actions.CodeCompleteQualifiedId(CurScope, SS, EnteringContext);
113        ConsumeCodeCompletionToken();
114      }
115    }
116
117    // nested-name-specifier:
118    //   nested-name-specifier 'template'[opt] simple-template-id '::'
119
120    // Parse the optional 'template' keyword, then make sure we have
121    // 'identifier <' after it.
122    if (Tok.is(tok::kw_template)) {
123      // If we don't have a scope specifier or an object type, this isn't a
124      // nested-name-specifier, since they aren't allowed to start with
125      // 'template'.
126      if (!HasScopeSpecifier && !ObjectType)
127        break;
128
129      TentativeParsingAction TPA(*this);
130      SourceLocation TemplateKWLoc = ConsumeToken();
131
132      UnqualifiedId TemplateName;
133      if (Tok.is(tok::identifier)) {
134        // Consume the identifier.
135        TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
136        ConsumeToken();
137      } else if (Tok.is(tok::kw_operator)) {
138        if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
139                                       TemplateName)) {
140          TPA.Commit();
141          break;
142        }
143
144        if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
145            TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
146          Diag(TemplateName.getSourceRange().getBegin(),
147               diag::err_id_after_template_in_nested_name_spec)
148            << TemplateName.getSourceRange();
149          TPA.Commit();
150          break;
151        }
152      } else {
153        TPA.Revert();
154        break;
155      }
156
157      // If the next token is not '<', we have a qualified-id that refers
158      // to a template name, such as T::template apply, but is not a
159      // template-id.
160      if (Tok.isNot(tok::less)) {
161        TPA.Revert();
162        break;
163      }
164
165      // Commit to parsing the template-id.
166      TPA.Commit();
167      TemplateTy Template
168        = Actions.ActOnDependentTemplateName(TemplateKWLoc, SS, TemplateName,
169                                             ObjectType, EnteringContext);
170      if (!Template)
171        return true;
172      if (AnnotateTemplateIdToken(Template, TNK_Dependent_template_name,
173                                  &SS, TemplateName, TemplateKWLoc, false))
174        return true;
175
176      continue;
177    }
178
179    if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
180      // We have
181      //
182      //   simple-template-id '::'
183      //
184      // So we need to check whether the simple-template-id is of the
185      // right kind (it should name a type or be dependent), and then
186      // convert it into a type within the nested-name-specifier.
187      TemplateIdAnnotation *TemplateId
188        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
189      if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
190        *MayBePseudoDestructor = true;
191        return false;
192      }
193
194      if (TemplateId->Kind == TNK_Type_template ||
195          TemplateId->Kind == TNK_Dependent_template_name) {
196        AnnotateTemplateIdTokenAsType(&SS);
197
198        assert(Tok.is(tok::annot_typename) &&
199               "AnnotateTemplateIdTokenAsType isn't working");
200        Token TypeToken = Tok;
201        ConsumeToken();
202        assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
203        SourceLocation CCLoc = ConsumeToken();
204
205        if (!HasScopeSpecifier) {
206          SS.setBeginLoc(TypeToken.getLocation());
207          HasScopeSpecifier = true;
208        }
209
210        if (TypeToken.getAnnotationValue())
211          SS.setScopeRep(
212            Actions.ActOnCXXNestedNameSpecifier(CurScope, SS,
213                                                TypeToken.getAnnotationValue(),
214                                                TypeToken.getAnnotationRange(),
215                                                CCLoc));
216        else
217          SS.setScopeRep(0);
218        SS.setEndLoc(CCLoc);
219        continue;
220      }
221
222      assert(false && "FIXME: Only type template names supported here");
223    }
224
225
226    // The rest of the nested-name-specifier possibilities start with
227    // tok::identifier.
228    if (Tok.isNot(tok::identifier))
229      break;
230
231    IdentifierInfo &II = *Tok.getIdentifierInfo();
232
233    // nested-name-specifier:
234    //   type-name '::'
235    //   namespace-name '::'
236    //   nested-name-specifier identifier '::'
237    Token Next = NextToken();
238
239    // If we get foo:bar, this is almost certainly a typo for foo::bar.  Recover
240    // and emit a fixit hint for it.
241    if (Next.is(tok::colon) && !ColonIsSacred) {
242      if (Actions.IsInvalidUnlessNestedName(CurScope, SS, II, ObjectType,
243                                            EnteringContext) &&
244          // If the token after the colon isn't an identifier, it's still an
245          // error, but they probably meant something else strange so don't
246          // recover like this.
247          PP.LookAhead(1).is(tok::identifier)) {
248        Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
249          << FixItHint::CreateReplacement(Next.getLocation(), "::");
250
251        // Recover as if the user wrote '::'.
252        Next.setKind(tok::coloncolon);
253      }
254    }
255
256    if (Next.is(tok::coloncolon)) {
257      if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
258          !Actions.isNonTypeNestedNameSpecifier(CurScope, SS, Tok.getLocation(),
259                                                II, ObjectType)) {
260        *MayBePseudoDestructor = true;
261        return false;
262      }
263
264      // We have an identifier followed by a '::'. Lookup this name
265      // as the name in a nested-name-specifier.
266      SourceLocation IdLoc = ConsumeToken();
267      assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
268             "NextToken() not working properly!");
269      SourceLocation CCLoc = ConsumeToken();
270
271      if (!HasScopeSpecifier) {
272        SS.setBeginLoc(IdLoc);
273        HasScopeSpecifier = true;
274      }
275
276      if (SS.isInvalid())
277        continue;
278
279      SS.setScopeRep(
280        Actions.ActOnCXXNestedNameSpecifier(CurScope, SS, IdLoc, CCLoc, II,
281                                            ObjectType, EnteringContext));
282      SS.setEndLoc(CCLoc);
283      continue;
284    }
285
286    // nested-name-specifier:
287    //   type-name '<'
288    if (Next.is(tok::less)) {
289      TemplateTy Template;
290      UnqualifiedId TemplateName;
291      TemplateName.setIdentifier(&II, Tok.getLocation());
292      bool MemberOfUnknownSpecialization;
293      if (TemplateNameKind TNK = Actions.isTemplateName(CurScope, SS,
294                                                        TemplateName,
295                                                        ObjectType,
296                                                        EnteringContext,
297                                                        Template,
298                                              MemberOfUnknownSpecialization)) {
299        // We have found a template name, so annotate this this token
300        // with a template-id annotation. We do not permit the
301        // template-id to be translated into a type annotation,
302        // because some clients (e.g., the parsing of class template
303        // specializations) still want to see the original template-id
304        // token.
305        ConsumeToken();
306        if (AnnotateTemplateIdToken(Template, TNK, &SS, TemplateName,
307                                    SourceLocation(), false))
308          return true;
309        continue;
310      }
311
312      if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
313          IsTemplateArgumentList(1)) {
314        // We have something like t::getAs<T>, where getAs is a
315        // member of an unknown specialization. However, this will only
316        // parse correctly as a template, so suggest the keyword 'template'
317        // before 'getAs' and treat this as a dependent template name.
318        Diag(Tok.getLocation(), diag::err_missing_dependent_template_keyword)
319          << II.getName()
320          << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
321
322        Template = Actions.ActOnDependentTemplateName(Tok.getLocation(), SS,
323                                                      TemplateName, ObjectType,
324                                                      EnteringContext);
325        if (!Template.get())
326          return true;
327
328        // Consume the identifier.
329        ConsumeToken();
330        if (AnnotateTemplateIdToken(Template, TNK_Dependent_template_name, &SS,
331                                    TemplateName, SourceLocation(), false))
332          return true;
333
334        continue;
335      }
336    }
337
338    // We don't have any tokens that form the beginning of a
339    // nested-name-specifier, so we're done.
340    break;
341  }
342
343  // Even if we didn't see any pieces of a nested-name-specifier, we
344  // still check whether there is a tilde in this position, which
345  // indicates a potential pseudo-destructor.
346  if (CheckForDestructor && Tok.is(tok::tilde))
347    *MayBePseudoDestructor = true;
348
349  return false;
350}
351
352/// ParseCXXIdExpression - Handle id-expression.
353///
354///       id-expression:
355///         unqualified-id
356///         qualified-id
357///
358///       qualified-id:
359///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
360///         '::' identifier
361///         '::' operator-function-id
362///         '::' template-id
363///
364/// NOTE: The standard specifies that, for qualified-id, the parser does not
365/// expect:
366///
367///   '::' conversion-function-id
368///   '::' '~' class-name
369///
370/// This may cause a slight inconsistency on diagnostics:
371///
372/// class C {};
373/// namespace A {}
374/// void f() {
375///   :: A :: ~ C(); // Some Sema error about using destructor with a
376///                  // namespace.
377///   :: ~ C(); // Some Parser error like 'unexpected ~'.
378/// }
379///
380/// We simplify the parser a bit and make it work like:
381///
382///       qualified-id:
383///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
384///         '::' unqualified-id
385///
386/// That way Sema can handle and report similar errors for namespaces and the
387/// global scope.
388///
389/// The isAddressOfOperand parameter indicates that this id-expression is a
390/// direct operand of the address-of operator. This is, besides member contexts,
391/// the only place where a qualified-id naming a non-static class member may
392/// appear.
393///
394Parser::OwningExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
395  // qualified-id:
396  //   '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
397  //   '::' unqualified-id
398  //
399  CXXScopeSpec SS;
400  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
401
402  UnqualifiedId Name;
403  if (ParseUnqualifiedId(SS,
404                         /*EnteringContext=*/false,
405                         /*AllowDestructorName=*/false,
406                         /*AllowConstructorName=*/false,
407                         /*ObjectType=*/0,
408                         Name))
409    return ExprError();
410
411  // This is only the direct operand of an & operator if it is not
412  // followed by a postfix-expression suffix.
413  if (isAddressOfOperand) {
414    switch (Tok.getKind()) {
415    case tok::l_square:
416    case tok::l_paren:
417    case tok::arrow:
418    case tok::period:
419    case tok::plusplus:
420    case tok::minusminus:
421      isAddressOfOperand = false;
422      break;
423
424    default:
425      break;
426    }
427  }
428
429  return Actions.ActOnIdExpression(CurScope, SS, Name, Tok.is(tok::l_paren),
430                                   isAddressOfOperand);
431
432}
433
434/// ParseCXXCasts - This handles the various ways to cast expressions to another
435/// type.
436///
437///       postfix-expression: [C++ 5.2p1]
438///         'dynamic_cast' '<' type-name '>' '(' expression ')'
439///         'static_cast' '<' type-name '>' '(' expression ')'
440///         'reinterpret_cast' '<' type-name '>' '(' expression ')'
441///         'const_cast' '<' type-name '>' '(' expression ')'
442///
443Parser::OwningExprResult Parser::ParseCXXCasts() {
444  tok::TokenKind Kind = Tok.getKind();
445  const char *CastName = 0;     // For error messages
446
447  switch (Kind) {
448  default: assert(0 && "Unknown C++ cast!"); abort();
449  case tok::kw_const_cast:       CastName = "const_cast";       break;
450  case tok::kw_dynamic_cast:     CastName = "dynamic_cast";     break;
451  case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
452  case tok::kw_static_cast:      CastName = "static_cast";      break;
453  }
454
455  SourceLocation OpLoc = ConsumeToken();
456  SourceLocation LAngleBracketLoc = Tok.getLocation();
457
458  if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
459    return ExprError();
460
461  TypeResult CastTy = ParseTypeName();
462  SourceLocation RAngleBracketLoc = Tok.getLocation();
463
464  if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
465    return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
466
467  SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
468
469  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, CastName))
470    return ExprError();
471
472  OwningExprResult Result = ParseExpression();
473
474  // Match the ')'.
475  RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
476
477  if (!Result.isInvalid() && !CastTy.isInvalid())
478    Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
479                                       LAngleBracketLoc, CastTy.get(),
480                                       RAngleBracketLoc,
481                                       LParenLoc, move(Result), RParenLoc);
482
483  return move(Result);
484}
485
486/// ParseCXXTypeid - This handles the C++ typeid expression.
487///
488///       postfix-expression: [C++ 5.2p1]
489///         'typeid' '(' expression ')'
490///         'typeid' '(' type-id ')'
491///
492Parser::OwningExprResult Parser::ParseCXXTypeid() {
493  assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
494
495  SourceLocation OpLoc = ConsumeToken();
496  SourceLocation LParenLoc = Tok.getLocation();
497  SourceLocation RParenLoc;
498
499  // typeid expressions are always parenthesized.
500  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
501      "typeid"))
502    return ExprError();
503
504  OwningExprResult Result(Actions);
505
506  if (isTypeIdInParens()) {
507    TypeResult Ty = ParseTypeName();
508
509    // Match the ')'.
510    MatchRHSPunctuation(tok::r_paren, LParenLoc);
511
512    if (Ty.isInvalid())
513      return ExprError();
514
515    Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
516                                    Ty.get(), RParenLoc);
517  } else {
518    // C++0x [expr.typeid]p3:
519    //   When typeid is applied to an expression other than an lvalue of a
520    //   polymorphic class type [...] The expression is an unevaluated
521    //   operand (Clause 5).
522    //
523    // Note that we can't tell whether the expression is an lvalue of a
524    // polymorphic class type until after we've parsed the expression, so
525    // we the expression is potentially potentially evaluated.
526    EnterExpressionEvaluationContext Unevaluated(Actions,
527                                       Action::PotentiallyPotentiallyEvaluated);
528    Result = ParseExpression();
529
530    // Match the ')'.
531    if (Result.isInvalid())
532      SkipUntil(tok::r_paren);
533    else {
534      MatchRHSPunctuation(tok::r_paren, LParenLoc);
535
536      Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
537                                      Result.release(), RParenLoc);
538    }
539  }
540
541  return move(Result);
542}
543
544/// \brief Parse a C++ pseudo-destructor expression after the base,
545/// . or -> operator, and nested-name-specifier have already been
546/// parsed.
547///
548///       postfix-expression: [C++ 5.2]
549///         postfix-expression . pseudo-destructor-name
550///         postfix-expression -> pseudo-destructor-name
551///
552///       pseudo-destructor-name:
553///         ::[opt] nested-name-specifier[opt] type-name :: ~type-name
554///         ::[opt] nested-name-specifier template simple-template-id ::
555///                 ~type-name
556///         ::[opt] nested-name-specifier[opt] ~type-name
557///
558Parser::OwningExprResult
559Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
560                                 tok::TokenKind OpKind,
561                                 CXXScopeSpec &SS,
562                                 Action::TypeTy *ObjectType) {
563  // We're parsing either a pseudo-destructor-name or a dependent
564  // member access that has the same form as a
565  // pseudo-destructor-name. We parse both in the same way and let
566  // the action model sort them out.
567  //
568  // Note that the ::[opt] nested-name-specifier[opt] has already
569  // been parsed, and if there was a simple-template-id, it has
570  // been coalesced into a template-id annotation token.
571  UnqualifiedId FirstTypeName;
572  SourceLocation CCLoc;
573  if (Tok.is(tok::identifier)) {
574    FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
575    ConsumeToken();
576    assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
577    CCLoc = ConsumeToken();
578  } else if (Tok.is(tok::annot_template_id)) {
579    FirstTypeName.setTemplateId(
580                              (TemplateIdAnnotation *)Tok.getAnnotationValue());
581    ConsumeToken();
582    assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
583    CCLoc = ConsumeToken();
584  } else {
585    FirstTypeName.setIdentifier(0, SourceLocation());
586  }
587
588  // Parse the tilde.
589  assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
590  SourceLocation TildeLoc = ConsumeToken();
591  if (!Tok.is(tok::identifier)) {
592    Diag(Tok, diag::err_destructor_tilde_identifier);
593    return ExprError();
594  }
595
596  // Parse the second type.
597  UnqualifiedId SecondTypeName;
598  IdentifierInfo *Name = Tok.getIdentifierInfo();
599  SourceLocation NameLoc = ConsumeToken();
600  SecondTypeName.setIdentifier(Name, NameLoc);
601
602  // If there is a '<', the second type name is a template-id. Parse
603  // it as such.
604  if (Tok.is(tok::less) &&
605      ParseUnqualifiedIdTemplateId(SS, Name, NameLoc, false, ObjectType,
606                                   SecondTypeName, /*AssumeTemplateName=*/true,
607                                   /*TemplateKWLoc*/SourceLocation()))
608    return ExprError();
609
610  return Actions.ActOnPseudoDestructorExpr(CurScope, move(Base), OpLoc, OpKind,
611                                           SS, FirstTypeName, CCLoc,
612                                           TildeLoc, SecondTypeName,
613                                           Tok.is(tok::l_paren));
614}
615
616/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
617///
618///       boolean-literal: [C++ 2.13.5]
619///         'true'
620///         'false'
621Parser::OwningExprResult Parser::ParseCXXBoolLiteral() {
622  tok::TokenKind Kind = Tok.getKind();
623  return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
624}
625
626/// ParseThrowExpression - This handles the C++ throw expression.
627///
628///       throw-expression: [C++ 15]
629///         'throw' assignment-expression[opt]
630Parser::OwningExprResult Parser::ParseThrowExpression() {
631  assert(Tok.is(tok::kw_throw) && "Not throw!");
632  SourceLocation ThrowLoc = ConsumeToken();           // Eat the throw token.
633
634  // If the current token isn't the start of an assignment-expression,
635  // then the expression is not present.  This handles things like:
636  //   "C ? throw : (void)42", which is crazy but legal.
637  switch (Tok.getKind()) {  // FIXME: move this predicate somewhere common.
638  case tok::semi:
639  case tok::r_paren:
640  case tok::r_square:
641  case tok::r_brace:
642  case tok::colon:
643  case tok::comma:
644    return Actions.ActOnCXXThrow(ThrowLoc, ExprArg(Actions));
645
646  default:
647    OwningExprResult Expr(ParseAssignmentExpression());
648    if (Expr.isInvalid()) return move(Expr);
649    return Actions.ActOnCXXThrow(ThrowLoc, move(Expr));
650  }
651}
652
653/// ParseCXXThis - This handles the C++ 'this' pointer.
654///
655/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
656/// a non-lvalue expression whose value is the address of the object for which
657/// the function is called.
658Parser::OwningExprResult Parser::ParseCXXThis() {
659  assert(Tok.is(tok::kw_this) && "Not 'this'!");
660  SourceLocation ThisLoc = ConsumeToken();
661  return Actions.ActOnCXXThis(ThisLoc);
662}
663
664/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
665/// Can be interpreted either as function-style casting ("int(x)")
666/// or class type construction ("ClassType(x,y,z)")
667/// or creation of a value-initialized type ("int()").
668///
669///       postfix-expression: [C++ 5.2p1]
670///         simple-type-specifier '(' expression-list[opt] ')'      [C++ 5.2.3]
671///         typename-specifier '(' expression-list[opt] ')'         [TODO]
672///
673Parser::OwningExprResult
674Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
675  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
676  TypeTy *TypeRep = Actions.ActOnTypeName(CurScope, DeclaratorInfo).get();
677
678  assert(Tok.is(tok::l_paren) && "Expected '('!");
679  SourceLocation LParenLoc = ConsumeParen();
680
681  ExprVector Exprs(Actions);
682  CommaLocsTy CommaLocs;
683
684  if (Tok.isNot(tok::r_paren)) {
685    if (ParseExpressionList(Exprs, CommaLocs)) {
686      SkipUntil(tok::r_paren);
687      return ExprError();
688    }
689  }
690
691  // Match the ')'.
692  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
693
694  // TypeRep could be null, if it references an invalid typedef.
695  if (!TypeRep)
696    return ExprError();
697
698  assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
699         "Unexpected number of commas!");
700  return Actions.ActOnCXXTypeConstructExpr(DS.getSourceRange(), TypeRep,
701                                           LParenLoc, move_arg(Exprs),
702                                           CommaLocs.data(), RParenLoc);
703}
704
705/// ParseCXXCondition - if/switch/while condition expression.
706///
707///       condition:
708///         expression
709///         type-specifier-seq declarator '=' assignment-expression
710/// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
711///             '=' assignment-expression
712///
713/// \param ExprResult if the condition was parsed as an expression, the
714/// parsed expression.
715///
716/// \param DeclResult if the condition was parsed as a declaration, the
717/// parsed declaration.
718///
719/// \param Loc The location of the start of the statement that requires this
720/// condition, e.g., the "for" in a for loop.
721///
722/// \param ConvertToBoolean Whether the condition expression should be
723/// converted to a boolean value.
724///
725/// \returns true if there was a parsing, false otherwise.
726bool Parser::ParseCXXCondition(OwningExprResult &ExprResult,
727                               DeclPtrTy &DeclResult,
728                               SourceLocation Loc,
729                               bool ConvertToBoolean) {
730  if (Tok.is(tok::code_completion)) {
731    Actions.CodeCompleteOrdinaryName(CurScope, Action::CCC_Condition);
732    ConsumeCodeCompletionToken();
733  }
734
735  if (!isCXXConditionDeclaration()) {
736    // Parse the expression.
737    ExprResult = ParseExpression(); // expression
738    DeclResult = DeclPtrTy();
739    if (ExprResult.isInvalid())
740      return true;
741
742    // If required, convert to a boolean value.
743    if (ConvertToBoolean)
744      ExprResult
745        = Actions.ActOnBooleanCondition(CurScope, Loc, move(ExprResult));
746    return ExprResult.isInvalid();
747  }
748
749  // type-specifier-seq
750  DeclSpec DS;
751  ParseSpecifierQualifierList(DS);
752
753  // declarator
754  Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
755  ParseDeclarator(DeclaratorInfo);
756
757  // simple-asm-expr[opt]
758  if (Tok.is(tok::kw_asm)) {
759    SourceLocation Loc;
760    OwningExprResult AsmLabel(ParseSimpleAsm(&Loc));
761    if (AsmLabel.isInvalid()) {
762      SkipUntil(tok::semi);
763      return true;
764    }
765    DeclaratorInfo.setAsmLabel(AsmLabel.release());
766    DeclaratorInfo.SetRangeEnd(Loc);
767  }
768
769  // If attributes are present, parse them.
770  if (Tok.is(tok::kw___attribute)) {
771    SourceLocation Loc;
772    AttributeList *AttrList = ParseGNUAttributes(&Loc);
773    DeclaratorInfo.AddAttributes(AttrList, Loc);
774  }
775
776  // Type-check the declaration itself.
777  Action::DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(CurScope,
778                                                                DeclaratorInfo);
779  DeclResult = Dcl.get();
780  ExprResult = ExprError();
781
782  // '=' assignment-expression
783  if (Tok.is(tok::equal)) {
784    SourceLocation EqualLoc = ConsumeToken();
785    OwningExprResult AssignExpr(ParseAssignmentExpression());
786    if (!AssignExpr.isInvalid())
787      Actions.AddInitializerToDecl(DeclResult, move(AssignExpr));
788  } else {
789    // FIXME: C++0x allows a braced-init-list
790    Diag(Tok, diag::err_expected_equal_after_declarator);
791  }
792
793  // FIXME: Build a reference to this declaration? Convert it to bool?
794  // (This is currently handled by Sema).
795
796  return false;
797}
798
799/// \brief Determine whether the current token starts a C++
800/// simple-type-specifier.
801bool Parser::isCXXSimpleTypeSpecifier() const {
802  switch (Tok.getKind()) {
803  case tok::annot_typename:
804  case tok::kw_short:
805  case tok::kw_long:
806  case tok::kw_signed:
807  case tok::kw_unsigned:
808  case tok::kw_void:
809  case tok::kw_char:
810  case tok::kw_int:
811  case tok::kw_float:
812  case tok::kw_double:
813  case tok::kw_wchar_t:
814  case tok::kw_char16_t:
815  case tok::kw_char32_t:
816  case tok::kw_bool:
817    // FIXME: C++0x decltype support.
818  // GNU typeof support.
819  case tok::kw_typeof:
820    return true;
821
822  default:
823    break;
824  }
825
826  return false;
827}
828
829/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
830/// This should only be called when the current token is known to be part of
831/// simple-type-specifier.
832///
833///       simple-type-specifier:
834///         '::'[opt] nested-name-specifier[opt] type-name
835///         '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
836///         char
837///         wchar_t
838///         bool
839///         short
840///         int
841///         long
842///         signed
843///         unsigned
844///         float
845///         double
846///         void
847/// [GNU]   typeof-specifier
848/// [C++0x] auto               [TODO]
849///
850///       type-name:
851///         class-name
852///         enum-name
853///         typedef-name
854///
855void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
856  DS.SetRangeStart(Tok.getLocation());
857  const char *PrevSpec;
858  unsigned DiagID;
859  SourceLocation Loc = Tok.getLocation();
860
861  switch (Tok.getKind()) {
862  case tok::identifier:   // foo::bar
863  case tok::coloncolon:   // ::foo::bar
864    assert(0 && "Annotation token should already be formed!");
865  default:
866    assert(0 && "Not a simple-type-specifier token!");
867    abort();
868
869  // type-name
870  case tok::annot_typename: {
871    DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
872                       Tok.getAnnotationValue());
873    break;
874  }
875
876  // builtin types
877  case tok::kw_short:
878    DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
879    break;
880  case tok::kw_long:
881    DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
882    break;
883  case tok::kw_signed:
884    DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
885    break;
886  case tok::kw_unsigned:
887    DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
888    break;
889  case tok::kw_void:
890    DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
891    break;
892  case tok::kw_char:
893    DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
894    break;
895  case tok::kw_int:
896    DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
897    break;
898  case tok::kw_float:
899    DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
900    break;
901  case tok::kw_double:
902    DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
903    break;
904  case tok::kw_wchar_t:
905    DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
906    break;
907  case tok::kw_char16_t:
908    DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
909    break;
910  case tok::kw_char32_t:
911    DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
912    break;
913  case tok::kw_bool:
914    DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
915    break;
916
917    // FIXME: C++0x decltype support.
918  // GNU typeof support.
919  case tok::kw_typeof:
920    ParseTypeofSpecifier(DS);
921    DS.Finish(Diags, PP);
922    return;
923  }
924  if (Tok.is(tok::annot_typename))
925    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
926  else
927    DS.SetRangeEnd(Tok.getLocation());
928  ConsumeToken();
929  DS.Finish(Diags, PP);
930}
931
932/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
933/// [dcl.name]), which is a non-empty sequence of type-specifiers,
934/// e.g., "const short int". Note that the DeclSpec is *not* finished
935/// by parsing the type-specifier-seq, because these sequences are
936/// typically followed by some form of declarator. Returns true and
937/// emits diagnostics if this is not a type-specifier-seq, false
938/// otherwise.
939///
940///   type-specifier-seq: [C++ 8.1]
941///     type-specifier type-specifier-seq[opt]
942///
943bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
944  DS.SetRangeStart(Tok.getLocation());
945  const char *PrevSpec = 0;
946  unsigned DiagID;
947  bool isInvalid = 0;
948
949  // Parse one or more of the type specifiers.
950  if (!ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
951      ParsedTemplateInfo(), /*SuppressDeclarations*/true)) {
952    Diag(Tok, diag::err_operator_missing_type_specifier);
953    return true;
954  }
955
956  while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
957         ParsedTemplateInfo(), /*SuppressDeclarations*/true))
958  {}
959
960  DS.Finish(Diags, PP);
961  return false;
962}
963
964/// \brief Finish parsing a C++ unqualified-id that is a template-id of
965/// some form.
966///
967/// This routine is invoked when a '<' is encountered after an identifier or
968/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
969/// whether the unqualified-id is actually a template-id. This routine will
970/// then parse the template arguments and form the appropriate template-id to
971/// return to the caller.
972///
973/// \param SS the nested-name-specifier that precedes this template-id, if
974/// we're actually parsing a qualified-id.
975///
976/// \param Name for constructor and destructor names, this is the actual
977/// identifier that may be a template-name.
978///
979/// \param NameLoc the location of the class-name in a constructor or
980/// destructor.
981///
982/// \param EnteringContext whether we're entering the scope of the
983/// nested-name-specifier.
984///
985/// \param ObjectType if this unqualified-id occurs within a member access
986/// expression, the type of the base object whose member is being accessed.
987///
988/// \param Id as input, describes the template-name or operator-function-id
989/// that precedes the '<'. If template arguments were parsed successfully,
990/// will be updated with the template-id.
991///
992/// \param AssumeTemplateId When true, this routine will assume that the name
993/// refers to a template without performing name lookup to verify.
994///
995/// \returns true if a parse error occurred, false otherwise.
996bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
997                                          IdentifierInfo *Name,
998                                          SourceLocation NameLoc,
999                                          bool EnteringContext,
1000                                          TypeTy *ObjectType,
1001                                          UnqualifiedId &Id,
1002                                          bool AssumeTemplateId,
1003                                          SourceLocation TemplateKWLoc) {
1004  assert((AssumeTemplateId || Tok.is(tok::less)) &&
1005         "Expected '<' to finish parsing a template-id");
1006
1007  TemplateTy Template;
1008  TemplateNameKind TNK = TNK_Non_template;
1009  switch (Id.getKind()) {
1010  case UnqualifiedId::IK_Identifier:
1011  case UnqualifiedId::IK_OperatorFunctionId:
1012  case UnqualifiedId::IK_LiteralOperatorId:
1013    if (AssumeTemplateId) {
1014      Template = Actions.ActOnDependentTemplateName(TemplateKWLoc, SS,
1015                                                    Id, ObjectType,
1016                                                    EnteringContext);
1017      TNK = TNK_Dependent_template_name;
1018      if (!Template.get())
1019        return true;
1020    } else {
1021      bool MemberOfUnknownSpecialization;
1022      TNK = Actions.isTemplateName(CurScope, SS, Id, ObjectType,
1023                                   EnteringContext, Template,
1024                                   MemberOfUnknownSpecialization);
1025
1026      if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1027          ObjectType && IsTemplateArgumentList()) {
1028        // We have something like t->getAs<T>(), where getAs is a
1029        // member of an unknown specialization. However, this will only
1030        // parse correctly as a template, so suggest the keyword 'template'
1031        // before 'getAs' and treat this as a dependent template name.
1032        std::string Name;
1033        if (Id.getKind() == UnqualifiedId::IK_Identifier)
1034          Name = Id.Identifier->getName();
1035        else {
1036          Name = "operator ";
1037          if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1038            Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1039          else
1040            Name += Id.Identifier->getName();
1041        }
1042        Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1043          << Name
1044          << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1045        Template = Actions.ActOnDependentTemplateName(TemplateKWLoc, SS,
1046                                                      Id, ObjectType,
1047                                                      EnteringContext);
1048        TNK = TNK_Dependent_template_name;
1049        if (!Template.get())
1050          return true;
1051      }
1052    }
1053    break;
1054
1055  case UnqualifiedId::IK_ConstructorName: {
1056    UnqualifiedId TemplateName;
1057    bool MemberOfUnknownSpecialization;
1058    TemplateName.setIdentifier(Name, NameLoc);
1059    TNK = Actions.isTemplateName(CurScope, SS, TemplateName, ObjectType,
1060                                 EnteringContext, Template,
1061                                 MemberOfUnknownSpecialization);
1062    break;
1063  }
1064
1065  case UnqualifiedId::IK_DestructorName: {
1066    UnqualifiedId TemplateName;
1067    bool MemberOfUnknownSpecialization;
1068    TemplateName.setIdentifier(Name, NameLoc);
1069    if (ObjectType) {
1070      Template = Actions.ActOnDependentTemplateName(TemplateKWLoc, SS,
1071                                                    TemplateName, ObjectType,
1072                                                    EnteringContext);
1073      TNK = TNK_Dependent_template_name;
1074      if (!Template.get())
1075        return true;
1076    } else {
1077      TNK = Actions.isTemplateName(CurScope, SS, TemplateName, ObjectType,
1078                                   EnteringContext, Template,
1079                                   MemberOfUnknownSpecialization);
1080
1081      if (TNK == TNK_Non_template && Id.DestructorName == 0) {
1082        Diag(NameLoc, diag::err_destructor_template_id)
1083          << Name << SS.getRange();
1084        return true;
1085      }
1086    }
1087    break;
1088  }
1089
1090  default:
1091    return false;
1092  }
1093
1094  if (TNK == TNK_Non_template)
1095    return false;
1096
1097  // Parse the enclosed template argument list.
1098  SourceLocation LAngleLoc, RAngleLoc;
1099  TemplateArgList TemplateArgs;
1100  if (Tok.is(tok::less) &&
1101      ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
1102                                       &SS, true, LAngleLoc,
1103                                       TemplateArgs,
1104                                       RAngleLoc))
1105    return true;
1106
1107  if (Id.getKind() == UnqualifiedId::IK_Identifier ||
1108      Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1109      Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
1110    // Form a parsed representation of the template-id to be stored in the
1111    // UnqualifiedId.
1112    TemplateIdAnnotation *TemplateId
1113      = TemplateIdAnnotation::Allocate(TemplateArgs.size());
1114
1115    if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1116      TemplateId->Name = Id.Identifier;
1117      TemplateId->Operator = OO_None;
1118      TemplateId->TemplateNameLoc = Id.StartLocation;
1119    } else {
1120      TemplateId->Name = 0;
1121      TemplateId->Operator = Id.OperatorFunctionId.Operator;
1122      TemplateId->TemplateNameLoc = Id.StartLocation;
1123    }
1124
1125    TemplateId->Template = Template.getAs<void*>();
1126    TemplateId->Kind = TNK;
1127    TemplateId->LAngleLoc = LAngleLoc;
1128    TemplateId->RAngleLoc = RAngleLoc;
1129    ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1130    for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
1131         Arg != ArgEnd; ++Arg)
1132      Args[Arg] = TemplateArgs[Arg];
1133
1134    Id.setTemplateId(TemplateId);
1135    return false;
1136  }
1137
1138  // Bundle the template arguments together.
1139  ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
1140                                     TemplateArgs.size());
1141
1142  // Constructor and destructor names.
1143  Action::TypeResult Type
1144    = Actions.ActOnTemplateIdType(Template, NameLoc,
1145                                  LAngleLoc, TemplateArgsPtr,
1146                                  RAngleLoc);
1147  if (Type.isInvalid())
1148    return true;
1149
1150  if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1151    Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1152  else
1153    Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1154
1155  return false;
1156}
1157
1158/// \brief Parse an operator-function-id or conversion-function-id as part
1159/// of a C++ unqualified-id.
1160///
1161/// This routine is responsible only for parsing the operator-function-id or
1162/// conversion-function-id; it does not handle template arguments in any way.
1163///
1164/// \code
1165///       operator-function-id: [C++ 13.5]
1166///         'operator' operator
1167///
1168///       operator: one of
1169///            new   delete  new[]   delete[]
1170///            +     -    *  /    %  ^    &   |   ~
1171///            !     =    <  >    += -=   *=  /=  %=
1172///            ^=    &=   |= <<   >> >>= <<=  ==  !=
1173///            <=    >=   && ||   ++ --   ,   ->* ->
1174///            ()    []
1175///
1176///       conversion-function-id: [C++ 12.3.2]
1177///         operator conversion-type-id
1178///
1179///       conversion-type-id:
1180///         type-specifier-seq conversion-declarator[opt]
1181///
1182///       conversion-declarator:
1183///         ptr-operator conversion-declarator[opt]
1184/// \endcode
1185///
1186/// \param The nested-name-specifier that preceded this unqualified-id. If
1187/// non-empty, then we are parsing the unqualified-id of a qualified-id.
1188///
1189/// \param EnteringContext whether we are entering the scope of the
1190/// nested-name-specifier.
1191///
1192/// \param ObjectType if this unqualified-id occurs within a member access
1193/// expression, the type of the base object whose member is being accessed.
1194///
1195/// \param Result on a successful parse, contains the parsed unqualified-id.
1196///
1197/// \returns true if parsing fails, false otherwise.
1198bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
1199                                        TypeTy *ObjectType,
1200                                        UnqualifiedId &Result) {
1201  assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
1202
1203  // Consume the 'operator' keyword.
1204  SourceLocation KeywordLoc = ConsumeToken();
1205
1206  // Determine what kind of operator name we have.
1207  unsigned SymbolIdx = 0;
1208  SourceLocation SymbolLocations[3];
1209  OverloadedOperatorKind Op = OO_None;
1210  switch (Tok.getKind()) {
1211    case tok::kw_new:
1212    case tok::kw_delete: {
1213      bool isNew = Tok.getKind() == tok::kw_new;
1214      // Consume the 'new' or 'delete'.
1215      SymbolLocations[SymbolIdx++] = ConsumeToken();
1216      if (Tok.is(tok::l_square)) {
1217        // Consume the '['.
1218        SourceLocation LBracketLoc = ConsumeBracket();
1219        // Consume the ']'.
1220        SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square,
1221                                                         LBracketLoc);
1222        if (RBracketLoc.isInvalid())
1223          return true;
1224
1225        SymbolLocations[SymbolIdx++] = LBracketLoc;
1226        SymbolLocations[SymbolIdx++] = RBracketLoc;
1227        Op = isNew? OO_Array_New : OO_Array_Delete;
1228      } else {
1229        Op = isNew? OO_New : OO_Delete;
1230      }
1231      break;
1232    }
1233
1234#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1235    case tok::Token:                                                     \
1236      SymbolLocations[SymbolIdx++] = ConsumeToken();                     \
1237      Op = OO_##Name;                                                    \
1238      break;
1239#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
1240#include "clang/Basic/OperatorKinds.def"
1241
1242    case tok::l_paren: {
1243      // Consume the '('.
1244      SourceLocation LParenLoc = ConsumeParen();
1245      // Consume the ')'.
1246      SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren,
1247                                                     LParenLoc);
1248      if (RParenLoc.isInvalid())
1249        return true;
1250
1251      SymbolLocations[SymbolIdx++] = LParenLoc;
1252      SymbolLocations[SymbolIdx++] = RParenLoc;
1253      Op = OO_Call;
1254      break;
1255    }
1256
1257    case tok::l_square: {
1258      // Consume the '['.
1259      SourceLocation LBracketLoc = ConsumeBracket();
1260      // Consume the ']'.
1261      SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square,
1262                                                       LBracketLoc);
1263      if (RBracketLoc.isInvalid())
1264        return true;
1265
1266      SymbolLocations[SymbolIdx++] = LBracketLoc;
1267      SymbolLocations[SymbolIdx++] = RBracketLoc;
1268      Op = OO_Subscript;
1269      break;
1270    }
1271
1272    case tok::code_completion: {
1273      // Code completion for the operator name.
1274      Actions.CodeCompleteOperatorName(CurScope);
1275
1276      // Consume the operator token.
1277      ConsumeCodeCompletionToken();
1278
1279      // Don't try to parse any further.
1280      return true;
1281    }
1282
1283    default:
1284      break;
1285  }
1286
1287  if (Op != OO_None) {
1288    // We have parsed an operator-function-id.
1289    Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
1290    return false;
1291  }
1292
1293  // Parse a literal-operator-id.
1294  //
1295  //   literal-operator-id: [C++0x 13.5.8]
1296  //     operator "" identifier
1297
1298  if (getLang().CPlusPlus0x && Tok.is(tok::string_literal)) {
1299    if (Tok.getLength() != 2)
1300      Diag(Tok.getLocation(), diag::err_operator_string_not_empty);
1301    ConsumeStringToken();
1302
1303    if (Tok.isNot(tok::identifier)) {
1304      Diag(Tok.getLocation(), diag::err_expected_ident);
1305      return true;
1306    }
1307
1308    IdentifierInfo *II = Tok.getIdentifierInfo();
1309    Result.setLiteralOperatorId(II, KeywordLoc, ConsumeToken());
1310    return false;
1311  }
1312
1313  // Parse a conversion-function-id.
1314  //
1315  //   conversion-function-id: [C++ 12.3.2]
1316  //     operator conversion-type-id
1317  //
1318  //   conversion-type-id:
1319  //     type-specifier-seq conversion-declarator[opt]
1320  //
1321  //   conversion-declarator:
1322  //     ptr-operator conversion-declarator[opt]
1323
1324  // Parse the type-specifier-seq.
1325  DeclSpec DS;
1326  if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
1327    return true;
1328
1329  // Parse the conversion-declarator, which is merely a sequence of
1330  // ptr-operators.
1331  Declarator D(DS, Declarator::TypeNameContext);
1332  ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
1333
1334  // Finish up the type.
1335  Action::TypeResult Ty = Actions.ActOnTypeName(CurScope, D);
1336  if (Ty.isInvalid())
1337    return true;
1338
1339  // Note that this is a conversion-function-id.
1340  Result.setConversionFunctionId(KeywordLoc, Ty.get(),
1341                                 D.getSourceRange().getEnd());
1342  return false;
1343}
1344
1345/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
1346/// name of an entity.
1347///
1348/// \code
1349///       unqualified-id: [C++ expr.prim.general]
1350///         identifier
1351///         operator-function-id
1352///         conversion-function-id
1353/// [C++0x] literal-operator-id [TODO]
1354///         ~ class-name
1355///         template-id
1356///
1357/// \endcode
1358///
1359/// \param The nested-name-specifier that preceded this unqualified-id. If
1360/// non-empty, then we are parsing the unqualified-id of a qualified-id.
1361///
1362/// \param EnteringContext whether we are entering the scope of the
1363/// nested-name-specifier.
1364///
1365/// \param AllowDestructorName whether we allow parsing of a destructor name.
1366///
1367/// \param AllowConstructorName whether we allow parsing a constructor name.
1368///
1369/// \param ObjectType if this unqualified-id occurs within a member access
1370/// expression, the type of the base object whose member is being accessed.
1371///
1372/// \param Result on a successful parse, contains the parsed unqualified-id.
1373///
1374/// \returns true if parsing fails, false otherwise.
1375bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
1376                                bool AllowDestructorName,
1377                                bool AllowConstructorName,
1378                                TypeTy *ObjectType,
1379                                UnqualifiedId &Result) {
1380
1381  // Handle 'A::template B'. This is for template-ids which have not
1382  // already been annotated by ParseOptionalCXXScopeSpecifier().
1383  bool TemplateSpecified = false;
1384  SourceLocation TemplateKWLoc;
1385  if (getLang().CPlusPlus && Tok.is(tok::kw_template) &&
1386      (ObjectType || SS.isSet())) {
1387    TemplateSpecified = true;
1388    TemplateKWLoc = ConsumeToken();
1389  }
1390
1391  // unqualified-id:
1392  //   identifier
1393  //   template-id (when it hasn't already been annotated)
1394  if (Tok.is(tok::identifier)) {
1395    // Consume the identifier.
1396    IdentifierInfo *Id = Tok.getIdentifierInfo();
1397    SourceLocation IdLoc = ConsumeToken();
1398
1399    if (!getLang().CPlusPlus) {
1400      // If we're not in C++, only identifiers matter. Record the
1401      // identifier and return.
1402      Result.setIdentifier(Id, IdLoc);
1403      return false;
1404    }
1405
1406    if (AllowConstructorName &&
1407        Actions.isCurrentClassName(*Id, CurScope, &SS)) {
1408      // We have parsed a constructor name.
1409      Result.setConstructorName(Actions.getTypeName(*Id, IdLoc, CurScope,
1410                                                    &SS, false),
1411                                IdLoc, IdLoc);
1412    } else {
1413      // We have parsed an identifier.
1414      Result.setIdentifier(Id, IdLoc);
1415    }
1416
1417    // If the next token is a '<', we may have a template.
1418    if (TemplateSpecified || Tok.is(tok::less))
1419      return ParseUnqualifiedIdTemplateId(SS, Id, IdLoc, EnteringContext,
1420                                          ObjectType, Result,
1421                                          TemplateSpecified, TemplateKWLoc);
1422
1423    return false;
1424  }
1425
1426  // unqualified-id:
1427  //   template-id (already parsed and annotated)
1428  if (Tok.is(tok::annot_template_id)) {
1429    TemplateIdAnnotation *TemplateId
1430      = static_cast<TemplateIdAnnotation*>(Tok.getAnnotationValue());
1431
1432    // If the template-name names the current class, then this is a constructor
1433    if (AllowConstructorName && TemplateId->Name &&
1434        Actions.isCurrentClassName(*TemplateId->Name, CurScope, &SS)) {
1435      if (SS.isSet()) {
1436        // C++ [class.qual]p2 specifies that a qualified template-name
1437        // is taken as the constructor name where a constructor can be
1438        // declared. Thus, the template arguments are extraneous, so
1439        // complain about them and remove them entirely.
1440        Diag(TemplateId->TemplateNameLoc,
1441             diag::err_out_of_line_constructor_template_id)
1442          << TemplateId->Name
1443          << FixItHint::CreateRemoval(
1444                    SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
1445        Result.setConstructorName(Actions.getTypeName(*TemplateId->Name,
1446                                                  TemplateId->TemplateNameLoc,
1447                                                      CurScope,
1448                                                      &SS, false),
1449                                  TemplateId->TemplateNameLoc,
1450                                  TemplateId->RAngleLoc);
1451        TemplateId->Destroy();
1452        ConsumeToken();
1453        return false;
1454      }
1455
1456      Result.setConstructorTemplateId(TemplateId);
1457      ConsumeToken();
1458      return false;
1459    }
1460
1461    // We have already parsed a template-id; consume the annotation token as
1462    // our unqualified-id.
1463    Result.setTemplateId(TemplateId);
1464    ConsumeToken();
1465    return false;
1466  }
1467
1468  // unqualified-id:
1469  //   operator-function-id
1470  //   conversion-function-id
1471  if (Tok.is(tok::kw_operator)) {
1472    if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
1473      return true;
1474
1475    // If we have an operator-function-id or a literal-operator-id and the next
1476    // token is a '<', we may have a
1477    //
1478    //   template-id:
1479    //     operator-function-id < template-argument-list[opt] >
1480    if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1481         Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
1482        (TemplateSpecified || Tok.is(tok::less)))
1483      return ParseUnqualifiedIdTemplateId(SS, 0, SourceLocation(),
1484                                          EnteringContext, ObjectType,
1485                                          Result,
1486                                          TemplateSpecified, TemplateKWLoc);
1487
1488    return false;
1489  }
1490
1491  if (getLang().CPlusPlus &&
1492      (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
1493    // C++ [expr.unary.op]p10:
1494    //   There is an ambiguity in the unary-expression ~X(), where X is a
1495    //   class-name. The ambiguity is resolved in favor of treating ~ as a
1496    //    unary complement rather than treating ~X as referring to a destructor.
1497
1498    // Parse the '~'.
1499    SourceLocation TildeLoc = ConsumeToken();
1500
1501    // Parse the class-name.
1502    if (Tok.isNot(tok::identifier)) {
1503      Diag(Tok, diag::err_destructor_tilde_identifier);
1504      return true;
1505    }
1506
1507    // Parse the class-name (or template-name in a simple-template-id).
1508    IdentifierInfo *ClassName = Tok.getIdentifierInfo();
1509    SourceLocation ClassNameLoc = ConsumeToken();
1510
1511    if (TemplateSpecified || Tok.is(tok::less)) {
1512      Result.setDestructorName(TildeLoc, 0, ClassNameLoc);
1513      return ParseUnqualifiedIdTemplateId(SS, ClassName, ClassNameLoc,
1514                                          EnteringContext, ObjectType, Result,
1515                                          TemplateSpecified, TemplateKWLoc);
1516    }
1517
1518    // Note that this is a destructor name.
1519    Action::TypeTy *Ty = Actions.getDestructorName(TildeLoc, *ClassName,
1520                                                   ClassNameLoc, CurScope,
1521                                                   SS, ObjectType,
1522                                                   EnteringContext);
1523    if (!Ty)
1524      return true;
1525
1526    Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
1527    return false;
1528  }
1529
1530  Diag(Tok, diag::err_expected_unqualified_id)
1531    << getLang().CPlusPlus;
1532  return true;
1533}
1534
1535/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
1536/// memory in a typesafe manner and call constructors.
1537///
1538/// This method is called to parse the new expression after the optional :: has
1539/// been already parsed.  If the :: was present, "UseGlobal" is true and "Start"
1540/// is its location.  Otherwise, "Start" is the location of the 'new' token.
1541///
1542///        new-expression:
1543///                   '::'[opt] 'new' new-placement[opt] new-type-id
1544///                                     new-initializer[opt]
1545///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
1546///                                     new-initializer[opt]
1547///
1548///        new-placement:
1549///                   '(' expression-list ')'
1550///
1551///        new-type-id:
1552///                   type-specifier-seq new-declarator[opt]
1553///
1554///        new-declarator:
1555///                   ptr-operator new-declarator[opt]
1556///                   direct-new-declarator
1557///
1558///        new-initializer:
1559///                   '(' expression-list[opt] ')'
1560/// [C++0x]           braced-init-list                                   [TODO]
1561///
1562Parser::OwningExprResult
1563Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
1564  assert(Tok.is(tok::kw_new) && "expected 'new' token");
1565  ConsumeToken();   // Consume 'new'
1566
1567  // A '(' now can be a new-placement or the '(' wrapping the type-id in the
1568  // second form of new-expression. It can't be a new-type-id.
1569
1570  ExprVector PlacementArgs(Actions);
1571  SourceLocation PlacementLParen, PlacementRParen;
1572
1573  bool ParenTypeId;
1574  DeclSpec DS;
1575  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1576  if (Tok.is(tok::l_paren)) {
1577    // If it turns out to be a placement, we change the type location.
1578    PlacementLParen = ConsumeParen();
1579    if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
1580      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1581      return ExprError();
1582    }
1583
1584    PlacementRParen = MatchRHSPunctuation(tok::r_paren, PlacementLParen);
1585    if (PlacementRParen.isInvalid()) {
1586      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1587      return ExprError();
1588    }
1589
1590    if (PlacementArgs.empty()) {
1591      // Reset the placement locations. There was no placement.
1592      PlacementLParen = PlacementRParen = SourceLocation();
1593      ParenTypeId = true;
1594    } else {
1595      // We still need the type.
1596      if (Tok.is(tok::l_paren)) {
1597        SourceLocation LParen = ConsumeParen();
1598        ParseSpecifierQualifierList(DS);
1599        DeclaratorInfo.SetSourceRange(DS.getSourceRange());
1600        ParseDeclarator(DeclaratorInfo);
1601        MatchRHSPunctuation(tok::r_paren, LParen);
1602        ParenTypeId = true;
1603      } else {
1604        if (ParseCXXTypeSpecifierSeq(DS))
1605          DeclaratorInfo.setInvalidType(true);
1606        else {
1607          DeclaratorInfo.SetSourceRange(DS.getSourceRange());
1608          ParseDeclaratorInternal(DeclaratorInfo,
1609                                  &Parser::ParseDirectNewDeclarator);
1610        }
1611        ParenTypeId = false;
1612      }
1613    }
1614  } else {
1615    // A new-type-id is a simplified type-id, where essentially the
1616    // direct-declarator is replaced by a direct-new-declarator.
1617    if (ParseCXXTypeSpecifierSeq(DS))
1618      DeclaratorInfo.setInvalidType(true);
1619    else {
1620      DeclaratorInfo.SetSourceRange(DS.getSourceRange());
1621      ParseDeclaratorInternal(DeclaratorInfo,
1622                              &Parser::ParseDirectNewDeclarator);
1623    }
1624    ParenTypeId = false;
1625  }
1626  if (DeclaratorInfo.isInvalidType()) {
1627    SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1628    return ExprError();
1629  }
1630
1631  ExprVector ConstructorArgs(Actions);
1632  SourceLocation ConstructorLParen, ConstructorRParen;
1633
1634  if (Tok.is(tok::l_paren)) {
1635    ConstructorLParen = ConsumeParen();
1636    if (Tok.isNot(tok::r_paren)) {
1637      CommaLocsTy CommaLocs;
1638      if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
1639        SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1640        return ExprError();
1641      }
1642    }
1643    ConstructorRParen = MatchRHSPunctuation(tok::r_paren, ConstructorLParen);
1644    if (ConstructorRParen.isInvalid()) {
1645      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1646      return ExprError();
1647    }
1648  }
1649
1650  return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
1651                             move_arg(PlacementArgs), PlacementRParen,
1652                             ParenTypeId, DeclaratorInfo, ConstructorLParen,
1653                             move_arg(ConstructorArgs), ConstructorRParen);
1654}
1655
1656/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
1657/// passed to ParseDeclaratorInternal.
1658///
1659///        direct-new-declarator:
1660///                   '[' expression ']'
1661///                   direct-new-declarator '[' constant-expression ']'
1662///
1663void Parser::ParseDirectNewDeclarator(Declarator &D) {
1664  // Parse the array dimensions.
1665  bool first = true;
1666  while (Tok.is(tok::l_square)) {
1667    SourceLocation LLoc = ConsumeBracket();
1668    OwningExprResult Size(first ? ParseExpression()
1669                                : ParseConstantExpression());
1670    if (Size.isInvalid()) {
1671      // Recover
1672      SkipUntil(tok::r_square);
1673      return;
1674    }
1675    first = false;
1676
1677    SourceLocation RLoc = MatchRHSPunctuation(tok::r_square, LLoc);
1678    D.AddTypeInfo(DeclaratorChunk::getArray(0, /*static=*/false, /*star=*/false,
1679                                            Size.release(), LLoc, RLoc),
1680                  RLoc);
1681
1682    if (RLoc.isInvalid())
1683      return;
1684  }
1685}
1686
1687/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
1688/// This ambiguity appears in the syntax of the C++ new operator.
1689///
1690///        new-expression:
1691///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
1692///                                     new-initializer[opt]
1693///
1694///        new-placement:
1695///                   '(' expression-list ')'
1696///
1697bool Parser::ParseExpressionListOrTypeId(ExprListTy &PlacementArgs,
1698                                         Declarator &D) {
1699  // The '(' was already consumed.
1700  if (isTypeIdInParens()) {
1701    ParseSpecifierQualifierList(D.getMutableDeclSpec());
1702    D.SetSourceRange(D.getDeclSpec().getSourceRange());
1703    ParseDeclarator(D);
1704    return D.isInvalidType();
1705  }
1706
1707  // It's not a type, it has to be an expression list.
1708  // Discard the comma locations - ActOnCXXNew has enough parameters.
1709  CommaLocsTy CommaLocs;
1710  return ParseExpressionList(PlacementArgs, CommaLocs);
1711}
1712
1713/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
1714/// to free memory allocated by new.
1715///
1716/// This method is called to parse the 'delete' expression after the optional
1717/// '::' has been already parsed.  If the '::' was present, "UseGlobal" is true
1718/// and "Start" is its location.  Otherwise, "Start" is the location of the
1719/// 'delete' token.
1720///
1721///        delete-expression:
1722///                   '::'[opt] 'delete' cast-expression
1723///                   '::'[opt] 'delete' '[' ']' cast-expression
1724Parser::OwningExprResult
1725Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
1726  assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
1727  ConsumeToken(); // Consume 'delete'
1728
1729  // Array delete?
1730  bool ArrayDelete = false;
1731  if (Tok.is(tok::l_square)) {
1732    ArrayDelete = true;
1733    SourceLocation LHS = ConsumeBracket();
1734    SourceLocation RHS = MatchRHSPunctuation(tok::r_square, LHS);
1735    if (RHS.isInvalid())
1736      return ExprError();
1737  }
1738
1739  OwningExprResult Operand(ParseCastExpression(false));
1740  if (Operand.isInvalid())
1741    return move(Operand);
1742
1743  return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, move(Operand));
1744}
1745
1746static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
1747  switch(kind) {
1748  default: assert(false && "Not a known unary type trait.");
1749  case tok::kw___has_nothrow_assign:      return UTT_HasNothrowAssign;
1750  case tok::kw___has_nothrow_copy:        return UTT_HasNothrowCopy;
1751  case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
1752  case tok::kw___has_trivial_assign:      return UTT_HasTrivialAssign;
1753  case tok::kw___has_trivial_copy:        return UTT_HasTrivialCopy;
1754  case tok::kw___has_trivial_constructor: return UTT_HasTrivialConstructor;
1755  case tok::kw___has_trivial_destructor:  return UTT_HasTrivialDestructor;
1756  case tok::kw___has_virtual_destructor:  return UTT_HasVirtualDestructor;
1757  case tok::kw___is_abstract:             return UTT_IsAbstract;
1758  case tok::kw___is_class:                return UTT_IsClass;
1759  case tok::kw___is_empty:                return UTT_IsEmpty;
1760  case tok::kw___is_enum:                 return UTT_IsEnum;
1761  case tok::kw___is_pod:                  return UTT_IsPOD;
1762  case tok::kw___is_polymorphic:          return UTT_IsPolymorphic;
1763  case tok::kw___is_union:                return UTT_IsUnion;
1764  case tok::kw___is_literal:              return UTT_IsLiteral;
1765  }
1766}
1767
1768/// ParseUnaryTypeTrait - Parse the built-in unary type-trait
1769/// pseudo-functions that allow implementation of the TR1/C++0x type traits
1770/// templates.
1771///
1772///       primary-expression:
1773/// [GNU]             unary-type-trait '(' type-id ')'
1774///
1775Parser::OwningExprResult Parser::ParseUnaryTypeTrait() {
1776  UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
1777  SourceLocation Loc = ConsumeToken();
1778
1779  SourceLocation LParen = Tok.getLocation();
1780  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1781    return ExprError();
1782
1783  // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
1784  // there will be cryptic errors about mismatched parentheses and missing
1785  // specifiers.
1786  TypeResult Ty = ParseTypeName();
1787
1788  SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
1789
1790  if (Ty.isInvalid())
1791    return ExprError();
1792
1793  return Actions.ActOnUnaryTypeTrait(UTT, Loc, LParen, Ty.get(), RParen);
1794}
1795
1796/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
1797/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
1798/// based on the context past the parens.
1799Parser::OwningExprResult
1800Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
1801                                         TypeTy *&CastTy,
1802                                         SourceLocation LParenLoc,
1803                                         SourceLocation &RParenLoc) {
1804  assert(getLang().CPlusPlus && "Should only be called for C++!");
1805  assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
1806  assert(isTypeIdInParens() && "Not a type-id!");
1807
1808  OwningExprResult Result(Actions, true);
1809  CastTy = 0;
1810
1811  // We need to disambiguate a very ugly part of the C++ syntax:
1812  //
1813  // (T())x;  - type-id
1814  // (T())*x; - type-id
1815  // (T())/x; - expression
1816  // (T());   - expression
1817  //
1818  // The bad news is that we cannot use the specialized tentative parser, since
1819  // it can only verify that the thing inside the parens can be parsed as
1820  // type-id, it is not useful for determining the context past the parens.
1821  //
1822  // The good news is that the parser can disambiguate this part without
1823  // making any unnecessary Action calls.
1824  //
1825  // It uses a scheme similar to parsing inline methods. The parenthesized
1826  // tokens are cached, the context that follows is determined (possibly by
1827  // parsing a cast-expression), and then we re-introduce the cached tokens
1828  // into the token stream and parse them appropriately.
1829
1830  ParenParseOption ParseAs;
1831  CachedTokens Toks;
1832
1833  // Store the tokens of the parentheses. We will parse them after we determine
1834  // the context that follows them.
1835  if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
1836    // We didn't find the ')' we expected.
1837    MatchRHSPunctuation(tok::r_paren, LParenLoc);
1838    return ExprError();
1839  }
1840
1841  if (Tok.is(tok::l_brace)) {
1842    ParseAs = CompoundLiteral;
1843  } else {
1844    bool NotCastExpr;
1845    // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
1846    if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
1847      NotCastExpr = true;
1848    } else {
1849      // Try parsing the cast-expression that may follow.
1850      // If it is not a cast-expression, NotCastExpr will be true and no token
1851      // will be consumed.
1852      Result = ParseCastExpression(false/*isUnaryExpression*/,
1853                                   false/*isAddressofOperand*/,
1854                                   NotCastExpr, 0/*TypeOfCast*/);
1855    }
1856
1857    // If we parsed a cast-expression, it's really a type-id, otherwise it's
1858    // an expression.
1859    ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
1860  }
1861
1862  // The current token should go after the cached tokens.
1863  Toks.push_back(Tok);
1864  // Re-enter the stored parenthesized tokens into the token stream, so we may
1865  // parse them now.
1866  PP.EnterTokenStream(Toks.data(), Toks.size(),
1867                      true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
1868  // Drop the current token and bring the first cached one. It's the same token
1869  // as when we entered this function.
1870  ConsumeAnyToken();
1871
1872  if (ParseAs >= CompoundLiteral) {
1873    TypeResult Ty = ParseTypeName();
1874
1875    // Match the ')'.
1876    if (Tok.is(tok::r_paren))
1877      RParenLoc = ConsumeParen();
1878    else
1879      MatchRHSPunctuation(tok::r_paren, LParenLoc);
1880
1881    if (ParseAs == CompoundLiteral) {
1882      ExprType = CompoundLiteral;
1883      return ParseCompoundLiteralExpression(Ty.get(), LParenLoc, RParenLoc);
1884    }
1885
1886    // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
1887    assert(ParseAs == CastExpr);
1888
1889    if (Ty.isInvalid())
1890      return ExprError();
1891
1892    CastTy = Ty.get();
1893
1894    // Result is what ParseCastExpression returned earlier.
1895    if (!Result.isInvalid())
1896      Result = Actions.ActOnCastExpr(CurScope, LParenLoc, CastTy, RParenLoc,
1897                                     move(Result));
1898    return move(Result);
1899  }
1900
1901  // Not a compound literal, and not followed by a cast-expression.
1902  assert(ParseAs == SimpleExpr);
1903
1904  ExprType = SimpleExpr;
1905  Result = ParseExpression();
1906  if (!Result.isInvalid() && Tok.is(tok::r_paren))
1907    Result = Actions.ActOnParenExpr(LParenLoc, Tok.getLocation(), move(Result));
1908
1909  // Match the ')'.
1910  if (Result.isInvalid()) {
1911    SkipUntil(tok::r_paren);
1912    return ExprError();
1913  }
1914
1915  if (Tok.is(tok::r_paren))
1916    RParenLoc = ConsumeParen();
1917  else
1918    MatchRHSPunctuation(tok::r_paren, LParenLoc);
1919
1920  return move(Result);
1921}
1922