Logo ROOT  
Reference Guide
 
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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 // Make a list of modules and submodules that we can check for headers.
2790 // We use a SetVector to prevent an infinite loop in unlikely case the
2791 // modules somehow are messed up and don't form a tree...
2792 llvm::SetVector<const clang::Module *> modules;
2793 modules.insert(&module);
2794 for (size_t i = 0; i < modules.size(); ++i) {
2795 const clang::Module *M = modules[i];
2796 for (const clang::Module *subModule : M->submodules())
2797 modules.insert(subModule);
2798 }
2799
2800 for (const clang::Module *m : modules) {
2802 for (clang::Module *used : m->DirectUses) {
2804 }
2805 }
2806
2807 // We want to check for all headers except the list of excluded headers here.
2808 for (auto HK : {clang::Module::HK_Normal, clang::Module::HK_Textual, clang::Module::HK_Private,
2809 clang::Module::HK_PrivateTextual}) {
2810 auto &headerList = m->Headers[HK];
2811 for (const clang::Module::Header &moduleHeader : headerList) {
2813 }
2814 }
2815 }
2816}
2817
2818////////////////////////////////////////////////////////////////////////////////
2819/// Return the absolute type of typeDesc.
2820/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
2821/// we remove * and const keywords. (we do not want to remove & ).
2822/// You need to use the result immediately before it is being overwritten.
2823
2825{
2826 static char t[4096];
2827 static const char* constwd = "const ";
2828 static const char* constwdend = "const";
2829
2830 const char *s;
2831 char *p=t;
2832 int lev=0;
2833 for (s=typeDesc;*s;s++) {
2834 if (*s=='<') lev++;
2835 if (*s=='>') lev--;
2836 if (lev==0 && *s=='*') continue;
2837 if (lev==0 && (strncmp(constwd,s,strlen(constwd))==0
2838 ||strcmp(constwdend,s)==0 ) ) {
2839 s+=strlen(constwd)-1; // -1 because the loop adds 1
2840 continue;
2841 }
2842 if (lev==0 && *s==' ' && *(s+1)!='*') { p = t; continue;}
2843 if (p - t > (long)sizeof(t)) {
2844 printf("ERROR (rootcling): type name too long for StortTypeName: %s\n",
2845 typeDesc);
2846 p[0] = 0;
2847 return t;
2848 }
2849 *p++ = *s;
2850 }
2851 p[0]=0;
2852
2853 return t;
2854}
2855
2856bool ROOT::TMetaUtils::IsStreamableObject(const clang::FieldDecl &m,
2857 const cling::Interpreter& interp)
2858{
2859 auto comment = ROOT::TMetaUtils::GetComment( m );
2860
2861 // Transient
2862 if (!comment.empty() && comment[0] == '!')
2863 return false;
2864
2865 clang::QualType type = m.getType();
2866
2867 if (type->isReferenceType()) {
2868 // Reference can not be streamed.
2869 return false;
2870 }
2871
2872 std::string mTypeName = type.getAsString(m.getASTContext().getPrintingPolicy());
2873 if (!strcmp(mTypeName.c_str(), "string") || !strcmp(mTypeName.c_str(), "string*")) {
2874 return true;
2875 }
2876 if (!strcmp(mTypeName.c_str(), "std::string") || !strcmp(mTypeName.c_str(), "std::string*")) {
2877 return true;
2878 }
2879
2881 return true;
2882 }
2883
2884 const clang::Type *rawtype = type.getTypePtr()->getBaseElementTypeUnsafe ();
2885
2886 if (rawtype->isPointerType()) {
2887 //Get to the 'raw' type.
2888 clang::QualType pointee;
2889 while ( (pointee = rawtype->getPointeeType()) , pointee.getTypePtrOrNull() && pointee.getTypePtr() != rawtype)
2890 {
2891 rawtype = pointee.getTypePtr();
2892 }
2893 }
2894
2895 if (rawtype->isFundamentalType() || rawtype->isEnumeralType()) {
2896 // not an ojbect.
2897 return false;
2898 }
2899
2900 const clang::CXXRecordDecl *cxxdecl = rawtype->getAsCXXRecordDecl();
2902 if (!(ROOT::TMetaUtils::ClassInfo__HasMethod(cxxdecl,"Class_Version", interp))) return true;
2904 if (version > 0) return true;
2905 }
2906 return false;
2907}
2908
2909////////////////////////////////////////////////////////////////////////////////
2910/// Return the absolute type of typeDesc.
2911/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
2912/// we remove * and const keywords. (we do not want to remove & ).
2913/// You need to use the result immediately before it is being overwritten.
2914
2915std::string ROOT::TMetaUtils::ShortTypeName(const clang::FieldDecl &m)
2916{
2917 const clang::Type *rawtype = m.getType().getTypePtr();
2918
2919 //Get to the 'raw' type.
2920 clang::QualType pointee;
2921 while ( rawtype->isPointerType() && ((pointee = rawtype->getPointeeType()) , pointee.getTypePtrOrNull()) && pointee.getTypePtr() != rawtype)
2922 {
2923 rawtype = pointee.getTypePtr();
2924 }
2925
2926 std::string result;
2927 ROOT::TMetaUtils::GetQualifiedName(result, clang::QualType(rawtype,0), m);
2928 return result;
2929}
2930
2931////////////////////////////////////////////////////////////////////////////////
2932
2933clang::RecordDecl *ROOT::TMetaUtils::GetUnderlyingRecordDecl(clang::QualType type)
2934{
2935 const clang::Type *rawtype = ROOT::TMetaUtils::GetUnderlyingType(type);
2936
2937 if (rawtype->isFundamentalType() || rawtype->isEnumeralType()) {
2938 // not an object.
2939 return nullptr;
2940 }
2941 return rawtype->getAsCXXRecordDecl();
2942}
2943
2944////////////////////////////////////////////////////////////////////////////////
2945/// Generate the code of the class
2946/// If the requestor is genreflex, request the new streamer format
2947
2949 const AnnotatedRecordDecl &cl,
2950 const cling::Interpreter &interp,
2952 std::ostream& dictStream,
2954 bool isGenreflex=false)
2955{
2956 const clang::CXXRecordDecl* decl = llvm::dyn_cast<clang::CXXRecordDecl>(cl.GetRecordDecl());
2957
2958 if (!decl || !decl->isCompleteDefinition()) {
2959 return;
2960 }
2961
2962 std::string fullname;
2964 if (TClassEdit::IsSTLCont(fullname) ) {
2965 Internal::RStl::Instance().GenerateTClassFor(cl.GetNormalizedName(), llvm::dyn_cast<clang::CXXRecordDecl>(cl.GetRecordDecl()), interp, normCtxt);
2966 return;
2967 }
2968
2970 // The !genreflex is there to prevent genreflex to select collections which are data members
2971 // This is to maintain the behaviour of ROOT5 and ROOT6 up to 6.07 included.
2972 if (cl.RootFlag() && !isGenreflex) ROOT::TMetaUtils::WritePointersSTL(cl, interp, normCtxt); // In particular this detect if the class has a version number.
2973 if (!(cl.RequestNoStreamer())) {
2974 (*WriteStreamerFunc)(cl, interp, normCtxt, dictStream, isGenreflex || cl.RequestStreamerInfo());
2975 } else
2976 ROOT::TMetaUtils::Info(nullptr, "Class %s: Do not generate Streamer() [*** custom streamer ***]\n",fullname.c_str());
2977 } else {
2978 ROOT::TMetaUtils::Info(nullptr, "Class %s: Streamer() not declared\n", fullname.c_str());
2979
2980 // See comment above about the !isGenreflex
2982 }
2984}
2985
2986////////////////////////////////////////////////////////////////////////////////
2987/// Add any unspecified template parameters to the class template instance,
2988/// mentioned anywhere in the type.
2989///
2990/// Note: this does not strip any typedef but could be merged with cling::utils::Transform::GetPartiallyDesugaredType
2991/// if we can safely replace TClassEdit::IsStd with a test on the declaring scope
2992/// and if we can resolve the fact that the added parameter do not take into account possible use/dependences on Double32_t
2993/// and if we decide that adding the default is the right long term solution or not.
2994/// Whether it is or not depend on the I/O on whether the default template argument might change or not
2995/// and whether they (should) affect the on disk layout (for STL containers, we do know they do not).
2996
2998 const cling::Interpreter &interpreter,
3000{
3001 const clang::ASTContext& Ctx = interpreter.getCI()->getASTContext();
3002
3003 clang::QualType originalType = instanceType;
3004
3005 // In case of name* we need to strip the pointer first, add the default and attach
3006 // the pointer once again.
3007 if (llvm::isa<clang::PointerType>(instanceType.getTypePtr())) {
3008 // Get the qualifiers.
3009 clang::Qualifiers quals = instanceType.getQualifiers();
3010 clang::QualType newPointee = AddDefaultParameters(instanceType->getPointeeType(), interpreter, normCtxt);
3011 if (newPointee != instanceType->getPointeeType()) {
3012 instanceType = Ctx.getPointerType(newPointee);
3013 // Add back the qualifiers.
3014 instanceType = Ctx.getQualifiedType(instanceType, quals);
3015 }
3016 return instanceType;
3017 }
3018
3019 // In case of Int_t& we need to strip the pointer first, desugar and attach
3020 // the pointer once again.
3021 if (llvm::isa<clang::ReferenceType>(instanceType.getTypePtr())) {
3022 // Get the qualifiers.
3023 bool isLValueRefTy = llvm::isa<clang::LValueReferenceType>(instanceType.getTypePtr());
3024 clang::Qualifiers quals = instanceType.getQualifiers();
3025 clang::QualType newPointee = AddDefaultParameters(instanceType->getPointeeType(), interpreter, normCtxt);
3026
3027 if (newPointee != instanceType->getPointeeType()) {
3028 // Add the r- or l- value reference type back to the desugared one
3029 if (isLValueRefTy)
3030 instanceType = Ctx.getLValueReferenceType(newPointee);
3031 else
3032 instanceType = Ctx.getRValueReferenceType(newPointee);
3033 // Add back the qualifiers.
3034 instanceType = Ctx.getQualifiedType(instanceType, quals);
3035 }
3036 return instanceType;
3037 }
3038
3039 // Treat the Scope.
3040 bool prefix_changed = false;
3041 clang::NestedNameSpecifier *prefix = nullptr;
3042 clang::Qualifiers prefix_qualifiers = instanceType.getLocalQualifiers();
3043 const clang::ElaboratedType* etype
3044 = llvm::dyn_cast<clang::ElaboratedType>(instanceType.getTypePtr());
3045 if (etype) {
3046 // We have to also handle the prefix.
3047 prefix = AddDefaultParametersNNS(Ctx, etype->getQualifier(), interpreter, normCtxt);
3048 prefix_changed = prefix != etype->getQualifier();
3049 instanceType = clang::QualType(etype->getNamedType().getTypePtr(),0);
3050 }
3051
3052 // In case of template specializations iterate over the arguments and
3053 // add unspecified default parameter.
3054
3055 const clang::TemplateSpecializationType* TST
3056 = llvm::dyn_cast<const clang::TemplateSpecializationType>(instanceType.getTypePtr());
3057
3058 const clang::ClassTemplateSpecializationDecl* TSTdecl
3059 = llvm::dyn_cast_or_null<const clang::ClassTemplateSpecializationDecl>(instanceType.getTypePtr()->getAsCXXRecordDecl());
3060
3061 // Don't add the default paramater onto std classes.
3062 // We really need this for __shared_ptr which add a enum constant value which
3063 // is spelled in its 'numeral' form and thus the resulting type name is
3064 // incorrect. We also can used this for any of the STL collections where we
3065 // know we don't want the default argument. For the other members of the
3066 // std namespace this is dubious (because TMetaUtils::GetNormalizedName would
3067 // not drop those defaults). [I.e. the real test ought to be is std and
3068 // name is __shared_ptr or vector or list or set or etc.]
3070
3071 bool mightHaveChanged = false;
3072 if (TST && TSTdecl) {
3073
3074 clang::Sema& S = interpreter.getCI()->getSema();
3075 clang::TemplateDecl *Template = TSTdecl->getSpecializedTemplate()->getMostRecentDecl();
3076 clang::TemplateParameterList *Params = Template->getTemplateParameters();
3077 clang::TemplateParameterList::iterator Param = Params->begin(); // , ParamEnd = Params->end();
3078 //llvm::SmallVectorImpl<TemplateArgument> Converted; // Need to contains the other arguments.
3079 // Converted seems to be the same as our 'desArgs'
3080
3081 unsigned int dropDefault = normCtxt.GetConfig().DropDefaultArg(*Template);
3082
3083 llvm::SmallVector<clang::TemplateArgument, 4> desArgs;
3084 llvm::SmallVector<clang::TemplateArgument, 4> canonArgs;
3085 llvm::ArrayRef<clang::TemplateArgument> template_arguments = TST->template_arguments();
3086 unsigned int Idecl = 0, Edecl = TSTdecl->getTemplateArgs().size();
3087 unsigned int maxAddArg = TSTdecl->getTemplateArgs().size() - dropDefault;
3088 for (const clang::TemplateArgument *I = template_arguments.begin(), *E = template_arguments.end(); Idecl != Edecl;
3089 I != E ? ++I : nullptr, ++Idecl, ++Param) {
3090
3091 if (I != E) {
3092
3093 if (I->getKind() == clang::TemplateArgument::Template) {
3094 clang::TemplateName templateName = I->getAsTemplate();
3095 clang::TemplateDecl* templateDecl = templateName.getAsTemplateDecl();
3096 if (templateDecl) {
3097 clang::DeclContext* declCtxt = templateDecl->getDeclContext();
3098
3099 if (declCtxt && !templateName.getAsQualifiedTemplateName()){
3100 clang::NamespaceDecl* ns = clang::dyn_cast<clang::NamespaceDecl>(declCtxt);
3101 clang::NestedNameSpecifier* nns;
3102 if (ns) {
3103 nns = cling::utils::TypeName::CreateNestedNameSpecifier(Ctx, ns);
3104 } else if (clang::TagDecl* TD = llvm::dyn_cast<clang::TagDecl>(declCtxt)) {
3105 nns = cling::utils::TypeName::CreateNestedNameSpecifier(Ctx,TD, false /*FullyQualified*/);
3106 } else {
3107 // TU scope
3108 desArgs.push_back(*I);
3109 continue;
3110 }
3111 clang::TemplateName UnderlyingTN(templateDecl);
3112 if (clang::UsingShadowDecl *USD = templateName.getAsUsingShadowDecl())
3113 UnderlyingTN = clang::TemplateName(USD);
3114 clang::TemplateName templateNameWithNSS ( Ctx.getQualifiedTemplateName(nns, false, UnderlyingTN) );
3115 desArgs.push_back(clang::TemplateArgument(templateNameWithNSS));
3116 mightHaveChanged = true;
3117 continue;
3118 }
3119 }
3120 }
3121
3122 if (I->getKind() != clang::TemplateArgument::Type) {
3123 desArgs.push_back(*I);
3124 continue;
3125 }
3126
3127 clang::QualType SubTy = I->getAsType();
3128
3129 // Check if the type needs more desugaring and recurse.
3130 // (Originally this was limited to elaborated and templated type,
3131 // but we also need to do it for pointer and reference type
3132 // and who knows what, so do it always)
3133 clang::QualType newSubTy = AddDefaultParameters(SubTy,
3135 normCtxt);
3136 if (SubTy != newSubTy) {
3137 mightHaveChanged = true;
3138 desArgs.push_back(clang::TemplateArgument(newSubTy));
3139 } else {
3140 desArgs.push_back(*I);
3141 }
3142 // Converted.push_back(TemplateArgument(ArgTypeForTemplate));
3143 } else if (!isStdDropDefault && Idecl < maxAddArg) {
3144
3145 mightHaveChanged = true;
3146
3147 const clang::TemplateArgument& templateArg
3148 = TSTdecl->getTemplateArgs().get(Idecl);
3149 if (templateArg.getKind() != clang::TemplateArgument::Type) {
3150 desArgs.push_back(templateArg);
3151 continue;
3152 }
3153 clang::QualType SubTy = templateArg.getAsType();
3154
3155 clang::SourceLocation TemplateLoc = Template->getSourceRange ().getBegin(); //NOTE: not sure that this is the 'right' location.
3156 clang::SourceLocation RAngleLoc = TSTdecl->getSourceRange().getBegin(); // NOTE: most likely wrong, I think this is expecting the location of right angle
3157
3158 clang::TemplateTypeParmDecl *TTP = llvm::dyn_cast<clang::TemplateTypeParmDecl>(*Param);
3159 {
3160 // We may induce template instantiation
3161 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interpreter));
3162 bool HasDefaultArgs;
3163 clang::TemplateArgumentLoc ArgType = S.SubstDefaultTemplateArgumentIfAvailable(
3164 Template,
3166 RAngleLoc,
3167 TTP,
3168 desArgs,
3169 canonArgs,
3171 // The substition can fail, in which case there would have been compilation
3172 // error printed on the screen.
3173 if (ArgType.getArgument().isNull()
3174 || ArgType.getArgument().getKind() != clang::TemplateArgument::Type) {
3175 ROOT::TMetaUtils::Error("ROOT::TMetaUtils::AddDefaultParameters",
3176 "Template parameter substitution failed for %s around %s\n",
3177 instanceType.getAsString().c_str(), SubTy.getAsString().c_str());
3178 break;
3179 }
3180 clang::QualType BetterSubTy = ArgType.getArgument().getAsType();
3181 SubTy = cling::utils::Transform::GetPartiallyDesugaredType(Ctx,BetterSubTy,normCtxt.GetConfig(),/*fullyQualified=*/ true);
3182 }
3184 desArgs.push_back(clang::TemplateArgument(SubTy));
3185 } else {
3186 // We are past the end of the list of specified arguements and we
3187 // do not want to add the default, no need to continue.
3188 break;
3189 }
3190 }
3191
3192 // If we added default parameter, allocate new type in the AST.
3193 if (mightHaveChanged) {
3194 instanceType = Ctx.getTemplateSpecializationType(TST->getTemplateName(),
3195 desArgs,
3196 TST->getCanonicalTypeInternal());
3197 }
3198 }
3199
3201 if (prefix) {
3202 instanceType = Ctx.getElaboratedType(clang::ElaboratedTypeKeyword::None, prefix, instanceType);
3203 instanceType = Ctx.getQualifiedType(instanceType,prefix_qualifiers);
3204 }
3205 return instanceType;
3206}
3207
3208////////////////////////////////////////////////////////////////////////////////
3209/// ValidArrayIndex return a static string (so use it or copy it immediatly, do not
3210/// call GrabIndex twice in the same expression) containing the size of the
3211/// array data member.
3212/// In case of error, or if the size is not specified, GrabIndex returns 0.
3213/// If errnum is not null, *errnum updated with the error number:
3214/// Cint::G__DataMemberInfo::G__VALID : valid array index
3215/// Cint::G__DataMemberInfo::G__NOT_INT : array index is not an int
3216/// Cint::G__DataMemberInfo::G__NOT_DEF : index not defined before array
3217/// (this IS an error for streaming to disk)
3218/// Cint::G__DataMemberInfo::G__IS_PRIVATE: index exist in a parent class but is private
3219/// Cint::G__DataMemberInfo::G__UNKNOWN : index is not known
3220/// If errstr is not null, *errstr is updated with the address of a static
3221/// string containing the part of the index with is invalid.
3222
3223llvm::StringRef ROOT::TMetaUtils::DataMemberInfo__ValidArrayIndex(const cling::Interpreter &interp, const clang::DeclaratorDecl &m, int *errnum, llvm::StringRef *errstr)
3224{
3225 llvm::StringRef title;
3226
3227 // Try to get the comment either from the annotation or the header file if present
3228 if (clang::AnnotateAttr *A = m.getAttr<clang::AnnotateAttr>())
3229 title = A->getAnnotation();
3230 else
3231 // Try to get the comment from the header file if present
3233
3234 // Let's see if the user provided us with some information
3235 // with the format: //[dimension] this is the dim of the array
3236 // dimension can be an arithmetical expression containing, literal integer,
3237 // the operator *,+ and - and data member of integral type. In addition the
3238 // data members used for the size of the array need to be defined prior to
3239 // the array.
3240
3241 if (errnum) *errnum = VALID;
3242
3243 if (title.size() == 0 || (title[0] != '[')) return llvm::StringRef();
3244 size_t rightbracket = title.find(']');
3245 if (rightbracket == llvm::StringRef::npos) return llvm::StringRef();
3246
3247 std::string working;
3248 llvm::StringRef indexvar(title.data()+1,rightbracket-1);
3249
3250 // now we should have indexvar=dimension
3251 // Let's see if this is legal.
3252 // which means a combination of data member and digit separated by '*','+','-'
3253 // First we remove white spaces.
3254 unsigned int i;
3255 size_t indexvarlen = indexvar.size();
3256 for ( i=0; i<indexvarlen; i++) {
3257 if (!isspace(indexvar[i])) {
3258 working += indexvar[i];
3259 }
3260 }
3261
3262 // Now we go through all indentifiers
3263 const char *tokenlist = "*+-";
3264 char *current = const_cast<char*>(working.c_str());
3265 current = strtok(current,tokenlist); // this method does not need to be reentrant
3266
3267 while (current) {
3268 // Check the token
3269 if (isdigit(current[0])) {
3270 for(i=0;i<strlen(current);i++) {
3271 if (!isdigit(current[i])) {
3272 // Error we only access integer.
3273 //NOTE: *** Need to print an error;
3274 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not an interger\n",
3275 // member.MemberOf()->Name(), member.Name(), current);
3276 if (errstr) *errstr = current;
3277 if (errnum) *errnum = NOT_INT;
3278 return llvm::StringRef();
3279 }
3280 }
3281 } else { // current token is not a digit
3282 // first let's see if it is a data member:
3283 const clang::CXXRecordDecl *parent_clxx = llvm::dyn_cast<clang::CXXRecordDecl>(m.getDeclContext());
3284 const clang::FieldDecl *index1 = nullptr;
3285 if (parent_clxx)
3287 if ( index1 ) {
3288 if ( IsFieldDeclInt(index1) ) {
3289 // Let's see if it has already been written down in the
3290 // Streamer.
3291 // Let's see if we already wrote it down in the
3292 // streamer.
3293 for(clang::RecordDecl::field_iterator field_iter = parent_clxx->field_begin(), end = parent_clxx->field_end();
3294 field_iter != end;
3295 ++field_iter)
3296 {
3297 if ( field_iter->getNameAsString() == m.getNameAsString() ) {
3298 // we reached the current data member before
3299 // reaching the index so we have not written it yet!
3300 //NOTE: *** Need to print an error;
3301 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) has not been defined before the array \n",
3302 // member.MemberOf()->Name(), member.Name(), current);
3303 if (errstr) *errstr = current;
3304 if (errnum) *errnum = NOT_DEF;
3305 return llvm::StringRef();
3306 }
3307 if ( field_iter->getNameAsString() == index1->getNameAsString() ) {
3308 break;
3309 }
3310 } // end of while (m_local.Next())
3311 } else {
3312 //NOTE: *** Need to print an error;
3313 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not int \n",
3314 // member.MemberOf()->Name(), member.Name(), current);
3315 if (errstr) *errstr = current;
3316 if (errnum) *errnum = NOT_INT;
3317 return llvm::StringRef();
3318 }
3319 } else {
3320 // There is no variable by this name in this class, let see
3321 // the base classes!:
3322 int found = 0;
3323 if (parent_clxx) {
3324 clang::Sema& SemaR = const_cast<cling::Interpreter&>(interp).getSema();
3326 }
3327 if ( index1 ) {
3328 if ( IsFieldDeclInt(index1) ) {
3329 found = 1;
3330 } else {
3331 // We found a data member but it is the wrong type
3332 //NOTE: *** Need to print an error;
3333 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not int \n",
3334 // member.MemberOf()->Name(), member.Name(), current);
3335 if (errnum) *errnum = NOT_INT;
3336 if (errstr) *errstr = current;
3337 //NOTE: *** Need to print an error;
3338 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not int \n",
3339 // member.MemberOf()->Name(), member.Name(), current);
3340 if (errnum) *errnum = NOT_INT;
3341 if (errstr) *errstr = current;
3342 return llvm::StringRef();
3343 }
3344 if ( found && (index1->getAccess() == clang::AS_private) ) {
3345 //NOTE: *** Need to print an error;
3346 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is a private member of %s \n",
3347 if (errstr) *errstr = current;
3348 if (errnum) *errnum = IS_PRIVATE;
3349 return llvm::StringRef();
3350 }
3351 }
3352 if (!found) {
3353 //NOTE: *** Need to print an error;
3354 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not known \n",
3355 // member.MemberOf()->Name(), member.Name(), indexvar);
3356 if (errstr) *errstr = indexvar;
3357 if (errnum) *errnum = UNKNOWN;
3358 return llvm::StringRef();
3359 } // end of if not found
3360 } // end of if is a data member of the class
3361 } // end of if isdigit
3362
3363 current = strtok(nullptr, tokenlist);
3364 } // end of while loop on tokens
3365
3366 return indexvar;
3367
3368}
3369
3370////////////////////////////////////////////////////////////////////////////////
3371/// Return (in the argument 'output') a valid name of the C++ symbol/type (pass as 'input')
3372/// that can be used in C++ as a variable name.
3373
3374void ROOT::TMetaUtils::GetCppName(std::string &out, const char *in)
3375{
3376 unsigned int i = 0;
3377 char c;
3378 out.clear();
3379 while((c = in[i++])) {
3380 const char *repl = nullptr;
3381 switch(c) {
3382 case '+': repl = "pL"; break;
3383 case '-': repl = "mI"; break;
3384 case '*': repl = "mU"; break;
3385 case '/': repl = "dI"; break;
3386 case '&': repl = "aN"; break;
3387 case '%': repl = "pE"; break;
3388 case '|': repl = "oR"; break;
3389 case '^': repl = "hA"; break;
3390 case '>': repl = "gR"; break;
3391 case '<': repl = "lE"; break;
3392 case '=': repl = "eQ"; break;
3393 case '~': repl = "wA"; break;
3394 case '.': repl = "dO"; break;
3395 case '(': repl = "oP"; break;
3396 case ')': repl = "cP"; break;
3397 case '[': repl = "oB"; break;
3398 case ']': repl = "cB"; break;
3399 case '{': repl = "lB"; break;
3400 case '}': repl = "rB"; break;
3401 case ';': repl = "sC"; break;
3402 case '#': repl = "hS"; break;
3403 case '?': repl = "qM"; break;
3404 case '`': repl = "bT"; break;
3405 case '!': repl = "nO"; break;
3406 case ',': repl = "cO"; break;
3407 case '$': repl = "dA"; break;
3408 case ' ': repl = "sP"; break;
3409 case ':': repl = "cL"; break;
3410 case '"': repl = "dQ"; break;
3411 case '@': repl = "aT"; break;
3412 case '\'': repl = "sQ"; break;
3413 case '\': repl = "fI"; break;
3414 }
3415 if (repl)
3416 out.append(repl);
3417 else
3418 out.push_back(c);
3419 }
3420
3421 // If out is empty, or if it starts with a number, it's not a valid C++ variable. Prepend a "_"
3422 if (out.empty() || isdigit(out[0]))
3423 out.insert(out.begin(), '_');
3424}
3425
3426static clang::SourceLocation
3428 clang::SourceLocation sourceLoc) {
3429 // Follow macro expansion until we hit a source file.
3430 if (!sourceLoc.isFileID()) {
3431 return sourceManager.getExpansionRange(sourceLoc).getEnd();
3432 }
3433 return sourceLoc;
3434}
3435
3436////////////////////////////////////////////////////////////////////////////////
3437/// Return the header file to be included to declare the Decl.
3438
3439std::string ROOT::TMetaUtils::GetFileName(const clang::Decl& decl,
3440 const cling::Interpreter& interp)
3441{
3442 // It looks like the template specialization decl actually contains _less_ information
3443 // on the location of the code than the decl (in case where there is forward declaration,
3444 // that is what the specialization points to).
3445 //
3446 // const clang::CXXRecordDecl* clxx = llvm::dyn_cast<clang::CXXRecordDecl>(decl);
3447 // if (clxx) {
3448 // switch(clxx->getTemplateSpecializationKind()) {
3449 // case clang::TSK_Undeclared:
3450 // // We want the default behavior
3451 // break;
3452 // case clang::TSK_ExplicitInstantiationDeclaration:
3453 // case clang::TSK_ExplicitInstantiationDefinition:
3454 // case clang::TSK_ImplicitInstantiation: {
3455 // // We want the location of the template declaration:
3456 // const clang::ClassTemplateSpecializationDecl *tmplt_specialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl> (clxx);
3457 // if (tmplt_specialization) {
3458 // // return GetFileName(const_cast< clang::ClassTemplateSpecializationDecl *>(tmplt_specialization)->getSpecializedTemplate());
3459 // }
3460 // break;
3461 // }
3462 // case clang::TSK_ExplicitSpecialization:
3463 // // We want the default behavior
3464 // break;
3465 // default:
3466 // break;
3467 // }
3468 // }
3469
3470 using namespace clang;
3471 SourceLocation headerLoc = decl.getLocation();
3472
3473 static const char invalidFilename[] = "";
3474 if (!headerLoc.isValid()) return invalidFilename;
3475
3476 HeaderSearch& HdrSearch = interp.getCI()->getPreprocessor().getHeaderSearchInfo();
3477
3478 SourceManager& sourceManager = decl.getASTContext().getSourceManager();
3483 sourceManager.getIncludeLoc(headerFID));
3484
3485 OptionalFileEntryRef headerFE = sourceManager.getFileEntryRefForID(headerFID);
3486 while (includeLoc.isValid() && sourceManager.isInSystemHeader(includeLoc)) {
3488 // use HeaderSearch on the basename, to make sure it takes a header from
3489 // the include path (e.g. not from /usr/include/bits/)
3490 assert(headerFE && "Couldn't find FileEntry from FID!");
3491 auto FEhdr
3492 = HdrSearch.LookupFile(llvm::sys::path::filename(headerFE->getName()),
3494 true /*isAngled*/, nullptr/*FromDir*/, foundDir,
3495 ArrayRef<std::pair<OptionalFileEntryRef, DirectoryEntryRef>>(),
3496 nullptr/*Searchpath*/, nullptr/*RelPath*/,
3497 nullptr/*SuggestedModule*/, nullptr/*RequestingModule*/,
3498 nullptr/*IsMapped*/, nullptr /*IsFrameworkFound*/,
3499 false /*SkipCache*/,
3500 false /*BuildSystemModule*/,
3501 false /*OpenFile*/, true /*CacheFailures*/);
3502 if (FEhdr) break;
3503 headerFID = sourceManager.getFileID(includeLoc);
3504 headerFE = sourceManager.getFileEntryRefForID(headerFID);
3505 // If we have a system header in a module we can't just trace back the
3506 // original include with the preprocessor. But it should be enough if
3507 // we trace it back to the top-level system header that includes this
3508 // declaration.
3509 if (interp.getCI()->getLangOpts().Modules && !headerFE) {
3510 assert(decl.isFirstDecl() && "Couldn't trace back include from a decl"
3511 " that is not from an AST file");
3512 assert(StringRef(includeLoc.printToString(sourceManager)).starts_with("<module-includes>"));
3513 break;
3514 }
3516 sourceManager.getIncludeLoc(headerFID));
3517 }
3518
3519 if (!headerFE) return invalidFilename;
3520
3521 llvm::SmallString<256> headerFileName(headerFE->getName());
3522 // Remove double ../ from the path so that the search below finds a valid
3523 // longest match and does not result in growing paths.
3524 llvm::sys::path::remove_dots(headerFileName, /*remove_dot_dot=*/true);
3525
3526 // Now headerFID references the last valid system header or the original
3527 // user file.
3528 // Find out how to include it by matching file name to include paths.
3529 // We assume that the file "/A/B/C/D.h" can at some level be included as
3530 // "C/D.h". Be we cannot know whether that happens to be a different file
3531 // with the same name. Thus we first find the longest stem that can be
3532 // reached, say B/C/D.h. Then we find the shortest one, say C/D.h, that
3533 // points to the same file as the long version. If such a short version
3534 // exists it will be returned. If it doesn't the long version is returned.
3535 bool isAbsolute = llvm::sys::path::is_absolute(headerFileName);
3536 clang::OptionalFileEntryRef FELong;
3537 // Find the longest available match.
3538 for (llvm::sys::path::const_iterator
3539 IDir = llvm::sys::path::begin(headerFileName),
3540 EDir = llvm::sys::path::end(headerFileName);
3541 !FELong && IDir != EDir; ++IDir) {
3542 if (isAbsolute) {
3543 // skip "/" part
3544 isAbsolute = false;
3545 continue;
3546 }
3547 size_t lenTrailing = headerFileName.size() - (IDir->data() - headerFileName.data());
3548 llvm::StringRef trailingPart(IDir->data(), lenTrailing);
3549 assert(trailingPart.data() + trailingPart.size()
3550 == headerFileName.data() + headerFileName.size()
3551 && "Mismatched partitioning of file name!");
3554 true /*isAngled*/, nullptr/*FromDir*/, FoundDir,
3555 ArrayRef<std::pair<OptionalFileEntryRef, DirectoryEntryRef>>(),
3556 nullptr/*Searchpath*/, nullptr/*RelPath*/,
3557 nullptr/*SuggestedModule*/, nullptr/*RequestingModule*/,
3558 nullptr/*IsMapped*/, nullptr /*IsFrameworkFound*/);
3559 }
3560
3561 if (!FELong) {
3562 // We did not find any file part in any search path.
3563 return invalidFilename;
3564 }
3565
3566 // Iterates through path *parts* "C"; we need trailing parts "C/D.h"
3567 for (llvm::sys::path::reverse_iterator
3568 IDir = llvm::sys::path::rbegin(headerFileName),
3569 EDir = llvm::sys::path::rend(headerFileName);
3570 IDir != EDir; ++IDir) {
3571 size_t lenTrailing = headerFileName.size() - (IDir->data() - headerFileName.data());
3572 llvm::StringRef trailingPart(IDir->data(), lenTrailing);
3573 assert(trailingPart.data() + trailingPart.size()
3574 == headerFileName.data() + headerFileName.size()
3575 && "Mismatched partitioning of file name!");
3577 // Can we find it, and is it the same file as the long version?
3578 // (or are we back to the previously found spelling, which is fine, too)
3579 if (HdrSearch.LookupFile(trailingPart, SourceLocation(),
3580 true /*isAngled*/, nullptr/*FromDir*/, FoundDir,
3581 ArrayRef<std::pair<OptionalFileEntryRef, DirectoryEntryRef>>(),
3582 nullptr/*Searchpath*/, nullptr/*RelPath*/,
3583 nullptr/*SuggestedModule*/, nullptr/*RequestingModule*/,
3584 nullptr/*IsMapped*/, nullptr /*IsFrameworkFound*/) == FELong) {
3585 return trailingPart.str();
3586 }
3587 }
3588
3589 return invalidFilename;
3590}
3591
3592////////////////////////////////////////////////////////////////////////////////
3593
3595 const clang::QualType &qtype,
3596 const clang::ASTContext &astContext)
3597{
3598 std::string fqname = cling::utils::TypeName::GetFullyQualifiedName(qtype, astContext);
3602}
3603
3604////////////////////////////////////////////////////////////////////////////////
3605
3607 const clang::QualType &qtype,
3608 const cling::Interpreter &interpreter)
3609{
3610 // We need this because GetFullyQualifiedTypeName is triggering deserialization
3611 // This calling the same name function GetFullyQualifiedTypeName, but this should stay here because
3612 // callee doesn't have an interpreter pointer
3613 cling::Interpreter::PushTransactionRAII RAII(const_cast<cling::Interpreter*>(&interpreter));
3614
3616 qtype,
3617 interpreter.getCI()->getASTContext());
3618}
3619
3620////////////////////////////////////////////////////////////////////////////////
3621/// Get the template specialisation decl and template decl behind the qualtype
3622/// Returns true if successfully found, false otherwise
3623
3624bool ROOT::TMetaUtils::QualType2Template(const clang::QualType& qt,
3625 clang::ClassTemplateDecl*& ctd,
3626 clang::ClassTemplateSpecializationDecl*& ctsd)
3627{
3628 using namespace clang;
3629 const Type* theType = qt.getTypePtr();
3630 if (!theType){
3631 ctd=nullptr;
3632 ctsd=nullptr;
3633 return false;
3634 }
3635
3636 if (theType->isPointerType()) {
3637 return QualType2Template(theType->getPointeeType(), ctd, ctsd);
3638 }
3639
3640 if (const RecordType* rType = llvm::dyn_cast<RecordType>(theType)) {
3641 ctsd = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(rType->getDecl());
3642 if (ctsd) {
3643 ctd = ctsd->getSpecializedTemplate();
3644 return true;
3645 }
3646 }
3647
3648 if (const SubstTemplateTypeParmType* sttpType = llvm::dyn_cast<SubstTemplateTypeParmType>(theType)){
3649 return QualType2Template(sttpType->getReplacementType(), ctd, ctsd);
3650 }
3651
3652
3653 ctsd = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(qt->getAsCXXRecordDecl());
3654 if(ctsd){
3655 ctd = ctsd->getSpecializedTemplate();
3656 return true;
3657 }
3658
3659 ctd=nullptr;
3660 ctsd=nullptr;
3661 return false;
3662}
3663
3664////////////////////////////////////////////////////////////////////////////////
3665/// Extract from a qualtype the class template if this makes sense.
3666/// Retuns the ClassTemplateDecl or nullptr otherwise.
3667
3668clang::ClassTemplateDecl* ROOT::TMetaUtils::QualType2ClassTemplateDecl(const clang::QualType& qt)
3669{
3670 using namespace clang;
3674 return ctd;
3675}
3676
3677////////////////////////////////////////////////////////////////////////////////
3678/// These manipulations are necessary because a template specialisation type
3679/// does not inherit from a record type (there is an asymmetry between
3680/// the decls and the types in the clang interface).
3681/// We may need therefore to step into the "Decl dimension" to then get back
3682/// to the "type dimension".
3683
3684clang::TemplateName ROOT::TMetaUtils::ExtractTemplateNameFromQualType(const clang::QualType& qt)
3685{
3686 using namespace clang;
3688
3689 const Type* theType = qt.getTypePtr();
3690
3691 if (const TemplateSpecializationType* tst = llvm::dyn_cast_or_null<const TemplateSpecializationType>(theType)) {
3692 theTemplateName = tst->getTemplateName();
3693 } // We step into the decl dimension
3696 }
3697
3698 return theTemplateName;
3699}
3700
3701////////////////////////////////////////////////////////////////////////////////
3702
3703static bool areEqualTypes(const clang::TemplateArgument& tArg,
3704 llvm::SmallVectorImpl<clang::TemplateArgument>& preceedingTArgs,
3705 const clang::NamedDecl& tPar,
3706 const cling::Interpreter& interp,
3708{
3709 using namespace ROOT::TMetaUtils;
3710 using namespace clang;
3711
3712 // Check if this is a type for security
3713 TemplateTypeParmDecl* ttpdPtr = const_cast<TemplateTypeParmDecl*>(llvm::dyn_cast<TemplateTypeParmDecl>(&tPar));
3714 if (!ttpdPtr) return false;
3715 if (!ttpdPtr->hasDefaultArgument()) return false; // we should not be here in this case, but we protect us.
3716
3717 // Try the fast solution
3718 QualType tParQualType = ttpdPtr->getDefaultArgument();
3719 const QualType tArgQualType = tArg.getAsType();
3720
3721 // Now the equality tests for non template specialisations.
3722
3723 // The easy cases:
3724 // template <class T=double> class A; or
3725 // template <class T=A<float>> class B;
3726 if (tParQualType.getTypePtr() == tArgQualType.getTypePtr()) return true;
3727
3728 // Here the difficulty comes. We have to check if the argument is equal to its
3729 // default. We can do that bootstrapping an argument which has the default value
3730 // based on the preceeding arguments.
3731 // Basically we ask sema to give us the value of the argument given the template
3732 // of behind the parameter and the all the arguments.
3733 // So:
3734
3735 // Take the template out of the parameter
3736
3737 const clang::ElaboratedType* etype
3738 = llvm::dyn_cast<clang::ElaboratedType>(tParQualType.getTypePtr());
3739 while (etype) {
3740 tParQualType = clang::QualType(etype->getNamedType().getTypePtr(),0);
3741 etype = llvm::dyn_cast<clang::ElaboratedType>(tParQualType.getTypePtr());
3742 }
3743
3745 llvm::dyn_cast<TemplateSpecializationType>(tParQualType.getTypePtr());
3746
3747 if(!tst) // nothing more to be tried. They are different indeed.
3748 return false;
3749
3751 = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(tArgQualType->getAsCXXRecordDecl());
3752
3753 if(!TSTdecl) // nothing more to be tried. They are different indeed.
3754 return false;
3755
3756 TemplateDecl *Template = tst->getTemplateName().getAsTemplateDecl();
3757
3758 // Take the template location
3759 SourceLocation TemplateLoc = Template->getSourceRange ().getBegin();
3760
3761 // Get the position of the "<" (LA) of the specializaion
3762 SourceLocation LAngleLoc = TSTdecl->getSourceRange().getBegin();
3763
3764
3765 // Enclose in a scope for the RAII
3766 bool isEqual=false;
3768 {
3769 clang::Sema& S = interp.getCI()->getSema();
3770 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interp));
3771 llvm::SmallVector<clang::TemplateArgument, 4> canonArgs;
3772 bool HasDefaultArgs;
3773 TemplateArgumentLoc defTArgLoc = S.SubstDefaultTemplateArgumentIfAvailable(Template,
3775 LAngleLoc,
3776 ttpdPtr,
3778 canonArgs,
3780 // The substition can fail, in which case there would have been compilation
3781 // error printed on the screen.
3782 newArg = defTArgLoc.getArgument();
3783 if (newArg.isNull() ||
3784 newArg.getKind() != clang::TemplateArgument::Type) {
3785 ROOT::TMetaUtils::Error("areEqualTypes",
3786 "Template parameter substitution failed!");
3787 }
3788
3790 = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(newArg.getAsType()->getAsCXXRecordDecl());
3791// std::cout << "nSTdecl is " << nTSTdecl << std::endl;
3792
3793 isEqual = (nTSTdecl && nTSTdecl->getMostRecentDecl() == TSTdecl->getMostRecentDecl()) ||
3794 (tParQualType.getTypePtr() == newArg.getAsType().getTypePtr());
3795 }
3796
3797
3798 return isEqual;
3799}
3800
3801
3802////////////////////////////////////////////////////////////////////////////////
3803/// std::cout << "Are equal values?\n";
3804
3805static bool areEqualValues(const clang::TemplateArgument& tArg,
3806 const clang::NamedDecl& tPar)
3807{
3808 using namespace clang;
3809 const NonTypeTemplateParmDecl* nttpdPtr = llvm::dyn_cast<NonTypeTemplateParmDecl>(&tPar);
3810 if (!nttpdPtr) return false;
3812
3813 if (!nttpd.hasDefaultArgument())
3814 return false;
3815
3816 // 64 bits wide and signed (non unsigned, that is why "false")
3817 llvm::APSInt defaultValueAPSInt(64, false);
3818 if (Expr* defArgExpr = nttpd.getDefaultArgument()) {
3819 const ASTContext& astCtxt = nttpdPtr->getASTContext();
3820 if (auto Value = defArgExpr->getIntegerConstantExpr(astCtxt))
3822 }
3823
3824 const int value = tArg.getAsIntegral().getLimitedValue();
3825
3826 // std::cout << (value == defaultValueAPSInt ? "yes!":"no") << std::endl;
3827 return value == defaultValueAPSInt;
3828}
3829
3830////////////////////////////////////////////////////////////////////////////////
3831/// Check if this NamedDecl is a template parameter with a default argument.
3832/// This is a single interface to treat both integral and type parameters.
3833/// Returns true if this is the case, false otherwise
3834
3835static bool isTypeWithDefault(const clang::NamedDecl* nDecl)
3836{
3837 using namespace clang;
3838 if (!nDecl) return false;
3839 if (const TemplateTypeParmDecl* ttpd = llvm::dyn_cast<TemplateTypeParmDecl>(nDecl))
3840 return ttpd->hasDefaultArgument();
3841 if (const NonTypeTemplateParmDecl* nttpd = llvm::dyn_cast<NonTypeTemplateParmDecl>(nDecl))
3842 return nttpd->hasDefaultArgument();
3843 return false;
3844
3845}
3846
3847static void KeepNParams(clang::QualType& normalizedType,
3848 const clang::QualType& vanillaType,
3849 const cling::Interpreter& interp,
3851
3852// Returns true if normTArg might have changed.
3853static bool RecurseKeepNParams(clang::TemplateArgument &normTArg,
3854 const clang::TemplateArgument &tArg,
3855 const cling::Interpreter& interp,
3857 const clang::ASTContext& astCtxt)
3858{
3859 using namespace ROOT::TMetaUtils;
3860 using namespace clang;
3861
3862 // Once we know there is no more default parameter, we can run through to the end
3863 // and/or recurse in the template parameter packs.
3864
3865 // If this is a type,
3866 // we need first of all to recurse: this argument may need to be manipulated
3867 if (tArg.getKind() == clang::TemplateArgument::Type) {
3868 QualType thisNormQualType = normTArg.getAsType();
3869 QualType thisArgQualType = tArg.getAsType();
3872 interp,
3873 normCtxt);
3876 } else if (normTArg.getKind() == clang::TemplateArgument::Pack) {
3877 assert( tArg.getKind() == clang::TemplateArgument::Pack );
3878
3880 bool mightHaveChanged = true;
3881 for (auto I = normTArg.pack_begin(), E = normTArg.pack_end(),
3882 FI = tArg.pack_begin(), FE = tArg.pack_end();
3883 I != E && FI != FE; ++I, ++FI)
3884 {
3887 desArgs.push_back(pack_arg);
3888 }
3889 if (mightHaveChanged) {
3890 ASTContext &mutableCtx( const_cast<ASTContext&>(astCtxt) );
3891 normTArg = TemplateArgument::CreatePackCopy(mutableCtx, desArgs);
3892 }
3893 return mightHaveChanged;
3894 }
3895 return false;
3896}
3897
3898
3899////////////////////////////////////////////////////////////////////////////////
3900/// This function allows to manipulate the number of arguments in the type
3901/// of a template specialisation.
3902
3903static void KeepNParams(clang::QualType& normalizedType,
3904 const clang::QualType& vanillaType,
3905 const cling::Interpreter& interp,
3907{
3908 using namespace ROOT::TMetaUtils;
3909 using namespace clang;
3910
3911 // If this type has no template specialisation behind, we don't need to do
3912 // anything
3915 if (! QualType2Template(vanillaType, ctd, ctsd)) return ;
3916
3917 // Even if this is a template, if we don't keep any argument, return
3918 const int nArgsToKeep = normCtxt.GetNargsToKeep(ctd);
3919
3920 // Important in case of early return: we must restore the original qualtype
3922
3923 const ASTContext& astCtxt = ctsd->getASTContext();
3924
3925
3926 // In case of name* we need to strip the pointer first, add the default and attach
3927 // the pointer once again.
3928 if (llvm::isa<clang::PointerType>(normalizedType.getTypePtr())) {
3929 // Get the qualifiers.
3930 clang::Qualifiers quals = normalizedType.getQualifiers();
3931 auto valNormalizedType = normalizedType->getPointeeType();
3933 normalizedType = astCtxt.getPointerType(valNormalizedType);
3934 // Add back the qualifiers.
3935 normalizedType = astCtxt.getQualifiedType(normalizedType, quals);
3936 return;
3937 }
3938
3939 // In case of Int_t& we need to strip the pointer first, desugar and attach
3940 // the pointer once again.
3941 if (llvm::isa<clang::ReferenceType>(normalizedType.getTypePtr())) {
3942 // Get the qualifiers.
3943 bool isLValueRefTy = llvm::isa<clang::LValueReferenceType>(normalizedType.getTypePtr());
3944 clang::Qualifiers quals = normalizedType.getQualifiers();
3945 auto valNormType = normalizedType->getPointeeType();
3947
3948 // Add the r- or l- value reference type back to the desugared one
3949 if (isLValueRefTy)
3950 normalizedType = astCtxt.getLValueReferenceType(valNormType);
3951 else
3952 normalizedType = astCtxt.getRValueReferenceType(valNormType);
3953 // Add back the qualifiers.
3954 normalizedType = astCtxt.getQualifiedType(normalizedType, quals);
3955 return;
3956 }
3957
3958 // Treat the Scope (factorise the code out to reuse it in AddDefaultParameters)
3959 bool prefix_changed = false;
3960 clang::NestedNameSpecifier* prefix = nullptr;
3961 clang::Qualifiers prefix_qualifiers = normalizedType.getLocalQualifiers();
3962 const clang::ElaboratedType* etype
3963 = llvm::dyn_cast<clang::ElaboratedType>(normalizedType.getTypePtr());
3964 if (etype) {
3965 // We have to also handle the prefix.
3966 // TODO: we ought to be running KeepNParams
3967 prefix = AddDefaultParametersNNS(astCtxt, etype->getQualifier(), interp, normCtxt);
3968 prefix_changed = prefix != etype->getQualifier();
3969 normalizedType = clang::QualType(etype->getNamedType().getTypePtr(),0);
3970 }
3971
3972 // The canonical decl does not necessarily have the template default arguments.
3973 // Need to walk through the redecl chain to find it (we know there will be no
3974 // inconsistencies, at least)
3975 const clang::ClassTemplateDecl* ctdWithDefaultArgs = ctd;
3976 for (const RedeclarableTemplateDecl* rd: ctdWithDefaultArgs->redecls()) {
3977 clang::TemplateParameterList* tpl = rd->getTemplateParameters();
3978 if (tpl->getMinRequiredArguments () < tpl->size()) {
3979 ctdWithDefaultArgs = llvm::dyn_cast<clang::ClassTemplateDecl>(rd);
3980 break;
3981 }
3982 }
3983
3984 if (!ctdWithDefaultArgs) {
3985 Error("KeepNParams", "Not found template default arguments\n");
3987 return;
3988 }
3989
3990 TemplateParameterList* tParsPtr = ctdWithDefaultArgs->getTemplateParameters();
3992 const TemplateArgumentList& tArgs = ctsd->getTemplateArgs();
3993
3994 // We extract the template name from the type
3995 TemplateName theTemplateName = ExtractTemplateNameFromQualType(normalizedType);
3996 if (theTemplateName.isNull()) {
3998 return;
3999 }
4000
4002 llvm::dyn_cast<TemplateSpecializationType>(normalizedType.getTypePtr());
4003 if (!normalizedTst) {
4005 return;
4006 }
4007
4008 const clang::ClassTemplateSpecializationDecl* TSTdecl
4009 = llvm::dyn_cast_or_null<const clang::ClassTemplateSpecializationDecl>(normalizedType.getTypePtr()->getAsCXXRecordDecl());
4010 bool isStdDropDefault = TSTdecl && IsStdDropDefaultClass(*TSTdecl);
4011
4012 // Loop over the template parameters and arguments recursively.
4013 // We go down the two lanes: the one of template parameters (decls) and the
4014 // one of template arguments (QualTypes) in parallel. The former are a
4015 // property of the template, independent of its instantiations.
4016 // The latter are a property of the instance itself.
4017 llvm::SmallVector<TemplateArgument, 4> argsToKeep;
4018
4019 const int nArgs = tArgs.size();
4020 const auto &normArgs = normalizedTst->template_arguments();
4021 const int nNormArgs = normArgs.size();
4022
4023 bool mightHaveChanged = false;
4024
4025 // becomes true when a parameter has a value equal to its default
4026 for (int formal = 0, inst = 0; formal != nArgs; ++formal, ++inst) {
4027 const NamedDecl* tParPtr = tPars.getParam(formal);
4028 if (!tParPtr) {
4029 Error("KeepNParams", "The parameter number %s is null.\n", formal);
4030 continue;
4031 }
4032
4033 // Stop if the normalized TemplateSpecializationType has less arguments than
4034 // the one index is pointing at.
4035 // We piggy back on the AddDefaultParameters routine basically.
4036 if (formal == nNormArgs || inst == nNormArgs) break;
4037
4038 const TemplateArgument& tArg = tArgs.get(formal);
4040
4041 bool shouldKeepArg = nArgsToKeep < 0 || inst < nArgsToKeep;
4042 if (isStdDropDefault) shouldKeepArg = false;
4043
4044 // Nothing to do here: either this parameter has no default, or we have to keep it.
4045 // FIXME: Temporary measure to get Atlas started with this.
4046 // We put a hard cut on the number of template arguments to keep, w/o checking if
4047 // they are non default. This makes this feature UNUSABLE for cases like std::vector,
4048 // where 2 different entities would have the same name if an allocator different from
4049 // the default one is by chance used.
4051 if ( tParPtr->isTemplateParameterPack() ) {
4052 // This is the last template parameter in the template declaration
4053 // but it is signaling that there can be an arbitrary number of arguments
4054 // in the template instance. So to avoid inadvertenly dropping those
4055 // arguments we just process all remaining argument and exit the main loop.
4056 for( ; inst != nNormArgs; ++inst) {
4059 argsToKeep.push_back(normTArg);
4060 }
4061 // Done.
4062 break;
4063 }
4065 argsToKeep.push_back(normTArg);
4066 continue;
4067 } else {
4068 if (!isStdDropDefault) {
4069 // Here we should not break but rather check if the value is the default one.
4070 mightHaveChanged = true;
4071 break;
4072 }
4073 // For std, we want to check the default args values.
4074 }
4075
4076 // Now, we keep it only if it not is equal to its default, expressed in the arg
4077 // Some gymnastic is needed to decide how to check for equality according to the
4078 // flavour of Type: templateType or Integer
4079 bool equal=false;
4080 auto argKind = tArg.getKind();
4081 if (argKind == clang::TemplateArgument::Type){
4082 // we need all the info
4084 } else if (argKind == clang::TemplateArgument::Integral){
4085 equal = areEqualValues(tArg, *tParPtr);
4086 }
4087 if (!equal) {
4089 argsToKeep.push_back(normTArg);
4090 } else {
4091 mightHaveChanged = true;
4092 }
4093
4094
4095 } // of loop over parameters and arguments
4096
4099 return;
4100 }
4101
4102 // now, let's remanipulate our Qualtype
4103 if (mightHaveChanged) {
4104 Qualifiers qualifiers = normalizedType.getLocalQualifiers();
4105 normalizedType = astCtxt.getTemplateSpecializationType(theTemplateName,
4106 argsToKeep,
4107 normalizedType.getTypePtr()->getCanonicalTypeInternal());
4108 normalizedType = astCtxt.getQualifiedType(normalizedType, qualifiers);
4109 }
4110
4111 // Here we have (prefix_changed==true || mightHaveChanged), in both case
4112 // we need to reconstruct the type.
4113 if (prefix) {
4114 normalizedType = astCtxt.getElaboratedType(clang::ElaboratedTypeKeyword::None, prefix, normalizedType);
4116 }
4117
4118}
4119
4120////////////////////////////////////////////////////////////////////////////////
4121/// Return the type normalized for ROOT,
4122/// keeping only the ROOT opaque typedef (Double32_t, etc.) and
4123/// adding default template argument for all types except those explicitly
4124/// requested to be drop by the user.
4125/// Default template for STL collections are not yet removed by this routine.
4126
4127clang::QualType ROOT::TMetaUtils::GetNormalizedType(const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
4128{
4129 clang::ASTContext &ctxt = interpreter.getCI()->getASTContext();
4130
4131 // Modules can trigger deserialization.
4132 cling::Interpreter::PushTransactionRAII RAII(const_cast<cling::Interpreter*>(&interpreter));
4133 clang::QualType normalizedType = cling::utils::Transform::GetPartiallyDesugaredType(ctxt, type, normCtxt.GetConfig(), true /* fully qualify */);
4134
4135 // Readd missing default template parameters
4137
4138 // Get the number of arguments to keep in case they are not default.
4140
4141 return normalizedType;
4142}
4143
4144////////////////////////////////////////////////////////////////////////////////
4145/// Return the type name normalized for ROOT,
4146/// keeping only the ROOT opaque typedef (Double32_t, etc.) and
4147/// adding default template argument for all types except the STL collections
4148/// where we remove the default template argument if any.
4149///
4150/// This routine might actually belong in the interpreter because
4151/// cache the clang::Type might be intepreter specific.
4152
4153void ROOT::TMetaUtils::GetNormalizedName(std::string &norm_name, const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
4154{
4155 if (type.isNull()) {
4156 norm_name = "";
4157 return;
4158 }
4159
4161
4162 clang::ASTContext &ctxt = interpreter.getCI()->getASTContext();
4163 clang::PrintingPolicy policy(ctxt.getPrintingPolicy());
4164 policy.SuppressTagKeyword = true; // Never get the class or struct keyword
4165 policy.SuppressScope = true; // Force the scope to be coming from a clang::ElaboratedType.
4166 policy.AnonymousTagLocations = false; // Do not extract file name + line number for anonymous types.
4167 // The scope suppression is required for getting rid of the anonymous part of the name of a class defined in an anonymous namespace.
4168 // This gives us more control vs not using the clang::ElaboratedType and relying on the Policy.SuppressUnwrittenScope which would
4169 // strip both the anonymous and the inline namespace names (and we probably do not want the later to be suppressed).
4170
4171 std::string normalizedNameStep1;
4172
4173 // getAsStringInternal can trigger deserialization
4174 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interpreter));
4175 normalizedType.getAsStringInternal(normalizedNameStep1,policy);
4176
4177 // Still remove the std:: and default template argument for STL container and
4178 // normalize the location and amount of white spaces.
4181
4182 // The result of this routine is by definition a fully qualified name. There is an implicit starting '::' at the beginning of the name.
4183 // Depending on how the user typed their code, in particular typedef declarations, we may end up with an explicit '::' being
4184 // part of the result string. For consistency, we must remove it.
4185 if (norm_name.length()>2 && norm_name[0]==':' && norm_name[1]==':') {
4186 norm_name.erase(0,2);
4187 }
4188
4189}
4190
4191////////////////////////////////////////////////////////////////////////////////
4192
4194 const clang::TypeDecl* typeDecl,
4195 const cling::Interpreter &interpreter)
4196{
4198 const clang::Sema &sema = interpreter.getSema();
4199 clang::ASTContext& astCtxt = sema.getASTContext();
4200 clang::QualType qualType = astCtxt.getTypeDeclType(typeDecl);
4201
4203 qualType,
4205 tNormCtxt);
4206}
4207
4208////////////////////////////////////////////////////////////////////////////////
4209std::pair<std::string,clang::QualType>
4211 const cling::Interpreter &interpreter,
4214{
4215 std::string thisTypeName;
4216 GetNormalizedName(thisTypeName, thisType, interpreter, normCtxt );
4217 bool hasChanged;
4219 if (!hasChanged) return std::make_pair(thisTypeName,thisType);
4220
4222 ROOT::TMetaUtils::Info("ROOT::TMetaUtils::GetTypeForIO",
4223 "Name changed from %s to %s\n", thisTypeName.c_str(), thisTypeNameForIO.c_str());
4224 }
4225
4226 auto& lookupHelper = interpreter.getLookupHelper();
4227
4228 const clang::Type* typePtrForIO;
4230 cling::LookupHelper::DiagSetting::NoDiagnostics,
4231 &typePtrForIO);
4232
4233 // This should never happen
4234 if (!typePtrForIO) {
4235 ROOT::TMetaUtils::Fatal("ROOT::TMetaUtils::GetTypeForIO",
4236 "Type not found: %s.",thisTypeNameForIO.c_str());
4237 }
4238
4239 clang::QualType typeForIO(typePtrForIO,0);
4240
4241 // Check if this is a class. Indeed it could well be a POD
4242 if (!typeForIO->isRecordType()) {
4243 return std::make_pair(thisTypeNameForIO,typeForIO);
4244 }
4245
4246 auto thisDeclForIO = typeForIO->getAsCXXRecordDecl();
4247 if (!thisDeclForIO) {
4248 ROOT::TMetaUtils::Error("ROOT::TMetaUtils::GetTypeForIO",
4249 "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());
4250 return std::make_pair(thisTypeName,thisType);
4251 }
4252
4253 return std::make_pair(thisTypeNameForIO,typeForIO);
4254}
4255
4256////////////////////////////////////////////////////////////////////////////////
4257
4258clang::QualType ROOT::TMetaUtils::GetTypeForIO(const clang::QualType& thisType,
4259 const cling::Interpreter &interpreter,
4262{
4264}
4265
4266////////////////////////////////////////////////////////////////////////////////
4267/// Return the dictionary file name for a module
4268
4270{
4271 std::string dictFileName(moduleName);
4272 dictFileName += "_rdict.pcm";
4273 return dictFileName;
4274}
4275
4276int dumpDeclForAssert(const clang::Decl& D, const char* commentStart) {
4277 llvm::errs() << llvm::StringRef(commentStart, 80) << '\n';
4278 D.dump();
4279 return 0;
4280}
4281
4282////////////////////////////////////////////////////////////////////////////////
4283/// Returns the comment (// striped away), annotating declaration in a meaningful
4284/// for ROOT IO way.
4285/// Takes optional out parameter clang::SourceLocation returning the source
4286/// location of the comment.
4287///
4288/// CXXMethodDecls, FieldDecls and TagDecls are annotated.
4289/// CXXMethodDecls declarations and FieldDecls are annotated as follows:
4290/// Eg. void f(); // comment1
4291/// int member; // comment2
4292/// Inline definitions of CXXMethodDecls after the closing } \n. Eg:
4293/// void f()
4294/// {...} // comment3
4295/// TagDecls are annotated in the end of the ClassDef macro. Eg.
4296/// class MyClass {
4297/// ...
4298/// ClassDef(MyClass, 1) // comment4
4299///
4300
4301llvm::StringRef ROOT::TMetaUtils::GetComment(const clang::Decl &decl, clang::SourceLocation *loc)
4302{
4303 clang::SourceManager& sourceManager = decl.getASTContext().getSourceManager();
4304 clang::SourceLocation sourceLocation = decl.getEndLoc();
4305
4306 // If the location is a macro get the expansion location.
4307 sourceLocation = sourceManager.getExpansionRange(sourceLocation).getEnd();
4308 // FIXME: We should optimize this routine instead making it do the wrong thing
4309 // returning an empty comment if the decl came from the AST.
4310 // In order to do that we need to: check if the decl has an attribute and
4311 // return the attribute content (including walking the redecl chain) and if
4312 // this is not the case we should try finding it in the header file.
4313 // This will allow us to move the implementation of TCling*Info::Title() in
4314 // TClingDeclInfo.
4315 if (!decl.hasOwningModule() && sourceManager.isLoadedSourceLocation(sourceLocation)) {
4316 // Do not touch disk for nodes coming from the PCH.
4317 return "";
4318 }
4319
4320 bool invalid;
4321 const char *commentStart = sourceManager.getCharacterData(sourceLocation, &invalid);
4322 if (invalid)
4323 return "";
4324
4325 bool skipToSemi = true;
4326 if (const clang::FunctionDecl* FD = clang::dyn_cast<clang::FunctionDecl>(&decl)) {
4327 if (FD->isImplicit()) {
4328 // Compiler generated function.
4329 return "";
4330 }
4331 if (FD->isExplicitlyDefaulted() || FD->isDeletedAsWritten()) {
4332 // ctorOrFunc() = xyz; with commentStart pointing somewhere into
4333 // ctorOrFunc.
4334 // We have to skipToSemi
4335 } else if (FD->doesThisDeclarationHaveABody()) {
4336 // commentStart is at body's '}'
4337 // But we might end up e.g. at the ')' of a CPP macro
4338 assert((decl.getEndLoc() != sourceLocation || *commentStart == '}'
4340 && "Expected macro or end of body at '}'");
4341 if (*commentStart) ++commentStart;
4342
4343 // We might still have a ';'; skip the spaces and check.
4344 while (*commentStart && isspace(*commentStart)
4345 && *commentStart != '\n' && *commentStart != '\r') {
4346 ++commentStart;
4347 }
4348 if (*commentStart == ';') ++commentStart;
4349
4350 skipToSemi = false;
4351 }
4352 } else if (const clang::EnumConstantDecl* ECD
4353 = clang::dyn_cast<clang::EnumConstantDecl>(&decl)) {
4354 // either "konstant = 12, //COMMENT" or "lastkonstant // COMMENT"
4355 if (ECD->getNextDeclInContext())
4356 while (*commentStart && *commentStart != ',' && *commentStart != '\r' && *commentStart != '\n')
4357 ++commentStart;
4358 // else commentStart already points to the end.
4359
4360 skipToSemi = false;
4361 }
4362
4363 if (skipToSemi) {
4364 while (*commentStart && *commentStart != ';' && *commentStart != '\r' && *commentStart != '\n')
4365 ++commentStart;
4366 if (*commentStart == ';') ++commentStart;
4367 }
4368
4369 // Now skip the spaces until beginning of comments or EOL.
4370 while ( *commentStart && isspace(*commentStart)
4371 && *commentStart != '\n' && *commentStart != '\r') {
4372 ++commentStart;
4373 }
4374
4375 if (commentStart[0] != '/' ||
4376 (commentStart[1] != '/' && commentStart[1] != '*')) {
4377 // not a comment
4378 return "";
4379 }
4380
4381 // Treat by default c++ comments (+2) but also Doxygen comments (+4)
4382 // Int_t fPx; ///< Some doxygen comment for persistent data.
4383 // Int_t fPy; //!< Some doxygen comment for persistent data.
4384 // Int_t fPz; /*!< Some doxygen comment for persistent data. */
4385 // Int_t fPa; /**< Some doxygen comment for persistent data. */
4386 unsigned int skipChars = 2;
4387 if (commentStart[0] == '/' &&
4388 commentStart[1] == '/' &&
4389 (commentStart[2] == '/' || commentStart[2] == '!') &&
4390 commentStart[3] == '<') {
4391 skipChars = 4;
4392 } else if (commentStart[0] == '/' &&
4393 commentStart[1] == '*' &&
4394 (commentStart[2] == '*' || commentStart[2] == '!') &&
4395 commentStart[3] == '<') {
4396 skipChars = 4;
4397 }
4398
4400
4401 // Now skip the spaces after comment start until EOL.
4402 while ( *commentStart && isspace(*commentStart)
4403 && *commentStart != '\n' && *commentStart != '\r') {
4404 ++commentStart;
4405 }
4406 const char* commentEnd = commentStart;
4407 // Even for /* comments we only take the first line into account.
4408 while (*commentEnd && *commentEnd != '\n' && *commentEnd != '\r') {
4409 ++commentEnd;
4410 }
4411
4412 // "Skip" (don't include) trailing space.
4413 // *commentEnd points behind comment end thus check commentEnd[-1]
4414 while (commentEnd > commentStart && isspace(commentEnd[-1])) {
4415 --commentEnd;
4416 }
4417
4418 if (loc) {
4419 // Find the true beginning of a comment.
4420 unsigned offset = commentStart - sourceManager.getCharacterData(sourceLocation);
4421 *loc = sourceLocation.getLocWithOffset(offset - 1);
4422 }
4423
4424 return llvm::StringRef(commentStart, commentEnd - commentStart);
4425}
4426
4427////////////////////////////////////////////////////////////////////////////////
4428/// Return true if class has any of class declarations like ClassDef, ClassDefNV, ClassDefOverride
4429
4430bool ROOT::TMetaUtils::HasClassDefMacro(const clang::Decl *decl, const cling::Interpreter &interpreter)
4431{
4432 if (!decl) return false;
4433
4434 auto& sema = interpreter.getCI()->getSema();
4435 auto maybeMacroLoc = decl->getLocation();
4436
4437 if (!maybeMacroLoc.isMacroID()) return false;
4438
4439 static const std::vector<std::string> signatures =
4440 { "ClassDef", "ClassDefOverride", "ClassDefNV", "ClassDefInline", "ClassDefInlineOverride", "ClassDefInlineNV" };
4441
4442 for (auto &name : signatures)
4443 if (sema.findMacroSpelling(maybeMacroLoc, name))
4444 return true;
4445
4446 return false;
4447}
4448
4449////////////////////////////////////////////////////////////////////////////////
4450/// Return the class comment after the ClassDef:
4451/// class MyClass {
4452/// ...
4453/// ClassDef(MyClass, 1) // class comment
4454///
4455
4456llvm::StringRef ROOT::TMetaUtils::GetClassComment(const clang::CXXRecordDecl &decl,
4457 clang::SourceLocation *loc,
4458 const cling::Interpreter &interpreter)
4459{
4460 using namespace clang;
4461
4462 const Decl* DeclFileLineDecl
4463 = interpreter.getLookupHelper().findFunctionProto(&decl, "DeclFileLine", "",
4464 cling::LookupHelper::NoDiagnostics);
4465
4466 // For now we allow only a special macro (ClassDef) to have meaningful comments
4469 llvm::StringRef comment = ROOT::TMetaUtils::GetComment(*DeclFileLineDecl, &commentSLoc);
4470 if (comment.size()) {
4471 if (loc) {
4472 *loc = commentSLoc;
4473 }
4474 return comment;
4475 }
4476 }
4477 return llvm::StringRef();
4478}
4479
4480////////////////////////////////////////////////////////////////////////////////
4481/// Return the base/underlying type of a chain of array or pointers type.
4482/// Does not yet support the array and pointer part being intermixed.
4483
4484const clang::Type *ROOT::TMetaUtils::GetUnderlyingType(clang::QualType type)
4485{
4486 const clang::Type *rawtype = type.getTypePtr();
4487
4488 // NOTE: We probably meant isa<clang::ElaboratedType>
4489 if (rawtype->isElaboratedTypeSpecifier() ) {
4490 rawtype = rawtype->getCanonicalTypeInternal().getTypePtr();
4491 }
4492 if (rawtype->isArrayType()) {
4493 rawtype = type.getTypePtr()->getBaseElementTypeUnsafe ();
4494 }
4495 if (rawtype->isPointerType() || rawtype->isReferenceType() ) {
4496 //Get to the 'raw' type.
4497 clang::QualType pointee;
4498 while ( (pointee = rawtype->getPointeeType()) , pointee.getTypePtrOrNull() && pointee.getTypePtr() != rawtype)
4499 {
4500 rawtype = pointee.getTypePtr();
4501
4502 if (rawtype->isElaboratedTypeSpecifier() ) {
4503 rawtype = rawtype->getCanonicalTypeInternal().getTypePtr();
4504 }
4505 if (rawtype->isArrayType()) {
4506 rawtype = rawtype->getBaseElementTypeUnsafe ();
4507 }
4508 }
4509 }
4510 if (rawtype->isArrayType()) {
4511 rawtype = rawtype->getBaseElementTypeUnsafe ();
4512 }
4513 return rawtype;
4514}
4515
4516////////////////////////////////////////////////////////////////////////////////
4517/// Return true if the DeclContext is representing an entity reacheable from the
4518/// global namespace
4519
4520bool ROOT::TMetaUtils::IsCtxtReacheable(const clang::DeclContext &ctxt)
4521{
4522 if (ctxt.isNamespace() || ctxt.isTranslationUnit())
4523 return true;
4524 else if(const auto parentdecl = llvm::dyn_cast<clang::CXXRecordDecl>(&ctxt))
4526 else
4527 // For example "extern C" context.
4528 return true;
4529}
4530
4531////////////////////////////////////////////////////////////////////////////////
4532/// Return true if the decl is representing an entity reacheable from the
4533/// global namespace
4534
4536{
4537 const clang::DeclContext *ctxt = decl.getDeclContext();
4538 switch (decl.getAccess()) {
4539 case clang::AS_public:
4540 return !ctxt || IsCtxtReacheable(*ctxt);
4541 case clang::AS_protected:
4542 return false;
4543 case clang::AS_private:
4544 return false;
4545 case clang::AS_none:
4546 return !ctxt || IsCtxtReacheable(*ctxt);
4547 default:
4548 // IMPOSSIBLE
4549 assert(false && "Unexpected value for the access property value in Clang");
4550 return false;
4551 }
4552}
4553
4554////////////////////////////////////////////////////////////////////////////////
4555/// Return true, if the decl is part of the std namespace.
4556
4557bool ROOT::TMetaUtils::IsStdClass(const clang::RecordDecl &cl)
4558{
4559 return cling::utils::Analyze::IsStdClass(cl);
4560}
4561
4562////////////////////////////////////////////////////////////////////////////////
4563/// Return true, if the decl is part of the std namespace and we want
4564/// its default parameter dropped.
4565
4566bool ROOT::TMetaUtils::IsStdDropDefaultClass(const clang::RecordDecl &cl)
4567{
4568 // Might need to reduce it to shared_ptr and STL collection.s
4569 if (cling::utils::Analyze::IsStdClass(cl)) {
4570 static const char *names[] =
4571 { "shared_ptr", "__shared_ptr",
4572 "vector", "list", "deque", "map", "multimap", "set", "multiset", "bitset"};
4573 llvm::StringRef clname(cl.getName());
4574 for(auto &&name : names) {
4575 if (clname == name) return true;
4576 }
4577 }
4578 return false;
4579}
4580
4581////////////////////////////////////////////////////////////////////////////////
4582/// This is a recursive function
4583
4584bool ROOT::TMetaUtils::MatchWithDeclOrAnyOfPrevious(const clang::CXXRecordDecl &cl,
4585 const clang::CXXRecordDecl &currentCl)
4586{
4587 // We found it: let's return true
4588 if (&cl == &currentCl) return true;
4589
4590 const clang::CXXRecordDecl* previous = currentCl.getPreviousDecl();
4591
4592 // There is no previous decl, so we cannot possibly find it
4593 if (nullptr == previous){
4594 return false;
4595 }
4596
4597 // We try to find it in the previous
4599
4600}
4601
4602//______________________________________________________________________________
4603
4604bool ROOT::TMetaUtils::IsOfType(const clang::CXXRecordDecl &cl, const std::string& typ, const cling::LookupHelper& lh)
4605{
4606 // Return true if the decl is of type.
4607 // A proper hashtable for caching results would be the ideal solution
4608 // 1) Only one lookup per type
4609 // 2) No string comparison
4610 // We may use a map which becomes an unordered map if c++11 is enabled?
4611
4612 const clang::CXXRecordDecl *thisDecl =
4613 llvm::dyn_cast_or_null<clang::CXXRecordDecl>(lh.findScope(typ, cling::LookupHelper::WithDiagnostics));
4614
4615 // this would be probably an assert given that this state is not reachable unless a mistake is somewhere
4616 if (! thisDecl){
4617 Error("IsOfType","Record decl of type %s not found in the AST.", typ.c_str());
4618 return false;
4619 }
4620
4621 // Now loop on all previous decls to seek a match
4622 const clang::CXXRecordDecl *mostRecentDecl = thisDecl->getMostRecentDecl();
4624
4625 return matchFound;
4626}
4627
4628////////////////////////////////////////////////////////////////////////////////
4629/// type : type name: vector<list<classA,allocator>,allocator>
4630/// result: 0 : not stl container
4631/// abs(result): code of container 1=vector,2=list,3=deque,4=map
4632/// 5=multimap,6=set,7=multiset
4633
4635{
4636 // This routine could be enhanced to also support:
4637 //
4638 // testAlloc: if true, we test allocator, if it is not default result is negative
4639 // result: 0 : not stl container
4640 // abs(result): code of container 1=vector,2=list,3=deque,4=map
4641 // 5=multimap,6=set,7=multiset
4642 // positive val: we have a vector or list with default allocator to any depth
4643 // like vector<list<vector<int>>>
4644 // negative val: STL container other than vector or list, or non default allocator
4645 // For example: vector<deque<int>> has answer -1
4646
4647 if (!IsStdClass(cl)) {
4648 auto *nsDecl = llvm::dyn_cast<clang::NamespaceDecl>(cl.getDeclContext());
4649 if (cl.getName() != "RVec" || nsDecl == nullptr || nsDecl->getName() != "VecOps")
4650 return ROOT::kNotSTL;
4651
4652 auto *parentNsDecl = llvm::dyn_cast<clang::NamespaceDecl>(cl.getDeclContext()->getParent());
4653 if (parentNsDecl == nullptr || parentNsDecl->getName() != "ROOT")
4654 return ROOT::kNotSTL;
4655 }
4656
4657 return STLKind(cl.getName());
4658}
4659
4660static bool hasSomeTypedefSomewhere(const clang::Type* T) {
4661 using namespace clang;
4662 struct SearchTypedef: public TypeVisitor<SearchTypedef, bool> {
4663 bool VisitTypedefType(const TypedefType* TD) {
4664 return true;
4665 }
4666 bool VisitArrayType(const ArrayType* AT) {
4667 return Visit(AT->getElementType().getTypePtr());
4668 }
4669 bool VisitDecltypeType(const DecltypeType* DT) {
4670 return Visit(DT->getUnderlyingType().getTypePtr());
4671 }
4672 bool VisitPointerType(const PointerType* PT) {
4673 return Visit(PT->getPointeeType().getTypePtr());
4674 }
4675 bool VisitReferenceType(const ReferenceType* RT) {
4676 return Visit(RT->getPointeeType().getTypePtr());
4677 }
4679 return Visit(STST->getReplacementType().getTypePtr());
4680 }
4682 for (const TemplateArgument &TA : TST->template_arguments()) {
4683 if (TA.getKind() == TemplateArgument::Type && Visit(TA.getAsType().getTypePtr()))
4684 return true;
4685 }
4686 return false;
4687 }
4689 return false; // shrug...
4690 }
4691 bool VisitTypeOfType(const TypeOfType* TOT) {
4692 return TOT->getUnmodifiedType().getTypePtr();
4693 }
4695 NestedNameSpecifier* NNS = ET->getQualifier();
4696 while (NNS) {
4697 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
4698 if (Visit(NNS->getAsType()))
4699 return true;
4700 }
4701 NNS = NNS->getPrefix();
4702 }
4703 return Visit(ET->getNamedType().getTypePtr());
4704 }
4705 };
4706
4708 return ST.Visit(T);
4709}
4710
4711////////////////////////////////////////////////////////////////////////////////
4712/// Check if 'input' or any of its template parameter was substituted when
4713/// instantiating the class template instance and replace it with the
4714/// partially sugared types we have from 'instance'.
4715
4716clang::QualType ROOT::TMetaUtils::ReSubstTemplateArg(clang::QualType input, const clang::Type *instance)
4717{
4718 if (!instance) return input;
4719 // if there is no typedef in instance then there is nothing guiding any
4720 // template parameter typedef replacement.
4722 return input;
4723
4724 using namespace llvm;
4725 using namespace clang;
4726 const clang::ASTContext &Ctxt = instance->getAsCXXRecordDecl()->getASTContext();
4727
4728 // Treat scope (clang::ElaboratedType) if any.
4729 const clang::ElaboratedType* etype
4730 = llvm::dyn_cast<clang::ElaboratedType>(input.getTypePtr());
4731 if (etype) {
4732 // We have to also handle the prefix.
4733
4734 clang::Qualifiers scope_qualifiers = input.getLocalQualifiers();
4735 assert(instance->getAsCXXRecordDecl() != nullptr && "ReSubstTemplateArg only makes sense with a type representing a class.");
4736
4737 clang::NestedNameSpecifier *scope = ReSubstTemplateArgNNS(Ctxt,etype->getQualifier(),instance);
4738 clang::QualType subTy = ReSubstTemplateArg(clang::QualType(etype->getNamedType().getTypePtr(),0),instance);
4739
4740 if (scope)
4741 subTy = Ctxt.getElaboratedType(clang::ElaboratedTypeKeyword::None, scope, subTy);
4742 subTy = Ctxt.getQualifiedType(subTy,scope_qualifiers);
4743 return subTy;
4744 }
4745
4746 QualType QT = input;
4747
4748 // In case of Int_t* we need to strip the pointer first, ReSubst and attach
4749 // the pointer once again.
4750 if (isa<clang::PointerType>(QT.getTypePtr())) {
4751 // Get the qualifiers.
4752 Qualifiers quals = QT.getQualifiers();
4753 QualType nQT;
4754 nQT = ReSubstTemplateArg(QT->getPointeeType(),instance);
4755 if (nQT == QT->getPointeeType()) return QT;
4756
4757 QT = Ctxt.getPointerType(nQT);
4758 // Add back the qualifiers.
4759 QT = Ctxt.getQualifiedType(QT, quals);
4760 return QT;
4761 }
4762
4763 // In case of Int_t& we need to strip the pointer first, ReSubst and attach
4764 // the reference once again.
4765 if (isa<ReferenceType>(QT.getTypePtr())) {
4766 // Get the qualifiers.
4767 bool isLValueRefTy = isa<LValueReferenceType>(QT.getTypePtr());
4768 Qualifiers quals = QT.getQualifiers();
4769 QualType nQT;
4770 nQT = ReSubstTemplateArg(QT->getPointeeType(),instance);
4771 if (nQT == QT->getPointeeType()) return QT;
4772
4773 // Add the r- or l-value reference type back to the desugared one.
4774 if (isLValueRefTy)
4775 QT = Ctxt.getLValueReferenceType(nQT);
4776 else
4777 QT = Ctxt.getRValueReferenceType(nQT);
4778 // Add back the qualifiers.
4779 QT = Ctxt.getQualifiedType(QT, quals);
4780 return QT;
4781 }
4782
4783 // In case of Int_t[2] we need to strip the array first, ReSubst and attach
4784 // the array once again.
4785 if (isa<clang::ArrayType>(QT.getTypePtr())) {
4786 // Get the qualifiers.
4787 Qualifiers quals = QT.getQualifiers();
4788
4789 if (const auto arr = dyn_cast<ConstantArrayType>(QT.getTypePtr())) {
4790 QualType newQT= ReSubstTemplateArg(arr->getElementType(),instance);
4791
4792 if (newQT == arr->getElementType()) return QT;
4793 QT = Ctxt.getConstantArrayType(newQT,
4794 arr->getSize(),
4795 arr->getSizeExpr(),
4796 arr->getSizeModifier(),
4797 arr->getIndexTypeCVRQualifiers());
4798
4799 } else if (const auto arr = dyn_cast<DependentSizedArrayType>(QT.getTypePtr())) {
4800 QualType newQT = ReSubstTemplateArg(arr->getElementType(),instance);
4801
4802 if (newQT == QT) return QT;
4803 QT = Ctxt.getDependentSizedArrayType (newQT,
4804 arr->getSizeExpr(),
4805 arr->getSizeModifier(),
4806 arr->getIndexTypeCVRQualifiers(),
4807 arr->getBracketsRange());
4808
4809 } else if (const auto arr = dyn_cast<IncompleteArrayType>(QT.getTypePtr())) {
4810 QualType newQT = ReSubstTemplateArg(arr->getElementType(),instance);
4811
4812 if (newQT == arr->getElementType()) return QT;
4813 QT = Ctxt.getIncompleteArrayType (newQT,
4814 arr->getSizeModifier(),
4815 arr->getIndexTypeCVRQualifiers());
4816
4817 } else if (const auto arr = dyn_cast<VariableArrayType>(QT.getTypePtr())) {
4818 QualType newQT = ReSubstTemplateArg(arr->getElementType(),instance);
4819
4820 if (newQT == arr->getElementType()) return QT;
4821 QT = Ctxt.getVariableArrayType (newQT,
4822 arr->getSizeExpr(),
4823 arr->getSizeModifier(),
4824 arr->getIndexTypeCVRQualifiers(),
4825 arr->getBracketsRange());
4826 }
4827
4828 // Add back the qualifiers.
4829 QT = Ctxt.getQualifiedType(QT, quals);
4830 return QT;
4831 }
4832
4833 // If the instance is also an elaborated type, we need to skip
4834 etype = llvm::dyn_cast<clang::ElaboratedType>(instance);
4835 if (etype) {
4836 instance = etype->getNamedType().getTypePtr();
4837 if (!instance) return input;
4838 }
4839
4840 const clang::TemplateSpecializationType* TST
4841 = llvm::dyn_cast<const clang::TemplateSpecializationType>(instance);
4842
4843 if (!TST) return input;
4844
4845 const clang::ClassTemplateSpecializationDecl* TSTdecl
4846 = llvm::dyn_cast_or_null<const clang::ClassTemplateSpecializationDecl>(instance->getAsCXXRecordDecl());
4847
4848 if (!TSTdecl) return input;
4849
4850 const clang::SubstTemplateTypeParmType *substType
4851 = llvm::dyn_cast<clang::SubstTemplateTypeParmType>(input.getTypePtr());
4852
4853 if (substType) {
4854 // Make sure it got replaced from this template
4855 const clang::ClassTemplateDecl *replacedCtxt = nullptr;
4856
4857 const clang::DeclContext *replacedDeclCtxt = substType->getReplacedParameter()->getDeclContext();
4858 const clang::CXXRecordDecl *decl = llvm::dyn_cast<clang::CXXRecordDecl>(replacedDeclCtxt);
4859 unsigned int index = substType->getReplacedParameter()->getIndex();
4860 if (decl) {
4861
4862 if (decl->getKind() == clang::Decl::ClassTemplatePartialSpecialization) {
4863 const clang::ClassTemplatePartialSpecializationDecl *spec = llvm::dyn_cast<clang::ClassTemplatePartialSpecializationDecl>(decl);
4864
4865 unsigned int depth = substType->getReplacedParameter()->getDepth();
4866
4867 const TemplateArgument *instanceArgs = spec->getTemplateArgs().data();
4868 unsigned int instanceNArgs = spec->getTemplateArgs().size();
4869
4870 // Search for the 'right' replacement.
4871
4872 for(unsigned int A = 0; A < instanceNArgs; ++A) {
4873 if (instanceArgs[A].getKind() == clang::TemplateArgument::Type) {
4874 clang::QualType argQualType = instanceArgs[A].getAsType();
4875
4876 const clang::TemplateTypeParmType *replacementType;
4877
4878 replacementType = llvm::dyn_cast<clang::TemplateTypeParmType>(argQualType);
4879
4880 if (!replacementType) {
4881 const clang::SubstTemplateTypeParmType *argType
4882 = llvm::dyn_cast<clang::SubstTemplateTypeParmType>(argQualType);
4883 if (argType) {
4884 clang::QualType replacementQT = argType->getReplacementType();
4885 replacementType = llvm::dyn_cast<clang::TemplateTypeParmType>(replacementQT);
4886 }
4887 }
4888 if (replacementType &&
4889 depth == replacementType->getDepth() &&
4890 index == replacementType->getIndex() )
4891 {
4892 index = A;
4893 break;
4894 }
4895 }
4896 }
4897 replacedCtxt = spec->getSpecializedTemplate();
4898 } else {
4899 replacedCtxt = decl->getDescribedClassTemplate();
4900 }
4901 } else if (auto const declguide = llvm::dyn_cast<clang::CXXDeductionGuideDecl>(replacedDeclCtxt)) {
4902 replacedCtxt = llvm::dyn_cast<clang::ClassTemplateDecl>(declguide->getDeducedTemplate());
4903 } else if (auto const ctdecl = llvm::dyn_cast<clang::ClassTemplateDecl>(replacedDeclCtxt)) {
4905 } else {
4906 std::string astDump;
4907 llvm::raw_string_ostream ostream(astDump);
4908 instance->dump(ostream, Ctxt);
4909 ostream.flush();
4910 ROOT::TMetaUtils::Warning("ReSubstTemplateArg","Unexpected type of declaration context for template parameter: %s.\n\tThe responsible class is:\n\t%s\n",
4911 replacedDeclCtxt->getDeclKindName(), astDump.c_str());
4912 replacedCtxt = nullptr;
4913 }
4914
4915 if ((replacedCtxt && replacedCtxt->getCanonicalDecl() == TSTdecl->getSpecializedTemplate()->getCanonicalDecl())
4916 || /* the following is likely just redundant */
4917 substType->getReplacedParameter()
4918 == TSTdecl->getSpecializedTemplate ()->getTemplateParameters()->getParam(index))
4919 {
4920 const auto &TAs = TST->template_arguments();
4921 if (index >= TAs.size()) {
4922 // The argument replaced was a default template argument that is
4923 // being listed as part of the instance ...
4924 // so we probably don't really know how to spell it ... we would need to recreate it
4925 // (See AddDefaultParameters).
4926 return input;
4927 } else if (TAs[index].getKind() == clang::TemplateArgument::Type) {
4928 return TAs[index].getAsType();
4929 } else {
4930 // The argument is (likely) a value or expression and there is nothing for us
4931 // to change
4932 return input;
4933 }
4934 }
4935 }
4936 // Maybe a class template instance, recurse and rebuild
4937 const clang::TemplateSpecializationType* inputTST
4938 = llvm::dyn_cast<const clang::TemplateSpecializationType>(input.getTypePtr());
4939 const clang::ASTContext& astCtxt = TSTdecl->getASTContext();
4940
4941 if (inputTST) {
4942 bool mightHaveChanged = false;
4943 llvm::SmallVector<clang::TemplateArgument, 4> desArgs;
4944 for (const clang::TemplateArgument &TA : inputTST->template_arguments()) {
4945 if (TA.getKind() != clang::TemplateArgument::Type) {
4946 desArgs.push_back(TA);
4947 continue;
4948 }
4949
4950 clang::QualType SubTy = TA.getAsType();
4951 // Check if the type needs more desugaring and recurse.
4952 if (llvm::isa<clang::ElaboratedType>(SubTy)
4953 || llvm::isa<clang::SubstTemplateTypeParmType>(SubTy)
4954 || llvm::isa<clang::TemplateSpecializationType>(SubTy)) {
4955 clang::QualType newSubTy = ReSubstTemplateArg(SubTy,instance);
4957 if (!newSubTy.isNull()) {
4958 desArgs.push_back(clang::TemplateArgument(newSubTy));
4959 }
4960 } else
4961 desArgs.push_back(TA);
4962 }
4963
4964 // If desugaring happened allocate new type in the AST.
4965 if (mightHaveChanged) {
4966 clang::Qualifiers qualifiers = input.getLocalQualifiers();
4967 input = astCtxt.getTemplateSpecializationType(inputTST->getTemplateName(),
4968 desArgs,
4969 inputTST->getCanonicalTypeInternal());
4970 input = astCtxt.getQualifiedType(input, qualifiers);
4971 }
4972 }
4973
4974 return input;
4975}
4976
4977////////////////////////////////////////////////////////////////////////////////
4978/// Remove the last n template arguments from the name
4979
4981{
4982 if ( nArgsToRemove == 0 || name == "")
4983 return 0;
4984
4985 // We proceed from the right to the left, counting commas which are not
4986 // enclosed by < >.
4987 const unsigned int length = name.length();
4988 unsigned int cur=0; // let's start beyond the first > from the right
4989 unsigned int nArgsRemoved=0;
4990 unsigned int nBraces=0;
4991 char c='@';
4993 c = name[cur];
4994 if (c == '<') nBraces++;
4995 if (c == '>') nBraces--;
4996 if (c == ',' && nBraces==1 /*So we are not in a sub-template*/) nArgsRemoved++;
4997 cur++;
4998 }
4999 cur--;
5000 name = name.substr(0,cur)+">";
5001 return 0;
5002
5003}
5004
5005////////////////////////////////////////////////////////////////////////////////
5006/// Converts STL container name to number. vector -> 1, etc..
5007
5009{
5010 static const char *stls[] = //container names
5011 {"any","vector","list", "deque","map","multimap","set","multiset","bitset",
5012 "forward_list","unordered_set","unordered_multiset","unordered_map","unordered_multimap", "RVec", nullptr};
5013 static const ROOT::ESTLType values[] =
5024 };
5025 // kind of stl container
5026 for (int k = 1; stls[k]; k++) {
5027 if (type == stls[k])
5028 return values[k];
5029 }
5030 return ROOT::kNotSTL;
5031}
5032
5033////////////////////////////////////////////////////////////////////////////////
5034
5035const clang::TypedefNameDecl *ROOT::TMetaUtils::GetAnnotatedRedeclarable(const clang::TypedefNameDecl *TND)
5036{
5037 if (!TND)
5038 return nullptr;
5039
5040 TND = TND->getMostRecentDecl();
5041 while (TND && !(TND->hasAttrs()))
5042 TND = TND->getPreviousDecl();
5043
5044 return TND;
5045}
5046
5047////////////////////////////////////////////////////////////////////////////////
5048
5049const clang::TagDecl *ROOT::TMetaUtils::GetAnnotatedRedeclarable(const clang::TagDecl *TD)
5050{
5051 if (!TD)
5052 return nullptr;
5053
5054 TD = TD->getMostRecentDecl();
5055 while (TD && !(TD->hasAttrs() && TD->isThisDeclarationADefinition()))
5056 TD = TD->getPreviousDecl();
5057
5058 return TD;
5059}
5060
5061////////////////////////////////////////////////////////////////////////////////
5062/// Extract the immediately outer namespace and then launch the recursion
5063
5065 std::list<std::pair<std::string,bool> >& enclosingNamespaces)
5066{
5067 const clang::DeclContext* enclosingNamespaceDeclCtxt = decl.getDeclContext();
5068 if (!enclosingNamespaceDeclCtxt) return;
5069
5070 const clang::NamespaceDecl* enclosingNamespace =
5071 clang::dyn_cast<clang::NamespaceDecl>(enclosingNamespaceDeclCtxt);
5072 if (!enclosingNamespace) return;
5073
5074 enclosingNamespaces.push_back(std::make_pair(enclosingNamespace->getNameAsString(),
5075 enclosingNamespace->isInline()));
5076
5078
5079}
5080
5081////////////////////////////////////////////////////////////////////////////////
5082/// Extract enclosing namespaces recursively
5083
5085 std::list<std::pair<std::string,bool> >& enclosingNamespaces)
5086{
5087 const clang::DeclContext* enclosingNamespaceDeclCtxt = ctxt.getParent ();
5088
5089 // If no parent is found, nothing more to be done
5091 return;
5092 }
5093
5094 // Check if the parent is a namespace (it could be a class for example)
5095 // if not, nothing to be done here
5096 const clang::NamespaceDecl* enclosingNamespace = clang::dyn_cast<clang::NamespaceDecl>(enclosingNamespaceDeclCtxt);
5097 if (!enclosingNamespace) return;
5098
5099 // Add to the list of parent namespaces
5100 enclosingNamespaces.push_back(std::make_pair(enclosingNamespace->getNameAsString(),
5101 enclosingNamespace->isInline()));
5102
5103 // here the recursion
5105}
5106
5107////////////////////////////////////////////////////////////////////////////////
5108/// Extract the names and types of containing scopes.
5109/// Stop if a class is met and return its pointer.
5110
5111const clang::RecordDecl *ROOT::TMetaUtils::ExtractEnclosingScopes(const clang::Decl& decl,
5112 std::list<std::pair<std::string,unsigned int> >& enclosingSc)
5113{
5114 const clang::DeclContext* enclosingDeclCtxt = decl.getDeclContext();
5115 if (!enclosingDeclCtxt) return nullptr;
5116
5117 unsigned int scopeType;
5118
5119 if (auto enclosingNamespacePtr =
5120 clang::dyn_cast<clang::NamespaceDecl>(enclosingDeclCtxt)){
5121 scopeType= enclosingNamespacePtr->isInline() ? 1 : 0; // inline or simple namespace
5122 enclosingSc.push_back(std::make_pair(enclosingNamespacePtr->getNameAsString(),scopeType));
5124 }
5125
5126 if (auto enclosingClassPtr =
5127 clang::dyn_cast<clang::RecordDecl>(enclosingDeclCtxt)){
5128 return enclosingClassPtr;
5129 }
5130
5131 return nullptr;
5132}
5133
5134////////////////////////////////////////////////////////////////////////////////
5135/// Reimplementation of TSystem::ExpandPathName() that cannot be
5136/// used from TMetaUtils.
5137
5138static void replaceEnvVars(const char* varname, std::string& txt)
5139{
5140 std::string::size_type beginVar = 0;
5141 std::string::size_type endVar = 0;
5142 while ((beginVar = txt.find('$', beginVar)) != std::string::npos
5143 && beginVar + 1 < txt.length()) {
5144 std::string::size_type beginVarName = beginVar + 1;
5145 std::string::size_type endVarName = std::string::npos;
5146 if (txt[beginVarName] == '(') {
5147 // "$(VARNAME)" style.
5148 endVarName = txt.find(')', beginVarName);
5149 ++beginVarName;
5150 if (endVarName == std::string::npos) {
5151 ROOT::TMetaUtils::Error(nullptr, "Missing ')' for '$(' in $%s at %s\n",
5152 varname, txt.c_str() + beginVar);
5153 return;
5154 }
5155 endVar = endVarName + 1;
5156 } else {
5157 // "$VARNAME/..." style.
5158 beginVarName = beginVar + 1;
5160 while (isalnum(txt[endVarName]) || txt[endVarName] == '_')
5161 ++endVarName;
5163 }
5164
5165 const char* val = getenv(txt.substr(beginVarName,
5166 endVarName - beginVarName).c_str());
5167 if (!val) val = "";
5168
5169 txt.replace(beginVar, endVar - beginVar, val);
5170 int lenval = strlen(val);
5171 int delta = lenval - (endVar - beginVar); // these many extra chars,
5172 endVar += delta; // advance the end marker accordingly.
5173
5174 // Look for the next one
5175 beginVar = endVar + 1;
5176 }
5177}
5178
5179////////////////////////////////////////////////////////////////////////////////
5180/// Organise the parameters for cling in order to guarantee relocatability
5181/// It treats the gcc toolchain and the root include path
5182/// FIXME: enables relocatability for experiments' framework headers until PCMs
5183/// are available.
5184
5186{
5187 const char* envInclPath = getenv("ROOT_INCLUDE_PATH");
5188
5189 if (!envInclPath)
5190 return;
5191 std::istringstream envInclPathsStream(envInclPath);
5192 std::string inclPath;
5193 while (std::getline(envInclPathsStream, inclPath, ':')) {
5194 // Can't use TSystem in here; re-implement TSystem::ExpandPathName().
5195 replaceEnvVars("ROOT_INCLUDE_PATH", inclPath);
5196 if (!inclPath.empty()) {
5197 clingArgs.push_back("-I");
5198 clingArgs.push_back(inclPath);
5199 }
5200 }
5201}
5202
5203////////////////////////////////////////////////////////////////////////////////
5204
5205void ROOT::TMetaUtils::ReplaceAll(std::string& str, const std::string& from, const std::string& to,bool recurse)
5206{
5207 if(from.empty())
5208 return;
5209 size_t start_pos = 0;
5210 bool changed=true;
5211 while (changed){
5212 changed=false;
5213 start_pos = 0;
5214 while((start_pos = str.find(from, start_pos)) != std::string::npos) {
5215 str.replace(start_pos, from.length(), to);
5216 start_pos += to.length();
5217 if (recurse) changed = true;
5218 }
5219 }
5220}
5221
5222////////////////////////////////////////////////////////////////////////////////
5223/// Return the separator suitable for this platform.
5228
5229////////////////////////////////////////////////////////////////////////////////
5230
5231bool ROOT::TMetaUtils::EndsWith(const std::string &theString, const std::string &theSubstring)
5232{
5233 if (theString.size() < theSubstring.size()) return false;
5234 const unsigned int theSubstringSize = theSubstring.size();
5235 return 0 == theString.compare(theString.size() - theSubstringSize,
5237 theSubstring);
5238}
5239
5240////////////////////////////////////////////////////////////////////////////////
5241
5242bool ROOT::TMetaUtils::BeginsWith(const std::string &theString, const std::string &theSubstring)
5243{
5244 if (theString.size() < theSubstring.size()) return false;
5245 const unsigned int theSubstringSize = theSubstring.size();
5246 return 0 == theString.compare(0,
5248 theSubstring);
5249}
5250
5251
5252
5253////////////////////////////////////////////////////////////////////////////////
5254
5256{
5257 // Note, should change this into take llvm::StringRef.
5258
5259 if ((strstr(filename, "LinkDef") || strstr(filename, "Linkdef") ||
5260 strstr(filename, "linkdef")) && strstr(filename, ".h")) {
5261 return true;
5262 }
5263 size_t len = strlen(filename);
5264 size_t linkdeflen = 9; /* strlen("linkdef.h") */
5265 if (len >= 9) {
5266 if (0 == strncasecmp(filename + (len - linkdeflen), "linkdef", linkdeflen - 2)
5267 && 0 == strcmp(filename + (len - 2), ".h")
5268 ) {
5269 return true;
5270 } else {
5271 return false;
5272 }
5273 } else {
5274 return false;
5275 }
5276}
5277
5278////////////////////////////////////////////////////////////////////////////////
5279
5281{
5282 return llvm::sys::path::extension(filename) == ".h" ||
5283 llvm::sys::path::extension(filename) == ".hh" ||
5284 llvm::sys::path::extension(filename) == ".hpp" ||
5285 llvm::sys::path::extension(filename) == ".H" ||
5286 llvm::sys::path::extension(filename) == ".h++" ||
5287 llvm::sys::path::extension(filename) == "hxx" ||
5288 llvm::sys::path::extension(filename) == "Hxx" ||
5289 llvm::sys::path::extension(filename) == "HXX";
5290}
5291
5292////////////////////////////////////////////////////////////////////////////////
5293
5294const std::string ROOT::TMetaUtils::AST2SourceTools::Decls2FwdDecls(const std::vector<const clang::Decl *> &decls,
5295 cling::Interpreter::IgnoreFilesFunc_t ignoreFiles,
5296 const cling::Interpreter &interp,
5297 std::string *logs)
5298{
5299 clang::Sema &sema = interp.getSema();
5300 cling::Transaction theTransaction(sema);
5301 std::set<clang::Decl *> addedDecls;
5302 for (auto decl : decls) {
5303 // again waiting for cling
5304 clang::Decl *ncDecl = const_cast<clang::Decl *>(decl);
5305 theTransaction.append(ncDecl);
5306 }
5307 std::string newFwdDecl;
5308 llvm::raw_string_ostream llvmOstr(newFwdDecl);
5309
5310 std::string locallogs;
5311 llvm::raw_string_ostream llvmLogStr(locallogs);
5312 interp.forwardDeclare(theTransaction, sema.getPreprocessor(), sema.getASTContext(), llvmOstr, true,
5313 logs ? &llvmLogStr : nullptr, ignoreFiles);
5314 llvmOstr.flush();
5315 llvmLogStr.flush();
5316 if (logs)
5317 logs->swap(locallogs);
5318 return newFwdDecl;
5319}
5320
5321////////////////////////////////////////////////////////////////////////////////
5322/// Take the namespaces which enclose the decl and put them around the
5323/// definition string.
5324/// For example, if the definition string is "myClass" which is enclosed by
5325/// the namespaces ns1 and ns2, one would get:
5326/// namespace ns2{ namespace ns1 { class myClass; } }
5327
5329 std::string& defString)
5330{
5332 return rcd ? 1:0;
5333}
5334
5335////////////////////////////////////////////////////////////////////////////////
5336/// Take the scopes which enclose the decl and put them around the
5337/// definition string.
5338/// If a class is encountered, bail out.
5339
5340const clang::RecordDecl* ROOT::TMetaUtils::AST2SourceTools::EncloseInScopes(const clang::Decl& decl,
5341 std::string& defString)
5342{
5343 std::list<std::pair<std::string,unsigned int> > enclosingNamespaces;
5345
5346 if (rcdPtr) return rcdPtr;
5347
5348 // Check if we have enclosing namespaces
5349 static const std::string scopeType [] = {"namespace ", "inline namespace ", "class "};
5350
5351 std::string scopeName;
5352 std::string scopeContent;
5353 unsigned int scopeIndex;
5354 for (auto const & encScope : enclosingNamespaces){
5355 scopeIndex = encScope.second;
5356 scopeName = encScope.first;
5357 scopeContent = " { " + defString + " }";
5359 scopeName +
5361 }
5362 return nullptr;
5363}
5364
5365////////////////////////////////////////////////////////////////////////////////
5366/// Loop over the template parameters and build a string for template arguments
5367/// using the fully qualified name
5368/// There are different cases:
5369/// Case 1: a simple template parameter
5370/// E.g. `template<typename T> class A;`
5371/// Case 2: a non-type: either an integer or an enum
5372/// E.g. `template<int I, Foo > class A;` where `Foo` is `enum Foo {red, blue};`
5373/// 2 sub cases here:
5374/// SubCase 2.a: the parameter is an enum: bail out, cannot be treated.
5375/// SubCase 2.b: use the fully qualified name
5376/// Case 3: a TemplateTemplate argument
5377/// E.g. `template <template <typename> class T> class container { };`
5378
5380 const clang::TemplateParameterList& tmplParamList,
5381 const cling::Interpreter& interpreter)
5382{
5383 templateArgs="<";
5384 for (auto prmIt = tmplParamList.begin();
5385 prmIt != tmplParamList.end(); prmIt++){
5386
5387 if (prmIt != tmplParamList.begin())
5388 templateArgs += ", ";
5389
5390 auto nDecl = *prmIt;
5391 std::string typeName;
5392
5393 // Case 1
5394 if (llvm::isa<clang::TemplateTypeParmDecl>(nDecl)){
5395 typeName = "typename ";
5396 if (nDecl->isParameterPack())
5397 typeName += "... ";
5398 typeName += (*prmIt)->getNameAsString();
5399 }
5400 // Case 2
5401 else if (auto nttpd = llvm::dyn_cast<clang::NonTypeTemplateParmDecl>(nDecl)){
5402 auto theType = nttpd->getType();
5403 // If this is an enum, use int as it is impossible to fwd declare and
5404 // this makes sense since it is not a type...
5405 if (theType.getAsString().find("enum") != std::string::npos){
5406 std::string astDump;
5407 llvm::raw_string_ostream ostream(astDump);
5408 nttpd->dump(ostream);
5409 ostream.flush();
5410 ROOT::TMetaUtils::Warning(nullptr,"Forward declarations of templates with enums as template parameters. The responsible class is: %s\n", astDump.c_str());
5411 return 1;
5412 } else {
5414 theType,
5415 interpreter);
5416 }
5417 }
5418 // Case 3: TemplateTemplate argument
5419 else if (auto ttpd = llvm::dyn_cast<clang::TemplateTemplateParmDecl>(nDecl)){
5421 if (retCode!=0){
5422 std::string astDump;
5423 llvm::raw_string_ostream ostream(astDump);
5424 ttpd->dump(ostream);
5425 ostream.flush();
5426 ROOT::TMetaUtils::Error(nullptr,"Cannot reconstruct template template parameter forward declaration for %s\n", astDump.c_str());
5427 return 1;
5428 }
5429 }
5430
5431 templateArgs += typeName;
5432 }
5433
5434 templateArgs+=">";
5435 return 0;
5436}
5437
5438////////////////////////////////////////////////////////////////////////////////
5439/// Convert a tmplt decl to its fwd decl
5440
5442 const cling::Interpreter& interpreter,
5443 std::string& defString)
5444{
5445 std::string templatePrefixString;
5446 auto tmplParamList= templDecl.getTemplateParameters();
5447 if (!tmplParamList){ // Should never happen
5448 Error(nullptr,
5449 "Cannot extract template parameter list for %s",
5450 templDecl.getNameAsString().c_str());
5451 return 1;
5452 }
5453
5455 if (retCode!=0){
5456 Warning(nullptr,
5457 "Problems with arguments for forward declaration of class %s\n",
5458 templDecl.getNameAsString().c_str());
5459 return retCode;
5460 }
5461 templatePrefixString = "template " + templatePrefixString + " ";
5462
5463 defString = templatePrefixString + "class ";
5464 if (templDecl.isParameterPack())
5465 defString += "... ";
5466 defString += templDecl.getNameAsString();
5467 if (llvm::isa<clang::TemplateTemplateParmDecl>(&templDecl)) {
5468 // When fwd declaring the template template arg of
5469 // namespace N { template <template <class T> class C> class X; }
5470 // we don't need to put it into any namespace, and we want no trailing
5471 // ';'
5472 return 0;
5473 }
5474 defString += ';';
5476}
5477
5478////////////////////////////////////////////////////////////////////////////////
5479
5480static int TreatSingleTemplateArg(const clang::TemplateArgument& arg,
5481 std::string& argFwdDecl,
5482 const cling::Interpreter& interpreter,
5483 bool acceptStl=false)
5484{
5485 using namespace ROOT::TMetaUtils::AST2SourceTools;
5486
5487 // We do nothing in presence of ints, bools, templates.
5488 // We should probably in presence of templates though...
5489 if (clang::TemplateArgument::Type != arg.getKind()) return 0;
5490
5491 auto argQualType = arg.getAsType();
5492
5493 // Recursively remove all *
5494 while (llvm::isa<clang::PointerType>(argQualType.getTypePtr())) argQualType = argQualType->getPointeeType();
5495
5496 auto argTypePtr = argQualType.getTypePtr();
5497
5498 // Bail out on enums
5499 if (llvm::isa<clang::EnumType>(argTypePtr)){
5500 return 1;
5501 }
5502
5503 // If this is a built-in, just return: fwd decl not necessary.
5504 if (llvm::isa<clang::BuiltinType>(argTypePtr)){
5505 return 0;
5506 }
5507
5508 // Treat typedefs which are arguments
5509 if (auto tdTypePtr = llvm::dyn_cast<clang::TypedefType>(argTypePtr)) {
5510 FwdDeclFromTypeDefNameDecl(*tdTypePtr->getDecl(), interpreter, argFwdDecl);
5511 return 0;
5512 }
5513
5514 if (auto argRecTypePtr = llvm::dyn_cast<clang::RecordType>(argTypePtr)){
5515 // Now we cannot but have a RecordType
5516 if (auto argRecDeclPtr = argRecTypePtr->getDecl()){
5517 FwdDeclFromRcdDecl(*argRecDeclPtr,interpreter,argFwdDecl,acceptStl);
5518 }
5519 return 0;
5520 }
5521
5522 return 1;
5523}
5524
5525////////////////////////////////////////////////////////////////////////////////
5526/// Convert a tmplt decl to its fwd decl
5527
5529 const cling::Interpreter& interpreter,
5530 std::string& defString,
5531 const std::string &normalizedName)
5532{
5533 // If this is an explicit specialization, inject it into cling, too, such that it can have
5534 // externalLexicalStorage, see TCling.cxx's ExtVisibleStorageAdder::VisitClassTemplateSpecializationDecl.
5535 if (auto tmplSpecDeclPtr = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(&recordDecl)) {
5536 if (const auto *specDef = tmplSpecDeclPtr->getDefinition()) {
5537 if (specDef->getTemplateSpecializationKind() != clang::TSK_ExplicitSpecialization)
5538 return 0;
5539 // normalizedName contains scope, no need to enclose in namespace!
5541 std::cout << " Forward declaring template spec " << normalizedName << ":\n";
5542 for (auto arg : tmplSpecDeclPtr->getTemplateArgs().asArray()) {
5543 std::string argFwdDecl;
5544 int retCode = TreatSingleTemplateArg(arg, argFwdDecl, interpreter, /*acceptStl=*/false);
5546 std::cout << " o Template argument ";
5547 if (retCode == 0) {
5548 std::cout << "successfully treated. Arg fwd decl: " << argFwdDecl << std::endl;
5549 } else {
5550 std::cout << "could not be treated. Abort fwd declaration generation.\n";
5551 }
5552 }
5553
5554 if (retCode != 0) { // A sign we must bail out
5555 return retCode;
5556 }
5557 defString += argFwdDecl + '\n';
5558 }
5559 defString += "template <> class " + normalizedName + ';';
5560 return 0;
5561 }
5562 }
5563
5564 return 0;
5565}
5566
5567////////////////////////////////////////////////////////////////////////////////
5568/// Convert a rcd decl to its fwd decl
5569/// If this is a template specialisation, treat in the proper way.
5570/// If it is contained in a class, just fwd declare the class.
5571
5573 const cling::Interpreter& interpreter,
5574 std::string& defString,
5575 bool acceptStl)
5576{
5577 // Do not fwd declare the templates in the stl.
5579 return 0;
5580
5581 // Do not fwd declare unnamed decls.
5582 if (!recordDecl.getIdentifier())
5583 return 0;
5584
5585 // We may need to fwd declare the arguments of the template
5586 std::string argsFwdDecl;
5587
5588 if (auto tmplSpecDeclPtr = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(&recordDecl)){
5589 std::string argFwdDecl;
5591 std::cout << "Class " << recordDecl.getNameAsString()
5592 << " is a template specialisation. Treating its arguments.\n";
5593 for(auto arg : tmplSpecDeclPtr->getTemplateArgs().asArray()){
5596 std::cout << " o Template argument ";
5597 if (retCode==0){
5598 std::cout << "successfully treated. Arg fwd decl: " << argFwdDecl << std::endl;
5599 } else {
5600 std::cout << "could not be treated. Abort fwd declaration generation.\n";
5601 }
5602 }
5603
5604 if (retCode!=0){ // A sign we must bail out
5605 return retCode;
5606 }
5608 }
5609
5610 if (acceptStl){
5612 return 0;
5613 }
5614
5615 int retCode=0;
5616 if (auto tmplDeclPtr = tmplSpecDeclPtr->getSpecializedTemplate()){
5618 }
5619 defString = argsFwdDecl + "\n" + defString;
5620 return retCode;
5621
5622 }
5623
5624 defString = "class " + recordDecl.getNameAsString() + ";";
5625 const clang::RecordDecl* rcd = EncloseInScopes(recordDecl, defString);
5626
5627 if (rcd){
5629 }
5630 // Add a \n here to avoid long lines which contain duplications, for example (from MathCore):
5631 // namespace ROOT { namespace Math { class IBaseFunctionMultiDim; } }namespace ROOT { namespace Fit { template <typename FunType> class Chi2FCN; } }
5632 // namespace ROOT { namespace Math { class IGradientFunctionMultiDim; } }namespace ROOT { namespace Fit { template <typename FunType> class Chi2FCN; } }
5633 defString = argsFwdDecl + "\n" + defString;
5634
5635 return 0;
5636}
5637
5638////////////////////////////////////////////////////////////////////////////////
5639/// Extract "forward declaration" of a typedef.
5640/// If the typedef is contained in a class, just fwd declare the class.
5641/// If not, fwd declare the typedef and all the dependent typedefs and types if necessary.
5642
5644 const cling::Interpreter& interpreter,
5645 std::string& fwdDeclString,
5646 std::unordered_set<std::string>* fwdDeclSetPtr)
5647{
5648 std::string buffer = tdnDecl.getNameAsString();
5649 std::string underlyingName;
5650 auto underlyingType = tdnDecl.getUnderlyingType().getCanonicalType();
5651 if (const clang::TagType* TT
5652 = llvm::dyn_cast<clang::TagType>(underlyingType.getTypePtr())) {
5653 if (clang::NamedDecl* ND = TT->getDecl()) {
5654 if (!ND->getIdentifier()) {
5655 // No fwd decl for unnamed underlying entities.
5656 return 0;
5657 }
5658 }
5659 }
5660
5661 TNormalizedCtxt nCtxt(interpreter.getLookupHelper());
5665 nCtxt);
5666
5667 // Heuristic: avoid entities like myclass<myType1, myType2::xyz>
5668 if (underlyingName.find(">::") != std::string::npos)
5669 return 0;
5670
5671 buffer="typedef "+underlyingName+" "+buffer+";";
5672 const clang::RecordDecl* rcd=EncloseInScopes(tdnDecl,buffer);
5673 if (rcd) {
5674 // We do not need the whole series of scopes, just the class.
5675 // It is enough to trigger an uncomplete type autoload/parse callback
5676 // for example: MyClass::blabla::otherNs::myTypedef
5678 }
5679
5680 // Start Recursion if the underlying type is a TypedefNameDecl
5681 // Note: the simple cast w/o the getSingleStepDesugaredType call
5682 // does not work in case the typedef is in a namespace.
5683 auto& ctxt = tdnDecl.getASTContext();
5684 auto immediatelyUnderlyingType = underlyingType.getSingleStepDesugaredType(ctxt);
5685
5686 if (auto underlyingTdnTypePtr = llvm::dyn_cast<clang::TypedefType>(immediatelyUnderlyingType.getTypePtr())){
5687 std::string tdnFwdDecl;
5691 tdnFwdDecl,
5693 if (!fwdDeclSetPtr || fwdDeclSetPtr->insert(tdnFwdDecl).second)
5695 } else if (auto CXXRcdDeclPtr = immediatelyUnderlyingType->getAsCXXRecordDecl()){
5696 std::string classFwdDecl;
5698 std::cout << "Typedef " << tdnDecl.getNameAsString() << " hides a class: "
5699 << CXXRcdDeclPtr->getNameAsString() << std::endl;
5703 true /* acceptStl*/);
5704 if (retCode!=0){ // bail out
5705 return 0;
5706 }
5707
5708 if (!fwdDeclSetPtr || fwdDeclSetPtr->insert(classFwdDecl).second)
5710 }
5711
5712 fwdDeclString+=buffer;
5713
5714 return 0;
5715}
5716
5717////////////////////////////////////////////////////////////////////////////////
5718/// Get the default value as string.
5719/// Limited at the moment to:
5720/// - Integers
5721/// - Booleans
5722
5723int ROOT::TMetaUtils::AST2SourceTools::GetDefArg(const clang::ParmVarDecl& par,
5724 std::string& valAsString,
5725 const clang::PrintingPolicy& ppolicy)
5726{
5727 auto defArgExprPtr = par.getDefaultArg();
5728 auto& ctxt = par.getASTContext();
5729 if(!defArgExprPtr->isEvaluatable(ctxt)){
5730 return -1;
5731 }
5732
5733 auto defArgType = par.getType();
5734
5735 // The value is a boolean
5736 if (defArgType->isBooleanType()){
5737 bool result;
5738 defArgExprPtr->EvaluateAsBooleanCondition (result,ctxt);
5739 valAsString=std::to_string(result);
5740 return 0;
5741 }
5742
5743 // The value is an integer
5744 if (defArgType->isIntegerType()){
5745 clang::Expr::EvalResult evalResult;
5746 defArgExprPtr->EvaluateAsInt(evalResult, ctxt);
5747 llvm::APSInt result = evalResult.Val.getInt();
5748 auto uintVal = *result.getRawData();
5749 if (result.isNegative()){
5750 long long int intVal=uintVal*-1;
5751 valAsString=std::to_string(intVal);
5752 } else {
5753 valAsString=std::to_string(uintVal);
5754 }
5755
5756 return 0;
5757 }
5758
5759 // The value is something else. We go for the generalised printer
5760 llvm::raw_string_ostream rso(valAsString);
5761 defArgExprPtr->printPretty(rso,nullptr,ppolicy);
5762 valAsString = rso.str();
5763 // We can be in presence of a string. Let's escape the characters properly.
5764 ROOT::TMetaUtils::ReplaceAll(valAsString,"\\"","__TEMP__VAL__");
5766 ROOT::TMetaUtils::ReplaceAll(valAsString,"__TEMP__VAL__","\\"");
5767
5768 return 0;
5769}
5770
The file contains utilities which are foundational and could be used across the core component of ROO...
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
#define R(a, b, c, d, e, f, g, h, i)
Definition RSha256.hxx:110
static Roo_reg_AGKInteg1D instance
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
short Version_t
Definition RtypesCore.h:65
static void indent(ostringstream &buf, int indent_level)
static bool RecurseKeepNParams(clang::TemplateArgument &normTArg, const clang::TemplateArgument &tArg, const cling::Interpreter &interp, const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt, const clang::ASTContext &astCtxt)
static clang::SourceLocation getFinalSpellingLoc(clang::SourceManager &sourceManager, clang::SourceLocation sourceLoc)
const clang::DeclContext * GetEnclosingSpace(const clang::RecordDecl &cl)
bool IsTemplate(const clang::Decl &cl)
static void KeepNParams(clang::QualType &normalizedType, const clang::QualType &vanillaType, const cling::Interpreter &interp, const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt)
This function allows to manipulate the number of arguments in the type of a template specialisation.
static void CreateNameTypeMap(const clang::CXXRecordDecl &cl, ROOT::MembersTypeMap_t &nameType)
Create the data member name-type map for given class.
const clang::CXXMethodDecl * GetMethodWithProto(const clang::Decl *cinfo, const char *method, const char *proto, const cling::Interpreter &interp, bool diagnose)
int dumpDeclForAssert(const clang::Decl &D, const char *commentStart)
static void replaceEnvVars(const char *varname, std::string &txt)
Reimplementation of TSystem::ExpandPathName() that cannot be used from TMetaUtils.
static bool areEqualValues(const clang::TemplateArgument &tArg, const clang::NamedDecl &tPar)
std::cout << "Are equal values?\n";
static bool isTypeWithDefault(const clang::NamedDecl *nDecl)
Check if this NamedDecl is a template parameter with a default argument.
static int TreatSingleTemplateArg(const clang::TemplateArgument &arg, std::string &argFwdDecl, const cling::Interpreter &interpreter, bool acceptStl=false)
static bool areEqualTypes(const clang::TemplateArgument &tArg, llvm::SmallVectorImpl< clang::TemplateArgument > &preceedingTArgs, const clang::NamedDecl &tPar, const cling::Interpreter &interp, const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt)
static bool hasSomeTypedefSomewhere(const clang::Type *T)
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:185
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:229
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t dest
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t target
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h length
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t TPoint TPoint const char mode
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
char name[80]
Definition TGX11.cxx:110
const char * proto
Definition civetweb.c:17535
#define free
Definition civetweb.c:1539
const_iterator begin() const
const_iterator end() const
const clang::RecordDecl * GetRecordDecl() const
AnnotatedRecordDecl(long index, const clang::RecordDecl *decl, bool rStreamerInfo, bool rNoStreamer, bool rRequestNoInputOperator, bool rRequestOnlyTClass, int rRequestedVersionNumber, int rRequestedRNTupleSerializationMode, const cling::Interpreter &interpret, const TNormalizedCtxt &normCtxt)
There is no requested type name.
const clang::RecordDecl * fDecl
const char * GetRequestedName() const
static std::string BuildDemangledTypeInfo(const clang::RecordDecl *rDecl, const std::string &normalizedName)
const std::string & GetDemangledTypeInfo() const
const char * GetNormalizedName() const
const clang::CXXRecordDecl * fArgType
const clang::CXXRecordDecl * GetType() const
RConstructorType(const char *type_of_arg, const cling::Interpreter &)
bool IsDeclaredScope(const std::string &base, bool &isInlined) override
bool IsAlreadyPartiallyDesugaredName(const std::string &nondef, const std::string &nameLong) override
ExistingTypeCheck_t fExistingTypeCheck
TClingLookupHelper(cling::Interpreter &interpreter, TNormalizedCtxt &normCtxt, ExistingTypeCheck_t existingTypeCheck, AutoParse_t autoParse, bool *shuttingDownPtr, const int *pgDebug=nullptr)
bool GetPartiallyDesugaredNameWithScopeHandling(const std::string &tname, std::string &result, bool dropstd=true) override
We assume that we have a simple type: [const] typename[*&][const].
void GetPartiallyDesugaredName(std::string &nameLong) override
bool ExistingTypeCheck(const std::string &tname, std::string &result) override
Helper routine to ry hard to avoid looking up in the Cling database as this could enduce an unwanted ...
const Config_t & GetConfig() const
TNormalizedCtxt::Config_t::SkipCollection DeclsCont_t
TNormalizedCtxt::TemplPtrIntMap_t TemplPtrIntMap_t
int GetNargsToKeep(const clang::ClassTemplateDecl *templ) const
Get from the map the number of arguments to keep.
TNormalizedCtxt::Config_t Config_t
TNormalizedCtxtImpl(const cling::LookupHelper &lh)
Initialize the list of typedef to keep (i.e.
TNormalizedCtxt::TypesCont_t TypesCont_t
void AddTemplAndNargsToKeep(const clang::ClassTemplateDecl *templ, unsigned int i)
Add to the internal map the pointer of a template as key and the number of template arguments to keep...
void keepTypedef(const cling::LookupHelper &lh, const char *name, bool replace=false)
Insert the type with name into the collection of typedefs to keep.
const TypesCont_t & GetTypeWithAlternative() const
const TemplPtrIntMap_t GetTemplNargsToKeepMap() const
static TemplPtrIntMap_t fTemplatePtrArgsToKeepMap
void AddTemplAndNargsToKeep(const clang::ClassTemplateDecl *templ, unsigned int i)
void keepTypedef(const cling::LookupHelper &lh, const char *name, bool replace=false)
cling::utils::Transform::Config Config_t
std::map< const clang::ClassTemplateDecl *, int > TemplPtrIntMap_t
TNormalizedCtxt(const cling::LookupHelper &lh)
TNormalizedCtxtImpl * fImpl
const TypesCont_t & GetTypeWithAlternative() const
std::set< const clang::Type * > TypesCont_t
int GetNargsToKeep(const clang::ClassTemplateDecl *templ) const
const Config_t & GetConfig() const
const TemplPtrIntMap_t GetTemplNargsToKeepMap() const
#define I(x, y, z)
const std::string & GetPathSeparator()
int EncloseInNamespaces(const clang::Decl &decl, std::string &defString)
Take the namespaces which enclose the decl and put them around the definition string.
int FwdDeclFromTypeDefNameDecl(const clang::TypedefNameDecl &tdnDecl, const cling::Interpreter &interpreter, std::string &fwdDeclString, std::unordered_set< std::string > *fwdDeclSet=nullptr)
Extract "forward declaration" of a typedef.
int PrepareArgsForFwdDecl(std::string &templateArgs, const clang::TemplateParameterList &tmplParamList, const cling::Interpreter &interpreter)
Loop over the template parameters and build a string for template arguments using the fully qualified...
int FwdDeclFromTmplDecl(const clang::TemplateDecl &tmplDecl, const cling::Interpreter &interpreter, std::string &defString)
Convert a tmplt decl to its fwd decl.
const clang::RecordDecl * EncloseInScopes(const clang::Decl &decl, std::string &defString)
Take the scopes which enclose the decl and put them around the definition string.
int FwdDeclFromRcdDecl(const clang::RecordDecl &recordDecl, const cling::Interpreter &interpreter, std::string &defString, bool acceptStl=false)
Convert a rcd decl to its fwd decl If this is a template specialisation, treat in the proper way.
int GetDefArg(const clang::ParmVarDecl &par, std::string &valAsString, const clang::PrintingPolicy &pp)
Get the default value as string.
int FwdDeclIfTmplSpec(const clang::RecordDecl &recordDecl, const cling::Interpreter &interpreter, std::string &defString, const std::string &normalizedName)
Convert a tmplt decl to its fwd decl.
const std::string Decls2FwdDecls(const std::vector< const clang::Decl * > &decls, bool(*ignoreFiles)(const clang::PresumedLoc &), const cling::Interpreter &interp, std::string *logs)
bool HasClassDefMacro(const clang::Decl *decl, const cling::Interpreter &interpreter)
Return true if class has any of class declarations like ClassDef, ClassDefNV, ClassDefOverride.
llvm::StringRef GetClassComment(const clang::CXXRecordDecl &decl, clang::SourceLocation *loc, const cling::Interpreter &interpreter)
Return the class comment after the ClassDef: class MyClass { ... ClassDef(MyClass,...
const T * GetAnnotatedRedeclarable(const T *Redecl)
int extractPropertyNameValFromString(const std::string attributeStr, std::string &attrName, std::string &attrValue)
bool hasOpaqueTypedef(clang::QualType instanceType, const TNormalizedCtxt &normCtxt)
Return true if the type is a Double32_t or Float16_t or is a instance template that depends on Double...
EIOCtorCategory CheckConstructor(const clang::CXXRecordDecl *, const RConstructorType &, const cling::Interpreter &interp)
Check if class has constructor of provided type - either default or with single argument.
clang::RecordDecl * GetUnderlyingRecordDecl(clang::QualType type)
bool BeginsWith(const std::string &theString, const std::string &theSubstring)
bool IsDeclReacheable(const clang::Decl &decl)
Return true if the decl is representing an entity reacheable from the global namespace.
const clang::FunctionDecl * ClassInfo__HasMethod(const clang::DeclContext *cl, char const *, const cling::Interpreter &interp)
bool GetNameWithinNamespace(std::string &, std::string &, std::string &, clang::CXXRecordDecl const *)
Return true if one of the class' enclosing scope is a namespace and set fullname to the fully qualifi...
const clang::RecordDecl * ExtractEnclosingScopes(const clang::Decl &decl, std::list< std::pair< std::string, unsigned int > > &enclosingSc)
Extract the names and types of containing scopes.
bool HasCustomOperatorNewArrayPlacement(clang::RecordDecl const &, const cling::Interpreter &interp)
return true if we can find a custom operator new with placement
void Error(const char *location, const char *fmt,...)
void WriteClassInit(std::ostream &finalString, const AnnotatedRecordDecl &cl, const clang::CXXRecordDecl *decl, const cling::Interpreter &interp, const TNormalizedCtxt &normCtxt, const RConstructorTypes &ctorTypes, bool &needCollectionProxy)
FIXME: a function of 450+ lines!
void Info(const char *location, const char *fmt,...)
int WriteNamespaceHeader(std::ostream &, const clang::RecordDecl *)
int GetClassVersion(const clang::RecordDecl *cl, const cling::Interpreter &interp)
Return the version number of the class or -1 if the function Class_Version does not exist.
clang::QualType GetTypeForIO(const clang::QualType &templateInstanceType, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt, TClassEdit::EModType mode=TClassEdit::kNone)
int extractAttrString(clang::Attr *attribute, std::string &attrString)
Extract attr string.
void GetNormalizedName(std::string &norm_name, const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
Return the type name normalized for ROOT, keeping only the ROOT opaque typedef (Double32_t,...
void WritePointersSTL(const AnnotatedRecordDecl &cl, const cling::Interpreter &interp, const TNormalizedCtxt &normCtxt)
Write interface function for STL members.
bool HasNewMerge(clang::CXXRecordDecl const *, const cling::Interpreter &)
Return true if the class has a method Merge(TCollection*,TFileMergeInfo*)
bool CheckPublicFuncWithProto(clang::CXXRecordDecl const *, char const *, char const *, const cling::Interpreter &, bool diagnose)
Return true, if the function (defined by the name and prototype) exists and is public.
std::string GetFileName(const clang::Decl &decl, const cling::Interpreter &interp)
Return the header file to be included to declare the Decl.
void WriteStandaloneReadRules(std::ostream &finalString, bool rawrules, std::vector< std::string > &standaloneTargets, const cling::Interpreter &interp)
clang::ClassTemplateDecl * QualType2ClassTemplateDecl(const clang::QualType &qt)
Extract from a qualtype the class template if this makes sense.
int IsSTLContainer(const AnnotatedRecordDecl &annotated)
Is this an STL container.
void Fatal(const char *location, const char *fmt,...)
std::list< RConstructorType > RConstructorTypes
int extractPropertyNameVal(clang::Attr *attribute, std::string &attrName, std::string &attrValue)
std::string GetModuleFileName(const char *moduleName)
Return the dictionary file name for a module.
clang::QualType ReSubstTemplateArg(clang::QualType input, const clang::Type *instance)
Check if 'input' or any of its template parameter was substituted when instantiating the class templa...
bool NeedDestructor(clang::CXXRecordDecl const *, const cling::Interpreter &)
bool EndsWith(const std::string &theString, const std::string &theSubstring)
void GetFullyQualifiedTypeName(std::string &name, const clang::QualType &type, const cling::Interpreter &interpreter)
bool NeedTemplateKeyword(clang::CXXRecordDecl const *)
bool HasCustomConvStreamerMemberFunction(const AnnotatedRecordDecl &cl, const clang::CXXRecordDecl *clxx, const cling::Interpreter &interp, const TNormalizedCtxt &normCtxt)
Return true if the class has a custom member function streamer.
bool HasDirectoryAutoAdd(clang::CXXRecordDecl const *, const cling::Interpreter &)
Return true if the class has a method DirectoryAutoAdd(TDirectory *)
const clang::FunctionDecl * GetFuncWithProto(const clang::Decl *cinfo, const char *method, const char *proto, const cling::Interpreter &gInterp, bool diagnose)
int ElementStreamer(std::ostream &finalString, const clang::NamedDecl &forcontext, const clang::QualType &qti, const char *t, int rwmode, const cling::Interpreter &interp, const char *tcl=nullptr)
bool MatchWithDeclOrAnyOfPrevious(const clang::CXXRecordDecl &cl, const clang::CXXRecordDecl &currentCl)
This is a recursive function.
clang::QualType GetNormalizedType(const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
Return the type normalized for ROOT, keeping only the ROOT opaque typedef (Double32_t,...
const char * ShortTypeName(const char *typeDesc)
Return the absolute type of typeDesc.
void GetCppName(std::string &output, const char *input)
Return (in the argument 'output') a valid name of the C++ symbol/type (pass as 'input') that can be u...
bool HasCustomOperatorNewPlacement(char const *, clang::RecordDecl const &, const cling::Interpreter &)
return true if we can find a custom operator new with placement
bool IsStdClass(const clang::RecordDecl &cl)
Return true, if the decl is part of the std namespace.
bool HasResetAfterMerge(clang::CXXRecordDecl const *, const cling::Interpreter &)
Return true if the class has a method ResetAfterMerge(TFileMergeInfo *)
ROOT::ESTLType STLKind(const llvm::StringRef type)
Converts STL container name to number. vector -> 1, etc..
void WriteClassCode(CallWriteStreamer_t WriteStreamerFunc, const AnnotatedRecordDecl &cl, const cling::Interpreter &interp, const TNormalizedCtxt &normCtxt, std::ostream &finalString, const RConstructorTypes &ctorTypes, bool isGenreflex)
Generate the code of the class If the requestor is genreflex, request the new streamer format.
bool HasOldMerge(clang::CXXRecordDecl const *, const cling::Interpreter &)
Return true if the class has a method Merge(TCollection*)
clang::TemplateName ExtractTemplateNameFromQualType(const clang::QualType &qt)
These manipulations are necessary because a template specialisation type does not inherit from a reco...
int RemoveTemplateArgsFromName(std::string &name, unsigned int)
Remove the last n template arguments from the name.
long GetLineNumber(clang::Decl const *)
It looks like the template specialization decl actually contains less information on the location of ...
void WriteAuxFunctions(std::ostream &finalString, const AnnotatedRecordDecl &cl, const clang::CXXRecordDecl *decl, const cling::Interpreter &interp, const RConstructorTypes &ctorTypes, const TNormalizedCtxt &normCtxt)
std::string NormalizedName; GetNormalizedName(NormalizedName, decl->getASTContext()....
void foreachHeaderInModule(const clang::Module &module, const std::function< void(const clang::Module::Header &)> &closure, bool includeDirectlyUsedModules=true)
Calls the given lambda on every header in the given module.
bool IsBase(const clang::CXXRecordDecl *cl, const clang::CXXRecordDecl *base, const clang::CXXRecordDecl *context, const cling::Interpreter &interp)
void ExtractCtxtEnclosingNameSpaces(const clang::DeclContext &, std::list< std::pair< std::string, bool > > &)
Extract enclosing namespaces recursively.
std::pair< bool, int > GetTrivialIntegralReturnValue(const clang::FunctionDecl *funcCV, const cling::Interpreter &interp)
If the function contains 'just': return SomeValue; this routine will extract this value and return it...
bool HasCustomStreamerMemberFunction(const AnnotatedRecordDecl &cl, const clang::CXXRecordDecl *clxx, const cling::Interpreter &interp, const TNormalizedCtxt &normCtxt)
Return true if the class has a custom member function streamer.
std::string GetRealPath(const std::string &path)
clang::QualType AddDefaultParameters(clang::QualType instanceType, const cling::Interpreter &interpret, const TNormalizedCtxt &normCtxt)
Add any unspecified template parameters to the class template instance, mentioned anywhere in the typ...
std::pair< std::string, clang::QualType > GetNameTypeForIO(const clang::QualType &templateInstanceType, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt, TClassEdit::EModType mode=TClassEdit::kNone)
void GetQualifiedName(std::string &qual_name, const clang::QualType &type, const clang::NamedDecl &forcontext)
Main implementation relying on GetFullyQualifiedTypeName All other GetQualifiedName functions leverag...
bool ExtractAttrIntPropertyFromName(const clang::Decl &decl, const std::string &propName, int &propValue)
This routine counts on the "propName<separator>propValue" format.
bool IsLinkdefFile(const char *filename)
void WriteRulesRegistration(std::ostream &finalString, const std::string &dictName, const std::vector< std::string > &standaloneTargets)
llvm::StringRef GetComment(const clang::Decl &decl, clang::SourceLocation *loc=nullptr)
Returns the comment (// striped away), annotating declaration in a meaningful for ROOT IO way.
void SetPathsForRelocatability(std::vector< std::string > &clingArgs)
Organise the parameters for cling in order to guarantee relocatability It treats the gcc toolchain an...
bool IsStreamableObject(const clang::FieldDecl &m, const cling::Interpreter &interp)
void ReplaceAll(std::string &str, const std::string &from, const std::string &to, bool recurse=false)
bool QualType2Template(const clang::QualType &qt, clang::ClassTemplateDecl *&ctd, clang::ClassTemplateSpecializationDecl *&ctsd)
Get the template specialisation decl and template decl behind the qualtype Returns true if successful...
std::string TrueName(const clang::FieldDecl &m)
TrueName strips the typedefs and array dimensions.
const clang::Type * GetUnderlyingType(clang::QualType type)
Return the base/underlying type of a chain of array or pointers type.
ROOT::ESTLType IsSTLCont(const clang::RecordDecl &cl)
type : type name: vector<list<classA,allocator>,allocator> result: 0 : not stl container abs(result):...
bool IsStdDropDefaultClass(const clang::RecordDecl &cl)
Return true, if the decl is part of the std namespace and we want its default parameter dropped.
bool RequireCompleteType(const cling::Interpreter &interp, const clang::CXXRecordDecl *cl)
bool IsHeaderName(const std::string &filename)
void Warning(const char *location, const char *fmt,...)
bool IsCtxtReacheable(const clang::DeclContext &ctxt)
Return true if the DeclContext is representing an entity reacheable from the global namespace.
bool IsOfType(const clang::CXXRecordDecl &cl, const std::string &type, const cling::LookupHelper &lh)
const std::string & GetPathSeparator()
Return the separator suitable for this platform.
bool CheckDefaultConstructor(const clang::CXXRecordDecl *, const cling::Interpreter &interp)
Checks if default constructor exists and accessible.
EIOCtorCategory CheckIOConstructor(const clang::CXXRecordDecl *, const char *, const clang::CXXRecordDecl *, const cling::Interpreter &interp)
Checks IO constructor - must be public and with specified argument.
bool ExtractAttrPropertyFromName(const clang::Decl &decl, const std::string &propName, std::string &propValue)
This routine counts on the "propName<separator>propValue" format.
const clang::CXXRecordDecl * ScopeSearch(const char *name, const cling::Interpreter &gInterp, bool diagnose, const clang::Type **resultType)
Return the scope corresponding to 'name' or std::'name'.
int & GetErrorIgnoreLevel()
void ExtractEnclosingNameSpaces(const clang::Decl &, std::list< std::pair< std::string, bool > > &)
Extract the immediately outer namespace and then launch the recursion.
bool HasIOConstructor(clang::CXXRecordDecl const *, std::string &, const RConstructorTypes &, const cling::Interpreter &)
return true if we can find an constructor calleable without any arguments or with one the IOCtor spec...
llvm::StringRef DataMemberInfo__ValidArrayIndex(const cling::Interpreter &interp, const clang::DeclaratorDecl &m, int *errnum=nullptr, llvm::StringRef *errstr=nullptr)
ValidArrayIndex return a static string (so use it or copy it immediatly, do not call GrabIndex twice ...
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
void WriteSchemaList(std::list< SchemaRuleMap_t > &rules, const std::string &listName, std::ostream &output)
Write schema rules.
std::map< std::string, ROOT::Internal::TSchemaType > MembersTypeMap_t
ESTLType
Definition ESTLType.h:28
@ kSTLbitset
Definition ESTLType.h:37
@ kSTLmap
Definition ESTLType.h:33
@ kSTLunorderedmultiset
Definition ESTLType.h:43
@ kROOTRVec
Definition ESTLType.h:46
@ kSTLend
Definition ESTLType.h:47
@ kSTLset
Definition ESTLType.h:35
@ kSTLmultiset
Definition ESTLType.h:36
@ kSTLdeque
Definition ESTLType.h:32
@ kSTLvector
Definition ESTLType.h:30
@ kSTLunorderedmultimap
Definition ESTLType.h:45
@ kSTLunorderedset
Definition ESTLType.h:42
@ kSTLlist
Definition ESTLType.h:31
@ kSTLforwardlist
Definition ESTLType.h:41
@ kSTLunorderedmap
Definition ESTLType.h:44
@ kNotSTL
Definition ESTLType.h:29
@ kSTLmultimap
Definition ESTLType.h:34
void WriteReadRuleFunc(SchemaRuleMap_t &rule, int index, std::string &mappedName, MembersTypeMap_t &members, std::ostream &output)
Write the conversion function for Read rule, the function name is being written to rule["funcname"].
R__EXTERN SchemaRuleClassMap_t gReadRules
bool HasValidDataMembers(SchemaRuleMap_t &rule, MembersTypeMap_t &members, std::string &error_string)
Check if given rule contains references to valid data members.
void WriteReadRawRuleFunc(SchemaRuleMap_t &rule, int index, std::string &mappedName, MembersTypeMap_t &members, std::ostream &output)
Write the conversion function for ReadRaw rule, the function name is being written to rule["funcname"...
R__EXTERN SchemaRuleClassMap_t gReadRawRules
ROOT::ESTLType STLKind(std::string_view type)
Converts STL container name to number.
bool IsStdClass(const char *type)
return true if the class belongs to the std namespace
std::string GetLong64_Name(const char *original)
Replace 'long long' and 'unsigned long long' by 'Long64_t' and 'ULong64_t'.
ROOT::ESTLType IsSTLCont(std::string_view type)
type : type name: vector<list<classA,allocator>,allocator> result: 0 : not stl container code of cont...
char * DemangleName(const char *mangled_name, int &errorCode)
Definition TClassEdit.h:208
std::string GetNameForIO(const std::string &templateInstanceName, TClassEdit::EModType mode=TClassEdit::kNone, bool *hasChanged=nullptr)
void GetNormalizedName(std::string &norm_name, std::string_view name)
Return the normalized name.
@ kKeepOuterConst
Definition TClassEdit.h:87
@ kDropStlDefault
Definition TClassEdit.h:82
bool IsSTLBitset(const char *type)
Return true is the name is std::bitset<number> or bitset<number>
constexpr Double_t C()
Velocity of light in .
Definition TMath.h:114
static const char * what
Definition stlLoader.cc:5
TMarker m
Definition textangle.C:8
auto * tt
Definition textangle.C:16