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