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