]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseExprCXX.cpp
Merged ^/head r283871 through r284187.
[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.is(tok::kw_decltype) || Tok.is(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.is(tok::coloncolon) || Tok.is(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     SourceLocation Loc;
845     IdentifierInfo *Id = nullptr;
846     SourceLocation EllipsisLoc;
847     ExprResult Init;
848     
849     if (Tok.is(tok::kw_this)) {
850       Kind = LCK_This;
851       Loc = ConsumeToken();
852     } else {
853       if (Tok.is(tok::amp)) {
854         Kind = LCK_ByRef;
855         ConsumeToken();
856
857         if (Tok.is(tok::code_completion)) {
858           Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, 
859                                                /*AfterAmpersand=*/true);
860           cutOffParsing();
861           break;
862         }
863       }
864
865       if (Tok.is(tok::identifier)) {
866         Id = Tok.getIdentifierInfo();
867         Loc = ConsumeToken();
868       } else if (Tok.is(tok::kw_this)) {
869         // FIXME: If we want to suggest a fixit here, will need to return more
870         // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
871         // Clear()ed to prevent emission in case of tentative parsing?
872         return DiagResult(diag::err_this_captured_by_reference);
873       } else {
874         return DiagResult(diag::err_expected_capture);
875       }
876
877       if (Tok.is(tok::l_paren)) {
878         BalancedDelimiterTracker Parens(*this, tok::l_paren);
879         Parens.consumeOpen();
880
881         ExprVector Exprs;
882         CommaLocsTy Commas;
883         if (SkippedInits) {
884           Parens.skipToEnd();
885           *SkippedInits = true;
886         } else if (ParseExpressionList(Exprs, Commas)) {
887           Parens.skipToEnd();
888           Init = ExprError();
889         } else {
890           Parens.consumeClose();
891           Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
892                                             Parens.getCloseLocation(),
893                                             Exprs);
894         }
895       } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
896         // Each lambda init-capture forms its own full expression, which clears
897         // Actions.MaybeODRUseExprs. So create an expression evaluation context
898         // to save the necessary state, and restore it later.
899         EnterExpressionEvaluationContext EC(Actions,
900                                             Sema::PotentiallyEvaluated);
901         bool HadEquals = TryConsumeToken(tok::equal);
902
903         if (!SkippedInits) {
904           // Warn on constructs that will change meaning when we implement N3922
905           if (!HadEquals && Tok.is(tok::l_brace)) {
906             Diag(Tok, diag::warn_init_capture_direct_list_init)
907               << FixItHint::CreateInsertion(Tok.getLocation(), "=");
908           }
909           Init = ParseInitializer();
910         } else if (Tok.is(tok::l_brace)) {
911           BalancedDelimiterTracker Braces(*this, tok::l_brace);
912           Braces.consumeOpen();
913           Braces.skipToEnd();
914           *SkippedInits = true;
915         } else {
916           // We're disambiguating this:
917           //
918           //   [..., x = expr
919           //
920           // We need to find the end of the following expression in order to
921           // determine whether this is an Obj-C message send's receiver, a
922           // C99 designator, or a lambda init-capture.
923           //
924           // Parse the expression to find where it ends, and annotate it back
925           // onto the tokens. We would have parsed this expression the same way
926           // in either case: both the RHS of an init-capture and the RHS of an
927           // assignment expression are parsed as an initializer-clause, and in
928           // neither case can anything be added to the scope between the '[' and
929           // here.
930           //
931           // FIXME: This is horrible. Adding a mechanism to skip an expression
932           // would be much cleaner.
933           // FIXME: If there is a ',' before the next ']' or ':', we can skip to
934           // that instead. (And if we see a ':' with no matching '?', we can
935           // classify this as an Obj-C message send.)
936           SourceLocation StartLoc = Tok.getLocation();
937           InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
938           Init = ParseInitializer();
939
940           if (Tok.getLocation() != StartLoc) {
941             // Back out the lexing of the token after the initializer.
942             PP.RevertCachedTokens(1);
943
944             // Replace the consumed tokens with an appropriate annotation.
945             Tok.setLocation(StartLoc);
946             Tok.setKind(tok::annot_primary_expr);
947             setExprAnnotation(Tok, Init);
948             Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
949             PP.AnnotateCachedTokens(Tok);
950
951             // Consume the annotated initializer.
952             ConsumeToken();
953           }
954         }
955       } else
956         TryConsumeToken(tok::ellipsis, EllipsisLoc);
957     }
958     // If this is an init capture, process the initialization expression
959     // right away.  For lambda init-captures such as the following:
960     // const int x = 10;
961     //  auto L = [i = x+1](int a) {
962     //    return [j = x+2,
963     //           &k = x](char b) { };
964     //  };
965     // keep in mind that each lambda init-capture has to have:
966     //  - its initialization expression executed in the context
967     //    of the enclosing/parent decl-context.
968     //  - but the variable itself has to be 'injected' into the
969     //    decl-context of its lambda's call-operator (which has
970     //    not yet been created).
971     // Each init-expression is a full-expression that has to get
972     // Sema-analyzed (for capturing etc.) before its lambda's
973     // call-operator's decl-context, scope & scopeinfo are pushed on their
974     // respective stacks.  Thus if any variable is odr-used in the init-capture
975     // it will correctly get captured in the enclosing lambda, if one exists.
976     // The init-variables above are created later once the lambdascope and
977     // call-operators decl-context is pushed onto its respective stack.
978
979     // Since the lambda init-capture's initializer expression occurs in the
980     // context of the enclosing function or lambda, therefore we can not wait
981     // till a lambda scope has been pushed on before deciding whether the
982     // variable needs to be captured.  We also need to process all
983     // lvalue-to-rvalue conversions and discarded-value conversions,
984     // so that we can avoid capturing certain constant variables.
985     // For e.g.,
986     //  void test() {
987     //   const int x = 10;
988     //   auto L = [&z = x](char a) { <-- don't capture by the current lambda
989     //     return [y = x](int i) { <-- don't capture by enclosing lambda
990     //          return y;
991     //     }
992     //   };
993     // If x was not const, the second use would require 'L' to capture, and
994     // that would be an error.
995
996     ParsedType InitCaptureParsedType;
997     if (Init.isUsable()) {
998       // Get the pointer and store it in an lvalue, so we can use it as an
999       // out argument.
1000       Expr *InitExpr = Init.get();
1001       // This performs any lvalue-to-rvalue conversions if necessary, which
1002       // can affect what gets captured in the containing decl-context.
1003       QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
1004         Loc, Kind == LCK_ByRef, Id, InitExpr);
1005       Init = InitExpr;
1006       InitCaptureParsedType.set(InitCaptureType);
1007     }
1008     Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
1009   }
1010
1011   T.consumeClose();
1012   Intro.Range.setEnd(T.getCloseLocation());
1013   return DiagResult();
1014 }
1015
1016 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
1017 ///
1018 /// Returns true if it hit something unexpected.
1019 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1020   TentativeParsingAction PA(*this);
1021
1022   bool SkippedInits = false;
1023   Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
1024
1025   if (DiagID) {
1026     PA.Revert();
1027     return true;
1028   }
1029
1030   if (SkippedInits) {
1031     // Parse it again, but this time parse the init-captures too.
1032     PA.Revert();
1033     Intro = LambdaIntroducer();
1034     DiagID = ParseLambdaIntroducer(Intro);
1035     assert(!DiagID && "parsing lambda-introducer failed on reparse");
1036     return false;
1037   }
1038
1039   PA.Commit();
1040   return false;
1041 }
1042
1043 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1044 /// expression.
1045 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1046                      LambdaIntroducer &Intro) {
1047   SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1048   Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1049
1050   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1051                                 "lambda expression parsing");
1052
1053  
1054
1055   // FIXME: Call into Actions to add any init-capture declarations to the
1056   // scope while parsing the lambda-declarator and compound-statement.
1057
1058   // Parse lambda-declarator[opt].
1059   DeclSpec DS(AttrFactory);
1060   Declarator D(DS, Declarator::LambdaExprContext);
1061   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1062   Actions.PushLambdaScope();    
1063
1064   TypeResult TrailingReturnType;
1065   if (Tok.is(tok::l_paren)) {
1066     ParseScope PrototypeScope(this,
1067                               Scope::FunctionPrototypeScope |
1068                               Scope::FunctionDeclarationScope |
1069                               Scope::DeclScope);
1070
1071     SourceLocation DeclEndLoc;
1072     BalancedDelimiterTracker T(*this, tok::l_paren);
1073     T.consumeOpen();
1074     SourceLocation LParenLoc = T.getOpenLocation();
1075
1076     // Parse parameter-declaration-clause.
1077     ParsedAttributes Attr(AttrFactory);
1078     SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1079     SourceLocation EllipsisLoc;
1080     
1081     if (Tok.isNot(tok::r_paren)) {
1082       Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1083       ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1084       // For a generic lambda, each 'auto' within the parameter declaration 
1085       // clause creates a template type parameter, so increment the depth.
1086       if (Actions.getCurGenericLambda()) 
1087         ++CurTemplateDepthTracker;
1088     }
1089     T.consumeClose();
1090     SourceLocation RParenLoc = T.getCloseLocation();
1091     DeclEndLoc = RParenLoc;
1092
1093     // GNU-style attributes must be parsed before the mutable specifier to be
1094     // compatible with GCC.
1095     MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1096
1097     // MSVC-style attributes must be parsed before the mutable specifier to be
1098     // compatible with MSVC.
1099     MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1100
1101     // Parse 'mutable'[opt].
1102     SourceLocation MutableLoc;
1103     if (TryConsumeToken(tok::kw_mutable, MutableLoc))
1104       DeclEndLoc = MutableLoc;
1105
1106     // Parse exception-specification[opt].
1107     ExceptionSpecificationType ESpecType = EST_None;
1108     SourceRange ESpecRange;
1109     SmallVector<ParsedType, 2> DynamicExceptions;
1110     SmallVector<SourceRange, 2> DynamicExceptionRanges;
1111     ExprResult NoexceptExpr;
1112     CachedTokens *ExceptionSpecTokens;
1113     ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1114                                                ESpecRange,
1115                                                DynamicExceptions,
1116                                                DynamicExceptionRanges,
1117                                                NoexceptExpr,
1118                                                ExceptionSpecTokens);
1119
1120     if (ESpecType != EST_None)
1121       DeclEndLoc = ESpecRange.getEnd();
1122
1123     // Parse attribute-specifier[opt].
1124     MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1125
1126     SourceLocation FunLocalRangeEnd = DeclEndLoc;
1127
1128     // Parse trailing-return-type[opt].
1129     if (Tok.is(tok::arrow)) {
1130       FunLocalRangeEnd = Tok.getLocation();
1131       SourceRange Range;
1132       TrailingReturnType = ParseTrailingReturnType(Range);
1133       if (Range.getEnd().isValid())
1134         DeclEndLoc = Range.getEnd();
1135     }
1136
1137     PrototypeScope.Exit();
1138
1139     SourceLocation NoLoc;
1140     D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1141                                            /*isAmbiguous=*/false,
1142                                            LParenLoc,
1143                                            ParamInfo.data(), ParamInfo.size(),
1144                                            EllipsisLoc, RParenLoc,
1145                                            DS.getTypeQualifiers(),
1146                                            /*RefQualifierIsLValueRef=*/true,
1147                                            /*RefQualifierLoc=*/NoLoc,
1148                                            /*ConstQualifierLoc=*/NoLoc,
1149                                            /*VolatileQualifierLoc=*/NoLoc,
1150                                            /*RestrictQualifierLoc=*/NoLoc,
1151                                            MutableLoc,
1152                                            ESpecType, ESpecRange.getBegin(),
1153                                            DynamicExceptions.data(),
1154                                            DynamicExceptionRanges.data(),
1155                                            DynamicExceptions.size(),
1156                                            NoexceptExpr.isUsable() ?
1157                                              NoexceptExpr.get() : nullptr,
1158                                            /*ExceptionSpecTokens*/nullptr,
1159                                            LParenLoc, FunLocalRangeEnd, D,
1160                                            TrailingReturnType),
1161                   Attr, DeclEndLoc);
1162   } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow) ||
1163              Tok.is(tok::kw___attribute) ||
1164              (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1165     // It's common to forget that one needs '()' before 'mutable', an attribute
1166     // specifier, or the result type. Deal with this.
1167     unsigned TokKind = 0;
1168     switch (Tok.getKind()) {
1169     case tok::kw_mutable: TokKind = 0; break;
1170     case tok::arrow: TokKind = 1; break;
1171     case tok::kw___attribute:
1172     case tok::l_square: TokKind = 2; break;
1173     default: llvm_unreachable("Unknown token kind");
1174     }
1175
1176     Diag(Tok, diag::err_lambda_missing_parens)
1177       << TokKind
1178       << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1179     SourceLocation DeclLoc = Tok.getLocation();
1180     SourceLocation DeclEndLoc = DeclLoc;
1181
1182     // GNU-style attributes must be parsed before the mutable specifier to be
1183     // compatible with GCC.
1184     ParsedAttributes Attr(AttrFactory);
1185     MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1186
1187     // Parse 'mutable', if it's there.
1188     SourceLocation MutableLoc;
1189     if (Tok.is(tok::kw_mutable)) {
1190       MutableLoc = ConsumeToken();
1191       DeclEndLoc = MutableLoc;
1192     }
1193
1194     // Parse attribute-specifier[opt].
1195     MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1196
1197     // Parse the return type, if there is one.
1198     if (Tok.is(tok::arrow)) {
1199       SourceRange Range;
1200       TrailingReturnType = ParseTrailingReturnType(Range);
1201       if (Range.getEnd().isValid())
1202         DeclEndLoc = Range.getEnd();
1203     }
1204
1205     SourceLocation NoLoc;
1206     D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1207                                                /*isAmbiguous=*/false,
1208                                                /*LParenLoc=*/NoLoc,
1209                                                /*Params=*/nullptr,
1210                                                /*NumParams=*/0,
1211                                                /*EllipsisLoc=*/NoLoc,
1212                                                /*RParenLoc=*/NoLoc,
1213                                                /*TypeQuals=*/0,
1214                                                /*RefQualifierIsLValueRef=*/true,
1215                                                /*RefQualifierLoc=*/NoLoc,
1216                                                /*ConstQualifierLoc=*/NoLoc,
1217                                                /*VolatileQualifierLoc=*/NoLoc,
1218                                                /*RestrictQualifierLoc=*/NoLoc,
1219                                                MutableLoc,
1220                                                EST_None,
1221                                                /*ESpecLoc=*/NoLoc,
1222                                                /*Exceptions=*/nullptr,
1223                                                /*ExceptionRanges=*/nullptr,
1224                                                /*NumExceptions=*/0,
1225                                                /*NoexceptExpr=*/nullptr,
1226                                                /*ExceptionSpecTokens=*/nullptr,
1227                                                DeclLoc, DeclEndLoc, D,
1228                                                TrailingReturnType),
1229                   Attr, DeclEndLoc);
1230   }
1231   
1232
1233   // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1234   // it.
1235   unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
1236   ParseScope BodyScope(this, ScopeFlags);
1237
1238   Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1239
1240   // Parse compound-statement.
1241   if (!Tok.is(tok::l_brace)) {
1242     Diag(Tok, diag::err_expected_lambda_body);
1243     Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1244     return ExprError();
1245   }
1246
1247   StmtResult Stmt(ParseCompoundStatementBody());
1248   BodyScope.Exit();
1249
1250   if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1251     return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1252
1253   Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1254   return ExprError();
1255 }
1256
1257 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1258 /// type.
1259 ///
1260 ///       postfix-expression: [C++ 5.2p1]
1261 ///         'dynamic_cast' '<' type-name '>' '(' expression ')'
1262 ///         'static_cast' '<' type-name '>' '(' expression ')'
1263 ///         'reinterpret_cast' '<' type-name '>' '(' expression ')'
1264 ///         'const_cast' '<' type-name '>' '(' expression ')'
1265 ///
1266 ExprResult Parser::ParseCXXCasts() {
1267   tok::TokenKind Kind = Tok.getKind();
1268   const char *CastName = nullptr; // For error messages
1269
1270   switch (Kind) {
1271   default: llvm_unreachable("Unknown C++ cast!");
1272   case tok::kw_const_cast:       CastName = "const_cast";       break;
1273   case tok::kw_dynamic_cast:     CastName = "dynamic_cast";     break;
1274   case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1275   case tok::kw_static_cast:      CastName = "static_cast";      break;
1276   }
1277
1278   SourceLocation OpLoc = ConsumeToken();
1279   SourceLocation LAngleBracketLoc = Tok.getLocation();
1280
1281   // Check for "<::" which is parsed as "[:".  If found, fix token stream,
1282   // diagnose error, suggest fix, and recover parsing.
1283   if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1284     Token Next = NextToken();
1285     if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1286       FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1287   }
1288
1289   if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1290     return ExprError();
1291
1292   // Parse the common declaration-specifiers piece.
1293   DeclSpec DS(AttrFactory);
1294   ParseSpecifierQualifierList(DS);
1295
1296   // Parse the abstract-declarator, if present.
1297   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1298   ParseDeclarator(DeclaratorInfo);
1299
1300   SourceLocation RAngleBracketLoc = Tok.getLocation();
1301
1302   if (ExpectAndConsume(tok::greater))
1303     return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1304
1305   SourceLocation LParenLoc, RParenLoc;
1306   BalancedDelimiterTracker T(*this, tok::l_paren);
1307
1308   if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1309     return ExprError();
1310
1311   ExprResult Result = ParseExpression();
1312
1313   // Match the ')'.
1314   T.consumeClose();
1315
1316   if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1317     Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1318                                        LAngleBracketLoc, DeclaratorInfo,
1319                                        RAngleBracketLoc,
1320                                        T.getOpenLocation(), Result.get(), 
1321                                        T.getCloseLocation());
1322
1323   return Result;
1324 }
1325
1326 /// ParseCXXTypeid - This handles the C++ typeid expression.
1327 ///
1328 ///       postfix-expression: [C++ 5.2p1]
1329 ///         'typeid' '(' expression ')'
1330 ///         'typeid' '(' type-id ')'
1331 ///
1332 ExprResult Parser::ParseCXXTypeid() {
1333   assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1334
1335   SourceLocation OpLoc = ConsumeToken();
1336   SourceLocation LParenLoc, RParenLoc;
1337   BalancedDelimiterTracker T(*this, tok::l_paren);
1338
1339   // typeid expressions are always parenthesized.
1340   if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1341     return ExprError();
1342   LParenLoc = T.getOpenLocation();
1343
1344   ExprResult Result;
1345
1346   // C++0x [expr.typeid]p3:
1347   //   When typeid is applied to an expression other than an lvalue of a
1348   //   polymorphic class type [...] The expression is an unevaluated
1349   //   operand (Clause 5).
1350   //
1351   // Note that we can't tell whether the expression is an lvalue of a
1352   // polymorphic class type until after we've parsed the expression; we
1353   // speculatively assume the subexpression is unevaluated, and fix it up
1354   // later.
1355   //
1356   // We enter the unevaluated context before trying to determine whether we
1357   // have a type-id, because the tentative parse logic will try to resolve
1358   // names, and must treat them as unevaluated.
1359   EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1360                                                Sema::ReuseLambdaContextDecl);
1361
1362   if (isTypeIdInParens()) {
1363     TypeResult Ty = ParseTypeName();
1364
1365     // Match the ')'.
1366     T.consumeClose();
1367     RParenLoc = T.getCloseLocation();
1368     if (Ty.isInvalid() || RParenLoc.isInvalid())
1369       return ExprError();
1370
1371     Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1372                                     Ty.get().getAsOpaquePtr(), RParenLoc);
1373   } else {
1374     Result = ParseExpression();
1375
1376     // Match the ')'.
1377     if (Result.isInvalid())
1378       SkipUntil(tok::r_paren, StopAtSemi);
1379     else {
1380       T.consumeClose();
1381       RParenLoc = T.getCloseLocation();
1382       if (RParenLoc.isInvalid())
1383         return ExprError();
1384
1385       Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1386                                       Result.get(), RParenLoc);
1387     }
1388   }
1389
1390   return Result;
1391 }
1392
1393 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1394 ///
1395 ///         '__uuidof' '(' expression ')'
1396 ///         '__uuidof' '(' type-id ')'
1397 ///
1398 ExprResult Parser::ParseCXXUuidof() {
1399   assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1400
1401   SourceLocation OpLoc = ConsumeToken();
1402   BalancedDelimiterTracker T(*this, tok::l_paren);
1403
1404   // __uuidof expressions are always parenthesized.
1405   if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1406     return ExprError();
1407
1408   ExprResult Result;
1409
1410   if (isTypeIdInParens()) {
1411     TypeResult Ty = ParseTypeName();
1412
1413     // Match the ')'.
1414     T.consumeClose();
1415
1416     if (Ty.isInvalid())
1417       return ExprError();
1418
1419     Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1420                                     Ty.get().getAsOpaquePtr(), 
1421                                     T.getCloseLocation());
1422   } else {
1423     EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1424     Result = ParseExpression();
1425
1426     // Match the ')'.
1427     if (Result.isInvalid())
1428       SkipUntil(tok::r_paren, StopAtSemi);
1429     else {
1430       T.consumeClose();
1431
1432       Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1433                                       /*isType=*/false,
1434                                       Result.get(), T.getCloseLocation());
1435     }
1436   }
1437
1438   return Result;
1439 }
1440
1441 /// \brief Parse a C++ pseudo-destructor expression after the base,
1442 /// . or -> operator, and nested-name-specifier have already been
1443 /// parsed.
1444 ///
1445 ///       postfix-expression: [C++ 5.2]
1446 ///         postfix-expression . pseudo-destructor-name
1447 ///         postfix-expression -> pseudo-destructor-name
1448 ///
1449 ///       pseudo-destructor-name: 
1450 ///         ::[opt] nested-name-specifier[opt] type-name :: ~type-name 
1451 ///         ::[opt] nested-name-specifier template simple-template-id :: 
1452 ///                 ~type-name 
1453 ///         ::[opt] nested-name-specifier[opt] ~type-name
1454 ///       
1455 ExprResult 
1456 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1457                                  tok::TokenKind OpKind,
1458                                  CXXScopeSpec &SS,
1459                                  ParsedType ObjectType) {
1460   // We're parsing either a pseudo-destructor-name or a dependent
1461   // member access that has the same form as a
1462   // pseudo-destructor-name. We parse both in the same way and let
1463   // the action model sort them out.
1464   //
1465   // Note that the ::[opt] nested-name-specifier[opt] has already
1466   // been parsed, and if there was a simple-template-id, it has
1467   // been coalesced into a template-id annotation token.
1468   UnqualifiedId FirstTypeName;
1469   SourceLocation CCLoc;
1470   if (Tok.is(tok::identifier)) {
1471     FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1472     ConsumeToken();
1473     assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1474     CCLoc = ConsumeToken();
1475   } else if (Tok.is(tok::annot_template_id)) {
1476     // FIXME: retrieve TemplateKWLoc from template-id annotation and
1477     // store it in the pseudo-dtor node (to be used when instantiating it).
1478     FirstTypeName.setTemplateId(
1479                               (TemplateIdAnnotation *)Tok.getAnnotationValue());
1480     ConsumeToken();
1481     assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1482     CCLoc = ConsumeToken();
1483   } else {
1484     FirstTypeName.setIdentifier(nullptr, SourceLocation());
1485   }
1486
1487   // Parse the tilde.
1488   assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1489   SourceLocation TildeLoc = ConsumeToken();
1490
1491   if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1492     DeclSpec DS(AttrFactory);
1493     ParseDecltypeSpecifier(DS);
1494     if (DS.getTypeSpecType() == TST_error)
1495       return ExprError();
1496     return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1497                                              TildeLoc, DS);
1498   }
1499
1500   if (!Tok.is(tok::identifier)) {
1501     Diag(Tok, diag::err_destructor_tilde_identifier);
1502     return ExprError();
1503   }
1504   
1505   // Parse the second type.
1506   UnqualifiedId SecondTypeName;
1507   IdentifierInfo *Name = Tok.getIdentifierInfo();
1508   SourceLocation NameLoc = ConsumeToken();
1509   SecondTypeName.setIdentifier(Name, NameLoc);
1510   
1511   // If there is a '<', the second type name is a template-id. Parse
1512   // it as such.
1513   if (Tok.is(tok::less) &&
1514       ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1515                                    Name, NameLoc,
1516                                    false, ObjectType, SecondTypeName,
1517                                    /*AssumeTemplateName=*/true))
1518     return ExprError();
1519
1520   return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1521                                            SS, FirstTypeName, CCLoc, TildeLoc,
1522                                            SecondTypeName);
1523 }
1524
1525 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1526 ///
1527 ///       boolean-literal: [C++ 2.13.5]
1528 ///         'true'
1529 ///         'false'
1530 ExprResult Parser::ParseCXXBoolLiteral() {
1531   tok::TokenKind Kind = Tok.getKind();
1532   return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1533 }
1534
1535 /// ParseThrowExpression - This handles the C++ throw expression.
1536 ///
1537 ///       throw-expression: [C++ 15]
1538 ///         'throw' assignment-expression[opt]
1539 ExprResult Parser::ParseThrowExpression() {
1540   assert(Tok.is(tok::kw_throw) && "Not throw!");
1541   SourceLocation ThrowLoc = ConsumeToken();           // Eat the throw token.
1542
1543   // If the current token isn't the start of an assignment-expression,
1544   // then the expression is not present.  This handles things like:
1545   //   "C ? throw : (void)42", which is crazy but legal.
1546   switch (Tok.getKind()) {  // FIXME: move this predicate somewhere common.
1547   case tok::semi:
1548   case tok::r_paren:
1549   case tok::r_square:
1550   case tok::r_brace:
1551   case tok::colon:
1552   case tok::comma:
1553     return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1554
1555   default:
1556     ExprResult Expr(ParseAssignmentExpression());
1557     if (Expr.isInvalid()) return Expr;
1558     return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1559   }
1560 }
1561
1562 /// ParseCXXThis - This handles the C++ 'this' pointer.
1563 ///
1564 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1565 /// a non-lvalue expression whose value is the address of the object for which
1566 /// the function is called.
1567 ExprResult Parser::ParseCXXThis() {
1568   assert(Tok.is(tok::kw_this) && "Not 'this'!");
1569   SourceLocation ThisLoc = ConsumeToken();
1570   return Actions.ActOnCXXThis(ThisLoc);
1571 }
1572
1573 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1574 /// Can be interpreted either as function-style casting ("int(x)")
1575 /// or class type construction ("ClassType(x,y,z)")
1576 /// or creation of a value-initialized type ("int()").
1577 /// See [C++ 5.2.3].
1578 ///
1579 ///       postfix-expression: [C++ 5.2p1]
1580 ///         simple-type-specifier '(' expression-list[opt] ')'
1581 /// [C++0x] simple-type-specifier braced-init-list
1582 ///         typename-specifier '(' expression-list[opt] ')'
1583 /// [C++0x] typename-specifier braced-init-list
1584 ///
1585 ExprResult
1586 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1587   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1588   ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1589
1590   assert((Tok.is(tok::l_paren) ||
1591           (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1592          && "Expected '(' or '{'!");
1593
1594   if (Tok.is(tok::l_brace)) {
1595     ExprResult Init = ParseBraceInitializer();
1596     if (Init.isInvalid())
1597       return Init;
1598     Expr *InitList = Init.get();
1599     return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1600                                              MultiExprArg(&InitList, 1),
1601                                              SourceLocation());
1602   } else {
1603     BalancedDelimiterTracker T(*this, tok::l_paren);
1604     T.consumeOpen();
1605
1606     ExprVector Exprs;
1607     CommaLocsTy CommaLocs;
1608
1609     if (Tok.isNot(tok::r_paren)) {
1610       if (ParseExpressionList(Exprs, CommaLocs, [&] {
1611             Actions.CodeCompleteConstructor(getCurScope(),
1612                                       TypeRep.get()->getCanonicalTypeInternal(),
1613                                             DS.getLocEnd(), Exprs);
1614          })) {
1615         SkipUntil(tok::r_paren, StopAtSemi);
1616         return ExprError();
1617       }
1618     }
1619
1620     // Match the ')'.
1621     T.consumeClose();
1622
1623     // TypeRep could be null, if it references an invalid typedef.
1624     if (!TypeRep)
1625       return ExprError();
1626
1627     assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1628            "Unexpected number of commas!");
1629     return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(), 
1630                                              Exprs,
1631                                              T.getCloseLocation());
1632   }
1633 }
1634
1635 /// ParseCXXCondition - if/switch/while condition expression.
1636 ///
1637 ///       condition:
1638 ///         expression
1639 ///         type-specifier-seq declarator '=' assignment-expression
1640 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1641 /// [C++11] type-specifier-seq declarator braced-init-list
1642 /// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1643 ///             '=' assignment-expression
1644 ///
1645 /// \param ExprOut if the condition was parsed as an expression, the parsed
1646 /// expression.
1647 ///
1648 /// \param DeclOut if the condition was parsed as a declaration, the parsed
1649 /// declaration.
1650 ///
1651 /// \param Loc The location of the start of the statement that requires this
1652 /// condition, e.g., the "for" in a for loop.
1653 ///
1654 /// \param ConvertToBoolean Whether the condition expression should be
1655 /// converted to a boolean value.
1656 ///
1657 /// \returns true if there was a parsing, false otherwise.
1658 bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1659                                Decl *&DeclOut,
1660                                SourceLocation Loc,
1661                                bool ConvertToBoolean) {
1662   if (Tok.is(tok::code_completion)) {
1663     Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1664     cutOffParsing();
1665     return true;
1666   }
1667
1668   ParsedAttributesWithRange attrs(AttrFactory);
1669   MaybeParseCXX11Attributes(attrs);
1670
1671   if (!isCXXConditionDeclaration()) {
1672     ProhibitAttributes(attrs);
1673
1674     // Parse the expression.
1675     ExprOut = ParseExpression(); // expression
1676     DeclOut = nullptr;
1677     if (ExprOut.isInvalid())
1678       return true;
1679
1680     // If required, convert to a boolean value.
1681     if (ConvertToBoolean)
1682       ExprOut
1683         = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1684     return ExprOut.isInvalid();
1685   }
1686
1687   // type-specifier-seq
1688   DeclSpec DS(AttrFactory);
1689   DS.takeAttributesFrom(attrs);
1690   ParseSpecifierQualifierList(DS);
1691
1692   // declarator
1693   Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1694   ParseDeclarator(DeclaratorInfo);
1695
1696   // simple-asm-expr[opt]
1697   if (Tok.is(tok::kw_asm)) {
1698     SourceLocation Loc;
1699     ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1700     if (AsmLabel.isInvalid()) {
1701       SkipUntil(tok::semi, StopAtSemi);
1702       return true;
1703     }
1704     DeclaratorInfo.setAsmLabel(AsmLabel.get());
1705     DeclaratorInfo.SetRangeEnd(Loc);
1706   }
1707
1708   // If attributes are present, parse them.
1709   MaybeParseGNUAttributes(DeclaratorInfo);
1710
1711   // Type-check the declaration itself.
1712   DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), 
1713                                                         DeclaratorInfo);
1714   DeclOut = Dcl.get();
1715   ExprOut = ExprError();
1716
1717   // '=' assignment-expression
1718   // If a '==' or '+=' is found, suggest a fixit to '='.
1719   bool CopyInitialization = isTokenEqualOrEqualTypo();
1720   if (CopyInitialization)
1721     ConsumeToken();
1722
1723   ExprResult InitExpr = ExprError();
1724   if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1725     Diag(Tok.getLocation(),
1726          diag::warn_cxx98_compat_generalized_initializer_lists);
1727     InitExpr = ParseBraceInitializer();
1728   } else if (CopyInitialization) {
1729     InitExpr = ParseAssignmentExpression();
1730   } else if (Tok.is(tok::l_paren)) {
1731     // This was probably an attempt to initialize the variable.
1732     SourceLocation LParen = ConsumeParen(), RParen = LParen;
1733     if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1734       RParen = ConsumeParen();
1735     Diag(DeclOut ? DeclOut->getLocation() : LParen,
1736          diag::err_expected_init_in_condition_lparen)
1737       << SourceRange(LParen, RParen);
1738   } else {
1739     Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1740          diag::err_expected_init_in_condition);
1741   }
1742
1743   if (!InitExpr.isInvalid())
1744     Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
1745                                  DS.containsPlaceholderType());
1746   else
1747     Actions.ActOnInitializerError(DeclOut);
1748
1749   // FIXME: Build a reference to this declaration? Convert it to bool?
1750   // (This is currently handled by Sema).
1751
1752   Actions.FinalizeDeclaration(DeclOut);
1753   
1754   return false;
1755 }
1756
1757 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1758 /// This should only be called when the current token is known to be part of
1759 /// simple-type-specifier.
1760 ///
1761 ///       simple-type-specifier:
1762 ///         '::'[opt] nested-name-specifier[opt] type-name
1763 ///         '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1764 ///         char
1765 ///         wchar_t
1766 ///         bool
1767 ///         short
1768 ///         int
1769 ///         long
1770 ///         signed
1771 ///         unsigned
1772 ///         float
1773 ///         double
1774 ///         void
1775 /// [GNU]   typeof-specifier
1776 /// [C++0x] auto               [TODO]
1777 ///
1778 ///       type-name:
1779 ///         class-name
1780 ///         enum-name
1781 ///         typedef-name
1782 ///
1783 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1784   DS.SetRangeStart(Tok.getLocation());
1785   const char *PrevSpec;
1786   unsigned DiagID;
1787   SourceLocation Loc = Tok.getLocation();
1788   const clang::PrintingPolicy &Policy =
1789       Actions.getASTContext().getPrintingPolicy();
1790
1791   switch (Tok.getKind()) {
1792   case tok::identifier:   // foo::bar
1793   case tok::coloncolon:   // ::foo::bar
1794     llvm_unreachable("Annotation token should already be formed!");
1795   default:
1796     llvm_unreachable("Not a simple-type-specifier token!");
1797
1798   // type-name
1799   case tok::annot_typename: {
1800     if (getTypeAnnotation(Tok))
1801       DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1802                          getTypeAnnotation(Tok), Policy);
1803     else
1804       DS.SetTypeSpecError();
1805     
1806     DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1807     ConsumeToken();
1808     
1809     // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1810     // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1811     // Objective-C interface.  If we don't have Objective-C or a '<', this is
1812     // just a normal reference to a typedef name.
1813     if (Tok.is(tok::less) && getLangOpts().ObjC1)
1814       ParseObjCProtocolQualifiers(DS);
1815     
1816     DS.Finish(Diags, PP, Policy);
1817     return;
1818   }
1819
1820   // builtin types
1821   case tok::kw_short:
1822     DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1823     break;
1824   case tok::kw_long:
1825     DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1826     break;
1827   case tok::kw___int64:
1828     DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1829     break;
1830   case tok::kw_signed:
1831     DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1832     break;
1833   case tok::kw_unsigned:
1834     DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1835     break;
1836   case tok::kw_void:
1837     DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1838     break;
1839   case tok::kw_char:
1840     DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1841     break;
1842   case tok::kw_int:
1843     DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1844     break;
1845   case tok::kw___int128:
1846     DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1847     break;
1848   case tok::kw_half:
1849     DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1850     break;
1851   case tok::kw_float:
1852     DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1853     break;
1854   case tok::kw_double:
1855     DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1856     break;
1857   case tok::kw_wchar_t:
1858     DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1859     break;
1860   case tok::kw_char16_t:
1861     DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1862     break;
1863   case tok::kw_char32_t:
1864     DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1865     break;
1866   case tok::kw_bool:
1867     DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1868     break;
1869   case tok::annot_decltype:
1870   case tok::kw_decltype:
1871     DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1872     return DS.Finish(Diags, PP, Policy);
1873
1874   // GNU typeof support.
1875   case tok::kw_typeof:
1876     ParseTypeofSpecifier(DS);
1877     DS.Finish(Diags, PP, Policy);
1878     return;
1879   }
1880   if (Tok.is(tok::annot_typename))
1881     DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1882   else
1883     DS.SetRangeEnd(Tok.getLocation());
1884   ConsumeToken();
1885   DS.Finish(Diags, PP, Policy);
1886 }
1887
1888 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1889 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1890 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1891 /// by parsing the type-specifier-seq, because these sequences are
1892 /// typically followed by some form of declarator. Returns true and
1893 /// emits diagnostics if this is not a type-specifier-seq, false
1894 /// otherwise.
1895 ///
1896 ///   type-specifier-seq: [C++ 8.1]
1897 ///     type-specifier type-specifier-seq[opt]
1898 ///
1899 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
1900   ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
1901   DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
1902   return false;
1903 }
1904
1905 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
1906 /// some form. 
1907 ///
1908 /// This routine is invoked when a '<' is encountered after an identifier or
1909 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1910 /// whether the unqualified-id is actually a template-id. This routine will
1911 /// then parse the template arguments and form the appropriate template-id to
1912 /// return to the caller.
1913 ///
1914 /// \param SS the nested-name-specifier that precedes this template-id, if
1915 /// we're actually parsing a qualified-id.
1916 ///
1917 /// \param Name for constructor and destructor names, this is the actual
1918 /// identifier that may be a template-name.
1919 ///
1920 /// \param NameLoc the location of the class-name in a constructor or 
1921 /// destructor.
1922 ///
1923 /// \param EnteringContext whether we're entering the scope of the 
1924 /// nested-name-specifier.
1925 ///
1926 /// \param ObjectType if this unqualified-id occurs within a member access
1927 /// expression, the type of the base object whose member is being accessed.
1928 ///
1929 /// \param Id as input, describes the template-name or operator-function-id
1930 /// that precedes the '<'. If template arguments were parsed successfully,
1931 /// will be updated with the template-id.
1932 /// 
1933 /// \param AssumeTemplateId When true, this routine will assume that the name
1934 /// refers to a template without performing name lookup to verify. 
1935 ///
1936 /// \returns true if a parse error occurred, false otherwise.
1937 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
1938                                           SourceLocation TemplateKWLoc,
1939                                           IdentifierInfo *Name,
1940                                           SourceLocation NameLoc,
1941                                           bool EnteringContext,
1942                                           ParsedType ObjectType,
1943                                           UnqualifiedId &Id,
1944                                           bool AssumeTemplateId) {
1945   assert((AssumeTemplateId || Tok.is(tok::less)) &&
1946          "Expected '<' to finish parsing a template-id");
1947   
1948   TemplateTy Template;
1949   TemplateNameKind TNK = TNK_Non_template;
1950   switch (Id.getKind()) {
1951   case UnqualifiedId::IK_Identifier:
1952   case UnqualifiedId::IK_OperatorFunctionId:
1953   case UnqualifiedId::IK_LiteralOperatorId:
1954     if (AssumeTemplateId) {
1955       TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
1956                                                Id, ObjectType, EnteringContext,
1957                                                Template);
1958       if (TNK == TNK_Non_template)
1959         return true;
1960     } else {
1961       bool MemberOfUnknownSpecialization;
1962       TNK = Actions.isTemplateName(getCurScope(), SS,
1963                                    TemplateKWLoc.isValid(), Id,
1964                                    ObjectType, EnteringContext, Template,
1965                                    MemberOfUnknownSpecialization);
1966       
1967       if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1968           ObjectType && IsTemplateArgumentList()) {
1969         // We have something like t->getAs<T>(), where getAs is a 
1970         // member of an unknown specialization. However, this will only
1971         // parse correctly as a template, so suggest the keyword 'template'
1972         // before 'getAs' and treat this as a dependent template name.
1973         std::string Name;
1974         if (Id.getKind() == UnqualifiedId::IK_Identifier)
1975           Name = Id.Identifier->getName();
1976         else {
1977           Name = "operator ";
1978           if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1979             Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1980           else
1981             Name += Id.Identifier->getName();
1982         }
1983         Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1984           << Name
1985           << FixItHint::CreateInsertion(Id.StartLocation, "template ");
1986         TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1987                                                  SS, TemplateKWLoc, Id,
1988                                                  ObjectType, EnteringContext,
1989                                                  Template);
1990         if (TNK == TNK_Non_template)
1991           return true;              
1992       }
1993     }
1994     break;
1995       
1996   case UnqualifiedId::IK_ConstructorName: {
1997     UnqualifiedId TemplateName;
1998     bool MemberOfUnknownSpecialization;
1999     TemplateName.setIdentifier(Name, NameLoc);
2000     TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2001                                  TemplateName, ObjectType, 
2002                                  EnteringContext, Template,
2003                                  MemberOfUnknownSpecialization);
2004     break;
2005   }
2006       
2007   case UnqualifiedId::IK_DestructorName: {
2008     UnqualifiedId TemplateName;
2009     bool MemberOfUnknownSpecialization;
2010     TemplateName.setIdentifier(Name, NameLoc);
2011     if (ObjectType) {
2012       TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2013                                                SS, TemplateKWLoc, TemplateName,
2014                                                ObjectType, EnteringContext,
2015                                                Template);
2016       if (TNK == TNK_Non_template)
2017         return true;
2018     } else {
2019       TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2020                                    TemplateName, ObjectType, 
2021                                    EnteringContext, Template,
2022                                    MemberOfUnknownSpecialization);
2023       
2024       if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2025         Diag(NameLoc, diag::err_destructor_template_id)
2026           << Name << SS.getRange();
2027         return true;        
2028       }
2029     }
2030     break;
2031   }
2032       
2033   default:
2034     return false;
2035   }
2036   
2037   if (TNK == TNK_Non_template)
2038     return false;
2039   
2040   // Parse the enclosed template argument list.
2041   SourceLocation LAngleLoc, RAngleLoc;
2042   TemplateArgList TemplateArgs;
2043   if (Tok.is(tok::less) &&
2044       ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
2045                                        SS, true, LAngleLoc,
2046                                        TemplateArgs,
2047                                        RAngleLoc))
2048     return true;
2049   
2050   if (Id.getKind() == UnqualifiedId::IK_Identifier ||
2051       Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2052       Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
2053     // Form a parsed representation of the template-id to be stored in the
2054     // UnqualifiedId.
2055     TemplateIdAnnotation *TemplateId
2056       = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
2057
2058     // FIXME: Store name for literal operator too.
2059     if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2060       TemplateId->Name = Id.Identifier;
2061       TemplateId->Operator = OO_None;
2062       TemplateId->TemplateNameLoc = Id.StartLocation;
2063     } else {
2064       TemplateId->Name = nullptr;
2065       TemplateId->Operator = Id.OperatorFunctionId.Operator;
2066       TemplateId->TemplateNameLoc = Id.StartLocation;
2067     }
2068
2069     TemplateId->SS = SS;
2070     TemplateId->TemplateKWLoc = TemplateKWLoc;
2071     TemplateId->Template = Template;
2072     TemplateId->Kind = TNK;
2073     TemplateId->LAngleLoc = LAngleLoc;
2074     TemplateId->RAngleLoc = RAngleLoc;
2075     ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
2076     for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); 
2077          Arg != ArgEnd; ++Arg)
2078       Args[Arg] = TemplateArgs[Arg];
2079     
2080     Id.setTemplateId(TemplateId);
2081     return false;
2082   }
2083
2084   // Bundle the template arguments together.
2085   ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2086
2087   // Constructor and destructor names.
2088   TypeResult Type
2089     = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2090                                   Template, NameLoc,
2091                                   LAngleLoc, TemplateArgsPtr, RAngleLoc,
2092                                   /*IsCtorOrDtorName=*/true);
2093   if (Type.isInvalid())
2094     return true;
2095   
2096   if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2097     Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2098   else
2099     Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2100   
2101   return false;
2102 }
2103
2104 /// \brief Parse an operator-function-id or conversion-function-id as part
2105 /// of a C++ unqualified-id.
2106 ///
2107 /// This routine is responsible only for parsing the operator-function-id or
2108 /// conversion-function-id; it does not handle template arguments in any way.
2109 ///
2110 /// \code
2111 ///       operator-function-id: [C++ 13.5]
2112 ///         'operator' operator
2113 ///
2114 ///       operator: one of
2115 ///            new   delete  new[]   delete[]
2116 ///            +     -    *  /    %  ^    &   |   ~
2117 ///            !     =    <  >    += -=   *=  /=  %=
2118 ///            ^=    &=   |= <<   >> >>= <<=  ==  !=
2119 ///            <=    >=   && ||   ++ --   ,   ->* ->
2120 ///            ()    []
2121 ///
2122 ///       conversion-function-id: [C++ 12.3.2]
2123 ///         operator conversion-type-id
2124 ///
2125 ///       conversion-type-id:
2126 ///         type-specifier-seq conversion-declarator[opt]
2127 ///
2128 ///       conversion-declarator:
2129 ///         ptr-operator conversion-declarator[opt]
2130 /// \endcode
2131 ///
2132 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2133 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2134 ///
2135 /// \param EnteringContext whether we are entering the scope of the 
2136 /// nested-name-specifier.
2137 ///
2138 /// \param ObjectType if this unqualified-id occurs within a member access
2139 /// expression, the type of the base object whose member is being accessed.
2140 ///
2141 /// \param Result on a successful parse, contains the parsed unqualified-id.
2142 ///
2143 /// \returns true if parsing fails, false otherwise.
2144 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2145                                         ParsedType ObjectType,
2146                                         UnqualifiedId &Result) {
2147   assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2148   
2149   // Consume the 'operator' keyword.
2150   SourceLocation KeywordLoc = ConsumeToken();
2151   
2152   // Determine what kind of operator name we have.
2153   unsigned SymbolIdx = 0;
2154   SourceLocation SymbolLocations[3];
2155   OverloadedOperatorKind Op = OO_None;
2156   switch (Tok.getKind()) {
2157     case tok::kw_new:
2158     case tok::kw_delete: {
2159       bool isNew = Tok.getKind() == tok::kw_new;
2160       // Consume the 'new' or 'delete'.
2161       SymbolLocations[SymbolIdx++] = ConsumeToken();
2162       // Check for array new/delete.
2163       if (Tok.is(tok::l_square) &&
2164           (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2165         // Consume the '[' and ']'.
2166         BalancedDelimiterTracker T(*this, tok::l_square);
2167         T.consumeOpen();
2168         T.consumeClose();
2169         if (T.getCloseLocation().isInvalid())
2170           return true;
2171         
2172         SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2173         SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2174         Op = isNew? OO_Array_New : OO_Array_Delete;
2175       } else {
2176         Op = isNew? OO_New : OO_Delete;
2177       }
2178       break;
2179     }
2180       
2181 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2182     case tok::Token:                                                     \
2183       SymbolLocations[SymbolIdx++] = ConsumeToken();                     \
2184       Op = OO_##Name;                                                    \
2185       break;
2186 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2187 #include "clang/Basic/OperatorKinds.def"
2188       
2189     case tok::l_paren: {
2190       // Consume the '(' and ')'.
2191       BalancedDelimiterTracker T(*this, tok::l_paren);
2192       T.consumeOpen();
2193       T.consumeClose();
2194       if (T.getCloseLocation().isInvalid())
2195         return true;
2196       
2197       SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2198       SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2199       Op = OO_Call;
2200       break;
2201     }
2202       
2203     case tok::l_square: {
2204       // Consume the '[' and ']'.
2205       BalancedDelimiterTracker T(*this, tok::l_square);
2206       T.consumeOpen();
2207       T.consumeClose();
2208       if (T.getCloseLocation().isInvalid())
2209         return true;
2210       
2211       SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2212       SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2213       Op = OO_Subscript;
2214       break;
2215     }
2216       
2217     case tok::code_completion: {
2218       // Code completion for the operator name.
2219       Actions.CodeCompleteOperatorName(getCurScope());
2220       cutOffParsing();      
2221       // Don't try to parse any further.
2222       return true;
2223     }
2224       
2225     default:
2226       break;
2227   }
2228   
2229   if (Op != OO_None) {
2230     // We have parsed an operator-function-id.
2231     Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2232     return false;
2233   }
2234
2235   // Parse a literal-operator-id.
2236   //
2237   //   literal-operator-id: C++11 [over.literal]
2238   //     operator string-literal identifier
2239   //     operator user-defined-string-literal
2240
2241   if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2242     Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2243
2244     SourceLocation DiagLoc;
2245     unsigned DiagId = 0;
2246
2247     // We're past translation phase 6, so perform string literal concatenation
2248     // before checking for "".
2249     SmallVector<Token, 4> Toks;
2250     SmallVector<SourceLocation, 4> TokLocs;
2251     while (isTokenStringLiteral()) {
2252       if (!Tok.is(tok::string_literal) && !DiagId) {
2253         // C++11 [over.literal]p1:
2254         //   The string-literal or user-defined-string-literal in a
2255         //   literal-operator-id shall have no encoding-prefix [...].
2256         DiagLoc = Tok.getLocation();
2257         DiagId = diag::err_literal_operator_string_prefix;
2258       }
2259       Toks.push_back(Tok);
2260       TokLocs.push_back(ConsumeStringToken());
2261     }
2262
2263     StringLiteralParser Literal(Toks, PP);
2264     if (Literal.hadError)
2265       return true;
2266
2267     // Grab the literal operator's suffix, which will be either the next token
2268     // or a ud-suffix from the string literal.
2269     IdentifierInfo *II = nullptr;
2270     SourceLocation SuffixLoc;
2271     if (!Literal.getUDSuffix().empty()) {
2272       II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2273       SuffixLoc =
2274         Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2275                                        Literal.getUDSuffixOffset(),
2276                                        PP.getSourceManager(), getLangOpts());
2277     } else if (Tok.is(tok::identifier)) {
2278       II = Tok.getIdentifierInfo();
2279       SuffixLoc = ConsumeToken();
2280       TokLocs.push_back(SuffixLoc);
2281     } else {
2282       Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2283       return true;
2284     }
2285
2286     // The string literal must be empty.
2287     if (!Literal.GetString().empty() || Literal.Pascal) {
2288       // C++11 [over.literal]p1:
2289       //   The string-literal or user-defined-string-literal in a
2290       //   literal-operator-id shall [...] contain no characters
2291       //   other than the implicit terminating '\0'.
2292       DiagLoc = TokLocs.front();
2293       DiagId = diag::err_literal_operator_string_not_empty;
2294     }
2295
2296     if (DiagId) {
2297       // This isn't a valid literal-operator-id, but we think we know
2298       // what the user meant. Tell them what they should have written.
2299       SmallString<32> Str;
2300       Str += "\"\" ";
2301       Str += II->getName();
2302       Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2303           SourceRange(TokLocs.front(), TokLocs.back()), Str);
2304     }
2305
2306     Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2307
2308     return Actions.checkLiteralOperatorId(SS, Result);
2309   }
2310
2311   // Parse a conversion-function-id.
2312   //
2313   //   conversion-function-id: [C++ 12.3.2]
2314   //     operator conversion-type-id
2315   //
2316   //   conversion-type-id:
2317   //     type-specifier-seq conversion-declarator[opt]
2318   //
2319   //   conversion-declarator:
2320   //     ptr-operator conversion-declarator[opt]
2321   
2322   // Parse the type-specifier-seq.
2323   DeclSpec DS(AttrFactory);
2324   if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2325     return true;
2326   
2327   // Parse the conversion-declarator, which is merely a sequence of
2328   // ptr-operators.
2329   Declarator D(DS, Declarator::ConversionIdContext);
2330   ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2331
2332   // Finish up the type.
2333   TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2334   if (Ty.isInvalid())
2335     return true;
2336   
2337   // Note that this is a conversion-function-id.
2338   Result.setConversionFunctionId(KeywordLoc, Ty.get(), 
2339                                  D.getSourceRange().getEnd());
2340   return false;  
2341 }
2342
2343 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2344 /// name of an entity.
2345 ///
2346 /// \code
2347 ///       unqualified-id: [C++ expr.prim.general]
2348 ///         identifier
2349 ///         operator-function-id
2350 ///         conversion-function-id
2351 /// [C++0x] literal-operator-id [TODO]
2352 ///         ~ class-name
2353 ///         template-id
2354 ///
2355 /// \endcode
2356 ///
2357 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2358 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2359 ///
2360 /// \param EnteringContext whether we are entering the scope of the 
2361 /// nested-name-specifier.
2362 ///
2363 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2364 ///
2365 /// \param AllowConstructorName whether we allow parsing a constructor name.
2366 ///
2367 /// \param ObjectType if this unqualified-id occurs within a member access
2368 /// expression, the type of the base object whose member is being accessed.
2369 ///
2370 /// \param Result on a successful parse, contains the parsed unqualified-id.
2371 ///
2372 /// \returns true if parsing fails, false otherwise.
2373 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2374                                 bool AllowDestructorName,
2375                                 bool AllowConstructorName,
2376                                 ParsedType ObjectType,
2377                                 SourceLocation& TemplateKWLoc,
2378                                 UnqualifiedId &Result) {
2379
2380   // Handle 'A::template B'. This is for template-ids which have not
2381   // already been annotated by ParseOptionalCXXScopeSpecifier().
2382   bool TemplateSpecified = false;
2383   if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
2384       (ObjectType || SS.isSet())) {
2385     TemplateSpecified = true;
2386     TemplateKWLoc = ConsumeToken();
2387   }
2388
2389   // unqualified-id:
2390   //   identifier
2391   //   template-id (when it hasn't already been annotated)
2392   if (Tok.is(tok::identifier)) {
2393     // Consume the identifier.
2394     IdentifierInfo *Id = Tok.getIdentifierInfo();
2395     SourceLocation IdLoc = ConsumeToken();
2396
2397     if (!getLangOpts().CPlusPlus) {
2398       // If we're not in C++, only identifiers matter. Record the
2399       // identifier and return.
2400       Result.setIdentifier(Id, IdLoc);
2401       return false;
2402     }
2403
2404     if (AllowConstructorName && 
2405         Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2406       // We have parsed a constructor name.
2407       ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2408                                           &SS, false, false,
2409                                           ParsedType(),
2410                                           /*IsCtorOrDtorName=*/true,
2411                                           /*NonTrivialTypeSourceInfo=*/true);
2412       Result.setConstructorName(Ty, IdLoc, IdLoc);
2413     } else {
2414       // We have parsed an identifier.
2415       Result.setIdentifier(Id, IdLoc);      
2416     }
2417
2418     // If the next token is a '<', we may have a template.
2419     if (TemplateSpecified || Tok.is(tok::less))
2420       return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2421                                           EnteringContext, ObjectType,
2422                                           Result, TemplateSpecified);
2423     
2424     return false;
2425   }
2426   
2427   // unqualified-id:
2428   //   template-id (already parsed and annotated)
2429   if (Tok.is(tok::annot_template_id)) {
2430     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2431
2432     // If the template-name names the current class, then this is a constructor 
2433     if (AllowConstructorName && TemplateId->Name &&
2434         Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2435       if (SS.isSet()) {
2436         // C++ [class.qual]p2 specifies that a qualified template-name
2437         // is taken as the constructor name where a constructor can be
2438         // declared. Thus, the template arguments are extraneous, so
2439         // complain about them and remove them entirely.
2440         Diag(TemplateId->TemplateNameLoc, 
2441              diag::err_out_of_line_constructor_template_id)
2442           << TemplateId->Name
2443           << FixItHint::CreateRemoval(
2444                     SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2445         ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2446                                             TemplateId->TemplateNameLoc,
2447                                             getCurScope(),
2448                                             &SS, false, false,
2449                                             ParsedType(),
2450                                             /*IsCtorOrDtorName=*/true,
2451                                             /*NontrivialTypeSourceInfo=*/true);
2452         Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2453                                   TemplateId->RAngleLoc);
2454         ConsumeToken();
2455         return false;
2456       }
2457
2458       Result.setConstructorTemplateId(TemplateId);
2459       ConsumeToken();
2460       return false;
2461     }
2462
2463     // We have already parsed a template-id; consume the annotation token as
2464     // our unqualified-id.
2465     Result.setTemplateId(TemplateId);
2466     TemplateKWLoc = TemplateId->TemplateKWLoc;
2467     ConsumeToken();
2468     return false;
2469   }
2470   
2471   // unqualified-id:
2472   //   operator-function-id
2473   //   conversion-function-id
2474   if (Tok.is(tok::kw_operator)) {
2475     if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2476       return true;
2477     
2478     // If we have an operator-function-id or a literal-operator-id and the next
2479     // token is a '<', we may have a
2480     // 
2481     //   template-id:
2482     //     operator-function-id < template-argument-list[opt] >
2483     if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2484          Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
2485         (TemplateSpecified || Tok.is(tok::less)))
2486       return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2487                                           nullptr, SourceLocation(),
2488                                           EnteringContext, ObjectType,
2489                                           Result, TemplateSpecified);
2490
2491     return false;
2492   }
2493   
2494   if (getLangOpts().CPlusPlus && 
2495       (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2496     // C++ [expr.unary.op]p10:
2497     //   There is an ambiguity in the unary-expression ~X(), where X is a 
2498     //   class-name. The ambiguity is resolved in favor of treating ~ as a 
2499     //    unary complement rather than treating ~X as referring to a destructor.
2500     
2501     // Parse the '~'.
2502     SourceLocation TildeLoc = ConsumeToken();
2503
2504     if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2505       DeclSpec DS(AttrFactory);
2506       SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2507       if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2508         Result.setDestructorName(TildeLoc, Type, EndLoc);
2509         return false;
2510       }
2511       return true;
2512     }
2513     
2514     // Parse the class-name.
2515     if (Tok.isNot(tok::identifier)) {
2516       Diag(Tok, diag::err_destructor_tilde_identifier);
2517       return true;
2518     }
2519
2520     // If the user wrote ~T::T, correct it to T::~T.
2521     DeclaratorScopeObj DeclScopeObj(*this, SS);
2522     if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2523       // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2524       // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2525       // it will confuse this recovery logic.
2526       ColonProtectionRAIIObject ColonRAII(*this, false);
2527
2528       if (SS.isSet()) {
2529         AnnotateScopeToken(SS, /*NewAnnotation*/true);
2530         SS.clear();
2531       }
2532       if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2533         return true;
2534       if (SS.isNotEmpty())
2535         ObjectType = ParsedType();
2536       if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2537           !SS.isSet()) {
2538         Diag(TildeLoc, diag::err_destructor_tilde_scope);
2539         return true;
2540       }
2541
2542       // Recover as if the tilde had been written before the identifier.
2543       Diag(TildeLoc, diag::err_destructor_tilde_scope)
2544         << FixItHint::CreateRemoval(TildeLoc)
2545         << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2546
2547       // Temporarily enter the scope for the rest of this function.
2548       if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2549         DeclScopeObj.EnterDeclaratorScope();
2550     }
2551
2552     // Parse the class-name (or template-name in a simple-template-id).
2553     IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2554     SourceLocation ClassNameLoc = ConsumeToken();
2555
2556     if (TemplateSpecified || Tok.is(tok::less)) {
2557       Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
2558       return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2559                                           ClassName, ClassNameLoc,
2560                                           EnteringContext, ObjectType,
2561                                           Result, TemplateSpecified);
2562     }
2563
2564     // Note that this is a destructor name.
2565     ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, 
2566                                               ClassNameLoc, getCurScope(),
2567                                               SS, ObjectType,
2568                                               EnteringContext);
2569     if (!Ty)
2570       return true;
2571
2572     Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2573     return false;
2574   }
2575   
2576   Diag(Tok, diag::err_expected_unqualified_id)
2577     << getLangOpts().CPlusPlus;
2578   return true;
2579 }
2580
2581 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2582 /// memory in a typesafe manner and call constructors.
2583 ///
2584 /// This method is called to parse the new expression after the optional :: has
2585 /// been already parsed.  If the :: was present, "UseGlobal" is true and "Start"
2586 /// is its location.  Otherwise, "Start" is the location of the 'new' token.
2587 ///
2588 ///        new-expression:
2589 ///                   '::'[opt] 'new' new-placement[opt] new-type-id
2590 ///                                     new-initializer[opt]
2591 ///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2592 ///                                     new-initializer[opt]
2593 ///
2594 ///        new-placement:
2595 ///                   '(' expression-list ')'
2596 ///
2597 ///        new-type-id:
2598 ///                   type-specifier-seq new-declarator[opt]
2599 /// [GNU]             attributes type-specifier-seq new-declarator[opt]
2600 ///
2601 ///        new-declarator:
2602 ///                   ptr-operator new-declarator[opt]
2603 ///                   direct-new-declarator
2604 ///
2605 ///        new-initializer:
2606 ///                   '(' expression-list[opt] ')'
2607 /// [C++0x]           braced-init-list
2608 ///
2609 ExprResult
2610 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2611   assert(Tok.is(tok::kw_new) && "expected 'new' token");
2612   ConsumeToken();   // Consume 'new'
2613
2614   // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2615   // second form of new-expression. It can't be a new-type-id.
2616
2617   ExprVector PlacementArgs;
2618   SourceLocation PlacementLParen, PlacementRParen;
2619
2620   SourceRange TypeIdParens;
2621   DeclSpec DS(AttrFactory);
2622   Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
2623   if (Tok.is(tok::l_paren)) {
2624     // If it turns out to be a placement, we change the type location.
2625     BalancedDelimiterTracker T(*this, tok::l_paren);
2626     T.consumeOpen();
2627     PlacementLParen = T.getOpenLocation();
2628     if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2629       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2630       return ExprError();
2631     }
2632
2633     T.consumeClose();
2634     PlacementRParen = T.getCloseLocation();
2635     if (PlacementRParen.isInvalid()) {
2636       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2637       return ExprError();
2638     }
2639
2640     if (PlacementArgs.empty()) {
2641       // Reset the placement locations. There was no placement.
2642       TypeIdParens = T.getRange();
2643       PlacementLParen = PlacementRParen = SourceLocation();
2644     } else {
2645       // We still need the type.
2646       if (Tok.is(tok::l_paren)) {
2647         BalancedDelimiterTracker T(*this, tok::l_paren);
2648         T.consumeOpen();
2649         MaybeParseGNUAttributes(DeclaratorInfo);
2650         ParseSpecifierQualifierList(DS);
2651         DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2652         ParseDeclarator(DeclaratorInfo);
2653         T.consumeClose();
2654         TypeIdParens = T.getRange();
2655       } else {
2656         MaybeParseGNUAttributes(DeclaratorInfo);
2657         if (ParseCXXTypeSpecifierSeq(DS))
2658           DeclaratorInfo.setInvalidType(true);
2659         else {
2660           DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2661           ParseDeclaratorInternal(DeclaratorInfo,
2662                                   &Parser::ParseDirectNewDeclarator);
2663         }
2664       }
2665     }
2666   } else {
2667     // A new-type-id is a simplified type-id, where essentially the
2668     // direct-declarator is replaced by a direct-new-declarator.
2669     MaybeParseGNUAttributes(DeclaratorInfo);
2670     if (ParseCXXTypeSpecifierSeq(DS))
2671       DeclaratorInfo.setInvalidType(true);
2672     else {
2673       DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2674       ParseDeclaratorInternal(DeclaratorInfo,
2675                               &Parser::ParseDirectNewDeclarator);
2676     }
2677   }
2678   if (DeclaratorInfo.isInvalidType()) {
2679     SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2680     return ExprError();
2681   }
2682
2683   ExprResult Initializer;
2684
2685   if (Tok.is(tok::l_paren)) {
2686     SourceLocation ConstructorLParen, ConstructorRParen;
2687     ExprVector ConstructorArgs;
2688     BalancedDelimiterTracker T(*this, tok::l_paren);
2689     T.consumeOpen();
2690     ConstructorLParen = T.getOpenLocation();
2691     if (Tok.isNot(tok::r_paren)) {
2692       CommaLocsTy CommaLocs;
2693       if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2694             ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2695                                                        DeclaratorInfo).get();
2696             Actions.CodeCompleteConstructor(getCurScope(),
2697                                       TypeRep.get()->getCanonicalTypeInternal(),
2698                                             DeclaratorInfo.getLocEnd(),
2699                                             ConstructorArgs);
2700       })) {
2701         SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2702         return ExprError();
2703       }
2704     }
2705     T.consumeClose();
2706     ConstructorRParen = T.getCloseLocation();
2707     if (ConstructorRParen.isInvalid()) {
2708       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2709       return ExprError();
2710     }
2711     Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2712                                              ConstructorRParen,
2713                                              ConstructorArgs);
2714   } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2715     Diag(Tok.getLocation(),
2716          diag::warn_cxx98_compat_generalized_initializer_lists);
2717     Initializer = ParseBraceInitializer();
2718   }
2719   if (Initializer.isInvalid())
2720     return Initializer;
2721
2722   return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2723                              PlacementArgs, PlacementRParen,
2724                              TypeIdParens, DeclaratorInfo, Initializer.get());
2725 }
2726
2727 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2728 /// passed to ParseDeclaratorInternal.
2729 ///
2730 ///        direct-new-declarator:
2731 ///                   '[' expression ']'
2732 ///                   direct-new-declarator '[' constant-expression ']'
2733 ///
2734 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2735   // Parse the array dimensions.
2736   bool first = true;
2737   while (Tok.is(tok::l_square)) {
2738     // An array-size expression can't start with a lambda.
2739     if (CheckProhibitedCXX11Attribute())
2740       continue;
2741
2742     BalancedDelimiterTracker T(*this, tok::l_square);
2743     T.consumeOpen();
2744
2745     ExprResult Size(first ? ParseExpression()
2746                                 : ParseConstantExpression());
2747     if (Size.isInvalid()) {
2748       // Recover
2749       SkipUntil(tok::r_square, StopAtSemi);
2750       return;
2751     }
2752     first = false;
2753
2754     T.consumeClose();
2755
2756     // Attributes here appertain to the array type. C++11 [expr.new]p5.
2757     ParsedAttributes Attrs(AttrFactory);
2758     MaybeParseCXX11Attributes(Attrs);
2759
2760     D.AddTypeInfo(DeclaratorChunk::getArray(0,
2761                                             /*static=*/false, /*star=*/false,
2762                                             Size.get(),
2763                                             T.getOpenLocation(),
2764                                             T.getCloseLocation()),
2765                   Attrs, T.getCloseLocation());
2766
2767     if (T.getCloseLocation().isInvalid())
2768       return;
2769   }
2770 }
2771
2772 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2773 /// This ambiguity appears in the syntax of the C++ new operator.
2774 ///
2775 ///        new-expression:
2776 ///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2777 ///                                     new-initializer[opt]
2778 ///
2779 ///        new-placement:
2780 ///                   '(' expression-list ')'
2781 ///
2782 bool Parser::ParseExpressionListOrTypeId(
2783                                    SmallVectorImpl<Expr*> &PlacementArgs,
2784                                          Declarator &D) {
2785   // The '(' was already consumed.
2786   if (isTypeIdInParens()) {
2787     ParseSpecifierQualifierList(D.getMutableDeclSpec());
2788     D.SetSourceRange(D.getDeclSpec().getSourceRange());
2789     ParseDeclarator(D);
2790     return D.isInvalidType();
2791   }
2792
2793   // It's not a type, it has to be an expression list.
2794   // Discard the comma locations - ActOnCXXNew has enough parameters.
2795   CommaLocsTy CommaLocs;
2796   return ParseExpressionList(PlacementArgs, CommaLocs);
2797 }
2798
2799 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2800 /// to free memory allocated by new.
2801 ///
2802 /// This method is called to parse the 'delete' expression after the optional
2803 /// '::' has been already parsed.  If the '::' was present, "UseGlobal" is true
2804 /// and "Start" is its location.  Otherwise, "Start" is the location of the
2805 /// 'delete' token.
2806 ///
2807 ///        delete-expression:
2808 ///                   '::'[opt] 'delete' cast-expression
2809 ///                   '::'[opt] 'delete' '[' ']' cast-expression
2810 ExprResult
2811 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2812   assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2813   ConsumeToken(); // Consume 'delete'
2814
2815   // Array delete?
2816   bool ArrayDelete = false;
2817   if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2818     // C++11 [expr.delete]p1:
2819     //   Whenever the delete keyword is followed by empty square brackets, it
2820     //   shall be interpreted as [array delete].
2821     //   [Footnote: A lambda expression with a lambda-introducer that consists
2822     //              of empty square brackets can follow the delete keyword if
2823     //              the lambda expression is enclosed in parentheses.]
2824     // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2825     //        lambda-introducer.
2826     ArrayDelete = true;
2827     BalancedDelimiterTracker T(*this, tok::l_square);
2828
2829     T.consumeOpen();
2830     T.consumeClose();
2831     if (T.getCloseLocation().isInvalid())
2832       return ExprError();
2833   }
2834
2835   ExprResult Operand(ParseCastExpression(false));
2836   if (Operand.isInvalid())
2837     return Operand;
2838
2839   return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2840 }
2841
2842 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2843   switch (kind) {
2844   default: llvm_unreachable("Not a known type trait");
2845 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2846 case tok::kw_ ## Spelling: return UTT_ ## Name;
2847 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2848 case tok::kw_ ## Spelling: return BTT_ ## Name;
2849 #include "clang/Basic/TokenKinds.def"
2850 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2851   case tok::kw_ ## Spelling: return TT_ ## Name;
2852 #include "clang/Basic/TokenKinds.def"
2853   }
2854 }
2855
2856 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2857   switch(kind) {
2858   default: llvm_unreachable("Not a known binary type trait");
2859   case tok::kw___array_rank:                 return ATT_ArrayRank;
2860   case tok::kw___array_extent:               return ATT_ArrayExtent;
2861   }
2862 }
2863
2864 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2865   switch(kind) {
2866   default: llvm_unreachable("Not a known unary expression trait.");
2867   case tok::kw___is_lvalue_expr:             return ET_IsLValueExpr;
2868   case tok::kw___is_rvalue_expr:             return ET_IsRValueExpr;
2869   }
2870 }
2871
2872 static unsigned TypeTraitArity(tok::TokenKind kind) {
2873   switch (kind) {
2874     default: llvm_unreachable("Not a known type trait");
2875 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2876 #include "clang/Basic/TokenKinds.def"
2877   }
2878 }
2879
2880 /// \brief Parse the built-in type-trait pseudo-functions that allow 
2881 /// implementation of the TR1/C++11 type traits templates.
2882 ///
2883 ///       primary-expression:
2884 ///          unary-type-trait '(' type-id ')'
2885 ///          binary-type-trait '(' type-id ',' type-id ')'
2886 ///          type-trait '(' type-id-seq ')'
2887 ///
2888 ///       type-id-seq:
2889 ///          type-id ...[opt] type-id-seq[opt]
2890 ///
2891 ExprResult Parser::ParseTypeTrait() {
2892   tok::TokenKind Kind = Tok.getKind();
2893   unsigned Arity = TypeTraitArity(Kind);
2894
2895   SourceLocation Loc = ConsumeToken();
2896   
2897   BalancedDelimiterTracker Parens(*this, tok::l_paren);
2898   if (Parens.expectAndConsume())
2899     return ExprError();
2900
2901   SmallVector<ParsedType, 2> Args;
2902   do {
2903     // Parse the next type.
2904     TypeResult Ty = ParseTypeName();
2905     if (Ty.isInvalid()) {
2906       Parens.skipToEnd();
2907       return ExprError();
2908     }
2909
2910     // Parse the ellipsis, if present.
2911     if (Tok.is(tok::ellipsis)) {
2912       Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2913       if (Ty.isInvalid()) {
2914         Parens.skipToEnd();
2915         return ExprError();
2916       }
2917     }
2918     
2919     // Add this type to the list of arguments.
2920     Args.push_back(Ty.get());
2921   } while (TryConsumeToken(tok::comma));
2922
2923   if (Parens.consumeClose())
2924     return ExprError();
2925
2926   SourceLocation EndLoc = Parens.getCloseLocation();
2927
2928   if (Arity && Args.size() != Arity) {
2929     Diag(EndLoc, diag::err_type_trait_arity)
2930       << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2931     return ExprError();
2932   }
2933
2934   if (!Arity && Args.empty()) {
2935     Diag(EndLoc, diag::err_type_trait_arity)
2936       << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2937     return ExprError();
2938   }
2939
2940   return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
2941 }
2942
2943 /// ParseArrayTypeTrait - Parse the built-in array type-trait
2944 /// pseudo-functions.
2945 ///
2946 ///       primary-expression:
2947 /// [Embarcadero]     '__array_rank' '(' type-id ')'
2948 /// [Embarcadero]     '__array_extent' '(' type-id ',' expression ')'
2949 ///
2950 ExprResult Parser::ParseArrayTypeTrait() {
2951   ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2952   SourceLocation Loc = ConsumeToken();
2953
2954   BalancedDelimiterTracker T(*this, tok::l_paren);
2955   if (T.expectAndConsume())
2956     return ExprError();
2957
2958   TypeResult Ty = ParseTypeName();
2959   if (Ty.isInvalid()) {
2960     SkipUntil(tok::comma, StopAtSemi);
2961     SkipUntil(tok::r_paren, StopAtSemi);
2962     return ExprError();
2963   }
2964
2965   switch (ATT) {
2966   case ATT_ArrayRank: {
2967     T.consumeClose();
2968     return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
2969                                        T.getCloseLocation());
2970   }
2971   case ATT_ArrayExtent: {
2972     if (ExpectAndConsume(tok::comma)) {
2973       SkipUntil(tok::r_paren, StopAtSemi);
2974       return ExprError();
2975     }
2976
2977     ExprResult DimExpr = ParseExpression();
2978     T.consumeClose();
2979
2980     return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2981                                        T.getCloseLocation());
2982   }
2983   }
2984   llvm_unreachable("Invalid ArrayTypeTrait!");
2985 }
2986
2987 /// ParseExpressionTrait - Parse built-in expression-trait
2988 /// pseudo-functions like __is_lvalue_expr( xxx ).
2989 ///
2990 ///       primary-expression:
2991 /// [Embarcadero]     expression-trait '(' expression ')'
2992 ///
2993 ExprResult Parser::ParseExpressionTrait() {
2994   ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2995   SourceLocation Loc = ConsumeToken();
2996
2997   BalancedDelimiterTracker T(*this, tok::l_paren);
2998   if (T.expectAndConsume())
2999     return ExprError();
3000
3001   ExprResult Expr = ParseExpression();
3002
3003   T.consumeClose();
3004
3005   return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3006                                       T.getCloseLocation());
3007 }
3008
3009
3010 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3011 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3012 /// based on the context past the parens.
3013 ExprResult
3014 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3015                                          ParsedType &CastTy,
3016                                          BalancedDelimiterTracker &Tracker,
3017                                          ColonProtectionRAIIObject &ColonProt) {
3018   assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3019   assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3020   assert(isTypeIdInParens() && "Not a type-id!");
3021
3022   ExprResult Result(true);
3023   CastTy = ParsedType();
3024
3025   // We need to disambiguate a very ugly part of the C++ syntax:
3026   //
3027   // (T())x;  - type-id
3028   // (T())*x; - type-id
3029   // (T())/x; - expression
3030   // (T());   - expression
3031   //
3032   // The bad news is that we cannot use the specialized tentative parser, since
3033   // it can only verify that the thing inside the parens can be parsed as
3034   // type-id, it is not useful for determining the context past the parens.
3035   //
3036   // The good news is that the parser can disambiguate this part without
3037   // making any unnecessary Action calls.
3038   //
3039   // It uses a scheme similar to parsing inline methods. The parenthesized
3040   // tokens are cached, the context that follows is determined (possibly by
3041   // parsing a cast-expression), and then we re-introduce the cached tokens
3042   // into the token stream and parse them appropriately.
3043
3044   ParenParseOption ParseAs;
3045   CachedTokens Toks;
3046
3047   // Store the tokens of the parentheses. We will parse them after we determine
3048   // the context that follows them.
3049   if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3050     // We didn't find the ')' we expected.
3051     Tracker.consumeClose();
3052     return ExprError();
3053   }
3054
3055   if (Tok.is(tok::l_brace)) {
3056     ParseAs = CompoundLiteral;
3057   } else {
3058     bool NotCastExpr;
3059     if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3060       NotCastExpr = true;
3061     } else {
3062       // Try parsing the cast-expression that may follow.
3063       // If it is not a cast-expression, NotCastExpr will be true and no token
3064       // will be consumed.
3065       ColonProt.restore();
3066       Result = ParseCastExpression(false/*isUnaryExpression*/,
3067                                    false/*isAddressofOperand*/,
3068                                    NotCastExpr,
3069                                    // type-id has priority.
3070                                    IsTypeCast);
3071     }
3072
3073     // If we parsed a cast-expression, it's really a type-id, otherwise it's
3074     // an expression.
3075     ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3076   }
3077
3078   // The current token should go after the cached tokens.
3079   Toks.push_back(Tok);
3080   // Re-enter the stored parenthesized tokens into the token stream, so we may
3081   // parse them now.
3082   PP.EnterTokenStream(Toks.data(), Toks.size(),
3083                       true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
3084   // Drop the current token and bring the first cached one. It's the same token
3085   // as when we entered this function.
3086   ConsumeAnyToken();
3087
3088   if (ParseAs >= CompoundLiteral) {
3089     // Parse the type declarator.
3090     DeclSpec DS(AttrFactory);
3091     Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
3092     {
3093       ColonProtectionRAIIObject InnerColonProtection(*this);
3094       ParseSpecifierQualifierList(DS);
3095       ParseDeclarator(DeclaratorInfo);
3096     }
3097
3098     // Match the ')'.
3099     Tracker.consumeClose();
3100     ColonProt.restore();
3101
3102     if (ParseAs == CompoundLiteral) {
3103       ExprType = CompoundLiteral;
3104       if (DeclaratorInfo.isInvalidType())
3105         return ExprError();
3106
3107       TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3108       return ParseCompoundLiteralExpression(Ty.get(),
3109                                             Tracker.getOpenLocation(),
3110                                             Tracker.getCloseLocation());
3111     }
3112
3113     // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3114     assert(ParseAs == CastExpr);
3115
3116     if (DeclaratorInfo.isInvalidType())
3117       return ExprError();
3118
3119     // Result is what ParseCastExpression returned earlier.
3120     if (!Result.isInvalid())
3121       Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3122                                     DeclaratorInfo, CastTy,
3123                                     Tracker.getCloseLocation(), Result.get());
3124     return Result;
3125   }
3126
3127   // Not a compound literal, and not followed by a cast-expression.
3128   assert(ParseAs == SimpleExpr);
3129
3130   ExprType = SimpleExpr;
3131   Result = ParseExpression();
3132   if (!Result.isInvalid() && Tok.is(tok::r_paren))
3133     Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(), 
3134                                     Tok.getLocation(), Result.get());
3135
3136   // Match the ')'.
3137   if (Result.isInvalid()) {
3138     SkipUntil(tok::r_paren, StopAtSemi);
3139     return ExprError();
3140   }
3141
3142   Tracker.consumeClose();
3143   return Result;
3144 }