63#include "RConfigure.h"
64#include "compiledata.h"
83#include "clang/AST/ASTContext.h"
84#include "clang/AST/Decl.h"
85#include "clang/AST/DeclarationName.h"
86#include "clang/AST/GlobalDecl.h"
87#include "clang/AST/RecordLayout.h"
88#include "clang/AST/DeclVisitor.h"
89#include "clang/AST/RecursiveASTVisitor.h"
90#include "clang/AST/Type.h"
91#include "clang/Basic/SourceLocation.h"
92#include "clang/Basic/Specifiers.h"
93#include "clang/Basic/TargetInfo.h"
94#include "clang/CodeGen/ModuleBuilder.h"
95#include "clang/Frontend/CompilerInstance.h"
96#include "clang/Frontend/FrontendDiagnostic.h"
97#include "clang/Lex/HeaderSearch.h"
98#include "clang/Lex/Preprocessor.h"
99#include "clang/Lex/PreprocessorOptions.h"
100#include "clang/Parse/Parser.h"
101#include "clang/Sema/Lookup.h"
102#include "clang/Sema/Sema.h"
103#include "clang/Serialization/ASTReader.h"
104#include "clang/Serialization/GlobalModuleIndex.h"
106#include "cling/Interpreter/ClangInternalState.h"
107#include "cling/Interpreter/DynamicLibraryManager.h"
108#include "cling/Interpreter/Interpreter.h"
109#include "cling/Interpreter/LookupHelper.h"
110#include "cling/Interpreter/Value.h"
111#include "cling/Interpreter/Transaction.h"
112#include "cling/MetaProcessor/MetaProcessor.h"
113#include "cling/Utils/AST.h"
114#include "cling/Utils/ParserStateRAII.h"
115#include "cling/Utils/SourceNormalization.h"
116#include "cling/Interpreter/Exception.h"
118#include "llvm/IR/GlobalValue.h"
119#include "llvm/IR/Module.h"
121#include "llvm/Support/DynamicLibrary.h"
122#include "llvm/Support/raw_ostream.h"
123#include "llvm/Support/Path.h"
124#include "llvm/Support/Process.h"
125#include "llvm/Object/ELFObjectFile.h"
126#include "llvm/Object/ObjectFile.h"
127#include "llvm/Object/SymbolicFile.h"
128#include "llvm/Support/FileSystem.h"
142#include <unordered_map>
143#include <unordered_set>
151#define R__DLLEXPORT __attribute__ ((visibility ("default")))
159#include <mach-o/dyld.h>
160#include <mach-o/loader.h>
167#if defined(R__LINUX) || defined(R__FBSD)
174#if defined(__CYGWIN__)
175#include <sys/cygwin.h>
176#define HMODULE void *
178 __declspec(dllimport)
void * __stdcall GetCurrentProcess();
179 __declspec(dllimport)
bool __stdcall EnumProcessModules(
void *,
void **,
unsigned long,
unsigned long *);
180 __declspec(dllimport)
unsigned long __stdcall GetModuleFileNameExW(
void *,
void *,
wchar_t *,
unsigned long);
187# define STDIN_FILENO 0
190# define STDOUT_FILENO 1
193# define STDERR_FILENO 2
203#undef GetModuleFileName
204#define RTLD_DEFAULT ((void *)::GetModuleHandle(NULL))
205#define dlsym(library, function_name) ::GetProcAddress((HMODULE)library, function_name)
206#define dlopen(library_name, flags) ::LoadLibraryA(library_name)
207#define dlclose(library) ::FreeLibrary((HMODULE)library)
208#define R__DLLEXPORT __declspec(dllexport)
216 return D->getDeclContext();
219 return llvm::dyn_cast<clang::NamespaceDecl>(DC);
222 return llvm::dyn_cast<clang::RecordDecl>(DC);
225 return DC->dumpDeclContext();
234 return ((clang::Decl*)D)->dump();
237 if (clang::NamedDecl* ND = llvm::dyn_cast<clang::NamedDecl>(D)) {
240 llvm::raw_string_ostream OS(
name);
241 ND->getNameForDiagnostic(OS, D->getASTContext().getPrintingPolicy(),
244 printf(
"%s\n",
name.c_str());
252 return D->isInvalidDecl();
256 assert(info && info->
IsValid());
257 return info->
GetDecl()->isInvalidDecl();
260using std::string, std::vector;
261using namespace clang;
265 static const std::string gInterpreterClassDef = R
"ICF(
267#define ClassDef(name, id) \
268_ClassDefInterp_(name,id,virtual,) \
269static int DeclFileLine() { return __LINE__; }
271#define ClassDefNV(name, id) \
272_ClassDefInterp_(name,id,,) \
273static int DeclFileLine() { return __LINE__; }
274#undef ClassDefOverride
275#define ClassDefOverride(name, id) \
276_ClassDefInterp_(name,id,,override) \
277static int DeclFileLine() { return __LINE__; }
280 static const std::string gNonInterpreterClassDef = R
"ICF(
281#define __ROOTCLING__ 1
283#define ClassDef(name,id) \
284_ClassDefOutline_(name,id,virtual,) \
285static int DeclFileLine() { return __LINE__; }
287#define ClassDefNV(name, id)\
288_ClassDefOutline_(name,id,,)\
289static int DeclFileLine() { return __LINE__; }
290#undef ClassDefOverride
291#define ClassDefOverride(name, id)\
292_ClassDefOutline_(name,id,,override)\
293static int DeclFileLine() { return __LINE__; }
297 static const std::string gClassDefInterpMacro = R
"ICF(
300#define _ClassDefInterp_(name,id,virtual_keyword, overrd) \
303 static TClass *Class() { static TClass* sIsA = 0; if (!sIsA) sIsA = TClass::GetClass(#name); return sIsA; } \
304 static const char *Class_Name() { return #name; } \
305 virtual_keyword Bool_t CheckTObjectHashConsistency() const overrd { return true; } \
306 static Version_t Class_Version() { return id; } \
307 static TClass *Dictionary() { return 0; } \
308 virtual_keyword TClass *IsA() const overrd { return name::Class(); } \
309 virtual_keyword void ShowMembers(TMemberInspector&insp) const overrd { ::ROOT::Class_ShowMembers(name::Class(), this, insp); } \
310 virtual_keyword void Streamer(TBuffer&) overrd { ::Error("Streamer", "Cannot stream interpreted class."); } \
311 void StreamerNVirtual(TBuffer&ClassDef_StreamerNVirtual_b) { name::Streamer(ClassDef_StreamerNVirtual_b); } \
312 static const char *DeclFileName() { return __FILE__; } \
313 static int ImplFileLine() { return 0; } \
314 static const char *ImplFileName() { return __FILE__; }
353 return ((
TCling*)
gCling)->LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
392 static vector<const NamedDecl*> updateList;
395 if (entered) topLevel =
kFALSE;
410 updateList.push_back(TD);
413 while (!updateList.empty()) {
415 updateList.pop_back();
422 const clang::Decl* D =
static_cast<const clang::Decl*
>(enumObj->
GetDeclId());
423 if(
const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
425 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
426 EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
428 std::string constbuf;
429 if (
const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
430 PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
431 llvm::raw_string_ostream stream(constbuf);
433 Policy.AnonymousTagLocations =
false;
434 (END)->getNameForDiagnostic(stream, Policy,
false);
436 const char* constantName = constbuf.c_str();
440 const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
441 if (valAPSInt.isSigned()) {
442 value = valAPSInt.getSExtValue();
444 value = valAPSInt.getZExtValue();
451 DataMemberInfo_t* dmInfo = (DataMemberInfo_t*) tcDmInfo;
462 globals->
Add(enumConstant);
474 TEnum* enumType =
nullptr;
475 const clang::Decl* D =
static_cast<const clang::Decl*
>(VD);
477 if (
const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
479 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
480 llvm::raw_string_ostream stream(buf);
482 Policy.AnonymousTagLocations =
false;
483 ED->getNameForDiagnostic(stream, Policy,
false);
489 const char*
name = buf.c_str();
500 const clang::Decl* D =
static_cast<const clang::Decl*
>(DV);
502 if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
503 && !dyn_cast<clang::RecordDecl>(D))
return;
505 if (isa<clang::FunctionDecl>(D->getDeclContext())
506 || isa<clang::TagDecl>(D->getDeclContext()))
510 if (
const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
511 if (RD->getDescribedClassTemplate())
513 }
else if (
const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
514 if (FD->getDescribedFunctionTemplate())
518 if (
const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
519 if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
522 else if (
const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
524 if (
const TagDecl *TD = dyn_cast<TagDecl>(D)) {
528 }
else if (
const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
533 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
537 if (isa<EnumDecl>(ND))
542 if (!(isa<VarDecl>(ND)))
546 if (
gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
550 gROOT->GetListOfGlobals()->Add(
new TGlobal((DataMemberInfo_t *)
552 cast<ValueDecl>(ND),
nullptr)));
584 const char* canonicalName) {
585 ((
TCling*)
gCling)->LibraryLoaded(dyLibHandle, canonicalName);
590 ((
TCling *)
gCling)->RegisterRdictForLoadPCM(pcmFileNameFullPath, pcmContent);
594 const char* canonicalName) {
595 ((
TCling*)
gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
601 return ((
TCling*)
gCling)->GetObjectAddress(Name, LookupCtx);
611 auto tcling =
new TCling(
"C++",
"cling C++ Interpreter", argv, interpLibHandle);
635 return ((
TCling*)
gCling)->GetClassSharedLibs(className, skipCore);
641 return ((
TCling*)
gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
646 string file(fileName);
652 string &args,
string &io,
string &fname)
654 string file(fileName);
655 TString f, amode, arguments, aclicio;
658 io = aclicio.
Data(); fname =
f.Data();
668 char *__unDName(
char *demangled,
const char *mangled,
int out_len,
669 void * (* pAlloc )(
size_t),
void (* pFree )(
void *),
670 unsigned short int flags);
682 using namespace clang;
683 if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
687 if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
700 const std::vector<std::string> &headers,
701 const std::vector<std::string> &fwdDecls,
702 const std::vector<std::string> &unknown)
708 if (classes.empty()) {
712 const std::string& className = classes[0];
714 TString fileName =
"AutoDict_";
715 std::string::const_iterator sIt;
716 for (sIt = className.begin(); sIt != className.end(); ++sIt) {
717 if (*sIt ==
'<' || *sIt ==
'>' ||
718 *sIt ==
' ' || *sIt ==
'*' ||
719 *sIt ==
',' || *sIt ==
'&' ||
727 if (classes.size() > 1) {
729 std::vector<std::string>::const_iterator it = classes.begin();
730 while ((++it) != classes.end()) {
732 chk = chk * 3 + it->at(
cursor);
745 static const std::set<std::string> sSTLTypes {
746 "vector",
"list",
"forward_list",
"deque",
"map",
"unordered_map",
"multimap",
747 "unordered_multimap",
"set",
"unordered_set",
"multiset",
"unordered_multiset",
748 "queue",
"priority_queue",
"stack",
"iterator"};
749 std::vector<std::string>::const_iterator it;
750 std::string fileContent(
"");
751 for (it = headers.begin(); it != headers.end(); ++it) {
752 fileContent +=
"#include \"" + *it +
"\"\n";
754 for (it = unknown.begin(); it != unknown.end(); ++it) {
760 while (dirbase.
Length() && dirbase !=
"."
761 && dirbase !=
"include" && dirbase !=
"inc"
762 && dirbase !=
"prec_stl") {
766 fileContent +=
TString(
"#include \"") + header +
"\"\n";
769 for (it = fwdDecls.begin(); it != fwdDecls.end(); ++it) {
770 fileContent +=
"class " + *it +
";\n";
772 fileContent +=
"#ifdef __CLING__ \n";
773 fileContent +=
"#pragma link C++ nestedclasses;\n";
774 fileContent +=
"#pragma link C++ nestedtypedefs;\n";
775 for (it = classes.begin(); it != classes.end(); ++it) {
777 size_t posTemplate =
n.find(
'<');
778 std::set<std::string>::const_iterator iSTLType = sSTLTypes.end();
779 if (posTemplate != std::string::npos) {
780 n.erase(posTemplate, std::string::npos);
781 if (
n.compare(0, 5,
"std::") == 0) {
784 iSTLType = sSTLTypes.find(
n);
786 fileContent +=
"#pragma link C++ class ";
787 fileContent += *it +
"+;\n" ;
788 if (iSTLType == sSTLTypes.end()) {
791 fileContent +=
"#pragma link C++ class " + *it +
"::*+;\n" ;
794 fileContent +=
"#endif\n";
798 filePointer = fopen(fileName,
"w");
799 if (filePointer ==
nullptr) {
805 fprintf(filePointer,
"%s", fileContent.c_str());
821 const std::vector<std::string> &headers,
822 const std::vector<std::string> &fwdDecls,
823 const std::vector<std::string> &unknown)
829 std::vector<std::string> classes;
830 classes.push_back(className);
858 void exceptionErrorHandler(
void * ,
861 throw std::runtime_error(std::string(
">>> Interpreter compilation error:\n") + reason);
875 class clangDiagSuppr {
877 clangDiagSuppr(clang::DiagnosticsEngine& diag): fDiagEngine(diag){
878 fOldDiagValue = fDiagEngine.getIgnoreAllWarnings();
879 fDiagEngine.setIgnoreAllWarnings(
true);
883 fDiagEngine.setIgnoreAllWarnings(fOldDiagValue);
886 clang::DiagnosticsEngine& fDiagEngine;
909 if (strncmp(tname.c_str(),
"const ", 6) == 0) {
912 unsigned long end = tname.length();
913 while( end && (tname[end-1]==
'&' || tname[end-1]==
'*' || tname[end-1]==
']') ) {
914 if ( tname[end-1]==
']' ) {
916 while ( end && tname[end-1]!=
'[' ) --end;
920 std::string innerbuf;
922 if (end != tname.length()) {
924 inner = innerbuf.c_str();
926 inner = tname.c_str()+
offset;
930 if (
gROOT->GetListOfClasses()->FindObject(inner)
940 const char *newname =
type->GetFullTypeName();
942 newname =
"Long64_t";
944 newname =
"ULong64_t";
946 if (strcmp(inner,newname) == 0) {
951 if ( end != tname.length() ) {
952 result += tname.substr(end,tname.length()-end);
960 if (lastPos != inner)
964 const auto enName = lastPos;
965 const auto scopeNameSize = ((
Long64_t)lastPos - (
Long64_t)inner) /
sizeof(
decltype(*lastPos)) - 2;
966 char *scopeName =
new char[scopeNameSize + 1];
967 strncpy(scopeName, inner, scopeNameSize);
968 scopeName[scopeNameSize] =
'\0';
970 if (
auto scope =
static_cast<TClass *
>(
gROOT->GetListOfClasses()->FindObject(scopeName))) {
971 auto enumTable =
dynamic_cast<const THashList *
>(scope->GetListOfEnums(
false));
972 if (enumTable && enumTable->THashList::FindObject(enName)) {
delete [] scopeName;
return true; }
976 auto listOfEnums = scope->GetListOfEnums();
978 auto enumTable =
dynamic_cast<const THashList *
>(listOfEnums);
979 if (enumTable && enumTable->THashList::FindObject(enName)) {
delete [] scopeName;
return true; }
986 auto enumTable =
dynamic_cast<const THashList *
>(
gROOT->GetListOfEnums());
987 if (enumTable && enumTable->THashList::FindObject(inner))
return true;
1010 return fContent.c_str();
1018 bool notPresent = fLinesHashSet.emplace(fHashFunc(str)).second;
1032static bool LoadModule(
const std::string &ModuleName, cling::Interpreter &interp)
1042 assert(!currentDir.empty());
1045 ::Info(
"TCling::__LoadModule",
"Preloading module %s. \n",
1046 ModuleName.c_str());
1048 return interp.loadModule(ModuleName,
true);
1054static void LoadModules(
const std::vector<std::string> &modules, cling::Interpreter &interp)
1056 for (
const auto &modName : modules)
1062 const static bool foundSymbol = dlsym(RTLD_DEFAULT,
"usedToIdentifyRootClingByDlSym");
1067static bool HasASTFileOnDisk(clang::Module *M,
const clang::Preprocessor &PP, std::string *FullFileName =
nullptr)
1069 const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1071 std::string ModuleFileName;
1072 if (!HSOpts.PrebuiltModulePaths.empty())
1074 ModuleFileName = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(M->Name);
1076 *FullFileName = ModuleFileName;
1078 return !ModuleFileName.empty();
1084 CompilerInstance &CI = *interp.getCI();
1085 Preprocessor &PP = CI.getPreprocessor();
1086 auto ModuleManager = CI.getASTReader();
1087 assert(ModuleManager);
1092 if (ModuleIndexPath.empty())
1095 ModuleManager->resetForReload();
1096 ModuleManager->loadGlobalIndex();
1097 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1102 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1103 bool RecreateIndex =
false;
1104 for (ModuleMap::module_iterator
I = MMap.module_begin(), E = MMap.module_end();
I != E; ++
I) {
1105 Module *TheModule =
I->second;
1110 RecreateIndex =
true;
1112 if (RecreateIndex) {
1113 cling::Interpreter::PushTransactionRAII deserRAII(&interp);
1114 clang::GlobalModuleIndex::UserDefinedInterestingIDs IDs;
1116 struct DefinitionFinder :
public RecursiveASTVisitor<DefinitionFinder> {
1117 DefinitionFinder(clang::GlobalModuleIndex::UserDefinedInterestingIDs& IDs,
1118 clang::TranslationUnitDecl* TU) : DefinitionIDs(IDs) {
1121 bool VisitNamedDecl(NamedDecl *ND) {
1122 if (!ND->isFromASTFile())
1124 if (!ND->getIdentifier())
1127 if (ND->getAccess() == AS_protected || ND->getAccess() == AS_private)
1130 if (TagDecl *TD = llvm::dyn_cast<TagDecl>(ND)) {
1131 if (TD->isCompleteDefinition())
1133 }
else if (NamespaceDecl *NSD = llvm::dyn_cast<NamespaceDecl>(ND)) {
1134 Register(NSD,
false);
1136 else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(ND))
1142 clang::GlobalModuleIndex::UserDefinedInterestingIDs &DefinitionIDs;
1143 void Register(
const NamedDecl* ND,
bool AddSingleEntry =
true) {
1144 assert(ND->isFromASTFile());
1147 if (!ND->hasOwningModule()) {
1149 SourceManager &SM = ND->getASTContext().getSourceManager();
1150 SourceLocation Loc = ND->getLocation();
1151 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
1153 assert(FE->getName().contains(
"input_line_"));
1158 Module *OwningModule = ND->getOwningModule()->getTopLevelModule();
1159 assert(OwningModule);
1160 assert(!ND->getName().empty() &&
"Empty name");
1161 if (AddSingleEntry && DefinitionIDs.count(ND->getName()))
1167 DefinitionIDs[ND->getName()].push_back(OwningModule->getASTFile());
1170 DefinitionFinder defFinder(IDs, CI.getASTContext().getTranslationUnitDecl());
1172 llvm::cantFail(GlobalModuleIndex::writeIndex(CI.getFileManager(),
1173 CI.getPCHContainerReader(),
1176 ModuleManager->resetForReload();
1177 ModuleManager->loadGlobalIndex();
1178 GlobalIndex = ModuleManager->getGlobalIndex();
1187 if (!clingInterp.getCI()->getLangOpts().Modules)
1191 cling::Interpreter::PushTransactionRAII deserRAII(&clingInterp);
1209 LoadModule(
"_Builtin_intrinsics", clingInterp);
1213 std::vector<std::string> CoreModules = {
"ROOT_Foundation_C",
1216 "ROOT_Foundation_Stage1_NoRTTI",
1225 std::vector<std::string> CommonModules = {
"MathCore"};
1231 std::vector<std::string> FIXMEModules = {
"Hist"};
1232 clang::CompilerInstance &CI = *clingInterp.getCI();
1233 clang::Preprocessor &PP = CI.getPreprocessor();
1234 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1235 if (MMap.findModule(
"RInterface"))
1236 FIXMEModules.push_back(
"RInterface");
1240 GlobalModuleIndex *GlobalIndex =
nullptr;
1244 GlobalIndex = CI.getASTReader()->getGlobalIndex();
1246 llvm::StringSet<> KnownModuleFileNames;
1248 GlobalIndex->getKnownModuleFileNames(KnownModuleFileNames);
1250 std::vector<std::string> PendingModules;
1251 PendingModules.reserve(256);
1252 for (
auto I = MMap.module_begin(), E = MMap.module_end();
I != E; ++
I) {
1253 clang::Module *M =
I->second;
1257 std::string FullASTFilePath;
1261 if (GlobalIndex && KnownModuleFileNames.count(FullASTFilePath))
1264 if (M->IsUnimportable)
1272 if (std::find(CoreModules.begin(), CoreModules.end(), M->Name) != CoreModules.end())
1280 PendingModules.push_back(M->Name);
1287 assert(clingInterp.getMacro(
"gROOT") &&
"Couldn't load gROOT macro?");
1291 clingInterp.declare(R
"CODE(
1303 std::string PreIncludes;
1304 bool hasCxxModules = clingInterp.getCI()->getLangOpts().Modules;
1310 PreIncludes +=
"#include \"RtypesCore.h\"\n";
1313 PreIncludes +=
"#include \"Rtypes.h\"\n";
1315 PreIncludes += gClassDefInterpMacro +
"\n"
1316 + gInterpreterClassDef +
"\n"
1318 "#define ClassImp(X);\n";
1321 PreIncludes +=
"#include <string>\n";
1326 PreIncludes +=
"#include <cassert>\n";
1328 PreIncludes +=
"using namespace std;\n";
1329 clingInterp.declare(PreIncludes);
1349#ifdef R__USE_CXXMODULES
1353 llvm::install_fatal_error_handler(&exceptionErrorHandler);
1357 std::vector<std::string> clingArgsStorage;
1358 clingArgsStorage.push_back(
"cling4root");
1359 for (
const char*
const* arg = argv; *arg; ++arg)
1360 clingArgsStorage.push_back(*arg);
1363 if (!fromRootCling) {
1368 clingArgsStorage.push_back(
"-I" + interpInclude);
1371 clingArgsStorage.push_back(
"-I" + interpInclude +
"/cling");
1374 clingArgsStorage.push_back(
"-I" + interpInclude +
"/cling/plugins/include");
1385 std::string pchFilename = interpInclude +
"/allDict.cxx.pch";
1390 clingArgsStorage.push_back(
"-include-pch");
1391 clingArgsStorage.push_back(pchFilename);
1394 clingArgsStorage.push_back(
"-Wno-undefined-inline");
1395 clingArgsStorage.push_back(
"-fsigned-char");
1400 clingArgsStorage.push_back(
"-O1");
1403 clingArgsStorage.push_back(
"-mllvm");
1404 clingArgsStorage.push_back(
"-optimize-regalloc=0");
1409 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(
"EXTRA_CLING_ARGS");
1410 if (EnvOpt.has_value()) {
1411 StringRef Env(*EnvOpt);
1412 while (!Env.empty()) {
1414 std::tie(Arg, Env) = Env.split(
' ');
1415 clingArgsStorage.push_back(Arg.str());
1419 auto GetEnvVarPath = [](
const std::string &EnvVar, std::vector<std::string> &Paths) {
1420 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1421 if (EnvOpt.has_value()) {
1422 StringRef Env(*EnvOpt);
1423 while (!Env.empty()) {
1426 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1427 Paths.push_back(Arg.str());
1433 std::vector<std::string> Paths;
1438 GetEnvVarPath(
"CLING_PREBUILT_MODULE_PATH", Paths);
1439 std::string EnvVarPath;
1440 for (
const std::string& P : Paths)
1443 gSystem->
Setenv(
"CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1447 EnvOpt = llvm::sys::Process::GetEnv(
"ROOT_CLING_TIMING");
1448 if (EnvOpt.has_value())
1449 clingArgsStorage.push_back(
"-ftime-report");
1456 std::vector<std::string> ModuleMaps;
1459 GetEnvVarPath(
"CLING_MODULEMAP_FILES", ModuleMaps);
1463 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1464 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1466 for (
const std::string& M : ModuleMaps)
1467 clingArgsStorage.push_back(
"-fmodule-map-file=" + M);
1469 std::string ModulesCachePath;
1470 EnvOpt = llvm::sys::Process::GetEnv(
"CLING_MODULES_CACHE_PATH");
1471 if (EnvOpt.has_value()){
1472 StringRef Env(*EnvOpt);
1473 assert(llvm::sys::fs::exists(Env) &&
"Path does not exist!");
1474 ModulesCachePath = Env.str();
1479 clingArgsStorage.push_back(
"-fmodules-cache-path=" + ModulesCachePath);
1482 std::vector<const char*> interpArgs;
1483 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1484 eArg = clingArgsStorage.end(); iArg != eArg; ++iArg)
1485 interpArgs.push_back(iArg->c_str());
1492 if (!fromRootCling) {
1494 interpArgs.push_back(
"-fmodules");
1495 interpArgs.push_back(
"-fno-implicit-module-maps");
1499 interpArgs.push_back(
"-Rmodule-build");
1505 interpArgs.push_back(
"-fno-autolink");
1510 interpArgs.push_back(
"-ffast-math");
1516 extraArgs && *extraArgs; ++extraArgs) {
1517 if (!strcmp(*extraArgs,
"-resource-dir")) {
1519 llvmResourceDir = *(++extraArgs);
1521 interpArgs.push_back(*extraArgs);
1525 std::vector<std::string> _empty;
1527 for (
const auto &arg: args)
1528 interpArgs.emplace_back(arg.c_str());
1531 cling::Interpreter::ModuleFileExtensions extensions;
1532 EnvOpt = llvm::sys::Process::GetEnv(
"ROOTDEBUG_RDICT");
1533 if (!EnvOpt.has_value())
1534 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1536 fInterpreter = std::make_unique<cling::Interpreter>(interpArgs.size(),
1538 llvmResourceDir, extensions,
1542 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHOrModuleValidation =
1543 DisableValidationForModuleKind::All;
1547 fInterpreter->getCI()->getLangOpts().SpellChecking =
false;
1550 auto isModulesArg = [](
const char* arg) {
return !strcmp(arg,
"-fmodules"); };
1551 bool hasModulesArg = std::find_if(interpArgs.begin(), interpArgs.end(), isModulesArg) != interpArgs.end();
1552 fInterpreter->getCI()->getLangOpts().Modules = hasModulesArg;
1557 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO,
false);
1577 if (!fromRootCling) {
1582 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1583 auto &Policy =
const_cast<clang::PrintingPolicy &
>(
fInterpreter->getCI()->getASTContext().getPrintingPolicy());
1587 Policy.SplitTemplateClosers =
true;
1589 Policy.SuppressDefaultTemplateArgs =
false;
1595 std::unique_ptr<TClingCallbacks>
1601 if (!fromRootCling) {
1602 cling::DynamicLibraryManager& DLM = *
fInterpreter->getDynamicLibraryManager();
1607 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) ->
bool{
1608 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1609 return stem.startswith(
"libNew") || stem.startswith(
"libcppyy_backend");
1612 DLM.initializeDyld(ShouldPermanentlyIgnore);
1650 assert(
GetRootMapFiles() ==
nullptr &&
"Must be called before LoadLibraryMap!");
1669 auto setFactory = []() {
1673 static bool doneFactory = setFactory();
1685 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1686 ::Error(
"TCling::RegisterRdictForLoadPCM",
"Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1703 if (listOfKeys && ((listOfKeys->GetSize() == 0) ||
1704 ((listOfKeys->GetSize() == 1) &&
1705 !strcmp(((
TKey *)listOfKeys->At(0))->GetName(),
"EMPTY")
1712 ::Info(
"TCling::LoadPCMImpl",
"reading protoclasses for %s \n", pcmFile.
GetName());
1718 auto listOfGlobals =
gROOT->GetListOfGlobals();
1719 auto listOfEnums =
dynamic_cast<THashList *
>(
gROOT->GetListOfEnums());
1721 for (
auto selEnum : *enums) {
1722 const char *enumScope = selEnum->
GetTitle();
1723 const char *enumName = selEnum->GetName();
1724 if (strcmp(enumScope,
"") == 0) {
1727 if (!listOfEnums->THashList::FindObject(enumName)) {
1728 ((
TEnum *)selEnum)->SetClass(
nullptr);
1729 listOfEnums->Add(selEnum);
1731 for (
auto enumConstant : *
static_cast<TEnum *
>(selEnum)->GetConstants()) {
1732 if (!listOfGlobals->FindObject(enumConstant)) {
1733 listOfGlobals->Add(enumConstant);
1740 if (!nsTClassEntry) {
1743 auto listOfEnums = nsTClassEntry->
fEnums.load();
1754 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1755 ((
TEnum *)selEnum)->SetClass(nsTClassEntry);
1756 listOfEnums->Add(selEnum);
1764 pcmFile.
GetObject(
"__ProtoClasses", protoClasses);
1767 for (
auto obj : *protoClasses) {
1777 for (
auto proto : *protoClasses) {
1785 ::Error(
"TCling::LoadPCM",
"Inconsistent TClassTable for %s",
proto->GetName());
1796 protoClasses->
Clear();
1797 delete protoClasses;
1801 pcmFile.
GetObject(
"__Typedefs", dataTypes);
1803 for (
auto typedf : *dataTypes)
1804 gROOT->GetListOfTypes()->Add(typedf);
1817 assert(!pcmFileNameFullPath.empty());
1818 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1821 TString pcmFileName = pcmFileNameFullPath;
1829 llvm::SaveAndRestore<Int_t> SaveGDebug(
gDebug);
1832 ::Info(
"TCling::LoadPCM",
"Loading ROOT PCM %s", pcmFileName.
Data());
1837 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1842 llvm::StringRef pcmContent = pendingRdict->second;
1844 std::string RDictFileOpts = pcmFileNameFullPath +
"?filetype=pcm";
1845 TMemFile pcmMemFile(RDictFileOpts.c_str(), range);
1860 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1861 ::Error(
"TCling::LoadPCM",
"ROOT PCM %s file does not exist",
1862 pcmFileNameFullPath.data());
1865 ::Info(
"TCling::LoadPCM",
"In-memory ROOT PCM candidate %s\n",
1866 rdict.first.c_str());
1870 if (!
gROOT->IsRootFile(pcmFileName)) {
1871 Fatal(
"LoadPCM",
"The file %s is not a ROOT as was expected\n", pcmFileName.
Data());
1874 TFile pcmFile(pcmFileName +
"?filetype=pcm",
"READ");
1881 using namespace clang;
1883 class ExtLexicalStorageAdder:
public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1888 bool VisitRecordDecl(clang::RecordDecl* rcd){
1890 Info(
"ExtLexicalStorageAdder",
1891 "Adding external lexical storage to class %s",
1892 rcd->getNameAsString().c_str());
1893 auto reDeclPtr = rcd->getMostRecentDecl();
1895 reDeclPtr->setHasExternalLexicalStorage();
1896 }
while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1909 const std::string &ModuleMapName )
const
1911 assert(llvm::sys::path::is_absolute(FullPath));
1912 Preprocessor &PP =
fInterpreter->getCI()->getPreprocessor();
1913 FileManager &FM = PP.getFileManager();
1916 if (
auto DE = FM.getOptionalDirectoryRef(FullPath)) {
1917 HeaderSearch &HS = PP.getHeaderSearchInfo();
1918 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1919 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1920 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1922 HSOpts.AddPrebuiltModulePath(FullPath);
1927 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1928 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1929 if (
auto FE = FM.getOptionalFileRef(ModuleMapFileName,
false,
1931 if (!HS.loadModuleMapFile(*FE,
false))
1933 Error(
"RegisterPrebuiltModulePath",
"Could not load modulemap in %s", ModuleMapFileName.c_str());
1950 "libforward_listDict",
1958 "libunordered_setDict",
1959 "libunordered_multisetDict",
1960 "libunordered_mapDict",
1961 "libunordered_multimapDict",
1969 char dyLibError[1000];
1970 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1971 dyLibError,
sizeof(dyLibError), NULL);
1973 const char *dyLibError = dlerror();
1975 ::Error(
"TCling::RegisterModule",
"Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
1976 (dyLibError) ? dyLibError :
"");
2013 const char** headers,
2014 const char** includePaths,
2015 const char* payloadCode,
2016 const char* fwdDeclsCode,
2017 void (*triggerFunc)(),
2019 const char** classesHeaders,
2020 Bool_t lateRegistration ,
2027 if (fromRootCling)
return;
2036 bool isACLiC = strstr(modulename,
"_ACLiC_dict") !=
nullptr;
2037 if (hasHeaderParsingOnDemand && isACLiC) {
2039 Info(
"TCling::RegisterModule",
2040 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2041 hasHeaderParsingOnDemand =
false;
2055 for (
const char** inclPath = includePaths; *inclPath; ++inclPath) {
2058 cling::Transaction* T =
nullptr;
2060 for (
auto& fwdDeclArgToSkipPair : fwdDeclsArgToSkip){
2061 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2062 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2063 auto compRes =
fInterpreter->declare(fwdDecl.c_str(), &T);
2064 assert(cling::Interpreter::kSuccess == compRes &&
2065 "A fwd declaration could not be compiled");
2066 if (compRes!=cling::Interpreter::kSuccess){
2067 Warning(
"TCling::RegisterModule",
2068 "Problems in declaring string '%s' were encountered.",
2083 TString code = gNonInterpreterClassDef;
2085 code += payloadCode;
2087 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2088 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2090 if (dyLibName.empty()) {
2091 ::Error(
"TCling::RegisterModule",
"Dictionary trigger function for %s not found", modulename);
2096 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2098 bool wasDlopened =
false;
2103 if (!lateRegistration) {
2110 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2120 if (hasHeaderParsingOnDemand && fwdDeclsCode){
2123 std::string fwdDeclsCodeLessEnums;
2127 std::string fwdDeclsLine;
2128 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2129 std::vector<std::string> scopes;
2130 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2131 const auto enumPos = fwdDeclsLine.find(
"enum __attribute__((annotate(\"");
2133 if (enumPos != std::string::npos) {
2140 auto nsPos = fwdDeclsLine.find(
"namespace");
2141 R__ASSERT(nsPos < enumPos &&
"Inconsistent enum and enclosing scope parsing!");
2142 while (nsPos < enumPos && nsPos != std::string::npos) {
2144 const auto nsNameStart = nsPos + 10;
2145 const auto nsNameEnd = fwdDeclsLine.find(
'{', nsNameStart);
2146 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2147 scopes.push_back(nsName);
2148 nsPos = fwdDeclsLine.find(
"namespace", nsNameEnd);
2151 clang::DeclContext* DC =
nullptr;
2152 for (
auto &&aScope: scopes) {
2153 DC = cling::utils::Lookup::Namespace(&
fInterpreter->getSema(), aScope.c_str(), DC);
2159 if (scopes.empty() || DC) {
2163 size_t posEnumName = fwdDeclsLine.rfind(
"\"))) ");
2164 R__ASSERT(posEnumName != std::string::npos &&
"Inconsistent enum fwd decl!");
2166 while (isspace(fwdDeclsLine[posEnumName]))
2168 size_t posEnumNameEnd = fwdDeclsLine.find(
" : ", posEnumName);
2169 R__ASSERT(posEnumNameEnd != std::string::npos &&
"Inconsistent enum fwd decl (end)!");
2170 while (isspace(fwdDeclsLine[posEnumNameEnd]))
2174 std::string enumName = fwdDeclsLine.substr(posEnumName,
2175 posEnumNameEnd - posEnumName + 1);
2177 if (clang::NamedDecl* enumDecl
2178 = cling::utils::Lookup::Named(&
fInterpreter->getSema(),
2179 enumName.c_str(), DC)) {
2182 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) &&
"not an enum decl!");
2189 fwdDeclsCodeLessEnums += fwdDeclsLine +
"\n";
2193 if (!fwdDeclsCodeLessEnums.empty()){
2194 auto compRes =
fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
2195 assert(cling::Interpreter::kSuccess == compRes &&
2196 "The forward declarations could not be compiled");
2197 if (compRes!=cling::Interpreter::kSuccess){
2198 Warning(
"TCling::RegisterModule",
2199 "Problems in compiling forward declarations for module %s: '%s'",
2200 modulename, fwdDeclsCodeLessEnums.c_str()) ;
2208 ExtLexicalStorageAdder elsa;
2209 for (
auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
2210 cling::Transaction::DelayCallInfo& dci = *dciIt;
2211 for(
auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2212 clang::Decl* declPtr = *dit;
2213 elsa.TraverseDecl(declPtr);
2227 for (
const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2228 temp=*classesHeader;
2230 size_t theTemplateHash = 0;
2231 bool addTemplate =
false;
2232 size_t posTemplate = temp.find(
'<');
2233 if (posTemplate != std::string::npos) {
2235 std::string templateName = temp.substr(0, posTemplate);
2241 for (
const char** classesHeader_inner = classesHeader; 0!=strcmp(*classesHeader_inner,
"@"); ++classesHeader_inner,++classesHeader){
2243 if (payloadCode == *classesHeader_inner ){
2245 if (addTemplate)
fPayloads.insert(theTemplateHash);
2248 Info(
"TCling::RegisterModule",
2249 "Adding a header for %s", temp.c_str());
2255 addTemplate =
false;
2263 bool ModuleWasSuccessfullyLoaded =
false;
2265 std::string ModuleName = modulename;
2266 if (llvm::StringRef(modulename).startswith(
"lib"))
2267 ModuleName = llvm::StringRef(modulename).substr(3).str();
2272 clang::Preprocessor &PP = TheSema.getPreprocessor();
2273 std::string ModuleMapName;
2275 ModuleMapName = ModuleName +
".modulemap";
2277 ModuleMapName =
"module.modulemap";
2285 if (!ModuleWasSuccessfullyLoaded) {
2287 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2288 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2289 if (moduleMap.findModule(ModuleName))
2290 Info(
"TCling::RegisterModule",
"Module %s in modulemap failed to load.", ModuleName.c_str());
2295 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2298 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2299 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2300 llvm::sys::path::append(pcmFileNameFullPath,
2302 LoadPCM(pcmFileNameFullPath.str().str());
2309 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2311#if defined(R__MUST_REVISIT)
2312#if R__MUST_REVISIT(6,2)
2313 Warning(
"TCling::RegisterModule",
"Diagnostics suppression should be gone by now.");
2317 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand){
2320 const cling::Transaction* watermark =
fInterpreter->getLastTransaction();
2321 cling::Interpreter::CompilationResult compRes =
fInterpreter->parseForModule(code.
Data());
2327 assert(cling::Interpreter::kSuccess == compRes &&
2328 "Payload code of a dictionary could not be parsed correctly.");
2329 if (compRes!=cling::Interpreter::kSuccess) {
2330 Warning(
"TCling::RegisterModule",
2331 "Problems declaring payload for module %s.", modulename) ;
2344 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand) {
2347 "#undef __ROOTCLING__\n"
2348 + gInterpreterClassDef +
2353 assert(isSharedLib);
2356 dlclose(dyLibHandle);
2362 ASTContext &C = CI.getASTContext();
2370 if (IdentifierInfoLookup *External = C.Idents.getExternalIdentifierLookup()) {
2371 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2372 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2373 std::string
I = Ident.str();
2397 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2403 if ( i->first == oldcl ) {
2426 const char* input_line,
2427 cling::Interpreter::CompilationResult& compRes,
2431 return metaProcessor->process(input_line, compRes,
result);
2433 catch (cling::InterpreterException&
ex)
2435 Error(
"HandleInterpreterException",
"%s\n%s",
ex.what(),
"Execution of your code was aborted.");
2437 compRes = cling::Interpreter::kFailure;
2446 if (
auto ie =
dynamic_cast<const cling::InterpreterException*
>(&
e)) {
2472 gROOT->SetLineIsProcessing();
2476 gROOT->SetLineHasBeenProcessed();
2489 gROOT->SetLineIsProcessing();
2491 struct InterpreterFlagsRAII {
2492 cling::Interpreter* fInterpreter;
2493 bool fWasDynamicLookupEnabled;
2495 InterpreterFlagsRAII(cling::Interpreter* interp):
2496 fInterpreter(interp),
2497 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2499 fInterpreter->enableDynamicLookup(
true);
2501 ~InterpreterFlagsRAII() {
2502 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2503 gROOT->SetLineHasBeenProcessed();
2512 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2513 if (!strncmp(sLine.
Data(),
".L", 2) || !strncmp(sLine.
Data(),
".x", 2) ||
2514 !strncmp(sLine.
Data(),
".X", 2)) {
2522 aclicMode, arguments, io);
2523 if (aclicMode.
Length()) {
2525 R__ASSERT(aclicMode[0]==
'+' &&
"ACLiC mode must start with a +");
2527 if (aclicMode[1]==
'+') {
2533 compRes = cling::Interpreter::kFailure;
2535 if (strncmp(sLine.
Data(),
".L", 2) != 0) {
2538 if (arguments.
Length() == 0) {
2547 mod_line = function + arguments + io;
2551 }
else if (cling::DynamicLibraryManager::isSharedLibrary(fname.
Data()) &&
2552 strncmp(sLine.
Data(),
".L", 2) != 0) {
2555 compRes = cling::Interpreter::kFailure;
2557 if (arguments.
Length() == 0) {
2571 ext = fname.
Last(
'_');
2577 mod_line = function + arguments + io;
2582 size_t unnamedMacroOpenCurly;
2585 std::string codeline;
2588 std::ifstream in(fname, std::ifstream::binary);
2590 std::getline(in, codeline);
2591 code += codeline +
"\n";
2593 unnamedMacroOpenCurly
2594 = cling::utils::isUnnamedMacro(code,
fInterpreter->getCI()->getLangOpts());
2598 if (unnamedMacroOpenCurly != std::string::npos) {
2600 unnamedMacroOpenCurly);
2610 if (0!=strncmp(sLine.
Data(),
".autodict ",10) && sLine !=
".autodict") {
2615 bool isInclusionDirective = sLine.
Contains(
"\n#include") || sLine.
BeginsWith(
"#include");
2616 if (isInclusionDirective) {
2633 case cling::Interpreter::kSuccess: *error =
kNoError;
break;
2634 case cling::Interpreter::kFailure: *error =
kRecoverable;
break;
2635 case cling::Interpreter::kMoreInputExpected: *error =
kProcessing;
break;
2638 if (compRes == cling::Interpreter::kSuccess
2669 if (path[0] ==
'-' && path[1] ==
'I')
2676 snprintf(drive, 3,
"%c:", _getdrive() +
'A' - 1);
2701 static const TClassRef clRefString(
"std::string");
2702 if (clRefString == cl) {
2721 const char* cobj = (
const char*) obj;
2728 auto inspInspect = [&] (ptrdiff_t
offset){
2734 switch(complexType) {
2741 inspInspect(
sizeof(
float));
2746 inspInspect(
sizeof(
double));
2751 inspInspect(
sizeof(
int));
2756 inspInspect(
sizeof(
long));
2761 static clang::PrintingPolicy
2763 if (printPol.Indentation) {
2765 printPol.Indentation = 0;
2766 printPol.SuppressInitializers =
true;
2769 const char* clname = cl->
GetName();
2772 const clang::ASTContext& astContext =
fInterpreter->getCI()->getASTContext();
2773 const clang::Decl *scopeDecl =
nullptr;
2774 const clang::Type *recordType =
nullptr;
2778 scopeDecl = clingCI->
GetDecl();
2779 recordType = clingCI->
GetType();
2781 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
2783 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2787 Error(
"InspectMembers",
"Cannot find Decl for class %s", clname);
2790 const clang::CXXRecordDecl* recordDecl
2791 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2793 Error(
"InspectMembers",
"Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2802 astContext.getASTRecordLayout(recordDecl);
2804 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2805 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2808 const clang::ASTRecordLayout& recLayout
2809 = astContext.getASTRecordLayout(recordDecl);
2816 if (cl->
Size() != recLayout.getSize().getQuantity()) {
2817 Error(
"InspectMembers",
"TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2821 unsigned iNField = 0;
2824 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2825 eField = recordDecl->field_end(); iField != eField;
2826 ++iField, ++iNField) {
2829 clang::QualType memberQT = iField->getType();
2834 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT,
fNormalizedCtxt->
GetConfig(),
false );
2835 if (memberQT.isNull()) {
2836 std::string memberName;
2837 llvm::raw_string_ostream stream(memberName);
2839 printPol.AnonymousTagLocations =
false;
2840 iField->getNameForDiagnostic(stream, printPol,
true );
2842 Error(
"InspectMembers",
2843 "Cannot retrieve QualType for member %s while inspecting class %s",
2844 memberName.c_str(), clname);
2847 const clang::Type* memType = memberQT.getTypePtr();
2849 std::string memberName;
2850 llvm::raw_string_ostream stream(memberName);
2852 printPol.AnonymousTagLocations =
false;
2853 iField->getNameForDiagnostic(stream, printPol,
true );
2855 Error(
"InspectMembers",
2856 "Cannot retrieve Type for member %s while inspecting class %s",
2857 memberName.c_str(), clname);
2861 const clang::Type* memNonPtrType = memType;
2862 Bool_t ispointer =
false;
2863 if (memNonPtrType->isPointerType()) {
2865 clang::QualType ptrQT
2866 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2871 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT,
fNormalizedCtxt->
GetConfig(),
false );
2872 if (ptrQT.isNull()) {
2873 std::string memberName;
2874 llvm::raw_string_ostream stream(memberName);
2876 printPol.AnonymousTagLocations =
false;
2877 iField->getNameForDiagnostic(stream, printPol,
true );
2879 Error(
"InspectMembers",
2880 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2881 memberName.c_str(), clname);
2884 memNonPtrType = ptrQT.getTypePtr();
2888 llvm::SmallString<8> arraySize;
2889 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2890 unsigned arrLevel = 0;
2891 bool haveErrorDueToArray =
false;
2895 const clang::ConstantArrayType* constArrType =
2896 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2898 constArrType->getSize().toStringUnsigned(arraySize);
2901 clang::QualType subArrQT = arrType->getElementType();
2902 if (subArrQT.isNull()) {
2903 std::string memberName;
2904 llvm::raw_string_ostream stream(memberName);
2906 printPol.AnonymousTagLocations =
false;
2907 iField->getNameForDiagnostic(stream, printPol,
true );
2909 Error(
"InspectMembers",
2910 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2911 arrLevel, subArrQT.getAsString(printPol).c_str(),
2912 memberName.c_str(), clname);
2913 haveErrorDueToArray =
true;
2916 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2918 if (haveErrorDueToArray) {
2923 std::string fieldName;
2924 if (memType->isPointerType()) {
2929 std::string ioname(iField->getName());
2931 fieldName += ioname;
2932 fieldName += arraySize;
2937 clang::CharUnits
offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2938 ptrdiff_t fieldOffset =
offset.getQuantity();
2948 auto iFiledQtype = iField->getType();
2949 if (
auto tagDecl = iFiledQtype->getAsTagDecl()){
2950 auto declAccess = tagDecl->getAccess();
2951 if (declAccess == AS_private || declAccess == AS_protected) {
2957 insp.
Inspect(
const_cast<TClass*
>(cl), insp.
GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2960 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2961 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
2964 std::string sFieldRecName;
2967 clang::QualType(memNonPtrType,0),
2977 insp.
InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
2978 (fieldName +
'.').c_str(), transient);
2986 unsigned iNBase = 0;
2987 for (clang::CXXRecordDecl::base_class_const_iterator iBase
2988 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
2989 iBase != eBase; ++iBase, ++iNBase) {
2990 clang::QualType baseQT = iBase->getType();
2991 if (baseQT.isNull()) {
2992 Error(
"InspectMembers",
2993 "Cannot find QualType for base number %d while inspecting class %s",
2997 const clang::CXXRecordDecl* baseDecl
2998 = baseQT->getAsCXXRecordDecl();
3000 Error(
"InspectMembers",
3001 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
3006 std::string sBaseName;
3008 std::vector<TClass*> foundClasses;
3010 if (foundClasses.size()==1){
3011 baseCl=foundClasses[0];
3024 std::string qualNameForDiag;
3026 Error(
"InspectMembers",
3027 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
3032 if (iBase->isVirtual()) {
3035 Error(
"InspectMembers",
3036 "Base %s of class %s is virtual but no object provided",
3037 sBaseName.c_str(), clname);
3045 baseOffset = ci->
GetBaseOffset(baseCi,
const_cast<void*
>(obj),
3047 if (baseOffset == -1) {
3048 Error(
"InspectMembers",
3049 "Error calculating offset of virtual base %s of class %s",
3050 sBaseName.c_str(), clname);
3053 Error(
"InspectMembers",
3054 "Cannot calculate offset of virtual base %s of class %s",
3055 sBaseName.c_str(), clname);
3060 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3107 bool oldDynLookup =
fInterpreter->isDynamicLookupEnabled();
3136 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.
Data());
3151 llvm::StringRef ModuleName(libname);
3152 ModuleName = llvm::sys::path::stem(ModuleName);
3153 ModuleName.consume_front(
"lib");
3161 clang::ModuleMap &moduleMap =
fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3162 clang::Module *M = moduleMap.findModule(ModuleName);
3163 return M && !M->IsUnimportable && M->getASTFile();
3182 size_t at = std::string::npos;
3183 while ((at = file_name.find(
"/./")) != std::string::npos)
3184 file_name.replace(at, 3,
"/");
3186 std::string filesStr =
"";
3187 llvm::raw_string_ostream filesOS(filesStr);
3188 clang::SourceManager &SM =
fInterpreter->getCI()->getSourceManager();
3189 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3192 llvm::SmallVector<llvm::StringRef, 100> files;
3193 llvm::StringRef(filesStr).split(files,
"\n");
3195 std::set<std::string> fileMap;
3196 llvm::StringRef file_name_ref(file_name);
3198 for (llvm::SmallVector<llvm::StringRef, 100>::const_iterator
3199 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3200 if ((*iF) == file_name_ref)
return kTRUE;
3201 fileMap.insert(iF->str());
3204 if (fileMap.empty())
return kFALSE;
3207 TString sFilename(file_name.c_str());
3209 && fileMap.count(sFilename.
Data())) {
3217 while (incPath.
Index(
" :") != -1) {
3221 sFilename = file_name.c_str();
3223 && fileMap.count(sFilename.
Data())) {
3232 clang::ConstSearchDirIterator *CurDir =
nullptr;
3233 clang::Preprocessor &PP =
fInterpreter->getCI()->getPreprocessor();
3234 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3235 auto FE = HS.LookupFile(file_name.c_str(),
3236 clang::SourceLocation(),
3239 clang::ArrayRef<std::pair<
const clang::FileEntry *,
3240 const clang::DirectoryEntry *>>(),
3253 clang::SourceManager &SM =
fInterpreter->getCI()->getSourceManager();
3255 clang::FileID FID = SM.translateFile(*FE);
3256 if (!FID.isInvalid() && FID.getHashValue() == 0)
3259 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3260 if (SLocE.isFile() && !SLocE.getFile().getContentCache().getBufferIfLoaded())
3262 if (!FID.isInvalid())
3266 sFilename = FE->getName().str();
3268 && fileMap.count(sFilename.
Data())) {
3276#if defined(R__MACOSX)
3284static bool R__UpdateLibFileForLinking(
TString &lib)
3286 const char *mapfile =
nullptr;
3288 mapfile =
"/System/Library/dyld/dyld_shared_cache_x86_64.map";
3290 mapfile =
"/System/Library/dyld/dyld_shared_cache_arm64e.map";
3292 #error unsupported architecture
3294 if (std::ifstream cacheMap{mapfile}) {
3296 while (getline(cacheMap,
line)) {
3297 if (
line.find(lib) != std::string::npos) {
3309#if defined (R__LINUX) || defined (R__FBSD)
3315static int callback_for_dl_iterate_phdr(
struct dl_phdr_info *info,
size_t size,
void *
data)
3318 static std::unordered_set<
decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3320 auto newLibs =
static_cast<std::vector<std::string>*
>(
data);
3321 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3323 if (info->dlpi_name && info->dlpi_name[0]
3328 && strncmp(info->dlpi_name,
"[vdso]", 6)
3332 && strncmp(info->dlpi_name,
"/libexec/ld-elf.so.1", 20)
3334 && strncmp(info->dlpi_name,
"linux-vdso.so", 13)
3335 && strncmp(info->dlpi_name,
"linux-vdso32.so", 15)
3336 && strncmp(info->dlpi_name,
"linux-vdso64.so", 15)
3337 && strncmp(info->dlpi_name,
"linux-gate.so", 13))
3338 newLibs->emplace_back(info->dlpi_name);
3339 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3352#if defined(R__WIN32) || defined(__CYGWIN__)
3353 HMODULE hModules[1024];
3355 unsigned long cbModules;
3357 hProcess = (
void *)::GetCurrentProcess();
3358 ::EnumProcessModules(hProcess, hModules,
sizeof(hModules), &cbModules);
3360 for (i = 1; i < (cbModules /
sizeof(
void *)); i++) {
3361 static const int bufsize = 260;
3362 wchar_t winname[bufsize];
3363 char posixname[bufsize];
3364 ::GetModuleFileNameExW(hProcess, hModules[i], winname, bufsize);
3365#if defined(__CYGWIN__)
3366 cygwin_conv_path(CCP_WIN_W_TO_POSIX, winname, posixname, bufsize);
3368 std::wstring wpath = winname;
3369 std::replace(wpath.begin(), wpath.end(),
'\\',
'/');
3370 string path(wpath.begin(), wpath.end());
3371 strncpy(posixname, path.c_str(), bufsize);
3377#elif defined(R__MACOSX)
3381 while (
const mach_header* mh = _dyld_get_image_header(imageIndex)) {
3383 if (mh->filetype == MH_DYLIB) {
3384 if (
const char* imageName = _dyld_get_image_name(imageIndex)) {
3392#elif defined(R__LINUX) || defined(R__FBSD)
3396 std::vector<std::string> newLibs;
3397 dl_iterate_phdr(callback_for_dl_iterate_phdr, &newLibs);
3398 for (
auto &&lib: newLibs)
3401 Error(
"TCling::UpdateListOfLoadedSharedLibraries",
3402 "Platform not supported!");
3408static bool StartsWithStrLit(
const char *haystack,
const char (&needle)[
N]) {
3409 return !strncmp(haystack, needle,
N - 1);
3424 cling::DynamicLibraryManager* DLM =
fInterpreter->getDynamicLibraryManager();
3425 if (!DLM->isLibraryLoaded(
filename)) {
3426 DLM->loadLibrary(
filename,
true ,
true );
3429#if defined(R__MACOSX)
3431 auto lenFilename = strlen(
filename);
3432 auto isInMacOSSystemDir = [](
const char *fn) {
3433 return StartsWithStrLit(fn,
"/usr/lib/") || StartsWithStrLit(fn,
"/System/Library/");
3435 if (!strcmp(
filename,
"cl_kernels")
3438 || StartsWithStrLit(
filename,
"/usr/lib/system/")
3439 || StartsWithStrLit(
filename,
"/usr/lib/libc++")
3440 || StartsWithStrLit(
filename,
"/System/Library/Frameworks/")
3441 || StartsWithStrLit(
filename,
"/System/Library/PrivateFrameworks/")
3442 || StartsWithStrLit(
filename,
"/System/Library/CoreServices/")
3443 || StartsWithStrLit(
filename,
"/usr/lib/libSystem")
3444 || StartsWithStrLit(
filename,
"/usr/lib/libstdc++")
3445 || StartsWithStrLit(
filename,
"/usr/lib/libicucore")
3446 || StartsWithStrLit(
filename,
"/usr/lib/libbsm")
3447 || StartsWithStrLit(
filename,
"/usr/lib/libobjc")
3448 || StartsWithStrLit(
filename,
"/usr/lib/libresolv")
3449 || StartsWithStrLit(
filename,
"/usr/lib/libauto")
3450 || StartsWithStrLit(
filename,
"/usr/lib/libcups")
3451 || StartsWithStrLit(
filename,
"/usr/lib/libDiagnosticMessagesClient")
3452 || StartsWithStrLit(
filename,
"/usr/lib/liblangid")
3453 || StartsWithStrLit(
filename,
"/usr/lib/libCRFSuite")
3454 || StartsWithStrLit(
filename,
"/usr/lib/libpam")
3455 || StartsWithStrLit(
filename,
"/usr/lib/libOpenScriptingUtil")
3456 || StartsWithStrLit(
filename,
"/usr/lib/libextension")
3457 || StartsWithStrLit(
filename,
"/usr/lib/libAudioToolboxUtility")
3458 || StartsWithStrLit(
filename,
"/usr/lib/liboah")
3459 || StartsWithStrLit(
filename,
"/usr/lib/libRosetta")
3460 || StartsWithStrLit(
filename,
"/usr/lib/libCoreEntitlements")
3461 || StartsWithStrLit(
filename,
"/usr/lib/libssl.")
3462 || StartsWithStrLit(
filename,
"/usr/lib/libcrypto.")
3468 || StartsWithStrLit(
filename,
"/usr/lib/system/libsystem_kernel")
3469 || StartsWithStrLit(
filename,
"/usr/lib/system/libsystem_platform")
3470 || StartsWithStrLit(
filename,
"/usr/lib/system/libsystem_pthread")
3475 || (lenFilename > 4 && !strcmp(
filename + lenFilename - 4,
".tbd")))
3478 R__UpdateLibFileForLinking(sFileName);
3480#elif defined(__CYGWIN__)
3482 static const int bufsize = 260;
3483 char posixwindir[bufsize];
3484 char *windir = getenv(
"WINDIR");
3486 cygwin_conv_path(CCP_WIN_A_TO_POSIX, windir, posixwindir, bufsize);
3488 snprintf(posixwindir,
sizeof(posixwindir),
"/Windows/");
3489 if (strstr(
filename, posixwindir) ||
3492#elif defined(R__WIN32)
3495#elif defined (R__LINUX)
3519 assert(!
IsFromRootCling() &&
"Trying to load library from rootcling!");
3523 cling::DynamicLibraryManager* DLM =
fInterpreter->getDynamicLibraryManager();
3524 std::string canonLib = DLM->lookupLibrary(
filename);
3525 cling::DynamicLibraryManager::LoadLibResult res
3526 = cling::DynamicLibraryManager::kLoadLibNotFound;
3527 if (!canonLib.empty()) {
3529 res = DLM->loadLibrary(
filename, system,
true);
3533 cling::Interpreter::CompilationResult compRes;
3535 if (compRes == cling::Interpreter::kSuccess)
3536 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3540 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3544 case cling::DynamicLibraryManager::kLoadLibSuccess:
return 0;
3545 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded:
return 1;
3595 Warning(
"Calc",
"waiting for cling thread to free");
3598 gROOT->SetLineIsProcessing();
3605 cling::Value valRef;
3606 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3610 catch (cling::InterpreterException&
ex)
3612 Error(
"Calc",
"%s.\n%s",
ex.what(),
"Evaluation of your expression was aborted.");
3614 cr = cling::Interpreter::kFailure;
3617 if (cr != cling::Interpreter::kSuccess) {
3625 if (!valRef.isValid()) {
3634 if (valRef.isVoid()) {
3641 gROOT->SetLineHasBeenProcessed();
3651 void (*histaddFunc)(
const char*
line))
3656#if defined(R__MUST_REVISIT)
3657#if R__MUST_REVISIT(6,2)
3658 Warning(
"SetGetline",
"Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3671 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3672 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3673 || T.macros_begin() != T.macros_end()
3674 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3697 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)
fgSetOfSpecials)->find(obj);
3715#if defined(R__MUST_REVISIT)
3716#if R__MUST_REVISIT(6,2)
3718 Warning(
"Reset",
"Cling should support the equivalent of scratch_upto(&fDictPos)");
3728#if defined(R__MUST_REVISIT)
3729#if R__MUST_REVISIT(6,2)
3731 Warning(
"ResetAll",
"Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3758#if defined(R__MUST_REVISIT)
3759#if R__MUST_REVISIT(6,2)
3761 Warning(
"ResetGlobalVar",
"Cling should support the equivalent of resetglobalvar(obj)");
3773#if defined(R__MUST_REVISIT)
3774#if R__MUST_REVISIT(6,2)
3776 Warning(
"RewindDictionary",
"Cling should provide a way to revert transaction similar to rewinddictionary()");
3787#if defined(R__MUST_REVISIT)
3788#if R__MUST_REVISIT(6,2)
3790 Warning(
"DeleteGlobal",
"Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3802#if defined(R__MUST_REVISIT)
3803#if R__MUST_REVISIT(6,2)
3804 Warning(
"DeleteVariable",
"should do more that just reseting the value to zero");
3809 llvm::StringRef srName(
name);
3810 const char* unscopedName =
name;
3811 llvm::StringRef::size_type posScope = srName.rfind(
"::");
3812 const clang::DeclContext* declCtx =
nullptr;
3813 if (posScope != llvm::StringRef::npos) {
3814 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
3815 const clang::Decl* scopeDecl
3816 = lh.findScope(srName.substr(0, posScope),
3817 cling::LookupHelper::WithDiagnostics);
3819 Error(
"DeleteVariable",
"Cannot find enclosing scope for variable %s",
3823 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3825 Error(
"DeleteVariable",
3826 "Enclosing scope for variable %s is not a declaration context",
3830 unscopedName += posScope + 2;
3834 clang::NamedDecl* nVarDecl
3835 = cling::utils::Lookup::Named(&
fInterpreter->getSema(), unscopedName, declCtx);
3837 Error(
"DeleteVariable",
"Unknown variable %s",
name);
3840 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3842 Error(
"DeleteVariable",
"Entity %s is not a variable",
name);
3846 clang::QualType qType = varDecl->getType();
3847 const clang::Type*
type = qType->getUnqualifiedDesugaredType();
3850 if (
type->isPointerType()) {
3851 int** ppInt = (
int**)
fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3853 if (ppInt) *ppInt =
nullptr;
3863#if defined(R__MUST_REVISIT)
3864#if R__MUST_REVISIT(6,2)
3866 Warning(
"SaveContext",
"Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3876#if defined(R__MUST_REVISIT)
3877#if R__MUST_REVISIT(6,2)
3879 Warning(
"SaveGlobalsContext",
"Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3927 std::tuple<int,double>
value;
3931 size_t offset0 = ((
char*)&(std::get<0>(
value))) - ((
char*)&
value);
3932 size_t offset1 = ((
char*)&(std::get<1>(
value))) - ((
char*)&
value);
3934 size_t ascOffset0 = ((
char*)&(asc.
_0)) - ((
char*)&asc);
3935 size_t ascOffset1 = ((
char*)&(asc.
_1)) - ((
char*)&asc);
3937 size_t desOffset0 = ((
char*)&(des.
_0)) - ((
char*)&des);
3938 size_t desOffset1 = ((
char*)&(des.
_1)) - ((
char*)&des);
3940 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3942 }
else if (offset0 == desOffset0 && offset1 == desOffset1) {
3952 std::string alternateName =
"TEmulatedTuple";
3953 alternateName.append( classname + 5 );
3955 std::string fullname =
"ROOT::Internal::" + alternateName;
3956 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
3962 auto iter = tupleContent.
fElements.begin() + 1;
3963 auto theEnd = tupleContent.
fElements.end() - 1;
3964 auto deleter = [](TypeInfo_t *
type) {
3967 std::unique_ptr<TypeInfo_t,
decltype(deleter)>
type{
gInterpreter->TypeInfo_Factory(), deleter };
3968 while (iter != theEnd) {
3972 Error(
"Load",
"Could not declare alternate type for %s since %s (or one of its context) is private or protected",
3973 classname, iter->c_str());
3980 std::string guard_name;
3982 std::ostringstream guard;
3983 guard <<
"ROOT_INTERNAL_TEmulated_";
3984 guard << guard_name;
3986 std::ostringstream alternateTuple;
3987 alternateTuple <<
"#ifndef " << guard.str() <<
"\n";
3988 alternateTuple <<
"#define " << guard.str() <<
"\n";
3989 alternateTuple <<
"namespace ROOT { namespace Internal {\n";
3990 alternateTuple <<
"template <class... Types> struct TEmulatedTuple;\n";
3991 alternateTuple <<
"template <> struct " << alternateName <<
" {\n";
3996 unsigned int nMember = 0;
3997 auto iter = tupleContent.
fElements.begin() + 1;
3998 auto theEnd = tupleContent.
fElements.end() - 1;
3999 while (iter != theEnd) {
4000 alternateTuple <<
" " << *iter <<
" _" << nMember <<
";\n";
4007 unsigned int nMember = tupleContent.
fElements.size() - 3;
4008 auto iter = tupleContent.
fElements.rbegin() + 1;
4009 auto theEnd = tupleContent.
fElements.rend() - 1;
4010 while (iter != theEnd) {
4011 alternateTuple <<
" " << *iter <<
" _" << nMember <<
";\n";
4018 Fatal(
"TCling::SetClassInfo::AlternateTuple",
4019 "Layout of std::tuple on this platform is unexpected.");
4024 alternateTuple <<
"};\n";
4025 alternateTuple <<
"}}\n";
4026 alternateTuple <<
"#endif\n";
4031 Error(
"Load",
"Could not declare %s",alternateName.c_str());
4034 alternateName =
"ROOT::Internal::" + alternateName;
4035 return alternateName;
4075 auto SetWithoutClassInfoState = [](
TClass *cl)
4088 if (strncmp(cl->
GetName(),
"tuple<",strlen(
"tuple<"))==0) {
4091 if (reload ||
name.empty()) {
4093 SetWithoutClassInfoState(cl);
4105 SetWithoutClassInfoState(cl);
4122 zombieCandidate =
kTRUE;
4129 zombieCandidate =
kTRUE;
4182 static const char *anonEnum =
"anonymous enum ";
4183 static const int cmplen = strlen(anonEnum);
4210 const char *classname =
name;
4213 class MaybeSuspendAutoLoadParse {
4214 int fStoreAutoLoad = 0;
4215 int fStoreAutoParse = 0;
4216 bool fSuspendedAutoParse =
false;
4218 MaybeSuspendAutoLoadParse(
int autoload) {
4219 fStoreAutoLoad = ((
TCling*)
gCling)->SetClassAutoLoading(autoload);
4223 fSuspendedAutoParse =
true;
4224 fStoreAutoParse = ((
TCling*)
gCling)->SetSuspendAutoParsing(
true);
4227 ~MaybeSuspendAutoLoadParse() {
4228 if (fSuspendedAutoParse)
4229 ((
TCling*)
gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4230 ((
TCling*)
gCling)->SetClassAutoLoading(fStoreAutoLoad);
4234 MaybeSuspendAutoLoadParse autoLoadParseRAII( autoload );
4236 autoLoadParseRAII.SuspendAutoParsing();
4245 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
4246 const clang::Type *
type =
nullptr;
4247 const clang::Decl *decl
4248 = lh.findScope(classname,
4249 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4250 : cling::LookupHelper::NoDiagnostics,
4254 decl = lh.findScope(buf,
4255 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4256 : cling::LookupHelper::NoDiagnostics,
4273 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4274 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4275 (
type->getAsCXXRecordDecl());
4276 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4293 if (tci.
Property() & propertiesMask) {
4294 bool hasClassDefInline =
false;
4295 if (isClassOrNamespaceOnly) {
4301 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4303 bool success =
false;
4304 std::tie(success, lineNumber) =
4306 hasClassDefInline = success && (lineNumber == -1);
4314 if (hasClassDefInline)
4353 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
4356 const clang::Decl *decl
4357 = lh.findClassTemplate(
name,
4358 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4359 : cling::LookupHelper::NoDiagnostics);
4361 std::string strname =
"std::";
4363 decl = lh.findClassTemplate(strname,
4364 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4365 : cling::LookupHelper::NoDiagnostics);
4367 return nullptr != decl;
4391 cl->
fBase = listOfBase;
4407 D =
fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4410 if (
const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4413 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4414 const_cast< clang::DeclContext *
>(DC)->collectAllContexts(allDeclContexts);
4415 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(), declEnd = allDeclContexts.end();
4416 declIter != declEnd; ++declIter) {
4418 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4419 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4420 if (
const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4423 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4424 llvm::raw_string_ostream stream(buf);
4426 Policy.AnonymousTagLocations =
false;
4427 ED->getNameForDiagnostic(stream, Policy,
false);
4431 const char*
name = buf.c_str();
4455 D =
fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4459 if (
const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4462 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4463 const_cast< clang::DeclContext *
>(DC)->collectAllContexts(allDeclContexts);
4464 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(),
4465 declEnd = allDeclContexts.end(); declIter != declEnd; ++declIter) {
4467 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4468 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4469 if (
const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4470 funcTempList->
Get(FTD);
4528 if (
m->fMethodArgs) {
4539 m->fMethodArgs = arglist;
4584 if (llvm::isa<clang::NamespaceDecl>(cli->
GetDecl())) {
4593 Error(
"GenerateTClass",
4594 "Cannot find %s::Class_Version()! Class version might be wrong.",
4601 if (newvers == -1) {
4609 newvers = callfunc.
ExecInt(
nullptr);
4611 Error(
"GenerateTClass",
4612 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4616 if (newvers != oldvers) {
4633static void GenerateTClass_GatherInnerIncludes(cling::Interpreter *interp,
TString &includes,
TClingClassInfo *info)
4637 const clang::ClassTemplateSpecializationDecl *templateCl
4638 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->
GetDecl());
4640 for(
unsigned int i=0; i < templateCl->getTemplateArgs().
size(); ++i) {
4641 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4642 if (arg.getKind() == clang::TemplateArgument::Type) {
4645 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4647 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4650 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4651 GenerateTClass_GatherInnerIncludes(interp, includes, &subinfo);
4654 llvm::raw_string_ostream OS(Result);
4655 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4656 Warning(
"TCling::GenerateTClass",
"Missing header file for %s",OS.str().c_str());
4671 if (!info || !info->
IsValid()) {
4672 Fatal(
"GenerateTClass",
"Requires a valid ClassInfo object");
4677 std::string classname;
4681 Info(
"GenerateTClass",
"Will (try to) generate the compiled TClass for %s.",classname.c_str());
4685 GenerateTClass_GatherInnerIncludes(
fInterpreter,includes,info);
4691 Error(
"GenerateTClass",
"Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4695 if (cl ==
nullptr) {
4697 cl =
new TClass(classinfo, version,
nullptr,
nullptr, -1, -1, silent);
4702 cl =
new TClass(classinfo, 1,
nullptr,
nullptr, -1, -1, silent);
4727 if (classes ==
nullptr || classes[0] == 0) {
4728 Error(
"TCling::GenerateDictionary",
"Cannot generate dictionary without passing classes.");
4732 std::vector<std::string> listClasses;
4734 const char* current = classes, *prev = classes;
4738 if (*current ==
';') {
4739 listClasses.push_back(std::string(prev, current - prev));
4742 else if (*(current + 1) == 0) {
4743 listClasses.push_back(std::string(prev, current + 1 - prev));
4747 std::vector<std::string> listIncludes;
4751 const char* current = includes, *prev = includes;
4755 if (*current ==
';') {
4756 listIncludes.push_back(std::string(prev, current - prev));
4759 else if (*(current + 1) == 0) {
4760 listIncludes.push_back(std::string(prev, current + 1 - prev));
4766 std::vector<std::string>(), std::vector<std::string>());
4790 if (
const ValueDecl* decl = (
const ValueDecl*)
d){
4793 if (hasIoName && ioName !=
name)
return nullptr;
4805 using namespace clang;
4807 DeclarationName DName = &SemaR.Context.Idents.get(
name);
4809 LookupResult
R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4810 Sema::ForExternalRedeclaration);
4812 cling::utils::Lookup::Named(&SemaR,
R);
4814 LookupResult::Filter
F =
R.makeFilter();
4816 while (
F.hasNext()) {
4817 NamedDecl *D =
F.next();
4818 if (isa<VarDecl>(D) || isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
4819 isa<IndirectFieldDecl>(D))
4825 if (
R.isSingleResult())
4826 return R.getFoundDecl();
4838 const clang::Decl* possibleEnum =
nullptr;
4843 const clang::DeclContext* dc =
nullptr;
4844 if (
const clang::Decl* D = cci->
GetDecl()) {
4845 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4846 dc = dyn_cast<clang::RecordDecl>(D);
4853 possibleEnum = cling::utils::Lookup::Tag(&
fInterpreter->getSema(),
name, dc);
4855 Error(
"TCling::GetEnum",
"DeclContext not found for %s .\n",
name);
4864 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4865 && isa<clang::EnumDecl>(possibleEnum)) {
4866 return possibleEnum;
4876 if (!gv)
return nullptr;
4878 llvm::StringRef mangled_name = gv->getName();
4893 std::string scopename(demangled_name_c);
4894 free(demangled_name_c);
4900 std::string dataname;
4902 if (!strncmp(scopename.c_str(),
"typeinfo for ",
sizeof(
"typeinfo for ")-1)) {
4903 scopename.erase(0,
sizeof(
"typeinfo for ")-1);
4904 }
else if (!strncmp(scopename.c_str(),
"vtable for ",
sizeof(
"vtable for ")-1)) {
4905 scopename.erase(0,
sizeof(
"vtable for ")-1);
4908 std::string::size_type pos = scopename.rfind(
'(');
4909 if (pos != std::string::npos) {
4913 pos = scopename.rfind(
':');
4914 if (pos != std::string::npos) {
4915 if ((pos != 0) && (scopename[pos-1] ==
':')) {
4916 dataname = scopename.substr(pos+1);
4917 scopename.erase(pos-1);
4921 dataname = scopename;
4929 if (scopename.size()) {
4945 Error(
"GetDataMemberWithValue()",
"not implemented");
4955 Error(
"GetDataMemberAtAddr()",
"not implemented");
4965 const char* params,
Bool_t objectIsConst )
4983 return mangled_name;
4998 GetMethod(method,
proto, objectIsConst,
nullptr ,
mode).GetMangledName();
5010 const char* params,
Bool_t objectIsConst )
5051 std::vector<DeclId_t>& res)
const
5054 clang::ASTContext& Ctx = S.Context;
5055 const clang::Decl* CtxDecl
5057 Ctx.getTranslationUnitDecl();
5058 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
5059 const clang::DeclContext* DeclCtx = RecDecl;
5062 DeclCtx = dyn_cast<clang::NamespaceDecl>(CtxDecl);
5063 if (!DeclCtx)
return;
5065 clang::DeclarationName DName;
5070 if (RecDecl->getNameAsString() == funcname) {
5071 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5072 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
5073 }
else if (funcname[0] ==
'~' && RecDecl->getNameAsString() == funcname + 1) {
5074 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5075 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
5077 DName = &Ctx.Idents.get(funcname);
5080 DName = &Ctx.Idents.get(funcname);
5084 clang::LookupResult
R(S, DName, clang::SourceLocation(),
5085 Sema::LookupOrdinaryName, clang::Sema::NotForRedeclaration);
5086 R.suppressDiagnostics();
5087 S.LookupQualifiedName(
R,
const_cast<DeclContext*
>(DeclCtx));
5088 if (
R.empty())
return;
5090 res.reserve(res.size() + (
R.end() -
R.begin()));
5091 for (clang::LookupResult::iterator IR =
R.begin(), ER =
R.end();
5093 if (
const clang::FunctionDecl* FD
5094 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5095 if (!FD->getDescribedFunctionTemplate()) {
5098 }
else if (
const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5100 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5121 GetMethod(method,
proto, objectIsConst,
nullptr ,
mode).InterfaceMethod();
5260 const char* params,
Bool_t objectIsConst,
int* error)
5280 const char* params,
int* error)
5282 Execute(obj,cl,method,params,
false,error);
5297 Error(
"Execute",
"No method was defined");
5306 if (argc > nparms) {
5307 Error(
"Execute",
"Too many parameters to call %s, got %d but expected at most %d.",method->
GetName(),argc,nparms);
5310 if (nparms != argc) {
5320 Int_t firstDefault = -1;
5321 for (
Int_t i = 0; i < nparms; i ++) {
5328 if (firstDefault >= 0) {
5329 Error(
"Execute",
"Too few arguments to call %s, got only %d but expected at least %d and at most %d.",method->
GetName(),argc,firstDefault,nparms);
5331 Error(
"Execute",
"Too few arguments to call %s, got only %d but expected %d.",method->
GetName(),argc,nparms);
5337 const char* listpar =
"";
5342 for (
Int_t i = 0; i < argc; i ++) {
5351 chpar += (nxtpar->
String()).ReplaceAll(
"\"",
"\\\"");
5358 complete += nxtpar->
String();
5361 listpar = complete.
Data();
5388 const void* args[] ,
5393 Error(
"ExecuteWithArgsAndReturn",
"No method was defined");
5420 Warning(
"GetTopLevelMacroName",
"Must change return type!");
5467#if defined(R__MUST_REVISIT)
5468#if R__MUST_REVISIT(6,0)
5469 Warning(
"GetCurrentMacroName",
"Must change return type!");