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