1e5dd7070Spatrick //===--- ParseTemplate.cpp - Template 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 parsing of C++ templates.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "clang/AST/ASTContext.h"
14e5dd7070Spatrick #include "clang/AST/DeclTemplate.h"
15e5dd7070Spatrick #include "clang/AST/ExprCXX.h"
16e5dd7070Spatrick #include "clang/Parse/ParseDiagnostic.h"
17e5dd7070Spatrick #include "clang/Parse/Parser.h"
18e5dd7070Spatrick #include "clang/Parse/RAIIObjectsForParser.h"
19e5dd7070Spatrick #include "clang/Sema/DeclSpec.h"
20e5dd7070Spatrick #include "clang/Sema/ParsedTemplate.h"
21e5dd7070Spatrick #include "clang/Sema/Scope.h"
22*12c85518Srobert #include "clang/Sema/SemaDiagnostic.h"
23e5dd7070Spatrick #include "llvm/Support/TimeProfiler.h"
24e5dd7070Spatrick using namespace clang;
25e5dd7070Spatrick 
26ec727ea7Spatrick /// Re-enter a possible template scope, creating as many template parameter
27ec727ea7Spatrick /// scopes as necessary.
28ec727ea7Spatrick /// \return The number of template parameter scopes entered.
ReenterTemplateScopes(MultiParseScope & S,Decl * D)29ec727ea7Spatrick unsigned Parser::ReenterTemplateScopes(MultiParseScope &S, Decl *D) {
30ec727ea7Spatrick   return Actions.ActOnReenterTemplateScope(D, [&] {
31ec727ea7Spatrick     S.Enter(Scope::TemplateParamScope);
32ec727ea7Spatrick     return Actions.getCurScope();
33ec727ea7Spatrick   });
34ec727ea7Spatrick }
35ec727ea7Spatrick 
36e5dd7070Spatrick /// Parse a template declaration, explicit instantiation, or
37e5dd7070Spatrick /// explicit specialization.
ParseDeclarationStartingWithTemplate(DeclaratorContext Context,SourceLocation & DeclEnd,ParsedAttributes & AccessAttrs,AccessSpecifier AS)38e5dd7070Spatrick Decl *Parser::ParseDeclarationStartingWithTemplate(
39e5dd7070Spatrick     DeclaratorContext Context, SourceLocation &DeclEnd,
40e5dd7070Spatrick     ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
41e5dd7070Spatrick   ObjCDeclContextSwitch ObjCDC(*this);
42e5dd7070Spatrick 
43e5dd7070Spatrick   if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
44e5dd7070Spatrick     return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(),
45e5dd7070Spatrick                                       DeclEnd, AccessAttrs, AS);
46e5dd7070Spatrick   }
47e5dd7070Spatrick   return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AccessAttrs,
48e5dd7070Spatrick                                                   AS);
49e5dd7070Spatrick }
50e5dd7070Spatrick 
51e5dd7070Spatrick /// Parse a template declaration or an explicit specialization.
52e5dd7070Spatrick ///
53e5dd7070Spatrick /// Template declarations include one or more template parameter lists
54e5dd7070Spatrick /// and either the function or class template declaration. Explicit
55e5dd7070Spatrick /// specializations contain one or more 'template < >' prefixes
56e5dd7070Spatrick /// followed by a (possibly templated) declaration. Since the
57e5dd7070Spatrick /// syntactic form of both features is nearly identical, we parse all
58e5dd7070Spatrick /// of the template headers together and let semantic analysis sort
59e5dd7070Spatrick /// the declarations from the explicit specializations.
60e5dd7070Spatrick ///
61e5dd7070Spatrick ///       template-declaration: [C++ temp]
62e5dd7070Spatrick ///         'export'[opt] 'template' '<' template-parameter-list '>' declaration
63e5dd7070Spatrick ///
64e5dd7070Spatrick ///       template-declaration: [C++2a]
65e5dd7070Spatrick ///         template-head declaration
66e5dd7070Spatrick ///         template-head concept-definition
67e5dd7070Spatrick ///
68e5dd7070Spatrick ///       TODO: requires-clause
69e5dd7070Spatrick ///       template-head: [C++2a]
70e5dd7070Spatrick ///         'template' '<' template-parameter-list '>'
71e5dd7070Spatrick ///             requires-clause[opt]
72e5dd7070Spatrick ///
73e5dd7070Spatrick ///       explicit-specialization: [ C++ temp.expl.spec]
74e5dd7070Spatrick ///         'template' '<' '>' declaration
ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,SourceLocation & DeclEnd,ParsedAttributes & AccessAttrs,AccessSpecifier AS)75e5dd7070Spatrick Decl *Parser::ParseTemplateDeclarationOrSpecialization(
76e5dd7070Spatrick     DeclaratorContext Context, SourceLocation &DeclEnd,
77e5dd7070Spatrick     ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
78e5dd7070Spatrick   assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
79e5dd7070Spatrick          "Token does not start a template declaration.");
80e5dd7070Spatrick 
81ec727ea7Spatrick   MultiParseScope TemplateParamScopes(*this);
82e5dd7070Spatrick 
83e5dd7070Spatrick   // Tell the action that names should be checked in the context of
84e5dd7070Spatrick   // the declaration to come.
85e5dd7070Spatrick   ParsingDeclRAIIObject
86e5dd7070Spatrick     ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
87e5dd7070Spatrick 
88e5dd7070Spatrick   // Parse multiple levels of template headers within this template
89e5dd7070Spatrick   // parameter scope, e.g.,
90e5dd7070Spatrick   //
91e5dd7070Spatrick   //   template<typename T>
92e5dd7070Spatrick   //     template<typename U>
93e5dd7070Spatrick   //       class A<T>::B { ... };
94e5dd7070Spatrick   //
95e5dd7070Spatrick   // We parse multiple levels non-recursively so that we can build a
96e5dd7070Spatrick   // single data structure containing all of the template parameter
97e5dd7070Spatrick   // lists to easily differentiate between the case above and:
98e5dd7070Spatrick   //
99e5dd7070Spatrick   //   template<typename T>
100e5dd7070Spatrick   //   class A {
101e5dd7070Spatrick   //     template<typename U> class B;
102e5dd7070Spatrick   //   };
103e5dd7070Spatrick   //
104e5dd7070Spatrick   // In the first case, the action for declaring A<T>::B receives
105e5dd7070Spatrick   // both template parameter lists. In the second case, the action for
106e5dd7070Spatrick   // defining A<T>::B receives just the inner template parameter list
107e5dd7070Spatrick   // (and retrieves the outer template parameter list from its
108e5dd7070Spatrick   // context).
109e5dd7070Spatrick   bool isSpecialization = true;
110e5dd7070Spatrick   bool LastParamListWasEmpty = false;
111e5dd7070Spatrick   TemplateParameterLists ParamLists;
112e5dd7070Spatrick   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
113e5dd7070Spatrick 
114e5dd7070Spatrick   do {
115e5dd7070Spatrick     // Consume the 'export', if any.
116e5dd7070Spatrick     SourceLocation ExportLoc;
117e5dd7070Spatrick     TryConsumeToken(tok::kw_export, ExportLoc);
118e5dd7070Spatrick 
119e5dd7070Spatrick     // Consume the 'template', which should be here.
120e5dd7070Spatrick     SourceLocation TemplateLoc;
121e5dd7070Spatrick     if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
122e5dd7070Spatrick       Diag(Tok.getLocation(), diag::err_expected_template);
123e5dd7070Spatrick       return nullptr;
124e5dd7070Spatrick     }
125e5dd7070Spatrick 
126e5dd7070Spatrick     // Parse the '<' template-parameter-list '>'
127e5dd7070Spatrick     SourceLocation LAngleLoc, RAngleLoc;
128e5dd7070Spatrick     SmallVector<NamedDecl*, 4> TemplateParams;
129ec727ea7Spatrick     if (ParseTemplateParameters(TemplateParamScopes,
130ec727ea7Spatrick                                 CurTemplateDepthTracker.getDepth(),
131e5dd7070Spatrick                                 TemplateParams, LAngleLoc, RAngleLoc)) {
132e5dd7070Spatrick       // Skip until the semi-colon or a '}'.
133e5dd7070Spatrick       SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
134e5dd7070Spatrick       TryConsumeToken(tok::semi);
135e5dd7070Spatrick       return nullptr;
136e5dd7070Spatrick     }
137e5dd7070Spatrick 
138e5dd7070Spatrick     ExprResult OptionalRequiresClauseConstraintER;
139e5dd7070Spatrick     if (!TemplateParams.empty()) {
140e5dd7070Spatrick       isSpecialization = false;
141e5dd7070Spatrick       ++CurTemplateDepthTracker;
142e5dd7070Spatrick 
143e5dd7070Spatrick       if (TryConsumeToken(tok::kw_requires)) {
144e5dd7070Spatrick         OptionalRequiresClauseConstraintER =
145a9ac8606Spatrick             Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
146e5dd7070Spatrick                 /*IsTrailingRequiresClause=*/false));
147e5dd7070Spatrick         if (!OptionalRequiresClauseConstraintER.isUsable()) {
148e5dd7070Spatrick           // Skip until the semi-colon or a '}'.
149e5dd7070Spatrick           SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
150e5dd7070Spatrick           TryConsumeToken(tok::semi);
151e5dd7070Spatrick           return nullptr;
152e5dd7070Spatrick         }
153e5dd7070Spatrick       }
154e5dd7070Spatrick     } else {
155e5dd7070Spatrick       LastParamListWasEmpty = true;
156e5dd7070Spatrick     }
157e5dd7070Spatrick 
158e5dd7070Spatrick     ParamLists.push_back(Actions.ActOnTemplateParameterList(
159e5dd7070Spatrick         CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
160e5dd7070Spatrick         TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
161e5dd7070Spatrick   } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
162e5dd7070Spatrick 
163e5dd7070Spatrick   // Parse the actual template declaration.
164e5dd7070Spatrick   if (Tok.is(tok::kw_concept))
165e5dd7070Spatrick     return ParseConceptDefinition(
166e5dd7070Spatrick         ParsedTemplateInfo(&ParamLists, isSpecialization,
167e5dd7070Spatrick                            LastParamListWasEmpty),
168e5dd7070Spatrick         DeclEnd);
169e5dd7070Spatrick 
170e5dd7070Spatrick   return ParseSingleDeclarationAfterTemplate(
171e5dd7070Spatrick       Context,
172e5dd7070Spatrick       ParsedTemplateInfo(&ParamLists, isSpecialization, LastParamListWasEmpty),
173e5dd7070Spatrick       ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
174e5dd7070Spatrick }
175e5dd7070Spatrick 
176e5dd7070Spatrick /// Parse a single declaration that declares a template,
177e5dd7070Spatrick /// template specialization, or explicit instantiation of a template.
178e5dd7070Spatrick ///
179e5dd7070Spatrick /// \param DeclEnd will receive the source location of the last token
180e5dd7070Spatrick /// within this declaration.
181e5dd7070Spatrick ///
182e5dd7070Spatrick /// \param AS the access specifier associated with this
183e5dd7070Spatrick /// declaration. Will be AS_none for namespace-scope declarations.
184e5dd7070Spatrick ///
185e5dd7070Spatrick /// \returns the new declaration.
ParseSingleDeclarationAfterTemplate(DeclaratorContext Context,const ParsedTemplateInfo & TemplateInfo,ParsingDeclRAIIObject & DiagsFromTParams,SourceLocation & DeclEnd,ParsedAttributes & AccessAttrs,AccessSpecifier AS)186e5dd7070Spatrick Decl *Parser::ParseSingleDeclarationAfterTemplate(
187e5dd7070Spatrick     DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
188e5dd7070Spatrick     ParsingDeclRAIIObject &DiagsFromTParams, SourceLocation &DeclEnd,
189e5dd7070Spatrick     ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
190e5dd7070Spatrick   assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
191e5dd7070Spatrick          "Template information required");
192e5dd7070Spatrick 
193e5dd7070Spatrick   if (Tok.is(tok::kw_static_assert)) {
194e5dd7070Spatrick     // A static_assert declaration may not be templated.
195e5dd7070Spatrick     Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
196e5dd7070Spatrick       << TemplateInfo.getSourceRange();
197e5dd7070Spatrick     // Parse the static_assert declaration to improve error recovery.
198e5dd7070Spatrick     return ParseStaticAssertDeclaration(DeclEnd);
199e5dd7070Spatrick   }
200e5dd7070Spatrick 
201a9ac8606Spatrick   if (Context == DeclaratorContext::Member) {
202e5dd7070Spatrick     // We are parsing a member template.
203*12c85518Srobert     DeclGroupPtrTy D = ParseCXXClassMemberDeclaration(
204*12c85518Srobert         AS, AccessAttrs, TemplateInfo, &DiagsFromTParams);
205*12c85518Srobert 
206*12c85518Srobert     if (!D || !D.get().isSingleDecl())
207e5dd7070Spatrick       return nullptr;
208*12c85518Srobert     return D.get().getSingleDecl();
209e5dd7070Spatrick   }
210e5dd7070Spatrick 
211*12c85518Srobert   ParsedAttributes prefixAttrs(AttrFactory);
212e5dd7070Spatrick   MaybeParseCXX11Attributes(prefixAttrs);
213e5dd7070Spatrick 
214e5dd7070Spatrick   if (Tok.is(tok::kw_using)) {
215e5dd7070Spatrick     auto usingDeclPtr = ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
216e5dd7070Spatrick                                                          prefixAttrs);
217e5dd7070Spatrick     if (!usingDeclPtr || !usingDeclPtr.get().isSingleDecl())
218e5dd7070Spatrick       return nullptr;
219e5dd7070Spatrick     return usingDeclPtr.get().getSingleDecl();
220e5dd7070Spatrick   }
221e5dd7070Spatrick 
222e5dd7070Spatrick   // Parse the declaration specifiers, stealing any diagnostics from
223e5dd7070Spatrick   // the template parameters.
224e5dd7070Spatrick   ParsingDeclSpec DS(*this, &DiagsFromTParams);
225e5dd7070Spatrick 
226e5dd7070Spatrick   ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
227e5dd7070Spatrick                              getDeclSpecContextFromDeclaratorContext(Context));
228e5dd7070Spatrick 
229e5dd7070Spatrick   if (Tok.is(tok::semi)) {
230e5dd7070Spatrick     ProhibitAttributes(prefixAttrs);
231e5dd7070Spatrick     DeclEnd = ConsumeToken();
232e5dd7070Spatrick     RecordDecl *AnonRecord = nullptr;
233e5dd7070Spatrick     Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
234*12c85518Srobert         getCurScope(), AS, DS, ParsedAttributesView::none(),
235e5dd7070Spatrick         TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
236e5dd7070Spatrick                                     : MultiTemplateParamsArg(),
237e5dd7070Spatrick         TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
238e5dd7070Spatrick         AnonRecord);
239e5dd7070Spatrick     assert(!AnonRecord &&
240e5dd7070Spatrick            "Anonymous unions/structs should not be valid with template");
241e5dd7070Spatrick     DS.complete(Decl);
242e5dd7070Spatrick     return Decl;
243e5dd7070Spatrick   }
244e5dd7070Spatrick 
245e5dd7070Spatrick   // Move the attributes from the prefix into the DS.
246e5dd7070Spatrick   if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
247e5dd7070Spatrick     ProhibitAttributes(prefixAttrs);
248e5dd7070Spatrick 
249e5dd7070Spatrick   // Parse the declarator.
250*12c85518Srobert   ParsingDeclarator DeclaratorInfo(*this, DS, prefixAttrs,
251*12c85518Srobert                                    (DeclaratorContext)Context);
252e5dd7070Spatrick   if (TemplateInfo.TemplateParams)
253e5dd7070Spatrick     DeclaratorInfo.setTemplateParameterLists(*TemplateInfo.TemplateParams);
254*12c85518Srobert 
255*12c85518Srobert   // Turn off usual access checking for template specializations and
256*12c85518Srobert   // instantiations.
257*12c85518Srobert   // C++20 [temp.spec] 13.9/6.
258*12c85518Srobert   // This disables the access checking rules for function template explicit
259*12c85518Srobert   // instantiation and explicit specialization:
260*12c85518Srobert   // - parameter-list;
261*12c85518Srobert   // - template-argument-list;
262*12c85518Srobert   // - noexcept-specifier;
263*12c85518Srobert   // - dynamic-exception-specifications (deprecated in C++11, removed since
264*12c85518Srobert   //   C++17).
265*12c85518Srobert   bool IsTemplateSpecOrInst =
266*12c85518Srobert       (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
267*12c85518Srobert        TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
268*12c85518Srobert   SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
269*12c85518Srobert 
270e5dd7070Spatrick   ParseDeclarator(DeclaratorInfo);
271*12c85518Srobert 
272*12c85518Srobert   if (IsTemplateSpecOrInst)
273*12c85518Srobert     SAC.done();
274*12c85518Srobert 
275e5dd7070Spatrick   // Error parsing the declarator?
276e5dd7070Spatrick   if (!DeclaratorInfo.hasName()) {
277e5dd7070Spatrick     // If so, skip until the semi-colon or a }.
278e5dd7070Spatrick     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
279e5dd7070Spatrick     if (Tok.is(tok::semi))
280e5dd7070Spatrick       ConsumeToken();
281e5dd7070Spatrick     return nullptr;
282e5dd7070Spatrick   }
283e5dd7070Spatrick 
284e5dd7070Spatrick   llvm::TimeTraceScope TimeScope("ParseTemplate", [&]() {
285ec727ea7Spatrick     return std::string(DeclaratorInfo.getIdentifier() != nullptr
286e5dd7070Spatrick                            ? DeclaratorInfo.getIdentifier()->getName()
287ec727ea7Spatrick                            : "<unknown>");
288e5dd7070Spatrick   });
289e5dd7070Spatrick 
290e5dd7070Spatrick   LateParsedAttrList LateParsedAttrs(true);
291e5dd7070Spatrick   if (DeclaratorInfo.isFunctionDeclarator()) {
292*12c85518Srobert     if (Tok.is(tok::kw_requires)) {
293*12c85518Srobert       CXXScopeSpec &ScopeSpec = DeclaratorInfo.getCXXScopeSpec();
294*12c85518Srobert       DeclaratorScopeObj DeclScopeObj(*this, ScopeSpec);
295*12c85518Srobert       if (ScopeSpec.isValid() &&
296*12c85518Srobert           Actions.ShouldEnterDeclaratorScope(getCurScope(), ScopeSpec))
297*12c85518Srobert         DeclScopeObj.EnterDeclaratorScope();
298e5dd7070Spatrick       ParseTrailingRequiresClause(DeclaratorInfo);
299*12c85518Srobert     }
300e5dd7070Spatrick 
301e5dd7070Spatrick     MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
302e5dd7070Spatrick   }
303e5dd7070Spatrick 
304e5dd7070Spatrick   if (DeclaratorInfo.isFunctionDeclarator() &&
305e5dd7070Spatrick       isStartOfFunctionDefinition(DeclaratorInfo)) {
306e5dd7070Spatrick 
307e5dd7070Spatrick     // Function definitions are only allowed at file scope and in C++ classes.
308e5dd7070Spatrick     // The C++ inline method definition case is handled elsewhere, so we only
309e5dd7070Spatrick     // need to handle the file scope definition case.
310a9ac8606Spatrick     if (Context != DeclaratorContext::File) {
311e5dd7070Spatrick       Diag(Tok, diag::err_function_definition_not_allowed);
312e5dd7070Spatrick       SkipMalformedDecl();
313e5dd7070Spatrick       return nullptr;
314e5dd7070Spatrick     }
315e5dd7070Spatrick 
316e5dd7070Spatrick     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
317e5dd7070Spatrick       // Recover by ignoring the 'typedef'. This was probably supposed to be
318e5dd7070Spatrick       // the 'typename' keyword, which we should have already suggested adding
319e5dd7070Spatrick       // if it's appropriate.
320e5dd7070Spatrick       Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
321e5dd7070Spatrick         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
322e5dd7070Spatrick       DS.ClearStorageClassSpecs();
323e5dd7070Spatrick     }
324e5dd7070Spatrick 
325e5dd7070Spatrick     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
326e5dd7070Spatrick       if (DeclaratorInfo.getName().getKind() !=
327e5dd7070Spatrick           UnqualifiedIdKind::IK_TemplateId) {
328e5dd7070Spatrick         // If the declarator-id is not a template-id, issue a diagnostic and
329e5dd7070Spatrick         // recover by ignoring the 'template' keyword.
330e5dd7070Spatrick         Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
331e5dd7070Spatrick         return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
332e5dd7070Spatrick                                        &LateParsedAttrs);
333e5dd7070Spatrick       } else {
334e5dd7070Spatrick         SourceLocation LAngleLoc
335e5dd7070Spatrick           = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
336e5dd7070Spatrick         Diag(DeclaratorInfo.getIdentifierLoc(),
337e5dd7070Spatrick              diag::err_explicit_instantiation_with_definition)
338e5dd7070Spatrick             << SourceRange(TemplateInfo.TemplateLoc)
339e5dd7070Spatrick             << FixItHint::CreateInsertion(LAngleLoc, "<>");
340e5dd7070Spatrick 
341e5dd7070Spatrick         // Recover as if it were an explicit specialization.
342e5dd7070Spatrick         TemplateParameterLists FakedParamLists;
343e5dd7070Spatrick         FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
344*12c85518Srobert             0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc,
345*12c85518Srobert             std::nullopt, LAngleLoc, nullptr));
346e5dd7070Spatrick 
347e5dd7070Spatrick         return ParseFunctionDefinition(
348e5dd7070Spatrick             DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
349e5dd7070Spatrick                                                /*isSpecialization=*/true,
350e5dd7070Spatrick                                                /*lastParameterListWasEmpty=*/true),
351e5dd7070Spatrick             &LateParsedAttrs);
352e5dd7070Spatrick       }
353e5dd7070Spatrick     }
354e5dd7070Spatrick     return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
355e5dd7070Spatrick                                    &LateParsedAttrs);
356e5dd7070Spatrick   }
357e5dd7070Spatrick 
358e5dd7070Spatrick   // Parse this declaration.
359e5dd7070Spatrick   Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
360e5dd7070Spatrick                                                    TemplateInfo);
361e5dd7070Spatrick 
362e5dd7070Spatrick   if (Tok.is(tok::comma)) {
363e5dd7070Spatrick     Diag(Tok, diag::err_multiple_template_declarators)
364e5dd7070Spatrick       << (int)TemplateInfo.Kind;
365e5dd7070Spatrick     SkipUntil(tok::semi);
366e5dd7070Spatrick     return ThisDecl;
367e5dd7070Spatrick   }
368e5dd7070Spatrick 
369e5dd7070Spatrick   // Eat the semi colon after the declaration.
370e5dd7070Spatrick   ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
371e5dd7070Spatrick   if (LateParsedAttrs.size() > 0)
372e5dd7070Spatrick     ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
373e5dd7070Spatrick   DeclaratorInfo.complete(ThisDecl);
374e5dd7070Spatrick   return ThisDecl;
375e5dd7070Spatrick }
376e5dd7070Spatrick 
377e5dd7070Spatrick /// \brief Parse a single declaration that declares a concept.
378e5dd7070Spatrick ///
379e5dd7070Spatrick /// \param DeclEnd will receive the source location of the last token
380e5dd7070Spatrick /// within this declaration.
381e5dd7070Spatrick ///
382e5dd7070Spatrick /// \returns the new declaration.
383e5dd7070Spatrick Decl *
ParseConceptDefinition(const ParsedTemplateInfo & TemplateInfo,SourceLocation & DeclEnd)384e5dd7070Spatrick Parser::ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
385e5dd7070Spatrick                                SourceLocation &DeclEnd) {
386e5dd7070Spatrick   assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
387e5dd7070Spatrick          "Template information required");
388e5dd7070Spatrick   assert(Tok.is(tok::kw_concept) &&
389e5dd7070Spatrick          "ParseConceptDefinition must be called when at a 'concept' keyword");
390e5dd7070Spatrick 
391e5dd7070Spatrick   ConsumeToken(); // Consume 'concept'
392e5dd7070Spatrick 
393e5dd7070Spatrick   SourceLocation BoolKWLoc;
394e5dd7070Spatrick   if (TryConsumeToken(tok::kw_bool, BoolKWLoc))
395*12c85518Srobert     Diag(Tok.getLocation(), diag::err_concept_legacy_bool_keyword) <<
396e5dd7070Spatrick         FixItHint::CreateRemoval(SourceLocation(BoolKWLoc));
397e5dd7070Spatrick 
398e5dd7070Spatrick   DiagnoseAndSkipCXX11Attributes();
399e5dd7070Spatrick 
400e5dd7070Spatrick   CXXScopeSpec SS;
401ec727ea7Spatrick   if (ParseOptionalCXXScopeSpecifier(
402ec727ea7Spatrick           SS, /*ObjectType=*/nullptr,
403*12c85518Srobert           /*ObjectHasErrors=*/false, /*EnteringContext=*/false,
404ec727ea7Spatrick           /*MayBePseudoDestructor=*/nullptr,
405e5dd7070Spatrick           /*IsTypename=*/false, /*LastII=*/nullptr, /*OnlyNamespace=*/true) ||
406e5dd7070Spatrick       SS.isInvalid()) {
407e5dd7070Spatrick     SkipUntil(tok::semi);
408e5dd7070Spatrick     return nullptr;
409e5dd7070Spatrick   }
410e5dd7070Spatrick 
411e5dd7070Spatrick   if (SS.isNotEmpty())
412e5dd7070Spatrick     Diag(SS.getBeginLoc(),
413e5dd7070Spatrick          diag::err_concept_definition_not_identifier);
414e5dd7070Spatrick 
415e5dd7070Spatrick   UnqualifiedId Result;
416ec727ea7Spatrick   if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
417ec727ea7Spatrick                          /*ObjectHadErrors=*/false, /*EnteringContext=*/false,
418e5dd7070Spatrick                          /*AllowDestructorName=*/false,
419e5dd7070Spatrick                          /*AllowConstructorName=*/false,
420e5dd7070Spatrick                          /*AllowDeductionGuide=*/false,
421ec727ea7Spatrick                          /*TemplateKWLoc=*/nullptr, Result)) {
422e5dd7070Spatrick     SkipUntil(tok::semi);
423e5dd7070Spatrick     return nullptr;
424e5dd7070Spatrick   }
425e5dd7070Spatrick 
426e5dd7070Spatrick   if (Result.getKind() != UnqualifiedIdKind::IK_Identifier) {
427e5dd7070Spatrick     Diag(Result.getBeginLoc(), diag::err_concept_definition_not_identifier);
428e5dd7070Spatrick     SkipUntil(tok::semi);
429e5dd7070Spatrick     return nullptr;
430e5dd7070Spatrick   }
431e5dd7070Spatrick 
432e5dd7070Spatrick   IdentifierInfo *Id = Result.Identifier;
433e5dd7070Spatrick   SourceLocation IdLoc = Result.getBeginLoc();
434e5dd7070Spatrick 
435e5dd7070Spatrick   DiagnoseAndSkipCXX11Attributes();
436e5dd7070Spatrick 
437e5dd7070Spatrick   if (!TryConsumeToken(tok::equal)) {
438e5dd7070Spatrick     Diag(Tok.getLocation(), diag::err_expected) << tok::equal;
439e5dd7070Spatrick     SkipUntil(tok::semi);
440e5dd7070Spatrick     return nullptr;
441e5dd7070Spatrick   }
442e5dd7070Spatrick 
443e5dd7070Spatrick   ExprResult ConstraintExprResult =
444e5dd7070Spatrick       Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
445e5dd7070Spatrick   if (ConstraintExprResult.isInvalid()) {
446e5dd7070Spatrick     SkipUntil(tok::semi);
447e5dd7070Spatrick     return nullptr;
448e5dd7070Spatrick   }
449e5dd7070Spatrick 
450e5dd7070Spatrick   DeclEnd = Tok.getLocation();
451e5dd7070Spatrick   ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
452e5dd7070Spatrick   Expr *ConstraintExpr = ConstraintExprResult.get();
453e5dd7070Spatrick   return Actions.ActOnConceptDefinition(getCurScope(),
454e5dd7070Spatrick                                         *TemplateInfo.TemplateParams,
455e5dd7070Spatrick                                         Id, IdLoc, ConstraintExpr);
456e5dd7070Spatrick }
457e5dd7070Spatrick 
458e5dd7070Spatrick /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
459e5dd7070Spatrick /// angle brackets. Depth is the depth of this template-parameter-list, which
460e5dd7070Spatrick /// is the number of template headers directly enclosing this template header.
461e5dd7070Spatrick /// TemplateParams is the current list of template parameters we're building.
462e5dd7070Spatrick /// The template parameter we parse will be added to this list. LAngleLoc and
463e5dd7070Spatrick /// RAngleLoc will receive the positions of the '<' and '>', respectively,
464e5dd7070Spatrick /// that enclose this template parameter list.
465e5dd7070Spatrick ///
466e5dd7070Spatrick /// \returns true if an error occurred, false otherwise.
ParseTemplateParameters(MultiParseScope & TemplateScopes,unsigned Depth,SmallVectorImpl<NamedDecl * > & TemplateParams,SourceLocation & LAngleLoc,SourceLocation & RAngleLoc)467e5dd7070Spatrick bool Parser::ParseTemplateParameters(
468ec727ea7Spatrick     MultiParseScope &TemplateScopes, unsigned Depth,
469ec727ea7Spatrick     SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc,
470ec727ea7Spatrick     SourceLocation &RAngleLoc) {
471e5dd7070Spatrick   // Get the template parameter list.
472e5dd7070Spatrick   if (!TryConsumeToken(tok::less, LAngleLoc)) {
473e5dd7070Spatrick     Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
474e5dd7070Spatrick     return true;
475e5dd7070Spatrick   }
476e5dd7070Spatrick 
477e5dd7070Spatrick   // Try to parse the template parameter list.
478e5dd7070Spatrick   bool Failed = false;
479ec727ea7Spatrick   // FIXME: Missing greatergreatergreater support.
480ec727ea7Spatrick   if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater)) {
481ec727ea7Spatrick     TemplateScopes.Enter(Scope::TemplateParamScope);
482e5dd7070Spatrick     Failed = ParseTemplateParameterList(Depth, TemplateParams);
483ec727ea7Spatrick   }
484e5dd7070Spatrick 
485e5dd7070Spatrick   if (Tok.is(tok::greatergreater)) {
486e5dd7070Spatrick     // No diagnostic required here: a template-parameter-list can only be
487e5dd7070Spatrick     // followed by a declaration or, for a template template parameter, the
488e5dd7070Spatrick     // 'class' keyword. Therefore, the second '>' will be diagnosed later.
489e5dd7070Spatrick     // This matters for elegant diagnosis of:
490e5dd7070Spatrick     //   template<template<typename>> struct S;
491e5dd7070Spatrick     Tok.setKind(tok::greater);
492e5dd7070Spatrick     RAngleLoc = Tok.getLocation();
493e5dd7070Spatrick     Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
494e5dd7070Spatrick   } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
495e5dd7070Spatrick     Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
496e5dd7070Spatrick     return true;
497e5dd7070Spatrick   }
498e5dd7070Spatrick   return false;
499e5dd7070Spatrick }
500e5dd7070Spatrick 
501e5dd7070Spatrick /// ParseTemplateParameterList - Parse a template parameter list. If
502e5dd7070Spatrick /// the parsing fails badly (i.e., closing bracket was left out), this
503e5dd7070Spatrick /// will try to put the token stream in a reasonable position (closing
504e5dd7070Spatrick /// a statement, etc.) and return false.
505e5dd7070Spatrick ///
506e5dd7070Spatrick ///       template-parameter-list:    [C++ temp]
507e5dd7070Spatrick ///         template-parameter
508e5dd7070Spatrick ///         template-parameter-list ',' template-parameter
509e5dd7070Spatrick bool
ParseTemplateParameterList(const unsigned Depth,SmallVectorImpl<NamedDecl * > & TemplateParams)510e5dd7070Spatrick Parser::ParseTemplateParameterList(const unsigned Depth,
511e5dd7070Spatrick                              SmallVectorImpl<NamedDecl*> &TemplateParams) {
512*12c85518Srobert   while (true) {
513e5dd7070Spatrick 
514e5dd7070Spatrick     if (NamedDecl *TmpParam
515e5dd7070Spatrick           = ParseTemplateParameter(Depth, TemplateParams.size())) {
516e5dd7070Spatrick       TemplateParams.push_back(TmpParam);
517e5dd7070Spatrick     } else {
518e5dd7070Spatrick       // If we failed to parse a template parameter, skip until we find
519e5dd7070Spatrick       // a comma or closing brace.
520e5dd7070Spatrick       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
521e5dd7070Spatrick                 StopAtSemi | StopBeforeMatch);
522e5dd7070Spatrick     }
523e5dd7070Spatrick 
524e5dd7070Spatrick     // Did we find a comma or the end of the template parameter list?
525e5dd7070Spatrick     if (Tok.is(tok::comma)) {
526e5dd7070Spatrick       ConsumeToken();
527e5dd7070Spatrick     } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
528e5dd7070Spatrick       // Don't consume this... that's done by template parser.
529e5dd7070Spatrick       break;
530e5dd7070Spatrick     } else {
531e5dd7070Spatrick       // Somebody probably forgot to close the template. Skip ahead and
532e5dd7070Spatrick       // try to get out of the expression. This error is currently
533e5dd7070Spatrick       // subsumed by whatever goes on in ParseTemplateParameter.
534e5dd7070Spatrick       Diag(Tok.getLocation(), diag::err_expected_comma_greater);
535e5dd7070Spatrick       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
536e5dd7070Spatrick                 StopAtSemi | StopBeforeMatch);
537e5dd7070Spatrick       return false;
538e5dd7070Spatrick     }
539e5dd7070Spatrick   }
540e5dd7070Spatrick   return true;
541e5dd7070Spatrick }
542e5dd7070Spatrick 
543e5dd7070Spatrick /// Determine whether the parser is at the start of a template
544e5dd7070Spatrick /// type parameter.
isStartOfTemplateTypeParameter()545e5dd7070Spatrick Parser::TPResult Parser::isStartOfTemplateTypeParameter() {
546e5dd7070Spatrick   if (Tok.is(tok::kw_class)) {
547e5dd7070Spatrick     // "class" may be the start of an elaborated-type-specifier or a
548e5dd7070Spatrick     // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
549e5dd7070Spatrick     switch (NextToken().getKind()) {
550e5dd7070Spatrick     case tok::equal:
551e5dd7070Spatrick     case tok::comma:
552e5dd7070Spatrick     case tok::greater:
553e5dd7070Spatrick     case tok::greatergreater:
554e5dd7070Spatrick     case tok::ellipsis:
555e5dd7070Spatrick       return TPResult::True;
556e5dd7070Spatrick 
557e5dd7070Spatrick     case tok::identifier:
558e5dd7070Spatrick       // This may be either a type-parameter or an elaborated-type-specifier.
559e5dd7070Spatrick       // We have to look further.
560e5dd7070Spatrick       break;
561e5dd7070Spatrick 
562e5dd7070Spatrick     default:
563e5dd7070Spatrick       return TPResult::False;
564e5dd7070Spatrick     }
565e5dd7070Spatrick 
566e5dd7070Spatrick     switch (GetLookAheadToken(2).getKind()) {
567e5dd7070Spatrick     case tok::equal:
568e5dd7070Spatrick     case tok::comma:
569e5dd7070Spatrick     case tok::greater:
570e5dd7070Spatrick     case tok::greatergreater:
571e5dd7070Spatrick       return TPResult::True;
572e5dd7070Spatrick 
573e5dd7070Spatrick     default:
574e5dd7070Spatrick       return TPResult::False;
575e5dd7070Spatrick     }
576e5dd7070Spatrick   }
577e5dd7070Spatrick 
578e5dd7070Spatrick   if (TryAnnotateTypeConstraint())
579e5dd7070Spatrick     return TPResult::Error;
580e5dd7070Spatrick 
581e5dd7070Spatrick   if (isTypeConstraintAnnotation() &&
582e5dd7070Spatrick       // Next token might be 'auto' or 'decltype', indicating that this
583e5dd7070Spatrick       // type-constraint is in fact part of a placeholder-type-specifier of a
584e5dd7070Spatrick       // non-type template parameter.
585e5dd7070Spatrick       !GetLookAheadToken(Tok.is(tok::annot_cxxscope) ? 2 : 1)
586e5dd7070Spatrick            .isOneOf(tok::kw_auto, tok::kw_decltype))
587e5dd7070Spatrick     return TPResult::True;
588e5dd7070Spatrick 
589e5dd7070Spatrick   // 'typedef' is a reasonably-common typo/thinko for 'typename', and is
590e5dd7070Spatrick   // ill-formed otherwise.
591e5dd7070Spatrick   if (Tok.isNot(tok::kw_typename) && Tok.isNot(tok::kw_typedef))
592e5dd7070Spatrick     return TPResult::False;
593e5dd7070Spatrick 
594e5dd7070Spatrick   // C++ [temp.param]p2:
595e5dd7070Spatrick   //   There is no semantic difference between class and typename in a
596e5dd7070Spatrick   //   template-parameter. typename followed by an unqualified-id
597e5dd7070Spatrick   //   names a template type parameter. typename followed by a
598e5dd7070Spatrick   //   qualified-id denotes the type in a non-type
599e5dd7070Spatrick   //   parameter-declaration.
600e5dd7070Spatrick   Token Next = NextToken();
601e5dd7070Spatrick 
602e5dd7070Spatrick   // If we have an identifier, skip over it.
603e5dd7070Spatrick   if (Next.getKind() == tok::identifier)
604e5dd7070Spatrick     Next = GetLookAheadToken(2);
605e5dd7070Spatrick 
606e5dd7070Spatrick   switch (Next.getKind()) {
607e5dd7070Spatrick   case tok::equal:
608e5dd7070Spatrick   case tok::comma:
609e5dd7070Spatrick   case tok::greater:
610e5dd7070Spatrick   case tok::greatergreater:
611e5dd7070Spatrick   case tok::ellipsis:
612e5dd7070Spatrick     return TPResult::True;
613e5dd7070Spatrick 
614e5dd7070Spatrick   case tok::kw_typename:
615e5dd7070Spatrick   case tok::kw_typedef:
616e5dd7070Spatrick   case tok::kw_class:
617e5dd7070Spatrick     // These indicate that a comma was missed after a type parameter, not that
618e5dd7070Spatrick     // we have found a non-type parameter.
619e5dd7070Spatrick     return TPResult::True;
620e5dd7070Spatrick 
621e5dd7070Spatrick   default:
622e5dd7070Spatrick     return TPResult::False;
623e5dd7070Spatrick   }
624e5dd7070Spatrick }
625e5dd7070Spatrick 
626e5dd7070Spatrick /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
627e5dd7070Spatrick ///
628e5dd7070Spatrick ///       template-parameter: [C++ temp.param]
629e5dd7070Spatrick ///         type-parameter
630e5dd7070Spatrick ///         parameter-declaration
631e5dd7070Spatrick ///
632e5dd7070Spatrick ///       type-parameter: (See below)
633e5dd7070Spatrick ///         type-parameter-key ...[opt] identifier[opt]
634e5dd7070Spatrick ///         type-parameter-key identifier[opt] = type-id
635e5dd7070Spatrick /// (C++2a) type-constraint ...[opt] identifier[opt]
636e5dd7070Spatrick /// (C++2a) type-constraint identifier[opt] = type-id
637e5dd7070Spatrick ///         'template' '<' template-parameter-list '>' type-parameter-key
638e5dd7070Spatrick ///               ...[opt] identifier[opt]
639e5dd7070Spatrick ///         'template' '<' template-parameter-list '>' type-parameter-key
640e5dd7070Spatrick ///               identifier[opt] '=' id-expression
641e5dd7070Spatrick ///
642e5dd7070Spatrick ///       type-parameter-key:
643e5dd7070Spatrick ///         class
644e5dd7070Spatrick ///         typename
645e5dd7070Spatrick ///
ParseTemplateParameter(unsigned Depth,unsigned Position)646e5dd7070Spatrick NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
647e5dd7070Spatrick 
648e5dd7070Spatrick   switch (isStartOfTemplateTypeParameter()) {
649e5dd7070Spatrick   case TPResult::True:
650e5dd7070Spatrick     // Is there just a typo in the input code? ('typedef' instead of
651e5dd7070Spatrick     // 'typename')
652e5dd7070Spatrick     if (Tok.is(tok::kw_typedef)) {
653e5dd7070Spatrick       Diag(Tok.getLocation(), diag::err_expected_template_parameter);
654e5dd7070Spatrick 
655e5dd7070Spatrick       Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
656e5dd7070Spatrick           << FixItHint::CreateReplacement(CharSourceRange::getCharRange(
657e5dd7070Spatrick                                               Tok.getLocation(),
658e5dd7070Spatrick                                               Tok.getEndLoc()),
659e5dd7070Spatrick                                           "typename");
660e5dd7070Spatrick 
661e5dd7070Spatrick       Tok.setKind(tok::kw_typename);
662e5dd7070Spatrick     }
663e5dd7070Spatrick 
664e5dd7070Spatrick     return ParseTypeParameter(Depth, Position);
665e5dd7070Spatrick   case TPResult::False:
666e5dd7070Spatrick     break;
667e5dd7070Spatrick 
668e5dd7070Spatrick   case TPResult::Error: {
669e5dd7070Spatrick     // We return an invalid parameter as opposed to null to avoid having bogus
670e5dd7070Spatrick     // diagnostics about an empty template parameter list.
671e5dd7070Spatrick     // FIXME: Fix ParseTemplateParameterList to better handle nullptr results
672e5dd7070Spatrick     //  from here.
673e5dd7070Spatrick     // Return a NTTP as if there was an error in a scope specifier, the user
674e5dd7070Spatrick     // probably meant to write the type of a NTTP.
675e5dd7070Spatrick     DeclSpec DS(getAttrFactory());
676e5dd7070Spatrick     DS.SetTypeSpecError();
677*12c85518Srobert     Declarator D(DS, ParsedAttributesView::none(),
678*12c85518Srobert                  DeclaratorContext::TemplateParam);
679e5dd7070Spatrick     D.SetIdentifier(nullptr, Tok.getLocation());
680e5dd7070Spatrick     D.setInvalidType(true);
681e5dd7070Spatrick     NamedDecl *ErrorParam = Actions.ActOnNonTypeTemplateParameter(
682e5dd7070Spatrick         getCurScope(), D, Depth, Position, /*EqualLoc=*/SourceLocation(),
683e5dd7070Spatrick         /*DefaultArg=*/nullptr);
684e5dd7070Spatrick     ErrorParam->setInvalidDecl(true);
685e5dd7070Spatrick     SkipUntil(tok::comma, tok::greater, tok::greatergreater,
686e5dd7070Spatrick               StopAtSemi | StopBeforeMatch);
687e5dd7070Spatrick     return ErrorParam;
688e5dd7070Spatrick   }
689e5dd7070Spatrick 
690e5dd7070Spatrick   case TPResult::Ambiguous:
691e5dd7070Spatrick     llvm_unreachable("template param classification can't be ambiguous");
692e5dd7070Spatrick   }
693e5dd7070Spatrick 
694e5dd7070Spatrick   if (Tok.is(tok::kw_template))
695e5dd7070Spatrick     return ParseTemplateTemplateParameter(Depth, Position);
696e5dd7070Spatrick 
697e5dd7070Spatrick   // If it's none of the above, then it must be a parameter declaration.
698e5dd7070Spatrick   // NOTE: This will pick up errors in the closure of the template parameter
699e5dd7070Spatrick   // list (e.g., template < ; Check here to implement >> style closures.
700e5dd7070Spatrick   return ParseNonTypeTemplateParameter(Depth, Position);
701e5dd7070Spatrick }
702e5dd7070Spatrick 
703e5dd7070Spatrick /// Check whether the current token is a template-id annotation denoting a
704e5dd7070Spatrick /// type-constraint.
isTypeConstraintAnnotation()705e5dd7070Spatrick bool Parser::isTypeConstraintAnnotation() {
706e5dd7070Spatrick   const Token &T = Tok.is(tok::annot_cxxscope) ? NextToken() : Tok;
707e5dd7070Spatrick   if (T.isNot(tok::annot_template_id))
708e5dd7070Spatrick     return false;
709e5dd7070Spatrick   const auto *ExistingAnnot =
710e5dd7070Spatrick       static_cast<TemplateIdAnnotation *>(T.getAnnotationValue());
711e5dd7070Spatrick   return ExistingAnnot->Kind == TNK_Concept_template;
712e5dd7070Spatrick }
713e5dd7070Spatrick 
714e5dd7070Spatrick /// Try parsing a type-constraint at the current location.
715e5dd7070Spatrick ///
716e5dd7070Spatrick ///     type-constraint:
717e5dd7070Spatrick ///       nested-name-specifier[opt] concept-name
718e5dd7070Spatrick ///       nested-name-specifier[opt] concept-name
719e5dd7070Spatrick ///           '<' template-argument-list[opt] '>'[opt]
720e5dd7070Spatrick ///
721e5dd7070Spatrick /// \returns true if an error occurred, and false otherwise.
TryAnnotateTypeConstraint()722e5dd7070Spatrick bool Parser::TryAnnotateTypeConstraint() {
723ec727ea7Spatrick   if (!getLangOpts().CPlusPlus20)
724e5dd7070Spatrick     return false;
725e5dd7070Spatrick   CXXScopeSpec SS;
726e5dd7070Spatrick   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
727ec727ea7Spatrick   if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
728*12c85518Srobert                                      /*ObjectHasErrors=*/false,
729e5dd7070Spatrick                                      /*EnteringContext=*/false,
730e5dd7070Spatrick                                      /*MayBePseudoDestructor=*/nullptr,
731e5dd7070Spatrick                                      // If this is not a type-constraint, then
732e5dd7070Spatrick                                      // this scope-spec is part of the typename
733e5dd7070Spatrick                                      // of a non-type template parameter
734e5dd7070Spatrick                                      /*IsTypename=*/true, /*LastII=*/nullptr,
735e5dd7070Spatrick                                      // We won't find concepts in
736e5dd7070Spatrick                                      // non-namespaces anyway, so might as well
737e5dd7070Spatrick                                      // parse this correctly for possible type
738e5dd7070Spatrick                                      // names.
739e5dd7070Spatrick                                      /*OnlyNamespace=*/false))
740e5dd7070Spatrick     return true;
741e5dd7070Spatrick 
742e5dd7070Spatrick   if (Tok.is(tok::identifier)) {
743e5dd7070Spatrick     UnqualifiedId PossibleConceptName;
744e5dd7070Spatrick     PossibleConceptName.setIdentifier(Tok.getIdentifierInfo(),
745e5dd7070Spatrick                                       Tok.getLocation());
746e5dd7070Spatrick 
747e5dd7070Spatrick     TemplateTy PossibleConcept;
748e5dd7070Spatrick     bool MemberOfUnknownSpecialization = false;
749e5dd7070Spatrick     auto TNK = Actions.isTemplateName(getCurScope(), SS,
750e5dd7070Spatrick                                       /*hasTemplateKeyword=*/false,
751e5dd7070Spatrick                                       PossibleConceptName,
752e5dd7070Spatrick                                       /*ObjectType=*/ParsedType(),
753e5dd7070Spatrick                                       /*EnteringContext=*/false,
754e5dd7070Spatrick                                       PossibleConcept,
755e5dd7070Spatrick                                       MemberOfUnknownSpecialization,
756e5dd7070Spatrick                                       /*Disambiguation=*/true);
757e5dd7070Spatrick     if (MemberOfUnknownSpecialization || !PossibleConcept ||
758e5dd7070Spatrick         TNK != TNK_Concept_template) {
759e5dd7070Spatrick       if (SS.isNotEmpty())
760e5dd7070Spatrick         AnnotateScopeToken(SS, !WasScopeAnnotation);
761e5dd7070Spatrick       return false;
762e5dd7070Spatrick     }
763e5dd7070Spatrick 
764e5dd7070Spatrick     // At this point we're sure we're dealing with a constrained parameter. It
765e5dd7070Spatrick     // may or may not have a template parameter list following the concept
766e5dd7070Spatrick     // name.
767e5dd7070Spatrick     if (AnnotateTemplateIdToken(PossibleConcept, TNK, SS,
768e5dd7070Spatrick                                    /*TemplateKWLoc=*/SourceLocation(),
769e5dd7070Spatrick                                    PossibleConceptName,
770e5dd7070Spatrick                                    /*AllowTypeAnnotation=*/false,
771e5dd7070Spatrick                                    /*TypeConstraint=*/true))
772e5dd7070Spatrick       return true;
773e5dd7070Spatrick   }
774e5dd7070Spatrick 
775e5dd7070Spatrick   if (SS.isNotEmpty())
776e5dd7070Spatrick     AnnotateScopeToken(SS, !WasScopeAnnotation);
777e5dd7070Spatrick   return false;
778e5dd7070Spatrick }
779e5dd7070Spatrick 
780e5dd7070Spatrick /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
781e5dd7070Spatrick /// Other kinds of template parameters are parsed in
782e5dd7070Spatrick /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
783e5dd7070Spatrick ///
784e5dd7070Spatrick ///       type-parameter:     [C++ temp.param]
785e5dd7070Spatrick ///         'class' ...[opt][C++0x] identifier[opt]
786e5dd7070Spatrick ///         'class' identifier[opt] '=' type-id
787e5dd7070Spatrick ///         'typename' ...[opt][C++0x] identifier[opt]
788e5dd7070Spatrick ///         'typename' identifier[opt] '=' type-id
ParseTypeParameter(unsigned Depth,unsigned Position)789e5dd7070Spatrick NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
790e5dd7070Spatrick   assert((Tok.isOneOf(tok::kw_class, tok::kw_typename) ||
791e5dd7070Spatrick           isTypeConstraintAnnotation()) &&
792e5dd7070Spatrick          "A type-parameter starts with 'class', 'typename' or a "
793e5dd7070Spatrick          "type-constraint");
794e5dd7070Spatrick 
795e5dd7070Spatrick   CXXScopeSpec TypeConstraintSS;
796e5dd7070Spatrick   TemplateIdAnnotation *TypeConstraint = nullptr;
797e5dd7070Spatrick   bool TypenameKeyword = false;
798e5dd7070Spatrick   SourceLocation KeyLoc;
799ec727ea7Spatrick   ParseOptionalCXXScopeSpecifier(TypeConstraintSS, /*ObjectType=*/nullptr,
800*12c85518Srobert                                  /*ObjectHasErrors=*/false,
801e5dd7070Spatrick                                  /*EnteringContext*/ false);
802e5dd7070Spatrick   if (Tok.is(tok::annot_template_id)) {
803e5dd7070Spatrick     // Consume the 'type-constraint'.
804e5dd7070Spatrick     TypeConstraint =
805e5dd7070Spatrick         static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
806e5dd7070Spatrick     assert(TypeConstraint->Kind == TNK_Concept_template &&
807e5dd7070Spatrick            "stray non-concept template-id annotation");
808e5dd7070Spatrick     KeyLoc = ConsumeAnnotationToken();
809e5dd7070Spatrick   } else {
810e5dd7070Spatrick     assert(TypeConstraintSS.isEmpty() &&
811e5dd7070Spatrick            "expected type constraint after scope specifier");
812e5dd7070Spatrick 
813e5dd7070Spatrick     // Consume the 'class' or 'typename' keyword.
814e5dd7070Spatrick     TypenameKeyword = Tok.is(tok::kw_typename);
815e5dd7070Spatrick     KeyLoc = ConsumeToken();
816e5dd7070Spatrick   }
817e5dd7070Spatrick 
818e5dd7070Spatrick   // Grab the ellipsis (if given).
819e5dd7070Spatrick   SourceLocation EllipsisLoc;
820e5dd7070Spatrick   if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
821e5dd7070Spatrick     Diag(EllipsisLoc,
822e5dd7070Spatrick          getLangOpts().CPlusPlus11
823e5dd7070Spatrick            ? diag::warn_cxx98_compat_variadic_templates
824e5dd7070Spatrick            : diag::ext_variadic_templates);
825e5dd7070Spatrick   }
826e5dd7070Spatrick 
827e5dd7070Spatrick   // Grab the template parameter name (if given)
828e5dd7070Spatrick   SourceLocation NameLoc = Tok.getLocation();
829e5dd7070Spatrick   IdentifierInfo *ParamName = nullptr;
830e5dd7070Spatrick   if (Tok.is(tok::identifier)) {
831e5dd7070Spatrick     ParamName = Tok.getIdentifierInfo();
832e5dd7070Spatrick     ConsumeToken();
833e5dd7070Spatrick   } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
834e5dd7070Spatrick                          tok::greatergreater)) {
835e5dd7070Spatrick     // Unnamed template parameter. Don't have to do anything here, just
836e5dd7070Spatrick     // don't consume this token.
837e5dd7070Spatrick   } else {
838e5dd7070Spatrick     Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
839e5dd7070Spatrick     return nullptr;
840e5dd7070Spatrick   }
841e5dd7070Spatrick 
842e5dd7070Spatrick   // Recover from misplaced ellipsis.
843e5dd7070Spatrick   bool AlreadyHasEllipsis = EllipsisLoc.isValid();
844e5dd7070Spatrick   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
845e5dd7070Spatrick     DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
846e5dd7070Spatrick 
847e5dd7070Spatrick   // Grab a default argument (if available).
848e5dd7070Spatrick   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
849e5dd7070Spatrick   // we introduce the type parameter into the local scope.
850e5dd7070Spatrick   SourceLocation EqualLoc;
851e5dd7070Spatrick   ParsedType DefaultArg;
852e5dd7070Spatrick   if (TryConsumeToken(tok::equal, EqualLoc))
853a9ac8606Spatrick     DefaultArg =
854a9ac8606Spatrick         ParseTypeName(/*Range=*/nullptr, DeclaratorContext::TemplateTypeArg)
855e5dd7070Spatrick             .get();
856e5dd7070Spatrick 
857e5dd7070Spatrick   NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(),
858e5dd7070Spatrick                                                   TypenameKeyword, EllipsisLoc,
859e5dd7070Spatrick                                                   KeyLoc, ParamName, NameLoc,
860e5dd7070Spatrick                                                   Depth, Position, EqualLoc,
861e5dd7070Spatrick                                                   DefaultArg,
862e5dd7070Spatrick                                                   TypeConstraint != nullptr);
863e5dd7070Spatrick 
864e5dd7070Spatrick   if (TypeConstraint) {
865e5dd7070Spatrick     Actions.ActOnTypeConstraint(TypeConstraintSS, TypeConstraint,
866e5dd7070Spatrick                                 cast<TemplateTypeParmDecl>(NewDecl),
867e5dd7070Spatrick                                 EllipsisLoc);
868e5dd7070Spatrick   }
869e5dd7070Spatrick 
870e5dd7070Spatrick   return NewDecl;
871e5dd7070Spatrick }
872e5dd7070Spatrick 
873e5dd7070Spatrick /// ParseTemplateTemplateParameter - Handle the parsing of template
874e5dd7070Spatrick /// template parameters.
875e5dd7070Spatrick ///
876e5dd7070Spatrick ///       type-parameter:    [C++ temp.param]
877*12c85518Srobert ///         template-head type-parameter-key ...[opt] identifier[opt]
878*12c85518Srobert ///         template-head type-parameter-key identifier[opt] = id-expression
879e5dd7070Spatrick ///       type-parameter-key:
880e5dd7070Spatrick ///         'class'
881e5dd7070Spatrick ///         'typename'       [C++1z]
882*12c85518Srobert ///       template-head:     [C++2a]
883*12c85518Srobert ///         'template' '<' template-parameter-list '>'
884*12c85518Srobert ///             requires-clause[opt]
ParseTemplateTemplateParameter(unsigned Depth,unsigned Position)885*12c85518Srobert NamedDecl *Parser::ParseTemplateTemplateParameter(unsigned Depth,
886*12c85518Srobert                                                   unsigned Position) {
887e5dd7070Spatrick   assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
888e5dd7070Spatrick 
889e5dd7070Spatrick   // Handle the template <...> part.
890e5dd7070Spatrick   SourceLocation TemplateLoc = ConsumeToken();
891e5dd7070Spatrick   SmallVector<NamedDecl*,8> TemplateParams;
892e5dd7070Spatrick   SourceLocation LAngleLoc, RAngleLoc;
893*12c85518Srobert   ExprResult OptionalRequiresClauseConstraintER;
894e5dd7070Spatrick   {
895ec727ea7Spatrick     MultiParseScope TemplateParmScope(*this);
896ec727ea7Spatrick     if (ParseTemplateParameters(TemplateParmScope, Depth + 1, TemplateParams,
897ec727ea7Spatrick                                 LAngleLoc, RAngleLoc)) {
898e5dd7070Spatrick       return nullptr;
899e5dd7070Spatrick     }
900*12c85518Srobert     if (TryConsumeToken(tok::kw_requires)) {
901*12c85518Srobert       OptionalRequiresClauseConstraintER =
902*12c85518Srobert           Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
903*12c85518Srobert               /*IsTrailingRequiresClause=*/false));
904*12c85518Srobert       if (!OptionalRequiresClauseConstraintER.isUsable()) {
905*12c85518Srobert         SkipUntil(tok::comma, tok::greater, tok::greatergreater,
906*12c85518Srobert                   StopAtSemi | StopBeforeMatch);
907*12c85518Srobert         return nullptr;
908*12c85518Srobert       }
909*12c85518Srobert     }
910e5dd7070Spatrick   }
911e5dd7070Spatrick 
912e5dd7070Spatrick   // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
913e5dd7070Spatrick   // Generate a meaningful error if the user forgot to put class before the
914e5dd7070Spatrick   // identifier, comma, or greater. Provide a fixit if the identifier, comma,
915e5dd7070Spatrick   // or greater appear immediately or after 'struct'. In the latter case,
916e5dd7070Spatrick   // replace the keyword with 'class'.
917e5dd7070Spatrick   if (!TryConsumeToken(tok::kw_class)) {
918e5dd7070Spatrick     bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
919e5dd7070Spatrick     const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
920e5dd7070Spatrick     if (Tok.is(tok::kw_typename)) {
921e5dd7070Spatrick       Diag(Tok.getLocation(),
922e5dd7070Spatrick            getLangOpts().CPlusPlus17
923e5dd7070Spatrick                ? diag::warn_cxx14_compat_template_template_param_typename
924e5dd7070Spatrick                : diag::ext_template_template_param_typename)
925e5dd7070Spatrick         << (!getLangOpts().CPlusPlus17
926e5dd7070Spatrick                 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
927e5dd7070Spatrick                 : FixItHint());
928e5dd7070Spatrick     } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
929e5dd7070Spatrick                             tok::greatergreater, tok::ellipsis)) {
930e5dd7070Spatrick       Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
931*12c85518Srobert           << getLangOpts().CPlusPlus17
932*12c85518Srobert           << (Replace
933*12c85518Srobert                   ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
934e5dd7070Spatrick                   : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
935e5dd7070Spatrick     } else
936*12c85518Srobert       Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
937*12c85518Srobert           << getLangOpts().CPlusPlus17;
938e5dd7070Spatrick 
939e5dd7070Spatrick     if (Replace)
940e5dd7070Spatrick       ConsumeToken();
941e5dd7070Spatrick   }
942e5dd7070Spatrick 
943e5dd7070Spatrick   // Parse the ellipsis, if given.
944e5dd7070Spatrick   SourceLocation EllipsisLoc;
945e5dd7070Spatrick   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
946e5dd7070Spatrick     Diag(EllipsisLoc,
947e5dd7070Spatrick          getLangOpts().CPlusPlus11
948e5dd7070Spatrick            ? diag::warn_cxx98_compat_variadic_templates
949e5dd7070Spatrick            : diag::ext_variadic_templates);
950e5dd7070Spatrick 
951e5dd7070Spatrick   // Get the identifier, if given.
952e5dd7070Spatrick   SourceLocation NameLoc = Tok.getLocation();
953e5dd7070Spatrick   IdentifierInfo *ParamName = nullptr;
954e5dd7070Spatrick   if (Tok.is(tok::identifier)) {
955e5dd7070Spatrick     ParamName = Tok.getIdentifierInfo();
956e5dd7070Spatrick     ConsumeToken();
957e5dd7070Spatrick   } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
958e5dd7070Spatrick                          tok::greatergreater)) {
959e5dd7070Spatrick     // Unnamed template parameter. Don't have to do anything here, just
960e5dd7070Spatrick     // don't consume this token.
961e5dd7070Spatrick   } else {
962e5dd7070Spatrick     Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
963e5dd7070Spatrick     return nullptr;
964e5dd7070Spatrick   }
965e5dd7070Spatrick 
966e5dd7070Spatrick   // Recover from misplaced ellipsis.
967e5dd7070Spatrick   bool AlreadyHasEllipsis = EllipsisLoc.isValid();
968e5dd7070Spatrick   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
969e5dd7070Spatrick     DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
970e5dd7070Spatrick 
971*12c85518Srobert   TemplateParameterList *ParamList = Actions.ActOnTemplateParameterList(
972*12c85518Srobert       Depth, SourceLocation(), TemplateLoc, LAngleLoc, TemplateParams,
973*12c85518Srobert       RAngleLoc, OptionalRequiresClauseConstraintER.get());
974e5dd7070Spatrick 
975e5dd7070Spatrick   // Grab a default argument (if available).
976e5dd7070Spatrick   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
977e5dd7070Spatrick   // we introduce the template parameter into the local scope.
978e5dd7070Spatrick   SourceLocation EqualLoc;
979e5dd7070Spatrick   ParsedTemplateArgument DefaultArg;
980e5dd7070Spatrick   if (TryConsumeToken(tok::equal, EqualLoc)) {
981e5dd7070Spatrick     DefaultArg = ParseTemplateTemplateArgument();
982e5dd7070Spatrick     if (DefaultArg.isInvalid()) {
983e5dd7070Spatrick       Diag(Tok.getLocation(),
984e5dd7070Spatrick            diag::err_default_template_template_parameter_not_template);
985e5dd7070Spatrick       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
986e5dd7070Spatrick                 StopAtSemi | StopBeforeMatch);
987e5dd7070Spatrick     }
988e5dd7070Spatrick   }
989e5dd7070Spatrick 
990e5dd7070Spatrick   return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
991e5dd7070Spatrick                                                 ParamList, EllipsisLoc,
992e5dd7070Spatrick                                                 ParamName, NameLoc, Depth,
993e5dd7070Spatrick                                                 Position, EqualLoc, DefaultArg);
994e5dd7070Spatrick }
995e5dd7070Spatrick 
996e5dd7070Spatrick /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
997e5dd7070Spatrick /// template parameters (e.g., in "template<int Size> class array;").
998e5dd7070Spatrick ///
999e5dd7070Spatrick ///       template-parameter:
1000e5dd7070Spatrick ///         ...
1001e5dd7070Spatrick ///         parameter-declaration
1002e5dd7070Spatrick NamedDecl *
ParseNonTypeTemplateParameter(unsigned Depth,unsigned Position)1003e5dd7070Spatrick Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
1004e5dd7070Spatrick   // Parse the declaration-specifiers (i.e., the type).
1005e5dd7070Spatrick   // FIXME: The type should probably be restricted in some way... Not all
1006e5dd7070Spatrick   // declarators (parts of declarators?) are accepted for parameters.
1007e5dd7070Spatrick   DeclSpec DS(AttrFactory);
1008e5dd7070Spatrick   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
1009e5dd7070Spatrick                              DeclSpecContext::DSC_template_param);
1010e5dd7070Spatrick 
1011e5dd7070Spatrick   // Parse this as a typename.
1012*12c85518Srobert   Declarator ParamDecl(DS, ParsedAttributesView::none(),
1013*12c85518Srobert                        DeclaratorContext::TemplateParam);
1014e5dd7070Spatrick   ParseDeclarator(ParamDecl);
1015e5dd7070Spatrick   if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
1016e5dd7070Spatrick     Diag(Tok.getLocation(), diag::err_expected_template_parameter);
1017e5dd7070Spatrick     return nullptr;
1018e5dd7070Spatrick   }
1019e5dd7070Spatrick 
1020e5dd7070Spatrick   // Recover from misplaced ellipsis.
1021e5dd7070Spatrick   SourceLocation EllipsisLoc;
1022e5dd7070Spatrick   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1023e5dd7070Spatrick     DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
1024e5dd7070Spatrick 
1025e5dd7070Spatrick   // If there is a default value, parse it.
1026e5dd7070Spatrick   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
1027e5dd7070Spatrick   // we introduce the template parameter into the local scope.
1028e5dd7070Spatrick   SourceLocation EqualLoc;
1029e5dd7070Spatrick   ExprResult DefaultArg;
1030e5dd7070Spatrick   if (TryConsumeToken(tok::equal, EqualLoc)) {
1031*12c85518Srobert     if (Tok.is(tok::l_paren) && NextToken().is(tok::l_brace)) {
1032*12c85518Srobert       Diag(Tok.getLocation(), diag::err_stmt_expr_in_default_arg) << 1;
1033*12c85518Srobert       SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1034*12c85518Srobert     } else {
1035e5dd7070Spatrick       // C++ [temp.param]p15:
1036e5dd7070Spatrick       //   When parsing a default template-argument for a non-type
1037e5dd7070Spatrick       //   template-parameter, the first non-nested > is taken as the
1038e5dd7070Spatrick       //   end of the template-parameter-list rather than a greater-than
1039e5dd7070Spatrick       //   operator.
1040e5dd7070Spatrick       GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1041e5dd7070Spatrick       EnterExpressionEvaluationContext ConstantEvaluated(
1042e5dd7070Spatrick           Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1043*12c85518Srobert       DefaultArg =
1044*12c85518Srobert           Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
1045e5dd7070Spatrick       if (DefaultArg.isInvalid())
1046e5dd7070Spatrick         SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1047e5dd7070Spatrick     }
1048*12c85518Srobert   }
1049e5dd7070Spatrick 
1050e5dd7070Spatrick   // Create the parameter.
1051e5dd7070Spatrick   return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
1052e5dd7070Spatrick                                                Depth, Position, EqualLoc,
1053e5dd7070Spatrick                                                DefaultArg.get());
1054e5dd7070Spatrick }
1055e5dd7070Spatrick 
DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,SourceLocation CorrectLoc,bool AlreadyHasEllipsis,bool IdentifierHasName)1056e5dd7070Spatrick void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
1057e5dd7070Spatrick                                        SourceLocation CorrectLoc,
1058e5dd7070Spatrick                                        bool AlreadyHasEllipsis,
1059e5dd7070Spatrick                                        bool IdentifierHasName) {
1060e5dd7070Spatrick   FixItHint Insertion;
1061e5dd7070Spatrick   if (!AlreadyHasEllipsis)
1062e5dd7070Spatrick     Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
1063e5dd7070Spatrick   Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
1064e5dd7070Spatrick       << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
1065e5dd7070Spatrick       << !IdentifierHasName;
1066e5dd7070Spatrick }
1067e5dd7070Spatrick 
DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,Declarator & D)1068e5dd7070Spatrick void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
1069e5dd7070Spatrick                                                    Declarator &D) {
1070e5dd7070Spatrick   assert(EllipsisLoc.isValid());
1071e5dd7070Spatrick   bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
1072e5dd7070Spatrick   if (!AlreadyHasEllipsis)
1073e5dd7070Spatrick     D.setEllipsisLoc(EllipsisLoc);
1074e5dd7070Spatrick   DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
1075e5dd7070Spatrick                             AlreadyHasEllipsis, D.hasName());
1076e5dd7070Spatrick }
1077e5dd7070Spatrick 
1078e5dd7070Spatrick /// Parses a '>' at the end of a template list.
1079e5dd7070Spatrick ///
1080e5dd7070Spatrick /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
1081e5dd7070Spatrick /// to determine if these tokens were supposed to be a '>' followed by
1082e5dd7070Spatrick /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
1083e5dd7070Spatrick ///
1084e5dd7070Spatrick /// \param RAngleLoc the location of the consumed '>'.
1085e5dd7070Spatrick ///
1086e5dd7070Spatrick /// \param ConsumeLastToken if true, the '>' is consumed.
1087e5dd7070Spatrick ///
1088e5dd7070Spatrick /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
1089e5dd7070Spatrick /// type parameter or type argument list, rather than a C++ template parameter
1090e5dd7070Spatrick /// or argument list.
1091e5dd7070Spatrick ///
1092e5dd7070Spatrick /// \returns true, if current token does not start with '>', false otherwise.
ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,SourceLocation & RAngleLoc,bool ConsumeLastToken,bool ObjCGenericList)1093ec727ea7Spatrick bool Parser::ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
1094ec727ea7Spatrick                                             SourceLocation &RAngleLoc,
1095e5dd7070Spatrick                                             bool ConsumeLastToken,
1096e5dd7070Spatrick                                             bool ObjCGenericList) {
1097e5dd7070Spatrick   // What will be left once we've consumed the '>'.
1098e5dd7070Spatrick   tok::TokenKind RemainingToken;
1099e5dd7070Spatrick   const char *ReplacementStr = "> >";
1100e5dd7070Spatrick   bool MergeWithNextToken = false;
1101e5dd7070Spatrick 
1102e5dd7070Spatrick   switch (Tok.getKind()) {
1103e5dd7070Spatrick   default:
1104ec727ea7Spatrick     Diag(getEndOfPreviousToken(), diag::err_expected) << tok::greater;
1105ec727ea7Spatrick     Diag(LAngleLoc, diag::note_matching) << tok::less;
1106e5dd7070Spatrick     return true;
1107e5dd7070Spatrick 
1108e5dd7070Spatrick   case tok::greater:
1109e5dd7070Spatrick     // Determine the location of the '>' token. Only consume this token
1110e5dd7070Spatrick     // if the caller asked us to.
1111e5dd7070Spatrick     RAngleLoc = Tok.getLocation();
1112e5dd7070Spatrick     if (ConsumeLastToken)
1113e5dd7070Spatrick       ConsumeToken();
1114e5dd7070Spatrick     return false;
1115e5dd7070Spatrick 
1116e5dd7070Spatrick   case tok::greatergreater:
1117e5dd7070Spatrick     RemainingToken = tok::greater;
1118e5dd7070Spatrick     break;
1119e5dd7070Spatrick 
1120e5dd7070Spatrick   case tok::greatergreatergreater:
1121e5dd7070Spatrick     RemainingToken = tok::greatergreater;
1122e5dd7070Spatrick     break;
1123e5dd7070Spatrick 
1124e5dd7070Spatrick   case tok::greaterequal:
1125e5dd7070Spatrick     RemainingToken = tok::equal;
1126e5dd7070Spatrick     ReplacementStr = "> =";
1127e5dd7070Spatrick 
1128e5dd7070Spatrick     // Join two adjacent '=' tokens into one, for cases like:
1129e5dd7070Spatrick     //   void (*p)() = f<int>;
1130e5dd7070Spatrick     //   return f<int>==p;
1131e5dd7070Spatrick     if (NextToken().is(tok::equal) &&
1132e5dd7070Spatrick         areTokensAdjacent(Tok, NextToken())) {
1133e5dd7070Spatrick       RemainingToken = tok::equalequal;
1134e5dd7070Spatrick       MergeWithNextToken = true;
1135e5dd7070Spatrick     }
1136e5dd7070Spatrick     break;
1137e5dd7070Spatrick 
1138e5dd7070Spatrick   case tok::greatergreaterequal:
1139e5dd7070Spatrick     RemainingToken = tok::greaterequal;
1140e5dd7070Spatrick     break;
1141e5dd7070Spatrick   }
1142e5dd7070Spatrick 
1143e5dd7070Spatrick   // This template-id is terminated by a token that starts with a '>'.
1144e5dd7070Spatrick   // Outside C++11 and Objective-C, this is now error recovery.
1145e5dd7070Spatrick   //
1146e5dd7070Spatrick   // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
1147e5dd7070Spatrick   // extend that treatment to also apply to the '>>>' token.
1148e5dd7070Spatrick   //
1149e5dd7070Spatrick   // Objective-C allows this in its type parameter / argument lists.
1150e5dd7070Spatrick 
1151e5dd7070Spatrick   SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
1152e5dd7070Spatrick   SourceLocation TokLoc = Tok.getLocation();
1153e5dd7070Spatrick   Token Next = NextToken();
1154e5dd7070Spatrick 
1155e5dd7070Spatrick   // Whether splitting the current token after the '>' would undesirably result
1156e5dd7070Spatrick   // in the remaining token pasting with the token after it. This excludes the
1157e5dd7070Spatrick   // MergeWithNextToken cases, which we've already handled.
1158e5dd7070Spatrick   bool PreventMergeWithNextToken =
1159e5dd7070Spatrick       (RemainingToken == tok::greater ||
1160e5dd7070Spatrick        RemainingToken == tok::greatergreater) &&
1161e5dd7070Spatrick       (Next.isOneOf(tok::greater, tok::greatergreater,
1162e5dd7070Spatrick                     tok::greatergreatergreater, tok::equal, tok::greaterequal,
1163e5dd7070Spatrick                     tok::greatergreaterequal, tok::equalequal)) &&
1164e5dd7070Spatrick       areTokensAdjacent(Tok, Next);
1165e5dd7070Spatrick 
1166e5dd7070Spatrick   // Diagnose this situation as appropriate.
1167e5dd7070Spatrick   if (!ObjCGenericList) {
1168e5dd7070Spatrick     // The source range of the replaced token(s).
1169e5dd7070Spatrick     CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
1170e5dd7070Spatrick         TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(),
1171e5dd7070Spatrick                                                getLangOpts()));
1172e5dd7070Spatrick 
1173e5dd7070Spatrick     // A hint to put a space between the '>>'s. In order to make the hint as
1174e5dd7070Spatrick     // clear as possible, we include the characters either side of the space in
1175e5dd7070Spatrick     // the replacement, rather than just inserting a space at SecondCharLoc.
1176e5dd7070Spatrick     FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
1177e5dd7070Spatrick                                                    ReplacementStr);
1178e5dd7070Spatrick 
1179e5dd7070Spatrick     // A hint to put another space after the token, if it would otherwise be
1180e5dd7070Spatrick     // lexed differently.
1181e5dd7070Spatrick     FixItHint Hint2;
1182e5dd7070Spatrick     if (PreventMergeWithNextToken)
1183e5dd7070Spatrick       Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
1184e5dd7070Spatrick 
1185e5dd7070Spatrick     unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
1186e5dd7070Spatrick     if (getLangOpts().CPlusPlus11 &&
1187e5dd7070Spatrick         (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
1188e5dd7070Spatrick       DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
1189e5dd7070Spatrick     else if (Tok.is(tok::greaterequal))
1190e5dd7070Spatrick       DiagId = diag::err_right_angle_bracket_equal_needs_space;
1191e5dd7070Spatrick     Diag(TokLoc, DiagId) << Hint1 << Hint2;
1192e5dd7070Spatrick   }
1193e5dd7070Spatrick 
1194e5dd7070Spatrick   // Find the "length" of the resulting '>' token. This is not always 1, as it
1195e5dd7070Spatrick   // can contain escaped newlines.
1196e5dd7070Spatrick   unsigned GreaterLength = Lexer::getTokenPrefixLength(
1197e5dd7070Spatrick       TokLoc, 1, PP.getSourceManager(), getLangOpts());
1198e5dd7070Spatrick 
1199e5dd7070Spatrick   // Annotate the source buffer to indicate that we split the token after the
1200e5dd7070Spatrick   // '>'. This allows us to properly find the end of, and extract the spelling
1201e5dd7070Spatrick   // of, the '>' token later.
1202e5dd7070Spatrick   RAngleLoc = PP.SplitToken(TokLoc, GreaterLength);
1203e5dd7070Spatrick 
1204e5dd7070Spatrick   // Strip the initial '>' from the token.
1205e5dd7070Spatrick   bool CachingTokens = PP.IsPreviousCachedToken(Tok);
1206e5dd7070Spatrick 
1207e5dd7070Spatrick   Token Greater = Tok;
1208e5dd7070Spatrick   Greater.setLocation(RAngleLoc);
1209e5dd7070Spatrick   Greater.setKind(tok::greater);
1210e5dd7070Spatrick   Greater.setLength(GreaterLength);
1211e5dd7070Spatrick 
1212e5dd7070Spatrick   unsigned OldLength = Tok.getLength();
1213e5dd7070Spatrick   if (MergeWithNextToken) {
1214e5dd7070Spatrick     ConsumeToken();
1215e5dd7070Spatrick     OldLength += Tok.getLength();
1216e5dd7070Spatrick   }
1217e5dd7070Spatrick 
1218e5dd7070Spatrick   Tok.setKind(RemainingToken);
1219e5dd7070Spatrick   Tok.setLength(OldLength - GreaterLength);
1220e5dd7070Spatrick 
1221e5dd7070Spatrick   // Split the second token if lexing it normally would lex a different token
1222e5dd7070Spatrick   // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
1223e5dd7070Spatrick   SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength);
1224e5dd7070Spatrick   if (PreventMergeWithNextToken)
1225e5dd7070Spatrick     AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength());
1226e5dd7070Spatrick   Tok.setLocation(AfterGreaterLoc);
1227e5dd7070Spatrick 
1228e5dd7070Spatrick   // Update the token cache to match what we just did if necessary.
1229e5dd7070Spatrick   if (CachingTokens) {
1230e5dd7070Spatrick     // If the previous cached token is being merged, delete it.
1231e5dd7070Spatrick     if (MergeWithNextToken)
1232e5dd7070Spatrick       PP.ReplacePreviousCachedToken({});
1233e5dd7070Spatrick 
1234e5dd7070Spatrick     if (ConsumeLastToken)
1235e5dd7070Spatrick       PP.ReplacePreviousCachedToken({Greater, Tok});
1236e5dd7070Spatrick     else
1237e5dd7070Spatrick       PP.ReplacePreviousCachedToken({Greater});
1238e5dd7070Spatrick   }
1239e5dd7070Spatrick 
1240e5dd7070Spatrick   if (ConsumeLastToken) {
1241e5dd7070Spatrick     PrevTokLocation = RAngleLoc;
1242e5dd7070Spatrick   } else {
1243e5dd7070Spatrick     PrevTokLocation = TokBeforeGreaterLoc;
1244e5dd7070Spatrick     PP.EnterToken(Tok, /*IsReinject=*/true);
1245e5dd7070Spatrick     Tok = Greater;
1246e5dd7070Spatrick   }
1247e5dd7070Spatrick 
1248e5dd7070Spatrick   return false;
1249e5dd7070Spatrick }
1250e5dd7070Spatrick 
1251e5dd7070Spatrick /// Parses a template-id that after the template name has
1252e5dd7070Spatrick /// already been parsed.
1253e5dd7070Spatrick ///
1254e5dd7070Spatrick /// This routine takes care of parsing the enclosed template argument
1255e5dd7070Spatrick /// list ('<' template-parameter-list [opt] '>') and placing the
1256e5dd7070Spatrick /// results into a form that can be transferred to semantic analysis.
1257e5dd7070Spatrick ///
1258e5dd7070Spatrick /// \param ConsumeLastToken if true, then we will consume the last
1259e5dd7070Spatrick /// token that forms the template-id. Otherwise, we will leave the
1260e5dd7070Spatrick /// last token in the stream (e.g., so that it can be replaced with an
1261e5dd7070Spatrick /// annotation token).
ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,SourceLocation & LAngleLoc,TemplateArgList & TemplateArgs,SourceLocation & RAngleLoc,TemplateTy Template)1262*12c85518Srobert bool Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
1263e5dd7070Spatrick                                               SourceLocation &LAngleLoc,
1264e5dd7070Spatrick                                               TemplateArgList &TemplateArgs,
1265*12c85518Srobert                                               SourceLocation &RAngleLoc,
1266*12c85518Srobert                                               TemplateTy Template) {
1267e5dd7070Spatrick   assert(Tok.is(tok::less) && "Must have already parsed the template-name");
1268e5dd7070Spatrick 
1269e5dd7070Spatrick   // Consume the '<'.
1270e5dd7070Spatrick   LAngleLoc = ConsumeToken();
1271e5dd7070Spatrick 
1272e5dd7070Spatrick   // Parse the optional template-argument-list.
1273e5dd7070Spatrick   bool Invalid = false;
1274e5dd7070Spatrick   {
1275e5dd7070Spatrick     GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1276e5dd7070Spatrick     if (!Tok.isOneOf(tok::greater, tok::greatergreater,
1277e5dd7070Spatrick                      tok::greatergreatergreater, tok::greaterequal,
1278e5dd7070Spatrick                      tok::greatergreaterequal))
1279*12c85518Srobert       Invalid = ParseTemplateArgumentList(TemplateArgs, Template, LAngleLoc);
1280e5dd7070Spatrick 
1281e5dd7070Spatrick     if (Invalid) {
1282e5dd7070Spatrick       // Try to find the closing '>'.
1283ec727ea7Spatrick       if (getLangOpts().CPlusPlus11)
1284ec727ea7Spatrick         SkipUntil(tok::greater, tok::greatergreater,
1285ec727ea7Spatrick                   tok::greatergreatergreater, StopAtSemi | StopBeforeMatch);
1286e5dd7070Spatrick       else
1287e5dd7070Spatrick         SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
1288e5dd7070Spatrick     }
1289e5dd7070Spatrick   }
1290e5dd7070Spatrick 
1291ec727ea7Spatrick   return ParseGreaterThanInTemplateList(LAngleLoc, RAngleLoc, ConsumeLastToken,
1292ec727ea7Spatrick                                         /*ObjCGenericList=*/false) ||
1293ec727ea7Spatrick          Invalid;
1294e5dd7070Spatrick }
1295e5dd7070Spatrick 
1296e5dd7070Spatrick /// Replace the tokens that form a simple-template-id with an
1297e5dd7070Spatrick /// annotation token containing the complete template-id.
1298e5dd7070Spatrick ///
1299e5dd7070Spatrick /// The first token in the stream must be the name of a template that
1300e5dd7070Spatrick /// is followed by a '<'. This routine will parse the complete
1301e5dd7070Spatrick /// simple-template-id and replace the tokens with a single annotation
1302e5dd7070Spatrick /// token with one of two different kinds: if the template-id names a
1303e5dd7070Spatrick /// type (and \p AllowTypeAnnotation is true), the annotation token is
1304e5dd7070Spatrick /// a type annotation that includes the optional nested-name-specifier
1305e5dd7070Spatrick /// (\p SS). Otherwise, the annotation token is a template-id
1306e5dd7070Spatrick /// annotation that does not include the optional
1307e5dd7070Spatrick /// nested-name-specifier.
1308e5dd7070Spatrick ///
1309e5dd7070Spatrick /// \param Template  the declaration of the template named by the first
1310e5dd7070Spatrick /// token (an identifier), as returned from \c Action::isTemplateName().
1311e5dd7070Spatrick ///
1312e5dd7070Spatrick /// \param TNK the kind of template that \p Template
1313e5dd7070Spatrick /// refers to, as returned from \c Action::isTemplateName().
1314e5dd7070Spatrick ///
1315e5dd7070Spatrick /// \param SS if non-NULL, the nested-name-specifier that precedes
1316e5dd7070Spatrick /// this template name.
1317e5dd7070Spatrick ///
1318e5dd7070Spatrick /// \param TemplateKWLoc if valid, specifies that this template-id
1319e5dd7070Spatrick /// annotation was preceded by the 'template' keyword and gives the
1320e5dd7070Spatrick /// location of that keyword. If invalid (the default), then this
1321e5dd7070Spatrick /// template-id was not preceded by a 'template' keyword.
1322e5dd7070Spatrick ///
1323e5dd7070Spatrick /// \param AllowTypeAnnotation if true (the default), then a
1324e5dd7070Spatrick /// simple-template-id that refers to a class template, template
1325e5dd7070Spatrick /// template parameter, or other template that produces a type will be
1326e5dd7070Spatrick /// replaced with a type annotation token. Otherwise, the
1327e5dd7070Spatrick /// simple-template-id is always replaced with a template-id
1328e5dd7070Spatrick /// annotation token.
1329e5dd7070Spatrick ///
1330e5dd7070Spatrick /// \param TypeConstraint if true, then this is actually a type-constraint,
1331e5dd7070Spatrick /// meaning that the template argument list can be omitted (and the template in
1332e5dd7070Spatrick /// question must be a concept).
1333e5dd7070Spatrick ///
1334e5dd7070Spatrick /// If an unrecoverable parse error occurs and no annotation token can be
1335e5dd7070Spatrick /// formed, this function returns true.
1336e5dd7070Spatrick ///
AnnotateTemplateIdToken(TemplateTy Template,TemplateNameKind TNK,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & TemplateName,bool AllowTypeAnnotation,bool TypeConstraint)1337e5dd7070Spatrick bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1338e5dd7070Spatrick                                      CXXScopeSpec &SS,
1339e5dd7070Spatrick                                      SourceLocation TemplateKWLoc,
1340e5dd7070Spatrick                                      UnqualifiedId &TemplateName,
1341e5dd7070Spatrick                                      bool AllowTypeAnnotation,
1342e5dd7070Spatrick                                      bool TypeConstraint) {
1343e5dd7070Spatrick   assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1344ec727ea7Spatrick   assert((Tok.is(tok::less) || TypeConstraint) &&
1345e5dd7070Spatrick          "Parser isn't at the beginning of a template-id");
1346e5dd7070Spatrick   assert(!(TypeConstraint && AllowTypeAnnotation) && "type-constraint can't be "
1347e5dd7070Spatrick                                                      "a type annotation");
1348e5dd7070Spatrick   assert((!TypeConstraint || TNK == TNK_Concept_template) && "type-constraint "
1349e5dd7070Spatrick          "must accompany a concept name");
1350ec727ea7Spatrick   assert((Template || TNK == TNK_Non_template) && "missing template name");
1351e5dd7070Spatrick 
1352e5dd7070Spatrick   // Consume the template-name.
1353e5dd7070Spatrick   SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1354e5dd7070Spatrick 
1355e5dd7070Spatrick   // Parse the enclosed template argument list.
1356e5dd7070Spatrick   SourceLocation LAngleLoc, RAngleLoc;
1357e5dd7070Spatrick   TemplateArgList TemplateArgs;
1358ec727ea7Spatrick   bool ArgsInvalid = false;
1359e5dd7070Spatrick   if (!TypeConstraint || Tok.is(tok::less)) {
1360*12c85518Srobert     ArgsInvalid = ParseTemplateIdAfterTemplateName(
1361*12c85518Srobert         false, LAngleLoc, TemplateArgs, RAngleLoc, Template);
1362ec727ea7Spatrick     // If we couldn't recover from invalid arguments, don't form an annotation
1363ec727ea7Spatrick     // token -- we don't know how much to annotate.
1364ec727ea7Spatrick     // FIXME: This can lead to duplicate diagnostics if we retry parsing this
1365ec727ea7Spatrick     // template-id in another context. Try to annotate anyway?
1366ec727ea7Spatrick     if (RAngleLoc.isInvalid())
1367e5dd7070Spatrick       return true;
1368e5dd7070Spatrick   }
1369e5dd7070Spatrick 
1370e5dd7070Spatrick   ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1371e5dd7070Spatrick 
1372e5dd7070Spatrick   // Build the annotation token.
1373e5dd7070Spatrick   if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1374ec727ea7Spatrick     TypeResult Type = ArgsInvalid
1375ec727ea7Spatrick                           ? TypeError()
1376ec727ea7Spatrick                           : Actions.ActOnTemplateIdType(
1377ec727ea7Spatrick                                 getCurScope(), SS, TemplateKWLoc, Template,
1378ec727ea7Spatrick                                 TemplateName.Identifier, TemplateNameLoc,
1379ec727ea7Spatrick                                 LAngleLoc, TemplateArgsPtr, RAngleLoc);
1380e5dd7070Spatrick 
1381e5dd7070Spatrick     Tok.setKind(tok::annot_typename);
1382ec727ea7Spatrick     setTypeAnnotation(Tok, Type);
1383e5dd7070Spatrick     if (SS.isNotEmpty())
1384e5dd7070Spatrick       Tok.setLocation(SS.getBeginLoc());
1385e5dd7070Spatrick     else if (TemplateKWLoc.isValid())
1386e5dd7070Spatrick       Tok.setLocation(TemplateKWLoc);
1387e5dd7070Spatrick     else
1388e5dd7070Spatrick       Tok.setLocation(TemplateNameLoc);
1389e5dd7070Spatrick   } else {
1390e5dd7070Spatrick     // Build a template-id annotation token that can be processed
1391e5dd7070Spatrick     // later.
1392e5dd7070Spatrick     Tok.setKind(tok::annot_template_id);
1393e5dd7070Spatrick 
1394e5dd7070Spatrick     IdentifierInfo *TemplateII =
1395e5dd7070Spatrick         TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1396e5dd7070Spatrick             ? TemplateName.Identifier
1397e5dd7070Spatrick             : nullptr;
1398e5dd7070Spatrick 
1399e5dd7070Spatrick     OverloadedOperatorKind OpKind =
1400e5dd7070Spatrick         TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1401e5dd7070Spatrick             ? OO_None
1402e5dd7070Spatrick             : TemplateName.OperatorFunctionId.Operator;
1403e5dd7070Spatrick 
1404e5dd7070Spatrick     TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1405e5dd7070Spatrick         TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
1406ec727ea7Spatrick         LAngleLoc, RAngleLoc, TemplateArgs, ArgsInvalid, TemplateIds);
1407e5dd7070Spatrick 
1408e5dd7070Spatrick     Tok.setAnnotationValue(TemplateId);
1409e5dd7070Spatrick     if (TemplateKWLoc.isValid())
1410e5dd7070Spatrick       Tok.setLocation(TemplateKWLoc);
1411e5dd7070Spatrick     else
1412e5dd7070Spatrick       Tok.setLocation(TemplateNameLoc);
1413e5dd7070Spatrick   }
1414e5dd7070Spatrick 
1415e5dd7070Spatrick   // Common fields for the annotation token
1416e5dd7070Spatrick   Tok.setAnnotationEndLoc(RAngleLoc);
1417e5dd7070Spatrick 
1418e5dd7070Spatrick   // In case the tokens were cached, have Preprocessor replace them with the
1419e5dd7070Spatrick   // annotation token.
1420e5dd7070Spatrick   PP.AnnotateCachedTokens(Tok);
1421e5dd7070Spatrick   return false;
1422e5dd7070Spatrick }
1423e5dd7070Spatrick 
1424e5dd7070Spatrick /// Replaces a template-id annotation token with a type
1425e5dd7070Spatrick /// annotation token.
1426e5dd7070Spatrick ///
1427e5dd7070Spatrick /// If there was a failure when forming the type from the template-id,
1428e5dd7070Spatrick /// a type annotation token will still be created, but will have a
1429e5dd7070Spatrick /// NULL type pointer to signify an error.
1430e5dd7070Spatrick ///
1431e5dd7070Spatrick /// \param SS The scope specifier appearing before the template-id, if any.
1432e5dd7070Spatrick ///
1433*12c85518Srobert /// \param AllowImplicitTypename whether this is a context where T::type
1434*12c85518Srobert /// denotes a dependent type.
1435e5dd7070Spatrick /// \param IsClassName Is this template-id appearing in a context where we
1436e5dd7070Spatrick /// know it names a class, such as in an elaborated-type-specifier or
1437e5dd7070Spatrick /// base-specifier? ('typename' and 'template' are unneeded and disallowed
1438e5dd7070Spatrick /// in those contexts.)
AnnotateTemplateIdTokenAsType(CXXScopeSpec & SS,ImplicitTypenameContext AllowImplicitTypename,bool IsClassName)1439*12c85518Srobert void Parser::AnnotateTemplateIdTokenAsType(
1440*12c85518Srobert     CXXScopeSpec &SS, ImplicitTypenameContext AllowImplicitTypename,
1441e5dd7070Spatrick     bool IsClassName) {
1442e5dd7070Spatrick   assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1443e5dd7070Spatrick 
1444e5dd7070Spatrick   TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1445ec727ea7Spatrick   assert(TemplateId->mightBeType() &&
1446e5dd7070Spatrick          "Only works for type and dependent templates");
1447e5dd7070Spatrick 
1448e5dd7070Spatrick   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1449e5dd7070Spatrick                                      TemplateId->NumArgs);
1450e5dd7070Spatrick 
1451ec727ea7Spatrick   TypeResult Type =
1452ec727ea7Spatrick       TemplateId->isInvalid()
1453ec727ea7Spatrick           ? TypeError()
1454ec727ea7Spatrick           : Actions.ActOnTemplateIdType(
1455ec727ea7Spatrick                 getCurScope(), SS, TemplateId->TemplateKWLoc,
1456ec727ea7Spatrick                 TemplateId->Template, TemplateId->Name,
1457ec727ea7Spatrick                 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
1458ec727ea7Spatrick                 TemplateArgsPtr, TemplateId->RAngleLoc,
1459*12c85518Srobert                 /*IsCtorOrDtorName=*/false, IsClassName, AllowImplicitTypename);
1460e5dd7070Spatrick   // Create the new "type" annotation token.
1461e5dd7070Spatrick   Tok.setKind(tok::annot_typename);
1462ec727ea7Spatrick   setTypeAnnotation(Tok, Type);
1463e5dd7070Spatrick   if (SS.isNotEmpty()) // it was a C++ qualified type name.
1464e5dd7070Spatrick     Tok.setLocation(SS.getBeginLoc());
1465e5dd7070Spatrick   // End location stays the same
1466e5dd7070Spatrick 
1467e5dd7070Spatrick   // Replace the template-id annotation token, and possible the scope-specifier
1468e5dd7070Spatrick   // that precedes it, with the typename annotation token.
1469e5dd7070Spatrick   PP.AnnotateCachedTokens(Tok);
1470e5dd7070Spatrick }
1471e5dd7070Spatrick 
1472e5dd7070Spatrick /// Determine whether the given token can end a template argument.
isEndOfTemplateArgument(Token Tok)1473e5dd7070Spatrick static bool isEndOfTemplateArgument(Token Tok) {
1474ec727ea7Spatrick   // FIXME: Handle '>>>'.
1475ec727ea7Spatrick   return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater,
1476ec727ea7Spatrick                      tok::greatergreatergreater);
1477e5dd7070Spatrick }
1478e5dd7070Spatrick 
1479e5dd7070Spatrick /// Parse a C++ template template argument.
ParseTemplateTemplateArgument()1480e5dd7070Spatrick ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1481e5dd7070Spatrick   if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1482e5dd7070Spatrick       !Tok.is(tok::annot_cxxscope))
1483e5dd7070Spatrick     return ParsedTemplateArgument();
1484e5dd7070Spatrick 
1485e5dd7070Spatrick   // C++0x [temp.arg.template]p1:
1486e5dd7070Spatrick   //   A template-argument for a template template-parameter shall be the name
1487e5dd7070Spatrick   //   of a class template or an alias template, expressed as id-expression.
1488e5dd7070Spatrick   //
1489e5dd7070Spatrick   // We parse an id-expression that refers to a class template or alias
1490e5dd7070Spatrick   // template. The grammar we parse is:
1491e5dd7070Spatrick   //
1492e5dd7070Spatrick   //   nested-name-specifier[opt] template[opt] identifier ...[opt]
1493e5dd7070Spatrick   //
1494e5dd7070Spatrick   // followed by a token that terminates a template argument, such as ',',
1495e5dd7070Spatrick   // '>', or (in some cases) '>>'.
1496e5dd7070Spatrick   CXXScopeSpec SS; // nested-name-specifier, if present
1497ec727ea7Spatrick   ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1498*12c85518Srobert                                  /*ObjectHasErrors=*/false,
1499e5dd7070Spatrick                                  /*EnteringContext=*/false);
1500e5dd7070Spatrick 
1501e5dd7070Spatrick   ParsedTemplateArgument Result;
1502e5dd7070Spatrick   SourceLocation EllipsisLoc;
1503e5dd7070Spatrick   if (SS.isSet() && Tok.is(tok::kw_template)) {
1504e5dd7070Spatrick     // Parse the optional 'template' keyword following the
1505e5dd7070Spatrick     // nested-name-specifier.
1506e5dd7070Spatrick     SourceLocation TemplateKWLoc = ConsumeToken();
1507e5dd7070Spatrick 
1508e5dd7070Spatrick     if (Tok.is(tok::identifier)) {
1509e5dd7070Spatrick       // We appear to have a dependent template name.
1510e5dd7070Spatrick       UnqualifiedId Name;
1511e5dd7070Spatrick       Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1512e5dd7070Spatrick       ConsumeToken(); // the identifier
1513e5dd7070Spatrick 
1514e5dd7070Spatrick       TryConsumeToken(tok::ellipsis, EllipsisLoc);
1515e5dd7070Spatrick 
1516ec727ea7Spatrick       // If the next token signals the end of a template argument, then we have
1517ec727ea7Spatrick       // a (possibly-dependent) template name that could be a template template
1518ec727ea7Spatrick       // argument.
1519e5dd7070Spatrick       TemplateTy Template;
1520e5dd7070Spatrick       if (isEndOfTemplateArgument(Tok) &&
1521ec727ea7Spatrick           Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Name,
1522e5dd7070Spatrick                                     /*ObjectType=*/nullptr,
1523e5dd7070Spatrick                                     /*EnteringContext=*/false, Template))
1524e5dd7070Spatrick         Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1525e5dd7070Spatrick     }
1526e5dd7070Spatrick   } else if (Tok.is(tok::identifier)) {
1527e5dd7070Spatrick     // We may have a (non-dependent) template name.
1528e5dd7070Spatrick     TemplateTy Template;
1529e5dd7070Spatrick     UnqualifiedId Name;
1530e5dd7070Spatrick     Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1531e5dd7070Spatrick     ConsumeToken(); // the identifier
1532e5dd7070Spatrick 
1533e5dd7070Spatrick     TryConsumeToken(tok::ellipsis, EllipsisLoc);
1534e5dd7070Spatrick 
1535e5dd7070Spatrick     if (isEndOfTemplateArgument(Tok)) {
1536e5dd7070Spatrick       bool MemberOfUnknownSpecialization;
1537e5dd7070Spatrick       TemplateNameKind TNK = Actions.isTemplateName(
1538e5dd7070Spatrick           getCurScope(), SS,
1539e5dd7070Spatrick           /*hasTemplateKeyword=*/false, Name,
1540e5dd7070Spatrick           /*ObjectType=*/nullptr,
1541e5dd7070Spatrick           /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1542e5dd7070Spatrick       if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1543e5dd7070Spatrick         // We have an id-expression that refers to a class template or
1544e5dd7070Spatrick         // (C++0x) alias template.
1545e5dd7070Spatrick         Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1546e5dd7070Spatrick       }
1547e5dd7070Spatrick     }
1548e5dd7070Spatrick   }
1549e5dd7070Spatrick 
1550e5dd7070Spatrick   // If this is a pack expansion, build it as such.
1551e5dd7070Spatrick   if (EllipsisLoc.isValid() && !Result.isInvalid())
1552e5dd7070Spatrick     Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1553e5dd7070Spatrick 
1554e5dd7070Spatrick   return Result;
1555e5dd7070Spatrick }
1556e5dd7070Spatrick 
1557e5dd7070Spatrick /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1558e5dd7070Spatrick ///
1559e5dd7070Spatrick ///       template-argument: [C++ 14.2]
1560e5dd7070Spatrick ///         constant-expression
1561e5dd7070Spatrick ///         type-id
1562e5dd7070Spatrick ///         id-expression
ParseTemplateArgument()1563e5dd7070Spatrick ParsedTemplateArgument Parser::ParseTemplateArgument() {
1564e5dd7070Spatrick   // C++ [temp.arg]p2:
1565e5dd7070Spatrick   //   In a template-argument, an ambiguity between a type-id and an
1566e5dd7070Spatrick   //   expression is resolved to a type-id, regardless of the form of
1567e5dd7070Spatrick   //   the corresponding template-parameter.
1568e5dd7070Spatrick   //
1569e5dd7070Spatrick   // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1570e5dd7070Spatrick   // up and annotate an identifier as an id-expression during disambiguation,
1571e5dd7070Spatrick   // so enter the appropriate context for a constant expression template
1572e5dd7070Spatrick   // argument before trying to disambiguate.
1573e5dd7070Spatrick 
1574e5dd7070Spatrick   EnterExpressionEvaluationContext EnterConstantEvaluated(
1575e5dd7070Spatrick     Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
1576e5dd7070Spatrick     /*LambdaContextDecl=*/nullptr,
1577e5dd7070Spatrick     /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
1578e5dd7070Spatrick   if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1579e5dd7070Spatrick     TypeResult TypeArg = ParseTypeName(
1580a9ac8606Spatrick         /*Range=*/nullptr, DeclaratorContext::TemplateArg);
1581e5dd7070Spatrick     return Actions.ActOnTemplateTypeArgument(TypeArg);
1582e5dd7070Spatrick   }
1583e5dd7070Spatrick 
1584e5dd7070Spatrick   // Try to parse a template template argument.
1585e5dd7070Spatrick   {
1586e5dd7070Spatrick     TentativeParsingAction TPA(*this);
1587e5dd7070Spatrick 
1588e5dd7070Spatrick     ParsedTemplateArgument TemplateTemplateArgument
1589e5dd7070Spatrick       = ParseTemplateTemplateArgument();
1590e5dd7070Spatrick     if (!TemplateTemplateArgument.isInvalid()) {
1591e5dd7070Spatrick       TPA.Commit();
1592e5dd7070Spatrick       return TemplateTemplateArgument;
1593e5dd7070Spatrick     }
1594e5dd7070Spatrick 
1595e5dd7070Spatrick     // Revert this tentative parse to parse a non-type template argument.
1596e5dd7070Spatrick     TPA.Revert();
1597e5dd7070Spatrick   }
1598e5dd7070Spatrick 
1599e5dd7070Spatrick   // Parse a non-type template argument.
1600e5dd7070Spatrick   SourceLocation Loc = Tok.getLocation();
1601e5dd7070Spatrick   ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
1602e5dd7070Spatrick   if (ExprArg.isInvalid() || !ExprArg.get()) {
1603e5dd7070Spatrick     return ParsedTemplateArgument();
1604e5dd7070Spatrick   }
1605e5dd7070Spatrick 
1606e5dd7070Spatrick   return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1607e5dd7070Spatrick                                 ExprArg.get(), Loc);
1608e5dd7070Spatrick }
1609e5dd7070Spatrick 
1610e5dd7070Spatrick /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1611e5dd7070Spatrick /// (C++ [temp.names]). Returns true if there was an error.
1612e5dd7070Spatrick ///
1613e5dd7070Spatrick ///       template-argument-list: [C++ 14.2]
1614e5dd7070Spatrick ///         template-argument
1615e5dd7070Spatrick ///         template-argument-list ',' template-argument
1616*12c85518Srobert ///
1617*12c85518Srobert /// \param Template is only used for code completion, and may be null.
ParseTemplateArgumentList(TemplateArgList & TemplateArgs,TemplateTy Template,SourceLocation OpenLoc)1618*12c85518Srobert bool Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
1619*12c85518Srobert                                        TemplateTy Template,
1620*12c85518Srobert                                        SourceLocation OpenLoc) {
1621e5dd7070Spatrick 
1622e5dd7070Spatrick   ColonProtectionRAIIObject ColonProtection(*this, false);
1623e5dd7070Spatrick 
1624*12c85518Srobert   auto RunSignatureHelp = [&] {
1625*12c85518Srobert     if (!Template)
1626*12c85518Srobert       return QualType();
1627*12c85518Srobert     CalledSignatureHelp = true;
1628*12c85518Srobert     return Actions.ProduceTemplateArgumentSignatureHelp(Template, TemplateArgs,
1629*12c85518Srobert                                                         OpenLoc);
1630*12c85518Srobert   };
1631*12c85518Srobert 
1632e5dd7070Spatrick   do {
1633*12c85518Srobert     PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
1634e5dd7070Spatrick     ParsedTemplateArgument Arg = ParseTemplateArgument();
1635e5dd7070Spatrick     SourceLocation EllipsisLoc;
1636e5dd7070Spatrick     if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1637e5dd7070Spatrick       Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1638e5dd7070Spatrick 
1639*12c85518Srobert     if (Arg.isInvalid()) {
1640*12c85518Srobert       if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1641*12c85518Srobert         RunSignatureHelp();
1642e5dd7070Spatrick       return true;
1643*12c85518Srobert     }
1644e5dd7070Spatrick 
1645e5dd7070Spatrick     // Save this template argument.
1646e5dd7070Spatrick     TemplateArgs.push_back(Arg);
1647e5dd7070Spatrick 
1648e5dd7070Spatrick     // If the next token is a comma, consume it and keep reading
1649e5dd7070Spatrick     // arguments.
1650e5dd7070Spatrick   } while (TryConsumeToken(tok::comma));
1651e5dd7070Spatrick 
1652e5dd7070Spatrick   return false;
1653e5dd7070Spatrick }
1654e5dd7070Spatrick 
1655e5dd7070Spatrick /// Parse a C++ explicit template instantiation
1656e5dd7070Spatrick /// (C++ [temp.explicit]).
1657e5dd7070Spatrick ///
1658e5dd7070Spatrick ///       explicit-instantiation:
1659e5dd7070Spatrick ///         'extern' [opt] 'template' declaration
1660e5dd7070Spatrick ///
1661e5dd7070Spatrick /// Note that the 'extern' is a GNU extension and C++11 feature.
ParseExplicitInstantiation(DeclaratorContext Context,SourceLocation ExternLoc,SourceLocation TemplateLoc,SourceLocation & DeclEnd,ParsedAttributes & AccessAttrs,AccessSpecifier AS)1662e5dd7070Spatrick Decl *Parser::ParseExplicitInstantiation(DeclaratorContext Context,
1663e5dd7070Spatrick                                          SourceLocation ExternLoc,
1664e5dd7070Spatrick                                          SourceLocation TemplateLoc,
1665e5dd7070Spatrick                                          SourceLocation &DeclEnd,
1666e5dd7070Spatrick                                          ParsedAttributes &AccessAttrs,
1667e5dd7070Spatrick                                          AccessSpecifier AS) {
1668e5dd7070Spatrick   // This isn't really required here.
1669e5dd7070Spatrick   ParsingDeclRAIIObject
1670e5dd7070Spatrick     ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1671e5dd7070Spatrick 
1672e5dd7070Spatrick   return ParseSingleDeclarationAfterTemplate(
1673e5dd7070Spatrick       Context, ParsedTemplateInfo(ExternLoc, TemplateLoc),
1674e5dd7070Spatrick       ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
1675e5dd7070Spatrick }
1676e5dd7070Spatrick 
getSourceRange() const1677e5dd7070Spatrick SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1678e5dd7070Spatrick   if (TemplateParams)
1679e5dd7070Spatrick     return getTemplateParamsRange(TemplateParams->data(),
1680e5dd7070Spatrick                                   TemplateParams->size());
1681e5dd7070Spatrick 
1682e5dd7070Spatrick   SourceRange R(TemplateLoc);
1683e5dd7070Spatrick   if (ExternLoc.isValid())
1684e5dd7070Spatrick     R.setBegin(ExternLoc);
1685e5dd7070Spatrick   return R;
1686e5dd7070Spatrick }
1687e5dd7070Spatrick 
LateTemplateParserCallback(void * P,LateParsedTemplate & LPT)1688e5dd7070Spatrick void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1689e5dd7070Spatrick   ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1690e5dd7070Spatrick }
1691e5dd7070Spatrick 
1692e5dd7070Spatrick /// Late parse a C++ function template in Microsoft mode.
ParseLateTemplatedFuncDef(LateParsedTemplate & LPT)1693e5dd7070Spatrick void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1694e5dd7070Spatrick   if (!LPT.D)
1695e5dd7070Spatrick      return;
1696e5dd7070Spatrick 
1697ec727ea7Spatrick   // Destroy TemplateIdAnnotations when we're done, if possible.
1698ec727ea7Spatrick   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
1699ec727ea7Spatrick 
1700e5dd7070Spatrick   // Get the FunctionDecl.
1701e5dd7070Spatrick   FunctionDecl *FunD = LPT.D->getAsFunction();
1702e5dd7070Spatrick   // Track template parameter depth.
1703e5dd7070Spatrick   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1704e5dd7070Spatrick 
1705e5dd7070Spatrick   // To restore the context after late parsing.
1706e5dd7070Spatrick   Sema::ContextRAII GlobalSavedContext(
1707e5dd7070Spatrick       Actions, Actions.Context.getTranslationUnitDecl());
1708e5dd7070Spatrick 
1709ec727ea7Spatrick   MultiParseScope Scopes(*this);
1710e5dd7070Spatrick 
1711ec727ea7Spatrick   // Get the list of DeclContexts to reenter.
1712ec727ea7Spatrick   SmallVector<DeclContext*, 4> DeclContextsToReenter;
1713ec727ea7Spatrick   for (DeclContext *DC = FunD; DC && !DC->isTranslationUnit();
1714ec727ea7Spatrick        DC = DC->getLexicalParent())
1715ec727ea7Spatrick     DeclContextsToReenter.push_back(DC);
1716e5dd7070Spatrick 
1717ec727ea7Spatrick   // Reenter scopes from outermost to innermost.
1718ec727ea7Spatrick   for (DeclContext *DC : reverse(DeclContextsToReenter)) {
1719ec727ea7Spatrick     CurTemplateDepthTracker.addDepth(
1720ec727ea7Spatrick         ReenterTemplateScopes(Scopes, cast<Decl>(DC)));
1721ec727ea7Spatrick     Scopes.Enter(Scope::DeclScope);
1722ec727ea7Spatrick     // We'll reenter the function context itself below.
1723ec727ea7Spatrick     if (DC != FunD)
1724ec727ea7Spatrick       Actions.PushDeclContext(Actions.getCurScope(), DC);
1725e5dd7070Spatrick   }
1726e5dd7070Spatrick 
1727e5dd7070Spatrick   assert(!LPT.Toks.empty() && "Empty body!");
1728e5dd7070Spatrick 
1729e5dd7070Spatrick   // Append the current token at the end of the new token stream so that it
1730e5dd7070Spatrick   // doesn't get lost.
1731e5dd7070Spatrick   LPT.Toks.push_back(Tok);
1732e5dd7070Spatrick   PP.EnterTokenStream(LPT.Toks, true, /*IsReinject*/true);
1733e5dd7070Spatrick 
1734e5dd7070Spatrick   // Consume the previously pushed token.
1735e5dd7070Spatrick   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1736e5dd7070Spatrick   assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1737e5dd7070Spatrick          "Inline method not starting with '{', ':' or 'try'");
1738e5dd7070Spatrick 
1739e5dd7070Spatrick   // Parse the method body. Function body parsing code is similar enough
1740e5dd7070Spatrick   // to be re-used for method bodies as well.
1741e5dd7070Spatrick   ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
1742e5dd7070Spatrick                                Scope::CompoundStmtScope);
1743e5dd7070Spatrick 
1744e5dd7070Spatrick   // Recreate the containing function DeclContext.
1745ec727ea7Spatrick   Sema::ContextRAII FunctionSavedContext(Actions, FunD->getLexicalParent());
1746e5dd7070Spatrick 
1747e5dd7070Spatrick   Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1748e5dd7070Spatrick 
1749e5dd7070Spatrick   if (Tok.is(tok::kw_try)) {
1750e5dd7070Spatrick     ParseFunctionTryBlock(LPT.D, FnScope);
1751e5dd7070Spatrick   } else {
1752e5dd7070Spatrick     if (Tok.is(tok::colon))
1753e5dd7070Spatrick       ParseConstructorInitializer(LPT.D);
1754e5dd7070Spatrick     else
1755e5dd7070Spatrick       Actions.ActOnDefaultCtorInitializers(LPT.D);
1756e5dd7070Spatrick 
1757e5dd7070Spatrick     if (Tok.is(tok::l_brace)) {
1758e5dd7070Spatrick       assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1759e5dd7070Spatrick               cast<FunctionTemplateDecl>(LPT.D)
1760e5dd7070Spatrick                       ->getTemplateParameters()
1761e5dd7070Spatrick                       ->getDepth() == TemplateParameterDepth - 1) &&
1762e5dd7070Spatrick              "TemplateParameterDepth should be greater than the depth of "
1763e5dd7070Spatrick              "current template being instantiated!");
1764e5dd7070Spatrick       ParseFunctionStatementBody(LPT.D, FnScope);
1765e5dd7070Spatrick       Actions.UnmarkAsLateParsedTemplate(FunD);
1766e5dd7070Spatrick     } else
1767e5dd7070Spatrick       Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1768e5dd7070Spatrick   }
1769e5dd7070Spatrick }
1770e5dd7070Spatrick 
1771e5dd7070Spatrick /// Lex a delayed template function for late parsing.
LexTemplateFunctionForLateParsing(CachedTokens & Toks)1772e5dd7070Spatrick void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1773e5dd7070Spatrick   tok::TokenKind kind = Tok.getKind();
1774e5dd7070Spatrick   if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1775e5dd7070Spatrick     // Consume everything up to (and including) the matching right brace.
1776e5dd7070Spatrick     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1777e5dd7070Spatrick   }
1778e5dd7070Spatrick 
1779e5dd7070Spatrick   // If we're in a function-try-block, we need to store all the catch blocks.
1780e5dd7070Spatrick   if (kind == tok::kw_try) {
1781e5dd7070Spatrick     while (Tok.is(tok::kw_catch)) {
1782e5dd7070Spatrick       ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1783e5dd7070Spatrick       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1784e5dd7070Spatrick     }
1785e5dd7070Spatrick   }
1786e5dd7070Spatrick }
1787e5dd7070Spatrick 
1788e5dd7070Spatrick /// We've parsed something that could plausibly be intended to be a template
1789e5dd7070Spatrick /// name (\p LHS) followed by a '<' token, and the following code can't possibly
1790e5dd7070Spatrick /// be an expression. Determine if this is likely to be a template-id and if so,
1791e5dd7070Spatrick /// diagnose it.
diagnoseUnknownTemplateId(ExprResult LHS,SourceLocation Less)1792e5dd7070Spatrick bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1793e5dd7070Spatrick   TentativeParsingAction TPA(*this);
1794e5dd7070Spatrick   // FIXME: We could look at the token sequence in a lot more detail here.
1795e5dd7070Spatrick   if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
1796e5dd7070Spatrick                 StopAtSemi | StopBeforeMatch)) {
1797e5dd7070Spatrick     TPA.Commit();
1798e5dd7070Spatrick 
1799e5dd7070Spatrick     SourceLocation Greater;
1800ec727ea7Spatrick     ParseGreaterThanInTemplateList(Less, Greater, true, false);
1801e5dd7070Spatrick     Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
1802e5dd7070Spatrick                                                Less, Greater);
1803e5dd7070Spatrick     return true;
1804e5dd7070Spatrick   }
1805e5dd7070Spatrick 
1806e5dd7070Spatrick   // There's no matching '>' token, this probably isn't supposed to be
1807e5dd7070Spatrick   // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1808e5dd7070Spatrick   TPA.Revert();
1809e5dd7070Spatrick   return false;
1810e5dd7070Spatrick }
1811e5dd7070Spatrick 
checkPotentialAngleBracket(ExprResult & PotentialTemplateName)1812e5dd7070Spatrick void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1813e5dd7070Spatrick   assert(Tok.is(tok::less) && "not at a potential angle bracket");
1814e5dd7070Spatrick 
1815e5dd7070Spatrick   bool DependentTemplateName = false;
1816e5dd7070Spatrick   if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName,
1817e5dd7070Spatrick                                                DependentTemplateName))
1818e5dd7070Spatrick     return;
1819e5dd7070Spatrick 
1820e5dd7070Spatrick   // OK, this might be a name that the user intended to be parsed as a
1821e5dd7070Spatrick   // template-name, followed by a '<' token. Check for some easy cases.
1822e5dd7070Spatrick 
1823e5dd7070Spatrick   // If we have potential_template<>, then it's supposed to be a template-name.
1824e5dd7070Spatrick   if (NextToken().is(tok::greater) ||
1825e5dd7070Spatrick       (getLangOpts().CPlusPlus11 &&
1826e5dd7070Spatrick        NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater))) {
1827e5dd7070Spatrick     SourceLocation Less = ConsumeToken();
1828e5dd7070Spatrick     SourceLocation Greater;
1829ec727ea7Spatrick     ParseGreaterThanInTemplateList(Less, Greater, true, false);
1830e5dd7070Spatrick     Actions.diagnoseExprIntendedAsTemplateName(
1831e5dd7070Spatrick         getCurScope(), PotentialTemplateName, Less, Greater);
1832e5dd7070Spatrick     // FIXME: Perform error recovery.
1833e5dd7070Spatrick     PotentialTemplateName = ExprError();
1834e5dd7070Spatrick     return;
1835e5dd7070Spatrick   }
1836e5dd7070Spatrick 
1837e5dd7070Spatrick   // If we have 'potential_template<type-id', assume it's supposed to be a
1838e5dd7070Spatrick   // template-name if there's a matching '>' later on.
1839e5dd7070Spatrick   {
1840e5dd7070Spatrick     // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1841e5dd7070Spatrick     TentativeParsingAction TPA(*this);
1842e5dd7070Spatrick     SourceLocation Less = ConsumeToken();
1843e5dd7070Spatrick     if (isTypeIdUnambiguously() &&
1844e5dd7070Spatrick         diagnoseUnknownTemplateId(PotentialTemplateName, Less)) {
1845e5dd7070Spatrick       TPA.Commit();
1846e5dd7070Spatrick       // FIXME: Perform error recovery.
1847e5dd7070Spatrick       PotentialTemplateName = ExprError();
1848e5dd7070Spatrick       return;
1849e5dd7070Spatrick     }
1850e5dd7070Spatrick     TPA.Revert();
1851e5dd7070Spatrick   }
1852e5dd7070Spatrick 
1853e5dd7070Spatrick   // Otherwise, remember that we saw this in case we see a potentially-matching
1854e5dd7070Spatrick   // '>' token later on.
1855e5dd7070Spatrick   AngleBracketTracker::Priority Priority =
1856e5dd7070Spatrick       (DependentTemplateName ? AngleBracketTracker::DependentName
1857e5dd7070Spatrick                              : AngleBracketTracker::PotentialTypo) |
1858e5dd7070Spatrick       (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
1859e5dd7070Spatrick                              : AngleBracketTracker::NoSpaceBeforeLess);
1860e5dd7070Spatrick   AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(),
1861e5dd7070Spatrick                     Priority);
1862e5dd7070Spatrick }
1863e5dd7070Spatrick 
checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc & LAngle,const Token & OpToken)1864e5dd7070Spatrick bool Parser::checkPotentialAngleBracketDelimiter(
1865e5dd7070Spatrick     const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1866e5dd7070Spatrick   // If a comma in an expression context is followed by a type that can be a
1867e5dd7070Spatrick   // template argument and cannot be an expression, then this is ill-formed,
1868e5dd7070Spatrick   // but might be intended to be part of a template-id.
1869e5dd7070Spatrick   if (OpToken.is(tok::comma) && isTypeIdUnambiguously() &&
1870e5dd7070Spatrick       diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)) {
1871e5dd7070Spatrick     AngleBrackets.clear(*this);
1872e5dd7070Spatrick     return true;
1873e5dd7070Spatrick   }
1874e5dd7070Spatrick 
1875e5dd7070Spatrick   // If a context that looks like a template-id is followed by '()', then
1876e5dd7070Spatrick   // this is ill-formed, but might be intended to be a template-id
1877e5dd7070Spatrick   // followed by '()'.
1878e5dd7070Spatrick   if (OpToken.is(tok::greater) && Tok.is(tok::l_paren) &&
1879e5dd7070Spatrick       NextToken().is(tok::r_paren)) {
1880e5dd7070Spatrick     Actions.diagnoseExprIntendedAsTemplateName(
1881e5dd7070Spatrick         getCurScope(), LAngle.TemplateName, LAngle.LessLoc,
1882e5dd7070Spatrick         OpToken.getLocation());
1883e5dd7070Spatrick     AngleBrackets.clear(*this);
1884e5dd7070Spatrick     return true;
1885e5dd7070Spatrick   }
1886e5dd7070Spatrick 
1887e5dd7070Spatrick   // After a '>' (etc), we're no longer potentially in a construct that's
1888e5dd7070Spatrick   // intended to be treated as a template-id.
1889e5dd7070Spatrick   if (OpToken.is(tok::greater) ||
1890e5dd7070Spatrick       (getLangOpts().CPlusPlus11 &&
1891e5dd7070Spatrick        OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater)))
1892e5dd7070Spatrick     AngleBrackets.clear(*this);
1893e5dd7070Spatrick   return false;
1894e5dd7070Spatrick }
1895