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);
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;
1247 bool supportedPlatform =
1250#elif defined(R__MACOSX)
1257 llvm::Optional<std::string> envUseGMI = llvm::sys::Process::GetEnv(
"ROOT_USE_GMI");
1258 if (envUseGMI.hasValue()) {
1261 "Cannot convert '%s' to bool, setting to false!",
1262 envUseGMI->c_str());
1266 if (supportedPlatform ==
value)
1267 ::Warning(
"TCling__RegisterCxxModules",
"Global module index is%sused already!",
1268 (
value) ?
" " :
" not ");
1269 supportedPlatform =
value;
1272 if (supportedPlatform) {
1276 GlobalIndex = CI.getASTReader()->getGlobalIndex();
1279 llvm::StringSet<> KnownModuleFileNames;
1281 GlobalIndex->getKnownModuleFileNames(KnownModuleFileNames);
1283 std::vector<std::string> PendingModules;
1284 PendingModules.reserve(256);
1285 for (
auto I = MMap.module_begin(),
E = MMap.module_end();
I !=
E; ++
I) {
1286 clang::Module *M =
I->second;
1290 std::string FullASTFilePath;
1294 if (GlobalIndex && KnownModuleFileNames.count(FullASTFilePath))
1297 if (M->IsUnimportable)
1305 if (std::find(CoreModules.begin(), CoreModules.end(), M->Name) != CoreModules.end())
1313 PendingModules.push_back(M->Name);
1320 assert(clingInterp.getMacro(
"gROOT") &&
"Couldn't load gROOT macro?");
1324 clingInterp.declare(R
"CODE(
1336 std::string PreIncludes;
1337 bool hasCxxModules = clingInterp.getCI()->getLangOpts().Modules;
1343 PreIncludes +=
"#include \"RtypesCore.h\"\n";
1346 PreIncludes +=
"#include \"Rtypes.h\"\n";
1348 PreIncludes += gClassDefInterpMacro +
"\n"
1349 + gInterpreterClassDef +
"\n"
1351 "#define ClassImp(X);\n";
1354 PreIncludes +=
"#include <string>\n";
1359 PreIncludes +=
"#include <cassert>\n";
1361 PreIncludes +=
"using namespace std;\n";
1362 clingInterp.declare(PreIncludes);
1382#ifdef R__USE_CXXMODULES
1386 llvm::install_fatal_error_handler(&exceptionErrorHandler);
1390 std::vector<std::string> clingArgsStorage;
1391 clingArgsStorage.push_back(
"cling4root");
1392 for (
const char*
const* arg = argv; *arg; ++arg)
1393 clingArgsStorage.push_back(*arg);
1396 if (!fromRootCling) {
1401 clingArgsStorage.push_back(
"-I" + interpInclude);
1404 clingArgsStorage.push_back(
"-I" + interpInclude +
"/cling");
1407 clingArgsStorage.push_back(
"-I" + interpInclude +
"/cling/plugins/include");
1418 std::string pchFilename = interpInclude +
"/allDict.cxx.pch";
1423 clingArgsStorage.push_back(
"-include-pch");
1424 clingArgsStorage.push_back(pchFilename);
1427 clingArgsStorage.push_back(
"-Wno-undefined-inline");
1428 clingArgsStorage.push_back(
"-fsigned-char");
1431#if !defined(_MSC_VER) || defined(_WIN64)
1432 clingArgsStorage.push_back(
"-O1");
1435 clingArgsStorage.push_back(
"-mllvm");
1436 clingArgsStorage.push_back(
"-optimize-regalloc=0");
1441 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(
"EXTRA_CLING_ARGS");
1442 if (EnvOpt.hasValue()) {
1443 StringRef Env(*EnvOpt);
1444 while (!Env.empty()) {
1446 std::tie(Arg, Env) = Env.split(
' ');
1447 clingArgsStorage.push_back(Arg.str());
1451 auto GetEnvVarPath = [](
const std::string &EnvVar,
1452 std::vector<std::string> &Paths) {
1453 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1454 if (EnvOpt.hasValue()) {
1455 StringRef Env(*EnvOpt);
1456 while (!Env.empty()) {
1459 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1460 Paths.push_back(Arg.str());
1466 std::vector<std::string> Paths;
1475 GetEnvVarPath(
"CLING_PREBUILT_MODULE_PATH", Paths);
1476 std::string EnvVarPath;
1477 for (
const std::string&
P : Paths)
1480 gSystem->
Setenv(
"CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1484 EnvOpt = llvm::sys::Process::GetEnv(
"ROOT_CLING_TIMING");
1485 if (EnvOpt.hasValue())
1486 clingArgsStorage.push_back(
"-ftime-report");
1493 std::vector<std::string> ModuleMaps;
1496 GetEnvVarPath(
"CLING_MODULEMAP_FILES", ModuleMaps);
1500 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1501 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1503 for (
const std::string& M : ModuleMaps)
1504 clingArgsStorage.push_back(
"-fmodule-map-file=" + M);
1506 std::string ModulesCachePath;
1507 EnvOpt = llvm::sys::Process::GetEnv(
"CLING_MODULES_CACHE_PATH");
1508 if (EnvOpt.hasValue()){
1509 StringRef Env(*EnvOpt);
1510 assert(llvm::sys::fs::exists(Env) &&
"Path does not exist!");
1511 ModulesCachePath = Env.str();
1516 clingArgsStorage.push_back(
"-fmodules-cache-path=" + ModulesCachePath);
1519 std::vector<const char*> interpArgs;
1520 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1521 eArg = clingArgsStorage.end(); iArg != eArg; ++iArg)
1522 interpArgs.push_back(iArg->c_str());
1529 if (!fromRootCling) {
1531 interpArgs.push_back(
"-fmodules");
1532 interpArgs.push_back(
"-fno-implicit-module-maps");
1536 interpArgs.push_back(
"-Rmodule-build");
1542 interpArgs.push_back(
"-fno-autolink");
1547 interpArgs.push_back(
"-ffast-math");
1553 extraArgs && *extraArgs; ++extraArgs) {
1554 if (!strcmp(*extraArgs,
"-resource-dir")) {
1556 llvmResourceDir = *(++extraArgs);
1558 interpArgs.push_back(*extraArgs);
1562 std::vector<std::string> _empty;
1564 for (
const auto &arg: args)
1565 interpArgs.emplace_back(arg.c_str());
1568 cling::Interpreter::ModuleFileExtensions extensions;
1569 EnvOpt = llvm::sys::Process::GetEnv(
"ROOTDEBUG_RDICT");
1570 if (!EnvOpt.hasValue())
1571 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1573 fInterpreter = std::make_unique<cling::Interpreter>(interpArgs.size(),
1575 llvmResourceDir, extensions,
1579 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHOrModuleValidation =
1584 fInterpreter->getCI()->getLangOpts().SpellChecking =
false;
1589 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO,
false);
1609 if (!fromRootCling) {
1614 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1615 auto &Policy =
const_cast<clang::PrintingPolicy &
>(
fInterpreter->getCI()->getASTContext().getPrintingPolicy());
1619 Policy.SplitTemplateClosers =
true;
1621 Policy.SuppressDefaultTemplateArgs =
false;
1627 std::unique_ptr<TClingCallbacks>
1633 if (!fromRootCling) {
1634 cling::DynamicLibraryManager& DLM = *
fInterpreter->getDynamicLibraryManager();
1639 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) ->
bool{
1640 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1641 return stem.startswith(
"libNew") || stem.startswith(
"libcppyy_backend");
1644 DLM.initializeDyld(ShouldPermanentlyIgnore);
1682 assert(
GetRootMapFiles() ==
nullptr &&
"Must be called before LoadLibraryMap!");
1701 auto setFactory = []() {
1705 static bool doneFactory = setFactory();
1717 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1718 ::Error(
"TCling::RegisterRdictForLoadPCM",
"Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1735 if (listOfKeys && ((listOfKeys->GetSize() == 0) ||
1736 ((listOfKeys->GetSize() == 1) &&
1737 !strcmp(((
TKey *)listOfKeys->At(0))->GetName(),
"EMPTY")
1744 ::Info(
"TCling::LoadPCMImpl",
"reading protoclasses for %s \n", pcmFile.
GetName());
1750 auto listOfGlobals =
gROOT->GetListOfGlobals();
1751 auto listOfEnums =
dynamic_cast<THashList *
>(
gROOT->GetListOfEnums());
1753 for (
auto selEnum : *enums) {
1754 const char *enumScope = selEnum->
GetTitle();
1755 const char *enumName = selEnum->GetName();
1756 if (strcmp(enumScope,
"") == 0) {
1759 if (!listOfEnums->THashList::FindObject(enumName)) {
1760 ((
TEnum *)selEnum)->SetClass(
nullptr);
1761 listOfEnums->Add(selEnum);
1764 if (!listOfGlobals->FindObject(enumConstant)) {
1765 listOfGlobals->Add(enumConstant);
1772 if (!nsTClassEntry) {
1775 auto listOfEnums = nsTClassEntry->
fEnums.load();
1786 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1787 ((
TEnum *)selEnum)->SetClass(nsTClassEntry);
1788 listOfEnums->Add(selEnum);
1796 pcmFile.
GetObject(
"__ProtoClasses", protoClasses);
1799 for (
auto obj : *protoClasses) {
1809 for (
auto proto : *protoClasses) {
1817 ::Error(
"TCling::LoadPCM",
"Inconsistent TClassTable for %s",
proto->GetName());
1828 protoClasses->Clear();
1829 delete protoClasses;
1833 pcmFile.
GetObject(
"__Typedefs", dataTypes);
1835 for (
auto typedf : *dataTypes)
1836 gROOT->GetListOfTypes()->Add(typedf);
1849 assert(!pcmFileNameFullPath.empty());
1850 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1853 TString pcmFileName = pcmFileNameFullPath;
1861 llvm::SaveAndRestore<Int_t> SaveGDebug(
gDebug);
1864 ::Info(
"TCling::LoadPCM",
"Loading ROOT PCM %s", pcmFileName.
Data());
1869 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1874 llvm::StringRef pcmContent = pendingRdict->second;
1876 std::string RDictFileOpts = pcmFileNameFullPath +
"?filetype=pcm";
1877 TMemFile pcmMemFile(RDictFileOpts.c_str(), range);
1886 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1887 ::Error(
"TCling::LoadPCM",
"ROOT PCM %s file does not exist",
1888 pcmFileNameFullPath.data());
1891 ::Info(
"TCling::LoadPCM",
"In-memory ROOT PCM candidate %s\n",
1892 rdict.first.c_str());
1896 if (!
gROOT->IsRootFile(pcmFileName)) {
1897 Fatal(
"LoadPCM",
"The file %s is not a ROOT as was expected\n", pcmFileName.
Data());
1900 TFile pcmFile(pcmFileName +
"?filetype=pcm",
"READ");
1907 using namespace clang;
1909 class ExtLexicalStorageAdder:
public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1914 bool VisitRecordDecl(clang::RecordDecl* rcd){
1916 Info(
"ExtLexicalStorageAdder",
1917 "Adding external lexical storage to class %s",
1918 rcd->getNameAsString().c_str());
1919 auto reDeclPtr = rcd->getMostRecentDecl();
1921 reDeclPtr->setHasExternalLexicalStorage();
1922 }
while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1935 const std::string &ModuleMapName )
const
1937 assert(llvm::sys::path::is_absolute(FullPath));
1938 Preprocessor &PP =
fInterpreter->getCI()->getPreprocessor();
1939 FileManager &FM = PP.getFileManager();
1942 if (
auto DE = FM.getOptionalDirectoryRef(FullPath)) {
1943 HeaderSearch &HS = PP.getHeaderSearchInfo();
1944 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1945 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1946 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1948 HSOpts.AddPrebuiltModulePath(FullPath);
1953 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1954 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1955 if (
auto FE = FM.getOptionalFileRef(ModuleMapFileName,
false,
1957 if (!HS.loadModuleMapFile(*FE,
false))
1959 Error(
"RegisterPrebuiltModulePath",
"Could not load modulemap in %s", ModuleMapFileName.c_str());
1976 "libforward_listDict",
1984 "libunordered_setDict",
1985 "libunordered_multisetDict",
1986 "libunordered_mapDict",
1987 "libunordered_multimapDict",
1995 char dyLibError[1000];
1996 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1997 dyLibError,
sizeof(dyLibError), NULL);
1999 const char *dyLibError = dlerror();
2001 ::Error(
"TCling::RegisterModule",
"Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
2002 (dyLibError) ? dyLibError :
"");
2039 const char** headers,
2040 const char** includePaths,
2041 const char* payloadCode,
2042 const char* fwdDeclsCode,
2043 void (*triggerFunc)(),
2045 const char** classesHeaders,
2046 Bool_t lateRegistration ,
2053 if (fromRootCling)
return;
2062 bool isACLiC = strstr(modulename,
"_ACLiC_dict") !=
nullptr;
2063 if (hasHeaderParsingOnDemand && isACLiC) {
2065 Info(
"TCling::RegisterModule",
2066 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2067 hasHeaderParsingOnDemand =
false;
2081 for (
const char** inclPath = includePaths; *inclPath; ++inclPath) {
2084 cling::Transaction*
T =
nullptr;
2086 for (
auto& fwdDeclArgToSkipPair : fwdDeclsArgToSkip){
2087 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2088 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2090 assert(cling::Interpreter::kSuccess == compRes &&
2091 "A fwd declaration could not be compiled");
2092 if (compRes!=cling::Interpreter::kSuccess){
2093 Warning(
"TCling::RegisterModule",
2094 "Problems in declaring string '%s' were encountered.",
2109 TString code = gNonInterpreterClassDef;
2111 code += payloadCode;
2113 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2114 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2116 if (dyLibName.empty()) {
2117 ::Error(
"TCling::RegisterModule",
"Dictionary trigger function for %s not found", modulename);
2122 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2124 bool wasDlopened =
false;
2129 if (!lateRegistration) {
2136 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2146 if (hasHeaderParsingOnDemand && fwdDeclsCode){
2149 std::string fwdDeclsCodeLessEnums;
2153 std::string fwdDeclsLine;
2154 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2155 std::vector<std::string> scopes;
2156 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2157 const auto enumPos = fwdDeclsLine.find(
"enum __attribute__((annotate(\"");
2159 if (enumPos != std::string::npos) {
2166 auto nsPos = fwdDeclsLine.find(
"namespace");
2167 R__ASSERT(nsPos < enumPos &&
"Inconsistent enum and enclosing scope parsing!");
2168 while (nsPos < enumPos && nsPos != std::string::npos) {
2170 const auto nsNameStart = nsPos + 10;
2171 const auto nsNameEnd = fwdDeclsLine.find(
'{', nsNameStart);
2172 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2173 scopes.push_back(nsName);
2174 nsPos = fwdDeclsLine.find(
"namespace", nsNameEnd);
2177 clang::DeclContext* DC =
nullptr;
2178 for (
auto &&aScope: scopes) {
2179 DC = cling::utils::Lookup::Namespace(&
fInterpreter->getSema(), aScope.c_str(), DC);
2185 if (scopes.empty() || DC) {
2187 size_t posEnumName = fwdDeclsLine.find(
"\"))) ", 32);
2188 R__ASSERT(posEnumName != std::string::npos &&
"Inconsistent enum fwd decl!");
2190 while (isspace(fwdDeclsLine[posEnumName]))
2192 size_t posEnumNameEnd = fwdDeclsLine.find(
" : ", posEnumName);
2193 R__ASSERT(posEnumNameEnd != std::string::npos &&
"Inconsistent enum fwd decl (end)!");
2194 while (isspace(fwdDeclsLine[posEnumNameEnd]))
2198 std::string enumName = fwdDeclsLine.substr(posEnumName,
2199 posEnumNameEnd - posEnumName + 1);
2201 if (clang::NamedDecl* enumDecl
2202 = cling::utils::Lookup::Named(&
fInterpreter->getSema(),
2203 enumName.c_str(), DC)) {
2206 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) &&
"not an enum decl!");
2213 fwdDeclsCodeLessEnums += fwdDeclsLine +
"\n";
2217 if (!fwdDeclsCodeLessEnums.empty()){
2218 auto compRes =
fInterpreter->declare(fwdDeclsCodeLessEnums, &
T);
2219 assert(cling::Interpreter::kSuccess == compRes &&
2220 "The forward declarations could not be compiled");
2221 if (compRes!=cling::Interpreter::kSuccess){
2222 Warning(
"TCling::RegisterModule",
2223 "Problems in compiling forward declarations for module %s: '%s'",
2224 modulename, fwdDeclsCodeLessEnums.c_str()) ;
2232 ExtLexicalStorageAdder elsa;
2233 for (
auto dciIt =
T->decls_begin();dciIt!=
T->decls_end();dciIt++){
2234 cling::Transaction::DelayCallInfo& dci = *dciIt;
2235 for(
auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2236 clang::Decl* declPtr = *dit;
2237 elsa.TraverseDecl(declPtr);
2251 for (
const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2252 temp=*classesHeader;
2254 size_t theTemplateHash = 0;
2255 bool addTemplate =
false;
2256 size_t posTemplate = temp.find(
'<');
2257 if (posTemplate != std::string::npos) {
2259 std::string templateName = temp.substr(0, posTemplate);
2265 for (
const char** classesHeader_inner = classesHeader; 0!=strcmp(*classesHeader_inner,
"@"); ++classesHeader_inner,++classesHeader){
2267 if (payloadCode == *classesHeader_inner ){
2269 if (addTemplate)
fPayloads.insert(theTemplateHash);
2272 Info(
"TCling::RegisterModule",
2273 "Adding a header for %s", temp.c_str());
2279 addTemplate =
false;
2287 bool ModuleWasSuccessfullyLoaded =
false;
2289 std::string ModuleName = modulename;
2290 if (llvm::StringRef(modulename).startswith(
"lib"))
2291 ModuleName = llvm::StringRef(modulename).substr(3).str();
2296 clang::Preprocessor &PP = TheSema.getPreprocessor();
2297 std::string ModuleMapName;
2299 ModuleMapName = ModuleName +
".modulemap";
2301 ModuleMapName =
"module.modulemap";
2309 if (!ModuleWasSuccessfullyLoaded) {
2311 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2312 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2313 if (moduleMap.findModule(ModuleName))
2314 Info(
"TCling::RegisterModule",
"Module %s in modulemap failed to load.", ModuleName.c_str());
2319 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2322 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2323 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2324 llvm::sys::path::append(pcmFileNameFullPath,
2326 LoadPCM(pcmFileNameFullPath.str().str());
2333 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2335#if defined(R__MUST_REVISIT)
2336#if R__MUST_REVISIT(6,2)
2337 Warning(
"TCling::RegisterModule",
"Diagnostics suppression should be gone by now.");
2341 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand){
2344 const cling::Transaction* watermark =
fInterpreter->getLastTransaction();
2345 cling::Interpreter::CompilationResult compRes =
fInterpreter->parseForModule(code.
Data());
2351 assert(cling::Interpreter::kSuccess == compRes &&
2352 "Payload code of a dictionary could not be parsed correctly.");
2353 if (compRes!=cling::Interpreter::kSuccess) {
2354 Warning(
"TCling::RegisterModule",
2355 "Problems declaring payload for module %s.", modulename) ;
2368 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand) {
2371 "#undef __ROOTCLING__\n"
2372 + gInterpreterClassDef +
2377 assert(isSharedLib);
2380 dlclose(dyLibHandle);
2386 ASTContext &
C = CI.getASTContext();
2394 if (IdentifierInfoLookup *External =
C.Idents.getExternalIdentifierLookup()) {
2395 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2396 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2397 std::string
I = Ident.str();
2421 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2427 if ( i->first == oldcl ) {
2450 const char* input_line,
2451 cling::Interpreter::CompilationResult& compRes,
2455 return metaProcessor->process(input_line, compRes,
result);
2457 catch (cling::InterpreterException&
ex)
2459 Error(
"HandleInterpreterException",
"%s\n%s",
ex.what(),
"Execution of your code was aborted.");
2461 compRes = cling::Interpreter::kFailure;
2470 if (
auto ie =
dynamic_cast<const cling::InterpreterException*
>(&
e)) {
2496 gROOT->SetLineIsProcessing();
2500 gROOT->SetLineHasBeenProcessed();
2513 gROOT->SetLineIsProcessing();
2515 struct InterpreterFlagsRAII {
2517 bool fWasDynamicLookupEnabled;
2519 InterpreterFlagsRAII(cling::Interpreter* interp):
2521 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2525 ~InterpreterFlagsRAII() {
2526 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2527 gROOT->SetLineHasBeenProcessed();
2536 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2537 if (!strncmp(sLine.
Data(),
".L", 2) || !strncmp(sLine.
Data(),
".x", 2) ||
2538 !strncmp(sLine.
Data(),
".X", 2)) {
2546 aclicMode, arguments, io);
2547 if (aclicMode.
Length()) {
2549 R__ASSERT(aclicMode[0]==
'+' &&
"ACLiC mode must start with a +");
2551 if (aclicMode[1]==
'+') {
2557 compRes = cling::Interpreter::kFailure;
2559 if (strncmp(sLine.
Data(),
".L", 2) != 0) {
2562 if (arguments.
Length()==0) {
2571 mod_line =
function + arguments + io;
2577 size_t unnamedMacroOpenCurly;
2580 std::string codeline;
2583 std::ifstream in(fname, std::ifstream::binary);
2585 std::getline(in, codeline);
2586 code += codeline +
"\n";
2588 unnamedMacroOpenCurly
2589 = cling::utils::isUnnamedMacro(code,
fInterpreter->getCI()->getLangOpts());
2593 if (unnamedMacroOpenCurly != std::string::npos) {
2595 unnamedMacroOpenCurly);
2605 if (0!=strncmp(sLine.
Data(),
".autodict ",10) && sLine !=
".autodict") {
2610 bool isInclusionDirective = sLine.
Contains(
"\n#include") || sLine.
BeginsWith(
"#include");
2611 if (isInclusionDirective) {
2628 case cling::Interpreter::kSuccess: *error =
kNoError;
break;
2629 case cling::Interpreter::kFailure: *error =
kRecoverable;
break;
2630 case cling::Interpreter::kMoreInputExpected: *error =
kProcessing;
break;
2633 if (compRes == cling::Interpreter::kSuccess
2664 if (path[0] ==
'-' && path[1] ==
'I')
2689 static const TClassRef clRefString(
"std::string");
2690 if (clRefString == cl) {
2700 const char* cobj = (
const char*) obj;
2707 auto inspInspect = [&] (ptrdiff_t
offset){
2713 switch(complexType) {
2720 inspInspect(
sizeof(
float));
2725 inspInspect(
sizeof(
double));
2730 inspInspect(
sizeof(
int));
2735 inspInspect(
sizeof(
long));
2740 static clang::PrintingPolicy
2742 if (printPol.Indentation) {
2744 printPol.Indentation = 0;
2745 printPol.SuppressInitializers =
true;
2748 const char* clname = cl->
GetName();
2751 const clang::ASTContext& astContext =
fInterpreter->getCI()->getASTContext();
2752 const clang::Decl *scopeDecl =
nullptr;
2757 scopeDecl = clingCI->
GetDecl();
2758 recordType = clingCI->
GetType();
2760 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
2762 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2766 Error(
"InspectMembers",
"Cannot find Decl for class %s", clname);
2769 const clang::CXXRecordDecl* recordDecl
2770 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2772 Error(
"InspectMembers",
"Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2781 astContext.getASTRecordLayout(recordDecl);
2783 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2784 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2787 const clang::ASTRecordLayout& recLayout
2788 = astContext.getASTRecordLayout(recordDecl);
2795 if (cl->
Size() != recLayout.getSize().getQuantity()) {
2796 Error(
"InspectMembers",
"TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2800 unsigned iNField = 0;
2803 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2804 eField = recordDecl->field_end(); iField != eField;
2805 ++iField, ++iNField) {
2808 clang::QualType memberQT = iField->getType();
2813 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT,
fNormalizedCtxt->
GetConfig(),
false );
2814 if (memberQT.isNull()) {
2815 std::string memberName;
2816 llvm::raw_string_ostream stream(memberName);
2818 printPol.AnonymousTagLocations =
false;
2819 iField->getNameForDiagnostic(stream, printPol,
true );
2821 Error(
"InspectMembers",
2822 "Cannot retrieve QualType for member %s while inspecting class %s",
2823 memberName.c_str(), clname);
2826 const clang::Type* memType = memberQT.getTypePtr();
2828 std::string memberName;
2829 llvm::raw_string_ostream stream(memberName);
2831 printPol.AnonymousTagLocations =
false;
2832 iField->getNameForDiagnostic(stream, printPol,
true );
2834 Error(
"InspectMembers",
2835 "Cannot retrieve Type for member %s while inspecting class %s",
2836 memberName.c_str(), clname);
2841 Bool_t ispointer =
false;
2842 if (memNonPtrType->isPointerType()) {
2844 clang::QualType ptrQT
2845 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2850 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT,
fNormalizedCtxt->
GetConfig(),
false );
2851 if (ptrQT.isNull()) {
2852 std::string memberName;
2853 llvm::raw_string_ostream stream(memberName);
2855 printPol.AnonymousTagLocations =
false;
2856 iField->getNameForDiagnostic(stream, printPol,
true );
2858 Error(
"InspectMembers",
2859 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2860 memberName.c_str(), clname);
2863 memNonPtrType = ptrQT.getTypePtr();
2867 llvm::SmallString<8> arraySize;
2868 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2869 unsigned arrLevel = 0;
2870 bool haveErrorDueToArray =
false;
2874 const clang::ConstantArrayType* constArrType =
2875 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2877 constArrType->getSize().toStringUnsigned(arraySize);
2880 clang::QualType subArrQT = arrType->getElementType();
2881 if (subArrQT.isNull()) {
2882 std::string memberName;
2883 llvm::raw_string_ostream stream(memberName);
2885 printPol.AnonymousTagLocations =
false;
2886 iField->getNameForDiagnostic(stream, printPol,
true );
2888 Error(
"InspectMembers",
2889 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2890 arrLevel, subArrQT.getAsString(printPol).c_str(),
2891 memberName.c_str(), clname);
2892 haveErrorDueToArray =
true;
2895 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2897 if (haveErrorDueToArray) {
2902 std::string fieldName;
2903 if (memType->isPointerType()) {
2908 std::string
ioname(iField->getName());
2911 fieldName += arraySize;
2916 clang::CharUnits
offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2917 ptrdiff_t fieldOffset =
offset.getQuantity();
2927 auto iFiledQtype = iField->getType();
2928 if (
auto tagDecl = iFiledQtype->getAsTagDecl()){
2929 auto declAccess = tagDecl->getAccess();
2930 if (declAccess == AS_private || declAccess == AS_protected) {
2936 insp.
Inspect(
const_cast<TClass*
>(cl), insp.
GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2939 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2940 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
2943 std::string sFieldRecName;
2946 clang::QualType(memNonPtrType,0),
2956 insp.
InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
2965 unsigned iNBase = 0;
2966 for (clang::CXXRecordDecl::base_class_const_iterator iBase
2967 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
2968 iBase != eBase; ++iBase, ++iNBase) {
2969 clang::QualType baseQT = iBase->getType();
2970 if (baseQT.isNull()) {
2971 Error(
"InspectMembers",
2972 "Cannot find QualType for base number %d while inspecting class %s",
2976 const clang::CXXRecordDecl* baseDecl
2977 = baseQT->getAsCXXRecordDecl();
2979 Error(
"InspectMembers",
2980 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
2985 std::string sBaseName;
2987 std::vector<TClass*> foundClasses;
2989 if (foundClasses.size()==1){
2990 baseCl=foundClasses[0];
3003 std::string qualNameForDiag;
3005 Error(
"InspectMembers",
3006 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
3011 if (iBase->isVirtual()) {
3014 Error(
"InspectMembers",
3015 "Base %s of class %s is virtual but no object provided",
3016 sBaseName.c_str(), clname);
3024 baseOffset = ci->
GetBaseOffset(baseCi,
const_cast<void*
>(obj),
3026 if (baseOffset == -1) {
3027 Error(
"InspectMembers",
3028 "Error calculating offset of virtual base %s of class %s",
3029 sBaseName.c_str(), clname);
3032 Error(
"InspectMembers",
3033 "Cannot calculate offset of virtual base %s of class %s",
3034 sBaseName.c_str(), clname);
3039 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3086 bool oldDynLookup =
fInterpreter->isDynamicLookupEnabled();
3115 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.
Data());
3130 llvm::StringRef ModuleName(libname);
3131 ModuleName = llvm::sys::path::stem(ModuleName);
3132 ModuleName.consume_front(
"lib");
3140 clang::ModuleMap &moduleMap =
fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3141 clang::Module *M = moduleMap.findModule(ModuleName);
3142 return M && !M->IsUnimportable && M->getASTFile();
3161 size_t at = std::string::npos;
3162 while ((at = file_name.find(
"/./")) != std::string::npos)
3163 file_name.replace(at, 3,
"/");
3165 std::string filesStr =
"";
3166 llvm::raw_string_ostream filesOS(filesStr);
3167 clang::SourceManager &SM =
fInterpreter->getCI()->getSourceManager();
3168 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3171 llvm::SmallVector<llvm::StringRef, 100> files;
3172 llvm::StringRef(filesStr).split(files,
"\n");
3174 std::set<std::string> fileMap;
3175 llvm::StringRef file_name_ref(file_name);
3177 for (llvm::SmallVector<llvm::StringRef, 100>::const_iterator
3178 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3179 if ((*iF) == file_name_ref)
return kTRUE;
3180 fileMap.insert(iF->str());
3183 if (fileMap.empty())
return kFALSE;
3186 TString sFilename(file_name.c_str());
3188 && fileMap.count(sFilename.
Data())) {
3196 while (incPath.
Index(
" :") != -1) {
3200 sFilename = file_name.c_str();
3202 && fileMap.count(sFilename.
Data())) {
3211 const clang::DirectoryLookup *CurDir =
nullptr;
3212 clang::Preprocessor &PP =
fInterpreter->getCI()->getPreprocessor();
3213 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3214 auto FE = HS.LookupFile(file_name.c_str(),
3215 clang::SourceLocation(),
3218 clang::ArrayRef<std::pair<
const clang::FileEntry *,
3219 const clang::DirectoryEntry *>>(),
3230 if (FE && FE->isValid()) {
3232 clang::SourceManager &SM =
fInterpreter->getCI()->getSourceManager();
3234 clang::FileID FID = SM.translateFile(*FE);
3235 if (!FID.isInvalid() && FID.getHashValue() == 0)
3238 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3239 if (SLocE.isFile() && !SLocE.getFile().getContentCache().getBufferIfLoaded())
3241 if (!FID.isInvalid())
3245 sFilename = FE->getName().str();
3247 && fileMap.count(sFilename.
Data())) {
3255#if defined(R__MACOSX)
3263static bool R__UpdateLibFileForLinking(
TString &lib)
3265 const char *mapfile =
nullptr;
3267 mapfile =
"/System/Library/dyld/dyld_shared_cache_x86_64.map";
3269 mapfile =
"/System/Library/dyld/dyld_shared_cache_arm64e.map";
3271 #error unsupported architecture
3273 if (std::ifstream cacheMap{mapfile}) {
3275 while (getline(cacheMap,
line)) {
3276 if (
line.find(lib) != std::string::npos) {
3294static int callback_for_dl_iterate_phdr(
struct dl_phdr_info *info,
size_t size,
void *
data)
3297 static std::unordered_set<
decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3299 auto newLibs =
static_cast<std::vector<std::string>*
>(
data);
3300 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3302 if (info->dlpi_name && info->dlpi_name[0]
3303 && strncmp(info->dlpi_name,
"linux-vdso.so", 13)
3304 && strncmp(info->dlpi_name,
"linux-vdso32.so", 15)
3305 && strncmp(info->dlpi_name,
"linux-vdso64.so", 15)
3306 && strncmp(info->dlpi_name,
"linux-gate.so", 13))
3307 newLibs->emplace_back(info->dlpi_name);
3308 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3321#if defined(R__WIN32) || defined(__CYGWIN__)
3322 HMODULE hModules[1024];
3324 unsigned long cbModules;
3326 hProcess = (
void *)::GetCurrentProcess();
3327 ::EnumProcessModules(hProcess, hModules,
sizeof(hModules), &cbModules);
3329 for (i = 1; i < (cbModules /
sizeof(
void *)); i++) {
3330 static const int bufsize = 260;
3331 wchar_t winname[bufsize];
3332 char posixname[bufsize];
3333 ::GetModuleFileNameExW(hProcess, hModules[i], winname, bufsize);
3334#if defined(__CYGWIN__)
3335 cygwin_conv_path(CCP_WIN_W_TO_POSIX, winname, posixname, bufsize);
3337 std::wstring wpath = winname;
3338 std::replace(wpath.begin(), wpath.end(),
'\\',
'/');
3339 string path(wpath.begin(), wpath.end());
3340 strncpy(posixname, path.c_str(), bufsize);
3346#elif defined(R__MACOSX)
3350 while (
const mach_header* mh = _dyld_get_image_header(imageIndex)) {
3352 if (mh->filetype == MH_DYLIB) {
3353 if (
const char* imageName = _dyld_get_image_name(imageIndex)) {
3361#elif defined(R__LINUX)
3365 std::vector<std::string> newLibs;
3366 dl_iterate_phdr(callback_for_dl_iterate_phdr, &newLibs);
3367 for (
auto &&lib: newLibs)
3370 Error(
"TCling::UpdateListOfLoadedSharedLibraries",
3371 "Platform not supported!");
3377static bool StartsWithStrLit(
const char *haystack,
const char (&needle)[
N]) {
3378 return !strncmp(haystack, needle,
N - 1);
3393 cling::DynamicLibraryManager* DLM =
fInterpreter->getDynamicLibraryManager();
3394 if (!DLM->isLibraryLoaded(
filename)) {
3395 DLM->loadLibrary(
filename,
true ,
true );
3398#if defined(R__MACOSX)
3400 auto lenFilename = strlen(
filename);
3401 auto isInMacOSSystemDir = [](
const char *fn) {
3402 return StartsWithStrLit(fn,
"/usr/lib/") || StartsWithStrLit(fn,
"/System/Library/");
3404 if (!strcmp(
filename,
"cl_kernels")
3407 || StartsWithStrLit(
filename,
"/usr/lib/system/")
3408 || StartsWithStrLit(
filename,
"/usr/lib/libc++")
3409 || StartsWithStrLit(
filename,
"/System/Library/Frameworks/")
3410 || StartsWithStrLit(
filename,
"/System/Library/PrivateFrameworks/")
3411 || StartsWithStrLit(
filename,
"/System/Library/CoreServices/")
3412 || StartsWithStrLit(
filename,
"/usr/lib/libSystem")
3413 || StartsWithStrLit(
filename,
"/usr/lib/libstdc++")
3414 || StartsWithStrLit(
filename,
"/usr/lib/libicucore")
3415 || StartsWithStrLit(
filename,
"/usr/lib/libbsm")
3416 || StartsWithStrLit(
filename,
"/usr/lib/libobjc")
3417 || StartsWithStrLit(
filename,
"/usr/lib/libresolv")
3418 || StartsWithStrLit(
filename,
"/usr/lib/libauto")
3419 || StartsWithStrLit(
filename,
"/usr/lib/libcups")
3420 || StartsWithStrLit(
filename,
"/usr/lib/libDiagnosticMessagesClient")
3421 || StartsWithStrLit(
filename,
"/usr/lib/liblangid")
3422 || StartsWithStrLit(
filename,
"/usr/lib/libCRFSuite")
3423 || StartsWithStrLit(
filename,
"/usr/lib/libpam")
3424 || StartsWithStrLit(
filename,
"/usr/lib/libOpenScriptingUtil")
3425 || StartsWithStrLit(
filename,
"/usr/lib/libextension")
3426 || StartsWithStrLit(
filename,
"/usr/lib/libAudioToolboxUtility")
3427 || StartsWithStrLit(
filename,
"/usr/lib/liboah")
3428 || StartsWithStrLit(
filename,
"/usr/lib/libRosetta")
3429 || StartsWithStrLit(
filename,
"/usr/lib/libCoreEntitlements")
3430 || StartsWithStrLit(
filename,
"/usr/lib/libssl.")
3431 || StartsWithStrLit(
filename,
"/usr/lib/libcrypto.")
3437 || StartsWithStrLit(
filename,
"/usr/lib/system/libsystem_kernel")
3438 || StartsWithStrLit(
filename,
"/usr/lib/system/libsystem_platform")
3439 || StartsWithStrLit(
filename,
"/usr/lib/system/libsystem_pthread")
3444 || (lenFilename > 4 && !strcmp(
filename + lenFilename - 4,
".tbd")))
3447 R__UpdateLibFileForLinking(sFileName);
3449#elif defined(__CYGWIN__)
3451 static const int bufsize = 260;
3452 char posixwindir[bufsize];
3453 char *windir = getenv(
"WINDIR");
3455 cygwin_conv_path(CCP_WIN_A_TO_POSIX, windir, posixwindir, bufsize);
3457 snprintf(posixwindir,
sizeof(posixwindir),
"/Windows/");
3458 if (strstr(
filename, posixwindir) ||
3461#elif defined(R__WIN32)
3464#elif defined (R__LINUX)
3488 assert(!
IsFromRootCling() &&
"Trying to load library from rootcling!");
3492 cling::DynamicLibraryManager* DLM =
fInterpreter->getDynamicLibraryManager();
3493 std::string canonLib = DLM->lookupLibrary(
filename);
3494 cling::DynamicLibraryManager::LoadLibResult res
3495 = cling::DynamicLibraryManager::kLoadLibNotFound;
3496 if (!canonLib.empty()) {
3498 res = DLM->loadLibrary(
filename, system,
true);
3502 cling::Interpreter::CompilationResult compRes;
3504 if (compRes == cling::Interpreter::kSuccess)
3505 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3509 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3513 case cling::DynamicLibraryManager::kLoadLibSuccess:
return 0;
3514 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded:
return 1;
3564 Warning(
"Calc",
"waiting for cling thread to free");
3567 gROOT->SetLineIsProcessing();
3575 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3579 catch (cling::InterpreterException&
ex)
3581 Error(
"Calc",
"%s.\n%s",
ex.what(),
"Evaluation of your expression was aborted.");
3583 cr = cling::Interpreter::kFailure;
3586 if (cr != cling::Interpreter::kSuccess) {
3594 if (!valRef.isValid()) {
3603 if (valRef.isVoid()) {
3610 gROOT->SetLineHasBeenProcessed();
3613 return valRef.simplisticCastAs<
Longptr_t>();
3620 void (*histaddFunc)(
const char*
line))
3625#if defined(R__MUST_REVISIT)
3626#if R__MUST_REVISIT(6,2)
3627 Warning(
"SetGetline",
"Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3640 if ((std::distance(
T.decls_begin(),
T.decls_end()) != 1)
3641 ||
T.deserialized_decls_begin() !=
T.deserialized_decls_end()
3642 ||
T.macros_begin() !=
T.macros_end()
3643 || ((!
T.getFirstDecl().isNull()) && ((*
T.getFirstDecl().begin()) !=
T.getWrapperFD()))) {
3666 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)
fgSetOfSpecials)->find(obj);
3684#if defined(R__MUST_REVISIT)
3685#if R__MUST_REVISIT(6,2)
3687 Warning(
"Reset",
"Cling should support the equivalent of scratch_upto(&fDictPos)");
3697#if defined(R__MUST_REVISIT)
3698#if R__MUST_REVISIT(6,2)
3700 Warning(
"ResetAll",
"Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3727#if defined(R__MUST_REVISIT)
3728#if R__MUST_REVISIT(6,2)
3730 Warning(
"ResetGlobalVar",
"Cling should support the equivalent of resetglobalvar(obj)");
3742#if defined(R__MUST_REVISIT)
3743#if R__MUST_REVISIT(6,2)
3745 Warning(
"RewindDictionary",
"Cling should provide a way to revert transaction similar to rewinddictionary()");
3756#if defined(R__MUST_REVISIT)
3757#if R__MUST_REVISIT(6,2)
3759 Warning(
"DeleteGlobal",
"Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3771#if defined(R__MUST_REVISIT)
3772#if R__MUST_REVISIT(6,2)
3773 Warning(
"DeleteVariable",
"should do more that just reseting the value to zero");
3778 llvm::StringRef srName(
name);
3779 const char* unscopedName =
name;
3780 llvm::StringRef::size_type posScope = srName.rfind(
"::");
3781 const clang::DeclContext* declCtx =
nullptr;
3782 if (posScope != llvm::StringRef::npos) {
3783 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
3784 const clang::Decl* scopeDecl
3785 = lh.findScope(srName.substr(0, posScope),
3786 cling::LookupHelper::WithDiagnostics);
3788 Error(
"DeleteVariable",
"Cannot find enclosing scope for variable %s",
3792 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3794 Error(
"DeleteVariable",
3795 "Enclosing scope for variable %s is not a declaration context",
3799 unscopedName += posScope + 2;
3803 clang::NamedDecl* nVarDecl
3804 = cling::utils::Lookup::Named(&
fInterpreter->getSema(), unscopedName, declCtx);
3806 Error(
"DeleteVariable",
"Unknown variable %s",
name);
3809 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3811 Error(
"DeleteVariable",
"Entity %s is not a variable",
name);
3815 clang::QualType qType = varDecl->getType();
3819 if (
type->isPointerType()) {
3820 int** ppInt = (
int**)
fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3822 if (ppInt) *ppInt =
nullptr;
3832#if defined(R__MUST_REVISIT)
3833#if R__MUST_REVISIT(6,2)
3835 Warning(
"SaveContext",
"Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3845#if defined(R__MUST_REVISIT)
3846#if R__MUST_REVISIT(6,2)
3848 Warning(
"SaveGlobalsContext",
"Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3896 std::tuple<int,double>
value;
3900 size_t offset0 = ((
char*)&(std::get<0>(
value))) - ((
char*)&
value);
3901 size_t offset1 = ((
char*)&(std::get<1>(
value))) - ((
char*)&
value);
3903 size_t ascOffset0 = ((
char*)&(asc.
_0)) - ((
char*)&asc);
3904 size_t ascOffset1 = ((
char*)&(asc.
_1)) - ((
char*)&asc);
3906 size_t desOffset0 = ((
char*)&(des.
_0)) - ((
char*)&des);
3907 size_t desOffset1 = ((
char*)&(des.
_1)) - ((
char*)&des);
3909 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3911 }
else if (offset0 == desOffset0 && offset1 == desOffset1) {
3918static std::string
AlternateTuple(
const char *classname,
const cling::LookupHelper& lh)
3921 std::string alternateName =
"TEmulatedTuple";
3922 alternateName.append( classname + 5 );
3924 std::string fullname =
"ROOT::Internal::" + alternateName;
3925 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
3929 std::string guard_name;
3931 std::ostringstream guard;
3932 guard <<
"ROOT_INTERNAL_TEmulated_";
3933 guard << guard_name;
3935 std::ostringstream alternateTuple;
3936 alternateTuple <<
"#ifndef " << guard.str() <<
"\n";
3937 alternateTuple <<
"#define " << guard.str() <<
"\n";
3938 alternateTuple <<
"namespace ROOT { namespace Internal {\n";
3939 alternateTuple <<
"template <class... Types> struct TEmulatedTuple;\n";
3940 alternateTuple <<
"template <> struct " << alternateName <<
" {\n";
3945 unsigned int nMember = 0;
3946 auto iter = tupleContent.
fElements.begin() + 1;
3947 auto theEnd = tupleContent.
fElements.end() - 1;
3948 while (iter != theEnd) {
3949 alternateTuple <<
" " << *iter <<
" _" << nMember <<
";\n";
3956 unsigned int nMember = tupleContent.
fElements.size() - 3;
3957 auto iter = tupleContent.
fElements.rbegin() + 1;
3958 auto theEnd = tupleContent.
fElements.rend() - 1;
3959 while (iter != theEnd) {
3960 alternateTuple <<
" " << *iter <<
" _" << nMember <<
";\n";
3967 Fatal(
"TCling::SetClassInfo::AlternateTuple",
3968 "Layout of std::tuple on this platform is unexpected.");
3973 alternateTuple <<
"};\n";
3974 alternateTuple <<
"}}\n";
3975 alternateTuple <<
"#endif\n";
3977 Error(
"Load",
"Could not declare %s",alternateName.c_str());
3980 alternateName =
"ROOT::Internal::" + alternateName;
3981 return alternateName;
4024 if (strncmp(cl->
GetName(),
"tuple<",strlen(
"tuple<"))==0) {
4060 zombieCandidate =
kTRUE;
4067 zombieCandidate =
kTRUE;
4121 static const char *anonEnum =
"anonymous enum ";
4122 static const int cmplen = strlen(anonEnum);
4149 const char *classname =
name;
4152 class MaybeSuspendAutoLoadParse {
4153 int fStoreAutoLoad = 0;
4154 int fStoreAutoParse = 0;
4155 bool fSuspendedAutoParse =
false;
4157 MaybeSuspendAutoLoadParse(
int autoload) {
4158 fStoreAutoLoad = ((
TCling*)
gCling)->SetClassAutoLoading(autoload);
4162 fSuspendedAutoParse =
true;
4163 fStoreAutoParse = ((
TCling*)
gCling)->SetSuspendAutoParsing(
true);
4166 ~MaybeSuspendAutoLoadParse() {
4167 if (fSuspendedAutoParse)
4168 ((
TCling*)
gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4169 ((
TCling*)
gCling)->SetClassAutoLoading(fStoreAutoLoad);
4173 MaybeSuspendAutoLoadParse autoLoadParseRAII( autoload );
4175 autoLoadParseRAII.SuspendAutoParsing();
4184 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
4186 const clang::Decl *decl
4187 = lh.findScope(classname,
4188 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4189 : cling::LookupHelper::NoDiagnostics,
4193 decl = lh.findScope(buf,
4194 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4195 : cling::LookupHelper::NoDiagnostics,
4212 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4213 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4214 (
type->getAsCXXRecordDecl());
4215 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4232 if (tci.
Property() & propertiesMask) {
4233 bool hasClassDefInline =
false;
4234 if (isClassOrNamespaceOnly) {
4240 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4242 bool success =
false;
4243 std::tie(success, lineNumber) =
4245 hasClassDefInline = success && (lineNumber == -1);
4253 if (hasClassDefInline)
4292 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
4293 const clang::Decl *decl
4294 = lh.findClassTemplate(
name,
4295 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4296 : cling::LookupHelper::NoDiagnostics);
4298 std::string strname =
"std::";
4300 decl = lh.findClassTemplate(strname,
4301 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4302 : cling::LookupHelper::NoDiagnostics);
4304 return nullptr != decl;
4328 cl->
fBase = listOfBase;
4344 D =
fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4347 if (
const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4350 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4351 const_cast< clang::DeclContext *
>(DC)->collectAllContexts(allDeclContexts);
4352 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(), declEnd = allDeclContexts.end();
4353 declIter != declEnd; ++declIter) {
4355 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4356 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4357 if (
const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4360 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4361 llvm::raw_string_ostream stream(buf);
4363 Policy.AnonymousTagLocations =
false;
4364 ED->getNameForDiagnostic(stream, Policy,
false);
4368 const char*
name = buf.c_str();
4392 D =
fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4396 if (
const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4399 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4400 const_cast< clang::DeclContext *
>(DC)->collectAllContexts(allDeclContexts);
4401 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(),
4402 declEnd = allDeclContexts.end(); declIter != declEnd; ++declIter) {
4404 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4405 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4406 if (
const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4407 funcTempList->
Get(FTD);
4465 if (
m->fMethodArgs) {
4476 m->fMethodArgs = arglist;
4523 if (llvm::isa<clang::NamespaceDecl>(cli->
GetDecl())) {
4532 Error(
"GenerateTClass",
4533 "Cannot find %s::Class_Version()! Class version might be wrong.",
4540 if (newvers == -1) {
4548 newvers = callfunc.
ExecInt(
nullptr);
4550 Error(
"GenerateTClass",
4551 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4555 if (newvers != oldvers) {
4572static void GenerateTClass_GatherInnerIncludes(cling::Interpreter *interp,
TString &includes,
TClingClassInfo *info)
4576 const clang::ClassTemplateSpecializationDecl *templateCl
4577 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->
GetDecl());
4579 for(
unsigned int i=0; i < templateCl->getTemplateArgs().
size(); ++i) {
4580 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4584 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4586 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4589 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4590 GenerateTClass_GatherInnerIncludes(interp, includes, &subinfo);
4593 llvm::raw_string_ostream OS(Result);
4594 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4595 Warning(
"TCling::GenerateTClass",
"Missing header file for %s",OS.str().c_str());
4610 if (!info || !info->
IsValid()) {
4611 Fatal(
"GenerateTClass",
"Requires a valid ClassInfo object");
4616 std::string classname;
4620 Info(
"GenerateTClass",
"Will (try to) generate the compiled TClass for %s.",classname.c_str());
4624 GenerateTClass_GatherInnerIncludes(
fInterpreter,includes,info);
4630 Error(
"GenerateTClass",
"Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4634 if (cl ==
nullptr) {
4636 cl =
new TClass(classinfo, version,
nullptr,
nullptr, -1, -1, silent);
4642 cl =
new TClass(classinfo, 1,
nullptr,
nullptr, -1, -1, silent);
4667 if (classes ==
nullptr || classes[0] == 0) {
4668 Error(
"TCling::GenerateDictionary",
"Cannot generate dictionary without passing classes.");
4672 std::vector<std::string> listClasses;
4674 const char* current = classes, *prev = classes;
4678 if (*current ==
';') {
4679 listClasses.push_back(std::string(prev, current - prev));
4682 else if (*(current + 1) == 0) {
4683 listClasses.push_back(std::string(prev, current + 1 - prev));
4687 std::vector<std::string> listIncludes;
4691 const char* current = includes, *prev = includes;
4695 if (*current ==
';') {
4696 listIncludes.push_back(std::string(prev, current - prev));
4699 else if (*(current + 1) == 0) {
4700 listIncludes.push_back(std::string(prev, current + 1 - prev));
4706 std::vector<std::string>(), std::vector<std::string>());
4727 if (
const ValueDecl* decl = (
const ValueDecl*)
d){
4730 if (hasIoName && ioName !=
name)
return nullptr;
4742 using namespace clang;
4744 DeclarationName DName = &SemaR.Context.Idents.get(
name);
4746 LookupResult
R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4747 Sema::ForExternalRedeclaration);
4751 cling::utils::Lookup::Named(&SemaR,
R);
4755 while (
F.hasNext()) {
4756 NamedDecl *D =
F.next();
4757 if (isa<VarDecl>(D) || isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
4758 isa<IndirectFieldDecl>(D))
4764 if (
R.isSingleResult())
4765 return R.getFoundDecl();
4777 const clang::Decl* possibleEnum =
nullptr;
4782 const clang::DeclContext* dc =
nullptr;
4783 if (
const clang::Decl* D = cci->
GetDecl()) {
4784 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4785 dc = dyn_cast<clang::RecordDecl>(D);
4792 possibleEnum = cling::utils::Lookup::Tag(&
fInterpreter->getSema(),
name, dc);
4794 Error(
"TCling::GetEnum",
"DeclContext not found for %s .\n",
name);
4803 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4804 && isa<clang::EnumDecl>(possibleEnum)) {
4805 return possibleEnum;
4815 if (!gv)
return nullptr;
4817 llvm::StringRef mangled_name = gv->getName();
4832 std::string scopename(demangled_name_c);
4833 free(demangled_name_c);
4839 std::string dataname;
4841 if (!strncmp(scopename.c_str(),
"typeinfo for ",
sizeof(
"typeinfo for ")-1)) {
4842 scopename.erase(0,
sizeof(
"typeinfo for ")-1);
4843 }
else if (!strncmp(scopename.c_str(),
"vtable for ",
sizeof(
"vtable for ")-1)) {
4844 scopename.erase(0,
sizeof(
"vtable for ")-1);
4847 std::string::size_type pos = scopename.rfind(
'(');
4848 if (pos != std::string::npos) {
4852 pos = scopename.rfind(
':');
4853 if (pos != std::string::npos) {
4854 if ((pos != 0) && (scopename[pos-1] ==
':')) {
4855 dataname = scopename.substr(pos+1);
4856 scopename.erase(pos-1);
4860 dataname = scopename;
4868 if (scopename.size()) {
4884 Error(
"GetDataMemberWithValue()",
"not implemented");
4894 Error(
"GetDataMemberAtAddr()",
"not implemented");
4904 const char* params,
Bool_t objectIsConst )
4922 return mangled_name;
4949 const char* params,
Bool_t objectIsConst )
4990 std::vector<DeclId_t>& res)
const
4993 clang::ASTContext& Ctx =
S.Context;
4994 const clang::Decl* CtxDecl
4996 Ctx.getTranslationUnitDecl();
4997 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
4998 const clang::DeclContext* DeclCtx = RecDecl;
5001 DeclCtx = dyn_cast<clang::NamespaceDecl>(CtxDecl);
5002 if (!DeclCtx)
return;
5004 clang::DeclarationName DName;
5009 if (RecDecl->getNameAsString() == funcname) {
5010 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5011 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
5012 }
else if (funcname[0] ==
'~' && RecDecl->getNameAsString() == funcname + 1) {
5013 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5014 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
5016 DName = &Ctx.Idents.get(funcname);
5019 DName = &Ctx.Idents.get(funcname);
5023 clang::LookupResult
R(
S, DName, clang::SourceLocation(),
5024 Sema::LookupOrdinaryName, clang::Sema::NotForRedeclaration);
5025 R.suppressDiagnostics();
5026 S.LookupQualifiedName(
R,
const_cast<DeclContext*
>(DeclCtx));
5027 if (
R.empty())
return;
5029 res.reserve(res.size() + (
R.end() -
R.begin()));
5030 for (clang::LookupResult::iterator IR =
R.begin(), ER =
R.end();
5032 if (
const clang::FunctionDecl* FD
5033 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5034 if (!FD->getDescribedFunctionTemplate()) {
5037 }
else if (
const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5039 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5199 const char* params,
Bool_t objectIsConst,
int* error)
5219 const char* params,
int* error)
5221 Execute(obj,cl,method,params,
false,error);
5236 Error(
"Execute",
"No method was defined");
5245 if (argc > nparms) {
5246 Error(
"Execute",
"Too many parameters to call %s, got %d but expected at most %d.",method->
GetName(),argc,nparms);
5249 if (nparms != argc) {
5259 Int_t firstDefault = -1;
5260 for (
Int_t i = 0; i < nparms; i ++) {
5267 if (firstDefault >= 0) {
5268 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);
5270 Error(
"Execute",
"Too few arguments to call %s, got only %d but expected %d.",method->
GetName(),argc,nparms);
5276 const char* listpar =
"";
5281 for (
Int_t i = 0; i < argc; i ++) {
5297 complete += nxtpar->
String();
5300 listpar = complete.
Data();
5327 const void* args[] ,
5332 Error(
"ExecuteWithArgsAndReturn",
"No method was defined");
5359 Warning(
"GetTopLevelMacroName",
"Must change return type!");
5406#if defined(R__MUST_REVISIT)
5407#if R__MUST_REVISIT(6,0)
5408 Warning(
"GetCurrentMacroName",
"Must change return type!");
5421 TTHREAD_TLS_DECL(std::string,t);
5423 if (!strstr(typeDesc,
"(*)(")) {
5424 const char *
s = strchr(typeDesc,
' ');
5425 const char *template_start = strchr(typeDesc,
'<');
5426 if (!strcmp(typeDesc,
"long long")) {
5429 else if (!strncmp(typeDesc,
"unsigned ",
s + 1 - typeDesc)) {
5436 else if (
s && (template_start ==
nullptr || (
s < template_start))) {