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