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