Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TClingUtils.cxx
Go to the documentation of this file.
1// @(#)root/metautils:$Id$
2// Author: Paul Russo, 2009-10-06
3
4/*************************************************************************
5 * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12//______________________________________________________________________________
13// //
14// ROOT::TMetaUtils provides utility wrappers around //
15// cling, the LLVM-based interpreter. It's an internal set of tools //
16// used by TCling and rootcling. //
17// //
18//______________________________________________________________________________
19#include <algorithm>
20#include <iostream>
21#include <sstream>
22#include <stdlib.h>
23#include <stdio.h>
24#include <unordered_set>
25#include <cctype>
26
27#include "RConfigure.h"
28#include <ROOT/RConfig.hxx>
30#include "Rtypes.h"
31#include "strlcpy.h"
32
33#include "RStl.h"
34
35#include "clang/AST/ASTContext.h"
36#include "clang/AST/Attr.h"
37#include "clang/AST/CXXInheritance.h"
38#include "clang/AST/Decl.h"
39#include "clang/AST/DeclTemplate.h"
40#include "clang/AST/Mangle.h"
41#include "clang/AST/Type.h"
42#include "clang/AST/TypeVisitor.h"
43#include "clang/Frontend/CompilerInstance.h"
44#include "clang/Lex/HeaderSearch.h"
45#include "clang/Lex/ModuleMap.h"
46#include "clang/Lex/Preprocessor.h"
47#include "clang/Lex/PreprocessorOptions.h"
48
49#include "clang/Sema/Lookup.h"
50#include "clang/Sema/Sema.h"
51#include "clang/Sema/SemaDiagnostic.h"
52
53#include "cling/Interpreter/LookupHelper.h"
54#include "cling/Interpreter/Transaction.h"
55#include "cling/Interpreter/Interpreter.h"
56#include "cling/Utils/AST.h"
57
58#include "llvm/Support/Path.h"
59#include "llvm/Support/FileSystem.h"
60
61#include "TClingUtils.h"
62
63#ifdef _WIN32
64#define strncasecmp _strnicmp
65#include <io.h>
66#else
67#include <unistd.h>
68#endif // _WIN32
69
70namespace ROOT {
71namespace TMetaUtils {
72
73std::string GetRealPath(const std::string &path)
74{
75 llvm::SmallString<256> result_path;
76 llvm::sys::fs::real_path(path, result_path, /*expandTilde*/true);
77 return result_path.str().str();
78}
79
80
81////////////////////////////////////////////////////////////////////////////////
82
84 using DeclsCont_t = TNormalizedCtxt::Config_t::SkipCollection;
88private:
92public:
93 TNormalizedCtxtImpl(const cling::LookupHelper &lh);
94
95 const Config_t &GetConfig() const { return fConfig; }
97 void AddTemplAndNargsToKeep(const clang::ClassTemplateDecl* templ, unsigned int i);
98 int GetNargsToKeep(const clang::ClassTemplateDecl* templ) const;
100 void keepTypedef(const cling::LookupHelper &lh, const char* name,
101 bool replace = false);
102};
103}
104}
105
106namespace {
107
108////////////////////////////////////////////////////////////////////////////////
109/// Add default parameter to the scope if needed.
110
111static clang::NestedNameSpecifier *AddDefaultParametersNNS(const clang::ASTContext& Ctx,
112 clang::NestedNameSpecifier* scope,
113 const cling::Interpreter &interpreter,
115 if (!scope) return nullptr;
116
117 const clang::Type* scope_type = scope->getAsType();
118 if (scope_type) {
119 // this is not a namespace, so we might need to desugar
120 clang::NestedNameSpecifier* outer_scope = scope->getPrefix();
121 if (outer_scope) {
123 }
124
125 clang::QualType addDefault =
127 // NOTE: Should check whether the type has changed or not.
128 if (addDefault.getTypePtr() != scope_type)
129 return clang::NestedNameSpecifier::Create(Ctx,outer_scope,
130 false /* template keyword wanted */,
131 addDefault.getTypePtr());
132 }
133 return scope;
134}
135
136////////////////////////////////////////////////////////////////////////////////
137
138static bool CheckDefinition(const clang::CXXRecordDecl *cl, const clang::CXXRecordDecl *context)
139{
140 if (!cl->hasDefinition()) {
141 if (context) {
142 ROOT::TMetaUtils::Error("CheckDefinition",
143 "Missing definition for class %s, please #include its header in the header of %s\n",
144 cl->getName().str().c_str(), context->getName().str().c_str());
145 } else {
146 ROOT::TMetaUtils::Error("CheckDefinition",
147 "Missing definition for class %s\n",
148 cl->getName().str().c_str());
149 }
150 return false;
151 }
152 return true;
153}
154
155////////////////////////////////////////////////////////////////////////////////
156/// Check if 'scope' or any of its template parameter was substituted when
157/// instantiating the class template instance and replace it with the
158/// partially sugared types we have from 'instance'.
159
160static clang::NestedNameSpecifier *ReSubstTemplateArgNNS(const clang::ASTContext &Ctxt,
161 clang::NestedNameSpecifier *scope,
162 const clang::Type *instance)
163{
164 if (!scope) return nullptr;
165
166 const clang::Type* scope_type = scope->getAsType();
167 if (scope_type) {
168 clang::NestedNameSpecifier* outer_scope = scope->getPrefix();
169 if (outer_scope) {
171 }
172 clang::QualType substScope =
174 // NOTE: Should check whether the type has changed or not.
175 scope = clang::NestedNameSpecifier::Create(Ctxt,outer_scope,
176 false /* template keyword wanted */,
177 substScope.getTypePtr());
178 }
179 return scope;
180}
181
182////////////////////////////////////////////////////////////////////////////////
183
184static bool IsTypeInt(const clang::Type *type)
185{
186 const clang::BuiltinType * builtin = llvm::dyn_cast<clang::BuiltinType>(type->getCanonicalTypeInternal().getTypePtr());
187 if (builtin) {
188 return builtin->isInteger(); // builtin->getKind() == clang::BuiltinType::Int;
189 } else {
190 return false;
191 }
192}
193
194////////////////////////////////////////////////////////////////////////////////
195
196static bool IsFieldDeclInt(const clang::FieldDecl *field)
197{
198 return IsTypeInt(field->getType().getTypePtr());
199}
200
201////////////////////////////////////////////////////////////////////////////////
202/// Return a data member name 'what' in the class described by 'cl' if any.
203
204static const clang::FieldDecl *GetDataMemberFromAll(const clang::CXXRecordDecl &cl, llvm::StringRef what)
205{
206 clang::ASTContext &C = cl.getASTContext();
207 clang::DeclarationName DName = &C.Idents.get(what);
208 auto R = cl.lookup(DName);
209 for (const clang::NamedDecl *D : R)
211 return FD;
212 return nullptr;
213}
214
215////////////////////////////////////////////////////////////////////////////////
216/// Return a data member name 'what' in any of the base classes of the class described by 'cl' if any.
217
218static const clang::FieldDecl *GetDataMemberFromAllParents(clang::Sema &SemaR, const clang::CXXRecordDecl &cl, const char *what)
219{
220 clang::DeclarationName DName = &SemaR.Context.Idents.get(what);
221 clang::LookupResult R(SemaR, DName, clang::SourceLocation(),
222 clang::Sema::LookupOrdinaryName,
223 clang::Sema::ForExternalRedeclaration);
224 SemaR.LookupInSuper(R, &const_cast<clang::CXXRecordDecl&>(cl));
225 if (R.empty())
226 return nullptr;
227 return llvm::dyn_cast<const clang::FieldDecl>(R.getFoundDecl());
228}
229
230static
231cling::LookupHelper::DiagSetting ToLHDS(bool wantDiags) {
232 return wantDiags
233 ? cling::LookupHelper::WithDiagnostics
234 : cling::LookupHelper::NoDiagnostics;
235}
236
237} // end of anonymous namespace
238
239
240namespace ROOT {
241namespace TMetaUtils {
242
243////////////////////////////////////////////////////////////////////////////////
244/// Add to the internal map the pointer of a template as key and the number of
245/// template arguments to keep as value.
246
247void TNormalizedCtxtImpl::AddTemplAndNargsToKeep(const clang::ClassTemplateDecl* templ,
248 unsigned int i){
249 if (!templ){
250 Error("TNormalizedCtxt::AddTemplAndNargsToKeep",
251 "Tring to specify a number of template arguments to keep for a null pointer. Exiting without assigning any value.\n");
252 return;
253 }
254
255 const clang::ClassTemplateDecl* canTempl = templ->getCanonicalDecl();
256
257 if(fTemplatePtrArgsToKeepMap.count(canTempl)==1 &&
259 const std::string templateName (canTempl->getNameAsString());
260 const std::string i_str (std::to_string(i));
261 const std::string previousArgsToKeep(std::to_string(fTemplatePtrArgsToKeepMap[canTempl]));
262 Error("TNormalizedCtxt::AddTemplAndNargsToKeep",
263 "Tring to specify for template %s %s arguments to keep, while before this number was %s\n",
264 canTempl->getNameAsString().c_str(),
265 i_str.c_str(),
266 previousArgsToKeep.c_str());
267 }
268
270}
271////////////////////////////////////////////////////////////////////////////////
272/// Get from the map the number of arguments to keep.
273/// It uses the canonical decl of the template as key.
274/// If not present, returns -1.
275
276int TNormalizedCtxtImpl::GetNargsToKeep(const clang::ClassTemplateDecl* templ) const{
277 const clang::ClassTemplateDecl* constTempl = templ->getCanonicalDecl();
279 int nArgsToKeep = (thePairPtr != fTemplatePtrArgsToKeepMap.end() ) ? thePairPtr->second : -1;
280 return nArgsToKeep;
281}
282
283
284////////////////////////////////////////////////////////////////////////////////
285
286TNormalizedCtxt::TNormalizedCtxt(const cling::LookupHelper &lh):
288{}
289
293
303void TNormalizedCtxt::AddTemplAndNargsToKeep(const clang::ClassTemplateDecl* templ, unsigned int i)
304{
306}
307int TNormalizedCtxt::GetNargsToKeep(const clang::ClassTemplateDecl* templ) const
308{
309 return fImpl->GetNargsToKeep(templ);
310}
314void TNormalizedCtxt::keepTypedef(const cling::LookupHelper &lh, const char* name,
315 bool replace /*= false*/)
316{
317 return fImpl->keepTypedef(lh, name, replace);
318}
319
320std::string AnnotatedRecordDecl::BuildDemangledTypeInfo(const clang::RecordDecl *rDecl,
321 const std::string &normalizedName)
322{
323 // Types with strong typedefs must not be findable through demangled type names, or else
324 // the demangled name will resolve to both sinblings double / Double32_t.
325 if (normalizedName.find("Double32_t") != std::string::npos
326 || normalizedName.find("Float16_t") != std::string::npos)
327 return {};
328 std::unique_ptr<clang::MangleContext> mangleCtx(rDecl->getASTContext().createMangleContext());
329 std::string mangledName;
330 {
331 llvm::raw_string_ostream sstr(mangledName);
332 if (const clang::TypeDecl* TD = llvm::dyn_cast<clang::TypeDecl>(rDecl)) {
333 mangleCtx->mangleCXXRTTI(clang::QualType(TD->getTypeForDecl(), 0), sstr);
334 }
335 }
336 if (!mangledName.empty()) {
337 int errDemangle = 0;
338#ifdef WIN32
339 if (mangledName[0] == '\01')
340 mangledName.erase(0, 1);
343 static const char typeinfoNameFor[] = " `RTTI Type Descriptor'";
345 std::string demangledName = demangledTIName;
347#else
350 static const char typeinfoNameFor[] = "typeinfo for ";
353#endif
355 return demangledName;
356 } else {
357#ifdef WIN32
358 ROOT::TMetaUtils::Error("AnnotatedRecordDecl::BuildDemangledTypeInfo",
359 "Demangled typeinfo name '%s' does not contain `RTTI Type Descriptor'\n",
361#else
362 ROOT::TMetaUtils::Error("AnnotatedRecordDecl::BuildDemangledTypeInfo",
363 "Demangled typeinfo name '%s' does not start with 'typeinfo for'\n",
365#endif
366 } // if demangled type_info starts with "typeinfo for "
367 } // if demangling worked
369 } // if mangling worked
370 return {};
371}
372
373
374////////////////////////////////////////////////////////////////////////////////
375/// There is no requested type name.
376/// Still let's normalized the actual name.
377
378// clang-format off
402
403////////////////////////////////////////////////////////////////////////////////
404/// Normalize the requested type name.
405
406// clang-format off
408 const clang::Type *requestedType,
409 const clang::RecordDecl *decl,
410 const char *requestName,
411 unsigned int nTemplateArgsToSkip,
412 bool rStreamerInfo,
413 bool rNoStreamer,
418 const cling::Interpreter &interpreter,
420 : fRuleIndex(index),
421 fDecl(decl),
422 fRequestedName(""),
423 fRequestStreamerInfo(rStreamerInfo),
424 fRequestNoStreamer(rNoStreamer),
425 fRequestNoInputOperator(rRequestNoInputOperator),
426 fRequestOnlyTClass(rRequestOnlyTClass),
427 fRequestedVersionNumber(rRequestVersionNumber),
428 fRequestedRNTupleSerializationMode(rRequestedRNTupleSerializationMode)
429// clang-format on
430{
431 // For comparison purposes.
433 splitname1.ShortType(fRequestedName, 0);
434
437 ROOT::TMetaUtils::Warning("AnnotatedRecordDecl",
438 "Could not remove the requested template arguments.\n");
439 }
441}
442
443////////////////////////////////////////////////////////////////////////////////
444/// Normalize the requested type name.
445
446// clang-format off
448 const clang::Type *requestedType,
449 const clang::RecordDecl *decl,
450 const char *requestName,
451 bool rStreamerInfo,
452 bool rNoStreamer,
457 const cling::Interpreter &interpreter,
459 : fRuleIndex(index),
460 fDecl(decl),
461 fRequestedName(""),
462 fRequestStreamerInfo(rStreamerInfo),
463 fRequestNoStreamer(rNoStreamer),
464 fRequestNoInputOperator(rRequestNoInputOperator),
465 fRequestOnlyTClass(rRequestOnlyTClass),
466 fRequestedVersionNumber(rRequestVersionNumber),
467 fRequestedRNTupleSerializationMode(rRequestedRNTupleSerializationMode)
468// clang-format on
469{
470 // For comparison purposes.
472 splitname1.ShortType(fRequestedName, 0);
473
476}
477
478////////////////////////////////////////////////////////////////////////////////
479/// Normalize the requested name.
480
481// clang-format off
483 const clang::RecordDecl *decl,
484 const char *requestName,
485 bool rStreamerInfo,
486 bool rNoStreamer,
491 const cling::Interpreter &interpreter,
493 : fRuleIndex(index),
494 fDecl(decl),
495 fRequestedName(""),
496 fRequestStreamerInfo(rStreamerInfo),
497 fRequestNoStreamer(rNoStreamer),
498 fRequestNoInputOperator(rRequestNoInputOperator),
499 fRequestOnlyTClass(rRequestOnlyTClass),
500 fRequestedVersionNumber(rRequestVersionNumber),
501 fRequestedRNTupleSerializationMode(rRequestedRNTupleSerializationMode)
502// clang-format on
503{
504 // const clang::ClassTemplateSpecializationDecl *tmplt_specialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl> (decl);
505 // if (tmplt_specialization) {
506 // tmplt_specialization->getTemplateArgs ().data()->print(decl->getASTContext().getPrintingPolicy(),llvm::outs());
507 // llvm::outs() << "\n";
508 // }
509 // const char *current = requestName;
510 // Strips spaces and std::
511 if (requestName && requestName[0]) {
514
516 } else {
517 TMetaUtils::GetNormalizedName( fNormalizedName, decl->getASTContext().getTypeDeclType(decl),interpreter,normCtxt);
518 }
520}
521
522////////////////////////////////////////////////////////////////////////////////
523
526 ExistingTypeCheck_t existingTypeCheck,
527 AutoParse_t autoParse,
528 bool *shuttingDownPtr,
529 const int* pgDebug /*= 0*/):
530 fInterpreter(&interpreter),fNormalizedCtxt(&normCtxt),
531 fExistingTypeCheck(existingTypeCheck),
532 fAutoParse(autoParse),
533 fInterpreterIsShuttingDownPtr(shuttingDownPtr),
534 fPDebug(pgDebug)
535{
536}
537
538////////////////////////////////////////////////////////////////////////////////
539/// Helper routine to ry hard to avoid looking up in the Cling database as
540/// this could enduce an unwanted autoparsing.
541
543 std::string &result)
544{
545 if (tname.empty()) return false;
546
548 else return false;
549}
550
551////////////////////////////////////////////////////////////////////////////////
552
554{
555 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
556 clang::QualType t = lh.findType(nameLong, ToLHDS(WantDiags()));
557 if (!t.isNull()) {
558 clang::QualType dest = cling::utils::Transform::GetPartiallyDesugaredType(fInterpreter->getCI()->getASTContext(), t, fNormalizedCtxt->GetConfig(), true /* fully qualify */);
559 if (!dest.isNull() && (dest != t)) {
560 // getAsStringInternal() appends.
561 nameLong.clear();
562 dest.getAsStringInternal(nameLong, fInterpreter->getCI()->getASTContext().getPrintingPolicy());
563 }
564 }
565}
566
567////////////////////////////////////////////////////////////////////////////////
568
570 const std::string &nameLong)
571{
572 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
573 clang::QualType t = lh.findType(nondef.c_str(), ToLHDS(WantDiags()));
574 if (!t.isNull()) {
575 clang::QualType dest = cling::utils::Transform::GetPartiallyDesugaredType(fInterpreter->getCI()->getASTContext(), t, fNormalizedCtxt->GetConfig(), true /* fully qualify */);
576 if (!dest.isNull() && (dest != t) &&
577 nameLong == t.getAsString(fInterpreter->getCI()->getASTContext().getPrintingPolicy()))
578 return true;
579 }
580 return false;
581}
582
583////////////////////////////////////////////////////////////////////////////////
584
585bool TClingLookupHelper::IsDeclaredScope(const std::string &base, bool &isInlined)
586{
587 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
588 const clang::Decl *scope = lh.findScope(base.c_str(), ToLHDS(WantDiags()), nullptr);
589
590 if (!scope) {
591 // the nesting namespace is not declared
592 isInlined = false;
593 return false;
594 }
595 const clang::NamespaceDecl *nsdecl = llvm::dyn_cast<clang::NamespaceDecl>(scope);
596 isInlined = nsdecl && nsdecl->isInline();
597 return true;
598}
599
600////////////////////////////////////////////////////////////////////////////////
601/// We assume that we have a simple type:
602/// [const] typename[*&][const]
603
605 std::string &result,
606 bool dropstd /* = true */)
607{
608 if (tname.empty()) return false;
609
610 // Try hard to avoid looking up in the Cling database as this could enduce
611 // an unwanted autoparsing.
612 // Note: this is always done by the callers and thus is redundant.
613 // Maybe replace with
616 return ! result.empty();
617 }
618
619 if (fAutoParse) fAutoParse(tname.c_str());
620
621 // Since we already check via other means (TClassTable which is populated by
622 // the dictonary loading, and the gROOT list of classes and enums, which are
623 // populated via TProtoClass/Enum), we should be able to disable the autoloading
624 // ... which requires access to libCore or libCling ...
625 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
626 clang::QualType t = lh.findType(tname.c_str(), ToLHDS(WantDiags()));
627 // Technically we ought to try:
628 // if (t.isNull()) t = lh.findType(TClassEdit::InsertStd(tname), ToLHDS(WantDiags()));
629 // at least until the 'normalized name' contains the std:: prefix.
630
631 if (!t.isNull()) {
633 if (!dest.isNull() && dest != t) {
634 // Since our input is not a template instance name, rather than going through the full
635 // TMetaUtils::GetNormalizedName, we just do the 'strip leading std' and fix
636 // white space.
637 clang::PrintingPolicy policy(fInterpreter->getCI()->getASTContext().getPrintingPolicy());
638 policy.SuppressTagKeyword = true; // Never get the class or struct keyword
639 policy.SuppressScope = true; // Force the scope to be coming from a clang::ElaboratedType.
640 // The scope suppression is required for getting rid of the anonymous part of the name of a class defined in an anonymous namespace.
641 // This gives us more control vs not using the clang::ElaboratedType and relying on the Policy.SuppressUnwrittenScope which would
642 // strip both the anonymous and the inline namespace names (and we probably do not want the later to be suppressed).
643 // getAsStringInternal() appends.
644 result.clear();
645 dest.getAsStringInternal(result, policy);
646 // Strip the std::
647 unsigned long offset = 0;
648 if (strncmp(result.c_str(), "const ", 6) == 0) {
649 offset = 6;
650 }
651 if (dropstd && strncmp(result.c_str()+offset, "std::", 5) == 0) {
652 result.erase(offset,5);
653 }
654 for(unsigned int i = 1; i<result.length(); ++i) {
655 if (result[i]=='s') {
656 if (result[i-1]=='<' || result[i-1]==',' || result[i-1]==' ') {
657 if (dropstd && result.compare(i,5,"std::",5) == 0) {
658 result.erase(i,5);
659 }
660 }
661 }
662 if (result[i]==' ') {
663 if (result[i-1] == ',') {
664 result.erase(i,1);
665 --i;
666 } else if ( (i+1) < result.length() &&
667 (result[i+1]=='*' || result[i+1]=='&' || result[i+1]=='[') ) {
668 result.erase(i,1);
669 --i;
670 }
671 }
672 }
673
674// std::string alt;
675// TMetaUtils::GetNormalizedName(alt, dest, *fInterpreter, *fNormalizedCtxt);
676// if (alt != result) fprintf(stderr,"norm: %s vs result=%s\n",alt.c_str(),result.c_str());
677
678 return true;
679 }
680 }
681 return false;
682}
683
684////////////////////////////////////////////////////////////////////////////////
685// TClassEdit will call this routine as soon as any of its static variable (used
686// for caching) is destroyed.
692
693 } // end namespace ROOT
694} // end namespace TMetaUtils
695
696
697////////////////////////////////////////////////////////////////////////////////
698/// Insert the type with name into the collection of typedefs to keep.
699/// if replace, replace occurrences of the canonical type by name.
700
702 const char* name,
703 bool replace /*=false*/) {
704 clang::QualType toSkip = lh.findType(name, cling::LookupHelper::WithDiagnostics);
705 if (const clang::Type* T = toSkip.getTypePtr()) {
706 const clang::TypedefType *tt = llvm::dyn_cast<clang::TypedefType>(T);
707 if (!tt) return;
708 clang::Decl* D = tt->getDecl();
709 fConfig.m_toSkip.insert(D);
710 if (replace) {
711 clang::QualType canon = toSkip->getCanonicalTypeInternal();
712 fConfig.m_toReplace.insert(std::make_pair(canon.getTypePtr(),T));
713 } else {
714 fTypeWithAlternative.insert(T);
715 }
716 }
717}
718
719////////////////////////////////////////////////////////////////////////////////
720/// Initialize the list of typedef to keep (i.e. make them opaque for normalization)
721/// and the list of typedef whose semantic is different from their underlying type
722/// (Double32_t and Float16_t).
723/// This might be specific to an interpreter.
724
726{
727 keepTypedef(lh, "Double32_t");
728 keepTypedef(lh, "Float16_t");
729 keepTypedef(lh, "Long64_t", true);
730 keepTypedef(lh, "ULong64_t", true);
731
732 clang::QualType toSkip = lh.findType("string", cling::LookupHelper::WithDiagnostics);
733 if (!toSkip.isNull()) {
734 if (const clang::TypedefType* TT
735 = llvm::dyn_cast_or_null<clang::TypedefType>(toSkip.getTypePtr()))
736 fConfig.m_toSkip.insert(TT->getDecl());
737 }
738 toSkip = lh.findType("std::string", cling::LookupHelper::WithDiagnostics);
739 if (!toSkip.isNull()) {
740 if (const clang::TypedefType* TT
741 = llvm::dyn_cast_or_null<clang::TypedefType>(toSkip.getTypePtr()))
742 fConfig.m_toSkip.insert(TT->getDecl());
743
744 clang::QualType canon = toSkip->getCanonicalTypeInternal();
745 fConfig.m_toReplace.insert(std::make_pair(canon.getTypePtr(),toSkip.getTypePtr()));
746 }
747}
748
751
752////////////////////////////////////////////////////////////////////////////////
753
754inline bool IsTemplate(const clang::Decl &cl)
755{
756 return (cl.getKind() == clang::Decl::ClassTemplatePartialSpecialization
757 || cl.getKind() == clang::Decl::ClassTemplateSpecialization);
758}
759
760
761////////////////////////////////////////////////////////////////////////////////
762
763const clang::FunctionDecl* ROOT::TMetaUtils::ClassInfo__HasMethod(const clang::DeclContext *cl, const char* name,
764 const cling::Interpreter& interp)
765{
766 clang::Sema* S = &interp.getSema();
767 const clang::NamedDecl* ND = cling::utils::Lookup::Named(S, name, cl);
768 if (ND == (clang::NamedDecl*)-1)
769 return (clang::FunctionDecl*)-1;
770 return llvm::dyn_cast_or_null<clang::FunctionDecl>(ND);
771}
772
773////////////////////////////////////////////////////////////////////////////////
774/// Return the scope corresponding to 'name' or std::'name'
775
776const clang::CXXRecordDecl *
777ROOT::TMetaUtils::ScopeSearch(const char *name, const cling::Interpreter &interp,
778 bool /*diagnose*/, const clang::Type** resultType)
779{
780 const cling::LookupHelper& lh = interp.getLookupHelper();
781 // We have many bogus diagnostics if we allow diagnostics here. Suppress.
782 // FIXME: silence them in the callers.
783 const clang::CXXRecordDecl *result
784 = llvm::dyn_cast_or_null<clang::CXXRecordDecl>
785 (lh.findScope(name, cling::LookupHelper::NoDiagnostics, resultType));
786 if (!result) {
787 std::string std_name("std::");
788 std_name += name;
789 // We have many bogus diagnostics if we allow diagnostics here. Suppress.
790 // FIXME: silence them in the callers.
791 result = llvm::dyn_cast_or_null<clang::CXXRecordDecl>
792 (lh.findScope(std_name, cling::LookupHelper::NoDiagnostics, resultType));
793 }
794 return result;
795}
796
797
798////////////////////////////////////////////////////////////////////////////////
799
800bool ROOT::TMetaUtils::RequireCompleteType(const cling::Interpreter &interp, const clang::CXXRecordDecl *cl)
801{
802 clang::QualType qType(cl->getTypeForDecl(),0);
803 return RequireCompleteType(interp,cl->getLocation(),qType);
804}
805
806////////////////////////////////////////////////////////////////////////////////
807
808bool ROOT::TMetaUtils::RequireCompleteType(const cling::Interpreter &interp, clang::SourceLocation Loc, clang::QualType Type)
809{
810 clang::Sema& S = interp.getCI()->getSema();
811 // Here we might not have an active transaction to handle
812 // the caused instantiation decl.
813 cling::Interpreter::PushTransactionRAII RAII(const_cast<cling::Interpreter*>(&interp));
814 return S.RequireCompleteType(Loc, Type, clang::diag::err_incomplete_type);
815}
816
817////////////////////////////////////////////////////////////////////////////////
818
819bool ROOT::TMetaUtils::IsBase(const clang::CXXRecordDecl *cl, const clang::CXXRecordDecl *base,
820 const clang::CXXRecordDecl *context, const cling::Interpreter &interp)
821{
822 if (!cl || !base) {
823 return false;
824 }
825
826 if (!cl->getDefinition() || !cl->isCompleteDefinition()) {
828 }
829
830 if (!CheckDefinition(cl, context) || !CheckDefinition(base, context)) {
831 return false;
832 }
833
834 if (!base->hasDefinition()) {
835 ROOT::TMetaUtils::Error("IsBase", "Missing definition for class %s\n", base->getName().str().c_str());
836 return false;
837 }
838 return cl->isDerivedFrom(base);
839}
840
841////////////////////////////////////////////////////////////////////////////////
842
843bool ROOT::TMetaUtils::IsBase(const clang::FieldDecl &m, const char* basename, const cling::Interpreter &interp)
844{
845 const clang::CXXRecordDecl* CRD = llvm::dyn_cast<clang::CXXRecordDecl>(ROOT::TMetaUtils::GetUnderlyingRecordDecl(m.getType()));
846 if (!CRD) {
847 return false;
848 }
849
850 const clang::NamedDecl *base
851 = ScopeSearch(basename, interp, true /*diagnose*/, nullptr);
852
853 if (base) {
854 return IsBase(CRD, llvm::dyn_cast<clang::CXXRecordDecl>( base ),
855 llvm::dyn_cast<clang::CXXRecordDecl>(m.getDeclContext()),interp);
856 }
857 return false;
858}
859
860////////////////////////////////////////////////////////////////////////////////
861
863 const clang::NamedDecl &forcontext,
864 const clang::QualType &qti,
865 const char *R__t,int rwmode,
866 const cling::Interpreter &interp,
867 const char *tcl)
868{
869 static const clang::CXXRecordDecl *TObject_decl
870 = ROOT::TMetaUtils::ScopeSearch("TObject", interp, true /*diag*/, nullptr);
871 enum {
872 kBIT_ISTOBJECT = 0x10000000,
873 kBIT_HASSTREAMER = 0x20000000,
874 kBIT_ISSTRING = 0x40000000,
875
876 kBIT_ISPOINTER = 0x00001000,
877 kBIT_ISFUNDAMENTAL = 0x00000020,
878 kBIT_ISENUM = 0x00000008
879 };
880
881 const clang::Type &ti( * qti.getTypePtr() );
882 std::string tiName;
884
885 std::string objType(ROOT::TMetaUtils::ShortTypeName(tiName.c_str()));
886
887 const clang::Type *rawtype = ROOT::TMetaUtils::GetUnderlyingType(clang::QualType(&ti,0));
888 std::string rawname;
890
891 clang::CXXRecordDecl *cxxtype = rawtype->getAsCXXRecordDecl() ;
893 int isTObj = cxxtype && (IsBase(cxxtype,TObject_decl,nullptr,interp) || rawname == "TObject");
894
895 long kase = 0;
896
897 if (ti.isPointerType()) kase |= kBIT_ISPOINTER;
898 if (rawtype->isFundamentalType()) kase |= kBIT_ISFUNDAMENTAL;
899 if (rawtype->isEnumeralType()) kase |= kBIT_ISENUM;
900
901
902 if (isTObj) kase |= kBIT_ISTOBJECT;
904 if (tiName == "string") kase |= kBIT_ISSTRING;
905 if (tiName == "string*") kase |= kBIT_ISSTRING;
906
907
908 if (!tcl)
909 tcl = " internal error in rootcling ";
910 // if (strcmp(objType,"string")==0) RStl::Instance().GenerateTClassFor( "string", interp, normCtxt );
911
912 if (rwmode == 0) { //Read mode
913
914 if (R__t) finalString << " " << tiName << " " << R__t << ";" << std::endl;
915 switch (kase) {
916
918 if (!R__t) return 0;
919 finalString << " R__b >> " << R__t << ";" << std::endl;
920 break;
921
923 if (!R__t) return 1;
924 finalString << " " << R__t << " = (" << tiName << ")R__b.ReadObjectAny(" << tcl << ");" << std::endl;
925 break;
926
927 case kBIT_ISENUM:
928 if (!R__t) return 0;
929 // fprintf(fp, " R__b >> (Int_t&)%s;\n",R__t);
930 // On some platforms enums and not 'Int_t' and casting to a reference to Int_t
931 // induces the silent creation of a temporary which is 'filled' __instead of__
932 // the desired enum. So we need to take it one step at a time.
933 finalString << " Int_t readtemp;" << std::endl
934 << " R__b >> readtemp;" << std::endl
935 << " " << R__t << " = static_cast<" << tiName << ">(readtemp);" << std::endl;
936 break;
937
938 case kBIT_HASSTREAMER:
940 if (!R__t) return 0;
941 finalString << " " << R__t << ".Streamer(R__b);" << std::endl;
942 break;
943
945 if (!R__t) return 1;
946 //fprintf(fp, " fprintf(stderr,\"info is %%p %%d\\n\",R__b.GetInfo(),R__b.GetInfo()?R__b.GetInfo()->GetOldVersion():-1);\n");
947 finalString << " if (R__b.GetInfo() && R__b.GetInfo()->GetOldVersion()<=3) {" << std::endl;
948 if (cxxtype && cxxtype->isAbstract()) {
949 finalString << " R__ASSERT(0);// " << objType << " is abstract. We assume that older file could not be produced using this streaming method." << std::endl;
950 } else {
951 finalString << " " << R__t << " = new " << objType << ";" << std::endl
952 << " " << R__t << "->Streamer(R__b);" << std::endl;
953 }
954 finalString << " } else {" << std::endl
955 << " " << R__t << " = (" << tiName << ")R__b.ReadObjectAny(" << tcl << ");" << std::endl
956 << " }" << std::endl;
957 break;
958
959 case kBIT_ISSTRING:
960 if (!R__t) return 0;
961 finalString << " {TString R__str;" << std::endl
962 << " R__str.Streamer(R__b);" << std::endl
963 << " " << R__t << " = R__str.Data();}" << std::endl;
964 break;
965
966 case kBIT_ISSTRING|kBIT_ISPOINTER:
967 if (!R__t) return 0;
968 finalString << " {TString R__str;" << std::endl
969 << " R__str.Streamer(R__b);" << std::endl
970 << " " << R__t << " = new string(R__str.Data());}" << std::endl;
971 break;
972
973 case kBIT_ISPOINTER:
974 if (!R__t) return 1;
975 finalString << " " << R__t << " = (" << tiName << ")R__b.ReadObjectAny(" << tcl << ");" << std::endl;
976 break;
977
978 default:
979 if (!R__t) return 1;
980 finalString << " R__b.StreamObject(&" << R__t << "," << tcl << ");" << std::endl;
981 break;
982 }
983
984 } else { //Write case
985
986 switch (kase) {
987
990 if (!R__t) return 0;
991 finalString << " R__b << " << R__t << ";" << std::endl;
992 break;
993
994 case kBIT_ISENUM:
995 if (!R__t) return 0;
996 finalString << " { void *ptr_enum = (void*)&" << R__t << ";\n";
997 finalString << " R__b >> *reinterpret_cast<Int_t*>(ptr_enum); }" << std::endl;
998 break;
999
1000 case kBIT_HASSTREAMER:
1002 if (!R__t) return 0;
1003 finalString << " ((" << objType << "&)" << R__t << ").Streamer(R__b);" << std::endl;
1004 break;
1005
1007 if (!R__t) return 1;
1008 finalString << " R__b.WriteObjectAny(" << R__t << "," << tcl << ");" << std::endl;
1009 break;
1010
1011 case kBIT_ISSTRING:
1012 if (!R__t) return 0;
1013 finalString << " {TString R__str(" << R__t << ".c_str());" << std::endl
1014 << " R__str.Streamer(R__b);};" << std::endl;
1015 break;
1016
1017 case kBIT_ISSTRING|kBIT_ISPOINTER:
1018 if (!R__t) return 0;
1019 finalString << " {TString R__str(" << R__t << "->c_str());" << std::endl
1020 << " R__str.Streamer(R__b);}" << std::endl;
1021 break;
1022
1023 case kBIT_ISPOINTER:
1024 if (!R__t) return 1;
1025 finalString << " R__b.WriteObjectAny(" << R__t << "," << tcl <<");" << std::endl;
1026 break;
1027
1028 default:
1029 if (!R__t) return 1;
1030 finalString << " R__b.StreamObject((" << objType << "*)&" << R__t << "," << tcl << ");" << std::endl;
1031 break;
1032 }
1033 }
1034 return 0;
1035}
1036
1037////////////////////////////////////////////////////////////////////////////////
1038/// Checks if default constructor exists and accessible
1039
1040bool ROOT::TMetaUtils::CheckDefaultConstructor(const clang::CXXRecordDecl* cl, const cling::Interpreter& interpreter)
1041{
1042 clang::CXXRecordDecl* ncCl = const_cast<clang::CXXRecordDecl*>(cl);
1043
1044 // We may induce template instantiation
1045 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interpreter));
1046
1047 if (auto* Ctor = interpreter.getCI()->getSema().LookupDefaultConstructor(ncCl)) {
1048 if (Ctor->getAccess() == clang::AS_public && !Ctor->isDeleted()) {
1049 return true;
1050 }
1051 }
1052
1053 return false;
1054}
1055
1056
1057////////////////////////////////////////////////////////////////////////////////
1058/// Checks IO constructor - must be public and with specified argument
1059
1061 const char *typeOfArg,
1062 const clang::CXXRecordDecl *expectedArgType,
1063 const cling::Interpreter& interpreter)
1064{
1065 if (typeOfArg && !expectedArgType) {
1066 const cling::LookupHelper& lh = interpreter.getLookupHelper();
1067 // We can not use findScope since the type we are given are usually,
1068 // only forward declared (and findScope explicitly reject them).
1069 clang::QualType instanceType = lh.findType(typeOfArg, cling::LookupHelper::WithDiagnostics);
1070 if (!instanceType.isNull())
1071 expectedArgType = instanceType->getAsCXXRecordDecl();
1072 }
1073
1074 if (!expectedArgType)
1075 return EIOCtorCategory::kAbsent;
1076
1077 // FIXME: We should not iterate here. That costs memory!
1078 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interpreter));
1079 for (auto iter = cl->ctor_begin(), end = cl->ctor_end(); iter != end; ++iter)
1080 {
1081 if ((iter->getAccess() != clang::AS_public) || (iter->getNumParams() != 1))
1082 continue;
1083
1084 // We can reach this constructor.
1085 clang::QualType argType((*iter->param_begin())->getType());
1086 argType = argType.getDesugaredType(cl->getASTContext());
1087 // Deal with pointers and references: ROOT-7723
1088 auto ioCtorCategory = EIOCtorCategory::kAbsent;
1089 if (argType->isPointerType()) {
1090 ioCtorCategory = EIOCtorCategory::kIOPtrType;
1091 argType = argType->getPointeeType();
1092 } else if (argType->isReferenceType()) {
1093 ioCtorCategory = EIOCtorCategory::kIORefType;
1094 argType = argType.getNonReferenceType();
1095 } else
1096 continue;
1097
1098 argType = argType.getDesugaredType(cl->getASTContext());
1099 const clang::CXXRecordDecl *argDecl = argType->getAsCXXRecordDecl();
1100 if (argDecl) {
1101 if (argDecl->getCanonicalDecl() == expectedArgType->getCanonicalDecl()) {
1102 return ioCtorCategory;
1103 }
1104 } else {
1105 std::string realArg = argType.getAsString();
1106 std::string clarg("class ");
1107 clarg += typeOfArg;
1108 if (realArg == clarg)
1109 return ioCtorCategory;
1110 }
1111 } // for each constructor
1112
1113 return EIOCtorCategory::kAbsent;
1114}
1115
1116
1117////////////////////////////////////////////////////////////////////////////////
1118/// Check if class has constructor of provided type - either default or with single argument
1119
1122 const cling::Interpreter& interpreter)
1123{
1124 const char *arg = ioctortype.GetName();
1125
1126 if (!ioctortype.GetType() && (!arg || !arg[0])) {
1127 // We are looking for a constructor with zero non-default arguments.
1128
1129 return CheckDefaultConstructor(cl, interpreter) ? EIOCtorCategory::kDefault : EIOCtorCategory::kAbsent;
1130 }
1131
1132 return CheckIOConstructor(cl, arg, ioctortype.GetType(), interpreter);
1133}
1134
1135
1136////////////////////////////////////////////////////////////////////////////////
1137
1138const clang::CXXMethodDecl *GetMethodWithProto(const clang::Decl* cinfo,
1139 const char *method, const char *proto,
1140 const cling::Interpreter &interp,
1141 bool diagnose)
1142{
1143 const clang::FunctionDecl* funcD
1144 = interp.getLookupHelper().findFunctionProto(cinfo, method, proto,
1145 diagnose ? cling::LookupHelper::WithDiagnostics
1146 : cling::LookupHelper::NoDiagnostics);
1147 if (funcD)
1148 return llvm::dyn_cast<const clang::CXXMethodDecl>(funcD);
1149
1150 return nullptr;
1151}
1152
1153
1154////////////////////////////////////////////////////////////////////////////////
1155
1156namespace ROOT {
1157 namespace TMetaUtils {
1158 RConstructorType::RConstructorType(const char *type_of_arg, const cling::Interpreter &interp) : fArgTypeName(type_of_arg),fArgType(nullptr)
1159 {
1160 const cling::LookupHelper& lh = interp.getLookupHelper();
1161 // We can not use findScope since the type we are given are usually,
1162 // only forward declared (and findScope explicitly reject them).
1163 clang::QualType instanceType = lh.findType(type_of_arg, cling::LookupHelper::WithDiagnostics);
1164 if (!instanceType.isNull())
1165 fArgType = instanceType->getAsCXXRecordDecl();
1166 }
1167 const char *RConstructorType::GetName() const { return fArgTypeName.c_str(); }
1168 const clang::CXXRecordDecl *RConstructorType::GetType() const { return fArgType; }
1169 }
1170}
1171
1172////////////////////////////////////////////////////////////////////////////////
1173/// return true if we can find an constructor calleable without any arguments
1174/// or with one the IOCtor special types.
1175
1176bool ROOT::TMetaUtils::HasIOConstructor(const clang::CXXRecordDecl *cl,
1177 std::string& arg,
1179 const cling::Interpreter &interp)
1180{
1181 if (cl->isAbstract()) return false;
1182
1183 for (auto & ctorType : ctorTypes) {
1184
1186
1187 if (EIOCtorCategory::kAbsent == ioCtorCat)
1188 continue;
1189
1190 std::string proto( ctorType.GetName() );
1191 bool defaultCtor = proto.empty();
1192 if (defaultCtor) {
1193 arg.clear();
1194 } else {
1195 // I/O constructors can take pointers or references to ctorTypes
1196 proto += " *";
1197 if (EIOCtorCategory::kIOPtrType == ioCtorCat) {
1198 arg = "( ("; //(MyType*)nullptr
1199 } else if (EIOCtorCategory::kIORefType == ioCtorCat) {
1200 arg = "( *("; //*(MyType*)nullptr
1201 }
1202 arg += proto;
1203 arg += ")nullptr )";
1204 }
1205 // Check for private operator new
1206 const clang::CXXMethodDecl *method
1207 = GetMethodWithProto(cl, "operator new", "size_t", interp,
1208 cling::LookupHelper::NoDiagnostics);
1209 if (method && method->getAccess() != clang::AS_public) {
1210 // The non-public op new is not going to improve for other c'tors.
1211 return false;
1212 }
1213
1214 // This one looks good!
1215 return true;
1216 }
1217 return false;
1218}
1219
1220////////////////////////////////////////////////////////////////////////////////
1221
1222bool ROOT::TMetaUtils::NeedDestructor(const clang::CXXRecordDecl *cl,
1223 const cling::Interpreter& interp)
1224{
1225 if (!cl) return false;
1226
1227 if (cl->hasUserDeclaredDestructor()) {
1228
1229 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interp));
1230 clang::CXXDestructorDecl *dest = cl->getDestructor();
1231 if (dest) {
1232 return (dest->getAccess() == clang::AS_public);
1233 } else {
1234 return true; // no destructor, so let's assume it means default?
1235 }
1236 }
1237 return true;
1238}
1239
1240////////////////////////////////////////////////////////////////////////////////
1241/// Return true, if the function (defined by the name and prototype) exists and is public
1242
1243bool ROOT::TMetaUtils::CheckPublicFuncWithProto(const clang::CXXRecordDecl *cl,
1244 const char *methodname,
1245 const char *proto,
1246 const cling::Interpreter &interp,
1247 bool diagnose)
1248{
1249 const clang::CXXMethodDecl *method
1251 diagnose ? cling::LookupHelper::WithDiagnostics
1252 : cling::LookupHelper::NoDiagnostics);
1253 return (method && method->getAccess() == clang::AS_public);
1254}
1255
1256////////////////////////////////////////////////////////////////////////////////
1257/// Return true if the class has a method DirectoryAutoAdd(TDirectory *)
1258
1259bool ROOT::TMetaUtils::HasDirectoryAutoAdd(const clang::CXXRecordDecl *cl, const cling::Interpreter &interp)
1260{
1261 // Detect if the class has a DirectoryAutoAdd
1262
1263 // Detect if the class or one of its parent has a DirectoryAutoAdd
1264 const char *proto = "TDirectory*";
1265 const char *name = "DirectoryAutoAdd";
1266
1267 return CheckPublicFuncWithProto(cl,name,proto,interp, false /*diags*/);
1268}
1269
1270
1271////////////////////////////////////////////////////////////////////////////////
1272/// Return true if the class has a method Merge(TCollection*,TFileMergeInfo*)
1273
1274bool ROOT::TMetaUtils::HasNewMerge(const clang::CXXRecordDecl *cl, const cling::Interpreter &interp)
1275{
1276 // Detect if the class has a 'new' Merge function.
1277
1278 // Detect if the class or one of its parent has a DirectoryAutoAdd
1279 const char *proto = "TCollection*,TFileMergeInfo*";
1280 const char *name = "Merge";
1281
1282 return CheckPublicFuncWithProto(cl,name,proto,interp, false /*diags*/);
1283}
1284
1285////////////////////////////////////////////////////////////////////////////////
1286/// Return true if the class has a method Merge(TCollection*)
1287
1288bool ROOT::TMetaUtils::HasOldMerge(const clang::CXXRecordDecl *cl, const cling::Interpreter &interp)
1289{
1290 // Detect if the class has an old fashion Merge function.
1291
1292 // Detect if the class or one of its parent has a DirectoryAutoAdd
1293 const char *proto = "TCollection*";
1294 const char *name = "Merge";
1295
1296 return CheckPublicFuncWithProto(cl,name,proto, interp, false /*diags*/);
1297}
1298
1299
1300////////////////////////////////////////////////////////////////////////////////
1301/// Return true if the class has a method ResetAfterMerge(TFileMergeInfo *)
1302
1303bool ROOT::TMetaUtils::HasResetAfterMerge(const clang::CXXRecordDecl *cl, const cling::Interpreter &interp)
1304{
1305 // Detect if the class has a 'new' Merge function.
1306 // bool hasMethod = cl.HasMethod("DirectoryAutoAdd");
1307
1308 // Detect if the class or one of its parent has a DirectoryAutoAdd
1309 const char *proto = "TFileMergeInfo*";
1310 const char *name = "ResetAfterMerge";
1311
1312 return CheckPublicFuncWithProto(cl,name,proto, interp, false /*diags*/);
1313}
1314
1315
1316////////////////////////////////////////////////////////////////////////////////
1317/// Return true if the class has a custom member function streamer.
1318
1320 const clang::CXXRecordDecl* clxx,
1321 const cling::Interpreter &interp,
1323{
1324 static const char *proto = "TBuffer&";
1325
1326 const clang::CXXMethodDecl *method
1327 = GetMethodWithProto(clxx,"Streamer",proto, interp,
1328 cling::LookupHelper::NoDiagnostics);
1329 const clang::DeclContext *clxx_as_context = llvm::dyn_cast<clang::DeclContext>(clxx);
1330
1331 return (method && method->getDeclContext() == clxx_as_context
1332 && ( cl.RequestNoStreamer() || !cl.RequestStreamerInfo()));
1333}
1334
1335////////////////////////////////////////////////////////////////////////////////
1336/// Return true if the class has a custom member function streamer.
1337
1339 const clang::CXXRecordDecl* clxx,
1340 const cling::Interpreter &interp,
1342{
1343 static const char *proto = "TBuffer&,TClass*";
1344
1345 const clang::CXXMethodDecl *method
1346 = GetMethodWithProto(clxx,"Streamer",proto, interp,
1347 cling::LookupHelper::NoDiagnostics);
1348 const clang::DeclContext *clxx_as_context = llvm::dyn_cast<clang::DeclContext>(clxx);
1349
1350 return (method && method->getDeclContext() == clxx_as_context
1351 && ( cl.RequestNoStreamer() || !cl.RequestStreamerInfo()));
1352}
1353
1354
1355////////////////////////////////////////////////////////////////////////////////
1356/// Main implementation relying on GetFullyQualifiedTypeName
1357/// All other GetQualifiedName functions leverage this one except the
1358/// one for namespaces.
1359
1360void ROOT::TMetaUtils::GetQualifiedName(std::string &qual_name, const clang::QualType &type, const clang::NamedDecl &forcontext)
1361{
1363}
1364
1365//----
1366std::string ROOT::TMetaUtils::GetQualifiedName(const clang::QualType &type, const clang::NamedDecl &forcontext)
1367{
1368 std::string result;
1370 type,
1371 forcontext);
1372 return result;
1373}
1374
1375
1376////////////////////////////////////////////////////////////////////////////////
1377
1378void ROOT::TMetaUtils::GetQualifiedName(std::string& qual_type, const clang::Type &type, const clang::NamedDecl &forcontext)
1379{
1380 clang::QualType qualType(&type,0);
1382 qualType,
1383 forcontext);
1384}
1385
1386//---
1387std::string ROOT::TMetaUtils::GetQualifiedName(const clang::Type &type, const clang::NamedDecl &forcontext)
1388{
1389 std::string result;
1391 type,
1392 forcontext);
1393 return result;
1394}
1395
1396// //______________________________________________________________________________
1397// void ROOT::TMetaUtils::GetQualifiedName(std::string &qual_name, const clang::NamespaceDecl &cl)
1398// {
1399// GetQualifiedName(qual_name,cl);
1400// }
1401//
1402// //----
1403// std::string ROOT::TMetaUtils::GetQualifiedName(const clang::NamespaceDecl &cl){
1404// return GetQualifiedName(cl);
1405// }
1406
1407////////////////////////////////////////////////////////////////////////////////
1408/// This implementation does not rely on GetFullyQualifiedTypeName
1409
1410void ROOT::TMetaUtils::GetQualifiedName(std::string &qual_name, const clang::NamedDecl &cl)
1411{
1412 llvm::raw_string_ostream stream(qual_name);
1413 clang::PrintingPolicy policy( cl.getASTContext().getPrintingPolicy() );
1414 policy.SuppressTagKeyword = true; // Never get the class or struct keyword
1415 policy.SuppressUnwrittenScope = true; // Don't write the inline or anonymous namespace names.
1416
1417 cl.getNameForDiagnostic(stream,policy,true);
1418 stream.flush(); // flush to string.
1419
1420 if ( qual_name == "(anonymous " || qual_name == "(unnamed" ) {
1421 size_t pos = qual_name.find(':');
1422 qual_name.erase(0,pos+2);
1423 }
1424}
1425
1426//----
1427std::string ROOT::TMetaUtils::GetQualifiedName(const clang::NamedDecl &cl){
1428 std::string result;
1430 return result;
1431}
1432
1433
1434////////////////////////////////////////////////////////////////////////////////
1435
1436void ROOT::TMetaUtils::GetQualifiedName(std::string &qual_name, const clang::RecordDecl &recordDecl)
1437{
1438 const clang::Type* declType ( recordDecl.getTypeForDecl() );
1439 clang::QualType qualType(declType,0);
1441 qualType,
1442 recordDecl);
1443}
1444
1445//----
1446std::string ROOT::TMetaUtils::GetQualifiedName(const clang::RecordDecl &recordDecl)
1447{
1448 std::string result;
1450 return result;
1451}
1452
1453////////////////////////////////////////////////////////////////////////////////
1454
1459
1460//----
1467
1468////////////////////////////////////////////////////////////////////////////////
1469/// Create the data member name-type map for given class
1470
1471static void CreateNameTypeMap(const clang::CXXRecordDecl &cl, ROOT::MembersTypeMap_t& nameType)
1472{
1473 std::stringstream dims;
1474 std::string typenameStr;
1475
1476 const clang::ASTContext& astContext = cl.getASTContext();
1477
1478 // Loop over the non static data member.
1479 for(clang::RecordDecl::field_iterator field_iter = cl.field_begin(), end = cl.field_end();
1480 field_iter != end;
1481 ++field_iter){
1482 // The CINT based code was filtering away static variables (they are not part of
1483 // the list starting with field_begin in clang), and const enums (which should
1484 // also not be part of this list).
1485 // It was also filtering out the 'G__virtualinfo' artificial member.
1486
1487 typenameStr.clear();
1488 dims.str("");
1489 dims.clear();
1490
1491 clang::QualType fieldType(field_iter->getType());
1492 if (fieldType->isConstantArrayType()) {
1493 const clang::ConstantArrayType *arrayType = llvm::dyn_cast<clang::ConstantArrayType>(fieldType.getTypePtr());
1494 while (arrayType) {
1495 dims << "[" << arrayType->getSize().getLimitedValue() << "]";
1496 fieldType = arrayType->getElementType();
1497 arrayType = llvm::dyn_cast<clang::ConstantArrayType>(arrayType->getArrayElementTypeNoTypeQual());
1498 }
1499 }
1500
1502 nameType[field_iter->getName().str()] = ROOT::Internal::TSchemaType(typenameStr.c_str(),dims.str().c_str());
1503 }
1504
1505 // And now the base classes
1506 // We also need to look at the base classes.
1507 for(clang::CXXRecordDecl::base_class_const_iterator iter = cl.bases_begin(), end = cl.bases_end();
1508 iter != end;
1509 ++iter){
1510 std::string basename( iter->getType()->getAsCXXRecordDecl()->getNameAsString() ); // Intentionally using only the unqualified name.
1512 }
1513}
1514
1515////////////////////////////////////////////////////////////////////////////////
1516
1517const clang::FunctionDecl *ROOT::TMetaUtils::GetFuncWithProto(const clang::Decl* cinfo,
1518 const char *method,
1519 const char *proto,
1520 const cling::Interpreter &interp,
1521 bool diagnose)
1522{
1523 return interp.getLookupHelper().findFunctionProto(cinfo, method, proto,
1524 diagnose ? cling::LookupHelper::WithDiagnostics
1525 : cling::LookupHelper::NoDiagnostics);
1526}
1527
1528////////////////////////////////////////////////////////////////////////////////
1529/// It looks like the template specialization decl actually contains _less_ information
1530/// on the location of the code than the decl (in case where there is forward declaration,
1531/// that is what the specialization points to.
1532///
1533/// const clang::CXXRecordDecl* clxx = llvm::dyn_cast<clang::CXXRecordDecl>(decl);
1534/// if (clxx) {
1535/// switch(clxx->getTemplateSpecializationKind()) {
1536/// case clang::TSK_Undeclared:
1537/// // We want the default behavior
1538/// break;
1539/// case clang::TSK_ExplicitInstantiationDeclaration:
1540/// case clang::TSK_ExplicitInstantiationDefinition:
1541/// case clang::TSK_ImplicitInstantiation: {
1542/// // We want the location of the template declaration:
1543/// const clang::ClassTemplateSpecializationDecl *tmplt_specialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl> (clxx);
1544/// if (tmplt_specialization) {
1545/// return GetLineNumber(const_cast< clang::ClassTemplateSpecializationDecl *>(tmplt_specialization)->getSpecializedTemplate());
1546/// }
1547/// break;
1548/// }
1549/// case clang::TSK_ExplicitSpecialization:
1550/// // We want the default behavior
1551/// break;
1552/// default:
1553/// break;
1554/// }
1555/// }
1556
1558{
1559 clang::SourceLocation sourceLocation = decl->getLocation();
1560 clang::SourceManager& sourceManager = decl->getASTContext().getSourceManager();
1561
1562 if (!sourceLocation.isValid() ) {
1563 return -1;
1564 }
1565
1566 if (!sourceLocation.isFileID()) {
1567 sourceLocation = sourceManager.getExpansionRange(sourceLocation).getEnd();
1568 }
1569
1570 if (sourceLocation.isValid() && sourceLocation.isFileID()) {
1571 return sourceManager.getLineNumber(sourceManager.getFileID(sourceLocation),sourceManager.getFileOffset(sourceLocation));
1572 }
1573 else {
1574 return -1;
1575 }
1576}
1577
1578////////////////////////////////////////////////////////////////////////////////
1579/// Return true if the type is a Double32_t or Float16_t or
1580/// is a instance template that depends on Double32_t or Float16_t.
1581
1583{
1584 while (llvm::isa<clang::PointerType>(instanceType.getTypePtr())
1585 || llvm::isa<clang::ReferenceType>(instanceType.getTypePtr()))
1586 {
1587 instanceType = instanceType->getPointeeType();
1588 }
1589
1590 const clang::ElaboratedType* etype
1591 = llvm::dyn_cast<clang::ElaboratedType>(instanceType.getTypePtr());
1592 if (etype) {
1593 instanceType = clang::QualType(etype->getNamedType().getTypePtr(),0);
1594 }
1595
1596 // There is no typedef to worried about, except for the opaque ones.
1597
1598 // Technically we should probably used our own list with just
1599 // Double32_t and Float16_t
1600 if (normCtxt.GetTypeWithAlternative().count(instanceType.getTypePtr())) {
1601 return true;
1602 }
1603
1604
1605 bool result = false;
1606 const clang::CXXRecordDecl* clxx = instanceType->getAsCXXRecordDecl();
1607 if (clxx && clxx->getTemplateSpecializationKind() != clang::TSK_Undeclared) {
1608 // do the template thing.
1609 const clang::TemplateSpecializationType* TST
1610 = llvm::dyn_cast<const clang::TemplateSpecializationType>(instanceType.getTypePtr());
1611 if (!TST) {
1612 // std::string type_name;
1613 // type_name = GetQualifiedName( instanceType, *clxx );
1614 // fprintf(stderr,"ERROR: Could not findS TST for %s\n",type_name.c_str());
1615 return false;
1616 }
1617 for (const clang::TemplateArgument &TA : TST->template_arguments()) {
1618 if (TA.getKind() == clang::TemplateArgument::Type) {
1620 }
1621 }
1622 }
1623 return result;
1624}
1625
1626////////////////////////////////////////////////////////////////////////////////
1627/// Return true if any of the argument is or contains a double32.
1628
1630 const cling::Interpreter &interp,
1632{
1633 const clang::CXXRecordDecl *clxx = llvm::dyn_cast<clang::CXXRecordDecl>(cl.GetRecordDecl());
1634 if (!clxx || clxx->getTemplateSpecializationKind() == clang::TSK_Undeclared) return false;
1635
1636 clang::QualType instanceType = interp.getLookupHelper().findType(cl.GetNormalizedName(),
1637 cling::LookupHelper::WithDiagnostics);
1638 if (instanceType.isNull()) {
1639 //Error(0,"Could not find the clang::Type for %s\n",cl.GetNormalizedName());
1640 return false;
1641 }
1642
1644}
1645
1646////////////////////////////////////////////////////////////////////////////////
1647/// Extract attr string
1648
1650{
1651 clang::AnnotateAttr* annAttr = clang::dyn_cast<clang::AnnotateAttr>(attribute);
1652 if (!annAttr) {
1653 //TMetaUtils::Error(0,"Could not cast Attribute to AnnotatedAttribute\n");
1654 return 1;
1655 }
1656 attrString = annAttr->getAnnotation().str();
1657 return 0;
1658}
1659
1660////////////////////////////////////////////////////////////////////////////////
1661
1663{
1664 // if separator found, extract name and value
1665 size_t substrFound (attributeStr.find(propNames::separator));
1666 if (substrFound==std::string::npos) {
1667 //TMetaUtils::Error(0,"Could not find property name-value separator (%s)\n",ROOT::TMetaUtils::PropertyNameValSeparator.c_str());
1668 return 1;
1669 }
1670 size_t EndPart1 = attributeStr.find_first_of(propNames::separator) ;
1671 attrName = attributeStr.substr(0, EndPart1);
1672 const int separatorLength(propNames::separator.size());
1674 return 0;
1675}
1676
1677////////////////////////////////////////////////////////////////////////////////
1678
1679int ROOT::TMetaUtils::extractPropertyNameVal(clang::Attr* attribute, std::string& attrName, std::string& attrValue)
1680{
1681 std::string attrString;
1683 if (0!=ret) return ret;
1685}
1686
1687////////////////////////////////////////////////////////////////////////////////
1688/// This routine counts on the "propName<separator>propValue" format
1689
1691 const std::string& propName,
1692 std::string& propValue)
1693{
1694 for (clang::Decl::attr_iterator attrIt = decl.attr_begin();
1695 attrIt!=decl.attr_end();++attrIt){
1696 clang::AnnotateAttr* annAttr = clang::dyn_cast<clang::AnnotateAttr>(*attrIt);
1697 if (!annAttr) continue;
1698
1699 llvm::StringRef attribute = annAttr->getAnnotation();
1700 std::pair<llvm::StringRef,llvm::StringRef> split = attribute.split(propNames::separator.c_str());
1701 if (split.first != propName.c_str()) continue;
1702 else {
1703 propValue = split.second.str();
1704 return true;
1705 }
1706 }
1707 return false;
1708}
1709
1710////////////////////////////////////////////////////////////////////////////////
1711/// This routine counts on the "propName<separator>propValue" format
1712
1714 const std::string& propName,
1715 int& propValue)
1716{
1717 for (clang::Decl::attr_iterator attrIt = decl.attr_begin();
1718 attrIt!=decl.attr_end();++attrIt){
1719 clang::AnnotateAttr* annAttr = clang::dyn_cast<clang::AnnotateAttr>(*attrIt);
1720 if (!annAttr) continue;
1721
1722 llvm::StringRef attribute = annAttr->getAnnotation();
1723 std::pair<llvm::StringRef,llvm::StringRef> split = attribute.split(propNames::separator.c_str());
1724 if (split.first != propName.c_str()) continue;
1725 else {
1726 return split.second.getAsInteger(10,propValue);
1727 }
1728 }
1729 return false;
1730}
1731
1732////////////////////////////////////////////////////////////////////////////////
1733/// FIXME: a function of 450+ lines!
1734
1736 const AnnotatedRecordDecl &cl,
1737 const clang::CXXRecordDecl *decl,
1738 const cling::Interpreter &interp,
1741 bool& needCollectionProxy)
1742{
1743 std::string classname = TClassEdit::GetLong64_Name(cl.GetNormalizedName());
1744
1745 std::string mappedname;
1746 ROOT::TMetaUtils::GetCppName(mappedname,classname.c_str());
1747 std::string csymbol = classname;
1748 std::string args;
1749
1750 if ( ! TClassEdit::IsStdClass( classname.c_str() ) ) {
1751
1752 // Prefix the full class name with '::' except for the STL
1753 // containers and std::string. This is to request the
1754 // real class instead of the class in the namespace ROOT::Shadow
1755 csymbol.insert(0,"::");
1756 }
1757
1758 int stl = TClassEdit::IsSTLCont(classname);
1759 bool bset = TClassEdit::IsSTLBitset(classname.c_str());
1760
1761 bool isStd = TMetaUtils::IsStdClass(*decl);
1762 const cling::LookupHelper& lh = interp.getLookupHelper();
1763 bool isString = TMetaUtils::IsOfType(*decl,"std::string",lh);
1764
1765 bool isStdNotString = isStd && !isString;
1766
1767 finalString << "namespace ROOT {" << "\n";
1768
1769 if (!ClassInfo__HasMethod(decl,"Dictionary",interp) || IsTemplate(*decl))
1770 {
1771 finalString << " static TClass *" << mappedname.c_str() << "_Dictionary();\n"
1772 << " static void " << mappedname.c_str() << "_TClassManip(TClass*);\n";
1773
1774
1775 }
1776
1777 if (HasIOConstructor(decl, args, ctorTypes, interp)) {
1778 finalString << " static void *new_" << mappedname.c_str() << "(void *p = nullptr);" << "\n";
1779
1780 if (args.size()==0 && NeedDestructor(decl, interp))
1781 {
1782 finalString << " static void *newArray_";
1783 finalString << mappedname.c_str();
1784 finalString << "(Long_t size, void *p);";
1785 finalString << "\n";
1786 }
1787 }
1788
1789 if (NeedDestructor(decl, interp)) {
1790 finalString << " static void delete_" << mappedname.c_str() << "(void *p);" << "\n" << " static void deleteArray_" << mappedname.c_str() << "(void *p);" << "\n" << " static void destruct_" << mappedname.c_str() << "(void *p);" << "\n";
1791 }
1793 finalString << " static void directoryAutoAdd_" << mappedname.c_str() << "(void *obj, TDirectory *dir);" << "\n";
1794 }
1796 finalString << " static void streamer_" << mappedname.c_str() << "(TBuffer &buf, void *obj);" << "\n";
1797 }
1799 finalString << " static void conv_streamer_" << mappedname.c_str() << "(TBuffer &buf, void *obj, const TClass*);" << "\n";
1800 }
1802 finalString << " static Long64_t merge_" << mappedname.c_str() << "(void *obj, TCollection *coll,TFileMergeInfo *info);" << "\n";
1803 }
1805 finalString << " static void reset_" << mappedname.c_str() << "(void *obj, TFileMergeInfo *info);" << "\n";
1806 }
1807
1808 //--------------------------------------------------------------------------
1809 // Check if we have any schema evolution rules for this class
1810 /////////////////////////////////////////////////////////////////////////////
1811
1812 ROOT::SchemaRuleClassMap_t::iterator rulesIt1 = ROOT::gReadRules.find( classname.c_str() );
1813 ROOT::SchemaRuleClassMap_t::iterator rulesIt2 = ROOT::gReadRawRules.find( classname.c_str() );
1814
1816 CreateNameTypeMap( *decl, nameTypeMap ); // here types for schema evo are written
1817
1818 //--------------------------------------------------------------------------
1819 // Process the read rules
1820 /////////////////////////////////////////////////////////////////////////////
1821
1822 if( rulesIt1 != ROOT::gReadRules.end() ) {
1823 int i = 0;
1824 finalString << "\n // Schema evolution read functions\n";
1825 std::list<ROOT::SchemaRuleMap_t>::iterator rIt = rulesIt1->second.fRules.begin();
1826 while (rIt != rulesIt1->second.fRules.end()) {
1827
1828 //--------------------------------------------------------------------
1829 // Check if the rules refer to valid data members
1830 ///////////////////////////////////////////////////////////////////////
1831
1832 std::string error_string;
1834 Warning(nullptr, "%s", error_string.c_str());
1835 rIt = rulesIt1->second.fRules.erase(rIt);
1836 continue;
1837 }
1838
1839 //---------------------------------------------------------------------
1840 // Write the conversion function if necessary
1841 ///////////////////////////////////////////////////////////////////////
1842
1843 if( rIt->find( "code" ) != rIt->end() ) {
1845 }
1846 ++rIt;
1847 }
1848 }
1849
1850
1851
1852
1853 //--------------------------------------------------------------------------
1854 // Process the read raw rules
1855 /////////////////////////////////////////////////////////////////////////////
1856
1857 if( rulesIt2 != ROOT::gReadRawRules.end() ) {
1858 int i = 0;
1859 finalString << "\n // Schema evolution read raw functions\n";
1860 std::list<ROOT::SchemaRuleMap_t>::iterator rIt = rulesIt2->second.fRules.begin();
1861 while (rIt != rulesIt2->second.fRules.end()) {
1862
1863 //--------------------------------------------------------------------
1864 // Check if the rules refer to valid data members
1865 ///////////////////////////////////////////////////////////////////////
1866
1867 std::string error_string;
1869 Warning(nullptr, "%s", error_string.c_str());
1870 rIt = rulesIt2->second.fRules.erase(rIt);
1871 continue;
1872 }
1873
1874 //---------------------------------------------------------------------
1875 // Write the conversion function
1876 ///////////////////////////////////////////////////////////////////////
1877
1878 if( rIt->find( "code" ) == rIt->end() )
1879 continue;
1880
1882 ++rIt;
1883 }
1884 }
1885
1886 finalString << "\n" << " // Function generating the singleton type initializer" << "\n";
1887
1888 finalString << " static TGenericClassInfo *GenerateInitInstanceLocal(const " << csymbol << "*)" << "\n" << " {" << "\n";
1889
1890 finalString << " " << csymbol << " *ptr = nullptr;" << "\n";
1891
1892 //fprintf(fp, " static ::ROOT::ClassInfo< %s > \n",classname.c_str());
1893 if (ClassInfo__HasMethod(decl,"IsA",interp) ) {
1894 finalString << " static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< " << csymbol << " >(nullptr);" << "\n";
1895 }
1896 else {
1897 finalString << " static ::TVirtualIsAProxy* isa_proxy = new ::TIsAProxy(typeid(" << csymbol << "));" << "\n";
1898 }
1899 finalString << " static ::ROOT::TGenericClassInfo " << "\n" << " instance(\"" << classname.c_str() << "\", ";
1900
1901 if (ClassInfo__HasMethod(decl,"Class_Version",interp)) {
1902 finalString << csymbol << "::Class_Version(), ";
1903 } else if (bset) {
1904 finalString << "2, "; // bitset 'version number'
1905 } else if (stl) {
1906 finalString << "-2, "; // "::TStreamerInfo::Class_Version(), ";
1907 } else if( cl.HasClassVersion() ) {
1908 finalString << cl.RequestedVersionNumber() << ", ";
1909 } else { // if (cl_input.RequestStreamerInfo()) {
1910
1911 // Need to find out if the operator>> is actually defined for this class.
1912 static const char *versionFunc = "GetClassVersion";
1913 // int ncha = strlen(classname.c_str())+strlen(versionFunc)+5;
1914 // char *funcname= new char[ncha];
1915 // snprintf(funcname,ncha,"%s<%s >",versionFunc,classname.c_str());
1916 std::string proto = classname + "*";
1917 const clang::Decl* ctxt = llvm::dyn_cast<clang::Decl>((*cl).getDeclContext());
1918 const clang::FunctionDecl *methodinfo
1920 interp, cling::LookupHelper::NoDiagnostics);
1921 // delete [] funcname;
1922
1923 if (methodinfo &&
1924 ROOT::TMetaUtils::GetFileName(*methodinfo, interp).find("Rtypes.h") == llvm::StringRef::npos) {
1925
1926 // GetClassVersion was defined in the header file.
1927 //fprintf(fp, "GetClassVersion((%s *)0x0), ",classname.c_str());
1928 finalString << "GetClassVersion< ";
1929 finalString << classname.c_str();
1930 finalString << " >(), ";
1931 }
1932 //static char temporary[1024];
1933 //sprintf(temporary,"GetClassVersion<%s>( (%s *) 0x0 )",classname.c_str(),classname.c_str());
1934 //fprintf(stderr,"DEBUG: %s has value %d\n",classname.c_str(),(int)G__int(G__calc(temporary)));
1935 }
1936
1937 std::string filename = ROOT::TMetaUtils::GetFileName(*cl, interp);
1938 if (filename.length() > 0) {
1939 for (unsigned int i=0; i<filename.length(); i++) {
1940 if (filename[i]=='\\') filename[i]='/';
1941 }
1942 }
1943 finalString << "\"" << filename << "\", " << ROOT::TMetaUtils::GetLineNumber(cl)
1944 << "," << "\n" << " typeid(" << csymbol
1945 << "), ::ROOT::Internal::DefineBehavior(ptr, ptr)," << "\n" << " ";
1946
1947 if (ClassInfo__HasMethod(decl,"Dictionary",interp) && !IsTemplate(*decl)) {
1948 finalString << "&" << csymbol << "::Dictionary, ";
1949 } else {
1950 finalString << "&" << mappedname << "_Dictionary, ";
1951 }
1952
1953 enum {
1954 TClassTable__kHasCustomStreamerMember = 0x10 // See TClassTable.h
1955 };
1956
1957 Int_t rootflag = cl.RootFlag();
1960 }
1961 finalString << "isa_proxy, " << rootflag << "," << "\n" << " sizeof(" << csymbol << ") );" << "\n";
1962 if (HasIOConstructor(decl, args, ctorTypes, interp)) {
1963 finalString << " instance.SetNew(&new_" << mappedname.c_str() << ");" << "\n";
1964 if (args.size()==0 && NeedDestructor(decl, interp))
1965 finalString << " instance.SetNewArray(&newArray_" << mappedname.c_str() << ");" << "\n";
1966 }
1967 if (NeedDestructor(decl, interp)) {
1968 finalString << " instance.SetDelete(&delete_" << mappedname.c_str() << ");" << "\n" << " instance.SetDeleteArray(&deleteArray_" << mappedname.c_str() << ");" << "\n" << " instance.SetDestructor(&destruct_" << mappedname.c_str() << ");" << "\n";
1969 }
1971 finalString << " instance.SetDirectoryAutoAdd(&directoryAutoAdd_" << mappedname.c_str() << ");" << "\n";
1972 }
1974 // We have a custom member function streamer or an older (not StreamerInfo based) automatic streamer.
1975 finalString << " instance.SetStreamerFunc(&streamer_" << mappedname.c_str() << ");" << "\n";
1976 }
1978 // We have a custom member function streamer or an older (not StreamerInfo based) automatic streamer.
1979 finalString << " instance.SetConvStreamerFunc(&conv_streamer_" << mappedname.c_str() << ");" << "\n";
1980 }
1982 finalString << " instance.SetMerge(&merge_" << mappedname.c_str() << ");" << "\n";
1983 }
1985 finalString << " instance.SetResetAfterMerge(&reset_" << mappedname.c_str() << ");" << "\n";
1986 }
1987 if (bset) {
1988 finalString << " instance.AdoptCollectionProxyInfo(TCollectionProxyInfo::Generate(TCollectionProxyInfo::" << "Pushback" << "<Internal::TStdBitsetHelper< " << classname.c_str() << " > >()));" << "\n";
1989
1990 needCollectionProxy = true;
1991 } else if (stl != 0 &&
1992 ((stl > 0 && stl<ROOT::kSTLend) || (stl < 0 && stl>-ROOT::kSTLend)) && // is an stl container
1993 (stl != ROOT::kSTLbitset && stl !=-ROOT::kSTLbitset) ){ // is no bitset
1994 int idx = classname.find("<");
1995 int stlType = (idx!=(int)std::string::npos) ? TClassEdit::STLKind(classname.substr(0,idx)) : 0;
1996 const char* methodTCP = nullptr;
1997 switch(stlType) {
1998 case ROOT::kSTLvector:
1999 case ROOT::kSTLlist:
2000 case ROOT::kSTLdeque:
2001 case ROOT::kROOTRVec:
2002 methodTCP="Pushback";
2003 break;
2005 methodTCP="Pushfront";
2006 break;
2007 case ROOT::kSTLmap:
2008 case ROOT::kSTLmultimap:
2011 methodTCP="MapInsert";
2012 break;
2013 case ROOT::kSTLset:
2014 case ROOT::kSTLmultiset:
2017 methodTCP="Insert";
2018 break;
2019 }
2020 // FIXME Workaround: for the moment we do not generate coll proxies with unique ptrs since
2021 // they imply copies and therefore do not compile.
2022 auto classNameForIO = TClassEdit::GetNameForIO(classname);
2023 finalString << " instance.AdoptCollectionProxyInfo(TCollectionProxyInfo::Generate(TCollectionProxyInfo::" << methodTCP << "< " << classNameForIO.c_str() << " >()));" << "\n";
2024
2025 needCollectionProxy = true;
2026 }
2027
2028 //---------------------------------------------------------------------------
2029 // Register Alternate spelling of the class name.
2030 /////////////////////////////////////////////////////////////////////////////
2031
2032 if (cl.GetRequestedName()[0] && classname != cl.GetRequestedName()) {
2033 finalString << "\n" << " instance.AdoptAlternate(::ROOT::AddClassAlternate(\""
2034 << classname << "\",\"" << cl.GetRequestedName() << "\"));\n";
2035 }
2036
2037 if (!cl.GetDemangledTypeInfo().empty()
2038 && cl.GetDemangledTypeInfo() != classname
2039 && cl.GetDemangledTypeInfo() != cl.GetRequestedName()) {
2040 finalString << "\n" << " instance.AdoptAlternate(::ROOT::AddClassAlternate(\""
2041 << classname << "\",\"" << cl.GetDemangledTypeInfo() << "\"));\n";
2042
2043 }
2044
2045 //---------------------------------------------------------------------------
2046 // Pass the schema evolution rules to TGenericClassInfo
2047 /////////////////////////////////////////////////////////////////////////////
2048
2049 if( (rulesIt1 != ROOT::gReadRules.end() && rulesIt1->second.size()>0) || (rulesIt2 != ROOT::gReadRawRules.end() && rulesIt2->second.size()>0) ) {
2050 finalString << "\n" << " ::ROOT::Internal::TSchemaHelper* rule;" << "\n";
2051 }
2052
2053 if( rulesIt1 != ROOT::gReadRules.end() ) {
2054 finalString << "\n" << " // the io read rules" << "\n" << " std::vector<::ROOT::Internal::TSchemaHelper> readrules(" << rulesIt1->second.size() << ");" << "\n";
2055 ROOT::WriteSchemaList(rulesIt1->second.fRules, "readrules", finalString);
2056 finalString << " instance.SetReadRules( readrules );" << "\n";
2057 rulesIt1->second.fGenerated = true;
2058 }
2059
2060 if( rulesIt2 != ROOT::gReadRawRules.end() ) {
2061 finalString << "\n" << " // the io read raw rules" << "\n" << " std::vector<::ROOT::Internal::TSchemaHelper> readrawrules(" << rulesIt2->second.size() << ");" << "\n";
2062 ROOT::WriteSchemaList(rulesIt2->second.fRules, "readrawrules", finalString);
2063 finalString << " instance.SetReadRawRules( readrawrules );" << "\n";
2064 rulesIt2->second.fGenerated = true;
2065 }
2066
2067 finalString << " return &instance;" << "\n" << " }" << "\n";
2068
2070 // The GenerateInitInstance for STL are not unique and should not be externally accessible
2071 finalString << " TGenericClassInfo *GenerateInitInstance(const " << csymbol << "*)" << "\n" << " {\n return GenerateInitInstanceLocal(static_cast<" << csymbol << "*>(nullptr));\n }" << "\n";
2072 }
2073
2074 finalString << " // Static variable to force the class initialization" << "\n";
2075 // must be one long line otherwise UseDummy does not work
2076
2077
2078 finalString << " static ::ROOT::TGenericClassInfo *_R__UNIQUE_DICT_(Init) = GenerateInitInstanceLocal(static_cast<const " << csymbol << "*>(nullptr)); R__UseDummy(_R__UNIQUE_DICT_(Init));" << "\n";
2079
2080 if (!ClassInfo__HasMethod(decl,"Dictionary",interp) || IsTemplate(*decl)) {
2081 finalString << "\n" << " // Dictionary for non-ClassDef classes" << "\n"
2082 << " static TClass *" << mappedname << "_Dictionary() {\n"
2083 << " TClass* theClass ="
2084 << "::ROOT::GenerateInitInstanceLocal(static_cast<const " << csymbol << "*>(nullptr))->GetClass();\n"
2085 << " " << mappedname << "_TClassManip(theClass);\n";
2086 finalString << " return theClass;\n";
2087 finalString << " }\n\n";
2088
2089 // Now manipulate tclass in order to percolate the properties expressed as
2090 // annotations of the decls.
2091 std::string manipString;
2092 std::string attribute_s;
2093 std::string attrName, attrValue;
2094 // Class properties
2095 bool attrMapExtracted = false;
2096 if (decl->hasAttrs()){
2097 // Loop on the attributes
2098 for (clang::Decl::attr_iterator attrIt = decl->attr_begin();
2099 attrIt!=decl->attr_end();++attrIt){
2101 continue;
2102 }
2104 continue;
2105 }
2106 if (attrName == "name" ||
2107 attrName == "pattern" ||
2108 attrName == "rootmap") continue;
2109 // A general property
2110 // 1) We need to create the property map (in the gen code)
2111 // 2) we need to take out the map (in the gen code)
2112 // 3) We need to bookkep the fact that the map is created and out (in this source)
2113 // 4) We fill the map (in the gen code)
2114 if (!attrMapExtracted){
2115 manipString+=" theClass->CreateAttributeMap();\n";
2116 manipString+=" TDictAttributeMap* attrMap( theClass->GetAttributeMap() );\n";
2117 attrMapExtracted=true;
2118 }
2119 manipString+=" attrMap->AddProperty(\""+attrName +"\",\""+attrValue+"\");\n";
2120 }
2121 } // end of class has properties
2122
2123 // Member properties
2124 // Loop on declarations inside the class, including data members
2125 for(clang::CXXRecordDecl::decl_iterator internalDeclIt = decl->decls_begin();
2126 internalDeclIt != decl->decls_end(); ++internalDeclIt){
2127 if (!(!(*internalDeclIt)->isImplicit()
2128 && (clang::isa<clang::FieldDecl>(*internalDeclIt) ||
2129 clang::isa<clang::VarDecl>(*internalDeclIt)))) continue; // Check if it's a var or a field
2130
2131 // Now let's check the attributes of the var/field
2132 if (!internalDeclIt->hasAttrs()) continue;
2133
2134 attrMapExtracted = false;
2135 bool memberPtrCreated = false;
2136
2137 for (clang::Decl::attr_iterator attrIt = internalDeclIt->attr_begin();
2138 attrIt!=internalDeclIt->attr_end();++attrIt){
2139
2140 // Get the attribute as string
2142 continue;
2143 }
2144
2145 // Check the name of the decl
2146 clang::NamedDecl* namedInternalDecl = clang::dyn_cast<clang::NamedDecl> (*internalDeclIt);
2147 if (!namedInternalDecl) {
2148 TMetaUtils::Error(nullptr, "Cannot convert field declaration to clang::NamedDecl");
2149 continue;
2150 }
2151 const std::string memberName(namedInternalDecl->getName());
2152 const std::string cppMemberName = "theMember_"+memberName;
2153
2154 // Prepare a string to get the data member, it can be used later.
2155 const std::string dataMemberCreation= " TDataMember* "+cppMemberName+" = theClass->GetDataMember(\""+memberName+"\");\n";
2156
2157 // Let's now attack regular properties
2158
2160 continue;
2161 }
2162
2163 // Skip these
2164 if (attrName == propNames::comment ||
2165 attrName == propNames::iotype ||
2166 attrName == propNames::ioname ) continue;
2167
2168 if (!memberPtrCreated){
2170 memberPtrCreated=true;
2171 }
2172
2173 if (!attrMapExtracted){
2174 manipString+=" "+cppMemberName+"->CreateAttributeMap();\n";
2175 manipString+=" TDictAttributeMap* memberAttrMap_"+memberName+"( theMember_"+memberName+"->GetAttributeMap() );\n";
2176 attrMapExtracted=true;
2177 }
2178
2179 manipString+=" memberAttrMap_"+memberName+"->AddProperty(\""+attrName +"\",\""+attrValue+"\");\n";
2180
2181
2182 } // End loop on attributes
2183 } // End loop on internal declarations
2184
2185
2186 finalString << " static void " << mappedname << "_TClassManip(TClass* " << (manipString.empty() ? "":"theClass") << "){\n"
2187 << manipString
2188 << " }\n\n";
2189 } // End of !ClassInfo__HasMethod(decl,"Dictionary") || IsTemplate(*decl))
2190
2191 finalString << "} // end of namespace ROOT" << "\n" << "\n";
2192}
2193
2195 std::vector<std::string> &standaloneTargets,
2196 const cling::Interpreter &interp)
2197{
2199 if (!rulesIt1.second.fGenerated) {
2200 const clang::Type *typeptr = nullptr;
2201 const clang::CXXRecordDecl *target =
2202 ROOT::TMetaUtils::ScopeSearch(rulesIt1.first.c_str(), interp, true /*diag*/, &typeptr);
2203
2204 if (!target && !rulesIt1.second.fTargetDecl) {
2205 auto &&nRules = rulesIt1.second.size();
2206 std::string rule{nRules > 1 ? "rules" : "rule"};
2207 std::string verb{nRules > 1 ? "were" : "was"};
2208 ROOT::TMetaUtils::Warning(nullptr, "%d %s for target class %s %s not used!\n", nRules, rule.c_str(),
2209 rulesIt1.first.c_str(), verb.c_str());
2210 continue;
2211 }
2212
2215
2216 std::string name;
2218
2219 std::string mappedname;
2221
2222 finalString << "namespace ROOT {" << "\n";
2223 // Also TClingUtils.cxx:1823
2224 int i = 0;
2225 finalString << "\n // Schema evolution read functions\n";
2226 std::list<ROOT::SchemaRuleMap_t>::iterator rIt = rulesIt1.second.fRules.begin();
2227 while (rIt != rulesIt1.second.fRules.end()) {
2228
2229 //--------------------------------------------------------------------
2230 // Check if the rules refer to valid data members
2231 ///////////////////////////////////////////////////////////////////////
2232
2233 std::string error_string;
2235 ROOT::TMetaUtils::Warning(nullptr, "%s", error_string.c_str());
2236 rIt = rulesIt1.second.fRules.erase(rIt);
2237 continue;
2238 }
2239
2240 //---------------------------------------------------------------------
2241 // Write the conversion function if necessary
2242 ///////////////////////////////////////////////////////////////////////
2243
2244 if (rIt->find("code") != rIt->end()) {
2245 if (rawrules)
2247 else
2249 }
2250 ++rIt;
2251 }
2252 finalString << "} // namespace ROOT" << "\n";
2253
2254 standaloneTargets.push_back(rulesIt1.first);
2255 rulesIt1.second.fGenerated = true;
2256 }
2257 }
2258}
2259
2261 const std::vector<std::string> &standaloneTargets)
2262{
2263 std::string functionname("RecordReadRules_");
2265
2266 finalString << "namespace ROOT {" << "\n";
2267 finalString << " // Registration Schema evolution read functions\n";
2268 finalString << " int " << functionname << "() {" << "\n";
2269 if (!standaloneTargets.empty())
2270 finalString << "\n"
2271 << " ::ROOT::Internal::TSchemaHelper* rule;" << "\n";
2272 for (const auto &target : standaloneTargets) {
2273 std::string name;
2275
2276 ROOT::SchemaRuleClassMap_t::iterator rulesIt1 = ROOT::gReadRules.find(target.c_str());
2277 finalString << " {\n";
2278 if (rulesIt1 != ROOT::gReadRules.end()) {
2279 finalString << " // the io read rules for " << target << "\n";
2280 finalString << " std::vector<::ROOT::Internal::TSchemaHelper> readrules(" << rulesIt1->second.size()
2281 << ");" << "\n";
2282 ROOT::WriteSchemaList(rulesIt1->second.fRules, "readrules", finalString);
2283 finalString << " TClass::RegisterReadRules(TSchemaRule::kReadRule, \"" << name
2284 << "\", std::move(readrules));\n";
2285 rulesIt1->second.fGenerated = true;
2286 }
2287 ROOT::SchemaRuleClassMap_t::iterator rulesIt2 = ROOT::gReadRawRules.find(target.c_str());
2288 if (rulesIt2 != ROOT::gReadRawRules.end()) {
2289 finalString << "\n // the io read raw rules for " << target << "\n";
2290 finalString << " std::vector<::ROOT::Internal::TSchemaHelper> readrawrules(" << rulesIt2->second.size()
2291 << ");" << "\n";
2292 ROOT::WriteSchemaList(rulesIt2->second.fRules, "readrawrules", finalString);
2293 finalString << " TClass::RegisterReadRules(TSchemaRule::kReadRawRule, \"" << name
2294 << "\", std::move(readrawrules));\n";
2295 rulesIt2->second.fGenerated = true;
2296 }
2297 finalString << " }\n";
2298 }
2299 finalString << " return 0;\n";
2300 finalString << " }\n";
2301 finalString << " static int _R__UNIQUE_DICT_(ReadRules_" << dictName << ") = " << functionname << "();";
2302 finalString << "R__UseDummy(_R__UNIQUE_DICT_(ReadRules_" << dictName << "));" << "\n";
2303 finalString << "} // namespace ROOT" << "\n";
2304}
2305
2306////////////////////////////////////////////////////////////////////////////////
2307/// Return true if one of the class' enclosing scope is a namespace and
2308/// set fullname to the fully qualified name,
2309/// clsname to the name within a namespace
2310/// and nsname to the namespace fully qualified name.
2311
2313 std::string &clsname,
2314 std::string &nsname,
2315 const clang::CXXRecordDecl *cl)
2316{
2317 fullname.clear();
2318 nsname.clear();
2319
2321 clsname = fullname;
2322
2323 // Inline namespace are stripped from the normalized name, we need to
2324 // strip it from the prefix we want to remove.
2325 auto ctxt = cl->getEnclosingNamespaceContext();
2326 while(ctxt && ctxt!=cl && ctxt->isInlineNamespace()) {
2327 ctxt = ctxt->getParent();
2328 }
2329 if (ctxt) {
2330 const clang::NamedDecl *namedCtxt = llvm::dyn_cast<clang::NamedDecl>(ctxt);
2331 if (namedCtxt && namedCtxt!=cl) {
2332 const clang::NamespaceDecl *nsdecl = llvm::dyn_cast<clang::NamespaceDecl>(namedCtxt);
2333 if (nsdecl && !nsdecl->isAnonymousNamespace()) {
2335 clsname.erase (0, nsname.size() + 2);
2336 return true;
2337 }
2338 }
2339 }
2340 return false;
2341}
2342
2343////////////////////////////////////////////////////////////////////////////////
2344
2345const clang::DeclContext *GetEnclosingSpace(const clang::RecordDecl &cl)
2346{
2347 const clang::DeclContext *ctxt = cl.getDeclContext();
2348 while(ctxt && !ctxt->isNamespace()) {
2349 ctxt = ctxt->getParent();
2350 }
2351 return ctxt;
2352}
2353
2354////////////////////////////////////////////////////////////////////////////////
2355/// Write all the necessary opening part of the namespace and
2356/// return the number of closing brackets needed
2357/// For example for Space1::Space2
2358/// we write: namespace Space1 { namespace Space2 {
2359/// and return 2.
2360
2361int ROOT::TMetaUtils::WriteNamespaceHeader(std::ostream &out, const clang::DeclContext *ctxt)
2362{
2363 int closing_brackets = 0;
2364
2365 //fprintf(stderr,"DEBUG: in WriteNamespaceHeader for %s with %s\n",
2366 // cl.Fullname(),namespace_obj.Fullname());
2367 if (ctxt && ctxt->isNamespace()) {
2368 closing_brackets = WriteNamespaceHeader(out,ctxt->getParent());
2369 const clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(ctxt);
2370 if (ns) {
2371 for (int indent = 0; indent < closing_brackets; ++indent)
2372 out << " ";
2373 if (ns->isInline())
2374 out << "inline ";
2375 out << "namespace " << ns->getNameAsString() << " {" << std::endl;
2377 }
2378 }
2379
2380 return closing_brackets;
2381}
2382
2383////////////////////////////////////////////////////////////////////////////////
2384
2385int ROOT::TMetaUtils::WriteNamespaceHeader(std::ostream &out, const clang::RecordDecl *cl)
2386{
2387 return WriteNamespaceHeader(out, GetEnclosingSpace(*cl));
2388}
2389
2390////////////////////////////////////////////////////////////////////////////////
2391
2392bool ROOT::TMetaUtils::NeedTemplateKeyword(const clang::CXXRecordDecl *cl)
2393{
2394 clang::TemplateSpecializationKind kind = cl->getTemplateSpecializationKind();
2395 if (kind == clang::TSK_Undeclared ) {
2396 // Note a template;
2397 return false;
2398 } else if (kind == clang::TSK_ExplicitSpecialization) {
2399 // This is a specialized templated class
2400 return false;
2401 } else {
2402 // This is an automatically or explicitly instantiated templated class.
2403 return true;
2404 }
2405}
2406
2407////////////////////////////////////////////////////////////////////////////////
2408/// return true if we can find a custom operator new with placement
2409
2410bool ROOT::TMetaUtils::HasCustomOperatorNewPlacement(const char *which, const clang::RecordDecl &cl, const cling::Interpreter &interp)
2411{
2412 const char *name = which;
2413 const char *proto = "size_t";
2414 const char *protoPlacement = "size_t,void*";
2415
2416 // First search in the enclosing namespaces
2417 const clang::FunctionDecl *operatornew
2418 = ROOT::TMetaUtils::GetFuncWithProto(llvm::dyn_cast<clang::Decl>(cl.getDeclContext()),
2419 name, proto, interp,
2420 cling::LookupHelper::NoDiagnostics);
2421 const clang::FunctionDecl *operatornewPlacement
2422 = ROOT::TMetaUtils::GetFuncWithProto(llvm::dyn_cast<clang::Decl>(cl.getDeclContext()),
2424 cling::LookupHelper::NoDiagnostics);
2425
2426 const clang::DeclContext *ctxtnew = nullptr;
2427 const clang::DeclContext *ctxtnewPlacement = nullptr;
2428
2429 if (operatornew) {
2430 ctxtnew = operatornew->getParent();
2431 }
2434 }
2435
2436 // Then in the class and base classes
2438 false /*diags*/);
2441 false /*diags*/);
2442
2443 if (operatornew) {
2444 ctxtnew = operatornew->getParent();
2445 }
2448 }
2449
2450 if (!ctxtnewPlacement) {
2451 return false;
2452 }
2453 if (!ctxtnew) {
2454 // Only a new with placement, no hiding
2455 return true;
2456 }
2457 // Both are non zero
2458 if (ctxtnew == ctxtnewPlacement) {
2459 // Same declaration ctxt, no hiding
2460 return true;
2461 }
2462 const clang::CXXRecordDecl* clnew = llvm::dyn_cast<clang::CXXRecordDecl>(ctxtnew);
2463 const clang::CXXRecordDecl* clnewPlacement = llvm::dyn_cast<clang::CXXRecordDecl>(ctxtnewPlacement);
2464 if (!clnew && !clnewPlacement) {
2465 // They are both in different namespaces, I am not sure of the rules.
2466 // we probably ought to find which one is closest ... for now bail
2467 // (because rootcling was also bailing on that).
2468 return true;
2469 }
2470 if (clnew && !clnewPlacement) {
2471 // operator new is class method hiding the outer scope operator new with placement.
2472 return false;
2473 }
2474 if (!clnew && clnewPlacement) {
2475 // operator new is a not class method and can not hide new with placement which is a method
2476 return true;
2477 }
2478 // Both are class methods
2479 if (clnew->isDerivedFrom(clnewPlacement)) {
2480 // operator new is in a more derived part of the hierarchy, it is hiding operator new with placement.
2481 return false;
2482 }
2483 // operator new with placement is in a more derived part of the hierarchy, it can't be hidden by operator new.
2484 return true;
2485}
2486
2487////////////////////////////////////////////////////////////////////////////////
2488/// return true if we can find a custom operator new with placement
2489
2490bool ROOT::TMetaUtils::HasCustomOperatorNewPlacement(const clang::RecordDecl &cl, const cling::Interpreter &interp)
2491{
2492 return HasCustomOperatorNewPlacement("operator new",cl, interp);
2493}
2494
2495////////////////////////////////////////////////////////////////////////////////
2496/// return true if we can find a custom operator new with placement
2497
2498bool ROOT::TMetaUtils::HasCustomOperatorNewArrayPlacement(const clang::RecordDecl &cl, const cling::Interpreter &interp)
2499{
2500 return HasCustomOperatorNewPlacement("operator new[]",cl, interp);
2501}
2502
2503////////////////////////////////////////////////////////////////////////////////
2504/// std::string NormalizedName;
2505/// GetNormalizedName(NormalizedName, decl->getASTContext().getTypeDeclType(decl), interp, normCtxt);
2506
2508 const AnnotatedRecordDecl &cl,
2509 const clang::CXXRecordDecl *decl,
2510 const cling::Interpreter &interp,
2513{
2514 std::string classname = TClassEdit::GetLong64_Name(cl.GetNormalizedName());
2515
2516 std::string mappedname;
2517 ROOT::TMetaUtils::GetCppName(mappedname,classname.c_str());
2518
2519 // Write the functions that are need for the TGenericClassInfo.
2520 // This includes
2521 // IsA
2522 // operator new
2523 // operator new[]
2524 // operator delete
2525 // operator delete[]
2526
2527 ROOT::TMetaUtils::GetCppName(mappedname,classname.c_str());
2528
2529 if ( ! TClassEdit::IsStdClass( classname.c_str() ) ) {
2530
2531 // Prefix the full class name with '::' except for the STL
2532 // containers and std::string. This is to request the
2533 // real class instead of the class in the namespace ROOT::Shadow
2534 classname.insert(0,"::");
2535 }
2536
2537 finalString << "namespace ROOT {" << "\n";
2538
2539 std::string args;
2540 if (HasIOConstructor(decl, args, ctorTypes, interp)) {
2541 // write the constructor wrapper only for concrete classes
2542 finalString << " // Wrappers around operator new" << "\n";
2543 finalString << " static void *new_" << mappedname.c_str() << "(void *p) {" << "\n" << " return p ? ";
2545 finalString << "new(p) ";
2546 finalString << classname.c_str();
2547 finalString << args;
2548 finalString << " : ";
2549 } else {
2550 finalString << "::new(static_cast<::ROOT::Internal::TOperatorNewHelper*>(p)) ";
2551 finalString << classname.c_str();
2552 finalString << args;
2553 finalString << " : ";
2554 }
2555 finalString << "new " << classname.c_str() << args << ";" << "\n";
2556 finalString << " }" << "\n";
2557
2558 if (args.size()==0 && NeedDestructor(decl, interp)) {
2559 // Can not can newArray if the destructor is not public.
2560 finalString << " static void *newArray_";
2561 finalString << mappedname.c_str();
2562 finalString << "(Long_t nElements, void *p) {";
2563 finalString << "\n";
2564 finalString << " return p ? ";
2566 finalString << "new(p) ";
2567 finalString << classname.c_str();
2568 finalString << "[nElements] : ";
2569 } else {
2570 finalString << "::new(static_cast<::ROOT::Internal::TOperatorNewHelper*>(p)) ";
2571 finalString << classname.c_str();
2572 finalString << "[nElements] : ";
2573 }
2574 finalString << "new ";
2575 finalString << classname.c_str();
2576 finalString << "[nElements];";
2577 finalString << "\n";
2578 finalString << " }";
2579 finalString << "\n";
2580 }
2581 }
2582
2583 if (NeedDestructor(decl, interp)) {
2584 finalString << " // Wrapper around operator delete" << "\n" << " static void delete_" << mappedname.c_str() << "(void *p) {" << "\n" << " delete (static_cast<" << classname.c_str() << "*>(p));" << "\n" << " }" << "\n" << " static void deleteArray_" << mappedname.c_str() << "(void *p) {" << "\n" << " delete [] (static_cast<" << classname.c_str() << "*>(p));" << "\n" << " }" << "\n" << " static void destruct_" << mappedname.c_str() << "(void *p) {" << "\n" << " typedef " << classname.c_str() << " current_t;" << "\n" << " (static_cast<current_t*>(p))->~current_t();" << "\n" << " }" << "\n";
2585 }
2586
2588 finalString << " // Wrapper around the directory auto add." << "\n" << " static void directoryAutoAdd_" << mappedname.c_str() << "(void *p, TDirectory *dir) {" << "\n" << " ((" << classname.c_str() << "*)p)->DirectoryAutoAdd(dir);" << "\n" << " }" << "\n";
2589 }
2590
2592 finalString << " // Wrapper around a custom streamer member function." << "\n" << " static void streamer_" << mappedname.c_str() << "(TBuffer &buf, void *obj) {" << "\n" << " ((" << classname.c_str() << "*)obj)->" << classname.c_str() << "::Streamer(buf);" << "\n" << " }" << "\n";
2593 }
2594
2596 finalString << " // Wrapper around a custom streamer member function." << "\n" << " static void conv_streamer_" << mappedname.c_str() << "(TBuffer &buf, void *obj, const TClass *onfile_class) {" << "\n" << " ((" << classname.c_str() << "*)obj)->" << classname.c_str() << "::Streamer(buf,onfile_class);" << "\n" << " }" << "\n";
2597 }
2598
2599 if (HasNewMerge(decl, interp)) {
2600 finalString << " // Wrapper around the merge function." << "\n" << " static Long64_t merge_" << mappedname.c_str() << "(void *obj,TCollection *coll,TFileMergeInfo *info) {" << "\n" << " return ((" << classname.c_str() << "*)obj)->Merge(coll,info);" << "\n" << " }" << "\n";
2601 } else if (HasOldMerge(decl, interp)) {
2602 finalString << " // Wrapper around the merge function." << "\n" << " static Long64_t merge_" << mappedname.c_str() << "(void *obj,TCollection *coll,TFileMergeInfo *) {" << "\n" << " return ((" << classname.c_str() << "*)obj)->Merge(coll);" << "\n" << " }" << "\n";
2603 }
2604
2606 finalString << " // Wrapper around the Reset function." << "\n" << " static void reset_" << mappedname.c_str() << "(void *obj,TFileMergeInfo *info) {" << "\n" << " ((" << classname.c_str() << "*)obj)->ResetAfterMerge(info);" << "\n" << " }" << "\n";
2607 }
2608 finalString << "} // end of namespace ROOT for class " << classname.c_str() << "\n" << "\n";
2609}
2610
2611////////////////////////////////////////////////////////////////////////////////
2612/// Write interface function for STL members
2613
2615 const cling::Interpreter &interp,
2617{
2618 std::string a;
2619 std::string clName;
2620 TMetaUtils::GetCppName(clName, ROOT::TMetaUtils::GetFileName(*cl.GetRecordDecl(), interp).c_str());
2622 if (version == 0) return;
2623 if (version < 0 && !(cl.RequestStreamerInfo()) ) return;
2624
2625
2626 const clang::CXXRecordDecl *clxx = llvm::dyn_cast<clang::CXXRecordDecl>(cl.GetRecordDecl());
2627 if (!clxx) return;
2628
2629 // We also need to look at the base classes.
2630 for(clang::CXXRecordDecl::base_class_const_iterator iter = clxx->bases_begin(), end = clxx->bases_end();
2631 iter != end;
2632 ++iter)
2633 {
2634 int k = ROOT::TMetaUtils::IsSTLContainer(*iter);
2635 if (k!=0) {
2636 Internal::RStl::Instance().GenerateTClassFor( iter->getType(), interp, normCtxt);
2637 }
2638 }
2639
2640 // Loop over the non static data member.
2641 for(clang::RecordDecl::field_iterator field_iter = clxx->field_begin(), end = clxx->field_end();
2642 field_iter != end;
2643 ++field_iter)
2644 {
2645 std::string mTypename;
2647
2648 //member is a string
2649 {
2651 if (!strcmp(shortTypeName, "string")) {
2652 continue;
2653 }
2654 }
2655
2657
2659 if (k!=0) {
2660 // fprintf(stderr,"Add %s which is also",m.Type()->Name());
2661 // fprintf(stderr," %s\n",R__TrueName(**field_iter) );
2662 clang::QualType utype(ROOT::TMetaUtils::GetUnderlyingType(field_iter->getType()),0);
2663 Internal::RStl::Instance().GenerateTClassFor(utype, interp, normCtxt);
2664 }
2665 }
2666}
2667
2668////////////////////////////////////////////////////////////////////////////////
2669/// TrueName strips the typedefs and array dimensions.
2670
2671std::string ROOT::TMetaUtils::TrueName(const clang::FieldDecl &m)
2672{
2673 const clang::Type *rawtype = m.getType()->getCanonicalTypeInternal().getTypePtr();
2674 if (rawtype->isArrayType()) {
2675 rawtype = rawtype->getBaseElementTypeUnsafe ();
2676 }
2677
2678 std::string result;
2679 ROOT::TMetaUtils::GetQualifiedName(result, clang::QualType(rawtype,0), m);
2680 return result;
2681}
2682
2683////////////////////////////////////////////////////////////////////////////////
2684/// Return the version number of the class or -1
2685/// if the function Class_Version does not exist.
2686
2687int ROOT::TMetaUtils::GetClassVersion(const clang::RecordDecl *cl, const cling::Interpreter& interp)
2688{
2689 const clang::CXXRecordDecl* CRD = llvm::dyn_cast<clang::CXXRecordDecl>(cl);
2690 if (!CRD) {
2691 // Must be an enum or namespace.
2692 // FIXME: Make it work for a namespace!
2693 return -1;
2694 }
2695 const clang::FunctionDecl* funcCV = ROOT::TMetaUtils::ClassInfo__HasMethod(CRD,"Class_Version",interp);
2696
2697 // if we have no Class_Info() return -1.
2698 if (!funcCV) return -1;
2699
2700 // if we have many Class_Info() (?!) return 1.
2701 if (funcCV == (clang::FunctionDecl*)-1) return 1;
2702
2704}
2705
2706////////////////////////////////////////////////////////////////////////////////
2707/// If the function contains 'just': return SomeValue;
2708/// this routine will extract this value and return it.
2709/// The first element is set to true we have the body of the function and it
2710/// is indeed a trivial function with just a return of a value.
2711/// The second element contains the value (or -1 is case of failure)
2712
2713std::pair<bool, int>
2714ROOT::TMetaUtils::GetTrivialIntegralReturnValue(const clang::FunctionDecl *funcCV, const cling::Interpreter &interp)
2715{
2716 using res_t = std::pair<bool, int>;
2717
2718 const clang::CompoundStmt* FuncBody
2719 = llvm::dyn_cast_or_null<clang::CompoundStmt>(funcCV->getBody());
2720 if (!FuncBody)
2721 return res_t{false, -1};
2722 if (FuncBody->size() != 1) {
2723 // This is a non-ClassDef(), complex function - it might depend on state
2724 // and thus we'll need the runtime and cannot determine the result
2725 // statically.
2726 return res_t{false, -1};
2727 }
2728 const clang::ReturnStmt* RetStmt
2729 = llvm::dyn_cast<clang::ReturnStmt>(FuncBody->body_back());
2730 if (!RetStmt)
2731 return res_t{false, -1};
2732 const clang::Expr* RetExpr = RetStmt->getRetValue();
2733 // ClassDef controls the content of Class_Version() but not the return
2734 // expression which is CPP expanded from what the user provided as second
2735 // ClassDef argument. It's usually just be an integer literal but it could
2736 // also be an enum or a variable template for all we know.
2737 // Go through ICE to be more general.
2738 if (auto RetRes = RetExpr->getIntegerConstantExpr(funcCV->getASTContext())) {
2739 if (RetRes->isSigned())
2740 return res_t{true, (Version_t)RetRes->getSExtValue()};
2741 return res_t{true, (Version_t)RetRes->getZExtValue()};
2742 }
2743 return res_t{false, -1};
2744}
2745
2746////////////////////////////////////////////////////////////////////////////////
2747/// Is this an STL container.
2748
2750{
2751 return TMetaUtils::IsSTLCont(*annotated.GetRecordDecl());
2752}
2753
2754////////////////////////////////////////////////////////////////////////////////
2755/// Is this an STL container?
2756
2758{
2759 clang::QualType type = m.getType();
2761
2762 if (decl) return TMetaUtils::IsSTLCont(*decl);
2763 else return ROOT::kNotSTL;
2764}
2765
2766////////////////////////////////////////////////////////////////////////////////
2767/// Is this an STL container?
2768
2769int ROOT::TMetaUtils::IsSTLContainer(const clang::CXXBaseSpecifier &base)
2770{
2771 clang::QualType type = base.getType();
2773
2774 if (decl) return TMetaUtils::IsSTLCont(*decl);
2775 else return ROOT::kNotSTL;
2776}
2777
2778////////////////////////////////////////////////////////////////////////////////
2779/// Calls the given lambda on every header in the given module.
2780/// includeDirectlyUsedModules designates if the foreach should also loop over
2781/// the headers in all modules that are directly used via a `use` declaration
2782/// in the modulemap.
2784 const std::function<void(const clang::Module::Header &)> &closure,
2786{
2787 // Iterates over all headers in a module and calls the closure on each.
2788
2789 // FIXME: We currently have to hardcode '4' to do this. Maybe we
2790 // will have a nicer way to do this in the future.
2791 // NOTE: This is on purpose '4', not '5' which is the size of the
2792 // vector. The last element is the list of excluded headers which we
2793 // obviously don't want to check here.
2794 const std::size_t publicHeaderIndex = 4;
2795
2796 // Integrity check in case this array changes its size at some point.
2797 const std::size_t maxArrayLength = ((sizeof module.Headers) / (sizeof *module.Headers));
2798 static_assert(publicHeaderIndex + 1 == maxArrayLength,
2799 "'Headers' has changed it's size, we need to update publicHeaderIndex");
2800
2801 // Make a list of modules and submodules that we can check for headers.
2802 // We use a SetVector to prevent an infinite loop in unlikely case the
2803 // modules somehow are messed up and don't form a tree...
2804 llvm::SetVector<const clang::Module *> modules;
2805 modules.insert(&module);
2806 for (size_t i = 0; i < modules.size(); ++i) {
2807 const clang::Module *M = modules[i];
2808 for (const clang::Module *subModule : M->submodules())
2809 modules.insert(subModule);
2810 }
2811
2812 for (const clang::Module *m : modules) {
2814 for (clang::Module *used : m->DirectUses) {
2816 }
2817 }
2818
2819 for (std::size_t i = 0; i < publicHeaderIndex; i++) {
2820 auto &headerList = m->Headers[i];
2821 for (const clang::Module::Header &moduleHeader : headerList) {
2823 }
2824 }
2825 }
2826}
2827
2828////////////////////////////////////////////////////////////////////////////////
2829/// Return the absolute type of typeDesc.
2830/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
2831/// we remove * and const keywords. (we do not want to remove & ).
2832/// You need to use the result immediately before it is being overwritten.
2833
2835{
2836 static char t[4096];
2837 static const char* constwd = "const ";
2838 static const char* constwdend = "const";
2839
2840 const char *s;
2841 char *p=t;
2842 int lev=0;
2843 for (s=typeDesc;*s;s++) {
2844 if (*s=='<') lev++;
2845 if (*s=='>') lev--;
2846 if (lev==0 && *s=='*') continue;
2847 if (lev==0 && (strncmp(constwd,s,strlen(constwd))==0
2848 ||strcmp(constwdend,s)==0 ) ) {
2849 s+=strlen(constwd)-1; // -1 because the loop adds 1
2850 continue;
2851 }
2852 if (lev==0 && *s==' ' && *(s+1)!='*') { p = t; continue;}
2853 if (p - t > (long)sizeof(t)) {
2854 printf("ERROR (rootcling): type name too long for StortTypeName: %s\n",
2855 typeDesc);
2856 p[0] = 0;
2857 return t;
2858 }
2859 *p++ = *s;
2860 }
2861 p[0]=0;
2862
2863 return t;
2864}
2865
2866bool ROOT::TMetaUtils::IsStreamableObject(const clang::FieldDecl &m,
2867 const cling::Interpreter& interp)
2868{
2869 auto comment = ROOT::TMetaUtils::GetComment( m );
2870
2871 // Transient
2872 if (!comment.empty() && comment[0] == '!')
2873 return false;
2874
2875 clang::QualType type = m.getType();
2876
2877 if (type->isReferenceType()) {
2878 // Reference can not be streamed.
2879 return false;
2880 }
2881
2882 std::string mTypeName = type.getAsString(m.getASTContext().getPrintingPolicy());
2883 if (!strcmp(mTypeName.c_str(), "string") || !strcmp(mTypeName.c_str(), "string*")) {
2884 return true;
2885 }
2886 if (!strcmp(mTypeName.c_str(), "std::string") || !strcmp(mTypeName.c_str(), "std::string*")) {
2887 return true;
2888 }
2889
2891 return true;
2892 }
2893
2894 const clang::Type *rawtype = type.getTypePtr()->getBaseElementTypeUnsafe ();
2895
2896 if (rawtype->isPointerType()) {
2897 //Get to the 'raw' type.
2898 clang::QualType pointee;
2899 while ( (pointee = rawtype->getPointeeType()) , pointee.getTypePtrOrNull() && pointee.getTypePtr() != rawtype)
2900 {
2901 rawtype = pointee.getTypePtr();
2902 }
2903 }
2904
2905 if (rawtype->isFundamentalType() || rawtype->isEnumeralType()) {
2906 // not an ojbect.
2907 return false;
2908 }
2909
2910 const clang::CXXRecordDecl *cxxdecl = rawtype->getAsCXXRecordDecl();
2912 if (!(ROOT::TMetaUtils::ClassInfo__HasMethod(cxxdecl,"Class_Version", interp))) return true;
2914 if (version > 0) return true;
2915 }
2916 return false;
2917}
2918
2919////////////////////////////////////////////////////////////////////////////////
2920/// Return the absolute type of typeDesc.
2921/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
2922/// we remove * and const keywords. (we do not want to remove & ).
2923/// You need to use the result immediately before it is being overwritten.
2924
2925std::string ROOT::TMetaUtils::ShortTypeName(const clang::FieldDecl &m)
2926{
2927 const clang::Type *rawtype = m.getType().getTypePtr();
2928
2929 //Get to the 'raw' type.
2930 clang::QualType pointee;
2931 while ( rawtype->isPointerType() && ((pointee = rawtype->getPointeeType()) , pointee.getTypePtrOrNull()) && pointee.getTypePtr() != rawtype)
2932 {
2933 rawtype = pointee.getTypePtr();
2934 }
2935
2936 std::string result;
2937 ROOT::TMetaUtils::GetQualifiedName(result, clang::QualType(rawtype,0), m);
2938 return result;
2939}
2940
2941////////////////////////////////////////////////////////////////////////////////
2942
2943clang::RecordDecl *ROOT::TMetaUtils::GetUnderlyingRecordDecl(clang::QualType type)
2944{
2945 const clang::Type *rawtype = ROOT::TMetaUtils::GetUnderlyingType(type);
2946
2947 if (rawtype->isFundamentalType() || rawtype->isEnumeralType()) {
2948 // not an object.
2949 return nullptr;
2950 }
2951 return rawtype->getAsCXXRecordDecl();
2952}
2953
2954////////////////////////////////////////////////////////////////////////////////
2955/// Generate the code of the class
2956/// If the requestor is genreflex, request the new streamer format
2957
2959 const AnnotatedRecordDecl &cl,
2960 const cling::Interpreter &interp,
2962 std::ostream& dictStream,
2964 bool isGenreflex=false)
2965{
2966 const clang::CXXRecordDecl* decl = llvm::dyn_cast<clang::CXXRecordDecl>(cl.GetRecordDecl());
2967
2968 if (!decl || !decl->isCompleteDefinition()) {
2969 return;
2970 }
2971
2972 std::string fullname;
2974 if (TClassEdit::IsSTLCont(fullname) ) {
2975 Internal::RStl::Instance().GenerateTClassFor(cl.GetNormalizedName(), llvm::dyn_cast<clang::CXXRecordDecl>(cl.GetRecordDecl()), interp, normCtxt);
2976 return;
2977 }
2978
2980 // The !genreflex is there to prevent genreflex to select collections which are data members
2981 // This is to maintain the behaviour of ROOT5 and ROOT6 up to 6.07 included.
2982 if (cl.RootFlag() && !isGenreflex) ROOT::TMetaUtils::WritePointersSTL(cl, interp, normCtxt); // In particular this detect if the class has a version number.
2983 if (!(cl.RequestNoStreamer())) {
2984 (*WriteStreamerFunc)(cl, interp, normCtxt, dictStream, isGenreflex || cl.RequestStreamerInfo());
2985 } else
2986 ROOT::TMetaUtils::Info(nullptr, "Class %s: Do not generate Streamer() [*** custom streamer ***]\n",fullname.c_str());
2987 } else {
2988 ROOT::TMetaUtils::Info(nullptr, "Class %s: Streamer() not declared\n", fullname.c_str());
2989
2990 // See comment above about the !isGenreflex
2992 }
2994}
2995
2996////////////////////////////////////////////////////////////////////////////////
2997/// Add any unspecified template parameters to the class template instance,
2998/// mentioned anywhere in the type.
2999///
3000/// Note: this does not strip any typedef but could be merged with cling::utils::Transform::GetPartiallyDesugaredType
3001/// if we can safely replace TClassEdit::IsStd with a test on the declaring scope
3002/// and if we can resolve the fact that the added parameter do not take into account possible use/dependences on Double32_t
3003/// and if we decide that adding the default is the right long term solution or not.
3004/// Whether it is or not depend on the I/O on whether the default template argument might change or not
3005/// and whether they (should) affect the on disk layout (for STL containers, we do know they do not).
3006
3008 const cling::Interpreter &interpreter,
3010{
3011 const clang::ASTContext& Ctx = interpreter.getCI()->getASTContext();
3012
3013 clang::QualType originalType = instanceType;
3014
3015 // In case of name* we need to strip the pointer first, add the default and attach
3016 // the pointer once again.
3017 if (llvm::isa<clang::PointerType>(instanceType.getTypePtr())) {
3018 // Get the qualifiers.
3019 clang::Qualifiers quals = instanceType.getQualifiers();
3020 clang::QualType newPointee = AddDefaultParameters(instanceType->getPointeeType(), interpreter, normCtxt);
3021 if (newPointee != instanceType->getPointeeType()) {
3022 instanceType = Ctx.getPointerType(newPointee);
3023 // Add back the qualifiers.
3024 instanceType = Ctx.getQualifiedType(instanceType, quals);
3025 }
3026 return instanceType;
3027 }
3028
3029 // In case of Int_t& we need to strip the pointer first, desugar and attach
3030 // the pointer once again.
3031 if (llvm::isa<clang::ReferenceType>(instanceType.getTypePtr())) {
3032 // Get the qualifiers.
3033 bool isLValueRefTy = llvm::isa<clang::LValueReferenceType>(instanceType.getTypePtr());
3034 clang::Qualifiers quals = instanceType.getQualifiers();
3035 clang::QualType newPointee = AddDefaultParameters(instanceType->getPointeeType(), interpreter, normCtxt);
3036
3037 if (newPointee != instanceType->getPointeeType()) {
3038 // Add the r- or l- value reference type back to the desugared one
3039 if (isLValueRefTy)
3040 instanceType = Ctx.getLValueReferenceType(newPointee);
3041 else
3042 instanceType = Ctx.getRValueReferenceType(newPointee);
3043 // Add back the qualifiers.
3044 instanceType = Ctx.getQualifiedType(instanceType, quals);
3045 }
3046 return instanceType;
3047 }
3048
3049 // Treat the Scope.
3050 bool prefix_changed = false;
3051 clang::NestedNameSpecifier *prefix = nullptr;
3052 clang::Qualifiers prefix_qualifiers = instanceType.getLocalQualifiers();
3053 const clang::ElaboratedType* etype
3054 = llvm::dyn_cast<clang::ElaboratedType>(instanceType.getTypePtr());
3055 if (etype) {
3056 // We have to also handle the prefix.
3057 prefix = AddDefaultParametersNNS(Ctx, etype->getQualifier(), interpreter, normCtxt);
3058 prefix_changed = prefix != etype->getQualifier();
3059 instanceType = clang::QualType(etype->getNamedType().getTypePtr(),0);
3060 }
3061
3062 // In case of template specializations iterate over the arguments and
3063 // add unspecified default parameter.
3064
3065 const clang::TemplateSpecializationType* TST
3066 = llvm::dyn_cast<const clang::TemplateSpecializationType>(instanceType.getTypePtr());
3067
3068 const clang::ClassTemplateSpecializationDecl* TSTdecl
3069 = llvm::dyn_cast_or_null<const clang::ClassTemplateSpecializationDecl>(instanceType.getTypePtr()->getAsCXXRecordDecl());
3070
3071 // Don't add the default paramater onto std classes.
3072 // We really need this for __shared_ptr which add a enum constant value which
3073 // is spelled in its 'numeral' form and thus the resulting type name is
3074 // incorrect. We also can used this for any of the STL collections where we
3075 // know we don't want the default argument. For the other members of the
3076 // std namespace this is dubious (because TMetaUtils::GetNormalizedName would
3077 // not drop those defaults). [I.e. the real test ought to be is std and
3078 // name is __shared_ptr or vector or list or set or etc.]
3080
3081 bool mightHaveChanged = false;
3082 if (TST && TSTdecl) {
3083
3084 clang::Sema& S = interpreter.getCI()->getSema();
3085 clang::TemplateDecl *Template = TSTdecl->getSpecializedTemplate()->getMostRecentDecl();
3086 clang::TemplateParameterList *Params = Template->getTemplateParameters();
3087 clang::TemplateParameterList::iterator Param = Params->begin(); // , ParamEnd = Params->end();
3088 //llvm::SmallVectorImpl<TemplateArgument> Converted; // Need to contains the other arguments.
3089 // Converted seems to be the same as our 'desArgs'
3090
3091 unsigned int dropDefault = normCtxt.GetConfig().DropDefaultArg(*Template);
3092
3093 llvm::SmallVector<clang::TemplateArgument, 4> desArgs;
3094 llvm::SmallVector<clang::TemplateArgument, 4> canonArgs;
3095 llvm::ArrayRef<clang::TemplateArgument> template_arguments = TST->template_arguments();
3096 unsigned int Idecl = 0, Edecl = TSTdecl->getTemplateArgs().size();
3097 unsigned int maxAddArg = TSTdecl->getTemplateArgs().size() - dropDefault;
3098 for (const clang::TemplateArgument *I = template_arguments.begin(), *E = template_arguments.end(); Idecl != Edecl;
3099 I != E ? ++I : nullptr, ++Idecl, ++Param) {
3100
3101 if (I != E) {
3102
3103 if (I->getKind() == clang::TemplateArgument::Template) {
3104 clang::TemplateName templateName = I->getAsTemplate();
3105 clang::TemplateDecl* templateDecl = templateName.getAsTemplateDecl();
3106 if (templateDecl) {
3107 clang::DeclContext* declCtxt = templateDecl->getDeclContext();
3108
3109 if (declCtxt && !templateName.getAsQualifiedTemplateName()){
3110 clang::NamespaceDecl* ns = clang::dyn_cast<clang::NamespaceDecl>(declCtxt);
3111 clang::NestedNameSpecifier* nns;
3112 if (ns) {
3113 nns = cling::utils::TypeName::CreateNestedNameSpecifier(Ctx, ns);
3114 } else if (clang::TagDecl* TD = llvm::dyn_cast<clang::TagDecl>(declCtxt)) {
3115 nns = cling::utils::TypeName::CreateNestedNameSpecifier(Ctx,TD, false /*FullyQualified*/);
3116 } else {
3117 // TU scope
3118 desArgs.push_back(*I);
3119 continue;
3120 }
3121 clang::TemplateName UnderlyingTN(templateDecl);
3122 if (clang::UsingShadowDecl *USD = templateName.getAsUsingShadowDecl())
3123 UnderlyingTN = clang::TemplateName(USD);
3124 clang::TemplateName templateNameWithNSS ( Ctx.getQualifiedTemplateName(nns, false, UnderlyingTN) );
3125 desArgs.push_back(clang::TemplateArgument(templateNameWithNSS));
3126 mightHaveChanged = true;
3127 continue;
3128 }
3129 }
3130 }
3131
3132 if (I->getKind() != clang::TemplateArgument::Type) {
3133 desArgs.push_back(*I);
3134 continue;
3135 }
3136
3137 clang::QualType SubTy = I->getAsType();
3138
3139 // Check if the type needs more desugaring and recurse.
3140 // (Originally this was limited to elaborated and templated type,
3141 // but we also need to do it for pointer and reference type
3142 // and who knows what, so do it always)
3143 clang::QualType newSubTy = AddDefaultParameters(SubTy,
3145 normCtxt);
3146 if (SubTy != newSubTy) {
3147 mightHaveChanged = true;
3148 desArgs.push_back(clang::TemplateArgument(newSubTy));
3149 } else {
3150 desArgs.push_back(*I);
3151 }
3152 // Converted.push_back(TemplateArgument(ArgTypeForTemplate));
3153 } else if (!isStdDropDefault && Idecl < maxAddArg) {
3154
3155 mightHaveChanged = true;
3156
3157 const clang::TemplateArgument& templateArg
3158 = TSTdecl->getTemplateArgs().get(Idecl);
3159 if (templateArg.getKind() != clang::TemplateArgument::Type) {
3160 desArgs.push_back(templateArg);
3161 continue;
3162 }
3163 clang::QualType SubTy = templateArg.getAsType();
3164
3165 clang::SourceLocation TemplateLoc = Template->getSourceRange ().getBegin(); //NOTE: not sure that this is the 'right' location.
3166 clang::SourceLocation RAngleLoc = TSTdecl->getSourceRange().getBegin(); // NOTE: most likely wrong, I think this is expecting the location of right angle
3167
3168 clang::TemplateTypeParmDecl *TTP = llvm::dyn_cast<clang::TemplateTypeParmDecl>(*Param);
3169 {
3170 // We may induce template instantiation
3171 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interpreter));
3172 bool HasDefaultArgs;
3173 clang::TemplateArgumentLoc ArgType = S.SubstDefaultTemplateArgumentIfAvailable(
3174 Template,
3176 RAngleLoc,
3177 TTP,
3178 desArgs,
3179 canonArgs,
3181 // The substition can fail, in which case there would have been compilation
3182 // error printed on the screen.
3183 if (ArgType.getArgument().isNull()
3184 || ArgType.getArgument().getKind() != clang::TemplateArgument::Type) {
3185 ROOT::TMetaUtils::Error("ROOT::TMetaUtils::AddDefaultParameters",
3186 "Template parameter substitution failed for %s around %s\n",
3187 instanceType.getAsString().c_str(), SubTy.getAsString().c_str());
3188 break;
3189 }
3190 clang::QualType BetterSubTy = ArgType.getArgument().getAsType();
3191 SubTy = cling::utils::Transform::GetPartiallyDesugaredType(Ctx,BetterSubTy,normCtxt.GetConfig(),/*fullyQualified=*/ true);
3192 }
3194 desArgs.push_back(clang::TemplateArgument(SubTy));
3195 } else {
3196 // We are past the end of the list of specified arguements and we
3197 // do not want to add the default, no need to continue.
3198 break;
3199 }
3200 }
3201
3202 // If we added default parameter, allocate new type in the AST.
3203 if (mightHaveChanged) {
3204 instanceType = Ctx.getTemplateSpecializationType(TST->getTemplateName(),
3205 desArgs,
3206 TST->getCanonicalTypeInternal());
3207 }
3208 }
3209
3211 if (prefix) {
3212 instanceType = Ctx.getElaboratedType(clang::ElaboratedTypeKeyword::None, prefix, instanceType);
3213 instanceType = Ctx.getQualifiedType(instanceType,prefix_qualifiers);
3214 }
3215 return instanceType;
3216}
3217
3218////////////////////////////////////////////////////////////////////////////////
3219/// ValidArrayIndex return a static string (so use it or copy it immediatly, do not
3220/// call GrabIndex twice in the same expression) containing the size of the
3221/// array data member.
3222/// In case of error, or if the size is not specified, GrabIndex returns 0.
3223/// If errnum is not null, *errnum updated with the error number:
3224/// Cint::G__DataMemberInfo::G__VALID : valid array index
3225/// Cint::G__DataMemberInfo::G__NOT_INT : array index is not an int
3226/// Cint::G__DataMemberInfo::G__NOT_DEF : index not defined before array
3227/// (this IS an error for streaming to disk)
3228/// Cint::G__DataMemberInfo::G__IS_PRIVATE: index exist in a parent class but is private
3229/// Cint::G__DataMemberInfo::G__UNKNOWN : index is not known
3230/// If errstr is not null, *errstr is updated with the address of a static
3231/// string containing the part of the index with is invalid.
3232
3233llvm::StringRef ROOT::TMetaUtils::DataMemberInfo__ValidArrayIndex(const cling::Interpreter &interp, const clang::DeclaratorDecl &m, int *errnum, llvm::StringRef *errstr)
3234{
3235 llvm::StringRef title;
3236
3237 // Try to get the comment either from the annotation or the header file if present
3238 if (clang::AnnotateAttr *A = m.getAttr<clang::AnnotateAttr>())
3239 title = A->getAnnotation();
3240 else
3241 // Try to get the comment from the header file if present
3243
3244 // Let's see if the user provided us with some information
3245 // with the format: //[dimension] this is the dim of the array
3246 // dimension can be an arithmetical expression containing, literal integer,
3247 // the operator *,+ and - and data member of integral type. In addition the
3248 // data members used for the size of the array need to be defined prior to
3249 // the array.
3250
3251 if (errnum) *errnum = VALID;
3252
3253 if (title.size() == 0 || (title[0] != '[')) return llvm::StringRef();
3254 size_t rightbracket = title.find(']');
3255 if (rightbracket == llvm::StringRef::npos) return llvm::StringRef();
3256
3257 std::string working;
3258 llvm::StringRef indexvar(title.data()+1,rightbracket-1);
3259
3260 // now we should have indexvar=dimension
3261 // Let's see if this is legal.
3262 // which means a combination of data member and digit separated by '*','+','-'
3263 // First we remove white spaces.
3264 unsigned int i;
3265 size_t indexvarlen = indexvar.size();
3266 for ( i=0; i<indexvarlen; i++) {
3267 if (!isspace(indexvar[i])) {
3268 working += indexvar[i];
3269 }
3270 }
3271
3272 // Now we go through all indentifiers
3273 const char *tokenlist = "*+-";
3274 char *current = const_cast<char*>(working.c_str());
3275 current = strtok(current,tokenlist); // this method does not need to be reentrant
3276
3277 while (current) {
3278 // Check the token
3279 if (isdigit(current[0])) {
3280 for(i=0;i<strlen(current);i++) {
3281 if (!isdigit(current[i])) {
3282 // Error we only access integer.
3283 //NOTE: *** Need to print an error;
3284 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not an interger\n",
3285 // member.MemberOf()->Name(), member.Name(), current);
3286 if (errstr) *errstr = current;
3287 if (errnum) *errnum = NOT_INT;
3288 return llvm::StringRef();
3289 }
3290 }
3291 } else { // current token is not a digit
3292 // first let's see if it is a data member:
3293 const clang::CXXRecordDecl *parent_clxx = llvm::dyn_cast<clang::CXXRecordDecl>(m.getDeclContext());
3294 const clang::FieldDecl *index1 = nullptr;
3295 if (parent_clxx)
3297 if ( index1 ) {
3298 if ( IsFieldDeclInt(index1) ) {
3299 // Let's see if it has already been written down in the
3300 // Streamer.
3301 // Let's see if we already wrote it down in the
3302 // streamer.
3303 for(clang::RecordDecl::field_iterator field_iter = parent_clxx->field_begin(), end = parent_clxx->field_end();
3304 field_iter != end;
3305 ++field_iter)
3306 {
3307 if ( field_iter->getNameAsString() == m.getNameAsString() ) {
3308 // we reached the current data member before
3309 // reaching the index so we have not written it yet!
3310 //NOTE: *** Need to print an error;
3311 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) has not been defined before the array \n",
3312 // member.MemberOf()->Name(), member.Name(), current);
3313 if (errstr) *errstr = current;
3314 if (errnum) *errnum = NOT_DEF;
3315 return llvm::StringRef();
3316 }
3317 if ( field_iter->getNameAsString() == index1->getNameAsString() ) {
3318 break;
3319 }
3320 } // end of while (m_local.Next())
3321 } else {
3322 //NOTE: *** Need to print an error;
3323 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not int \n",
3324 // member.MemberOf()->Name(), member.Name(), current);
3325 if (errstr) *errstr = current;
3326 if (errnum) *errnum = NOT_INT;
3327 return llvm::StringRef();
3328 }
3329 } else {
3330 // There is no variable by this name in this class, let see
3331 // the base classes!:
3332 int found = 0;
3333 if (parent_clxx) {
3334 clang::Sema& SemaR = const_cast<cling::Interpreter&>(interp).getSema();
3336 }
3337 if ( index1 ) {
3338 if ( IsFieldDeclInt(index1) ) {
3339 found = 1;
3340 } else {
3341 // We found a data member but it is the wrong type
3342 //NOTE: *** Need to print an error;
3343 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not int \n",
3344 // member.MemberOf()->Name(), member.Name(), current);
3345 if (errnum) *errnum = NOT_INT;
3346 if (errstr) *errstr = current;
3347 //NOTE: *** Need to print an error;
3348 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not int \n",
3349 // member.MemberOf()->Name(), member.Name(), current);
3350 if (errnum) *errnum = NOT_INT;
3351 if (errstr) *errstr = current;
3352 return llvm::StringRef();
3353 }
3354 if ( found && (index1->getAccess() == clang::AS_private) ) {
3355 //NOTE: *** Need to print an error;
3356 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is a private member of %s \n",
3357 if (errstr) *errstr = current;
3358 if (errnum) *errnum = IS_PRIVATE;
3359 return llvm::StringRef();
3360 }
3361 }
3362 if (!found) {
3363 //NOTE: *** Need to print an error;
3364 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not known \n",
3365 // member.MemberOf()->Name(), member.Name(), indexvar);
3366 if (errstr) *errstr = indexvar;
3367 if (errnum) *errnum = UNKNOWN;
3368 return llvm::StringRef();
3369 } // end of if not found
3370 } // end of if is a data member of the class
3371 } // end of if isdigit
3372
3373 current = strtok(nullptr, tokenlist);
3374 } // end of while loop on tokens
3375
3376 return indexvar;
3377
3378}
3379
3380////////////////////////////////////////////////////////////////////////////////
3381/// Return (in the argument 'output') a valid name of the C++ symbol/type (pass as 'input')
3382/// that can be used in C++ as a variable name.
3383
3384void ROOT::TMetaUtils::GetCppName(std::string &out, const char *in)
3385{
3386 unsigned int i = 0;
3387 char c;
3388 out.clear();
3389 while((c = in[i++])) {
3390 const char *repl = nullptr;
3391 switch(c) {
3392 case '+': repl = "pL"; break;
3393 case '-': repl = "mI"; break;
3394 case '*': repl = "mU"; break;
3395 case '/': repl = "dI"; break;
3396 case '&': repl = "aN"; break;
3397 case '%': repl = "pE"; break;
3398 case '|': repl = "oR"; break;
3399 case '^': repl = "hA"; break;
3400 case '>': repl = "gR"; break;
3401 case '<': repl = "lE"; break;
3402 case '=': repl = "eQ"; break;
3403 case '~': repl = "wA"; break;
3404 case '.': repl = "dO"; break;
3405 case '(': repl = "oP"; break;
3406 case ')': repl = "cP"; break;
3407 case '[': repl = "oB"; break;
3408 case ']': repl = "cB"; break;
3409 case '{': repl = "lB"; break;
3410 case '}': repl = "rB"; break;
3411 case ';': repl = "sC"; break;
3412 case '#': repl = "hS"; break;
3413 case '?': repl = "qM"; break;
3414 case '`': repl = "bT"; break;
3415 case '!': repl = "nO"; break;
3416 case ',': repl = "cO"; break;
3417 case '$': repl = "dA"; break;
3418 case ' ': repl = "sP"; break;
3419 case ':': repl = "cL"; break;
3420 case '"': repl = "dQ"; break;
3421 case '@': repl = "aT"; break;
3422 case '\'': repl = "sQ"; break;
3423 case '\\': repl = "fI"; break;
3424 }
3425 if (repl)
3426 out.append(repl);
3427 else
3428 out.push_back(c);
3429 }
3430
3431 // If out is empty, or if it starts with a number, it's not a valid C++ variable. Prepend a "_"
3432 if (out.empty() || isdigit(out[0]))
3433 out.insert(out.begin(), '_');
3434}
3435
3436static clang::SourceLocation
3438 clang::SourceLocation sourceLoc) {
3439 // Follow macro expansion until we hit a source file.
3440 if (!sourceLoc.isFileID()) {
3441 return sourceManager.getExpansionRange(sourceLoc).getEnd();
3442 }
3443 return sourceLoc;
3444}
3445
3446////////////////////////////////////////////////////////////////////////////////
3447/// Return the header file to be included to declare the Decl.
3448
3449std::string ROOT::TMetaUtils::GetFileName(const clang::Decl& decl,
3450 const cling::Interpreter& interp)
3451{
3452 // It looks like the template specialization decl actually contains _less_ information
3453 // on the location of the code than the decl (in case where there is forward declaration,
3454 // that is what the specialization points to).
3455 //
3456 // const clang::CXXRecordDecl* clxx = llvm::dyn_cast<clang::CXXRecordDecl>(decl);
3457 // if (clxx) {
3458 // switch(clxx->getTemplateSpecializationKind()) {
3459 // case clang::TSK_Undeclared:
3460 // // We want the default behavior
3461 // break;
3462 // case clang::TSK_ExplicitInstantiationDeclaration:
3463 // case clang::TSK_ExplicitInstantiationDefinition:
3464 // case clang::TSK_ImplicitInstantiation: {
3465 // // We want the location of the template declaration:
3466 // const clang::ClassTemplateSpecializationDecl *tmplt_specialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl> (clxx);
3467 // if (tmplt_specialization) {
3468 // // return GetFileName(const_cast< clang::ClassTemplateSpecializationDecl *>(tmplt_specialization)->getSpecializedTemplate());
3469 // }
3470 // break;
3471 // }
3472 // case clang::TSK_ExplicitSpecialization:
3473 // // We want the default behavior
3474 // break;
3475 // default:
3476 // break;
3477 // }
3478 // }
3479
3480 using namespace clang;
3481 SourceLocation headerLoc = decl.getLocation();
3482
3483 static const char invalidFilename[] = "";
3484 if (!headerLoc.isValid()) return invalidFilename;
3485
3486 HeaderSearch& HdrSearch = interp.getCI()->getPreprocessor().getHeaderSearchInfo();
3487
3488 SourceManager& sourceManager = decl.getASTContext().getSourceManager();
3493 sourceManager.getIncludeLoc(headerFID));
3494
3495 const FileEntry *headerFE = sourceManager.getFileEntryForID(headerFID);
3496 while (includeLoc.isValid() && sourceManager.isInSystemHeader(includeLoc)) {
3498 // use HeaderSearch on the basename, to make sure it takes a header from
3499 // the include path (e.g. not from /usr/include/bits/)
3500 assert(headerFE && "Couldn't find FileEntry from FID!");
3501 auto FEhdr
3502 = HdrSearch.LookupFile(llvm::sys::path::filename(headerFE->getName()),
3504 true /*isAngled*/, nullptr/*FromDir*/, foundDir,
3505 ArrayRef<std::pair<OptionalFileEntryRef, DirectoryEntryRef>>(),
3506 nullptr/*Searchpath*/, nullptr/*RelPath*/,
3507 nullptr/*SuggestedModule*/, nullptr/*RequestingModule*/,
3508 nullptr/*IsMapped*/, nullptr /*IsFrameworkFound*/,
3509 false /*SkipCache*/,
3510 false /*BuildSystemModule*/,
3511 false /*OpenFile*/, true /*CacheFailures*/);
3512 if (FEhdr) break;
3513 headerFID = sourceManager.getFileID(includeLoc);
3514 headerFE = sourceManager.getFileEntryForID(headerFID);
3515 // If we have a system header in a module we can't just trace back the
3516 // original include with the preprocessor. But it should be enough if
3517 // we trace it back to the top-level system header that includes this
3518 // declaration.
3519 if (interp.getCI()->getLangOpts().Modules && !headerFE) {
3520 assert(decl.isFirstDecl() && "Couldn't trace back include from a decl"
3521 " that is not from an AST file");
3522 assert(StringRef(includeLoc.printToString(sourceManager)).startswith("<module-includes>"));
3523 break;
3524 }
3526 sourceManager.getIncludeLoc(headerFID));
3527 }
3528
3529 if (!headerFE) return invalidFilename;
3530
3531 llvm::SmallString<256> headerFileName(headerFE->getName());
3532 // Remove double ../ from the path so that the search below finds a valid
3533 // longest match and does not result in growing paths.
3534 llvm::sys::path::remove_dots(headerFileName, /*remove_dot_dot=*/true);
3535
3536 // Now headerFID references the last valid system header or the original
3537 // user file.
3538 // Find out how to include it by matching file name to include paths.
3539 // We assume that the file "/A/B/C/D.h" can at some level be included as
3540 // "C/D.h". Be we cannot know whether that happens to be a different file
3541 // with the same name. Thus we first find the longest stem that can be
3542 // reached, say B/C/D.h. Then we find the shortest one, say C/D.h, that
3543 // points to the same file as the long version. If such a short version
3544 // exists it will be returned. If it doesn't the long version is returned.
3545 bool isAbsolute = llvm::sys::path::is_absolute(headerFileName);
3546 clang::OptionalFileEntryRef FELong;
3547 // Find the longest available match.
3548 for (llvm::sys::path::const_iterator
3549 IDir = llvm::sys::path::begin(headerFileName),
3550 EDir = llvm::sys::path::end(headerFileName);
3551 !FELong && IDir != EDir; ++IDir) {
3552 if (isAbsolute) {
3553 // skip "/" part
3554 isAbsolute = false;
3555 continue;
3556 }
3557 size_t lenTrailing = headerFileName.size() - (IDir->data() - headerFileName.data());
3558 llvm::StringRef trailingPart(IDir->data(), lenTrailing);
3559 assert(trailingPart.data() + trailingPart.size()
3560 == headerFileName.data() + headerFileName.size()
3561 && "Mismatched partitioning of file name!");
3564 true /*isAngled*/, nullptr/*FromDir*/, FoundDir,
3565 ArrayRef<std::pair<OptionalFileEntryRef, DirectoryEntryRef>>(),
3566 nullptr/*Searchpath*/, nullptr/*RelPath*/,
3567 nullptr/*SuggestedModule*/, nullptr/*RequestingModule*/,
3568 nullptr/*IsMapped*/, nullptr /*IsFrameworkFound*/);
3569 }
3570
3571 if (!FELong) {
3572 // We did not find any file part in any search path.
3573 return invalidFilename;
3574 }
3575
3576 // Iterates through path *parts* "C"; we need trailing parts "C/D.h"
3577 for (llvm::sys::path::reverse_iterator
3578 IDir = llvm::sys::path::rbegin(headerFileName),
3579 EDir = llvm::sys::path::rend(headerFileName);
3580 IDir != EDir; ++IDir) {
3581 size_t lenTrailing = headerFileName.size() - (IDir->data() - headerFileName.data());
3582 llvm::StringRef trailingPart(IDir->data(), lenTrailing);
3583 assert(trailingPart.data() + trailingPart.size()
3584 == headerFileName.data() + headerFileName.size()
3585 && "Mismatched partitioning of file name!");
3587 // Can we find it, and is it the same file as the long version?
3588 // (or are we back to the previously found spelling, which is fine, too)
3589 if (HdrSearch.LookupFile(trailingPart, SourceLocation(),
3590 true /*isAngled*/, nullptr/*FromDir*/, FoundDir,
3591 ArrayRef<std::pair<OptionalFileEntryRef, DirectoryEntryRef>>(),
3592 nullptr/*Searchpath*/, nullptr/*RelPath*/,
3593 nullptr/*SuggestedModule*/, nullptr/*RequestingModule*/,
3594 nullptr/*IsMapped*/, nullptr /*IsFrameworkFound*/) == FELong) {
3595 return trailingPart.str();
3596 }
3597 }
3598
3599 return invalidFilename;
3600}
3601
3602////////////////////////////////////////////////////////////////////////////////
3603
3605 const clang::QualType &qtype,
3606 const clang::ASTContext &astContext)
3607{
3608 std::string fqname = cling::utils::TypeName::GetFullyQualifiedName(qtype, astContext);
3612}
3613
3614////////////////////////////////////////////////////////////////////////////////
3615
3617 const clang::QualType &qtype,
3618 const cling::Interpreter &interpreter)
3619{
3620 // We need this because GetFullyQualifiedTypeName is triggering deserialization
3621 // This calling the same name function GetFullyQualifiedTypeName, but this should stay here because
3622 // callee doesn't have an interpreter pointer
3623 cling::Interpreter::PushTransactionRAII RAII(const_cast<cling::Interpreter*>(&interpreter));
3624
3626 qtype,
3627 interpreter.getCI()->getASTContext());
3628}
3629
3630////////////////////////////////////////////////////////////////////////////////
3631/// Get the template specialisation decl and template decl behind the qualtype
3632/// Returns true if successfully found, false otherwise
3633
3634bool ROOT::TMetaUtils::QualType2Template(const clang::QualType& qt,
3635 clang::ClassTemplateDecl*& ctd,
3636 clang::ClassTemplateSpecializationDecl*& ctsd)
3637{
3638 using namespace clang;
3639 const Type* theType = qt.getTypePtr();
3640 if (!theType){
3641 ctd=nullptr;
3642 ctsd=nullptr;
3643 return false;
3644 }
3645
3646 if (theType->isPointerType()) {
3647 return QualType2Template(theType->getPointeeType(), ctd, ctsd);
3648 }
3649
3650 if (const RecordType* rType = llvm::dyn_cast<RecordType>(theType)) {
3651 ctsd = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(rType->getDecl());
3652 if (ctsd) {
3653 ctd = ctsd->getSpecializedTemplate();
3654 return true;
3655 }
3656 }
3657
3658 if (const SubstTemplateTypeParmType* sttpType = llvm::dyn_cast<SubstTemplateTypeParmType>(theType)){
3659 return QualType2Template(sttpType->getReplacementType(), ctd, ctsd);
3660 }
3661
3662
3663 ctsd = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(qt->getAsCXXRecordDecl());
3664 if(ctsd){
3665 ctd = ctsd->getSpecializedTemplate();
3666 return true;
3667 }
3668
3669 ctd=nullptr;
3670 ctsd=nullptr;
3671 return false;
3672}
3673
3674////////////////////////////////////////////////////////////////////////////////
3675/// Extract from a qualtype the class template if this makes sense.
3676/// Retuns the ClassTemplateDecl or nullptr otherwise.
3677
3678clang::ClassTemplateDecl* ROOT::TMetaUtils::QualType2ClassTemplateDecl(const clang::QualType& qt)
3679{
3680 using namespace clang;
3684 return ctd;
3685}
3686
3687////////////////////////////////////////////////////////////////////////////////
3688/// These manipulations are necessary because a template specialisation type
3689/// does not inherit from a record type (there is an asymmetry between
3690/// the decls and the types in the clang interface).
3691/// We may need therefore to step into the "Decl dimension" to then get back
3692/// to the "type dimension".
3693
3694clang::TemplateName ROOT::TMetaUtils::ExtractTemplateNameFromQualType(const clang::QualType& qt)
3695{
3696 using namespace clang;
3698
3699 const Type* theType = qt.getTypePtr();
3700
3701 if (const TemplateSpecializationType* tst = llvm::dyn_cast_or_null<const TemplateSpecializationType>(theType)) {
3702 theTemplateName = tst->getTemplateName();
3703 } // We step into the decl dimension
3706 }
3707
3708 return theTemplateName;
3709}
3710
3711////////////////////////////////////////////////////////////////////////////////
3712
3713static bool areEqualTypes(const clang::TemplateArgument& tArg,
3714 llvm::SmallVectorImpl<clang::TemplateArgument>& preceedingTArgs,
3715 const clang::NamedDecl& tPar,
3716 const cling::Interpreter& interp,
3718{
3719 using namespace ROOT::TMetaUtils;
3720 using namespace clang;
3721
3722 // Check if this is a type for security
3723 TemplateTypeParmDecl* ttpdPtr = const_cast<TemplateTypeParmDecl*>(llvm::dyn_cast<TemplateTypeParmDecl>(&tPar));
3724 if (!ttpdPtr) return false;
3725 if (!ttpdPtr->hasDefaultArgument()) return false; // we should not be here in this case, but we protect us.
3726
3727 // Try the fast solution
3728 QualType tParQualType = ttpdPtr->getDefaultArgument();
3729 const QualType tArgQualType = tArg.getAsType();
3730
3731 // Now the equality tests for non template specialisations.
3732
3733 // The easy cases:
3734 // template <class T=double> class A; or
3735 // template <class T=A<float>> class B;
3736 if (tParQualType.getTypePtr() == tArgQualType.getTypePtr()) return true;
3737
3738 // Here the difficulty comes. We have to check if the argument is equal to its
3739 // default. We can do that bootstrapping an argument which has the default value
3740 // based on the preceeding arguments.
3741 // Basically we ask sema to give us the value of the argument given the template
3742 // of behind the parameter and the all the arguments.
3743 // So:
3744
3745 // Take the template out of the parameter
3746
3747 const clang::ElaboratedType* etype
3748 = llvm::dyn_cast<clang::ElaboratedType>(tParQualType.getTypePtr());
3749 while (etype) {
3750 tParQualType = clang::QualType(etype->getNamedType().getTypePtr(),0);
3751 etype = llvm::dyn_cast<clang::ElaboratedType>(tParQualType.getTypePtr());
3752 }
3753
3755 llvm::dyn_cast<TemplateSpecializationType>(tParQualType.getTypePtr());
3756
3757 if(!tst) // nothing more to be tried. They are different indeed.
3758 return false;
3759
3761 = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(tArgQualType->getAsCXXRecordDecl());
3762
3763 if(!TSTdecl) // nothing more to be tried. They are different indeed.
3764 return false;
3765
3766 TemplateDecl *Template = tst->getTemplateName().getAsTemplateDecl();
3767
3768 // Take the template location
3769 SourceLocation TemplateLoc = Template->getSourceRange ().getBegin();
3770
3771 // Get the position of the "<" (LA) of the specializaion
3772 SourceLocation LAngleLoc = TSTdecl->getSourceRange().getBegin();
3773
3774
3775 // Enclose in a scope for the RAII
3776 bool isEqual=false;
3778 {
3779 clang::Sema& S = interp.getCI()->getSema();
3780 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interp));
3781 llvm::SmallVector<clang::TemplateArgument, 4> canonArgs;
3782 bool HasDefaultArgs;
3783 TemplateArgumentLoc defTArgLoc = S.SubstDefaultTemplateArgumentIfAvailable(Template,
3785 LAngleLoc,
3786 ttpdPtr,
3788 canonArgs,
3790 // The substition can fail, in which case there would have been compilation
3791 // error printed on the screen.
3792 newArg = defTArgLoc.getArgument();
3793 if (newArg.isNull() ||
3794 newArg.getKind() != clang::TemplateArgument::Type) {
3795 ROOT::TMetaUtils::Error("areEqualTypes",
3796 "Template parameter substitution failed!");
3797 }
3798
3800 = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(newArg.getAsType()->getAsCXXRecordDecl());
3801// std::cout << "nSTdecl is " << nTSTdecl << std::endl;
3802
3803 isEqual = (nTSTdecl && nTSTdecl->getMostRecentDecl() == TSTdecl->getMostRecentDecl()) ||
3804 (tParQualType.getTypePtr() == newArg.getAsType().getTypePtr());
3805 }
3806
3807
3808 return isEqual;
3809}
3810
3811
3812////////////////////////////////////////////////////////////////////////////////
3813/// std::cout << "Are equal values?\n";
3814
3815static bool areEqualValues(const clang::TemplateArgument& tArg,
3816 const clang::NamedDecl& tPar)
3817{
3818 using namespace clang;
3819 const NonTypeTemplateParmDecl* nttpdPtr = llvm::dyn_cast<NonTypeTemplateParmDecl>(&tPar);
3820 if (!nttpdPtr) return false;
3822
3823 if (!nttpd.hasDefaultArgument())
3824 return false;
3825
3826 // 64 bits wide and signed (non unsigned, that is why "false")
3827 llvm::APSInt defaultValueAPSInt(64, false);
3828 if (Expr* defArgExpr = nttpd.getDefaultArgument()) {
3829 const ASTContext& astCtxt = nttpdPtr->getASTContext();
3830 if (auto Value = defArgExpr->getIntegerConstantExpr(astCtxt))
3832 }
3833
3834 const int value = tArg.getAsIntegral().getLimitedValue();
3835
3836 // std::cout << (value == defaultValueAPSInt ? "yes!":"no") << std::endl;
3837 return value == defaultValueAPSInt;
3838}
3839
3840////////////////////////////////////////////////////////////////////////////////
3841/// Check if this NamedDecl is a template parameter with a default argument.
3842/// This is a single interface to treat both integral and type parameters.
3843/// Returns true if this is the case, false otherwise
3844
3845static bool isTypeWithDefault(const clang::NamedDecl* nDecl)
3846{
3847 using namespace clang;
3848 if (!nDecl) return false;
3849 if (const TemplateTypeParmDecl* ttpd = llvm::dyn_cast<TemplateTypeParmDecl>(nDecl))
3850 return ttpd->hasDefaultArgument();
3851 if (const NonTypeTemplateParmDecl* nttpd = llvm::dyn_cast<NonTypeTemplateParmDecl>(nDecl))
3852 return nttpd->hasDefaultArgument();
3853 return false;
3854
3855}
3856
3857static void KeepNParams(clang::QualType& normalizedType,
3858 const clang::QualType& vanillaType,
3859 const cling::Interpreter& interp,
3861
3862// Returns true if normTArg might have changed.
3863static bool RecurseKeepNParams(clang::TemplateArgument &normTArg,
3864 const clang::TemplateArgument &tArg,
3865 const cling::Interpreter& interp,
3867 const clang::ASTContext& astCtxt)
3868{
3869 using namespace ROOT::TMetaUtils;
3870 using namespace clang;
3871
3872 // Once we know there is no more default parameter, we can run through to the end
3873 // and/or recurse in the template parameter packs.
3874
3875 // If this is a type,
3876 // we need first of all to recurse: this argument may need to be manipulated
3877 if (tArg.getKind() == clang::TemplateArgument::Type) {
3878 QualType thisNormQualType = normTArg.getAsType();
3879 QualType thisArgQualType = tArg.getAsType();
3882 interp,
3883 normCtxt);
3886 } else if (normTArg.getKind() == clang::TemplateArgument::Pack) {
3887 assert( tArg.getKind() == clang::TemplateArgument::Pack );
3888
3890 bool mightHaveChanged = true;
3891 for (auto I = normTArg.pack_begin(), E = normTArg.pack_end(),
3892 FI = tArg.pack_begin(), FE = tArg.pack_end();
3893 I != E && FI != FE; ++I, ++FI)
3894 {
3897 desArgs.push_back(pack_arg);
3898 }
3899 if (mightHaveChanged) {
3900 ASTContext &mutableCtx( const_cast<ASTContext&>(astCtxt) );
3901 normTArg = TemplateArgument::CreatePackCopy(mutableCtx, desArgs);
3902 }
3903 return mightHaveChanged;
3904 }
3905 return false;
3906}
3907
3908
3909////////////////////////////////////////////////////////////////////////////////
3910/// This function allows to manipulate the number of arguments in the type
3911/// of a template specialisation.
3912
3913static void KeepNParams(clang::QualType& normalizedType,
3914 const clang::QualType& vanillaType,
3915 const cling::Interpreter& interp,
3917{
3918 using namespace ROOT::TMetaUtils;
3919 using namespace clang;
3920
3921 // If this type has no template specialisation behind, we don't need to do
3922 // anything
3925 if (! QualType2Template(vanillaType, ctd, ctsd)) return ;
3926
3927 // Even if this is a template, if we don't keep any argument, return
3928 const int nArgsToKeep = normCtxt.GetNargsToKeep(ctd);
3929
3930 // Important in case of early return: we must restore the original qualtype
3932
3933 const ASTContext& astCtxt = ctsd->getASTContext();
3934
3935
3936 // In case of name* we need to strip the pointer first, add the default and attach
3937 // the pointer once again.
3938 if (llvm::isa<clang::PointerType>(normalizedType.getTypePtr())) {
3939 // Get the qualifiers.
3940 clang::Qualifiers quals = normalizedType.getQualifiers();
3941 auto valNormalizedType = normalizedType->getPointeeType();
3943 normalizedType = astCtxt.getPointerType(valNormalizedType);
3944 // Add back the qualifiers.
3945 normalizedType = astCtxt.getQualifiedType(normalizedType, quals);
3946 return;
3947 }
3948
3949 // In case of Int_t& we need to strip the pointer first, desugar and attach
3950 // the pointer once again.
3951 if (llvm::isa<clang::ReferenceType>(normalizedType.getTypePtr())) {
3952 // Get the qualifiers.
3953 bool isLValueRefTy = llvm::isa<clang::LValueReferenceType>(normalizedType.getTypePtr());
3954 clang::Qualifiers quals = normalizedType.getQualifiers();
3955 auto valNormType = normalizedType->getPointeeType();
3957
3958 // Add the r- or l- value reference type back to the desugared one
3959 if (isLValueRefTy)
3960 normalizedType = astCtxt.getLValueReferenceType(valNormType);
3961 else
3962 normalizedType = astCtxt.getRValueReferenceType(valNormType);
3963 // Add back the qualifiers.
3964 normalizedType = astCtxt.getQualifiedType(normalizedType, quals);
3965 return;
3966 }
3967
3968 // Treat the Scope (factorise the code out to reuse it in AddDefaultParameters)
3969 bool prefix_changed = false;
3970 clang::NestedNameSpecifier* prefix = nullptr;
3971 clang::Qualifiers prefix_qualifiers = normalizedType.getLocalQualifiers();
3972 const clang::ElaboratedType* etype
3973 = llvm::dyn_cast<clang::ElaboratedType>(normalizedType.getTypePtr());
3974 if (etype) {
3975 // We have to also handle the prefix.
3976 // TODO: we ought to be running KeepNParams
3977 prefix = AddDefaultParametersNNS(astCtxt, etype->getQualifier(), interp, normCtxt);
3978 prefix_changed = prefix != etype->getQualifier();
3979 normalizedType = clang::QualType(etype->getNamedType().getTypePtr(),0);
3980 }
3981
3982 // The canonical decl does not necessarily have the template default arguments.
3983 // Need to walk through the redecl chain to find it (we know there will be no
3984 // inconsistencies, at least)
3985 const clang::ClassTemplateDecl* ctdWithDefaultArgs = ctd;
3986 for (const RedeclarableTemplateDecl* rd: ctdWithDefaultArgs->redecls()) {
3987 clang::TemplateParameterList* tpl = rd->getTemplateParameters();
3988 if (tpl->getMinRequiredArguments () < tpl->size()) {
3989 ctdWithDefaultArgs = llvm::dyn_cast<clang::ClassTemplateDecl>(rd);
3990 break;
3991 }
3992 }
3993
3994 if (!ctdWithDefaultArgs) {
3995 Error("KeepNParams", "Not found template default arguments\n");
3997 return;
3998 }
3999
4000 TemplateParameterList* tParsPtr = ctdWithDefaultArgs->getTemplateParameters();
4002 const TemplateArgumentList& tArgs = ctsd->getTemplateArgs();
4003
4004 // We extract the template name from the type
4005 TemplateName theTemplateName = ExtractTemplateNameFromQualType(normalizedType);
4006 if (theTemplateName.isNull()) {
4008 return;
4009 }
4010
4012 llvm::dyn_cast<TemplateSpecializationType>(normalizedType.getTypePtr());
4013 if (!normalizedTst) {
4015 return;
4016 }
4017
4018 const clang::ClassTemplateSpecializationDecl* TSTdecl
4019 = llvm::dyn_cast_or_null<const clang::ClassTemplateSpecializationDecl>(normalizedType.getTypePtr()->getAsCXXRecordDecl());
4020 bool isStdDropDefault = TSTdecl && IsStdDropDefaultClass(*TSTdecl);
4021
4022 // Loop over the template parameters and arguments recursively.
4023 // We go down the two lanes: the one of template parameters (decls) and the
4024 // one of template arguments (QualTypes) in parallel. The former are a
4025 // property of the template, independent of its instantiations.
4026 // The latter are a property of the instance itself.
4027 llvm::SmallVector<TemplateArgument, 4> argsToKeep;
4028
4029 const int nArgs = tArgs.size();
4030 const auto &normArgs = normalizedTst->template_arguments();
4031 const int nNormArgs = normArgs.size();
4032
4033 bool mightHaveChanged = false;
4034
4035 // becomes true when a parameter has a value equal to its default
4036 for (int formal = 0, inst = 0; formal != nArgs; ++formal, ++inst) {
4037 const NamedDecl* tParPtr = tPars.getParam(formal);
4038 if (!tParPtr) {
4039 Error("KeepNParams", "The parameter number %s is null.\n", formal);
4040 continue;
4041 }
4042
4043 // Stop if the normalized TemplateSpecializationType has less arguments than
4044 // the one index is pointing at.
4045 // We piggy back on the AddDefaultParameters routine basically.
4046 if (formal == nNormArgs || inst == nNormArgs) break;
4047
4048 const TemplateArgument& tArg = tArgs.get(formal);
4050
4051 bool shouldKeepArg = nArgsToKeep < 0 || inst < nArgsToKeep;
4052 if (isStdDropDefault) shouldKeepArg = false;
4053
4054 // Nothing to do here: either this parameter has no default, or we have to keep it.
4055 // FIXME: Temporary measure to get Atlas started with this.
4056 // We put a hard cut on the number of template arguments to keep, w/o checking if
4057 // they are non default. This makes this feature UNUSABLE for cases like std::vector,
4058 // where 2 different entities would have the same name if an allocator different from
4059 // the default one is by chance used.
4061 if ( tParPtr->isTemplateParameterPack() ) {
4062 // This is the last template parameter in the template declaration
4063 // but it is signaling that there can be an arbitrary number of arguments
4064 // in the template instance. So to avoid inadvertenly dropping those
4065 // arguments we just process all remaining argument and exit the main loop.
4066 for( ; inst != nNormArgs; ++inst) {
4069 argsToKeep.push_back(normTArg);
4070 }
4071 // Done.
4072 break;
4073 }
4075 argsToKeep.push_back(normTArg);
4076 continue;
4077 } else {
4078 if (!isStdDropDefault) {
4079 // Here we should not break but rather check if the value is the default one.
4080 mightHaveChanged = true;
4081 break;
4082 }
4083 // For std, we want to check the default args values.
4084 }
4085
4086 // Now, we keep it only if it not is equal to its default, expressed in the arg
4087 // Some gymnastic is needed to decide how to check for equality according to the
4088 // flavour of Type: templateType or Integer
4089 bool equal=false;
4090 auto argKind = tArg.getKind();
4091 if (argKind == clang::TemplateArgument::Type){
4092 // we need all the info
4094 } else if (argKind == clang::TemplateArgument::Integral){
4095 equal = areEqualValues(tArg, *tParPtr);
4096 }
4097 if (!equal) {
4099 argsToKeep.push_back(normTArg);
4100 } else {
4101 mightHaveChanged = true;
4102 }
4103
4104
4105 } // of loop over parameters and arguments
4106
4109 return;
4110 }
4111
4112 // now, let's remanipulate our Qualtype
4113 if (mightHaveChanged) {
4114 Qualifiers qualifiers = normalizedType.getLocalQualifiers();
4115 normalizedType = astCtxt.getTemplateSpecializationType(theTemplateName,
4116 argsToKeep,
4117 normalizedType.getTypePtr()->getCanonicalTypeInternal());
4118 normalizedType = astCtxt.getQualifiedType(normalizedType, qualifiers);
4119 }
4120
4121 // Here we have (prefix_changed==true || mightHaveChanged), in both case
4122 // we need to reconstruct the type.
4123 if (prefix) {
4124 normalizedType = astCtxt.getElaboratedType(clang::ElaboratedTypeKeyword::None, prefix, normalizedType);
4126 }
4127
4128}
4129
4130////////////////////////////////////////////////////////////////////////////////
4131/// Return the type normalized for ROOT,
4132/// keeping only the ROOT opaque typedef (Double32_t, etc.) and
4133/// adding default template argument for all types except those explicitly
4134/// requested to be drop by the user.
4135/// Default template for STL collections are not yet removed by this routine.
4136
4137clang::QualType ROOT::TMetaUtils::GetNormalizedType(const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
4138{
4139 clang::ASTContext &ctxt = interpreter.getCI()->getASTContext();
4140
4141 // Modules can trigger deserialization.
4142 cling::Interpreter::PushTransactionRAII RAII(const_cast<cling::Interpreter*>(&interpreter));
4143 clang::QualType normalizedType = cling::utils::Transform::GetPartiallyDesugaredType(ctxt, type, normCtxt.GetConfig(), true /* fully qualify */);
4144
4145 // Readd missing default template parameters
4147
4148 // Get the number of arguments to keep in case they are not default.
4150
4151 return normalizedType;
4152}
4153
4154////////////////////////////////////////////////////////////////////////////////
4155/// Return the type name normalized for ROOT,
4156/// keeping only the ROOT opaque typedef (Double32_t, etc.) and
4157/// adding default template argument for all types except the STL collections
4158/// where we remove the default template argument if any.
4159///
4160/// This routine might actually belong in the interpreter because
4161/// cache the clang::Type might be intepreter specific.
4162
4163void ROOT::TMetaUtils::GetNormalizedName(std::string &norm_name, const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
4164{
4165 if (type.isNull()) {
4166 norm_name = "";
4167 return;
4168 }
4169
4171
4172 clang::ASTContext &ctxt = interpreter.getCI()->getASTContext();
4173 clang::PrintingPolicy policy(ctxt.getPrintingPolicy());
4174 policy.SuppressTagKeyword = true; // Never get the class or struct keyword
4175 policy.SuppressScope = true; // Force the scope to be coming from a clang::ElaboratedType.
4176 policy.AnonymousTagLocations = false; // Do not extract file name + line number for anonymous types.
4177 // The scope suppression is required for getting rid of the anonymous part of the name of a class defined in an anonymous namespace.
4178 // This gives us more control vs not using the clang::ElaboratedType and relying on the Policy.SuppressUnwrittenScope which would
4179 // strip both the anonymous and the inline namespace names (and we probably do not want the later to be suppressed).
4180
4181 std::string normalizedNameStep1;
4182
4183 // getAsStringInternal can trigger deserialization
4184 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interpreter));
4185 normalizedType.getAsStringInternal(normalizedNameStep1,policy);
4186
4187 // Still remove the std:: and default template argument for STL container and
4188 // normalize the location and amount of white spaces.
4191
4192 // The result of this routine is by definition a fully qualified name. There is an implicit starting '::' at the beginning of the name.
4193 // Depending on how the user typed their code, in particular typedef declarations, we may end up with an explicit '::' being
4194 // part of the result string. For consistency, we must remove it.
4195 if (norm_name.length()>2 && norm_name[0]==':' && norm_name[1]==':') {
4196 norm_name.erase(0,2);
4197 }
4198
4199}
4200
4201////////////////////////////////////////////////////////////////////////////////
4202
4204 const clang::TypeDecl* typeDecl,
4205 const cling::Interpreter &interpreter)
4206{
4208 const clang::Sema &sema = interpreter.getSema();
4209 clang::ASTContext& astCtxt = sema.getASTContext();
4210 clang::QualType qualType = astCtxt.getTypeDeclType(typeDecl);
4211
4213 qualType,
4215 tNormCtxt);
4216}
4217
4218////////////////////////////////////////////////////////////////////////////////
4219std::pair<std::string,clang::QualType>
4221 const cling::Interpreter &interpreter,
4224{
4225 std::string thisTypeName;
4226 GetNormalizedName(thisTypeName, thisType, interpreter, normCtxt );
4227 bool hasChanged;
4229 if (!hasChanged) return std::make_pair(thisTypeName,thisType);
4230
4232 ROOT::TMetaUtils::Info("ROOT::TMetaUtils::GetTypeForIO",
4233 "Name changed from %s to %s\n", thisTypeName.c_str(), thisTypeNameForIO.c_str());
4234 }
4235
4236 auto& lookupHelper = interpreter.getLookupHelper();
4237
4238 const clang::Type* typePtrForIO;
4240 cling::LookupHelper::DiagSetting::NoDiagnostics,
4241 &typePtrForIO);
4242
4243 // This should never happen
4244 if (!typePtrForIO) {
4245 ROOT::TMetaUtils::Fatal("ROOT::TMetaUtils::GetTypeForIO",
4246 "Type not found: %s.",thisTypeNameForIO.c_str());
4247 }
4248
4249 clang::QualType typeForIO(typePtrForIO,0);
4250
4251 // Check if this is a class. Indeed it could well be a POD
4252 if (!typeForIO->isRecordType()) {
4253 return std::make_pair(thisTypeNameForIO,typeForIO);
4254 }
4255
4256 auto thisDeclForIO = typeForIO->getAsCXXRecordDecl();
4257 if (!thisDeclForIO) {
4258 ROOT::TMetaUtils::Error("ROOT::TMetaUtils::GetTypeForIO",
4259 "The type for IO corresponding to %s is %s and it could not be found in the AST as class.\n", thisTypeName.c_str(), thisTypeNameForIO.c_str());
4260 return std::make_pair(thisTypeName,thisType);
4261 }
4262
4263 return std::make_pair(thisTypeNameForIO,typeForIO);
4264}
4265
4266////////////////////////////////////////////////////////////////////////////////
4267
4268clang::QualType ROOT::TMetaUtils::GetTypeForIO(const clang::QualType& thisType,
4269 const cling::Interpreter &interpreter,
4272{
4274}
4275
4276////////////////////////////////////////////////////////////////////////////////
4277/// Return the dictionary file name for a module
4278
4280{
4281 std::string dictFileName(moduleName);
4282 dictFileName += "_rdict.pcm";
4283 return dictFileName;
4284}
4285
4286int dumpDeclForAssert(const clang::Decl& D, const char* commentStart) {
4287 llvm::errs() << llvm::StringRef(commentStart, 80) << '\n';
4288 D.dump();
4289 return 0;
4290}
4291
4292////////////////////////////////////////////////////////////////////////////////
4293/// Returns the comment (// striped away), annotating declaration in a meaningful
4294/// for ROOT IO way.
4295/// Takes optional out parameter clang::SourceLocation returning the source
4296/// location of the comment.
4297///
4298/// CXXMethodDecls, FieldDecls and TagDecls are annotated.
4299/// CXXMethodDecls declarations and FieldDecls are annotated as follows:
4300/// Eg. void f(); // comment1
4301/// int member; // comment2
4302/// Inline definitions of CXXMethodDecls after the closing } \n. Eg:
4303/// void f()
4304/// {...} // comment3
4305/// TagDecls are annotated in the end of the ClassDef macro. Eg.
4306/// class MyClass {
4307/// ...
4308/// ClassDef(MyClass, 1) // comment4
4309///
4310
4311llvm::StringRef ROOT::TMetaUtils::GetComment(const clang::Decl &decl, clang::SourceLocation *loc)
4312{
4313 clang::SourceManager& sourceManager = decl.getASTContext().getSourceManager();
4314 clang::SourceLocation sourceLocation = decl.getEndLoc();
4315
4316 // If the location is a macro get the expansion location.
4317 sourceLocation = sourceManager.getExpansionRange(sourceLocation).getEnd();
4318 // FIXME: We should optimize this routine instead making it do the wrong thing
4319 // returning an empty comment if the decl came from the AST.
4320 // In order to do that we need to: check if the decl has an attribute and
4321 // return the attribute content (including walking the redecl chain) and if
4322 // this is not the case we should try finding it in the header file.
4323 // This will allow us to move the implementation of TCling*Info::Title() in
4324 // TClingDeclInfo.
4325 if (!decl.hasOwningModule() && sourceManager.isLoadedSourceLocation(sourceLocation)) {
4326 // Do not touch disk for nodes coming from the PCH.
4327 return "";
4328 }
4329
4330 bool invalid;
4331 const char *commentStart = sourceManager.getCharacterData(sourceLocation, &invalid);
4332 if (invalid)
4333 return "";
4334
4335 bool skipToSemi = true;
4336 if (const clang::FunctionDecl* FD = clang::dyn_cast<clang::FunctionDecl>(&decl)) {
4337 if (FD->isImplicit()) {
4338 // Compiler generated function.
4339 return "";
4340 }
4341 if (FD->isExplicitlyDefaulted() || FD->isDeletedAsWritten()) {
4342 // ctorOrFunc() = xyz; with commentStart pointing somewhere into
4343 // ctorOrFunc.
4344 // We have to skipToSemi
4345 } else if (FD->doesThisDeclarationHaveABody()) {
4346 // commentStart is at body's '}'
4347 // But we might end up e.g. at the ')' of a CPP macro
4348 assert((decl.getEndLoc() != sourceLocation || *commentStart == '}'
4350 && "Expected macro or end of body at '}'");
4351 if (*commentStart) ++commentStart;