File: | build/source/clang/lib/Sema/SemaTemplate.cpp |
Warning: | line 1407, column 5 Value stored to 'RD' is never read |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | //===----------------------------------------------------------------------===// |
7 | // |
8 | // This file implements semantic analysis for C++ templates. |
9 | //===----------------------------------------------------------------------===// |
10 | |
11 | #include "TreeTransform.h" |
12 | #include "clang/AST/ASTConsumer.h" |
13 | #include "clang/AST/ASTContext.h" |
14 | #include "clang/AST/Decl.h" |
15 | #include "clang/AST/DeclFriend.h" |
16 | #include "clang/AST/DeclTemplate.h" |
17 | #include "clang/AST/Expr.h" |
18 | #include "clang/AST/ExprCXX.h" |
19 | #include "clang/AST/RecursiveASTVisitor.h" |
20 | #include "clang/AST/TemplateName.h" |
21 | #include "clang/AST/TypeVisitor.h" |
22 | #include "clang/Basic/Builtins.h" |
23 | #include "clang/Basic/DiagnosticSema.h" |
24 | #include "clang/Basic/LangOptions.h" |
25 | #include "clang/Basic/PartialDiagnostic.h" |
26 | #include "clang/Basic/Stack.h" |
27 | #include "clang/Basic/TargetInfo.h" |
28 | #include "clang/Sema/DeclSpec.h" |
29 | #include "clang/Sema/Initialization.h" |
30 | #include "clang/Sema/Lookup.h" |
31 | #include "clang/Sema/Overload.h" |
32 | #include "clang/Sema/ParsedTemplate.h" |
33 | #include "clang/Sema/Scope.h" |
34 | #include "clang/Sema/SemaInternal.h" |
35 | #include "clang/Sema/Template.h" |
36 | #include "clang/Sema/TemplateDeduction.h" |
37 | #include "llvm/ADT/SmallBitVector.h" |
38 | #include "llvm/ADT/SmallString.h" |
39 | #include "llvm/ADT/StringExtras.h" |
40 | |
41 | #include <iterator> |
42 | #include <optional> |
43 | using namespace clang; |
44 | using namespace sema; |
45 | |
46 | // Exported for use by Parser. |
47 | SourceRange |
48 | clang::getTemplateParamsRange(TemplateParameterList const * const *Ps, |
49 | unsigned N) { |
50 | if (!N) return SourceRange(); |
51 | return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc()); |
52 | } |
53 | |
54 | unsigned Sema::getTemplateDepth(Scope *S) const { |
55 | unsigned Depth = 0; |
56 | |
57 | // Each template parameter scope represents one level of template parameter |
58 | // depth. |
59 | for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope; |
60 | TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) { |
61 | ++Depth; |
62 | } |
63 | |
64 | // Note that there are template parameters with the given depth. |
65 | auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); }; |
66 | |
67 | // Look for parameters of an enclosing generic lambda. We don't create a |
68 | // template parameter scope for these. |
69 | for (FunctionScopeInfo *FSI : getFunctionScopes()) { |
70 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) { |
71 | if (!LSI->TemplateParams.empty()) { |
72 | ParamsAtDepth(LSI->AutoTemplateParameterDepth); |
73 | break; |
74 | } |
75 | if (LSI->GLTemplateParameterList) { |
76 | ParamsAtDepth(LSI->GLTemplateParameterList->getDepth()); |
77 | break; |
78 | } |
79 | } |
80 | } |
81 | |
82 | // Look for parameters of an enclosing terse function template. We don't |
83 | // create a template parameter scope for these either. |
84 | for (const InventedTemplateParameterInfo &Info : |
85 | getInventedParameterInfos()) { |
86 | if (!Info.TemplateParams.empty()) { |
87 | ParamsAtDepth(Info.AutoTemplateParameterDepth); |
88 | break; |
89 | } |
90 | } |
91 | |
92 | return Depth; |
93 | } |
94 | |
95 | /// \brief Determine whether the declaration found is acceptable as the name |
96 | /// of a template and, if so, return that template declaration. Otherwise, |
97 | /// returns null. |
98 | /// |
99 | /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent |
100 | /// is true. In all other cases it will return a TemplateDecl (or null). |
101 | NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D, |
102 | bool AllowFunctionTemplates, |
103 | bool AllowDependent) { |
104 | D = D->getUnderlyingDecl(); |
105 | |
106 | if (isa<TemplateDecl>(D)) { |
107 | if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D)) |
108 | return nullptr; |
109 | |
110 | return D; |
111 | } |
112 | |
113 | if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) { |
114 | // C++ [temp.local]p1: |
115 | // Like normal (non-template) classes, class templates have an |
116 | // injected-class-name (Clause 9). The injected-class-name |
117 | // can be used with or without a template-argument-list. When |
118 | // it is used without a template-argument-list, it is |
119 | // equivalent to the injected-class-name followed by the |
120 | // template-parameters of the class template enclosed in |
121 | // <>. When it is used with a template-argument-list, it |
122 | // refers to the specified class template specialization, |
123 | // which could be the current specialization or another |
124 | // specialization. |
125 | if (Record->isInjectedClassName()) { |
126 | Record = cast<CXXRecordDecl>(Record->getDeclContext()); |
127 | if (Record->getDescribedClassTemplate()) |
128 | return Record->getDescribedClassTemplate(); |
129 | |
130 | if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record)) |
131 | return Spec->getSpecializedTemplate(); |
132 | } |
133 | |
134 | return nullptr; |
135 | } |
136 | |
137 | // 'using Dependent::foo;' can resolve to a template name. |
138 | // 'using typename Dependent::foo;' cannot (not even if 'foo' is an |
139 | // injected-class-name). |
140 | if (AllowDependent && isa<UnresolvedUsingValueDecl>(D)) |
141 | return D; |
142 | |
143 | return nullptr; |
144 | } |
145 | |
146 | void Sema::FilterAcceptableTemplateNames(LookupResult &R, |
147 | bool AllowFunctionTemplates, |
148 | bool AllowDependent) { |
149 | LookupResult::Filter filter = R.makeFilter(); |
150 | while (filter.hasNext()) { |
151 | NamedDecl *Orig = filter.next(); |
152 | if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent)) |
153 | filter.erase(); |
154 | } |
155 | filter.done(); |
156 | } |
157 | |
158 | bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R, |
159 | bool AllowFunctionTemplates, |
160 | bool AllowDependent, |
161 | bool AllowNonTemplateFunctions) { |
162 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { |
163 | if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent)) |
164 | return true; |
165 | if (AllowNonTemplateFunctions && |
166 | isa<FunctionDecl>((*I)->getUnderlyingDecl())) |
167 | return true; |
168 | } |
169 | |
170 | return false; |
171 | } |
172 | |
173 | TemplateNameKind Sema::isTemplateName(Scope *S, |
174 | CXXScopeSpec &SS, |
175 | bool hasTemplateKeyword, |
176 | const UnqualifiedId &Name, |
177 | ParsedType ObjectTypePtr, |
178 | bool EnteringContext, |
179 | TemplateTy &TemplateResult, |
180 | bool &MemberOfUnknownSpecialization, |
181 | bool Disambiguation) { |
182 | assert(getLangOpts().CPlusPlus && "No template names in C!")(static_cast <bool> (getLangOpts().CPlusPlus && "No template names in C!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No template names in C!\"" , "clang/lib/Sema/SemaTemplate.cpp", 182, __extension__ __PRETTY_FUNCTION__ )); |
183 | |
184 | DeclarationName TName; |
185 | MemberOfUnknownSpecialization = false; |
186 | |
187 | switch (Name.getKind()) { |
188 | case UnqualifiedIdKind::IK_Identifier: |
189 | TName = DeclarationName(Name.Identifier); |
190 | break; |
191 | |
192 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
193 | TName = Context.DeclarationNames.getCXXOperatorName( |
194 | Name.OperatorFunctionId.Operator); |
195 | break; |
196 | |
197 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
198 | TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier); |
199 | break; |
200 | |
201 | default: |
202 | return TNK_Non_template; |
203 | } |
204 | |
205 | QualType ObjectType = ObjectTypePtr.get(); |
206 | |
207 | AssumedTemplateKind AssumedTemplate; |
208 | LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName); |
209 | if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext, |
210 | MemberOfUnknownSpecialization, SourceLocation(), |
211 | &AssumedTemplate, |
212 | /*AllowTypoCorrection=*/!Disambiguation)) |
213 | return TNK_Non_template; |
214 | |
215 | if (AssumedTemplate != AssumedTemplateKind::None) { |
216 | TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName)); |
217 | // Let the parser know whether we found nothing or found functions; if we |
218 | // found nothing, we want to more carefully check whether this is actually |
219 | // a function template name versus some other kind of undeclared identifier. |
220 | return AssumedTemplate == AssumedTemplateKind::FoundNothing |
221 | ? TNK_Undeclared_template |
222 | : TNK_Function_template; |
223 | } |
224 | |
225 | if (R.empty()) |
226 | return TNK_Non_template; |
227 | |
228 | NamedDecl *D = nullptr; |
229 | UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin()); |
230 | if (R.isAmbiguous()) { |
231 | // If we got an ambiguity involving a non-function template, treat this |
232 | // as a template name, and pick an arbitrary template for error recovery. |
233 | bool AnyFunctionTemplates = false; |
234 | for (NamedDecl *FoundD : R) { |
235 | if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) { |
236 | if (isa<FunctionTemplateDecl>(FoundTemplate)) |
237 | AnyFunctionTemplates = true; |
238 | else { |
239 | D = FoundTemplate; |
240 | FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD); |
241 | break; |
242 | } |
243 | } |
244 | } |
245 | |
246 | // If we didn't find any templates at all, this isn't a template name. |
247 | // Leave the ambiguity for a later lookup to diagnose. |
248 | if (!D && !AnyFunctionTemplates) { |
249 | R.suppressDiagnostics(); |
250 | return TNK_Non_template; |
251 | } |
252 | |
253 | // If the only templates were function templates, filter out the rest. |
254 | // We'll diagnose the ambiguity later. |
255 | if (!D) |
256 | FilterAcceptableTemplateNames(R); |
257 | } |
258 | |
259 | // At this point, we have either picked a single template name declaration D |
260 | // or we have a non-empty set of results R containing either one template name |
261 | // declaration or a set of function templates. |
262 | |
263 | TemplateName Template; |
264 | TemplateNameKind TemplateKind; |
265 | |
266 | unsigned ResultCount = R.end() - R.begin(); |
267 | if (!D && ResultCount > 1) { |
268 | // We assume that we'll preserve the qualifier from a function |
269 | // template name in other ways. |
270 | Template = Context.getOverloadedTemplateName(R.begin(), R.end()); |
271 | TemplateKind = TNK_Function_template; |
272 | |
273 | // We'll do this lookup again later. |
274 | R.suppressDiagnostics(); |
275 | } else { |
276 | if (!D) { |
277 | D = getAsTemplateNameDecl(*R.begin()); |
278 | assert(D && "unambiguous result is not a template name")(static_cast <bool> (D && "unambiguous result is not a template name" ) ? void (0) : __assert_fail ("D && \"unambiguous result is not a template name\"" , "clang/lib/Sema/SemaTemplate.cpp", 278, __extension__ __PRETTY_FUNCTION__ )); |
279 | } |
280 | |
281 | if (isa<UnresolvedUsingValueDecl>(D)) { |
282 | // We don't yet know whether this is a template-name or not. |
283 | MemberOfUnknownSpecialization = true; |
284 | return TNK_Non_template; |
285 | } |
286 | |
287 | TemplateDecl *TD = cast<TemplateDecl>(D); |
288 | Template = |
289 | FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); |
290 | assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD)(static_cast <bool> (!FoundUsingShadow || FoundUsingShadow ->getTargetDecl() == TD) ? void (0) : __assert_fail ("!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD" , "clang/lib/Sema/SemaTemplate.cpp", 290, __extension__ __PRETTY_FUNCTION__ )); |
291 | if (SS.isSet() && !SS.isInvalid()) { |
292 | NestedNameSpecifier *Qualifier = SS.getScopeRep(); |
293 | Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword, |
294 | Template); |
295 | } |
296 | |
297 | if (isa<FunctionTemplateDecl>(TD)) { |
298 | TemplateKind = TNK_Function_template; |
299 | |
300 | // We'll do this lookup again later. |
301 | R.suppressDiagnostics(); |
302 | } else { |
303 | assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||(static_cast <bool> (isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl >(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl >(TD) || isa<ConceptDecl>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)" , "clang/lib/Sema/SemaTemplate.cpp", 305, __extension__ __PRETTY_FUNCTION__ )) |
304 | isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||(static_cast <bool> (isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl >(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl >(TD) || isa<ConceptDecl>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)" , "clang/lib/Sema/SemaTemplate.cpp", 305, __extension__ __PRETTY_FUNCTION__ )) |
305 | isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD))(static_cast <bool> (isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl >(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl >(TD) || isa<ConceptDecl>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)" , "clang/lib/Sema/SemaTemplate.cpp", 305, __extension__ __PRETTY_FUNCTION__ )); |
306 | TemplateKind = |
307 | isa<VarTemplateDecl>(TD) ? TNK_Var_template : |
308 | isa<ConceptDecl>(TD) ? TNK_Concept_template : |
309 | TNK_Type_template; |
310 | } |
311 | } |
312 | |
313 | TemplateResult = TemplateTy::make(Template); |
314 | return TemplateKind; |
315 | } |
316 | |
317 | bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name, |
318 | SourceLocation NameLoc, |
319 | ParsedTemplateTy *Template) { |
320 | CXXScopeSpec SS; |
321 | bool MemberOfUnknownSpecialization = false; |
322 | |
323 | // We could use redeclaration lookup here, but we don't need to: the |
324 | // syntactic form of a deduction guide is enough to identify it even |
325 | // if we can't look up the template name at all. |
326 | LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName); |
327 | if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(), |
328 | /*EnteringContext*/ false, |
329 | MemberOfUnknownSpecialization)) |
330 | return false; |
331 | |
332 | if (R.empty()) return false; |
333 | if (R.isAmbiguous()) { |
334 | // FIXME: Diagnose an ambiguity if we find at least one template. |
335 | R.suppressDiagnostics(); |
336 | return false; |
337 | } |
338 | |
339 | // We only treat template-names that name type templates as valid deduction |
340 | // guide names. |
341 | TemplateDecl *TD = R.getAsSingle<TemplateDecl>(); |
342 | if (!TD || !getAsTypeTemplateDecl(TD)) |
343 | return false; |
344 | |
345 | if (Template) |
346 | *Template = TemplateTy::make(TemplateName(TD)); |
347 | return true; |
348 | } |
349 | |
350 | bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, |
351 | SourceLocation IILoc, |
352 | Scope *S, |
353 | const CXXScopeSpec *SS, |
354 | TemplateTy &SuggestedTemplate, |
355 | TemplateNameKind &SuggestedKind) { |
356 | // We can't recover unless there's a dependent scope specifier preceding the |
357 | // template name. |
358 | // FIXME: Typo correction? |
359 | if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) || |
360 | computeDeclContext(*SS)) |
361 | return false; |
362 | |
363 | // The code is missing a 'template' keyword prior to the dependent template |
364 | // name. |
365 | NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); |
366 | Diag(IILoc, diag::err_template_kw_missing) |
367 | << Qualifier << II.getName() |
368 | << FixItHint::CreateInsertion(IILoc, "template "); |
369 | SuggestedTemplate |
370 | = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II)); |
371 | SuggestedKind = TNK_Dependent_template_name; |
372 | return true; |
373 | } |
374 | |
375 | bool Sema::LookupTemplateName(LookupResult &Found, |
376 | Scope *S, CXXScopeSpec &SS, |
377 | QualType ObjectType, |
378 | bool EnteringContext, |
379 | bool &MemberOfUnknownSpecialization, |
380 | RequiredTemplateKind RequiredTemplate, |
381 | AssumedTemplateKind *ATK, |
382 | bool AllowTypoCorrection) { |
383 | if (ATK) |
384 | *ATK = AssumedTemplateKind::None; |
385 | |
386 | if (SS.isInvalid()) |
387 | return true; |
388 | |
389 | Found.setTemplateNameLookup(true); |
390 | |
391 | // Determine where to perform name lookup |
392 | MemberOfUnknownSpecialization = false; |
393 | DeclContext *LookupCtx = nullptr; |
394 | bool IsDependent = false; |
395 | if (!ObjectType.isNull()) { |
396 | // This nested-name-specifier occurs in a member access expression, e.g., |
397 | // x->B::f, and we are looking into the type of the object. |
398 | assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist")(static_cast <bool> (SS.isEmpty() && "ObjectType and scope specifier cannot coexist" ) ? void (0) : __assert_fail ("SS.isEmpty() && \"ObjectType and scope specifier cannot coexist\"" , "clang/lib/Sema/SemaTemplate.cpp", 398, __extension__ __PRETTY_FUNCTION__ )); |
399 | LookupCtx = computeDeclContext(ObjectType); |
400 | IsDependent = !LookupCtx && ObjectType->isDependentType(); |
401 | assert((IsDependent || !ObjectType->isIncompleteType() ||(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType () || !ObjectType->getAs<TagType>() || ObjectType-> castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type" ) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\"" , "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__ )) |
402 | !ObjectType->getAs<TagType>() ||(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType () || !ObjectType->getAs<TagType>() || ObjectType-> castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type" ) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\"" , "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__ )) |
403 | ObjectType->castAs<TagType>()->isBeingDefined()) &&(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType () || !ObjectType->getAs<TagType>() || ObjectType-> castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type" ) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\"" , "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__ )) |
404 | "Caller should have completed object type")(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType () || !ObjectType->getAs<TagType>() || ObjectType-> castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type" ) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\"" , "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__ )); |
405 | |
406 | // Template names cannot appear inside an Objective-C class or object type |
407 | // or a vector type. |
408 | // |
409 | // FIXME: This is wrong. For example: |
410 | // |
411 | // template<typename T> using Vec = T __attribute__((ext_vector_type(4))); |
412 | // Vec<int> vi; |
413 | // vi.Vec<int>::~Vec<int>(); |
414 | // |
415 | // ... should be accepted but we will not treat 'Vec' as a template name |
416 | // here. The right thing to do would be to check if the name is a valid |
417 | // vector component name, and look up a template name if not. And similarly |
418 | // for lookups into Objective-C class and object types, where the same |
419 | // problem can arise. |
420 | if (ObjectType->isObjCObjectOrInterfaceType() || |
421 | ObjectType->isVectorType()) { |
422 | Found.clear(); |
423 | return false; |
424 | } |
425 | } else if (SS.isNotEmpty()) { |
426 | // This nested-name-specifier occurs after another nested-name-specifier, |
427 | // so long into the context associated with the prior nested-name-specifier. |
428 | LookupCtx = computeDeclContext(SS, EnteringContext); |
429 | IsDependent = !LookupCtx && isDependentScopeSpecifier(SS); |
430 | |
431 | // The declaration context must be complete. |
432 | if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx)) |
433 | return true; |
434 | } |
435 | |
436 | bool ObjectTypeSearchedInScope = false; |
437 | bool AllowFunctionTemplatesInLookup = true; |
438 | if (LookupCtx) { |
439 | // Perform "qualified" name lookup into the declaration context we |
440 | // computed, which is either the type of the base of a member access |
441 | // expression or the declaration context associated with a prior |
442 | // nested-name-specifier. |
443 | LookupQualifiedName(Found, LookupCtx); |
444 | |
445 | // FIXME: The C++ standard does not clearly specify what happens in the |
446 | // case where the object type is dependent, and implementations vary. In |
447 | // Clang, we treat a name after a . or -> as a template-name if lookup |
448 | // finds a non-dependent member or member of the current instantiation that |
449 | // is a type template, or finds no such members and lookup in the context |
450 | // of the postfix-expression finds a type template. In the latter case, the |
451 | // name is nonetheless dependent, and we may resolve it to a member of an |
452 | // unknown specialization when we come to instantiate the template. |
453 | IsDependent |= Found.wasNotFoundInCurrentInstantiation(); |
454 | } |
455 | |
456 | if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) { |
457 | // C++ [basic.lookup.classref]p1: |
458 | // In a class member access expression (5.2.5), if the . or -> token is |
459 | // immediately followed by an identifier followed by a <, the |
460 | // identifier must be looked up to determine whether the < is the |
461 | // beginning of a template argument list (14.2) or a less-than operator. |
462 | // The identifier is first looked up in the class of the object |
463 | // expression. If the identifier is not found, it is then looked up in |
464 | // the context of the entire postfix-expression and shall name a class |
465 | // template. |
466 | if (S) |
467 | LookupName(Found, S); |
468 | |
469 | if (!ObjectType.isNull()) { |
470 | // FIXME: We should filter out all non-type templates here, particularly |
471 | // variable templates and concepts. But the exclusion of alias templates |
472 | // and template template parameters is a wording defect. |
473 | AllowFunctionTemplatesInLookup = false; |
474 | ObjectTypeSearchedInScope = true; |
475 | } |
476 | |
477 | IsDependent |= Found.wasNotFoundInCurrentInstantiation(); |
478 | } |
479 | |
480 | if (Found.isAmbiguous()) |
481 | return false; |
482 | |
483 | if (ATK && SS.isEmpty() && ObjectType.isNull() && |
484 | !RequiredTemplate.hasTemplateKeyword()) { |
485 | // C++2a [temp.names]p2: |
486 | // A name is also considered to refer to a template if it is an |
487 | // unqualified-id followed by a < and name lookup finds either one or more |
488 | // functions or finds nothing. |
489 | // |
490 | // To keep our behavior consistent, we apply the "finds nothing" part in |
491 | // all language modes, and diagnose the empty lookup in ActOnCallExpr if we |
492 | // successfully form a call to an undeclared template-id. |
493 | bool AllFunctions = |
494 | getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) { |
495 | return isa<FunctionDecl>(ND->getUnderlyingDecl()); |
496 | }); |
497 | if (AllFunctions || (Found.empty() && !IsDependent)) { |
498 | // If lookup found any functions, or if this is a name that can only be |
499 | // used for a function, then strongly assume this is a function |
500 | // template-id. |
501 | *ATK = (Found.empty() && Found.getLookupName().isIdentifier()) |
502 | ? AssumedTemplateKind::FoundNothing |
503 | : AssumedTemplateKind::FoundFunctions; |
504 | Found.clear(); |
505 | return false; |
506 | } |
507 | } |
508 | |
509 | if (Found.empty() && !IsDependent && AllowTypoCorrection) { |
510 | // If we did not find any names, and this is not a disambiguation, attempt |
511 | // to correct any typos. |
512 | DeclarationName Name = Found.getLookupName(); |
513 | Found.clear(); |
514 | // Simple filter callback that, for keywords, only accepts the C++ *_cast |
515 | DefaultFilterCCC FilterCCC{}; |
516 | FilterCCC.WantTypeSpecifiers = false; |
517 | FilterCCC.WantExpressionKeywords = false; |
518 | FilterCCC.WantRemainingKeywords = false; |
519 | FilterCCC.WantCXXNamedCasts = true; |
520 | if (TypoCorrection Corrected = |
521 | CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S, |
522 | &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) { |
523 | if (auto *ND = Corrected.getFoundDecl()) |
524 | Found.addDecl(ND); |
525 | FilterAcceptableTemplateNames(Found); |
526 | if (Found.isAmbiguous()) { |
527 | Found.clear(); |
528 | } else if (!Found.empty()) { |
529 | Found.setLookupName(Corrected.getCorrection()); |
530 | if (LookupCtx) { |
531 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); |
532 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
533 | Name.getAsString() == CorrectedStr; |
534 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest) |
535 | << Name << LookupCtx << DroppedSpecifier |
536 | << SS.getRange()); |
537 | } else { |
538 | diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name); |
539 | } |
540 | } |
541 | } |
542 | } |
543 | |
544 | NamedDecl *ExampleLookupResult = |
545 | Found.empty() ? nullptr : Found.getRepresentativeDecl(); |
546 | FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup); |
547 | if (Found.empty()) { |
548 | if (IsDependent) { |
549 | MemberOfUnknownSpecialization = true; |
550 | return false; |
551 | } |
552 | |
553 | // If a 'template' keyword was used, a lookup that finds only non-template |
554 | // names is an error. |
555 | if (ExampleLookupResult && RequiredTemplate) { |
556 | Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template) |
557 | << Found.getLookupName() << SS.getRange() |
558 | << RequiredTemplate.hasTemplateKeyword() |
559 | << RequiredTemplate.getTemplateKeywordLoc(); |
560 | Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(), |
561 | diag::note_template_kw_refers_to_non_template) |
562 | << Found.getLookupName(); |
563 | return true; |
564 | } |
565 | |
566 | return false; |
567 | } |
568 | |
569 | if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope && |
570 | !getLangOpts().CPlusPlus11) { |
571 | // C++03 [basic.lookup.classref]p1: |
572 | // [...] If the lookup in the class of the object expression finds a |
573 | // template, the name is also looked up in the context of the entire |
574 | // postfix-expression and [...] |
575 | // |
576 | // Note: C++11 does not perform this second lookup. |
577 | LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), |
578 | LookupOrdinaryName); |
579 | FoundOuter.setTemplateNameLookup(true); |
580 | LookupName(FoundOuter, S); |
581 | // FIXME: We silently accept an ambiguous lookup here, in violation of |
582 | // [basic.lookup]/1. |
583 | FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false); |
584 | |
585 | NamedDecl *OuterTemplate; |
586 | if (FoundOuter.empty()) { |
587 | // - if the name is not found, the name found in the class of the |
588 | // object expression is used, otherwise |
589 | } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() || |
590 | !(OuterTemplate = |
591 | getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) { |
592 | // - if the name is found in the context of the entire |
593 | // postfix-expression and does not name a class template, the name |
594 | // found in the class of the object expression is used, otherwise |
595 | FoundOuter.clear(); |
596 | } else if (!Found.isSuppressingDiagnostics()) { |
597 | // - if the name found is a class template, it must refer to the same |
598 | // entity as the one found in the class of the object expression, |
599 | // otherwise the program is ill-formed. |
600 | if (!Found.isSingleResult() || |
601 | getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() != |
602 | OuterTemplate->getCanonicalDecl()) { |
603 | Diag(Found.getNameLoc(), |
604 | diag::ext_nested_name_member_ref_lookup_ambiguous) |
605 | << Found.getLookupName() |
606 | << ObjectType; |
607 | Diag(Found.getRepresentativeDecl()->getLocation(), |
608 | diag::note_ambig_member_ref_object_type) |
609 | << ObjectType; |
610 | Diag(FoundOuter.getFoundDecl()->getLocation(), |
611 | diag::note_ambig_member_ref_scope); |
612 | |
613 | // Recover by taking the template that we found in the object |
614 | // expression's type. |
615 | } |
616 | } |
617 | } |
618 | |
619 | return false; |
620 | } |
621 | |
622 | void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, |
623 | SourceLocation Less, |
624 | SourceLocation Greater) { |
625 | if (TemplateName.isInvalid()) |
626 | return; |
627 | |
628 | DeclarationNameInfo NameInfo; |
629 | CXXScopeSpec SS; |
630 | LookupNameKind LookupKind; |
631 | |
632 | DeclContext *LookupCtx = nullptr; |
633 | NamedDecl *Found = nullptr; |
634 | bool MissingTemplateKeyword = false; |
635 | |
636 | // Figure out what name we looked up. |
637 | if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) { |
638 | NameInfo = DRE->getNameInfo(); |
639 | SS.Adopt(DRE->getQualifierLoc()); |
640 | LookupKind = LookupOrdinaryName; |
641 | Found = DRE->getFoundDecl(); |
642 | } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) { |
643 | NameInfo = ME->getMemberNameInfo(); |
644 | SS.Adopt(ME->getQualifierLoc()); |
645 | LookupKind = LookupMemberName; |
646 | LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl(); |
647 | Found = ME->getMemberDecl(); |
648 | } else if (auto *DSDRE = |
649 | dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) { |
650 | NameInfo = DSDRE->getNameInfo(); |
651 | SS.Adopt(DSDRE->getQualifierLoc()); |
652 | MissingTemplateKeyword = true; |
653 | } else if (auto *DSME = |
654 | dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) { |
655 | NameInfo = DSME->getMemberNameInfo(); |
656 | SS.Adopt(DSME->getQualifierLoc()); |
657 | MissingTemplateKeyword = true; |
658 | } else { |
659 | llvm_unreachable("unexpected kind of potential template name")::llvm::llvm_unreachable_internal("unexpected kind of potential template name" , "clang/lib/Sema/SemaTemplate.cpp", 659); |
660 | } |
661 | |
662 | // If this is a dependent-scope lookup, diagnose that the 'template' keyword |
663 | // was missing. |
664 | if (MissingTemplateKeyword) { |
665 | Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing) |
666 | << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater); |
667 | return; |
668 | } |
669 | |
670 | // Try to correct the name by looking for templates and C++ named casts. |
671 | struct TemplateCandidateFilter : CorrectionCandidateCallback { |
672 | Sema &S; |
673 | TemplateCandidateFilter(Sema &S) : S(S) { |
674 | WantTypeSpecifiers = false; |
675 | WantExpressionKeywords = false; |
676 | WantRemainingKeywords = false; |
677 | WantCXXNamedCasts = true; |
678 | }; |
679 | bool ValidateCandidate(const TypoCorrection &Candidate) override { |
680 | if (auto *ND = Candidate.getCorrectionDecl()) |
681 | return S.getAsTemplateNameDecl(ND); |
682 | return Candidate.isKeyword(); |
683 | } |
684 | |
685 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
686 | return std::make_unique<TemplateCandidateFilter>(*this); |
687 | } |
688 | }; |
689 | |
690 | DeclarationName Name = NameInfo.getName(); |
691 | TemplateCandidateFilter CCC(*this); |
692 | if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC, |
693 | CTK_ErrorRecovery, LookupCtx)) { |
694 | auto *ND = Corrected.getFoundDecl(); |
695 | if (ND) |
696 | ND = getAsTemplateNameDecl(ND); |
697 | if (ND || Corrected.isKeyword()) { |
698 | if (LookupCtx) { |
699 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); |
700 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
701 | Name.getAsString() == CorrectedStr; |
702 | diagnoseTypo(Corrected, |
703 | PDiag(diag::err_non_template_in_member_template_id_suggest) |
704 | << Name << LookupCtx << DroppedSpecifier |
705 | << SS.getRange(), false); |
706 | } else { |
707 | diagnoseTypo(Corrected, |
708 | PDiag(diag::err_non_template_in_template_id_suggest) |
709 | << Name, false); |
710 | } |
711 | if (Found) |
712 | Diag(Found->getLocation(), |
713 | diag::note_non_template_in_template_id_found); |
714 | return; |
715 | } |
716 | } |
717 | |
718 | Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id) |
719 | << Name << SourceRange(Less, Greater); |
720 | if (Found) |
721 | Diag(Found->getLocation(), diag::note_non_template_in_template_id_found); |
722 | } |
723 | |
724 | /// ActOnDependentIdExpression - Handle a dependent id-expression that |
725 | /// was just parsed. This is only possible with an explicit scope |
726 | /// specifier naming a dependent type. |
727 | ExprResult |
728 | Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, |
729 | SourceLocation TemplateKWLoc, |
730 | const DeclarationNameInfo &NameInfo, |
731 | bool isAddressOfOperand, |
732 | const TemplateArgumentListInfo *TemplateArgs) { |
733 | DeclContext *DC = getFunctionLevelDeclContext(); |
734 | |
735 | // C++11 [expr.prim.general]p12: |
736 | // An id-expression that denotes a non-static data member or non-static |
737 | // member function of a class can only be used: |
738 | // (...) |
739 | // - if that id-expression denotes a non-static data member and it |
740 | // appears in an unevaluated operand. |
741 | // |
742 | // If this might be the case, form a DependentScopeDeclRefExpr instead of a |
743 | // CXXDependentScopeMemberExpr. The former can instantiate to either |
744 | // DeclRefExpr or MemberExpr depending on lookup results, while the latter is |
745 | // always a MemberExpr. |
746 | bool MightBeCxx11UnevalField = |
747 | getLangOpts().CPlusPlus11 && isUnevaluatedContext(); |
748 | |
749 | // Check if the nested name specifier is an enum type. |
750 | bool IsEnum = false; |
751 | if (NestedNameSpecifier *NNS = SS.getScopeRep()) |
752 | IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType()); |
753 | |
754 | if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum && |
755 | isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) { |
756 | QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(); |
757 | |
758 | // Since the 'this' expression is synthesized, we don't need to |
759 | // perform the double-lookup check. |
760 | NamedDecl *FirstQualifierInScope = nullptr; |
761 | |
762 | return CXXDependentScopeMemberExpr::Create( |
763 | Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true, |
764 | /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc, |
765 | FirstQualifierInScope, NameInfo, TemplateArgs); |
766 | } |
767 | |
768 | return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); |
769 | } |
770 | |
771 | ExprResult |
772 | Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, |
773 | SourceLocation TemplateKWLoc, |
774 | const DeclarationNameInfo &NameInfo, |
775 | const TemplateArgumentListInfo *TemplateArgs) { |
776 | // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc |
777 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); |
778 | if (!QualifierLoc) |
779 | return ExprError(); |
780 | |
781 | return DependentScopeDeclRefExpr::Create( |
782 | Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs); |
783 | } |
784 | |
785 | |
786 | /// Determine whether we would be unable to instantiate this template (because |
787 | /// it either has no definition, or is in the process of being instantiated). |
788 | bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, |
789 | NamedDecl *Instantiation, |
790 | bool InstantiatedFromMember, |
791 | const NamedDecl *Pattern, |
792 | const NamedDecl *PatternDef, |
793 | TemplateSpecializationKind TSK, |
794 | bool Complain /*= true*/) { |
795 | assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||(static_cast <bool> (isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl> (Instantiation)) ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)" , "clang/lib/Sema/SemaTemplate.cpp", 796, __extension__ __PRETTY_FUNCTION__ )) |
796 | isa<VarDecl>(Instantiation))(static_cast <bool> (isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl> (Instantiation)) ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)" , "clang/lib/Sema/SemaTemplate.cpp", 796, __extension__ __PRETTY_FUNCTION__ )); |
797 | |
798 | bool IsEntityBeingDefined = false; |
799 | if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef)) |
800 | IsEntityBeingDefined = TD->isBeingDefined(); |
801 | |
802 | if (PatternDef && !IsEntityBeingDefined) { |
803 | NamedDecl *SuggestedDef = nullptr; |
804 | if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef), |
805 | &SuggestedDef, |
806 | /*OnlyNeedComplete*/ false)) { |
807 | // If we're allowed to diagnose this and recover, do so. |
808 | bool Recover = Complain && !isSFINAEContext(); |
809 | if (Complain) |
810 | diagnoseMissingImport(PointOfInstantiation, SuggestedDef, |
811 | Sema::MissingImportKind::Definition, Recover); |
812 | return !Recover; |
813 | } |
814 | return false; |
815 | } |
816 | |
817 | if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) |
818 | return true; |
819 | |
820 | std::optional<unsigned> Note; |
821 | QualType InstantiationTy; |
822 | if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation)) |
823 | InstantiationTy = Context.getTypeDeclType(TD); |
824 | if (PatternDef) { |
825 | Diag(PointOfInstantiation, |
826 | diag::err_template_instantiate_within_definition) |
827 | << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation) |
828 | << InstantiationTy; |
829 | // Not much point in noting the template declaration here, since |
830 | // we're lexically inside it. |
831 | Instantiation->setInvalidDecl(); |
832 | } else if (InstantiatedFromMember) { |
833 | if (isa<FunctionDecl>(Instantiation)) { |
834 | Diag(PointOfInstantiation, |
835 | diag::err_explicit_instantiation_undefined_member) |
836 | << /*member function*/ 1 << Instantiation->getDeclName() |
837 | << Instantiation->getDeclContext(); |
838 | Note = diag::note_explicit_instantiation_here; |
839 | } else { |
840 | assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!")(static_cast <bool> (isa<TagDecl>(Instantiation) && "Must be a TagDecl!") ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) && \"Must be a TagDecl!\"" , "clang/lib/Sema/SemaTemplate.cpp", 840, __extension__ __PRETTY_FUNCTION__ )); |
841 | Diag(PointOfInstantiation, |
842 | diag::err_implicit_instantiate_member_undefined) |
843 | << InstantiationTy; |
844 | Note = diag::note_member_declared_at; |
845 | } |
846 | } else { |
847 | if (isa<FunctionDecl>(Instantiation)) { |
848 | Diag(PointOfInstantiation, |
849 | diag::err_explicit_instantiation_undefined_func_template) |
850 | << Pattern; |
851 | Note = diag::note_explicit_instantiation_here; |
852 | } else if (isa<TagDecl>(Instantiation)) { |
853 | Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) |
854 | << (TSK != TSK_ImplicitInstantiation) |
855 | << InstantiationTy; |
856 | Note = diag::note_template_decl_here; |
857 | } else { |
858 | assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!")(static_cast <bool> (isa<VarDecl>(Instantiation) && "Must be a VarDecl!") ? void (0) : __assert_fail ("isa<VarDecl>(Instantiation) && \"Must be a VarDecl!\"" , "clang/lib/Sema/SemaTemplate.cpp", 858, __extension__ __PRETTY_FUNCTION__ )); |
859 | if (isa<VarTemplateSpecializationDecl>(Instantiation)) { |
860 | Diag(PointOfInstantiation, |
861 | diag::err_explicit_instantiation_undefined_var_template) |
862 | << Instantiation; |
863 | Instantiation->setInvalidDecl(); |
864 | } else |
865 | Diag(PointOfInstantiation, |
866 | diag::err_explicit_instantiation_undefined_member) |
867 | << /*static data member*/ 2 << Instantiation->getDeclName() |
868 | << Instantiation->getDeclContext(); |
869 | Note = diag::note_explicit_instantiation_here; |
870 | } |
871 | } |
872 | if (Note) // Diagnostics were emitted. |
873 | Diag(Pattern->getLocation(), *Note); |
874 | |
875 | // In general, Instantiation isn't marked invalid to get more than one |
876 | // error for multiple undefined instantiations. But the code that does |
877 | // explicit declaration -> explicit definition conversion can't handle |
878 | // invalid declarations, so mark as invalid in that case. |
879 | if (TSK == TSK_ExplicitInstantiationDeclaration) |
880 | Instantiation->setInvalidDecl(); |
881 | return true; |
882 | } |
883 | |
884 | /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining |
885 | /// that the template parameter 'PrevDecl' is being shadowed by a new |
886 | /// declaration at location Loc. Returns true to indicate that this is |
887 | /// an error, and false otherwise. |
888 | void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { |
889 | assert(PrevDecl->isTemplateParameter() && "Not a template parameter")(static_cast <bool> (PrevDecl->isTemplateParameter() && "Not a template parameter") ? void (0) : __assert_fail ("PrevDecl->isTemplateParameter() && \"Not a template parameter\"" , "clang/lib/Sema/SemaTemplate.cpp", 889, __extension__ __PRETTY_FUNCTION__ )); |
890 | |
891 | // C++ [temp.local]p4: |
892 | // A template-parameter shall not be redeclared within its |
893 | // scope (including nested scopes). |
894 | // |
895 | // Make this a warning when MSVC compatibility is requested. |
896 | unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow |
897 | : diag::err_template_param_shadow; |
898 | Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName(); |
899 | Diag(PrevDecl->getLocation(), diag::note_template_param_here); |
900 | } |
901 | |
902 | /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset |
903 | /// the parameter D to reference the templated declaration and return a pointer |
904 | /// to the template declaration. Otherwise, do nothing to D and return null. |
905 | TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) { |
906 | if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) { |
907 | D = Temp->getTemplatedDecl(); |
908 | return Temp; |
909 | } |
910 | return nullptr; |
911 | } |
912 | |
913 | ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion( |
914 | SourceLocation EllipsisLoc) const { |
915 | assert(Kind == Template &&(static_cast <bool> (Kind == Template && "Only template template arguments can be pack expansions here" ) ? void (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\"" , "clang/lib/Sema/SemaTemplate.cpp", 916, __extension__ __PRETTY_FUNCTION__ )) |
916 | "Only template template arguments can be pack expansions here")(static_cast <bool> (Kind == Template && "Only template template arguments can be pack expansions here" ) ? void (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\"" , "clang/lib/Sema/SemaTemplate.cpp", 916, __extension__ __PRETTY_FUNCTION__ )); |
917 | assert(getAsTemplate().get().containsUnexpandedParameterPack() &&(static_cast <bool> (getAsTemplate().get().containsUnexpandedParameterPack () && "Template template argument pack expansion without packs" ) ? void (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\"" , "clang/lib/Sema/SemaTemplate.cpp", 918, __extension__ __PRETTY_FUNCTION__ )) |
918 | "Template template argument pack expansion without packs")(static_cast <bool> (getAsTemplate().get().containsUnexpandedParameterPack () && "Template template argument pack expansion without packs" ) ? void (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\"" , "clang/lib/Sema/SemaTemplate.cpp", 918, __extension__ __PRETTY_FUNCTION__ )); |
919 | ParsedTemplateArgument Result(*this); |
920 | Result.EllipsisLoc = EllipsisLoc; |
921 | return Result; |
922 | } |
923 | |
924 | static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, |
925 | const ParsedTemplateArgument &Arg) { |
926 | |
927 | switch (Arg.getKind()) { |
928 | case ParsedTemplateArgument::Type: { |
929 | TypeSourceInfo *DI; |
930 | QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); |
931 | if (!DI) |
932 | DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation()); |
933 | return TemplateArgumentLoc(TemplateArgument(T), DI); |
934 | } |
935 | |
936 | case ParsedTemplateArgument::NonType: { |
937 | Expr *E = static_cast<Expr *>(Arg.getAsExpr()); |
938 | return TemplateArgumentLoc(TemplateArgument(E), E); |
939 | } |
940 | |
941 | case ParsedTemplateArgument::Template: { |
942 | TemplateName Template = Arg.getAsTemplate().get(); |
943 | TemplateArgument TArg; |
944 | if (Arg.getEllipsisLoc().isValid()) |
945 | TArg = TemplateArgument(Template, std::optional<unsigned int>()); |
946 | else |
947 | TArg = Template; |
948 | return TemplateArgumentLoc( |
949 | SemaRef.Context, TArg, |
950 | Arg.getScopeSpec().getWithLocInContext(SemaRef.Context), |
951 | Arg.getLocation(), Arg.getEllipsisLoc()); |
952 | } |
953 | } |
954 | |
955 | llvm_unreachable("Unhandled parsed template argument")::llvm::llvm_unreachable_internal("Unhandled parsed template argument" , "clang/lib/Sema/SemaTemplate.cpp", 955); |
956 | } |
957 | |
958 | /// Translates template arguments as provided by the parser |
959 | /// into template arguments used by semantic analysis. |
960 | void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, |
961 | TemplateArgumentListInfo &TemplateArgs) { |
962 | for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) |
963 | TemplateArgs.addArgument(translateTemplateArgument(*this, |
964 | TemplateArgsIn[I])); |
965 | } |
966 | |
967 | static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, |
968 | SourceLocation Loc, |
969 | IdentifierInfo *Name) { |
970 | NamedDecl *PrevDecl = SemaRef.LookupSingleName( |
971 | S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); |
972 | if (PrevDecl && PrevDecl->isTemplateParameter()) |
973 | SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl); |
974 | } |
975 | |
976 | /// Convert a parsed type into a parsed template argument. This is mostly |
977 | /// trivial, except that we may have parsed a C++17 deduced class template |
978 | /// specialization type, in which case we should form a template template |
979 | /// argument instead of a type template argument. |
980 | ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) { |
981 | TypeSourceInfo *TInfo; |
982 | QualType T = GetTypeFromParser(ParsedType.get(), &TInfo); |
983 | if (T.isNull()) |
984 | return ParsedTemplateArgument(); |
985 | assert(TInfo && "template argument with no location")(static_cast <bool> (TInfo && "template argument with no location" ) ? void (0) : __assert_fail ("TInfo && \"template argument with no location\"" , "clang/lib/Sema/SemaTemplate.cpp", 985, __extension__ __PRETTY_FUNCTION__ )); |
986 | |
987 | // If we might have formed a deduced template specialization type, convert |
988 | // it to a template template argument. |
989 | if (getLangOpts().CPlusPlus17) { |
990 | TypeLoc TL = TInfo->getTypeLoc(); |
991 | SourceLocation EllipsisLoc; |
992 | if (auto PET = TL.getAs<PackExpansionTypeLoc>()) { |
993 | EllipsisLoc = PET.getEllipsisLoc(); |
994 | TL = PET.getPatternLoc(); |
995 | } |
996 | |
997 | CXXScopeSpec SS; |
998 | if (auto ET = TL.getAs<ElaboratedTypeLoc>()) { |
999 | SS.Adopt(ET.getQualifierLoc()); |
1000 | TL = ET.getNamedTypeLoc(); |
1001 | } |
1002 | |
1003 | if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) { |
1004 | TemplateName Name = DTST.getTypePtr()->getTemplateName(); |
1005 | if (SS.isSet()) |
1006 | Name = Context.getQualifiedTemplateName(SS.getScopeRep(), |
1007 | /*HasTemplateKeyword=*/false, |
1008 | Name); |
1009 | ParsedTemplateArgument Result(SS, TemplateTy::make(Name), |
1010 | DTST.getTemplateNameLoc()); |
1011 | if (EllipsisLoc.isValid()) |
1012 | Result = Result.getTemplatePackExpansion(EllipsisLoc); |
1013 | return Result; |
1014 | } |
1015 | } |
1016 | |
1017 | // This is a normal type template argument. Note, if the type template |
1018 | // argument is an injected-class-name for a template, it has a dual nature |
1019 | // and can be used as either a type or a template. We handle that in |
1020 | // convertTypeTemplateArgumentToTemplate. |
1021 | return ParsedTemplateArgument(ParsedTemplateArgument::Type, |
1022 | ParsedType.get().getAsOpaquePtr(), |
1023 | TInfo->getTypeLoc().getBeginLoc()); |
1024 | } |
1025 | |
1026 | /// ActOnTypeParameter - Called when a C++ template type parameter |
1027 | /// (e.g., "typename T") has been parsed. Typename specifies whether |
1028 | /// the keyword "typename" was used to declare the type parameter |
1029 | /// (otherwise, "class" was used), and KeyLoc is the location of the |
1030 | /// "class" or "typename" keyword. ParamName is the name of the |
1031 | /// parameter (NULL indicates an unnamed template parameter) and |
1032 | /// ParamNameLoc is the location of the parameter name (if any). |
1033 | /// If the type parameter has a default argument, it will be added |
1034 | /// later via ActOnTypeParameterDefault. |
1035 | NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename, |
1036 | SourceLocation EllipsisLoc, |
1037 | SourceLocation KeyLoc, |
1038 | IdentifierInfo *ParamName, |
1039 | SourceLocation ParamNameLoc, |
1040 | unsigned Depth, unsigned Position, |
1041 | SourceLocation EqualLoc, |
1042 | ParsedType DefaultArg, |
1043 | bool HasTypeConstraint) { |
1044 | assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() && "Template type parameter not in template parameter scope!") ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1045, __extension__ __PRETTY_FUNCTION__ )) |
1045 | "Template type parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() && "Template type parameter not in template parameter scope!") ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1045, __extension__ __PRETTY_FUNCTION__ )); |
1046 | |
1047 | bool IsParameterPack = EllipsisLoc.isValid(); |
1048 | TemplateTypeParmDecl *Param |
1049 | = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), |
1050 | KeyLoc, ParamNameLoc, Depth, Position, |
1051 | ParamName, Typename, IsParameterPack, |
1052 | HasTypeConstraint); |
1053 | Param->setAccess(AS_public); |
1054 | |
1055 | if (Param->isParameterPack()) |
1056 | if (auto *LSI = getEnclosingLambda()) |
1057 | LSI->LocalPacks.push_back(Param); |
1058 | |
1059 | if (ParamName) { |
1060 | maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName); |
1061 | |
1062 | // Add the template parameter into the current scope. |
1063 | S->AddDecl(Param); |
1064 | IdResolver.AddDecl(Param); |
1065 | } |
1066 | |
1067 | // C++0x [temp.param]p9: |
1068 | // A default template-argument may be specified for any kind of |
1069 | // template-parameter that is not a template parameter pack. |
1070 | if (DefaultArg && IsParameterPack) { |
1071 | Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
1072 | DefaultArg = nullptr; |
1073 | } |
1074 | |
1075 | // Handle the default argument, if provided. |
1076 | if (DefaultArg) { |
1077 | TypeSourceInfo *DefaultTInfo; |
1078 | GetTypeFromParser(DefaultArg, &DefaultTInfo); |
1079 | |
1080 | assert(DefaultTInfo && "expected source information for type")(static_cast <bool> (DefaultTInfo && "expected source information for type" ) ? void (0) : __assert_fail ("DefaultTInfo && \"expected source information for type\"" , "clang/lib/Sema/SemaTemplate.cpp", 1080, __extension__ __PRETTY_FUNCTION__ )); |
1081 | |
1082 | // Check for unexpanded parameter packs. |
1083 | if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo, |
1084 | UPPC_DefaultArgument)) |
1085 | return Param; |
1086 | |
1087 | // Check the template argument itself. |
1088 | if (CheckTemplateArgument(DefaultTInfo)) { |
1089 | Param->setInvalidDecl(); |
1090 | return Param; |
1091 | } |
1092 | |
1093 | Param->setDefaultArgument(DefaultTInfo); |
1094 | } |
1095 | |
1096 | return Param; |
1097 | } |
1098 | |
1099 | /// Convert the parser's template argument list representation into our form. |
1100 | static TemplateArgumentListInfo |
1101 | makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) { |
1102 | TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc, |
1103 | TemplateId.RAngleLoc); |
1104 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(), |
1105 | TemplateId.NumArgs); |
1106 | S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs); |
1107 | return TemplateArgs; |
1108 | } |
1109 | |
1110 | bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS, |
1111 | TemplateIdAnnotation *TypeConstr, |
1112 | TemplateTypeParmDecl *ConstrainedParameter, |
1113 | SourceLocation EllipsisLoc) { |
1114 | return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc, |
1115 | false); |
1116 | } |
1117 | |
1118 | bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS, |
1119 | TemplateIdAnnotation *TypeConstr, |
1120 | TemplateTypeParmDecl *ConstrainedParameter, |
1121 | SourceLocation EllipsisLoc, |
1122 | bool AllowUnexpandedPack) { |
1123 | TemplateName TN = TypeConstr->Template.get(); |
1124 | ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl()); |
1125 | |
1126 | // C++2a [temp.param]p4: |
1127 | // [...] The concept designated by a type-constraint shall be a type |
1128 | // concept ([temp.concept]). |
1129 | if (!CD->isTypeConcept()) { |
1130 | Diag(TypeConstr->TemplateNameLoc, |
1131 | diag::err_type_constraint_non_type_concept); |
1132 | return true; |
1133 | } |
1134 | |
1135 | bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid(); |
1136 | |
1137 | if (!WereArgsSpecified && |
1138 | CD->getTemplateParameters()->getMinRequiredArguments() > 1) { |
1139 | Diag(TypeConstr->TemplateNameLoc, |
1140 | diag::err_type_constraint_missing_arguments) << CD; |
1141 | return true; |
1142 | } |
1143 | |
1144 | DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name), |
1145 | TypeConstr->TemplateNameLoc); |
1146 | |
1147 | TemplateArgumentListInfo TemplateArgs; |
1148 | if (TypeConstr->LAngleLoc.isValid()) { |
1149 | TemplateArgs = |
1150 | makeTemplateArgumentListInfo(*this, *TypeConstr); |
1151 | |
1152 | if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) { |
1153 | for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) { |
1154 | if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint)) |
1155 | return true; |
1156 | } |
1157 | } |
1158 | } |
1159 | return AttachTypeConstraint( |
1160 | SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(), |
1161 | ConceptName, CD, |
1162 | TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr, |
1163 | ConstrainedParameter, EllipsisLoc); |
1164 | } |
1165 | |
1166 | template<typename ArgumentLocAppender> |
1167 | static ExprResult formImmediatelyDeclaredConstraint( |
1168 | Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, |
1169 | ConceptDecl *NamedConcept, SourceLocation LAngleLoc, |
1170 | SourceLocation RAngleLoc, QualType ConstrainedType, |
1171 | SourceLocation ParamNameLoc, ArgumentLocAppender Appender, |
1172 | SourceLocation EllipsisLoc) { |
1173 | |
1174 | TemplateArgumentListInfo ConstraintArgs; |
1175 | ConstraintArgs.addArgument( |
1176 | S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType), |
1177 | /*NTTPType=*/QualType(), ParamNameLoc)); |
1178 | |
1179 | ConstraintArgs.setRAngleLoc(RAngleLoc); |
1180 | ConstraintArgs.setLAngleLoc(LAngleLoc); |
1181 | Appender(ConstraintArgs); |
1182 | |
1183 | // C++2a [temp.param]p4: |
1184 | // [...] This constraint-expression E is called the immediately-declared |
1185 | // constraint of T. [...] |
1186 | CXXScopeSpec SS; |
1187 | SS.Adopt(NS); |
1188 | ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId( |
1189 | SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo, |
1190 | /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs); |
1191 | if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid()) |
1192 | return ImmediatelyDeclaredConstraint; |
1193 | |
1194 | // C++2a [temp.param]p4: |
1195 | // [...] If T is not a pack, then E is E', otherwise E is (E' && ...). |
1196 | // |
1197 | // We have the following case: |
1198 | // |
1199 | // template<typename T> concept C1 = true; |
1200 | // template<C1... T> struct s1; |
1201 | // |
1202 | // The constraint: (C1<T> && ...) |
1203 | // |
1204 | // Note that the type of C1<T> is known to be 'bool', so we don't need to do |
1205 | // any unqualified lookups for 'operator&&' here. |
1206 | return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr, |
1207 | /*LParenLoc=*/SourceLocation(), |
1208 | ImmediatelyDeclaredConstraint.get(), BO_LAnd, |
1209 | EllipsisLoc, /*RHS=*/nullptr, |
1210 | /*RParenLoc=*/SourceLocation(), |
1211 | /*NumExpansions=*/std::nullopt); |
1212 | } |
1213 | |
1214 | /// Attach a type-constraint to a template parameter. |
1215 | /// \returns true if an error occurred. This can happen if the |
1216 | /// immediately-declared constraint could not be formed (e.g. incorrect number |
1217 | /// of arguments for the named concept). |
1218 | bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS, |
1219 | DeclarationNameInfo NameInfo, |
1220 | ConceptDecl *NamedConcept, |
1221 | const TemplateArgumentListInfo *TemplateArgs, |
1222 | TemplateTypeParmDecl *ConstrainedParameter, |
1223 | SourceLocation EllipsisLoc) { |
1224 | // C++2a [temp.param]p4: |
1225 | // [...] If Q is of the form C<A1, ..., An>, then let E' be |
1226 | // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...] |
1227 | const ASTTemplateArgumentListInfo *ArgsAsWritten = |
1228 | TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context, |
1229 | *TemplateArgs) : nullptr; |
1230 | |
1231 | QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0); |
1232 | |
1233 | ExprResult ImmediatelyDeclaredConstraint = |
1234 | formImmediatelyDeclaredConstraint( |
1235 | *this, NS, NameInfo, NamedConcept, |
1236 | TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(), |
1237 | TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(), |
1238 | ParamAsArgument, ConstrainedParameter->getLocation(), |
1239 | [&] (TemplateArgumentListInfo &ConstraintArgs) { |
1240 | if (TemplateArgs) |
1241 | for (const auto &ArgLoc : TemplateArgs->arguments()) |
1242 | ConstraintArgs.addArgument(ArgLoc); |
1243 | }, EllipsisLoc); |
1244 | if (ImmediatelyDeclaredConstraint.isInvalid()) |
1245 | return true; |
1246 | |
1247 | ConstrainedParameter->setTypeConstraint(NS, NameInfo, |
1248 | /*FoundDecl=*/NamedConcept, |
1249 | NamedConcept, ArgsAsWritten, |
1250 | ImmediatelyDeclaredConstraint.get()); |
1251 | return false; |
1252 | } |
1253 | |
1254 | bool Sema::AttachTypeConstraint(AutoTypeLoc TL, |
1255 | NonTypeTemplateParmDecl *NewConstrainedParm, |
1256 | NonTypeTemplateParmDecl *OrigConstrainedParm, |
1257 | SourceLocation EllipsisLoc) { |
1258 | if (NewConstrainedParm->getType() != TL.getType() || |
1259 | TL.getAutoKeyword() != AutoTypeKeyword::Auto) { |
1260 | Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), |
1261 | diag::err_unsupported_placeholder_constraint) |
1262 | << NewConstrainedParm->getTypeSourceInfo() |
1263 | ->getTypeLoc() |
1264 | .getSourceRange(); |
1265 | return true; |
1266 | } |
1267 | // FIXME: Concepts: This should be the type of the placeholder, but this is |
1268 | // unclear in the wording right now. |
1269 | DeclRefExpr *Ref = |
1270 | BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(), |
1271 | VK_PRValue, OrigConstrainedParm->getLocation()); |
1272 | if (!Ref) |
1273 | return true; |
1274 | ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint( |
1275 | *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(), |
1276 | TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(), |
1277 | BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(), |
1278 | [&](TemplateArgumentListInfo &ConstraintArgs) { |
1279 | for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I) |
1280 | ConstraintArgs.addArgument(TL.getArgLoc(I)); |
1281 | }, |
1282 | EllipsisLoc); |
1283 | if (ImmediatelyDeclaredConstraint.isInvalid() || |
1284 | !ImmediatelyDeclaredConstraint.isUsable()) |
1285 | return true; |
1286 | |
1287 | NewConstrainedParm->setPlaceholderTypeConstraint( |
1288 | ImmediatelyDeclaredConstraint.get()); |
1289 | return false; |
1290 | } |
1291 | |
1292 | /// Check that the type of a non-type template parameter is |
1293 | /// well-formed. |
1294 | /// |
1295 | /// \returns the (possibly-promoted) parameter type if valid; |
1296 | /// otherwise, produces a diagnostic and returns a NULL type. |
1297 | QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, |
1298 | SourceLocation Loc) { |
1299 | if (TSI->getType()->isUndeducedType()) { |
1300 | // C++17 [temp.dep.expr]p3: |
1301 | // An id-expression is type-dependent if it contains |
1302 | // - an identifier associated by name lookup with a non-type |
1303 | // template-parameter declared with a type that contains a |
1304 | // placeholder type (7.1.7.4), |
1305 | TSI = SubstAutoTypeSourceInfoDependent(TSI); |
1306 | } |
1307 | |
1308 | return CheckNonTypeTemplateParameterType(TSI->getType(), Loc); |
1309 | } |
1310 | |
1311 | /// Require the given type to be a structural type, and diagnose if it is not. |
1312 | /// |
1313 | /// \return \c true if an error was produced. |
1314 | bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) { |
1315 | if (T->isDependentType()) |
1316 | return false; |
1317 | |
1318 | if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete)) |
1319 | return true; |
1320 | |
1321 | if (T->isStructuralType()) |
1322 | return false; |
1323 | |
1324 | // Structural types are required to be object types or lvalue references. |
1325 | if (T->isRValueReferenceType()) { |
1326 | Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T; |
1327 | return true; |
1328 | } |
1329 | |
1330 | // Don't mention structural types in our diagnostic prior to C++20. Also, |
1331 | // there's not much more we can say about non-scalar non-class types -- |
1332 | // because we can't see functions or arrays here, those can only be language |
1333 | // extensions. |
1334 | if (!getLangOpts().CPlusPlus20 || |
1335 | (!T->isScalarType() && !T->isRecordType())) { |
1336 | Diag(Loc, diag::err_template_nontype_parm_bad_type) << T; |
1337 | return true; |
1338 | } |
1339 | |
1340 | // Structural types are required to be literal types. |
1341 | if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal)) |
1342 | return true; |
1343 | |
1344 | Diag(Loc, diag::err_template_nontype_parm_not_structural) << T; |
1345 | |
1346 | // Drill down into the reason why the class is non-structural. |
1347 | while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { |
1348 | // All members are required to be public and non-mutable, and can't be of |
1349 | // rvalue reference type. Check these conditions first to prefer a "local" |
1350 | // reason over a more distant one. |
1351 | for (const FieldDecl *FD : RD->fields()) { |
1352 | if (FD->getAccess() != AS_public) { |
1353 | Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0; |
1354 | return true; |
1355 | } |
1356 | if (FD->isMutable()) { |
1357 | Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T; |
1358 | return true; |
1359 | } |
1360 | if (FD->getType()->isRValueReferenceType()) { |
1361 | Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field) |
1362 | << T; |
1363 | return true; |
1364 | } |
1365 | } |
1366 | |
1367 | // All bases are required to be public. |
1368 | for (const auto &BaseSpec : RD->bases()) { |
1369 | if (BaseSpec.getAccessSpecifier() != AS_public) { |
1370 | Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public) |
1371 | << T << 1; |
1372 | return true; |
1373 | } |
1374 | } |
1375 | |
1376 | // All subobjects are required to be of structural types. |
1377 | SourceLocation SubLoc; |
1378 | QualType SubType; |
1379 | int Kind = -1; |
1380 | |
1381 | for (const FieldDecl *FD : RD->fields()) { |
1382 | QualType T = Context.getBaseElementType(FD->getType()); |
1383 | if (!T->isStructuralType()) { |
1384 | SubLoc = FD->getLocation(); |
1385 | SubType = T; |
1386 | Kind = 0; |
1387 | break; |
1388 | } |
1389 | } |
1390 | |
1391 | if (Kind == -1) { |
1392 | for (const auto &BaseSpec : RD->bases()) { |
1393 | QualType T = BaseSpec.getType(); |
1394 | if (!T->isStructuralType()) { |
1395 | SubLoc = BaseSpec.getBaseTypeLoc(); |
1396 | SubType = T; |
1397 | Kind = 1; |
1398 | break; |
1399 | } |
1400 | } |
1401 | } |
1402 | |
1403 | assert(Kind != -1 && "couldn't find reason why type is not structural")(static_cast <bool> (Kind != -1 && "couldn't find reason why type is not structural" ) ? void (0) : __assert_fail ("Kind != -1 && \"couldn't find reason why type is not structural\"" , "clang/lib/Sema/SemaTemplate.cpp", 1403, __extension__ __PRETTY_FUNCTION__ )); |
1404 | Diag(SubLoc, diag::note_not_structural_subobject) |
1405 | << T << Kind << SubType; |
1406 | T = SubType; |
1407 | RD = T->getAsCXXRecordDecl(); |
Value stored to 'RD' is never read | |
1408 | } |
1409 | |
1410 | return true; |
1411 | } |
1412 | |
1413 | QualType Sema::CheckNonTypeTemplateParameterType(QualType T, |
1414 | SourceLocation Loc) { |
1415 | // We don't allow variably-modified types as the type of non-type template |
1416 | // parameters. |
1417 | if (T->isVariablyModifiedType()) { |
1418 | Diag(Loc, diag::err_variably_modified_nontype_template_param) |
1419 | << T; |
1420 | return QualType(); |
1421 | } |
1422 | |
1423 | // C++ [temp.param]p4: |
1424 | // |
1425 | // A non-type template-parameter shall have one of the following |
1426 | // (optionally cv-qualified) types: |
1427 | // |
1428 | // -- integral or enumeration type, |
1429 | if (T->isIntegralOrEnumerationType() || |
1430 | // -- pointer to object or pointer to function, |
1431 | T->isPointerType() || |
1432 | // -- lvalue reference to object or lvalue reference to function, |
1433 | T->isLValueReferenceType() || |
1434 | // -- pointer to member, |
1435 | T->isMemberPointerType() || |
1436 | // -- std::nullptr_t, or |
1437 | T->isNullPtrType() || |
1438 | // -- a type that contains a placeholder type. |
1439 | T->isUndeducedType()) { |
1440 | // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter |
1441 | // are ignored when determining its type. |
1442 | return T.getUnqualifiedType(); |
1443 | } |
1444 | |
1445 | // C++ [temp.param]p8: |
1446 | // |
1447 | // A non-type template-parameter of type "array of T" or |
1448 | // "function returning T" is adjusted to be of type "pointer to |
1449 | // T" or "pointer to function returning T", respectively. |
1450 | if (T->isArrayType() || T->isFunctionType()) |
1451 | return Context.getDecayedType(T); |
1452 | |
1453 | // If T is a dependent type, we can't do the check now, so we |
1454 | // assume that it is well-formed. Note that stripping off the |
1455 | // qualifiers here is not really correct if T turns out to be |
1456 | // an array type, but we'll recompute the type everywhere it's |
1457 | // used during instantiation, so that should be OK. (Using the |
1458 | // qualified type is equally wrong.) |
1459 | if (T->isDependentType()) |
1460 | return T.getUnqualifiedType(); |
1461 | |
1462 | // C++20 [temp.param]p6: |
1463 | // -- a structural type |
1464 | if (RequireStructuralType(T, Loc)) |
1465 | return QualType(); |
1466 | |
1467 | if (!getLangOpts().CPlusPlus20) { |
1468 | // FIXME: Consider allowing structural types as an extension in C++17. (In |
1469 | // earlier language modes, the template argument evaluation rules are too |
1470 | // inflexible.) |
1471 | Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T; |
1472 | return QualType(); |
1473 | } |
1474 | |
1475 | Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T; |
1476 | return T.getUnqualifiedType(); |
1477 | } |
1478 | |
1479 | NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, |
1480 | unsigned Depth, |
1481 | unsigned Position, |
1482 | SourceLocation EqualLoc, |
1483 | Expr *Default) { |
1484 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); |
1485 | |
1486 | // Check that we have valid decl-specifiers specified. |
1487 | auto CheckValidDeclSpecifiers = [this, &D] { |
1488 | // C++ [temp.param] |
1489 | // p1 |
1490 | // template-parameter: |
1491 | // ... |
1492 | // parameter-declaration |
1493 | // p2 |
1494 | // ... A storage class shall not be specified in a template-parameter |
1495 | // declaration. |
1496 | // [dcl.typedef]p1: |
1497 | // The typedef specifier [...] shall not be used in the decl-specifier-seq |
1498 | // of a parameter-declaration |
1499 | const DeclSpec &DS = D.getDeclSpec(); |
1500 | auto EmitDiag = [this](SourceLocation Loc) { |
1501 | Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm) |
1502 | << FixItHint::CreateRemoval(Loc); |
1503 | }; |
1504 | if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) |
1505 | EmitDiag(DS.getStorageClassSpecLoc()); |
1506 | |
1507 | if (DS.getThreadStorageClassSpec() != TSCS_unspecified) |
1508 | EmitDiag(DS.getThreadStorageClassSpecLoc()); |
1509 | |
1510 | // [dcl.inline]p1: |
1511 | // The inline specifier can be applied only to the declaration or |
1512 | // definition of a variable or function. |
1513 | |
1514 | if (DS.isInlineSpecified()) |
1515 | EmitDiag(DS.getInlineSpecLoc()); |
1516 | |
1517 | // [dcl.constexpr]p1: |
1518 | // The constexpr specifier shall be applied only to the definition of a |
1519 | // variable or variable template or the declaration of a function or |
1520 | // function template. |
1521 | |
1522 | if (DS.hasConstexprSpecifier()) |
1523 | EmitDiag(DS.getConstexprSpecLoc()); |
1524 | |
1525 | // [dcl.fct.spec]p1: |
1526 | // Function-specifiers can be used only in function declarations. |
1527 | |
1528 | if (DS.isVirtualSpecified()) |
1529 | EmitDiag(DS.getVirtualSpecLoc()); |
1530 | |
1531 | if (DS.hasExplicitSpecifier()) |
1532 | EmitDiag(DS.getExplicitSpecLoc()); |
1533 | |
1534 | if (DS.isNoreturnSpecified()) |
1535 | EmitDiag(DS.getNoreturnSpecLoc()); |
1536 | }; |
1537 | |
1538 | CheckValidDeclSpecifiers(); |
1539 | |
1540 | if (const auto *T = TInfo->getType()->getContainedDeducedType()) |
1541 | if (isa<AutoType>(T)) |
1542 | Diag(D.getIdentifierLoc(), |
1543 | diag::warn_cxx14_compat_template_nontype_parm_auto_type) |
1544 | << QualType(TInfo->getType()->getContainedAutoType(), 0); |
1545 | |
1546 | assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!" ) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1547, __extension__ __PRETTY_FUNCTION__ )) |
1547 | "Non-type template parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!" ) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1547, __extension__ __PRETTY_FUNCTION__ )); |
1548 | bool Invalid = false; |
1549 | |
1550 | QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc()); |
1551 | if (T.isNull()) { |
1552 | T = Context.IntTy; // Recover with an 'int' type. |
1553 | Invalid = true; |
1554 | } |
1555 | |
1556 | CheckFunctionOrTemplateParamDeclarator(S, D); |
1557 | |
1558 | IdentifierInfo *ParamName = D.getIdentifier(); |
1559 | bool IsParameterPack = D.hasEllipsis(); |
1560 | NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create( |
1561 | Context, Context.getTranslationUnitDecl(), D.getBeginLoc(), |
1562 | D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack, |
1563 | TInfo); |
1564 | Param->setAccess(AS_public); |
1565 | |
1566 | if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) |
1567 | if (TL.isConstrained()) |
1568 | if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc())) |
1569 | Invalid = true; |
1570 | |
1571 | if (Invalid) |
1572 | Param->setInvalidDecl(); |
1573 | |
1574 | if (Param->isParameterPack()) |
1575 | if (auto *LSI = getEnclosingLambda()) |
1576 | LSI->LocalPacks.push_back(Param); |
1577 | |
1578 | if (ParamName) { |
1579 | maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(), |
1580 | ParamName); |
1581 | |
1582 | // Add the template parameter into the current scope. |
1583 | S->AddDecl(Param); |
1584 | IdResolver.AddDecl(Param); |
1585 | } |
1586 | |
1587 | // C++0x [temp.param]p9: |
1588 | // A default template-argument may be specified for any kind of |
1589 | // template-parameter that is not a template parameter pack. |
1590 | if (Default && IsParameterPack) { |
1591 | Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
1592 | Default = nullptr; |
1593 | } |
1594 | |
1595 | // Check the well-formedness of the default template argument, if provided. |
1596 | if (Default) { |
1597 | // Check for unexpanded parameter packs. |
1598 | if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument)) |
1599 | return Param; |
1600 | |
1601 | TemplateArgument SugaredConverted, CanonicalConverted; |
1602 | ExprResult DefaultRes = CheckTemplateArgument( |
1603 | Param, Param->getType(), Default, SugaredConverted, CanonicalConverted, |
1604 | CTAK_Specified); |
1605 | if (DefaultRes.isInvalid()) { |
1606 | Param->setInvalidDecl(); |
1607 | return Param; |
1608 | } |
1609 | Default = DefaultRes.get(); |
1610 | |
1611 | Param->setDefaultArgument(Default); |
1612 | } |
1613 | |
1614 | return Param; |
1615 | } |
1616 | |
1617 | /// ActOnTemplateTemplateParameter - Called when a C++ template template |
1618 | /// parameter (e.g. T in template <template \<typename> class T> class array) |
1619 | /// has been parsed. S is the current scope. |
1620 | NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S, |
1621 | SourceLocation TmpLoc, |
1622 | TemplateParameterList *Params, |
1623 | SourceLocation EllipsisLoc, |
1624 | IdentifierInfo *Name, |
1625 | SourceLocation NameLoc, |
1626 | unsigned Depth, |
1627 | unsigned Position, |
1628 | SourceLocation EqualLoc, |
1629 | ParsedTemplateArgument Default) { |
1630 | assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() && "Template template parameter not in template parameter scope!" ) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1631, __extension__ __PRETTY_FUNCTION__ )) |
1631 | "Template template parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() && "Template template parameter not in template parameter scope!" ) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 1631, __extension__ __PRETTY_FUNCTION__ )); |
1632 | |
1633 | // Construct the parameter object. |
1634 | bool IsParameterPack = EllipsisLoc.isValid(); |
1635 | TemplateTemplateParmDecl *Param = |
1636 | TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), |
1637 | NameLoc.isInvalid()? TmpLoc : NameLoc, |
1638 | Depth, Position, IsParameterPack, |
1639 | Name, Params); |
1640 | Param->setAccess(AS_public); |
1641 | |
1642 | if (Param->isParameterPack()) |
1643 | if (auto *LSI = getEnclosingLambda()) |
1644 | LSI->LocalPacks.push_back(Param); |
1645 | |
1646 | // If the template template parameter has a name, then link the identifier |
1647 | // into the scope and lookup mechanisms. |
1648 | if (Name) { |
1649 | maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name); |
1650 | |
1651 | S->AddDecl(Param); |
1652 | IdResolver.AddDecl(Param); |
1653 | } |
1654 | |
1655 | if (Params->size() == 0) { |
1656 | Diag(Param->getLocation(), diag::err_template_template_parm_no_parms) |
1657 | << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc()); |
1658 | Param->setInvalidDecl(); |
1659 | } |
1660 | |
1661 | // C++0x [temp.param]p9: |
1662 | // A default template-argument may be specified for any kind of |
1663 | // template-parameter that is not a template parameter pack. |
1664 | if (IsParameterPack && !Default.isInvalid()) { |
1665 | Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
1666 | Default = ParsedTemplateArgument(); |
1667 | } |
1668 | |
1669 | if (!Default.isInvalid()) { |
1670 | // Check only that we have a template template argument. We don't want to |
1671 | // try to check well-formedness now, because our template template parameter |
1672 | // might have dependent types in its template parameters, which we wouldn't |
1673 | // be able to match now. |
1674 | // |
1675 | // If none of the template template parameter's template arguments mention |
1676 | // other template parameters, we could actually perform more checking here. |
1677 | // However, it isn't worth doing. |
1678 | TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); |
1679 | if (DefaultArg.getArgument().getAsTemplate().isNull()) { |
1680 | Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template) |
1681 | << DefaultArg.getSourceRange(); |
1682 | return Param; |
1683 | } |
1684 | |
1685 | // Check for unexpanded parameter packs. |
1686 | if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(), |
1687 | DefaultArg.getArgument().getAsTemplate(), |
1688 | UPPC_DefaultArgument)) |
1689 | return Param; |
1690 | |
1691 | Param->setDefaultArgument(Context, DefaultArg); |
1692 | } |
1693 | |
1694 | return Param; |
1695 | } |
1696 | |
1697 | namespace { |
1698 | class ConstraintRefersToContainingTemplateChecker |
1699 | : public TreeTransform<ConstraintRefersToContainingTemplateChecker> { |
1700 | bool Result = false; |
1701 | const FunctionDecl *Friend = nullptr; |
1702 | unsigned TemplateDepth = 0; |
1703 | |
1704 | // Check a record-decl that we've seen to see if it is a lexical parent of the |
1705 | // Friend, likely because it was referred to without its template arguments. |
1706 | void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) { |
1707 | CheckingRD = CheckingRD->getMostRecentDecl(); |
1708 | |
1709 | for (const DeclContext *DC = Friend->getLexicalDeclContext(); |
1710 | DC && !DC->isFileContext(); DC = DC->getParent()) |
1711 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) |
1712 | if (CheckingRD == RD->getMostRecentDecl()) |
1713 | Result = true; |
1714 | } |
1715 | |
1716 | void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { |
1717 | assert(D->getDepth() <= TemplateDepth &&(static_cast <bool> (D->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("D->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1719, __extension__ __PRETTY_FUNCTION__ )) |
1718 | "Nothing should reference a value below the actual template depth, "(static_cast <bool> (D->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("D->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1719, __extension__ __PRETTY_FUNCTION__ )) |
1719 | "depth is likely wrong")(static_cast <bool> (D->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("D->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1719, __extension__ __PRETTY_FUNCTION__ )); |
1720 | if (D->getDepth() != TemplateDepth) |
1721 | Result = true; |
1722 | |
1723 | // Necessary because the type of the NTTP might be what refers to the parent |
1724 | // constriant. |
1725 | TransformType(D->getType()); |
1726 | } |
1727 | |
1728 | public: |
1729 | using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>; |
1730 | |
1731 | ConstraintRefersToContainingTemplateChecker(Sema &SemaRef, |
1732 | const FunctionDecl *Friend, |
1733 | unsigned TemplateDepth) |
1734 | : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {} |
1735 | bool getResult() const { return Result; } |
1736 | |
1737 | // This should be the only template parm type that we have to deal with. |
1738 | // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and |
1739 | // FunctionParmPackExpr are all partially substituted, which cannot happen |
1740 | // with concepts at this point in translation. |
1741 | using inherited::TransformTemplateTypeParmType; |
1742 | QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, |
1743 | TemplateTypeParmTypeLoc TL, bool) { |
1744 | assert(TL.getDecl()->getDepth() <= TemplateDepth &&(static_cast <bool> (TL.getDecl()->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("TL.getDecl()->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1746, __extension__ __PRETTY_FUNCTION__ )) |
1745 | "Nothing should reference a value below the actual template depth, "(static_cast <bool> (TL.getDecl()->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("TL.getDecl()->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1746, __extension__ __PRETTY_FUNCTION__ )) |
1746 | "depth is likely wrong")(static_cast <bool> (TL.getDecl()->getDepth() <= TemplateDepth && "Nothing should reference a value below the actual template depth, " "depth is likely wrong") ? void (0) : __assert_fail ("TL.getDecl()->getDepth() <= TemplateDepth && \"Nothing should reference a value below the actual template depth, \" \"depth is likely wrong\"" , "clang/lib/Sema/SemaTemplate.cpp", 1746, __extension__ __PRETTY_FUNCTION__ )); |
1747 | if (TL.getDecl()->getDepth() != TemplateDepth) |
1748 | Result = true; |
1749 | return inherited::TransformTemplateTypeParmType( |
1750 | TLB, TL, |
1751 | /*SuppressObjCLifetime=*/false); |
1752 | } |
1753 | |
1754 | Decl *TransformDecl(SourceLocation Loc, Decl *D) { |
1755 | if (!D) |
1756 | return D; |
1757 | // FIXME : This is possibly an incomplete list, but it is unclear what other |
1758 | // Decl kinds could be used to refer to the template parameters. This is a |
1759 | // best guess so far based on examples currently available, but the |
1760 | // unreachable should catch future instances/cases. |
1761 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) |
1762 | TransformType(TD->getUnderlyingType()); |
1763 | else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D)) |
1764 | CheckNonTypeTemplateParmDecl(NTTPD); |
1765 | else if (auto *VD = dyn_cast<ValueDecl>(D)) |
1766 | TransformType(VD->getType()); |
1767 | else if (auto *TD = dyn_cast<TemplateDecl>(D)) |
1768 | TransformTemplateParameterList(TD->getTemplateParameters()); |
1769 | else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) |
1770 | CheckIfContainingRecord(RD); |
1771 | else if (isa<NamedDecl>(D)) { |
1772 | // No direct types to visit here I believe. |
1773 | } else |
1774 | llvm_unreachable("Don't know how to handle this declaration type yet")::llvm::llvm_unreachable_internal("Don't know how to handle this declaration type yet" , "clang/lib/Sema/SemaTemplate.cpp", 1774); |
1775 | return D; |
1776 | } |
1777 | }; |
1778 | } // namespace |
1779 | |
1780 | bool Sema::ConstraintExpressionDependsOnEnclosingTemplate( |
1781 | const FunctionDecl *Friend, unsigned TemplateDepth, |
1782 | const Expr *Constraint) { |
1783 | assert(Friend->getFriendObjectKind() && "Only works on a friend")(static_cast <bool> (Friend->getFriendObjectKind() && "Only works on a friend") ? void (0) : __assert_fail ("Friend->getFriendObjectKind() && \"Only works on a friend\"" , "clang/lib/Sema/SemaTemplate.cpp", 1783, __extension__ __PRETTY_FUNCTION__ )); |
1784 | ConstraintRefersToContainingTemplateChecker Checker(*this, Friend, |
1785 | TemplateDepth); |
1786 | Checker.TransformExpr(const_cast<Expr *>(Constraint)); |
1787 | return Checker.getResult(); |
1788 | } |
1789 | |
1790 | /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally |
1791 | /// constrained by RequiresClause, that contains the template parameters in |
1792 | /// Params. |
1793 | TemplateParameterList * |
1794 | Sema::ActOnTemplateParameterList(unsigned Depth, |
1795 | SourceLocation ExportLoc, |
1796 | SourceLocation TemplateLoc, |
1797 | SourceLocation LAngleLoc, |
1798 | ArrayRef<NamedDecl *> Params, |
1799 | SourceLocation RAngleLoc, |
1800 | Expr *RequiresClause) { |
1801 | if (ExportLoc.isValid()) |
1802 | Diag(ExportLoc, diag::warn_template_export_unsupported); |
1803 | |
1804 | for (NamedDecl *P : Params) |
1805 | warnOnReservedIdentifier(P); |
1806 | |
1807 | return TemplateParameterList::Create( |
1808 | Context, TemplateLoc, LAngleLoc, |
1809 | llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause); |
1810 | } |
1811 | |
1812 | static void SetNestedNameSpecifier(Sema &S, TagDecl *T, |
1813 | const CXXScopeSpec &SS) { |
1814 | if (SS.isSet()) |
1815 | T->setQualifierInfo(SS.getWithLocInContext(S.Context)); |
1816 | } |
1817 | |
1818 | DeclResult Sema::CheckClassTemplate( |
1819 | Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, |
1820 | CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, |
1821 | const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, |
1822 | AccessSpecifier AS, SourceLocation ModulePrivateLoc, |
1823 | SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, |
1824 | TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) { |
1825 | assert(TemplateParams && TemplateParams->size() > 0 &&(static_cast <bool> (TemplateParams && TemplateParams ->size() > 0 && "No template parameters") ? void (0) : __assert_fail ("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\"" , "clang/lib/Sema/SemaTemplate.cpp", 1826, __extension__ __PRETTY_FUNCTION__ )) |
1826 | "No template parameters")(static_cast <bool> (TemplateParams && TemplateParams ->size() > 0 && "No template parameters") ? void (0) : __assert_fail ("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\"" , "clang/lib/Sema/SemaTemplate.cpp", 1826, __extension__ __PRETTY_FUNCTION__ )); |
1827 | assert(TUK != TUK_Reference && "Can only declare or define class templates")(static_cast <bool> (TUK != TUK_Reference && "Can only declare or define class templates" ) ? void (0) : __assert_fail ("TUK != TUK_Reference && \"Can only declare or define class templates\"" , "clang/lib/Sema/SemaTemplate.cpp", 1827, __extension__ __PRETTY_FUNCTION__ )); |
1828 | bool Invalid = false; |
1829 | |
1830 | // Check that we can declare a template here. |
1831 | if (CheckTemplateDeclScope(S, TemplateParams)) |
1832 | return true; |
1833 | |
1834 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); |
1835 | assert(Kind != TTK_Enum && "can't build template of enumerated type")(static_cast <bool> (Kind != TTK_Enum && "can't build template of enumerated type" ) ? void (0) : __assert_fail ("Kind != TTK_Enum && \"can't build template of enumerated type\"" , "clang/lib/Sema/SemaTemplate.cpp", 1835, __extension__ __PRETTY_FUNCTION__ )); |
1836 | |
1837 | // There is no such thing as an unnamed class template. |
1838 | if (!Name) { |
1839 | Diag(KWLoc, diag::err_template_unnamed_class); |
1840 | return true; |
1841 | } |
1842 | |
1843 | // Find any previous declaration with this name. For a friend with no |
1844 | // scope explicitly specified, we only look for tag declarations (per |
1845 | // C++11 [basic.lookup.elab]p2). |
1846 | DeclContext *SemanticContext; |
1847 | LookupResult Previous(*this, Name, NameLoc, |
1848 | (SS.isEmpty() && TUK == TUK_Friend) |
1849 | ? LookupTagName : LookupOrdinaryName, |
1850 | forRedeclarationInCurContext()); |
1851 | if (SS.isNotEmpty() && !SS.isInvalid()) { |
1852 | SemanticContext = computeDeclContext(SS, true); |
1853 | if (!SemanticContext) { |
1854 | // FIXME: Horrible, horrible hack! We can't currently represent this |
1855 | // in the AST, and historically we have just ignored such friend |
1856 | // class templates, so don't complain here. |
1857 | Diag(NameLoc, TUK == TUK_Friend |
1858 | ? diag::warn_template_qualified_friend_ignored |
1859 | : diag::err_template_qualified_declarator_no_match) |
1860 | << SS.getScopeRep() << SS.getRange(); |
1861 | return TUK != TUK_Friend; |
1862 | } |
1863 | |
1864 | if (RequireCompleteDeclContext(SS, SemanticContext)) |
1865 | return true; |
1866 | |
1867 | // If we're adding a template to a dependent context, we may need to |
1868 | // rebuilding some of the types used within the template parameter list, |
1869 | // now that we know what the current instantiation is. |
1870 | if (SemanticContext->isDependentContext()) { |
1871 | ContextRAII SavedContext(*this, SemanticContext); |
1872 | if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) |
1873 | Invalid = true; |
1874 | } else if (TUK != TUK_Friend && TUK != TUK_Reference) |
1875 | diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false); |
1876 | |
1877 | LookupQualifiedName(Previous, SemanticContext); |
1878 | } else { |
1879 | SemanticContext = CurContext; |
1880 | |
1881 | // C++14 [class.mem]p14: |
1882 | // If T is the name of a class, then each of the following shall have a |
1883 | // name different from T: |
1884 | // -- every member template of class T |
1885 | if (TUK != TUK_Friend && |
1886 | DiagnoseClassNameShadow(SemanticContext, |
1887 | DeclarationNameInfo(Name, NameLoc))) |
1888 | return true; |
1889 | |
1890 | LookupName(Previous, S); |
1891 | } |
1892 | |
1893 | if (Previous.isAmbiguous()) |
1894 | return true; |
1895 | |
1896 | NamedDecl *PrevDecl = nullptr; |
1897 | if (Previous.begin() != Previous.end()) |
1898 | PrevDecl = (*Previous.begin())->getUnderlyingDecl(); |
1899 | |
1900 | if (PrevDecl && PrevDecl->isTemplateParameter()) { |
1901 | // Maybe we will complain about the shadowed template parameter. |
1902 | DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); |
1903 | // Just pretend that we didn't see the previous declaration. |
1904 | PrevDecl = nullptr; |
1905 | } |
1906 | |
1907 | // If there is a previous declaration with the same name, check |
1908 | // whether this is a valid redeclaration. |
1909 | ClassTemplateDecl *PrevClassTemplate = |
1910 | dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); |
1911 | |
1912 | // We may have found the injected-class-name of a class template, |
1913 | // class template partial specialization, or class template specialization. |
1914 | // In these cases, grab the template that is being defined or specialized. |
1915 | if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && |
1916 | cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { |
1917 | PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); |
1918 | PrevClassTemplate |
1919 | = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); |
1920 | if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { |
1921 | PrevClassTemplate |
1922 | = cast<ClassTemplateSpecializationDecl>(PrevDecl) |
1923 | ->getSpecializedTemplate(); |
1924 | } |
1925 | } |
1926 | |
1927 | if (TUK == TUK_Friend) { |
1928 | // C++ [namespace.memdef]p3: |
1929 | // [...] When looking for a prior declaration of a class or a function |
1930 | // declared as a friend, and when the name of the friend class or |
1931 | // function is neither a qualified name nor a template-id, scopes outside |
1932 | // the innermost enclosing namespace scope are not considered. |
1933 | if (!SS.isSet()) { |
1934 | DeclContext *OutermostContext = CurContext; |
1935 | while (!OutermostContext->isFileContext()) |
1936 | OutermostContext = OutermostContext->getLookupParent(); |
1937 | |
1938 | if (PrevDecl && |
1939 | (OutermostContext->Equals(PrevDecl->getDeclContext()) || |
1940 | OutermostContext->Encloses(PrevDecl->getDeclContext()))) { |
1941 | SemanticContext = PrevDecl->getDeclContext(); |
1942 | } else { |
1943 | // Declarations in outer scopes don't matter. However, the outermost |
1944 | // context we computed is the semantic context for our new |
1945 | // declaration. |
1946 | PrevDecl = PrevClassTemplate = nullptr; |
1947 | SemanticContext = OutermostContext; |
1948 | |
1949 | // Check that the chosen semantic context doesn't already contain a |
1950 | // declaration of this name as a non-tag type. |
1951 | Previous.clear(LookupOrdinaryName); |
1952 | DeclContext *LookupContext = SemanticContext; |
1953 | while (LookupContext->isTransparentContext()) |
1954 | LookupContext = LookupContext->getLookupParent(); |
1955 | LookupQualifiedName(Previous, LookupContext); |
1956 | |
1957 | if (Previous.isAmbiguous()) |
1958 | return true; |
1959 | |
1960 | if (Previous.begin() != Previous.end()) |
1961 | PrevDecl = (*Previous.begin())->getUnderlyingDecl(); |
1962 | } |
1963 | } |
1964 | } else if (PrevDecl && |
1965 | !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext, |
1966 | S, SS.isValid())) |
1967 | PrevDecl = PrevClassTemplate = nullptr; |
1968 | |
1969 | if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>( |
1970 | PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) { |
1971 | if (SS.isEmpty() && |
1972 | !(PrevClassTemplate && |
1973 | PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals( |
1974 | SemanticContext->getRedeclContext()))) { |
1975 | Diag(KWLoc, diag::err_using_decl_conflict_reverse); |
1976 | Diag(Shadow->getTargetDecl()->getLocation(), |
1977 | diag::note_using_decl_target); |
1978 | Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0; |
1979 | // Recover by ignoring the old declaration. |
1980 | PrevDecl = PrevClassTemplate = nullptr; |
1981 | } |
1982 | } |
1983 | |
1984 | if (PrevClassTemplate) { |
1985 | // Ensure that the template parameter lists are compatible. Skip this check |
1986 | // for a friend in a dependent context: the template parameter list itself |
1987 | // could be dependent. |
1988 | if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && |
1989 | !TemplateParameterListsAreEqual(TemplateParams, |
1990 | PrevClassTemplate->getTemplateParameters(), |
1991 | /*Complain=*/true, |
1992 | TPL_TemplateMatch)) |
1993 | return true; |
1994 | |
1995 | // C++ [temp.class]p4: |
1996 | // In a redeclaration, partial specialization, explicit |
1997 | // specialization or explicit instantiation of a class template, |
1998 | // the class-key shall agree in kind with the original class |
1999 | // template declaration (7.1.5.3). |
2000 | RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); |
2001 | if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, |
2002 | TUK == TUK_Definition, KWLoc, Name)) { |
2003 | Diag(KWLoc, diag::err_use_with_wrong_tag) |
2004 | << Name |
2005 | << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); |
2006 | Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); |
2007 | Kind = PrevRecordDecl->getTagKind(); |
2008 | } |
2009 | |
2010 | // Check for redefinition of this class template. |
2011 | if (TUK == TUK_Definition) { |
2012 | if (TagDecl *Def = PrevRecordDecl->getDefinition()) { |
2013 | // If we have a prior definition that is not visible, treat this as |
2014 | // simply making that previous definition visible. |
2015 | NamedDecl *Hidden = nullptr; |
2016 | if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { |
2017 | SkipBody->ShouldSkip = true; |
2018 | SkipBody->Previous = Def; |
2019 | auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate(); |
2020 | assert(Tmpl && "original definition of a class template is not a "(static_cast <bool> (Tmpl && "original definition of a class template is not a " "class template?") ? void (0) : __assert_fail ("Tmpl && \"original definition of a class template is not a \" \"class template?\"" , "clang/lib/Sema/SemaTemplate.cpp", 2021, __extension__ __PRETTY_FUNCTION__ )) |
2021 | "class template?")(static_cast <bool> (Tmpl && "original definition of a class template is not a " "class template?") ? void (0) : __assert_fail ("Tmpl && \"original definition of a class template is not a \" \"class template?\"" , "clang/lib/Sema/SemaTemplate.cpp", 2021, __extension__ __PRETTY_FUNCTION__ )); |
2022 | makeMergedDefinitionVisible(Hidden); |
2023 | makeMergedDefinitionVisible(Tmpl); |
2024 | } else { |
2025 | Diag(NameLoc, diag::err_redefinition) << Name; |
2026 | Diag(Def->getLocation(), diag::note_previous_definition); |
2027 | // FIXME: Would it make sense to try to "forget" the previous |
2028 | // definition, as part of error recovery? |
2029 | return true; |
2030 | } |
2031 | } |
2032 | } |
2033 | } else if (PrevDecl) { |
2034 | // C++ [temp]p5: |
2035 | // A class template shall not have the same name as any other |
2036 | // template, class, function, object, enumeration, enumerator, |
2037 | // namespace, or type in the same scope (3.3), except as specified |
2038 | // in (14.5.4). |
2039 | Diag(NameLoc, diag::err_redefinition_different_kind) << Name; |
2040 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); |
2041 | return true; |
2042 | } |
2043 | |
2044 | // Check the template parameter list of this declaration, possibly |
2045 | // merging in the template parameter list from the previous class |
2046 | // template declaration. Skip this check for a friend in a dependent |
2047 | // context, because the template parameter list might be dependent. |
2048 | if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && |
2049 | CheckTemplateParameterList( |
2050 | TemplateParams, |
2051 | PrevClassTemplate |
2052 | ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters() |
2053 | : nullptr, |
2054 | (SS.isSet() && SemanticContext && SemanticContext->isRecord() && |
2055 | SemanticContext->isDependentContext()) |
2056 | ? TPC_ClassTemplateMember |
2057 | : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate, |
2058 | SkipBody)) |
2059 | Invalid = true; |
2060 | |
2061 | if (SS.isSet()) { |
2062 | // If the name of the template was qualified, we must be defining the |
2063 | // template out-of-line. |
2064 | if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) { |
2065 | Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match |
2066 | : diag::err_member_decl_does_not_match) |
2067 | << Name << SemanticContext << /*IsDefinition*/true << SS.getRange(); |
2068 | Invalid = true; |
2069 | } |
2070 | } |
2071 | |
2072 | // If this is a templated friend in a dependent context we should not put it |
2073 | // on the redecl chain. In some cases, the templated friend can be the most |
2074 | // recent declaration tricking the template instantiator to make substitutions |
2075 | // there. |
2076 | // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious |
2077 | bool ShouldAddRedecl |
2078 | = !(TUK == TUK_Friend && CurContext->isDependentContext()); |
2079 | |
2080 | CXXRecordDecl *NewClass = |
2081 | CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name, |
2082 | PrevClassTemplate && ShouldAddRedecl ? |
2083 | PrevClassTemplate->getTemplatedDecl() : nullptr, |
2084 | /*DelayTypeCreation=*/true); |
2085 | SetNestedNameSpecifier(*this, NewClass, SS); |
2086 | if (NumOuterTemplateParamLists > 0) |
2087 | NewClass->setTemplateParameterListsInfo( |
2088 | Context, |
2089 | llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists)); |
2090 | |
2091 | // Add alignment attributes if necessary; these attributes are checked when |
2092 | // the ASTContext lays out the structure. |
2093 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { |
2094 | AddAlignmentAttributesForRecord(NewClass); |
2095 | AddMsStructLayoutForRecord(NewClass); |
2096 | } |
2097 | |
2098 | ClassTemplateDecl *NewTemplate |
2099 | = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, |
2100 | DeclarationName(Name), TemplateParams, |
2101 | NewClass); |
2102 | |
2103 | if (ShouldAddRedecl) |
2104 | NewTemplate->setPreviousDecl(PrevClassTemplate); |
2105 | |
2106 | NewClass->setDescribedClassTemplate(NewTemplate); |
2107 | |
2108 | if (ModulePrivateLoc.isValid()) |
2109 | NewTemplate->setModulePrivate(); |
2110 | |
2111 | // Build the type for the class template declaration now. |
2112 | QualType T = NewTemplate->getInjectedClassNameSpecialization(); |
2113 | T = Context.getInjectedClassNameType(NewClass, T); |
2114 | assert(T->isDependentType() && "Class template type is not dependent?")(static_cast <bool> (T->isDependentType() && "Class template type is not dependent?") ? void (0) : __assert_fail ("T->isDependentType() && \"Class template type is not dependent?\"" , "clang/lib/Sema/SemaTemplate.cpp", 2114, __extension__ __PRETTY_FUNCTION__ )); |
2115 | (void)T; |
2116 | |
2117 | // If we are providing an explicit specialization of a member that is a |
2118 | // class template, make a note of that. |
2119 | if (PrevClassTemplate && |
2120 | PrevClassTemplate->getInstantiatedFromMemberTemplate()) |
2121 | PrevClassTemplate->setMemberSpecialization(); |
2122 | |
2123 | // Set the access specifier. |
2124 | if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord()) |
2125 | SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); |
2126 | |
2127 | // Set the lexical context of these templates |
2128 | NewClass->setLexicalDeclContext(CurContext); |
2129 | NewTemplate->setLexicalDeclContext(CurContext); |
2130 | |
2131 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) |
2132 | NewClass->startDefinition(); |
2133 | |
2134 | ProcessDeclAttributeList(S, NewClass, Attr); |
2135 | |
2136 | if (PrevClassTemplate) |
2137 | mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl()); |
2138 | |
2139 | AddPushedVisibilityAttribute(NewClass); |
2140 | inferGslOwnerPointerAttribute(NewClass); |
2141 | |
2142 | if (TUK != TUK_Friend) { |
2143 | // Per C++ [basic.scope.temp]p2, skip the template parameter scopes. |
2144 | Scope *Outer = S; |
2145 | while ((Outer->getFlags() & Scope::TemplateParamScope) != 0) |
2146 | Outer = Outer->getParent(); |
2147 | PushOnScopeChains(NewTemplate, Outer); |
2148 | } else { |
2149 | if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { |
2150 | NewTemplate->setAccess(PrevClassTemplate->getAccess()); |
2151 | NewClass->setAccess(PrevClassTemplate->getAccess()); |
2152 | } |
2153 | |
2154 | NewTemplate->setObjectOfFriendDecl(); |
2155 | |
2156 | // Friend templates are visible in fairly strange ways. |
2157 | if (!CurContext->isDependentContext()) { |
2158 | DeclContext *DC = SemanticContext->getRedeclContext(); |
2159 | DC->makeDeclVisibleInContext(NewTemplate); |
2160 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) |
2161 | PushOnScopeChains(NewTemplate, EnclosingScope, |
2162 | /* AddToContext = */ false); |
2163 | } |
2164 | |
2165 | FriendDecl *Friend = FriendDecl::Create( |
2166 | Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc); |
2167 | Friend->setAccess(AS_public); |
2168 | CurContext->addDecl(Friend); |
2169 | } |
2170 | |
2171 | if (PrevClassTemplate) |
2172 | CheckRedeclarationInModule(NewTemplate, PrevClassTemplate); |
2173 | |
2174 | if (Invalid) { |
2175 | NewTemplate->setInvalidDecl(); |
2176 | NewClass->setInvalidDecl(); |
2177 | } |
2178 | |
2179 | ActOnDocumentableDecl(NewTemplate); |
2180 | |
2181 | if (SkipBody && SkipBody->ShouldSkip) |
2182 | return SkipBody->Previous; |
2183 | |
2184 | return NewTemplate; |
2185 | } |
2186 | |
2187 | namespace { |
2188 | /// Tree transform to "extract" a transformed type from a class template's |
2189 | /// constructor to a deduction guide. |
2190 | class ExtractTypeForDeductionGuide |
2191 | : public TreeTransform<ExtractTypeForDeductionGuide> { |
2192 | llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs; |
2193 | |
2194 | public: |
2195 | typedef TreeTransform<ExtractTypeForDeductionGuide> Base; |
2196 | ExtractTypeForDeductionGuide( |
2197 | Sema &SemaRef, |
2198 | llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) |
2199 | : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {} |
2200 | |
2201 | TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } |
2202 | |
2203 | QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { |
2204 | ASTContext &Context = SemaRef.getASTContext(); |
2205 | TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl(); |
2206 | TypedefNameDecl *Decl = OrigDecl; |
2207 | // Transform the underlying type of the typedef and clone the Decl only if |
2208 | // the typedef has a dependent context. |
2209 | if (OrigDecl->getDeclContext()->isDependentContext()) { |
2210 | TypeLocBuilder InnerTLB; |
2211 | QualType Transformed = |
2212 | TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc()); |
2213 | TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed); |
2214 | if (isa<TypeAliasDecl>(OrigDecl)) |
2215 | Decl = TypeAliasDecl::Create( |
2216 | Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(), |
2217 | OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI); |
2218 | else { |
2219 | assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef")(static_cast <bool> (isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef") ? void (0) : __assert_fail ("isa<TypedefDecl>(OrigDecl) && \"Not a Type alias or typedef\"" , "clang/lib/Sema/SemaTemplate.cpp", 2219, __extension__ __PRETTY_FUNCTION__ )); |
2220 | Decl = TypedefDecl::Create( |
2221 | Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(), |
2222 | OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI); |
2223 | } |
2224 | MaterializedTypedefs.push_back(Decl); |
2225 | } |
2226 | |
2227 | QualType TDTy = Context.getTypedefType(Decl); |
2228 | TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy); |
2229 | TypedefTL.setNameLoc(TL.getNameLoc()); |
2230 | |
2231 | return TDTy; |
2232 | } |
2233 | }; |
2234 | |
2235 | /// Transform to convert portions of a constructor declaration into the |
2236 | /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1. |
2237 | struct ConvertConstructorToDeductionGuideTransform { |
2238 | ConvertConstructorToDeductionGuideTransform(Sema &S, |
2239 | ClassTemplateDecl *Template) |
2240 | : SemaRef(S), Template(Template) {} |
2241 | |
2242 | Sema &SemaRef; |
2243 | ClassTemplateDecl *Template; |
2244 | |
2245 | DeclContext *DC = Template->getDeclContext(); |
2246 | CXXRecordDecl *Primary = Template->getTemplatedDecl(); |
2247 | DeclarationName DeductionGuideName = |
2248 | SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template); |
2249 | |
2250 | QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary); |
2251 | |
2252 | // Index adjustment to apply to convert depth-1 template parameters into |
2253 | // depth-0 template parameters. |
2254 | unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size(); |
2255 | |
2256 | /// Transform a constructor declaration into a deduction guide. |
2257 | NamedDecl *transformConstructor(FunctionTemplateDecl *FTD, |
2258 | CXXConstructorDecl *CD) { |
2259 | SmallVector<TemplateArgument, 16> SubstArgs; |
2260 | |
2261 | LocalInstantiationScope Scope(SemaRef); |
2262 | |
2263 | // C++ [over.match.class.deduct]p1: |
2264 | // -- For each constructor of the class template designated by the |
2265 | // template-name, a function template with the following properties: |
2266 | |
2267 | // -- The template parameters are the template parameters of the class |
2268 | // template followed by the template parameters (including default |
2269 | // template arguments) of the constructor, if any. |
2270 | TemplateParameterList *TemplateParams = Template->getTemplateParameters(); |
2271 | if (FTD) { |
2272 | TemplateParameterList *InnerParams = FTD->getTemplateParameters(); |
2273 | SmallVector<NamedDecl *, 16> AllParams; |
2274 | AllParams.reserve(TemplateParams->size() + InnerParams->size()); |
2275 | AllParams.insert(AllParams.begin(), |
2276 | TemplateParams->begin(), TemplateParams->end()); |
2277 | SubstArgs.reserve(InnerParams->size()); |
2278 | |
2279 | // Later template parameters could refer to earlier ones, so build up |
2280 | // a list of substituted template arguments as we go. |
2281 | for (NamedDecl *Param : *InnerParams) { |
2282 | MultiLevelTemplateArgumentList Args; |
2283 | Args.setKind(TemplateSubstitutionKind::Rewrite); |
2284 | Args.addOuterTemplateArguments(SubstArgs); |
2285 | Args.addOuterRetainedLevel(); |
2286 | NamedDecl *NewParam = transformTemplateParameter(Param, Args); |
2287 | if (!NewParam) |
2288 | return nullptr; |
2289 | AllParams.push_back(NewParam); |
2290 | SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument( |
2291 | SemaRef.Context.getInjectedTemplateArg(NewParam))); |
2292 | } |
2293 | |
2294 | // Substitute new template parameters into requires-clause if present. |
2295 | Expr *RequiresClause = nullptr; |
2296 | if (Expr *InnerRC = InnerParams->getRequiresClause()) { |
2297 | MultiLevelTemplateArgumentList Args; |
2298 | Args.setKind(TemplateSubstitutionKind::Rewrite); |
2299 | Args.addOuterTemplateArguments(SubstArgs); |
2300 | Args.addOuterRetainedLevel(); |
2301 | ExprResult E = SemaRef.SubstExpr(InnerRC, Args); |
2302 | if (E.isInvalid()) |
2303 | return nullptr; |
2304 | RequiresClause = E.getAs<Expr>(); |
2305 | } |
2306 | |
2307 | TemplateParams = TemplateParameterList::Create( |
2308 | SemaRef.Context, InnerParams->getTemplateLoc(), |
2309 | InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(), |
2310 | RequiresClause); |
2311 | } |
2312 | |
2313 | // If we built a new template-parameter-list, track that we need to |
2314 | // substitute references to the old parameters into references to the |
2315 | // new ones. |
2316 | MultiLevelTemplateArgumentList Args; |
2317 | Args.setKind(TemplateSubstitutionKind::Rewrite); |
2318 | if (FTD) { |
2319 | Args.addOuterTemplateArguments(SubstArgs); |
2320 | Args.addOuterRetainedLevel(); |
2321 | } |
2322 | |
2323 | FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc() |
2324 | .getAsAdjusted<FunctionProtoTypeLoc>(); |
2325 | assert(FPTL && "no prototype for constructor declaration")(static_cast <bool> (FPTL && "no prototype for constructor declaration" ) ? void (0) : __assert_fail ("FPTL && \"no prototype for constructor declaration\"" , "clang/lib/Sema/SemaTemplate.cpp", 2325, __extension__ __PRETTY_FUNCTION__ )); |
2326 | |
2327 | // Transform the type of the function, adjusting the return type and |
2328 | // replacing references to the old parameters with references to the |
2329 | // new ones. |
2330 | TypeLocBuilder TLB; |
2331 | SmallVector<ParmVarDecl*, 8> Params; |
2332 | SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs; |
2333 | QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args, |
2334 | MaterializedTypedefs); |
2335 | if (NewType.isNull()) |
2336 | return nullptr; |
2337 | TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType); |
2338 | |
2339 | return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(), |
2340 | NewTInfo, CD->getBeginLoc(), CD->getLocation(), |
2341 | CD->getEndLoc(), MaterializedTypedefs); |
2342 | } |
2343 | |
2344 | /// Build a deduction guide with the specified parameter types. |
2345 | NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) { |
2346 | SourceLocation Loc = Template->getLocation(); |
2347 | |
2348 | // Build the requested type. |
2349 | FunctionProtoType::ExtProtoInfo EPI; |
2350 | EPI.HasTrailingReturn = true; |
2351 | QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc, |
2352 | DeductionGuideName, EPI); |
2353 | TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc); |
2354 | |
2355 | FunctionProtoTypeLoc FPTL = |
2356 | TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>(); |
2357 | |
2358 | // Build the parameters, needed during deduction / substitution. |
2359 | SmallVector<ParmVarDecl*, 4> Params; |
2360 | for (auto T : ParamTypes) { |
2361 | ParmVarDecl *NewParam = ParmVarDecl::Create( |
2362 | SemaRef.Context, DC, Loc, Loc, nullptr, T, |
2363 | SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr); |
2364 | NewParam->setScopeInfo(0, Params.size()); |
2365 | FPTL.setParam(Params.size(), NewParam); |
2366 | Params.push_back(NewParam); |
2367 | } |
2368 | |
2369 | return buildDeductionGuide(Template->getTemplateParameters(), nullptr, |
2370 | ExplicitSpecifier(), TSI, Loc, Loc, Loc); |
2371 | } |
2372 | |
2373 | private: |
2374 | /// Transform a constructor template parameter into a deduction guide template |
2375 | /// parameter, rebuilding any internal references to earlier parameters and |
2376 | /// renumbering as we go. |
2377 | NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam, |
2378 | MultiLevelTemplateArgumentList &Args) { |
2379 | if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) { |
2380 | // TemplateTypeParmDecl's index cannot be changed after creation, so |
2381 | // substitute it directly. |
2382 | auto *NewTTP = TemplateTypeParmDecl::Create( |
2383 | SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), |
2384 | /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(), |
2385 | TTP->getIdentifier(), TTP->wasDeclaredWithTypename(), |
2386 | TTP->isParameterPack(), TTP->hasTypeConstraint(), |
2387 | TTP->isExpandedParameterPack() |
2388 | ? std::optional<unsigned>(TTP->getNumExpansionParameters()) |
2389 | : std::nullopt); |
2390 | if (const auto *TC = TTP->getTypeConstraint()) |
2391 | SemaRef.SubstTypeConstraint(NewTTP, TC, Args, |
2392 | /*EvaluateConstraint*/ true); |
2393 | if (TTP->hasDefaultArgument()) { |
2394 | TypeSourceInfo *InstantiatedDefaultArg = |
2395 | SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args, |
2396 | TTP->getDefaultArgumentLoc(), TTP->getDeclName()); |
2397 | if (InstantiatedDefaultArg) |
2398 | NewTTP->setDefaultArgument(InstantiatedDefaultArg); |
2399 | } |
2400 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam, |
2401 | NewTTP); |
2402 | return NewTTP; |
2403 | } |
2404 | |
2405 | if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam)) |
2406 | return transformTemplateParameterImpl(TTP, Args); |
2407 | |
2408 | return transformTemplateParameterImpl( |
2409 | cast<NonTypeTemplateParmDecl>(TemplateParam), Args); |
2410 | } |
2411 | template<typename TemplateParmDecl> |
2412 | TemplateParmDecl * |
2413 | transformTemplateParameterImpl(TemplateParmDecl *OldParam, |
2414 | MultiLevelTemplateArgumentList &Args) { |
2415 | // Ask the template instantiator to do the heavy lifting for us, then adjust |
2416 | // the index of the parameter once it's done. |
2417 | auto *NewParam = |
2418 | cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args)); |
2419 | assert(NewParam->getDepth() == 0 && "unexpected template param depth")(static_cast <bool> (NewParam->getDepth() == 0 && "unexpected template param depth") ? void (0) : __assert_fail ("NewParam->getDepth() == 0 && \"unexpected template param depth\"" , "clang/lib/Sema/SemaTemplate.cpp", 2419, __extension__ __PRETTY_FUNCTION__ )); |
2420 | NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment); |
2421 | return NewParam; |
2422 | } |
2423 | |
2424 | QualType transformFunctionProtoType( |
2425 | TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, |
2426 | SmallVectorImpl<ParmVarDecl *> &Params, |
2427 | MultiLevelTemplateArgumentList &Args, |
2428 | SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) { |
2429 | SmallVector<QualType, 4> ParamTypes; |
2430 | const FunctionProtoType *T = TL.getTypePtr(); |
2431 | |
2432 | // -- The types of the function parameters are those of the constructor. |
2433 | for (auto *OldParam : TL.getParams()) { |
2434 | ParmVarDecl *NewParam = |
2435 | transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs); |
2436 | if (!NewParam) |
2437 | return QualType(); |
2438 | ParamTypes.push_back(NewParam->getType()); |
2439 | Params.push_back(NewParam); |
2440 | } |
2441 | |
2442 | // -- The return type is the class template specialization designated by |
2443 | // the template-name and template arguments corresponding to the |
2444 | // template parameters obtained from the class template. |
2445 | // |
2446 | // We use the injected-class-name type of the primary template instead. |
2447 | // This has the convenient property that it is different from any type that |
2448 | // the user can write in a deduction-guide (because they cannot enter the |
2449 | // context of the template), so implicit deduction guides can never collide |
2450 | // with explicit ones. |
2451 | QualType ReturnType = DeducedType; |
2452 | TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation()); |
2453 | |
2454 | // Resolving a wording defect, we also inherit the variadicness of the |
2455 | // constructor. |
2456 | FunctionProtoType::ExtProtoInfo EPI; |
2457 | EPI.Variadic = T->isVariadic(); |
2458 | EPI.HasTrailingReturn = true; |
2459 | |
2460 | QualType Result = SemaRef.BuildFunctionType( |
2461 | ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI); |
2462 | if (Result.isNull()) |
2463 | return QualType(); |
2464 | |
2465 | FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result); |
2466 | NewTL.setLocalRangeBegin(TL.getLocalRangeBegin()); |
2467 | NewTL.setLParenLoc(TL.getLParenLoc()); |
2468 | NewTL.setRParenLoc(TL.getRParenLoc()); |
2469 | NewTL.setExceptionSpecRange(SourceRange()); |
2470 | NewTL.setLocalRangeEnd(TL.getLocalRangeEnd()); |
2471 | for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I) |
2472 | NewTL.setParam(I, Params[I]); |
2473 | |
2474 | return Result; |
2475 | } |
2476 | |
2477 | ParmVarDecl *transformFunctionTypeParam( |
2478 | ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args, |
2479 | llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) { |
2480 | TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo(); |
2481 | TypeSourceInfo *NewDI; |
2482 | if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) { |
2483 | // Expand out the one and only element in each inner pack. |
2484 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0); |
2485 | NewDI = |
2486 | SemaRef.SubstType(PackTL.getPatternLoc(), Args, |
2487 | OldParam->getLocation(), OldParam->getDeclName()); |
2488 | if (!NewDI) return nullptr; |
2489 | NewDI = |
2490 | SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(), |
2491 | PackTL.getTypePtr()->getNumExpansions()); |
2492 | } else |
2493 | NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(), |
2494 | OldParam->getDeclName()); |
2495 | if (!NewDI) |
2496 | return nullptr; |
2497 | |
2498 | // Extract the type. This (for instance) replaces references to typedef |
2499 | // members of the current instantiations with the definitions of those |
2500 | // typedefs, avoiding triggering instantiation of the deduced type during |
2501 | // deduction. |
2502 | NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs) |
2503 | .transform(NewDI); |
2504 | |
2505 | // Resolving a wording defect, we also inherit default arguments from the |
2506 | // constructor. |
2507 | ExprResult NewDefArg; |
2508 | if (OldParam->hasDefaultArg()) { |
2509 | // We don't care what the value is (we won't use it); just create a |
2510 | // placeholder to indicate there is a default argument. |
2511 | QualType ParamTy = NewDI->getType(); |
2512 | NewDefArg = new (SemaRef.Context) |
2513 | OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(), |
2514 | ParamTy.getNonLValueExprType(SemaRef.Context), |
2515 | ParamTy->isLValueReferenceType() ? VK_LValue |
2516 | : ParamTy->isRValueReferenceType() ? VK_XValue |
2517 | : VK_PRValue); |
2518 | } |
2519 | |
2520 | ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC, |
2521 | OldParam->getInnerLocStart(), |
2522 | OldParam->getLocation(), |
2523 | OldParam->getIdentifier(), |
2524 | NewDI->getType(), |
2525 | NewDI, |
2526 | OldParam->getStorageClass(), |
2527 | NewDefArg.get()); |
2528 | NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(), |
2529 | OldParam->getFunctionScopeIndex()); |
2530 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam); |
2531 | return NewParam; |
2532 | } |
2533 | |
2534 | FunctionTemplateDecl *buildDeductionGuide( |
2535 | TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor, |
2536 | ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart, |
2537 | SourceLocation Loc, SourceLocation LocEnd, |
2538 | llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) { |
2539 | DeclarationNameInfo Name(DeductionGuideName, Loc); |
2540 | ArrayRef<ParmVarDecl *> Params = |
2541 | TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(); |
2542 | |
2543 | // Build the implicit deduction guide template. |
2544 | auto *Guide = |
2545 | CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name, |
2546 | TInfo->getType(), TInfo, LocEnd, Ctor); |
2547 | Guide->setImplicit(); |
2548 | Guide->setParams(Params); |
2549 | |
2550 | for (auto *Param : Params) |
2551 | Param->setDeclContext(Guide); |
2552 | for (auto *TD : MaterializedTypedefs) |
2553 | TD->setDeclContext(Guide); |
2554 | |
2555 | auto *GuideTemplate = FunctionTemplateDecl::Create( |
2556 | SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide); |
2557 | GuideTemplate->setImplicit(); |
2558 | Guide->setDescribedFunctionTemplate(GuideTemplate); |
2559 | |
2560 | if (isa<CXXRecordDecl>(DC)) { |
2561 | Guide->setAccess(AS_public); |
2562 | GuideTemplate->setAccess(AS_public); |
2563 | } |
2564 | |
2565 | DC->addDecl(GuideTemplate); |
2566 | return GuideTemplate; |
2567 | } |
2568 | }; |
2569 | } |
2570 | |
2571 | void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template, |
2572 | SourceLocation Loc) { |
2573 | if (CXXRecordDecl *DefRecord = |
2574 | cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) { |
2575 | TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate(); |
2576 | Template = DescribedTemplate ? DescribedTemplate : Template; |
2577 | } |
2578 | |
2579 | DeclContext *DC = Template->getDeclContext(); |
2580 | if (DC->isDependentContext()) |
2581 | return; |
2582 | |
2583 | ConvertConstructorToDeductionGuideTransform Transform( |
2584 | *this, cast<ClassTemplateDecl>(Template)); |
2585 | if (!isCompleteType(Loc, Transform.DeducedType)) |
2586 | return; |
2587 | |
2588 | // Check whether we've already declared deduction guides for this template. |
2589 | // FIXME: Consider storing a flag on the template to indicate this. |
2590 | auto Existing = DC->lookup(Transform.DeductionGuideName); |
2591 | for (auto *D : Existing) |
2592 | if (D->isImplicit()) |
2593 | return; |
2594 | |
2595 | // In case we were expanding a pack when we attempted to declare deduction |
2596 | // guides, turn off pack expansion for everything we're about to do. |
2597 | ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); |
2598 | // Create a template instantiation record to track the "instantiation" of |
2599 | // constructors into deduction guides. |
2600 | // FIXME: Add a kind for this to give more meaningful diagnostics. But can |
2601 | // this substitution process actually fail? |
2602 | InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template); |
2603 | if (BuildingDeductionGuides.isInvalid()) |
2604 | return; |
2605 | |
2606 | // Convert declared constructors into deduction guide templates. |
2607 | // FIXME: Skip constructors for which deduction must necessarily fail (those |
2608 | // for which some class template parameter without a default argument never |
2609 | // appears in a deduced context). |
2610 | llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors; |
2611 | bool AddedAny = false; |
2612 | for (NamedDecl *D : LookupConstructors(Transform.Primary)) { |
2613 | D = D->getUnderlyingDecl(); |
2614 | if (D->isInvalidDecl() || D->isImplicit()) |
2615 | continue; |
2616 | |
2617 | D = cast<NamedDecl>(D->getCanonicalDecl()); |
2618 | |
2619 | // Within C++20 modules, we may have multiple same constructors in |
2620 | // multiple same RecordDecls. And it doesn't make sense to create |
2621 | // duplicated deduction guides for the duplicated constructors. |
2622 | if (ProcessedCtors.count(D)) |
2623 | continue; |
2624 | |
2625 | auto *FTD = dyn_cast<FunctionTemplateDecl>(D); |
2626 | auto *CD = |
2627 | dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D); |
2628 | // Class-scope explicit specializations (MS extension) do not result in |
2629 | // deduction guides. |
2630 | if (!CD || (!FTD && CD->isFunctionTemplateSpecialization())) |
2631 | continue; |
2632 | |
2633 | // Cannot make a deduction guide when unparsed arguments are present. |
2634 | if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) { |
2635 | return !P || P->hasUnparsedDefaultArg(); |
2636 | })) |
2637 | continue; |
2638 | |
2639 | ProcessedCtors.insert(D); |
2640 | Transform.transformConstructor(FTD, CD); |
2641 | AddedAny = true; |
2642 | } |
2643 | |
2644 | // C++17 [over.match.class.deduct] |
2645 | // -- If C is not defined or does not declare any constructors, an |
2646 | // additional function template derived as above from a hypothetical |
2647 | // constructor C(). |
2648 | if (!AddedAny) |
2649 | Transform.buildSimpleDeductionGuide(std::nullopt); |
2650 | |
2651 | // -- An additional function template derived as above from a hypothetical |
2652 | // constructor C(C), called the copy deduction candidate. |
2653 | cast<CXXDeductionGuideDecl>( |
2654 | cast<FunctionTemplateDecl>( |
2655 | Transform.buildSimpleDeductionGuide(Transform.DeducedType)) |
2656 | ->getTemplatedDecl()) |
2657 | ->setIsCopyDeductionCandidate(); |
2658 | } |
2659 | |
2660 | /// Diagnose the presence of a default template argument on a |
2661 | /// template parameter, which is ill-formed in certain contexts. |
2662 | /// |
2663 | /// \returns true if the default template argument should be dropped. |
2664 | static bool DiagnoseDefaultTemplateArgument(Sema &S, |
2665 | Sema::TemplateParamListContext TPC, |
2666 | SourceLocation ParamLoc, |
2667 | SourceRange DefArgRange) { |
2668 | switch (TPC) { |
2669 | case Sema::TPC_ClassTemplate: |
2670 | case Sema::TPC_VarTemplate: |
2671 | case Sema::TPC_TypeAliasTemplate: |
2672 | return false; |
2673 | |
2674 | case Sema::TPC_FunctionTemplate: |
2675 | case Sema::TPC_FriendFunctionTemplateDefinition: |
2676 | // C++ [temp.param]p9: |
2677 | // A default template-argument shall not be specified in a |
2678 | // function template declaration or a function template |
2679 | // definition [...] |
2680 | // If a friend function template declaration specifies a default |
2681 | // template-argument, that declaration shall be a definition and shall be |
2682 | // the only declaration of the function template in the translation unit. |
2683 | // (C++98/03 doesn't have this wording; see DR226). |
2684 | S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ? |
2685 | diag::warn_cxx98_compat_template_parameter_default_in_function_template |
2686 | : diag::ext_template_parameter_default_in_function_template) |
2687 | << DefArgRange; |
2688 | return false; |
2689 | |
2690 | case Sema::TPC_ClassTemplateMember: |
2691 | // C++0x [temp.param]p9: |
2692 | // A default template-argument shall not be specified in the |
2693 | // template-parameter-lists of the definition of a member of a |
2694 | // class template that appears outside of the member's class. |
2695 | S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) |
2696 | << DefArgRange; |
2697 | return true; |
2698 | |
2699 | case Sema::TPC_FriendClassTemplate: |
2700 | case Sema::TPC_FriendFunctionTemplate: |
2701 | // C++ [temp.param]p9: |
2702 | // A default template-argument shall not be specified in a |
2703 | // friend template declaration. |
2704 | S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) |
2705 | << DefArgRange; |
2706 | return true; |
2707 | |
2708 | // FIXME: C++0x [temp.param]p9 allows default template-arguments |
2709 | // for friend function templates if there is only a single |
2710 | // declaration (and it is a definition). Strange! |
2711 | } |
2712 | |
2713 | llvm_unreachable("Invalid TemplateParamListContext!")::llvm::llvm_unreachable_internal("Invalid TemplateParamListContext!" , "clang/lib/Sema/SemaTemplate.cpp", 2713); |
2714 | } |
2715 | |
2716 | /// Check for unexpanded parameter packs within the template parameters |
2717 | /// of a template template parameter, recursively. |
2718 | static bool DiagnoseUnexpandedParameterPacks(Sema &S, |
2719 | TemplateTemplateParmDecl *TTP) { |
2720 | // A template template parameter which is a parameter pack is also a pack |
2721 | // expansion. |
2722 | if (TTP->isParameterPack()) |
2723 | return false; |
2724 | |
2725 | TemplateParameterList *Params = TTP->getTemplateParameters(); |
2726 | for (unsigned I = 0, N = Params->size(); I != N; ++I) { |
2727 | NamedDecl *P = Params->getParam(I); |
2728 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) { |
2729 | if (!TTP->isParameterPack()) |
2730 | if (const TypeConstraint *TC = TTP->getTypeConstraint()) |
2731 | if (TC->hasExplicitTemplateArgs()) |
2732 | for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments()) |
2733 | if (S.DiagnoseUnexpandedParameterPack(ArgLoc, |
2734 | Sema::UPPC_TypeConstraint)) |
2735 | return true; |
2736 | continue; |
2737 | } |
2738 | |
2739 | if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { |
2740 | if (!NTTP->isParameterPack() && |
2741 | S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(), |
2742 | NTTP->getTypeSourceInfo(), |
2743 | Sema::UPPC_NonTypeTemplateParameterType)) |
2744 | return true; |
2745 | |
2746 | continue; |
2747 | } |
2748 | |
2749 | if (TemplateTemplateParmDecl *InnerTTP |
2750 | = dyn_cast<TemplateTemplateParmDecl>(P)) |
2751 | if (DiagnoseUnexpandedParameterPacks(S, InnerTTP)) |
2752 | return true; |
2753 | } |
2754 | |
2755 | return false; |
2756 | } |
2757 | |
2758 | /// Checks the validity of a template parameter list, possibly |
2759 | /// considering the template parameter list from a previous |
2760 | /// declaration. |
2761 | /// |
2762 | /// If an "old" template parameter list is provided, it must be |
2763 | /// equivalent (per TemplateParameterListsAreEqual) to the "new" |
2764 | /// template parameter list. |
2765 | /// |
2766 | /// \param NewParams Template parameter list for a new template |
2767 | /// declaration. This template parameter list will be updated with any |
2768 | /// default arguments that are carried through from the previous |
2769 | /// template parameter list. |
2770 | /// |
2771 | /// \param OldParams If provided, template parameter list from a |
2772 | /// previous declaration of the same template. Default template |
2773 | /// arguments will be merged from the old template parameter list to |
2774 | /// the new template parameter list. |
2775 | /// |
2776 | /// \param TPC Describes the context in which we are checking the given |
2777 | /// template parameter list. |
2778 | /// |
2779 | /// \param SkipBody If we might have already made a prior merged definition |
2780 | /// of this template visible, the corresponding body-skipping information. |
2781 | /// Default argument redefinition is not an error when skipping such a body, |
2782 | /// because (under the ODR) we can assume the default arguments are the same |
2783 | /// as the prior merged definition. |
2784 | /// |
2785 | /// \returns true if an error occurred, false otherwise. |
2786 | bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, |
2787 | TemplateParameterList *OldParams, |
2788 | TemplateParamListContext TPC, |
2789 | SkipBodyInfo *SkipBody) { |
2790 | bool Invalid = false; |
2791 | |
2792 | // C++ [temp.param]p10: |
2793 | // The set of default template-arguments available for use with a |
2794 | // template declaration or definition is obtained by merging the |
2795 | // default arguments from the definition (if in scope) and all |
2796 | // declarations in scope in the same way default function |
2797 | // arguments are (8.3.6). |
2798 | bool SawDefaultArgument = false; |
2799 | SourceLocation PreviousDefaultArgLoc; |
2800 | |
2801 | // Dummy initialization to avoid warnings. |
2802 | TemplateParameterList::iterator OldParam = NewParams->end(); |
2803 | if (OldParams) |
2804 | OldParam = OldParams->begin(); |
2805 | |
2806 | bool RemoveDefaultArguments = false; |
2807 | for (TemplateParameterList::iterator NewParam = NewParams->begin(), |
2808 | NewParamEnd = NewParams->end(); |
2809 | NewParam != NewParamEnd; ++NewParam) { |
2810 | // Whether we've seen a duplicate default argument in the same translation |
2811 | // unit. |
2812 | bool RedundantDefaultArg = false; |
2813 | // Whether we've found inconsis inconsitent default arguments in different |
2814 | // translation unit. |
2815 | bool InconsistentDefaultArg = false; |
2816 | // The name of the module which contains the inconsistent default argument. |
2817 | std::string PrevModuleName; |
2818 | |
2819 | SourceLocation OldDefaultLoc; |
2820 | SourceLocation NewDefaultLoc; |
2821 | |
2822 | // Variable used to diagnose missing default arguments |
2823 | bool MissingDefaultArg = false; |
2824 | |
2825 | // Variable used to diagnose non-final parameter packs |
2826 | bool SawParameterPack = false; |
2827 | |
2828 | if (TemplateTypeParmDecl *NewTypeParm |
2829 | = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { |
2830 | // Check the presence of a default argument here. |
2831 | if (NewTypeParm->hasDefaultArgument() && |
2832 | DiagnoseDefaultTemplateArgument(*this, TPC, |
2833 | NewTypeParm->getLocation(), |
2834 | NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() |
2835 | .getSourceRange())) |
2836 | NewTypeParm->removeDefaultArgument(); |
2837 | |
2838 | // Merge default arguments for template type parameters. |
2839 | TemplateTypeParmDecl *OldTypeParm |
2840 | = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr; |
2841 | if (NewTypeParm->isParameterPack()) { |
2842 | assert(!NewTypeParm->hasDefaultArgument() &&(static_cast <bool> (!NewTypeParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2843, __extension__ __PRETTY_FUNCTION__ )) |
2843 | "Parameter packs can't have a default argument!")(static_cast <bool> (!NewTypeParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2843, __extension__ __PRETTY_FUNCTION__ )); |
2844 | SawParameterPack = true; |
2845 | } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) && |
2846 | NewTypeParm->hasDefaultArgument() && |
2847 | (!SkipBody || !SkipBody->ShouldSkip)) { |
2848 | OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); |
2849 | NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); |
2850 | SawDefaultArgument = true; |
2851 | |
2852 | if (!OldTypeParm->getOwningModule() || |
2853 | isModuleUnitOfCurrentTU(OldTypeParm->getOwningModule())) |
2854 | RedundantDefaultArg = true; |
2855 | else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm, |
2856 | NewTypeParm)) { |
2857 | InconsistentDefaultArg = true; |
2858 | PrevModuleName = |
2859 | OldTypeParm->getImportedOwningModule()->getFullModuleName(); |
2860 | } |
2861 | PreviousDefaultArgLoc = NewDefaultLoc; |
2862 | } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { |
2863 | // Merge the default argument from the old declaration to the |
2864 | // new declaration. |
2865 | NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm); |
2866 | PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); |
2867 | } else if (NewTypeParm->hasDefaultArgument()) { |
2868 | SawDefaultArgument = true; |
2869 | PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); |
2870 | } else if (SawDefaultArgument) |
2871 | MissingDefaultArg = true; |
2872 | } else if (NonTypeTemplateParmDecl *NewNonTypeParm |
2873 | = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { |
2874 | // Check for unexpanded parameter packs. |
2875 | if (!NewNonTypeParm->isParameterPack() && |
2876 | DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(), |
2877 | NewNonTypeParm->getTypeSourceInfo(), |
2878 | UPPC_NonTypeTemplateParameterType)) { |
2879 | Invalid = true; |
2880 | continue; |
2881 | } |
2882 | |
2883 | // Check the presence of a default argument here. |
2884 | if (NewNonTypeParm->hasDefaultArgument() && |
2885 | DiagnoseDefaultTemplateArgument(*this, TPC, |
2886 | NewNonTypeParm->getLocation(), |
2887 | NewNonTypeParm->getDefaultArgument()->getSourceRange())) { |
2888 | NewNonTypeParm->removeDefaultArgument(); |
2889 | } |
2890 | |
2891 | // Merge default arguments for non-type template parameters |
2892 | NonTypeTemplateParmDecl *OldNonTypeParm |
2893 | = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr; |
2894 | if (NewNonTypeParm->isParameterPack()) { |
2895 | assert(!NewNonTypeParm->hasDefaultArgument() &&(static_cast <bool> (!NewNonTypeParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2896, __extension__ __PRETTY_FUNCTION__ )) |
2896 | "Parameter packs can't have a default argument!")(static_cast <bool> (!NewNonTypeParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2896, __extension__ __PRETTY_FUNCTION__ )); |
2897 | if (!NewNonTypeParm->isPackExpansion()) |
2898 | SawParameterPack = true; |
2899 | } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) && |
2900 | NewNonTypeParm->hasDefaultArgument() && |
2901 | (!SkipBody || !SkipBody->ShouldSkip)) { |
2902 | OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); |
2903 | NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); |
2904 | SawDefaultArgument = true; |
2905 | if (!OldNonTypeParm->getOwningModule() || |
2906 | isModuleUnitOfCurrentTU(OldNonTypeParm->getOwningModule())) |
2907 | RedundantDefaultArg = true; |
2908 | else if (!getASTContext().isSameDefaultTemplateArgument( |
2909 | OldNonTypeParm, NewNonTypeParm)) { |
2910 | InconsistentDefaultArg = true; |
2911 | PrevModuleName = |
2912 | OldNonTypeParm->getImportedOwningModule()->getFullModuleName(); |
2913 | } |
2914 | PreviousDefaultArgLoc = NewDefaultLoc; |
2915 | } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { |
2916 | // Merge the default argument from the old declaration to the |
2917 | // new declaration. |
2918 | NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm); |
2919 | PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); |
2920 | } else if (NewNonTypeParm->hasDefaultArgument()) { |
2921 | SawDefaultArgument = true; |
2922 | PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); |
2923 | } else if (SawDefaultArgument) |
2924 | MissingDefaultArg = true; |
2925 | } else { |
2926 | TemplateTemplateParmDecl *NewTemplateParm |
2927 | = cast<TemplateTemplateParmDecl>(*NewParam); |
2928 | |
2929 | // Check for unexpanded parameter packs, recursively. |
2930 | if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) { |
2931 | Invalid = true; |
2932 | continue; |
2933 | } |
2934 | |
2935 | // Check the presence of a default argument here. |
2936 | if (NewTemplateParm->hasDefaultArgument() && |
2937 | DiagnoseDefaultTemplateArgument(*this, TPC, |
2938 | NewTemplateParm->getLocation(), |
2939 | NewTemplateParm->getDefaultArgument().getSourceRange())) |
2940 | NewTemplateParm->removeDefaultArgument(); |
2941 | |
2942 | // Merge default arguments for template template parameters |
2943 | TemplateTemplateParmDecl *OldTemplateParm |
2944 | = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr; |
2945 | if (NewTemplateParm->isParameterPack()) { |
2946 | assert(!NewTemplateParm->hasDefaultArgument() &&(static_cast <bool> (!NewTemplateParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2947, __extension__ __PRETTY_FUNCTION__ )) |
2947 | "Parameter packs can't have a default argument!")(static_cast <bool> (!NewTemplateParm->hasDefaultArgument () && "Parameter packs can't have a default argument!" ) ? void (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\"" , "clang/lib/Sema/SemaTemplate.cpp", 2947, __extension__ __PRETTY_FUNCTION__ )); |
2948 | if (!NewTemplateParm->isPackExpansion()) |
2949 | SawParameterPack = true; |
2950 | } else if (OldTemplateParm && |
2951 | hasVisibleDefaultArgument(OldTemplateParm) && |
2952 | NewTemplateParm->hasDefaultArgument() && |
2953 | (!SkipBody || !SkipBody->ShouldSkip)) { |
2954 | OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); |
2955 | NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); |
2956 | SawDefaultArgument = true; |
2957 | if (!OldTemplateParm->getOwningModule() || |
2958 | isModuleUnitOfCurrentTU(OldTemplateParm->getOwningModule())) |
2959 | RedundantDefaultArg = true; |
2960 | else if (!getASTContext().isSameDefaultTemplateArgument( |
2961 | OldTemplateParm, NewTemplateParm)) { |
2962 | InconsistentDefaultArg = true; |
2963 | PrevModuleName = |
2964 | OldTemplateParm->getImportedOwningModule()->getFullModuleName(); |
2965 | } |
2966 | PreviousDefaultArgLoc = NewDefaultLoc; |
2967 | } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { |
2968 | // Merge the default argument from the old declaration to the |
2969 | // new declaration. |
2970 | NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm); |
2971 | PreviousDefaultArgLoc |
2972 | = OldTemplateParm->getDefaultArgument().getLocation(); |
2973 | } else if (NewTemplateParm->hasDefaultArgument()) { |
2974 | SawDefaultArgument = true; |
2975 | PreviousDefaultArgLoc |
2976 | = NewTemplateParm->getDefaultArgument().getLocation(); |
2977 | } else if (SawDefaultArgument) |
2978 | MissingDefaultArg = true; |
2979 | } |
2980 | |
2981 | // C++11 [temp.param]p11: |
2982 | // If a template parameter of a primary class template or alias template |
2983 | // is a template parameter pack, it shall be the last template parameter. |
2984 | if (SawParameterPack && (NewParam + 1) != NewParamEnd && |
2985 | (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate || |
2986 | TPC == TPC_TypeAliasTemplate)) { |
2987 | Diag((*NewParam)->getLocation(), |
2988 | diag::err_template_param_pack_must_be_last_template_parameter); |
2989 | Invalid = true; |
2990 | } |
2991 | |
2992 | // [basic.def.odr]/13: |
2993 | // There can be more than one definition of a |
2994 | // ... |
2995 | // default template argument |
2996 | // ... |
2997 | // in a program provided that each definition appears in a different |
2998 | // translation unit and the definitions satisfy the [same-meaning |
2999 | // criteria of the ODR]. |
3000 | // |
3001 | // Simply, the design of modules allows the definition of template default |
3002 | // argument to be repeated across translation unit. Note that the ODR is |
3003 | // checked elsewhere. But it is still not allowed to repeat template default |
3004 | // argument in the same translation unit. |
3005 | if (RedundantDefaultArg) { |
3006 | Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); |
3007 | Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); |
3008 | Invalid = true; |
3009 | } else if (InconsistentDefaultArg) { |
3010 | // We could only diagnose about the case that the OldParam is imported. |
3011 | // The case NewParam is imported should be handled in ASTReader. |
3012 | Diag(NewDefaultLoc, |
3013 | diag::err_template_param_default_arg_inconsistent_redefinition); |
3014 | Diag(OldDefaultLoc, |
3015 | diag::note_template_param_prev_default_arg_in_other_module) |
3016 | << PrevModuleName; |
3017 | Invalid = true; |
3018 | } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { |
3019 | // C++ [temp.param]p11: |
3020 | // If a template-parameter of a class template has a default |
3021 | // template-argument, each subsequent template-parameter shall either |
3022 | // have a default template-argument supplied or be a template parameter |
3023 | // pack. |
3024 | Diag((*NewParam)->getLocation(), |
3025 | diag::err_template_param_default_arg_missing); |
3026 | Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); |
3027 | Invalid = true; |
3028 | RemoveDefaultArguments = true; |
3029 | } |
3030 | |
3031 | // If we have an old template parameter list that we're merging |
3032 | // in, move on to the next parameter. |
3033 | if (OldParams) |
3034 | ++OldParam; |
3035 | } |
3036 | |
3037 | // We were missing some default arguments at the end of the list, so remove |
3038 | // all of the default arguments. |
3039 | if (RemoveDefaultArguments) { |
3040 | for (TemplateParameterList::iterator NewParam = NewParams->begin(), |
3041 | NewParamEnd = NewParams->end(); |
3042 | NewParam != NewParamEnd; ++NewParam) { |
3043 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam)) |
3044 | TTP->removeDefaultArgument(); |
3045 | else if (NonTypeTemplateParmDecl *NTTP |
3046 | = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) |
3047 | NTTP->removeDefaultArgument(); |
3048 | else |
3049 | cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument(); |
3050 | } |
3051 | } |
3052 | |
3053 | return Invalid; |
3054 | } |
3055 | |
3056 | namespace { |
3057 | |
3058 | /// A class which looks for a use of a certain level of template |
3059 | /// parameter. |
3060 | struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> { |
3061 | typedef RecursiveASTVisitor<DependencyChecker> super; |
3062 | |
3063 | unsigned Depth; |
3064 | |
3065 | // Whether we're looking for a use of a template parameter that makes the |
3066 | // overall construct type-dependent / a dependent type. This is strictly |
3067 | // best-effort for now; we may fail to match at all for a dependent type |
3068 | // in some cases if this is set. |
3069 | bool IgnoreNonTypeDependent; |
3070 | |
3071 | bool Match; |
3072 | SourceLocation MatchLoc; |
3073 | |
3074 | DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent) |
3075 | : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent), |
3076 | Match(false) {} |
3077 | |
3078 | DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent) |
3079 | : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) { |
3080 | NamedDecl *ND = Params->getParam(0); |
3081 | if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) { |
3082 | Depth = PD->getDepth(); |
3083 | } else if (NonTypeTemplateParmDecl *PD = |
3084 | dyn_cast<NonTypeTemplateParmDecl>(ND)) { |
3085 | Depth = PD->getDepth(); |
3086 | } else { |
3087 | Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth(); |
3088 | } |
3089 | } |
3090 | |
3091 | bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) { |
3092 | if (ParmDepth >= Depth) { |
3093 | Match = true; |
3094 | MatchLoc = Loc; |
3095 | return true; |
3096 | } |
3097 | return false; |
3098 | } |
3099 | |
3100 | bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) { |
3101 | // Prune out non-type-dependent expressions if requested. This can |
3102 | // sometimes result in us failing to find a template parameter reference |
3103 | // (if a value-dependent expression creates a dependent type), but this |
3104 | // mode is best-effort only. |
3105 | if (auto *E = dyn_cast_or_null<Expr>(S)) |
3106 | if (IgnoreNonTypeDependent && !E->isTypeDependent()) |
3107 | return true; |
3108 | return super::TraverseStmt(S, Q); |
3109 | } |
3110 | |
3111 | bool TraverseTypeLoc(TypeLoc TL) { |
3112 | if (IgnoreNonTypeDependent && !TL.isNull() && |
3113 | !TL.getType()->isDependentType()) |
3114 | return true; |
3115 | return super::TraverseTypeLoc(TL); |
3116 | } |
3117 | |
3118 | bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { |
3119 | return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc()); |
3120 | } |
3121 | |
3122 | bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) { |
3123 | // For a best-effort search, keep looking until we find a location. |
3124 | return IgnoreNonTypeDependent || !Matches(T->getDepth()); |
3125 | } |
3126 | |
3127 | bool TraverseTemplateName(TemplateName N) { |
3128 | if (TemplateTemplateParmDecl *PD = |
3129 | dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl())) |
3130 | if (Matches(PD->getDepth())) |
3131 | return false; |
3132 | return super::TraverseTemplateName(N); |
3133 | } |
3134 | |
3135 | bool VisitDeclRefExpr(DeclRefExpr *E) { |
3136 | if (NonTypeTemplateParmDecl *PD = |
3137 | dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) |
3138 | if (Matches(PD->getDepth(), E->getExprLoc())) |
3139 | return false; |
3140 | return super::VisitDeclRefExpr(E); |
3141 | } |
3142 | |
3143 | bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { |
3144 | return TraverseType(T->getReplacementType()); |
3145 | } |
3146 | |
3147 | bool |
3148 | VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) { |
3149 | return TraverseTemplateArgument(T->getArgumentPack()); |
3150 | } |
3151 | |
3152 | bool TraverseInjectedClassNameType(const InjectedClassNameType *T) { |
3153 | return TraverseType(T->getInjectedSpecializationType()); |
3154 | } |
3155 | }; |
3156 | } // end anonymous namespace |
3157 | |
3158 | /// Determines whether a given type depends on the given parameter |
3159 | /// list. |
3160 | static bool |
3161 | DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) { |
3162 | if (!Params->size()) |
3163 | return false; |
3164 | |
3165 | DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false); |
3166 | Checker.TraverseType(T); |
3167 | return Checker.Match; |
3168 | } |
3169 | |
3170 | // Find the source range corresponding to the named type in the given |
3171 | // nested-name-specifier, if any. |
3172 | static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, |
3173 | QualType T, |
3174 | const CXXScopeSpec &SS) { |
3175 | NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data()); |
3176 | while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) { |
3177 | if (const Type *CurType = NNS->getAsType()) { |
3178 | if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0))) |
3179 | return NNSLoc.getTypeLoc().getSourceRange(); |
3180 | } else |
3181 | break; |
3182 | |
3183 | NNSLoc = NNSLoc.getPrefix(); |
3184 | } |
3185 | |
3186 | return SourceRange(); |
3187 | } |
3188 | |
3189 | /// Match the given template parameter lists to the given scope |
3190 | /// specifier, returning the template parameter list that applies to the |
3191 | /// name. |
3192 | /// |
3193 | /// \param DeclStartLoc the start of the declaration that has a scope |
3194 | /// specifier or a template parameter list. |
3195 | /// |
3196 | /// \param DeclLoc The location of the declaration itself. |
3197 | /// |
3198 | /// \param SS the scope specifier that will be matched to the given template |
3199 | /// parameter lists. This scope specifier precedes a qualified name that is |
3200 | /// being declared. |
3201 | /// |
3202 | /// \param TemplateId The template-id following the scope specifier, if there |
3203 | /// is one. Used to check for a missing 'template<>'. |
3204 | /// |
3205 | /// \param ParamLists the template parameter lists, from the outermost to the |
3206 | /// innermost template parameter lists. |
3207 | /// |
3208 | /// \param IsFriend Whether to apply the slightly different rules for |
3209 | /// matching template parameters to scope specifiers in friend |
3210 | /// declarations. |
3211 | /// |
3212 | /// \param IsMemberSpecialization will be set true if the scope specifier |
3213 | /// denotes a fully-specialized type, and therefore this is a declaration of |
3214 | /// a member specialization. |
3215 | /// |
3216 | /// \returns the template parameter list, if any, that corresponds to the |
3217 | /// name that is preceded by the scope specifier @p SS. This template |
3218 | /// parameter list may have template parameters (if we're declaring a |
3219 | /// template) or may have no template parameters (if we're declaring a |
3220 | /// template specialization), or may be NULL (if what we're declaring isn't |
3221 | /// itself a template). |
3222 | TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier( |
3223 | SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, |
3224 | TemplateIdAnnotation *TemplateId, |
3225 | ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, |
3226 | bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) { |
3227 | IsMemberSpecialization = false; |
3228 | Invalid = false; |
3229 | |
3230 | // The sequence of nested types to which we will match up the template |
3231 | // parameter lists. We first build this list by starting with the type named |
3232 | // by the nested-name-specifier and walking out until we run out of types. |
3233 | SmallVector<QualType, 4> NestedTypes; |
3234 | QualType T; |
3235 | if (SS.getScopeRep()) { |
3236 | if (CXXRecordDecl *Record |
3237 | = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true))) |
3238 | T = Context.getTypeDeclType(Record); |
3239 | else |
3240 | T = QualType(SS.getScopeRep()->getAsType(), 0); |
3241 | } |
3242 | |
3243 | // If we found an explicit specialization that prevents us from needing |
3244 | // 'template<>' headers, this will be set to the location of that |
3245 | // explicit specialization. |
3246 | SourceLocation ExplicitSpecLoc; |
3247 | |
3248 | while (!T.isNull()) { |
3249 | NestedTypes.push_back(T); |
3250 | |
3251 | // Retrieve the parent of a record type. |
3252 | if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { |
3253 | // If this type is an explicit specialization, we're done. |
3254 | if (ClassTemplateSpecializationDecl *Spec |
3255 | = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { |
3256 | if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) && |
3257 | Spec->getSpecializationKind() == TSK_ExplicitSpecialization) { |
3258 | ExplicitSpecLoc = Spec->getLocation(); |
3259 | break; |
3260 | } |
3261 | } else if (Record->getTemplateSpecializationKind() |
3262 | == TSK_ExplicitSpecialization) { |
3263 | ExplicitSpecLoc = Record->getLocation(); |
3264 | break; |
3265 | } |
3266 | |
3267 | if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent())) |
3268 | T = Context.getTypeDeclType(Parent); |
3269 | else |
3270 | T = QualType(); |
3271 | continue; |
3272 | } |
3273 | |
3274 | if (const TemplateSpecializationType *TST |
3275 | = T->getAs<TemplateSpecializationType>()) { |
3276 | if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { |
3277 | if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext())) |
3278 | T = Context.getTypeDeclType(Parent); |
3279 | else |
3280 | T = QualType(); |
3281 | continue; |
3282 | } |
3283 | } |
3284 | |
3285 | // Look one step prior in a dependent template specialization type. |
3286 | if (const DependentTemplateSpecializationType *DependentTST |
3287 | = T->getAs<DependentTemplateSpecializationType>()) { |
3288 | if (NestedNameSpecifier *NNS = DependentTST->getQualifier()) |
3289 | T = QualType(NNS->getAsType(), 0); |
3290 | else |
3291 | T = QualType(); |
3292 | continue; |
3293 | } |
3294 | |
3295 | // Look one step prior in a dependent name type. |
3296 | if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){ |
3297 | if (NestedNameSpecifier *NNS = DependentName->getQualifier()) |
3298 | T = QualType(NNS->getAsType(), 0); |
3299 | else |
3300 | T = QualType(); |
3301 | continue; |
3302 | } |
3303 | |
3304 | // Retrieve the parent of an enumeration type. |
3305 | if (const EnumType *EnumT = T->getAs<EnumType>()) { |
3306 | // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization |
3307 | // check here. |
3308 | EnumDecl *Enum = EnumT->getDecl(); |
3309 | |
3310 | // Get to the parent type. |
3311 | if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent())) |
3312 | T = Context.getTypeDeclType(Parent); |
3313 | else |
3314 | T = QualType(); |
3315 | continue; |
3316 | } |
3317 | |
3318 | T = QualType(); |
3319 | } |
3320 | // Reverse the nested types list, since we want to traverse from the outermost |
3321 | // to the innermost while checking template-parameter-lists. |
3322 | std::reverse(NestedTypes.begin(), NestedTypes.end()); |
3323 | |
3324 | // C++0x [temp.expl.spec]p17: |
3325 | // A member or a member template may be nested within many |
3326 | // enclosing class templates. In an explicit specialization for |
3327 | // such a member, the member declaration shall be preceded by a |
3328 | // template<> for each enclosing class template that is |
3329 | // explicitly specialized. |
3330 | bool SawNonEmptyTemplateParameterList = false; |
3331 | |
3332 | auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) { |
3333 | if (SawNonEmptyTemplateParameterList) { |
3334 | if (!SuppressDiagnostic) |
3335 | Diag(DeclLoc, diag::err_specialize_member_of_template) |
3336 | << !Recovery << Range; |
3337 | Invalid = true; |
3338 | IsMemberSpecialization = false; |
3339 | return true; |
3340 | } |
3341 | |
3342 | return false; |
3343 | }; |
3344 | |
3345 | auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) { |
3346 | // Check that we can have an explicit specialization here. |
3347 | if (CheckExplicitSpecialization(Range, true)) |
3348 | return true; |
3349 | |
3350 | // We don't have a template header, but we should. |
3351 | SourceLocation ExpectedTemplateLoc; |
3352 | if (!ParamLists.empty()) |
3353 | ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc(); |
3354 | else |
3355 | ExpectedTemplateLoc = DeclStartLoc; |
3356 | |
3357 | if (!SuppressDiagnostic) |
3358 | Diag(DeclLoc, diag::err_template_spec_needs_header) |
3359 | << Range |
3360 | << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> "); |
3361 | return false; |
3362 | }; |
3363 | |
3364 | unsigned ParamIdx = 0; |
3365 | for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes; |
3366 | ++TypeIdx) { |
3367 | T = NestedTypes[TypeIdx]; |
3368 | |
3369 | // Whether we expect a 'template<>' header. |
3370 | bool NeedEmptyTemplateHeader = false; |
3371 | |
3372 | // Whether we expect a template header with parameters. |
3373 | bool NeedNonemptyTemplateHeader = false; |
3374 | |
3375 | // For a dependent type, the set of template parameters that we |
3376 | // expect to see. |
3377 | TemplateParameterList *ExpectedTemplateParams = nullptr; |
3378 | |
3379 | // C++0x [temp.expl.spec]p15: |
3380 | // A member or a member template may be nested within many enclosing |
3381 | // class templates. In an explicit specialization for such a member, the |
3382 | // member declaration shall be preceded by a template<> for each |
3383 | // enclosing class template that is explicitly specialized. |
3384 | if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { |
3385 | if (ClassTemplatePartialSpecializationDecl *Partial |
3386 | = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { |
3387 | ExpectedTemplateParams = Partial->getTemplateParameters(); |
3388 | NeedNonemptyTemplateHeader = true; |
3389 | } else if (Record->isDependentType()) { |
3390 | if (Record->getDescribedClassTemplate()) { |
3391 | ExpectedTemplateParams = Record->getDescribedClassTemplate() |
3392 | ->getTemplateParameters(); |
3393 | NeedNonemptyTemplateHeader = true; |
3394 | } |
3395 | } else if (ClassTemplateSpecializationDecl *Spec |
3396 | = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { |
3397 | // C++0x [temp.expl.spec]p4: |
3398 | // Members of an explicitly specialized class template are defined |
3399 | // in the same manner as members of normal classes, and not using |
3400 | // the template<> syntax. |
3401 | if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization) |
3402 | NeedEmptyTemplateHeader = true; |
3403 | else |
3404 | continue; |
3405 | } else if (Record->getTemplateSpecializationKind()) { |
3406 | if (Record->getTemplateSpecializationKind() |
3407 | != TSK_ExplicitSpecialization && |
3408 | TypeIdx == NumTypes - 1) |
3409 | IsMemberSpecialization = true; |
3410 | |
3411 | continue; |
3412 | } |
3413 | } else if (const TemplateSpecializationType *TST |
3414 | = T->getAs<TemplateSpecializationType>()) { |
3415 | if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { |
3416 | ExpectedTemplateParams = Template->getTemplateParameters(); |
3417 | NeedNonemptyTemplateHeader = true; |
3418 | } |
3419 | } else if (T->getAs<DependentTemplateSpecializationType>()) { |
3420 | // FIXME: We actually could/should check the template arguments here |
3421 | // against the corresponding template parameter list. |
3422 | NeedNonemptyTemplateHeader = false; |
3423 | } |
3424 | |
3425 | // C++ [temp.expl.spec]p16: |
3426 | // In an explicit specialization declaration for a member of a class |
3427 | // template or a member template that ap- pears in namespace scope, the |
3428 | // member template and some of its enclosing class templates may remain |
3429 | // unspecialized, except that the declaration shall not explicitly |
3430 | // specialize a class member template if its en- closing class templates |
3431 | // are not explicitly specialized as well. |
3432 | if (ParamIdx < ParamLists.size()) { |
3433 | if (ParamLists[ParamIdx]->size() == 0) { |
3434 | if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), |
3435 | false)) |
3436 | return nullptr; |
3437 | } else |
3438 | SawNonEmptyTemplateParameterList = true; |
3439 | } |
3440 | |
3441 | if (NeedEmptyTemplateHeader) { |
3442 | // If we're on the last of the types, and we need a 'template<>' header |
3443 | // here, then it's a member specialization. |
3444 | if (TypeIdx == NumTypes - 1) |
3445 | IsMemberSpecialization = true; |
3446 | |
3447 | if (ParamIdx < ParamLists.size()) { |
3448 | if (ParamLists[ParamIdx]->size() > 0) { |
3449 | // The header has template parameters when it shouldn't. Complain. |
3450 | if (!SuppressDiagnostic) |
3451 | Diag(ParamLists[ParamIdx]->getTemplateLoc(), |
3452 | diag::err_template_param_list_matches_nontemplate) |
3453 | << T |
3454 | << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(), |
3455 | ParamLists[ParamIdx]->getRAngleLoc()) |
3456 | << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); |
3457 | Invalid = true; |
3458 | return nullptr; |
3459 | } |
3460 | |
3461 | // Consume this template header. |
3462 | ++ParamIdx; |
3463 | continue; |
3464 | } |
3465 | |
3466 | if (!IsFriend) |
3467 | if (DiagnoseMissingExplicitSpecialization( |
3468 | getRangeOfTypeInNestedNameSpecifier(Context, T, SS))) |
3469 | return nullptr; |
3470 | |
3471 | continue; |
3472 | } |
3473 | |
3474 | if (NeedNonemptyTemplateHeader) { |
3475 | // In friend declarations we can have template-ids which don't |
3476 | // depend on the corresponding template parameter lists. But |
3477 | // assume that empty parameter lists are supposed to match this |
3478 | // template-id. |
3479 | if (IsFriend && T->isDependentType()) { |
3480 | if (ParamIdx < ParamLists.size() && |
3481 | DependsOnTemplateParameters(T, ParamLists[ParamIdx])) |
3482 | ExpectedTemplateParams = nullptr; |
3483 | else |
3484 | continue; |
3485 | } |
3486 | |
3487 | if (ParamIdx < ParamLists.size()) { |
3488 | // Check the template parameter list, if we can. |
3489 | if (ExpectedTemplateParams && |
3490 | !TemplateParameterListsAreEqual(ParamLists[ParamIdx], |
3491 | ExpectedTemplateParams, |
3492 | !SuppressDiagnostic, TPL_TemplateMatch)) |
3493 | Invalid = true; |
3494 | |
3495 | if (!Invalid && |
3496 | CheckTemplateParameterList(ParamLists[ParamIdx], nullptr, |
3497 | TPC_ClassTemplateMember)) |
3498 | Invalid = true; |
3499 | |
3500 | ++ParamIdx; |
3501 | continue; |
3502 | } |
3503 | |
3504 | if (!SuppressDiagnostic) |
3505 | Diag(DeclLoc, diag::err_template_spec_needs_template_parameters) |
3506 | << T |
3507 | << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); |
3508 | Invalid = true; |
3509 | continue; |
3510 | } |
3511 | } |
3512 | |
3513 | // If there were at least as many template-ids as there were template |
3514 | // parameter lists, then there are no template parameter lists remaining for |
3515 | // the declaration itself. |
3516 | if (ParamIdx >= ParamLists.size()) { |
3517 | if (TemplateId && !IsFriend) { |
3518 | // We don't have a template header for the declaration itself, but we |
3519 | // should. |
3520 | DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc, |
3521 | TemplateId->RAngleLoc)); |
3522 | |
3523 | // Fabricate an empty template parameter list for the invented header. |
3524 | return TemplateParameterList::Create(Context, SourceLocation(), |
3525 | SourceLocation(), std::nullopt, |
3526 | SourceLocation(), nullptr); |
3527 | } |
3528 | |
3529 | return nullptr; |
3530 | } |
3531 | |
3532 | // If there were too many template parameter lists, complain about that now. |
3533 | if (ParamIdx < ParamLists.size() - 1) { |
3534 | bool HasAnyExplicitSpecHeader = false; |
3535 | bool AllExplicitSpecHeaders = true; |
3536 | for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) { |
3537 | if (ParamLists[I]->size() == 0) |
3538 | HasAnyExplicitSpecHeader = true; |
3539 | else |
3540 | AllExplicitSpecHeaders = false; |
3541 | } |
3542 | |
3543 | if (!SuppressDiagnostic) |
3544 | Diag(ParamLists[ParamIdx]->getTemplateLoc(), |
3545 | AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers |
3546 | : diag::err_template_spec_extra_headers) |
3547 | << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(), |
3548 | ParamLists[ParamLists.size() - 2]->getRAngleLoc()); |
3549 | |
3550 | // If there was a specialization somewhere, such that 'template<>' is |
3551 | // not required, and there were any 'template<>' headers, note where the |
3552 | // specialization occurred. |
3553 | if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader && |
3554 | !SuppressDiagnostic) |
3555 | Diag(ExplicitSpecLoc, |
3556 | diag::note_explicit_template_spec_does_not_need_header) |
3557 | << NestedTypes.back(); |
3558 | |
3559 | // We have a template parameter list with no corresponding scope, which |
3560 | // means that the resulting template declaration can't be instantiated |
3561 | // properly (we'll end up with dependent nodes when we shouldn't). |
3562 | if (!AllExplicitSpecHeaders) |
3563 | Invalid = true; |
3564 | } |
3565 | |
3566 | // C++ [temp.expl.spec]p16: |
3567 | // In an explicit specialization declaration for a member of a class |
3568 | // template or a member template that ap- pears in namespace scope, the |
3569 | // member template and some of its enclosing class templates may remain |
3570 | // unspecialized, except that the declaration shall not explicitly |
3571 | // specialize a class member template if its en- closing class templates |
3572 | // are not explicitly specialized as well. |
3573 | if (ParamLists.back()->size() == 0 && |
3574 | CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), |
3575 | false)) |
3576 | return nullptr; |
3577 | |
3578 | // Return the last template parameter list, which corresponds to the |
3579 | // entity being declared. |
3580 | return ParamLists.back(); |
3581 | } |
3582 | |
3583 | void Sema::NoteAllFoundTemplates(TemplateName Name) { |
3584 | if (TemplateDecl *Template = Name.getAsTemplateDecl()) { |
3585 | Diag(Template->getLocation(), diag::note_template_declared_here) |
3586 | << (isa<FunctionTemplateDecl>(Template) |
3587 | ? 0 |
3588 | : isa<ClassTemplateDecl>(Template) |
3589 | ? 1 |
3590 | : isa<VarTemplateDecl>(Template) |
3591 | ? 2 |
3592 | : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4) |
3593 | << Template->getDeclName(); |
3594 | return; |
3595 | } |
3596 | |
3597 | if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) { |
3598 | for (OverloadedTemplateStorage::iterator I = OST->begin(), |
3599 | IEnd = OST->end(); |
3600 | I != IEnd; ++I) |
3601 | Diag((*I)->getLocation(), diag::note_template_declared_here) |
3602 | << 0 << (*I)->getDeclName(); |
3603 | |
3604 | return; |
3605 | } |
3606 | } |
3607 | |
3608 | static QualType |
3609 | checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, |
3610 | ArrayRef<TemplateArgument> Converted, |
3611 | SourceLocation TemplateLoc, |
3612 | TemplateArgumentListInfo &TemplateArgs) { |
3613 | ASTContext &Context = SemaRef.getASTContext(); |
3614 | |
3615 | switch (BTD->getBuiltinTemplateKind()) { |
3616 | case BTK__make_integer_seq: { |
3617 | // Specializations of __make_integer_seq<S, T, N> are treated like |
3618 | // S<T, 0, ..., N-1>. |
3619 | |
3620 | QualType OrigType = Converted[1].getAsType(); |
3621 | // C++14 [inteseq.intseq]p1: |
3622 | // T shall be an integer type. |
3623 | if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) { |
3624 | SemaRef.Diag(TemplateArgs[1].getLocation(), |
3625 | diag::err_integer_sequence_integral_element_type); |
3626 | return QualType(); |
3627 | } |
3628 | |
3629 | TemplateArgument NumArgsArg = Converted[2]; |
3630 | if (NumArgsArg.isDependent()) |
3631 | return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD), |
3632 | Converted); |
3633 | |
3634 | TemplateArgumentListInfo SyntheticTemplateArgs; |
3635 | // The type argument, wrapped in substitution sugar, gets reused as the |
3636 | // first template argument in the synthetic template argument list. |
3637 | SyntheticTemplateArgs.addArgument( |
3638 | TemplateArgumentLoc(TemplateArgument(OrigType), |
3639 | SemaRef.Context.getTrivialTypeSourceInfo( |
3640 | OrigType, TemplateArgs[1].getLocation()))); |
3641 | |
3642 | if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) { |
3643 | // Expand N into 0 ... N-1. |
3644 | for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned()); |
3645 | I < NumArgs; ++I) { |
3646 | TemplateArgument TA(Context, I, OrigType); |
3647 | SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc( |
3648 | TA, OrigType, TemplateArgs[2].getLocation())); |
3649 | } |
3650 | } else { |
3651 | // C++14 [inteseq.make]p1: |
3652 | // If N is negative the program is ill-formed. |
3653 | SemaRef.Diag(TemplateArgs[2].getLocation(), |
3654 | diag::err_integer_sequence_negative_length); |
3655 | return QualType(); |
3656 | } |
3657 | |
3658 | // The first template argument will be reused as the template decl that |
3659 | // our synthetic template arguments will be applied to. |
3660 | return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(), |
3661 | TemplateLoc, SyntheticTemplateArgs); |
3662 | } |
3663 | |
3664 | case BTK__type_pack_element: |
3665 | // Specializations of |
3666 | // __type_pack_element<Index, T_1, ..., T_N> |
3667 | // are treated like T_Index. |
3668 | assert(Converted.size() == 2 &&(static_cast <bool> (Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack" ) ? void (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\"" , "clang/lib/Sema/SemaTemplate.cpp", 3669, __extension__ __PRETTY_FUNCTION__ )) |
3669 | "__type_pack_element should be given an index and a parameter pack")(static_cast <bool> (Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack" ) ? void (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\"" , "clang/lib/Sema/SemaTemplate.cpp", 3669, __extension__ __PRETTY_FUNCTION__ )); |
3670 | |
3671 | TemplateArgument IndexArg = Converted[0], Ts = Converted[1]; |
3672 | if (IndexArg.isDependent() || Ts.isDependent()) |
3673 | return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD), |
3674 | Converted); |
3675 | |
3676 | llvm::APSInt Index = IndexArg.getAsIntegral(); |
3677 | assert(Index >= 0 && "the index used with __type_pack_element should be of "(static_cast <bool> (Index >= 0 && "the index used with __type_pack_element should be of " "type std::size_t, and hence be non-negative") ? void (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\"" , "clang/lib/Sema/SemaTemplate.cpp", 3678, __extension__ __PRETTY_FUNCTION__ )) |
3678 | "type std::size_t, and hence be non-negative")(static_cast <bool> (Index >= 0 && "the index used with __type_pack_element should be of " "type std::size_t, and hence be non-negative") ? void (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\"" , "clang/lib/Sema/SemaTemplate.cpp", 3678, __extension__ __PRETTY_FUNCTION__ )); |
3679 | // If the Index is out of bounds, the program is ill-formed. |
3680 | if (Index >= Ts.pack_size()) { |
3681 | SemaRef.Diag(TemplateArgs[0].getLocation(), |
3682 | diag::err_type_pack_element_out_of_bounds); |
3683 | return QualType(); |
3684 | } |
3685 | |
3686 | // We simply return the type at index `Index`. |
3687 | int64_t N = Index.getExtValue(); |
3688 | return Ts.getPackAsArray()[N].getAsType(); |
3689 | } |
3690 | llvm_unreachable("unexpected BuiltinTemplateDecl!")::llvm::llvm_unreachable_internal("unexpected BuiltinTemplateDecl!" , "clang/lib/Sema/SemaTemplate.cpp", 3690); |
3691 | } |
3692 | |
3693 | /// Determine whether this alias template is "enable_if_t". |
3694 | /// libc++ >=14 uses "__enable_if_t" in C++11 mode. |
3695 | static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) { |
3696 | return AliasTemplate->getName().equals("enable_if_t") || |
3697 | AliasTemplate->getName().equals("__enable_if_t"); |
3698 | } |
3699 | |
3700 | /// Collect all of the separable terms in the given condition, which |
3701 | /// might be a conjunction. |
3702 | /// |
3703 | /// FIXME: The right answer is to convert the logical expression into |
3704 | /// disjunctive normal form, so we can find the first failed term |
3705 | /// within each possible clause. |
3706 | static void collectConjunctionTerms(Expr *Clause, |
3707 | SmallVectorImpl<Expr *> &Terms) { |
3708 | if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) { |
3709 | if (BinOp->getOpcode() == BO_LAnd) { |
3710 | collectConjunctionTerms(BinOp->getLHS(), Terms); |
3711 | collectConjunctionTerms(BinOp->getRHS(), Terms); |
3712 | return; |
3713 | } |
3714 | } |
3715 | |
3716 | Terms.push_back(Clause); |
3717 | } |
3718 | |
3719 | // The ranges-v3 library uses an odd pattern of a top-level "||" with |
3720 | // a left-hand side that is value-dependent but never true. Identify |
3721 | // the idiom and ignore that term. |
3722 | static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) { |
3723 | // Top-level '||'. |
3724 | auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts()); |
3725 | if (!BinOp) return Cond; |
3726 | |
3727 | if (BinOp->getOpcode() != BO_LOr) return Cond; |
3728 | |
3729 | // With an inner '==' that has a literal on the right-hand side. |
3730 | Expr *LHS = BinOp->getLHS(); |
3731 | auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts()); |
3732 | if (!InnerBinOp) return Cond; |
3733 | |
3734 | if (InnerBinOp->getOpcode() != BO_EQ || |
3735 | !isa<IntegerLiteral>(InnerBinOp->getRHS())) |
3736 | return Cond; |
3737 | |
3738 | // If the inner binary operation came from a macro expansion named |
3739 | // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side |
3740 | // of the '||', which is the real, user-provided condition. |
3741 | SourceLocation Loc = InnerBinOp->getExprLoc(); |
3742 | if (!Loc.isMacroID()) return Cond; |
3743 | |
3744 | StringRef MacroName = PP.getImmediateMacroName(Loc); |
3745 | if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_") |
3746 | return BinOp->getRHS(); |
3747 | |
3748 | return Cond; |
3749 | } |
3750 | |
3751 | namespace { |
3752 | |
3753 | // A PrinterHelper that prints more helpful diagnostics for some sub-expressions |
3754 | // within failing boolean expression, such as substituting template parameters |
3755 | // for actual types. |
3756 | class FailedBooleanConditionPrinterHelper : public PrinterHelper { |
3757 | public: |
3758 | explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P) |
3759 | : Policy(P) {} |
3760 | |
3761 | bool handledStmt(Stmt *E, raw_ostream &OS) override { |
3762 | const auto *DR = dyn_cast<DeclRefExpr>(E); |
3763 | if (DR && DR->getQualifier()) { |
3764 | // If this is a qualified name, expand the template arguments in nested |
3765 | // qualifiers. |
3766 | DR->getQualifier()->print(OS, Policy, true); |
3767 | // Then print the decl itself. |
3768 | const ValueDecl *VD = DR->getDecl(); |
3769 | OS << VD->getName(); |
3770 | if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) { |
3771 | // This is a template variable, print the expanded template arguments. |
3772 | printTemplateArgumentList( |
3773 | OS, IV->getTemplateArgs().asArray(), Policy, |
3774 | IV->getSpecializedTemplate()->getTemplateParameters()); |
3775 | } |
3776 | return true; |
3777 | } |
3778 | return false; |
3779 | } |
3780 | |
3781 | private: |
3782 | const PrintingPolicy Policy; |
3783 | }; |
3784 | |
3785 | } // end anonymous namespace |
3786 | |
3787 | std::pair<Expr *, std::string> |
3788 | Sema::findFailedBooleanCondition(Expr *Cond) { |
3789 | Cond = lookThroughRangesV3Condition(PP, Cond); |
3790 | |
3791 | // Separate out all of the terms in a conjunction. |
3792 | SmallVector<Expr *, 4> Terms; |
3793 | collectConjunctionTerms(Cond, Terms); |
3794 | |
3795 | // Determine which term failed. |
3796 | Expr *FailedCond = nullptr; |
3797 | for (Expr *Term : Terms) { |
3798 | Expr *TermAsWritten = Term->IgnoreParenImpCasts(); |
3799 | |
3800 | // Literals are uninteresting. |
3801 | if (isa<CXXBoolLiteralExpr>(TermAsWritten) || |
3802 | isa<IntegerLiteral>(TermAsWritten)) |
3803 | continue; |
3804 | |
3805 | // The initialization of the parameter from the argument is |
3806 | // a constant-evaluated context. |
3807 | EnterExpressionEvaluationContext ConstantEvaluated( |
3808 | *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
3809 | |
3810 | bool Succeeded; |
3811 | if (Term->EvaluateAsBooleanCondition(Succeeded, Context) && |
3812 | !Succeeded) { |
3813 | FailedCond = TermAsWritten; |
3814 | break; |
3815 | } |
3816 | } |
3817 | if (!FailedCond) |
3818 | FailedCond = Cond->IgnoreParenImpCasts(); |
3819 | |
3820 | std::string Description; |
3821 | { |
3822 | llvm::raw_string_ostream Out(Description); |
3823 | PrintingPolicy Policy = getPrintingPolicy(); |
3824 | Policy.PrintCanonicalTypes = true; |
3825 | FailedBooleanConditionPrinterHelper Helper(Policy); |
3826 | FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr); |
3827 | } |
3828 | return { FailedCond, Description }; |
3829 | } |
3830 | |
3831 | QualType Sema::CheckTemplateIdType(TemplateName Name, |
3832 | SourceLocation TemplateLoc, |
3833 | TemplateArgumentListInfo &TemplateArgs) { |
3834 | DependentTemplateName *DTN |
3835 | = Name.getUnderlying().getAsDependentTemplateName(); |
3836 | if (DTN && DTN->isIdentifier()) |
3837 | // When building a template-id where the template-name is dependent, |
3838 | // assume the template is a type template. Either our assumption is |
3839 | // correct, or the code is ill-formed and will be diagnosed when the |
3840 | // dependent name is substituted. |
3841 | return Context.getDependentTemplateSpecializationType( |
3842 | ETK_None, DTN->getQualifier(), DTN->getIdentifier(), |
3843 | TemplateArgs.arguments()); |
3844 | |
3845 | if (Name.getAsAssumedTemplateName() && |
3846 | resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc)) |
3847 | return QualType(); |
3848 | |
3849 | TemplateDecl *Template = Name.getAsTemplateDecl(); |
3850 | if (!Template || isa<FunctionTemplateDecl>(Template) || |
3851 | isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) { |
3852 | // We might have a substituted template template parameter pack. If so, |
3853 | // build a template specialization type for it. |
3854 | if (Name.getAsSubstTemplateTemplateParmPack()) |
3855 | return Context.getTemplateSpecializationType(Name, |
3856 | TemplateArgs.arguments()); |
3857 | |
3858 | Diag(TemplateLoc, diag::err_template_id_not_a_type) |
3859 | << Name; |
3860 | NoteAllFoundTemplates(Name); |
3861 | return QualType(); |
3862 | } |
3863 | |
3864 | // Check that the template argument list is well-formed for this |
3865 | // template. |
3866 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
3867 | if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false, |
3868 | SugaredConverted, CanonicalConverted, |
3869 | /*UpdateArgsWithConversions=*/true)) |
3870 | return QualType(); |
3871 | |
3872 | QualType CanonType; |
3873 | |
3874 | if (TypeAliasTemplateDecl *AliasTemplate = |
3875 | dyn_cast<TypeAliasTemplateDecl>(Template)) { |
3876 | |
3877 | // Find the canonical type for this type alias template specialization. |
3878 | TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl(); |
3879 | if (Pattern->isInvalidDecl()) |
3880 | return QualType(); |
3881 | |
3882 | // Only substitute for the innermost template argument list. |
3883 | MultiLevelTemplateArgumentList TemplateArgLists; |
3884 | TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted, |
3885 | /*Final=*/false); |
3886 | TemplateArgLists.addOuterRetainedLevels( |
3887 | AliasTemplate->getTemplateParameters()->getDepth()); |
3888 | |
3889 | LocalInstantiationScope Scope(*this); |
3890 | InstantiatingTemplate Inst(*this, TemplateLoc, Template); |
3891 | if (Inst.isInvalid()) |
3892 | return QualType(); |
3893 | |
3894 | CanonType = SubstType(Pattern->getUnderlyingType(), |
3895 | TemplateArgLists, AliasTemplate->getLocation(), |
3896 | AliasTemplate->getDeclName()); |
3897 | if (CanonType.isNull()) { |
3898 | // If this was enable_if and we failed to find the nested type |
3899 | // within enable_if in a SFINAE context, dig out the specific |
3900 | // enable_if condition that failed and present that instead. |
3901 | if (isEnableIfAliasTemplate(AliasTemplate)) { |
3902 | if (auto DeductionInfo = isSFINAEContext()) { |
3903 | if (*DeductionInfo && |
3904 | (*DeductionInfo)->hasSFINAEDiagnostic() && |
3905 | (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() == |
3906 | diag::err_typename_nested_not_found_enable_if && |
3907 | TemplateArgs[0].getArgument().getKind() |
3908 | == TemplateArgument::Expression) { |
3909 | Expr *FailedCond; |
3910 | std::string FailedDescription; |
3911 | std::tie(FailedCond, FailedDescription) = |
3912 | findFailedBooleanCondition(TemplateArgs[0].getSourceExpression()); |
3913 | |
3914 | // Remove the old SFINAE diagnostic. |
3915 | PartialDiagnosticAt OldDiag = |
3916 | {SourceLocation(), PartialDiagnostic::NullDiagnostic()}; |
3917 | (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag); |
3918 | |
3919 | // Add a new SFINAE diagnostic specifying which condition |
3920 | // failed. |
3921 | (*DeductionInfo)->addSFINAEDiagnostic( |
3922 | OldDiag.first, |
3923 | PDiag(diag::err_typename_nested_not_found_requirement) |
3924 | << FailedDescription |
3925 | << FailedCond->getSourceRange()); |
3926 | } |
3927 | } |
3928 | } |
3929 | |
3930 | return QualType(); |
3931 | } |
3932 | } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) { |
3933 | CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted, |
3934 | TemplateLoc, TemplateArgs); |
3935 | } else if (Name.isDependent() || |
3936 | TemplateSpecializationType::anyDependentTemplateArguments( |
3937 | TemplateArgs, CanonicalConverted)) { |
3938 | // This class template specialization is a dependent |
3939 | // type. Therefore, its canonical type is another class template |
3940 | // specialization type that contains all of the converted |
3941 | // arguments in canonical form. This ensures that, e.g., A<T> and |
3942 | // A<T, T> have identical types when A is declared as: |
3943 | // |
3944 | // template<typename T, typename U = T> struct A; |
3945 | CanonType = Context.getCanonicalTemplateSpecializationType( |
3946 | Name, CanonicalConverted); |
3947 | |
3948 | // This might work out to be a current instantiation, in which |
3949 | // case the canonical type needs to be the InjectedClassNameType. |
3950 | // |
3951 | // TODO: in theory this could be a simple hashtable lookup; most |
3952 | // changes to CurContext don't change the set of current |
3953 | // instantiations. |
3954 | if (isa<ClassTemplateDecl>(Template)) { |
3955 | for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) { |
3956 | // If we get out to a namespace, we're done. |
3957 | if (Ctx->isFileContext()) break; |
3958 | |
3959 | // If this isn't a record, keep looking. |
3960 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx); |
3961 | if (!Record) continue; |
3962 | |
3963 | // Look for one of the two cases with InjectedClassNameTypes |
3964 | // and check whether it's the same template. |
3965 | if (!isa<ClassTemplatePartialSpecializationDecl>(Record) && |
3966 | !Record->getDescribedClassTemplate()) |
3967 | continue; |
3968 | |
3969 | // Fetch the injected class name type and check whether its |
3970 | // injected type is equal to the type we just built. |
3971 | QualType ICNT = Context.getTypeDeclType(Record); |
3972 | QualType Injected = cast<InjectedClassNameType>(ICNT) |
3973 | ->getInjectedSpecializationType(); |
3974 | |
3975 | if (CanonType != Injected->getCanonicalTypeInternal()) |
3976 | continue; |
3977 | |
3978 | // If so, the canonical type of this TST is the injected |
3979 | // class name type of the record we just found. |
3980 | assert(ICNT.isCanonical())(static_cast <bool> (ICNT.isCanonical()) ? void (0) : __assert_fail ("ICNT.isCanonical()", "clang/lib/Sema/SemaTemplate.cpp", 3980 , __extension__ __PRETTY_FUNCTION__)); |
3981 | CanonType = ICNT; |
3982 | break; |
3983 | } |
3984 | } |
3985 | } else if (ClassTemplateDecl *ClassTemplate = |
3986 | dyn_cast<ClassTemplateDecl>(Template)) { |
3987 | // Find the class template specialization declaration that |
3988 | // corresponds to these arguments. |
3989 | void *InsertPos = nullptr; |
3990 | ClassTemplateSpecializationDecl *Decl = |
3991 | ClassTemplate->findSpecialization(CanonicalConverted, InsertPos); |
3992 | if (!Decl) { |
3993 | // This is the first time we have referenced this class template |
3994 | // specialization. Create the canonical declaration and add it to |
3995 | // the set of specializations. |
3996 | Decl = ClassTemplateSpecializationDecl::Create( |
3997 | Context, ClassTemplate->getTemplatedDecl()->getTagKind(), |
3998 | ClassTemplate->getDeclContext(), |
3999 | ClassTemplate->getTemplatedDecl()->getBeginLoc(), |
4000 | ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted, |
4001 | nullptr); |
4002 | ClassTemplate->AddSpecialization(Decl, InsertPos); |
4003 | if (ClassTemplate->isOutOfLine()) |
4004 | Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext()); |
4005 | } |
4006 | |
4007 | if (Decl->getSpecializationKind() == TSK_Undeclared && |
4008 | ClassTemplate->getTemplatedDecl()->hasAttrs()) { |
4009 | InstantiatingTemplate Inst(*this, TemplateLoc, Decl); |
4010 | if (!Inst.isInvalid()) { |
4011 | MultiLevelTemplateArgumentList TemplateArgLists(Template, |
4012 | CanonicalConverted, |
4013 | /*Final=*/false); |
4014 | InstantiateAttrsForDecl(TemplateArgLists, |
4015 | ClassTemplate->getTemplatedDecl(), Decl); |
4016 | } |
4017 | } |
4018 | |
4019 | // Diagnose uses of this specialization. |
4020 | (void)DiagnoseUseOfDecl(Decl, TemplateLoc); |
4021 | |
4022 | CanonType = Context.getTypeDeclType(Decl); |
4023 | assert(isa<RecordType>(CanonType) &&(static_cast <bool> (isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType") ? void (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\"" , "clang/lib/Sema/SemaTemplate.cpp", 4024, __extension__ __PRETTY_FUNCTION__ )) |
4024 | "type of non-dependent specialization is not a RecordType")(static_cast <bool> (isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType") ? void (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\"" , "clang/lib/Sema/SemaTemplate.cpp", 4024, __extension__ __PRETTY_FUNCTION__ )); |
4025 | } else { |
4026 | llvm_unreachable("Unhandled template kind")::llvm::llvm_unreachable_internal("Unhandled template kind", "clang/lib/Sema/SemaTemplate.cpp" , 4026); |
4027 | } |
4028 | |
4029 | // Build the fully-sugared type for this class template |
4030 | // specialization, which refers back to the class template |
4031 | // specialization we created or found. |
4032 | return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(), |
4033 | CanonType); |
4034 | } |
4035 | |
4036 | void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName, |
4037 | TemplateNameKind &TNK, |
4038 | SourceLocation NameLoc, |
4039 | IdentifierInfo *&II) { |
4040 | assert(TNK == TNK_Undeclared_template && "not an undeclared template name")(static_cast <bool> (TNK == TNK_Undeclared_template && "not an undeclared template name") ? void (0) : __assert_fail ("TNK == TNK_Undeclared_template && \"not an undeclared template name\"" , "clang/lib/Sema/SemaTemplate.cpp", 4040, __extension__ __PRETTY_FUNCTION__ )); |
4041 | |
4042 | TemplateName Name = ParsedName.get(); |
4043 | auto *ATN = Name.getAsAssumedTemplateName(); |
4044 | assert(ATN && "not an assumed template name")(static_cast <bool> (ATN && "not an assumed template name" ) ? void (0) : __assert_fail ("ATN && \"not an assumed template name\"" , "clang/lib/Sema/SemaTemplate.cpp", 4044, __extension__ __PRETTY_FUNCTION__ )); |
4045 | II = ATN->getDeclName().getAsIdentifierInfo(); |
4046 | |
4047 | if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) { |
4048 | // Resolved to a type template name. |
4049 | ParsedName = TemplateTy::make(Name); |
4050 | TNK = TNK_Type_template; |
4051 | } |
4052 | } |
4053 | |
4054 | bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, |
4055 | SourceLocation NameLoc, |
4056 | bool Diagnose) { |
4057 | // We assumed this undeclared identifier to be an (ADL-only) function |
4058 | // template name, but it was used in a context where a type was required. |
4059 | // Try to typo-correct it now. |
4060 | AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName(); |
4061 | assert(ATN && "not an assumed template name")(static_cast <bool> (ATN && "not an assumed template name" ) ? void (0) : __assert_fail ("ATN && \"not an assumed template name\"" , "clang/lib/Sema/SemaTemplate.cpp", 4061, __extension__ __PRETTY_FUNCTION__ )); |
4062 | |
4063 | LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName); |
4064 | struct CandidateCallback : CorrectionCandidateCallback { |
4065 | bool ValidateCandidate(const TypoCorrection &TC) override { |
4066 | return TC.getCorrectionDecl() && |
4067 | getAsTypeTemplateDecl(TC.getCorrectionDecl()); |
4068 | } |
4069 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
4070 | return std::make_unique<CandidateCallback>(*this); |
4071 | } |
4072 | } FilterCCC; |
4073 | |
4074 | TypoCorrection Corrected = |
4075 | CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr, |
4076 | FilterCCC, CTK_ErrorRecovery); |
4077 | if (Corrected && Corrected.getFoundDecl()) { |
4078 | diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) |
4079 | << ATN->getDeclName()); |
4080 | Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()); |
4081 | return false; |
4082 | } |
4083 | |
4084 | if (Diagnose) |
4085 | Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName(); |
4086 | return true; |
4087 | } |
4088 | |
4089 | TypeResult Sema::ActOnTemplateIdType( |
4090 | Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
4091 | TemplateTy TemplateD, IdentifierInfo *TemplateII, |
4092 | SourceLocation TemplateIILoc, SourceLocation LAngleLoc, |
4093 | ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc, |
4094 | bool IsCtorOrDtorName, bool IsClassName, |
4095 | ImplicitTypenameContext AllowImplicitTypename) { |
4096 | if (SS.isInvalid()) |
4097 | return true; |
4098 | |
4099 | if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) { |
4100 | DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false); |
4101 | |
4102 | // C++ [temp.res]p3: |
4103 | // A qualified-id that refers to a type and in which the |
4104 | // nested-name-specifier depends on a template-parameter (14.6.2) |
4105 | // shall be prefixed by the keyword typename to indicate that the |
4106 | // qualified-id denotes a type, forming an |
4107 | // elaborated-type-specifier (7.1.5.3). |
4108 | if (!LookupCtx && isDependentScopeSpecifier(SS)) { |
4109 | // C++2a relaxes some of those restrictions in [temp.res]p5. |
4110 | if (AllowImplicitTypename == ImplicitTypenameContext::Yes) { |
4111 | if (getLangOpts().CPlusPlus20) |
4112 | Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename); |
4113 | else |
4114 | Diag(SS.getBeginLoc(), diag::ext_implicit_typename) |
4115 | << SS.getScopeRep() << TemplateII->getName() |
4116 | << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename "); |
4117 | } else |
4118 | Diag(SS.getBeginLoc(), diag::err_typename_missing_template) |
4119 | << SS.getScopeRep() << TemplateII->getName(); |
4120 | |
4121 | // FIXME: This is not quite correct recovery as we don't transform SS |
4122 | // into the corresponding dependent form (and we don't diagnose missing |
4123 | // 'template' keywords within SS as a result). |
4124 | return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc, |
4125 | TemplateD, TemplateII, TemplateIILoc, LAngleLoc, |
4126 | TemplateArgsIn, RAngleLoc); |
4127 | } |
4128 | |
4129 | // Per C++ [class.qual]p2, if the template-id was an injected-class-name, |
4130 | // it's not actually allowed to be used as a type in most cases. Because |
4131 | // we annotate it before we know whether it's valid, we have to check for |
4132 | // this case here. |
4133 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); |
4134 | if (LookupRD && LookupRD->getIdentifier() == TemplateII) { |
4135 | Diag(TemplateIILoc, |
4136 | TemplateKWLoc.isInvalid() |
4137 | ? diag::err_out_of_line_qualified_id_type_names_constructor |
4138 | : diag::ext_out_of_line_qualified_id_type_names_constructor) |
4139 | << TemplateII << 0 /*injected-class-name used as template name*/ |
4140 | << 1 /*if any keyword was present, it was 'template'*/; |
4141 | } |
4142 | } |
4143 | |
4144 | TemplateName Template = TemplateD.get(); |
4145 | if (Template.getAsAssumedTemplateName() && |
4146 | resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc)) |
4147 | return true; |
4148 | |
4149 | // Translate the parser's template argument list in our AST format. |
4150 | TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
4151 | translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
4152 | |
4153 | if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { |
4154 | assert(SS.getScopeRep() == DTN->getQualifier())(static_cast <bool> (SS.getScopeRep() == DTN->getQualifier ()) ? void (0) : __assert_fail ("SS.getScopeRep() == DTN->getQualifier()" , "clang/lib/Sema/SemaTemplate.cpp", 4154, __extension__ __PRETTY_FUNCTION__ )); |
4155 | QualType T = Context.getDependentTemplateSpecializationType( |
4156 | ETK_None, DTN->getQualifier(), DTN->getIdentifier(), |
4157 | TemplateArgs.arguments()); |
4158 | // Build type-source information. |
4159 | TypeLocBuilder TLB; |
4160 | DependentTemplateSpecializationTypeLoc SpecTL |
4161 | = TLB.push<DependentTemplateSpecializationTypeLoc>(T); |
4162 | SpecTL.setElaboratedKeywordLoc(SourceLocation()); |
4163 | SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4164 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
4165 | SpecTL.setTemplateNameLoc(TemplateIILoc); |
4166 | SpecTL.setLAngleLoc(LAngleLoc); |
4167 | SpecTL.setRAngleLoc(RAngleLoc); |
4168 | for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) |
4169 | SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); |
4170 | return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); |
4171 | } |
4172 | |
4173 | QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); |
4174 | if (SpecTy.isNull()) |
4175 | return true; |
4176 | |
4177 | // Build type-source information. |
4178 | TypeLocBuilder TLB; |
4179 | TemplateSpecializationTypeLoc SpecTL = |
4180 | TLB.push<TemplateSpecializationTypeLoc>(SpecTy); |
4181 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
4182 | SpecTL.setTemplateNameLoc(TemplateIILoc); |
4183 | SpecTL.setLAngleLoc(LAngleLoc); |
4184 | SpecTL.setRAngleLoc(RAngleLoc); |
4185 | for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) |
4186 | SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); |
4187 | |
4188 | // Create an elaborated-type-specifier containing the nested-name-specifier. |
4189 | QualType ElTy = getElaboratedType( |
4190 | ETK_None, !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy); |
4191 | ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy); |
4192 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); |
4193 | if (!ElabTL.isEmpty()) |
4194 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4195 | return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy)); |
4196 | } |
4197 | |
4198 | TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK, |
4199 | TypeSpecifierType TagSpec, |
4200 | SourceLocation TagLoc, |
4201 | CXXScopeSpec &SS, |
4202 | SourceLocation TemplateKWLoc, |
4203 | TemplateTy TemplateD, |
4204 | SourceLocation TemplateLoc, |
4205 | SourceLocation LAngleLoc, |
4206 | ASTTemplateArgsPtr TemplateArgsIn, |
4207 | SourceLocation RAngleLoc) { |
4208 | if (SS.isInvalid()) |
4209 | return TypeResult(true); |
4210 | |
4211 | TemplateName Template = TemplateD.get(); |
4212 | |
4213 | // Translate the parser's template argument list in our AST format. |
4214 | TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
4215 | translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
4216 | |
4217 | // Determine the tag kind |
4218 | TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); |
4219 | ElaboratedTypeKeyword Keyword |
4220 | = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); |
4221 | |
4222 | if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { |
4223 | assert(SS.getScopeRep() == DTN->getQualifier())(static_cast <bool> (SS.getScopeRep() == DTN->getQualifier ()) ? void (0) : __assert_fail ("SS.getScopeRep() == DTN->getQualifier()" , "clang/lib/Sema/SemaTemplate.cpp", 4223, __extension__ __PRETTY_FUNCTION__ )); |
4224 | QualType T = Context.getDependentTemplateSpecializationType( |
4225 | Keyword, DTN->getQualifier(), DTN->getIdentifier(), |
4226 | TemplateArgs.arguments()); |
4227 | |
4228 | // Build type-source information. |
4229 | TypeLocBuilder TLB; |
4230 | DependentTemplateSpecializationTypeLoc SpecTL |
4231 | = TLB.push<DependentTemplateSpecializationTypeLoc>(T); |
4232 | SpecTL.setElaboratedKeywordLoc(TagLoc); |
4233 | SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4234 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
4235 | SpecTL.setTemplateNameLoc(TemplateLoc); |
4236 | SpecTL.setLAngleLoc(LAngleLoc); |
4237 | SpecTL.setRAngleLoc(RAngleLoc); |
4238 | for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) |
4239 | SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); |
4240 | return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); |
4241 | } |
4242 | |
4243 | if (TypeAliasTemplateDecl *TAT = |
4244 | dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) { |
4245 | // C++0x [dcl.type.elab]p2: |
4246 | // If the identifier resolves to a typedef-name or the simple-template-id |
4247 | // resolves to an alias template specialization, the |
4248 | // elaborated-type-specifier is ill-formed. |
4249 | Diag(TemplateLoc, diag::err_tag_reference_non_tag) |
4250 | << TAT << NTK_TypeAliasTemplate << TagKind; |
4251 | Diag(TAT->getLocation(), diag::note_declared_at); |
4252 | } |
4253 | |
4254 | QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); |
4255 | if (Result.isNull()) |
4256 | return TypeResult(true); |
4257 | |
4258 | // Check the tag kind |
4259 | if (const RecordType *RT = Result->getAs<RecordType>()) { |
4260 | RecordDecl *D = RT->getDecl(); |
4261 | |
4262 | IdentifierInfo *Id = D->getIdentifier(); |
4263 | assert(Id && "templated class must have an identifier")(static_cast <bool> (Id && "templated class must have an identifier" ) ? void (0) : __assert_fail ("Id && \"templated class must have an identifier\"" , "clang/lib/Sema/SemaTemplate.cpp", 4263, __extension__ __PRETTY_FUNCTION__ )); |
4264 | |
4265 | if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, |
4266 | TagLoc, Id)) { |
4267 | Diag(TagLoc, diag::err_use_with_wrong_tag) |
4268 | << Result |
4269 | << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); |
4270 | Diag(D->getLocation(), diag::note_previous_use); |
4271 | } |
4272 | } |
4273 | |
4274 | // Provide source-location information for the template specialization. |
4275 | TypeLocBuilder TLB; |
4276 | TemplateSpecializationTypeLoc SpecTL |
4277 | = TLB.push<TemplateSpecializationTypeLoc>(Result); |
4278 | SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
4279 | SpecTL.setTemplateNameLoc(TemplateLoc); |
4280 | SpecTL.setLAngleLoc(LAngleLoc); |
4281 | SpecTL.setRAngleLoc(RAngleLoc); |
4282 | for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) |
4283 | SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); |
4284 | |
4285 | // Construct an elaborated type containing the nested-name-specifier (if any) |
4286 | // and tag keyword. |
4287 | Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result); |
4288 | ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); |
4289 | ElabTL.setElaboratedKeywordLoc(TagLoc); |
4290 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4291 | return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); |
4292 | } |
4293 | |
4294 | static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, |
4295 | NamedDecl *PrevDecl, |
4296 | SourceLocation Loc, |
4297 | bool IsPartialSpecialization); |
4298 | |
4299 | static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D); |
4300 | |
4301 | static bool isTemplateArgumentTemplateParameter( |
4302 | const TemplateArgument &Arg, unsigned Depth, unsigned Index) { |
4303 | switch (Arg.getKind()) { |
4304 | case TemplateArgument::Null: |
4305 | case TemplateArgument::NullPtr: |
4306 | case TemplateArgument::Integral: |
4307 | case TemplateArgument::Declaration: |
4308 | case TemplateArgument::Pack: |
4309 | case TemplateArgument::TemplateExpansion: |
4310 | return false; |
4311 | |
4312 | case TemplateArgument::Type: { |
4313 | QualType Type = Arg.getAsType(); |
4314 | const TemplateTypeParmType *TPT = |
4315 | Arg.getAsType()->getAs<TemplateTypeParmType>(); |
4316 | return TPT && !Type.hasQualifiers() && |
4317 | TPT->getDepth() == Depth && TPT->getIndex() == Index; |
4318 | } |
4319 | |
4320 | case TemplateArgument::Expression: { |
4321 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr()); |
4322 | if (!DRE || !DRE->getDecl()) |
4323 | return false; |
4324 | const NonTypeTemplateParmDecl *NTTP = |
4325 | dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); |
4326 | return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index; |
4327 | } |
4328 | |
4329 | case TemplateArgument::Template: |
4330 | const TemplateTemplateParmDecl *TTP = |
4331 | dyn_cast_or_null<TemplateTemplateParmDecl>( |
4332 | Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()); |
4333 | return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index; |
4334 | } |
4335 | llvm_unreachable("unexpected kind of template argument")::llvm::llvm_unreachable_internal("unexpected kind of template argument" , "clang/lib/Sema/SemaTemplate.cpp", 4335); |
4336 | } |
4337 | |
4338 | static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, |
4339 | ArrayRef<TemplateArgument> Args) { |
4340 | if (Params->size() != Args.size()) |
4341 | return false; |
4342 | |
4343 | unsigned Depth = Params->getDepth(); |
4344 | |
4345 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { |
4346 | TemplateArgument Arg = Args[I]; |
4347 | |
4348 | // If the parameter is a pack expansion, the argument must be a pack |
4349 | // whose only element is a pack expansion. |
4350 | if (Params->getParam(I)->isParameterPack()) { |
4351 | if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 || |
4352 | !Arg.pack_begin()->isPackExpansion()) |
4353 | return false; |
4354 | Arg = Arg.pack_begin()->getPackExpansionPattern(); |
4355 | } |
4356 | |
4357 | if (!isTemplateArgumentTemplateParameter(Arg, Depth, I)) |
4358 | return false; |
4359 | } |
4360 | |
4361 | return true; |
4362 | } |
4363 | |
4364 | template<typename PartialSpecDecl> |
4365 | static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) { |
4366 | if (Partial->getDeclContext()->isDependentContext()) |
4367 | return; |
4368 | |
4369 | // FIXME: Get the TDK from deduction in order to provide better diagnostics |
4370 | // for non-substitution-failure issues? |
4371 | TemplateDeductionInfo Info(Partial->getLocation()); |
4372 | if (S.isMoreSpecializedThanPrimary(Partial, Info)) |
4373 | return; |
4374 | |
4375 | auto *Template = Partial->getSpecializedTemplate(); |
4376 | S.Diag(Partial->getLocation(), |
4377 | diag::ext_partial_spec_not_more_specialized_than_primary) |
4378 | << isa<VarTemplateDecl>(Template); |
4379 | |
4380 | if (Info.hasSFINAEDiagnostic()) { |
4381 | PartialDiagnosticAt Diag = {SourceLocation(), |
4382 | PartialDiagnostic::NullDiagnostic()}; |
4383 | Info.takeSFINAEDiagnostic(Diag); |
4384 | SmallString<128> SFINAEArgString; |
4385 | Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString); |
4386 | S.Diag(Diag.first, |
4387 | diag::note_partial_spec_not_more_specialized_than_primary) |
4388 | << SFINAEArgString; |
4389 | } |
4390 | |
4391 | S.Diag(Template->getLocation(), diag::note_template_decl_here); |
4392 | SmallVector<const Expr *, 3> PartialAC, TemplateAC; |
4393 | Template->getAssociatedConstraints(TemplateAC); |
4394 | Partial->getAssociatedConstraints(PartialAC); |
4395 | S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template, |
4396 | TemplateAC); |
4397 | } |
4398 | |
4399 | static void |
4400 | noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, |
4401 | const llvm::SmallBitVector &DeducibleParams) { |
4402 | for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { |
4403 | if (!DeducibleParams[I]) { |
4404 | NamedDecl *Param = TemplateParams->getParam(I); |
4405 | if (Param->getDeclName()) |
4406 | S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) |
4407 | << Param->getDeclName(); |
4408 | else |
4409 | S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) |
4410 | << "(anonymous)"; |
4411 | } |
4412 | } |
4413 | } |
4414 | |
4415 | |
4416 | template<typename PartialSpecDecl> |
4417 | static void checkTemplatePartialSpecialization(Sema &S, |
4418 | PartialSpecDecl *Partial) { |
4419 | // C++1z [temp.class.spec]p8: (DR1495) |
4420 | // - The specialization shall be more specialized than the primary |
4421 | // template (14.5.5.2). |
4422 | checkMoreSpecializedThanPrimary(S, Partial); |
4423 | |
4424 | // C++ [temp.class.spec]p8: (DR1315) |
4425 | // - Each template-parameter shall appear at least once in the |
4426 | // template-id outside a non-deduced context. |
4427 | // C++1z [temp.class.spec.match]p3 (P0127R2) |
4428 | // If the template arguments of a partial specialization cannot be |
4429 | // deduced because of the structure of its template-parameter-list |
4430 | // and the template-id, the program is ill-formed. |
4431 | auto *TemplateParams = Partial->getTemplateParameters(); |
4432 | llvm::SmallBitVector DeducibleParams(TemplateParams->size()); |
4433 | S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, |
4434 | TemplateParams->getDepth(), DeducibleParams); |
4435 | |
4436 | if (!DeducibleParams.all()) { |
4437 | unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); |
4438 | S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible) |
4439 | << isa<VarTemplatePartialSpecializationDecl>(Partial) |
4440 | << (NumNonDeducible > 1) |
4441 | << SourceRange(Partial->getLocation(), |
4442 | Partial->getTemplateArgsAsWritten()->RAngleLoc); |
4443 | noteNonDeducibleParameters(S, TemplateParams, DeducibleParams); |
4444 | } |
4445 | } |
4446 | |
4447 | void Sema::CheckTemplatePartialSpecialization( |
4448 | ClassTemplatePartialSpecializationDecl *Partial) { |
4449 | checkTemplatePartialSpecialization(*this, Partial); |
4450 | } |
4451 | |
4452 | void Sema::CheckTemplatePartialSpecialization( |
4453 | VarTemplatePartialSpecializationDecl *Partial) { |
4454 | checkTemplatePartialSpecialization(*this, Partial); |
4455 | } |
4456 | |
4457 | void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) { |
4458 | // C++1z [temp.param]p11: |
4459 | // A template parameter of a deduction guide template that does not have a |
4460 | // default-argument shall be deducible from the parameter-type-list of the |
4461 | // deduction guide template. |
4462 | auto *TemplateParams = TD->getTemplateParameters(); |
4463 | llvm::SmallBitVector DeducibleParams(TemplateParams->size()); |
4464 | MarkDeducedTemplateParameters(TD, DeducibleParams); |
4465 | for (unsigned I = 0; I != TemplateParams->size(); ++I) { |
4466 | // A parameter pack is deducible (to an empty pack). |
4467 | auto *Param = TemplateParams->getParam(I); |
4468 | if (Param->isParameterPack() || hasVisibleDefaultArgument(Param)) |
4469 | DeducibleParams[I] = true; |
4470 | } |
4471 | |
4472 | if (!DeducibleParams.all()) { |
4473 | unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); |
4474 | Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible) |
4475 | << (NumNonDeducible > 1); |
4476 | noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams); |
4477 | } |
4478 | } |
4479 | |
4480 | DeclResult Sema::ActOnVarTemplateSpecialization( |
4481 | Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, |
4482 | TemplateParameterList *TemplateParams, StorageClass SC, |
4483 | bool IsPartialSpecialization) { |
4484 | // D must be variable template id. |
4485 | assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&(static_cast <bool> (D.getName().getKind() == UnqualifiedIdKind ::IK_TemplateId && "Variable template specialization is declared with a template id." ) ? void (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template id.\"" , "clang/lib/Sema/SemaTemplate.cpp", 4486, __extension__ __PRETTY_FUNCTION__ )) |
4486 | "Variable template specialization is declared with a template id.")(static_cast <bool> (D.getName().getKind() == UnqualifiedIdKind ::IK_TemplateId && "Variable template specialization is declared with a template id." ) ? void (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template id.\"" , "clang/lib/Sema/SemaTemplate.cpp", 4486, __extension__ __PRETTY_FUNCTION__ )); |
4487 | |
4488 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; |
4489 | TemplateArgumentListInfo TemplateArgs = |
4490 | makeTemplateArgumentListInfo(*this, *TemplateId); |
4491 | SourceLocation TemplateNameLoc = D.getIdentifierLoc(); |
4492 | SourceLocation LAngleLoc = TemplateId->LAngleLoc; |
4493 | SourceLocation RAngleLoc = TemplateId->RAngleLoc; |
4494 | |
4495 | TemplateName Name = TemplateId->Template.get(); |
4496 | |
4497 | // The template-id must name a variable template. |
4498 | VarTemplateDecl *VarTemplate = |
4499 | dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl()); |
4500 | if (!VarTemplate) { |
4501 | NamedDecl *FnTemplate; |
4502 | if (auto *OTS = Name.getAsOverloadedTemplate()) |
4503 | FnTemplate = *OTS->begin(); |
4504 | else |
4505 | FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl()); |
4506 | if (FnTemplate) |
4507 | return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method) |
4508 | << FnTemplate->getDeclName(); |
4509 | return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) |
4510 | << IsPartialSpecialization; |
4511 | } |
4512 | |
4513 | // Check for unexpanded parameter packs in any of the template arguments. |
4514 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
4515 | if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], |
4516 | UPPC_PartialSpecialization)) |
4517 | return true; |
4518 | |
4519 | // Check that the template argument list is well-formed for this |
4520 | // template. |
4521 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
4522 | if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs, |
4523 | false, SugaredConverted, CanonicalConverted, |
4524 | /*UpdateArgsWithConversions=*/true)) |
4525 | return true; |
4526 | |
4527 | // Find the variable template (partial) specialization declaration that |
4528 | // corresponds to these arguments. |
4529 | if (IsPartialSpecialization) { |
4530 | if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate, |
4531 | TemplateArgs.size(), |
4532 | CanonicalConverted)) |
4533 | return true; |
4534 | |
4535 | // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we |
4536 | // also do them during instantiation. |
4537 | if (!Name.isDependent() && |
4538 | !TemplateSpecializationType::anyDependentTemplateArguments( |
4539 | TemplateArgs, CanonicalConverted)) { |
4540 | Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) |
4541 | << VarTemplate->getDeclName(); |
4542 | IsPartialSpecialization = false; |
4543 | } |
4544 | |
4545 | if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(), |
4546 | CanonicalConverted) && |
4547 | (!Context.getLangOpts().CPlusPlus20 || |
4548 | !TemplateParams->hasAssociatedConstraints())) { |
4549 | // C++ [temp.class.spec]p9b3: |
4550 | // |
4551 | // -- The argument list of the specialization shall not be identical |
4552 | // to the implicit argument list of the primary template. |
4553 | Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) |
4554 | << /*variable template*/ 1 |
4555 | << /*is definition*/(SC != SC_Extern && !CurContext->isRecord()) |
4556 | << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); |
4557 | // FIXME: Recover from this by treating the declaration as a redeclaration |
4558 | // of the primary template. |
4559 | return true; |
4560 | } |
4561 | } |
4562 | |
4563 | void *InsertPos = nullptr; |
4564 | VarTemplateSpecializationDecl *PrevDecl = nullptr; |
4565 | |
4566 | if (IsPartialSpecialization) |
4567 | PrevDecl = VarTemplate->findPartialSpecialization( |
4568 | CanonicalConverted, TemplateParams, InsertPos); |
4569 | else |
4570 | PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos); |
4571 | |
4572 | VarTemplateSpecializationDecl *Specialization = nullptr; |
4573 | |
4574 | // Check whether we can declare a variable template specialization in |
4575 | // the current scope. |
4576 | if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl, |
4577 | TemplateNameLoc, |
4578 | IsPartialSpecialization)) |
4579 | return true; |
4580 | |
4581 | if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) { |
4582 | // Since the only prior variable template specialization with these |
4583 | // arguments was referenced but not declared, reuse that |
4584 | // declaration node as our own, updating its source location and |
4585 | // the list of outer template parameters to reflect our new declaration. |
4586 | Specialization = PrevDecl; |
4587 | Specialization->setLocation(TemplateNameLoc); |
4588 | PrevDecl = nullptr; |
4589 | } else if (IsPartialSpecialization) { |
4590 | // Create a new class template partial specialization declaration node. |
4591 | VarTemplatePartialSpecializationDecl *PrevPartial = |
4592 | cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl); |
4593 | VarTemplatePartialSpecializationDecl *Partial = |
4594 | VarTemplatePartialSpecializationDecl::Create( |
4595 | Context, VarTemplate->getDeclContext(), TemplateKWLoc, |
4596 | TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC, |
4597 | CanonicalConverted, TemplateArgs); |
4598 | |
4599 | if (!PrevPartial) |
4600 | VarTemplate->AddPartialSpecialization(Partial, InsertPos); |
4601 | Specialization = Partial; |
4602 | |
4603 | // If we are providing an explicit specialization of a member variable |
4604 | // template specialization, make a note of that. |
4605 | if (PrevPartial && PrevPartial->getInstantiatedFromMember()) |
4606 | PrevPartial->setMemberSpecialization(); |
4607 | |
4608 | CheckTemplatePartialSpecialization(Partial); |
4609 | } else { |
4610 | // Create a new class template specialization declaration node for |
4611 | // this explicit specialization or friend declaration. |
4612 | Specialization = VarTemplateSpecializationDecl::Create( |
4613 | Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc, |
4614 | VarTemplate, DI->getType(), DI, SC, CanonicalConverted); |
4615 | Specialization->setTemplateArgsInfo(TemplateArgs); |
4616 | |
4617 | if (!PrevDecl) |
4618 | VarTemplate->AddSpecialization(Specialization, InsertPos); |
4619 | } |
4620 | |
4621 | // C++ [temp.expl.spec]p6: |
4622 | // If a template, a member template or the member of a class template is |
4623 | // explicitly specialized then that specialization shall be declared |
4624 | // before the first use of that specialization that would cause an implicit |
4625 | // instantiation to take place, in every translation unit in which such a |
4626 | // use occurs; no diagnostic is required. |
4627 | if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { |
4628 | bool Okay = false; |
4629 | for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { |
4630 | // Is there any previous explicit specialization declaration? |
4631 | if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { |
4632 | Okay = true; |
4633 | break; |
4634 | } |
4635 | } |
4636 | |
4637 | if (!Okay) { |
4638 | SourceRange Range(TemplateNameLoc, RAngleLoc); |
4639 | Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) |
4640 | << Name << Range; |
4641 | |
4642 | Diag(PrevDecl->getPointOfInstantiation(), |
4643 | diag::note_instantiation_required_here) |
4644 | << (PrevDecl->getTemplateSpecializationKind() != |
4645 | TSK_ImplicitInstantiation); |
4646 | return true; |
4647 | } |
4648 | } |
4649 | |
4650 | Specialization->setTemplateKeywordLoc(TemplateKWLoc); |
4651 | Specialization->setLexicalDeclContext(CurContext); |
4652 | |
4653 | // Add the specialization into its lexical context, so that it can |
4654 | // be seen when iterating through the list of declarations in that |
4655 | // context. However, specializations are not found by name lookup. |
4656 | CurContext->addDecl(Specialization); |
4657 | |
4658 | // Note that this is an explicit specialization. |
4659 | Specialization->setSpecializationKind(TSK_ExplicitSpecialization); |
4660 | |
4661 | if (PrevDecl) { |
4662 | // Check that this isn't a redefinition of this specialization, |
4663 | // merging with previous declarations. |
4664 | LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName, |
4665 | forRedeclarationInCurContext()); |
4666 | PrevSpec.addDecl(PrevDecl); |
4667 | D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec)); |
4668 | } else if (Specialization->isStaticDataMember() && |
4669 | Specialization->isOutOfLine()) { |
4670 | Specialization->setAccess(VarTemplate->getAccess()); |
4671 | } |
4672 | |
4673 | return Specialization; |
4674 | } |
4675 | |
4676 | namespace { |
4677 | /// A partial specialization whose template arguments have matched |
4678 | /// a given template-id. |
4679 | struct PartialSpecMatchResult { |
4680 | VarTemplatePartialSpecializationDecl *Partial; |
4681 | TemplateArgumentList *Args; |
4682 | }; |
4683 | } // end anonymous namespace |
4684 | |
4685 | DeclResult |
4686 | Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, |
4687 | SourceLocation TemplateNameLoc, |
4688 | const TemplateArgumentListInfo &TemplateArgs) { |
4689 | assert(Template && "A variable template id without template?")(static_cast <bool> (Template && "A variable template id without template?" ) ? void (0) : __assert_fail ("Template && \"A variable template id without template?\"" , "clang/lib/Sema/SemaTemplate.cpp", 4689, __extension__ __PRETTY_FUNCTION__ )); |
4690 | |
4691 | // Check that the template argument list is well-formed for this template. |
4692 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
4693 | if (CheckTemplateArgumentList( |
4694 | Template, TemplateNameLoc, |
4695 | const_cast<TemplateArgumentListInfo &>(TemplateArgs), false, |
4696 | SugaredConverted, CanonicalConverted, |
4697 | /*UpdateArgsWithConversions=*/true)) |
4698 | return true; |
4699 | |
4700 | // Produce a placeholder value if the specialization is dependent. |
4701 | if (Template->getDeclContext()->isDependentContext() || |
4702 | TemplateSpecializationType::anyDependentTemplateArguments( |
4703 | TemplateArgs, CanonicalConverted)) |
4704 | return DeclResult(); |
4705 | |
4706 | // Find the variable template specialization declaration that |
4707 | // corresponds to these arguments. |
4708 | void *InsertPos = nullptr; |
4709 | if (VarTemplateSpecializationDecl *Spec = |
4710 | Template->findSpecialization(CanonicalConverted, InsertPos)) { |
4711 | checkSpecializationReachability(TemplateNameLoc, Spec); |
4712 | // If we already have a variable template specialization, return it. |
4713 | return Spec; |
4714 | } |
4715 | |
4716 | // This is the first time we have referenced this variable template |
4717 | // specialization. Create the canonical declaration and add it to |
4718 | // the set of specializations, based on the closest partial specialization |
4719 | // that it represents. That is, |
4720 | VarDecl *InstantiationPattern = Template->getTemplatedDecl(); |
4721 | TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack, |
4722 | CanonicalConverted); |
4723 | TemplateArgumentList *InstantiationArgs = &TemplateArgList; |
4724 | bool AmbiguousPartialSpec = false; |
4725 | typedef PartialSpecMatchResult MatchResult; |
4726 | SmallVector<MatchResult, 4> Matched; |
4727 | SourceLocation PointOfInstantiation = TemplateNameLoc; |
4728 | TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation, |
4729 | /*ForTakingAddress=*/false); |
4730 | |
4731 | // 1. Attempt to find the closest partial specialization that this |
4732 | // specializes, if any. |
4733 | // TODO: Unify with InstantiateClassTemplateSpecialization()? |
4734 | // Perhaps better after unification of DeduceTemplateArguments() and |
4735 | // getMoreSpecializedPartialSpecialization(). |
4736 | SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
4737 | Template->getPartialSpecializations(PartialSpecs); |
4738 | |
4739 | for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { |
4740 | VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; |
4741 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
4742 | |
4743 | if (TemplateDeductionResult Result = |
4744 | DeduceTemplateArguments(Partial, TemplateArgList, Info)) { |
4745 | // Store the failed-deduction information for use in diagnostics, later. |
4746 | // TODO: Actually use the failed-deduction info? |
4747 | FailedCandidates.addCandidate().set( |
4748 | DeclAccessPair::make(Template, AS_public), Partial, |
4749 | MakeDeductionFailureInfo(Context, Result, Info)); |
4750 | (void)Result; |
4751 | } else { |
4752 | Matched.push_back(PartialSpecMatchResult()); |
4753 | Matched.back().Partial = Partial; |
4754 | Matched.back().Args = Info.takeCanonical(); |
4755 | } |
4756 | } |
4757 | |
4758 | if (Matched.size() >= 1) { |
4759 | SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); |
4760 | if (Matched.size() == 1) { |
4761 | // -- If exactly one matching specialization is found, the |
4762 | // instantiation is generated from that specialization. |
4763 | // We don't need to do anything for this. |
4764 | } else { |
4765 | // -- If more than one matching specialization is found, the |
4766 | // partial order rules (14.5.4.2) are used to determine |
4767 | // whether one of the specializations is more specialized |
4768 | // than the others. If none of the specializations is more |
4769 | // specialized than all of the other matching |
4770 | // specializations, then the use of the variable template is |
4771 | // ambiguous and the program is ill-formed. |
4772 | for (SmallVector<MatchResult, 4>::iterator P = Best + 1, |
4773 | PEnd = Matched.end(); |
4774 | P != PEnd; ++P) { |
4775 | if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial, |
4776 | PointOfInstantiation) == |
4777 | P->Partial) |
4778 | Best = P; |
4779 | } |
4780 | |
4781 | // Determine if the best partial specialization is more specialized than |
4782 | // the others. |
4783 | for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), |
4784 | PEnd = Matched.end(); |
4785 | P != PEnd; ++P) { |
4786 | if (P != Best && getMoreSpecializedPartialSpecialization( |
4787 | P->Partial, Best->Partial, |
4788 | PointOfInstantiation) != Best->Partial) { |
4789 | AmbiguousPartialSpec = true; |
4790 | break; |
4791 | } |
4792 | } |
4793 | } |
4794 | |
4795 | // Instantiate using the best variable template partial specialization. |
4796 | InstantiationPattern = Best->Partial; |
4797 | InstantiationArgs = Best->Args; |
4798 | } else { |
4799 | // -- If no match is found, the instantiation is generated |
4800 | // from the primary template. |
4801 | // InstantiationPattern = Template->getTemplatedDecl(); |
4802 | } |
4803 | |
4804 | // 2. Create the canonical declaration. |
4805 | // Note that we do not instantiate a definition until we see an odr-use |
4806 | // in DoMarkVarDeclReferenced(). |
4807 | // FIXME: LateAttrs et al.? |
4808 | VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation( |
4809 | Template, InstantiationPattern, *InstantiationArgs, TemplateArgs, |
4810 | CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/); |
4811 | if (!Decl) |
4812 | return true; |
4813 | |
4814 | if (AmbiguousPartialSpec) { |
4815 | // Partial ordering did not produce a clear winner. Complain. |
4816 | Decl->setInvalidDecl(); |
4817 | Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) |
4818 | << Decl; |
4819 | |
4820 | // Print the matching partial specializations. |
4821 | for (MatchResult P : Matched) |
4822 | Diag(P.Partial->getLocation(), diag::note_partial_spec_match) |
4823 | << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(), |
4824 | *P.Args); |
4825 | return true; |
4826 | } |
4827 | |
4828 | if (VarTemplatePartialSpecializationDecl *D = |
4829 | dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern)) |
4830 | Decl->setInstantiationOf(D, InstantiationArgs); |
4831 | |
4832 | checkSpecializationReachability(TemplateNameLoc, Decl); |
4833 | |
4834 | assert(Decl && "No variable template specialization?")(static_cast <bool> (Decl && "No variable template specialization?" ) ? void (0) : __assert_fail ("Decl && \"No variable template specialization?\"" , "clang/lib/Sema/SemaTemplate.cpp", 4834, __extension__ __PRETTY_FUNCTION__ )); |
4835 | return Decl; |
4836 | } |
4837 | |
4838 | ExprResult |
4839 | Sema::CheckVarTemplateId(const CXXScopeSpec &SS, |
4840 | const DeclarationNameInfo &NameInfo, |
4841 | VarTemplateDecl *Template, SourceLocation TemplateLoc, |
4842 | const TemplateArgumentListInfo *TemplateArgs) { |
4843 | |
4844 | DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(), |
4845 | *TemplateArgs); |
4846 | if (Decl.isInvalid()) |
4847 | return ExprError(); |
4848 | |
4849 | if (!Decl.get()) |
4850 | return ExprResult(); |
4851 | |
4852 | VarDecl *Var = cast<VarDecl>(Decl.get()); |
4853 | if (!Var->getTemplateSpecializationKind()) |
4854 | Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation, |
4855 | NameInfo.getLoc()); |
4856 | |
4857 | // Build an ordinary singleton decl ref. |
4858 | return BuildDeclarationNameExpr(SS, NameInfo, Var, |
4859 | /*FoundD=*/nullptr, TemplateArgs); |
4860 | } |
4861 | |
4862 | void Sema::diagnoseMissingTemplateArguments(TemplateName Name, |
4863 | SourceLocation Loc) { |
4864 | Diag(Loc, diag::err_template_missing_args) |
4865 | << (int)getTemplateNameKindForDiagnostics(Name) << Name; |
4866 | if (TemplateDecl *TD = Name.getAsTemplateDecl()) { |
4867 | Diag(TD->getLocation(), diag::note_template_decl_here) |
4868 | << TD->getTemplateParameters()->getSourceRange(); |
4869 | } |
4870 | } |
4871 | |
4872 | ExprResult |
4873 | Sema::CheckConceptTemplateId(const CXXScopeSpec &SS, |
4874 | SourceLocation TemplateKWLoc, |
4875 | const DeclarationNameInfo &ConceptNameInfo, |
4876 | NamedDecl *FoundDecl, |
4877 | ConceptDecl *NamedConcept, |
4878 | const TemplateArgumentListInfo *TemplateArgs) { |
4879 | assert(NamedConcept && "A concept template id without a template?")(static_cast <bool> (NamedConcept && "A concept template id without a template?" ) ? void (0) : __assert_fail ("NamedConcept && \"A concept template id without a template?\"" , "clang/lib/Sema/SemaTemplate.cpp", 4879, __extension__ __PRETTY_FUNCTION__ )); |
4880 | |
4881 | llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
4882 | if (CheckTemplateArgumentList( |
4883 | NamedConcept, ConceptNameInfo.getLoc(), |
4884 | const_cast<TemplateArgumentListInfo &>(*TemplateArgs), |
4885 | /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted, |
4886 | /*UpdateArgsWithConversions=*/false)) |
4887 | return ExprError(); |
4888 | |
4889 | auto *CSD = ImplicitConceptSpecializationDecl::Create( |
4890 | Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(), |
4891 | CanonicalConverted); |
4892 | ConstraintSatisfaction Satisfaction; |
4893 | bool AreArgsDependent = |
4894 | TemplateSpecializationType::anyDependentTemplateArguments( |
4895 | *TemplateArgs, CanonicalConverted); |
4896 | MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted, |
4897 | /*Final=*/false); |
4898 | LocalInstantiationScope Scope(*this); |
4899 | |
4900 | EnterExpressionEvaluationContext EECtx{ |
4901 | *this, ExpressionEvaluationContext::ConstantEvaluated, CSD}; |
4902 | |
4903 | if (!AreArgsDependent && |
4904 | CheckConstraintSatisfaction( |
4905 | NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL, |
4906 | SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(), |
4907 | TemplateArgs->getRAngleLoc()), |
4908 | Satisfaction)) |
4909 | return ExprError(); |
4910 | |
4911 | return ConceptSpecializationExpr::Create( |
4912 | Context, |
4913 | SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{}, |
4914 | TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept, |
4915 | ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), CSD, |
4916 | AreArgsDependent ? nullptr : &Satisfaction); |
4917 | } |
4918 | |
4919 | ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, |
4920 | SourceLocation TemplateKWLoc, |
4921 | LookupResult &R, |
4922 | bool RequiresADL, |
4923 | const TemplateArgumentListInfo *TemplateArgs) { |
4924 | // FIXME: Can we do any checking at this point? I guess we could check the |
4925 | // template arguments that we have against the template name, if the template |
4926 | // name refers to a single template. That's not a terribly common case, |
4927 | // though. |
4928 | // foo<int> could identify a single function unambiguously |
4929 | // This approach does NOT work, since f<int>(1); |
4930 | // gets resolved prior to resorting to overload resolution |
4931 | // i.e., template<class T> void f(double); |
4932 | // vs template<class T, class U> void f(U); |
4933 | |
4934 | // These should be filtered out by our callers. |
4935 | assert(!R.isAmbiguous() && "ambiguous lookup when building templateid")(static_cast <bool> (!R.isAmbiguous() && "ambiguous lookup when building templateid" ) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"ambiguous lookup when building templateid\"" , "clang/lib/Sema/SemaTemplate.cpp", 4935, __extension__ __PRETTY_FUNCTION__ )); |
4936 | |
4937 | // Non-function templates require a template argument list. |
4938 | if (auto *TD = R.getAsSingle<TemplateDecl>()) { |
4939 | if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) { |
4940 | diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc()); |
4941 | return ExprError(); |
4942 | } |
4943 | } |
4944 | |
4945 | // In C++1y, check variable template ids. |
4946 | if (R.getAsSingle<VarTemplateDecl>()) { |
4947 | ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(), |
4948 | R.getAsSingle<VarTemplateDecl>(), |
4949 | TemplateKWLoc, TemplateArgs); |
4950 | if (Res.isInvalid() || Res.isUsable()) |
4951 | return Res; |
4952 | // Result is dependent. Carry on to build an UnresolvedLookupEpxr. |
4953 | } |
4954 | |
4955 | if (R.getAsSingle<ConceptDecl>()) { |
4956 | return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(), |
4957 | R.getFoundDecl(), |
4958 | R.getAsSingle<ConceptDecl>(), TemplateArgs); |
4959 | } |
4960 | |
4961 | // We don't want lookup warnings at this point. |
4962 | R.suppressDiagnostics(); |
4963 | |
4964 | UnresolvedLookupExpr *ULE |
4965 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), |
4966 | SS.getWithLocInContext(Context), |
4967 | TemplateKWLoc, |
4968 | R.getLookupNameInfo(), |
4969 | RequiresADL, TemplateArgs, |
4970 | R.begin(), R.end()); |
4971 | |
4972 | return ULE; |
4973 | } |
4974 | |
4975 | // We actually only call this from template instantiation. |
4976 | ExprResult |
4977 | Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, |
4978 | SourceLocation TemplateKWLoc, |
4979 | const DeclarationNameInfo &NameInfo, |
4980 | const TemplateArgumentListInfo *TemplateArgs) { |
4981 | |
4982 | assert(TemplateArgs || TemplateKWLoc.isValid())(static_cast <bool> (TemplateArgs || TemplateKWLoc.isValid ()) ? void (0) : __assert_fail ("TemplateArgs || TemplateKWLoc.isValid()" , "clang/lib/Sema/SemaTemplate.cpp", 4982, __extension__ __PRETTY_FUNCTION__ )); |
4983 | DeclContext *DC; |
4984 | if (!(DC = computeDeclContext(SS, false)) || |
4985 | DC->isDependentContext() || |
4986 | RequireCompleteDeclContext(SS, DC)) |
4987 | return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); |
4988 | |
4989 | bool MemberOfUnknownSpecialization; |
4990 | LookupResult R(*this, NameInfo, LookupOrdinaryName); |
4991 | if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(), |
4992 | /*Entering*/false, MemberOfUnknownSpecialization, |
4993 | TemplateKWLoc)) |
4994 | return ExprError(); |
4995 | |
4996 | if (R.isAmbiguous()) |
4997 | return ExprError(); |
4998 | |
4999 | if (R.empty()) { |
5000 | Diag(NameInfo.getLoc(), diag::err_no_member) |
5001 | << NameInfo.getName() << DC << SS.getRange(); |
5002 | return ExprError(); |
5003 | } |
5004 | |
5005 | if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) { |
5006 | Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template) |
5007 | << SS.getScopeRep() |
5008 | << NameInfo.getName().getAsString() << SS.getRange(); |
5009 | Diag(Temp->getLocation(), diag::note_referenced_class_template); |
5010 | return ExprError(); |
5011 | } |
5012 | |
5013 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs); |
5014 | } |
5015 | |
5016 | /// Form a template name from a name that is syntactically required to name a |
5017 | /// template, either due to use of the 'template' keyword or because a name in |
5018 | /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4). |
5019 | /// |
5020 | /// This action forms a template name given the name of the template and its |
5021 | /// optional scope specifier. This is used when the 'template' keyword is used |
5022 | /// or when the parsing context unambiguously treats a following '<' as |
5023 | /// introducing a template argument list. Note that this may produce a |
5024 | /// non-dependent template name if we can perform the lookup now and identify |
5025 | /// the named template. |
5026 | /// |
5027 | /// For example, given "x.MetaFun::template apply", the scope specifier |
5028 | /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location |
5029 | /// of the "template" keyword, and "apply" is the \p Name. |
5030 | TemplateNameKind Sema::ActOnTemplateName(Scope *S, |
5031 | CXXScopeSpec &SS, |
5032 | SourceLocation TemplateKWLoc, |
5033 | const UnqualifiedId &Name, |
5034 | ParsedType ObjectType, |
5035 | bool EnteringContext, |
5036 | TemplateTy &Result, |
5037 | bool AllowInjectedClassName) { |
5038 | if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent()) |
5039 | Diag(TemplateKWLoc, |
5040 | getLangOpts().CPlusPlus11 ? |
5041 | diag::warn_cxx98_compat_template_outside_of_template : |
5042 | diag::ext_template_outside_of_template) |
5043 | << FixItHint::CreateRemoval(TemplateKWLoc); |
5044 | |
5045 | if (SS.isInvalid()) |
5046 | return TNK_Non_template; |
5047 | |
5048 | // Figure out where isTemplateName is going to look. |
5049 | DeclContext *LookupCtx = nullptr; |
5050 | if (SS.isNotEmpty()) |
5051 | LookupCtx = computeDeclContext(SS, EnteringContext); |
5052 | else if (ObjectType) |
5053 | LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType)); |
5054 | |
5055 | // C++0x [temp.names]p5: |
5056 | // If a name prefixed by the keyword template is not the name of |
5057 | // a template, the program is ill-formed. [Note: the keyword |
5058 | // template may not be applied to non-template members of class |
5059 | // templates. -end note ] [ Note: as is the case with the |
5060 | // typename prefix, the template prefix is allowed in cases |
5061 | // where it is not strictly necessary; i.e., when the |
5062 | // nested-name-specifier or the expression on the left of the -> |
5063 | // or . is not dependent on a template-parameter, or the use |
5064 | // does not appear in the scope of a template. -end note] |
5065 | // |
5066 | // Note: C++03 was more strict here, because it banned the use of |
5067 | // the "template" keyword prior to a template-name that was not a |
5068 | // dependent name. C++ DR468 relaxed this requirement (the |
5069 | // "template" keyword is now permitted). We follow the C++0x |
5070 | // rules, even in C++03 mode with a warning, retroactively applying the DR. |
5071 | bool MemberOfUnknownSpecialization; |
5072 | TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name, |
5073 | ObjectType, EnteringContext, Result, |
5074 | MemberOfUnknownSpecialization); |
5075 | if (TNK != TNK_Non_template) { |
5076 | // We resolved this to a (non-dependent) template name. Return it. |
5077 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); |
5078 | if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD && |
5079 | Name.getKind() == UnqualifiedIdKind::IK_Identifier && |
5080 | Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) { |
5081 | // C++14 [class.qual]p2: |
5082 | // In a lookup in which function names are not ignored and the |
5083 | // nested-name-specifier nominates a class C, if the name specified |
5084 | // [...] is the injected-class-name of C, [...] the name is instead |
5085 | // considered to name the constructor |
5086 | // |
5087 | // We don't get here if naming the constructor would be valid, so we |
5088 | // just reject immediately and recover by treating the |
5089 | // injected-class-name as naming the template. |
5090 | Diag(Name.getBeginLoc(), |
5091 | diag::ext_out_of_line_qualified_id_type_names_constructor) |
5092 | << Name.Identifier |
5093 | << 0 /*injected-class-name used as template name*/ |
5094 | << TemplateKWLoc.isValid(); |
5095 | } |
5096 | return TNK; |
5097 | } |
5098 | |
5099 | if (!MemberOfUnknownSpecialization) { |
5100 | // Didn't find a template name, and the lookup wasn't dependent. |
5101 | // Do the lookup again to determine if this is a "nothing found" case or |
5102 | // a "not a template" case. FIXME: Refactor isTemplateName so we don't |
5103 | // need to do this. |
5104 | DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name); |
5105 | LookupResult R(*this, DNI.getName(), Name.getBeginLoc(), |
5106 | LookupOrdinaryName); |
5107 | bool MOUS; |
5108 | // Tell LookupTemplateName that we require a template so that it diagnoses |
5109 | // cases where it finds a non-template. |
5110 | RequiredTemplateKind RTK = TemplateKWLoc.isValid() |
5111 | ? RequiredTemplateKind(TemplateKWLoc) |
5112 | : TemplateNameIsRequired; |
5113 | if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS, |
5114 | RTK, nullptr, /*AllowTypoCorrection=*/false) && |
5115 | !R.isAmbiguous()) { |
5116 | if (LookupCtx) |
5117 | Diag(Name.getBeginLoc(), diag::err_no_member) |
5118 | << DNI.getName() << LookupCtx << SS.getRange(); |
5119 | else |
5120 | Diag(Name.getBeginLoc(), diag::err_undeclared_use) |
5121 | << DNI.getName() << SS.getRange(); |
5122 | } |
5123 | return TNK_Non_template; |
5124 | } |
5125 | |
5126 | NestedNameSpecifier *Qualifier = SS.getScopeRep(); |
5127 | |
5128 | switch (Name.getKind()) { |
5129 | case UnqualifiedIdKind::IK_Identifier: |
5130 | Result = TemplateTy::make( |
5131 | Context.getDependentTemplateName(Qualifier, Name.Identifier)); |
5132 | return TNK_Dependent_template_name; |
5133 | |
5134 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
5135 | Result = TemplateTy::make(Context.getDependentTemplateName( |
5136 | Qualifier, Name.OperatorFunctionId.Operator)); |
5137 | return TNK_Function_template; |
5138 | |
5139 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
5140 | // This is a kind of template name, but can never occur in a dependent |
5141 | // scope (literal operators can only be declared at namespace scope). |
5142 | break; |
5143 | |
5144 | default: |
5145 | break; |
5146 | } |
5147 | |
5148 | // This name cannot possibly name a dependent template. Diagnose this now |
5149 | // rather than building a dependent template name that can never be valid. |
5150 | Diag(Name.getBeginLoc(), |
5151 | diag::err_template_kw_refers_to_dependent_non_template) |
5152 | << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange() |
5153 | << TemplateKWLoc.isValid() << TemplateKWLoc; |
5154 | return TNK_Non_template; |
5155 | } |
5156 | |
5157 | bool Sema::CheckTemplateTypeArgument( |
5158 | TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL, |
5159 | SmallVectorImpl<TemplateArgument> &SugaredConverted, |
5160 | SmallVectorImpl<TemplateArgument> &CanonicalConverted) { |
5161 | const TemplateArgument &Arg = AL.getArgument(); |
5162 | QualType ArgType; |
5163 | TypeSourceInfo *TSI = nullptr; |
5164 | |
5165 | // Check template type parameter. |
5166 | switch(Arg.getKind()) { |
5167 | case TemplateArgument::Type: |
5168 | // C++ [temp.arg.type]p1: |
5169 | // A template-argument for a template-parameter which is a |
5170 | // type shall be a type-id. |
5171 | ArgType = Arg.getAsType(); |
5172 | TSI = AL.getTypeSourceInfo(); |
5173 | break; |
5174 | case TemplateArgument::Template: |
5175 | case TemplateArgument::TemplateExpansion: { |
5176 | // We have a template type parameter but the template argument |
5177 | // is a template without any arguments. |
5178 | SourceRange SR = AL.getSourceRange(); |
5179 | TemplateName Name = Arg.getAsTemplateOrTemplatePattern(); |
5180 | diagnoseMissingTemplateArguments(Name, SR.getEnd()); |
5181 | return true; |
5182 | } |
5183 | case TemplateArgument::Expression: { |
5184 | // We have a template type parameter but the template argument is an |
5185 | // expression; see if maybe it is missing the "typename" keyword. |
5186 | CXXScopeSpec SS; |
5187 | DeclarationNameInfo NameInfo; |
5188 | |
5189 | if (DependentScopeDeclRefExpr *ArgExpr = |
5190 | dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) { |
5191 | SS.Adopt(ArgExpr->getQualifierLoc()); |
5192 | NameInfo = ArgExpr->getNameInfo(); |
5193 | } else if (CXXDependentScopeMemberExpr *ArgExpr = |
5194 | dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) { |
5195 | if (ArgExpr->isImplicitAccess()) { |
5196 | SS.Adopt(ArgExpr->getQualifierLoc()); |
5197 | NameInfo = ArgExpr->getMemberNameInfo(); |
5198 | } |
5199 | } |
5200 | |
5201 | if (auto *II = NameInfo.getName().getAsIdentifierInfo()) { |
5202 | LookupResult Result(*this, NameInfo, LookupOrdinaryName); |
5203 | LookupParsedName(Result, CurScope, &SS); |
5204 | |
5205 | if (Result.getAsSingle<TypeDecl>() || |
5206 | Result.getResultKind() == |
5207 | LookupResult::NotFoundInCurrentInstantiation) { |
5208 | assert(SS.getScopeRep() && "dependent scope expr must has a scope!")(static_cast <bool> (SS.getScopeRep() && "dependent scope expr must has a scope!" ) ? void (0) : __assert_fail ("SS.getScopeRep() && \"dependent scope expr must has a scope!\"" , "clang/lib/Sema/SemaTemplate.cpp", 5208, __extension__ __PRETTY_FUNCTION__ )); |
5209 | // Suggest that the user add 'typename' before the NNS. |
5210 | SourceLocation Loc = AL.getSourceRange().getBegin(); |
5211 | Diag(Loc, getLangOpts().MSVCCompat |
5212 | ? diag::ext_ms_template_type_arg_missing_typename |
5213 | : diag::err_template_arg_must_be_type_suggest) |
5214 | << FixItHint::CreateInsertion(Loc, "typename "); |
5215 | Diag(Param->getLocation(), diag::note_template_param_here); |
5216 | |
5217 | // Recover by synthesizing a type using the location information that we |
5218 | // already have. |
5219 | ArgType = |
5220 | Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II); |
5221 | TypeLocBuilder TLB; |
5222 | DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType); |
5223 | TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/)); |
5224 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
5225 | TL.setNameLoc(NameInfo.getLoc()); |
5226 | TSI = TLB.getTypeSourceInfo(Context, ArgType); |
5227 | |
5228 | // Overwrite our input TemplateArgumentLoc so that we can recover |
5229 | // properly. |
5230 | AL = TemplateArgumentLoc(TemplateArgument(ArgType), |
5231 | TemplateArgumentLocInfo(TSI)); |
5232 | |
5233 | break; |
5234 | } |
5235 | } |
5236 | // fallthrough |
5237 | [[fallthrough]]; |
5238 | } |
5239 | default: { |
5240 | // We have a template type parameter but the template argument |
5241 | // is not a type. |
5242 | SourceRange SR = AL.getSourceRange(); |
5243 | Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; |
5244 | Diag(Param->getLocation(), diag::note_template_param_here); |
5245 | |
5246 | return true; |
5247 | } |
5248 | } |
5249 | |
5250 | if (CheckTemplateArgument(TSI)) |
5251 | return true; |
5252 | |
5253 | // Objective-C ARC: |
5254 | // If an explicitly-specified template argument type is a lifetime type |
5255 | // with no lifetime qualifier, the __strong lifetime qualifier is inferred. |
5256 | if (getLangOpts().ObjCAutoRefCount && |
5257 | ArgType->isObjCLifetimeType() && |
5258 | !ArgType.getObjCLifetime()) { |
5259 | Qualifiers Qs; |
5260 | Qs.setObjCLifetime(Qualifiers::OCL_Strong); |
5261 | ArgType = Context.getQualifiedType(ArgType, Qs); |
5262 | } |
5263 | |
5264 | SugaredConverted.push_back(TemplateArgument(ArgType)); |
5265 | CanonicalConverted.push_back( |
5266 | TemplateArgument(Context.getCanonicalType(ArgType))); |
5267 | return false; |
5268 | } |
5269 | |
5270 | /// Substitute template arguments into the default template argument for |
5271 | /// the given template type parameter. |
5272 | /// |
5273 | /// \param SemaRef the semantic analysis object for which we are performing |
5274 | /// the substitution. |
5275 | /// |
5276 | /// \param Template the template that we are synthesizing template arguments |
5277 | /// for. |
5278 | /// |
5279 | /// \param TemplateLoc the location of the template name that started the |
5280 | /// template-id we are checking. |
5281 | /// |
5282 | /// \param RAngleLoc the location of the right angle bracket ('>') that |
5283 | /// terminates the template-id. |
5284 | /// |
5285 | /// \param Param the template template parameter whose default we are |
5286 | /// substituting into. |
5287 | /// |
5288 | /// \param Converted the list of template arguments provided for template |
5289 | /// parameters that precede \p Param in the template parameter list. |
5290 | /// \returns the substituted template argument, or NULL if an error occurred. |
5291 | static TypeSourceInfo *SubstDefaultTemplateArgument( |
5292 | Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, |
5293 | SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, |
5294 | ArrayRef<TemplateArgument> SugaredConverted, |
5295 | ArrayRef<TemplateArgument> CanonicalConverted) { |
5296 | TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo(); |
5297 | |
5298 | // If the argument type is dependent, instantiate it now based |
5299 | // on the previously-computed template arguments. |
5300 | if (ArgType->getType()->isInstantiationDependentType()) { |
5301 | Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template, |
5302 | SugaredConverted, |
5303 | SourceRange(TemplateLoc, RAngleLoc)); |
5304 | if (Inst.isInvalid()) |
5305 | return nullptr; |
5306 | |
5307 | // Only substitute for the innermost template argument list. |
5308 | MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, |
5309 | /*Final=*/true); |
5310 | for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) |
5311 | TemplateArgLists.addOuterTemplateArguments(std::nullopt); |
5312 | |
5313 | bool ForLambdaCallOperator = false; |
5314 | if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext())) |
5315 | ForLambdaCallOperator = Rec->isLambda(); |
5316 | Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(), |
5317 | !ForLambdaCallOperator); |
5318 | ArgType = |
5319 | SemaRef.SubstType(ArgType, TemplateArgLists, |
5320 | Param->getDefaultArgumentLoc(), Param->getDeclName()); |
5321 | } |
5322 | |
5323 | return ArgType; |
5324 | } |
5325 | |
5326 | /// Substitute template arguments into the default template argument for |
5327 | /// the given non-type template parameter. |
5328 | /// |
5329 | /// \param SemaRef the semantic analysis object for which we are performing |
5330 | /// the substitution. |
5331 | /// |
5332 | /// \param Template the template that we are synthesizing template arguments |
5333 | /// for. |
5334 | /// |
5335 | /// \param TemplateLoc the location of the template name that started the |
5336 | /// template-id we are checking. |
5337 | /// |
5338 | /// \param RAngleLoc the location of the right angle bracket ('>') that |
5339 | /// terminates the template-id. |
5340 | /// |
5341 | /// \param Param the non-type template parameter whose default we are |
5342 | /// substituting into. |
5343 | /// |
5344 | /// \param Converted the list of template arguments provided for template |
5345 | /// parameters that precede \p Param in the template parameter list. |
5346 | /// |
5347 | /// \returns the substituted template argument, or NULL if an error occurred. |
5348 | static ExprResult SubstDefaultTemplateArgument( |
5349 | Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, |
5350 | SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param, |
5351 | ArrayRef<TemplateArgument> SugaredConverted, |
5352 | ArrayRef<TemplateArgument> CanonicalConverted) { |
5353 | Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template, |
5354 | SugaredConverted, |
5355 | SourceRange(TemplateLoc, RAngleLoc)); |
5356 | if (Inst.isInvalid()) |
5357 | return ExprError(); |
5358 | |
5359 | // Only substitute for the innermost template argument list. |
5360 | MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, |
5361 | /*Final=*/true); |
5362 | for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) |
5363 | TemplateArgLists.addOuterTemplateArguments(std::nullopt); |
5364 | |
5365 | Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); |
5366 | EnterExpressionEvaluationContext ConstantEvaluated( |
5367 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
5368 | return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists); |
5369 | } |
5370 | |
5371 | /// Substitute template arguments into the default template argument for |
5372 | /// the given template template parameter. |
5373 | /// |
5374 | /// \param SemaRef the semantic analysis object for which we are performing |
5375 | /// the substitution. |
5376 | /// |
5377 | /// \param Template the template that we are synthesizing template arguments |
5378 | /// for. |
5379 | /// |
5380 | /// \param TemplateLoc the location of the template name that started the |
5381 | /// template-id we are checking. |
5382 | /// |
5383 | /// \param RAngleLoc the location of the right angle bracket ('>') that |
5384 | /// terminates the template-id. |
5385 | /// |
5386 | /// \param Param the template template parameter whose default we are |
5387 | /// substituting into. |
5388 | /// |
5389 | /// \param Converted the list of template arguments provided for template |
5390 | /// parameters that precede \p Param in the template parameter list. |
5391 | /// |
5392 | /// \param QualifierLoc Will be set to the nested-name-specifier (with |
5393 | /// source-location information) that precedes the template name. |
5394 | /// |
5395 | /// \returns the substituted template argument, or NULL if an error occurred. |
5396 | static TemplateName SubstDefaultTemplateArgument( |
5397 | Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, |
5398 | SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param, |
5399 | ArrayRef<TemplateArgument> SugaredConverted, |
5400 | ArrayRef<TemplateArgument> CanonicalConverted, |
5401 | NestedNameSpecifierLoc &QualifierLoc) { |
5402 | Sema::InstantiatingTemplate Inst( |
5403 | SemaRef, TemplateLoc, TemplateParameter(Param), Template, |
5404 | SugaredConverted, SourceRange(TemplateLoc, RAngleLoc)); |
5405 | if (Inst.isInvalid()) |
5406 | return TemplateName(); |
5407 | |
5408 | // Only substitute for the innermost template argument list. |
5409 | MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, |
5410 | /*Final=*/true); |
5411 | for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) |
5412 | TemplateArgLists.addOuterTemplateArguments(std::nullopt); |
5413 | |
5414 | Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); |
5415 | // Substitute into the nested-name-specifier first, |
5416 | QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc(); |
5417 | if (QualifierLoc) { |
5418 | QualifierLoc = |
5419 | SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists); |
5420 | if (!QualifierLoc) |
5421 | return TemplateName(); |
5422 | } |
5423 | |
5424 | return SemaRef.SubstTemplateName( |
5425 | QualifierLoc, |
5426 | Param->getDefaultArgument().getArgument().getAsTemplate(), |
5427 | Param->getDefaultArgument().getTemplateNameLoc(), |
5428 | TemplateArgLists); |
5429 | } |
5430 | |
5431 | /// If the given template parameter has a default template |
5432 | /// argument, substitute into that default template argument and |
5433 | /// return the corresponding template argument. |
5434 | TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable( |
5435 | TemplateDecl *Template, SourceLocation TemplateLoc, |
5436 | SourceLocation RAngleLoc, Decl *Param, |
5437 | ArrayRef<TemplateArgument> SugaredConverted, |
5438 | ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) { |
5439 | HasDefaultArg = false; |
5440 | |
5441 | if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) { |
5442 | if (!hasReachableDefaultArgument(TypeParm)) |
5443 | return TemplateArgumentLoc(); |
5444 | |
5445 | HasDefaultArg = true; |
5446 | TypeSourceInfo *DI = SubstDefaultTemplateArgument( |
5447 | *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted, |
5448 | CanonicalConverted); |
5449 | if (DI) |
5450 | return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); |
5451 | |
5452 | return TemplateArgumentLoc(); |
5453 | } |
5454 | |
5455 | if (NonTypeTemplateParmDecl *NonTypeParm |
5456 | = dyn_cast<NonTypeTemplateParmDecl>(Param)) { |
5457 | if (!hasReachableDefaultArgument(NonTypeParm)) |
5458 | return TemplateArgumentLoc(); |
5459 | |
5460 | HasDefaultArg = true; |
5461 | ExprResult Arg = SubstDefaultTemplateArgument( |
5462 | *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted, |
5463 | CanonicalConverted); |
5464 | if (Arg.isInvalid()) |
5465 | return TemplateArgumentLoc(); |
5466 | |
5467 | Expr *ArgE = Arg.getAs<Expr>(); |
5468 | return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); |
5469 | } |
5470 | |
5471 | TemplateTemplateParmDecl *TempTempParm |
5472 | = cast<TemplateTemplateParmDecl>(Param); |
5473 | if (!hasReachableDefaultArgument(TempTempParm)) |
5474 | return TemplateArgumentLoc(); |
5475 | |
5476 | HasDefaultArg = true; |
5477 | NestedNameSpecifierLoc QualifierLoc; |
5478 | TemplateName TName = SubstDefaultTemplateArgument( |
5479 | *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted, |
5480 | CanonicalConverted, QualifierLoc); |
5481 | if (TName.isNull()) |
5482 | return TemplateArgumentLoc(); |
5483 | |
5484 | return TemplateArgumentLoc( |
5485 | Context, TemplateArgument(TName), |
5486 | TempTempParm->getDefaultArgument().getTemplateQualifierLoc(), |
5487 | TempTempParm->getDefaultArgument().getTemplateNameLoc()); |
5488 | } |
5489 | |
5490 | /// Convert a template-argument that we parsed as a type into a template, if |
5491 | /// possible. C++ permits injected-class-names to perform dual service as |
5492 | /// template template arguments and as template type arguments. |
5493 | static TemplateArgumentLoc |
5494 | convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) { |
5495 | // Extract and step over any surrounding nested-name-specifier. |
5496 | NestedNameSpecifierLoc QualLoc; |
5497 | if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) { |
5498 | if (ETLoc.getTypePtr()->getKeyword() != ETK_None) |
5499 | return TemplateArgumentLoc(); |
5500 | |
5501 | QualLoc = ETLoc.getQualifierLoc(); |
5502 | TLoc = ETLoc.getNamedTypeLoc(); |
5503 | } |
5504 | // If this type was written as an injected-class-name, it can be used as a |
5505 | // template template argument. |
5506 | if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>()) |
5507 | return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(), |
5508 | QualLoc, InjLoc.getNameLoc()); |
5509 | |
5510 | // If this type was written as an injected-class-name, it may have been |
5511 | // converted to a RecordType during instantiation. If the RecordType is |
5512 | // *not* wrapped in a TemplateSpecializationType and denotes a class |
5513 | // template specialization, it must have come from an injected-class-name. |
5514 | if (auto RecLoc = TLoc.getAs<RecordTypeLoc>()) |
5515 | if (auto *CTSD = |
5516 | dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl())) |
5517 | return TemplateArgumentLoc(Context, |
5518 | TemplateName(CTSD->getSpecializedTemplate()), |
5519 | QualLoc, RecLoc.getNameLoc()); |
5520 | |
5521 | return TemplateArgumentLoc(); |
5522 | } |
5523 | |
5524 | /// Check that the given template argument corresponds to the given |
5525 | /// template parameter. |
5526 | /// |
5527 | /// \param Param The template parameter against which the argument will be |
5528 | /// checked. |
5529 | /// |
5530 | /// \param Arg The template argument, which may be updated due to conversions. |
5531 | /// |
5532 | /// \param Template The template in which the template argument resides. |
5533 | /// |
5534 | /// \param TemplateLoc The location of the template name for the template |
5535 | /// whose argument list we're matching. |
5536 | /// |
5537 | /// \param RAngleLoc The location of the right angle bracket ('>') that closes |
5538 | /// the template argument list. |
5539 | /// |
5540 | /// \param ArgumentPackIndex The index into the argument pack where this |
5541 | /// argument will be placed. Only valid if the parameter is a parameter pack. |
5542 | /// |
5543 | /// \param Converted The checked, converted argument will be added to the |
5544 | /// end of this small vector. |
5545 | /// |
5546 | /// \param CTAK Describes how we arrived at this particular template argument: |
5547 | /// explicitly written, deduced, etc. |
5548 | /// |
5549 | /// \returns true on error, false otherwise. |
5550 | bool Sema::CheckTemplateArgument( |
5551 | NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, |
5552 | SourceLocation TemplateLoc, SourceLocation RAngleLoc, |
5553 | unsigned ArgumentPackIndex, |
5554 | SmallVectorImpl<TemplateArgument> &SugaredConverted, |
5555 | SmallVectorImpl<TemplateArgument> &CanonicalConverted, |
5556 | CheckTemplateArgumentKind CTAK) { |
5557 | // Check template type parameters. |
5558 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) |
5559 | return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted, |
5560 | CanonicalConverted); |
5561 | |
5562 | // Check non-type template parameters. |
5563 | if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { |
5564 | // Do substitution on the type of the non-type template parameter |
5565 | // with the template arguments we've seen thus far. But if the |
5566 | // template has a dependent context then we cannot substitute yet. |
5567 | QualType NTTPType = NTTP->getType(); |
5568 | if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack()) |
5569 | NTTPType = NTTP->getExpansionType(ArgumentPackIndex); |
5570 | |
5571 | if (NTTPType->isInstantiationDependentType() && |
5572 | !isa<TemplateTemplateParmDecl>(Template) && |
5573 | !Template->getDeclContext()->isDependentContext()) { |
5574 | // Do substitution on the type of the non-type template parameter. |
5575 | InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP, |
5576 | SugaredConverted, |
5577 | SourceRange(TemplateLoc, RAngleLoc)); |
5578 | if (Inst.isInvalid()) |
5579 | return true; |
5580 | |
5581 | MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted, |
5582 | /*Final=*/true); |
5583 | // If the parameter is a pack expansion, expand this slice of the pack. |
5584 | if (auto *PET = NTTPType->getAs<PackExpansionType>()) { |
5585 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, |
5586 | ArgumentPackIndex); |
5587 | NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(), |
5588 | NTTP->getDeclName()); |
5589 | } else { |
5590 | NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(), |
5591 | NTTP->getDeclName()); |
5592 | } |
5593 | |
5594 | // If that worked, check the non-type template parameter type |
5595 | // for validity. |
5596 | if (!NTTPType.isNull()) |
5597 | NTTPType = CheckNonTypeTemplateParameterType(NTTPType, |
5598 | NTTP->getLocation()); |
5599 | if (NTTPType.isNull()) |
5600 | return true; |
5601 | } |
5602 | |
5603 | switch (Arg.getArgument().getKind()) { |
5604 | case TemplateArgument::Null: |
5605 | llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here" , "clang/lib/Sema/SemaTemplate.cpp", 5605); |
5606 | |
5607 | case TemplateArgument::Expression: { |
5608 | Expr *E = Arg.getArgument().getAsExpr(); |
5609 | TemplateArgument SugaredResult, CanonicalResult; |
5610 | unsigned CurSFINAEErrors = NumSFINAEErrors; |
5611 | ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult, |
5612 | CanonicalResult, CTAK); |
5613 | if (Res.isInvalid()) |
5614 | return true; |
5615 | // If the current template argument causes an error, give up now. |
5616 | if (CurSFINAEErrors < NumSFINAEErrors) |
5617 | return true; |
5618 | |
5619 | // If the resulting expression is new, then use it in place of the |
5620 | // old expression in the template argument. |
5621 | if (Res.get() != E) { |
5622 | TemplateArgument TA(Res.get()); |
5623 | Arg = TemplateArgumentLoc(TA, Res.get()); |
5624 | } |
5625 | |
5626 | SugaredConverted.push_back(SugaredResult); |
5627 | CanonicalConverted.push_back(CanonicalResult); |
5628 | break; |
5629 | } |
5630 | |
5631 | case TemplateArgument::Declaration: |
5632 | case TemplateArgument::Integral: |
5633 | case TemplateArgument::NullPtr: |
5634 | // We've already checked this template argument, so just copy |
5635 | // it to the list of converted arguments. |
5636 | SugaredConverted.push_back(Arg.getArgument()); |
5637 | CanonicalConverted.push_back( |
5638 | Context.getCanonicalTemplateArgument(Arg.getArgument())); |
5639 | break; |
5640 | |
5641 | case TemplateArgument::Template: |
5642 | case TemplateArgument::TemplateExpansion: |
5643 | // We were given a template template argument. It may not be ill-formed; |
5644 | // see below. |
5645 | if (DependentTemplateName *DTN |
5646 | = Arg.getArgument().getAsTemplateOrTemplatePattern() |
5647 | .getAsDependentTemplateName()) { |
5648 | // We have a template argument such as \c T::template X, which we |
5649 | // parsed as a template template argument. However, since we now |
5650 | // know that we need a non-type template argument, convert this |
5651 | // template name into an expression. |
5652 | |
5653 | DeclarationNameInfo NameInfo(DTN->getIdentifier(), |
5654 | Arg.getTemplateNameLoc()); |
5655 | |
5656 | CXXScopeSpec SS; |
5657 | SS.Adopt(Arg.getTemplateQualifierLoc()); |
5658 | // FIXME: the template-template arg was a DependentTemplateName, |
5659 | // so it was provided with a template keyword. However, its source |
5660 | // location is not stored in the template argument structure. |
5661 | SourceLocation TemplateKWLoc; |
5662 | ExprResult E = DependentScopeDeclRefExpr::Create( |
5663 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, |
5664 | nullptr); |
5665 | |
5666 | // If we parsed the template argument as a pack expansion, create a |
5667 | // pack expansion expression. |
5668 | if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){ |
5669 | E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc()); |
5670 | if (E.isInvalid()) |
5671 | return true; |
5672 | } |
5673 | |
5674 | TemplateArgument SugaredResult, CanonicalResult; |
5675 | E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult, |
5676 | CanonicalResult, CTAK_Specified); |
5677 | if (E.isInvalid()) |
5678 | return true; |
5679 | |
5680 | SugaredConverted.push_back(SugaredResult); |
5681 | CanonicalConverted.push_back(CanonicalResult); |
5682 | break; |
5683 | } |
5684 | |
5685 | // We have a template argument that actually does refer to a class |
5686 | // template, alias template, or template template parameter, and |
5687 | // therefore cannot be a non-type template argument. |
5688 | Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) |
5689 | << Arg.getSourceRange(); |
5690 | |
5691 | Diag(Param->getLocation(), diag::note_template_param_here); |
5692 | return true; |
5693 | |
5694 | case TemplateArgument::Type: { |
5695 | // We have a non-type template parameter but the template |
5696 | // argument is a type. |
5697 | |
5698 | // C++ [temp.arg]p2: |
5699 | // In a template-argument, an ambiguity between a type-id and |
5700 | // an expression is resolved to a type-id, regardless of the |
5701 | // form of the corresponding template-parameter. |
5702 | // |
5703 | // We warn specifically about this case, since it can be rather |
5704 | // confusing for users. |
5705 | QualType T = Arg.getArgument().getAsType(); |
5706 | SourceRange SR = Arg.getSourceRange(); |
5707 | if (T->isFunctionType()) |
5708 | Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; |
5709 | else |
5710 | Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; |
5711 | Diag(Param->getLocation(), diag::note_template_param_here); |
5712 | return true; |
5713 | } |
5714 | |
5715 | case TemplateArgument::Pack: |
5716 | llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs" , "clang/lib/Sema/SemaTemplate.cpp", 5716); |
5717 | } |
5718 | |
5719 | return false; |
5720 | } |
5721 | |
5722 | |
5723 | // Check template template parameters. |
5724 | TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); |
5725 | |
5726 | TemplateParameterList *Params = TempParm->getTemplateParameters(); |
5727 | if (TempParm->isExpandedParameterPack()) |
5728 | Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex); |
5729 | |
5730 | // Substitute into the template parameter list of the template |
5731 | // template parameter, since previously-supplied template arguments |
5732 | // may appear within the template template parameter. |
5733 | // |
5734 | // FIXME: Skip this if the parameters aren't instantiation-dependent. |
5735 | { |
5736 | // Set up a template instantiation context. |
5737 | LocalInstantiationScope Scope(*this); |
5738 | InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm, |
5739 | SugaredConverted, |
5740 | SourceRange(TemplateLoc, RAngleLoc)); |
5741 | if (Inst.isInvalid()) |
5742 | return true; |
5743 | |
5744 | Params = |
5745 | SubstTemplateParams(Params, CurContext, |
5746 | MultiLevelTemplateArgumentList( |
5747 | Template, SugaredConverted, /*Final=*/true), |
5748 | /*EvaluateConstraints=*/false); |
5749 | if (!Params) |
5750 | return true; |
5751 | } |
5752 | |
5753 | // C++1z [temp.local]p1: (DR1004) |
5754 | // When [the injected-class-name] is used [...] as a template-argument for |
5755 | // a template template-parameter [...] it refers to the class template |
5756 | // itself. |
5757 | if (Arg.getArgument().getKind() == TemplateArgument::Type) { |
5758 | TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate( |
5759 | Context, Arg.getTypeSourceInfo()->getTypeLoc()); |
5760 | if (!ConvertedArg.getArgument().isNull()) |
5761 | Arg = ConvertedArg; |
5762 | } |
5763 | |
5764 | switch (Arg.getArgument().getKind()) { |
5765 | case TemplateArgument::Null: |
5766 | llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here" , "clang/lib/Sema/SemaTemplate.cpp", 5766); |
5767 | |
5768 | case TemplateArgument::Template: |
5769 | case TemplateArgument::TemplateExpansion: |
5770 | if (CheckTemplateTemplateArgument(TempParm, Params, Arg)) |
5771 | return true; |
5772 | |
5773 | SugaredConverted.push_back(Arg.getArgument()); |
5774 | CanonicalConverted.push_back( |
5775 | Context.getCanonicalTemplateArgument(Arg.getArgument())); |
5776 | break; |
5777 | |
5778 | case TemplateArgument::Expression: |
5779 | case TemplateArgument::Type: |
5780 | // We have a template template parameter but the template |
5781 | // argument does not refer to a template. |
5782 | Diag(Arg.getLocation(), diag::err_template_arg_must_be_template) |
5783 | << getLangOpts().CPlusPlus11; |
5784 | return true; |
5785 | |
5786 | case TemplateArgument::Declaration: |
5787 | llvm_unreachable("Declaration argument with template template parameter")::llvm::llvm_unreachable_internal("Declaration argument with template template parameter" , "clang/lib/Sema/SemaTemplate.cpp", 5787); |
5788 | case TemplateArgument::Integral: |
5789 | llvm_unreachable("Integral argument with template template parameter")::llvm::llvm_unreachable_internal("Integral argument with template template parameter" , "clang/lib/Sema/SemaTemplate.cpp", 5789); |
5790 | case TemplateArgument::NullPtr: |
5791 | llvm_unreachable("Null pointer argument with template template parameter")::llvm::llvm_unreachable_internal("Null pointer argument with template template parameter" , "clang/lib/Sema/SemaTemplate.cpp", 5791); |
5792 | |
5793 | case TemplateArgument::Pack: |
5794 | llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs" , "clang/lib/Sema/SemaTemplate.cpp", 5794); |
5795 | } |
5796 | |
5797 | return false; |
5798 | } |
5799 | |
5800 | /// Diagnose a missing template argument. |
5801 | template<typename TemplateParmDecl> |
5802 | static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, |
5803 | TemplateDecl *TD, |
5804 | const TemplateParmDecl *D, |
5805 | TemplateArgumentListInfo &Args) { |
5806 | // Dig out the most recent declaration of the template parameter; there may be |
5807 | // declarations of the template that are more recent than TD. |
5808 | D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl()) |
5809 | ->getTemplateParameters() |
5810 | ->getParam(D->getIndex())); |
5811 | |
5812 | // If there's a default argument that's not reachable, diagnose that we're |
5813 | // missing a module import. |
5814 | llvm::SmallVector<Module*, 8> Modules; |
5815 | if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) { |
5816 | S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD), |
5817 | D->getDefaultArgumentLoc(), Modules, |
5818 | Sema::MissingImportKind::DefaultArgument, |
5819 | /*Recover*/true); |
5820 | return true; |
5821 | } |
5822 | |
5823 | // FIXME: If there's a more recent default argument that *is* visible, |
5824 | // diagnose that it was declared too late. |
5825 | |
5826 | TemplateParameterList *Params = TD->getTemplateParameters(); |
5827 | |
5828 | S.Diag(Loc, diag::err_template_arg_list_different_arity) |
5829 | << /*not enough args*/0 |
5830 | << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD)) |
5831 | << TD; |
5832 | S.Diag(TD->getLocation(), diag::note_template_decl_here) |
5833 | << Params->getSourceRange(); |
5834 | return true; |
5835 | } |
5836 | |
5837 | /// Check that the given template argument list is well-formed |
5838 | /// for specializing the given template. |
5839 | bool Sema::CheckTemplateArgumentList( |
5840 | TemplateDecl *Template, SourceLocation TemplateLoc, |
5841 | TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, |
5842 | SmallVectorImpl<TemplateArgument> &SugaredConverted, |
5843 | SmallVectorImpl<TemplateArgument> &CanonicalConverted, |
5844 | bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) { |
5845 | |
5846 | if (ConstraintsNotSatisfied) |
5847 | *ConstraintsNotSatisfied = false; |
5848 | |
5849 | // Make a copy of the template arguments for processing. Only make the |
5850 | // changes at the end when successful in matching the arguments to the |
5851 | // template. |
5852 | TemplateArgumentListInfo NewArgs = TemplateArgs; |
5853 | |
5854 | // Make sure we get the template parameter list from the most |
5855 | // recent declaration, since that is the only one that is guaranteed to |
5856 | // have all the default template argument information. |
5857 | TemplateParameterList *Params = |
5858 | cast<TemplateDecl>(Template->getMostRecentDecl()) |
5859 | ->getTemplateParameters(); |
5860 | |
5861 | SourceLocation RAngleLoc = NewArgs.getRAngleLoc(); |
5862 | |
5863 | // C++ [temp.arg]p1: |
5864 | // [...] The type and form of each template-argument specified in |
5865 | // a template-id shall match the type and form specified for the |
5866 | // corresponding parameter declared by the template in its |
5867 | // template-parameter-list. |
5868 | bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template); |
5869 | SmallVector<TemplateArgument, 2> SugaredArgumentPack; |
5870 | SmallVector<TemplateArgument, 2> CanonicalArgumentPack; |
5871 | unsigned ArgIdx = 0, NumArgs = NewArgs.size(); |
5872 | LocalInstantiationScope InstScope(*this, true); |
5873 | for (TemplateParameterList::iterator Param = Params->begin(), |
5874 | ParamEnd = Params->end(); |
5875 | Param != ParamEnd; /* increment in loop */) { |
5876 | // If we have an expanded parameter pack, make sure we don't have too |
5877 | // many arguments. |
5878 | if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) { |
5879 | if (*Expansions == SugaredArgumentPack.size()) { |
5880 | // We're done with this parameter pack. Pack up its arguments and add |
5881 | // them to the list. |
5882 | SugaredConverted.push_back( |
5883 | TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack)); |
5884 | SugaredArgumentPack.clear(); |
5885 | |
5886 | CanonicalConverted.push_back( |
5887 | TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack)); |
5888 | CanonicalArgumentPack.clear(); |
5889 | |
5890 | // This argument is assigned to the next parameter. |
5891 | ++Param; |
5892 | continue; |
5893 | } else if (ArgIdx == NumArgs && !PartialTemplateArgs) { |
5894 | // Not enough arguments for this parameter pack. |
5895 | Diag(TemplateLoc, diag::err_template_arg_list_different_arity) |
5896 | << /*not enough args*/0 |
5897 | << (int)getTemplateNameKindForDiagnostics(TemplateName(Template)) |
5898 | << Template; |
5899 | Diag(Template->getLocation(), diag::note_template_decl_here) |
5900 | << Params->getSourceRange(); |
5901 | return true; |
5902 | } |
5903 | } |
5904 | |
5905 | if (ArgIdx < NumArgs) { |
5906 | // Check the template argument we were given. |
5907 | if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc, |
5908 | RAngleLoc, SugaredArgumentPack.size(), |
5909 | SugaredConverted, CanonicalConverted, |
5910 | CTAK_Specified)) |
5911 | return true; |
5912 | |
5913 | CanonicalConverted.back().setIsDefaulted( |
5914 | clang::isSubstitutedDefaultArgument( |
5915 | Context, NewArgs[ArgIdx].getArgument(), *Param, |
5916 | CanonicalConverted, Params->getDepth())); |
5917 | |
5918 | bool PackExpansionIntoNonPack = |
5919 | NewArgs[ArgIdx].getArgument().isPackExpansion() && |
5920 | (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param)); |
5921 | if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) || |
5922 | isa<ConceptDecl>(Template))) { |
5923 | // Core issue 1430: we have a pack expansion as an argument to an |
5924 | // alias template, and it's not part of a parameter pack. This |
5925 | // can't be canonicalized, so reject it now. |
5926 | // As for concepts - we cannot normalize constraints where this |
5927 | // situation exists. |
5928 | Diag(NewArgs[ArgIdx].getLocation(), |
5929 | diag::err_template_expansion_into_fixed_list) |
5930 | << (isa<ConceptDecl>(Template) ? 1 : 0) |
5931 | << NewArgs[ArgIdx].getSourceRange(); |
5932 | Diag((*Param)->getLocation(), diag::note_template_param_here); |
5933 | return true; |
5934 | } |
5935 | |
5936 | // We're now done with this argument. |
5937 | ++ArgIdx; |
5938 | |
5939 | if ((*Param)->isTemplateParameterPack()) { |
5940 | // The template parameter was a template parameter pack, so take the |
5941 | // deduced argument and place it on the argument pack. Note that we |
5942 | // stay on the same template parameter so that we can deduce more |
5943 | // arguments. |
5944 | SugaredArgumentPack.push_back(SugaredConverted.pop_back_val()); |
5945 | CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val()); |
5946 | } else { |
5947 | // Move to the next template parameter. |
5948 |