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