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