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