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