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