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