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