ParseExprCXX.cpp revision 5e9392ba18f5925e26cc5714d1412eda0d219826
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      HasScopeSpecifier = true;
287
288      ASTTemplateArgsPtr TemplateArgsPtr(Actions,
289                                         TemplateId->getTemplateArgs(),
290                                         TemplateId->NumArgs);
291
292      if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
293                                              /*FIXME:*/SourceLocation(),
294                                              SS,
295                                              TemplateId->Template,
296                                              TemplateId->TemplateNameLoc,
297                                              TemplateId->LAngleLoc,
298                                              TemplateArgsPtr,
299                                              TemplateId->RAngleLoc,
300                                              CCLoc,
301                                              EnteringContext)) {
302        SourceLocation StartLoc
303          = SS.getBeginLoc().isValid()? SS.getBeginLoc()
304                                      : TemplateId->TemplateNameLoc;
305        SS.SetInvalid(SourceRange(StartLoc, CCLoc));
306      }
307
308      continue;
309    }
310
311
312    // The rest of the nested-name-specifier possibilities start with
313    // tok::identifier.
314    if (Tok.isNot(tok::identifier))
315      break;
316
317    IdentifierInfo &II = *Tok.getIdentifierInfo();
318
319    // nested-name-specifier:
320    //   type-name '::'
321    //   namespace-name '::'
322    //   nested-name-specifier identifier '::'
323    Token Next = NextToken();
324
325    // If we get foo:bar, this is almost certainly a typo for foo::bar.  Recover
326    // and emit a fixit hint for it.
327    if (Next.is(tok::colon) && !ColonIsSacred) {
328      if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
329                                            Tok.getLocation(),
330                                            Next.getLocation(), ObjectType,
331                                            EnteringContext) &&
332          // If the token after the colon isn't an identifier, it's still an
333          // error, but they probably meant something else strange so don't
334          // recover like this.
335          PP.LookAhead(1).is(tok::identifier)) {
336        Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
337          << FixItHint::CreateReplacement(Next.getLocation(), "::");
338
339        // Recover as if the user wrote '::'.
340        Next.setKind(tok::coloncolon);
341      }
342    }
343
344    if (Next.is(tok::coloncolon)) {
345      if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
346          !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
347                                                II, ObjectType)) {
348        *MayBePseudoDestructor = true;
349        return false;
350      }
351
352      // We have an identifier followed by a '::'. Lookup this name
353      // as the name in a nested-name-specifier.
354      SourceLocation IdLoc = ConsumeToken();
355      assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
356             "NextToken() not working properly!");
357      SourceLocation CCLoc = ConsumeToken();
358
359      HasScopeSpecifier = true;
360      if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
361                                              ObjectType, EnteringContext, SS))
362        SS.SetInvalid(SourceRange(IdLoc, CCLoc));
363
364      continue;
365    }
366
367    CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
368
369    // nested-name-specifier:
370    //   type-name '<'
371    if (Next.is(tok::less)) {
372      TemplateTy Template;
373      UnqualifiedId TemplateName;
374      TemplateName.setIdentifier(&II, Tok.getLocation());
375      bool MemberOfUnknownSpecialization;
376      if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
377                                              /*hasTemplateKeyword=*/false,
378                                                        TemplateName,
379                                                        ObjectType,
380                                                        EnteringContext,
381                                                        Template,
382                                              MemberOfUnknownSpecialization)) {
383        // We have found a template name, so annotate this token
384        // with a template-id annotation. We do not permit the
385        // template-id to be translated into a type annotation,
386        // because some clients (e.g., the parsing of class template
387        // specializations) still want to see the original template-id
388        // token.
389        ConsumeToken();
390        if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,
391                                    SourceLocation(), false))
392          return true;
393        continue;
394      }
395
396      if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
397          (IsTypename || IsTemplateArgumentList(1))) {
398        // We have something like t::getAs<T>, where getAs is a
399        // member of an unknown specialization. However, this will only
400        // parse correctly as a template, so suggest the keyword 'template'
401        // before 'getAs' and treat this as a dependent template name.
402        unsigned DiagID = diag::err_missing_dependent_template_keyword;
403        if (getLang().MicrosoftExt)
404          DiagID = diag::warn_missing_dependent_template_keyword;
405
406        Diag(Tok.getLocation(), DiagID)
407          << II.getName()
408          << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
409
410        if (TemplateNameKind TNK
411              = Actions.ActOnDependentTemplateName(getCurScope(),
412                                                   Tok.getLocation(), SS,
413                                                   TemplateName, ObjectType,
414                                                   EnteringContext, Template)) {
415          // Consume the identifier.
416          ConsumeToken();
417          if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,
418                                      SourceLocation(), false))
419            return true;
420        }
421        else
422          return true;
423
424        continue;
425      }
426    }
427
428    // We don't have any tokens that form the beginning of a
429    // nested-name-specifier, so we're done.
430    break;
431  }
432
433  // Even if we didn't see any pieces of a nested-name-specifier, we
434  // still check whether there is a tilde in this position, which
435  // indicates a potential pseudo-destructor.
436  if (CheckForDestructor && Tok.is(tok::tilde))
437    *MayBePseudoDestructor = true;
438
439  return false;
440}
441
442/// ParseCXXIdExpression - Handle id-expression.
443///
444///       id-expression:
445///         unqualified-id
446///         qualified-id
447///
448///       qualified-id:
449///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
450///         '::' identifier
451///         '::' operator-function-id
452///         '::' template-id
453///
454/// NOTE: The standard specifies that, for qualified-id, the parser does not
455/// expect:
456///
457///   '::' conversion-function-id
458///   '::' '~' class-name
459///
460/// This may cause a slight inconsistency on diagnostics:
461///
462/// class C {};
463/// namespace A {}
464/// void f() {
465///   :: A :: ~ C(); // Some Sema error about using destructor with a
466///                  // namespace.
467///   :: ~ C(); // Some Parser error like 'unexpected ~'.
468/// }
469///
470/// We simplify the parser a bit and make it work like:
471///
472///       qualified-id:
473///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
474///         '::' unqualified-id
475///
476/// That way Sema can handle and report similar errors for namespaces and the
477/// global scope.
478///
479/// The isAddressOfOperand parameter indicates that this id-expression is a
480/// direct operand of the address-of operator. This is, besides member contexts,
481/// the only place where a qualified-id naming a non-static class member may
482/// appear.
483///
484ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
485  // qualified-id:
486  //   '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
487  //   '::' unqualified-id
488  //
489  CXXScopeSpec SS;
490  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
491
492  UnqualifiedId Name;
493  if (ParseUnqualifiedId(SS,
494                         /*EnteringContext=*/false,
495                         /*AllowDestructorName=*/false,
496                         /*AllowConstructorName=*/false,
497                         /*ObjectType=*/ ParsedType(),
498                         Name))
499    return ExprError();
500
501  // This is only the direct operand of an & operator if it is not
502  // followed by a postfix-expression suffix.
503  if (isAddressOfOperand && isPostfixExpressionSuffixStart())
504    isAddressOfOperand = false;
505
506  return Actions.ActOnIdExpression(getCurScope(), SS, Name, Tok.is(tok::l_paren),
507                                   isAddressOfOperand);
508
509}
510
511/// ParseLambdaExpression - Parse a C++0x lambda expression.
512///
513///       lambda-expression:
514///         lambda-introducer lambda-declarator[opt] compound-statement
515///
516///       lambda-introducer:
517///         '[' lambda-capture[opt] ']'
518///
519///       lambda-capture:
520///         capture-default
521///         capture-list
522///         capture-default ',' capture-list
523///
524///       capture-default:
525///         '&'
526///         '='
527///
528///       capture-list:
529///         capture
530///         capture-list ',' capture
531///
532///       capture:
533///         identifier
534///         '&' identifier
535///         'this'
536///
537///       lambda-declarator:
538///         '(' parameter-declaration-clause ')' attribute-specifier[opt]
539///           'mutable'[opt] exception-specification[opt]
540///           trailing-return-type[opt]
541///
542ExprResult Parser::ParseLambdaExpression() {
543  // Parse lambda-introducer.
544  LambdaIntroducer Intro;
545
546  llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
547  if (DiagID) {
548    Diag(Tok, DiagID.getValue());
549    SkipUntil(tok::r_square);
550  }
551
552  return ParseLambdaExpressionAfterIntroducer(Intro);
553}
554
555/// TryParseLambdaExpression - Use lookahead and potentially tentative
556/// parsing to determine if we are looking at a C++0x lambda expression, and parse
557/// it if we are.
558///
559/// If we are not looking at a lambda expression, returns ExprError().
560ExprResult Parser::TryParseLambdaExpression() {
561  assert(getLang().CPlusPlus0x
562         && Tok.is(tok::l_square)
563         && "Not at the start of a possible lambda expression.");
564
565  const Token Next = NextToken(), After = GetLookAheadToken(2);
566
567  // If lookahead indicates this is a lambda...
568  if (Next.is(tok::r_square) ||     // []
569      Next.is(tok::equal) ||        // [=
570      (Next.is(tok::amp) &&         // [&] or [&,
571       (After.is(tok::r_square) ||
572        After.is(tok::comma))) ||
573      (Next.is(tok::identifier) &&  // [identifier]
574       After.is(tok::r_square))) {
575    return ParseLambdaExpression();
576  }
577
578  // If lookahead indicates this is an Objective-C message...
579  if (Next.is(tok::identifier) && After.is(tok::identifier)) {
580    return ExprError();
581  }
582
583  LambdaIntroducer Intro;
584  if (TryParseLambdaIntroducer(Intro))
585    return ExprError();
586  return ParseLambdaExpressionAfterIntroducer(Intro);
587}
588
589/// ParseLambdaExpression - Parse a lambda introducer.
590///
591/// Returns a DiagnosticID if it hit something unexpected.
592llvm::Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro) {
593  typedef llvm::Optional<unsigned> DiagResult;
594
595  assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
596  BalancedDelimiterTracker T(*this, tok::l_square);
597  T.consumeOpen();
598
599  Intro.Range.setBegin(T.getOpenLocation());
600
601  bool first = true;
602
603  // Parse capture-default.
604  if (Tok.is(tok::amp) &&
605      (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
606    Intro.Default = LCD_ByRef;
607    ConsumeToken();
608    first = false;
609  } else if (Tok.is(tok::equal)) {
610    Intro.Default = LCD_ByCopy;
611    ConsumeToken();
612    first = false;
613  }
614
615  while (Tok.isNot(tok::r_square)) {
616    if (!first) {
617      if (Tok.isNot(tok::comma))
618        return DiagResult(diag::err_expected_comma_or_rsquare);
619      ConsumeToken();
620    }
621
622    first = false;
623
624    // Parse capture.
625    LambdaCaptureKind Kind = LCK_ByCopy;
626    SourceLocation Loc;
627    IdentifierInfo* Id = 0;
628
629    if (Tok.is(tok::kw_this)) {
630      Kind = LCK_This;
631      Loc = ConsumeToken();
632    } else {
633      if (Tok.is(tok::amp)) {
634        Kind = LCK_ByRef;
635        ConsumeToken();
636      }
637
638      if (Tok.is(tok::identifier)) {
639        Id = Tok.getIdentifierInfo();
640        Loc = ConsumeToken();
641      } else if (Tok.is(tok::kw_this)) {
642        // FIXME: If we want to suggest a fixit here, will need to return more
643        // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
644        // Clear()ed to prevent emission in case of tentative parsing?
645        return DiagResult(diag::err_this_captured_by_reference);
646      } else {
647        return DiagResult(diag::err_expected_capture);
648      }
649    }
650
651    Intro.addCapture(Kind, Loc, Id);
652  }
653
654  T.consumeClose();
655  Intro.Range.setEnd(T.getCloseLocation());
656
657  return DiagResult();
658}
659
660/// TryParseLambdaExpression - Tentatively parse a lambda introducer.
661///
662/// Returns true if it hit something unexpected.
663bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
664  TentativeParsingAction PA(*this);
665
666  llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
667
668  if (DiagID) {
669    PA.Revert();
670    return true;
671  }
672
673  PA.Commit();
674  return false;
675}
676
677/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
678/// expression.
679ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
680                     LambdaIntroducer &Intro) {
681  Diag(Intro.Range.getBegin(), diag::warn_cxx98_compat_lambda);
682
683  // Parse lambda-declarator[opt].
684  DeclSpec DS(AttrFactory);
685  Declarator D(DS, Declarator::PrototypeContext);
686
687  if (Tok.is(tok::l_paren)) {
688    ParseScope PrototypeScope(this,
689                              Scope::FunctionPrototypeScope |
690                              Scope::DeclScope);
691
692    SourceLocation DeclLoc, DeclEndLoc;
693    BalancedDelimiterTracker T(*this, tok::l_paren);
694    T.consumeOpen();
695    DeclLoc = T.getOpenLocation();
696
697    // Parse parameter-declaration-clause.
698    ParsedAttributes Attr(AttrFactory);
699    llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
700    SourceLocation EllipsisLoc;
701
702    if (Tok.isNot(tok::r_paren))
703      ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
704
705    T.consumeClose();
706    DeclEndLoc = T.getCloseLocation();
707
708    // Parse 'mutable'[opt].
709    SourceLocation MutableLoc;
710    if (Tok.is(tok::kw_mutable)) {
711      MutableLoc = ConsumeToken();
712      DeclEndLoc = MutableLoc;
713    }
714
715    // Parse exception-specification[opt].
716    ExceptionSpecificationType ESpecType = EST_None;
717    SourceRange ESpecRange;
718    llvm::SmallVector<ParsedType, 2> DynamicExceptions;
719    llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
720    ExprResult NoexceptExpr;
721    ESpecType = MaybeParseExceptionSpecification(ESpecRange,
722                                                 DynamicExceptions,
723                                                 DynamicExceptionRanges,
724                                                 NoexceptExpr);
725
726    if (ESpecType != EST_None)
727      DeclEndLoc = ESpecRange.getEnd();
728
729    // Parse attribute-specifier[opt].
730    MaybeParseCXX0XAttributes(Attr, &DeclEndLoc);
731
732    // Parse trailing-return-type[opt].
733    ParsedType TrailingReturnType;
734    if (Tok.is(tok::arrow)) {
735      SourceRange Range;
736      TrailingReturnType = ParseTrailingReturnType(Range).get();
737      if (Range.getEnd().isValid())
738        DeclEndLoc = Range.getEnd();
739    }
740
741    PrototypeScope.Exit();
742
743    D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
744                                           /*isVariadic=*/EllipsisLoc.isValid(),
745                                           EllipsisLoc,
746                                           ParamInfo.data(), ParamInfo.size(),
747                                           DS.getTypeQualifiers(),
748                                           /*RefQualifierIsLValueRef=*/true,
749                                           /*RefQualifierLoc=*/SourceLocation(),
750                                         /*ConstQualifierLoc=*/SourceLocation(),
751                                      /*VolatileQualifierLoc=*/SourceLocation(),
752                                           MutableLoc,
753                                           ESpecType, ESpecRange.getBegin(),
754                                           DynamicExceptions.data(),
755                                           DynamicExceptionRanges.data(),
756                                           DynamicExceptions.size(),
757                                           NoexceptExpr.isUsable() ?
758                                             NoexceptExpr.get() : 0,
759                                           DeclLoc, DeclEndLoc, D,
760                                           TrailingReturnType),
761                  Attr, DeclEndLoc);
762  }
763
764  // Parse compound-statement.
765  if (Tok.is(tok::l_brace)) {
766    // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
767    // it.
768    ParseScope BodyScope(this, Scope::BlockScope | Scope::FnScope |
769                               Scope::BreakScope | Scope::ContinueScope |
770                               Scope::DeclScope);
771
772    StmtResult Stmt(ParseCompoundStatementBody());
773
774    BodyScope.Exit();
775  } else {
776    Diag(Tok, diag::err_expected_lambda_body);
777  }
778
779  return ExprEmpty();
780}
781
782/// ParseCXXCasts - This handles the various ways to cast expressions to another
783/// type.
784///
785///       postfix-expression: [C++ 5.2p1]
786///         'dynamic_cast' '<' type-name '>' '(' expression ')'
787///         'static_cast' '<' type-name '>' '(' expression ')'
788///         'reinterpret_cast' '<' type-name '>' '(' expression ')'
789///         'const_cast' '<' type-name '>' '(' expression ')'
790///
791ExprResult Parser::ParseCXXCasts() {
792  tok::TokenKind Kind = Tok.getKind();
793  const char *CastName = 0;     // For error messages
794
795  switch (Kind) {
796  default: llvm_unreachable("Unknown C++ cast!");
797  case tok::kw_const_cast:       CastName = "const_cast";       break;
798  case tok::kw_dynamic_cast:     CastName = "dynamic_cast";     break;
799  case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
800  case tok::kw_static_cast:      CastName = "static_cast";      break;
801  }
802
803  SourceLocation OpLoc = ConsumeToken();
804  SourceLocation LAngleBracketLoc = Tok.getLocation();
805
806  // Check for "<::" which is parsed as "[:".  If found, fix token stream,
807  // diagnose error, suggest fix, and recover parsing.
808  Token Next = NextToken();
809  if (Tok.is(tok::l_square) && Tok.getLength() == 2 && Next.is(tok::colon) &&
810      AreTokensAdjacent(PP, Tok, Next))
811    FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
812
813  if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
814    return ExprError();
815
816  // Parse the common declaration-specifiers piece.
817  DeclSpec DS(AttrFactory);
818  ParseSpecifierQualifierList(DS);
819
820  // Parse the abstract-declarator, if present.
821  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
822  ParseDeclarator(DeclaratorInfo);
823
824  SourceLocation RAngleBracketLoc = Tok.getLocation();
825
826  if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
827    return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
828
829  SourceLocation LParenLoc, RParenLoc;
830  BalancedDelimiterTracker T(*this, tok::l_paren);
831
832  if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
833    return ExprError();
834
835  ExprResult Result = ParseExpression();
836
837  // Match the ')'.
838  T.consumeClose();
839
840  if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
841    Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
842                                       LAngleBracketLoc, DeclaratorInfo,
843                                       RAngleBracketLoc,
844                                       T.getOpenLocation(), Result.take(),
845                                       T.getCloseLocation());
846
847  return move(Result);
848}
849
850/// ParseCXXTypeid - This handles the C++ typeid expression.
851///
852///       postfix-expression: [C++ 5.2p1]
853///         'typeid' '(' expression ')'
854///         'typeid' '(' type-id ')'
855///
856ExprResult Parser::ParseCXXTypeid() {
857  assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
858
859  SourceLocation OpLoc = ConsumeToken();
860  SourceLocation LParenLoc, RParenLoc;
861  BalancedDelimiterTracker T(*this, tok::l_paren);
862
863  // typeid expressions are always parenthesized.
864  if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
865    return ExprError();
866  LParenLoc = T.getOpenLocation();
867
868  ExprResult Result;
869
870  if (isTypeIdInParens()) {
871    TypeResult Ty = ParseTypeName();
872
873    // Match the ')'.
874    T.consumeClose();
875    RParenLoc = T.getCloseLocation();
876    if (Ty.isInvalid() || RParenLoc.isInvalid())
877      return ExprError();
878
879    Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
880                                    Ty.get().getAsOpaquePtr(), RParenLoc);
881  } else {
882    // C++0x [expr.typeid]p3:
883    //   When typeid is applied to an expression other than an lvalue of a
884    //   polymorphic class type [...] The expression is an unevaluated
885    //   operand (Clause 5).
886    //
887    // Note that we can't tell whether the expression is an lvalue of a
888    // polymorphic class type until after we've parsed the expression, so
889    // we the expression is potentially potentially evaluated.
890    EnterExpressionEvaluationContext Unevaluated(Actions,
891                                       Sema::PotentiallyPotentiallyEvaluated);
892    Result = ParseExpression();
893
894    // Match the ')'.
895    if (Result.isInvalid())
896      SkipUntil(tok::r_paren);
897    else {
898      T.consumeClose();
899      RParenLoc = T.getCloseLocation();
900      if (RParenLoc.isInvalid())
901        return ExprError();
902
903      Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
904                                      Result.release(), RParenLoc);
905    }
906  }
907
908  return move(Result);
909}
910
911/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
912///
913///         '__uuidof' '(' expression ')'
914///         '__uuidof' '(' type-id ')'
915///
916ExprResult Parser::ParseCXXUuidof() {
917  assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
918
919  SourceLocation OpLoc = ConsumeToken();
920  BalancedDelimiterTracker T(*this, tok::l_paren);
921
922  // __uuidof expressions are always parenthesized.
923  if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
924    return ExprError();
925
926  ExprResult Result;
927
928  if (isTypeIdInParens()) {
929    TypeResult Ty = ParseTypeName();
930
931    // Match the ')'.
932    T.consumeClose();
933
934    if (Ty.isInvalid())
935      return ExprError();
936
937    Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
938                                    Ty.get().getAsOpaquePtr(),
939                                    T.getCloseLocation());
940  } else {
941    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
942    Result = ParseExpression();
943
944    // Match the ')'.
945    if (Result.isInvalid())
946      SkipUntil(tok::r_paren);
947    else {
948      T.consumeClose();
949
950      Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
951                                      /*isType=*/false,
952                                      Result.release(), T.getCloseLocation());
953    }
954  }
955
956  return move(Result);
957}
958
959/// \brief Parse a C++ pseudo-destructor expression after the base,
960/// . or -> operator, and nested-name-specifier have already been
961/// parsed.
962///
963///       postfix-expression: [C++ 5.2]
964///         postfix-expression . pseudo-destructor-name
965///         postfix-expression -> pseudo-destructor-name
966///
967///       pseudo-destructor-name:
968///         ::[opt] nested-name-specifier[opt] type-name :: ~type-name
969///         ::[opt] nested-name-specifier template simple-template-id ::
970///                 ~type-name
971///         ::[opt] nested-name-specifier[opt] ~type-name
972///
973ExprResult
974Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
975                                 tok::TokenKind OpKind,
976                                 CXXScopeSpec &SS,
977                                 ParsedType ObjectType) {
978  // We're parsing either a pseudo-destructor-name or a dependent
979  // member access that has the same form as a
980  // pseudo-destructor-name. We parse both in the same way and let
981  // the action model sort them out.
982  //
983  // Note that the ::[opt] nested-name-specifier[opt] has already
984  // been parsed, and if there was a simple-template-id, it has
985  // been coalesced into a template-id annotation token.
986  UnqualifiedId FirstTypeName;
987  SourceLocation CCLoc;
988  if (Tok.is(tok::identifier)) {
989    FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
990    ConsumeToken();
991    assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
992    CCLoc = ConsumeToken();
993  } else if (Tok.is(tok::annot_template_id)) {
994    FirstTypeName.setTemplateId(
995                              (TemplateIdAnnotation *)Tok.getAnnotationValue());
996    ConsumeToken();
997    assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
998    CCLoc = ConsumeToken();
999  } else {
1000    FirstTypeName.setIdentifier(0, SourceLocation());
1001  }
1002
1003  // Parse the tilde.
1004  assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1005  SourceLocation TildeLoc = ConsumeToken();
1006  if (!Tok.is(tok::identifier)) {
1007    Diag(Tok, diag::err_destructor_tilde_identifier);
1008    return ExprError();
1009  }
1010
1011  // Parse the second type.
1012  UnqualifiedId SecondTypeName;
1013  IdentifierInfo *Name = Tok.getIdentifierInfo();
1014  SourceLocation NameLoc = ConsumeToken();
1015  SecondTypeName.setIdentifier(Name, NameLoc);
1016
1017  // If there is a '<', the second type name is a template-id. Parse
1018  // it as such.
1019  if (Tok.is(tok::less) &&
1020      ParseUnqualifiedIdTemplateId(SS, Name, NameLoc, false, ObjectType,
1021                                   SecondTypeName, /*AssumeTemplateName=*/true,
1022                                   /*TemplateKWLoc*/SourceLocation()))
1023    return ExprError();
1024
1025  return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1026                                           OpLoc, OpKind,
1027                                           SS, FirstTypeName, CCLoc,
1028                                           TildeLoc, SecondTypeName,
1029                                           Tok.is(tok::l_paren));
1030}
1031
1032/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1033///
1034///       boolean-literal: [C++ 2.13.5]
1035///         'true'
1036///         'false'
1037ExprResult Parser::ParseCXXBoolLiteral() {
1038  tok::TokenKind Kind = Tok.getKind();
1039  return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1040}
1041
1042/// ParseThrowExpression - This handles the C++ throw expression.
1043///
1044///       throw-expression: [C++ 15]
1045///         'throw' assignment-expression[opt]
1046ExprResult Parser::ParseThrowExpression() {
1047  assert(Tok.is(tok::kw_throw) && "Not throw!");
1048  SourceLocation ThrowLoc = ConsumeToken();           // Eat the throw token.
1049
1050  // If the current token isn't the start of an assignment-expression,
1051  // then the expression is not present.  This handles things like:
1052  //   "C ? throw : (void)42", which is crazy but legal.
1053  switch (Tok.getKind()) {  // FIXME: move this predicate somewhere common.
1054  case tok::semi:
1055  case tok::r_paren:
1056  case tok::r_square:
1057  case tok::r_brace:
1058  case tok::colon:
1059  case tok::comma:
1060    return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
1061
1062  default:
1063    ExprResult Expr(ParseAssignmentExpression());
1064    if (Expr.isInvalid()) return move(Expr);
1065    return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
1066  }
1067}
1068
1069/// ParseCXXThis - This handles the C++ 'this' pointer.
1070///
1071/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1072/// a non-lvalue expression whose value is the address of the object for which
1073/// the function is called.
1074ExprResult Parser::ParseCXXThis() {
1075  assert(Tok.is(tok::kw_this) && "Not 'this'!");
1076  SourceLocation ThisLoc = ConsumeToken();
1077  return Actions.ActOnCXXThis(ThisLoc);
1078}
1079
1080/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1081/// Can be interpreted either as function-style casting ("int(x)")
1082/// or class type construction ("ClassType(x,y,z)")
1083/// or creation of a value-initialized type ("int()").
1084/// See [C++ 5.2.3].
1085///
1086///       postfix-expression: [C++ 5.2p1]
1087///         simple-type-specifier '(' expression-list[opt] ')'
1088/// [C++0x] simple-type-specifier braced-init-list
1089///         typename-specifier '(' expression-list[opt] ')'
1090/// [C++0x] typename-specifier braced-init-list
1091///
1092ExprResult
1093Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1094  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1095  ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1096
1097  assert((Tok.is(tok::l_paren) ||
1098          (getLang().CPlusPlus0x && Tok.is(tok::l_brace)))
1099         && "Expected '(' or '{'!");
1100
1101  if (Tok.is(tok::l_brace)) {
1102
1103    // FIXME: Convert to a proper type construct expression.
1104    return ParseBraceInitializer();
1105
1106  } else {
1107    GreaterThanIsOperatorScope G(GreaterThanIsOperator, true);
1108
1109    BalancedDelimiterTracker T(*this, tok::l_paren);
1110    T.consumeOpen();
1111
1112    ExprVector Exprs(Actions);
1113    CommaLocsTy CommaLocs;
1114
1115    if (Tok.isNot(tok::r_paren)) {
1116      if (ParseExpressionList(Exprs, CommaLocs)) {
1117        SkipUntil(tok::r_paren);
1118        return ExprError();
1119      }
1120    }
1121
1122    // Match the ')'.
1123    T.consumeClose();
1124
1125    // TypeRep could be null, if it references an invalid typedef.
1126    if (!TypeRep)
1127      return ExprError();
1128
1129    assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1130           "Unexpected number of commas!");
1131    return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1132                                             move_arg(Exprs),
1133                                             T.getCloseLocation());
1134  }
1135}
1136
1137/// ParseCXXCondition - if/switch/while condition expression.
1138///
1139///       condition:
1140///         expression
1141///         type-specifier-seq declarator '=' assignment-expression
1142/// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1143///             '=' assignment-expression
1144///
1145/// \param ExprResult if the condition was parsed as an expression, the
1146/// parsed expression.
1147///
1148/// \param DeclResult if the condition was parsed as a declaration, the
1149/// parsed declaration.
1150///
1151/// \param Loc The location of the start of the statement that requires this
1152/// condition, e.g., the "for" in a for loop.
1153///
1154/// \param ConvertToBoolean Whether the condition expression should be
1155/// converted to a boolean value.
1156///
1157/// \returns true if there was a parsing, false otherwise.
1158bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1159                               Decl *&DeclOut,
1160                               SourceLocation Loc,
1161                               bool ConvertToBoolean) {
1162  if (Tok.is(tok::code_completion)) {
1163    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1164    cutOffParsing();
1165    return true;
1166  }
1167
1168  if (!isCXXConditionDeclaration()) {
1169    // Parse the expression.
1170    ExprOut = ParseExpression(); // expression
1171    DeclOut = 0;
1172    if (ExprOut.isInvalid())
1173      return true;
1174
1175    // If required, convert to a boolean value.
1176    if (ConvertToBoolean)
1177      ExprOut
1178        = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1179    return ExprOut.isInvalid();
1180  }
1181
1182  // type-specifier-seq
1183  DeclSpec DS(AttrFactory);
1184  ParseSpecifierQualifierList(DS);
1185
1186  // declarator
1187  Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1188  ParseDeclarator(DeclaratorInfo);
1189
1190  // simple-asm-expr[opt]
1191  if (Tok.is(tok::kw_asm)) {
1192    SourceLocation Loc;
1193    ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1194    if (AsmLabel.isInvalid()) {
1195      SkipUntil(tok::semi);
1196      return true;
1197    }
1198    DeclaratorInfo.setAsmLabel(AsmLabel.release());
1199    DeclaratorInfo.SetRangeEnd(Loc);
1200  }
1201
1202  // If attributes are present, parse them.
1203  MaybeParseGNUAttributes(DeclaratorInfo);
1204
1205  // Type-check the declaration itself.
1206  DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
1207                                                        DeclaratorInfo);
1208  DeclOut = Dcl.get();
1209  ExprOut = ExprError();
1210
1211  // '=' assignment-expression
1212  if (isTokenEqualOrMistypedEqualEqual(
1213                               diag::err_invalid_equalequal_after_declarator)) {
1214    ConsumeToken();
1215    ExprResult AssignExpr(ParseAssignmentExpression());
1216    if (!AssignExpr.isInvalid())
1217      Actions.AddInitializerToDecl(DeclOut, AssignExpr.take(), false,
1218                                   DS.getTypeSpecType() == DeclSpec::TST_auto);
1219  } else {
1220    // FIXME: C++0x allows a braced-init-list
1221    Diag(Tok, diag::err_expected_equal_after_declarator);
1222  }
1223
1224  // FIXME: Build a reference to this declaration? Convert it to bool?
1225  // (This is currently handled by Sema).
1226
1227  Actions.FinalizeDeclaration(DeclOut);
1228
1229  return false;
1230}
1231
1232/// \brief Determine whether the current token starts a C++
1233/// simple-type-specifier.
1234bool Parser::isCXXSimpleTypeSpecifier() const {
1235  switch (Tok.getKind()) {
1236  case tok::annot_typename:
1237  case tok::kw_short:
1238  case tok::kw_long:
1239  case tok::kw___int64:
1240  case tok::kw_signed:
1241  case tok::kw_unsigned:
1242  case tok::kw_void:
1243  case tok::kw_char:
1244  case tok::kw_int:
1245  case tok::kw_half:
1246  case tok::kw_float:
1247  case tok::kw_double:
1248  case tok::kw_wchar_t:
1249  case tok::kw_char16_t:
1250  case tok::kw_char32_t:
1251  case tok::kw_bool:
1252  case tok::kw_decltype:
1253  case tok::kw_typeof:
1254  case tok::kw___underlying_type:
1255    return true;
1256
1257  default:
1258    break;
1259  }
1260
1261  return false;
1262}
1263
1264/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1265/// This should only be called when the current token is known to be part of
1266/// simple-type-specifier.
1267///
1268///       simple-type-specifier:
1269///         '::'[opt] nested-name-specifier[opt] type-name
1270///         '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1271///         char
1272///         wchar_t
1273///         bool
1274///         short
1275///         int
1276///         long
1277///         signed
1278///         unsigned
1279///         float
1280///         double
1281///         void
1282/// [GNU]   typeof-specifier
1283/// [C++0x] auto               [TODO]
1284///
1285///       type-name:
1286///         class-name
1287///         enum-name
1288///         typedef-name
1289///
1290void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1291  DS.SetRangeStart(Tok.getLocation());
1292  const char *PrevSpec;
1293  unsigned DiagID;
1294  SourceLocation Loc = Tok.getLocation();
1295
1296  switch (Tok.getKind()) {
1297  case tok::identifier:   // foo::bar
1298  case tok::coloncolon:   // ::foo::bar
1299    llvm_unreachable("Annotation token should already be formed!");
1300  default:
1301    llvm_unreachable("Not a simple-type-specifier token!");
1302
1303  // type-name
1304  case tok::annot_typename: {
1305    if (getTypeAnnotation(Tok))
1306      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1307                         getTypeAnnotation(Tok));
1308    else
1309      DS.SetTypeSpecError();
1310
1311    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1312    ConsumeToken();
1313
1314    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1315    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1316    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1317    // just a normal reference to a typedef name.
1318    if (Tok.is(tok::less) && getLang().ObjC1)
1319      ParseObjCProtocolQualifiers(DS);
1320
1321    DS.Finish(Diags, PP);
1322    return;
1323  }
1324
1325  // builtin types
1326  case tok::kw_short:
1327    DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1328    break;
1329  case tok::kw_long:
1330    DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
1331    break;
1332  case tok::kw___int64:
1333    DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1334    break;
1335  case tok::kw_signed:
1336    DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1337    break;
1338  case tok::kw_unsigned:
1339    DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1340    break;
1341  case tok::kw_void:
1342    DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1343    break;
1344  case tok::kw_char:
1345    DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1346    break;
1347  case tok::kw_int:
1348    DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1349    break;
1350  case tok::kw_half:
1351    DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
1352    break;
1353  case tok::kw_float:
1354    DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1355    break;
1356  case tok::kw_double:
1357    DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1358    break;
1359  case tok::kw_wchar_t:
1360    DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1361    break;
1362  case tok::kw_char16_t:
1363    DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1364    break;
1365  case tok::kw_char32_t:
1366    DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1367    break;
1368  case tok::kw_bool:
1369    DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1370    break;
1371
1372    // FIXME: C++0x decltype support.
1373  // GNU typeof support.
1374  case tok::kw_typeof:
1375    ParseTypeofSpecifier(DS);
1376    DS.Finish(Diags, PP);
1377    return;
1378  }
1379  if (Tok.is(tok::annot_typename))
1380    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1381  else
1382    DS.SetRangeEnd(Tok.getLocation());
1383  ConsumeToken();
1384  DS.Finish(Diags, PP);
1385}
1386
1387/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1388/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1389/// e.g., "const short int". Note that the DeclSpec is *not* finished
1390/// by parsing the type-specifier-seq, because these sequences are
1391/// typically followed by some form of declarator. Returns true and
1392/// emits diagnostics if this is not a type-specifier-seq, false
1393/// otherwise.
1394///
1395///   type-specifier-seq: [C++ 8.1]
1396///     type-specifier type-specifier-seq[opt]
1397///
1398bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1399  DS.SetRangeStart(Tok.getLocation());
1400  const char *PrevSpec = 0;
1401  unsigned DiagID;
1402  bool isInvalid = 0;
1403
1404  // Parse one or more of the type specifiers.
1405  if (!ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1406      ParsedTemplateInfo(), /*SuppressDeclarations*/true)) {
1407    Diag(Tok, diag::err_expected_type);
1408    return true;
1409  }
1410
1411  while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1412         ParsedTemplateInfo(), /*SuppressDeclarations*/true))
1413  {}
1414
1415  DS.Finish(Diags, PP);
1416  return false;
1417}
1418
1419/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1420/// some form.
1421///
1422/// This routine is invoked when a '<' is encountered after an identifier or
1423/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1424/// whether the unqualified-id is actually a template-id. This routine will
1425/// then parse the template arguments and form the appropriate template-id to
1426/// return to the caller.
1427///
1428/// \param SS the nested-name-specifier that precedes this template-id, if
1429/// we're actually parsing a qualified-id.
1430///
1431/// \param Name for constructor and destructor names, this is the actual
1432/// identifier that may be a template-name.
1433///
1434/// \param NameLoc the location of the class-name in a constructor or
1435/// destructor.
1436///
1437/// \param EnteringContext whether we're entering the scope of the
1438/// nested-name-specifier.
1439///
1440/// \param ObjectType if this unqualified-id occurs within a member access
1441/// expression, the type of the base object whose member is being accessed.
1442///
1443/// \param Id as input, describes the template-name or operator-function-id
1444/// that precedes the '<'. If template arguments were parsed successfully,
1445/// will be updated with the template-id.
1446///
1447/// \param AssumeTemplateId When true, this routine will assume that the name
1448/// refers to a template without performing name lookup to verify.
1449///
1450/// \returns true if a parse error occurred, false otherwise.
1451bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1452                                          IdentifierInfo *Name,
1453                                          SourceLocation NameLoc,
1454                                          bool EnteringContext,
1455                                          ParsedType ObjectType,
1456                                          UnqualifiedId &Id,
1457                                          bool AssumeTemplateId,
1458                                          SourceLocation TemplateKWLoc) {
1459  assert((AssumeTemplateId || Tok.is(tok::less)) &&
1460         "Expected '<' to finish parsing a template-id");
1461
1462  TemplateTy Template;
1463  TemplateNameKind TNK = TNK_Non_template;
1464  switch (Id.getKind()) {
1465  case UnqualifiedId::IK_Identifier:
1466  case UnqualifiedId::IK_OperatorFunctionId:
1467  case UnqualifiedId::IK_LiteralOperatorId:
1468    if (AssumeTemplateId) {
1469      TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, SS,
1470                                               Id, ObjectType, EnteringContext,
1471                                               Template);
1472      if (TNK == TNK_Non_template)
1473        return true;
1474    } else {
1475      bool MemberOfUnknownSpecialization;
1476      TNK = Actions.isTemplateName(getCurScope(), SS,
1477                                   TemplateKWLoc.isValid(), Id,
1478                                   ObjectType, EnteringContext, Template,
1479                                   MemberOfUnknownSpecialization);
1480
1481      if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1482          ObjectType && IsTemplateArgumentList()) {
1483        // We have something like t->getAs<T>(), where getAs is a
1484        // member of an unknown specialization. However, this will only
1485        // parse correctly as a template, so suggest the keyword 'template'
1486        // before 'getAs' and treat this as a dependent template name.
1487        std::string Name;
1488        if (Id.getKind() == UnqualifiedId::IK_Identifier)
1489          Name = Id.Identifier->getName();
1490        else {
1491          Name = "operator ";
1492          if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1493            Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1494          else
1495            Name += Id.Identifier->getName();
1496        }
1497        Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1498          << Name
1499          << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1500        TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc,
1501                                                 SS, Id, ObjectType,
1502                                                 EnteringContext, Template);
1503        if (TNK == TNK_Non_template)
1504          return true;
1505      }
1506    }
1507    break;
1508
1509  case UnqualifiedId::IK_ConstructorName: {
1510    UnqualifiedId TemplateName;
1511    bool MemberOfUnknownSpecialization;
1512    TemplateName.setIdentifier(Name, NameLoc);
1513    TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1514                                 TemplateName, ObjectType,
1515                                 EnteringContext, Template,
1516                                 MemberOfUnknownSpecialization);
1517    break;
1518  }
1519
1520  case UnqualifiedId::IK_DestructorName: {
1521    UnqualifiedId TemplateName;
1522    bool MemberOfUnknownSpecialization;
1523    TemplateName.setIdentifier(Name, NameLoc);
1524    if (ObjectType) {
1525      TNK = Actions.ActOnDependentTemplateName(getCurScope(), TemplateKWLoc, SS,
1526                                               TemplateName, ObjectType,
1527                                               EnteringContext, Template);
1528      if (TNK == TNK_Non_template)
1529        return true;
1530    } else {
1531      TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1532                                   TemplateName, ObjectType,
1533                                   EnteringContext, Template,
1534                                   MemberOfUnknownSpecialization);
1535
1536      if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
1537        Diag(NameLoc, diag::err_destructor_template_id)
1538          << Name << SS.getRange();
1539        return true;
1540      }
1541    }
1542    break;
1543  }
1544
1545  default:
1546    return false;
1547  }
1548
1549  if (TNK == TNK_Non_template)
1550    return false;
1551
1552  // Parse the enclosed template argument list.
1553  SourceLocation LAngleLoc, RAngleLoc;
1554  TemplateArgList TemplateArgs;
1555  if (Tok.is(tok::less) &&
1556      ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
1557                                       SS, true, LAngleLoc,
1558                                       TemplateArgs,
1559                                       RAngleLoc))
1560    return true;
1561
1562  if (Id.getKind() == UnqualifiedId::IK_Identifier ||
1563      Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1564      Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
1565    // Form a parsed representation of the template-id to be stored in the
1566    // UnqualifiedId.
1567    TemplateIdAnnotation *TemplateId
1568      = TemplateIdAnnotation::Allocate(TemplateArgs.size());
1569
1570    if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1571      TemplateId->Name = Id.Identifier;
1572      TemplateId->Operator = OO_None;
1573      TemplateId->TemplateNameLoc = Id.StartLocation;
1574    } else {
1575      TemplateId->Name = 0;
1576      TemplateId->Operator = Id.OperatorFunctionId.Operator;
1577      TemplateId->TemplateNameLoc = Id.StartLocation;
1578    }
1579
1580    TemplateId->SS = SS;
1581    TemplateId->Template = Template;
1582    TemplateId->Kind = TNK;
1583    TemplateId->LAngleLoc = LAngleLoc;
1584    TemplateId->RAngleLoc = RAngleLoc;
1585    ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1586    for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
1587         Arg != ArgEnd; ++Arg)
1588      Args[Arg] = TemplateArgs[Arg];
1589
1590    Id.setTemplateId(TemplateId);
1591    return false;
1592  }
1593
1594  // Bundle the template arguments together.
1595  ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
1596                                     TemplateArgs.size());
1597
1598  // Constructor and destructor names.
1599  TypeResult Type
1600    = Actions.ActOnTemplateIdType(SS, Template, NameLoc,
1601                                  LAngleLoc, TemplateArgsPtr,
1602                                  RAngleLoc);
1603  if (Type.isInvalid())
1604    return true;
1605
1606  if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1607    Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1608  else
1609    Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1610
1611  return false;
1612}
1613
1614/// \brief Parse an operator-function-id or conversion-function-id as part
1615/// of a C++ unqualified-id.
1616///
1617/// This routine is responsible only for parsing the operator-function-id or
1618/// conversion-function-id; it does not handle template arguments in any way.
1619///
1620/// \code
1621///       operator-function-id: [C++ 13.5]
1622///         'operator' operator
1623///
1624///       operator: one of
1625///            new   delete  new[]   delete[]
1626///            +     -    *  /    %  ^    &   |   ~
1627///            !     =    <  >    += -=   *=  /=  %=
1628///            ^=    &=   |= <<   >> >>= <<=  ==  !=
1629///            <=    >=   && ||   ++ --   ,   ->* ->
1630///            ()    []
1631///
1632///       conversion-function-id: [C++ 12.3.2]
1633///         operator conversion-type-id
1634///
1635///       conversion-type-id:
1636///         type-specifier-seq conversion-declarator[opt]
1637///
1638///       conversion-declarator:
1639///         ptr-operator conversion-declarator[opt]
1640/// \endcode
1641///
1642/// \param The nested-name-specifier that preceded this unqualified-id. If
1643/// non-empty, then we are parsing the unqualified-id of a qualified-id.
1644///
1645/// \param EnteringContext whether we are entering the scope of the
1646/// nested-name-specifier.
1647///
1648/// \param ObjectType if this unqualified-id occurs within a member access
1649/// expression, the type of the base object whose member is being accessed.
1650///
1651/// \param Result on a successful parse, contains the parsed unqualified-id.
1652///
1653/// \returns true if parsing fails, false otherwise.
1654bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
1655                                        ParsedType ObjectType,
1656                                        UnqualifiedId &Result) {
1657  assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
1658
1659  // Consume the 'operator' keyword.
1660  SourceLocation KeywordLoc = ConsumeToken();
1661
1662  // Determine what kind of operator name we have.
1663  unsigned SymbolIdx = 0;
1664  SourceLocation SymbolLocations[3];
1665  OverloadedOperatorKind Op = OO_None;
1666  switch (Tok.getKind()) {
1667    case tok::kw_new:
1668    case tok::kw_delete: {
1669      bool isNew = Tok.getKind() == tok::kw_new;
1670      // Consume the 'new' or 'delete'.
1671      SymbolLocations[SymbolIdx++] = ConsumeToken();
1672      if (Tok.is(tok::l_square)) {
1673        // Consume the '[' and ']'.
1674        BalancedDelimiterTracker T(*this, tok::l_square);
1675        T.consumeOpen();
1676        T.consumeClose();
1677        if (T.getCloseLocation().isInvalid())
1678          return true;
1679
1680        SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1681        SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1682        Op = isNew? OO_Array_New : OO_Array_Delete;
1683      } else {
1684        Op = isNew? OO_New : OO_Delete;
1685      }
1686      break;
1687    }
1688
1689#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1690    case tok::Token:                                                     \
1691      SymbolLocations[SymbolIdx++] = ConsumeToken();                     \
1692      Op = OO_##Name;                                                    \
1693      break;
1694#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
1695#include "clang/Basic/OperatorKinds.def"
1696
1697    case tok::l_paren: {
1698      // Consume the '(' and ')'.
1699      BalancedDelimiterTracker T(*this, tok::l_paren);
1700      T.consumeOpen();
1701      T.consumeClose();
1702      if (T.getCloseLocation().isInvalid())
1703        return true;
1704
1705      SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1706      SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1707      Op = OO_Call;
1708      break;
1709    }
1710
1711    case tok::l_square: {
1712      // Consume the '[' and ']'.
1713      BalancedDelimiterTracker T(*this, tok::l_square);
1714      T.consumeOpen();
1715      T.consumeClose();
1716      if (T.getCloseLocation().isInvalid())
1717        return true;
1718
1719      SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1720      SymbolLocations[SymbolIdx++] = T.getCloseLocation();
1721      Op = OO_Subscript;
1722      break;
1723    }
1724
1725    case tok::code_completion: {
1726      // Code completion for the operator name.
1727      Actions.CodeCompleteOperatorName(getCurScope());
1728      cutOffParsing();
1729      // Don't try to parse any further.
1730      return true;
1731    }
1732
1733    default:
1734      break;
1735  }
1736
1737  if (Op != OO_None) {
1738    // We have parsed an operator-function-id.
1739    Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
1740    return false;
1741  }
1742
1743  // Parse a literal-operator-id.
1744  //
1745  //   literal-operator-id: [C++0x 13.5.8]
1746  //     operator "" identifier
1747
1748  if (getLang().CPlusPlus0x && Tok.is(tok::string_literal)) {
1749    Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
1750    if (Tok.getLength() != 2)
1751      Diag(Tok.getLocation(), diag::err_operator_string_not_empty);
1752    ConsumeStringToken();
1753
1754    if (Tok.isNot(tok::identifier)) {
1755      Diag(Tok.getLocation(), diag::err_expected_ident);
1756      return true;
1757    }
1758
1759    IdentifierInfo *II = Tok.getIdentifierInfo();
1760    Result.setLiteralOperatorId(II, KeywordLoc, ConsumeToken());
1761    return false;
1762  }
1763
1764  // Parse a conversion-function-id.
1765  //
1766  //   conversion-function-id: [C++ 12.3.2]
1767  //     operator conversion-type-id
1768  //
1769  //   conversion-type-id:
1770  //     type-specifier-seq conversion-declarator[opt]
1771  //
1772  //   conversion-declarator:
1773  //     ptr-operator conversion-declarator[opt]
1774
1775  // Parse the type-specifier-seq.
1776  DeclSpec DS(AttrFactory);
1777  if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
1778    return true;
1779
1780  // Parse the conversion-declarator, which is merely a sequence of
1781  // ptr-operators.
1782  Declarator D(DS, Declarator::TypeNameContext);
1783  ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
1784
1785  // Finish up the type.
1786  TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
1787  if (Ty.isInvalid())
1788    return true;
1789
1790  // Note that this is a conversion-function-id.
1791  Result.setConversionFunctionId(KeywordLoc, Ty.get(),
1792                                 D.getSourceRange().getEnd());
1793  return false;
1794}
1795
1796/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
1797/// name of an entity.
1798///
1799/// \code
1800///       unqualified-id: [C++ expr.prim.general]
1801///         identifier
1802///         operator-function-id
1803///         conversion-function-id
1804/// [C++0x] literal-operator-id [TODO]
1805///         ~ class-name
1806///         template-id
1807///
1808/// \endcode
1809///
1810/// \param The nested-name-specifier that preceded this unqualified-id. If
1811/// non-empty, then we are parsing the unqualified-id of a qualified-id.
1812///
1813/// \param EnteringContext whether we are entering the scope of the
1814/// nested-name-specifier.
1815///
1816/// \param AllowDestructorName whether we allow parsing of a destructor name.
1817///
1818/// \param AllowConstructorName whether we allow parsing a constructor name.
1819///
1820/// \param ObjectType if this unqualified-id occurs within a member access
1821/// expression, the type of the base object whose member is being accessed.
1822///
1823/// \param Result on a successful parse, contains the parsed unqualified-id.
1824///
1825/// \returns true if parsing fails, false otherwise.
1826bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
1827                                bool AllowDestructorName,
1828                                bool AllowConstructorName,
1829                                ParsedType ObjectType,
1830                                UnqualifiedId &Result) {
1831
1832  // Handle 'A::template B'. This is for template-ids which have not
1833  // already been annotated by ParseOptionalCXXScopeSpecifier().
1834  bool TemplateSpecified = false;
1835  SourceLocation TemplateKWLoc;
1836  if (getLang().CPlusPlus && Tok.is(tok::kw_template) &&
1837      (ObjectType || SS.isSet())) {
1838    TemplateSpecified = true;
1839    TemplateKWLoc = ConsumeToken();
1840  }
1841
1842  // unqualified-id:
1843  //   identifier
1844  //   template-id (when it hasn't already been annotated)
1845  if (Tok.is(tok::identifier)) {
1846    // Consume the identifier.
1847    IdentifierInfo *Id = Tok.getIdentifierInfo();
1848    SourceLocation IdLoc = ConsumeToken();
1849
1850    if (!getLang().CPlusPlus) {
1851      // If we're not in C++, only identifiers matter. Record the
1852      // identifier and return.
1853      Result.setIdentifier(Id, IdLoc);
1854      return false;
1855    }
1856
1857    if (AllowConstructorName &&
1858        Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
1859      // We have parsed a constructor name.
1860      Result.setConstructorName(Actions.getTypeName(*Id, IdLoc, getCurScope(),
1861                                                    &SS, false, false,
1862                                                    ParsedType(),
1863                                            /*NonTrivialTypeSourceInfo=*/true),
1864                                IdLoc, IdLoc);
1865    } else {
1866      // We have parsed an identifier.
1867      Result.setIdentifier(Id, IdLoc);
1868    }
1869
1870    // If the next token is a '<', we may have a template.
1871    if (TemplateSpecified || Tok.is(tok::less))
1872      return ParseUnqualifiedIdTemplateId(SS, Id, IdLoc, EnteringContext,
1873                                          ObjectType, Result,
1874                                          TemplateSpecified, TemplateKWLoc);
1875
1876    return false;
1877  }
1878
1879  // unqualified-id:
1880  //   template-id (already parsed and annotated)
1881  if (Tok.is(tok::annot_template_id)) {
1882    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1883
1884    // If the template-name names the current class, then this is a constructor
1885    if (AllowConstructorName && TemplateId->Name &&
1886        Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
1887      if (SS.isSet()) {
1888        // C++ [class.qual]p2 specifies that a qualified template-name
1889        // is taken as the constructor name where a constructor can be
1890        // declared. Thus, the template arguments are extraneous, so
1891        // complain about them and remove them entirely.
1892        Diag(TemplateId->TemplateNameLoc,
1893             diag::err_out_of_line_constructor_template_id)
1894          << TemplateId->Name
1895          << FixItHint::CreateRemoval(
1896                    SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
1897        Result.setConstructorName(Actions.getTypeName(*TemplateId->Name,
1898                                                  TemplateId->TemplateNameLoc,
1899                                                      getCurScope(),
1900                                                      &SS, false, false,
1901                                                      ParsedType(),
1902                                            /*NontrivialTypeSourceInfo=*/true),
1903                                  TemplateId->TemplateNameLoc,
1904                                  TemplateId->RAngleLoc);
1905        ConsumeToken();
1906        return false;
1907      }
1908
1909      Result.setConstructorTemplateId(TemplateId);
1910      ConsumeToken();
1911      return false;
1912    }
1913
1914    // We have already parsed a template-id; consume the annotation token as
1915    // our unqualified-id.
1916    Result.setTemplateId(TemplateId);
1917    ConsumeToken();
1918    return false;
1919  }
1920
1921  // unqualified-id:
1922  //   operator-function-id
1923  //   conversion-function-id
1924  if (Tok.is(tok::kw_operator)) {
1925    if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
1926      return true;
1927
1928    // If we have an operator-function-id or a literal-operator-id and the next
1929    // token is a '<', we may have a
1930    //
1931    //   template-id:
1932    //     operator-function-id < template-argument-list[opt] >
1933    if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1934         Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
1935        (TemplateSpecified || Tok.is(tok::less)))
1936      return ParseUnqualifiedIdTemplateId(SS, 0, SourceLocation(),
1937                                          EnteringContext, ObjectType,
1938                                          Result,
1939                                          TemplateSpecified, TemplateKWLoc);
1940
1941    return false;
1942  }
1943
1944  if (getLang().CPlusPlus &&
1945      (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
1946    // C++ [expr.unary.op]p10:
1947    //   There is an ambiguity in the unary-expression ~X(), where X is a
1948    //   class-name. The ambiguity is resolved in favor of treating ~ as a
1949    //    unary complement rather than treating ~X as referring to a destructor.
1950
1951    // Parse the '~'.
1952    SourceLocation TildeLoc = ConsumeToken();
1953
1954    // Parse the class-name.
1955    if (Tok.isNot(tok::identifier)) {
1956      Diag(Tok, diag::err_destructor_tilde_identifier);
1957      return true;
1958    }
1959
1960    // Parse the class-name (or template-name in a simple-template-id).
1961    IdentifierInfo *ClassName = Tok.getIdentifierInfo();
1962    SourceLocation ClassNameLoc = ConsumeToken();
1963
1964    if (TemplateSpecified || Tok.is(tok::less)) {
1965      Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
1966      return ParseUnqualifiedIdTemplateId(SS, ClassName, ClassNameLoc,
1967                                          EnteringContext, ObjectType, Result,
1968                                          TemplateSpecified, TemplateKWLoc);
1969    }
1970
1971    // Note that this is a destructor name.
1972    ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
1973                                              ClassNameLoc, getCurScope(),
1974                                              SS, ObjectType,
1975                                              EnteringContext);
1976    if (!Ty)
1977      return true;
1978
1979    Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
1980    return false;
1981  }
1982
1983  Diag(Tok, diag::err_expected_unqualified_id)
1984    << getLang().CPlusPlus;
1985  return true;
1986}
1987
1988/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
1989/// memory in a typesafe manner and call constructors.
1990///
1991/// This method is called to parse the new expression after the optional :: has
1992/// been already parsed.  If the :: was present, "UseGlobal" is true and "Start"
1993/// is its location.  Otherwise, "Start" is the location of the 'new' token.
1994///
1995///        new-expression:
1996///                   '::'[opt] 'new' new-placement[opt] new-type-id
1997///                                     new-initializer[opt]
1998///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
1999///                                     new-initializer[opt]
2000///
2001///        new-placement:
2002///                   '(' expression-list ')'
2003///
2004///        new-type-id:
2005///                   type-specifier-seq new-declarator[opt]
2006/// [GNU]             attributes type-specifier-seq new-declarator[opt]
2007///
2008///        new-declarator:
2009///                   ptr-operator new-declarator[opt]
2010///                   direct-new-declarator
2011///
2012///        new-initializer:
2013///                   '(' expression-list[opt] ')'
2014/// [C++0x]           braced-init-list
2015///
2016ExprResult
2017Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2018  assert(Tok.is(tok::kw_new) && "expected 'new' token");
2019  ConsumeToken();   // Consume 'new'
2020
2021  // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2022  // second form of new-expression. It can't be a new-type-id.
2023
2024  ExprVector PlacementArgs(Actions);
2025  SourceLocation PlacementLParen, PlacementRParen;
2026
2027  SourceRange TypeIdParens;
2028  DeclSpec DS(AttrFactory);
2029  Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2030  if (Tok.is(tok::l_paren)) {
2031    // If it turns out to be a placement, we change the type location.
2032    BalancedDelimiterTracker T(*this, tok::l_paren);
2033    T.consumeOpen();
2034    PlacementLParen = T.getOpenLocation();
2035    if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2036      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2037      return ExprError();
2038    }
2039
2040    T.consumeClose();
2041    PlacementRParen = T.getCloseLocation();
2042    if (PlacementRParen.isInvalid()) {
2043      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2044      return ExprError();
2045    }
2046
2047    if (PlacementArgs.empty()) {
2048      // Reset the placement locations. There was no placement.
2049      TypeIdParens = T.getRange();
2050      PlacementLParen = PlacementRParen = SourceLocation();
2051    } else {
2052      // We still need the type.
2053      if (Tok.is(tok::l_paren)) {
2054        BalancedDelimiterTracker T(*this, tok::l_paren);
2055        T.consumeOpen();
2056        MaybeParseGNUAttributes(DeclaratorInfo);
2057        ParseSpecifierQualifierList(DS);
2058        DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2059        ParseDeclarator(DeclaratorInfo);
2060        T.consumeClose();
2061        TypeIdParens = T.getRange();
2062      } else {
2063        MaybeParseGNUAttributes(DeclaratorInfo);
2064        if (ParseCXXTypeSpecifierSeq(DS))
2065          DeclaratorInfo.setInvalidType(true);
2066        else {
2067          DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2068          ParseDeclaratorInternal(DeclaratorInfo,
2069                                  &Parser::ParseDirectNewDeclarator);
2070        }
2071      }
2072    }
2073  } else {
2074    // A new-type-id is a simplified type-id, where essentially the
2075    // direct-declarator is replaced by a direct-new-declarator.
2076    MaybeParseGNUAttributes(DeclaratorInfo);
2077    if (ParseCXXTypeSpecifierSeq(DS))
2078      DeclaratorInfo.setInvalidType(true);
2079    else {
2080      DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2081      ParseDeclaratorInternal(DeclaratorInfo,
2082                              &Parser::ParseDirectNewDeclarator);
2083    }
2084  }
2085  if (DeclaratorInfo.isInvalidType()) {
2086    SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2087    return ExprError();
2088  }
2089
2090  ExprVector ConstructorArgs(Actions);
2091  SourceLocation ConstructorLParen, ConstructorRParen;
2092
2093  if (Tok.is(tok::l_paren)) {
2094    BalancedDelimiterTracker T(*this, tok::l_paren);
2095    T.consumeOpen();
2096    ConstructorLParen = T.getOpenLocation();
2097    if (Tok.isNot(tok::r_paren)) {
2098      CommaLocsTy CommaLocs;
2099      if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2100        SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2101        return ExprError();
2102      }
2103    }
2104    T.consumeClose();
2105    ConstructorRParen = T.getCloseLocation();
2106    if (ConstructorRParen.isInvalid()) {
2107      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
2108      return ExprError();
2109    }
2110  } else if (Tok.is(tok::l_brace) && getLang().CPlusPlus0x) {
2111    Diag(Tok.getLocation(),
2112         diag::warn_cxx98_compat_generalized_initializer_lists);
2113    // FIXME: Have to communicate the init-list to ActOnCXXNew.
2114    ParseBraceInitializer();
2115  }
2116
2117  return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2118                             move_arg(PlacementArgs), PlacementRParen,
2119                             TypeIdParens, DeclaratorInfo, ConstructorLParen,
2120                             move_arg(ConstructorArgs), ConstructorRParen);
2121}
2122
2123/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2124/// passed to ParseDeclaratorInternal.
2125///
2126///        direct-new-declarator:
2127///                   '[' expression ']'
2128///                   direct-new-declarator '[' constant-expression ']'
2129///
2130void Parser::ParseDirectNewDeclarator(Declarator &D) {
2131  // Parse the array dimensions.
2132  bool first = true;
2133  while (Tok.is(tok::l_square)) {
2134    BalancedDelimiterTracker T(*this, tok::l_square);
2135    T.consumeOpen();
2136
2137    ExprResult Size(first ? ParseExpression()
2138                                : ParseConstantExpression());
2139    if (Size.isInvalid()) {
2140      // Recover
2141      SkipUntil(tok::r_square);
2142      return;
2143    }
2144    first = false;
2145
2146    T.consumeClose();
2147
2148    ParsedAttributes attrs(AttrFactory);
2149    D.AddTypeInfo(DeclaratorChunk::getArray(0,
2150                                            /*static=*/false, /*star=*/false,
2151                                            Size.release(),
2152                                            T.getOpenLocation(),
2153                                            T.getCloseLocation()),
2154                  attrs, T.getCloseLocation());
2155
2156    if (T.getCloseLocation().isInvalid())
2157      return;
2158  }
2159}
2160
2161/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2162/// This ambiguity appears in the syntax of the C++ new operator.
2163///
2164///        new-expression:
2165///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2166///                                     new-initializer[opt]
2167///
2168///        new-placement:
2169///                   '(' expression-list ')'
2170///
2171bool Parser::ParseExpressionListOrTypeId(
2172                                   SmallVectorImpl<Expr*> &PlacementArgs,
2173                                         Declarator &D) {
2174  // The '(' was already consumed.
2175  if (isTypeIdInParens()) {
2176    ParseSpecifierQualifierList(D.getMutableDeclSpec());
2177    D.SetSourceRange(D.getDeclSpec().getSourceRange());
2178    ParseDeclarator(D);
2179    return D.isInvalidType();
2180  }
2181
2182  // It's not a type, it has to be an expression list.
2183  // Discard the comma locations - ActOnCXXNew has enough parameters.
2184  CommaLocsTy CommaLocs;
2185  return ParseExpressionList(PlacementArgs, CommaLocs);
2186}
2187
2188/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2189/// to free memory allocated by new.
2190///
2191/// This method is called to parse the 'delete' expression after the optional
2192/// '::' has been already parsed.  If the '::' was present, "UseGlobal" is true
2193/// and "Start" is its location.  Otherwise, "Start" is the location of the
2194/// 'delete' token.
2195///
2196///        delete-expression:
2197///                   '::'[opt] 'delete' cast-expression
2198///                   '::'[opt] 'delete' '[' ']' cast-expression
2199ExprResult
2200Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2201  assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2202  ConsumeToken(); // Consume 'delete'
2203
2204  // Array delete?
2205  bool ArrayDelete = false;
2206  if (Tok.is(tok::l_square)) {
2207    ArrayDelete = true;
2208    BalancedDelimiterTracker T(*this, tok::l_square);
2209
2210    T.consumeOpen();
2211    T.consumeClose();
2212    if (T.getCloseLocation().isInvalid())
2213      return ExprError();
2214  }
2215
2216  ExprResult Operand(ParseCastExpression(false));
2217  if (Operand.isInvalid())
2218    return move(Operand);
2219
2220  return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
2221}
2222
2223static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
2224  switch(kind) {
2225  default: llvm_unreachable("Not a known unary type trait.");
2226  case tok::kw___has_nothrow_assign:      return UTT_HasNothrowAssign;
2227  case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
2228  case tok::kw___has_nothrow_copy:           return UTT_HasNothrowCopy;
2229  case tok::kw___has_trivial_assign:      return UTT_HasTrivialAssign;
2230  case tok::kw___has_trivial_constructor:
2231                                    return UTT_HasTrivialDefaultConstructor;
2232  case tok::kw___has_trivial_copy:           return UTT_HasTrivialCopy;
2233  case tok::kw___has_trivial_destructor:  return UTT_HasTrivialDestructor;
2234  case tok::kw___has_virtual_destructor:  return UTT_HasVirtualDestructor;
2235  case tok::kw___is_abstract:             return UTT_IsAbstract;
2236  case tok::kw___is_arithmetic:              return UTT_IsArithmetic;
2237  case tok::kw___is_array:                   return UTT_IsArray;
2238  case tok::kw___is_class:                return UTT_IsClass;
2239  case tok::kw___is_complete_type:           return UTT_IsCompleteType;
2240  case tok::kw___is_compound:                return UTT_IsCompound;
2241  case tok::kw___is_const:                   return UTT_IsConst;
2242  case tok::kw___is_empty:                return UTT_IsEmpty;
2243  case tok::kw___is_enum:                 return UTT_IsEnum;
2244  case tok::kw___is_final:                 return UTT_IsFinal;
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