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