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__; }
343 return ((
TCling*)
gCling)->LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
382 static vector<const NamedDecl*> updateList;
385 if (entered) topLevel =
kFALSE;
400 updateList.push_back(TD);
403 while (!updateList.empty()) {
405 updateList.pop_back();
412 const clang::Decl* D =
static_cast<const clang::Decl*
>(enumObj->
GetDeclId());
413 if(
const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
415 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
416 EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
418 std::string constbuf;
419 if (
const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
420 PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
421 llvm::raw_string_ostream stream(constbuf);
423 Policy.AnonymousTagLocations =
false;
424 (END)->getNameForDiagnostic(stream, Policy,
false);
426 const char* constantName = constbuf.c_str();
430 const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
431 if (valAPSInt.isSigned()) {
432 value = valAPSInt.getSExtValue();
434 value = valAPSInt.getZExtValue();
441 DataMemberInfo_t* dmInfo = (DataMemberInfo_t*) tcDmInfo;
452 globals->
Add(enumConstant);
465 const clang::Decl* D =
static_cast<const clang::Decl*
>(VD);
467 if (
const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
469 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
470 llvm::raw_string_ostream stream(buf);
472 Policy.AnonymousTagLocations =
false;
473 ED->getNameForDiagnostic(stream, Policy,
false);
479 const char*
name = buf.c_str();
490 const clang::Decl* D =
static_cast<const clang::Decl*
>(DV);
492 if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
493 && !dyn_cast<clang::RecordDecl>(D))
return;
495 if (isa<clang::FunctionDecl>(D->getDeclContext())
496 || isa<clang::TagDecl>(D->getDeclContext()))
500 if (
const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
501 if (RD->getDescribedClassTemplate())
503 }
else if (
const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
504 if (FD->getDescribedFunctionTemplate())
508 if (
const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
509 if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
512 else if (
const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
514 if (
const TagDecl *TD = dyn_cast<TagDecl>(D)) {
518 }
else if (
const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
523 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
527 if (isa<EnumDecl>(ND))
532 if (!(isa<VarDecl>(ND)))
536 if (
gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
540 gROOT->GetListOfGlobals()->Add(
new TGlobal((DataMemberInfo_t *)
542 cast<ValueDecl>(ND), 0)));
574 const char* canonicalName) {
575 ((
TCling*)
gCling)->LibraryLoaded(dyLibHandle, canonicalName);
580 ((
TCling *)
gCling)->RegisterRdictForLoadPCM(pcmFileNameFullPath, pcmContent);
584 const char* canonicalName) {
585 ((
TCling*)
gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
601 auto tcling =
new TCling(
"C++",
"cling C++ Interpreter", argv);
602 cling::DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(interpLibHandle);
625 return ((
TCling*)
gCling)->GetClassSharedLibs(className);
631 return ((
TCling*)
gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
636 string file(fileName);
642 string &args,
string &io,
string &fname)
644 string file(fileName);
645 TString f, amode, arguments, aclicio;
648 io = aclicio.
Data(); fname =
f.Data();
658 char *__unDName(
char *demangled,
const char *mangled,
int out_len,
659 void * (* pAlloc )(
size_t),
void (* pFree )(
void *),
660 unsigned short int flags);
672 using namespace clang;
673 if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
677 if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
689 return ((
TCling*)
gCling)->LazyFunctionCreatorAutoload(mangled_name);
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 == NULL) {
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.getModuleManager();
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.getModuleManager()->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->IsMissingRequirement)
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");
1433 clingArgsStorage.push_back(
"-O1");
1436 clingArgsStorage.push_back(
"-mllvm");
1437 clingArgsStorage.push_back(
"-optimize-regalloc=0");
1442 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(
"EXTRA_CLING_ARGS");
1443 if (EnvOpt.hasValue()) {
1444 StringRef Env(*EnvOpt);
1445 while (!Env.empty()) {
1447 std::tie(Arg, Env) = Env.split(
' ');
1448 clingArgsStorage.push_back(Arg.str());
1452 auto GetEnvVarPath = [](
const std::string &EnvVar,
1453 std::vector<std::string> &Paths) {
1454 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1455 if (EnvOpt.hasValue()) {
1456 StringRef Env(*EnvOpt);
1457 while (!Env.empty()) {
1460 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1461 Paths.push_back(Arg.str());
1467 std::vector<std::string> Paths;
1476 GetEnvVarPath(
"CLING_PREBUILT_MODULE_PATH", Paths);
1477 std::string EnvVarPath;
1478 for (
const std::string&
P : Paths)
1481 gSystem->
Setenv(
"CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1485 EnvOpt = llvm::sys::Process::GetEnv(
"ROOT_CLING_TIMING");
1486 if (EnvOpt.hasValue())
1487 clingArgsStorage.push_back(
"-ftime-report");
1494 std::vector<std::string> ModuleMaps;
1497 GetEnvVarPath(
"CLING_MODULEMAP_FILES", ModuleMaps);
1501 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1502 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1504 for (
const std::string& M : ModuleMaps)
1505 clingArgsStorage.push_back(
"-fmodule-map-file=" + M);
1507 std::string ModulesCachePath;
1508 EnvOpt = llvm::sys::Process::GetEnv(
"CLING_MODULES_CACHE_PATH");
1509 if (EnvOpt.hasValue()){
1510 StringRef Env(*EnvOpt);
1511 assert(llvm::sys::fs::exists(Env) &&
"Path does not exist!");
1512 ModulesCachePath = Env.str();
1517 clingArgsStorage.push_back(
"-fmodules-cache-path=" + ModulesCachePath);
1520 std::vector<const char*> interpArgs;
1521 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1522 eArg = clingArgsStorage.end(); iArg != eArg; ++iArg)
1523 interpArgs.push_back(iArg->c_str());
1530 if (!fromRootCling) {
1532 interpArgs.push_back(
"-fmodules");
1533 interpArgs.push_back(
"-fno-implicit-module-maps");
1537 interpArgs.push_back(
"-Rmodule-build");
1543 interpArgs.push_back(
"-fno-autolink");
1548 interpArgs.push_back(
"-ffast-math");
1554 extraArgs && *extraArgs; ++extraArgs) {
1555 if (!strcmp(*extraArgs,
"-resource-dir")) {
1557 llvmResourceDir = *(++extraArgs);
1559 interpArgs.push_back(*extraArgs);
1564 interpArgs.push_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 = llvm::make_unique<cling::Interpreter>(interpArgs.size(),
1575 llvmResourceDir, extensions);
1578 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHValidation =
true;
1582 fInterpreter->getCI()->getLangOpts().SpellChecking =
false;
1587 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO,
false);
1607 if (!fromRootCling) {
1612 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1617 std::unique_ptr<TClingCallbacks>
1623 if (!fromRootCling) {
1624 cling::DynamicLibraryManager& DLM = *
fInterpreter->getDynamicLibraryManager();
1629 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) ->
bool{
1630 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1631 return stem.startswith(
"libNew") || stem.startswith(
"libcppyy_backend");
1634 DLM.initializeDyld(ShouldPermanentlyIgnore);
1673 assert(
GetRootMapFiles() == 0 &&
"Must be called before LoadLibraryMap!");
1692 auto setFactory = []() {
1696 static bool doneFactory = setFactory();
1708 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1709 ::Error(
"TCling::RegisterRdictForLoadPCM",
"Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1726 if (listOfKeys && ((listOfKeys->GetSize() == 0) ||
1727 ((listOfKeys->GetSize() == 1) &&
1728 !strcmp(((
TKey *)listOfKeys->At(0))->GetName(),
"EMPTY")
1735 ::Info(
"TCling::LoadPCMImpl",
"reading protoclasses for %s \n", pcmFile.
GetName());
1741 auto listOfGlobals =
gROOT->GetListOfGlobals();
1742 auto listOfEnums =
dynamic_cast<THashList *
>(
gROOT->GetListOfEnums());
1744 for (
auto selEnum : *enums) {
1745 const char *enumScope = selEnum->
GetTitle();
1746 const char *enumName = selEnum->GetName();
1747 if (strcmp(enumScope,
"") == 0) {
1750 if (!listOfEnums->THashList::FindObject(enumName)) {
1751 ((
TEnum *)selEnum)->SetClass(
nullptr);
1752 listOfEnums->Add(selEnum);
1755 if (!listOfGlobals->FindObject(enumConstant)) {
1756 listOfGlobals->Add(enumConstant);
1763 if (!nsTClassEntry) {
1766 auto listOfEnums = nsTClassEntry->
fEnums.load();
1777 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1778 ((
TEnum *)selEnum)->SetClass(nsTClassEntry);
1779 listOfEnums->Add(selEnum);
1787 pcmFile.
GetObject(
"__ProtoClasses", protoClasses);
1790 for (
auto obj : *protoClasses) {
1800 for (
auto proto : *protoClasses) {
1808 ::Error(
"TCling::LoadPCM",
"Inconsistent TClassTable for %s",
proto->GetName());
1819 protoClasses->Clear();
1820 delete protoClasses;
1824 pcmFile.
GetObject(
"__Typedefs", dataTypes);
1826 for (
auto typedf : *dataTypes)
1827 gROOT->GetListOfTypes()->Add(typedf);
1840 assert(!pcmFileNameFullPath.empty());
1841 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1844 TString pcmFileName = pcmFileNameFullPath;
1852 llvm::SaveAndRestore<Int_t> SaveGDebug(
gDebug);
1855 ::Info(
"TCling::LoadPCM",
"Loading ROOT PCM %s", pcmFileName.
Data());
1860 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1865 llvm::StringRef pcmContent = pendingRdict->second;
1867 std::string RDictFileOpts = pcmFileNameFullPath +
"?filetype=pcm";
1868 TMemFile pcmMemFile(RDictFileOpts.c_str(), range);
1877 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1878 ::Error(
"TCling::LoadPCM",
"ROOT PCM %s file does not exist",
1879 pcmFileNameFullPath.data());
1882 ::Info(
"TCling::LoadPCM",
"In-memory ROOT PCM candidate %s\n",
1883 rdict.first.c_str());
1887 if (!
gROOT->IsRootFile(pcmFileName)) {
1888 Fatal(
"LoadPCM",
"The file %s is not a ROOT as was expected\n", pcmFileName.
Data());
1891 TFile pcmFile(pcmFileName +
"?filetype=pcm",
"READ");
1898 using namespace clang;
1900 class ExtLexicalStorageAdder:
public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1905 bool VisitRecordDecl(clang::RecordDecl* rcd){
1907 Info(
"ExtLexicalStorageAdder",
1908 "Adding external lexical storage to class %s",
1909 rcd->getNameAsString().c_str());
1910 auto reDeclPtr = rcd->getMostRecentDecl();
1912 reDeclPtr->setHasExternalLexicalStorage();
1913 }
while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1926 const std::string &ModuleMapName )
const
1928 assert(llvm::sys::path::is_absolute(FullPath));
1929 Preprocessor &PP =
fInterpreter->getCI()->getPreprocessor();
1930 FileManager &FM = PP.getFileManager();
1933 const DirectoryEntry *DE = FM.getDirectory(FullPath);
1935 HeaderSearch &HS = PP.getHeaderSearchInfo();
1936 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1937 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1938 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1940 HSOpts.AddPrebuiltModulePath(FullPath);
1945 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1946 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1947 const FileEntry *FE = FM.getFile(ModuleMapFileName,
false,
1950 if (!HS.loadModuleMapFile(FE,
false))
1952 Error(
"RegisterPrebuiltModulePath",
"Could not load modulemap in %s", ModuleMapFileName.c_str());
1969 "libforward_listDict",
1977 "libunordered_setDict",
1978 "libunordered_multisetDict",
1979 "libunordered_mapDict",
1980 "libunordered_multimapDict",
1988 char dyLibError[1000];
1989 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1990 dyLibError,
sizeof(dyLibError), NULL);
1992 const char *dyLibError = dlerror();
1994 ::Error(
"TCling::RegisterModule",
"Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
1995 (dyLibError) ? dyLibError :
"");
2032 const char** headers,
2033 const char** includePaths,
2034 const char* payloadCode,
2035 const char* fwdDeclsCode,
2036 void (*triggerFunc)(),
2038 const char** classesHeaders,
2039 Bool_t lateRegistration ,
2046 if (fromRootCling)
return;
2055 bool isACLiC = strstr(modulename,
"_ACLiC_dict") !=
nullptr;
2056 if (hasHeaderParsingOnDemand && isACLiC) {
2058 Info(
"TCling::RegisterModule",
2059 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2060 hasHeaderParsingOnDemand =
false;
2074 for (
const char** inclPath = includePaths; *inclPath; ++inclPath) {
2077 cling::Transaction*
T = 0;
2079 for (
auto& fwdDeclArgToSkipPair : fwdDeclsArgToSkip){
2080 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2081 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2083 assert(cling::Interpreter::kSuccess == compRes &&
2084 "A fwd declaration could not be compiled");
2085 if (compRes!=cling::Interpreter::kSuccess){
2086 Warning(
"TCling::RegisterModule",
2087 "Problems in declaring string '%s' were encountered.",
2102 TString code = gNonInterpreterClassDef;
2104 code += payloadCode;
2106 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2107 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2109 if (dyLibName.empty()) {
2110 ::Error(
"TCling::RegisterModule",
"Dictionary trigger function for %s not found", modulename);
2115 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2117 bool wasDlopened =
false;
2122 if (!lateRegistration) {
2129 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2139 if (hasHeaderParsingOnDemand && fwdDeclsCode){
2142 std::string fwdDeclsCodeLessEnums;
2146 std::string fwdDeclsLine;
2147 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2148 std::vector<std::string> scopes;
2149 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2150 const auto enumPos = fwdDeclsLine.find(
"enum __attribute__((annotate(\"");
2152 if (enumPos != std::string::npos) {
2159 auto nsPos = fwdDeclsLine.find(
"namespace");
2160 R__ASSERT(nsPos < enumPos &&
"Inconsistent enum and enclosing scope parsing!");
2161 while (nsPos < enumPos && nsPos != std::string::npos) {
2163 const auto nsNameStart = nsPos + 10;
2164 const auto nsNameEnd = fwdDeclsLine.find(
'{', nsNameStart);
2165 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2166 scopes.push_back(nsName);
2167 nsPos = fwdDeclsLine.find(
"namespace", nsNameEnd);
2170 clang::DeclContext* DC = 0;
2171 for (
auto &&aScope: scopes) {
2172 DC = cling::utils::Lookup::Namespace(&
fInterpreter->getSema(), aScope.c_str(), DC);
2178 if (scopes.empty() || DC) {
2180 size_t posEnumName = fwdDeclsLine.find(
"\"))) ", 32);
2181 R__ASSERT(posEnumName != std::string::npos &&
"Inconsistent enum fwd decl!");
2183 while (isspace(fwdDeclsLine[posEnumName]))
2185 size_t posEnumNameEnd = fwdDeclsLine.find(
" : ", posEnumName);
2186 R__ASSERT(posEnumNameEnd != std::string::npos &&
"Inconsistent enum fwd decl (end)!");
2187 while (isspace(fwdDeclsLine[posEnumNameEnd]))
2191 std::string enumName = fwdDeclsLine.substr(posEnumName,
2192 posEnumNameEnd - posEnumName + 1);
2194 if (clang::NamedDecl* enumDecl
2195 = cling::utils::Lookup::Named(&
fInterpreter->getSema(),
2196 enumName.c_str(), DC)) {
2199 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) &&
"not an enum decl!");
2206 fwdDeclsCodeLessEnums += fwdDeclsLine +
"\n";
2210 if (!fwdDeclsCodeLessEnums.empty()){
2211 auto compRes =
fInterpreter->declare(fwdDeclsCodeLessEnums, &
T);
2212 assert(cling::Interpreter::kSuccess == compRes &&
2213 "The forward declarations could not be compiled");
2214 if (compRes!=cling::Interpreter::kSuccess){
2215 Warning(
"TCling::RegisterModule",
2216 "Problems in compiling forward declarations for module %s: '%s'",
2217 modulename, fwdDeclsCodeLessEnums.c_str()) ;
2225 ExtLexicalStorageAdder elsa;
2226 for (
auto dciIt =
T->decls_begin();dciIt!=
T->decls_end();dciIt++){
2227 cling::Transaction::DelayCallInfo& dci = *dciIt;
2228 for(
auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2229 clang::Decl* declPtr = *dit;
2230 elsa.TraverseDecl(declPtr);
2244 for (
const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2245 temp=*classesHeader;
2247 size_t theTemplateHash = 0;
2248 bool addTemplate =
false;
2249 size_t posTemplate = temp.find(
'<');
2250 if (posTemplate != std::string::npos) {
2252 std::string templateName = temp.substr(0, posTemplate);
2258 for (
const char** classesHeader_inner = classesHeader; 0!=strcmp(*classesHeader_inner,
"@"); ++classesHeader_inner,++classesHeader){
2260 if (payloadCode == *classesHeader_inner ){
2262 if (addTemplate)
fPayloads.insert(theTemplateHash);
2265 Info(
"TCling::RegisterModule",
2266 "Adding a header for %s", temp.c_str());
2272 addTemplate =
false;
2280 bool ModuleWasSuccessfullyLoaded =
false;
2282 std::string ModuleName = modulename;
2283 if (llvm::StringRef(modulename).startswith(
"lib"))
2284 ModuleName = llvm::StringRef(modulename).substr(3).str();
2289 clang::Preprocessor &PP = TheSema.getPreprocessor();
2290 std::string ModuleMapName;
2292 ModuleMapName = ModuleName +
".modulemap";
2294 ModuleMapName =
"module.modulemap";
2302 if (!ModuleWasSuccessfullyLoaded) {
2304 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2305 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2306 if (moduleMap.findModule(ModuleName))
2307 Info(
"TCling::RegisterModule",
"Module %s in modulemap failed to load.", ModuleName.c_str());
2312 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2315 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2316 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2317 llvm::sys::path::append(pcmFileNameFullPath,
2319 LoadPCM(pcmFileNameFullPath.str().str());
2326 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2328#if defined(R__MUST_REVISIT)
2329#if R__MUST_REVISIT(6,2)
2330 Warning(
"TCling::RegisterModule",
"Diagnostics suppression should be gone by now.");
2334 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand){
2337 const cling::Transaction* watermark =
fInterpreter->getLastTransaction();
2338 cling::Interpreter::CompilationResult compRes =
fInterpreter->parseForModule(code.
Data());
2344 assert(cling::Interpreter::kSuccess == compRes &&
2345 "Payload code of a dictionary could not be parsed correctly.");
2346 if (compRes!=cling::Interpreter::kSuccess) {
2347 Warning(
"TCling::RegisterModule",
2348 "Problems declaring payload for module %s.", modulename) ;
2361 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand) {
2364 "#undef __ROOTCLING__\n"
2365 + gInterpreterClassDef +
2370 assert(isSharedLib);
2373 dlclose(dyLibHandle);
2379 ASTContext &
C = CI.getASTContext();
2387 if (IdentifierInfoLookup *External =
C.Idents.getExternalIdentifierLookup()) {
2388 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2389 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2390 std::string
I = Ident.str();
2414 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2420 if ( i->first == oldcl ) {
2443 const char* input_line,
2444 cling::Interpreter::CompilationResult& compRes,
2448 return metaProcessor->process(input_line, compRes,
result);
2450 catch (cling::InterpreterException&
ex)
2452 Error(
"HandleInterpreterException",
"%s\n%s",
ex.what(),
"Execution of your code was aborted.");
2454 compRes = cling::Interpreter::kFailure;
2463 if (
auto ie =
dynamic_cast<const cling::InterpreterException*
>(&
e)) {
2489 gROOT->SetLineIsProcessing();
2493 gROOT->SetLineHasBeenProcessed();
2506 gROOT->SetLineIsProcessing();
2508 struct InterpreterFlagsRAII {
2510 bool fWasDynamicLookupEnabled;
2512 InterpreterFlagsRAII(cling::Interpreter* interp):
2514 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2518 ~InterpreterFlagsRAII() {
2519 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2520 gROOT->SetLineHasBeenProcessed();
2529 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2530 if (!strncmp(sLine.
Data(),
".L", 2) || !strncmp(sLine.
Data(),
".x", 2) ||
2531 !strncmp(sLine.
Data(),
".X", 2)) {
2539 aclicMode, arguments, io);
2540 if (aclicMode.
Length()) {
2542 R__ASSERT(aclicMode[0]==
'+' &&
"ACLiC mode must start with a +");
2544 if (aclicMode[1]==
'+') {
2550 compRes = cling::Interpreter::kFailure;
2552 if (strncmp(sLine.
Data(),
".L", 2) != 0) {
2555 if (arguments.
Length()==0) {
2564 mod_line =
function + arguments + io;
2570 size_t unnamedMacroOpenCurly;
2573 std::string codeline;
2576 std::ifstream in(fname, std::ifstream::binary);
2578 std::getline(in, codeline);
2579 code += codeline +
"\n";
2581 unnamedMacroOpenCurly
2582 = cling::utils::isUnnamedMacro(code,
fInterpreter->getCI()->getLangOpts());
2586 if (unnamedMacroOpenCurly != std::string::npos) {
2588 unnamedMacroOpenCurly);
2598 if (0!=strncmp(sLine.
Data(),
".autodict ",10) && sLine !=
".autodict") {
2603 bool isInclusionDirective = sLine.
Contains(
"\n#include") || sLine.
BeginsWith(
"#include");
2604 if (isInclusionDirective) {
2621 case cling::Interpreter::kSuccess: *error =
kNoError;
break;
2622 case cling::Interpreter::kFailure: *error =
kRecoverable;
break;
2623 case cling::Interpreter::kMoreInputExpected: *error =
kProcessing;
break;
2626 if (compRes == cling::Interpreter::kSuccess
2657 if (path[0] ==
'-' && path[1] ==
'I')
2682 static const TClassRef clRefString(
"std::string");
2683 if (clRefString == cl) {
2693 const char* cobj = (
const char*) obj;
2700 auto inspInspect = [&] (ptrdiff_t
offset){
2706 switch(complexType) {
2713 inspInspect(
sizeof(
float));
2718 inspInspect(
sizeof(
double));
2723 inspInspect(
sizeof(
int));
2728 inspInspect(
sizeof(
long));
2733 static clang::PrintingPolicy
2735 if (printPol.Indentation) {
2737 printPol.Indentation = 0;
2738 printPol.SuppressInitializers =
true;
2741 const char* clname = cl->
GetName();
2744 const clang::ASTContext& astContext =
fInterpreter->getCI()->getASTContext();
2745 const clang::Decl *scopeDecl = 0;
2750 scopeDecl = clingCI->
GetDecl();
2751 recordType = clingCI->
GetType();
2753 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
2755 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2759 Error(
"InspectMembers",
"Cannot find Decl for class %s", clname);
2762 const clang::CXXRecordDecl* recordDecl
2763 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2765 Error(
"InspectMembers",
"Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2774 astContext.getASTRecordLayout(recordDecl);
2776 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2777 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2780 const clang::ASTRecordLayout& recLayout
2781 = astContext.getASTRecordLayout(recordDecl);
2788 if (cl->
Size() != recLayout.getSize().getQuantity()) {
2789 Error(
"InspectMembers",
"TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2793 unsigned iNField = 0;
2796 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2797 eField = recordDecl->field_end(); iField != eField;
2798 ++iField, ++iNField) {
2801 clang::QualType memberQT = iField->getType();
2806 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT,
fNormalizedCtxt->
GetConfig(),
false );
2807 if (memberQT.isNull()) {
2808 std::string memberName;
2809 llvm::raw_string_ostream stream(memberName);
2811 printPol.AnonymousTagLocations =
false;
2812 iField->getNameForDiagnostic(stream, printPol,
true );
2814 Error(
"InspectMembers",
2815 "Cannot retrieve QualType for member %s while inspecting class %s",
2816 memberName.c_str(), clname);
2819 const clang::Type* memType = memberQT.getTypePtr();
2821 std::string memberName;
2822 llvm::raw_string_ostream stream(memberName);
2824 printPol.AnonymousTagLocations =
false;
2825 iField->getNameForDiagnostic(stream, printPol,
true );
2827 Error(
"InspectMembers",
2828 "Cannot retrieve Type for member %s while inspecting class %s",
2829 memberName.c_str(), clname);
2834 Bool_t ispointer =
false;
2835 if (memNonPtrType->isPointerType()) {
2837 clang::QualType ptrQT
2838 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2843 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT,
fNormalizedCtxt->
GetConfig(),
false );
2844 if (ptrQT.isNull()) {
2845 std::string memberName;
2846 llvm::raw_string_ostream stream(memberName);
2848 printPol.AnonymousTagLocations =
false;
2849 iField->getNameForDiagnostic(stream, printPol,
true );
2851 Error(
"InspectMembers",
2852 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2853 memberName.c_str(), clname);
2856 memNonPtrType = ptrQT.getTypePtr();
2860 llvm::SmallString<8> arraySize;
2861 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2862 unsigned arrLevel = 0;
2863 bool haveErrorDueToArray =
false;
2867 const clang::ConstantArrayType* constArrType =
2868 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2870 constArrType->getSize().toStringUnsigned(arraySize);
2873 clang::QualType subArrQT = arrType->getElementType();
2874 if (subArrQT.isNull()) {
2875 std::string memberName;
2876 llvm::raw_string_ostream stream(memberName);
2878 printPol.AnonymousTagLocations =
false;
2879 iField->getNameForDiagnostic(stream, printPol,
true );
2881 Error(
"InspectMembers",
2882 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2883 arrLevel, subArrQT.getAsString(printPol).c_str(),
2884 memberName.c_str(), clname);
2885 haveErrorDueToArray =
true;
2888 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2890 if (haveErrorDueToArray) {
2895 std::string fieldName;
2896 if (memType->isPointerType()) {
2901 std::string
ioname(iField->getName());
2904 fieldName += arraySize;
2909 clang::CharUnits
offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2910 ptrdiff_t fieldOffset =
offset.getQuantity();
2920 auto iFiledQtype = iField->getType();
2921 if (
auto tagDecl = iFiledQtype->getAsTagDecl()){
2922 auto declAccess = tagDecl->getAccess();
2923 if (declAccess == AS_private || declAccess == AS_protected) {
2929 insp.
Inspect(
const_cast<TClass*
>(cl), insp.
GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2932 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2933 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
2936 std::string sFieldRecName;
2939 clang::QualType(memNonPtrType,0),
2949 insp.
InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
2958 unsigned iNBase = 0;
2959 for (clang::CXXRecordDecl::base_class_const_iterator iBase
2960 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
2961 iBase != eBase; ++iBase, ++iNBase) {
2962 clang::QualType baseQT = iBase->getType();
2963 if (baseQT.isNull()) {
2964 Error(
"InspectMembers",
2965 "Cannot find QualType for base number %d while inspecting class %s",
2969 const clang::CXXRecordDecl* baseDecl
2970 = baseQT->getAsCXXRecordDecl();
2972 Error(
"InspectMembers",
2973 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
2978 std::string sBaseName;
2980 std::vector<TClass*> foundClasses;
2982 if (foundClasses.size()==1){
2983 baseCl=foundClasses[0];
2996 std::string qualNameForDiag;
2998 Error(
"InspectMembers",
2999 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
3004 if (iBase->isVirtual()) {
3007 Error(
"InspectMembers",
3008 "Base %s of class %s is virtual but no object provided",
3009 sBaseName.c_str(), clname);
3017 baseOffset = ci->
GetBaseOffset(baseCi,
const_cast<void*
>(obj),
3019 if (baseOffset == -1) {
3020 Error(
"InspectMembers",
3021 "Error calculating offset of virtual base %s of class %s",
3022 sBaseName.c_str(), clname);
3025 Error(
"InspectMembers",
3026 "Cannot calculate offset of virtual base %s of class %s",
3027 sBaseName.c_str(), clname);
3032 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3079 bool oldDynLookup =
fInterpreter->isDynamicLookupEnabled();
3108 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.
Data());
3123 llvm::StringRef ModuleName(libname);
3124 ModuleName = llvm::sys::path::stem(ModuleName);
3125 ModuleName.consume_front(
"lib");
3133 clang::ModuleMap &moduleMap =
fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3134 clang::Module *M = moduleMap.findModule(ModuleName);
3135 return M && !M->IsMissingRequirement && M->getASTFile();
3154 size_t at = std::string::npos;
3155 while ((at = file_name.find(
"/./")) != std::string::npos)
3156 file_name.replace(at, 3,
"/");
3158 std::string filesStr =
"";
3159 llvm::raw_string_ostream filesOS(filesStr);
3160 clang::SourceManager &SM =
fInterpreter->getCI()->getSourceManager();
3161 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3164 llvm::SmallVector<llvm::StringRef, 100> files;
3165 llvm::StringRef(filesStr).split(files,
"\n");
3167 std::set<std::string> fileMap;
3169 for (llvm::SmallVector<llvm::StringRef, 100>::const_iterator
3170 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3171 if ((*iF) == file_name.c_str())
return kTRUE;
3172 fileMap.insert(*iF);
3175 if (fileMap.empty())
return kFALSE;
3178 TString sFilename(file_name.c_str());
3180 && fileMap.count(sFilename.
Data())) {
3188 while (incPath.
Index(
" :") != -1) {
3192 sFilename = file_name.c_str();
3194 && fileMap.count(sFilename.
Data())) {
3203 const clang::DirectoryLookup *CurDir = 0;
3204 clang::Preprocessor &PP =
fInterpreter->getCI()->getPreprocessor();
3205 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3206 const clang::FileEntry *FE = HS.LookupFile(file_name.c_str(),
3207 clang::SourceLocation(),
3210 clang::ArrayRef<std::pair<
const clang::FileEntry *,
3211 const clang::DirectoryEntry *>>(),
3222 if (FE && FE->isValid()) {
3224 clang::SourceManager &SM =
fInterpreter->getCI()->getSourceManager();
3226 clang::FileID FID = SM.translateFile(FE);
3227 if (!FID.isInvalid() && FID.getHashValue() == 0)
3230 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3231 if (SLocE.isFile() && SLocE.getFile().getContentCache()->getRawBuffer() == 0)
3233 if (!FID.isInvalid())
3237 sFilename = FE->getName();
3239 && fileMap.count(sFilename.
Data())) {
3247#if defined(R__MACOSX)
3255static bool R__UpdateLibFileForLinking(
TString &lib)
3257 const char *mapfile =
nullptr;
3259 mapfile =
"/System/Library/dyld/dyld_shared_cache_x86_64.map";
3261 mapfile =
"/System/Library/dyld/dyld_shared_cache_arm64e.map";
3263 #error unsupported architecture
3265 if (std::ifstream cacheMap{mapfile}) {
3267 while (getline(cacheMap,
line)) {
3268 if (
line.find(lib) != std::string::npos) {
3286static int callback_for_dl_iterate_phdr(
struct dl_phdr_info *info,
size_t size,
void *
data)
3289 static std::unordered_set<
decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3291 auto newLibs =
static_cast<std::vector<std::string>*
>(
data);
3292 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3294 if (info->dlpi_name && info->dlpi_name[0]
3295 && strncmp(info->dlpi_name,
"linux-vdso.so", 13)
3296 && strncmp(info->dlpi_name,
"linux-vdso32.so", 15)
3297 && strncmp(info->dlpi_name,
"linux-vdso64.so", 15)
3298 && strncmp(info->dlpi_name,
"linux-gate.so", 13))
3299 newLibs->emplace_back(info->dlpi_name);
3300 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3313#if defined(R__WIN32) || defined(__CYGWIN__)
3314 HMODULE hModules[1024];
3316 unsigned long cbModules;
3318 hProcess = (
void *)::GetCurrentProcess();
3319 ::EnumProcessModules(hProcess, hModules,
sizeof(hModules), &cbModules);
3321 for (i = 1; i < (cbModules /
sizeof(
void *)); i++) {
3322 static const int bufsize = 260;
3323 wchar_t winname[bufsize];
3324 char posixname[bufsize];
3325 ::GetModuleFileNameExW(hProcess, hModules[i], winname, bufsize);
3326#if defined(__CYGWIN__)
3327 cygwin_conv_path(CCP_WIN_W_TO_POSIX, winname, posixname, bufsize);
3329 std::wstring wpath = winname;
3330 std::replace(wpath.begin(), wpath.end(),
'\\',
'/');
3331 string path(wpath.begin(), wpath.end());
3332 strncpy(posixname, path.c_str(), bufsize);
3338#elif defined(R__MACOSX)
3342 while (
const mach_header* mh = _dyld_get_image_header(imageIndex)) {
3344 if (mh->filetype == MH_DYLIB) {
3345 if (
const char* imageName = _dyld_get_image_name(imageIndex)) {
3353#elif defined(R__LINUX)
3357 std::vector<std::string> newLibs;
3358 dl_iterate_phdr(callback_for_dl_iterate_phdr, &newLibs);
3359 for (
auto &&lib: newLibs)
3362 Error(
"TCling::UpdateListOfLoadedSharedLibraries",
3363 "Platform not supported!");
3378 cling::DynamicLibraryManager* DLM =
fInterpreter->getDynamicLibraryManager();
3379 if (!DLM->isLibraryLoaded(
filename)) {
3380 DLM->loadLibrary(
filename,
true ,
true );
3383#if defined(R__MACOSX)
3385 auto lenFilename = strlen(
filename);
3386 if (!strncmp(
filename,
"/usr/lib/system/", 16)
3387 || !strncmp(
filename,
"/usr/lib/libc++", 15)
3388 || !strncmp(
filename,
"/System/Library/Frameworks/", 27)
3389 || !strncmp(
filename,
"/System/Library/PrivateFrameworks/", 34)
3390 || !strncmp(
filename,
"/System/Library/CoreServices/", 29)
3392 || strstr(
filename,
"/usr/lib/libSystem")
3393 || strstr(
filename,
"/usr/lib/libstdc++")
3394 || strstr(
filename,
"/usr/lib/libicucore")
3395 || strstr(
filename,
"/usr/lib/libbsm")
3396 || strstr(
filename,
"/usr/lib/libobjc")
3397 || strstr(
filename,
"/usr/lib/libresolv")
3398 || strstr(
filename,
"/usr/lib/libauto")
3399 || strstr(
filename,
"/usr/lib/libcups")
3400 || strstr(
filename,
"/usr/lib/libDiagnosticMessagesClient")
3401 || strstr(
filename,
"/usr/lib/liblangid")
3402 || strstr(
filename,
"/usr/lib/libCRFSuite")
3403 || strstr(
filename,
"/usr/lib/libpam")
3404 || strstr(
filename,
"/usr/lib/libOpenScriptingUtil")
3405 || strstr(
filename,
"/usr/lib/libextension")
3406 || strstr(
filename,
"/usr/lib/libAudioToolboxUtility")
3407 || strstr(
filename,
"/usr/lib/liboah")
3408 || strstr(
filename,
"/usr/lib/libRosetta")
3409 || strstr(
filename,
"/usr/lib/libCoreEntitlements")
3410 || strstr(
filename,
"/usr/lib/libssl.")
3411 || strstr(
filename,
"/usr/lib/libcrypto.")
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();
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();
3592 return valRef.simplisticCastAs<
Longptr_t>();
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 = 0;
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();
3798 if (
type->isPointerType()) {
3799 int** ppInt = (
int**)
fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3801 if (ppInt) *ppInt = 0;
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;
4003 if (strncmp(cl->
GetName(),
"tuple<",strlen(
"tuple<"))==0) {
4039 zombieCandidate =
kTRUE;
4046 zombieCandidate =
kTRUE;
4100 static const char *anonEnum =
"anonymous enum ";
4101 static const int cmplen = strlen(anonEnum);
4128 const char *classname =
name;
4131 class MaybeSuspendAutoLoadParse {
4132 int fStoreAutoLoad = 0;
4133 int fStoreAutoParse = 0;
4134 bool fSuspendedAutoParse =
false;
4136 MaybeSuspendAutoLoadParse(
int autoload) {
4137 fStoreAutoLoad = ((
TCling*)
gCling)->SetClassAutoLoading(autoload);
4141 fSuspendedAutoParse =
true;
4142 fStoreAutoParse = ((
TCling*)
gCling)->SetSuspendAutoParsing(
true);
4145 ~MaybeSuspendAutoLoadParse() {
4146 if (fSuspendedAutoParse)
4147 ((
TCling*)
gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4148 ((
TCling*)
gCling)->SetClassAutoLoading(fStoreAutoLoad);
4152 MaybeSuspendAutoLoadParse autoLoadParseRAII( autoload );
4154 autoLoadParseRAII.SuspendAutoParsing();
4163 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
4165 const clang::Decl *decl
4166 = lh.findScope(classname,
4167 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4168 : cling::LookupHelper::NoDiagnostics,
4172 decl = lh.findScope(buf,
4173 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4174 : cling::LookupHelper::NoDiagnostics,
4191 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4192 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4193 (
type->getAsCXXRecordDecl());
4194 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4211 if (tci.
Property() & propertiesMask) {
4212 bool hasClassDefInline =
false;
4213 if (isClassOrNamespaceOnly) {
4219 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4221 bool success =
false;
4222 std::tie(success, lineNumber) =
4224 hasClassDefInline = success && (lineNumber == -1);
4232 if (hasClassDefInline)
4271 const cling::LookupHelper& lh =
fInterpreter->getLookupHelper();
4272 const clang::Decl *decl
4273 = lh.findClassTemplate(
name,
4274 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4275 : cling::LookupHelper::NoDiagnostics);
4277 std::string strname =
"std::";
4279 decl = lh.findClassTemplate(strname,
4280 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4281 : cling::LookupHelper::NoDiagnostics);
4307 cl->
fBase = listOfBase;
4323 D =
fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4326 if (
const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4329 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4330 const_cast< clang::DeclContext *
>(DC)->collectAllContexts(allDeclContexts);
4331 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(), declEnd = allDeclContexts.end();
4332 declIter != declEnd; ++declIter) {
4334 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4335 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4336 if (
const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4339 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4340 llvm::raw_string_ostream stream(buf);
4342 Policy.AnonymousTagLocations =
false;
4343 ED->getNameForDiagnostic(stream, Policy,
false);
4347 const char*
name = buf.c_str();
4371 D =
fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4375 if (
const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4378 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4379 const_cast< clang::DeclContext *
>(DC)->collectAllContexts(allDeclContexts);
4380 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(),
4381 declEnd = allDeclContexts.end(); declIter != declEnd; ++declIter) {
4383 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4384 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4385 if (
const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4386 funcTempList->
Get(FTD);
4444 if (
m->fMethodArgs) {
4455 m->fMethodArgs = arglist;
4502 if (llvm::isa<clang::NamespaceDecl>(cli->
GetDecl())) {
4511 Error(
"GenerateTClass",
4512 "Cannot find %s::Class_Version()! Class version might be wrong.",
4519 if (newvers == -1) {
4527 newvers = callfunc.
ExecInt(0);
4529 Error(
"GenerateTClass",
4530 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4534 if (newvers != oldvers) {
4551static void GenerateTClass_GatherInnerIncludes(cling::Interpreter *interp,
TString &includes,
TClingClassInfo *info)
4555 const clang::ClassTemplateSpecializationDecl *templateCl
4556 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->
GetDecl());
4558 for(
unsigned int i=0; i < templateCl->getTemplateArgs().
size(); ++i) {
4559 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4563 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4565 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4568 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4569 GenerateTClass_GatherInnerIncludes(interp, includes, &subinfo);
4572 llvm::raw_string_ostream OS(Result);
4573 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4574 Warning(
"TCling::GenerateTClass",
"Missing header file for %s",OS.str().c_str());
4589 if (!info || !info->
IsValid()) {
4590 Fatal(
"GenerateTClass",
"Requires a valid ClassInfo object");
4595 std::string classname;
4599 Info(
"GenerateTClass",
"Will (try to) generate the compiled TClass for %s.",classname.c_str());
4603 GenerateTClass_GatherInnerIncludes(
fInterpreter,includes,info);
4609 Error(
"GenerateTClass",
"Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4615 cl =
new TClass(classinfo, version, 0, 0, -1, -1, silent);
4621 cl =
new TClass(classinfo, 1, 0, 0, -1, -1, silent);
4646 if (classes == 0 || classes[0] == 0) {
4647 Error(
"TCling::GenerateDictionary",
"Cannot generate dictionary without passing classes.");
4651 std::vector<std::string> listClasses;
4653 const char* current = classes, *prev = classes;
4657 if (*current ==
';') {
4658 listClasses.push_back(std::string(prev, current - prev));
4661 else if (*(current + 1) == 0) {
4662 listClasses.push_back(std::string(prev, current + 1 - prev));
4666 std::vector<std::string> listIncludes;
4670 const char* current = includes, *prev = includes;
4674 if (*current ==
';') {
4675 listIncludes.push_back(std::string(prev, current - prev));
4678 else if (*(current + 1) == 0) {
4679 listIncludes.push_back(std::string(prev, current + 1 - prev));
4685 std::vector<std::string>(), std::vector<std::string>());
4706 if (
const ValueDecl* decl = (
const ValueDecl*)
d){
4709 if (hasIoName && ioName !=
name)
return 0;
4721 using namespace clang;
4723 DeclarationName DName = &SemaR.Context.Idents.get(
name);
4725 LookupResult
R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4726 Sema::ForExternalRedeclaration);
4730 cling::utils::Lookup::Named(&SemaR,
R);
4734 while (
F.hasNext()) {
4735 NamedDecl *D =
F.next();
4736 if (isa<VarDecl>(D) || isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
4737 isa<IndirectFieldDecl>(D))
4743 if (
R.isSingleResult())
4744 return R.getFoundDecl();
4756 const clang::Decl* possibleEnum = 0;
4761 const clang::DeclContext* dc = 0;
4762 if (
const clang::Decl* D = cci->
GetDecl()) {
4763 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4764 dc = dyn_cast<clang::RecordDecl>(D);
4771 possibleEnum = cling::utils::Lookup::Tag(&
fInterpreter->getSema(),
name, dc);
4773 Error(
"TCling::GetEnum",
"DeclContext not found for %s .\n",
name);
4782 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4783 && isa<clang::EnumDecl>(possibleEnum)) {
4784 return possibleEnum;
4796 llvm::StringRef mangled_name = gv->getName();
4811 std::string scopename(demangled_name_c);
4812 free(demangled_name_c);
4818 std::string dataname;
4820 if (!strncmp(scopename.c_str(),
"typeinfo for ",
sizeof(
"typeinfo for ")-1)) {
4821 scopename.erase(0,
sizeof(
"typeinfo for ")-1);
4822 }
else if (!strncmp(scopename.c_str(),
"vtable for ",
sizeof(
"vtable for ")-1)) {
4823 scopename.erase(0,
sizeof(
"vtable for ")-1);
4826 std::string::size_type pos = scopename.rfind(
'(');
4827 if (pos != std::string::npos) {
4831 pos = scopename.rfind(
':');
4832 if (pos != std::string::npos) {
4833 if ((pos != 0) && (scopename[pos-1] ==
':')) {
4834 dataname = scopename.substr(pos+1);
4835 scopename.erase(pos-1);
4839 dataname = scopename;
4847 if (scopename.size()) {
4863 Error(
"GetDataMemberWithValue()",
"not implemented");
4873 Error(
"GetDataMemberAtAddr()",
"not implemented");
4883 const char* params,
Bool_t objectIsConst )
4901 return mangled_name;
4928 const char* params,
Bool_t objectIsConst )
4969 std::vector<DeclId_t>& res)
const
4972 clang::ASTContext& Ctx =
S.Context;
4973 const clang::Decl* CtxDecl
4975 Ctx.getTranslationUnitDecl();
4976 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
4977 const clang::DeclContext* DeclCtx = RecDecl;
4980 DeclCtx = dyn_cast<clang::NamespaceDecl>(CtxDecl);
4981 if (!DeclCtx)
return;
4983 clang::DeclarationName DName;
4988 if (RecDecl->getNameAsString() == funcname) {
4989 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
4990 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
4991 }
else if (funcname[0] ==
'~' && RecDecl->getNameAsString() == funcname + 1) {
4992 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
4993 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
4995 DName = &Ctx.Idents.get(funcname);
4998 DName = &Ctx.Idents.get(funcname);
5002 clang::LookupResult
R(
S, DName, clang::SourceLocation(),
5003 Sema::LookupOrdinaryName, clang::Sema::NotForRedeclaration);
5004 R.suppressDiagnostics();
5005 S.LookupQualifiedName(
R,
const_cast<DeclContext*
>(DeclCtx));
5006 if (
R.empty())
return;
5008 res.reserve(res.size() + (
R.end() -
R.begin()));
5009 for (clang::LookupResult::iterator IR =
R.begin(), ER =
R.end();
5011 if (
const clang::FunctionDecl* FD
5012 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5013 if (!FD->getDescribedFunctionTemplate()) {
5016 }
else if (
const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5018 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5178 const char* params,
Bool_t objectIsConst,
int* error)
5198 const char* params,
int* error)
5200 Execute(obj,cl,method,params,
false,error);
5215 Error(
"Execute",
"No method was defined");
5224 if (argc > nparms) {
5225 Error(
"Execute",
"Too many parameters to call %s, got %d but expected at most %d.",method->
GetName(),argc,nparms);
5228 if (nparms != argc) {
5238 Int_t firstDefault = -1;
5239 for (
Int_t i = 0; i < nparms; i ++) {
5246 if (firstDefault >= 0) {
5247 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);
5249 Error(
"Execute",
"Too few arguments to call %s, got only %d but expected %d.",method->
GetName(),argc,nparms);
5255 const char* listpar =
"";
5260 for (
Int_t i = 0; i < argc; i ++) {
5276 complete += nxtpar->
String();
5279 listpar = complete.
Data();
5306 const void* args[] ,
5311 Error(
"ExecuteWithArgsAndReturn",
"No method was defined");
5338 Warning(
"GetTopLevelMacroName",
"Must change return type!");
5385#if defined(R__MUST_REVISIT)
5386#if R__MUST_REVISIT(6,0)
5387 Warning(
"GetCurrentMacroName",
"Must change return type!");
5400 TTHREAD_TLS_DECL(std::string,t);
5402 if (!strstr(typeDesc,
"(*)(")) {
5403 const char *
s = strchr(typeDesc,
' ');
5404 const char *template_start = strchr(typeDesc,
'<');
5405 if (!strcmp(typeDesc,
"long long")) {
5408 else if (!strncmp(typeDesc,
"unsigned ",
s + 1 - typeDesc)) {
5415 else if (
s && (template_start == 0 || (
s < template_start))) {
5425 auto l = t.length();
5426 while (
l > 0 && (t[
l - 1] ==
'*' || t[
l - 1] ==
'&'))
5434 assert(rootmapfile && *rootmapfile);
5437 libName.consume_back(
".rootmap");
5439 return !
gInterpreter->HasPCMForLibrary(libName.str().c_str());
5450 if (!(rootmapfile && *rootmapfile))