63#include "RConfigure.h"
64#include "compiledata.h"
65#include "TClingUtils.h"
81#include "clang/AST/ASTContext.h"
82#include "clang/AST/Decl.h"
83#include "clang/AST/DeclarationName.h"
84#include "clang/AST/GlobalDecl.h"
85#include "clang/AST/RecordLayout.h"
86#include "clang/AST/DeclVisitor.h"
87#include "clang/AST/RecursiveASTVisitor.h"
88#include "clang/AST/Type.h"
89#include "clang/Basic/SourceLocation.h"
90#include "clang/Basic/Specifiers.h"
91#include "clang/Basic/TargetInfo.h"
92#include "clang/CodeGen/ModuleBuilder.h"
93#include "clang/Frontend/CompilerInstance.h"
94#include "clang/Frontend/FrontendDiagnostic.h"
95#include "clang/Lex/HeaderSearch.h"
96#include "clang/Lex/Preprocessor.h"
97#include "clang/Lex/PreprocessorOptions.h"
98#include "clang/Sema/Lookup.h"
99#include "clang/Sema/Sema.h"
100#include "clang/Parse/Parser.h"
102#include "cling/Interpreter/ClangInternalState.h"
103#include "cling/Interpreter/DynamicLibraryManager.h"
104#include "cling/Interpreter/Interpreter.h"
105#include "cling/Interpreter/LookupHelper.h"
106#include "cling/Interpreter/Value.h"
107#include "cling/Interpreter/Transaction.h"
108#include "cling/MetaProcessor/MetaProcessor.h"
109#include "cling/Utils/AST.h"
110#include "cling/Utils/ParserStateRAII.h"
111#include "cling/Utils/SourceNormalization.h"
112#include "cling/Interpreter/Exception.h"
114#include "llvm/IR/GlobalValue.h"
115#include "llvm/IR/Module.h"
117#include "llvm/Support/DynamicLibrary.h"
118#include "llvm/Support/raw_ostream.h"
119#include "llvm/Support/Path.h"
120#include "llvm/Support/Process.h"
121#include "llvm/Object/ELFObjectFile.h"
122#include "llvm/Object/ObjectFile.h"
123#include "llvm/Object/SymbolicFile.h"
124#include "llvm/Support/FileSystem.h"
138#include <unordered_map>
145#define R__DLLEXPORT __attribute__ ((visibility ("default")))
153#include <mach-o/dyld.h>
154#include <mach-o/loader.h>
161#if defined(__CYGWIN__)
162#include <sys/cygwin.h>
163#define HMODULE void *
165 __declspec(dllimport)
void * __stdcall GetCurrentProcess();
166 __declspec(dllimport)
bool __stdcall EnumProcessModules(
void *,
void **,
unsigned long,
unsigned long *);
167 __declspec(dllimport)
unsigned long __stdcall GetModuleFileNameExW(
void *,
void *,
wchar_t *,
unsigned long);
174# define STDIN_FILENO 0
177# define STDOUT_FILENO 1
180# define STDERR_FILENO 2
189#undef GetModuleFileName
190#define RTLD_DEFAULT ((void *)::GetModuleHandle(NULL))
191#define dlsym(library, function_name) ::GetProcAddress((HMODULE)library, function_name)
192#define dlopen(library_name, flags) ::LoadLibraryA(library_name)
193#define dlclose(library) ::FreeLibrary((HMODULE)library)
194#define R__DLLEXPORT __declspec(dllexport)
202 class TCling_UnloadMarker {
204 ~TCling_UnloadMarker() {
210 static TCling_UnloadMarker gTClingUnloadMarker;
219 return D->getDeclContext();
222 return llvm::dyn_cast<clang::NamespaceDecl>(DC);
225 return llvm::dyn_cast<clang::RecordDecl>(DC);
228 return DC->dumpDeclContext();
237 return ((clang::Decl*)D)->dump();
240 if (clang::NamedDecl* ND = llvm::dyn_cast<clang::NamedDecl>(D)) {
243 llvm::raw_string_ostream OS(
name);
244 ND->getNameForDiagnostic(OS, D->getASTContext().getPrintingPolicy(),
247 printf(
"%s\n",
name.c_str());
255 return D->isInvalidDecl();
259 assert(info && info->
IsValid());
260 return info->
GetDecl()->isInvalidDecl();
264using namespace clang;
268 static const std::string gInterpreterClassDef = R
"ICF(
270#define ClassDef(name, id) \
271_ClassDefInterp_(name,id,virtual,) \
272static int DeclFileLine() { return __LINE__; }
274#define ClassDefNV(name, id) \
275_ClassDefInterp_(name,id,,) \
276static int DeclFileLine() { return __LINE__; }
277#undef ClassDefOverride
278#define ClassDefOverride(name, id) \
279_ClassDefInterp_(name,id,,override) \
280static int DeclFileLine() { return __LINE__; }
283 static const std::string gNonInterpreterClassDef = R
"ICF(
284#define __ROOTCLING__ 1
286#define ClassDef(name,id) \
287_ClassDefOutline_(name,id,virtual,) \
288static int DeclFileLine() { return __LINE__; }
290#define ClassDefNV(name, id)\
291_ClassDefOutline_(name,id,,)\
292static int DeclFileLine() { return __LINE__; }
293#undef ClassDefOverride
294#define ClassDefOverride(name, id)\
295_ClassDefOutline_(name,id,,override)\
296static int DeclFileLine() { return __LINE__; }
300 static const std::string gClassDefInterpMacro = R
"ICF(
303#define _ClassDefInterp_(name,id,virtual_keyword, overrd) \
306 static TClass *Class() { static TClass* sIsA = 0; if (!sIsA) sIsA = TClass::GetClass(#name); return sIsA; } \
307 static const char *Class_Name() { return #name; } \
308 virtual_keyword Bool_t CheckTObjectHashConsistency() const overrd { return true; } \
309 static Version_t Class_Version() { return id; } \
310 static TClass *Dictionary() { return 0; } \
311 virtual_keyword TClass *IsA() const overrd { return name::Class(); } \
312 virtual_keyword void ShowMembers(TMemberInspector&insp) const overrd { ::ROOT::Class_ShowMembers(name::Class(), this, insp); } \
313 virtual_keyword void Streamer(TBuffer&) overrd { ::Error("Streamer", "Cannot stream interpreted class."); } \
314 void StreamerNVirtual(TBuffer&ClassDef_StreamerNVirtual_b) { name::Streamer(ClassDef_StreamerNVirtual_b); } \
315 static const char *DeclFileName() { return __FILE__; } \
316 static int ImplFileLine() { return 0; } \
317 static const char *ImplFileName() { return __FILE__; }
348 return ((
TCling*)
gCling)->LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
387 static vector<const NamedDecl*> updateList;
390 if (entered) topLevel =
kFALSE;
405 updateList.push_back(TD);
408 while (!updateList.empty()) {
410 updateList.pop_back();
417 const clang::Decl* D =
static_cast<const clang::Decl*
>(enumObj->
GetDeclId());
418 if(
const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
420 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
421 EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
423 std::string constbuf;
424 if (
const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
425 PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
426 llvm::raw_string_ostream stream(constbuf);
428 Policy.AnonymousTagLocations =
false;
429 (END)->getNameForDiagnostic(stream, Policy,
false);
431 const char* constantName = constbuf.c_str();
435 const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
436 if (valAPSInt.isSigned()) {
437 value = valAPSInt.getSExtValue();
439 value = valAPSInt.getZExtValue();
446 DataMemberInfo_t* dmInfo = (DataMemberInfo_t*) tcDmInfo;
450 enumConstant =
new TEnumConstant(dmInfo, constantName, value, enumObj);
457 globals->
Add(enumConstant);
470 const clang::Decl* D =
static_cast<const clang::Decl*
>(VD);
472 if (
const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
474 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
475 llvm::raw_string_ostream stream(buf);
477 Policy.AnonymousTagLocations =
false;
478 ED->getNameForDiagnostic(stream, Policy,
false);
484 const char*
name = buf.c_str();
495 const clang::Decl* D =
static_cast<const clang::Decl*
>(DV);
497 if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
498 && !dyn_cast<clang::RecordDecl>(D))
return;
500 if (isa<clang::FunctionDecl>(D->getDeclContext())
501 || isa<clang::TagDecl>(D->getDeclContext()))
505 if (
const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
506 if (RD->getDescribedClassTemplate())
508 }
else if (
const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
509 if (FD->getDescribedFunctionTemplate())
513 if (
const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
514 if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
517 else if (
const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
519 if (
const TagDecl *TD = dyn_cast<TagDecl>(D)) {
523 }
else if (
const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
528 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
532 if (isa<EnumDecl>(ND))
537 if (!(isa<VarDecl>(ND)))
541 if (
gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
545 gROOT->GetListOfGlobals()->Add(
new TGlobal((DataMemberInfo_t *)
547 cast<ValueDecl>(ND), 0)));
579 const char* canonicalName) {
580 ((
TCling*)
gCling)->LibraryLoaded(dyLibHandle, canonicalName);
585 ((
TCling *)
gCling)->RegisterRdictForLoadPCM(pcmFileNameFullPath, pcmContent);
589 const char* canonicalName) {
590 ((
TCling*)
gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
606 cling::DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(interpLibHandle);
607 return new TCling(
"C++",
"cling C++ Interpreter", argv);
629 return ((
TCling*)
gCling)->GetClassSharedLibs(className);
635 return ((
TCling*)
gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
640 string file(fileName);
646 string &args,
string &io,
string &fname)
648 string file(fileName);
649 TString f, amode, arguments, aclicio;
651 mode = amode.
Data(); args = arguments.
Data();
652 io = aclicio.
Data(); fname =
f.Data();
657 std::vector<std::string> &sPaths,
658 cling::Interpreter &interpreter,
bool searchSystem);
667 char *__unDName(
char *demangled,
const char *mangled,
int out_len,
668 void * (* pAlloc )(
size_t),
void (* pFree )(
void *),
669 unsigned short int flags);
681 using namespace clang;
682 if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
686 if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
698 return ((
TCling*)
gCling)->LazyFunctionCreatorAutoload(mangled_name);
707 const std::vector<std::string> &headers,
708 const std::vector<std::string> &fwdDecls,
709 const std::vector<std::string> &unknown)
715 if (classes.empty()) {
719 const std::string& className = classes[0];
721 TString fileName =
"AutoDict_";
722 std::string::const_iterator sIt;
723 for (sIt = className.begin(); sIt != className.end(); ++sIt) {
724 if (*sIt ==
'<' || *sIt ==
'>' ||
725 *sIt ==
' ' || *sIt ==
'*' ||
726 *sIt ==
',' || *sIt ==
'&' ||
734 if (classes.size() > 1) {
736 std::vector<std::string>::const_iterator it = classes.begin();
737 while ((++it) != classes.end()) {
738 for (
UInt_t cursor = 0; cursor != it->length(); ++cursor) {
739 chk = chk * 3 + it->at(cursor);
752 static const std::set<std::string> sSTLTypes {
753 "vector",
"list",
"forward_list",
"deque",
"map",
"unordered_map",
"multimap",
754 "unordered_multimap",
"set",
"unordered_set",
"multiset",
"unordered_multiset",
755 "queue",
"priority_queue",
"stack",
"iterator"};
756 std::vector<std::string>::const_iterator it;
757 std::string fileContent(
"");
758 for (it = headers.begin(); it != headers.end(); ++it) {
759 fileContent +=
"#include \"" + *it +
"\"\n";
761 for (it = unknown.begin(); it != unknown.end(); ++it) {
767 while (dirbase.
Length() && dirbase !=
"."
768 && dirbase !=
"include" && dirbase !=
"inc"
769 && dirbase !=
"prec_stl") {
773 fileContent +=
TString(
"#include \"") + header +
"\"\n";
776 for (it = fwdDecls.begin(); it != fwdDecls.end(); ++it) {
777 fileContent +=
"class " + *it +
";\n";
779 fileContent +=
"#ifdef __CINT__ \n";
780 fileContent +=
"#pragma link C++ nestedclasses;\n";
781 fileContent +=
"#pragma link C++ nestedtypedefs;\n";
782 for (it = classes.begin(); it != classes.end(); ++it) {
784 size_t posTemplate =
n.find(
'<');
785 std::set<std::string>::const_iterator iSTLType = sSTLTypes.end();
786 if (posTemplate != std::string::npos) {
787 n.erase(posTemplate, std::string::npos);
788 if (
n.compare(0, 5,
"std::") == 0) {
791 iSTLType = sSTLTypes.find(
n);
793 fileContent +=
"#pragma link C++ class ";
794 fileContent += *it +
"+;\n" ;
795 fileContent +=
"#pragma link C++ class ";
796 if (iSTLType != sSTLTypes.end()) {
800 fileContent += *it +
"::*;\n" ;
805 fileContent += *it +
"::*+;\n" ;
808 fileContent +=
"#endif\n";
812 filePointer = fopen(fileName,
"w");
813 if (filePointer == NULL) {
819 fprintf(filePointer,
"%s", fileContent.c_str());
835 const std::vector<std::string> &headers,
836 const std::vector<std::string> &fwdDecls,
837 const std::vector<std::string> &unknown)
843 std::vector<std::string> classes;
844 classes.push_back(className);
872 void exceptionErrorHandler(
void * ,
873 const std::string& reason,
875 throw std::runtime_error(std::string(
">>> Interpreter compilation error:\n") + reason);
889 class clangDiagSuppr {
891 clangDiagSuppr(clang::DiagnosticsEngine& diag): fDiagEngine(diag){
892 fOldDiagValue = fDiagEngine.getIgnoreAllWarnings();
893 fDiagEngine.setIgnoreAllWarnings(
true);
897 fDiagEngine.setIgnoreAllWarnings(fOldDiagValue);
900 clang::DiagnosticsEngine& fDiagEngine;
922 unsigned long offset = 0;
923 if (strncmp(tname.c_str(),
"const ", 6) == 0) {
926 unsigned long end = tname.length();
927 while( end && (tname[end-1]==
'&' || tname[end-1]==
'*' || tname[end-1]==
']') ) {
928 if ( tname[end-1]==
']' ) {
930 while ( end && tname[end-1]!=
'[' ) --end;
934 std::string innerbuf;
936 if (end != tname.length()) {
937 innerbuf = tname.substr(offset,end-offset);
938 inner = innerbuf.c_str();
940 inner = tname.c_str()+offset;
944 if (
gROOT->GetListOfClasses()->FindObject(inner)
954 const char *newname =
type->GetFullTypeName();
956 newname =
"Long64_t";
958 newname =
"ULong64_t";
960 if (strcmp(inner,newname) == 0) {
963 if (offset) result =
"const ";
965 if ( end != tname.length() ) {
966 result += tname.substr(end,tname.length()-end);
968 if (result == tname) result.clear();
974 if (lastPos != inner)
978 const auto enName = lastPos;
979 const auto scopeNameSize = ((
Long64_t)lastPos - (
Long64_t)inner) /
sizeof(
decltype(*lastPos)) - 2;
980 char *scopeName =
new char[scopeNameSize + 1];
981 strncpy(scopeName, inner, scopeNameSize);
982 scopeName[scopeNameSize] =
'\0';
984 if (
auto scope =
static_cast<TClass *
>(
gROOT->GetListOfClasses()->FindObject(scopeName))) {
985 auto enumTable =
dynamic_cast<const THashList *
>(scope->GetListOfEnums(
false));
986 if (enumTable && enumTable->THashList::FindObject(enName))
return true;
990 auto listOfEnums = scope->GetListOfEnums();
992 auto enumTable =
dynamic_cast<const THashList *
>(listOfEnums);
993 if (enumTable && enumTable->THashList::FindObject(enName))
return true;
1000 auto enumTable =
dynamic_cast<const THashList *
>(
gROOT->GetListOfEnums());
1001 if (enumTable && enumTable->THashList::FindObject(inner))
return true;
1024 return fContent.c_str();
1032 bool notPresent = fLinesHashSet.emplace(fHashFunc(str)).second;
1046static bool LoadModule(
const std::string &ModuleName, cling::Interpreter &interp)
1056 assert(!currentDir.empty());
1058 return interp.loadModule(ModuleName,
true);
1064static void LoadModules(
const std::vector<std::string> &modules, cling::Interpreter &interp)
1066 for (
const auto &modName : modules)
1072 const static bool foundSymbol = dlsym(RTLD_DEFAULT,
"usedToIdentifyRootClingByDlSym");
1078 const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1080 std::string ModuleFileName;
1081 if (!HSOpts.PrebuiltModulePaths.empty())
1083 ModuleFileName = PP.getHeaderSearchInfo().getModuleFileName(M->Name,
"",
true);
1084 if (ModuleFileName.empty())
return "";
1086 std::string ModuleName = llvm::sys::path::filename(ModuleFileName);
1088 return std::string(llvm::sys::path::stem(ModuleName));
1093 if (!clingInterp.getCI()->getLangOpts().Modules)
1105 LoadModule(
"_Builtin_intrinsics", clingInterp);
1109 std::vector<std::string> CoreModules = {
"ROOT_Foundation_C",
1112 "ROOT_Foundation_Stage1_NoRTTI",
1117 static constexpr std::array<const char *, 3> ExcludeModules = {
1118 {
"Rtools",
"RSQLite",
"RInterface"}};
1125 clang::CompilerInstance &CI = *clingInterp.getCI();
1126 clang::ModuleMap &moduleMap = CI.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1127 clang::Preprocessor &PP = CI.getPreprocessor();
1128 std::vector<std::string> ModulesPreloaded;
1129 for (
auto I = moduleMap.module_begin(),
E = moduleMap.module_end();
I !=
E; ++
I) {
1130 clang::Module *M =
I->second;
1134 if (!ModuleName.empty() &&
1135 std::find(CoreModules.begin(), CoreModules.end(), ModuleName) == CoreModules.end() &&
1136 std::find(ExcludeModules.begin(), ExcludeModules.end(), ModuleName) ==
1137 ExcludeModules.end()) {
1138 if (M->IsSystem && !M->IsMissingRequirement)
1140 else if (!M->IsSystem && !M->IsMissingRequirement)
1141 ModulesPreloaded.push_back(ModuleName);
1148 assert(clingInterp.getMacro(
"gROOT") &&
"Couldn't load gROOT macro?");
1156 clingInterp.declare(
"#ifdef I\n #undef I\n #endif\n");
1160 clingInterp.declare(
"#ifdef complex\n #undef complex\n #endif\n");
1164 clingInterp.declare(
"#ifdef PI\n #undef PI\n #endif\n");
1165 clingInterp.declare(
"#ifdef ERROR\n #undef ERROR\n #endif\n");
1170 std::string PreIncludes;
1171 bool hasCxxModules = clingInterp.getCI()->getLangOpts().Modules;
1177 PreIncludes +=
"#include \"RtypesCore.h\"\n";
1180 PreIncludes +=
"#include \"Rtypes.h\"\n";
1182 PreIncludes += gClassDefInterpMacro +
"\n"
1183 + gInterpreterClassDef +
"\n"
1185 "#define ClassImp(X);\n";
1188 PreIncludes +=
"#include <string>\n";
1193 PreIncludes +=
"#include <cassert>\n";
1195 PreIncludes +=
"using namespace std;\n";
1196 clingInterp.declare(PreIncludes);
1214#ifdef R__USE_CXXMODULES
1218 llvm::install_fatal_error_handler(&exceptionErrorHandler);
1222 std::vector<std::string> clingArgsStorage;
1223 clingArgsStorage.push_back(
"cling4root");
1224 for (
const char*
const* arg = argv; *arg; ++arg)
1225 clingArgsStorage.push_back(*arg);
1228 if (!fromRootCling) {
1229 ROOT::TMetaUtils::SetPathsForRelocatability(clingArgsStorage);
1233 clingArgsStorage.push_back(
"-I" + interpInclude);
1236 clingArgsStorage.push_back(
"-I" + interpInclude +
"/cling");
1247 std::string pchFilename = interpInclude +
"/allDict.cxx.pch";
1252 clingArgsStorage.push_back(
"-include-pch");
1253 clingArgsStorage.push_back(pchFilename);
1256 clingArgsStorage.push_back(
"-Wno-undefined-inline");
1257 clingArgsStorage.push_back(
"-fsigned-char");
1261 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(
"EXTRA_CLING_ARGS");
1262 if (EnvOpt.hasValue()) {
1263 StringRef Env(*EnvOpt);
1264 while (!Env.empty()) {
1266 std::tie(Arg, Env) = Env.split(
' ');
1267 clingArgsStorage.push_back(Arg.str());
1271 auto GetEnvVarPath = [](
const std::string &EnvVar,
1272 std::vector<std::string> &Paths) {
1273 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1274 if (EnvOpt.hasValue()) {
1275 StringRef Env(*EnvOpt);
1276 while (!Env.empty()) {
1279 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1280 Paths.push_back(Arg.str());
1286 std::vector<std::string> Paths;
1291 GetEnvVarPath(
"CLING_PREBUILT_MODULE_PATH", Paths);
1293 std::string EnvVarPath;
1294 for (
const std::string&
P : Paths)
1297 gSystem->
Setenv(
"CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1301 EnvOpt = llvm::sys::Process::GetEnv(
"ROOT_CLING_TIMING");
1302 if (EnvOpt.hasValue())
1303 clingArgsStorage.push_back(
"-ftime-report");
1310 std::vector<std::string> Paths;
1312 GetEnvVarPath(
"CLING_MODULEMAP_PATH", Paths);
1317 for (
const std::string&
P : Paths) {
1319 +
"module.modulemap";
1320 if (!llvm::sys::fs::exists(ModuleMapLoc)) {
1322 ::Info(
"TCling::TCling",
"Modulemap %s does not exist \n",
1323 ModuleMapLoc.c_str());
1328 clingArgsStorage.push_back(
"-fmodule-map-file=" + ModuleMapLoc);
1332 std::vector<const char*> interpArgs;
1333 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1334 eArg = clingArgsStorage.end(); iArg != eArg; ++iArg)
1335 interpArgs.push_back(iArg->c_str());
1342 if (!fromRootCling) {
1344 interpArgs.push_back(
"-fmodules");
1345 interpArgs.push_back(
"-fno-implicit-module-maps");
1349 interpArgs.push_back(
"-Rmodule-build");
1355 interpArgs.push_back(
"-fno-autolink");
1360 interpArgs.push_back(
"-ffast-math");
1366 extraArgs && *extraArgs; ++extraArgs) {
1367 if (!strcmp(*extraArgs,
"-resource-dir")) {
1369 llvmResourceDir = *(++extraArgs);
1371 interpArgs.push_back(*extraArgs);
1376 interpArgs.push_back(arg.c_str());
1380 cling::Interpreter::ModuleFileExtensions extensions;
1381 EnvOpt = llvm::sys::Process::GetEnv(
"ROOTDEBUG_RDICT");
1382 if (!EnvOpt.hasValue())
1383 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1385 fInterpreter = llvm::make_unique<cling::Interpreter>(interpArgs.size(),
1387 llvmResourceDir, extensions);
1389 if (!fromRootCling) {
1394 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHValidation =
true;
1398 fInterpreter->getCI()->getLangOpts().SpellChecking =
false;
1403 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO,
false);
1423 if (!fromRootCling) {
1433 std::unique_ptr<TClingCallbacks>
1439 if (!fromRootCling) {
1487#if defined(__CYGWIN__) && defined(__GNUC__)
1489#elif defined(G__WIN32)
1490 MEMORY_BASIC_INFORMATION mbi;
1491 if (!VirtualQuery (func, &mbi,
sizeof (mbi)))
1496 HMODULE hMod = (HMODULE) mbi.AllocationBase;
1497 char moduleName[MAX_PATH];
1499 if (!GetModuleFileNameA (hMod, moduleName,
sizeof (moduleName)))
1503 return ROOT::TMetaUtils::GetRealPath(moduleName);
1506 if (dladdr((
void*)func, &info) == 0) {
1510 if (strchr(info.dli_fname,
'/'))
1511 return ROOT::TMetaUtils::GetRealPath(info.dli_fname);
1515# if defined(R__MACOSX)
1516 char buf[PATH_MAX] = { 0 };
1517 uint32_t bufsize =
sizeof(buf);
1518 if (_NSGetExecutablePath(buf, &bufsize) >= 0)
1519 return ROOT::TMetaUtils::GetRealPath(buf);
1520 return ROOT::TMetaUtils::GetRealPath(info.dli_fname);
1521# elif defined(R__UNIX)
1522 char buf[PATH_MAX] = { 0 };
1524 if (readlink(
"/proc/self/exe", buf,
sizeof(buf)) > 0)
1525 return ROOT::TMetaUtils::GetRealPath(buf);
1526 std::string pipeCmd = std::string(
"which \"") + info.dli_fname +
"\"";
1527 FILE* pipe = popen(pipeCmd.c_str(),
"r");
1529 return ROOT::TMetaUtils::GetRealPath(info.dli_fname);
1531 while (fgets(buf,
sizeof(buf), pipe)) {
1535 return ROOT::TMetaUtils::GetRealPath(result);
1537# error "Unsupported platform."
1551 auto setFactory = []() {
1555 static bool doneFactory = setFactory();
1567 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1568 ::Error(
"TCling::RegisterRdictForLoadPCM",
"Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1585 if (listOfKeys && ((listOfKeys->GetSize() == 0) ||
1586 ((listOfKeys->GetSize() == 1) &&
1587 !strcmp(((
TKey *)listOfKeys->At(0))->GetName(),
"EMPTY")
1594 ::Info(
"TCling::LoadPCMImpl",
"reading protoclasses for %s \n", pcmFile.
GetName());
1596 pcmFile.
GetObject(
"__ProtoClasses", protoClasses);
1599 for (
auto obj : *protoClasses) {
1609 for (
auto proto : *protoClasses) {
1617 ::Error(
"TCling::LoadPCM",
"Inconsistent TClassTable for %s",
proto->GetName());
1628 protoClasses->Clear();
1629 delete protoClasses;
1633 pcmFile.
GetObject(
"__Typedefs", dataTypes);
1635 for (
auto typedf : *dataTypes)
1636 gROOT->GetListOfTypes()->Add(typedf);
1645 auto listOfGlobals =
gROOT->GetListOfGlobals();
1646 auto listOfEnums =
dynamic_cast<THashList *
>(
gROOT->GetListOfEnums());
1648 for (
auto selEnum : *enums) {
1649 const char *enumScope = selEnum->
GetTitle();
1650 const char *enumName = selEnum->GetName();
1651 if (strcmp(enumScope,
"") == 0) {
1654 if (!listOfEnums->THashList::FindObject(enumName)) {
1655 ((
TEnum *)selEnum)->SetClass(
nullptr);
1656 listOfEnums->Add(selEnum);
1659 if (!listOfGlobals->FindObject(enumConstant)) {
1660 listOfGlobals->Add(enumConstant);
1667 if (!nsTClassEntry) {
1670 auto listOfEnums = nsTClassEntry->
fEnums.load();
1681 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1682 ((
TEnum *)selEnum)->SetClass(nsTClassEntry);
1683 listOfEnums->Add(selEnum);
1699 assert(!pcmFileNameFullPath.empty());
1700 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1703 TString pcmFileName = pcmFileNameFullPath;
1711 llvm::SaveAndRestore<Int_t> SaveGDebug(
gDebug);
1714 ::Info(
"TCling::LoadPCM",
"Loading ROOT PCM %s", pcmFileName.
Data());
1719 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1720 pcmFileNameFullPath = ROOT::TMetaUtils::GetRealPath(pcmFileNameFullPath);
1724 llvm::StringRef pcmContent = pendingRdict->second;
1726 std::string RDictFileOpts = pcmFileNameFullPath +
"?filetype=pcm";
1727 TMemFile pcmMemFile(RDictFileOpts.c_str(), range);
1736 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1737 ::Error(
"TCling::LoadPCM",
"ROOT PCM %s file does not exist",
1738 pcmFileNameFullPath.data());
1741 ::Info(
"TCling::LoadPCM",
"In-memory ROOT PCM candidate %s\n",
1742 rdict.first.c_str());
1746 if (!
gROOT->IsRootFile(pcmFileName)) {
1747 Fatal(
"LoadPCM",
"The file %s is not a ROOT as was expected\n", pcmFileName.
Data());
1750 TFile pcmFile(pcmFileName +
"?filetype=pcm",
"READ");
1757 using namespace clang;
1759 class ExtLexicalStorageAdder:
public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1764 bool VisitRecordDecl(clang::RecordDecl* rcd){
1766 Info(
"ExtLexicalStorageAdder",
1767 "Adding external lexical storage to class %s",
1768 rcd->getNameAsString().c_str());
1769 auto reDeclPtr = rcd->getMostRecentDecl();
1771 reDeclPtr->setHasExternalLexicalStorage();
1772 }
while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1785 const std::string &ModuleMapName )
const
1787 assert(llvm::sys::path::is_absolute(FullPath));
1788 Preprocessor &PP =
fInterpreter->getCI()->getPreprocessor();
1789 FileManager &FM = PP.getFileManager();
1792 const DirectoryEntry *DE = FM.getDirectory(FullPath);
1794 HeaderSearch &HS = PP.getHeaderSearchInfo();
1795 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1796 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1797 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1799 HSOpts.AddPrebuiltModulePath(FullPath);
1804 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1805 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1806 const FileEntry *FE = FM.getFile(ModuleMapFileName,
false,
1811 if (FE && !this->
IsLoaded(FE->getName().data())) {
1812 if (!HS.loadModuleMapFile(FE,
false))
1814 Error(
"RegisterPrebuiltModulePath",
"Could not load modulemap in %s", ModuleMapFileName.c_str());
1830 "libforward_listDict",
1838 "libunordered_setDict",
1839 "libunordered_multisetDict",
1840 "libunordered_mapDict",
1841 "libunordered_multimapDict",
1849 char dyLibError[1000];
1850 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1851 dyLibError,
sizeof(dyLibError), NULL);
1853 const char *dyLibError = dlerror();
1855 ::Error(
"TCling::RegisterModule",
"Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
1856 (dyLibError) ? dyLibError :
"");
1893 const char** headers,
1894 const char** includePaths,
1895 const char* payloadCode,
1896 const char* fwdDeclsCode,
1897 void (*triggerFunc)(),
1899 const char** classesHeaders,
1900 Bool_t lateRegistration ,
1907 if (fromRootCling)
return;
1916 bool isACLiC = strstr(modulename,
"_ACLiC_dict") !=
nullptr;
1917 if (hasHeaderParsingOnDemand && isACLiC) {
1919 Info(
"TCling::RegisterModule",
1920 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
1921 hasHeaderParsingOnDemand =
false;
1935 for (
const char** inclPath = includePaths; *inclPath; ++inclPath) {
1938 cling::Transaction*
T = 0;
1940 for (
auto& fwdDeclArgToSkipPair : fwdDeclsArgToSkip){
1941 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
1942 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
1944 assert(cling::Interpreter::kSuccess == compRes &&
1945 "A fwd declaration could not be compiled");
1946 if (compRes!=cling::Interpreter::kSuccess){
1947 Warning(
"TCling::RegisterModule",
1948 "Problems in declaring string '%s' were encountered.",
1955 fNormalizedCtxt->AddTemplAndNargsToKeep(TD->getCanonicalDecl(), nArgsToSkip);
1963 TString code = gNonInterpreterClassDef;
1965 code += payloadCode;
1968 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
1970 if (dyLibName.empty()) {
1971 ::Error(
"TCling::RegisterModule",
"Dictionary trigger function for %s not found", modulename);
1976 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
1978 bool wasDlopened =
false;
1983 if (!lateRegistration) {
1990 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2000 if (hasHeaderParsingOnDemand && fwdDeclsCode){
2003 std::string fwdDeclsCodeLessEnums;
2007 std::string fwdDeclsLine;
2008 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2009 std::vector<std::string> scopes;
2010 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2011 const auto enumPos = fwdDeclsLine.find(
"enum __attribute__((annotate(\"");
2013 if (enumPos != std::string::npos) {
2020 auto nsPos = fwdDeclsLine.find(
"namespace");
2021 R__ASSERT(nsPos < enumPos &&
"Inconsistent enum and enclosing scope parsing!");
2022 while (nsPos < enumPos && nsPos != std::string::npos) {
2024 const auto nsNameStart = nsPos + 10;
2025 const auto nsNameEnd = fwdDeclsLine.find(
'{', nsNameStart);
2026 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2027 scopes.push_back(nsName);
2028 nsPos = fwdDeclsLine.find(
"namespace", nsNameEnd);
2031 clang::DeclContext* DC = 0;
2032 for (
auto &&aScope: scopes) {
2033 DC = cling::utils::Lookup::Namespace(&
fInterpreter->getSema(), aScope.c_str(), DC);
2039 if (scopes.empty() || DC) {
2041 size_t posEnumName = fwdDeclsLine.find(
"\"))) ", 32);
2042 R__ASSERT(posEnumName != std::string::npos &&
"Inconsistent enum fwd decl!");
2044 while (isspace(fwdDeclsLine[posEnumName]))
2046 size_t posEnumNameEnd = fwdDeclsLine.find(
" : ", posEnumName);
2047 R__ASSERT(posEnumNameEnd != std::string::npos &&
"Inconsistent enum fwd decl (end)!");
2048 while (isspace(fwdDeclsLine[posEnumNameEnd]))
2052 std::string enumName = fwdDeclsLine.substr(posEnumName,
2053 posEnumNameEnd - posEnumName + 1);
2055 if (clang::NamedDecl* enumDecl
2056 = cling::utils::Lookup::Named(&
fInterpreter->getSema(),
2057 enumName.c_str(), DC)) {
2060 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) &&
"not an enum decl!");
2067 fwdDeclsCodeLessEnums += fwdDeclsLine +
"\n";
2071 if (fwdDeclsCodeLessEnums.size() != 0){
2072 auto compRes =
fInterpreter->declare(fwdDeclsCodeLessEnums, &
T);
2073 assert(cling::Interpreter::kSuccess == compRes &&
2074 "The forward declarations could not be compiled");
2075 if (compRes!=cling::Interpreter::kSuccess){
2076 Warning(
"TCling::RegisterModule",
2077 "Problems in compiling forward declarations for module %s: '%s'",
2078 modulename, fwdDeclsCodeLessEnums.c_str()) ;
2086 ExtLexicalStorageAdder elsa;
2087 for (
auto dciIt =
T->decls_begin();dciIt!=
T->decls_end();dciIt++){
2088 cling::Transaction::DelayCallInfo& dci = *dciIt;
2089 for(
auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2090 clang::Decl* declPtr = *dit;
2091 elsa.TraverseDecl(declPtr);
2105 for (
const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2106 temp=*classesHeader;
2108 size_t theTemplateHash = 0;
2109 bool addTemplate =
false;
2110 size_t posTemplate = temp.find(
'<');
2111 if (posTemplate != std::string::npos) {
2113 std::string templateName = temp.substr(0, posTemplate);
2119 for (
const char** classesHeader_inner = classesHeader; 0!=strcmp(*classesHeader_inner,
"@"); ++classesHeader_inner,++classesHeader){
2121 if (payloadCode == *classesHeader_inner ){
2123 if (addTemplate)
fPayloads.insert(theTemplateHash);
2126 Info(
"TCling::RegisterModule",
2127 "Adding a header for %s", temp.c_str());
2133 addTemplate =
false;
2141 bool ModuleWasSuccessfullyLoaded =
false;
2143 std::string ModuleName = modulename;
2144 if (llvm::StringRef(modulename).startswith(
"lib"))
2145 ModuleName = llvm::StringRef(modulename).substr(3).str();
2150 clang::Preprocessor &PP = TheSema.getPreprocessor();
2151 std::string ModuleMapName;
2153 ModuleMapName = ModuleName +
".modulemap";
2155 ModuleMapName =
"module.modulemap";
2162 if (!ModuleWasSuccessfullyLoaded) {
2164 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2165 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2166 if (moduleMap.findModule(ModuleName))
2167 Info(
"TCling::RegisterModule",
"Module %s in modulemap failed to load.", ModuleName.c_str());
2172 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2175 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2176 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2177 llvm::sys::path::append(pcmFileNameFullPath,
2178 ROOT::TMetaUtils::GetModuleFileName(modulename));
2179 LoadPCM(pcmFileNameFullPath.str().str());
2186 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2188#if defined(R__MUST_REVISIT)
2189#if R__MUST_REVISIT(6,2)
2190 Warning(
"TCling::RegisterModule",
"Diagnostics suppression should be gone by now.");
2194 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand){
2197 const cling::Transaction* watermark =
fInterpreter->getLastTransaction();
2198 cling::Interpreter::CompilationResult compRes =
fInterpreter->parseForModule(code.
Data());
2204 assert(cling::Interpreter::kSuccess == compRes &&
2205 "Payload code of a dictionary could not be parsed correctly.");
2206 if (compRes!=cling::Interpreter::kSuccess) {
2207 Warning(
"TCling::RegisterModule",
2208 "Problems declaring payload for module %s.", modulename) ;
2221 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand) {
2224 "#undef __ROOTCLING__\n"
2225 + gInterpreterClassDef +
2230 assert(isSharedLib);
2233 dlclose(dyLibHandle);
2253 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2259 if ( i->first == oldcl ) {
2282 const char* input_line,
2283 cling::Interpreter::CompilationResult& compRes,
2287 return metaProcessor->process(input_line, compRes, result);
2289 catch (cling::InterpreterException&
ex)
2291 Error(
"HandleInterpreterException",
"%s.\n%s",
ex.what(),
"Execution of your code was aborted.");
2293 compRes = cling::Interpreter::kFailure;
2302 if (
auto ie =
dynamic_cast<const cling::InterpreterException*
>(&
e)) {
2328 gROOT->SetLineIsProcessing();
2332 gROOT->SetLineHasBeenProcessed();
2345 gROOT->SetLineIsProcessing();
2347 struct InterpreterFlagsRAII {
2349 bool fWasDynamicLookupEnabled;
2351 InterpreterFlagsRAII(cling::Interpreter* interp):
2353 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2357 ~InterpreterFlagsRAII() {
2358 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2359 gROOT->SetLineHasBeenProcessed();
2368 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2369 if (!strncmp(sLine.
Data(),
".L", 2) || !strncmp(sLine.
Data(),
".x", 2) ||
2370 !strncmp(sLine.
Data(),
".X", 2)) {
2378 aclicMode, arguments, io);
2379 if (aclicMode.
Length()) {
2381 R__ASSERT(aclicMode[0]==
'+' &&
"ACLiC mode must start with a +");
2383 if (aclicMode[1]==
'+') {
2389 compRes = cling::Interpreter::kFailure;
2391 if (strncmp(sLine.
Data(),
".L", 2) != 0) {
2394 if (arguments.
Length()==0) {
2403 mod_line =
function + arguments + io;
2409 size_t unnamedMacroOpenCurly;
2412 std::string codeline;
2413 std::ifstream in(fname);
2415 std::getline(in, codeline);
2416 code += codeline +
"\n";
2418 unnamedMacroOpenCurly
2419 = cling::utils::isUnnamedMacro(code,
fInterpreter->getCI()->getLangOpts());
2423 if (unnamedMacroOpenCurly != std::string::npos) {
2425 unnamedMacroOpenCurly);
2435 if (0!=strncmp(sLine.
Data(),
".autodict ",10) && sLine !=
".autodict") {
2440 bool isInclusionDirective = sLine.
Contains(
"\n#include") || sLine.
BeginsWith(
"#include");
2441 if (isInclusionDirective) {
2449 if (result.isValid())
2458 case cling::Interpreter::kSuccess: *error =
kNoError;
break;
2459 case cling::Interpreter::kFailure: *error =
kRecoverable;
break;
2460 case cling::Interpreter::kMoreInputExpected: *error =
kProcessing;
break;
2463 if (compRes == cling::Interpreter::kSuccess
2465 && !result.isVoid())
2467 return result.simplisticCastAs<
long>();
2489 if (path[0] ==
'-' && path[1] ==
'I')
2513 static const TClassRef clRefString(
"std::string");
2514 if (clRefString == cl) {
2524 const char* cobj = (
const char*) obj;
2531 auto inspInspect = [&] (ptrdiff_t offset){
2537 switch(complexType) {
2544 inspInspect(
sizeof(
float));
2549 inspInspect(
sizeof(
double));
2554 inspInspect(
sizeof(
int));
2559 inspInspect(
sizeof(
long));
2564 static clang::PrintingPolicy
2566 if (printPol.Indentation) {
2568 printPol.Indentation = 0;
2569 printPol.SuppressInitializers =
true;
2572 const char* clname = cl->
GetName();
2575 const clang::ASTContext& astContext =
fInterpreter->getCI()->getASTContext();
2576 const clang::Decl *scopeDecl = 0;
2581 scopeDecl = clingCI->
GetDecl();
2582 recordType = clingCI->
GetType();
2584 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
2586 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2590 Error(
"InspectMembers",
"Cannot find Decl for class %s", clname);
2593 const clang::CXXRecordDecl* recordDecl
2594 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2596 Error(
"InspectMembers",
"Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2605 astContext.getASTRecordLayout(recordDecl);
2607 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2608 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2611 const clang::ASTRecordLayout& recLayout
2612 = astContext.getASTRecordLayout(recordDecl);
2619 if (cl->
Size() != recLayout.getSize().getQuantity()) {
2620 Error(
"InspectMembers",
"TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2624 unsigned iNField = 0;
2627 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2628 eField = recordDecl->field_end(); iField != eField;
2629 ++iField, ++iNField) {
2632 clang::QualType memberQT = iField->getType();
2635 memberQT = ROOT::TMetaUtils::ReSubstTemplateArg(memberQT, recordType);
2637 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT,
fNormalizedCtxt->GetConfig(),
false );
2638 if (memberQT.isNull()) {
2639 std::string memberName;
2640 llvm::raw_string_ostream stream(memberName);
2642 printPol.AnonymousTagLocations =
false;
2643 iField->getNameForDiagnostic(stream, printPol,
true );
2645 Error(
"InspectMembers",
2646 "Cannot retrieve QualType for member %s while inspecting class %s",
2647 memberName.c_str(), clname);
2650 const clang::Type* memType = memberQT.getTypePtr();
2652 std::string memberName;
2653 llvm::raw_string_ostream stream(memberName);
2655 printPol.AnonymousTagLocations =
false;
2656 iField->getNameForDiagnostic(stream, printPol,
true );
2658 Error(
"InspectMembers",
2659 "Cannot retrieve Type for member %s while inspecting class %s",
2660 memberName.c_str(), clname);
2665 Bool_t ispointer =
false;
2666 if (memNonPtrType->isPointerType()) {
2668 clang::QualType ptrQT
2669 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2672 ptrQT = ROOT::TMetaUtils::ReSubstTemplateArg(ptrQT, recordType);
2674 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT,
fNormalizedCtxt->GetConfig(),
false );
2675 if (ptrQT.isNull()) {
2676 std::string memberName;
2677 llvm::raw_string_ostream stream(memberName);
2679 printPol.AnonymousTagLocations =
false;
2680 iField->getNameForDiagnostic(stream, printPol,
true );
2682 Error(
"InspectMembers",
2683 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2684 memberName.c_str(), clname);
2687 memNonPtrType = ptrQT.getTypePtr();
2691 llvm::SmallString<8> arraySize;
2692 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2693 unsigned arrLevel = 0;
2694 bool haveErrorDueToArray =
false;
2698 const clang::ConstantArrayType* constArrType =
2699 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2701 constArrType->getSize().toStringUnsigned(arraySize);
2704 clang::QualType subArrQT = arrType->getElementType();
2705 if (subArrQT.isNull()) {
2706 std::string memberName;
2707 llvm::raw_string_ostream stream(memberName);
2709 printPol.AnonymousTagLocations =
false;
2710 iField->getNameForDiagnostic(stream, printPol,
true );
2712 Error(
"InspectMembers",
2713 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2714 arrLevel, subArrQT.getAsString(printPol).c_str(),
2715 memberName.c_str(), clname);
2716 haveErrorDueToArray =
true;
2719 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2721 if (haveErrorDueToArray) {
2726 std::string fieldName;
2727 if (memType->isPointerType()) {
2732 std::string ioname(iField->getName());
2733 ROOT::TMetaUtils::ExtractAttrPropertyFromName(**iField,
"ioname",ioname);
2734 fieldName += ioname;
2735 fieldName += arraySize;
2740 clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2741 ptrdiff_t fieldOffset = offset.getQuantity();
2751 auto iFiledQtype = iField->getType();
2752 if (
auto tagDecl = iFiledQtype->getAsTagDecl()){
2753 auto declAccess = tagDecl->getAccess();
2754 if (declAccess == AS_private || declAccess == AS_protected) {
2760 insp.
Inspect(
const_cast<TClass*
>(cl), insp.
GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2763 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2764 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
2767 std::string sFieldRecName;
2768 if (!ROOT::TMetaUtils::ExtractAttrPropertyFromName(*fieldRecDecl,
"iotype",sFieldRecName)){
2770 clang::QualType(memNonPtrType,0),
2780 insp.
InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
2781 (fieldName +
'.').c_str(), transient);
2789 unsigned iNBase = 0;
2790 for (clang::CXXRecordDecl::base_class_const_iterator iBase
2791 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
2792 iBase != eBase; ++iBase, ++iNBase) {
2793 clang::QualType baseQT = iBase->getType();
2794 if (baseQT.isNull()) {
2795 Error(
"InspectMembers",
2796 "Cannot find QualType for base number %d while inspecting class %s",
2800 const clang::CXXRecordDecl* baseDecl
2801 = baseQT->getAsCXXRecordDecl();
2803 Error(
"InspectMembers",
2804 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
2809 std::string sBaseName;
2811 std::vector<TClass*> foundClasses;
2813 if (foundClasses.size()==1){
2814 baseCl=foundClasses[0];
2827 std::string qualNameForDiag;
2828 ROOT::TMetaUtils::GetQualifiedName(qualNameForDiag, *baseDecl);
2829 Error(
"InspectMembers",
2830 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
2835 if (iBase->isVirtual()) {
2838 Error(
"InspectMembers",
2839 "Base %s of class %s is virtual but no object provided",
2840 sBaseName.c_str(), clname);
2848 baseOffset = ci->
GetBaseOffset(baseCi,
const_cast<void*
>(obj),
2850 if (baseOffset == -1) {
2851 Error(
"InspectMembers",
2852 "Error calculating offset of virtual base %s of class %s",
2853 sBaseName.c_str(), clname);
2856 Error(
"InspectMembers",
2857 "Cannot calculate offset of virtual base %s of class %s",
2858 sBaseName.c_str(), clname);
2863 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
2910 bool oldDynLookup =
fInterpreter->isDynamicLookupEnabled();
2937 assert(
GetRootMapFiles() == 0 &&
"Must be called before LoadLibraryMap!");
2961 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.
Data());
2976 llvm::StringRef ModuleName(libname);
2977 ModuleName = llvm::sys::path::stem(ModuleName);
2978 ModuleName.consume_front(
"lib");
2980 clang::ModuleMap &moduleMap =
fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
2981 clang::Module *M = moduleMap.findModule(ModuleName);
2982 return M && !M->IsMissingRequirement && M->getASTFile();
3000 std::string file_name = filename;
3001 size_t at = std::string::npos;
3002 while ((at = file_name.find(
"/./")) != std::string::npos)
3003 file_name.replace(at, 3,
"/");
3005 std::string filesStr =
"";
3006 llvm::raw_string_ostream filesOS(filesStr);
3007 clang::SourceManager &SM =
fInterpreter->getCI()->getSourceManager();
3008 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3011 llvm::SmallVector<llvm::StringRef, 100> files;
3012 llvm::StringRef(filesStr).split(files,
"\n");
3014 std::set<std::string> fileMap;
3016 for (llvm::SmallVector<llvm::StringRef, 100>::const_iterator
3017 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3018 if ((*iF) == file_name.c_str())
return kTRUE;
3019 fileMap.insert(*iF);
3022 if (fileMap.empty())
return kFALSE;
3025 TString sFilename(file_name.c_str());
3027 && fileMap.count(sFilename.
Data())) {
3035 while (incPath.
Index(
" :") != -1) {
3039 sFilename = file_name.c_str();
3041 && fileMap.count(sFilename.
Data())) {
3050 const clang::DirectoryLookup *CurDir = 0;
3051 clang::Preprocessor &PP =
fInterpreter->getCI()->getPreprocessor();
3052 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3053 const clang::FileEntry *FE = HS.LookupFile(file_name.c_str(),
3054 clang::SourceLocation(),
3057 clang::ArrayRef<std::pair<
const clang::FileEntry *,
3058 const clang::DirectoryEntry *>>(),
3068 if (FE && FE->isValid()) {
3070 clang::SourceManager &SM =
fInterpreter->getCI()->getSourceManager();
3072 clang::FileID FID = SM.translateFile(FE);
3073 if (!FID.isInvalid() && FID.getHashValue() == 0)
3076 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3077 if (SLocE.isFile() && SLocE.getFile().getContentCache()->getRawBuffer() == 0)
3079 if (!FID.isInvalid())
3083 sFilename = FE->getName();
3085 && fileMap.count(sFilename.
Data())) {
3093#if defined(R__MACOSX)
3101static bool R__UpdateLibFileForLinking(
TString &lib)
3103 const char *mapfile =
nullptr;
3105 mapfile =
"/System/Library/dyld/dyld_shared_cache_x86_64.map";
3107 mapfile =
"/System/Library/dyld/dyld_shared_cache_arm64e.map";
3109 #error unsupported architecture
3111 if (std::ifstream cacheMap{mapfile}) {
3113 while (getline(cacheMap,
line)) {
3114 if (
line.find(lib) != std::string::npos) {
3118 if (lib ==
"-loah" || lib ==
"-lRosetta")
3135#if defined(R__WIN32) || defined(__CYGWIN__)
3136 HMODULE hModules[1024];
3138 unsigned long cbModules;
3140 hProcess = (
void *)::GetCurrentProcess();
3141 ::EnumProcessModules(hProcess, hModules,
sizeof(hModules), &cbModules);
3143 for (i = 1; i < (cbModules /
sizeof(
void *)); i++) {
3144 static const int bufsize = 260;
3145 wchar_t winname[bufsize];
3146 char posixname[bufsize];
3147 ::GetModuleFileNameExW(hProcess, hModules[i], winname, bufsize);
3148#if defined(__CYGWIN__)
3149 cygwin_conv_path(CCP_WIN_W_TO_POSIX, winname, posixname, bufsize);
3151 std::wstring wpath = winname;
3152 std::replace(wpath.begin(), wpath.end(),
'\\',
'/');
3153 string path(wpath.begin(), wpath.end());
3154 strncpy(posixname, path.c_str(), bufsize);
3160#elif defined(R__MACOSX)
3164 while (
const mach_header* mh = _dyld_get_image_header(imageIndex)) {
3166 if (mh->filetype == MH_DYLIB) {
3167 if (
const char* imageName = _dyld_get_image_name(imageIndex)) {
3175#elif defined(R__LINUX)
3188 PointerNo4* procLinkMap = (PointerNo4*)dlopen(0, RTLD_LAZY | RTLD_GLOBAL);
3191 LinkMap* linkMap = (LinkMap*) ((PointerNo4*)procLinkMap->fPtr)->fPtr;
3195 dlclose(procLinkMap);
3199 while (iDyLib->fNext) {
3200 iDyLib = iDyLib->fNext;
3205 Error(
"TCling::UpdateListOfLoadedSharedLibraries",
3206 "Platform not supported!");
3217 if (!filename)
return;
3221 cling::DynamicLibraryManager* DLM =
fInterpreter->getDynamicLibraryManager();
3222 if (!DLM->isLibraryLoaded(filename)) {
3223 DLM->loadLibrary(filename,
true );
3226#if defined(R__MACOSX)
3228 auto lenFilename = strlen(filename);
3229 if (!strncmp(filename,
"/usr/lib/system/", 16)
3230 || !strncmp(filename,
"/usr/lib/libc++", 15)
3231 || !strncmp(filename,
"/System/Library/Frameworks/", 27)
3232 || !strncmp(filename,
"/System/Library/PrivateFrameworks/", 34)
3233 || !strncmp(filename,
"/System/Library/CoreServices/", 29)
3234 || !strcmp(filename,
"cl_kernels")
3235 || strstr(filename,
"/usr/lib/libSystem")
3236 || strstr(filename,
"/usr/lib/libstdc++")
3237 || strstr(filename,
"/usr/lib/libicucore")
3238 || strstr(filename,
"/usr/lib/libbsm")
3239 || strstr(filename,
"/usr/lib/libobjc")
3240 || strstr(filename,
"/usr/lib/libresolv")
3241 || strstr(filename,
"/usr/lib/libauto")
3242 || strstr(filename,
"/usr/lib/libcups")
3243 || strstr(filename,
"/usr/lib/libDiagnosticMessagesClient")
3244 || strstr(filename,
"/usr/lib/liblangid")
3245 || strstr(filename,
"/usr/lib/libCRFSuite")
3246 || strstr(filename,
"/usr/lib/libpam")
3247 || strstr(filename,
"/usr/lib/libOpenScriptingUtil")
3248 || strstr(filename,
"/usr/lib/libextension")
3249 || strstr(filename,
"/usr/lib/libAudioToolboxUtility")
3253 || (lenFilename > 4 && !strcmp(filename + lenFilename - 4,
".tbd")))
3256 R__UpdateLibFileForLinking(sFileName);
3257 filename = sFileName.
Data();
3258#elif defined(__CYGWIN__)
3260 static const int bufsize = 260;
3261 char posixwindir[bufsize];
3262 char *windir = getenv(
"WINDIR");
3264 cygwin_conv_path(CCP_WIN_A_TO_POSIX, windir, posixwindir, bufsize);
3266 snprintf(posixwindir,
sizeof(posixwindir),
"/Windows/");
3267 if (strstr(filename, posixwindir) ||
3268 strstr(filename,
"/usr/bin/cyg"))
3270#elif defined(R__WIN32)
3271 if (strstr(filename,
"/Windows/"))
3273#elif defined (R__LINUX)
3274 if (strstr(filename,
"/ld-linux")
3275 || strstr(filename,
"linux-gnu/")
3276 || strstr(filename,
"/libstdc++.")
3277 || strstr(filename,
"/libgcc")
3278 || strstr(filename,
"/libc.")
3279 || strstr(filename,
"/libdl.")
3280 || strstr(filename,
"/libm."))
3297 assert(!
IsFromRootCling() &&
"Trying to load library from rootcling!");
3301 cling::DynamicLibraryManager* DLM =
fInterpreter->getDynamicLibraryManager();
3302 std::string canonLib = DLM->lookupLibrary(filename);
3303 cling::DynamicLibraryManager::LoadLibResult res
3304 = cling::DynamicLibraryManager::kLoadLibNotFound;
3305 if (!canonLib.empty()) {
3307 res = DLM->loadLibrary(filename, system);
3311 cling::Interpreter::CompilationResult compRes;
3313 if (compRes == cling::Interpreter::kSuccess)
3314 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3318 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3322 case cling::DynamicLibraryManager::kLoadLibSuccess:
return 0;
3323 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded:
return 1;
3373 Warning(
"Calc",
"waiting for cling thread to free");
3376 gROOT->SetLineIsProcessing();
3384 cling::Interpreter::CompilationResult cr =
fInterpreter->evaluate(
line, valRef);
3385 if (cr != cling::Interpreter::kSuccess) {
3393 if (!valRef.isValid()) {
3402 if (valRef.isVoid()) {
3409 gROOT->SetLineHasBeenProcessed();
3412 return valRef.simplisticCastAs<
long>();
3419 void (*histaddFunc)(
const char*
line))
3424#if defined(R__MUST_REVISIT)
3425#if R__MUST_REVISIT(6,2)
3426 Warning(
"SetGetline",
"Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3439 if ((std::distance(
T.decls_begin(),
T.decls_end()) != 1)
3440 ||
T.deserialized_decls_begin() !=
T.deserialized_decls_end()
3441 ||
T.macros_begin() !=
T.macros_end()
3442 || ((!
T.getFirstDecl().isNull()) && ((*
T.getFirstDecl().begin()) !=
T.getWrapperFD()))) {
3465 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)
fgSetOfSpecials)->find(obj);
3483#if defined(R__MUST_REVISIT)
3484#if R__MUST_REVISIT(6,2)
3486 Warning(
"Reset",
"Cling should support the equivalent of scratch_upto(&fDictPos)");
3496#if defined(R__MUST_REVISIT)
3497#if R__MUST_REVISIT(6,2)
3499 Warning(
"ResetAll",
"Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3526#if defined(R__MUST_REVISIT)
3527#if R__MUST_REVISIT(6,2)
3529 Warning(
"ResetGlobalVar",
"Cling should support the equivalent of resetglobalvar(obj)");
3541#if defined(R__MUST_REVISIT)
3542#if R__MUST_REVISIT(6,2)
3544 Warning(
"RewindDictionary",
"Cling should provide a way to revert transaction similar to rewinddictionary()");
3555#if defined(R__MUST_REVISIT)
3556#if R__MUST_REVISIT(6,2)
3558 Warning(
"DeleteGlobal",
"Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3570#if defined(R__MUST_REVISIT)
3571#if R__MUST_REVISIT(6,2)
3572 Warning(
"DeleteVariable",
"should do more that just reseting the value to zero");
3577 llvm::StringRef srName(
name);
3578 const char* unscopedName =
name;
3579 llvm::StringRef::size_type posScope = srName.rfind(
"::");
3580 const clang::DeclContext* declCtx = 0;
3581 if (posScope != llvm::StringRef::npos) {
3582 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
3583 const clang::Decl* scopeDecl
3584 = lh.findScope(srName.substr(0, posScope),
3585 cling::LookupHelper::WithDiagnostics);
3587 Error(
"DeleteVariable",
"Cannot find enclosing scope for variable %s",
3591 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3593 Error(
"DeleteVariable",
3594 "Enclosing scope for variable %s is not a declaration context",
3598 unscopedName += posScope + 2;
3602 clang::NamedDecl* nVarDecl
3603 = cling::utils::Lookup::Named(&
fInterpreter->getSema(), unscopedName, declCtx);
3605 Error(
"DeleteVariable",
"Unknown variable %s",
name);
3608 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3610 Error(
"DeleteVariable",
"Entity %s is not a variable",
name);
3614 clang::QualType qType = varDecl->getType();
3618 if (
type->isPointerType()) {
3619 int** ppInt = (
int**)
fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3621 if (ppInt) *ppInt = 0;
3631#if defined(R__MUST_REVISIT)
3632#if R__MUST_REVISIT(6,2)
3634 Warning(
"SaveContext",
"Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3644#if defined(R__MUST_REVISIT)
3645#if R__MUST_REVISIT(6,2)
3647 Warning(
"SaveGlobalsContext",
"Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3681struct AlternateTupleIntDoubleAsc
3687struct AlternateTupleIntDoubleDes
3695 std::tuple<int,double> value;
3696 AlternateTupleIntDoubleAsc asc;
3697 AlternateTupleIntDoubleDes des;
3699 size_t offset0 = ((
char*)&(std::get<0>(value))) - ((
char*)&value);
3700 size_t offset1 = ((
char*)&(std::get<1>(value))) - ((
char*)&value);
3702 size_t ascOffset0 = ((
char*)&(asc._0)) - ((
char*)&asc);
3703 size_t ascOffset1 = ((
char*)&(asc._1)) - ((
char*)&asc);
3705 size_t desOffset0 = ((
char*)&(des._0)) - ((
char*)&des);
3706 size_t desOffset1 = ((
char*)&(des._1)) - ((
char*)&des);
3708 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3710 }
else if (offset0 == desOffset0 && offset1 == desOffset1) {
3717static std::string
AlternateTuple(
const char *classname,
const cling::LookupHelper& lh)
3720 std::string alternateName =
"TEmulatedTuple";
3721 alternateName.append( classname + 5 );
3723 std::string fullname =
"ROOT::Internal::" + alternateName;
3724 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
3728 std::string guard_name;
3729 ROOT::TMetaUtils::GetCppName(guard_name,alternateName.c_str());
3730 std::ostringstream guard;
3731 guard <<
"ROOT_INTERNAL_TEmulated_";
3732 guard << guard_name;
3734 std::ostringstream alternateTuple;
3735 alternateTuple <<
"#ifndef " << guard.str() <<
"\n";
3736 alternateTuple <<
"#define " << guard.str() <<
"\n";
3737 alternateTuple <<
"namespace ROOT { namespace Internal {\n";
3738 alternateTuple <<
"template <class... Types> struct TEmulatedTuple;\n";
3739 alternateTuple <<
"template <> struct " << alternateName <<
" {\n";
3744 unsigned int nMember = 0;
3745 auto iter = tupleContent.
fElements.begin() + 1;
3746 auto theEnd = tupleContent.
fElements.end() - 1;
3747 while (iter != theEnd) {
3748 alternateTuple <<
" " << *iter <<
" _" << nMember <<
";\n";
3755 unsigned int nMember = tupleContent.
fElements.size() - 3;
3756 auto iter = tupleContent.
fElements.rbegin() + 1;
3757 auto theEnd = tupleContent.
fElements.rend() - 1;
3758 while (iter != theEnd) {
3759 alternateTuple <<
" " << *iter <<
" _" << nMember <<
";\n";
3766 Fatal(
"TCling::SetClassInfo::AlternateTuple",
3767 "Layout of std::tuple on this platform is unexpected.");
3772 alternateTuple <<
"};\n";
3773 alternateTuple <<
"}}\n";
3774 alternateTuple <<
"#endif\n";
3776 Error(
"Load",
"Could not declare %s",alternateName.c_str());
3779 alternateName =
"ROOT::Internal::" + alternateName;
3780 return alternateName;
3823 if (strncmp(cl->
GetName(),
"tuple<",strlen(
"tuple<"))==0) {
3855 zombieCandidate =
kTRUE;
3862 zombieCandidate =
kTRUE;
3916 static const char *anonEnum =
"anonymous enum ";
3917 static const int cmplen = strlen(anonEnum);
3944 const char *classname =
name;
3955 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
3957 const clang::Decl *decl
3958 = lh.findScope(classname,
3959 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
3960 : cling::LookupHelper::NoDiagnostics,
3964 decl = lh.findScope(buf,
3965 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
3966 : cling::LookupHelper::NoDiagnostics,
3983 clang::ClassTemplateSpecializationDecl *tmpltDecl =
3984 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
3985 (
type->getAsCXXRecordDecl());
3986 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4005 if (tci.
Property() & propertiesMask) {
4006 bool hasClassDefInline =
false;
4007 if (isClassOrNamespaceOnly) {
4013 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4015 bool success =
false;
4016 std::tie(success, lineNumber) =
4017 ROOT::TMetaUtils::GetTrivialIntegralReturnValue(implLineFunc.GetMethodDecl(), *
fInterpreter);
4018 hasClassDefInline = success && (lineNumber == -1);
4027 if (hasClassDefInline)
4070 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
4071 const clang::Decl *decl
4072 = lh.findClassTemplate(
name,
4073 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4074 : cling::LookupHelper::NoDiagnostics);
4076 std::string strname =
"std::";
4078 decl = lh.findClassTemplate(strname,
4079 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4080 : cling::LookupHelper::NoDiagnostics);
4106 cl->
fBase = listOfBase;
4122 D =
fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4125 if (
const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4128 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4129 const_cast< clang::DeclContext *
>(DC)->collectAllContexts(allDeclContexts);
4130 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(), declEnd = allDeclContexts.end();
4131 declIter != declEnd; ++declIter) {
4133 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4134 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4135 if (
const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4138 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4139 llvm::raw_string_ostream stream(buf);
4141 Policy.AnonymousTagLocations =
false;
4142 ED->getNameForDiagnostic(stream, Policy,
false);
4146 const char*
name = buf.c_str();
4170 D =
fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4174 if (
const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4177 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4178 const_cast< clang::DeclContext *
>(DC)->collectAllContexts(allDeclContexts);
4179 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(),
4180 declEnd = allDeclContexts.end(); declIter != declEnd; ++declIter) {
4182 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4183 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4184 if (
const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4185 funcTempList->
Get(FTD);
4243 if (
m->fMethodArgs) {
4254 m->fMethodArgs = arglist;
4293 if (llvm::isa<clang::NamespaceDecl>(cli->
GetDecl())) {
4302 Error(
"GenerateTClass",
4303 "Cannot find %s::Class_Version()! Class version might be wrong.",
4308 newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->
GetDecl()),
4310 if (newvers == -1) {
4318 newvers = callfunc.
ExecInt(0);
4320 Error(
"GenerateTClass",
4321 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4325 if (newvers != oldvers) {
4342static void GenerateTClass_GatherInnerIncludes(cling::Interpreter *interp,
TString &includes,
TClingClassInfo *info)
4346 const clang::ClassTemplateSpecializationDecl *templateCl
4347 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->
GetDecl());
4349 for(
unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
4350 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4352 const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
4354 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4356 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4359 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4360 GenerateTClass_GatherInnerIncludes(interp, includes, &subinfo);
4363 llvm::raw_string_ostream OS(Result);
4364 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4365 Warning(
"TCling::GenerateTClass",
"Missing header file for %s",OS.str().c_str());
4380 if (!info || !info->
IsValid()) {
4381 Fatal(
"GenerateTClass",
"Requires a valid ClassInfo object");
4386 std::string classname;
4390 Info(
"GenerateTClass",
"Will (try to) generate the compiled TClass for %s.",classname.c_str());
4394 GenerateTClass_GatherInnerIncludes(
fInterpreter,includes,info);
4400 Error(
"GenerateTClass",
"Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4406 cl =
new TClass(classinfo, version, 0, 0, -1, -1, silent);
4412 cl =
new TClass(classinfo, 1, 0, 0, -1, -1, silent);
4437 if (classes == 0 || classes[0] == 0) {
4438 Error(
"TCling::GenerateDictionary",
"Cannot generate dictionary without passing classes.");
4442 std::vector<std::string> listClasses;
4444 const char* current = classes, *prev = classes;
4448 if (*current ==
';') {
4449 listClasses.push_back(std::string(prev, current - prev));
4452 else if (*(current + 1) == 0) {
4453 listClasses.push_back(std::string(prev, current + 1 - prev));
4457 std::vector<std::string> listIncludes;
4461 const char* current = includes, *prev = includes;
4465 if (*current ==
';') {
4466 listIncludes.push_back(std::string(prev, current - prev));
4469 else if (*(current + 1) == 0) {
4470 listIncludes.push_back(std::string(prev, current + 1 - prev));
4476 std::vector<std::string>(), std::vector<std::string>());
4497 if (
const ValueDecl* decl = (
const ValueDecl*)
d){
4499 bool hasIoName = ROOT::TMetaUtils::ExtractAttrPropertyFromName(*decl,
"ioname",ioName);
4500 if (hasIoName && ioName !=
name)
return 0;
4512 using namespace clang;
4514 DeclarationName DName = &SemaR.Context.Idents.get(
name);
4516 LookupResult
R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4517 Sema::ForRedeclaration);
4521 cling::utils::Lookup::Named(&SemaR,
R);
4525 while (
F.hasNext()) {
4526 NamedDecl *D =
F.next();
4527 if (isa<VarDecl>(D) || isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
4528 isa<IndirectFieldDecl>(D))
4534 if (
R.isSingleResult())
4535 return R.getFoundDecl();
4547 const clang::Decl* possibleEnum = 0;
4552 const clang::DeclContext* dc = 0;
4553 if (
const clang::Decl* D = cci->
GetDecl()) {
4554 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4555 dc = dyn_cast<clang::RecordDecl>(D);
4562 possibleEnum = cling::utils::Lookup::Tag(&
fInterpreter->getSema(),
name, dc);
4564 Error(
"TCling::GetEnum",
"DeclContext not found for %s .\n",
name);
4573 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4574 && isa<clang::EnumDecl>(possibleEnum)) {
4575 return possibleEnum;
4587 llvm::StringRef mangled_name = gv->getName();
4602 std::string scopename(demangled_name_c);
4603 free(demangled_name_c);
4609 std::string dataname;
4611 if (!strncmp(scopename.c_str(),
"typeinfo for ",
sizeof(
"typeinfo for ")-1)) {
4612 scopename.erase(0,
sizeof(
"typeinfo for ")-1);
4613 }
else if (!strncmp(scopename.c_str(),
"vtable for ",
sizeof(
"vtable for ")-1)) {
4614 scopename.erase(0,
sizeof(
"vtable for ")-1);
4617 std::string::size_type pos = scopename.rfind(
'(');
4618 if (pos != std::string::npos) {
4622 pos = scopename.rfind(
':');
4623 if (pos != std::string::npos) {
4624 if ((pos != 0) && (scopename[pos-1] ==
':')) {
4625 dataname = scopename.substr(pos+1);
4626 scopename.erase(pos-1);
4630 dataname = scopename;
4638 if (scopename.size()) {
4654 Error(
"GetDataMemberWithValue()",
"not implemented");
4664 Error(
"GetDataMemberAtAddr()",
"not implemented");
4674 const char* params,
Bool_t objectIsConst )
4686 func.
SetFunc(&gcl, method, params, &offset);
4692 return mangled_name;
4707 GetMethod(method,
proto, objectIsConst, 0 , mode).GetMangledName();
4719 const char* params,
Bool_t objectIsConst )
4731 func.
SetFunc(&gcl, method, params, &offset);
4760 std::vector<DeclId_t>& res)
const
4763 clang::ASTContext& Ctx =
S.Context;
4764 const clang::Decl* CtxDecl
4766 Ctx.getTranslationUnitDecl();
4767 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
4768 const clang::DeclContext* DeclCtx = RecDecl;
4771 DeclCtx = dyn_cast<clang::NamespaceDecl>(CtxDecl);
4772 if (!DeclCtx)
return;
4774 clang::DeclarationName DName;
4779 if (RecDecl->getNameAsString() == funcname) {
4780 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
4781 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
4782 }
else if (funcname[0] ==
'~' && RecDecl->getNameAsString() == funcname + 1) {
4783 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
4784 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
4786 DName = &Ctx.Idents.get(funcname);
4789 DName = &Ctx.Idents.get(funcname);
4792 clang::LookupResult
R(
S, DName, clang::SourceLocation(),
4793 Sema::LookupOrdinaryName, clang::Sema::ForRedeclaration);
4794 S.LookupQualifiedName(
R,
const_cast<DeclContext*
>(DeclCtx));
4795 if (
R.empty())
return;
4797 res.reserve(res.size() + (
R.end() -
R.begin()));
4798 for (clang::LookupResult::iterator IR =
R.begin(), ER =
R.end();
4800 if (
const clang::FunctionDecl* FD
4801 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
4802 if (!FD->getDescribedFunctionTemplate()) {
4962 const char* params,
Bool_t objectIsConst,
int* error)
4975 void* address = (
void*)((
Long_t)addr + offset);
4982 const char* params,
int* error)
4984 Execute(obj,cl,method,params,
false,error);
4999 Error(
"Execute",
"No method was defined");
5008 if (argc > nparms) {
5009 Error(
"Execute",
"Too many parameters to call %s, got %d but expected at most %d.",method->
GetName(),argc,nparms);
5012 if (nparms != argc) {
5022 Int_t firstDefault = -1;
5023 for (
Int_t i = 0; i < nparms; i ++) {
5030 if (firstDefault >= 0) {
5031 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);
5033 Error(
"Execute",
"Too few arguments to call %s, got only %d but expected %d.",method->
GetName(),argc,nparms);
5039 const char* listpar =
"";
5044 for (
Int_t i = 0; i < argc; i ++) {
5053 chpar += (nxtpar->
String()).ReplaceAll(
"\"",
"\\\"");
5060 complete += nxtpar->
String();
5063 listpar = complete.
Data();
5081 const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->
GetMethodDecl());
5083 void* address = (
void*)((
Long_t)addr + offset);
5090 const void* args[] ,
5095 Error(
"ExecuteWithArgsAndReturn",
"No method was defined");
5122 Warning(
"GetTopLevelMacroName",
"Must change return type!");
5169#if defined(R__MUST_REVISIT)
5170#if R__MUST_REVISIT(6,0)
5171 Warning(
"GetCurrentMacroName",
"Must change return type!");
5184 TTHREAD_TLS(
char*) t = 0;
5185 TTHREAD_TLS(
unsigned int) tlen = 0;
5187 unsigned int dlen = strlen(typeDesc);
5190 t =
new char[dlen + 1];
5193 const char*
s, *template_start;
5194 if (!strstr(typeDesc,
"(*)(")) {
5195 s = strchr(typeDesc,
' ');
5196 template_start = strchr(typeDesc,
'<');
5197 if (!strcmp(typeDesc,
"long long")) {
5198 strlcpy(t, typeDesc, dlen + 1);
5200 else if (!strncmp(typeDesc,
"unsigned ",
s + 1 - typeDesc)) {
5201 strlcpy(t, typeDesc, dlen + 1);
5207 else if (
s && (template_start == 0 || (
s < template_start))) {
5208 strlcpy(t,
s + 1, dlen + 1);
5211 strlcpy(t, typeDesc, dlen + 1);
5215 strlcpy(t, typeDesc, dlen + 1);
5218 while (
l > 0 && (t[
l - 1] ==
'*' || t[
l - 1] ==
'&')) {
5226 assert(rootmapfile && *rootmapfile);
5228 llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5229 libName.consume_back(
".rootmap");
5231 return !
gInterpreter->HasPCMForLibrary(libName.str().c_str());
5242 if (!(rootmapfile && *rootmapfile))
5249 const std::map<char, unsigned int> keyLenMap = {{
'c',6},{
'n',10},{
't',8},{
'h',7},{
'e',5},{
'v',4}};
5251 std::string rootmapfileNoBackslash(rootmapfile);
5253 std::replace(rootmapfileNoBackslash.begin(), rootmapfileNoBackslash.end(),
'\\',
'/');
5260 uniqueString->
Append(std::string(
"\n#line 1 \"Forward declarations from ") + rootmapfileNoBackslash +
"\"\n");
5262 std::ifstream
file(rootmapfileNoBackslash);
5265 std::string lib_name;
5267 bool newFormat =
false;
5268 while (getline(
file,
line,
'\n')) {
5269 if (!newFormat && (
line.compare(0, 8,
"Library.") == 0 ||
line.compare(0, 8,
"Declare.") == 0)) {
5275 if (
line.compare(0, 9,
"{ decls }") == 0) {
5278 while (getline(
file,
line,
'\n')) {
5281 if (!uniqueString) {
5282 Error(
"ReadRootmapFile",
"Cannot handle \"{ decls }\" sections in custom rootmap file %s",
5283 rootmapfileNoBackslash.c_str());
5289 const char firstChar =
line[0];
5290 if (firstChar ==
'[') {
5292 auto brpos =
line.find(
']');
5293 if (brpos == string::npos)
5295 lib_name =
line.substr(1, brpos - 1);
5297 while (lib_name[nspaces] ==
' ')
5300 lib_name.replace(0, nspaces,
"");
5302 TString lib_nameTstr(lib_name.c_str());
5307 Info(
"ReadRootmapFile",
"new section for %s", lib_nameTstr.
Data());
5309 Info(
"ReadRootmapFile",
"section for %s (library does not exist)", lib_nameTstr.
Data());
5315 auto keyLenIt = keyLenMap.find(firstChar);
5316 if (keyLenIt == keyLenMap.end())
5318 unsigned int keyLen = keyLenIt->second;
5320 const char *keyname =
line.c_str() + keyLen;
5322 Info(
"ReadRootmapFile",
"class %s in %s", keyname, lib_name.c_str());
5325 if (lib_name != isThere->
GetValue()) {
5326 if (firstChar ==
'n') {
5328 Info(
"ReadRootmapFile",
"namespace %s found in %s is already in %s", keyname, lib_name.c_str(),
5330 }
else if (firstChar ==
'h') {
5335 Warning(
"ReadRootmapFile",
"%s %s found in %s is already in %s",
line.substr(0, keyLen).c_str(),
5336 keyname, lib_name.c_str(), isThere->
GetValue());
5340 Info(
"ReadRootmapFile",
"Key %s was already defined for %s", keyname, lib_name.c_str());
5401 using namespace clang;
5403 class ExtVisibleStorageAdder:
public RecursiveASTVisitor<ExtVisibleStorageAdder>{
5409 ExtVisibleStorageAdder(std::unordered_set<const NamespaceDecl*>& nsSet): fNSSet(nsSet) {};
5410 bool VisitNamespaceDecl(NamespaceDecl* nsDecl) {
5415 nsDecl->setHasExternalVisibleStorage();
5416 fNSSet.insert(nsDecl);
5420 std::unordered_set<const NamespaceDecl*>& fNSSet;
5468 for (
Int_t j = 0; j < i; j++) {
5479 Info(
"LoadLibraryMap",
"%s",
d.Data());
5484 if (
f.EndsWith(
".rootmap")) {
5490 Info(
"LoadLibraryMap",
" rootmap file: %s", p.