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