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