xref: /openbsd-src/gnu/llvm/clang/lib/Parse/ParseExprCXX.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This file implements the Expression parsing implementation for C++.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick #include "clang/AST/ASTContext.h"
13e5dd7070Spatrick #include "clang/AST/Decl.h"
14e5dd7070Spatrick #include "clang/AST/DeclTemplate.h"
15e5dd7070Spatrick #include "clang/AST/ExprCXX.h"
16e5dd7070Spatrick #include "clang/Basic/PrettyStackTrace.h"
17*12c85518Srobert #include "clang/Basic/TokenKinds.h"
18e5dd7070Spatrick #include "clang/Lex/LiteralSupport.h"
19e5dd7070Spatrick #include "clang/Parse/ParseDiagnostic.h"
20a9ac8606Spatrick #include "clang/Parse/Parser.h"
21e5dd7070Spatrick #include "clang/Parse/RAIIObjectsForParser.h"
22e5dd7070Spatrick #include "clang/Sema/DeclSpec.h"
23e5dd7070Spatrick #include "clang/Sema/ParsedTemplate.h"
24e5dd7070Spatrick #include "clang/Sema/Scope.h"
25*12c85518Srobert #include "llvm/Support/Compiler.h"
26e5dd7070Spatrick #include "llvm/Support/ErrorHandling.h"
27e5dd7070Spatrick #include <numeric>
28e5dd7070Spatrick 
29e5dd7070Spatrick using namespace clang;
30e5dd7070Spatrick 
SelectDigraphErrorMessage(tok::TokenKind Kind)31e5dd7070Spatrick static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
32e5dd7070Spatrick   switch (Kind) {
33e5dd7070Spatrick     // template name
34e5dd7070Spatrick     case tok::unknown:             return 0;
35e5dd7070Spatrick     // casts
36ec727ea7Spatrick     case tok::kw_addrspace_cast:   return 1;
37ec727ea7Spatrick     case tok::kw_const_cast:       return 2;
38ec727ea7Spatrick     case tok::kw_dynamic_cast:     return 3;
39ec727ea7Spatrick     case tok::kw_reinterpret_cast: return 4;
40ec727ea7Spatrick     case tok::kw_static_cast:      return 5;
41e5dd7070Spatrick     default:
42e5dd7070Spatrick       llvm_unreachable("Unknown type for digraph error message.");
43e5dd7070Spatrick   }
44e5dd7070Spatrick }
45e5dd7070Spatrick 
46e5dd7070Spatrick // Are the two tokens adjacent in the same source file?
areTokensAdjacent(const Token & First,const Token & Second)47e5dd7070Spatrick bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
48e5dd7070Spatrick   SourceManager &SM = PP.getSourceManager();
49e5dd7070Spatrick   SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
50e5dd7070Spatrick   SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
51e5dd7070Spatrick   return FirstEnd == SM.getSpellingLoc(Second.getLocation());
52e5dd7070Spatrick }
53e5dd7070Spatrick 
54e5dd7070Spatrick // Suggest fixit for "<::" after a cast.
FixDigraph(Parser & P,Preprocessor & PP,Token & DigraphToken,Token & ColonToken,tok::TokenKind Kind,bool AtDigraph)55e5dd7070Spatrick static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
56e5dd7070Spatrick                        Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
57e5dd7070Spatrick   // Pull '<:' and ':' off token stream.
58e5dd7070Spatrick   if (!AtDigraph)
59e5dd7070Spatrick     PP.Lex(DigraphToken);
60e5dd7070Spatrick   PP.Lex(ColonToken);
61e5dd7070Spatrick 
62e5dd7070Spatrick   SourceRange Range;
63e5dd7070Spatrick   Range.setBegin(DigraphToken.getLocation());
64e5dd7070Spatrick   Range.setEnd(ColonToken.getLocation());
65e5dd7070Spatrick   P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
66e5dd7070Spatrick       << SelectDigraphErrorMessage(Kind)
67e5dd7070Spatrick       << FixItHint::CreateReplacement(Range, "< ::");
68e5dd7070Spatrick 
69e5dd7070Spatrick   // Update token information to reflect their change in token type.
70e5dd7070Spatrick   ColonToken.setKind(tok::coloncolon);
71e5dd7070Spatrick   ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
72e5dd7070Spatrick   ColonToken.setLength(2);
73e5dd7070Spatrick   DigraphToken.setKind(tok::less);
74e5dd7070Spatrick   DigraphToken.setLength(1);
75e5dd7070Spatrick 
76e5dd7070Spatrick   // Push new tokens back to token stream.
77e5dd7070Spatrick   PP.EnterToken(ColonToken, /*IsReinject*/ true);
78e5dd7070Spatrick   if (!AtDigraph)
79e5dd7070Spatrick     PP.EnterToken(DigraphToken, /*IsReinject*/ true);
80e5dd7070Spatrick }
81e5dd7070Spatrick 
82e5dd7070Spatrick // Check for '<::' which should be '< ::' instead of '[:' when following
83e5dd7070Spatrick // a template name.
CheckForTemplateAndDigraph(Token & Next,ParsedType ObjectType,bool EnteringContext,IdentifierInfo & II,CXXScopeSpec & SS)84e5dd7070Spatrick void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
85e5dd7070Spatrick                                         bool EnteringContext,
86e5dd7070Spatrick                                         IdentifierInfo &II, CXXScopeSpec &SS) {
87e5dd7070Spatrick   if (!Next.is(tok::l_square) || Next.getLength() != 2)
88e5dd7070Spatrick     return;
89e5dd7070Spatrick 
90e5dd7070Spatrick   Token SecondToken = GetLookAheadToken(2);
91e5dd7070Spatrick   if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
92e5dd7070Spatrick     return;
93e5dd7070Spatrick 
94e5dd7070Spatrick   TemplateTy Template;
95e5dd7070Spatrick   UnqualifiedId TemplateName;
96e5dd7070Spatrick   TemplateName.setIdentifier(&II, Tok.getLocation());
97e5dd7070Spatrick   bool MemberOfUnknownSpecialization;
98e5dd7070Spatrick   if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
99e5dd7070Spatrick                               TemplateName, ObjectType, EnteringContext,
100e5dd7070Spatrick                               Template, MemberOfUnknownSpecialization))
101e5dd7070Spatrick     return;
102e5dd7070Spatrick 
103e5dd7070Spatrick   FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
104e5dd7070Spatrick              /*AtDigraph*/false);
105e5dd7070Spatrick }
106e5dd7070Spatrick 
107e5dd7070Spatrick /// Parse global scope or nested-name-specifier if present.
108e5dd7070Spatrick ///
109e5dd7070Spatrick /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
110e5dd7070Spatrick /// may be preceded by '::'). Note that this routine will not parse ::new or
111e5dd7070Spatrick /// ::delete; it will just leave them in the token stream.
112e5dd7070Spatrick ///
113e5dd7070Spatrick ///       '::'[opt] nested-name-specifier
114e5dd7070Spatrick ///       '::'
115e5dd7070Spatrick ///
116e5dd7070Spatrick ///       nested-name-specifier:
117e5dd7070Spatrick ///         type-name '::'
118e5dd7070Spatrick ///         namespace-name '::'
119e5dd7070Spatrick ///         nested-name-specifier identifier '::'
120e5dd7070Spatrick ///         nested-name-specifier 'template'[opt] simple-template-id '::'
121e5dd7070Spatrick ///
122e5dd7070Spatrick ///
123e5dd7070Spatrick /// \param SS the scope specifier that will be set to the parsed
124e5dd7070Spatrick /// nested-name-specifier (or empty)
125e5dd7070Spatrick ///
126e5dd7070Spatrick /// \param ObjectType if this nested-name-specifier is being parsed following
127e5dd7070Spatrick /// the "." or "->" of a member access expression, this parameter provides the
128e5dd7070Spatrick /// type of the object whose members are being accessed.
129e5dd7070Spatrick ///
130ec727ea7Spatrick /// \param ObjectHadErrors if this unqualified-id occurs within a member access
131ec727ea7Spatrick /// expression, indicates whether the original subexpressions had any errors.
132ec727ea7Spatrick /// When true, diagnostics for missing 'template' keyword will be supressed.
133ec727ea7Spatrick ///
134e5dd7070Spatrick /// \param EnteringContext whether we will be entering into the context of
135e5dd7070Spatrick /// the nested-name-specifier after parsing it.
136e5dd7070Spatrick ///
137e5dd7070Spatrick /// \param MayBePseudoDestructor When non-NULL, points to a flag that
138e5dd7070Spatrick /// indicates whether this nested-name-specifier may be part of a
139e5dd7070Spatrick /// pseudo-destructor name. In this case, the flag will be set false
140ec727ea7Spatrick /// if we don't actually end up parsing a destructor name. Moreover,
141e5dd7070Spatrick /// if we do end up determining that we are parsing a destructor name,
142e5dd7070Spatrick /// the last component of the nested-name-specifier is not parsed as
143e5dd7070Spatrick /// part of the scope specifier.
144e5dd7070Spatrick ///
145e5dd7070Spatrick /// \param IsTypename If \c true, this nested-name-specifier is known to be
146e5dd7070Spatrick /// part of a type name. This is used to improve error recovery.
147e5dd7070Spatrick ///
148e5dd7070Spatrick /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
149e5dd7070Spatrick /// filled in with the leading identifier in the last component of the
150e5dd7070Spatrick /// nested-name-specifier, if any.
151e5dd7070Spatrick ///
152e5dd7070Spatrick /// \param OnlyNamespace If true, only considers namespaces in lookup.
153e5dd7070Spatrick ///
154e5dd7070Spatrick ///
155e5dd7070Spatrick /// \returns true if there was an error parsing a scope specifier
ParseOptionalCXXScopeSpecifier(CXXScopeSpec & SS,ParsedType ObjectType,bool ObjectHadErrors,bool EnteringContext,bool * MayBePseudoDestructor,bool IsTypename,IdentifierInfo ** LastII,bool OnlyNamespace,bool InUsingDeclaration)156ec727ea7Spatrick bool Parser::ParseOptionalCXXScopeSpecifier(
157ec727ea7Spatrick     CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
158ec727ea7Spatrick     bool EnteringContext, bool *MayBePseudoDestructor, bool IsTypename,
159ec727ea7Spatrick     IdentifierInfo **LastII, bool OnlyNamespace, bool InUsingDeclaration) {
160e5dd7070Spatrick   assert(getLangOpts().CPlusPlus &&
161e5dd7070Spatrick          "Call sites of this function should be guarded by checking for C++");
162e5dd7070Spatrick 
163e5dd7070Spatrick   if (Tok.is(tok::annot_cxxscope)) {
164e5dd7070Spatrick     assert(!LastII && "want last identifier but have already annotated scope");
165e5dd7070Spatrick     assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
166e5dd7070Spatrick     Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
167e5dd7070Spatrick                                                  Tok.getAnnotationRange(),
168e5dd7070Spatrick                                                  SS);
169e5dd7070Spatrick     ConsumeAnnotationToken();
170e5dd7070Spatrick     return false;
171e5dd7070Spatrick   }
172e5dd7070Spatrick 
173e5dd7070Spatrick   // Has to happen before any "return false"s in this function.
174e5dd7070Spatrick   bool CheckForDestructor = false;
175e5dd7070Spatrick   if (MayBePseudoDestructor && *MayBePseudoDestructor) {
176e5dd7070Spatrick     CheckForDestructor = true;
177e5dd7070Spatrick     *MayBePseudoDestructor = false;
178e5dd7070Spatrick   }
179e5dd7070Spatrick 
180e5dd7070Spatrick   if (LastII)
181e5dd7070Spatrick     *LastII = nullptr;
182e5dd7070Spatrick 
183e5dd7070Spatrick   bool HasScopeSpecifier = false;
184e5dd7070Spatrick 
185e5dd7070Spatrick   if (Tok.is(tok::coloncolon)) {
186e5dd7070Spatrick     // ::new and ::delete aren't nested-name-specifiers.
187e5dd7070Spatrick     tok::TokenKind NextKind = NextToken().getKind();
188e5dd7070Spatrick     if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
189e5dd7070Spatrick       return false;
190e5dd7070Spatrick 
191e5dd7070Spatrick     if (NextKind == tok::l_brace) {
192e5dd7070Spatrick       // It is invalid to have :: {, consume the scope qualifier and pretend
193e5dd7070Spatrick       // like we never saw it.
194e5dd7070Spatrick       Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
195e5dd7070Spatrick     } else {
196e5dd7070Spatrick       // '::' - Global scope qualifier.
197e5dd7070Spatrick       if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
198e5dd7070Spatrick         return true;
199e5dd7070Spatrick 
200e5dd7070Spatrick       HasScopeSpecifier = true;
201e5dd7070Spatrick     }
202e5dd7070Spatrick   }
203e5dd7070Spatrick 
204e5dd7070Spatrick   if (Tok.is(tok::kw___super)) {
205e5dd7070Spatrick     SourceLocation SuperLoc = ConsumeToken();
206e5dd7070Spatrick     if (!Tok.is(tok::coloncolon)) {
207e5dd7070Spatrick       Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
208e5dd7070Spatrick       return true;
209e5dd7070Spatrick     }
210e5dd7070Spatrick 
211e5dd7070Spatrick     return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
212e5dd7070Spatrick   }
213e5dd7070Spatrick 
214e5dd7070Spatrick   if (!HasScopeSpecifier &&
215e5dd7070Spatrick       Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
216e5dd7070Spatrick     DeclSpec DS(AttrFactory);
217e5dd7070Spatrick     SourceLocation DeclLoc = Tok.getLocation();
218e5dd7070Spatrick     SourceLocation EndLoc  = ParseDecltypeSpecifier(DS);
219e5dd7070Spatrick 
220e5dd7070Spatrick     SourceLocation CCLoc;
221e5dd7070Spatrick     // Work around a standard defect: 'decltype(auto)::' is not a
222e5dd7070Spatrick     // nested-name-specifier.
223e5dd7070Spatrick     if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
224e5dd7070Spatrick         !TryConsumeToken(tok::coloncolon, CCLoc)) {
225e5dd7070Spatrick       AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
226e5dd7070Spatrick       return false;
227e5dd7070Spatrick     }
228e5dd7070Spatrick 
229e5dd7070Spatrick     if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
230e5dd7070Spatrick       SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
231e5dd7070Spatrick 
232e5dd7070Spatrick     HasScopeSpecifier = true;
233e5dd7070Spatrick   }
234e5dd7070Spatrick 
235e5dd7070Spatrick   // Preferred type might change when parsing qualifiers, we need the original.
236e5dd7070Spatrick   auto SavedType = PreferredType;
237e5dd7070Spatrick   while (true) {
238e5dd7070Spatrick     if (HasScopeSpecifier) {
239e5dd7070Spatrick       if (Tok.is(tok::code_completion)) {
240a9ac8606Spatrick         cutOffParsing();
241e5dd7070Spatrick         // Code completion for a nested-name-specifier, where the code
242e5dd7070Spatrick         // completion token follows the '::'.
243e5dd7070Spatrick         Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext,
244e5dd7070Spatrick                                         InUsingDeclaration, ObjectType.get(),
245e5dd7070Spatrick                                         SavedType.get(SS.getBeginLoc()));
246e5dd7070Spatrick         // Include code completion token into the range of the scope otherwise
247e5dd7070Spatrick         // when we try to annotate the scope tokens the dangling code completion
248e5dd7070Spatrick         // token will cause assertion in
249e5dd7070Spatrick         // Preprocessor::AnnotatePreviousCachedTokens.
250e5dd7070Spatrick         SS.setEndLoc(Tok.getLocation());
251e5dd7070Spatrick         return true;
252e5dd7070Spatrick       }
253e5dd7070Spatrick 
254e5dd7070Spatrick       // C++ [basic.lookup.classref]p5:
255e5dd7070Spatrick       //   If the qualified-id has the form
256e5dd7070Spatrick       //
257e5dd7070Spatrick       //       ::class-name-or-namespace-name::...
258e5dd7070Spatrick       //
259e5dd7070Spatrick       //   the class-name-or-namespace-name is looked up in global scope as a
260e5dd7070Spatrick       //   class-name or namespace-name.
261e5dd7070Spatrick       //
262e5dd7070Spatrick       // To implement this, we clear out the object type as soon as we've
263e5dd7070Spatrick       // seen a leading '::' or part of a nested-name-specifier.
264e5dd7070Spatrick       ObjectType = nullptr;
265e5dd7070Spatrick     }
266e5dd7070Spatrick 
267e5dd7070Spatrick     // nested-name-specifier:
268e5dd7070Spatrick     //   nested-name-specifier 'template'[opt] simple-template-id '::'
269e5dd7070Spatrick 
270e5dd7070Spatrick     // Parse the optional 'template' keyword, then make sure we have
271e5dd7070Spatrick     // 'identifier <' after it.
272e5dd7070Spatrick     if (Tok.is(tok::kw_template)) {
273e5dd7070Spatrick       // If we don't have a scope specifier or an object type, this isn't a
274e5dd7070Spatrick       // nested-name-specifier, since they aren't allowed to start with
275e5dd7070Spatrick       // 'template'.
276e5dd7070Spatrick       if (!HasScopeSpecifier && !ObjectType)
277e5dd7070Spatrick         break;
278e5dd7070Spatrick 
279e5dd7070Spatrick       TentativeParsingAction TPA(*this);
280e5dd7070Spatrick       SourceLocation TemplateKWLoc = ConsumeToken();
281e5dd7070Spatrick 
282e5dd7070Spatrick       UnqualifiedId TemplateName;
283e5dd7070Spatrick       if (Tok.is(tok::identifier)) {
284e5dd7070Spatrick         // Consume the identifier.
285e5dd7070Spatrick         TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
286e5dd7070Spatrick         ConsumeToken();
287e5dd7070Spatrick       } else if (Tok.is(tok::kw_operator)) {
288e5dd7070Spatrick         // We don't need to actually parse the unqualified-id in this case,
289e5dd7070Spatrick         // because a simple-template-id cannot start with 'operator', but
290e5dd7070Spatrick         // go ahead and parse it anyway for consistency with the case where
291e5dd7070Spatrick         // we already annotated the template-id.
292e5dd7070Spatrick         if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
293e5dd7070Spatrick                                        TemplateName)) {
294e5dd7070Spatrick           TPA.Commit();
295e5dd7070Spatrick           break;
296e5dd7070Spatrick         }
297e5dd7070Spatrick 
298e5dd7070Spatrick         if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
299e5dd7070Spatrick             TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
300e5dd7070Spatrick           Diag(TemplateName.getSourceRange().getBegin(),
301e5dd7070Spatrick                diag::err_id_after_template_in_nested_name_spec)
302e5dd7070Spatrick             << TemplateName.getSourceRange();
303e5dd7070Spatrick           TPA.Commit();
304e5dd7070Spatrick           break;
305e5dd7070Spatrick         }
306e5dd7070Spatrick       } else {
307e5dd7070Spatrick         TPA.Revert();
308e5dd7070Spatrick         break;
309e5dd7070Spatrick       }
310e5dd7070Spatrick 
311e5dd7070Spatrick       // If the next token is not '<', we have a qualified-id that refers
312e5dd7070Spatrick       // to a template name, such as T::template apply, but is not a
313e5dd7070Spatrick       // template-id.
314e5dd7070Spatrick       if (Tok.isNot(tok::less)) {
315e5dd7070Spatrick         TPA.Revert();
316e5dd7070Spatrick         break;
317e5dd7070Spatrick       }
318e5dd7070Spatrick 
319e5dd7070Spatrick       // Commit to parsing the template-id.
320e5dd7070Spatrick       TPA.Commit();
321e5dd7070Spatrick       TemplateTy Template;
322ec727ea7Spatrick       TemplateNameKind TNK = Actions.ActOnTemplateName(
323e5dd7070Spatrick           getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
324ec727ea7Spatrick           EnteringContext, Template, /*AllowInjectedClassName*/ true);
325e5dd7070Spatrick       if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
326e5dd7070Spatrick                                   TemplateName, false))
327e5dd7070Spatrick         return true;
328e5dd7070Spatrick 
329e5dd7070Spatrick       continue;
330e5dd7070Spatrick     }
331e5dd7070Spatrick 
332e5dd7070Spatrick     if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
333e5dd7070Spatrick       // We have
334e5dd7070Spatrick       //
335e5dd7070Spatrick       //   template-id '::'
336e5dd7070Spatrick       //
337e5dd7070Spatrick       // So we need to check whether the template-id is a simple-template-id of
338e5dd7070Spatrick       // the right kind (it should name a type or be dependent), and then
339e5dd7070Spatrick       // convert it into a type within the nested-name-specifier.
340e5dd7070Spatrick       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
341e5dd7070Spatrick       if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
342e5dd7070Spatrick         *MayBePseudoDestructor = true;
343e5dd7070Spatrick         return false;
344e5dd7070Spatrick       }
345e5dd7070Spatrick 
346e5dd7070Spatrick       if (LastII)
347e5dd7070Spatrick         *LastII = TemplateId->Name;
348e5dd7070Spatrick 
349e5dd7070Spatrick       // Consume the template-id token.
350e5dd7070Spatrick       ConsumeAnnotationToken();
351e5dd7070Spatrick 
352e5dd7070Spatrick       assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
353e5dd7070Spatrick       SourceLocation CCLoc = ConsumeToken();
354e5dd7070Spatrick 
355e5dd7070Spatrick       HasScopeSpecifier = true;
356e5dd7070Spatrick 
357e5dd7070Spatrick       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
358e5dd7070Spatrick                                          TemplateId->NumArgs);
359e5dd7070Spatrick 
360ec727ea7Spatrick       if (TemplateId->isInvalid() ||
361ec727ea7Spatrick           Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
362e5dd7070Spatrick                                               SS,
363e5dd7070Spatrick                                               TemplateId->TemplateKWLoc,
364e5dd7070Spatrick                                               TemplateId->Template,
365e5dd7070Spatrick                                               TemplateId->TemplateNameLoc,
366e5dd7070Spatrick                                               TemplateId->LAngleLoc,
367e5dd7070Spatrick                                               TemplateArgsPtr,
368e5dd7070Spatrick                                               TemplateId->RAngleLoc,
369e5dd7070Spatrick                                               CCLoc,
370e5dd7070Spatrick                                               EnteringContext)) {
371e5dd7070Spatrick         SourceLocation StartLoc
372e5dd7070Spatrick           = SS.getBeginLoc().isValid()? SS.getBeginLoc()
373e5dd7070Spatrick                                       : TemplateId->TemplateNameLoc;
374e5dd7070Spatrick         SS.SetInvalid(SourceRange(StartLoc, CCLoc));
375e5dd7070Spatrick       }
376e5dd7070Spatrick 
377e5dd7070Spatrick       continue;
378e5dd7070Spatrick     }
379e5dd7070Spatrick 
380e5dd7070Spatrick     // The rest of the nested-name-specifier possibilities start with
381e5dd7070Spatrick     // tok::identifier.
382e5dd7070Spatrick     if (Tok.isNot(tok::identifier))
383e5dd7070Spatrick       break;
384e5dd7070Spatrick 
385e5dd7070Spatrick     IdentifierInfo &II = *Tok.getIdentifierInfo();
386e5dd7070Spatrick 
387e5dd7070Spatrick     // nested-name-specifier:
388e5dd7070Spatrick     //   type-name '::'
389e5dd7070Spatrick     //   namespace-name '::'
390e5dd7070Spatrick     //   nested-name-specifier identifier '::'
391e5dd7070Spatrick     Token Next = NextToken();
392e5dd7070Spatrick     Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
393e5dd7070Spatrick                                     ObjectType);
394e5dd7070Spatrick 
395e5dd7070Spatrick     // If we get foo:bar, this is almost certainly a typo for foo::bar.  Recover
396e5dd7070Spatrick     // and emit a fixit hint for it.
397e5dd7070Spatrick     if (Next.is(tok::colon) && !ColonIsSacred) {
398e5dd7070Spatrick       if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
399e5dd7070Spatrick                                             EnteringContext) &&
400e5dd7070Spatrick           // If the token after the colon isn't an identifier, it's still an
401e5dd7070Spatrick           // error, but they probably meant something else strange so don't
402e5dd7070Spatrick           // recover like this.
403e5dd7070Spatrick           PP.LookAhead(1).is(tok::identifier)) {
404e5dd7070Spatrick         Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
405e5dd7070Spatrick           << FixItHint::CreateReplacement(Next.getLocation(), "::");
406e5dd7070Spatrick         // Recover as if the user wrote '::'.
407e5dd7070Spatrick         Next.setKind(tok::coloncolon);
408e5dd7070Spatrick       }
409e5dd7070Spatrick     }
410e5dd7070Spatrick 
411e5dd7070Spatrick     if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
412e5dd7070Spatrick       // It is invalid to have :: {, consume the scope qualifier and pretend
413e5dd7070Spatrick       // like we never saw it.
414e5dd7070Spatrick       Token Identifier = Tok; // Stash away the identifier.
415e5dd7070Spatrick       ConsumeToken();         // Eat the identifier, current token is now '::'.
416e5dd7070Spatrick       Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
417e5dd7070Spatrick           << tok::identifier;
418e5dd7070Spatrick       UnconsumeToken(Identifier); // Stick the identifier back.
419e5dd7070Spatrick       Next = NextToken();         // Point Next at the '{' token.
420e5dd7070Spatrick     }
421e5dd7070Spatrick 
422e5dd7070Spatrick     if (Next.is(tok::coloncolon)) {
423ec727ea7Spatrick       if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
424e5dd7070Spatrick         *MayBePseudoDestructor = true;
425e5dd7070Spatrick         return false;
426e5dd7070Spatrick       }
427e5dd7070Spatrick 
428e5dd7070Spatrick       if (ColonIsSacred) {
429e5dd7070Spatrick         const Token &Next2 = GetLookAheadToken(2);
430e5dd7070Spatrick         if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
431e5dd7070Spatrick             Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
432e5dd7070Spatrick           Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
433e5dd7070Spatrick               << Next2.getName()
434e5dd7070Spatrick               << FixItHint::CreateReplacement(Next.getLocation(), ":");
435e5dd7070Spatrick           Token ColonColon;
436e5dd7070Spatrick           PP.Lex(ColonColon);
437e5dd7070Spatrick           ColonColon.setKind(tok::colon);
438e5dd7070Spatrick           PP.EnterToken(ColonColon, /*IsReinject*/ true);
439e5dd7070Spatrick           break;
440e5dd7070Spatrick         }
441e5dd7070Spatrick       }
442e5dd7070Spatrick 
443e5dd7070Spatrick       if (LastII)
444e5dd7070Spatrick         *LastII = &II;
445e5dd7070Spatrick 
446e5dd7070Spatrick       // We have an identifier followed by a '::'. Lookup this name
447e5dd7070Spatrick       // as the name in a nested-name-specifier.
448e5dd7070Spatrick       Token Identifier = Tok;
449e5dd7070Spatrick       SourceLocation IdLoc = ConsumeToken();
450e5dd7070Spatrick       assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
451e5dd7070Spatrick              "NextToken() not working properly!");
452e5dd7070Spatrick       Token ColonColon = Tok;
453e5dd7070Spatrick       SourceLocation CCLoc = ConsumeToken();
454e5dd7070Spatrick 
455e5dd7070Spatrick       bool IsCorrectedToColon = false;
456e5dd7070Spatrick       bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
457e5dd7070Spatrick       if (Actions.ActOnCXXNestedNameSpecifier(
458*12c85518Srobert               getCurScope(), IdInfo, EnteringContext, SS, CorrectionFlagPtr,
459*12c85518Srobert               OnlyNamespace)) {
460e5dd7070Spatrick         // Identifier is not recognized as a nested name, but we can have
461e5dd7070Spatrick         // mistyped '::' instead of ':'.
462e5dd7070Spatrick         if (CorrectionFlagPtr && IsCorrectedToColon) {
463e5dd7070Spatrick           ColonColon.setKind(tok::colon);
464e5dd7070Spatrick           PP.EnterToken(Tok, /*IsReinject*/ true);
465e5dd7070Spatrick           PP.EnterToken(ColonColon, /*IsReinject*/ true);
466e5dd7070Spatrick           Tok = Identifier;
467e5dd7070Spatrick           break;
468e5dd7070Spatrick         }
469e5dd7070Spatrick         SS.SetInvalid(SourceRange(IdLoc, CCLoc));
470e5dd7070Spatrick       }
471e5dd7070Spatrick       HasScopeSpecifier = true;
472e5dd7070Spatrick       continue;
473e5dd7070Spatrick     }
474e5dd7070Spatrick 
475e5dd7070Spatrick     CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
476e5dd7070Spatrick 
477e5dd7070Spatrick     // nested-name-specifier:
478e5dd7070Spatrick     //   type-name '<'
479e5dd7070Spatrick     if (Next.is(tok::less)) {
480e5dd7070Spatrick 
481e5dd7070Spatrick       TemplateTy Template;
482e5dd7070Spatrick       UnqualifiedId TemplateName;
483e5dd7070Spatrick       TemplateName.setIdentifier(&II, Tok.getLocation());
484e5dd7070Spatrick       bool MemberOfUnknownSpecialization;
485e5dd7070Spatrick       if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
486e5dd7070Spatrick                                               /*hasTemplateKeyword=*/false,
487e5dd7070Spatrick                                                         TemplateName,
488e5dd7070Spatrick                                                         ObjectType,
489e5dd7070Spatrick                                                         EnteringContext,
490e5dd7070Spatrick                                                         Template,
491e5dd7070Spatrick                                               MemberOfUnknownSpecialization)) {
492e5dd7070Spatrick         // If lookup didn't find anything, we treat the name as a template-name
493e5dd7070Spatrick         // anyway. C++20 requires this, and in prior language modes it improves
494e5dd7070Spatrick         // error recovery. But before we commit to this, check that we actually
495e5dd7070Spatrick         // have something that looks like a template-argument-list next.
496e5dd7070Spatrick         if (!IsTypename && TNK == TNK_Undeclared_template &&
497e5dd7070Spatrick             isTemplateArgumentList(1) == TPResult::False)
498e5dd7070Spatrick           break;
499e5dd7070Spatrick 
500e5dd7070Spatrick         // We have found a template name, so annotate this token
501e5dd7070Spatrick         // with a template-id annotation. We do not permit the
502e5dd7070Spatrick         // template-id to be translated into a type annotation,
503e5dd7070Spatrick         // because some clients (e.g., the parsing of class template
504e5dd7070Spatrick         // specializations) still want to see the original template-id
505e5dd7070Spatrick         // token, and it might not be a type at all (e.g. a concept name in a
506e5dd7070Spatrick         // type-constraint).
507e5dd7070Spatrick         ConsumeToken();
508e5dd7070Spatrick         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
509e5dd7070Spatrick                                     TemplateName, false))
510e5dd7070Spatrick           return true;
511e5dd7070Spatrick         continue;
512e5dd7070Spatrick       }
513e5dd7070Spatrick 
514e5dd7070Spatrick       if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
515e5dd7070Spatrick           (IsTypename || isTemplateArgumentList(1) == TPResult::True)) {
516ec727ea7Spatrick         // If we had errors before, ObjectType can be dependent even without any
517ec727ea7Spatrick         // templates. Do not report missing template keyword in that case.
518ec727ea7Spatrick         if (!ObjectHadErrors) {
519e5dd7070Spatrick           // We have something like t::getAs<T>, where getAs is a
520e5dd7070Spatrick           // member of an unknown specialization. However, this will only
521e5dd7070Spatrick           // parse correctly as a template, so suggest the keyword 'template'
522e5dd7070Spatrick           // before 'getAs' and treat this as a dependent template name.
523e5dd7070Spatrick           unsigned DiagID = diag::err_missing_dependent_template_keyword;
524e5dd7070Spatrick           if (getLangOpts().MicrosoftExt)
525e5dd7070Spatrick             DiagID = diag::warn_missing_dependent_template_keyword;
526e5dd7070Spatrick 
527e5dd7070Spatrick           Diag(Tok.getLocation(), DiagID)
528e5dd7070Spatrick               << II.getName()
529e5dd7070Spatrick               << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
530ec727ea7Spatrick         }
531e5dd7070Spatrick 
532ec727ea7Spatrick         SourceLocation TemplateNameLoc = ConsumeToken();
533ec727ea7Spatrick 
534ec727ea7Spatrick         TemplateNameKind TNK = Actions.ActOnTemplateName(
535ec727ea7Spatrick             getCurScope(), SS, TemplateNameLoc, TemplateName, ObjectType,
536ec727ea7Spatrick             EnteringContext, Template, /*AllowInjectedClassName*/ true);
537e5dd7070Spatrick         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
538e5dd7070Spatrick                                     TemplateName, false))
539e5dd7070Spatrick           return true;
540e5dd7070Spatrick 
541e5dd7070Spatrick         continue;
542e5dd7070Spatrick       }
543e5dd7070Spatrick     }
544e5dd7070Spatrick 
545e5dd7070Spatrick     // We don't have any tokens that form the beginning of a
546e5dd7070Spatrick     // nested-name-specifier, so we're done.
547e5dd7070Spatrick     break;
548e5dd7070Spatrick   }
549e5dd7070Spatrick 
550e5dd7070Spatrick   // Even if we didn't see any pieces of a nested-name-specifier, we
551e5dd7070Spatrick   // still check whether there is a tilde in this position, which
552e5dd7070Spatrick   // indicates a potential pseudo-destructor.
553ec727ea7Spatrick   if (CheckForDestructor && !HasScopeSpecifier && Tok.is(tok::tilde))
554e5dd7070Spatrick     *MayBePseudoDestructor = true;
555e5dd7070Spatrick 
556e5dd7070Spatrick   return false;
557e5dd7070Spatrick }
558e5dd7070Spatrick 
tryParseCXXIdExpression(CXXScopeSpec & SS,bool isAddressOfOperand,Token & Replacement)559e5dd7070Spatrick ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS,
560e5dd7070Spatrick                                            bool isAddressOfOperand,
561e5dd7070Spatrick                                            Token &Replacement) {
562e5dd7070Spatrick   ExprResult E;
563e5dd7070Spatrick 
564e5dd7070Spatrick   // We may have already annotated this id-expression.
565e5dd7070Spatrick   switch (Tok.getKind()) {
566e5dd7070Spatrick   case tok::annot_non_type: {
567e5dd7070Spatrick     NamedDecl *ND = getNonTypeAnnotation(Tok);
568e5dd7070Spatrick     SourceLocation Loc = ConsumeAnnotationToken();
569e5dd7070Spatrick     E = Actions.ActOnNameClassifiedAsNonType(getCurScope(), SS, ND, Loc, Tok);
570e5dd7070Spatrick     break;
571e5dd7070Spatrick   }
572e5dd7070Spatrick 
573e5dd7070Spatrick   case tok::annot_non_type_dependent: {
574e5dd7070Spatrick     IdentifierInfo *II = getIdentifierAnnotation(Tok);
575e5dd7070Spatrick     SourceLocation Loc = ConsumeAnnotationToken();
576e5dd7070Spatrick 
577e5dd7070Spatrick     // This is only the direct operand of an & operator if it is not
578e5dd7070Spatrick     // followed by a postfix-expression suffix.
579e5dd7070Spatrick     if (isAddressOfOperand && isPostfixExpressionSuffixStart())
580e5dd7070Spatrick       isAddressOfOperand = false;
581e5dd7070Spatrick 
582e5dd7070Spatrick     E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc,
583e5dd7070Spatrick                                                       isAddressOfOperand);
584e5dd7070Spatrick     break;
585e5dd7070Spatrick   }
586e5dd7070Spatrick 
587e5dd7070Spatrick   case tok::annot_non_type_undeclared: {
588e5dd7070Spatrick     assert(SS.isEmpty() &&
589e5dd7070Spatrick            "undeclared non-type annotation should be unqualified");
590e5dd7070Spatrick     IdentifierInfo *II = getIdentifierAnnotation(Tok);
591e5dd7070Spatrick     SourceLocation Loc = ConsumeAnnotationToken();
592e5dd7070Spatrick     E = Actions.ActOnNameClassifiedAsUndeclaredNonType(II, Loc);
593e5dd7070Spatrick     break;
594e5dd7070Spatrick   }
595e5dd7070Spatrick 
596e5dd7070Spatrick   default:
597e5dd7070Spatrick     SourceLocation TemplateKWLoc;
598e5dd7070Spatrick     UnqualifiedId Name;
599ec727ea7Spatrick     if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
600ec727ea7Spatrick                            /*ObjectHadErrors=*/false,
601e5dd7070Spatrick                            /*EnteringContext=*/false,
602e5dd7070Spatrick                            /*AllowDestructorName=*/false,
603e5dd7070Spatrick                            /*AllowConstructorName=*/false,
604ec727ea7Spatrick                            /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name))
605e5dd7070Spatrick       return ExprError();
606e5dd7070Spatrick 
607e5dd7070Spatrick     // This is only the direct operand of an & operator if it is not
608e5dd7070Spatrick     // followed by a postfix-expression suffix.
609e5dd7070Spatrick     if (isAddressOfOperand && isPostfixExpressionSuffixStart())
610e5dd7070Spatrick       isAddressOfOperand = false;
611e5dd7070Spatrick 
612e5dd7070Spatrick     E = Actions.ActOnIdExpression(
613e5dd7070Spatrick         getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
614e5dd7070Spatrick         isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
615e5dd7070Spatrick         &Replacement);
616e5dd7070Spatrick     break;
617e5dd7070Spatrick   }
618e5dd7070Spatrick 
619e5dd7070Spatrick   if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
620e5dd7070Spatrick     checkPotentialAngleBracket(E);
621e5dd7070Spatrick   return E;
622e5dd7070Spatrick }
623e5dd7070Spatrick 
624e5dd7070Spatrick /// ParseCXXIdExpression - Handle id-expression.
625e5dd7070Spatrick ///
626e5dd7070Spatrick ///       id-expression:
627e5dd7070Spatrick ///         unqualified-id
628e5dd7070Spatrick ///         qualified-id
629e5dd7070Spatrick ///
630e5dd7070Spatrick ///       qualified-id:
631e5dd7070Spatrick ///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
632e5dd7070Spatrick ///         '::' identifier
633e5dd7070Spatrick ///         '::' operator-function-id
634e5dd7070Spatrick ///         '::' template-id
635e5dd7070Spatrick ///
636e5dd7070Spatrick /// NOTE: The standard specifies that, for qualified-id, the parser does not
637e5dd7070Spatrick /// expect:
638e5dd7070Spatrick ///
639e5dd7070Spatrick ///   '::' conversion-function-id
640e5dd7070Spatrick ///   '::' '~' class-name
641e5dd7070Spatrick ///
642e5dd7070Spatrick /// This may cause a slight inconsistency on diagnostics:
643e5dd7070Spatrick ///
644e5dd7070Spatrick /// class C {};
645e5dd7070Spatrick /// namespace A {}
646e5dd7070Spatrick /// void f() {
647e5dd7070Spatrick ///   :: A :: ~ C(); // Some Sema error about using destructor with a
648e5dd7070Spatrick ///                  // namespace.
649e5dd7070Spatrick ///   :: ~ C(); // Some Parser error like 'unexpected ~'.
650e5dd7070Spatrick /// }
651e5dd7070Spatrick ///
652e5dd7070Spatrick /// We simplify the parser a bit and make it work like:
653e5dd7070Spatrick ///
654e5dd7070Spatrick ///       qualified-id:
655e5dd7070Spatrick ///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
656e5dd7070Spatrick ///         '::' unqualified-id
657e5dd7070Spatrick ///
658e5dd7070Spatrick /// That way Sema can handle and report similar errors for namespaces and the
659e5dd7070Spatrick /// global scope.
660e5dd7070Spatrick ///
661e5dd7070Spatrick /// The isAddressOfOperand parameter indicates that this id-expression is a
662e5dd7070Spatrick /// direct operand of the address-of operator. This is, besides member contexts,
663e5dd7070Spatrick /// the only place where a qualified-id naming a non-static class member may
664e5dd7070Spatrick /// appear.
665e5dd7070Spatrick ///
ParseCXXIdExpression(bool isAddressOfOperand)666e5dd7070Spatrick ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
667e5dd7070Spatrick   // qualified-id:
668e5dd7070Spatrick   //   '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
669e5dd7070Spatrick   //   '::' unqualified-id
670e5dd7070Spatrick   //
671e5dd7070Spatrick   CXXScopeSpec SS;
672ec727ea7Spatrick   ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
673*12c85518Srobert                                  /*ObjectHasErrors=*/false,
674ec727ea7Spatrick                                  /*EnteringContext=*/false);
675e5dd7070Spatrick 
676e5dd7070Spatrick   Token Replacement;
677e5dd7070Spatrick   ExprResult Result =
678e5dd7070Spatrick       tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
679e5dd7070Spatrick   if (Result.isUnset()) {
680e5dd7070Spatrick     // If the ExprResult is valid but null, then typo correction suggested a
681e5dd7070Spatrick     // keyword replacement that needs to be reparsed.
682e5dd7070Spatrick     UnconsumeToken(Replacement);
683e5dd7070Spatrick     Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
684e5dd7070Spatrick   }
685e5dd7070Spatrick   assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
686e5dd7070Spatrick                               "for a previous keyword suggestion");
687e5dd7070Spatrick   return Result;
688e5dd7070Spatrick }
689e5dd7070Spatrick 
690e5dd7070Spatrick /// ParseLambdaExpression - Parse a C++11 lambda expression.
691e5dd7070Spatrick ///
692e5dd7070Spatrick ///       lambda-expression:
693a9ac8606Spatrick ///         lambda-introducer lambda-declarator compound-statement
694e5dd7070Spatrick ///         lambda-introducer '<' template-parameter-list '>'
695a9ac8606Spatrick ///             requires-clause[opt] lambda-declarator compound-statement
696e5dd7070Spatrick ///
697e5dd7070Spatrick ///       lambda-introducer:
698e5dd7070Spatrick ///         '[' lambda-capture[opt] ']'
699e5dd7070Spatrick ///
700e5dd7070Spatrick ///       lambda-capture:
701e5dd7070Spatrick ///         capture-default
702e5dd7070Spatrick ///         capture-list
703e5dd7070Spatrick ///         capture-default ',' capture-list
704e5dd7070Spatrick ///
705e5dd7070Spatrick ///       capture-default:
706e5dd7070Spatrick ///         '&'
707e5dd7070Spatrick ///         '='
708e5dd7070Spatrick ///
709e5dd7070Spatrick ///       capture-list:
710e5dd7070Spatrick ///         capture
711e5dd7070Spatrick ///         capture-list ',' capture
712e5dd7070Spatrick ///
713e5dd7070Spatrick ///       capture:
714e5dd7070Spatrick ///         simple-capture
715e5dd7070Spatrick ///         init-capture     [C++1y]
716e5dd7070Spatrick ///
717e5dd7070Spatrick ///       simple-capture:
718e5dd7070Spatrick ///         identifier
719e5dd7070Spatrick ///         '&' identifier
720e5dd7070Spatrick ///         'this'
721e5dd7070Spatrick ///
722e5dd7070Spatrick ///       init-capture:      [C++1y]
723e5dd7070Spatrick ///         identifier initializer
724e5dd7070Spatrick ///         '&' identifier initializer
725e5dd7070Spatrick ///
726e5dd7070Spatrick ///       lambda-declarator:
727a9ac8606Spatrick ///         lambda-specifiers     [C++2b]
728a9ac8606Spatrick ///         '(' parameter-declaration-clause ')' lambda-specifiers
729a9ac8606Spatrick ///             requires-clause[opt]
730a9ac8606Spatrick ///
731a9ac8606Spatrick ///       lambda-specifiers:
732a9ac8606Spatrick ///         decl-specifier-seq[opt] noexcept-specifier[opt]
733a9ac8606Spatrick ///             attribute-specifier-seq[opt] trailing-return-type[opt]
734e5dd7070Spatrick ///
ParseLambdaExpression()735e5dd7070Spatrick ExprResult Parser::ParseLambdaExpression() {
736e5dd7070Spatrick   // Parse lambda-introducer.
737e5dd7070Spatrick   LambdaIntroducer Intro;
738e5dd7070Spatrick   if (ParseLambdaIntroducer(Intro)) {
739e5dd7070Spatrick     SkipUntil(tok::r_square, StopAtSemi);
740e5dd7070Spatrick     SkipUntil(tok::l_brace, StopAtSemi);
741e5dd7070Spatrick     SkipUntil(tok::r_brace, StopAtSemi);
742e5dd7070Spatrick     return ExprError();
743e5dd7070Spatrick   }
744e5dd7070Spatrick 
745e5dd7070Spatrick   return ParseLambdaExpressionAfterIntroducer(Intro);
746e5dd7070Spatrick }
747e5dd7070Spatrick 
748e5dd7070Spatrick /// Use lookahead and potentially tentative parsing to determine if we are
749e5dd7070Spatrick /// looking at a C++11 lambda expression, and parse it if we are.
750e5dd7070Spatrick ///
751e5dd7070Spatrick /// If we are not looking at a lambda expression, returns ExprError().
TryParseLambdaExpression()752e5dd7070Spatrick ExprResult Parser::TryParseLambdaExpression() {
753e5dd7070Spatrick   assert(getLangOpts().CPlusPlus11
754e5dd7070Spatrick          && Tok.is(tok::l_square)
755e5dd7070Spatrick          && "Not at the start of a possible lambda expression.");
756e5dd7070Spatrick 
757e5dd7070Spatrick   const Token Next = NextToken();
758e5dd7070Spatrick   if (Next.is(tok::eof)) // Nothing else to lookup here...
759e5dd7070Spatrick     return ExprEmpty();
760e5dd7070Spatrick 
761e5dd7070Spatrick   const Token After = GetLookAheadToken(2);
762e5dd7070Spatrick   // If lookahead indicates this is a lambda...
763e5dd7070Spatrick   if (Next.is(tok::r_square) ||     // []
764e5dd7070Spatrick       Next.is(tok::equal) ||        // [=
765e5dd7070Spatrick       (Next.is(tok::amp) &&         // [&] or [&,
766e5dd7070Spatrick        After.isOneOf(tok::r_square, tok::comma)) ||
767e5dd7070Spatrick       (Next.is(tok::identifier) &&  // [identifier]
768e5dd7070Spatrick        After.is(tok::r_square)) ||
769e5dd7070Spatrick       Next.is(tok::ellipsis)) {     // [...
770e5dd7070Spatrick     return ParseLambdaExpression();
771e5dd7070Spatrick   }
772e5dd7070Spatrick 
773e5dd7070Spatrick   // If lookahead indicates an ObjC message send...
774e5dd7070Spatrick   // [identifier identifier
775e5dd7070Spatrick   if (Next.is(tok::identifier) && After.is(tok::identifier))
776e5dd7070Spatrick     return ExprEmpty();
777e5dd7070Spatrick 
778e5dd7070Spatrick   // Here, we're stuck: lambda introducers and Objective-C message sends are
779e5dd7070Spatrick   // unambiguous, but it requires arbitrary lookhead.  [a,b,c,d,e,f,g] is a
780e5dd7070Spatrick   // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send.  Instead of
781e5dd7070Spatrick   // writing two routines to parse a lambda introducer, just try to parse
782e5dd7070Spatrick   // a lambda introducer first, and fall back if that fails.
783e5dd7070Spatrick   LambdaIntroducer Intro;
784e5dd7070Spatrick   {
785e5dd7070Spatrick     TentativeParsingAction TPA(*this);
786e5dd7070Spatrick     LambdaIntroducerTentativeParse Tentative;
787e5dd7070Spatrick     if (ParseLambdaIntroducer(Intro, &Tentative)) {
788e5dd7070Spatrick       TPA.Commit();
789e5dd7070Spatrick       return ExprError();
790e5dd7070Spatrick     }
791e5dd7070Spatrick 
792e5dd7070Spatrick     switch (Tentative) {
793e5dd7070Spatrick     case LambdaIntroducerTentativeParse::Success:
794e5dd7070Spatrick       TPA.Commit();
795e5dd7070Spatrick       break;
796e5dd7070Spatrick 
797e5dd7070Spatrick     case LambdaIntroducerTentativeParse::Incomplete:
798e5dd7070Spatrick       // Didn't fully parse the lambda-introducer, try again with a
799e5dd7070Spatrick       // non-tentative parse.
800e5dd7070Spatrick       TPA.Revert();
801e5dd7070Spatrick       Intro = LambdaIntroducer();
802e5dd7070Spatrick       if (ParseLambdaIntroducer(Intro))
803e5dd7070Spatrick         return ExprError();
804e5dd7070Spatrick       break;
805e5dd7070Spatrick 
806e5dd7070Spatrick     case LambdaIntroducerTentativeParse::MessageSend:
807e5dd7070Spatrick     case LambdaIntroducerTentativeParse::Invalid:
808e5dd7070Spatrick       // Not a lambda-introducer, might be a message send.
809e5dd7070Spatrick       TPA.Revert();
810e5dd7070Spatrick       return ExprEmpty();
811e5dd7070Spatrick     }
812e5dd7070Spatrick   }
813e5dd7070Spatrick 
814e5dd7070Spatrick   return ParseLambdaExpressionAfterIntroducer(Intro);
815e5dd7070Spatrick }
816e5dd7070Spatrick 
817e5dd7070Spatrick /// Parse a lambda introducer.
818e5dd7070Spatrick /// \param Intro A LambdaIntroducer filled in with information about the
819e5dd7070Spatrick ///        contents of the lambda-introducer.
820e5dd7070Spatrick /// \param Tentative If non-null, we are disambiguating between a
821e5dd7070Spatrick ///        lambda-introducer and some other construct. In this mode, we do not
822e5dd7070Spatrick ///        produce any diagnostics or take any other irreversible action unless
823e5dd7070Spatrick ///        we're sure that this is a lambda-expression.
824e5dd7070Spatrick /// \return \c true if parsing (or disambiguation) failed with a diagnostic and
825e5dd7070Spatrick ///         the caller should bail out / recover.
ParseLambdaIntroducer(LambdaIntroducer & Intro,LambdaIntroducerTentativeParse * Tentative)826e5dd7070Spatrick bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
827e5dd7070Spatrick                                    LambdaIntroducerTentativeParse *Tentative) {
828e5dd7070Spatrick   if (Tentative)
829e5dd7070Spatrick     *Tentative = LambdaIntroducerTentativeParse::Success;
830e5dd7070Spatrick 
831e5dd7070Spatrick   assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
832e5dd7070Spatrick   BalancedDelimiterTracker T(*this, tok::l_square);
833e5dd7070Spatrick   T.consumeOpen();
834e5dd7070Spatrick 
835e5dd7070Spatrick   Intro.Range.setBegin(T.getOpenLocation());
836e5dd7070Spatrick 
837e5dd7070Spatrick   bool First = true;
838e5dd7070Spatrick 
839e5dd7070Spatrick   // Produce a diagnostic if we're not tentatively parsing; otherwise track
840e5dd7070Spatrick   // that our parse has failed.
841e5dd7070Spatrick   auto Invalid = [&](llvm::function_ref<void()> Action) {
842e5dd7070Spatrick     if (Tentative) {
843e5dd7070Spatrick       *Tentative = LambdaIntroducerTentativeParse::Invalid;
844e5dd7070Spatrick       return false;
845e5dd7070Spatrick     }
846e5dd7070Spatrick     Action();
847e5dd7070Spatrick     return true;
848e5dd7070Spatrick   };
849e5dd7070Spatrick 
850e5dd7070Spatrick   // Perform some irreversible action if this is a non-tentative parse;
851e5dd7070Spatrick   // otherwise note that our actions were incomplete.
852e5dd7070Spatrick   auto NonTentativeAction = [&](llvm::function_ref<void()> Action) {
853e5dd7070Spatrick     if (Tentative)
854e5dd7070Spatrick       *Tentative = LambdaIntroducerTentativeParse::Incomplete;
855e5dd7070Spatrick     else
856e5dd7070Spatrick       Action();
857e5dd7070Spatrick   };
858e5dd7070Spatrick 
859e5dd7070Spatrick   // Parse capture-default.
860e5dd7070Spatrick   if (Tok.is(tok::amp) &&
861e5dd7070Spatrick       (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
862e5dd7070Spatrick     Intro.Default = LCD_ByRef;
863e5dd7070Spatrick     Intro.DefaultLoc = ConsumeToken();
864e5dd7070Spatrick     First = false;
865e5dd7070Spatrick     if (!Tok.getIdentifierInfo()) {
866e5dd7070Spatrick       // This can only be a lambda; no need for tentative parsing any more.
867e5dd7070Spatrick       // '[[and]]' can still be an attribute, though.
868e5dd7070Spatrick       Tentative = nullptr;
869e5dd7070Spatrick     }
870e5dd7070Spatrick   } else if (Tok.is(tok::equal)) {
871e5dd7070Spatrick     Intro.Default = LCD_ByCopy;
872e5dd7070Spatrick     Intro.DefaultLoc = ConsumeToken();
873e5dd7070Spatrick     First = false;
874e5dd7070Spatrick     Tentative = nullptr;
875e5dd7070Spatrick   }
876e5dd7070Spatrick 
877e5dd7070Spatrick   while (Tok.isNot(tok::r_square)) {
878e5dd7070Spatrick     if (!First) {
879e5dd7070Spatrick       if (Tok.isNot(tok::comma)) {
880e5dd7070Spatrick         // Provide a completion for a lambda introducer here. Except
881e5dd7070Spatrick         // in Objective-C, where this is Almost Surely meant to be a message
882e5dd7070Spatrick         // send. In that case, fail here and let the ObjC message
883e5dd7070Spatrick         // expression parser perform the completion.
884e5dd7070Spatrick         if (Tok.is(tok::code_completion) &&
885e5dd7070Spatrick             !(getLangOpts().ObjC && Tentative)) {
886a9ac8606Spatrick           cutOffParsing();
887e5dd7070Spatrick           Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
888e5dd7070Spatrick                                                /*AfterAmpersand=*/false);
889e5dd7070Spatrick           break;
890e5dd7070Spatrick         }
891e5dd7070Spatrick 
892e5dd7070Spatrick         return Invalid([&] {
893e5dd7070Spatrick           Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare);
894e5dd7070Spatrick         });
895e5dd7070Spatrick       }
896e5dd7070Spatrick       ConsumeToken();
897e5dd7070Spatrick     }
898e5dd7070Spatrick 
899e5dd7070Spatrick     if (Tok.is(tok::code_completion)) {
900a9ac8606Spatrick       cutOffParsing();
901e5dd7070Spatrick       // If we're in Objective-C++ and we have a bare '[', then this is more
902e5dd7070Spatrick       // likely to be a message receiver.
903e5dd7070Spatrick       if (getLangOpts().ObjC && Tentative && First)
904e5dd7070Spatrick         Actions.CodeCompleteObjCMessageReceiver(getCurScope());
905e5dd7070Spatrick       else
906e5dd7070Spatrick         Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
907e5dd7070Spatrick                                              /*AfterAmpersand=*/false);
908e5dd7070Spatrick       break;
909e5dd7070Spatrick     }
910e5dd7070Spatrick 
911e5dd7070Spatrick     First = false;
912e5dd7070Spatrick 
913e5dd7070Spatrick     // Parse capture.
914e5dd7070Spatrick     LambdaCaptureKind Kind = LCK_ByCopy;
915e5dd7070Spatrick     LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
916e5dd7070Spatrick     SourceLocation Loc;
917e5dd7070Spatrick     IdentifierInfo *Id = nullptr;
918e5dd7070Spatrick     SourceLocation EllipsisLocs[4];
919e5dd7070Spatrick     ExprResult Init;
920e5dd7070Spatrick     SourceLocation LocStart = Tok.getLocation();
921e5dd7070Spatrick 
922e5dd7070Spatrick     if (Tok.is(tok::star)) {
923e5dd7070Spatrick       Loc = ConsumeToken();
924e5dd7070Spatrick       if (Tok.is(tok::kw_this)) {
925e5dd7070Spatrick         ConsumeToken();
926e5dd7070Spatrick         Kind = LCK_StarThis;
927e5dd7070Spatrick       } else {
928e5dd7070Spatrick         return Invalid([&] {
929e5dd7070Spatrick           Diag(Tok.getLocation(), diag::err_expected_star_this_capture);
930e5dd7070Spatrick         });
931e5dd7070Spatrick       }
932e5dd7070Spatrick     } else if (Tok.is(tok::kw_this)) {
933e5dd7070Spatrick       Kind = LCK_This;
934e5dd7070Spatrick       Loc = ConsumeToken();
935a9ac8606Spatrick     } else if (Tok.isOneOf(tok::amp, tok::equal) &&
936a9ac8606Spatrick                NextToken().isOneOf(tok::comma, tok::r_square) &&
937a9ac8606Spatrick                Intro.Default == LCD_None) {
938a9ac8606Spatrick       // We have a lone "&" or "=" which is either a misplaced capture-default
939a9ac8606Spatrick       // or the start of a capture (in the "&" case) with the rest of the
940a9ac8606Spatrick       // capture missing. Both are an error but a misplaced capture-default
941a9ac8606Spatrick       // is more likely if we don't already have a capture default.
942a9ac8606Spatrick       return Invalid(
943a9ac8606Spatrick           [&] { Diag(Tok.getLocation(), diag::err_capture_default_first); });
944e5dd7070Spatrick     } else {
945e5dd7070Spatrick       TryConsumeToken(tok::ellipsis, EllipsisLocs[0]);
946e5dd7070Spatrick 
947e5dd7070Spatrick       if (Tok.is(tok::amp)) {
948e5dd7070Spatrick         Kind = LCK_ByRef;
949e5dd7070Spatrick         ConsumeToken();
950e5dd7070Spatrick 
951e5dd7070Spatrick         if (Tok.is(tok::code_completion)) {
952a9ac8606Spatrick           cutOffParsing();
953e5dd7070Spatrick           Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
954e5dd7070Spatrick                                                /*AfterAmpersand=*/true);
955e5dd7070Spatrick           break;
956e5dd7070Spatrick         }
957e5dd7070Spatrick       }
958e5dd7070Spatrick 
959e5dd7070Spatrick       TryConsumeToken(tok::ellipsis, EllipsisLocs[1]);
960e5dd7070Spatrick 
961e5dd7070Spatrick       if (Tok.is(tok::identifier)) {
962e5dd7070Spatrick         Id = Tok.getIdentifierInfo();
963e5dd7070Spatrick         Loc = ConsumeToken();
964e5dd7070Spatrick       } else if (Tok.is(tok::kw_this)) {
965e5dd7070Spatrick         return Invalid([&] {
966e5dd7070Spatrick           // FIXME: Suggest a fixit here.
967e5dd7070Spatrick           Diag(Tok.getLocation(), diag::err_this_captured_by_reference);
968e5dd7070Spatrick         });
969e5dd7070Spatrick       } else {
970e5dd7070Spatrick         return Invalid([&] {
971e5dd7070Spatrick           Diag(Tok.getLocation(), diag::err_expected_capture);
972e5dd7070Spatrick         });
973e5dd7070Spatrick       }
974e5dd7070Spatrick 
975e5dd7070Spatrick       TryConsumeToken(tok::ellipsis, EllipsisLocs[2]);
976e5dd7070Spatrick 
977e5dd7070Spatrick       if (Tok.is(tok::l_paren)) {
978e5dd7070Spatrick         BalancedDelimiterTracker Parens(*this, tok::l_paren);
979e5dd7070Spatrick         Parens.consumeOpen();
980e5dd7070Spatrick 
981e5dd7070Spatrick         InitKind = LambdaCaptureInitKind::DirectInit;
982e5dd7070Spatrick 
983e5dd7070Spatrick         ExprVector Exprs;
984e5dd7070Spatrick         if (Tentative) {
985e5dd7070Spatrick           Parens.skipToEnd();
986e5dd7070Spatrick           *Tentative = LambdaIntroducerTentativeParse::Incomplete;
987*12c85518Srobert         } else if (ParseExpressionList(Exprs)) {
988e5dd7070Spatrick           Parens.skipToEnd();
989e5dd7070Spatrick           Init = ExprError();
990e5dd7070Spatrick         } else {
991e5dd7070Spatrick           Parens.consumeClose();
992e5dd7070Spatrick           Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
993e5dd7070Spatrick                                             Parens.getCloseLocation(),
994e5dd7070Spatrick                                             Exprs);
995e5dd7070Spatrick         }
996e5dd7070Spatrick       } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
997e5dd7070Spatrick         // Each lambda init-capture forms its own full expression, which clears
998e5dd7070Spatrick         // Actions.MaybeODRUseExprs. So create an expression evaluation context
999e5dd7070Spatrick         // to save the necessary state, and restore it later.
1000e5dd7070Spatrick         EnterExpressionEvaluationContext EC(
1001e5dd7070Spatrick             Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1002e5dd7070Spatrick 
1003e5dd7070Spatrick         if (TryConsumeToken(tok::equal))
1004e5dd7070Spatrick           InitKind = LambdaCaptureInitKind::CopyInit;
1005e5dd7070Spatrick         else
1006e5dd7070Spatrick           InitKind = LambdaCaptureInitKind::ListInit;
1007e5dd7070Spatrick 
1008e5dd7070Spatrick         if (!Tentative) {
1009e5dd7070Spatrick           Init = ParseInitializer();
1010e5dd7070Spatrick         } else if (Tok.is(tok::l_brace)) {
1011e5dd7070Spatrick           BalancedDelimiterTracker Braces(*this, tok::l_brace);
1012e5dd7070Spatrick           Braces.consumeOpen();
1013e5dd7070Spatrick           Braces.skipToEnd();
1014e5dd7070Spatrick           *Tentative = LambdaIntroducerTentativeParse::Incomplete;
1015e5dd7070Spatrick         } else {
1016e5dd7070Spatrick           // We're disambiguating this:
1017e5dd7070Spatrick           //
1018e5dd7070Spatrick           //   [..., x = expr
1019e5dd7070Spatrick           //
1020e5dd7070Spatrick           // We need to find the end of the following expression in order to
1021e5dd7070Spatrick           // determine whether this is an Obj-C message send's receiver, a
1022e5dd7070Spatrick           // C99 designator, or a lambda init-capture.
1023e5dd7070Spatrick           //
1024e5dd7070Spatrick           // Parse the expression to find where it ends, and annotate it back
1025e5dd7070Spatrick           // onto the tokens. We would have parsed this expression the same way
1026e5dd7070Spatrick           // in either case: both the RHS of an init-capture and the RHS of an
1027e5dd7070Spatrick           // assignment expression are parsed as an initializer-clause, and in
1028e5dd7070Spatrick           // neither case can anything be added to the scope between the '[' and
1029e5dd7070Spatrick           // here.
1030e5dd7070Spatrick           //
1031e5dd7070Spatrick           // FIXME: This is horrible. Adding a mechanism to skip an expression
1032e5dd7070Spatrick           // would be much cleaner.
1033e5dd7070Spatrick           // FIXME: If there is a ',' before the next ']' or ':', we can skip to
1034e5dd7070Spatrick           // that instead. (And if we see a ':' with no matching '?', we can
1035e5dd7070Spatrick           // classify this as an Obj-C message send.)
1036e5dd7070Spatrick           SourceLocation StartLoc = Tok.getLocation();
1037e5dd7070Spatrick           InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
1038e5dd7070Spatrick           Init = ParseInitializer();
1039e5dd7070Spatrick           if (!Init.isInvalid())
1040e5dd7070Spatrick             Init = Actions.CorrectDelayedTyposInExpr(Init.get());
1041e5dd7070Spatrick 
1042e5dd7070Spatrick           if (Tok.getLocation() != StartLoc) {
1043e5dd7070Spatrick             // Back out the lexing of the token after the initializer.
1044e5dd7070Spatrick             PP.RevertCachedTokens(1);
1045e5dd7070Spatrick 
1046e5dd7070Spatrick             // Replace the consumed tokens with an appropriate annotation.
1047e5dd7070Spatrick             Tok.setLocation(StartLoc);
1048e5dd7070Spatrick             Tok.setKind(tok::annot_primary_expr);
1049e5dd7070Spatrick             setExprAnnotation(Tok, Init);
1050e5dd7070Spatrick             Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
1051e5dd7070Spatrick             PP.AnnotateCachedTokens(Tok);
1052e5dd7070Spatrick 
1053e5dd7070Spatrick             // Consume the annotated initializer.
1054e5dd7070Spatrick             ConsumeAnnotationToken();
1055e5dd7070Spatrick           }
1056e5dd7070Spatrick         }
1057e5dd7070Spatrick       }
1058e5dd7070Spatrick 
1059e5dd7070Spatrick       TryConsumeToken(tok::ellipsis, EllipsisLocs[3]);
1060e5dd7070Spatrick     }
1061e5dd7070Spatrick 
1062e5dd7070Spatrick     // Check if this is a message send before we act on a possible init-capture.
1063e5dd7070Spatrick     if (Tentative && Tok.is(tok::identifier) &&
1064e5dd7070Spatrick         NextToken().isOneOf(tok::colon, tok::r_square)) {
1065e5dd7070Spatrick       // This can only be a message send. We're done with disambiguation.
1066e5dd7070Spatrick       *Tentative = LambdaIntroducerTentativeParse::MessageSend;
1067e5dd7070Spatrick       return false;
1068e5dd7070Spatrick     }
1069e5dd7070Spatrick 
1070e5dd7070Spatrick     // Ensure that any ellipsis was in the right place.
1071e5dd7070Spatrick     SourceLocation EllipsisLoc;
1072*12c85518Srobert     if (llvm::any_of(EllipsisLocs,
1073e5dd7070Spatrick                      [](SourceLocation Loc) { return Loc.isValid(); })) {
1074e5dd7070Spatrick       // The '...' should appear before the identifier in an init-capture, and
1075e5dd7070Spatrick       // after the identifier otherwise.
1076e5dd7070Spatrick       bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit;
1077e5dd7070Spatrick       SourceLocation *ExpectedEllipsisLoc =
1078e5dd7070Spatrick           !InitCapture      ? &EllipsisLocs[2] :
1079e5dd7070Spatrick           Kind == LCK_ByRef ? &EllipsisLocs[1] :
1080e5dd7070Spatrick                               &EllipsisLocs[0];
1081e5dd7070Spatrick       EllipsisLoc = *ExpectedEllipsisLoc;
1082e5dd7070Spatrick 
1083e5dd7070Spatrick       unsigned DiagID = 0;
1084e5dd7070Spatrick       if (EllipsisLoc.isInvalid()) {
1085e5dd7070Spatrick         DiagID = diag::err_lambda_capture_misplaced_ellipsis;
1086e5dd7070Spatrick         for (SourceLocation Loc : EllipsisLocs) {
1087e5dd7070Spatrick           if (Loc.isValid())
1088e5dd7070Spatrick             EllipsisLoc = Loc;
1089e5dd7070Spatrick         }
1090e5dd7070Spatrick       } else {
1091e5dd7070Spatrick         unsigned NumEllipses = std::accumulate(
1092e5dd7070Spatrick             std::begin(EllipsisLocs), std::end(EllipsisLocs), 0,
1093e5dd7070Spatrick             [](int N, SourceLocation Loc) { return N + Loc.isValid(); });
1094e5dd7070Spatrick         if (NumEllipses > 1)
1095e5dd7070Spatrick           DiagID = diag::err_lambda_capture_multiple_ellipses;
1096e5dd7070Spatrick       }
1097e5dd7070Spatrick       if (DiagID) {
1098e5dd7070Spatrick         NonTentativeAction([&] {
1099e5dd7070Spatrick           // Point the diagnostic at the first misplaced ellipsis.
1100e5dd7070Spatrick           SourceLocation DiagLoc;
1101e5dd7070Spatrick           for (SourceLocation &Loc : EllipsisLocs) {
1102e5dd7070Spatrick             if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) {
1103e5dd7070Spatrick               DiagLoc = Loc;
1104e5dd7070Spatrick               break;
1105e5dd7070Spatrick             }
1106e5dd7070Spatrick           }
1107e5dd7070Spatrick           assert(DiagLoc.isValid() && "no location for diagnostic");
1108e5dd7070Spatrick 
1109e5dd7070Spatrick           // Issue the diagnostic and produce fixits showing where the ellipsis
1110e5dd7070Spatrick           // should have been written.
1111e5dd7070Spatrick           auto &&D = Diag(DiagLoc, DiagID);
1112e5dd7070Spatrick           if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) {
1113e5dd7070Spatrick             SourceLocation ExpectedLoc =
1114e5dd7070Spatrick                 InitCapture ? Loc
1115e5dd7070Spatrick                             : Lexer::getLocForEndOfToken(
1116e5dd7070Spatrick                                   Loc, 0, PP.getSourceManager(), getLangOpts());
1117e5dd7070Spatrick             D << InitCapture << FixItHint::CreateInsertion(ExpectedLoc, "...");
1118e5dd7070Spatrick           }
1119e5dd7070Spatrick           for (SourceLocation &Loc : EllipsisLocs) {
1120e5dd7070Spatrick             if (&Loc != ExpectedEllipsisLoc && Loc.isValid())
1121e5dd7070Spatrick               D << FixItHint::CreateRemoval(Loc);
1122e5dd7070Spatrick           }
1123e5dd7070Spatrick         });
1124e5dd7070Spatrick       }
1125e5dd7070Spatrick     }
1126e5dd7070Spatrick 
1127e5dd7070Spatrick     // Process the init-capture initializers now rather than delaying until we
1128e5dd7070Spatrick     // form the lambda-expression so that they can be handled in the context
1129e5dd7070Spatrick     // enclosing the lambda-expression, rather than in the context of the
1130e5dd7070Spatrick     // lambda-expression itself.
1131e5dd7070Spatrick     ParsedType InitCaptureType;
1132e5dd7070Spatrick     if (Init.isUsable())
1133e5dd7070Spatrick       Init = Actions.CorrectDelayedTyposInExpr(Init.get());
1134e5dd7070Spatrick     if (Init.isUsable()) {
1135e5dd7070Spatrick       NonTentativeAction([&] {
1136e5dd7070Spatrick         // Get the pointer and store it in an lvalue, so we can use it as an
1137e5dd7070Spatrick         // out argument.
1138e5dd7070Spatrick         Expr *InitExpr = Init.get();
1139e5dd7070Spatrick         // This performs any lvalue-to-rvalue conversions if necessary, which
1140e5dd7070Spatrick         // can affect what gets captured in the containing decl-context.
1141e5dd7070Spatrick         InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
1142e5dd7070Spatrick             Loc, Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, InitExpr);
1143e5dd7070Spatrick         Init = InitExpr;
1144e5dd7070Spatrick       });
1145e5dd7070Spatrick     }
1146e5dd7070Spatrick 
1147e5dd7070Spatrick     SourceLocation LocEnd = PrevTokLocation;
1148e5dd7070Spatrick 
1149e5dd7070Spatrick     Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
1150e5dd7070Spatrick                      InitCaptureType, SourceRange(LocStart, LocEnd));
1151e5dd7070Spatrick   }
1152e5dd7070Spatrick 
1153e5dd7070Spatrick   T.consumeClose();
1154e5dd7070Spatrick   Intro.Range.setEnd(T.getCloseLocation());
1155e5dd7070Spatrick   return false;
1156e5dd7070Spatrick }
1157e5dd7070Spatrick 
tryConsumeLambdaSpecifierToken(Parser & P,SourceLocation & MutableLoc,SourceLocation & StaticLoc,SourceLocation & ConstexprLoc,SourceLocation & ConstevalLoc,SourceLocation & DeclEndLoc)1158e5dd7070Spatrick static void tryConsumeLambdaSpecifierToken(Parser &P,
1159e5dd7070Spatrick                                            SourceLocation &MutableLoc,
1160*12c85518Srobert                                            SourceLocation &StaticLoc,
1161e5dd7070Spatrick                                            SourceLocation &ConstexprLoc,
1162e5dd7070Spatrick                                            SourceLocation &ConstevalLoc,
1163e5dd7070Spatrick                                            SourceLocation &DeclEndLoc) {
1164e5dd7070Spatrick   assert(MutableLoc.isInvalid());
1165*12c85518Srobert   assert(StaticLoc.isInvalid());
1166e5dd7070Spatrick   assert(ConstexprLoc.isInvalid());
1167*12c85518Srobert   assert(ConstevalLoc.isInvalid());
1168e5dd7070Spatrick   // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1169e5dd7070Spatrick   // to the final of those locations. Emit an error if we have multiple
1170e5dd7070Spatrick   // copies of those keywords and recover.
1171e5dd7070Spatrick 
1172*12c85518Srobert   auto ConsumeLocation = [&P, &DeclEndLoc](SourceLocation &SpecifierLoc,
1173*12c85518Srobert                                            int DiagIndex) {
1174*12c85518Srobert     if (SpecifierLoc.isValid()) {
1175*12c85518Srobert       P.Diag(P.getCurToken().getLocation(),
1176*12c85518Srobert              diag::err_lambda_decl_specifier_repeated)
1177*12c85518Srobert           << DiagIndex
1178*12c85518Srobert           << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1179*12c85518Srobert     }
1180*12c85518Srobert     SpecifierLoc = P.ConsumeToken();
1181*12c85518Srobert     DeclEndLoc = SpecifierLoc;
1182*12c85518Srobert   };
1183*12c85518Srobert 
1184e5dd7070Spatrick   while (true) {
1185e5dd7070Spatrick     switch (P.getCurToken().getKind()) {
1186*12c85518Srobert     case tok::kw_mutable:
1187*12c85518Srobert       ConsumeLocation(MutableLoc, 0);
1188*12c85518Srobert       break;
1189*12c85518Srobert     case tok::kw_static:
1190*12c85518Srobert       ConsumeLocation(StaticLoc, 1);
1191*12c85518Srobert       break;
1192e5dd7070Spatrick     case tok::kw_constexpr:
1193*12c85518Srobert       ConsumeLocation(ConstexprLoc, 2);
1194*12c85518Srobert       break;
1195e5dd7070Spatrick     case tok::kw_consteval:
1196*12c85518Srobert       ConsumeLocation(ConstevalLoc, 3);
1197*12c85518Srobert       break;
1198e5dd7070Spatrick     default:
1199e5dd7070Spatrick       return;
1200e5dd7070Spatrick     }
1201e5dd7070Spatrick   }
1202e5dd7070Spatrick }
1203e5dd7070Spatrick 
addStaticToLambdaDeclSpecifier(Parser & P,SourceLocation StaticLoc,DeclSpec & DS)1204*12c85518Srobert static void addStaticToLambdaDeclSpecifier(Parser &P, SourceLocation StaticLoc,
1205*12c85518Srobert                                            DeclSpec &DS) {
1206*12c85518Srobert   if (StaticLoc.isValid()) {
1207*12c85518Srobert     P.Diag(StaticLoc, !P.getLangOpts().CPlusPlus2b
1208*12c85518Srobert                           ? diag::err_static_lambda
1209*12c85518Srobert                           : diag::warn_cxx20_compat_static_lambda);
1210*12c85518Srobert     const char *PrevSpec = nullptr;
1211*12c85518Srobert     unsigned DiagID = 0;
1212*12c85518Srobert     DS.SetStorageClassSpec(P.getActions(), DeclSpec::SCS_static, StaticLoc,
1213*12c85518Srobert                            PrevSpec, DiagID,
1214*12c85518Srobert                            P.getActions().getASTContext().getPrintingPolicy());
1215*12c85518Srobert     assert(PrevSpec == nullptr && DiagID == 0 &&
1216*12c85518Srobert            "Static cannot have been set previously!");
1217*12c85518Srobert   }
1218*12c85518Srobert }
1219*12c85518Srobert 
1220e5dd7070Spatrick static void
addConstexprToLambdaDeclSpecifier(Parser & P,SourceLocation ConstexprLoc,DeclSpec & DS)1221e5dd7070Spatrick addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1222e5dd7070Spatrick                                   DeclSpec &DS) {
1223e5dd7070Spatrick   if (ConstexprLoc.isValid()) {
1224e5dd7070Spatrick     P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1225e5dd7070Spatrick                              ? diag::ext_constexpr_on_lambda_cxx17
1226e5dd7070Spatrick                              : diag::warn_cxx14_compat_constexpr_on_lambda);
1227e5dd7070Spatrick     const char *PrevSpec = nullptr;
1228e5dd7070Spatrick     unsigned DiagID = 0;
1229a9ac8606Spatrick     DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, ConstexprLoc, PrevSpec,
1230a9ac8606Spatrick                         DiagID);
1231e5dd7070Spatrick     assert(PrevSpec == nullptr && DiagID == 0 &&
1232e5dd7070Spatrick            "Constexpr cannot have been set previously!");
1233e5dd7070Spatrick   }
1234e5dd7070Spatrick }
1235e5dd7070Spatrick 
addConstevalToLambdaDeclSpecifier(Parser & P,SourceLocation ConstevalLoc,DeclSpec & DS)1236e5dd7070Spatrick static void addConstevalToLambdaDeclSpecifier(Parser &P,
1237e5dd7070Spatrick                                               SourceLocation ConstevalLoc,
1238e5dd7070Spatrick                                               DeclSpec &DS) {
1239e5dd7070Spatrick   if (ConstevalLoc.isValid()) {
1240e5dd7070Spatrick     P.Diag(ConstevalLoc, diag::warn_cxx20_compat_consteval);
1241e5dd7070Spatrick     const char *PrevSpec = nullptr;
1242e5dd7070Spatrick     unsigned DiagID = 0;
1243a9ac8606Spatrick     DS.SetConstexprSpec(ConstexprSpecKind::Consteval, ConstevalLoc, PrevSpec,
1244a9ac8606Spatrick                         DiagID);
1245e5dd7070Spatrick     if (DiagID != 0)
1246e5dd7070Spatrick       P.Diag(ConstevalLoc, DiagID) << PrevSpec;
1247e5dd7070Spatrick   }
1248e5dd7070Spatrick }
1249e5dd7070Spatrick 
DiagnoseStaticSpecifierRestrictions(Parser & P,SourceLocation StaticLoc,SourceLocation MutableLoc,const LambdaIntroducer & Intro)1250*12c85518Srobert static void DiagnoseStaticSpecifierRestrictions(Parser &P,
1251*12c85518Srobert                                                 SourceLocation StaticLoc,
1252*12c85518Srobert                                                 SourceLocation MutableLoc,
1253*12c85518Srobert                                                 const LambdaIntroducer &Intro) {
1254*12c85518Srobert   if (StaticLoc.isInvalid())
1255*12c85518Srobert     return;
1256*12c85518Srobert 
1257*12c85518Srobert   // [expr.prim.lambda.general] p4
1258*12c85518Srobert   // The lambda-specifier-seq shall not contain both mutable and static.
1259*12c85518Srobert   // If the lambda-specifier-seq contains static, there shall be no
1260*12c85518Srobert   // lambda-capture.
1261*12c85518Srobert   if (MutableLoc.isValid())
1262*12c85518Srobert     P.Diag(StaticLoc, diag::err_static_mutable_lambda);
1263*12c85518Srobert   if (Intro.hasLambdaCapture()) {
1264*12c85518Srobert     P.Diag(StaticLoc, diag::err_static_lambda_captures);
1265*12c85518Srobert   }
1266*12c85518Srobert }
1267*12c85518Srobert 
1268e5dd7070Spatrick /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1269e5dd7070Spatrick /// expression.
ParseLambdaExpressionAfterIntroducer(LambdaIntroducer & Intro)1270e5dd7070Spatrick ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1271e5dd7070Spatrick                      LambdaIntroducer &Intro) {
1272e5dd7070Spatrick   SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1273e5dd7070Spatrick   Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1274e5dd7070Spatrick 
1275e5dd7070Spatrick   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1276e5dd7070Spatrick                                 "lambda expression parsing");
1277e5dd7070Spatrick 
1278e5dd7070Spatrick 
1279e5dd7070Spatrick 
1280e5dd7070Spatrick   // FIXME: Call into Actions to add any init-capture declarations to the
1281e5dd7070Spatrick   // scope while parsing the lambda-declarator and compound-statement.
1282e5dd7070Spatrick 
1283e5dd7070Spatrick   // Parse lambda-declarator[opt].
1284e5dd7070Spatrick   DeclSpec DS(AttrFactory);
1285*12c85518Srobert   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::LambdaExpr);
1286e5dd7070Spatrick   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1287e5dd7070Spatrick   Actions.PushLambdaScope();
1288e5dd7070Spatrick 
1289e5dd7070Spatrick   ParsedAttributes Attr(AttrFactory);
1290e5dd7070Spatrick   if (getLangOpts().CUDA) {
1291e5dd7070Spatrick     // In CUDA code, GNU attributes are allowed to appear immediately after the
1292e5dd7070Spatrick     // "[...]", even if there is no "(...)" before the lambda body.
1293*12c85518Srobert     //
1294*12c85518Srobert     // Note that we support __noinline__ as a keyword in this mode and thus
1295*12c85518Srobert     // it has to be separately handled.
1296*12c85518Srobert     while (true) {
1297*12c85518Srobert       if (Tok.is(tok::kw___noinline__)) {
1298*12c85518Srobert         IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1299*12c85518Srobert         SourceLocation AttrNameLoc = ConsumeToken();
1300*12c85518Srobert         Attr.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1301*12c85518Srobert                     ParsedAttr::AS_Keyword);
1302*12c85518Srobert       } else if (Tok.is(tok::kw___attribute))
1303*12c85518Srobert         ParseGNUAttributes(Attr, nullptr, &D);
1304*12c85518Srobert       else
1305*12c85518Srobert         break;
1306*12c85518Srobert     }
1307*12c85518Srobert 
1308*12c85518Srobert     D.takeAttributes(Attr);
1309e5dd7070Spatrick   }
1310e5dd7070Spatrick 
1311e5dd7070Spatrick   // Helper to emit a warning if we see a CUDA host/device/global attribute
1312e5dd7070Spatrick   // after '(...)'. nvcc doesn't accept this.
1313e5dd7070Spatrick   auto WarnIfHasCUDATargetAttr = [&] {
1314e5dd7070Spatrick     if (getLangOpts().CUDA)
1315e5dd7070Spatrick       for (const ParsedAttr &A : Attr)
1316e5dd7070Spatrick         if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1317e5dd7070Spatrick             A.getKind() == ParsedAttr::AT_CUDAHost ||
1318e5dd7070Spatrick             A.getKind() == ParsedAttr::AT_CUDAGlobal)
1319e5dd7070Spatrick           Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1320e5dd7070Spatrick               << A.getAttrName()->getName();
1321e5dd7070Spatrick   };
1322e5dd7070Spatrick 
1323ec727ea7Spatrick   MultiParseScope TemplateParamScope(*this);
1324ec727ea7Spatrick   if (Tok.is(tok::less)) {
1325ec727ea7Spatrick     Diag(Tok, getLangOpts().CPlusPlus20
1326e5dd7070Spatrick                   ? diag::warn_cxx17_compat_lambda_template_parameter_list
1327e5dd7070Spatrick                   : diag::ext_lambda_template_parameter_list);
1328e5dd7070Spatrick 
1329e5dd7070Spatrick     SmallVector<NamedDecl*, 4> TemplateParams;
1330e5dd7070Spatrick     SourceLocation LAngleLoc, RAngleLoc;
1331ec727ea7Spatrick     if (ParseTemplateParameters(TemplateParamScope,
1332ec727ea7Spatrick                                 CurTemplateDepthTracker.getDepth(),
1333e5dd7070Spatrick                                 TemplateParams, LAngleLoc, RAngleLoc)) {
1334e5dd7070Spatrick       Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1335e5dd7070Spatrick       return ExprError();
1336e5dd7070Spatrick     }
1337e5dd7070Spatrick 
1338e5dd7070Spatrick     if (TemplateParams.empty()) {
1339e5dd7070Spatrick       Diag(RAngleLoc,
1340e5dd7070Spatrick            diag::err_lambda_template_parameter_list_empty);
1341e5dd7070Spatrick     } else {
1342a9ac8606Spatrick       ExprResult RequiresClause;
1343a9ac8606Spatrick       if (TryConsumeToken(tok::kw_requires)) {
1344a9ac8606Spatrick         RequiresClause =
1345a9ac8606Spatrick             Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
1346a9ac8606Spatrick                 /*IsTrailingRequiresClause=*/false));
1347a9ac8606Spatrick         if (RequiresClause.isInvalid())
1348a9ac8606Spatrick           SkipUntil({tok::l_brace, tok::l_paren}, StopAtSemi | StopBeforeMatch);
1349a9ac8606Spatrick       }
1350a9ac8606Spatrick 
1351e5dd7070Spatrick       Actions.ActOnLambdaExplicitTemplateParameterList(
1352a9ac8606Spatrick           LAngleLoc, TemplateParams, RAngleLoc, RequiresClause);
1353e5dd7070Spatrick       ++CurTemplateDepthTracker;
1354e5dd7070Spatrick     }
1355e5dd7070Spatrick   }
1356e5dd7070Spatrick 
1357a9ac8606Spatrick   // Implement WG21 P2173, which allows attributes immediately before the
1358a9ac8606Spatrick   // lambda declarator and applies them to the corresponding function operator
1359a9ac8606Spatrick   // or operator template declaration. We accept this as a conforming extension
1360a9ac8606Spatrick   // in all language modes that support lambdas.
1361a9ac8606Spatrick   if (isCXX11AttributeSpecifier()) {
1362a9ac8606Spatrick     Diag(Tok, getLangOpts().CPlusPlus2b
1363a9ac8606Spatrick                   ? diag::warn_cxx20_compat_decl_attrs_on_lambda
1364a9ac8606Spatrick                   : diag::ext_decl_attrs_on_lambda);
1365a9ac8606Spatrick     MaybeParseCXX11Attributes(D);
1366a9ac8606Spatrick   }
1367a9ac8606Spatrick 
1368e5dd7070Spatrick   TypeResult TrailingReturnType;
1369a9ac8606Spatrick   SourceLocation TrailingReturnTypeLoc;
1370a9ac8606Spatrick 
1371a9ac8606Spatrick   auto ParseLambdaSpecifiers =
1372a9ac8606Spatrick       [&](SourceLocation LParenLoc, SourceLocation RParenLoc,
1373a9ac8606Spatrick           MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo,
1374a9ac8606Spatrick           SourceLocation EllipsisLoc) {
1375a9ac8606Spatrick         SourceLocation DeclEndLoc = RParenLoc;
1376a9ac8606Spatrick 
1377a9ac8606Spatrick         // GNU-style attributes must be parsed before the mutable specifier to
1378a9ac8606Spatrick         // be compatible with GCC. MSVC-style attributes must be parsed before
1379a9ac8606Spatrick         // the mutable specifier to be compatible with MSVC.
1380a9ac8606Spatrick         MaybeParseAttributes(PAKM_GNU | PAKM_Declspec, Attr);
1381a9ac8606Spatrick 
1382*12c85518Srobert         // Parse lambda specifiers and update the DeclEndLoc.
1383a9ac8606Spatrick         SourceLocation MutableLoc;
1384*12c85518Srobert         SourceLocation StaticLoc;
1385a9ac8606Spatrick         SourceLocation ConstexprLoc;
1386a9ac8606Spatrick         SourceLocation ConstevalLoc;
1387*12c85518Srobert         tryConsumeLambdaSpecifierToken(*this, MutableLoc, StaticLoc,
1388*12c85518Srobert                                        ConstexprLoc, ConstevalLoc, DeclEndLoc);
1389a9ac8606Spatrick 
1390*12c85518Srobert         DiagnoseStaticSpecifierRestrictions(*this, StaticLoc, MutableLoc,
1391*12c85518Srobert                                             Intro);
1392*12c85518Srobert 
1393*12c85518Srobert         addStaticToLambdaDeclSpecifier(*this, StaticLoc, DS);
1394a9ac8606Spatrick         addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1395a9ac8606Spatrick         addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS);
1396a9ac8606Spatrick         // Parse exception-specification[opt].
1397a9ac8606Spatrick         ExceptionSpecificationType ESpecType = EST_None;
1398a9ac8606Spatrick         SourceRange ESpecRange;
1399a9ac8606Spatrick         SmallVector<ParsedType, 2> DynamicExceptions;
1400a9ac8606Spatrick         SmallVector<SourceRange, 2> DynamicExceptionRanges;
1401a9ac8606Spatrick         ExprResult NoexceptExpr;
1402a9ac8606Spatrick         CachedTokens *ExceptionSpecTokens;
1403a9ac8606Spatrick         ESpecType = tryParseExceptionSpecification(
1404a9ac8606Spatrick             /*Delayed=*/false, ESpecRange, DynamicExceptions,
1405a9ac8606Spatrick             DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens);
1406a9ac8606Spatrick 
1407a9ac8606Spatrick         if (ESpecType != EST_None)
1408a9ac8606Spatrick           DeclEndLoc = ESpecRange.getEnd();
1409a9ac8606Spatrick 
1410a9ac8606Spatrick         // Parse attribute-specifier[opt].
1411*12c85518Srobert         if (MaybeParseCXX11Attributes(Attr))
1412*12c85518Srobert           DeclEndLoc = Attr.Range.getEnd();
1413a9ac8606Spatrick 
1414a9ac8606Spatrick         // Parse OpenCL addr space attribute.
1415a9ac8606Spatrick         if (Tok.isOneOf(tok::kw___private, tok::kw___global, tok::kw___local,
1416a9ac8606Spatrick                         tok::kw___constant, tok::kw___generic)) {
1417a9ac8606Spatrick           ParseOpenCLQualifiers(DS.getAttributes());
1418a9ac8606Spatrick           ConsumeToken();
1419a9ac8606Spatrick         }
1420a9ac8606Spatrick 
1421a9ac8606Spatrick         SourceLocation FunLocalRangeEnd = DeclEndLoc;
1422a9ac8606Spatrick 
1423a9ac8606Spatrick         // Parse trailing-return-type[opt].
1424a9ac8606Spatrick         if (Tok.is(tok::arrow)) {
1425a9ac8606Spatrick           FunLocalRangeEnd = Tok.getLocation();
1426a9ac8606Spatrick           SourceRange Range;
1427a9ac8606Spatrick           TrailingReturnType = ParseTrailingReturnType(
1428a9ac8606Spatrick               Range, /*MayBeFollowedByDirectInit*/ false);
1429a9ac8606Spatrick           TrailingReturnTypeLoc = Range.getBegin();
1430a9ac8606Spatrick           if (Range.getEnd().isValid())
1431a9ac8606Spatrick             DeclEndLoc = Range.getEnd();
1432a9ac8606Spatrick         }
1433a9ac8606Spatrick 
1434a9ac8606Spatrick         SourceLocation NoLoc;
1435a9ac8606Spatrick         D.AddTypeInfo(
1436a9ac8606Spatrick             DeclaratorChunk::getFunction(
1437a9ac8606Spatrick                 /*HasProto=*/true,
1438a9ac8606Spatrick                 /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1439a9ac8606Spatrick                 ParamInfo.size(), EllipsisLoc, RParenLoc,
1440a9ac8606Spatrick                 /*RefQualifierIsLvalueRef=*/true,
1441a9ac8606Spatrick                 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType, ESpecRange,
1442a9ac8606Spatrick                 DynamicExceptions.data(), DynamicExceptionRanges.data(),
1443a9ac8606Spatrick                 DynamicExceptions.size(),
1444a9ac8606Spatrick                 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1445a9ac8606Spatrick                 /*ExceptionSpecTokens*/ nullptr,
1446*12c85518Srobert                 /*DeclsInPrototype=*/std::nullopt, LParenLoc, FunLocalRangeEnd,
1447*12c85518Srobert                 D, TrailingReturnType, TrailingReturnTypeLoc, &DS),
1448a9ac8606Spatrick             std::move(Attr), DeclEndLoc);
1449a9ac8606Spatrick       };
1450a9ac8606Spatrick 
1451e5dd7070Spatrick   if (Tok.is(tok::l_paren)) {
1452a9ac8606Spatrick     ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1453e5dd7070Spatrick                                         Scope::FunctionDeclarationScope |
1454e5dd7070Spatrick                                         Scope::DeclScope);
1455e5dd7070Spatrick 
1456e5dd7070Spatrick     BalancedDelimiterTracker T(*this, tok::l_paren);
1457e5dd7070Spatrick     T.consumeOpen();
1458e5dd7070Spatrick     SourceLocation LParenLoc = T.getOpenLocation();
1459e5dd7070Spatrick 
1460e5dd7070Spatrick     // Parse parameter-declaration-clause.
1461e5dd7070Spatrick     SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1462e5dd7070Spatrick     SourceLocation EllipsisLoc;
1463e5dd7070Spatrick 
1464e5dd7070Spatrick     if (Tok.isNot(tok::r_paren)) {
1465e5dd7070Spatrick       Actions.RecordParsingTemplateParameterDepth(
1466e5dd7070Spatrick           CurTemplateDepthTracker.getOriginalDepth());
1467e5dd7070Spatrick 
1468*12c85518Srobert       ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1469e5dd7070Spatrick       // For a generic lambda, each 'auto' within the parameter declaration
1470e5dd7070Spatrick       // clause creates a template type parameter, so increment the depth.
1471e5dd7070Spatrick       // If we've parsed any explicit template parameters, then the depth will
1472e5dd7070Spatrick       // have already been incremented. So we make sure that at most a single
1473e5dd7070Spatrick       // depth level is added.
1474e5dd7070Spatrick       if (Actions.getCurGenericLambda())
1475e5dd7070Spatrick         CurTemplateDepthTracker.setAddedDepth(1);
1476e5dd7070Spatrick     }
1477e5dd7070Spatrick 
1478e5dd7070Spatrick     T.consumeClose();
1479e5dd7070Spatrick 
1480a9ac8606Spatrick     // Parse lambda-specifiers.
1481a9ac8606Spatrick     ParseLambdaSpecifiers(LParenLoc, /*DeclEndLoc=*/T.getCloseLocation(),
1482a9ac8606Spatrick                           ParamInfo, EllipsisLoc);
1483e5dd7070Spatrick 
1484e5dd7070Spatrick     // Parse requires-clause[opt].
1485e5dd7070Spatrick     if (Tok.is(tok::kw_requires))
1486e5dd7070Spatrick       ParseTrailingRequiresClause(D);
1487e5dd7070Spatrick   } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1488*12c85518Srobert                          tok::kw_constexpr, tok::kw_consteval, tok::kw_static,
1489e5dd7070Spatrick                          tok::kw___private, tok::kw___global, tok::kw___local,
1490e5dd7070Spatrick                          tok::kw___constant, tok::kw___generic,
1491*12c85518Srobert                          tok::kw_groupshared, tok::kw_requires,
1492*12c85518Srobert                          tok::kw_noexcept) ||
1493e5dd7070Spatrick              (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1494a9ac8606Spatrick     if (!getLangOpts().CPlusPlus2b)
1495a9ac8606Spatrick       // It's common to forget that one needs '()' before 'mutable', an
1496a9ac8606Spatrick       // attribute specifier, the result type, or the requires clause. Deal with
1497a9ac8606Spatrick       // this.
1498a9ac8606Spatrick       Diag(Tok, diag::ext_lambda_missing_parens)
1499e5dd7070Spatrick           << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1500e5dd7070Spatrick 
1501e5dd7070Spatrick     SourceLocation NoLoc;
1502a9ac8606Spatrick     // Parse lambda-specifiers.
1503a9ac8606Spatrick     std::vector<DeclaratorChunk::ParamInfo> EmptyParamInfo;
1504a9ac8606Spatrick     ParseLambdaSpecifiers(/*LParenLoc=*/NoLoc, /*RParenLoc=*/NoLoc,
1505a9ac8606Spatrick                           EmptyParamInfo, /*EllipsisLoc=*/NoLoc);
1506a9ac8606Spatrick   }
1507e5dd7070Spatrick 
1508e5dd7070Spatrick   WarnIfHasCUDATargetAttr();
1509e5dd7070Spatrick 
1510e5dd7070Spatrick   // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1511e5dd7070Spatrick   // it.
1512e5dd7070Spatrick   unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1513e5dd7070Spatrick                         Scope::CompoundStmtScope;
1514e5dd7070Spatrick   ParseScope BodyScope(this, ScopeFlags);
1515e5dd7070Spatrick 
1516e5dd7070Spatrick   Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1517e5dd7070Spatrick 
1518e5dd7070Spatrick   // Parse compound-statement.
1519e5dd7070Spatrick   if (!Tok.is(tok::l_brace)) {
1520e5dd7070Spatrick     Diag(Tok, diag::err_expected_lambda_body);
1521e5dd7070Spatrick     Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1522e5dd7070Spatrick     return ExprError();
1523e5dd7070Spatrick   }
1524e5dd7070Spatrick 
1525e5dd7070Spatrick   StmtResult Stmt(ParseCompoundStatementBody());
1526e5dd7070Spatrick   BodyScope.Exit();
1527e5dd7070Spatrick   TemplateParamScope.Exit();
1528e5dd7070Spatrick 
1529e5dd7070Spatrick   if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1530e5dd7070Spatrick     return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1531e5dd7070Spatrick 
1532e5dd7070Spatrick   Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1533e5dd7070Spatrick   return ExprError();
1534e5dd7070Spatrick }
1535e5dd7070Spatrick 
1536e5dd7070Spatrick /// ParseCXXCasts - This handles the various ways to cast expressions to another
1537e5dd7070Spatrick /// type.
1538e5dd7070Spatrick ///
1539e5dd7070Spatrick ///       postfix-expression: [C++ 5.2p1]
1540e5dd7070Spatrick ///         'dynamic_cast' '<' type-name '>' '(' expression ')'
1541e5dd7070Spatrick ///         'static_cast' '<' type-name '>' '(' expression ')'
1542e5dd7070Spatrick ///         'reinterpret_cast' '<' type-name '>' '(' expression ')'
1543e5dd7070Spatrick ///         'const_cast' '<' type-name '>' '(' expression ')'
1544e5dd7070Spatrick ///
1545ec727ea7Spatrick /// C++ for OpenCL s2.3.1 adds:
1546ec727ea7Spatrick ///         'addrspace_cast' '<' type-name '>' '(' expression ')'
ParseCXXCasts()1547e5dd7070Spatrick ExprResult Parser::ParseCXXCasts() {
1548e5dd7070Spatrick   tok::TokenKind Kind = Tok.getKind();
1549e5dd7070Spatrick   const char *CastName = nullptr; // For error messages
1550e5dd7070Spatrick 
1551e5dd7070Spatrick   switch (Kind) {
1552e5dd7070Spatrick   default: llvm_unreachable("Unknown C++ cast!");
1553ec727ea7Spatrick   case tok::kw_addrspace_cast:   CastName = "addrspace_cast";   break;
1554e5dd7070Spatrick   case tok::kw_const_cast:       CastName = "const_cast";       break;
1555e5dd7070Spatrick   case tok::kw_dynamic_cast:     CastName = "dynamic_cast";     break;
1556e5dd7070Spatrick   case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1557e5dd7070Spatrick   case tok::kw_static_cast:      CastName = "static_cast";      break;
1558e5dd7070Spatrick   }
1559e5dd7070Spatrick 
1560e5dd7070Spatrick   SourceLocation OpLoc = ConsumeToken();
1561e5dd7070Spatrick   SourceLocation LAngleBracketLoc = Tok.getLocation();
1562e5dd7070Spatrick 
1563e5dd7070Spatrick   // Check for "<::" which is parsed as "[:".  If found, fix token stream,
1564e5dd7070Spatrick   // diagnose error, suggest fix, and recover parsing.
1565e5dd7070Spatrick   if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1566e5dd7070Spatrick     Token Next = NextToken();
1567e5dd7070Spatrick     if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1568e5dd7070Spatrick       FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1569e5dd7070Spatrick   }
1570e5dd7070Spatrick 
1571e5dd7070Spatrick   if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1572e5dd7070Spatrick     return ExprError();
1573e5dd7070Spatrick 
1574e5dd7070Spatrick   // Parse the common declaration-specifiers piece.
1575e5dd7070Spatrick   DeclSpec DS(AttrFactory);
1576*12c85518Srobert   ParseSpecifierQualifierList(DS, /*AccessSpecifier=*/AS_none,
1577*12c85518Srobert                               DeclSpecContext::DSC_type_specifier);
1578e5dd7070Spatrick 
1579e5dd7070Spatrick   // Parse the abstract-declarator, if present.
1580*12c85518Srobert   Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1581*12c85518Srobert                             DeclaratorContext::TypeName);
1582e5dd7070Spatrick   ParseDeclarator(DeclaratorInfo);
1583e5dd7070Spatrick 
1584e5dd7070Spatrick   SourceLocation RAngleBracketLoc = Tok.getLocation();
1585e5dd7070Spatrick 
1586e5dd7070Spatrick   if (ExpectAndConsume(tok::greater))
1587e5dd7070Spatrick     return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1588e5dd7070Spatrick 
1589e5dd7070Spatrick   BalancedDelimiterTracker T(*this, tok::l_paren);
1590e5dd7070Spatrick 
1591e5dd7070Spatrick   if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1592e5dd7070Spatrick     return ExprError();
1593e5dd7070Spatrick 
1594e5dd7070Spatrick   ExprResult Result = ParseExpression();
1595e5dd7070Spatrick 
1596e5dd7070Spatrick   // Match the ')'.
1597e5dd7070Spatrick   T.consumeClose();
1598e5dd7070Spatrick 
1599e5dd7070Spatrick   if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1600e5dd7070Spatrick     Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1601e5dd7070Spatrick                                        LAngleBracketLoc, DeclaratorInfo,
1602e5dd7070Spatrick                                        RAngleBracketLoc,
1603e5dd7070Spatrick                                        T.getOpenLocation(), Result.get(),
1604e5dd7070Spatrick                                        T.getCloseLocation());
1605e5dd7070Spatrick 
1606e5dd7070Spatrick   return Result;
1607e5dd7070Spatrick }
1608e5dd7070Spatrick 
1609e5dd7070Spatrick /// ParseCXXTypeid - This handles the C++ typeid expression.
1610e5dd7070Spatrick ///
1611e5dd7070Spatrick ///       postfix-expression: [C++ 5.2p1]
1612e5dd7070Spatrick ///         'typeid' '(' expression ')'
1613e5dd7070Spatrick ///         'typeid' '(' type-id ')'
1614e5dd7070Spatrick ///
ParseCXXTypeid()1615e5dd7070Spatrick ExprResult Parser::ParseCXXTypeid() {
1616e5dd7070Spatrick   assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1617e5dd7070Spatrick 
1618e5dd7070Spatrick   SourceLocation OpLoc = ConsumeToken();
1619e5dd7070Spatrick   SourceLocation LParenLoc, RParenLoc;
1620e5dd7070Spatrick   BalancedDelimiterTracker T(*this, tok::l_paren);
1621e5dd7070Spatrick 
1622e5dd7070Spatrick   // typeid expressions are always parenthesized.
1623e5dd7070Spatrick   if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1624e5dd7070Spatrick     return ExprError();
1625e5dd7070Spatrick   LParenLoc = T.getOpenLocation();
1626e5dd7070Spatrick 
1627e5dd7070Spatrick   ExprResult Result;
1628e5dd7070Spatrick 
1629e5dd7070Spatrick   // C++0x [expr.typeid]p3:
1630e5dd7070Spatrick   //   When typeid is applied to an expression other than an lvalue of a
1631e5dd7070Spatrick   //   polymorphic class type [...] The expression is an unevaluated
1632e5dd7070Spatrick   //   operand (Clause 5).
1633e5dd7070Spatrick   //
1634e5dd7070Spatrick   // Note that we can't tell whether the expression is an lvalue of a
1635e5dd7070Spatrick   // polymorphic class type until after we've parsed the expression; we
1636e5dd7070Spatrick   // speculatively assume the subexpression is unevaluated, and fix it up
1637e5dd7070Spatrick   // later.
1638e5dd7070Spatrick   //
1639e5dd7070Spatrick   // We enter the unevaluated context before trying to determine whether we
1640e5dd7070Spatrick   // have a type-id, because the tentative parse logic will try to resolve
1641e5dd7070Spatrick   // names, and must treat them as unevaluated.
1642e5dd7070Spatrick   EnterExpressionEvaluationContext Unevaluated(
1643e5dd7070Spatrick       Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1644e5dd7070Spatrick       Sema::ReuseLambdaContextDecl);
1645e5dd7070Spatrick 
1646e5dd7070Spatrick   if (isTypeIdInParens()) {
1647e5dd7070Spatrick     TypeResult Ty = ParseTypeName();
1648e5dd7070Spatrick 
1649e5dd7070Spatrick     // Match the ')'.
1650e5dd7070Spatrick     T.consumeClose();
1651e5dd7070Spatrick     RParenLoc = T.getCloseLocation();
1652e5dd7070Spatrick     if (Ty.isInvalid() || RParenLoc.isInvalid())
1653e5dd7070Spatrick       return ExprError();
1654e5dd7070Spatrick 
1655e5dd7070Spatrick     Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1656e5dd7070Spatrick                                     Ty.get().getAsOpaquePtr(), RParenLoc);
1657e5dd7070Spatrick   } else {
1658e5dd7070Spatrick     Result = ParseExpression();
1659e5dd7070Spatrick 
1660e5dd7070Spatrick     // Match the ')'.
1661e5dd7070Spatrick     if (Result.isInvalid())
1662e5dd7070Spatrick       SkipUntil(tok::r_paren, StopAtSemi);
1663e5dd7070Spatrick     else {
1664e5dd7070Spatrick       T.consumeClose();
1665e5dd7070Spatrick       RParenLoc = T.getCloseLocation();
1666e5dd7070Spatrick       if (RParenLoc.isInvalid())
1667e5dd7070Spatrick         return ExprError();
1668e5dd7070Spatrick 
1669e5dd7070Spatrick       Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1670e5dd7070Spatrick                                       Result.get(), RParenLoc);
1671e5dd7070Spatrick     }
1672e5dd7070Spatrick   }
1673e5dd7070Spatrick 
1674e5dd7070Spatrick   return Result;
1675e5dd7070Spatrick }
1676e5dd7070Spatrick 
1677e5dd7070Spatrick /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1678e5dd7070Spatrick ///
1679e5dd7070Spatrick ///         '__uuidof' '(' expression ')'
1680e5dd7070Spatrick ///         '__uuidof' '(' type-id ')'
1681e5dd7070Spatrick ///
ParseCXXUuidof()1682e5dd7070Spatrick ExprResult Parser::ParseCXXUuidof() {
1683e5dd7070Spatrick   assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1684e5dd7070Spatrick 
1685e5dd7070Spatrick   SourceLocation OpLoc = ConsumeToken();
1686e5dd7070Spatrick   BalancedDelimiterTracker T(*this, tok::l_paren);
1687e5dd7070Spatrick 
1688e5dd7070Spatrick   // __uuidof expressions are always parenthesized.
1689e5dd7070Spatrick   if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1690e5dd7070Spatrick     return ExprError();
1691e5dd7070Spatrick 
1692e5dd7070Spatrick   ExprResult Result;
1693e5dd7070Spatrick 
1694e5dd7070Spatrick   if (isTypeIdInParens()) {
1695e5dd7070Spatrick     TypeResult Ty = ParseTypeName();
1696e5dd7070Spatrick 
1697e5dd7070Spatrick     // Match the ')'.
1698e5dd7070Spatrick     T.consumeClose();
1699e5dd7070Spatrick 
1700e5dd7070Spatrick     if (Ty.isInvalid())
1701e5dd7070Spatrick       return ExprError();
1702e5dd7070Spatrick 
1703e5dd7070Spatrick     Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1704e5dd7070Spatrick                                     Ty.get().getAsOpaquePtr(),
1705e5dd7070Spatrick                                     T.getCloseLocation());
1706e5dd7070Spatrick   } else {
1707e5dd7070Spatrick     EnterExpressionEvaluationContext Unevaluated(
1708e5dd7070Spatrick         Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1709e5dd7070Spatrick     Result = ParseExpression();
1710e5dd7070Spatrick 
1711e5dd7070Spatrick     // Match the ')'.
1712e5dd7070Spatrick     if (Result.isInvalid())
1713e5dd7070Spatrick       SkipUntil(tok::r_paren, StopAtSemi);
1714e5dd7070Spatrick     else {
1715e5dd7070Spatrick       T.consumeClose();
1716e5dd7070Spatrick 
1717e5dd7070Spatrick       Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1718e5dd7070Spatrick                                       /*isType=*/false,
1719e5dd7070Spatrick                                       Result.get(), T.getCloseLocation());
1720e5dd7070Spatrick     }
1721e5dd7070Spatrick   }
1722e5dd7070Spatrick 
1723e5dd7070Spatrick   return Result;
1724e5dd7070Spatrick }
1725e5dd7070Spatrick 
1726e5dd7070Spatrick /// Parse a C++ pseudo-destructor expression after the base,
1727e5dd7070Spatrick /// . or -> operator, and nested-name-specifier have already been
1728ec727ea7Spatrick /// parsed. We're handling this fragment of the grammar:
1729e5dd7070Spatrick ///
1730ec727ea7Spatrick ///       postfix-expression: [C++2a expr.post]
1731ec727ea7Spatrick ///         postfix-expression . template[opt] id-expression
1732ec727ea7Spatrick ///         postfix-expression -> template[opt] id-expression
1733e5dd7070Spatrick ///
1734ec727ea7Spatrick ///       id-expression:
1735ec727ea7Spatrick ///         qualified-id
1736ec727ea7Spatrick ///         unqualified-id
1737ec727ea7Spatrick ///
1738ec727ea7Spatrick ///       qualified-id:
1739ec727ea7Spatrick ///         nested-name-specifier template[opt] unqualified-id
1740ec727ea7Spatrick ///
1741ec727ea7Spatrick ///       nested-name-specifier:
1742ec727ea7Spatrick ///         type-name ::
1743ec727ea7Spatrick ///         decltype-specifier ::    FIXME: not implemented, but probably only
1744ec727ea7Spatrick ///                                         allowed in C++ grammar by accident
1745ec727ea7Spatrick ///         nested-name-specifier identifier ::
1746ec727ea7Spatrick ///         nested-name-specifier template[opt] simple-template-id ::
1747ec727ea7Spatrick ///         [...]
1748ec727ea7Spatrick ///
1749ec727ea7Spatrick ///       unqualified-id:
1750e5dd7070Spatrick ///         ~ type-name
1751ec727ea7Spatrick ///         ~ decltype-specifier
1752ec727ea7Spatrick ///         [...]
1753e5dd7070Spatrick ///
1754ec727ea7Spatrick /// ... where the all but the last component of the nested-name-specifier
1755ec727ea7Spatrick /// has already been parsed, and the base expression is not of a non-dependent
1756ec727ea7Spatrick /// class type.
1757e5dd7070Spatrick ExprResult
ParseCXXPseudoDestructor(Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,CXXScopeSpec & SS,ParsedType ObjectType)1758e5dd7070Spatrick Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1759e5dd7070Spatrick                                  tok::TokenKind OpKind,
1760e5dd7070Spatrick                                  CXXScopeSpec &SS,
1761e5dd7070Spatrick                                  ParsedType ObjectType) {
1762ec727ea7Spatrick   // If the last component of the (optional) nested-name-specifier is
1763ec727ea7Spatrick   // template[opt] simple-template-id, it has already been annotated.
1764e5dd7070Spatrick   UnqualifiedId FirstTypeName;
1765e5dd7070Spatrick   SourceLocation CCLoc;
1766e5dd7070Spatrick   if (Tok.is(tok::identifier)) {
1767e5dd7070Spatrick     FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1768e5dd7070Spatrick     ConsumeToken();
1769e5dd7070Spatrick     assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1770e5dd7070Spatrick     CCLoc = ConsumeToken();
1771e5dd7070Spatrick   } else if (Tok.is(tok::annot_template_id)) {
1772ec727ea7Spatrick     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1773ec727ea7Spatrick     // FIXME: Carry on and build an AST representation for tooling.
1774ec727ea7Spatrick     if (TemplateId->isInvalid())
1775ec727ea7Spatrick       return ExprError();
1776ec727ea7Spatrick     FirstTypeName.setTemplateId(TemplateId);
1777e5dd7070Spatrick     ConsumeAnnotationToken();
1778e5dd7070Spatrick     assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1779e5dd7070Spatrick     CCLoc = ConsumeToken();
1780e5dd7070Spatrick   } else {
1781ec727ea7Spatrick     assert(SS.isEmpty() && "missing last component of nested name specifier");
1782e5dd7070Spatrick     FirstTypeName.setIdentifier(nullptr, SourceLocation());
1783e5dd7070Spatrick   }
1784e5dd7070Spatrick 
1785e5dd7070Spatrick   // Parse the tilde.
1786e5dd7070Spatrick   assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1787e5dd7070Spatrick   SourceLocation TildeLoc = ConsumeToken();
1788e5dd7070Spatrick 
1789ec727ea7Spatrick   if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid()) {
1790e5dd7070Spatrick     DeclSpec DS(AttrFactory);
1791e5dd7070Spatrick     ParseDecltypeSpecifier(DS);
1792e5dd7070Spatrick     if (DS.getTypeSpecType() == TST_error)
1793e5dd7070Spatrick       return ExprError();
1794e5dd7070Spatrick     return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1795e5dd7070Spatrick                                              TildeLoc, DS);
1796e5dd7070Spatrick   }
1797e5dd7070Spatrick 
1798e5dd7070Spatrick   if (!Tok.is(tok::identifier)) {
1799e5dd7070Spatrick     Diag(Tok, diag::err_destructor_tilde_identifier);
1800e5dd7070Spatrick     return ExprError();
1801e5dd7070Spatrick   }
1802e5dd7070Spatrick 
1803e5dd7070Spatrick   // Parse the second type.
1804e5dd7070Spatrick   UnqualifiedId SecondTypeName;
1805e5dd7070Spatrick   IdentifierInfo *Name = Tok.getIdentifierInfo();
1806e5dd7070Spatrick   SourceLocation NameLoc = ConsumeToken();
1807e5dd7070Spatrick   SecondTypeName.setIdentifier(Name, NameLoc);
1808e5dd7070Spatrick 
1809e5dd7070Spatrick   // If there is a '<', the second type name is a template-id. Parse
1810e5dd7070Spatrick   // it as such.
1811ec727ea7Spatrick   //
1812ec727ea7Spatrick   // FIXME: This is not a context in which a '<' is assumed to start a template
1813ec727ea7Spatrick   // argument list. This affects examples such as
1814ec727ea7Spatrick   //   void f(auto *p) { p->~X<int>(); }
1815ec727ea7Spatrick   // ... but there's no ambiguity, and nowhere to write 'template' in such an
1816ec727ea7Spatrick   // example, so we accept it anyway.
1817e5dd7070Spatrick   if (Tok.is(tok::less) &&
1818ec727ea7Spatrick       ParseUnqualifiedIdTemplateId(
1819ec727ea7Spatrick           SS, ObjectType, Base && Base->containsErrors(), SourceLocation(),
1820ec727ea7Spatrick           Name, NameLoc, false, SecondTypeName,
1821e5dd7070Spatrick           /*AssumeTemplateId=*/true))
1822e5dd7070Spatrick     return ExprError();
1823e5dd7070Spatrick 
1824e5dd7070Spatrick   return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1825e5dd7070Spatrick                                            SS, FirstTypeName, CCLoc, TildeLoc,
1826e5dd7070Spatrick                                            SecondTypeName);
1827e5dd7070Spatrick }
1828e5dd7070Spatrick 
1829e5dd7070Spatrick /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1830e5dd7070Spatrick ///
1831e5dd7070Spatrick ///       boolean-literal: [C++ 2.13.5]
1832e5dd7070Spatrick ///         'true'
1833e5dd7070Spatrick ///         'false'
ParseCXXBoolLiteral()1834e5dd7070Spatrick ExprResult Parser::ParseCXXBoolLiteral() {
1835e5dd7070Spatrick   tok::TokenKind Kind = Tok.getKind();
1836e5dd7070Spatrick   return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1837e5dd7070Spatrick }
1838e5dd7070Spatrick 
1839e5dd7070Spatrick /// ParseThrowExpression - This handles the C++ throw expression.
1840e5dd7070Spatrick ///
1841e5dd7070Spatrick ///       throw-expression: [C++ 15]
1842e5dd7070Spatrick ///         'throw' assignment-expression[opt]
ParseThrowExpression()1843e5dd7070Spatrick ExprResult Parser::ParseThrowExpression() {
1844e5dd7070Spatrick   assert(Tok.is(tok::kw_throw) && "Not throw!");
1845e5dd7070Spatrick   SourceLocation ThrowLoc = ConsumeToken();           // Eat the throw token.
1846e5dd7070Spatrick 
1847e5dd7070Spatrick   // If the current token isn't the start of an assignment-expression,
1848e5dd7070Spatrick   // then the expression is not present.  This handles things like:
1849e5dd7070Spatrick   //   "C ? throw : (void)42", which is crazy but legal.
1850e5dd7070Spatrick   switch (Tok.getKind()) {  // FIXME: move this predicate somewhere common.
1851e5dd7070Spatrick   case tok::semi:
1852e5dd7070Spatrick   case tok::r_paren:
1853e5dd7070Spatrick   case tok::r_square:
1854e5dd7070Spatrick   case tok::r_brace:
1855e5dd7070Spatrick   case tok::colon:
1856e5dd7070Spatrick   case tok::comma:
1857e5dd7070Spatrick     return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1858e5dd7070Spatrick 
1859e5dd7070Spatrick   default:
1860e5dd7070Spatrick     ExprResult Expr(ParseAssignmentExpression());
1861e5dd7070Spatrick     if (Expr.isInvalid()) return Expr;
1862e5dd7070Spatrick     return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1863e5dd7070Spatrick   }
1864e5dd7070Spatrick }
1865e5dd7070Spatrick 
1866e5dd7070Spatrick /// Parse the C++ Coroutines co_yield expression.
1867e5dd7070Spatrick ///
1868e5dd7070Spatrick ///       co_yield-expression:
1869e5dd7070Spatrick ///         'co_yield' assignment-expression[opt]
ParseCoyieldExpression()1870e5dd7070Spatrick ExprResult Parser::ParseCoyieldExpression() {
1871e5dd7070Spatrick   assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1872e5dd7070Spatrick 
1873e5dd7070Spatrick   SourceLocation Loc = ConsumeToken();
1874e5dd7070Spatrick   ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1875e5dd7070Spatrick                                          : ParseAssignmentExpression();
1876e5dd7070Spatrick   if (!Expr.isInvalid())
1877e5dd7070Spatrick     Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1878e5dd7070Spatrick   return Expr;
1879e5dd7070Spatrick }
1880e5dd7070Spatrick 
1881e5dd7070Spatrick /// ParseCXXThis - This handles the C++ 'this' pointer.
1882e5dd7070Spatrick ///
1883e5dd7070Spatrick /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1884e5dd7070Spatrick /// a non-lvalue expression whose value is the address of the object for which
1885e5dd7070Spatrick /// the function is called.
ParseCXXThis()1886e5dd7070Spatrick ExprResult Parser::ParseCXXThis() {
1887e5dd7070Spatrick   assert(Tok.is(tok::kw_this) && "Not 'this'!");
1888e5dd7070Spatrick   SourceLocation ThisLoc = ConsumeToken();
1889e5dd7070Spatrick   return Actions.ActOnCXXThis(ThisLoc);
1890e5dd7070Spatrick }
1891e5dd7070Spatrick 
1892e5dd7070Spatrick /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1893e5dd7070Spatrick /// Can be interpreted either as function-style casting ("int(x)")
1894e5dd7070Spatrick /// or class type construction ("ClassType(x,y,z)")
1895e5dd7070Spatrick /// or creation of a value-initialized type ("int()").
1896e5dd7070Spatrick /// See [C++ 5.2.3].
1897e5dd7070Spatrick ///
1898e5dd7070Spatrick ///       postfix-expression: [C++ 5.2p1]
1899e5dd7070Spatrick ///         simple-type-specifier '(' expression-list[opt] ')'
1900e5dd7070Spatrick /// [C++0x] simple-type-specifier braced-init-list
1901e5dd7070Spatrick ///         typename-specifier '(' expression-list[opt] ')'
1902e5dd7070Spatrick /// [C++0x] typename-specifier braced-init-list
1903e5dd7070Spatrick ///
1904e5dd7070Spatrick /// In C++1z onwards, the type specifier can also be a template-name.
1905e5dd7070Spatrick ExprResult
ParseCXXTypeConstructExpression(const DeclSpec & DS)1906e5dd7070Spatrick Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1907*12c85518Srobert   Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1908*12c85518Srobert                             DeclaratorContext::FunctionalCast);
1909e5dd7070Spatrick   ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1910e5dd7070Spatrick 
1911e5dd7070Spatrick   assert((Tok.is(tok::l_paren) ||
1912e5dd7070Spatrick           (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1913e5dd7070Spatrick          && "Expected '(' or '{'!");
1914e5dd7070Spatrick 
1915e5dd7070Spatrick   if (Tok.is(tok::l_brace)) {
1916ec727ea7Spatrick     PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1917e5dd7070Spatrick     ExprResult Init = ParseBraceInitializer();
1918e5dd7070Spatrick     if (Init.isInvalid())
1919e5dd7070Spatrick       return Init;
1920e5dd7070Spatrick     Expr *InitList = Init.get();
1921e5dd7070Spatrick     return Actions.ActOnCXXTypeConstructExpr(
1922e5dd7070Spatrick         TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
1923e5dd7070Spatrick         InitList->getEndLoc(), /*ListInitialization=*/true);
1924e5dd7070Spatrick   } else {
1925e5dd7070Spatrick     BalancedDelimiterTracker T(*this, tok::l_paren);
1926e5dd7070Spatrick     T.consumeOpen();
1927e5dd7070Spatrick 
1928e5dd7070Spatrick     PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1929e5dd7070Spatrick 
1930e5dd7070Spatrick     ExprVector Exprs;
1931e5dd7070Spatrick 
1932e5dd7070Spatrick     auto RunSignatureHelp = [&]() {
1933e5dd7070Spatrick       QualType PreferredType;
1934e5dd7070Spatrick       if (TypeRep)
1935e5dd7070Spatrick         PreferredType = Actions.ProduceConstructorSignatureHelp(
1936*12c85518Srobert             TypeRep.get()->getCanonicalTypeInternal(), DS.getEndLoc(), Exprs,
1937*12c85518Srobert             T.getOpenLocation(), /*Braced=*/false);
1938e5dd7070Spatrick       CalledSignatureHelp = true;
1939e5dd7070Spatrick       return PreferredType;
1940e5dd7070Spatrick     };
1941e5dd7070Spatrick 
1942e5dd7070Spatrick     if (Tok.isNot(tok::r_paren)) {
1943*12c85518Srobert       if (ParseExpressionList(Exprs, [&] {
1944e5dd7070Spatrick             PreferredType.enterFunctionArgument(Tok.getLocation(),
1945e5dd7070Spatrick                                                 RunSignatureHelp);
1946e5dd7070Spatrick           })) {
1947e5dd7070Spatrick         if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1948e5dd7070Spatrick           RunSignatureHelp();
1949e5dd7070Spatrick         SkipUntil(tok::r_paren, StopAtSemi);
1950e5dd7070Spatrick         return ExprError();
1951e5dd7070Spatrick       }
1952e5dd7070Spatrick     }
1953e5dd7070Spatrick 
1954e5dd7070Spatrick     // Match the ')'.
1955e5dd7070Spatrick     T.consumeClose();
1956e5dd7070Spatrick 
1957e5dd7070Spatrick     // TypeRep could be null, if it references an invalid typedef.
1958e5dd7070Spatrick     if (!TypeRep)
1959e5dd7070Spatrick       return ExprError();
1960e5dd7070Spatrick 
1961e5dd7070Spatrick     return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1962e5dd7070Spatrick                                              Exprs, T.getCloseLocation(),
1963e5dd7070Spatrick                                              /*ListInitialization=*/false);
1964e5dd7070Spatrick   }
1965e5dd7070Spatrick }
1966e5dd7070Spatrick 
1967*12c85518Srobert Parser::DeclGroupPtrTy
ParseAliasDeclarationInInitStatement(DeclaratorContext Context,ParsedAttributes & Attrs)1968*12c85518Srobert Parser::ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
1969*12c85518Srobert                                              ParsedAttributes &Attrs) {
1970*12c85518Srobert   assert(Tok.is(tok::kw_using) && "Expected using");
1971*12c85518Srobert   assert((Context == DeclaratorContext::ForInit ||
1972*12c85518Srobert           Context == DeclaratorContext::SelectionInit) &&
1973*12c85518Srobert          "Unexpected Declarator Context");
1974*12c85518Srobert   DeclGroupPtrTy DG;
1975*12c85518Srobert   SourceLocation DeclStart = ConsumeToken(), DeclEnd;
1976*12c85518Srobert 
1977*12c85518Srobert   DG = ParseUsingDeclaration(Context, {}, DeclStart, DeclEnd, Attrs, AS_none);
1978*12c85518Srobert   if (!DG)
1979*12c85518Srobert     return DG;
1980*12c85518Srobert 
1981*12c85518Srobert   Diag(DeclStart, !getLangOpts().CPlusPlus2b
1982*12c85518Srobert                       ? diag::ext_alias_in_init_statement
1983*12c85518Srobert                       : diag::warn_cxx20_alias_in_init_statement)
1984*12c85518Srobert       << SourceRange(DeclStart, DeclEnd);
1985*12c85518Srobert 
1986*12c85518Srobert   return DG;
1987*12c85518Srobert }
1988*12c85518Srobert 
1989e5dd7070Spatrick /// ParseCXXCondition - if/switch/while condition expression.
1990e5dd7070Spatrick ///
1991e5dd7070Spatrick ///       condition:
1992e5dd7070Spatrick ///         expression
1993e5dd7070Spatrick ///         type-specifier-seq declarator '=' assignment-expression
1994e5dd7070Spatrick /// [C++11] type-specifier-seq declarator '=' initializer-clause
1995e5dd7070Spatrick /// [C++11] type-specifier-seq declarator braced-init-list
1996e5dd7070Spatrick /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1997e5dd7070Spatrick ///             brace-or-equal-initializer
1998e5dd7070Spatrick /// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1999e5dd7070Spatrick ///             '=' assignment-expression
2000e5dd7070Spatrick ///
2001e5dd7070Spatrick /// In C++1z, a condition may in some contexts be preceded by an
2002e5dd7070Spatrick /// optional init-statement. This function will parse that too.
2003e5dd7070Spatrick ///
2004e5dd7070Spatrick /// \param InitStmt If non-null, an init-statement is permitted, and if present
2005e5dd7070Spatrick /// will be parsed and stored here.
2006e5dd7070Spatrick ///
2007e5dd7070Spatrick /// \param Loc The location of the start of the statement that requires this
2008e5dd7070Spatrick /// condition, e.g., the "for" in a for loop.
2009e5dd7070Spatrick ///
2010*12c85518Srobert /// \param MissingOK Whether an empty condition is acceptable here. Otherwise
2011*12c85518Srobert /// it is considered an error to be recovered from.
2012*12c85518Srobert ///
2013e5dd7070Spatrick /// \param FRI If non-null, a for range declaration is permitted, and if
2014e5dd7070Spatrick /// present will be parsed and stored here, and a null result will be returned.
2015e5dd7070Spatrick ///
2016a9ac8606Spatrick /// \param EnterForConditionScope If true, enter a continue/break scope at the
2017a9ac8606Spatrick /// appropriate moment for a 'for' loop.
2018a9ac8606Spatrick ///
2019e5dd7070Spatrick /// \returns The parsed condition.
2020*12c85518Srobert Sema::ConditionResult
ParseCXXCondition(StmtResult * InitStmt,SourceLocation Loc,Sema::ConditionKind CK,bool MissingOK,ForRangeInfo * FRI,bool EnterForConditionScope)2021*12c85518Srobert Parser::ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc,
2022*12c85518Srobert                           Sema::ConditionKind CK, bool MissingOK,
2023*12c85518Srobert                           ForRangeInfo *FRI, bool EnterForConditionScope) {
2024a9ac8606Spatrick   // Helper to ensure we always enter a continue/break scope if requested.
2025a9ac8606Spatrick   struct ForConditionScopeRAII {
2026a9ac8606Spatrick     Scope *S;
2027a9ac8606Spatrick     void enter(bool IsConditionVariable) {
2028a9ac8606Spatrick       if (S) {
2029a9ac8606Spatrick         S->AddFlags(Scope::BreakScope | Scope::ContinueScope);
2030a9ac8606Spatrick         S->setIsConditionVarScope(IsConditionVariable);
2031a9ac8606Spatrick       }
2032a9ac8606Spatrick     }
2033a9ac8606Spatrick     ~ForConditionScopeRAII() {
2034a9ac8606Spatrick       if (S)
2035a9ac8606Spatrick         S->setIsConditionVarScope(false);
2036a9ac8606Spatrick     }
2037a9ac8606Spatrick   } ForConditionScope{EnterForConditionScope ? getCurScope() : nullptr};
2038a9ac8606Spatrick 
2039e5dd7070Spatrick   ParenBraceBracketBalancer BalancerRAIIObj(*this);
2040e5dd7070Spatrick   PreferredType.enterCondition(Actions, Tok.getLocation());
2041e5dd7070Spatrick 
2042e5dd7070Spatrick   if (Tok.is(tok::code_completion)) {
2043e5dd7070Spatrick     cutOffParsing();
2044a9ac8606Spatrick     Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
2045e5dd7070Spatrick     return Sema::ConditionError();
2046e5dd7070Spatrick   }
2047e5dd7070Spatrick 
2048*12c85518Srobert   ParsedAttributes attrs(AttrFactory);
2049e5dd7070Spatrick   MaybeParseCXX11Attributes(attrs);
2050e5dd7070Spatrick 
2051e5dd7070Spatrick   const auto WarnOnInit = [this, &CK] {
2052e5dd7070Spatrick     Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
2053e5dd7070Spatrick                                 ? diag::warn_cxx14_compat_init_statement
2054e5dd7070Spatrick                                 : diag::ext_init_statement)
2055e5dd7070Spatrick         << (CK == Sema::ConditionKind::Switch);
2056e5dd7070Spatrick   };
2057e5dd7070Spatrick 
2058e5dd7070Spatrick   // Determine what kind of thing we have.
2059e5dd7070Spatrick   switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
2060e5dd7070Spatrick   case ConditionOrInitStatement::Expression: {
2061a9ac8606Spatrick     // If this is a for loop, we're entering its condition.
2062a9ac8606Spatrick     ForConditionScope.enter(/*IsConditionVariable=*/false);
2063a9ac8606Spatrick 
2064e5dd7070Spatrick     ProhibitAttributes(attrs);
2065e5dd7070Spatrick 
2066e5dd7070Spatrick     // We can have an empty expression here.
2067e5dd7070Spatrick     //   if (; true);
2068e5dd7070Spatrick     if (InitStmt && Tok.is(tok::semi)) {
2069e5dd7070Spatrick       WarnOnInit();
2070e5dd7070Spatrick       SourceLocation SemiLoc = Tok.getLocation();
2071e5dd7070Spatrick       if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
2072e5dd7070Spatrick         Diag(SemiLoc, diag::warn_empty_init_statement)
2073e5dd7070Spatrick             << (CK == Sema::ConditionKind::Switch)
2074e5dd7070Spatrick             << FixItHint::CreateRemoval(SemiLoc);
2075e5dd7070Spatrick       }
2076e5dd7070Spatrick       ConsumeToken();
2077e5dd7070Spatrick       *InitStmt = Actions.ActOnNullStmt(SemiLoc);
2078*12c85518Srobert       return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
2079e5dd7070Spatrick     }
2080e5dd7070Spatrick 
2081e5dd7070Spatrick     // Parse the expression.
2082e5dd7070Spatrick     ExprResult Expr = ParseExpression(); // expression
2083e5dd7070Spatrick     if (Expr.isInvalid())
2084e5dd7070Spatrick       return Sema::ConditionError();
2085e5dd7070Spatrick 
2086e5dd7070Spatrick     if (InitStmt && Tok.is(tok::semi)) {
2087e5dd7070Spatrick       WarnOnInit();
2088e5dd7070Spatrick       *InitStmt = Actions.ActOnExprStmt(Expr.get());
2089e5dd7070Spatrick       ConsumeToken();
2090*12c85518Srobert       return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
2091e5dd7070Spatrick     }
2092e5dd7070Spatrick 
2093*12c85518Srobert     return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK,
2094*12c85518Srobert                                   MissingOK);
2095e5dd7070Spatrick   }
2096e5dd7070Spatrick 
2097e5dd7070Spatrick   case ConditionOrInitStatement::InitStmtDecl: {
2098e5dd7070Spatrick     WarnOnInit();
2099*12c85518Srobert     DeclGroupPtrTy DG;
2100e5dd7070Spatrick     SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2101*12c85518Srobert     if (Tok.is(tok::kw_using))
2102*12c85518Srobert       DG = ParseAliasDeclarationInInitStatement(
2103*12c85518Srobert           DeclaratorContext::SelectionInit, attrs);
2104*12c85518Srobert     else {
2105*12c85518Srobert       ParsedAttributes DeclSpecAttrs(AttrFactory);
2106*12c85518Srobert       DG = ParseSimpleDeclaration(DeclaratorContext::SelectionInit, DeclEnd,
2107*12c85518Srobert                                   attrs, DeclSpecAttrs, /*RequireSemi=*/true);
2108*12c85518Srobert     }
2109e5dd7070Spatrick     *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
2110*12c85518Srobert     return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
2111e5dd7070Spatrick   }
2112e5dd7070Spatrick 
2113e5dd7070Spatrick   case ConditionOrInitStatement::ForRangeDecl: {
2114a9ac8606Spatrick     // This is 'for (init-stmt; for-range-decl : range-expr)'.
2115a9ac8606Spatrick     // We're not actually in a for loop yet, so 'break' and 'continue' aren't
2116a9ac8606Spatrick     // permitted here.
2117e5dd7070Spatrick     assert(FRI && "should not parse a for range declaration here");
2118e5dd7070Spatrick     SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2119*12c85518Srobert     ParsedAttributes DeclSpecAttrs(AttrFactory);
2120*12c85518Srobert     DeclGroupPtrTy DG = ParseSimpleDeclaration(
2121*12c85518Srobert         DeclaratorContext::ForInit, DeclEnd, attrs, DeclSpecAttrs, false, FRI);
2122e5dd7070Spatrick     FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2123a9ac8606Spatrick     assert((FRI->ColonLoc.isValid() || !DG) &&
2124a9ac8606Spatrick            "cannot find for range declaration");
2125e5dd7070Spatrick     return Sema::ConditionResult();
2126e5dd7070Spatrick   }
2127e5dd7070Spatrick 
2128e5dd7070Spatrick   case ConditionOrInitStatement::ConditionDecl:
2129e5dd7070Spatrick   case ConditionOrInitStatement::Error:
2130e5dd7070Spatrick     break;
2131e5dd7070Spatrick   }
2132e5dd7070Spatrick 
2133a9ac8606Spatrick   // If this is a for loop, we're entering its condition.
2134a9ac8606Spatrick   ForConditionScope.enter(/*IsConditionVariable=*/true);
2135a9ac8606Spatrick 
2136e5dd7070Spatrick   // type-specifier-seq
2137e5dd7070Spatrick   DeclSpec DS(AttrFactory);
2138e5dd7070Spatrick   ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
2139e5dd7070Spatrick 
2140e5dd7070Spatrick   // declarator
2141*12c85518Srobert   Declarator DeclaratorInfo(DS, attrs, DeclaratorContext::Condition);
2142e5dd7070Spatrick   ParseDeclarator(DeclaratorInfo);
2143e5dd7070Spatrick 
2144e5dd7070Spatrick   // simple-asm-expr[opt]
2145e5dd7070Spatrick   if (Tok.is(tok::kw_asm)) {
2146e5dd7070Spatrick     SourceLocation Loc;
2147e5dd7070Spatrick     ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2148e5dd7070Spatrick     if (AsmLabel.isInvalid()) {
2149e5dd7070Spatrick       SkipUntil(tok::semi, StopAtSemi);
2150e5dd7070Spatrick       return Sema::ConditionError();
2151e5dd7070Spatrick     }
2152e5dd7070Spatrick     DeclaratorInfo.setAsmLabel(AsmLabel.get());
2153e5dd7070Spatrick     DeclaratorInfo.SetRangeEnd(Loc);
2154e5dd7070Spatrick   }
2155e5dd7070Spatrick 
2156e5dd7070Spatrick   // If attributes are present, parse them.
2157e5dd7070Spatrick   MaybeParseGNUAttributes(DeclaratorInfo);
2158e5dd7070Spatrick 
2159e5dd7070Spatrick   // Type-check the declaration itself.
2160e5dd7070Spatrick   DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
2161e5dd7070Spatrick                                                         DeclaratorInfo);
2162e5dd7070Spatrick   if (Dcl.isInvalid())
2163e5dd7070Spatrick     return Sema::ConditionError();
2164e5dd7070Spatrick   Decl *DeclOut = Dcl.get();
2165e5dd7070Spatrick 
2166e5dd7070Spatrick   // '=' assignment-expression
2167e5dd7070Spatrick   // If a '==' or '+=' is found, suggest a fixit to '='.
2168e5dd7070Spatrick   bool CopyInitialization = isTokenEqualOrEqualTypo();
2169e5dd7070Spatrick   if (CopyInitialization)
2170e5dd7070Spatrick     ConsumeToken();
2171e5dd7070Spatrick 
2172e5dd7070Spatrick   ExprResult InitExpr = ExprError();
2173e5dd7070Spatrick   if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2174e5dd7070Spatrick     Diag(Tok.getLocation(),
2175e5dd7070Spatrick          diag::warn_cxx98_compat_generalized_initializer_lists);
2176e5dd7070Spatrick     InitExpr = ParseBraceInitializer();
2177e5dd7070Spatrick   } else if (CopyInitialization) {
2178e5dd7070Spatrick     PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
2179e5dd7070Spatrick     InitExpr = ParseAssignmentExpression();
2180e5dd7070Spatrick   } else if (Tok.is(tok::l_paren)) {
2181e5dd7070Spatrick     // This was probably an attempt to initialize the variable.
2182e5dd7070Spatrick     SourceLocation LParen = ConsumeParen(), RParen = LParen;
2183e5dd7070Spatrick     if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
2184e5dd7070Spatrick       RParen = ConsumeParen();
2185e5dd7070Spatrick     Diag(DeclOut->getLocation(),
2186e5dd7070Spatrick          diag::err_expected_init_in_condition_lparen)
2187e5dd7070Spatrick       << SourceRange(LParen, RParen);
2188e5dd7070Spatrick   } else {
2189e5dd7070Spatrick     Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
2190e5dd7070Spatrick   }
2191e5dd7070Spatrick 
2192e5dd7070Spatrick   if (!InitExpr.isInvalid())
2193e5dd7070Spatrick     Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
2194e5dd7070Spatrick   else
2195e5dd7070Spatrick     Actions.ActOnInitializerError(DeclOut);
2196e5dd7070Spatrick 
2197e5dd7070Spatrick   Actions.FinalizeDeclaration(DeclOut);
2198e5dd7070Spatrick   return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
2199e5dd7070Spatrick }
2200e5dd7070Spatrick 
2201e5dd7070Spatrick /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2202e5dd7070Spatrick /// This should only be called when the current token is known to be part of
2203e5dd7070Spatrick /// simple-type-specifier.
2204e5dd7070Spatrick ///
2205e5dd7070Spatrick ///       simple-type-specifier:
2206e5dd7070Spatrick ///         '::'[opt] nested-name-specifier[opt] type-name
2207e5dd7070Spatrick ///         '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
2208e5dd7070Spatrick ///         char
2209e5dd7070Spatrick ///         wchar_t
2210e5dd7070Spatrick ///         bool
2211e5dd7070Spatrick ///         short
2212e5dd7070Spatrick ///         int
2213e5dd7070Spatrick ///         long
2214e5dd7070Spatrick ///         signed
2215e5dd7070Spatrick ///         unsigned
2216e5dd7070Spatrick ///         float
2217e5dd7070Spatrick ///         double
2218e5dd7070Spatrick ///         void
2219e5dd7070Spatrick /// [GNU]   typeof-specifier
2220e5dd7070Spatrick /// [C++0x] auto               [TODO]
2221e5dd7070Spatrick ///
2222e5dd7070Spatrick ///       type-name:
2223e5dd7070Spatrick ///         class-name
2224e5dd7070Spatrick ///         enum-name
2225e5dd7070Spatrick ///         typedef-name
2226e5dd7070Spatrick ///
ParseCXXSimpleTypeSpecifier(DeclSpec & DS)2227e5dd7070Spatrick void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
2228e5dd7070Spatrick   DS.SetRangeStart(Tok.getLocation());
2229e5dd7070Spatrick   const char *PrevSpec;
2230e5dd7070Spatrick   unsigned DiagID;
2231e5dd7070Spatrick   SourceLocation Loc = Tok.getLocation();
2232e5dd7070Spatrick   const clang::PrintingPolicy &Policy =
2233e5dd7070Spatrick       Actions.getASTContext().getPrintingPolicy();
2234e5dd7070Spatrick 
2235e5dd7070Spatrick   switch (Tok.getKind()) {
2236e5dd7070Spatrick   case tok::identifier:   // foo::bar
2237e5dd7070Spatrick   case tok::coloncolon:   // ::foo::bar
2238e5dd7070Spatrick     llvm_unreachable("Annotation token should already be formed!");
2239e5dd7070Spatrick   default:
2240e5dd7070Spatrick     llvm_unreachable("Not a simple-type-specifier token!");
2241e5dd7070Spatrick 
2242e5dd7070Spatrick   // type-name
2243e5dd7070Spatrick   case tok::annot_typename: {
2244e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
2245e5dd7070Spatrick                        getTypeAnnotation(Tok), Policy);
2246e5dd7070Spatrick     DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2247e5dd7070Spatrick     ConsumeAnnotationToken();
2248e5dd7070Spatrick 
2249e5dd7070Spatrick     DS.Finish(Actions, Policy);
2250e5dd7070Spatrick     return;
2251e5dd7070Spatrick   }
2252e5dd7070Spatrick 
2253*12c85518Srobert   case tok::kw__ExtInt:
2254*12c85518Srobert   case tok::kw__BitInt: {
2255*12c85518Srobert     DiagnoseBitIntUse(Tok);
2256ec727ea7Spatrick     ExprResult ER = ParseExtIntegerArgument();
2257ec727ea7Spatrick     if (ER.isInvalid())
2258ec727ea7Spatrick       DS.SetTypeSpecError();
2259ec727ea7Spatrick     else
2260*12c85518Srobert       DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
2261ec727ea7Spatrick 
2262ec727ea7Spatrick     // Do this here because we have already consumed the close paren.
2263ec727ea7Spatrick     DS.SetRangeEnd(PrevTokLocation);
2264ec727ea7Spatrick     DS.Finish(Actions, Policy);
2265ec727ea7Spatrick     return;
2266ec727ea7Spatrick   }
2267ec727ea7Spatrick 
2268e5dd7070Spatrick   // builtin types
2269e5dd7070Spatrick   case tok::kw_short:
2270a9ac8606Spatrick     DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID,
2271a9ac8606Spatrick                         Policy);
2272e5dd7070Spatrick     break;
2273e5dd7070Spatrick   case tok::kw_long:
2274a9ac8606Spatrick     DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID,
2275a9ac8606Spatrick                         Policy);
2276e5dd7070Spatrick     break;
2277e5dd7070Spatrick   case tok::kw___int64:
2278a9ac8606Spatrick     DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc, PrevSpec, DiagID,
2279a9ac8606Spatrick                         Policy);
2280e5dd7070Spatrick     break;
2281e5dd7070Spatrick   case tok::kw_signed:
2282a9ac8606Spatrick     DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
2283e5dd7070Spatrick     break;
2284e5dd7070Spatrick   case tok::kw_unsigned:
2285a9ac8606Spatrick     DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID);
2286e5dd7070Spatrick     break;
2287e5dd7070Spatrick   case tok::kw_void:
2288e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
2289e5dd7070Spatrick     break;
2290*12c85518Srobert   case tok::kw_auto:
2291*12c85518Srobert     DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID, Policy);
2292*12c85518Srobert     break;
2293e5dd7070Spatrick   case tok::kw_char:
2294e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
2295e5dd7070Spatrick     break;
2296e5dd7070Spatrick   case tok::kw_int:
2297e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
2298e5dd7070Spatrick     break;
2299e5dd7070Spatrick   case tok::kw___int128:
2300e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
2301e5dd7070Spatrick     break;
2302ec727ea7Spatrick   case tok::kw___bf16:
2303ec727ea7Spatrick     DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy);
2304ec727ea7Spatrick     break;
2305e5dd7070Spatrick   case tok::kw_half:
2306e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
2307e5dd7070Spatrick     break;
2308e5dd7070Spatrick   case tok::kw_float:
2309e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
2310e5dd7070Spatrick     break;
2311e5dd7070Spatrick   case tok::kw_double:
2312e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
2313e5dd7070Spatrick     break;
2314e5dd7070Spatrick   case tok::kw__Float16:
2315e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2316e5dd7070Spatrick     break;
2317e5dd7070Spatrick   case tok::kw___float128:
2318e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2319e5dd7070Spatrick     break;
2320*12c85518Srobert   case tok::kw___ibm128:
2321*12c85518Srobert     DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec, DiagID, Policy);
2322*12c85518Srobert     break;
2323e5dd7070Spatrick   case tok::kw_wchar_t:
2324e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
2325e5dd7070Spatrick     break;
2326e5dd7070Spatrick   case tok::kw_char8_t:
2327e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2328e5dd7070Spatrick     break;
2329e5dd7070Spatrick   case tok::kw_char16_t:
2330e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
2331e5dd7070Spatrick     break;
2332e5dd7070Spatrick   case tok::kw_char32_t:
2333e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
2334e5dd7070Spatrick     break;
2335e5dd7070Spatrick   case tok::kw_bool:
2336e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
2337e5dd7070Spatrick     break;
2338e5dd7070Spatrick #define GENERIC_IMAGE_TYPE(ImgType, Id)                                        \
2339e5dd7070Spatrick   case tok::kw_##ImgType##_t:                                                  \
2340e5dd7070Spatrick     DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID,     \
2341e5dd7070Spatrick                        Policy);                                                \
2342e5dd7070Spatrick     break;
2343e5dd7070Spatrick #include "clang/Basic/OpenCLImageTypes.def"
2344e5dd7070Spatrick 
2345e5dd7070Spatrick   case tok::annot_decltype:
2346e5dd7070Spatrick   case tok::kw_decltype:
2347e5dd7070Spatrick     DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2348e5dd7070Spatrick     return DS.Finish(Actions, Policy);
2349e5dd7070Spatrick 
2350e5dd7070Spatrick   // GNU typeof support.
2351e5dd7070Spatrick   case tok::kw_typeof:
2352e5dd7070Spatrick     ParseTypeofSpecifier(DS);
2353e5dd7070Spatrick     DS.Finish(Actions, Policy);
2354e5dd7070Spatrick     return;
2355e5dd7070Spatrick   }
2356e5dd7070Spatrick   ConsumeAnyToken();
2357e5dd7070Spatrick   DS.SetRangeEnd(PrevTokLocation);
2358e5dd7070Spatrick   DS.Finish(Actions, Policy);
2359e5dd7070Spatrick }
2360e5dd7070Spatrick 
2361e5dd7070Spatrick /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2362e5dd7070Spatrick /// [dcl.name]), which is a non-empty sequence of type-specifiers,
2363e5dd7070Spatrick /// e.g., "const short int". Note that the DeclSpec is *not* finished
2364e5dd7070Spatrick /// by parsing the type-specifier-seq, because these sequences are
2365e5dd7070Spatrick /// typically followed by some form of declarator. Returns true and
2366e5dd7070Spatrick /// emits diagnostics if this is not a type-specifier-seq, false
2367e5dd7070Spatrick /// otherwise.
2368e5dd7070Spatrick ///
2369e5dd7070Spatrick ///   type-specifier-seq: [C++ 8.1]
2370e5dd7070Spatrick ///     type-specifier type-specifier-seq[opt]
2371e5dd7070Spatrick ///
ParseCXXTypeSpecifierSeq(DeclSpec & DS,DeclaratorContext Context)2372*12c85518Srobert bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS, DeclaratorContext Context) {
2373*12c85518Srobert   ParseSpecifierQualifierList(DS, AS_none,
2374*12c85518Srobert                               getDeclSpecContextFromDeclaratorContext(Context));
2375e5dd7070Spatrick   DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2376e5dd7070Spatrick   return false;
2377e5dd7070Spatrick }
2378e5dd7070Spatrick 
2379e5dd7070Spatrick /// Finish parsing a C++ unqualified-id that is a template-id of
2380e5dd7070Spatrick /// some form.
2381e5dd7070Spatrick ///
2382e5dd7070Spatrick /// This routine is invoked when a '<' is encountered after an identifier or
2383e5dd7070Spatrick /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2384e5dd7070Spatrick /// whether the unqualified-id is actually a template-id. This routine will
2385e5dd7070Spatrick /// then parse the template arguments and form the appropriate template-id to
2386e5dd7070Spatrick /// return to the caller.
2387e5dd7070Spatrick ///
2388e5dd7070Spatrick /// \param SS the nested-name-specifier that precedes this template-id, if
2389e5dd7070Spatrick /// we're actually parsing a qualified-id.
2390e5dd7070Spatrick ///
2391ec727ea7Spatrick /// \param ObjectType if this unqualified-id occurs within a member access
2392ec727ea7Spatrick /// expression, the type of the base object whose member is being accessed.
2393ec727ea7Spatrick ///
2394ec727ea7Spatrick /// \param ObjectHadErrors this unqualified-id occurs within a member access
2395ec727ea7Spatrick /// expression, indicates whether the original subexpressions had any errors.
2396ec727ea7Spatrick ///
2397e5dd7070Spatrick /// \param Name for constructor and destructor names, this is the actual
2398e5dd7070Spatrick /// identifier that may be a template-name.
2399e5dd7070Spatrick ///
2400e5dd7070Spatrick /// \param NameLoc the location of the class-name in a constructor or
2401e5dd7070Spatrick /// destructor.
2402e5dd7070Spatrick ///
2403e5dd7070Spatrick /// \param EnteringContext whether we're entering the scope of the
2404e5dd7070Spatrick /// nested-name-specifier.
2405e5dd7070Spatrick ///
2406e5dd7070Spatrick /// \param Id as input, describes the template-name or operator-function-id
2407e5dd7070Spatrick /// that precedes the '<'. If template arguments were parsed successfully,
2408e5dd7070Spatrick /// will be updated with the template-id.
2409e5dd7070Spatrick ///
2410e5dd7070Spatrick /// \param AssumeTemplateId When true, this routine will assume that the name
2411e5dd7070Spatrick /// refers to a template without performing name lookup to verify.
2412e5dd7070Spatrick ///
2413e5dd7070Spatrick /// \returns true if a parse error occurred, false otherwise.
ParseUnqualifiedIdTemplateId(CXXScopeSpec & SS,ParsedType ObjectType,bool ObjectHadErrors,SourceLocation TemplateKWLoc,IdentifierInfo * Name,SourceLocation NameLoc,bool EnteringContext,UnqualifiedId & Id,bool AssumeTemplateId)2414ec727ea7Spatrick bool Parser::ParseUnqualifiedIdTemplateId(
2415ec727ea7Spatrick     CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
2416ec727ea7Spatrick     SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc,
2417ec727ea7Spatrick     bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) {
2418e5dd7070Spatrick   assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2419e5dd7070Spatrick 
2420e5dd7070Spatrick   TemplateTy Template;
2421e5dd7070Spatrick   TemplateNameKind TNK = TNK_Non_template;
2422e5dd7070Spatrick   switch (Id.getKind()) {
2423e5dd7070Spatrick   case UnqualifiedIdKind::IK_Identifier:
2424e5dd7070Spatrick   case UnqualifiedIdKind::IK_OperatorFunctionId:
2425e5dd7070Spatrick   case UnqualifiedIdKind::IK_LiteralOperatorId:
2426e5dd7070Spatrick     if (AssumeTemplateId) {
2427e5dd7070Spatrick       // We defer the injected-class-name checks until we've found whether
2428e5dd7070Spatrick       // this template-id is used to form a nested-name-specifier or not.
2429ec727ea7Spatrick       TNK = Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Id,
2430ec727ea7Spatrick                                       ObjectType, EnteringContext, Template,
2431ec727ea7Spatrick                                       /*AllowInjectedClassName*/ true);
2432e5dd7070Spatrick     } else {
2433e5dd7070Spatrick       bool MemberOfUnknownSpecialization;
2434e5dd7070Spatrick       TNK = Actions.isTemplateName(getCurScope(), SS,
2435e5dd7070Spatrick                                    TemplateKWLoc.isValid(), Id,
2436e5dd7070Spatrick                                    ObjectType, EnteringContext, Template,
2437e5dd7070Spatrick                                    MemberOfUnknownSpecialization);
2438e5dd7070Spatrick       // If lookup found nothing but we're assuming that this is a template
2439e5dd7070Spatrick       // name, double-check that makes sense syntactically before committing
2440e5dd7070Spatrick       // to it.
2441e5dd7070Spatrick       if (TNK == TNK_Undeclared_template &&
2442e5dd7070Spatrick           isTemplateArgumentList(0) == TPResult::False)
2443e5dd7070Spatrick         return false;
2444e5dd7070Spatrick 
2445e5dd7070Spatrick       if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2446e5dd7070Spatrick           ObjectType && isTemplateArgumentList(0) == TPResult::True) {
2447ec727ea7Spatrick         // If we had errors before, ObjectType can be dependent even without any
2448ec727ea7Spatrick         // templates, do not report missing template keyword in that case.
2449ec727ea7Spatrick         if (!ObjectHadErrors) {
2450e5dd7070Spatrick           // We have something like t->getAs<T>(), where getAs is a
2451e5dd7070Spatrick           // member of an unknown specialization. However, this will only
2452e5dd7070Spatrick           // parse correctly as a template, so suggest the keyword 'template'
2453e5dd7070Spatrick           // before 'getAs' and treat this as a dependent template name.
2454e5dd7070Spatrick           std::string Name;
2455e5dd7070Spatrick           if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2456ec727ea7Spatrick             Name = std::string(Id.Identifier->getName());
2457e5dd7070Spatrick           else {
2458e5dd7070Spatrick             Name = "operator ";
2459e5dd7070Spatrick             if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
2460e5dd7070Spatrick               Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2461e5dd7070Spatrick             else
2462e5dd7070Spatrick               Name += Id.Identifier->getName();
2463e5dd7070Spatrick           }
2464e5dd7070Spatrick           Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2465e5dd7070Spatrick               << Name
2466e5dd7070Spatrick               << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2467ec727ea7Spatrick         }
2468ec727ea7Spatrick         TNK = Actions.ActOnTemplateName(
2469e5dd7070Spatrick             getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2470e5dd7070Spatrick             Template, /*AllowInjectedClassName*/ true);
2471ec727ea7Spatrick       } else if (TNK == TNK_Non_template) {
2472ec727ea7Spatrick         return false;
2473e5dd7070Spatrick       }
2474e5dd7070Spatrick     }
2475e5dd7070Spatrick     break;
2476e5dd7070Spatrick 
2477e5dd7070Spatrick   case UnqualifiedIdKind::IK_ConstructorName: {
2478e5dd7070Spatrick     UnqualifiedId TemplateName;
2479e5dd7070Spatrick     bool MemberOfUnknownSpecialization;
2480e5dd7070Spatrick     TemplateName.setIdentifier(Name, NameLoc);
2481e5dd7070Spatrick     TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2482e5dd7070Spatrick                                  TemplateName, ObjectType,
2483e5dd7070Spatrick                                  EnteringContext, Template,
2484e5dd7070Spatrick                                  MemberOfUnknownSpecialization);
2485ec727ea7Spatrick     if (TNK == TNK_Non_template)
2486ec727ea7Spatrick       return false;
2487e5dd7070Spatrick     break;
2488e5dd7070Spatrick   }
2489e5dd7070Spatrick 
2490e5dd7070Spatrick   case UnqualifiedIdKind::IK_DestructorName: {
2491e5dd7070Spatrick     UnqualifiedId TemplateName;
2492e5dd7070Spatrick     bool MemberOfUnknownSpecialization;
2493e5dd7070Spatrick     TemplateName.setIdentifier(Name, NameLoc);
2494e5dd7070Spatrick     if (ObjectType) {
2495ec727ea7Spatrick       TNK = Actions.ActOnTemplateName(
2496e5dd7070Spatrick           getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2497e5dd7070Spatrick           EnteringContext, Template, /*AllowInjectedClassName*/ true);
2498e5dd7070Spatrick     } else {
2499e5dd7070Spatrick       TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2500e5dd7070Spatrick                                    TemplateName, ObjectType,
2501e5dd7070Spatrick                                    EnteringContext, Template,
2502e5dd7070Spatrick                                    MemberOfUnknownSpecialization);
2503e5dd7070Spatrick 
2504e5dd7070Spatrick       if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2505e5dd7070Spatrick         Diag(NameLoc, diag::err_destructor_template_id)
2506e5dd7070Spatrick           << Name << SS.getRange();
2507ec727ea7Spatrick         // Carry on to parse the template arguments before bailing out.
2508e5dd7070Spatrick       }
2509e5dd7070Spatrick     }
2510e5dd7070Spatrick     break;
2511e5dd7070Spatrick   }
2512e5dd7070Spatrick 
2513e5dd7070Spatrick   default:
2514e5dd7070Spatrick     return false;
2515e5dd7070Spatrick   }
2516e5dd7070Spatrick 
2517e5dd7070Spatrick   // Parse the enclosed template argument list.
2518e5dd7070Spatrick   SourceLocation LAngleLoc, RAngleLoc;
2519e5dd7070Spatrick   TemplateArgList TemplateArgs;
2520*12c85518Srobert   if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs, RAngleLoc,
2521*12c85518Srobert                                        Template))
2522e5dd7070Spatrick     return true;
2523e5dd7070Spatrick 
2524ec727ea7Spatrick   // If this is a non-template, we already issued a diagnostic.
2525ec727ea7Spatrick   if (TNK == TNK_Non_template)
2526ec727ea7Spatrick     return true;
2527ec727ea7Spatrick 
2528e5dd7070Spatrick   if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2529e5dd7070Spatrick       Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2530e5dd7070Spatrick       Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
2531e5dd7070Spatrick     // Form a parsed representation of the template-id to be stored in the
2532e5dd7070Spatrick     // UnqualifiedId.
2533e5dd7070Spatrick 
2534e5dd7070Spatrick     // FIXME: Store name for literal operator too.
2535e5dd7070Spatrick     IdentifierInfo *TemplateII =
2536e5dd7070Spatrick         Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2537e5dd7070Spatrick                                                          : nullptr;
2538e5dd7070Spatrick     OverloadedOperatorKind OpKind =
2539e5dd7070Spatrick         Id.getKind() == UnqualifiedIdKind::IK_Identifier
2540e5dd7070Spatrick             ? OO_None
2541e5dd7070Spatrick             : Id.OperatorFunctionId.Operator;
2542e5dd7070Spatrick 
2543e5dd7070Spatrick     TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2544e5dd7070Spatrick         TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2545ec727ea7Spatrick         LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, TemplateIds);
2546e5dd7070Spatrick 
2547e5dd7070Spatrick     Id.setTemplateId(TemplateId);
2548e5dd7070Spatrick     return false;
2549e5dd7070Spatrick   }
2550e5dd7070Spatrick 
2551e5dd7070Spatrick   // Bundle the template arguments together.
2552e5dd7070Spatrick   ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2553e5dd7070Spatrick 
2554e5dd7070Spatrick   // Constructor and destructor names.
2555e5dd7070Spatrick   TypeResult Type = Actions.ActOnTemplateIdType(
2556e5dd7070Spatrick       getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2557e5dd7070Spatrick       TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
2558e5dd7070Spatrick   if (Type.isInvalid())
2559e5dd7070Spatrick     return true;
2560e5dd7070Spatrick 
2561e5dd7070Spatrick   if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
2562e5dd7070Spatrick     Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2563e5dd7070Spatrick   else
2564e5dd7070Spatrick     Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2565e5dd7070Spatrick 
2566e5dd7070Spatrick   return false;
2567e5dd7070Spatrick }
2568e5dd7070Spatrick 
2569e5dd7070Spatrick /// Parse an operator-function-id or conversion-function-id as part
2570e5dd7070Spatrick /// of a C++ unqualified-id.
2571e5dd7070Spatrick ///
2572e5dd7070Spatrick /// This routine is responsible only for parsing the operator-function-id or
2573e5dd7070Spatrick /// conversion-function-id; it does not handle template arguments in any way.
2574e5dd7070Spatrick ///
2575e5dd7070Spatrick /// \code
2576e5dd7070Spatrick ///       operator-function-id: [C++ 13.5]
2577e5dd7070Spatrick ///         'operator' operator
2578e5dd7070Spatrick ///
2579e5dd7070Spatrick ///       operator: one of
2580e5dd7070Spatrick ///            new   delete  new[]   delete[]
2581e5dd7070Spatrick ///            +     -    *  /    %  ^    &   |   ~
2582e5dd7070Spatrick ///            !     =    <  >    += -=   *=  /=  %=
2583e5dd7070Spatrick ///            ^=    &=   |= <<   >> >>= <<=  ==  !=
2584e5dd7070Spatrick ///            <=    >=   && ||   ++ --   ,   ->* ->
2585e5dd7070Spatrick ///            ()    []   <=>
2586e5dd7070Spatrick ///
2587e5dd7070Spatrick ///       conversion-function-id: [C++ 12.3.2]
2588e5dd7070Spatrick ///         operator conversion-type-id
2589e5dd7070Spatrick ///
2590e5dd7070Spatrick ///       conversion-type-id:
2591e5dd7070Spatrick ///         type-specifier-seq conversion-declarator[opt]
2592e5dd7070Spatrick ///
2593e5dd7070Spatrick ///       conversion-declarator:
2594e5dd7070Spatrick ///         ptr-operator conversion-declarator[opt]
2595e5dd7070Spatrick /// \endcode
2596e5dd7070Spatrick ///
2597e5dd7070Spatrick /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2598e5dd7070Spatrick /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2599e5dd7070Spatrick ///
2600e5dd7070Spatrick /// \param EnteringContext whether we are entering the scope of the
2601e5dd7070Spatrick /// nested-name-specifier.
2602e5dd7070Spatrick ///
2603e5dd7070Spatrick /// \param ObjectType if this unqualified-id occurs within a member access
2604e5dd7070Spatrick /// expression, the type of the base object whose member is being accessed.
2605e5dd7070Spatrick ///
2606e5dd7070Spatrick /// \param Result on a successful parse, contains the parsed unqualified-id.
2607e5dd7070Spatrick ///
2608e5dd7070Spatrick /// \returns true if parsing fails, false otherwise.
ParseUnqualifiedIdOperator(CXXScopeSpec & SS,bool EnteringContext,ParsedType ObjectType,UnqualifiedId & Result)2609e5dd7070Spatrick bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2610e5dd7070Spatrick                                         ParsedType ObjectType,
2611e5dd7070Spatrick                                         UnqualifiedId &Result) {
2612e5dd7070Spatrick   assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2613e5dd7070Spatrick 
2614e5dd7070Spatrick   // Consume the 'operator' keyword.
2615e5dd7070Spatrick   SourceLocation KeywordLoc = ConsumeToken();
2616e5dd7070Spatrick 
2617e5dd7070Spatrick   // Determine what kind of operator name we have.
2618e5dd7070Spatrick   unsigned SymbolIdx = 0;
2619e5dd7070Spatrick   SourceLocation SymbolLocations[3];
2620e5dd7070Spatrick   OverloadedOperatorKind Op = OO_None;
2621e5dd7070Spatrick   switch (Tok.getKind()) {
2622e5dd7070Spatrick     case tok::kw_new:
2623e5dd7070Spatrick     case tok::kw_delete: {
2624e5dd7070Spatrick       bool isNew = Tok.getKind() == tok::kw_new;
2625e5dd7070Spatrick       // Consume the 'new' or 'delete'.
2626e5dd7070Spatrick       SymbolLocations[SymbolIdx++] = ConsumeToken();
2627e5dd7070Spatrick       // Check for array new/delete.
2628e5dd7070Spatrick       if (Tok.is(tok::l_square) &&
2629e5dd7070Spatrick           (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2630e5dd7070Spatrick         // Consume the '[' and ']'.
2631e5dd7070Spatrick         BalancedDelimiterTracker T(*this, tok::l_square);
2632e5dd7070Spatrick         T.consumeOpen();
2633e5dd7070Spatrick         T.consumeClose();
2634e5dd7070Spatrick         if (T.getCloseLocation().isInvalid())
2635e5dd7070Spatrick           return true;
2636e5dd7070Spatrick 
2637e5dd7070Spatrick         SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2638e5dd7070Spatrick         SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2639e5dd7070Spatrick         Op = isNew? OO_Array_New : OO_Array_Delete;
2640e5dd7070Spatrick       } else {
2641e5dd7070Spatrick         Op = isNew? OO_New : OO_Delete;
2642e5dd7070Spatrick       }
2643e5dd7070Spatrick       break;
2644e5dd7070Spatrick     }
2645e5dd7070Spatrick 
2646e5dd7070Spatrick #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2647e5dd7070Spatrick     case tok::Token:                                                     \
2648e5dd7070Spatrick       SymbolLocations[SymbolIdx++] = ConsumeToken();                     \
2649e5dd7070Spatrick       Op = OO_##Name;                                                    \
2650e5dd7070Spatrick       break;
2651e5dd7070Spatrick #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2652e5dd7070Spatrick #include "clang/Basic/OperatorKinds.def"
2653e5dd7070Spatrick 
2654e5dd7070Spatrick     case tok::l_paren: {
2655e5dd7070Spatrick       // Consume the '(' and ')'.
2656e5dd7070Spatrick       BalancedDelimiterTracker T(*this, tok::l_paren);
2657e5dd7070Spatrick       T.consumeOpen();
2658e5dd7070Spatrick       T.consumeClose();
2659e5dd7070Spatrick       if (T.getCloseLocation().isInvalid())
2660e5dd7070Spatrick         return true;
2661e5dd7070Spatrick 
2662e5dd7070Spatrick       SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2663e5dd7070Spatrick       SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2664e5dd7070Spatrick       Op = OO_Call;
2665e5dd7070Spatrick       break;
2666e5dd7070Spatrick     }
2667e5dd7070Spatrick 
2668e5dd7070Spatrick     case tok::l_square: {
2669e5dd7070Spatrick       // Consume the '[' and ']'.
2670e5dd7070Spatrick       BalancedDelimiterTracker T(*this, tok::l_square);
2671e5dd7070Spatrick       T.consumeOpen();
2672e5dd7070Spatrick       T.consumeClose();
2673e5dd7070Spatrick       if (T.getCloseLocation().isInvalid())
2674e5dd7070Spatrick         return true;
2675e5dd7070Spatrick 
2676e5dd7070Spatrick       SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2677e5dd7070Spatrick       SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2678e5dd7070Spatrick       Op = OO_Subscript;
2679e5dd7070Spatrick       break;
2680e5dd7070Spatrick     }
2681e5dd7070Spatrick 
2682e5dd7070Spatrick     case tok::code_completion: {
2683a9ac8606Spatrick       // Don't try to parse any further.
2684a9ac8606Spatrick       cutOffParsing();
2685e5dd7070Spatrick       // Code completion for the operator name.
2686e5dd7070Spatrick       Actions.CodeCompleteOperatorName(getCurScope());
2687e5dd7070Spatrick       return true;
2688e5dd7070Spatrick     }
2689e5dd7070Spatrick 
2690e5dd7070Spatrick     default:
2691e5dd7070Spatrick       break;
2692e5dd7070Spatrick   }
2693e5dd7070Spatrick 
2694e5dd7070Spatrick   if (Op != OO_None) {
2695e5dd7070Spatrick     // We have parsed an operator-function-id.
2696e5dd7070Spatrick     Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2697e5dd7070Spatrick     return false;
2698e5dd7070Spatrick   }
2699e5dd7070Spatrick 
2700e5dd7070Spatrick   // Parse a literal-operator-id.
2701e5dd7070Spatrick   //
2702e5dd7070Spatrick   //   literal-operator-id: C++11 [over.literal]
2703e5dd7070Spatrick   //     operator string-literal identifier
2704e5dd7070Spatrick   //     operator user-defined-string-literal
2705e5dd7070Spatrick 
2706e5dd7070Spatrick   if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2707e5dd7070Spatrick     Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2708e5dd7070Spatrick 
2709e5dd7070Spatrick     SourceLocation DiagLoc;
2710e5dd7070Spatrick     unsigned DiagId = 0;
2711e5dd7070Spatrick 
2712e5dd7070Spatrick     // We're past translation phase 6, so perform string literal concatenation
2713e5dd7070Spatrick     // before checking for "".
2714e5dd7070Spatrick     SmallVector<Token, 4> Toks;
2715e5dd7070Spatrick     SmallVector<SourceLocation, 4> TokLocs;
2716e5dd7070Spatrick     while (isTokenStringLiteral()) {
2717e5dd7070Spatrick       if (!Tok.is(tok::string_literal) && !DiagId) {
2718e5dd7070Spatrick         // C++11 [over.literal]p1:
2719e5dd7070Spatrick         //   The string-literal or user-defined-string-literal in a
2720e5dd7070Spatrick         //   literal-operator-id shall have no encoding-prefix [...].
2721e5dd7070Spatrick         DiagLoc = Tok.getLocation();
2722e5dd7070Spatrick         DiagId = diag::err_literal_operator_string_prefix;
2723e5dd7070Spatrick       }
2724e5dd7070Spatrick       Toks.push_back(Tok);
2725e5dd7070Spatrick       TokLocs.push_back(ConsumeStringToken());
2726e5dd7070Spatrick     }
2727e5dd7070Spatrick 
2728e5dd7070Spatrick     StringLiteralParser Literal(Toks, PP);
2729e5dd7070Spatrick     if (Literal.hadError)
2730e5dd7070Spatrick       return true;
2731e5dd7070Spatrick 
2732e5dd7070Spatrick     // Grab the literal operator's suffix, which will be either the next token
2733e5dd7070Spatrick     // or a ud-suffix from the string literal.
2734a9ac8606Spatrick     bool IsUDSuffix = !Literal.getUDSuffix().empty();
2735e5dd7070Spatrick     IdentifierInfo *II = nullptr;
2736e5dd7070Spatrick     SourceLocation SuffixLoc;
2737a9ac8606Spatrick     if (IsUDSuffix) {
2738e5dd7070Spatrick       II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2739e5dd7070Spatrick       SuffixLoc =
2740e5dd7070Spatrick         Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2741e5dd7070Spatrick                                        Literal.getUDSuffixOffset(),
2742e5dd7070Spatrick                                        PP.getSourceManager(), getLangOpts());
2743e5dd7070Spatrick     } else if (Tok.is(tok::identifier)) {
2744e5dd7070Spatrick       II = Tok.getIdentifierInfo();
2745e5dd7070Spatrick       SuffixLoc = ConsumeToken();
2746e5dd7070Spatrick       TokLocs.push_back(SuffixLoc);
2747e5dd7070Spatrick     } else {
2748e5dd7070Spatrick       Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2749e5dd7070Spatrick       return true;
2750e5dd7070Spatrick     }
2751e5dd7070Spatrick 
2752e5dd7070Spatrick     // The string literal must be empty.
2753e5dd7070Spatrick     if (!Literal.GetString().empty() || Literal.Pascal) {
2754e5dd7070Spatrick       // C++11 [over.literal]p1:
2755e5dd7070Spatrick       //   The string-literal or user-defined-string-literal in a
2756e5dd7070Spatrick       //   literal-operator-id shall [...] contain no characters
2757e5dd7070Spatrick       //   other than the implicit terminating '\0'.
2758e5dd7070Spatrick       DiagLoc = TokLocs.front();
2759e5dd7070Spatrick       DiagId = diag::err_literal_operator_string_not_empty;
2760e5dd7070Spatrick     }
2761e5dd7070Spatrick 
2762e5dd7070Spatrick     if (DiagId) {
2763e5dd7070Spatrick       // This isn't a valid literal-operator-id, but we think we know
2764e5dd7070Spatrick       // what the user meant. Tell them what they should have written.
2765e5dd7070Spatrick       SmallString<32> Str;
2766e5dd7070Spatrick       Str += "\"\"";
2767e5dd7070Spatrick       Str += II->getName();
2768e5dd7070Spatrick       Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2769e5dd7070Spatrick           SourceRange(TokLocs.front(), TokLocs.back()), Str);
2770e5dd7070Spatrick     }
2771e5dd7070Spatrick 
2772e5dd7070Spatrick     Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2773e5dd7070Spatrick 
2774a9ac8606Spatrick     return Actions.checkLiteralOperatorId(SS, Result, IsUDSuffix);
2775e5dd7070Spatrick   }
2776e5dd7070Spatrick 
2777e5dd7070Spatrick   // Parse a conversion-function-id.
2778e5dd7070Spatrick   //
2779e5dd7070Spatrick   //   conversion-function-id: [C++ 12.3.2]
2780e5dd7070Spatrick   //     operator conversion-type-id
2781e5dd7070Spatrick   //
2782e5dd7070Spatrick   //   conversion-type-id:
2783e5dd7070Spatrick   //     type-specifier-seq conversion-declarator[opt]
2784e5dd7070Spatrick   //
2785e5dd7070Spatrick   //   conversion-declarator:
2786e5dd7070Spatrick   //     ptr-operator conversion-declarator[opt]
2787e5dd7070Spatrick 
2788e5dd7070Spatrick   // Parse the type-specifier-seq.
2789e5dd7070Spatrick   DeclSpec DS(AttrFactory);
2790*12c85518Srobert   if (ParseCXXTypeSpecifierSeq(
2791*12c85518Srobert           DS, DeclaratorContext::ConversionId)) // FIXME: ObjectType?
2792e5dd7070Spatrick     return true;
2793e5dd7070Spatrick 
2794e5dd7070Spatrick   // Parse the conversion-declarator, which is merely a sequence of
2795e5dd7070Spatrick   // ptr-operators.
2796*12c85518Srobert   Declarator D(DS, ParsedAttributesView::none(),
2797*12c85518Srobert                DeclaratorContext::ConversionId);
2798e5dd7070Spatrick   ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2799e5dd7070Spatrick 
2800e5dd7070Spatrick   // Finish up the type.
2801e5dd7070Spatrick   TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2802e5dd7070Spatrick   if (Ty.isInvalid())
2803e5dd7070Spatrick     return true;
2804e5dd7070Spatrick 
2805e5dd7070Spatrick   // Note that this is a conversion-function-id.
2806e5dd7070Spatrick   Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2807e5dd7070Spatrick                                  D.getSourceRange().getEnd());
2808e5dd7070Spatrick   return false;
2809e5dd7070Spatrick }
2810e5dd7070Spatrick 
2811e5dd7070Spatrick /// Parse a C++ unqualified-id (or a C identifier), which describes the
2812e5dd7070Spatrick /// name of an entity.
2813e5dd7070Spatrick ///
2814e5dd7070Spatrick /// \code
2815e5dd7070Spatrick ///       unqualified-id: [C++ expr.prim.general]
2816e5dd7070Spatrick ///         identifier
2817e5dd7070Spatrick ///         operator-function-id
2818e5dd7070Spatrick ///         conversion-function-id
2819e5dd7070Spatrick /// [C++0x] literal-operator-id [TODO]
2820e5dd7070Spatrick ///         ~ class-name
2821e5dd7070Spatrick ///         template-id
2822e5dd7070Spatrick ///
2823e5dd7070Spatrick /// \endcode
2824e5dd7070Spatrick ///
2825e5dd7070Spatrick /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2826e5dd7070Spatrick /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2827e5dd7070Spatrick ///
2828ec727ea7Spatrick /// \param ObjectType if this unqualified-id occurs within a member access
2829ec727ea7Spatrick /// expression, the type of the base object whose member is being accessed.
2830ec727ea7Spatrick ///
2831ec727ea7Spatrick /// \param ObjectHadErrors if this unqualified-id occurs within a member access
2832ec727ea7Spatrick /// expression, indicates whether the original subexpressions had any errors.
2833ec727ea7Spatrick /// When true, diagnostics for missing 'template' keyword will be supressed.
2834ec727ea7Spatrick ///
2835e5dd7070Spatrick /// \param EnteringContext whether we are entering the scope of the
2836e5dd7070Spatrick /// nested-name-specifier.
2837e5dd7070Spatrick ///
2838e5dd7070Spatrick /// \param AllowDestructorName whether we allow parsing of a destructor name.
2839e5dd7070Spatrick ///
2840e5dd7070Spatrick /// \param AllowConstructorName whether we allow parsing a constructor name.
2841e5dd7070Spatrick ///
2842e5dd7070Spatrick /// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2843e5dd7070Spatrick ///
2844e5dd7070Spatrick /// \param Result on a successful parse, contains the parsed unqualified-id.
2845e5dd7070Spatrick ///
2846e5dd7070Spatrick /// \returns true if parsing fails, false otherwise.
ParseUnqualifiedId(CXXScopeSpec & SS,ParsedType ObjectType,bool ObjectHadErrors,bool EnteringContext,bool AllowDestructorName,bool AllowConstructorName,bool AllowDeductionGuide,SourceLocation * TemplateKWLoc,UnqualifiedId & Result)2847ec727ea7Spatrick bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
2848ec727ea7Spatrick                                 bool ObjectHadErrors, bool EnteringContext,
2849e5dd7070Spatrick                                 bool AllowDestructorName,
2850e5dd7070Spatrick                                 bool AllowConstructorName,
2851e5dd7070Spatrick                                 bool AllowDeductionGuide,
2852e5dd7070Spatrick                                 SourceLocation *TemplateKWLoc,
2853e5dd7070Spatrick                                 UnqualifiedId &Result) {
2854e5dd7070Spatrick   if (TemplateKWLoc)
2855e5dd7070Spatrick     *TemplateKWLoc = SourceLocation();
2856e5dd7070Spatrick 
2857e5dd7070Spatrick   // Handle 'A::template B'. This is for template-ids which have not
2858e5dd7070Spatrick   // already been annotated by ParseOptionalCXXScopeSpecifier().
2859e5dd7070Spatrick   bool TemplateSpecified = false;
2860e5dd7070Spatrick   if (Tok.is(tok::kw_template)) {
2861e5dd7070Spatrick     if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2862e5dd7070Spatrick       TemplateSpecified = true;
2863e5dd7070Spatrick       *TemplateKWLoc = ConsumeToken();
2864e5dd7070Spatrick     } else {
2865e5dd7070Spatrick       SourceLocation TemplateLoc = ConsumeToken();
2866e5dd7070Spatrick       Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2867e5dd7070Spatrick         << FixItHint::CreateRemoval(TemplateLoc);
2868e5dd7070Spatrick     }
2869e5dd7070Spatrick   }
2870e5dd7070Spatrick 
2871e5dd7070Spatrick   // unqualified-id:
2872e5dd7070Spatrick   //   identifier
2873e5dd7070Spatrick   //   template-id (when it hasn't already been annotated)
2874e5dd7070Spatrick   if (Tok.is(tok::identifier)) {
2875*12c85518Srobert   ParseIdentifier:
2876e5dd7070Spatrick     // Consume the identifier.
2877e5dd7070Spatrick     IdentifierInfo *Id = Tok.getIdentifierInfo();
2878e5dd7070Spatrick     SourceLocation IdLoc = ConsumeToken();
2879e5dd7070Spatrick 
2880e5dd7070Spatrick     if (!getLangOpts().CPlusPlus) {
2881e5dd7070Spatrick       // If we're not in C++, only identifiers matter. Record the
2882e5dd7070Spatrick       // identifier and return.
2883e5dd7070Spatrick       Result.setIdentifier(Id, IdLoc);
2884e5dd7070Spatrick       return false;
2885e5dd7070Spatrick     }
2886e5dd7070Spatrick 
2887e5dd7070Spatrick     ParsedTemplateTy TemplateName;
2888e5dd7070Spatrick     if (AllowConstructorName &&
2889e5dd7070Spatrick         Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2890e5dd7070Spatrick       // We have parsed a constructor name.
2891e5dd7070Spatrick       ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2892e5dd7070Spatrick                                                  EnteringContext);
2893e5dd7070Spatrick       if (!Ty)
2894e5dd7070Spatrick         return true;
2895e5dd7070Spatrick       Result.setConstructorName(Ty, IdLoc, IdLoc);
2896e5dd7070Spatrick     } else if (getLangOpts().CPlusPlus17 &&
2897e5dd7070Spatrick                AllowDeductionGuide && SS.isEmpty() &&
2898e5dd7070Spatrick                Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2899e5dd7070Spatrick                                             &TemplateName)) {
2900e5dd7070Spatrick       // We have parsed a template-name naming a deduction guide.
2901e5dd7070Spatrick       Result.setDeductionGuideName(TemplateName, IdLoc);
2902e5dd7070Spatrick     } else {
2903e5dd7070Spatrick       // We have parsed an identifier.
2904e5dd7070Spatrick       Result.setIdentifier(Id, IdLoc);
2905e5dd7070Spatrick     }
2906e5dd7070Spatrick 
2907e5dd7070Spatrick     // If the next token is a '<', we may have a template.
2908e5dd7070Spatrick     TemplateTy Template;
2909e5dd7070Spatrick     if (Tok.is(tok::less))
2910e5dd7070Spatrick       return ParseUnqualifiedIdTemplateId(
2911ec727ea7Spatrick           SS, ObjectType, ObjectHadErrors,
2912ec727ea7Spatrick           TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2913ec727ea7Spatrick           EnteringContext, Result, TemplateSpecified);
2914e5dd7070Spatrick     else if (TemplateSpecified &&
2915ec727ea7Spatrick              Actions.ActOnTemplateName(
2916e5dd7070Spatrick                  getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2917e5dd7070Spatrick                  EnteringContext, Template,
2918e5dd7070Spatrick                  /*AllowInjectedClassName*/ true) == TNK_Non_template)
2919e5dd7070Spatrick       return true;
2920e5dd7070Spatrick 
2921e5dd7070Spatrick     return false;
2922e5dd7070Spatrick   }
2923e5dd7070Spatrick 
2924e5dd7070Spatrick   // unqualified-id:
2925e5dd7070Spatrick   //   template-id (already parsed and annotated)
2926e5dd7070Spatrick   if (Tok.is(tok::annot_template_id)) {
2927e5dd7070Spatrick     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2928e5dd7070Spatrick 
2929ec727ea7Spatrick     // FIXME: Consider passing invalid template-ids on to callers; they may
2930ec727ea7Spatrick     // be able to recover better than we can.
2931ec727ea7Spatrick     if (TemplateId->isInvalid()) {
2932ec727ea7Spatrick       ConsumeAnnotationToken();
2933ec727ea7Spatrick       return true;
2934ec727ea7Spatrick     }
2935ec727ea7Spatrick 
2936e5dd7070Spatrick     // If the template-name names the current class, then this is a constructor
2937e5dd7070Spatrick     if (AllowConstructorName && TemplateId->Name &&
2938e5dd7070Spatrick         Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2939e5dd7070Spatrick       if (SS.isSet()) {
2940e5dd7070Spatrick         // C++ [class.qual]p2 specifies that a qualified template-name
2941e5dd7070Spatrick         // is taken as the constructor name where a constructor can be
2942e5dd7070Spatrick         // declared. Thus, the template arguments are extraneous, so
2943e5dd7070Spatrick         // complain about them and remove them entirely.
2944e5dd7070Spatrick         Diag(TemplateId->TemplateNameLoc,
2945e5dd7070Spatrick              diag::err_out_of_line_constructor_template_id)
2946e5dd7070Spatrick           << TemplateId->Name
2947e5dd7070Spatrick           << FixItHint::CreateRemoval(
2948e5dd7070Spatrick                     SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2949e5dd7070Spatrick         ParsedType Ty = Actions.getConstructorName(
2950e5dd7070Spatrick             *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2951e5dd7070Spatrick             EnteringContext);
2952e5dd7070Spatrick         if (!Ty)
2953e5dd7070Spatrick           return true;
2954e5dd7070Spatrick         Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2955e5dd7070Spatrick                                   TemplateId->RAngleLoc);
2956e5dd7070Spatrick         ConsumeAnnotationToken();
2957e5dd7070Spatrick         return false;
2958e5dd7070Spatrick       }
2959e5dd7070Spatrick 
2960e5dd7070Spatrick       Result.setConstructorTemplateId(TemplateId);
2961e5dd7070Spatrick       ConsumeAnnotationToken();
2962e5dd7070Spatrick       return false;
2963e5dd7070Spatrick     }
2964e5dd7070Spatrick 
2965e5dd7070Spatrick     // We have already parsed a template-id; consume the annotation token as
2966e5dd7070Spatrick     // our unqualified-id.
2967e5dd7070Spatrick     Result.setTemplateId(TemplateId);
2968e5dd7070Spatrick     SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2969e5dd7070Spatrick     if (TemplateLoc.isValid()) {
2970e5dd7070Spatrick       if (TemplateKWLoc && (ObjectType || SS.isSet()))
2971e5dd7070Spatrick         *TemplateKWLoc = TemplateLoc;
2972e5dd7070Spatrick       else
2973e5dd7070Spatrick         Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2974e5dd7070Spatrick             << FixItHint::CreateRemoval(TemplateLoc);
2975e5dd7070Spatrick     }
2976e5dd7070Spatrick     ConsumeAnnotationToken();
2977e5dd7070Spatrick     return false;
2978e5dd7070Spatrick   }
2979e5dd7070Spatrick 
2980e5dd7070Spatrick   // unqualified-id:
2981e5dd7070Spatrick   //   operator-function-id
2982e5dd7070Spatrick   //   conversion-function-id
2983e5dd7070Spatrick   if (Tok.is(tok::kw_operator)) {
2984e5dd7070Spatrick     if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2985e5dd7070Spatrick       return true;
2986e5dd7070Spatrick 
2987e5dd7070Spatrick     // If we have an operator-function-id or a literal-operator-id and the next
2988e5dd7070Spatrick     // token is a '<', we may have a
2989e5dd7070Spatrick     //
2990e5dd7070Spatrick     //   template-id:
2991e5dd7070Spatrick     //     operator-function-id < template-argument-list[opt] >
2992e5dd7070Spatrick     TemplateTy Template;
2993e5dd7070Spatrick     if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2994e5dd7070Spatrick          Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
2995e5dd7070Spatrick         Tok.is(tok::less))
2996e5dd7070Spatrick       return ParseUnqualifiedIdTemplateId(
2997ec727ea7Spatrick           SS, ObjectType, ObjectHadErrors,
2998ec727ea7Spatrick           TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2999ec727ea7Spatrick           SourceLocation(), EnteringContext, Result, TemplateSpecified);
3000e5dd7070Spatrick     else if (TemplateSpecified &&
3001ec727ea7Spatrick              Actions.ActOnTemplateName(
3002e5dd7070Spatrick                  getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
3003e5dd7070Spatrick                  EnteringContext, Template,
3004e5dd7070Spatrick                  /*AllowInjectedClassName*/ true) == TNK_Non_template)
3005e5dd7070Spatrick       return true;
3006e5dd7070Spatrick 
3007e5dd7070Spatrick     return false;
3008e5dd7070Spatrick   }
3009e5dd7070Spatrick 
3010e5dd7070Spatrick   if (getLangOpts().CPlusPlus &&
3011e5dd7070Spatrick       (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
3012e5dd7070Spatrick     // C++ [expr.unary.op]p10:
3013e5dd7070Spatrick     //   There is an ambiguity in the unary-expression ~X(), where X is a
3014e5dd7070Spatrick     //   class-name. The ambiguity is resolved in favor of treating ~ as a
3015e5dd7070Spatrick     //    unary complement rather than treating ~X as referring to a destructor.
3016e5dd7070Spatrick 
3017e5dd7070Spatrick     // Parse the '~'.
3018e5dd7070Spatrick     SourceLocation TildeLoc = ConsumeToken();
3019e5dd7070Spatrick 
3020ec727ea7Spatrick     if (TemplateSpecified) {
3021ec727ea7Spatrick       // C++ [temp.names]p3:
3022ec727ea7Spatrick       //   A name prefixed by the keyword template shall be a template-id [...]
3023ec727ea7Spatrick       //
3024ec727ea7Spatrick       // A template-id cannot begin with a '~' token. This would never work
3025ec727ea7Spatrick       // anyway: x.~A<int>() would specify that the destructor is a template,
3026ec727ea7Spatrick       // not that 'A' is a template.
3027ec727ea7Spatrick       //
3028ec727ea7Spatrick       // FIXME: Suggest replacing the attempted destructor name with a correct
3029ec727ea7Spatrick       // destructor name and recover. (This is not trivial if this would become
3030ec727ea7Spatrick       // a pseudo-destructor name).
3031ec727ea7Spatrick       Diag(*TemplateKWLoc, diag::err_unexpected_template_in_destructor_name)
3032ec727ea7Spatrick         << Tok.getLocation();
3033ec727ea7Spatrick       return true;
3034ec727ea7Spatrick     }
3035ec727ea7Spatrick 
3036e5dd7070Spatrick     if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
3037e5dd7070Spatrick       DeclSpec DS(AttrFactory);
3038e5dd7070Spatrick       SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
3039e5dd7070Spatrick       if (ParsedType Type =
3040e5dd7070Spatrick               Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
3041e5dd7070Spatrick         Result.setDestructorName(TildeLoc, Type, EndLoc);
3042e5dd7070Spatrick         return false;
3043e5dd7070Spatrick       }
3044e5dd7070Spatrick       return true;
3045e5dd7070Spatrick     }
3046e5dd7070Spatrick 
3047e5dd7070Spatrick     // Parse the class-name.
3048e5dd7070Spatrick     if (Tok.isNot(tok::identifier)) {
3049e5dd7070Spatrick       Diag(Tok, diag::err_destructor_tilde_identifier);
3050e5dd7070Spatrick       return true;
3051e5dd7070Spatrick     }
3052e5dd7070Spatrick 
3053e5dd7070Spatrick     // If the user wrote ~T::T, correct it to T::~T.
3054e5dd7070Spatrick     DeclaratorScopeObj DeclScopeObj(*this, SS);
3055ec727ea7Spatrick     if (NextToken().is(tok::coloncolon)) {
3056e5dd7070Spatrick       // Don't let ParseOptionalCXXScopeSpecifier() "correct"
3057e5dd7070Spatrick       // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
3058e5dd7070Spatrick       // it will confuse this recovery logic.
3059e5dd7070Spatrick       ColonProtectionRAIIObject ColonRAII(*this, false);
3060e5dd7070Spatrick 
3061e5dd7070Spatrick       if (SS.isSet()) {
3062e5dd7070Spatrick         AnnotateScopeToken(SS, /*NewAnnotation*/true);
3063e5dd7070Spatrick         SS.clear();
3064e5dd7070Spatrick       }
3065ec727ea7Spatrick       if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors,
3066ec727ea7Spatrick                                          EnteringContext))
3067e5dd7070Spatrick         return true;
3068e5dd7070Spatrick       if (SS.isNotEmpty())
3069e5dd7070Spatrick         ObjectType = nullptr;
3070e5dd7070Spatrick       if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
3071e5dd7070Spatrick           !SS.isSet()) {
3072e5dd7070Spatrick         Diag(TildeLoc, diag::err_destructor_tilde_scope);
3073e5dd7070Spatrick         return true;
3074e5dd7070Spatrick       }
3075e5dd7070Spatrick 
3076e5dd7070Spatrick       // Recover as if the tilde had been written before the identifier.
3077e5dd7070Spatrick       Diag(TildeLoc, diag::err_destructor_tilde_scope)
3078e5dd7070Spatrick         << FixItHint::CreateRemoval(TildeLoc)
3079e5dd7070Spatrick         << FixItHint::CreateInsertion(Tok.getLocation(), "~");
3080e5dd7070Spatrick 
3081e5dd7070Spatrick       // Temporarily enter the scope for the rest of this function.
3082e5dd7070Spatrick       if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3083e5dd7070Spatrick         DeclScopeObj.EnterDeclaratorScope();
3084e5dd7070Spatrick     }
3085e5dd7070Spatrick 
3086e5dd7070Spatrick     // Parse the class-name (or template-name in a simple-template-id).
3087e5dd7070Spatrick     IdentifierInfo *ClassName = Tok.getIdentifierInfo();
3088e5dd7070Spatrick     SourceLocation ClassNameLoc = ConsumeToken();
3089e5dd7070Spatrick 
3090e5dd7070Spatrick     if (Tok.is(tok::less)) {
3091e5dd7070Spatrick       Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
3092e5dd7070Spatrick       return ParseUnqualifiedIdTemplateId(
3093ec727ea7Spatrick           SS, ObjectType, ObjectHadErrors,
3094ec727ea7Spatrick           TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
3095ec727ea7Spatrick           ClassNameLoc, EnteringContext, Result, TemplateSpecified);
3096e5dd7070Spatrick     }
3097e5dd7070Spatrick 
3098e5dd7070Spatrick     // Note that this is a destructor name.
3099e5dd7070Spatrick     ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
3100e5dd7070Spatrick                                               ClassNameLoc, getCurScope(),
3101e5dd7070Spatrick                                               SS, ObjectType,
3102e5dd7070Spatrick                                               EnteringContext);
3103e5dd7070Spatrick     if (!Ty)
3104e5dd7070Spatrick       return true;
3105e5dd7070Spatrick 
3106e5dd7070Spatrick     Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
3107e5dd7070Spatrick     return false;
3108e5dd7070Spatrick   }
3109e5dd7070Spatrick 
3110*12c85518Srobert   switch (Tok.getKind()) {
3111*12c85518Srobert #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
3112*12c85518Srobert #include "clang/Basic/TransformTypeTraits.def"
3113*12c85518Srobert     if (!NextToken().is(tok::l_paren)) {
3114*12c85518Srobert       Tok.setKind(tok::identifier);
3115*12c85518Srobert       Diag(Tok, diag::ext_keyword_as_ident)
3116*12c85518Srobert           << Tok.getIdentifierInfo()->getName() << 0;
3117*12c85518Srobert       goto ParseIdentifier;
3118*12c85518Srobert     }
3119*12c85518Srobert     [[fallthrough]];
3120*12c85518Srobert   default:
3121*12c85518Srobert     Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
3122e5dd7070Spatrick     return true;
3123e5dd7070Spatrick   }
3124*12c85518Srobert }
3125e5dd7070Spatrick 
3126e5dd7070Spatrick /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
3127e5dd7070Spatrick /// memory in a typesafe manner and call constructors.
3128e5dd7070Spatrick ///
3129e5dd7070Spatrick /// This method is called to parse the new expression after the optional :: has
3130e5dd7070Spatrick /// been already parsed.  If the :: was present, "UseGlobal" is true and "Start"
3131e5dd7070Spatrick /// is its location.  Otherwise, "Start" is the location of the 'new' token.
3132e5dd7070Spatrick ///
3133e5dd7070Spatrick ///        new-expression:
3134e5dd7070Spatrick ///                   '::'[opt] 'new' new-placement[opt] new-type-id
3135e5dd7070Spatrick ///                                     new-initializer[opt]
3136e5dd7070Spatrick ///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3137e5dd7070Spatrick ///                                     new-initializer[opt]
3138e5dd7070Spatrick ///
3139e5dd7070Spatrick ///        new-placement:
3140e5dd7070Spatrick ///                   '(' expression-list ')'
3141e5dd7070Spatrick ///
3142e5dd7070Spatrick ///        new-type-id:
3143e5dd7070Spatrick ///                   type-specifier-seq new-declarator[opt]
3144e5dd7070Spatrick /// [GNU]             attributes type-specifier-seq new-declarator[opt]
3145e5dd7070Spatrick ///
3146e5dd7070Spatrick ///        new-declarator:
3147e5dd7070Spatrick ///                   ptr-operator new-declarator[opt]
3148e5dd7070Spatrick ///                   direct-new-declarator
3149e5dd7070Spatrick ///
3150e5dd7070Spatrick ///        new-initializer:
3151e5dd7070Spatrick ///                   '(' expression-list[opt] ')'
3152e5dd7070Spatrick /// [C++0x]           braced-init-list
3153e5dd7070Spatrick ///
3154e5dd7070Spatrick ExprResult
ParseCXXNewExpression(bool UseGlobal,SourceLocation Start)3155e5dd7070Spatrick Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
3156e5dd7070Spatrick   assert(Tok.is(tok::kw_new) && "expected 'new' token");
3157e5dd7070Spatrick   ConsumeToken();   // Consume 'new'
3158e5dd7070Spatrick 
3159e5dd7070Spatrick   // A '(' now can be a new-placement or the '(' wrapping the type-id in the
3160e5dd7070Spatrick   // second form of new-expression. It can't be a new-type-id.
3161e5dd7070Spatrick 
3162e5dd7070Spatrick   ExprVector PlacementArgs;
3163e5dd7070Spatrick   SourceLocation PlacementLParen, PlacementRParen;
3164e5dd7070Spatrick 
3165e5dd7070Spatrick   SourceRange TypeIdParens;
3166e5dd7070Spatrick   DeclSpec DS(AttrFactory);
3167*12c85518Srobert   Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3168*12c85518Srobert                             DeclaratorContext::CXXNew);
3169e5dd7070Spatrick   if (Tok.is(tok::l_paren)) {
3170e5dd7070Spatrick     // If it turns out to be a placement, we change the type location.
3171e5dd7070Spatrick     BalancedDelimiterTracker T(*this, tok::l_paren);
3172e5dd7070Spatrick     T.consumeOpen();
3173e5dd7070Spatrick     PlacementLParen = T.getOpenLocation();
3174e5dd7070Spatrick     if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
3175e5dd7070Spatrick       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3176e5dd7070Spatrick       return ExprError();
3177e5dd7070Spatrick     }
3178e5dd7070Spatrick 
3179e5dd7070Spatrick     T.consumeClose();
3180e5dd7070Spatrick     PlacementRParen = T.getCloseLocation();
3181e5dd7070Spatrick     if (PlacementRParen.isInvalid()) {
3182e5dd7070Spatrick       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3183e5dd7070Spatrick       return ExprError();
3184e5dd7070Spatrick     }
3185e5dd7070Spatrick 
3186e5dd7070Spatrick     if (PlacementArgs.empty()) {
3187e5dd7070Spatrick       // Reset the placement locations. There was no placement.
3188e5dd7070Spatrick       TypeIdParens = T.getRange();
3189e5dd7070Spatrick       PlacementLParen = PlacementRParen = SourceLocation();
3190e5dd7070Spatrick     } else {
3191e5dd7070Spatrick       // We still need the type.
3192e5dd7070Spatrick       if (Tok.is(tok::l_paren)) {
3193e5dd7070Spatrick         BalancedDelimiterTracker T(*this, tok::l_paren);
3194e5dd7070Spatrick         T.consumeOpen();
3195e5dd7070Spatrick         MaybeParseGNUAttributes(DeclaratorInfo);
3196e5dd7070Spatrick         ParseSpecifierQualifierList(DS);
3197e5dd7070Spatrick         DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3198e5dd7070Spatrick         ParseDeclarator(DeclaratorInfo);
3199e5dd7070Spatrick         T.consumeClose();
3200e5dd7070Spatrick         TypeIdParens = T.getRange();
3201e5dd7070Spatrick       } else {
3202e5dd7070Spatrick         MaybeParseGNUAttributes(DeclaratorInfo);
3203e5dd7070Spatrick         if (ParseCXXTypeSpecifierSeq(DS))
3204e5dd7070Spatrick           DeclaratorInfo.setInvalidType(true);
3205e5dd7070Spatrick         else {
3206e5dd7070Spatrick           DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3207e5dd7070Spatrick           ParseDeclaratorInternal(DeclaratorInfo,
3208e5dd7070Spatrick                                   &Parser::ParseDirectNewDeclarator);
3209e5dd7070Spatrick         }
3210e5dd7070Spatrick       }
3211e5dd7070Spatrick     }
3212e5dd7070Spatrick   } else {
3213e5dd7070Spatrick     // A new-type-id is a simplified type-id, where essentially the
3214e5dd7070Spatrick     // direct-declarator is replaced by a direct-new-declarator.
3215e5dd7070Spatrick     MaybeParseGNUAttributes(DeclaratorInfo);
3216e5dd7070Spatrick     if (ParseCXXTypeSpecifierSeq(DS))
3217e5dd7070Spatrick       DeclaratorInfo.setInvalidType(true);
3218e5dd7070Spatrick     else {
3219e5dd7070Spatrick       DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3220e5dd7070Spatrick       ParseDeclaratorInternal(DeclaratorInfo,
3221e5dd7070Spatrick                               &Parser::ParseDirectNewDeclarator);
3222e5dd7070Spatrick     }
3223e5dd7070Spatrick   }
3224e5dd7070Spatrick   if (DeclaratorInfo.isInvalidType()) {
3225e5dd7070Spatrick     SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3226e5dd7070Spatrick     return ExprError();
3227e5dd7070Spatrick   }
3228e5dd7070Spatrick 
3229e5dd7070Spatrick   ExprResult Initializer;
3230e5dd7070Spatrick 
3231e5dd7070Spatrick   if (Tok.is(tok::l_paren)) {
3232e5dd7070Spatrick     SourceLocation ConstructorLParen, ConstructorRParen;
3233e5dd7070Spatrick     ExprVector ConstructorArgs;
3234e5dd7070Spatrick     BalancedDelimiterTracker T(*this, tok::l_paren);
3235e5dd7070Spatrick     T.consumeOpen();
3236e5dd7070Spatrick     ConstructorLParen = T.getOpenLocation();
3237e5dd7070Spatrick     if (Tok.isNot(tok::r_paren)) {
3238e5dd7070Spatrick       auto RunSignatureHelp = [&]() {
3239e5dd7070Spatrick         ParsedType TypeRep =
3240e5dd7070Spatrick             Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
3241ec727ea7Spatrick         QualType PreferredType;
3242ec727ea7Spatrick         // ActOnTypeName might adjust DeclaratorInfo and return a null type even
3243ec727ea7Spatrick         // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
3244ec727ea7Spatrick         // `new decltype(invalid) (^)`.
3245ec727ea7Spatrick         if (TypeRep)
3246ec727ea7Spatrick           PreferredType = Actions.ProduceConstructorSignatureHelp(
3247*12c85518Srobert               TypeRep.get()->getCanonicalTypeInternal(),
3248*12c85518Srobert               DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen,
3249*12c85518Srobert               /*Braced=*/false);
3250e5dd7070Spatrick         CalledSignatureHelp = true;
3251e5dd7070Spatrick         return PreferredType;
3252e5dd7070Spatrick       };
3253*12c85518Srobert       if (ParseExpressionList(ConstructorArgs, [&] {
3254e5dd7070Spatrick             PreferredType.enterFunctionArgument(Tok.getLocation(),
3255e5dd7070Spatrick                                                 RunSignatureHelp);
3256e5dd7070Spatrick           })) {
3257e5dd7070Spatrick         if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3258e5dd7070Spatrick           RunSignatureHelp();
3259e5dd7070Spatrick         SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3260e5dd7070Spatrick         return ExprError();
3261e5dd7070Spatrick       }
3262e5dd7070Spatrick     }
3263e5dd7070Spatrick     T.consumeClose();
3264e5dd7070Spatrick     ConstructorRParen = T.getCloseLocation();
3265e5dd7070Spatrick     if (ConstructorRParen.isInvalid()) {
3266e5dd7070Spatrick       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3267e5dd7070Spatrick       return ExprError();
3268e5dd7070Spatrick     }
3269e5dd7070Spatrick     Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
3270e5dd7070Spatrick                                              ConstructorRParen,
3271e5dd7070Spatrick                                              ConstructorArgs);
3272e5dd7070Spatrick   } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
3273e5dd7070Spatrick     Diag(Tok.getLocation(),
3274e5dd7070Spatrick          diag::warn_cxx98_compat_generalized_initializer_lists);
3275e5dd7070Spatrick     Initializer = ParseBraceInitializer();
3276e5dd7070Spatrick   }
3277e5dd7070Spatrick   if (Initializer.isInvalid())
3278e5dd7070Spatrick     return Initializer;
3279e5dd7070Spatrick 
3280e5dd7070Spatrick   return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
3281e5dd7070Spatrick                              PlacementArgs, PlacementRParen,
3282e5dd7070Spatrick                              TypeIdParens, DeclaratorInfo, Initializer.get());
3283e5dd7070Spatrick }
3284e5dd7070Spatrick 
3285e5dd7070Spatrick /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
3286e5dd7070Spatrick /// passed to ParseDeclaratorInternal.
3287e5dd7070Spatrick ///
3288e5dd7070Spatrick ///        direct-new-declarator:
3289e5dd7070Spatrick ///                   '[' expression[opt] ']'
3290e5dd7070Spatrick ///                   direct-new-declarator '[' constant-expression ']'
3291e5dd7070Spatrick ///
ParseDirectNewDeclarator(Declarator & D)3292e5dd7070Spatrick void Parser::ParseDirectNewDeclarator(Declarator &D) {
3293e5dd7070Spatrick   // Parse the array dimensions.
3294e5dd7070Spatrick   bool First = true;
3295e5dd7070Spatrick   while (Tok.is(tok::l_square)) {
3296e5dd7070Spatrick     // An array-size expression can't start with a lambda.
3297e5dd7070Spatrick     if (CheckProhibitedCXX11Attribute())
3298e5dd7070Spatrick       continue;
3299e5dd7070Spatrick 
3300e5dd7070Spatrick     BalancedDelimiterTracker T(*this, tok::l_square);
3301e5dd7070Spatrick     T.consumeOpen();
3302e5dd7070Spatrick 
3303e5dd7070Spatrick     ExprResult Size =
3304e5dd7070Spatrick         First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
3305e5dd7070Spatrick               : ParseConstantExpression();
3306e5dd7070Spatrick     if (Size.isInvalid()) {
3307e5dd7070Spatrick       // Recover
3308e5dd7070Spatrick       SkipUntil(tok::r_square, StopAtSemi);
3309e5dd7070Spatrick       return;
3310e5dd7070Spatrick     }
3311e5dd7070Spatrick     First = false;
3312e5dd7070Spatrick 
3313e5dd7070Spatrick     T.consumeClose();
3314e5dd7070Spatrick 
3315e5dd7070Spatrick     // Attributes here appertain to the array type. C++11 [expr.new]p5.
3316e5dd7070Spatrick     ParsedAttributes Attrs(AttrFactory);
3317e5dd7070Spatrick     MaybeParseCXX11Attributes(Attrs);
3318e5dd7070Spatrick 
3319e5dd7070Spatrick     D.AddTypeInfo(DeclaratorChunk::getArray(0,
3320e5dd7070Spatrick                                             /*isStatic=*/false, /*isStar=*/false,
3321e5dd7070Spatrick                                             Size.get(), T.getOpenLocation(),
3322e5dd7070Spatrick                                             T.getCloseLocation()),
3323e5dd7070Spatrick                   std::move(Attrs), T.getCloseLocation());
3324e5dd7070Spatrick 
3325e5dd7070Spatrick     if (T.getCloseLocation().isInvalid())
3326e5dd7070Spatrick       return;
3327e5dd7070Spatrick   }
3328e5dd7070Spatrick }
3329e5dd7070Spatrick 
3330e5dd7070Spatrick /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3331e5dd7070Spatrick /// This ambiguity appears in the syntax of the C++ new operator.
3332e5dd7070Spatrick ///
3333e5dd7070Spatrick ///        new-expression:
3334e5dd7070Spatrick ///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3335e5dd7070Spatrick ///                                     new-initializer[opt]
3336e5dd7070Spatrick ///
3337e5dd7070Spatrick ///        new-placement:
3338e5dd7070Spatrick ///                   '(' expression-list ')'
3339e5dd7070Spatrick ///
ParseExpressionListOrTypeId(SmallVectorImpl<Expr * > & PlacementArgs,Declarator & D)3340e5dd7070Spatrick bool Parser::ParseExpressionListOrTypeId(
3341e5dd7070Spatrick                                    SmallVectorImpl<Expr*> &PlacementArgs,
3342e5dd7070Spatrick                                          Declarator &D) {
3343e5dd7070Spatrick   // The '(' was already consumed.
3344e5dd7070Spatrick   if (isTypeIdInParens()) {
3345e5dd7070Spatrick     ParseSpecifierQualifierList(D.getMutableDeclSpec());
3346e5dd7070Spatrick     D.SetSourceRange(D.getDeclSpec().getSourceRange());
3347e5dd7070Spatrick     ParseDeclarator(D);
3348e5dd7070Spatrick     return D.isInvalidType();
3349e5dd7070Spatrick   }
3350e5dd7070Spatrick 
3351e5dd7070Spatrick   // It's not a type, it has to be an expression list.
3352*12c85518Srobert   return ParseExpressionList(PlacementArgs);
3353e5dd7070Spatrick }
3354e5dd7070Spatrick 
3355e5dd7070Spatrick /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3356e5dd7070Spatrick /// to free memory allocated by new.
3357e5dd7070Spatrick ///
3358e5dd7070Spatrick /// This method is called to parse the 'delete' expression after the optional
3359e5dd7070Spatrick /// '::' has been already parsed.  If the '::' was present, "UseGlobal" is true
3360e5dd7070Spatrick /// and "Start" is its location.  Otherwise, "Start" is the location of the
3361e5dd7070Spatrick /// 'delete' token.
3362e5dd7070Spatrick ///
3363e5dd7070Spatrick ///        delete-expression:
3364e5dd7070Spatrick ///                   '::'[opt] 'delete' cast-expression
3365e5dd7070Spatrick ///                   '::'[opt] 'delete' '[' ']' cast-expression
3366e5dd7070Spatrick ExprResult
ParseCXXDeleteExpression(bool UseGlobal,SourceLocation Start)3367e5dd7070Spatrick Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3368e5dd7070Spatrick   assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
3369e5dd7070Spatrick   ConsumeToken(); // Consume 'delete'
3370e5dd7070Spatrick 
3371e5dd7070Spatrick   // Array delete?
3372e5dd7070Spatrick   bool ArrayDelete = false;
3373e5dd7070Spatrick   if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
3374e5dd7070Spatrick     // C++11 [expr.delete]p1:
3375e5dd7070Spatrick     //   Whenever the delete keyword is followed by empty square brackets, it
3376e5dd7070Spatrick     //   shall be interpreted as [array delete].
3377e5dd7070Spatrick     //   [Footnote: A lambda expression with a lambda-introducer that consists
3378e5dd7070Spatrick     //              of empty square brackets can follow the delete keyword if
3379e5dd7070Spatrick     //              the lambda expression is enclosed in parentheses.]
3380e5dd7070Spatrick 
3381e5dd7070Spatrick     const Token Next = GetLookAheadToken(2);
3382e5dd7070Spatrick 
3383e5dd7070Spatrick     // Basic lookahead to check if we have a lambda expression.
3384e5dd7070Spatrick     if (Next.isOneOf(tok::l_brace, tok::less) ||
3385e5dd7070Spatrick         (Next.is(tok::l_paren) &&
3386e5dd7070Spatrick          (GetLookAheadToken(3).is(tok::r_paren) ||
3387e5dd7070Spatrick           (GetLookAheadToken(3).is(tok::identifier) &&
3388e5dd7070Spatrick            GetLookAheadToken(4).is(tok::identifier))))) {
3389e5dd7070Spatrick       TentativeParsingAction TPA(*this);
3390e5dd7070Spatrick       SourceLocation LSquareLoc = Tok.getLocation();
3391e5dd7070Spatrick       SourceLocation RSquareLoc = NextToken().getLocation();
3392e5dd7070Spatrick 
3393e5dd7070Spatrick       // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3394e5dd7070Spatrick       // case.
3395e5dd7070Spatrick       SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3396e5dd7070Spatrick       SourceLocation RBraceLoc;
3397e5dd7070Spatrick       bool EmitFixIt = false;
3398e5dd7070Spatrick       if (Tok.is(tok::l_brace)) {
3399e5dd7070Spatrick         ConsumeBrace();
3400e5dd7070Spatrick         SkipUntil(tok::r_brace, StopBeforeMatch);
3401e5dd7070Spatrick         RBraceLoc = Tok.getLocation();
3402e5dd7070Spatrick         EmitFixIt = true;
3403e5dd7070Spatrick       }
3404e5dd7070Spatrick 
3405e5dd7070Spatrick       TPA.Revert();
3406e5dd7070Spatrick 
3407e5dd7070Spatrick       if (EmitFixIt)
3408e5dd7070Spatrick         Diag(Start, diag::err_lambda_after_delete)
3409e5dd7070Spatrick             << SourceRange(Start, RSquareLoc)
3410e5dd7070Spatrick             << FixItHint::CreateInsertion(LSquareLoc, "(")
3411e5dd7070Spatrick             << FixItHint::CreateInsertion(
3412e5dd7070Spatrick                    Lexer::getLocForEndOfToken(
3413e5dd7070Spatrick                        RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3414e5dd7070Spatrick                    ")");
3415e5dd7070Spatrick       else
3416e5dd7070Spatrick         Diag(Start, diag::err_lambda_after_delete)
3417e5dd7070Spatrick             << SourceRange(Start, RSquareLoc);
3418e5dd7070Spatrick 
3419e5dd7070Spatrick       // Warn that the non-capturing lambda isn't surrounded by parentheses
3420e5dd7070Spatrick       // to disambiguate it from 'delete[]'.
3421e5dd7070Spatrick       ExprResult Lambda = ParseLambdaExpression();
3422e5dd7070Spatrick       if (Lambda.isInvalid())
3423e5dd7070Spatrick         return ExprError();
3424e5dd7070Spatrick 
3425e5dd7070Spatrick       // Evaluate any postfix expressions used on the lambda.
3426e5dd7070Spatrick       Lambda = ParsePostfixExpressionSuffix(Lambda);
3427e5dd7070Spatrick       if (Lambda.isInvalid())
3428e5dd7070Spatrick         return ExprError();
3429e5dd7070Spatrick       return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3430e5dd7070Spatrick                                     Lambda.get());
3431e5dd7070Spatrick     }
3432e5dd7070Spatrick 
3433e5dd7070Spatrick     ArrayDelete = true;
3434e5dd7070Spatrick     BalancedDelimiterTracker T(*this, tok::l_square);
3435e5dd7070Spatrick 
3436e5dd7070Spatrick     T.consumeOpen();
3437e5dd7070Spatrick     T.consumeClose();
3438e5dd7070Spatrick     if (T.getCloseLocation().isInvalid())
3439e5dd7070Spatrick       return ExprError();
3440e5dd7070Spatrick   }
3441e5dd7070Spatrick 
3442e5dd7070Spatrick   ExprResult Operand(ParseCastExpression(AnyCastExpr));
3443e5dd7070Spatrick   if (Operand.isInvalid())
3444e5dd7070Spatrick     return Operand;
3445e5dd7070Spatrick 
3446e5dd7070Spatrick   return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
3447e5dd7070Spatrick }
3448e5dd7070Spatrick 
3449e5dd7070Spatrick /// ParseRequiresExpression - Parse a C++2a requires-expression.
3450e5dd7070Spatrick /// C++2a [expr.prim.req]p1
3451e5dd7070Spatrick ///     A requires-expression provides a concise way to express requirements on
3452e5dd7070Spatrick ///     template arguments. A requirement is one that can be checked by name
3453e5dd7070Spatrick ///     lookup (6.4) or by checking properties of types and expressions.
3454e5dd7070Spatrick ///
3455e5dd7070Spatrick ///     requires-expression:
3456e5dd7070Spatrick ///         'requires' requirement-parameter-list[opt] requirement-body
3457e5dd7070Spatrick ///
3458e5dd7070Spatrick ///     requirement-parameter-list:
3459e5dd7070Spatrick ///         '(' parameter-declaration-clause[opt] ')'
3460e5dd7070Spatrick ///
3461e5dd7070Spatrick ///     requirement-body:
3462e5dd7070Spatrick ///         '{' requirement-seq '}'
3463e5dd7070Spatrick ///
3464e5dd7070Spatrick ///     requirement-seq:
3465e5dd7070Spatrick ///         requirement
3466e5dd7070Spatrick ///         requirement-seq requirement
3467e5dd7070Spatrick ///
3468e5dd7070Spatrick ///     requirement:
3469e5dd7070Spatrick ///         simple-requirement
3470e5dd7070Spatrick ///         type-requirement
3471e5dd7070Spatrick ///         compound-requirement
3472e5dd7070Spatrick ///         nested-requirement
ParseRequiresExpression()3473e5dd7070Spatrick ExprResult Parser::ParseRequiresExpression() {
3474e5dd7070Spatrick   assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword");
3475e5dd7070Spatrick   SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires'
3476e5dd7070Spatrick 
3477e5dd7070Spatrick   llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls;
3478e5dd7070Spatrick   if (Tok.is(tok::l_paren)) {
3479e5dd7070Spatrick     // requirement parameter list is present.
3480e5dd7070Spatrick     ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope |
3481e5dd7070Spatrick                                     Scope::DeclScope);
3482e5dd7070Spatrick     BalancedDelimiterTracker Parens(*this, tok::l_paren);
3483e5dd7070Spatrick     Parens.consumeOpen();
3484e5dd7070Spatrick     if (!Tok.is(tok::r_paren)) {
3485e5dd7070Spatrick       ParsedAttributes FirstArgAttrs(getAttrFactory());
3486e5dd7070Spatrick       SourceLocation EllipsisLoc;
3487e5dd7070Spatrick       llvm::SmallVector<DeclaratorChunk::ParamInfo, 2> LocalParameters;
3488a9ac8606Spatrick       ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr,
3489e5dd7070Spatrick                                       FirstArgAttrs, LocalParameters,
3490e5dd7070Spatrick                                       EllipsisLoc);
3491e5dd7070Spatrick       if (EllipsisLoc.isValid())
3492e5dd7070Spatrick         Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis);
3493e5dd7070Spatrick       for (auto &ParamInfo : LocalParameters)
3494e5dd7070Spatrick         LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param));
3495e5dd7070Spatrick     }
3496e5dd7070Spatrick     Parens.consumeClose();
3497e5dd7070Spatrick   }
3498e5dd7070Spatrick 
3499e5dd7070Spatrick   BalancedDelimiterTracker Braces(*this, tok::l_brace);
3500e5dd7070Spatrick   if (Braces.expectAndConsume())
3501e5dd7070Spatrick     return ExprError();
3502e5dd7070Spatrick 
3503e5dd7070Spatrick   // Start of requirement list
3504e5dd7070Spatrick   llvm::SmallVector<concepts::Requirement *, 2> Requirements;
3505e5dd7070Spatrick 
3506e5dd7070Spatrick   // C++2a [expr.prim.req]p2
3507e5dd7070Spatrick   //   Expressions appearing within a requirement-body are unevaluated operands.
3508e5dd7070Spatrick   EnterExpressionEvaluationContext Ctx(
3509e5dd7070Spatrick       Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3510e5dd7070Spatrick 
3511e5dd7070Spatrick   ParseScope BodyScope(this, Scope::DeclScope);
3512*12c85518Srobert   // Create a separate diagnostic pool for RequiresExprBodyDecl.
3513*12c85518Srobert   // Dependent diagnostics are attached to this Decl and non-depenedent
3514*12c85518Srobert   // diagnostics are surfaced after this parse.
3515*12c85518Srobert   ParsingDeclRAIIObject ParsingBodyDecl(*this, ParsingDeclRAIIObject::NoParent);
3516e5dd7070Spatrick   RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr(
3517e5dd7070Spatrick       RequiresKWLoc, LocalParameterDecls, getCurScope());
3518e5dd7070Spatrick 
3519e5dd7070Spatrick   if (Tok.is(tok::r_brace)) {
3520e5dd7070Spatrick     // Grammar does not allow an empty body.
3521e5dd7070Spatrick     // requirement-body:
3522e5dd7070Spatrick     //   { requirement-seq }
3523e5dd7070Spatrick     // requirement-seq:
3524e5dd7070Spatrick     //   requirement
3525e5dd7070Spatrick     //   requirement-seq requirement
3526e5dd7070Spatrick     Diag(Tok, diag::err_empty_requires_expr);
3527e5dd7070Spatrick     // Continue anyway and produce a requires expr with no requirements.
3528e5dd7070Spatrick   } else {
3529e5dd7070Spatrick     while (!Tok.is(tok::r_brace)) {
3530e5dd7070Spatrick       switch (Tok.getKind()) {
3531e5dd7070Spatrick       case tok::l_brace: {
3532e5dd7070Spatrick         // Compound requirement
3533e5dd7070Spatrick         // C++ [expr.prim.req.compound]
3534e5dd7070Spatrick         //     compound-requirement:
3535e5dd7070Spatrick         //         '{' expression '}' 'noexcept'[opt]
3536e5dd7070Spatrick         //             return-type-requirement[opt] ';'
3537e5dd7070Spatrick         //     return-type-requirement:
3538e5dd7070Spatrick         //         trailing-return-type
3539e5dd7070Spatrick         //         '->' cv-qualifier-seq[opt] constrained-parameter
3540e5dd7070Spatrick         //             cv-qualifier-seq[opt] abstract-declarator[opt]
3541e5dd7070Spatrick         BalancedDelimiterTracker ExprBraces(*this, tok::l_brace);
3542e5dd7070Spatrick         ExprBraces.consumeOpen();
3543e5dd7070Spatrick         ExprResult Expression =
3544e5dd7070Spatrick             Actions.CorrectDelayedTyposInExpr(ParseExpression());
3545e5dd7070Spatrick         if (!Expression.isUsable()) {
3546e5dd7070Spatrick           ExprBraces.skipToEnd();
3547e5dd7070Spatrick           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3548e5dd7070Spatrick           break;
3549e5dd7070Spatrick         }
3550e5dd7070Spatrick         if (ExprBraces.consumeClose())
3551e5dd7070Spatrick           ExprBraces.skipToEnd();
3552e5dd7070Spatrick 
3553e5dd7070Spatrick         concepts::Requirement *Req = nullptr;
3554e5dd7070Spatrick         SourceLocation NoexceptLoc;
3555e5dd7070Spatrick         TryConsumeToken(tok::kw_noexcept, NoexceptLoc);
3556e5dd7070Spatrick         if (Tok.is(tok::semi)) {
3557e5dd7070Spatrick           Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc);
3558e5dd7070Spatrick           if (Req)
3559e5dd7070Spatrick             Requirements.push_back(Req);
3560e5dd7070Spatrick           break;
3561e5dd7070Spatrick         }
3562e5dd7070Spatrick         if (!TryConsumeToken(tok::arrow))
3563e5dd7070Spatrick           // User probably forgot the arrow, remind them and try to continue.
3564e5dd7070Spatrick           Diag(Tok, diag::err_requires_expr_missing_arrow)
3565e5dd7070Spatrick               << FixItHint::CreateInsertion(Tok.getLocation(), "->");
3566e5dd7070Spatrick         // Try to parse a 'type-constraint'
3567e5dd7070Spatrick         if (TryAnnotateTypeConstraint()) {
3568e5dd7070Spatrick           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3569e5dd7070Spatrick           break;
3570e5dd7070Spatrick         }
3571e5dd7070Spatrick         if (!isTypeConstraintAnnotation()) {
3572e5dd7070Spatrick           Diag(Tok, diag::err_requires_expr_expected_type_constraint);
3573e5dd7070Spatrick           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3574e5dd7070Spatrick           break;
3575e5dd7070Spatrick         }
3576e5dd7070Spatrick         CXXScopeSpec SS;
3577e5dd7070Spatrick         if (Tok.is(tok::annot_cxxscope)) {
3578e5dd7070Spatrick           Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3579e5dd7070Spatrick                                                        Tok.getAnnotationRange(),
3580e5dd7070Spatrick                                                        SS);
3581e5dd7070Spatrick           ConsumeAnnotationToken();
3582e5dd7070Spatrick         }
3583e5dd7070Spatrick 
3584e5dd7070Spatrick         Req = Actions.ActOnCompoundRequirement(
3585e5dd7070Spatrick             Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok),
3586e5dd7070Spatrick             TemplateParameterDepth);
3587e5dd7070Spatrick         ConsumeAnnotationToken();
3588e5dd7070Spatrick         if (Req)
3589e5dd7070Spatrick           Requirements.push_back(Req);
3590e5dd7070Spatrick         break;
3591e5dd7070Spatrick       }
3592e5dd7070Spatrick       default: {
3593e5dd7070Spatrick         bool PossibleRequiresExprInSimpleRequirement = false;
3594e5dd7070Spatrick         if (Tok.is(tok::kw_requires)) {
3595e5dd7070Spatrick           auto IsNestedRequirement = [&] {
3596e5dd7070Spatrick             RevertingTentativeParsingAction TPA(*this);
3597e5dd7070Spatrick             ConsumeToken(); // 'requires'
3598e5dd7070Spatrick             if (Tok.is(tok::l_brace))
3599e5dd7070Spatrick               // This is a requires expression
3600e5dd7070Spatrick               // requires (T t) {
3601e5dd7070Spatrick               //   requires { t++; };
3602e5dd7070Spatrick               //   ...      ^
3603e5dd7070Spatrick               // }
3604e5dd7070Spatrick               return false;
3605e5dd7070Spatrick             if (Tok.is(tok::l_paren)) {
3606e5dd7070Spatrick               // This might be the parameter list of a requires expression
3607e5dd7070Spatrick               ConsumeParen();
3608e5dd7070Spatrick               auto Res = TryParseParameterDeclarationClause();
3609e5dd7070Spatrick               if (Res != TPResult::False) {
3610e5dd7070Spatrick                 // Skip to the closing parenthesis
3611e5dd7070Spatrick                 // FIXME: Don't traverse these tokens twice (here and in
3612e5dd7070Spatrick                 //  TryParseParameterDeclarationClause).
3613e5dd7070Spatrick                 unsigned Depth = 1;
3614e5dd7070Spatrick                 while (Depth != 0) {
3615e5dd7070Spatrick                   if (Tok.is(tok::l_paren))
3616e5dd7070Spatrick                     Depth++;
3617e5dd7070Spatrick                   else if (Tok.is(tok::r_paren))
3618e5dd7070Spatrick                     Depth--;
3619e5dd7070Spatrick                   ConsumeAnyToken();
3620e5dd7070Spatrick                 }
3621e5dd7070Spatrick                 // requires (T t) {
3622e5dd7070Spatrick                 //   requires () ?
3623e5dd7070Spatrick                 //   ...         ^
3624e5dd7070Spatrick                 //   - OR -
3625e5dd7070Spatrick                 //   requires (int x) ?
3626e5dd7070Spatrick                 //   ...              ^
3627e5dd7070Spatrick                 // }
3628e5dd7070Spatrick                 if (Tok.is(tok::l_brace))
3629e5dd7070Spatrick                   // requires (...) {
3630e5dd7070Spatrick                   //                ^ - a requires expression as a
3631e5dd7070Spatrick                   //                    simple-requirement.
3632e5dd7070Spatrick                   return false;
3633e5dd7070Spatrick               }
3634e5dd7070Spatrick             }
3635e5dd7070Spatrick             return true;
3636e5dd7070Spatrick           };
3637e5dd7070Spatrick           if (IsNestedRequirement()) {
3638e5dd7070Spatrick             ConsumeToken();
3639e5dd7070Spatrick             // Nested requirement
3640e5dd7070Spatrick             // C++ [expr.prim.req.nested]
3641e5dd7070Spatrick             //     nested-requirement:
3642e5dd7070Spatrick             //         'requires' constraint-expression ';'
3643e5dd7070Spatrick             ExprResult ConstraintExpr =
3644e5dd7070Spatrick                 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
3645e5dd7070Spatrick             if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) {
3646e5dd7070Spatrick               SkipUntil(tok::semi, tok::r_brace,
3647e5dd7070Spatrick                         SkipUntilFlags::StopBeforeMatch);
3648e5dd7070Spatrick               break;
3649e5dd7070Spatrick             }
3650e5dd7070Spatrick             if (auto *Req =
3651e5dd7070Spatrick                     Actions.ActOnNestedRequirement(ConstraintExpr.get()))
3652e5dd7070Spatrick               Requirements.push_back(Req);
3653e5dd7070Spatrick             else {
3654e5dd7070Spatrick               SkipUntil(tok::semi, tok::r_brace,
3655e5dd7070Spatrick                         SkipUntilFlags::StopBeforeMatch);
3656e5dd7070Spatrick               break;
3657e5dd7070Spatrick             }
3658e5dd7070Spatrick             break;
3659e5dd7070Spatrick           } else
3660e5dd7070Spatrick             PossibleRequiresExprInSimpleRequirement = true;
3661e5dd7070Spatrick         } else if (Tok.is(tok::kw_typename)) {
3662e5dd7070Spatrick           // This might be 'typename T::value_type;' (a type requirement) or
3663e5dd7070Spatrick           // 'typename T::value_type{};' (a simple requirement).
3664e5dd7070Spatrick           TentativeParsingAction TPA(*this);
3665e5dd7070Spatrick 
3666e5dd7070Spatrick           // We need to consume the typename to allow 'requires { typename a; }'
3667e5dd7070Spatrick           SourceLocation TypenameKWLoc = ConsumeToken();
3668*12c85518Srobert           if (TryAnnotateOptionalCXXScopeToken()) {
3669e5dd7070Spatrick             TPA.Commit();
3670e5dd7070Spatrick             SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3671e5dd7070Spatrick             break;
3672e5dd7070Spatrick           }
3673e5dd7070Spatrick           CXXScopeSpec SS;
3674e5dd7070Spatrick           if (Tok.is(tok::annot_cxxscope)) {
3675e5dd7070Spatrick             Actions.RestoreNestedNameSpecifierAnnotation(
3676e5dd7070Spatrick                 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3677e5dd7070Spatrick             ConsumeAnnotationToken();
3678e5dd7070Spatrick           }
3679e5dd7070Spatrick 
3680e5dd7070Spatrick           if (Tok.isOneOf(tok::identifier, tok::annot_template_id) &&
3681e5dd7070Spatrick               !NextToken().isOneOf(tok::l_brace, tok::l_paren)) {
3682e5dd7070Spatrick             TPA.Commit();
3683e5dd7070Spatrick             SourceLocation NameLoc = Tok.getLocation();
3684e5dd7070Spatrick             IdentifierInfo *II = nullptr;
3685e5dd7070Spatrick             TemplateIdAnnotation *TemplateId = nullptr;
3686e5dd7070Spatrick             if (Tok.is(tok::identifier)) {
3687e5dd7070Spatrick               II = Tok.getIdentifierInfo();
3688e5dd7070Spatrick               ConsumeToken();
3689e5dd7070Spatrick             } else {
3690e5dd7070Spatrick               TemplateId = takeTemplateIdAnnotation(Tok);
3691e5dd7070Spatrick               ConsumeAnnotationToken();
3692ec727ea7Spatrick               if (TemplateId->isInvalid())
3693ec727ea7Spatrick                 break;
3694e5dd7070Spatrick             }
3695e5dd7070Spatrick 
3696e5dd7070Spatrick             if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS,
3697e5dd7070Spatrick                                                          NameLoc, II,
3698e5dd7070Spatrick                                                          TemplateId)) {
3699e5dd7070Spatrick               Requirements.push_back(Req);
3700e5dd7070Spatrick             }
3701e5dd7070Spatrick             break;
3702e5dd7070Spatrick           }
3703e5dd7070Spatrick           TPA.Revert();
3704e5dd7070Spatrick         }
3705e5dd7070Spatrick         // Simple requirement
3706e5dd7070Spatrick         // C++ [expr.prim.req.simple]
3707e5dd7070Spatrick         //     simple-requirement:
3708e5dd7070Spatrick         //         expression ';'
3709e5dd7070Spatrick         SourceLocation StartLoc = Tok.getLocation();
3710e5dd7070Spatrick         ExprResult Expression =
3711e5dd7070Spatrick             Actions.CorrectDelayedTyposInExpr(ParseExpression());
3712e5dd7070Spatrick         if (!Expression.isUsable()) {
3713e5dd7070Spatrick           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3714e5dd7070Spatrick           break;
3715e5dd7070Spatrick         }
3716e5dd7070Spatrick         if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement)
3717*12c85518Srobert           Diag(StartLoc, diag::err_requires_expr_in_simple_requirement)
3718e5dd7070Spatrick               << FixItHint::CreateInsertion(StartLoc, "requires");
3719e5dd7070Spatrick         if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get()))
3720e5dd7070Spatrick           Requirements.push_back(Req);
3721e5dd7070Spatrick         else {
3722e5dd7070Spatrick           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3723e5dd7070Spatrick           break;
3724e5dd7070Spatrick         }
3725e5dd7070Spatrick         // User may have tried to put some compound requirement stuff here
3726e5dd7070Spatrick         if (Tok.is(tok::kw_noexcept)) {
3727e5dd7070Spatrick           Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept)
3728e5dd7070Spatrick               << FixItHint::CreateInsertion(StartLoc, "{")
3729e5dd7070Spatrick               << FixItHint::CreateInsertion(Tok.getLocation(), "}");
3730e5dd7070Spatrick           SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3731e5dd7070Spatrick           break;
3732e5dd7070Spatrick         }
3733e5dd7070Spatrick         break;
3734e5dd7070Spatrick       }
3735e5dd7070Spatrick       }
3736e5dd7070Spatrick       if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) {
3737e5dd7070Spatrick         SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3738e5dd7070Spatrick         TryConsumeToken(tok::semi);
3739e5dd7070Spatrick         break;
3740e5dd7070Spatrick       }
3741e5dd7070Spatrick     }
3742e5dd7070Spatrick     if (Requirements.empty()) {
3743e5dd7070Spatrick       // Don't emit an empty requires expr here to avoid confusing the user with
3744e5dd7070Spatrick       // other diagnostics quoting an empty requires expression they never
3745e5dd7070Spatrick       // wrote.
3746e5dd7070Spatrick       Braces.consumeClose();
3747e5dd7070Spatrick       Actions.ActOnFinishRequiresExpr();
3748e5dd7070Spatrick       return ExprError();
3749e5dd7070Spatrick     }
3750e5dd7070Spatrick   }
3751e5dd7070Spatrick   Braces.consumeClose();
3752e5dd7070Spatrick   Actions.ActOnFinishRequiresExpr();
3753*12c85518Srobert   ParsingBodyDecl.complete(Body);
3754e5dd7070Spatrick   return Actions.ActOnRequiresExpr(RequiresKWLoc, Body, LocalParameterDecls,
3755e5dd7070Spatrick                                    Requirements, Braces.getCloseLocation());
3756e5dd7070Spatrick }
3757e5dd7070Spatrick 
TypeTraitFromTokKind(tok::TokenKind kind)3758e5dd7070Spatrick static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3759e5dd7070Spatrick   switch (kind) {
3760e5dd7070Spatrick   default: llvm_unreachable("Not a known type trait");
3761e5dd7070Spatrick #define TYPE_TRAIT_1(Spelling, Name, Key) \
3762e5dd7070Spatrick case tok::kw_ ## Spelling: return UTT_ ## Name;
3763e5dd7070Spatrick #define TYPE_TRAIT_2(Spelling, Name, Key) \
3764e5dd7070Spatrick case tok::kw_ ## Spelling: return BTT_ ## Name;
3765e5dd7070Spatrick #include "clang/Basic/TokenKinds.def"
3766e5dd7070Spatrick #define TYPE_TRAIT_N(Spelling, Name, Key) \
3767e5dd7070Spatrick   case tok::kw_ ## Spelling: return TT_ ## Name;
3768e5dd7070Spatrick #include "clang/Basic/TokenKinds.def"
3769e5dd7070Spatrick   }
3770e5dd7070Spatrick }
3771e5dd7070Spatrick 
ArrayTypeTraitFromTokKind(tok::TokenKind kind)3772e5dd7070Spatrick static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3773e5dd7070Spatrick   switch (kind) {
3774ec727ea7Spatrick   default:
3775ec727ea7Spatrick     llvm_unreachable("Not a known array type trait");
3776ec727ea7Spatrick #define ARRAY_TYPE_TRAIT(Spelling, Name, Key)                                  \
3777ec727ea7Spatrick   case tok::kw_##Spelling:                                                     \
3778ec727ea7Spatrick     return ATT_##Name;
3779ec727ea7Spatrick #include "clang/Basic/TokenKinds.def"
3780e5dd7070Spatrick   }
3781e5dd7070Spatrick }
3782e5dd7070Spatrick 
ExpressionTraitFromTokKind(tok::TokenKind kind)3783e5dd7070Spatrick static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3784e5dd7070Spatrick   switch (kind) {
3785ec727ea7Spatrick   default:
3786ec727ea7Spatrick     llvm_unreachable("Not a known unary expression trait.");
3787ec727ea7Spatrick #define EXPRESSION_TRAIT(Spelling, Name, Key)                                  \
3788ec727ea7Spatrick   case tok::kw_##Spelling:                                                     \
3789ec727ea7Spatrick     return ET_##Name;
3790ec727ea7Spatrick #include "clang/Basic/TokenKinds.def"
3791e5dd7070Spatrick   }
3792e5dd7070Spatrick }
3793e5dd7070Spatrick 
3794e5dd7070Spatrick /// Parse the built-in type-trait pseudo-functions that allow
3795e5dd7070Spatrick /// implementation of the TR1/C++11 type traits templates.
3796e5dd7070Spatrick ///
3797e5dd7070Spatrick ///       primary-expression:
3798e5dd7070Spatrick ///          unary-type-trait '(' type-id ')'
3799e5dd7070Spatrick ///          binary-type-trait '(' type-id ',' type-id ')'
3800e5dd7070Spatrick ///          type-trait '(' type-id-seq ')'
3801e5dd7070Spatrick ///
3802e5dd7070Spatrick ///       type-id-seq:
3803e5dd7070Spatrick ///          type-id ...[opt] type-id-seq[opt]
3804e5dd7070Spatrick ///
ParseTypeTrait()3805e5dd7070Spatrick ExprResult Parser::ParseTypeTrait() {
3806e5dd7070Spatrick   tok::TokenKind Kind = Tok.getKind();
3807e5dd7070Spatrick 
3808e5dd7070Spatrick   SourceLocation Loc = ConsumeToken();
3809e5dd7070Spatrick 
3810e5dd7070Spatrick   BalancedDelimiterTracker Parens(*this, tok::l_paren);
3811e5dd7070Spatrick   if (Parens.expectAndConsume())
3812e5dd7070Spatrick     return ExprError();
3813e5dd7070Spatrick 
3814e5dd7070Spatrick   SmallVector<ParsedType, 2> Args;
3815e5dd7070Spatrick   do {
3816e5dd7070Spatrick     // Parse the next type.
3817e5dd7070Spatrick     TypeResult Ty = ParseTypeName();
3818e5dd7070Spatrick     if (Ty.isInvalid()) {
3819e5dd7070Spatrick       Parens.skipToEnd();
3820e5dd7070Spatrick       return ExprError();
3821e5dd7070Spatrick     }
3822e5dd7070Spatrick 
3823e5dd7070Spatrick     // Parse the ellipsis, if present.
3824e5dd7070Spatrick     if (Tok.is(tok::ellipsis)) {
3825e5dd7070Spatrick       Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3826e5dd7070Spatrick       if (Ty.isInvalid()) {
3827e5dd7070Spatrick         Parens.skipToEnd();
3828e5dd7070Spatrick         return ExprError();
3829e5dd7070Spatrick       }
3830e5dd7070Spatrick     }
3831e5dd7070Spatrick 
3832e5dd7070Spatrick     // Add this type to the list of arguments.
3833e5dd7070Spatrick     Args.push_back(Ty.get());
3834e5dd7070Spatrick   } while (TryConsumeToken(tok::comma));
3835e5dd7070Spatrick 
3836e5dd7070Spatrick   if (Parens.consumeClose())
3837e5dd7070Spatrick     return ExprError();
3838e5dd7070Spatrick 
3839e5dd7070Spatrick   SourceLocation EndLoc = Parens.getCloseLocation();
3840e5dd7070Spatrick 
3841e5dd7070Spatrick   return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3842e5dd7070Spatrick }
3843e5dd7070Spatrick 
3844e5dd7070Spatrick /// ParseArrayTypeTrait - Parse the built-in array type-trait
3845e5dd7070Spatrick /// pseudo-functions.
3846e5dd7070Spatrick ///
3847e5dd7070Spatrick ///       primary-expression:
3848e5dd7070Spatrick /// [Embarcadero]     '__array_rank' '(' type-id ')'
3849e5dd7070Spatrick /// [Embarcadero]     '__array_extent' '(' type-id ',' expression ')'
3850e5dd7070Spatrick ///
ParseArrayTypeTrait()3851e5dd7070Spatrick ExprResult Parser::ParseArrayTypeTrait() {
3852e5dd7070Spatrick   ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3853e5dd7070Spatrick   SourceLocation Loc = ConsumeToken();
3854e5dd7070Spatrick 
3855e5dd7070Spatrick   BalancedDelimiterTracker T(*this, tok::l_paren);
3856e5dd7070Spatrick   if (T.expectAndConsume())
3857e5dd7070Spatrick     return ExprError();
3858e5dd7070Spatrick 
3859e5dd7070Spatrick   TypeResult Ty = ParseTypeName();
3860e5dd7070Spatrick   if (Ty.isInvalid()) {
3861e5dd7070Spatrick     SkipUntil(tok::comma, StopAtSemi);
3862e5dd7070Spatrick     SkipUntil(tok::r_paren, StopAtSemi);
3863e5dd7070Spatrick     return ExprError();
3864e5dd7070Spatrick   }
3865e5dd7070Spatrick 
3866e5dd7070Spatrick   switch (ATT) {
3867e5dd7070Spatrick   case ATT_ArrayRank: {
3868e5dd7070Spatrick     T.consumeClose();
3869e5dd7070Spatrick     return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3870e5dd7070Spatrick                                        T.getCloseLocation());
3871e5dd7070Spatrick   }
3872e5dd7070Spatrick   case ATT_ArrayExtent: {
3873e5dd7070Spatrick     if (ExpectAndConsume(tok::comma)) {
3874e5dd7070Spatrick       SkipUntil(tok::r_paren, StopAtSemi);
3875e5dd7070Spatrick       return ExprError();
3876e5dd7070Spatrick     }
3877e5dd7070Spatrick 
3878e5dd7070Spatrick     ExprResult DimExpr = ParseExpression();
3879e5dd7070Spatrick     T.consumeClose();
3880e5dd7070Spatrick 
3881e5dd7070Spatrick     return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3882e5dd7070Spatrick                                        T.getCloseLocation());
3883e5dd7070Spatrick   }
3884e5dd7070Spatrick   }
3885e5dd7070Spatrick   llvm_unreachable("Invalid ArrayTypeTrait!");
3886e5dd7070Spatrick }
3887e5dd7070Spatrick 
3888e5dd7070Spatrick /// ParseExpressionTrait - Parse built-in expression-trait
3889e5dd7070Spatrick /// pseudo-functions like __is_lvalue_expr( xxx ).
3890e5dd7070Spatrick ///
3891e5dd7070Spatrick ///       primary-expression:
3892e5dd7070Spatrick /// [Embarcadero]     expression-trait '(' expression ')'
3893e5dd7070Spatrick ///
ParseExpressionTrait()3894e5dd7070Spatrick ExprResult Parser::ParseExpressionTrait() {
3895e5dd7070Spatrick   ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3896e5dd7070Spatrick   SourceLocation Loc = ConsumeToken();
3897e5dd7070Spatrick 
3898e5dd7070Spatrick   BalancedDelimiterTracker T(*this, tok::l_paren);
3899e5dd7070Spatrick   if (T.expectAndConsume())
3900e5dd7070Spatrick     return ExprError();
3901e5dd7070Spatrick 
3902e5dd7070Spatrick   ExprResult Expr = ParseExpression();
3903e5dd7070Spatrick 
3904e5dd7070Spatrick   T.consumeClose();
3905e5dd7070Spatrick 
3906e5dd7070Spatrick   return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3907e5dd7070Spatrick                                       T.getCloseLocation());
3908e5dd7070Spatrick }
3909e5dd7070Spatrick 
3910e5dd7070Spatrick 
3911e5dd7070Spatrick /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3912e5dd7070Spatrick /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3913e5dd7070Spatrick /// based on the context past the parens.
3914e5dd7070Spatrick ExprResult
ParseCXXAmbiguousParenExpression(ParenParseOption & ExprType,ParsedType & CastTy,BalancedDelimiterTracker & Tracker,ColonProtectionRAIIObject & ColonProt)3915e5dd7070Spatrick Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3916e5dd7070Spatrick                                          ParsedType &CastTy,
3917e5dd7070Spatrick                                          BalancedDelimiterTracker &Tracker,
3918e5dd7070Spatrick                                          ColonProtectionRAIIObject &ColonProt) {
3919e5dd7070Spatrick   assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3920e5dd7070Spatrick   assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3921e5dd7070Spatrick   assert(isTypeIdInParens() && "Not a type-id!");
3922e5dd7070Spatrick 
3923e5dd7070Spatrick   ExprResult Result(true);
3924e5dd7070Spatrick   CastTy = nullptr;
3925e5dd7070Spatrick 
3926e5dd7070Spatrick   // We need to disambiguate a very ugly part of the C++ syntax:
3927e5dd7070Spatrick   //
3928e5dd7070Spatrick   // (T())x;  - type-id
3929e5dd7070Spatrick   // (T())*x; - type-id
3930e5dd7070Spatrick   // (T())/x; - expression
3931e5dd7070Spatrick   // (T());   - expression
3932e5dd7070Spatrick   //
3933e5dd7070Spatrick   // The bad news is that we cannot use the specialized tentative parser, since
3934e5dd7070Spatrick   // it can only verify that the thing inside the parens can be parsed as
3935e5dd7070Spatrick   // type-id, it is not useful for determining the context past the parens.
3936e5dd7070Spatrick   //
3937e5dd7070Spatrick   // The good news is that the parser can disambiguate this part without
3938e5dd7070Spatrick   // making any unnecessary Action calls.
3939e5dd7070Spatrick   //
3940e5dd7070Spatrick   // It uses a scheme similar to parsing inline methods. The parenthesized
3941e5dd7070Spatrick   // tokens are cached, the context that follows is determined (possibly by
3942e5dd7070Spatrick   // parsing a cast-expression), and then we re-introduce the cached tokens
3943e5dd7070Spatrick   // into the token stream and parse them appropriately.
3944e5dd7070Spatrick 
3945e5dd7070Spatrick   ParenParseOption ParseAs;
3946e5dd7070Spatrick   CachedTokens Toks;
3947e5dd7070Spatrick 
3948e5dd7070Spatrick   // Store the tokens of the parentheses. We will parse them after we determine
3949e5dd7070Spatrick   // the context that follows them.
3950e5dd7070Spatrick   if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3951e5dd7070Spatrick     // We didn't find the ')' we expected.
3952e5dd7070Spatrick     Tracker.consumeClose();
3953e5dd7070Spatrick     return ExprError();
3954e5dd7070Spatrick   }
3955e5dd7070Spatrick 
3956e5dd7070Spatrick   if (Tok.is(tok::l_brace)) {
3957e5dd7070Spatrick     ParseAs = CompoundLiteral;
3958e5dd7070Spatrick   } else {
3959e5dd7070Spatrick     bool NotCastExpr;
3960e5dd7070Spatrick     if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3961e5dd7070Spatrick       NotCastExpr = true;
3962e5dd7070Spatrick     } else {
3963e5dd7070Spatrick       // Try parsing the cast-expression that may follow.
3964e5dd7070Spatrick       // If it is not a cast-expression, NotCastExpr will be true and no token
3965e5dd7070Spatrick       // will be consumed.
3966e5dd7070Spatrick       ColonProt.restore();
3967e5dd7070Spatrick       Result = ParseCastExpression(AnyCastExpr,
3968e5dd7070Spatrick                                    false/*isAddressofOperand*/,
3969e5dd7070Spatrick                                    NotCastExpr,
3970e5dd7070Spatrick                                    // type-id has priority.
3971e5dd7070Spatrick                                    IsTypeCast);
3972e5dd7070Spatrick     }
3973e5dd7070Spatrick 
3974e5dd7070Spatrick     // If we parsed a cast-expression, it's really a type-id, otherwise it's
3975e5dd7070Spatrick     // an expression.
3976e5dd7070Spatrick     ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3977e5dd7070Spatrick   }
3978e5dd7070Spatrick 
3979e5dd7070Spatrick   // Create a fake EOF to mark end of Toks buffer.
3980e5dd7070Spatrick   Token AttrEnd;
3981e5dd7070Spatrick   AttrEnd.startToken();
3982e5dd7070Spatrick   AttrEnd.setKind(tok::eof);
3983e5dd7070Spatrick   AttrEnd.setLocation(Tok.getLocation());
3984e5dd7070Spatrick   AttrEnd.setEofData(Toks.data());
3985e5dd7070Spatrick   Toks.push_back(AttrEnd);
3986e5dd7070Spatrick 
3987e5dd7070Spatrick   // The current token should go after the cached tokens.
3988e5dd7070Spatrick   Toks.push_back(Tok);
3989e5dd7070Spatrick   // Re-enter the stored parenthesized tokens into the token stream, so we may
3990e5dd7070Spatrick   // parse them now.
3991e5dd7070Spatrick   PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
3992e5dd7070Spatrick                       /*IsReinject*/ true);
3993e5dd7070Spatrick   // Drop the current token and bring the first cached one. It's the same token
3994e5dd7070Spatrick   // as when we entered this function.
3995e5dd7070Spatrick   ConsumeAnyToken();
3996e5dd7070Spatrick 
3997e5dd7070Spatrick   if (ParseAs >= CompoundLiteral) {
3998e5dd7070Spatrick     // Parse the type declarator.
3999e5dd7070Spatrick     DeclSpec DS(AttrFactory);
4000*12c85518Srobert     Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
4001*12c85518Srobert                               DeclaratorContext::TypeName);
4002e5dd7070Spatrick     {
4003e5dd7070Spatrick       ColonProtectionRAIIObject InnerColonProtection(*this);
4004e5dd7070Spatrick       ParseSpecifierQualifierList(DS);
4005e5dd7070Spatrick       ParseDeclarator(DeclaratorInfo);
4006e5dd7070Spatrick     }
4007e5dd7070Spatrick 
4008e5dd7070Spatrick     // Match the ')'.
4009e5dd7070Spatrick     Tracker.consumeClose();
4010e5dd7070Spatrick     ColonProt.restore();
4011e5dd7070Spatrick 
4012e5dd7070Spatrick     // Consume EOF marker for Toks buffer.
4013e5dd7070Spatrick     assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
4014e5dd7070Spatrick     ConsumeAnyToken();
4015e5dd7070Spatrick 
4016e5dd7070Spatrick     if (ParseAs == CompoundLiteral) {
4017e5dd7070Spatrick       ExprType = CompoundLiteral;
4018e5dd7070Spatrick       if (DeclaratorInfo.isInvalidType())
4019e5dd7070Spatrick         return ExprError();
4020e5dd7070Spatrick 
4021e5dd7070Spatrick       TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
4022e5dd7070Spatrick       return ParseCompoundLiteralExpression(Ty.get(),
4023e5dd7070Spatrick                                             Tracker.getOpenLocation(),
4024e5dd7070Spatrick                                             Tracker.getCloseLocation());
4025e5dd7070Spatrick     }
4026e5dd7070Spatrick 
4027e5dd7070Spatrick     // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
4028e5dd7070Spatrick     assert(ParseAs == CastExpr);
4029e5dd7070Spatrick 
4030e5dd7070Spatrick     if (DeclaratorInfo.isInvalidType())
4031e5dd7070Spatrick       return ExprError();
4032e5dd7070Spatrick 
4033e5dd7070Spatrick     // Result is what ParseCastExpression returned earlier.
4034e5dd7070Spatrick     if (!Result.isInvalid())
4035e5dd7070Spatrick       Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
4036e5dd7070Spatrick                                     DeclaratorInfo, CastTy,
4037e5dd7070Spatrick                                     Tracker.getCloseLocation(), Result.get());
4038e5dd7070Spatrick     return Result;
4039e5dd7070Spatrick   }
4040e5dd7070Spatrick 
4041e5dd7070Spatrick   // Not a compound literal, and not followed by a cast-expression.
4042e5dd7070Spatrick   assert(ParseAs == SimpleExpr);
4043e5dd7070Spatrick 
4044e5dd7070Spatrick   ExprType = SimpleExpr;
4045e5dd7070Spatrick   Result = ParseExpression();
4046e5dd7070Spatrick   if (!Result.isInvalid() && Tok.is(tok::r_paren))
4047e5dd7070Spatrick     Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
4048e5dd7070Spatrick                                     Tok.getLocation(), Result.get());
4049e5dd7070Spatrick 
4050e5dd7070Spatrick   // Match the ')'.
4051e5dd7070Spatrick   if (Result.isInvalid()) {
4052e5dd7070Spatrick     while (Tok.isNot(tok::eof))
4053e5dd7070Spatrick       ConsumeAnyToken();
4054e5dd7070Spatrick     assert(Tok.getEofData() == AttrEnd.getEofData());
4055e5dd7070Spatrick     ConsumeAnyToken();
4056e5dd7070Spatrick     return ExprError();
4057e5dd7070Spatrick   }
4058e5dd7070Spatrick 
4059e5dd7070Spatrick   Tracker.consumeClose();
4060e5dd7070Spatrick   // Consume EOF marker for Toks buffer.
4061e5dd7070Spatrick   assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
4062e5dd7070Spatrick   ConsumeAnyToken();
4063e5dd7070Spatrick   return Result;
4064e5dd7070Spatrick }
4065e5dd7070Spatrick 
4066e5dd7070Spatrick /// Parse a __builtin_bit_cast(T, E).
ParseBuiltinBitCast()4067e5dd7070Spatrick ExprResult Parser::ParseBuiltinBitCast() {
4068e5dd7070Spatrick   SourceLocation KWLoc = ConsumeToken();
4069e5dd7070Spatrick 
4070e5dd7070Spatrick   BalancedDelimiterTracker T(*this, tok::l_paren);
4071e5dd7070Spatrick   if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
4072e5dd7070Spatrick     return ExprError();
4073e5dd7070Spatrick 
4074e5dd7070Spatrick   // Parse the common declaration-specifiers piece.
4075e5dd7070Spatrick   DeclSpec DS(AttrFactory);
4076e5dd7070Spatrick   ParseSpecifierQualifierList(DS);
4077e5dd7070Spatrick 
4078e5dd7070Spatrick   // Parse the abstract-declarator, if present.
4079*12c85518Srobert   Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
4080*12c85518Srobert                             DeclaratorContext::TypeName);
4081e5dd7070Spatrick   ParseDeclarator(DeclaratorInfo);
4082e5dd7070Spatrick 
4083e5dd7070Spatrick   if (ExpectAndConsume(tok::comma)) {
4084e5dd7070Spatrick     Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
4085e5dd7070Spatrick     SkipUntil(tok::r_paren, StopAtSemi);
4086e5dd7070Spatrick     return ExprError();
4087e5dd7070Spatrick   }
4088e5dd7070Spatrick 
4089e5dd7070Spatrick   ExprResult Operand = ParseExpression();
4090e5dd7070Spatrick 
4091e5dd7070Spatrick   if (T.consumeClose())
4092e5dd7070Spatrick     return ExprError();
4093e5dd7070Spatrick 
4094e5dd7070Spatrick   if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
4095e5dd7070Spatrick     return ExprError();
4096e5dd7070Spatrick 
4097e5dd7070Spatrick   return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
4098e5dd7070Spatrick                                          T.getCloseLocation());
4099e5dd7070Spatrick }
4100