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