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