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>
150#define R__DLLEXPORT __attribute__ ((visibility ("default")))
158#include <mach-o/dyld.h>
159#include <mach-o/loader.h>
173#if defined(__CYGWIN__)
174#include <sys/cygwin.h>
175#define HMODULE void *
177 __declspec(dllimport)
void * __stdcall GetCurrentProcess();
178 __declspec(dllimport)
bool __stdcall EnumProcessModules(
void *,
void **,
unsigned long,
unsigned long *);
179 __declspec(dllimport)
unsigned long __stdcall GetModuleFileNameExW(
void *,
void *,
wchar_t *,
unsigned long);
186# define STDIN_FILENO 0
189# define STDOUT_FILENO 1
192# define STDERR_FILENO 2
201#undef GetModuleFileName
202#define RTLD_DEFAULT ((void *)::GetModuleHandle(NULL))
203#define dlsym(library, function_name) ::GetProcAddress((HMODULE)library, function_name)
204#define dlopen(library_name, flags) ::LoadLibraryA(library_name)
205#define dlclose(library) ::FreeLibrary((HMODULE)library)
206#define R__DLLEXPORT __declspec(dllexport)
214 return D->getDeclContext();
217 return llvm::dyn_cast<clang::NamespaceDecl>(DC);
220 return llvm::dyn_cast<clang::RecordDecl>(DC);
223 return DC->dumpDeclContext();
232 return ((clang::Decl*)D)->dump();
235 if (clang::NamedDecl* ND = llvm::dyn_cast<clang::NamedDecl>(D)) {
238 llvm::raw_string_ostream OS(
name);
239 ND->getNameForDiagnostic(OS, D->getASTContext().getPrintingPolicy(),
242 printf(
"%s\n",
name.c_str());
250 return D->isInvalidDecl();
254 assert(info && info->
IsValid());
255 return info->
GetDecl()->isInvalidDecl();
259using namespace clang;
263 static const std::string gInterpreterClassDef = R
"ICF(
265#define ClassDef(name, id) \
266_ClassDefInterp_(name,id,virtual,) \
267static int DeclFileLine() { return __LINE__; }
269#define ClassDefNV(name, id) \
270_ClassDefInterp_(name,id,,) \
271static int DeclFileLine() { return __LINE__; }
272#undef ClassDefOverride
273#define ClassDefOverride(name, id) \
274_ClassDefInterp_(name,id,,override) \
275static int DeclFileLine() { return __LINE__; }
278 static const std::string gNonInterpreterClassDef = R
"ICF(
279#define __ROOTCLING__ 1
281#define ClassDef(name,id) \
282_ClassDefOutline_(name,id,virtual,) \
283static int DeclFileLine() { return __LINE__; }
285#define ClassDefNV(name, id)\
286_ClassDefOutline_(name,id,,)\
287static int DeclFileLine() { return __LINE__; }
288#undef ClassDefOverride
289#define ClassDefOverride(name, id)\
290_ClassDefOutline_(name,id,,override)\
291static int DeclFileLine() { return __LINE__; }
295 static const std::string gClassDefInterpMacro = R
"ICF(
298#define _ClassDefInterp_(name,id,virtual_keyword, overrd) \
301 static TClass *Class() { static TClass* sIsA = 0; if (!sIsA) sIsA = TClass::GetClass(#name); return sIsA; } \
302 static const char *Class_Name() { return #name; } \
303 virtual_keyword Bool_t CheckTObjectHashConsistency() const overrd { return true; } \
304 static Version_t Class_Version() { return id; } \
305 static TClass *Dictionary() { return 0; } \
306 virtual_keyword TClass *IsA() const overrd { return name::Class(); } \
307 virtual_keyword void ShowMembers(TMemberInspector&insp) const overrd { ::ROOT::Class_ShowMembers(name::Class(), this, insp); } \
308 virtual_keyword void Streamer(TBuffer&) overrd { ::Error("Streamer", "Cannot stream interpreted class."); } \
309 void StreamerNVirtual(TBuffer&ClassDef_StreamerNVirtual_b) { name::Streamer(ClassDef_StreamerNVirtual_b); } \
310 static const char *DeclFileName() { return __FILE__; } \
311 static int ImplFileLine() { return 0; } \
312 static const char *ImplFileName() { return __FILE__; }
351 return ((
TCling*)
gCling)->LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
390 static vector<const NamedDecl*> updateList;
393 if (entered) topLevel =
kFALSE;
408 updateList.push_back(TD);
411 while (!updateList.empty()) {
413 updateList.pop_back();
420 const clang::Decl* D =
static_cast<const clang::Decl*
>(enumObj->
GetDeclId());
421 if(
const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
423 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
424 EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
426 std::string constbuf;
427 if (
const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
428 PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
429 llvm::raw_string_ostream stream(constbuf);
431 Policy.AnonymousTagLocations =
false;
432 (END)->getNameForDiagnostic(stream, Policy,
false);
434 const char* constantName = constbuf.c_str();
438 const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
439 if (valAPSInt.isSigned()) {
440 value = valAPSInt.getSExtValue();
442 value = valAPSInt.getZExtValue();
449 DataMemberInfo_t* dmInfo = (DataMemberInfo_t*) tcDmInfo;
460 globals->
Add(enumConstant);
472 TEnum* enumType =
nullptr;
473 const clang::Decl* D =
static_cast<const clang::Decl*
>(VD);
475 if (
const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
477 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
478 llvm::raw_string_ostream stream(buf);
480 Policy.AnonymousTagLocations =
false;
481 ED->getNameForDiagnostic(stream, Policy,
false);
487 const char*
name = buf.c_str();
498 const clang::Decl* D =
static_cast<const clang::Decl*
>(DV);
500 if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
501 && !dyn_cast<clang::RecordDecl>(D))
return;
503 if (isa<clang::FunctionDecl>(D->getDeclContext())
504 || isa<clang::TagDecl>(D->getDeclContext()))
508 if (
const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
509 if (RD->getDescribedClassTemplate())
511 }
else if (
const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
512 if (FD->getDescribedFunctionTemplate())
516 if (
const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
517 if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
520 else if (
const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
522 if (
const TagDecl *TD = dyn_cast<TagDecl>(D)) {
526 }
else if (
const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
531 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
535 if (isa<EnumDecl>(ND))
540 if (!(isa<VarDecl>(ND)))
544 if (
gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
548 gROOT->GetListOfGlobals()->Add(
new TGlobal((DataMemberInfo_t *)
550 cast<ValueDecl>(ND),
nullptr)));
582 const char* canonicalName) {
583 ((
TCling*)
gCling)->LibraryLoaded(dyLibHandle, canonicalName);
588 ((
TCling *)
gCling)->RegisterRdictForLoadPCM(pcmFileNameFullPath, pcmContent);
592 const char* canonicalName) {
593 ((
TCling*)
gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
599 return ((
TCling*)
gCling)->GetObjectAddress(Name, LookupCtx);
609 auto tcling =
new TCling(
"C++",
"cling C++ Interpreter", argv, interpLibHandle);
639 return ((
TCling*)
gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
644 string file(fileName);
650 string &args,
string &io,
string &fname)
652 string file(fileName);
653 TString f, amode, arguments, aclicio;
656 io = aclicio.
Data(); fname =
f.Data();
666 char *__unDName(
char *demangled,
const char *mangled,
int out_len,
667 void * (* pAlloc )(
size_t),
void (* pFree )(
void *),
668 unsigned short int flags);
680 using namespace clang;
681 if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
685 if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
698 const std::vector<std::string> &headers,
699 const std::vector<std::string> &fwdDecls,
700 const std::vector<std::string> &unknown)
706 if (classes.empty()) {
710 const std::string& className = classes[0];
712 TString fileName =
"AutoDict_";
713 std::string::const_iterator sIt;
714 for (sIt = className.begin(); sIt != className.end(); ++sIt) {
715 if (*sIt ==
'<' || *sIt ==
'>' ||
716 *sIt ==
' ' || *sIt ==
'*' ||
717 *sIt ==
',' || *sIt ==
'&' ||
725 if (classes.size() > 1) {
727 std::vector<std::string>::const_iterator it = classes.begin();
728 while ((++it) != classes.end()) {
730 chk = chk * 3 + it->at(
cursor);
743 static const std::set<std::string> sSTLTypes {
744 "vector",
"list",
"forward_list",
"deque",
"map",
"unordered_map",
"multimap",
745 "unordered_multimap",
"set",
"unordered_set",
"multiset",
"unordered_multiset",
746 "queue",
"priority_queue",
"stack",
"iterator"};
747 std::vector<std::string>::const_iterator it;
748 std::string fileContent(
"");
749 for (it = headers.begin(); it != headers.end(); ++it) {
750 fileContent +=
"#include \"" + *it +
"\"\n";
752 for (it = unknown.begin(); it != unknown.end(); ++it) {
758 while (dirbase.
Length() && dirbase !=
"."
759 && dirbase !=
"include" && dirbase !=
"inc"
760 && dirbase !=
"prec_stl") {
764 fileContent +=
TString(
"#include \"") + header +
"\"\n";
767 for (it = fwdDecls.begin(); it != fwdDecls.end(); ++it) {
768 fileContent +=
"class " + *it +
";\n";
770 fileContent +=
"#ifdef __CLING__ \n";
771 fileContent +=
"#pragma link C++ nestedclasses;\n";
772 fileContent +=
"#pragma link C++ nestedtypedefs;\n";
773 for (it = classes.begin(); it != classes.end(); ++it) {
775 size_t posTemplate =
n.find(
'<');
776 std::set<std::string>::const_iterator iSTLType = sSTLTypes.end();
777 if (posTemplate != std::string::npos) {
778 n.erase(posTemplate, std::string::npos);
779 if (
n.compare(0, 5,
"std::") == 0) {
782 iSTLType = sSTLTypes.find(
n);
784 fileContent +=
"#pragma link C++ class ";
785 fileContent += *it +
"+;\n" ;
786 fileContent +=
"#pragma link C++ class ";
787 if (iSTLType != sSTLTypes.end()) {
791 fileContent += *it +
"::*;\n" ;
796 fileContent += *it +
"::*+;\n" ;
799 fileContent +=
"#endif\n";
803 filePointer = fopen(fileName,
"w");
804 if (filePointer ==
nullptr) {
810 fprintf(filePointer,
"%s", fileContent.c_str());
826 const std::vector<std::string> &headers,
827 const std::vector<std::string> &fwdDecls,
828 const std::vector<std::string> &unknown)
834 std::vector<std::string> classes;
835 classes.push_back(className);
863 void exceptionErrorHandler(
void * ,
864 const std::string& reason,
866 throw std::runtime_error(std::string(
">>> Interpreter compilation error:\n") + reason);
880 class clangDiagSuppr {
882 clangDiagSuppr(clang::DiagnosticsEngine& diag): fDiagEngine(diag){
883 fOldDiagValue = fDiagEngine.getIgnoreAllWarnings();
884 fDiagEngine.setIgnoreAllWarnings(
true);
888 fDiagEngine.setIgnoreAllWarnings(fOldDiagValue);
891 clang::DiagnosticsEngine& fDiagEngine;
914 if (strncmp(tname.c_str(),
"const ", 6) == 0) {
917 unsigned long end = tname.length();
918 while( end && (tname[end-1]==
'&' || tname[end-1]==
'*' || tname[end-1]==
']') ) {
919 if ( tname[end-1]==
']' ) {
921 while ( end && tname[end-1]!=
'[' ) --end;
925 std::string innerbuf;
927 if (end != tname.length()) {
929 inner = innerbuf.c_str();
931 inner = tname.c_str()+
offset;
935 if (
gROOT->GetListOfClasses()->FindObject(inner)
945 const char *newname =
type->GetFullTypeName();
947 newname =
"Long64_t";
949 newname =
"ULong64_t";
951 if (strcmp(inner,newname) == 0) {
956 if ( end != tname.length() ) {
957 result += tname.substr(end,tname.length()-end);
965 if (lastPos != inner)
969 const auto enName = lastPos;
970 const auto scopeNameSize = ((
Long64_t)lastPos - (
Long64_t)inner) /
sizeof(
decltype(*lastPos)) - 2;
971 char *scopeName =
new char[scopeNameSize + 1];
972 strncpy(scopeName, inner, scopeNameSize);
973 scopeName[scopeNameSize] =
'\0';
975 if (
auto scope =
static_cast<TClass *
>(
gROOT->GetListOfClasses()->FindObject(scopeName))) {
976 auto enumTable =
dynamic_cast<const THashList *
>(scope->GetListOfEnums(
false));
977 if (enumTable && enumTable->THashList::FindObject(enName)) {
delete [] scopeName;
return true; }
981 auto listOfEnums = scope->GetListOfEnums();
983 auto enumTable =
dynamic_cast<const THashList *
>(listOfEnums);
984 if (enumTable && enumTable->THashList::FindObject(enName)) {
delete [] scopeName;
return true; }
991 auto enumTable =
dynamic_cast<const THashList *
>(
gROOT->GetListOfEnums());
992 if (enumTable && enumTable->THashList::FindObject(inner))
return true;
1015 return fContent.c_str();
1023 bool notPresent = fLinesHashSet.emplace(fHashFunc(str)).second;
1037static bool LoadModule(
const std::string &ModuleName, cling::Interpreter &interp)
1047 assert(!currentDir.empty());
1050 ::Info(
"TCling::__LoadModule",
"Preloading module %s. \n",
1051 ModuleName.c_str());
1053 return interp.loadModule(ModuleName,
true);
1059static void LoadModules(
const std::vector<std::string> &modules, cling::Interpreter &interp)
1061 for (
const auto &modName : modules)
1067 const static bool foundSymbol = dlsym(RTLD_DEFAULT,
"usedToIdentifyRootClingByDlSym");
1072static bool HasASTFileOnDisk(clang::Module *M,
const clang::Preprocessor &PP, std::string *FullFileName =
nullptr)
1074 const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1076 std::string ModuleFileName;
1077 if (!HSOpts.PrebuiltModulePaths.empty())
1079 ModuleFileName = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(M->Name);
1081 *FullFileName = ModuleFileName;
1083 return !ModuleFileName.empty();
1089 CompilerInstance &CI = *interp.getCI();
1090 Preprocessor &PP = CI.getPreprocessor();
1091 auto ModuleManager = CI.getASTReader();
1092 assert(ModuleManager);
1097 if (ModuleIndexPath.empty())
1100 ModuleManager->resetForReload();
1101 ModuleManager->loadGlobalIndex();
1102 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1107 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1108 bool RecreateIndex =
false;
1109 for (ModuleMap::module_iterator
I = MMap.module_begin(), E = MMap.module_end();
I != E; ++
I) {
1110 Module *TheModule =
I->second;
1115 RecreateIndex =
true;
1117 if (RecreateIndex) {
1118 cling::Interpreter::PushTransactionRAII deserRAII(&interp);
1119 clang::GlobalModuleIndex::UserDefinedInterestingIDs IDs;
1121 struct DefinitionFinder :
public RecursiveASTVisitor<DefinitionFinder> {
1122 DefinitionFinder(clang::GlobalModuleIndex::UserDefinedInterestingIDs& IDs,
1123 clang::TranslationUnitDecl* TU) : DefinitionIDs(IDs) {
1126 bool VisitNamedDecl(NamedDecl *ND) {
1127 if (!ND->isFromASTFile())
1129 if (!ND->getIdentifier())
1132 if (ND->getAccess() == AS_protected || ND->getAccess() == AS_private)
1135 if (TagDecl *TD = llvm::dyn_cast<TagDecl>(ND)) {
1136 if (TD->isCompleteDefinition())
1138 }
else if (NamespaceDecl *NSD = llvm::dyn_cast<NamespaceDecl>(ND)) {
1139 Register(NSD,
false);
1141 else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(ND))
1147 clang::GlobalModuleIndex::UserDefinedInterestingIDs &DefinitionIDs;
1148 void Register(
const NamedDecl* ND,
bool AddSingleEntry =
true) {
1149 assert(ND->isFromASTFile());
1152 if (!ND->hasOwningModule()) {
1154 SourceManager &SM = ND->getASTContext().getSourceManager();
1155 SourceLocation Loc = ND->getLocation();
1156 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
1158 assert(FE->getName().contains(
"input_line_"));
1163 Module *OwningModule = ND->getOwningModule()->getTopLevelModule();
1164 assert(OwningModule);
1165 assert(!ND->getName().empty() &&
"Empty name");
1166 if (AddSingleEntry && DefinitionIDs.count(ND->getName()))
1172 DefinitionIDs[ND->getName()].push_back(OwningModule->getASTFile());
1175 DefinitionFinder defFinder(IDs, CI.getASTContext().getTranslationUnitDecl());
1177 llvm::cantFail(GlobalModuleIndex::writeIndex(CI.getFileManager(),
1178 CI.getPCHContainerReader(),
1181 ModuleManager->resetForReload();
1182 ModuleManager->loadGlobalIndex();
1183 GlobalIndex = ModuleManager->getGlobalIndex();
1192 if (!clingInterp.getCI()->getLangOpts().Modules)
1196 cling::Interpreter::PushTransactionRAII deserRAII(&clingInterp);
1214 LoadModule(
"_Builtin_intrinsics", clingInterp);
1218 std::vector<std::string> CoreModules = {
"ROOT_Foundation_C",
1221 "ROOT_Foundation_Stage1_NoRTTI",
1230 std::vector<std::string> CommonModules = {
"MathCore"};
1236 std::vector<std::string> FIXMEModules = {
"Hist"};
1237 clang::CompilerInstance &CI = *clingInterp.getCI();
1238 clang::Preprocessor &PP = CI.getPreprocessor();
1239 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1240 if (MMap.findModule(
"RInterface"))
1241 FIXMEModules.push_back(
"RInterface");
1245 GlobalModuleIndex *GlobalIndex =
nullptr;
1249 GlobalIndex = CI.getASTReader()->getGlobalIndex();
1251 llvm::StringSet<> KnownModuleFileNames;
1253 GlobalIndex->getKnownModuleFileNames(KnownModuleFileNames);
1255 std::vector<std::string> PendingModules;
1256 PendingModules.reserve(256);
1257 for (
auto I = MMap.module_begin(), E = MMap.module_end();
I != E; ++
I) {
1258 clang::Module *M =
I->second;
1262 std::string FullASTFilePath;
1266 if (GlobalIndex && KnownModuleFileNames.count(FullASTFilePath))
1269 if (M->IsUnimportable)
1277 if (std::find(CoreModules.begin(), CoreModules.end(), M->Name) != CoreModules.end())
1285 PendingModules.push_back(M->Name);
1292 assert(clingInterp.getMacro(
"gROOT") &&
"Couldn't load gROOT macro?");
1296 clingInterp.declare(R
"CODE(
1308 std::string PreIncludes;
1309 bool hasCxxModules = clingInterp.getCI()->getLangOpts().Modules;
1315 PreIncludes +=
"#include \"RtypesCore.h\"\n";
1318 PreIncludes +=
"#include \"Rtypes.h\"\n";
1320 PreIncludes += gClassDefInterpMacro +
"\n"
1321 + gInterpreterClassDef +
"\n"
1323 "#define ClassImp(X);\n";
1326 PreIncludes +=
"#include <string>\n";
1331 PreIncludes +=
"#include <cassert>\n";
1333 PreIncludes +=
"using namespace std;\n";
1334 clingInterp.declare(PreIncludes);
1354#ifdef R__USE_CXXMODULES
1358 llvm::install_fatal_error_handler(&exceptionErrorHandler);
1362 std::vector<std::string> clingArgsStorage;
1363 clingArgsStorage.push_back(
"cling4root");
1364 for (
const char*
const* arg = argv; *arg; ++arg)
1365 clingArgsStorage.push_back(*arg);
1368 if (!fromRootCling) {
1373 clingArgsStorage.push_back(
"-I" + interpInclude);
1376 clingArgsStorage.push_back(
"-I" + interpInclude +
"/cling");
1379 clingArgsStorage.push_back(
"-I" + interpInclude +
"/cling/plugins/include");
1390 std::string pchFilename = interpInclude +
"/allDict.cxx.pch";
1395 clingArgsStorage.push_back(
"-include-pch");
1396 clingArgsStorage.push_back(pchFilename);
1399 clingArgsStorage.push_back(
"-Wno-undefined-inline");
1400 clingArgsStorage.push_back(
"-fsigned-char");
1403#if !defined(_MSC_VER) || defined(_WIN64)
1404 clingArgsStorage.push_back(
"-O1");
1407 clingArgsStorage.push_back(
"-mllvm");
1408 clingArgsStorage.push_back(
"-optimize-regalloc=0");
1413 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(
"EXTRA_CLING_ARGS");
1414 if (EnvOpt.hasValue()) {
1415 StringRef Env(*EnvOpt);
1416 while (!Env.empty()) {
1418 std::tie(Arg, Env) = Env.split(
' ');
1419 clingArgsStorage.push_back(Arg.str());
1423 auto GetEnvVarPath = [](
const std::string &EnvVar,
1424 std::vector<std::string> &Paths) {
1425 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1426 if (EnvOpt.hasValue()) {
1427 StringRef Env(*EnvOpt);
1428 while (!Env.empty()) {
1431 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1432 Paths.push_back(Arg.str());
1438 std::vector<std::string> Paths;
1443 GetEnvVarPath(
"CLING_PREBUILT_MODULE_PATH", Paths);
1444 std::string EnvVarPath;
1445 for (
const std::string& P : Paths)
1448 gSystem->
Setenv(
"CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1452 EnvOpt = llvm::sys::Process::GetEnv(
"ROOT_CLING_TIMING");
1453 if (EnvOpt.hasValue())
1454 clingArgsStorage.push_back(
"-ftime-report");
1461 std::vector<std::string> ModuleMaps;
1464 GetEnvVarPath(
"CLING_MODULEMAP_FILES", ModuleMaps);
1468 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1469 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1471 for (
const std::string& M : ModuleMaps)
1472 clingArgsStorage.push_back(
"-fmodule-map-file=" + M);
1474 std::string ModulesCachePath;
1475 EnvOpt = llvm::sys::Process::GetEnv(
"CLING_MODULES_CACHE_PATH");
1476 if (EnvOpt.hasValue()){
1477 StringRef Env(*EnvOpt);
1478 assert(llvm::sys::fs::exists(Env) &&
"Path does not exist!");
1479 ModulesCachePath = Env.str();
1484 clingArgsStorage.push_back(
"-fmodules-cache-path=" + ModulesCachePath);
1487 std::vector<const char*> interpArgs;
1488 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1489 eArg = clingArgsStorage.end(); iArg != eArg; ++iArg)
1490 interpArgs.push_back(iArg->c_str());
1497 if (!fromRootCling) {
1499 interpArgs.push_back(
"-fmodules");
1500 interpArgs.push_back(
"-fno-implicit-module-maps");
1504 interpArgs.push_back(
"-Rmodule-build");
1510 interpArgs.push_back(
"-fno-autolink");
1515 interpArgs.push_back(
"-ffast-math");
1521 extraArgs && *extraArgs; ++extraArgs) {
1522 if (!strcmp(*extraArgs,
"-resource-dir")) {
1524 llvmResourceDir = *(++extraArgs);
1526 interpArgs.push_back(*extraArgs);
1530 std::vector<std::string> _empty;
1532 for (
const auto &arg: args)
1533 interpArgs.emplace_back(arg.c_str());
1536 cling::Interpreter::ModuleFileExtensions extensions;
1537 EnvOpt = llvm::sys::Process::GetEnv(
"ROOTDEBUG_RDICT");
1538 if (!EnvOpt.hasValue())
1539 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1541 fInterpreter = std::make_unique<cling::Interpreter>(interpArgs.size(),
1543 llvmResourceDir, extensions,
1547 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHOrModuleValidation =
1548 DisableValidationForModuleKind::All;
1552 fInterpreter->getCI()->getLangOpts().SpellChecking =
false;
1555 auto isModulesArg = [](
const char* arg) {
return !strcmp(arg,
"-fmodules"); };
1556 bool hasModulesArg = std::find_if(interpArgs.begin(), interpArgs.end(), isModulesArg) != interpArgs.end();
1557 fInterpreter->getCI()->getLangOpts().Modules = hasModulesArg;
1562 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO,
false);
1582 if (!fromRootCling) {
1587 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1588 auto &Policy =
const_cast<clang::PrintingPolicy &
>(
fInterpreter->getCI()->getASTContext().getPrintingPolicy());
1592 Policy.SplitTemplateClosers =
true;
1594 Policy.SuppressDefaultTemplateArgs =
false;
1600 std::unique_ptr<TClingCallbacks>
1606 if (!fromRootCling) {
1607 cling::DynamicLibraryManager& DLM = *
fInterpreter->getDynamicLibraryManager();
1612 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) ->
bool{
1613 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1614 return stem.startswith(
"libNew") || stem.startswith(
"libcppyy_backend");
1617 DLM.initializeDyld(ShouldPermanentlyIgnore);
1655 assert(
GetRootMapFiles() ==
nullptr &&
"Must be called before LoadLibraryMap!");
1674 auto setFactory = []() {
1678 static bool doneFactory = setFactory();
1690 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1691 ::Error(
"TCling::RegisterRdictForLoadPCM",
"Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1708 if (listOfKeys && ((listOfKeys->GetSize() == 0) ||
1709 ((listOfKeys->GetSize() == 1) &&
1710 !strcmp(((
TKey *)listOfKeys->At(0))->GetName(),
"EMPTY")
1717 ::Info(
"TCling::LoadPCMImpl",
"reading protoclasses for %s \n", pcmFile.
GetName());
1723 auto listOfGlobals =
gROOT->GetListOfGlobals();
1724 auto listOfEnums =
dynamic_cast<THashList *
>(
gROOT->GetListOfEnums());
1726 for (
auto selEnum : *enums) {
1727 const char *enumScope = selEnum->
GetTitle();
1728 const char *enumName = selEnum->GetName();
1729 if (strcmp(enumScope,
"") == 0) {
1732 if (!listOfEnums->THashList::FindObject(enumName)) {
1733 ((
TEnum *)selEnum)->SetClass(
nullptr);
1734 listOfEnums->Add(selEnum);
1736 for (
auto enumConstant : *
static_cast<TEnum *
>(selEnum)->GetConstants()) {
1737 if (!listOfGlobals->FindObject(enumConstant)) {
1738 listOfGlobals->Add(enumConstant);
1745 if (!nsTClassEntry) {
1748 auto listOfEnums = nsTClassEntry->
fEnums.load();
1759 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1760 ((
TEnum *)selEnum)->SetClass(nsTClassEntry);
1761 listOfEnums->Add(selEnum);
1769 pcmFile.
GetObject(
"__ProtoClasses", protoClasses);
1772 for (
auto obj : *protoClasses) {
1782 for (
auto proto : *protoClasses) {
1790 ::Error(
"TCling::LoadPCM",
"Inconsistent TClassTable for %s",
proto->GetName());
1801 protoClasses->
Clear();
1802 delete protoClasses;
1806 pcmFile.
GetObject(
"__Typedefs", dataTypes);
1808 for (
auto typedf : *dataTypes)
1809 gROOT->GetListOfTypes()->Add(typedf);
1822 assert(!pcmFileNameFullPath.empty());
1823 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1826 TString pcmFileName = pcmFileNameFullPath;
1834 llvm::SaveAndRestore<Int_t> SaveGDebug(
gDebug);
1837 ::Info(
"TCling::LoadPCM",
"Loading ROOT PCM %s", pcmFileName.
Data());
1842 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1847 llvm::StringRef pcmContent = pendingRdict->second;
1849 std::string RDictFileOpts = pcmFileNameFullPath +
"?filetype=pcm";
1850 TMemFile pcmMemFile(RDictFileOpts.c_str(), range);
1865 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1866 ::Error(
"TCling::LoadPCM",
"ROOT PCM %s file does not exist",
1867 pcmFileNameFullPath.data());
1870 ::Info(
"TCling::LoadPCM",
"In-memory ROOT PCM candidate %s\n",
1871 rdict.first.c_str());
1875 if (!
gROOT->IsRootFile(pcmFileName)) {
1876 Fatal(
"LoadPCM",
"The file %s is not a ROOT as was expected\n", pcmFileName.
Data());
1879 TFile pcmFile(pcmFileName +
"?filetype=pcm",
"READ");
1886 using namespace clang;
1888 class ExtLexicalStorageAdder:
public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1893 bool VisitRecordDecl(clang::RecordDecl* rcd){
1895 Info(
"ExtLexicalStorageAdder",
1896 "Adding external lexical storage to class %s",
1897 rcd->getNameAsString().c_str());
1898 auto reDeclPtr = rcd->getMostRecentDecl();
1900 reDeclPtr->setHasExternalLexicalStorage();
1901 }
while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1914 const std::string &ModuleMapName )
const
1916 assert(llvm::sys::path::is_absolute(FullPath));
1917 Preprocessor &PP =
fInterpreter->getCI()->getPreprocessor();
1918 FileManager &FM = PP.getFileManager();
1921 if (
auto DE = FM.getOptionalDirectoryRef(FullPath)) {
1922 HeaderSearch &HS = PP.getHeaderSearchInfo();
1923 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1924 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1925 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1927 HSOpts.AddPrebuiltModulePath(FullPath);
1932 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1933 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1934 if (
auto FE = FM.getOptionalFileRef(ModuleMapFileName,
false,
1936 if (!HS.loadModuleMapFile(*FE,
false))
1938 Error(
"RegisterPrebuiltModulePath",
"Could not load modulemap in %s", ModuleMapFileName.c_str());
1955 "libforward_listDict",
1963 "libunordered_setDict",
1964 "libunordered_multisetDict",
1965 "libunordered_mapDict",
1966 "libunordered_multimapDict",
1974 char dyLibError[1000];
1975 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1976 dyLibError,
sizeof(dyLibError), NULL);
1978 const char *dyLibError = dlerror();
1980 ::Error(
"TCling::RegisterModule",
"Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
1981 (dyLibError) ? dyLibError :
"");
2018 const char** headers,
2019 const char** includePaths,
2020 const char* payloadCode,
2021 const char* fwdDeclsCode,
2022 void (*triggerFunc)(),
2024 const char** classesHeaders,
2025 Bool_t lateRegistration ,
2032 if (fromRootCling)
return;
2041 bool isACLiC = strstr(modulename,
"_ACLiC_dict") !=
nullptr;
2042 if (hasHeaderParsingOnDemand && isACLiC) {
2044 Info(
"TCling::RegisterModule",
2045 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2046 hasHeaderParsingOnDemand =
false;
2060 for (
const char** inclPath = includePaths; *inclPath; ++inclPath) {
2063 cling::Transaction* T =
nullptr;
2065 for (
auto& fwdDeclArgToSkipPair : fwdDeclsArgToSkip){
2066 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2067 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2068 auto compRes =
fInterpreter->declare(fwdDecl.c_str(), &T);
2069 assert(cling::Interpreter::kSuccess == compRes &&
2070 "A fwd declaration could not be compiled");
2071 if (compRes!=cling::Interpreter::kSuccess){
2072 Warning(
"TCling::RegisterModule",
2073 "Problems in declaring string '%s' were encountered.",
2088 TString code = gNonInterpreterClassDef;
2090 code += payloadCode;
2092 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2093 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2095 if (dyLibName.empty()) {
2096 ::Error(
"TCling::RegisterModule",
"Dictionary trigger function for %s not found", modulename);
2101 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2103 bool wasDlopened =
false;
2108 if (!lateRegistration) {
2115 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2125 if (hasHeaderParsingOnDemand && fwdDeclsCode){
2128 std::string fwdDeclsCodeLessEnums;
2132 std::string fwdDeclsLine;
2133 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2134 std::vector<std::string> scopes;
2135 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2136 const auto enumPos = fwdDeclsLine.find(
"enum __attribute__((annotate(\"");
2138 if (enumPos != std::string::npos) {
2145 auto nsPos = fwdDeclsLine.find(
"namespace");
2146 R__ASSERT(nsPos < enumPos &&
"Inconsistent enum and enclosing scope parsing!");
2147 while (nsPos < enumPos && nsPos != std::string::npos) {
2149 const auto nsNameStart = nsPos + 10;
2150 const auto nsNameEnd = fwdDeclsLine.find(
'{', nsNameStart);
2151 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2152 scopes.push_back(nsName);
2153 nsPos = fwdDeclsLine.find(
"namespace", nsNameEnd);
2156 clang::DeclContext* DC =
nullptr;
2157 for (
auto &&aScope: scopes) {
2158 DC = cling::utils::Lookup::Namespace(&
fInterpreter->getSema(), aScope.c_str(), DC);
2164 if (scopes.empty() || DC) {
2166 size_t posEnumName = fwdDeclsLine.find(
"\"))) ", 32);
2167 R__ASSERT(posEnumName != std::string::npos &&
"Inconsistent enum fwd decl!");
2169 while (isspace(fwdDeclsLine[posEnumName]))
2171 size_t posEnumNameEnd = fwdDeclsLine.find(
" : ", posEnumName);
2172 R__ASSERT(posEnumNameEnd != std::string::npos &&
"Inconsistent enum fwd decl (end)!");
2173 while (isspace(fwdDeclsLine[posEnumNameEnd]))
2177 std::string enumName = fwdDeclsLine.substr(posEnumName,
2178 posEnumNameEnd - posEnumName + 1);
2180 if (clang::NamedDecl* enumDecl
2181 = cling::utils::Lookup::Named(&
fInterpreter->getSema(),
2182 enumName.c_str(), DC)) {
2185 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) &&
"not an enum decl!");
2192 fwdDeclsCodeLessEnums += fwdDeclsLine +
"\n";
2196 if (!fwdDeclsCodeLessEnums.empty()){
2197 auto compRes =
fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
2198 assert(cling::Interpreter::kSuccess == compRes &&
2199 "The forward declarations could not be compiled");
2200 if (compRes!=cling::Interpreter::kSuccess){
2201 Warning(
"TCling::RegisterModule",
2202 "Problems in compiling forward declarations for module %s: '%s'",
2203 modulename, fwdDeclsCodeLessEnums.c_str()) ;
2211 ExtLexicalStorageAdder elsa;
2212 for (
auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
2213 cling::Transaction::DelayCallInfo& dci = *dciIt;
2214 for(
auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2215 clang::Decl* declPtr = *dit;
2216 elsa.TraverseDecl(declPtr);
2230 for (
const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2231 temp=*classesHeader;
2233 size_t theTemplateHash = 0;
2234 bool addTemplate =
false;
2235 size_t posTemplate = temp.find(
'<');
2236 if (posTemplate != std::string::npos) {
2238 std::string templateName = temp.substr(0, posTemplate);
2244 for (
const char** classesHeader_inner = classesHeader; 0!=strcmp(*classesHeader_inner,
"@"); ++classesHeader_inner,++classesHeader){
2246 if (payloadCode == *classesHeader_inner ){
2248 if (addTemplate)
fPayloads.insert(theTemplateHash);
2251 Info(
"TCling::RegisterModule",
2252 "Adding a header for %s", temp.c_str());
2258 addTemplate =
false;
2266 bool ModuleWasSuccessfullyLoaded =
false;
2268 std::string ModuleName = modulename;
2269 if (llvm::StringRef(modulename).startswith(
"lib"))
2270 ModuleName = llvm::StringRef(modulename).substr(3).str();
2275 clang::Preprocessor &PP = TheSema.getPreprocessor();
2276 std::string ModuleMapName;
2278 ModuleMapName = ModuleName +
".modulemap";
2280 ModuleMapName =
"module.modulemap";
2288 if (!ModuleWasSuccessfullyLoaded) {
2290 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2291 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2292 if (moduleMap.findModule(ModuleName))
2293 Info(
"TCling::RegisterModule",
"Module %s in modulemap failed to load.", ModuleName.c_str());
2298 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2301 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2302 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2303 llvm::sys::path::append(pcmFileNameFullPath,
2305 LoadPCM(pcmFileNameFullPath.str().str());
2312 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2314#if defined(R__MUST_REVISIT)
2315#if R__MUST_REVISIT(6,2)
2316 Warning(
"TCling::RegisterModule",
"Diagnostics suppression should be gone by now.");
2320 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand){
2323 const cling::Transaction* watermark =
fInterpreter->getLastTransaction();
2324 cling::Interpreter::CompilationResult compRes =
fInterpreter->parseForModule(code.
Data());
2330 assert(cling::Interpreter::kSuccess == compRes &&
2331 "Payload code of a dictionary could not be parsed correctly.");
2332 if (compRes!=cling::Interpreter::kSuccess) {
2333 Warning(
"TCling::RegisterModule",
2334 "Problems declaring payload for module %s.", modulename) ;
2347 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand) {
2350 "#undef __ROOTCLING__\n"
2351 + gInterpreterClassDef +
2356 assert(isSharedLib);
2359 dlclose(dyLibHandle);
2365 ASTContext &C = CI.getASTContext();
2373 if (IdentifierInfoLookup *External = C.Idents.getExternalIdentifierLookup()) {
2374 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2375 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2376 std::string
I = Ident.str();
2400 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2406 if ( i->first == oldcl ) {
2429 const char* input_line,
2430 cling::Interpreter::CompilationResult& compRes,
2434 return metaProcessor->process(input_line, compRes,
result);
2436 catch (cling::InterpreterException&
ex)
2438 Error(
"HandleInterpreterException",
"%s\n%s",
ex.what(),
"Execution of your code was aborted.");
2440 compRes = cling::Interpreter::kFailure;
2449 if (
auto ie =
dynamic_cast<const cling::InterpreterException*
>(&
e)) {
2475 gROOT->SetLineIsProcessing();
2479 gROOT->SetLineHasBeenProcessed();
2492 gROOT->SetLineIsProcessing();
2494 struct InterpreterFlagsRAII {
2495 cling::Interpreter* fInterpreter;
2496 bool fWasDynamicLookupEnabled;
2498 InterpreterFlagsRAII(cling::Interpreter* interp):
2499 fInterpreter(interp),
2500 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2502 fInterpreter->enableDynamicLookup(
true);
2504 ~InterpreterFlagsRAII() {
2505 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2506 gROOT->SetLineHasBeenProcessed();
2515 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2516 if (!strncmp(sLine.
Data(),
".L", 2) || !strncmp(sLine.
Data(),
".x", 2) ||
2517 !strncmp(sLine.
Data(),
".X", 2)) {
2525 aclicMode, arguments, io);
2526 if (aclicMode.
Length()) {
2528 R__ASSERT(aclicMode[0]==
'+' &&
"ACLiC mode must start with a +");
2530 if (aclicMode[1]==
'+') {
2536 compRes = cling::Interpreter::kFailure;
2538 if (strncmp(sLine.
Data(),
".L", 2) != 0) {
2541 if (arguments.
Length()==0) {
2550 mod_line = function + arguments + io;
2556 size_t unnamedMacroOpenCurly;
2559 std::string codeline;
2562 std::ifstream in(fname, std::ifstream::binary);
2564 std::getline(in, codeline);
2565 code += codeline +
"\n";
2567 unnamedMacroOpenCurly
2568 = cling::utils::isUnnamedMacro(code,
fInterpreter->getCI()->getLangOpts());
2572 if (unnamedMacroOpenCurly != std::string::npos) {
2574 unnamedMacroOpenCurly);
2584 if (0!=strncmp(sLine.
Data(),
".autodict ",10) && sLine !=
".autodict") {
2589 bool isInclusionDirective = sLine.
Contains(
"\n#include") || sLine.
BeginsWith(
"#include");
2590 if (isInclusionDirective) {
2607 case cling::Interpreter::kSuccess: *error =
kNoError;
break;
2608 case cling::Interpreter::kFailure: *error =
kRecoverable;
break;
2609 case cling::Interpreter::kMoreInputExpected: *error =
kProcessing;
break;
2612 if (compRes == cling::Interpreter::kSuccess
2643 if (path[0] ==
'-' && path[1] ==
'I')
2668 static const TClassRef clRefString(
"std::string");
2669 if (clRefString == cl) {
2679 const char* cobj = (
const char*) obj;
2686 auto inspInspect = [&] (ptrdiff_t
offset){
2692 switch(complexType) {
2699 inspInspect(
sizeof(
float));
2704 inspInspect(
sizeof(
double));
2709 inspInspect(
sizeof(
int));
2714 inspInspect(
sizeof(
long));
2719 static clang::PrintingPolicy
2721 if (printPol.Indentation) {
2723 printPol.Indentation = 0;
2724 printPol.SuppressInitializers =
true;
2727 const char* clname = cl->
GetName();
2730 const clang::ASTContext& astContext =
fInterpreter->getCI()->getASTContext();
2731 const clang::Decl *scopeDecl =
nullptr;
2732 const clang::Type *recordType =
nullptr;
2736 scopeDecl = clingCI->
GetDecl();
2737 recordType = clingCI->
GetType();
2739 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
2741 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2745 Error(
"InspectMembers",
"Cannot find Decl for class %s", clname);
2748 const clang::CXXRecordDecl* recordDecl
2749 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2751 Error(
"InspectMembers",
"Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2760 astContext.getASTRecordLayout(recordDecl);
2762 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2763 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2766 const clang::ASTRecordLayout& recLayout
2767 = astContext.getASTRecordLayout(recordDecl);
2774 if (cl->
Size() != recLayout.getSize().getQuantity()) {
2775 Error(
"InspectMembers",
"TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2779 unsigned iNField = 0;
2782 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2783 eField = recordDecl->field_end(); iField != eField;
2784 ++iField, ++iNField) {
2787 clang::QualType memberQT = iField->getType();
2792 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT,
fNormalizedCtxt->
GetConfig(),
false );
2793 if (memberQT.isNull()) {
2794 std::string memberName;
2795 llvm::raw_string_ostream stream(memberName);
2797 printPol.AnonymousTagLocations =
false;
2798 iField->getNameForDiagnostic(stream, printPol,
true );
2800 Error(
"InspectMembers",
2801 "Cannot retrieve QualType for member %s while inspecting class %s",
2802 memberName.c_str(), clname);
2805 const clang::Type* memType = memberQT.getTypePtr();
2807 std::string memberName;
2808 llvm::raw_string_ostream stream(memberName);
2810 printPol.AnonymousTagLocations =
false;
2811 iField->getNameForDiagnostic(stream, printPol,
true );
2813 Error(
"InspectMembers",
2814 "Cannot retrieve Type for member %s while inspecting class %s",
2815 memberName.c_str(), clname);
2819 const clang::Type* memNonPtrType = memType;
2820 Bool_t ispointer =
false;
2821 if (memNonPtrType->isPointerType()) {
2823 clang::QualType ptrQT
2824 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2829 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT,
fNormalizedCtxt->
GetConfig(),
false );
2830 if (ptrQT.isNull()) {
2831 std::string memberName;
2832 llvm::raw_string_ostream stream(memberName);
2834 printPol.AnonymousTagLocations =
false;
2835 iField->getNameForDiagnostic(stream, printPol,
true );
2837 Error(
"InspectMembers",
2838 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2839 memberName.c_str(), clname);
2842 memNonPtrType = ptrQT.getTypePtr();
2846 llvm::SmallString<8> arraySize;
2847 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2848 unsigned arrLevel = 0;
2849 bool haveErrorDueToArray =
false;
2853 const clang::ConstantArrayType* constArrType =
2854 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2856 constArrType->getSize().toStringUnsigned(arraySize);
2859 clang::QualType subArrQT = arrType->getElementType();
2860 if (subArrQT.isNull()) {
2861 std::string memberName;
2862 llvm::raw_string_ostream stream(memberName);
2864 printPol.AnonymousTagLocations =
false;
2865 iField->getNameForDiagnostic(stream, printPol,
true );
2867 Error(
"InspectMembers",
2868 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2869 arrLevel, subArrQT.getAsString(printPol).c_str(),
2870 memberName.c_str(), clname);
2871 haveErrorDueToArray =
true;
2874 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2876 if (haveErrorDueToArray) {
2881 std::string fieldName;
2882 if (memType->isPointerType()) {
2887 std::string ioname(iField->getName());
2889 fieldName += ioname;
2890 fieldName += arraySize;
2895 clang::CharUnits
offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2896 ptrdiff_t fieldOffset =
offset.getQuantity();
2906 auto iFiledQtype = iField->getType();
2907 if (
auto tagDecl = iFiledQtype->getAsTagDecl()){
2908 auto declAccess = tagDecl->getAccess();
2909 if (declAccess == AS_private || declAccess == AS_protected) {
2915 insp.
Inspect(
const_cast<TClass*
>(cl), insp.
GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2918 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2919 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
2922 std::string sFieldRecName;
2925 clang::QualType(memNonPtrType,0),
2935 insp.
InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
2936 (fieldName +
'.').c_str(), transient);
2944 unsigned iNBase = 0;
2945 for (clang::CXXRecordDecl::base_class_const_iterator iBase
2946 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
2947 iBase != eBase; ++iBase, ++iNBase) {
2948 clang::QualType baseQT = iBase->getType();
2949 if (baseQT.isNull()) {
2950 Error(
"InspectMembers",
2951 "Cannot find QualType for base number %d while inspecting class %s",
2955 const clang::CXXRecordDecl* baseDecl
2956 = baseQT->getAsCXXRecordDecl();
2958 Error(
"InspectMembers",
2959 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
2964 std::string sBaseName;
2966 std::vector<TClass*> foundClasses;
2968 if (foundClasses.size()==1){
2969 baseCl=foundClasses[0];
2982 std::string qualNameForDiag;
2984 Error(
"InspectMembers",
2985 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
2990 if (iBase->isVirtual()) {
2993 Error(
"InspectMembers",
2994 "Base %s of class %s is virtual but no object provided",
2995 sBaseName.c_str(), clname);
3003 baseOffset = ci->
GetBaseOffset(baseCi,
const_cast<void*
>(obj),
3005 if (baseOffset == -1) {
3006 Error(
"InspectMembers",
3007 "Error calculating offset of virtual base %s of class %s",
3008 sBaseName.c_str(), clname);
3011 Error(
"InspectMembers",
3012 "Cannot calculate offset of virtual base %s of class %s",
3013 sBaseName.c_str(), clname);
3018 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3065 bool oldDynLookup =
fInterpreter->isDynamicLookupEnabled();
3094 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.
Data());
3109 llvm::StringRef ModuleName(libname);
3110 ModuleName = llvm::sys::path::stem(ModuleName);
3111 ModuleName.consume_front(
"lib");
3119 clang::ModuleMap &moduleMap =
fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3120 clang::Module *M = moduleMap.findModule(ModuleName);
3121 return M && !M->IsUnimportable && M->getASTFile();
3140 size_t at = std::string::npos;
3141 while ((at = file_name.find(
"/./")) != std::string::npos)
3142 file_name.replace(at, 3,
"/");
3144 std::string filesStr =
"";
3145 llvm::raw_string_ostream filesOS(filesStr);
3146 clang::SourceManager &SM =
fInterpreter->getCI()->getSourceManager();
3147 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3150 llvm::SmallVector<llvm::StringRef, 100> files;
3151 llvm::StringRef(filesStr).split(files,
"\n");
3153 std::set<std::string> fileMap;
3154 llvm::StringRef file_name_ref(file_name);
3156 for (llvm::SmallVector<llvm::StringRef, 100>::const_iterator
3157 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3158 if ((*iF) == file_name_ref)
return kTRUE;
3159 fileMap.insert(iF->str());
3162 if (fileMap.empty())
return kFALSE;
3165 TString sFilename(file_name.c_str());
3167 && fileMap.count(sFilename.
Data())) {
3175 while (incPath.
Index(
" :") != -1) {
3179 sFilename = file_name.c_str();
3181 && fileMap.count(sFilename.
Data())) {
3190 const clang::DirectoryLookup *CurDir =
nullptr;
3191 clang::Preprocessor &PP =
fInterpreter->getCI()->getPreprocessor();
3192 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3193 auto FE = HS.LookupFile(file_name.c_str(),
3194 clang::SourceLocation(),
3197 clang::ArrayRef<std::pair<
const clang::FileEntry *,
3198 const clang::DirectoryEntry *>>(),
3209 if (FE && FE->isValid()) {
3211 clang::SourceManager &SM =
fInterpreter->getCI()->getSourceManager();
3213 clang::FileID FID = SM.translateFile(*FE);
3214 if (!FID.isInvalid() && FID.getHashValue() == 0)
3217 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3218 if (SLocE.isFile() && !SLocE.getFile().getContentCache().getBufferIfLoaded())
3220 if (!FID.isInvalid())
3224 sFilename = FE->getName().str();
3226 && fileMap.count(sFilename.
Data())) {
3234#if defined(R__MACOSX)
3242static bool R__UpdateLibFileForLinking(
TString &lib)
3244 const char *mapfile =
nullptr;
3246 mapfile =
"/System/Library/dyld/dyld_shared_cache_x86_64.map";
3248 mapfile =
"/System/Library/dyld/dyld_shared_cache_arm64e.map";
3250 #error unsupported architecture
3252 if (std::ifstream cacheMap{mapfile}) {
3254 while (getline(cacheMap,
line)) {
3255 if (
line.find(lib) != std::string::npos) {
3273static int callback_for_dl_iterate_phdr(
struct dl_phdr_info *info,
size_t size,
void *
data)
3276 static std::unordered_set<
decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3278 auto newLibs =
static_cast<std::vector<std::string>*
>(
data);
3279 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3281 if (info->dlpi_name && info->dlpi_name[0]
3282 && strncmp(info->dlpi_name,
"linux-vdso.so", 13)
3283 && strncmp(info->dlpi_name,
"linux-vdso32.so", 15)
3284 && strncmp(info->dlpi_name,
"linux-vdso64.so", 15)
3285 && strncmp(info->dlpi_name,
"linux-gate.so", 13))
3286 newLibs->emplace_back(info->dlpi_name);
3287 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3300#if defined(R__WIN32) || defined(__CYGWIN__)
3301 HMODULE hModules[1024];
3303 unsigned long cbModules;
3305 hProcess = (
void *)::GetCurrentProcess();
3306 ::EnumProcessModules(hProcess, hModules,
sizeof(hModules), &cbModules);
3308 for (i = 1; i < (cbModules /
sizeof(
void *)); i++) {
3309 static const int bufsize = 260;
3310 wchar_t winname[bufsize];
3311 char posixname[bufsize];
3312 ::GetModuleFileNameExW(hProcess, hModules[i], winname, bufsize);
3313#if defined(__CYGWIN__)
3314 cygwin_conv_path(CCP_WIN_W_TO_POSIX, winname, posixname, bufsize);
3316 std::wstring wpath = winname;
3317 std::replace(wpath.begin(), wpath.end(),
'\\',
'/');
3318 string path(wpath.begin(), wpath.end());
3319 strncpy(posixname, path.c_str(), bufsize);
3325#elif defined(R__MACOSX)
3329 while (
const mach_header* mh = _dyld_get_image_header(imageIndex)) {
3331 if (mh->filetype == MH_DYLIB) {
3332 if (
const char* imageName = _dyld_get_image_name(imageIndex)) {
3340#elif defined(R__LINUX)
3344 std::vector<std::string> newLibs;
3345 dl_iterate_phdr(callback_for_dl_iterate_phdr, &newLibs);
3346 for (
auto &&lib: newLibs)
3349 Error(
"TCling::UpdateListOfLoadedSharedLibraries",
3350 "Platform not supported!");
3356static bool StartsWithStrLit(
const char *haystack,
const char (&needle)[
N]) {
3357 return !strncmp(haystack, needle,
N - 1);
3372 cling::DynamicLibraryManager* DLM =
fInterpreter->getDynamicLibraryManager();
3373 if (!DLM->isLibraryLoaded(
filename)) {
3374 DLM->loadLibrary(
filename,
true ,
true );
3377#if defined(R__MACOSX)
3379 auto lenFilename = strlen(
filename);
3380 auto isInMacOSSystemDir = [](
const char *fn) {
3381 return StartsWithStrLit(fn,
"/usr/lib/") || StartsWithStrLit(fn,
"/System/Library/");
3383 if (!strcmp(
filename,
"cl_kernels")
3386 || StartsWithStrLit(
filename,
"/usr/lib/system/")
3387 || StartsWithStrLit(
filename,
"/usr/lib/libc++")
3388 || StartsWithStrLit(
filename,
"/System/Library/Frameworks/")
3389 || StartsWithStrLit(
filename,
"/System/Library/PrivateFrameworks/")
3390 || StartsWithStrLit(
filename,
"/System/Library/CoreServices/")
3391 || StartsWithStrLit(
filename,
"/usr/lib/libSystem")
3392 || StartsWithStrLit(
filename,
"/usr/lib/libstdc++")
3393 || StartsWithStrLit(
filename,
"/usr/lib/libicucore")
3394 || StartsWithStrLit(
filename,
"/usr/lib/libbsm")
3395 || StartsWithStrLit(
filename,
"/usr/lib/libobjc")
3396 || StartsWithStrLit(
filename,
"/usr/lib/libresolv")
3397 || StartsWithStrLit(
filename,
"/usr/lib/libauto")
3398 || StartsWithStrLit(
filename,
"/usr/lib/libcups")
3399 || StartsWithStrLit(
filename,
"/usr/lib/libDiagnosticMessagesClient")
3400 || StartsWithStrLit(
filename,
"/usr/lib/liblangid")
3401 || StartsWithStrLit(
filename,
"/usr/lib/libCRFSuite")
3402 || StartsWithStrLit(
filename,
"/usr/lib/libpam")
3403 || StartsWithStrLit(
filename,
"/usr/lib/libOpenScriptingUtil")
3404 || StartsWithStrLit(
filename,
"/usr/lib/libextension")
3405 || StartsWithStrLit(
filename,
"/usr/lib/libAudioToolboxUtility")
3406 || StartsWithStrLit(
filename,
"/usr/lib/liboah")
3407 || StartsWithStrLit(
filename,
"/usr/lib/libRosetta")
3408 || StartsWithStrLit(
filename,
"/usr/lib/libCoreEntitlements")
3409 || StartsWithStrLit(
filename,
"/usr/lib/libssl.")
3410 || StartsWithStrLit(
filename,
"/usr/lib/libcrypto.")
3416 || StartsWithStrLit(
filename,
"/usr/lib/system/libsystem_kernel")
3417 || StartsWithStrLit(
filename,
"/usr/lib/system/libsystem_platform")
3418 || StartsWithStrLit(
filename,
"/usr/lib/system/libsystem_pthread")
3423 || (lenFilename > 4 && !strcmp(
filename + lenFilename - 4,
".tbd")))
3426 R__UpdateLibFileForLinking(sFileName);
3428#elif defined(__CYGWIN__)
3430 static const int bufsize = 260;
3431 char posixwindir[bufsize];
3432 char *windir = getenv(
"WINDIR");
3434 cygwin_conv_path(CCP_WIN_A_TO_POSIX, windir, posixwindir, bufsize);
3436 snprintf(posixwindir,
sizeof(posixwindir),
"/Windows/");
3437 if (strstr(
filename, posixwindir) ||
3440#elif defined(R__WIN32)
3443#elif defined (R__LINUX)
3467 assert(!
IsFromRootCling() &&
"Trying to load library from rootcling!");
3471 cling::DynamicLibraryManager* DLM =
fInterpreter->getDynamicLibraryManager();
3472 std::string canonLib = DLM->lookupLibrary(
filename);
3473 cling::DynamicLibraryManager::LoadLibResult res
3474 = cling::DynamicLibraryManager::kLoadLibNotFound;
3475 if (!canonLib.empty()) {
3477 res = DLM->loadLibrary(
filename, system,
true);
3481 cling::Interpreter::CompilationResult compRes;
3483 if (compRes == cling::Interpreter::kSuccess)
3484 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3488 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3492 case cling::DynamicLibraryManager::kLoadLibSuccess:
return 0;
3493 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded:
return 1;
3543 Warning(
"Calc",
"waiting for cling thread to free");
3546 gROOT->SetLineIsProcessing();
3553 cling::Value valRef;
3554 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3558 catch (cling::InterpreterException&
ex)
3560 Error(
"Calc",
"%s.\n%s",
ex.what(),
"Evaluation of your expression was aborted.");
3562 cr = cling::Interpreter::kFailure;
3565 if (cr != cling::Interpreter::kSuccess) {
3573 if (!valRef.isValid()) {
3582 if (valRef.isVoid()) {
3589 gROOT->SetLineHasBeenProcessed();
3599 void (*histaddFunc)(
const char*
line))
3604#if defined(R__MUST_REVISIT)
3605#if R__MUST_REVISIT(6,2)
3606 Warning(
"SetGetline",
"Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3619 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3620 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3621 || T.macros_begin() != T.macros_end()
3622 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3645 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)
fgSetOfSpecials)->find(obj);
3663#if defined(R__MUST_REVISIT)
3664#if R__MUST_REVISIT(6,2)
3666 Warning(
"Reset",
"Cling should support the equivalent of scratch_upto(&fDictPos)");
3676#if defined(R__MUST_REVISIT)
3677#if R__MUST_REVISIT(6,2)
3679 Warning(
"ResetAll",
"Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3706#if defined(R__MUST_REVISIT)
3707#if R__MUST_REVISIT(6,2)
3709 Warning(
"ResetGlobalVar",
"Cling should support the equivalent of resetglobalvar(obj)");
3721#if defined(R__MUST_REVISIT)
3722#if R__MUST_REVISIT(6,2)
3724 Warning(
"RewindDictionary",
"Cling should provide a way to revert transaction similar to rewinddictionary()");
3735#if defined(R__MUST_REVISIT)
3736#if R__MUST_REVISIT(6,2)
3738 Warning(
"DeleteGlobal",
"Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3750#if defined(R__MUST_REVISIT)
3751#if R__MUST_REVISIT(6,2)
3752 Warning(
"DeleteVariable",
"should do more that just reseting the value to zero");
3757 llvm::StringRef srName(
name);
3758 const char* unscopedName =
name;
3759 llvm::StringRef::size_type posScope = srName.rfind(
"::");
3760 const clang::DeclContext* declCtx =
nullptr;
3761 if (posScope != llvm::StringRef::npos) {
3762 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
3763 const clang::Decl* scopeDecl
3764 = lh.findScope(srName.substr(0, posScope),
3765 cling::LookupHelper::WithDiagnostics);
3767 Error(
"DeleteVariable",
"Cannot find enclosing scope for variable %s",
3771 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3773 Error(
"DeleteVariable",
3774 "Enclosing scope for variable %s is not a declaration context",
3778 unscopedName += posScope + 2;
3782 clang::NamedDecl* nVarDecl
3783 = cling::utils::Lookup::Named(&
fInterpreter->getSema(), unscopedName, declCtx);
3785 Error(
"DeleteVariable",
"Unknown variable %s",
name);
3788 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3790 Error(
"DeleteVariable",
"Entity %s is not a variable",
name);
3794 clang::QualType qType = varDecl->getType();
3795 const clang::Type*
type = qType->getUnqualifiedDesugaredType();
3798 if (
type->isPointerType()) {
3799 int** ppInt = (
int**)
fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3801 if (ppInt) *ppInt =
nullptr;
3811#if defined(R__MUST_REVISIT)
3812#if R__MUST_REVISIT(6,2)
3814 Warning(
"SaveContext",
"Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3824#if defined(R__MUST_REVISIT)
3825#if R__MUST_REVISIT(6,2)
3827 Warning(
"SaveGlobalsContext",
"Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3875 std::tuple<int,double>
value;
3879 size_t offset0 = ((
char*)&(std::get<0>(
value))) - ((
char*)&
value);
3880 size_t offset1 = ((
char*)&(std::get<1>(
value))) - ((
char*)&
value);
3882 size_t ascOffset0 = ((
char*)&(asc.
_0)) - ((
char*)&asc);
3883 size_t ascOffset1 = ((
char*)&(asc.
_1)) - ((
char*)&asc);
3885 size_t desOffset0 = ((
char*)&(des.
_0)) - ((
char*)&des);
3886 size_t desOffset1 = ((
char*)&(des.
_1)) - ((
char*)&des);
3888 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3890 }
else if (offset0 == desOffset0 && offset1 == desOffset1) {
3897static std::string
AlternateTuple(
const char *classname,
const cling::LookupHelper& lh)
3900 std::string alternateName =
"TEmulatedTuple";
3901 alternateName.append( classname + 5 );
3903 std::string fullname =
"ROOT::Internal::" + alternateName;
3904 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
3908 std::string guard_name;
3910 std::ostringstream guard;
3911 guard <<
"ROOT_INTERNAL_TEmulated_";
3912 guard << guard_name;
3914 std::ostringstream alternateTuple;
3915 alternateTuple <<
"#ifndef " << guard.str() <<
"\n";
3916 alternateTuple <<
"#define " << guard.str() <<
"\n";
3917 alternateTuple <<
"namespace ROOT { namespace Internal {\n";
3918 alternateTuple <<
"template <class... Types> struct TEmulatedTuple;\n";
3919 alternateTuple <<
"template <> struct " << alternateName <<
" {\n";
3924 unsigned int nMember = 0;
3925 auto iter = tupleContent.
fElements.begin() + 1;
3926 auto theEnd = tupleContent.
fElements.end() - 1;
3927 while (iter != theEnd) {
3928 alternateTuple <<
" " << *iter <<
" _" << nMember <<
";\n";
3935 unsigned int nMember = tupleContent.
fElements.size() - 3;
3936 auto iter = tupleContent.
fElements.rbegin() + 1;
3937 auto theEnd = tupleContent.
fElements.rend() - 1;
3938 while (iter != theEnd) {
3939 alternateTuple <<
" " << *iter <<
" _" << nMember <<
";\n";
3946 Fatal(
"TCling::SetClassInfo::AlternateTuple",
3947 "Layout of std::tuple on this platform is unexpected.");
3952 alternateTuple <<
"};\n";
3953 alternateTuple <<
"}}\n";
3954 alternateTuple <<
"#endif\n";
3956 Error(
"Load",
"Could not declare %s",alternateName.c_str());
3959 alternateName =
"ROOT::Internal::" + alternateName;
3960 return alternateName;
4000 auto SetWithoutClassInfoState = [](
TClass *cl)
4013 if (strncmp(cl->
GetName(),
"tuple<",strlen(
"tuple<"))==0) {
4016 if (reload ||
name.empty()) {
4018 SetWithoutClassInfoState(cl);
4030 SetWithoutClassInfoState(cl);
4047 zombieCandidate =
kTRUE;
4054 zombieCandidate =
kTRUE;
4108 static const char *anonEnum =
"anonymous enum ";
4109 static const int cmplen = strlen(anonEnum);
4136 const char *classname =
name;
4139 class MaybeSuspendAutoLoadParse {
4140 int fStoreAutoLoad = 0;
4141 int fStoreAutoParse = 0;
4142 bool fSuspendedAutoParse =
false;
4144 MaybeSuspendAutoLoadParse(
int autoload) {
4145 fStoreAutoLoad = ((
TCling*)
gCling)->SetClassAutoLoading(autoload);
4149 fSuspendedAutoParse =
true;
4150 fStoreAutoParse = ((
TCling*)
gCling)->SetSuspendAutoParsing(
true);
4153 ~MaybeSuspendAutoLoadParse() {
4154 if (fSuspendedAutoParse)
4155 ((
TCling*)
gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4156 ((
TCling*)
gCling)->SetClassAutoLoading(fStoreAutoLoad);
4160 MaybeSuspendAutoLoadParse autoLoadParseRAII( autoload );
4162 autoLoadParseRAII.SuspendAutoParsing();
4171 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
4172 const clang::Type *
type =
nullptr;
4173 const clang::Decl *decl
4174 = lh.findScope(classname,
4175 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4176 : cling::LookupHelper::NoDiagnostics,
4180 decl = lh.findScope(buf,
4181 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4182 : cling::LookupHelper::NoDiagnostics,
4199 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4200 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4201 (
type->getAsCXXRecordDecl());
4202 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4219 if (tci.
Property() & propertiesMask) {
4220 bool hasClassDefInline =
false;
4221 if (isClassOrNamespaceOnly) {
4227 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4229 bool success =
false;
4230 std::tie(success, lineNumber) =
4232 hasClassDefInline = success && (lineNumber == -1);
4240 if (hasClassDefInline)
4279 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
4280 const clang::Decl *decl
4281 = lh.findClassTemplate(
name,
4282 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4283 : cling::LookupHelper::NoDiagnostics);
4285 std::string strname =
"std::";
4287 decl = lh.findClassTemplate(strname,
4288 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4289 : cling::LookupHelper::NoDiagnostics);
4291 return nullptr != decl;
4315 cl->
fBase = listOfBase;
4331 D =
fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4334 if (
const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4337 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4338 const_cast< clang::DeclContext *
>(DC)->collectAllContexts(allDeclContexts);
4339 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(), declEnd = allDeclContexts.end();
4340 declIter != declEnd; ++declIter) {
4342 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4343 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4344 if (
const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4347 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4348 llvm::raw_string_ostream stream(buf);
4350 Policy.AnonymousTagLocations =
false;
4351 ED->getNameForDiagnostic(stream, Policy,
false);
4355 const char*
name = buf.c_str();
4379 D =
fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4383 if (
const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4386 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4387 const_cast< clang::DeclContext *
>(DC)->collectAllContexts(allDeclContexts);
4388 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(),
4389 declEnd = allDeclContexts.end(); declIter != declEnd; ++declIter) {
4391 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4392 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4393 if (
const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4394 funcTempList->
Get(FTD);
4452 if (
m->fMethodArgs) {
4463 m->fMethodArgs = arglist;
4510 if (llvm::isa<clang::NamespaceDecl>(cli->
GetDecl())) {
4519 Error(
"GenerateTClass",
4520 "Cannot find %s::Class_Version()! Class version might be wrong.",
4527 if (newvers == -1) {
4535 newvers = callfunc.
ExecInt(
nullptr);
4537 Error(
"GenerateTClass",
4538 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4542 if (newvers != oldvers) {
4559static void GenerateTClass_GatherInnerIncludes(cling::Interpreter *interp,
TString &includes,
TClingClassInfo *info)
4563 const clang::ClassTemplateSpecializationDecl *templateCl
4564 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->
GetDecl());
4566 for(
unsigned int i=0; i < templateCl->getTemplateArgs().
size(); ++i) {
4567 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4568 if (arg.getKind() == clang::TemplateArgument::Type) {
4571 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4573 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4576 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4577 GenerateTClass_GatherInnerIncludes(interp, includes, &subinfo);
4580 llvm::raw_string_ostream OS(Result);
4581 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4582 Warning(
"TCling::GenerateTClass",
"Missing header file for %s",OS.str().c_str());
4597 if (!info || !info->
IsValid()) {
4598 Fatal(
"GenerateTClass",
"Requires a valid ClassInfo object");
4603 std::string classname;
4607 Info(
"GenerateTClass",
"Will (try to) generate the compiled TClass for %s.",classname.c_str());
4611 GenerateTClass_GatherInnerIncludes(
fInterpreter,includes,info);
4617 Error(
"GenerateTClass",
"Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4621 if (cl ==
nullptr) {
4623 cl =
new TClass(classinfo, version,
nullptr,
nullptr, -1, -1, silent);
4629 cl =
new TClass(classinfo, 1,
nullptr,
nullptr, -1, -1, silent);
4654 if (classes ==
nullptr || classes[0] == 0) {
4655 Error(
"TCling::GenerateDictionary",
"Cannot generate dictionary without passing classes.");
4659 std::vector<std::string> listClasses;
4661 const char* current = classes, *prev = classes;
4665 if (*current ==
';') {
4666 listClasses.push_back(std::string(prev, current - prev));
4669 else if (*(current + 1) == 0) {
4670 listClasses.push_back(std::string(prev, current + 1 - prev));
4674 std::vector<std::string> listIncludes;
4678 const char* current = includes, *prev = includes;
4682 if (*current ==
';') {
4683 listIncludes.push_back(std::string(prev, current - prev));
4686 else if (*(current + 1) == 0) {
4687 listIncludes.push_back(std::string(prev, current + 1 - prev));
4693 std::vector<std::string>(), std::vector<std::string>());
4714 if (
const ValueDecl* decl = (
const ValueDecl*)
d){
4717 if (hasIoName && ioName !=
name)
return nullptr;
4729 using namespace clang;
4731 DeclarationName DName = &SemaR.Context.Idents.get(
name);
4733 LookupResult
R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4734 Sema::ForExternalRedeclaration);
4738 cling::utils::Lookup::Named(&SemaR,
R);
4740 LookupResult::Filter
F =
R.makeFilter();
4742 while (
F.hasNext()) {
4743 NamedDecl *D =
F.next();
4744 if (isa<VarDecl>(D) || isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
4745 isa<IndirectFieldDecl>(D))
4751 if (
R.isSingleResult())
4752 return R.getFoundDecl();
4764 const clang::Decl* possibleEnum =
nullptr;
4769 const clang::DeclContext* dc =
nullptr;
4770 if (
const clang::Decl* D = cci->
GetDecl()) {
4771 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4772 dc = dyn_cast<clang::RecordDecl>(D);
4779 possibleEnum = cling::utils::Lookup::Tag(&
fInterpreter->getSema(),
name, dc);
4781 Error(
"TCling::GetEnum",
"DeclContext not found for %s .\n",
name);
4790 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4791 && isa<clang::EnumDecl>(possibleEnum)) {
4792 return possibleEnum;
4802 if (!gv)
return nullptr;
4804 llvm::StringRef mangled_name = gv->getName();
4819 std::string scopename(demangled_name_c);
4820 free(demangled_name_c);
4826 std::string dataname;
4828 if (!strncmp(scopename.c_str(),
"typeinfo for ",
sizeof(
"typeinfo for ")-1)) {
4829 scopename.erase(0,
sizeof(
"typeinfo for ")-1);
4830 }
else if (!strncmp(scopename.c_str(),
"vtable for ",
sizeof(
"vtable for ")-1)) {
4831 scopename.erase(0,
sizeof(
"vtable for ")-1);
4834 std::string::size_type pos = scopename.rfind(
'(');
4835 if (pos != std::string::npos) {
4839 pos = scopename.rfind(
':');
4840 if (pos != std::string::npos) {
4841 if ((pos != 0) && (scopename[pos-1] ==
':')) {
4842 dataname = scopename.substr(pos+1);
4843 scopename.erase(pos-1);
4847 dataname = scopename;
4855 if (scopename.size()) {
4871 Error(
"GetDataMemberWithValue()",
"not implemented");
4881 Error(
"GetDataMemberAtAddr()",
"not implemented");
4891 const char* params,
Bool_t objectIsConst )
4909 return mangled_name;
4924 GetMethod(method,
proto, objectIsConst,
nullptr ,
mode).GetMangledName();
4936 const char* params,
Bool_t objectIsConst )
4977 std::vector<DeclId_t>& res)
const
4980 clang::ASTContext& Ctx = S.Context;
4981 const clang::Decl* CtxDecl
4983 Ctx.getTranslationUnitDecl();
4984 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
4985 const clang::DeclContext* DeclCtx = RecDecl;
4988 DeclCtx = dyn_cast<clang::NamespaceDecl>(CtxDecl);
4989 if (!DeclCtx)
return;
4991 clang::DeclarationName DName;
4996 if (RecDecl->getNameAsString() == funcname) {
4997 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
4998 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
4999 }
else if (funcname[0] ==
'~' && RecDecl->getNameAsString() == funcname + 1) {
5000 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5001 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
5003 DName = &Ctx.Idents.get(funcname);
5006 DName = &Ctx.Idents.get(funcname);
5010 clang::LookupResult
R(S, DName, clang::SourceLocation(),
5011 Sema::LookupOrdinaryName, clang::Sema::NotForRedeclaration);
5012 R.suppressDiagnostics();
5013 S.LookupQualifiedName(
R,
const_cast<DeclContext*
>(DeclCtx));
5014 if (
R.empty())
return;
5016 res.reserve(res.size() + (
R.end() -
R.begin()));
5017 for (clang::LookupResult::iterator IR =
R.begin(), ER =
R.end();
5019 if (
const clang::FunctionDecl* FD
5020 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5021 if (!FD->getDescribedFunctionTemplate()) {
5024 }
else if (
const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5026 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5047 GetMethod(method,
proto, objectIsConst,
nullptr ,
mode).InterfaceMethod();
5186 const char* params,
Bool_t objectIsConst,
int* error)
5206 const char* params,
int* error)
5208 Execute(obj,cl,method,params,
false,error);
5223 Error(
"Execute",
"No method was defined");
5232 if (argc > nparms) {
5233 Error(
"Execute",
"Too many parameters to call %s, got %d but expected at most %d.",method->
GetName(),argc,nparms);
5236 if (nparms != argc) {
5246 Int_t firstDefault = -1;
5247 for (
Int_t i = 0; i < nparms; i ++) {
5254 if (firstDefault >= 0) {
5255 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);
5257 Error(
"Execute",
"Too few arguments to call %s, got only %d but expected %d.",method->
GetName(),argc,nparms);
5263 const char* listpar =
"";
5268 for (
Int_t i = 0; i < argc; i ++) {
5277 chpar += (nxtpar->
String()).ReplaceAll(
"\"",
"\\\"");
5284 complete += nxtpar->
String();
5287 listpar = complete.
Data();
5314 const void* args[] ,
5319 Error(
"ExecuteWithArgsAndReturn",
"No method was defined");
5346 Warning(
"GetTopLevelMacroName",
"Must change return type!");
5393#if defined(R__MUST_REVISIT)
5394#if R__MUST_REVISIT(6,0)
5395 Warning(
"GetCurrentMacroName",
"Must change return type!");
5408 TTHREAD_TLS_DECL(std::string,t);
5410 if (!strstr(typeDesc,
"(*)(")) {
5411 const char *s = strchr(typeDesc,
' ');
5412 const char *template_start = strchr(typeDesc,
'<');
5413 if (!strcmp(typeDesc,
"long long")) {
5416 else if (!strncmp(typeDesc,
"unsigned ", s + 1 - typeDesc)) {
5423 else if (s && (template_start ==
nullptr || (s < template_start))) {
5433 auto l = t.length();
5434 while (
l > 0 && (t[
l - 1] ==
'*' || t[
l - 1] ==
'&'))
5442 assert(rootmapfile && *rootmapfile);
5444 llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5445 libName.consume_back(
".rootmap");
5447 return !
gInterpreter->HasPCMForLibrary(libName.str().c_str());
5458 if (!(rootmapfile && *rootmapfile))
5465 const std::map<char, unsigned int> keyLenMap = {{
'c',6},{
'n',10},{
't',8},{
'h',7},{
'e',5},{
'v',4}};
5467 std::string rootmapfileNoBackslash(rootmapfile);
5469 std::replace(rootmapfileNoBackslash.begin(), rootmapfileNoBackslash.end(),
'\\',
'/');
5476 std::string lineDirective = std::string(
"\n#line 2 \"Forward declarations from ") + rootmapfileNoBackslash +
"\"\n";
5478 std::ifstream
file(rootmapfileNoBackslash);
5481 std::string lib_name;