1//===------- QualTypeNames.cpp - Generate Complete QualType Names ---------===//
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
9#include "clang/AST/QualTypeNames.h"
10#include "clang/AST/DeclTemplate.h"
11#include "clang/AST/DeclarationName.h"
12#include "clang/AST/Mangle.h"
13#include "clang/AST/Type.h"
14
15namespace clang {
16
17namespace TypeName {
18
19/// Create a NestedNameSpecifier for Namesp and its enclosing
20/// scopes.
21///
22/// \param[in] Ctx - the AST Context to be used.
23/// \param[in] Namesp - the NamespaceDecl for which a NestedNameSpecifier
24/// is requested.
25/// \param[in] WithGlobalNsPrefix - Indicate whether the global namespace
26/// specifier "::" should be prepended or not.
27static NestedNameSpecifier *createNestedNameSpecifier(
28 const ASTContext &Ctx,
29 const NamespaceDecl *Namesp,
30 bool WithGlobalNsPrefix);
31
32/// Create a NestedNameSpecifier for TagDecl and its enclosing
33/// scopes.
34///
35/// \param[in] Ctx - the AST Context to be used.
36/// \param[in] TD - the TagDecl for which a NestedNameSpecifier is
37/// requested.
38/// \param[in] FullyQualify - Convert all template arguments into fully
39/// qualified names.
40/// \param[in] WithGlobalNsPrefix - Indicate whether the global namespace
41/// specifier "::" should be prepended or not.
42static NestedNameSpecifier *createNestedNameSpecifier(
43 const ASTContext &Ctx, const TypeDecl *TD,
44 bool FullyQualify, bool WithGlobalNsPrefix);
45
46static NestedNameSpecifier *createNestedNameSpecifierForScopeOf(
47 const ASTContext &Ctx, const Decl *decl,
48 bool FullyQualified, bool WithGlobalNsPrefix);
49
50static NestedNameSpecifier *getFullyQualifiedNestedNameSpecifier(
51 const ASTContext &Ctx, NestedNameSpecifier *scope, bool WithGlobalNsPrefix);
52
53static bool getFullyQualifiedTemplateName(const ASTContext &Ctx,
54 TemplateName &TName,
55 bool WithGlobalNsPrefix) {
56 bool Changed = false;
57 NestedNameSpecifier *NNS = nullptr;
58
59 TemplateDecl *ArgTDecl = TName.getAsTemplateDecl();
60 // ArgTDecl won't be NULL because we asserted that this isn't a
61 // dependent context very early in the call chain.
62 assert(ArgTDecl != nullptr);
63 QualifiedTemplateName *QTName = TName.getAsQualifiedTemplateName();
64
65 if (QTName &&
66 !QTName->hasTemplateKeyword() &&
67 (NNS = QTName->getQualifier())) {
68 NestedNameSpecifier *QNNS = getFullyQualifiedNestedNameSpecifier(
69 Ctx, scope: NNS, WithGlobalNsPrefix);
70 if (QNNS != NNS) {
71 Changed = true;
72 NNS = QNNS;
73 } else {
74 NNS = nullptr;
75 }
76 } else {
77 NNS = createNestedNameSpecifierForScopeOf(
78 Ctx, ArgTDecl, true, WithGlobalNsPrefix);
79 }
80 if (NNS) {
81 TemplateName UnderlyingTN(ArgTDecl);
82 if (UsingShadowDecl *USD = TName.getAsUsingShadowDecl())
83 UnderlyingTN = TemplateName(USD);
84 TName =
85 Ctx.getQualifiedTemplateName(NNS,
86 /*TemplateKeyword=*/false, Template: UnderlyingTN);
87 Changed = true;
88 }
89 return Changed;
90}
91
92static bool getFullyQualifiedTemplateArgument(const ASTContext &Ctx,
93 TemplateArgument &Arg,
94 bool WithGlobalNsPrefix) {
95 bool Changed = false;
96
97 // Note: we do not handle TemplateArgument::Expression, to replace it
98 // we need the information for the template instance decl.
99
100 if (Arg.getKind() == TemplateArgument::Template) {
101 TemplateName TName = Arg.getAsTemplate();
102 Changed = getFullyQualifiedTemplateName(Ctx, TName, WithGlobalNsPrefix);
103 if (Changed) {
104 Arg = TemplateArgument(TName);
105 }
106 } else if (Arg.getKind() == TemplateArgument::Type) {
107 QualType SubTy = Arg.getAsType();
108 // Check if the type needs more desugaring and recurse.
109 QualType QTFQ = getFullyQualifiedType(QT: SubTy, Ctx, WithGlobalNsPrefix);
110 if (QTFQ != SubTy) {
111 Arg = TemplateArgument(QTFQ);
112 Changed = true;
113 }
114 }
115 return Changed;
116}
117
118static const Type *getFullyQualifiedTemplateType(const ASTContext &Ctx,
119 const Type *TypePtr,
120 bool WithGlobalNsPrefix) {
121 // DependentTemplateTypes exist within template declarations and
122 // definitions. Therefore we shouldn't encounter them at the end of
123 // a translation unit. If we do, the caller has made an error.
124 assert(!isa<DependentTemplateSpecializationType>(TypePtr));
125 // In case of template specializations, iterate over the arguments
126 // and fully qualify them as well.
127 if (const auto *TST = dyn_cast<const TemplateSpecializationType>(Val: TypePtr)) {
128 bool MightHaveChanged = false;
129 SmallVector<TemplateArgument, 4> FQArgs;
130 // Cheap to copy and potentially modified by
131 // getFullyQualifedTemplateArgument.
132 for (TemplateArgument Arg : TST->template_arguments()) {
133 MightHaveChanged |= getFullyQualifiedTemplateArgument(
134 Ctx, Arg, WithGlobalNsPrefix);
135 FQArgs.push_back(Elt: Arg);
136 }
137
138 // If a fully qualified arg is different from the unqualified arg,
139 // allocate new type in the AST.
140 if (MightHaveChanged) {
141 QualType QT = Ctx.getTemplateSpecializationType(
142 T: TST->getTemplateName(), SpecifiedArgs: FQArgs,
143 /*CanonicalArgs=*/std::nullopt, Underlying: TST->desugar());
144 // getTemplateSpecializationType returns a fully qualified
145 // version of the specialization itself, so no need to qualify
146 // it.
147 return QT.getTypePtr();
148 }
149 } else if (const auto *TSTRecord = dyn_cast<const RecordType>(Val: TypePtr)) {
150 // We are asked to fully qualify and we have a Record Type,
151 // which can point to a template instantiation with no sugar in any of
152 // its template argument, however we still need to fully qualify them.
153
154 if (const auto *TSTDecl =
155 dyn_cast<ClassTemplateSpecializationDecl>(Val: TSTRecord->getDecl())) {
156 const TemplateArgumentList &TemplateArgs = TSTDecl->getTemplateArgs();
157
158 bool MightHaveChanged = false;
159 SmallVector<TemplateArgument, 4> FQArgs;
160 for (unsigned int I = 0, E = TemplateArgs.size(); I != E; ++I) {
161 // cheap to copy and potentially modified by
162 // getFullyQualifedTemplateArgument
163 TemplateArgument Arg(TemplateArgs[I]);
164 MightHaveChanged |= getFullyQualifiedTemplateArgument(
165 Ctx, Arg, WithGlobalNsPrefix);
166 FQArgs.push_back(Elt: Arg);
167 }
168
169 // If a fully qualified arg is different from the unqualified arg,
170 // allocate new type in the AST.
171 if (MightHaveChanged) {
172 TemplateName TN(TSTDecl->getSpecializedTemplate());
173 QualType QT = Ctx.getTemplateSpecializationType(
174 TN, FQArgs,
175 /*CanonicalArgs=*/std::nullopt,
176 TSTRecord->getCanonicalTypeInternal());
177 // getTemplateSpecializationType returns a fully qualified
178 // version of the specialization itself, so no need to qualify
179 // it.
180 return QT.getTypePtr();
181 }
182 }
183 }
184 return TypePtr;
185}
186
187static NestedNameSpecifier *createOuterNNS(const ASTContext &Ctx, const Decl *D,
188 bool FullyQualify,
189 bool WithGlobalNsPrefix) {
190 const DeclContext *DC = D->getDeclContext();
191 if (const auto *NS = dyn_cast<NamespaceDecl>(Val: DC)) {
192 while (NS && NS->isInline()) {
193 // Ignore inline namespace;
194 NS = dyn_cast<NamespaceDecl>(NS->getDeclContext());
195 }
196 if (NS && NS->getDeclName()) {
197 return createNestedNameSpecifier(Ctx, Namesp: NS, WithGlobalNsPrefix);
198 }
199 return nullptr; // no starting '::', no anonymous
200 } else if (const auto *TD = dyn_cast<TagDecl>(Val: DC)) {
201 return createNestedNameSpecifier(Ctx, TD, FullyQualify, WithGlobalNsPrefix);
202 } else if (const auto *TDD = dyn_cast<TypedefNameDecl>(Val: DC)) {
203 return createNestedNameSpecifier(
204 Ctx, TDD, FullyQualify, WithGlobalNsPrefix);
205 } else if (WithGlobalNsPrefix && DC->isTranslationUnit()) {
206 return NestedNameSpecifier::GlobalSpecifier(Context: Ctx);
207 }
208 return nullptr; // no starting '::' if |WithGlobalNsPrefix| is false
209}
210
211/// Return a fully qualified version of this name specifier.
212static NestedNameSpecifier *getFullyQualifiedNestedNameSpecifier(
213 const ASTContext &Ctx, NestedNameSpecifier *Scope,
214 bool WithGlobalNsPrefix) {
215 switch (Scope->getKind()) {
216 case NestedNameSpecifier::Global:
217 case NestedNameSpecifier::Super:
218 // Already fully qualified
219 return Scope;
220 case NestedNameSpecifier::Namespace:
221 return TypeName::createNestedNameSpecifier(
222 Ctx, Namesp: Scope->getAsNamespace(), WithGlobalNsPrefix);
223 case NestedNameSpecifier::NamespaceAlias:
224 // Namespace aliases are only valid for the duration of the
225 // scope where they were introduced, and therefore are often
226 // invalid at the end of the TU. So use the namespace name more
227 // likely to be valid at the end of the TU.
228 return TypeName::createNestedNameSpecifier(
229 Ctx,
230 Namesp: Scope->getAsNamespaceAlias()->getNamespace()->getCanonicalDecl(),
231 WithGlobalNsPrefix);
232 case NestedNameSpecifier::Identifier:
233 // A function or some other construct that makes it un-namable
234 // at the end of the TU. Skip the current component of the name,
235 // but use the name of it's prefix.
236 return getFullyQualifiedNestedNameSpecifier(
237 Ctx, Scope: Scope->getPrefix(), WithGlobalNsPrefix);
238 case NestedNameSpecifier::TypeSpec: {
239 const Type *Type = Scope->getAsType();
240 // Find decl context.
241 const TagDecl *TD = nullptr;
242 if (const TagType *TagDeclType = Type->getAs<TagType>()) {
243 TD = TagDeclType->getDecl();
244 } else {
245 TD = Type->getAsCXXRecordDecl();
246 }
247 if (TD) {
248 return TypeName::createNestedNameSpecifier(Ctx, TD,
249 true /*FullyQualified*/,
250 WithGlobalNsPrefix);
251 } else if (const auto *TDD = dyn_cast<TypedefType>(Val: Type)) {
252 return TypeName::createNestedNameSpecifier(Ctx, TDD->getDecl(),
253 true /*FullyQualified*/,
254 WithGlobalNsPrefix);
255 }
256 return Scope;
257 }
258 }
259 llvm_unreachable("bad NNS kind");
260}
261
262/// Create a nested name specifier for the declaring context of
263/// the type.
264static NestedNameSpecifier *createNestedNameSpecifierForScopeOf(
265 const ASTContext &Ctx, const Decl *Decl,
266 bool FullyQualified, bool WithGlobalNsPrefix) {
267 assert(Decl);
268
269 const DeclContext *DC = Decl->getDeclContext()->getRedeclContext();
270 const auto *Outer = dyn_cast<NamedDecl>(Val: DC);
271 const auto *OuterNS = dyn_cast<NamespaceDecl>(Val: DC);
272 if (Outer && !(OuterNS && OuterNS->isAnonymousNamespace())) {
273 if (const auto *CxxDecl = dyn_cast<CXXRecordDecl>(Val: DC)) {
274 if (ClassTemplateDecl *ClassTempl =
275 CxxDecl->getDescribedClassTemplate()) {
276 // We are in the case of a type(def) that was declared in a
277 // class template but is *not* type dependent. In clang, it
278 // gets attached to the class template declaration rather than
279 // any specific class template instantiation. This result in
280 // 'odd' fully qualified typename:
281 //
282 // vector<_Tp,_Alloc>::size_type
283 //
284 // Make the situation is 'useable' but looking a bit odd by
285 // picking a random instance as the declaring context.
286 if (ClassTempl->spec_begin() != ClassTempl->spec_end()) {
287 Decl = *(ClassTempl->spec_begin());
288 Outer = dyn_cast<NamedDecl>(Val: Decl);
289 OuterNS = dyn_cast<NamespaceDecl>(Val: Decl);
290 }
291 }
292 }
293
294 if (OuterNS) {
295 return createNestedNameSpecifier(Ctx, Namesp: OuterNS, WithGlobalNsPrefix);
296 } else if (const auto *TD = dyn_cast<TagDecl>(Val: Outer)) {
297 return createNestedNameSpecifier(
298 Ctx, TD, FullyQualified, WithGlobalNsPrefix);
299 } else if (isa<TranslationUnitDecl>(Val: Outer)) {
300 // Context is the TU. Nothing needs to be done.
301 return nullptr;
302 } else {
303 // Decl's context was neither the TU, a namespace, nor a
304 // TagDecl, which means it is a type local to a scope, and not
305 // accessible at the end of the TU.
306 return nullptr;
307 }
308 } else if (WithGlobalNsPrefix && DC->isTranslationUnit()) {
309 return NestedNameSpecifier::GlobalSpecifier(Context: Ctx);
310 }
311 return nullptr;
312}
313
314/// Create a nested name specifier for the declaring context of
315/// the type.
316static NestedNameSpecifier *createNestedNameSpecifierForScopeOf(
317 const ASTContext &Ctx, const Type *TypePtr,
318 bool FullyQualified, bool WithGlobalNsPrefix) {
319 if (!TypePtr) return nullptr;
320
321 Decl *Decl = nullptr;
322 // There are probably other cases ...
323 if (const auto *TDT = dyn_cast<TypedefType>(Val: TypePtr)) {
324 Decl = TDT->getDecl();
325 } else if (const auto *TagDeclType = dyn_cast<TagType>(Val: TypePtr)) {
326 Decl = TagDeclType->getDecl();
327 } else if (const auto *TST = dyn_cast<TemplateSpecializationType>(Val: TypePtr)) {
328 Decl = TST->getTemplateName().getAsTemplateDecl();
329 } else {
330 Decl = TypePtr->getAsCXXRecordDecl();
331 }
332
333 if (!Decl) return nullptr;
334
335 return createNestedNameSpecifierForScopeOf(
336 Ctx, Decl, FullyQualified, WithGlobalNsPrefix);
337}
338
339NestedNameSpecifier *createNestedNameSpecifier(const ASTContext &Ctx,
340 const NamespaceDecl *Namespace,
341 bool WithGlobalNsPrefix) {
342 while (Namespace && Namespace->isInline()) {
343 // Ignore inline namespace;
344 Namespace = dyn_cast<NamespaceDecl>(Namespace->getDeclContext());
345 }
346 if (!Namespace) return nullptr;
347
348 bool FullyQualified = true; // doesn't matter, DeclContexts are namespaces
349 return NestedNameSpecifier::Create(
350 Context: Ctx,
351 Prefix: createOuterNNS(Ctx, Namespace, FullyQualified, WithGlobalNsPrefix),
352 NS: Namespace);
353}
354
355NestedNameSpecifier *createNestedNameSpecifier(const ASTContext &Ctx,
356 const TypeDecl *TD,
357 bool FullyQualify,
358 bool WithGlobalNsPrefix) {
359 const Type *TypePtr = TD->getTypeForDecl();
360 if (isa<const TemplateSpecializationType>(Val: TypePtr) ||
361 isa<const RecordType>(Val: TypePtr)) {
362 // We are asked to fully qualify and we have a Record Type (which
363 // may point to a template specialization) or Template
364 // Specialization Type. We need to fully qualify their arguments.
365
366 TypePtr = getFullyQualifiedTemplateType(Ctx, TypePtr, WithGlobalNsPrefix);
367 }
368
369 return NestedNameSpecifier::Create(
370 Context: Ctx, Prefix: createOuterNNS(Ctx, TD, FullyQualify, WithGlobalNsPrefix), T: TypePtr);
371}
372
373/// Return the fully qualified type, including fully-qualified
374/// versions of any template parameters.
375QualType getFullyQualifiedType(QualType QT, const ASTContext &Ctx,
376 bool WithGlobalNsPrefix) {
377 // In case of myType* we need to strip the pointer first, fully
378 // qualify and attach the pointer once again.
379 if (isa<PointerType>(Val: QT.getTypePtr())) {
380 // Get the qualifiers.
381 Qualifiers Quals = QT.getQualifiers();
382 QT = getFullyQualifiedType(QT: QT->getPointeeType(), Ctx, WithGlobalNsPrefix);
383 QT = Ctx.getPointerType(T: QT);
384 // Add back the qualifiers.
385 QT = Ctx.getQualifiedType(T: QT, Qs: Quals);
386 return QT;
387 }
388
389 if (auto *MPT = dyn_cast<MemberPointerType>(Val: QT.getTypePtr())) {
390 // Get the qualifiers.
391 Qualifiers Quals = QT.getQualifiers();
392 // Fully qualify the pointee and class types.
393 QT = getFullyQualifiedType(QT: QT->getPointeeType(), Ctx, WithGlobalNsPrefix);
394 NestedNameSpecifier *Qualifier = getFullyQualifiedNestedNameSpecifier(
395 Ctx, Scope: MPT->getQualifier(), WithGlobalNsPrefix);
396 QT = Ctx.getMemberPointerType(T: QT, Qualifier,
397 Cls: MPT->getMostRecentCXXRecordDecl());
398 // Add back the qualifiers.
399 QT = Ctx.getQualifiedType(T: QT, Qs: Quals);
400 return QT;
401 }
402
403 // In case of myType& we need to strip the reference first, fully
404 // qualify and attach the reference once again.
405 if (isa<ReferenceType>(Val: QT.getTypePtr())) {
406 // Get the qualifiers.
407 bool IsLValueRefTy = isa<LValueReferenceType>(Val: QT.getTypePtr());
408 Qualifiers Quals = QT.getQualifiers();
409 QT = getFullyQualifiedType(QT: QT->getPointeeType(), Ctx, WithGlobalNsPrefix);
410 // Add the r- or l-value reference type back to the fully
411 // qualified one.
412 if (IsLValueRefTy)
413 QT = Ctx.getLValueReferenceType(T: QT);
414 else
415 QT = Ctx.getRValueReferenceType(T: QT);
416 // Add back the qualifiers.
417 QT = Ctx.getQualifiedType(T: QT, Qs: Quals);
418 return QT;
419 }
420
421 // Handle types with attributes such as `unique_ptr<int> _Nonnull`.
422 if (auto *AT = dyn_cast<AttributedType>(Val: QT.getTypePtr())) {
423 QualType NewModified =
424 getFullyQualifiedType(QT: AT->getModifiedType(), Ctx, WithGlobalNsPrefix);
425 QualType NewEquivalent =
426 getFullyQualifiedType(QT: AT->getEquivalentType(), Ctx, WithGlobalNsPrefix);
427 Qualifiers Qualifiers = QT.getLocalQualifiers();
428 return Ctx.getQualifiedType(
429 T: Ctx.getAttributedType(attrKind: AT->getAttrKind(), modifiedType: NewModified, equivalentType: NewEquivalent),
430 Qs: Qualifiers);
431 }
432
433 // Remove the part of the type related to the type being a template
434 // parameter (we won't report it as part of the 'type name' and it
435 // is actually make the code below to be more complex (to handle
436 // those)
437 while (isa<SubstTemplateTypeParmType>(Val: QT.getTypePtr())) {
438 // Get the qualifiers.
439 Qualifiers Quals = QT.getQualifiers();
440
441 QT = cast<SubstTemplateTypeParmType>(Val: QT.getTypePtr())->desugar();
442
443 // Add back the qualifiers.
444 QT = Ctx.getQualifiedType(T: QT, Qs: Quals);
445 }
446
447 NestedNameSpecifier *Prefix = nullptr;
448 // Local qualifiers are attached to the QualType outside of the
449 // elaborated type. Retrieve them before descending into the
450 // elaborated type.
451 Qualifiers PrefixQualifiers = QT.getLocalQualifiers();
452 QT = QualType(QT.getTypePtr(), 0);
453 ElaboratedTypeKeyword Keyword = ElaboratedTypeKeyword::None;
454 if (const auto *ETypeInput = dyn_cast<ElaboratedType>(Val: QT.getTypePtr())) {
455 QT = ETypeInput->getNamedType();
456 assert(!QT.hasLocalQualifiers());
457 Keyword = ETypeInput->getKeyword();
458 }
459
460 // We don't consider the alias introduced by `using a::X` as a new type.
461 // The qualified name is still a::X.
462 if (const auto *UT = QT->getAs<UsingType>()) {
463 QT = Ctx.getQualifiedType(T: UT->getUnderlyingType(), Qs: PrefixQualifiers);
464 return getFullyQualifiedType(QT, Ctx, WithGlobalNsPrefix);
465 }
466
467 // Create a nested name specifier if needed.
468 Prefix = createNestedNameSpecifierForScopeOf(Ctx, TypePtr: QT.getTypePtr(),
469 FullyQualified: true /*FullyQualified*/,
470 WithGlobalNsPrefix);
471
472 // In case of template specializations iterate over the arguments and
473 // fully qualify them as well.
474 if (isa<const TemplateSpecializationType>(Val: QT.getTypePtr()) ||
475 isa<const RecordType>(Val: QT.getTypePtr())) {
476 // We are asked to fully qualify and we have a Record Type (which
477 // may point to a template specialization) or Template
478 // Specialization Type. We need to fully qualify their arguments.
479
480 const Type *TypePtr = getFullyQualifiedTemplateType(
481 Ctx, TypePtr: QT.getTypePtr(), WithGlobalNsPrefix);
482 QT = QualType(TypePtr, 0);
483 }
484 if (Prefix || Keyword != ElaboratedTypeKeyword::None) {
485 QT = Ctx.getElaboratedType(Keyword, NNS: Prefix, NamedType: QT);
486 }
487 QT = Ctx.getQualifiedType(T: QT, Qs: PrefixQualifiers);
488 return QT;
489}
490
491std::string getFullyQualifiedName(QualType QT,
492 const ASTContext &Ctx,
493 const PrintingPolicy &Policy,
494 bool WithGlobalNsPrefix) {
495 QualType FQQT = getFullyQualifiedType(QT, Ctx, WithGlobalNsPrefix);
496 return FQQT.getAsString(Policy);
497}
498
499} // end namespace TypeName
500} // end namespace clang
501

Provided by KDAB

Privacy Policy
Learn to use CMake with our Intro Training
Find out more

source code of clang/lib/AST/QualTypeNames.cpp