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