Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TCling.cxx
Go to the documentation of this file.
1// @(#)root/meta:$Id$
2// vim: sw=3 ts=3 expandtab foldmethod=indent
3
4/*************************************************************************
5 * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12/** \class TCling
13
14This class defines an interface to the cling C++ interpreter.
15
16Cling is a full ANSI compliant C++-11 interpreter based on
17clang/LLVM technology.
18*/
19
20#include "TCling.h"
21
23
24#include "TClingBaseClassInfo.h"
25#include "TClingCallFunc.h"
26#include "TClingClassInfo.h"
28#include "TClingMethodArgInfo.h"
29#include "TClingMethodInfo.h"
31#include "TClingTypedefInfo.h"
32#include "TClingTypeInfo.h"
33#include "TClingValue.h"
34
35#include "TROOT.h"
36#include "TApplication.h"
37#include "TGlobal.h"
38#include "TDataType.h"
39#include "TClass.h"
40#include "TClassEdit.h"
41#include "TClassTable.h"
42#include "TClingCallbacks.h"
43#include "TClingDiagnostics.h"
44#include "TBaseClass.h"
45#include "TDataMember.h"
46#include "TMemberInspector.h"
47#include "TMethod.h"
48#include "TMethodArg.h"
49#include "TFunctionTemplate.h"
50#include "TObjArray.h"
51#include "TObjString.h"
52#include "TString.h"
53#include "THashList.h"
54#include "TVirtualPad.h"
55#include "TSystem.h"
56#include "TVirtualMutex.h"
57#include "TError.h"
58#include "TEnv.h"
59#include "TEnum.h"
60#include "TEnumConstant.h"
61#include "THashTable.h"
63#include "RConfigure.h"
64#include "compiledata.h"
65#include "strlcpy.h"
66#include "snprintf.h"
67#include "TClingUtils.h"
70#include "TListOfDataMembers.h"
71#include "TListOfEnums.h"
73#include "TListOfFunctions.h"
75#include "TMemFile.h"
76#include "TProtoClass.h"
77#include "TStreamerInfo.h" // This is here to avoid to use the plugin manager
78#include "ThreadLocalStorage.h"
79#include "TFile.h"
80#include "TKey.h"
81#include "ClingRAII.h"
82
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"
105
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"
117
118#include <CppInterOp/CppInterOp.h>
119
120#include "llvm/IR/GlobalValue.h"
121#include "llvm/IR/Module.h"
122
123#include "llvm/Support/DynamicLibrary.h"
124#include "llvm/Support/raw_ostream.h"
125#include "llvm/Support/Path.h"
126#include "llvm/Support/Process.h"
127#include "llvm/Object/ELFObjectFile.h"
128#include "llvm/Object/ObjectFile.h"
129#include "llvm/Object/SymbolicFile.h"
130#include "llvm/Support/FileSystem.h"
131
132#include <algorithm>
133#include <iostream>
134#include <cassert>
135#include <map>
136#include <set>
137#include <stdexcept>
138#include <cstdint>
139#include <fstream>
140#include <sstream>
141#include <string>
142#include <tuple>
143#include <typeinfo>
144#include <unordered_map>
145#include <unordered_set>
146#include <utility>
147#include <vector>
148#include <functional>
149#include <optional>
150
151#ifndef R__WIN32
152#include <cxxabi.h>
153#define R__DLLEXPORT __attribute__ ((visibility ("default")))
154#include <sys/stat.h>
155#endif
156#include <climits>
157#include <cstdio>
158
159#ifdef __APPLE__
160#include <dlfcn.h>
161#include <mach-o/dyld.h>
162#include <mach-o/loader.h>
163#endif // __APPLE__
164
165#ifdef R__UNIX
166#include <dlfcn.h>
167#endif
168
169#if defined(R__LINUX) || defined(R__FBSD)
170# ifndef _GNU_SOURCE
171# define _GNU_SOURCE
172# endif
173# include <link.h> // dl_iterate_phdr()
174#endif
175
176#if defined(__CYGWIN__)
177#include <sys/cygwin.h>
178#define HMODULE void *
179extern "C" {
181 __declspec(dllimport) bool __stdcall EnumProcessModules(void *, void **, unsigned long, unsigned long *);
182 __declspec(dllimport) unsigned long __stdcall GetModuleFileNameExW(void *, void *, wchar_t *, unsigned long);
183}
184#endif
185
186// Fragment copied from LLVM's raw_ostream.cpp
187#if defined(_MSC_VER)
188#ifndef STDIN_FILENO
189# define STDIN_FILENO 0
190#endif
191#ifndef STDOUT_FILENO
192# define STDOUT_FILENO 1
193#endif
194#ifndef STDERR_FILENO
195# define STDERR_FILENO 2
196#endif
197#ifndef R__WIN32
198//#if defined(HAVE_UNISTD_H)
199# include <unistd.h>
200//#endif
201#else
202#include "Windows4Root.h"
203#include <Psapi.h>
204#include <direct.h>
205#undef GetModuleFileName
206#define RTLD_DEFAULT ((void *)::GetModuleHandle(NULL))
207#define dlsym(library, function_name) ::GetProcAddress((HMODULE)library, function_name)
208#define dlopen(library_name, flags) ::LoadLibraryA(library_name)
209#define dlclose(library) ::FreeLibrary((HMODULE)library)
210#define R__DLLEXPORT __declspec(dllexport)
211#endif
212#endif
213
214//______________________________________________________________________________
215// These functions are helpers for debugging issues with non-LLVMDEV builds.
216//
217R__DLLEXPORT clang::DeclContext* TCling__DEBUG__getDeclContext(clang::Decl* D) {
218 return D->getDeclContext();
219}
220R__DLLEXPORT clang::NamespaceDecl* TCling__DEBUG__DCtoNamespace(clang::DeclContext* DC) {
221 return llvm::dyn_cast<clang::NamespaceDecl>(DC);
222}
223R__DLLEXPORT clang::RecordDecl* TCling__DEBUG__DCtoRecordDecl(clang::DeclContext* DC) {
224 return llvm::dyn_cast<clang::RecordDecl>(DC);
225}
226R__DLLEXPORT void TCling__DEBUG__dump(clang::DeclContext* DC) {
227 return DC->dumpDeclContext();
228}
229R__DLLEXPORT void TCling__DEBUG__dump(clang::Decl* D) {
230 return D->dump();
231}
232R__DLLEXPORT void TCling__DEBUG__dump(clang::FunctionDecl* FD) {
233 return FD->dump();
234}
236 return ((clang::Decl*)D)->dump();
237}
239 if (clang::NamedDecl* ND = llvm::dyn_cast<clang::NamedDecl>(D)) {
240 std::string name;
241 {
242 llvm::raw_string_ostream OS(name);
243 ND->getNameForDiagnostic(OS, D->getASTContext().getPrintingPolicy(),
244 true /*Qualified*/);
245 }
246 printf("%s\n", name.c_str());
247 }
248}
249//______________________________________________________________________________
250// These functions are helpers for testing issues directly rather than
251// relying on side effects.
252// This is used for the test for ROOT-7462/ROOT-6070
254 return D->isInvalidDecl();
255}
258 assert(info && info->IsValid());
259 return info->GetDecl()->isInvalidDecl();
260}
261
262using std::string, std::vector;
263using namespace clang;
264using namespace ROOT;
265
266namespace {
267 static const std::string gInterpreterClassDef = R"ICF(
268#undef ClassDef
269#define ClassDef(name, id) \
270_ClassDefInterp_(name,id,virtual,) \
271static int DeclFileLine() { return __LINE__; }
272#undef ClassDefNV
273#define ClassDefNV(name, id) \
274_ClassDefInterp_(name,id,,) \
275static int DeclFileLine() { return __LINE__; }
276#undef ClassDefOverride
277#define ClassDefOverride(name, id) \
278_ClassDefInterp_(name,id,,override) \
279static int DeclFileLine() { return __LINE__; }
280)ICF";
281
282 static const std::string gNonInterpreterClassDef = R"ICF(
283#define __ROOTCLING__ 1
284#undef ClassDef
285#define ClassDef(name,id) \
286_ClassDefOutline_(name,id,virtual,) \
287static int DeclFileLine() { return __LINE__; }
288#undef ClassDefNV
289#define ClassDefNV(name, id)\
290_ClassDefOutline_(name,id,,)\
291static int DeclFileLine() { return __LINE__; }
292#undef ClassDefOverride
293#define ClassDefOverride(name, id)\
294_ClassDefOutline_(name,id,,override)\
295static int DeclFileLine() { return __LINE__; }
296)ICF";
297
298// The macros below use ::Error, so let's ensure it is included
299 static const std::string gClassDefInterpMacro = R"ICF(
300#include "TError.h"
301
302#define _ClassDefInterp_(name,id,virtual_keyword, overrd) \
303private: \
304public: \
305 static TClass *Class() { static TClass* sIsA = 0; if (!sIsA) sIsA = TClass::GetClass(#name); return sIsA; } \
306 static const char *Class_Name() { return #name; } \
307 virtual_keyword Bool_t CheckTObjectHashConsistency() const overrd { \
308 static std::atomic<UChar_t> recurseBlocker(0); \
309 if (R__likely(recurseBlocker >= 2)) { \
310 return ::ROOT::Internal::THashConsistencyHolder<decltype(*this)>::fgHashConsistency; \
311 } else if (recurseBlocker == 1) { \
312 return false; \
313 } else if (recurseBlocker++ == 0) { \
314 ::ROOT::Internal::THashConsistencyHolder<decltype(*this)>::fgHashConsistency = \
315 ::ROOT::Internal::HasConsistentHashMember(_QUOTE_(name)) || \
316 ::ROOT::Internal::HasConsistentHashMember(*IsA()); \
317 ++recurseBlocker; \
318 return ::ROOT::Internal::THashConsistencyHolder<decltype(*this)>::fgHashConsistency; \
319 } \
320 return false; /* unreachable */ \
321 } \
322 static Version_t Class_Version() { return id; } \
323 static TClass *Dictionary() { return 0; } \
324 virtual_keyword TClass *IsA() const overrd { return name::Class(); } \
325 virtual_keyword void ShowMembers(TMemberInspector&insp) const overrd { ::ROOT::Class_ShowMembers(name::Class(), this, insp); } \
326 virtual_keyword void Streamer(TBuffer&) overrd { ::Error("Streamer", "Cannot stream interpreted class."); } \
327 void StreamerNVirtual(TBuffer&ClassDef_StreamerNVirtual_b) { name::Streamer(ClassDef_StreamerNVirtual_b); } \
328 static const char *DeclFileName() { return __FILE__; } \
329 static int ImplFileLine() { return 0; } \
330 static const char *ImplFileName() { return __FILE__; }
331)ICF";
332}
334
335// The functions are used to bridge cling/clang/llvm compiled with no-rtti and
336// ROOT (which uses rtti)
337
338////////////////////////////////////////////////////////////////////////////////
339/// Print a StackTrace!
340
341extern "C"
345
346////////////////////////////////////////////////////////////////////////////////
347/// Load a library.
348
349extern "C" int TCling__LoadLibrary(const char *library)
350{
352 return gSystem->Load(library, "", false);
353}
354
355////////////////////////////////////////////////////////////////////////////////
356/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
357
358extern "C" void TCling__RestoreInterpreterMutex(void *delta)
359{
360 ((TCling*)gCling)->ApplyToInterpreterMutex(delta);
361}
362
363////////////////////////////////////////////////////////////////////////////////
364/// Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name,
365/// which is extracted by error messages we get from callback from cling. Return true
366/// when the missing library was autoloaded.
367
368extern "C" bool TCling__LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
369{
370 return ((TCling*)gCling)->LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
371}
372
373////////////////////////////////////////////////////////////////////////////////
374/// Reset the interpreter lock to the state it had before interpreter-related
375/// calls happened.
376
378{
379 return ((TCling*)gCling)->RewindInterpreterMutex();
380}
381
382////////////////////////////////////////////////////////////////////////////////
383/// Lock the interpreter.
384
386{
387 if (gInterpreterMutex) {
389 }
390 return nullptr;
391}
392
393////////////////////////////////////////////////////////////////////////////////
394/// Unlock the interpreter.
395
397{
398 if (gInterpreterMutex) {
400 }
401}
402
403////////////////////////////////////////////////////////////////////////////////
404/// Update TClingClassInfo for a class (e.g. upon seeing a definition).
405
407{
408 static Bool_t entered = kFALSE;
411
412 if (entered) topLevel = kFALSE;
413 else {
414 entered = kTRUE;
415 topLevel = kTRUE;
416 }
417 if (topLevel) {
418 ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(TD);
419 } else {
420 // If we are called indirectly from within another call to
421 // TCling::UpdateClassInfo, we delay the update until the dictionary loading
422 // is finished (i.e. when we return to the top level TCling::UpdateClassInfo).
423 // This allows for the dictionary to be fully populated when we actually
424 // update the TClass object. The updating of the TClass sometimes
425 // (STL containers and when there is an emulated class) forces the building
426 // of the TClass object's real data (which needs the dictionary info).
427 updateList.push_back(TD);
428 }
429 if (topLevel) {
430 while (!updateList.empty()) {
431 ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(updateList.back());
432 updateList.pop_back();
433 }
434 entered = kFALSE;
435 }
436}
437
439 const clang::Decl* D = static_cast<const clang::Decl*>(enumObj->GetDeclId());
440 if(const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
441 // Add the constants to the enum type.
442 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
443 EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
444 // Get name of the enum type.
445 std::string constbuf;
446 if (const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
447 PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
448 llvm::raw_string_ostream stream(constbuf);
449 // Don't trigger fopen of the source file to count lines:
450 Policy.AnonymousTagLocations = false;
451 (END)->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
452 }
453 const char* constantName = constbuf.c_str();
454
455 // Get value of the constant.
457 const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
458 if (valAPSInt.isSigned()) {
459 value = valAPSInt.getSExtValue();
460 } else {
461 value = valAPSInt.getZExtValue();
462 }
463
464 // Create the TEnumConstant or update it if existing
465 TEnumConstant* enumConstant = nullptr;
466 TClingClassInfo* tcCInfo = (TClingClassInfo*)(cl ? cl->GetClassInfo() : nullptr);
469 if (TObject* encAsTObj = enumObj->GetConstants()->FindObject(constantName)){
470 ((TEnumConstant*)encAsTObj)->Update(dmInfo);
471 } else {
473 }
474
475 // Add the global constants to the list of Globals.
476 if (!cl) {
477 TCollection* globals = gROOT->GetListOfGlobals(false);
478 if (!globals->FindObject(constantName)) {
479 globals->Add(enumConstant);
480 }
481 }
482 }
483 }
484}
485
487{
488 // Handle new enum declaration for either global and nested enums.
489
490 // Create the enum type.
491 TEnum* enumType = nullptr;
492 const clang::Decl* D = static_cast<const clang::Decl*>(VD);
493 std::string buf;
494 if (const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
495 // Get name of the enum type.
496 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
497 llvm::raw_string_ostream stream(buf);
498 // Don't trigger fopen of the source file to count lines:
499 Policy.AnonymousTagLocations = false;
500 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
501 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
502 }
503 if (buf.empty()) {
504 return nullptr;
505 }
506 const char* name = buf.c_str();
507 enumType = new TEnum(name, VD, cl);
509
510 return enumType;
511}
512
513void TCling::HandleNewDecl(const void* DV, bool isDeserialized, std::set<TClass*> &modifiedTClasses) {
514 // Handle new declaration.
515 // Record the modified class, struct and namespaces in 'modifiedTClasses'.
516
517 const clang::Decl* D = static_cast<const clang::Decl*>(DV);
518
519 if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
520 && !dyn_cast<clang::RecordDecl>(D)) return;
521
522 if (isa<clang::FunctionDecl>(D->getDeclContext())
523 || isa<clang::TagDecl>(D->getDeclContext()))
524 return;
525
526 // Don't list templates.
527 if (const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
528 if (RD->getDescribedClassTemplate())
529 return;
530 } else if (const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
531 if (FD->getDescribedFunctionTemplate())
532 return;
533 }
534
535 if (const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
536 if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
538 }
539 else if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
540
541 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
542 // Mostly just for EnumDecl (the other TagDecl are handled
543 // by the 'RecordDecl' if statement.
545 } else if (const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
547 }
548
549 // We care about declarations on the global scope.
550 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
551 return;
552
553 // Enums are lazyly created, thus we don not need to handle them here.
554 if (isa<EnumDecl>(ND))
555 return;
556
557 // ROOT says that global is enum(lazylycreated)/var/field declared on the global
558 // scope.
559 if (!(isa<VarDecl>(ND)))
560 return;
561
562 // Skip if already in the list.
563 if (gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
564 return;
565
566 // Put the global constants and global enums in the corresponding lists.
567 gROOT->GetListOfGlobals()->Add(new TGlobal((DataMemberInfo_t *)
569 cast<ValueDecl>(ND), nullptr)));
570 }
571}
572
573extern "C"
575{
576 // We are sure in this context of the type of the interpreter
577 normCtxt = &( (TCling*) gInterpreter)->GetNormalizedContext();
578}
579
580extern "C"
581void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter*) {
582 ((TCling*)gCling)->UpdateListsOnCommitted(T);
583}
584
585extern "C"
586void TCling__UpdateListsOnUnloaded(const cling::Transaction &T) {
587 ((TCling*)gCling)->UpdateListsOnUnloaded(T);
588}
589
590extern "C"
591void TCling__InvalidateGlobal(const clang::Decl *D) {
592 ((TCling*)gCling)->InvalidateGlobal(D);
593}
594
595extern "C"
596void TCling__TransactionRollback(const cling::Transaction &T) {
597 ((TCling*)gCling)->TransactionRollback(T);
598}
599
600extern "C" void TCling__LibraryLoadedRTTI(const void* dyLibHandle,
601 const char* canonicalName) {
602 ((TCling*)gCling)->LibraryLoaded(dyLibHandle, canonicalName);
603}
604
605extern "C" void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
606{
607 ((TCling *)gCling)->RegisterRdictForLoadPCM(pcmFileNameFullPath, pcmContent);
608}
609
610extern "C" void TCling__LibraryUnloadedRTTI(const void* dyLibHandle,
611 const char* canonicalName) {
612 ((TCling*)gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
613}
614
615
616extern "C"
617TObject* TCling__GetObjectAddress(const char *Name, void *&LookupCtx) {
618 return ((TCling*)gCling)->GetObjectAddress(Name, LookupCtx);
619}
620
621extern "C" const Decl* TCling__GetObjectDecl(TObject *obj) {
622 return ((TClingClassInfo*)obj->IsA()->GetClassInfo())->GetDecl();
623}
624
626 const char* argv[])
627{
628 auto tcling = new TCling("C++", "cling C++ Interpreter", argv, interpLibHandle);
629
630 return tcling;
631}
632
634{
635 delete interp;
636}
637
638// Load library containing specified class. Returns 0 in case of error
639// and 1 in case if success.
640extern "C" int TCling__AutoLoadCallback(const char* className)
641{
642 return ((TCling*)gCling)->AutoLoad(className);
643}
644
645extern "C" int TCling__AutoParseCallback(const char* className)
646{
647 return ((TCling*)gCling)->AutoParse(className);
648}
649
650extern "C" const char* TCling__GetClassSharedLibs(const char* className, bool skipCore)
651{
652 return ((TCling*)gCling)->GetClassSharedLibs(className, skipCore);
654
655// Returns 0 for failure 1 for success
656extern "C" int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* nsDecl)
657{
658 return ((TCling*)gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
659}
660
661extern "C" int TCling__CompileMacro(const char *fileName, const char *options)
662{
663 string file(fileName);
664 string opt(options);
665 return gSystem->CompileMacro(file.c_str(), opt.c_str());
666}
667
668extern "C" void TCling__SplitAclicMode(const char* fileName, string &mode,
669 string &args, string &io, string &fname)
670{
671 string file(fileName);
672 TString f, amode, arguments, aclicio;
673 f = gSystem->SplitAclicMode(file.c_str(), amode, arguments, aclicio);
674 mode = amode.Data(); args = arguments.Data();
675 io = aclicio.Data(); fname = f.Data();
676}
677
678//______________________________________________________________________________
679//
680//
681//
682
683#ifdef R__WIN32
684extern "C" {
685 char *__unDName(char *demangled, const char *mangled, int out_len,
686 void * (* pAlloc )(size_t), void (* pFree )(void *),
687 unsigned short int flags);
688}
689#endif
690
691////////////////////////////////////////////////////////////////////////////////
692/// Find a template decl within N nested namespaces, 0<=N<inf
693/// Assumes 1 and only 1 template present and 1 and only 1 entity contained
694/// by the namespace. Example: `ns1::ns2::..::%nsN::%myTemplate`
695/// Returns nullptr in case of error
696
697static clang::ClassTemplateDecl* FindTemplateInNamespace(clang::Decl* decl)
698{
699 using namespace clang;
700 if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
701 return FindTemplateInNamespace(*nsd->decls_begin());
702 }
703
704 if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
705 return ctd;
706 }
707
708 return nullptr; // something went wrong.
709}
710
711//______________________________________________________________________________
712//
713//
714//
715
716int TCling_GenerateDictionary(const std::vector<std::string> &classes,
717 const std::vector<std::string> &headers,
718 const std::vector<std::string> &fwdDecls,
719 const std::vector<std::string> &unknown)
720{
721 //This function automatically creates the "LinkDef.h" file for templated
722 //classes then executes CompileMacro on it.
723 //The name of the file depends on the class name, and it's not generated again
724 //if the file exist.
725 if (classes.empty()) {
726 return 0;
727 }
728 // Use the name of the first class as the main name.
729 const std::string& className = classes[0];
730 //(0) prepare file name
731 TString fileName = "AutoDict_";
732 std::string::const_iterator sIt;
733 for (sIt = className.begin(); sIt != className.end(); ++sIt) {
734 if (*sIt == '<' || *sIt == '>' ||
735 *sIt == ' ' || *sIt == '*' ||
736 *sIt == ',' || *sIt == '&' ||
737 *sIt == ':') {
738 fileName += '_';
739 }
740 else {
741 fileName += *sIt;
742 }
743 }
744 if (classes.size() > 1) {
745 Int_t chk = 0;
746 std::vector<std::string>::const_iterator it = classes.begin();
747 while ((++it) != classes.end()) {
748 for (UInt_t cursor = 0; cursor != it->length(); ++cursor) {
749 chk = chk * 3 + it->at(cursor);
750 }
751 }
752 fileName += TString::Format("_%u", chk);
753 }
754 fileName += ".cxx";
755 if (gSystem->AccessPathName(fileName) != 0) {
756 //file does not exist
757 //(1) prepare file data
758 // If STL, also request iterators' operators.
759 // vector is special: we need to check whether
760 // vector::iterator is a typedef to pointer or a
761 // class.
762 static const std::set<std::string> sSTLTypes {
763 "vector","list","forward_list","deque","map","unordered_map","multimap",
764 "unordered_multimap","set","unordered_set","multiset","unordered_multiset",
765 "queue","priority_queue","stack","iterator"};
766 std::vector<std::string>::const_iterator it;
767 std::string fileContent("");
768 for (it = headers.begin(); it != headers.end(); ++it) {
769 fileContent += "#include \"" + *it + "\"\n";
770 }
771 for (it = unknown.begin(); it != unknown.end(); ++it) {
772 TClass* cl = TClass::GetClass(it->c_str());
773 if (cl && cl->GetDeclFileName()) {
774 TString header = gSystem->BaseName(cl->GetDeclFileName());
777 while (dirbase.Length() && dirbase != "."
778 && dirbase != "include" && dirbase != "inc"
779 && dirbase != "prec_stl") {
781 dir = gSystem->GetDirName(dir);
782 }
783 fileContent += TString("#include \"") + header + "\"\n";
784 }
785 }
786 for (it = fwdDecls.begin(); it != fwdDecls.end(); ++it) {
787 fileContent += "class " + *it + ";\n";
788 }
789 fileContent += "#ifdef __CLING__ \n";
790 fileContent += "#pragma link C++ nestedclasses;\n";
791 fileContent += "#pragma link C++ nestedtypedefs;\n";
792 for (it = classes.begin(); it != classes.end(); ++it) {
793 std::string n(*it);
794 size_t posTemplate = n.find('<');
795 std::set<std::string>::const_iterator iSTLType = sSTLTypes.end();
796 if (posTemplate != std::string::npos) {
797 n.erase(posTemplate, std::string::npos);
798 if (n.compare(0, 5, "std::") == 0) {
799 n.erase(0, 5);
800 }
801 iSTLType = sSTLTypes.find(n);
802 }
803 fileContent += "#pragma link C++ class ";
804 fileContent += *it + "+;\n" ;
805 if (iSTLType == sSTLTypes.end()) {
806 // Not an STL class; we need to allow the I/O of contained
807 // classes (now that we have a dictionary for them).
808 fileContent += "#pragma link C++ class " + *it + "::*+;\n" ;
809 }
810 }
811 fileContent += "#endif\n";
812 //end(1)
813 //(2) prepare the file
815 filePointer = fopen(fileName, "w");
816 if (filePointer == nullptr) {
817 //can't open a file
818 return 1;
819 }
820 //end(2)
821 //write data into the file
822 fprintf(filePointer, "%s", fileContent.c_str());
824 }
825 //(3) checking if we can compile a macro, if not then cleaning
827 gErrorIgnoreLevel = kWarning; // no "Info: creating library..."
828 Int_t ret = gSystem->CompileMacro(fileName, "k");
830 if (ret == 0) { //can't compile a macro
831 return 2;
832 }
833 //end(3)
834 return 0;
835}
836
837int TCling_GenerateDictionary(const std::string& className,
838 const std::vector<std::string> &headers,
839 const std::vector<std::string> &fwdDecls,
840 const std::vector<std::string> &unknown)
841{
842 //This function automatically creates the "LinkDef.h" file for templated
843 //classes then executes CompileMacro on it.
844 //The name of the file depends on the class name, and it's not generated again
845 //if the file exist.
846 std::vector<std::string> classes;
847 classes.push_back(className);
849}
850
851//______________________________________________________________________________
852//
853//
854//
855
856// It is a "fantom" method to synchronize user keyboard input
857// and ROOT prompt line (for WIN32)
858const char* fantomline = "TRint::EndOfLineAction();";
859
860//______________________________________________________________________________
861//
862//
863//
864
865void* TCling::fgSetOfSpecials = nullptr;
866
867//______________________________________________________________________________
868//
869// llvm error handler through exceptions; see also cling/UserInterface
870//
871namespace {
872 // Handle fatal llvm errors by throwing an exception.
873 // Yes, throwing exceptions in error handlers is bad.
874 // Doing nothing is pretty terrible, too.
875 void exceptionErrorHandler(void * /*user_data*/,
876 const char *reason,
877 bool /*gen_crash_diag*/) {
878 throw std::runtime_error(std::string(">>> Interpreter compilation error:\n") + reason);
879 }
880}
881
882//______________________________________________________________________________
883//
884//
885//
886
887////////////////////////////////////////////////////////////////////////////////
888
889namespace{
890 // An instance of this class causes the diagnostics of clang to be suppressed
891 // during its lifetime
892 class clangDiagSuppr {
893 public:
894 clangDiagSuppr(clang::DiagnosticsEngine& diag): fDiagEngine(diag){
895 fOldDiagValue = fDiagEngine.getIgnoreAllWarnings();
896 fDiagEngine.setIgnoreAllWarnings(true);
897 }
898
900 fDiagEngine.setIgnoreAllWarnings(fOldDiagValue);
901 }
902 private:
903 clang::DiagnosticsEngine& fDiagEngine;
904 bool fOldDiagValue;
905 };
906
907}
908
909////////////////////////////////////////////////////////////////////////////////
910/// Allow calling autoparsing from TMetaUtils
912{
913 return gCling->AutoParse(cname);
914}
915
916////////////////////////////////////////////////////////////////////////////////
917/// Try hard to avoid looking up in the Cling database as this could enduce
918/// an unwanted autoparsing.
919
921 std::string &result)
922{
923 result.clear();
924
925 unsigned long offset = 0;
926 if (strncmp(tname.c_str(), "const ", 6) == 0) {
927 offset = 6;
928 }
929 unsigned long end = tname.length();
930 while( end && (tname[end-1]=='&' || tname[end-1]=='*' || tname[end-1]==']') ) {
931 if ( tname[end-1]==']' ) {
932 --end;
933 while ( end && tname[end-1]!='[' ) --end;
934 }
935 --end;
936 }
937 std::string innerbuf;
938 const char *inner;
939 if (end != tname.length()) {
940 innerbuf = tname.substr(offset,end-offset);
941 inner = innerbuf.c_str();
942 } else {
943 inner = tname.c_str()+offset;
944 }
945
946 //if (strchr(tname.c_str(),'[')!=0) fprintf(stderr,"DEBUG: checking on %s vs %s %lu %lu\n",tname.c_str(),inner,offset,end);
947 if (gROOT->GetListOfClasses()->FindObject(inner)
949 // This is a known class.
950 return true;
951 }
952
953 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
954 TDataType *type = (TDataType *)typeTable->THashTable::FindObject( inner );
955 if (type) {
956 // This is a raw type and an already loaded typedef.
957 const char *newname = type->GetFullTypeName();
958 if (type->GetType() == kLong64_t) {
959 newname = "Long64_t";
960 } else if (type->GetType() == kULong64_t) {
961 newname = "ULong64_t";
962 }
963 if (strcmp(inner,newname) == 0) {
964 return true;
965 }
966 if (offset) result = "const ";
967 result += newname;
968 if ( end != tname.length() ) {
969 result += tname.substr(end,tname.length()-end);
970 }
971 if (result == tname) result.clear();
972 return true;
973 }
974
975 // Check if the name is an enumerator
977 if (lastPos != inner) // Main switch: case 1 - scoped enum, case 2 global enum
978 {
979 // We have a scope
980 const auto enName = lastPos;
981 const auto scopeNameSize = (lastPos - inner) / sizeof(decltype(*lastPos)) - 2;
982 std::string scopeName{inner, scopeNameSize};
983 // Check if the scope is in the list of classes
984 if (auto scope = static_cast<TClass *>(gROOT->GetListOfClasses()->FindObject(scopeName.c_str()))) {
985 auto enumTable = dynamic_cast<const THashList *>(scope->GetListOfEnums(false));
986 if (enumTable && enumTable->THashList::FindObject(enName))
987 return true;
988 }
989 // It may still be in one of the loaded protoclasses
990 else if (auto scope = static_cast<TProtoClass *>(gClassTable->GetProtoNorm(scopeName.c_str()))) {
991 auto listOfEnums = scope->GetListOfEnums();
992 if (listOfEnums) { // it could be null: no enumerators in the protoclass
993 auto enumTable = dynamic_cast<const THashList *>(listOfEnums);
994 if (enumTable && enumTable->THashList::FindObject(enName))
995 return true;
996 }
997 }
998 } else
999 {
1000 // We don't have any scope: this could only be a global enum
1001 auto enumTable = dynamic_cast<const THashList *>(gROOT->GetListOfEnums());
1002 if (enumTable && enumTable->THashList::FindObject(inner)) return true;
1003 }
1004
1006 {
1007 // This is a class name.
1008 return true;
1009 }
1010
1011 return false;
1012}
1013
1014////////////////////////////////////////////////////////////////////////////////
1015/// Check if the class name is present in TClassTable.
1016///
1017/// \param[in] tname class name to check.
1018/// \param[out] result If a class name has an alternative name registered in
1019/// TClassTable, it will be copied into this string.
1020bool TClingLookupHelper__CheckInClassTable(const std::string &tname, std::string &result)
1021{
1022 result.clear();
1023
1024 if (gROOT->GetListOfClasses()->FindObject(tname.c_str()) || TClassTable::Check(tname.c_str(), result)) {
1025 // This is a known class.
1026 return true;
1027 }
1028
1029 return false;
1030}
1031
1032////////////////////////////////////////////////////////////////////////////////
1033
1038
1039////////////////////////////////////////////////////////////////////////////////
1040
1042{
1043 return fContent.c_str();
1044}
1045
1046////////////////////////////////////////////////////////////////////////////////
1047/// Append string to the storage if not added already.
1048
1049inline bool TCling::TUniqueString::Append(const std::string& str)
1050{
1051 bool notPresent = fLinesHashSet.emplace(fHashFunc(str)).second;
1052 if (notPresent){
1053 fContent+=str;
1054 }
1055 return notPresent;
1056}
1057
1058std::string TCling::ToString(const char* type, void* obj)
1059{
1060 return fInterpreter->toString(type, obj);
1061}
1062
1063////////////////////////////////////////////////////////////////////////////////
1064///\returns true if the module was loaded.
1065static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
1066{
1067 // When starting up ROOT, cling would load all modulemap files on the include
1068 // paths. However, in a ROOT session, it is very common to run aclic which
1069 // will invoke rootcling and possibly produce a modulemap and a module in
1070 // the current folder.
1071 //
1072 // Before failing, try loading the modulemap in the current folder and try
1073 // loading the requested module from it.
1074 std::string currentDir = gSystem->WorkingDirectory();
1075 assert(!currentDir.empty());
1077 if (gDebug > 2)
1078 ::Info("TCling::__LoadModule", "Preloading module %s. \n",
1079 ModuleName.c_str());
1080
1081 return interp.loadModule(ModuleName, /*Complain=*/true);
1082}
1083
1084////////////////////////////////////////////////////////////////////////////////
1085/// Loads the C++ modules that we require to run any ROOT program. This is just
1086/// supposed to make a C++ module from a modulemap available to the interpreter.
1087static void LoadModules(const std::vector<std::string> &modules, cling::Interpreter &interp)
1088{
1089 for (const auto &modName : modules)
1091}
1092
1093static bool IsFromRootCling() {
1094 // rootcling also uses TCling for generating the dictionary ROOT files.
1095 const static bool foundSymbol = dlsym(RTLD_DEFAULT, "usedToIdentifyRootClingByDlSym");
1096 return foundSymbol;
1097}
1098
1099/// Checks if there is an ASTFile on disk for the given module \c M.
1100static bool HasASTFileOnDisk(clang::Module *M, const clang::Preprocessor &PP, std::string *FullFileName = nullptr)
1101{
1102 const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1103
1104 std::string ModuleFileName;
1105 if (!HSOpts.PrebuiltModulePaths.empty())
1106 // Load the module from *only* in the prebuilt module path.
1107 ModuleFileName = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(M->Name);
1108 if (FullFileName)
1110
1111 return !ModuleFileName.empty();
1112}
1113
1114static bool HaveFullGlobalModuleIndex = false;
1116{
1117 CompilerInstance &CI = *interp.getCI();
1118 Preprocessor &PP = CI.getPreprocessor();
1119 auto ModuleManager = CI.getASTReader();
1121 // StringRef ModuleIndexPath = HSI.getModuleCachePath();
1122 // HeaderSearch& HSI = PP.getHeaderSearchInfo();
1123 // HSI.setModuleCachePath(TROOT::GetSharedLibDir().Data());
1124 std::string ModuleIndexPath = TROOT::GetSharedLibDir().Data();
1125 if (ModuleIndexPath.empty())
1126 return nullptr;
1127 // Get an existing global index. This loads it if not already loaded.
1128 ModuleManager->resetForReload();
1129 ModuleManager->loadGlobalIndex();
1130 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1131
1132 // For finding modules needing to be imported for fixit messages,
1133 // we need to make the global index cover all modules, so we do that here.
1135 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1136 bool RecreateIndex = false;
1137 for (ModuleMap::module_iterator I = MMap.module_begin(), E = MMap.module_end(); I != E; ++I) {
1138 Module *TheModule = I->second;
1139 // We want the index only of the prebuilt modules.
1141 continue;
1142 LoadModule(TheModule->Name, interp);
1143 RecreateIndex = true;
1144 }
1145 if (RecreateIndex) {
1146 cling::Interpreter::PushTransactionRAII deserRAII(&interp);
1147 clang::GlobalModuleIndex::UserDefinedInterestingIDs IDs;
1148
1149 struct DefinitionFinder : public RecursiveASTVisitor<DefinitionFinder> {
1150 DefinitionFinder(clang::GlobalModuleIndex::UserDefinedInterestingIDs& IDs,
1151 clang::TranslationUnitDecl* TU) : DefinitionIDs(IDs) {
1153 }
1154 bool VisitNamedDecl(NamedDecl *ND) {
1155 if (!ND->isFromASTFile())
1156 return true;
1157 if (!ND->getIdentifier())
1158 return true;
1159
1160 if (ND->getAccess() == AS_protected || ND->getAccess() == AS_private)
1161 return true;
1162
1163 if (TagDecl *TD = llvm::dyn_cast<TagDecl>(ND)) {
1164 if (TD->isCompleteDefinition())
1165 Register(TD);
1166 } else if (NamespaceDecl *NSD = llvm::dyn_cast<NamespaceDecl>(ND)) {
1167 Register(NSD, /*AddSingleEntry=*/ false);
1168 }
1170 Register(TND);
1171 // FIXME: Add the rest...
1172 return true; // continue decending
1173 }
1174 private:
1175 clang::GlobalModuleIndex::UserDefinedInterestingIDs &DefinitionIDs;
1176 void Register(const NamedDecl* ND, bool AddSingleEntry = true) {
1177 assert(ND->isFromASTFile());
1178 // FIXME: All decls should have an owning module once rootcling
1179 // updates its generated decls from within the LookupHelper & co.
1180 if (!ND->hasOwningModule()) {
1181#ifndef NDEBUG
1182 SourceManager &SM = ND->getASTContext().getSourceManager();
1183 SourceLocation Loc = ND->getLocation();
1184 OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getFileID(Loc));
1185 (void)FE;
1186 assert(FE->getName().contains("input_line_"));
1187#endif
1188 return;
1189 }
1190
1191 Module *OwningModule = ND->getOwningModule()->getTopLevelModule();
1193 assert(!ND->getName().empty() && "Empty name");
1194 if (AddSingleEntry && DefinitionIDs.count(ND->getName()))
1195 return;
1196 // FIXME: The FileEntry in not stable to serialize.
1197 // FIXME: We might end up with many times with the same module.
1198 // FIXME: We might end up two modules containing a definition.
1199 // FIXME: What do we do if no definition is found.
1200 DefinitionIDs[ND->getName()].push_back(OwningModule->getASTFile());
1201 }
1202 };
1203 DefinitionFinder defFinder(IDs, CI.getASTContext().getTranslationUnitDecl());
1204
1205 llvm::cantFail(GlobalModuleIndex::writeIndex(CI.getFileManager(),
1206 CI.getPCHContainerReader(),
1208 &IDs));
1209 ModuleManager->resetForReload();
1210 ModuleManager->loadGlobalIndex();
1211 GlobalIndex = ModuleManager->getGlobalIndex();
1212 }
1214 }
1215 return GlobalIndex;
1216}
1217
1218static void RegisterCxxModules(cling::Interpreter &clingInterp)
1219{
1220 if (!clingInterp.getCI()->getLangOpts().Modules)
1221 return;
1222
1223 // Loading of a module might deserialize.
1224 cling::Interpreter::PushTransactionRAII deserRAII(&clingInterp);
1225
1226 // Setup core C++ modules if we have any to setup.
1227
1228 // Load libc and stl first.
1229 // Load vcruntime module for windows
1230#ifdef R__WIN32
1231 LoadModule("vcruntime", clingInterp);
1232 LoadModule("services", clingInterp);
1233#endif
1234
1235#ifdef R__MACOSX
1236 LoadModule("Darwin", clingInterp);
1237#else
1238 LoadModule("libc", clingInterp);
1239#endif
1240 LoadModule("std", clingInterp);
1241
1242 LoadModule("_Builtin_intrinsics", clingInterp);
1243
1244 // Load core modules
1245 // This should be vector in order to be able to pass it to LoadModules
1246 std::vector<std::string> CoreModules = {"ROOT_Foundation_C",
1247 "ROOT_Config",
1248 "ROOT_Rtypes",
1249 "ROOT_Foundation_Stage1_NoRTTI",
1250 "Core",
1251 "Rint",
1252 "RIO"};
1253
1255
1256 // Take this branch only from ROOT because we don't need to preload modules in rootcling
1257 if (!IsFromRootCling()) {
1258 std::vector<std::string> CommonModules = {"MathCore"};
1260
1261 // These modules should not be preloaded but they fix issues.
1262 // FIXME: Hist is not a core module but is very entangled to MathCore and
1263 // causes issues.
1264 std::vector<std::string> FIXMEModules = {"Hist"};
1265 clang::CompilerInstance &CI = *clingInterp.getCI();
1266 clang::Preprocessor &PP = CI.getPreprocessor();
1267 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1268 if (MMap.findModule("RInterface"))
1269 FIXMEModules.push_back("RInterface");
1270
1272
1273 GlobalModuleIndex *GlobalIndex = nullptr;
1275 // FIXME: The ASTReader still calls loadGlobalIndex and loads the file
1276 // We should investigate how to suppress it completely.
1277 GlobalIndex = CI.getASTReader()->getGlobalIndex();
1278
1279 llvm::StringSet<> KnownModuleFileNames;
1280 if (GlobalIndex)
1281 GlobalIndex->getKnownModuleFileNames(KnownModuleFileNames);
1282
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;
1287 assert(M);
1288
1289 // We want to load only already created modules.
1290 std::string FullASTFilePath;
1292 continue;
1293
1295 continue;
1296
1297 if (M->IsUnimportable)
1298 continue;
1299
1300 if (GlobalIndex)
1301 LoadModule(M->Name, clingInterp);
1302 else {
1303 // FIXME: We may be able to remove those checks as cling::loadModule
1304 // checks if a module was alredy loaded.
1305 if (std::find(CoreModules.begin(), CoreModules.end(), M->Name) != CoreModules.end())
1306 continue; // This is a core module which was already loaded.
1307
1308 // Load system modules now and delay the other modules after we have
1309 // loaded all system ones.
1310 if (M->IsSystem)
1311 LoadModule(M->Name, clingInterp);
1312 else
1313 PendingModules.push_back(M->Name);
1314 }
1315 }
1317 }
1318
1319 // Check that the gROOT macro was exported by any core module.
1320 assert(clingInterp.getMacro("gROOT") && "Couldn't load gROOT macro?");
1321
1322 // `ERROR` and `PI` are from loading R related modules, which conflict with
1323 // user's code.
1324 clingInterp.declare(R"CODE(
1325#ifdef PI
1326# undef PI
1327#endif
1328#ifdef ERROR
1329# undef ERROR
1330#endif
1331 )CODE");
1332}
1333
1334static void RegisterPreIncludedHeaders(cling::Interpreter &clingInterp)
1335{
1336 std::string PreIncludes;
1337 bool hasCxxModules = clingInterp.getCI()->getLangOpts().Modules;
1338
1339 // For the list to also include string, we have to include it now.
1340 // rootcling does parts already if needed, e.g. genreflex does not want using
1341 // namespace std.
1342 if (IsFromRootCling()) {
1343 PreIncludes += "#include \"RtypesCore.h\"\n";
1344 } else {
1345 if (!hasCxxModules)
1346 PreIncludes += "#include \"Rtypes.h\"\n";
1347
1349 + gInterpreterClassDef + "\n"
1350 "#undef ClassImp\n" // bw compatibility
1351 "#define ClassImp(X);\n"; // bw compatibility
1352 }
1353 if (!hasCxxModules)
1354 PreIncludes += "#include <string>\n";
1355
1356 // We must include it even when we have modules because it is marked as
1357 // textual in the modulemap due to the nature of the assert header.
1358#ifndef R__WIN32
1359 PreIncludes += "#include <cassert>\n";
1360#endif
1361 PreIncludes += "using namespace std;\n";
1362 clingInterp.declare(PreIncludes);
1363}
1364
1365////////////////////////////////////////////////////////////////////////////////
1366/// Initialize the cling interpreter interface.
1367/// \param name name for TInterpreter
1368/// \param title title for TInterpreter
1369/// \param argv - array of arguments passed to the cling::Interpreter constructor
1370/// e.g. `-DFOO=bar`. The last element of the array must be `nullptr`.
1371/// \param interpLibHandle handle to interpreter library
1372
1373TCling::TCling(const char *name, const char *title, const char* const argv[], void *interpLibHandle)
1374: TInterpreter(name, title), fGlobalsListSerial(-1), fMapfile(nullptr),
1375 fRootmapFiles(nullptr), fLockProcessLine(true), fNormalizedCtxt(nullptr), fLookupHelper(nullptr),
1376 fPrevLoadedDynLibInfo(nullptr), fClingCallbacks(nullptr), fAutoLoadCallBack(nullptr),
1378{
1379 fPrompt[0] = 0;
1380 const bool fromRootCling = IsFromRootCling();
1381
1382 fCxxModulesEnabled = false;
1383#ifdef R__USE_CXXMODULES
1384 fCxxModulesEnabled = true;
1385#endif
1386
1387 llvm::install_fatal_error_handler(&exceptionErrorHandler);
1388
1389 fTemporaries = new std::vector<cling::Value>();
1390
1391 std::vector<std::string> clingArgsStorage;
1392 clingArgsStorage.push_back("cling4root");
1393 for (const char* const* arg = argv; *arg; ++arg)
1394 clingArgsStorage.push_back(*arg);
1395
1396 // rootcling sets its arguments through TROOT::GetExtraInterpreterArgs().
1397 if (!fromRootCling) {
1399
1400 // Add -I early so ASTReader can find the headers.
1401 std::string interpInclude(TROOT::GetEtcDir().Data());
1402 clingArgsStorage.push_back("-I" + interpInclude);
1403
1404 // Add include path to etc/cling.
1405 clingArgsStorage.push_back("-I" + interpInclude + "/cling");
1406
1407 // Add include path to etc/cling.
1408 clingArgsStorage.push_back("-I" + interpInclude + "/cling/plugins/include");
1409
1410 // Add the root include directory and etc/ to list searched by default.
1411 clingArgsStorage.push_back(std::string(("-I" + TROOT::GetIncludeDir()).Data()));
1412
1413 // Add the current path to the include path
1414 // TCling::AddIncludePath(".");
1415
1416 // Attach the PCH (unless we have C++ modules enabled which provide the
1417 // same functionality).
1418 if (!fCxxModulesEnabled) {
1419 std::string pchFilename = interpInclude + "/allDict.cxx.pch";
1420 if (gSystem->Getenv("ROOT_PCH")) {
1421 pchFilename = gSystem->Getenv("ROOT_PCH");
1422 }
1423
1424 clingArgsStorage.push_back("-include-pch");
1425 clingArgsStorage.push_back(pchFilename);
1426 }
1427
1428 clingArgsStorage.push_back("-Wno-undefined-inline");
1429 clingArgsStorage.push_back("-fsigned-char");
1430 clingArgsStorage.push_back("-fsized-deallocation");
1431 // The -O1 optimization flag has nasty side effects on Windows (32 and 64 bit)
1432 // See the GitHub issues #9809 and #9944
1433 // TODO: to be reviewed after the upgrade of LLVM & Clang
1434#ifndef _MSC_VER
1435 clingArgsStorage.push_back("-O1");
1436 // Disable optimized register allocation which is turned on automatically
1437 // by -O1, but seems to require -O2 to not explode in run time.
1438 clingArgsStorage.push_back("-mllvm");
1439 clingArgsStorage.push_back("-optimize-regalloc=0");
1440#endif
1441
1442#ifdef CLING_WITH_ADAPTIVECPP
1443 std::string acppInclude(TROOT::GetIncludeDir() + "/AdaptiveCpp");
1444
1445 clingArgsStorage.push_back("-isystem");
1446 clingArgsStorage.push_back(acppInclude);
1447 clingArgsStorage.push_back("-mllvm");
1448 clingArgsStorage.push_back("-acpp-sscp");
1449#endif
1450 }
1451
1452 // Process externally passed arguments if present.
1453 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv("EXTRA_CLING_ARGS");
1454 if (EnvOpt.has_value()) {
1456 while (!Env.empty()) {
1457 StringRef Arg;
1458 std::tie(Arg, Env) = Env.split(' ');
1459 clingArgsStorage.push_back(Arg.str());
1460 }
1461 }
1462
1463 auto GetEnvVarPath = [](const std::string &EnvVar, std::vector<std::string> &Paths) {
1464 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1465 if (EnvOpt.has_value()) {
1467 while (!Env.empty()) {
1468 StringRef Arg;
1469 std::tie(Arg, Env) = Env.split(ROOT::FoundationUtils::GetEnvPathSeparator());
1470 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1471 Paths.push_back(Arg.str());
1472 }
1473 }
1474 };
1475
1476 if (fCxxModulesEnabled) {
1477 std::vector<std::string> Paths;
1478 // ROOT usually knows better where its libraries are. This way we can
1479 // discover modules without having to should thisroot.sh and should fix
1480 // gnuinstall.
1481 Paths.push_back(TROOT::GetSharedLibDir().Data());
1482 GetEnvVarPath("CLING_PREBUILT_MODULE_PATH", Paths);
1483 std::string EnvVarPath;
1484 for (const std::string& P : Paths)
1486 // FIXME: We should make cling -fprebuilt-module-path work.
1487 gSystem->Setenv("CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1488 }
1489
1490 // FIXME: This only will enable frontend timing reports.
1491 EnvOpt = llvm::sys::Process::GetEnv("ROOT_CLING_TIMING");
1492 if (EnvOpt.has_value())
1493 clingArgsStorage.push_back("-ftime-report");
1494
1495 // Add the overlay file. Note that we cannot factor it out for both root
1496 // and rootcling because rootcling activates modules only if -cxxmodule
1497 // flag is passed.
1499 // For now we prefer rootcling to enumerate explicitly its modulemaps.
1500 std::vector<std::string> ModuleMaps;
1501 std::string ModuleMapSuffix = ROOT::FoundationUtils::GetPathSeparator() + "ROOT.modulemap";
1502 ModuleMaps.push_back(TROOT::GetIncludeDir().Data() + ModuleMapSuffix);
1503 GetEnvVarPath("CLING_MODULEMAP_FILES", ModuleMaps);
1504
1505 std::string cwd = gSystem->WorkingDirectory();
1506 // Give highest precedence of the modulemap in the cwd if any.
1507 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1508 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1509
1510 for (const std::string& M : ModuleMaps)
1511 clingArgsStorage.push_back("-fmodule-map-file=" + M);
1512
1513 std::string ModulesCachePath;
1514 EnvOpt = llvm::sys::Process::GetEnv("CLING_MODULES_CACHE_PATH");
1515 if (EnvOpt.has_value()){
1517 assert(llvm::sys::fs::exists(Env) && "Path does not exist!");
1518 ModulesCachePath = Env.str();
1519 } else {
1521 }
1522
1523 clingArgsStorage.push_back("-fmodules-cache-path=" + ModulesCachePath);
1524 }
1525
1526 std::vector<const char*> interpArgs;
1527 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1529 interpArgs.push_back(iArg->c_str());
1530
1531 // Activate C++ modules support. If we are running within rootcling, it's up
1532 // to rootcling to set this flag depending on whether it wants to produce
1533 // C++ modules.
1535 if (fCxxModulesEnabled) {
1536 if (!fromRootCling) {
1537 // We only set this flag, rest is done by the CIFactory.
1538 interpArgs.push_back("-fmodules");
1539 interpArgs.push_back("-fno-implicit-module-maps");
1540 // We should never build modules during runtime, so let's enable the
1541 // module build remarks from clang to make it easier to spot when we do
1542 // this by accident.
1543 interpArgs.push_back("-Rmodule-build");
1544 }
1545 // ROOT implements its AutoLoading upon module's link directives. We
1546 // generate module A { header "A.h" link "A.so" export * } where ROOT's
1547 // facilities use the link directive to dynamically load the relevant
1548 // library. So, we need to suppress clang's default autolink behavior.
1549 interpArgs.push_back("-fno-autolink");
1550 }
1551
1552#ifdef R__FAST_MATH
1553 // Same setting as in rootcling_impl.cxx.
1554 interpArgs.push_back("-ffast-math");
1555#endif
1556
1558 // Add statically injected extra arguments, usually coming from rootcling.
1559 for (const char** extraArgs = TROOT::GetExtraInterpreterArgs();
1560 extraArgs && *extraArgs; ++extraArgs) {
1561 if (!strcmp(*extraArgs, "-resource-dir")) {
1562 // Take the next arg as the llvm resource directory.
1564 } else {
1565 interpArgs.push_back(*extraArgs);
1566 }
1567 }
1568
1569 std::vector<std::string> _empty;
1571 for (const auto &arg: args)
1572 interpArgs.emplace_back(arg.c_str());
1573
1574 // Add the Rdict module file extension.
1575 cling::Interpreter::ModuleFileExtensions extensions;
1576 EnvOpt = llvm::sys::Process::GetEnv("ROOTDEBUG_RDICT");
1577 if (!EnvOpt.has_value())
1578 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1579
1580 fInterpreter = std::make_unique<cling::Interpreter>(interpArgs.size(),
1581 &(interpArgs[0]),
1584
1585 if (!fInterpreter->getCI()) { // Compiler instance could not be created. See https://its.cern.ch/jira/browse/ROOT-10239
1586 return;
1587 }
1588
1589 // Tell CppInterOp that the cling::Interpreter instance is managed externally by ROOT
1590 // Sets the interpreter by passing the fInterpreter handle as soon as TCling is initialized
1591 if (!IsFromRootCling())
1592 Cpp::UseExternalInterpreter(fInterpreter.get());
1593
1594 // Don't check whether modules' files exist.
1595 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHOrModuleValidation =
1596 DisableValidationForModuleKind::All;
1597
1598 // Until we can disable AutoLoading during Sema::CorrectTypo() we have
1599 // to disable spell checking.
1600 fInterpreter->getCI()->getLangOpts().SpellChecking = false;
1601
1602 // Sync modules on/off between clang and us: clang turns it on for C++ >= 20.
1603 auto isModulesArg = [](const char* arg) { return !strcmp(arg, "-fmodules"); };
1604 bool hasModulesArg = std::find_if(interpArgs.begin(), interpArgs.end(), isModulesArg) != interpArgs.end();
1605 fInterpreter->getCI()->getLangOpts().Modules = hasModulesArg;
1606
1607 // We need stream that doesn't close its file descriptor, thus we are not
1608 // using llvm::outs. Keeping file descriptor open we will be able to use
1609 // the results in pipes (Savannah #99234).
1610 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO, /*ShouldClose*/false);
1611 fMetaProcessor = std::make_unique<cling::MetaProcessor>(*fInterpreter, fMPOuts);
1612
1615
1616 // We are now ready (enough is loaded) to init the list of opaque typedefs.
1622
1623 // Disallow auto-parsing in rootcling
1625
1626 ResetAll();
1627
1628 // Enable dynamic lookup
1629 if (!fromRootCling) {
1630 fInterpreter->enableDynamicLookup();
1631 }
1632
1633 // Enable ClinG's DefinitionShadower for ROOT.
1634 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1635 auto &Policy = const_cast<clang::PrintingPolicy &>(fInterpreter->getCI()->getASTContext().getPrintingPolicy());
1636 // Print 'a<b<c> >' rather than 'a<b<c>>'.
1637 // FIXME: We should probably switch to the default printing policy setting
1638 // after adjusting tons of reference files.
1639 Policy.SplitTemplateClosers = true;
1640 // Keep default templare arguments, required for dictionary generation.
1641 Policy.SuppressDefaultTemplateArgs = false;
1642
1643
1644 // Attach cling callbacks last; they might need TROOT::fInterpreter
1645 // and should thus not be triggered during the equivalent of
1646 // TROOT::fInterpreter = new TCling;
1647 std::unique_ptr<TClingCallbacks>
1651 fInterpreter->setCallbacks(std::move(clingCallbacks));
1652
1653 if (!fromRootCling) {
1654 cling::DynamicLibraryManager& DLM = *fInterpreter->getDynamicLibraryManager();
1655 // Make sure cling looks into ROOT's libdir, even if not part of LD_LIBRARY_PATH
1656 // e.g. because of an RPATH build.
1657 DLM.addSearchPath(TROOT::GetSharedLibDir().Data(), /*isUser=*/true,
1658 /*prepend=*/true);
1659 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) -> bool{
1660 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1661 return stem.starts_with("libNew") || stem.starts_with("libcppyy_backend");
1662 };
1663 // Initialize the dyld for AutoloadLibraryGenerator.
1664 DLM.initializeDyld(ShouldPermanentlyIgnore);
1665 }
1666}
1667
1668
1669////////////////////////////////////////////////////////////////////////////////
1670/// Destroy the interpreter interface.
1671
1673{
1674 // ROOT's atexit functions require the interepreter to be available.
1675 // Run them before shutting down.
1676 if (!IsFromRootCling())
1677 GetInterpreterImpl()->runAtExitFuncs();
1678 fIsShuttingDown = true;
1679 delete fMapfile;
1680 delete fRootmapFiles;
1681 delete fTemporaries;
1682 delete fNormalizedCtxt;
1683 delete fLookupHelper;
1684 gCling = nullptr;
1685}
1686
1687////////////////////////////////////////////////////////////////////////////////
1688/// Initialize the interpreter, once TROOT::fInterpreter is set.
1689
1691{
1692 if (!fClingCallbacks) // Compiler instance could not be created. See https://its.cern.ch/jira/browse/ROOT-10239
1693 return;
1695
1696 // We are set up. Enable ROOT's AutoLoading.
1697 if (IsFromRootCling())
1698 return;
1699
1700 // Read the rules before enabling the auto loading to not inadvertently
1701 // load the libraries for the classes concerned even-though the user is
1702 // *not* using them.
1703 // Note this call must happen before the first call to LoadLibraryMap.
1704 assert(GetRootMapFiles() == nullptr && "Must be called before LoadLibraryMap!");
1705 TClass::ReadRules(); // Read the default customization rules ...
1706
1708 SetClassAutoLoading(true);
1709}
1710
1712{
1713 fIsShuttingDown = true;
1714 ResetGlobals();
1715}
1716
1717////////////////////////////////////////////////////////////////////////////////
1718/// Helper to initialize TVirtualStreamerInfo's factor early.
1719/// Use static initialization to insure only one TStreamerInfo is created.
1721{
1722 // Use lambda since SetFactory return void.
1723 auto setFactory = []() {
1725 return kTRUE;
1726 };
1727 static bool doneFactory = setFactory();
1728 return doneFactory; // avoid unused variable warning.
1729}
1730
1731////////////////////////////////////////////////////////////////////////////////
1732/// Register Rdict data for future loading by LoadPCM;
1733
1734void TCling::RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
1735{
1736 if (IsFromRootCling())
1737 return;
1738
1739 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1740 ::Error("TCling::RegisterRdictForLoadPCM", "Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1741 return;
1742 }
1743
1744 // The pcmFileNameFullPath must be resolved already because we cannot resolve
1745 // a link to a non-existent file.
1747}
1748
1749////////////////////////////////////////////////////////////////////////////////
1750/// Tries to load a PCM from TFile; returns true on success.
1751/// The caller of this function should be holding the ROOT Write lock.
1752
1754{
1755 auto listOfKeys = pcmFile.GetListOfKeys();
1756
1757 // This is an empty pcm
1758 if (listOfKeys && ((listOfKeys->GetSize() == 0) || // Nothing here, or
1759 ((listOfKeys->GetSize() == 1) && // only one, and
1760 !strcmp(((TKey *)listOfKeys->At(0))->GetName(), "EMPTY") // name is EMPTY
1761 ))) {
1762 return;
1763 }
1764
1766 if (gDebug > 1)
1767 ::Info("TCling::LoadPCMImpl", "reading protoclasses for %s \n", pcmFile.GetName());
1768
1770 pcmFile.GetObject("__Enums", enums);
1771 if (enums) {
1772 // Cache the pointers
1773 auto listOfGlobals = gROOT->GetListOfGlobals();
1774 auto listOfEnums = dynamic_cast<THashList *>(gROOT->GetListOfEnums());
1775 // Loop on enums and then on enum constants
1776 for (auto selEnum : *enums) {
1777 const char *enumScope = selEnum->GetTitle();
1778 const char *enumName = selEnum->GetName();
1779 if (strcmp(enumScope, "") == 0) {
1780 // This is a global enum and is added to the
1781 // list of enums and its constants to the list of globals
1782 if (!listOfEnums->THashList::FindObject(enumName)) {
1783 ((TEnum *)selEnum)->SetClass(nullptr);
1784 listOfEnums->Add(selEnum);
1785 }
1786 for (auto enumConstant : *static_cast<TEnum *>(selEnum)->GetConstants()) {
1787 if (!listOfGlobals->FindObject(enumConstant)) {
1789 }
1790 }
1791 } else {
1792 // This enum is in a namespace. A TClass entry is bootstrapped if
1793 // none exists yet and the enum is added to it
1795 if (!nsTClassEntry) {
1797 }
1798 auto listOfEnums = nsTClassEntry->fEnums.load();
1799 if (!listOfEnums) {
1800 if ((kIsClass | kIsStruct | kIsUnion) & nsTClassEntry->Property()) {
1801 // For this case, the list will be immutable once constructed
1802 // (i.e. in this case, by the end of this routine).
1804 } else {
1805 // namespaces can have enums added to them
1807 }
1808 }
1809 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1810 ((TEnum *)selEnum)->SetClass(nsTClassEntry);
1811 listOfEnums->Add(selEnum);
1812 }
1813 }
1814 }
1815 enums->Clear();
1816 delete enums;
1817 }
1818
1819 pcmFile.GetObject("__ProtoClasses", protoClasses);
1820
1821 if (protoClasses) {
1822 for (auto obj : *protoClasses) {
1823 TProtoClass *proto = (TProtoClass *)obj;
1825 }
1826 // Now that all TClass-es know how to set them up we can update
1827 // existing TClasses, which might cause the creation of e.g. TBaseClass
1828 // objects which in turn requires the creation of TClasses, that could
1829 // come from the PCH, but maybe later in the loop. Instead of resolving
1830 // a dependency graph the addition to the TClassTable above allows us
1831 // to create these dependent TClasses as needed below.
1832 for (auto proto : *protoClasses) {
1833 if (TClass *existingCl = (TClass *)gROOT->GetListOfClasses()->FindObject(proto->GetName())) {
1834 // We have an existing TClass object. It might be emulated
1835 // or interpreted; we now have more information available.
1836 // Make that available.
1837 if (existingCl->GetState() != TClass::kHasTClassInit) {
1838 DictFuncPtr_t dict = gClassTable->GetDict(proto->GetName());
1839 if (!dict) {
1840 ::Error("TCling::LoadPCM", "Inconsistent TClassTable for %s", proto->GetName());
1841 } else {
1842 // This will replace the existing TClass.
1843 TClass *ncl = (*dict)();
1844 if (ncl)
1845 ncl->PostLoadCheck();
1846 }
1847 }
1848 }
1849 }
1850
1851 protoClasses->Clear(); // Ownership was transferred to TClassTable.
1852 delete protoClasses;
1853 }
1854
1856 pcmFile.GetObject("__Typedefs", dataTypes);
1857 if (dataTypes) {
1858 for (auto typedf : *dataTypes)
1859 gROOT->GetListOfTypes()->Add(typedf);
1860 dataTypes->Clear(); // Ownership was transferred to TListOfTypes.
1861 delete dataTypes;
1862 }
1863}
1864
1865////////////////////////////////////////////////////////////////////////////////
1866/// Tries to load a rdict PCM, issues diagnostics if it fails.
1867/// The caller of this function should be holding the ROOT Write lock.
1868
1870{
1873 assert(!pcmFileNameFullPath.empty());
1874 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1875
1876 // Easier to work with the ROOT interfaces.
1878
1879 // Prevent the ROOT-PCMs hitting this during auto-load during
1880 // JITting - which will cause recursive compilation.
1881 // Avoid to call the plugin manager at all.
1883
1885 llvm::SaveAndRestore<Int_t> SaveGDebug(gDebug);
1886 if (gDebug > 5) {
1887 gDebug -= 5;
1888 ::Info("TCling::LoadPCM", "Loading ROOT PCM %s", pcmFileName.Data());
1889 } else {
1890 gDebug = 0;
1891 }
1892
1893 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1895
1897 if (pendingRdict != fPendingRdicts.end()) {
1898 llvm::StringRef pcmContent = pendingRdict->second;
1900 std::string RDictFileOpts = pcmFileNameFullPath + "?filetype=pcm";
1902
1903 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
1905 // Currently the module file are never unloaded (even if the library is
1906 // unloaded) and, of course, never reloaded.
1907 // Consequently, we must NOT remove the `pendingRdict` from the list
1908 // of pending dictionary, otherwise if a library is unloaded and then
1909 // reload we will be unable to update properly the TClass object
1910 // (because we wont be able to load the rootpcm file by executing the
1911 // above lines)
1912
1913 return;
1914 }
1915
1916 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1917 ::Error("TCling::LoadPCM", "ROOT PCM %s file does not exist",
1918 pcmFileNameFullPath.data());
1919 if (!fPendingRdicts.empty())
1920 for (const auto &rdict : fPendingRdicts)
1921 ::Info("TCling::LoadPCM", "In-memory ROOT PCM candidate %s\n",
1922 rdict.first.c_str());
1923 return;
1924 }
1925
1926 if (!gROOT->IsRootFile(pcmFileName)) {
1927 Fatal("LoadPCM", "The file %s is not a ROOT as was expected\n", pcmFileName.Data());
1928 return;
1929 }
1930 TFile pcmFile(pcmFileName + "?filetype=pcm", "READ");
1932}
1933
1934//______________________________________________________________________________
1935
1936namespace {
1937 using namespace clang;
1938
1939 class ExtLexicalStorageAdder: public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1940 // This class is to be considered an helper for autoparsing.
1941 // It visits the AST and marks all classes (in all of their redeclarations)
1942 // with the setHasExternalLexicalStorage method.
1943 public:
1944 bool VisitRecordDecl(clang::RecordDecl* rcd){
1945 if (gDebug > 2)
1946 Info("ExtLexicalStorageAdder",
1947 "Adding external lexical storage to class %s",
1948 rcd->getNameAsString().c_str());
1949 auto reDeclPtr = rcd->getMostRecentDecl();
1950 do {
1951 reDeclPtr->setHasExternalLexicalStorage();
1952 } while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1953
1954 return false;
1955 }
1956 };
1957
1958
1959}
1960
1961////////////////////////////////////////////////////////////////////////////////
1962///\returns true if the module map was loaded, false on error or if the map was
1963/// already loaded.
1965 const std::string &ModuleMapName /*= "module.modulemap"*/) const
1966{
1967 assert(llvm::sys::path::is_absolute(FullPath));
1968 Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
1969 FileManager &FM = PP.getFileManager();
1970 // FIXME: In a ROOT session we can add an include path (through .I /inc/path)
1971 // We should look for modulemap files there too.
1972 if (auto DE = FM.getOptionalDirectoryRef(FullPath)) {
1973 HeaderSearch &HS = PP.getHeaderSearchInfo();
1974 HeaderSearchOptions &HSOpts = const_cast<HeaderSearchOptions&>(HS.getHeaderSearchOpts());
1975 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1976 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1977 if (!pathExists)
1978 HSOpts.AddPrebuiltModulePath(FullPath);
1979 // We cannot use HS.lookupModuleMapFile(DE, /*IsFramework*/ false);
1980 // because its internal call to getFile has CacheFailure set to true.
1981 // In our case, modulemaps can appear any time due to ACLiC.
1982 // Code copied from HS.lookupModuleMapFile.
1983 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1984 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1985 if (auto FE = FM.getOptionalFileRef(ModuleMapFileName, /*openFile*/ false,
1986 /*CacheFailure*/ false)) {
1987 if (!HS.parseAndLoadModuleMapFile(*FE, /*IsSystem*/ false))
1988 return true;
1989 Error("RegisterPrebuiltModulePath", "Could not load modulemap in %s", ModuleMapFileName.c_str());
1990 }
1991 }
1992 return false;
1993}
1994
1995////////////////////////////////////////////////////////////////////////////////
1996/// List of dicts that have the PCM information already in the PCH.
1997static const std::unordered_set<std::string> gIgnoredPCMNames = {"libCore",
1998 "libRint",
1999 "libThread",
2000 "libRIO",
2001 "libImt",
2002 "libMultiProc",
2003 "libcomplexDict",
2004 "libdequeDict",
2005 "liblistDict",
2006 "libforward_listDict",
2007 "libvectorDict",
2008 "libmapDict",
2009 "libmultimap2Dict",
2010 "libmap2Dict",
2011 "libmultimapDict",
2012 "libsetDict",
2013 "libmultisetDict",
2014 "libunordered_setDict",
2015 "libunordered_multisetDict",
2016 "libunordered_mapDict",
2017 "libunordered_multimapDict",
2018 "libvalarrayDict",
2019 "G__GenVector32",
2020 "G__Smatrix32"};
2021
2022static void PrintDlError(const char *dyLibName, const char *modulename)
2023{
2024#ifdef R__WIN32
2025 char dyLibError[1000];
2027 dyLibError, sizeof(dyLibError), NULL);
2028#else
2029 const char *dyLibError = dlerror();
2030#endif
2031 ::Error("TCling::RegisterModule", "Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
2032 (dyLibError) ? dyLibError : "");
2033}
2034
2035////////////////////////////////////////////////////////////////////////////////
2036// Update all the TClass registered in fClassesToUpdate
2037
2039{
2040 while (!fClassesToUpdate.empty()) {
2041 TClass *oldcl = fClassesToUpdate.back().first;
2042 // If somehow the TClass has already been loaded (maybe it was registered several time),
2043 // we skip it. Otherwise, the existing TClass is in mode kInterpreted, kEmulated or
2044 // maybe even kForwardDeclared and needs to replaced.
2045 if (oldcl->GetState() != TClass::kHasTClassInit) {
2046 // if (gDebug > 2) Info("RegisterModule", "Forcing TClass init for %s", oldcl->GetName());
2047 DictFuncPtr_t dict = fClassesToUpdate.back().second;
2048 fClassesToUpdate.pop_back();
2049 // Calling func could manipulate the list so, let maintain the list
2050 // then call the dictionary function.
2051 TClass *ncl = dict();
2052 if (ncl) ncl->PostLoadCheck();
2053 } else {
2054 fClassesToUpdate.pop_back();
2055 }
2056 }
2057}
2058////////////////////////////////////////////////////////////////////////////////
2059/// Inject the module named "modulename" into cling; load all headers.
2060/// headers is a 0-terminated array of header files to `#include` after
2061/// loading the module. The module is searched for in all $LD_LIBRARY_PATH
2062/// entries (or %PATH% on Windows).
2063/// This function gets called by the static initialization of dictionary
2064/// libraries.
2065/// The payload code is injected "as is" in the interpreter.
2066/// The value of 'triggerFunc' is used to find the shared library location.
2067/// The caller of this function should be holding the ROOT Write lock.
2068
2070 const char** headers,
2071 const char** includePaths,
2072 const char* payloadCode,
2073 const char* fwdDeclsCode,
2074 void (*triggerFunc)(),
2076 const char** classesHeaders,
2077 Bool_t lateRegistration /*=false*/,
2078 Bool_t hasCxxModule /*=false*/)
2079{
2080 const bool fromRootCling = IsFromRootCling();
2081 // We need the dictionary initialization but we don't want to inject the
2082 // declarations into the interpreter, except for those we really need for
2083 // I/O; see rootcling.cxx after the call to TCling__GetInterpreter().
2084 if (fromRootCling) return;
2085
2086 // When we cannot provide a module for the library we should enable header
2087 // parsing. This 'mixed' mode ensures gradual migration to modules.
2088 llvm::SaveAndRestore<bool> SaveHeaderParsing(fHeaderParsingOnDemand);
2090
2091 // Treat Aclic Libs in a special way. Do not delay the parsing.
2093 bool isACLiC = strstr(modulename, "_ACLiC_dict") != nullptr;
2095 if (gDebug>1)
2096 Info("TCling::RegisterModule",
2097 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2099 }
2100
2101
2102 // Make sure we relookup symbols that were search for before we loaded
2103 // their autoparse information. We could be more subtil and remove only
2104 // the failed one or only the one in this module, but for now this is
2105 // better than nothing.
2106 fLookedUpClasses.clear();
2107
2108 // Make sure we do not set off AutoLoading or autoparsing during the
2109 // module registration!
2111
2112 for (const char** inclPath = includePaths; *inclPath; ++inclPath) {
2114 }
2115 cling::Transaction* T = nullptr;
2116 // Put the template decls and the number of arguments to skip in the TNormalizedCtxt
2118 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2119 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2120 auto compRes = fInterpreter->declare(fwdDecl.c_str(), &T);
2121 assert(cling::Interpreter::kSuccess == compRes &&
2122 "A fwd declaration could not be compiled");
2123 if (compRes!=cling::Interpreter::kSuccess){
2124 Warning("TCling::RegisterModule",
2125 "Problems in declaring string '%s' were encountered.",
2126 fwdDecl.c_str()) ;
2127 continue;
2128 }
2129
2130 // Drill through namespaces recursively until the template is found
2131 if(ClassTemplateDecl* TD = FindTemplateInNamespace(T->getFirstDecl().getSingleDecl())){
2133 }
2134
2135 }
2136
2137 // FIXME: Remove #define __ROOTCLING__ once PCMs are there.
2138 // This is used to give Sema the same view on ACLiC'ed files (which
2139 // are then #included through the dictionary) as rootcling had.
2141 if (payloadCode)
2142 code += payloadCode;
2143
2144 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2145 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2146
2147 if (dyLibName.empty()) {
2148 ::Error("TCling::RegisterModule", "Dictionary trigger function for %s not found", modulename);
2149 return;
2150 }
2151
2152 // The triggerFunc may not be in a shared object but in an executable.
2153 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2154
2155 bool wasDlopened = false;
2156
2157 // If this call happens after dlopen has finished (i.e. late registration)
2158 // there is no need to dlopen the library recursively. See ROOT-8437 where
2159 // the dyLibName would correspond to the binary.
2160 if (!lateRegistration) {
2161
2162 if (isSharedLib) {
2163 // We need to open the dictionary shared library, to resolve symbols
2164 // requested by the JIT from it: as the library is currently being dlopen'ed,
2165 // its symbols are not yet reachable from the process.
2166 // Recursive dlopen seems to work just fine.
2167 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2168 if (dyLibHandle) {
2170 wasDlopened = true;
2171 } else {
2173 }
2174 }
2175 } // if (!lateRegistration)
2176
2178 // We now parse the forward declarations. All the classes are then modified
2179 // in order for them to have an external lexical storage.
2180 std::string fwdDeclsCodeLessEnums;
2181 {
2182 // Search for enum forward decls and only declare them if no
2183 // declaration exists yet.
2184 std::string fwdDeclsLine;
2185 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2186 std::vector<std::string> scopes;
2187 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2188 const auto enumPos = fwdDeclsLine.find("enum __attribute__((annotate(\"");
2189 // We check if the line contains a fwd declaration of an enum
2190 if (enumPos != std::string::npos) {
2191 // We clear the scopes which we may have carried from a previous iteration
2192 scopes.clear();
2193 // We check if the enum is not in a scope. If yes, save its name
2194 // and the names of the enclosing scopes.
2195 if (enumPos != 0) {
2196 // it's enclosed in namespaces. We need to understand what they are
2197 auto nsPos = fwdDeclsLine.find("namespace");
2198 R__ASSERT(nsPos < enumPos && "Inconsistent enum and enclosing scope parsing!");
2199 while (nsPos < enumPos && nsPos != std::string::npos) {
2200 // we have a namespace, let's put it in the collection of scopes
2201 const auto nsNameStart = nsPos + 10;
2202 const auto nsNameEnd = fwdDeclsLine.find('{', nsNameStart);
2203 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2204 scopes.push_back(nsName);
2205 nsPos = fwdDeclsLine.find("namespace", nsNameEnd);
2206 }
2207 }
2208 clang::DeclContext* DC = nullptr;
2209 for (auto &&aScope: scopes) {
2210 DC = cling::utils::Lookup::Namespace(&fInterpreter->getSema(), aScope.c_str(), DC);
2211 if (!DC) {
2212 // No decl context means we have to fwd declare the enum.
2213 break;
2214 }
2215 }
2216 if (scopes.empty() || DC) {
2217 // We know the scope; let's look for the enum. For that, look
2218 // for the *last* closing parentheses of an attribute because
2219 // there can be multiple.
2220 size_t posEnumName = fwdDeclsLine.rfind("\"))) ");
2221 R__ASSERT(posEnumName != std::string::npos && "Inconsistent enum fwd decl!");
2222 posEnumName += 5; // skip "\"))) "
2224 ++posEnumName;
2225 size_t posEnumNameEnd = fwdDeclsLine.find(" : ", posEnumName);
2226 R__ASSERT(posEnumNameEnd != std::string::npos && "Inconsistent enum fwd decl (end)!");
2229 // posEnumNameEnd now points to the last character of the name.
2230
2231 std::string enumName = fwdDeclsLine.substr(posEnumName,
2233
2234 if (clang::NamedDecl* enumDecl
2235 = cling::utils::Lookup::Named(&fInterpreter->getSema(),
2236 enumName.c_str(), DC)) {
2237 // We have an existing enum decl (forward or definition);
2238 // skip this.
2239 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) && "not an enum decl!");
2240 (void)enumDecl;
2241 continue;
2242 }
2243 }
2244 }
2245
2247 }
2248 }
2249
2250 if (!fwdDeclsCodeLessEnums.empty()){ // Avoid the overhead if nothing is to be declared
2251 auto compRes = fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
2252 assert(cling::Interpreter::kSuccess == compRes &&
2253 "The forward declarations could not be compiled");
2254 if (compRes!=cling::Interpreter::kSuccess){
2255 Warning("TCling::RegisterModule",
2256 "Problems in compiling forward declarations for module %s: '%s'",
2258 }
2259 else if (T){
2260 // Loop over all decls in the transaction and go through them all
2261 // to mark them properly.
2262 // In order to do that, we first iterate over all the DelayedCallInfos
2263 // within the transaction. Then we loop over all Decls in the DeclGroupRef
2264 // contained in the DelayedCallInfos. For each decl, we traverse.
2265 ExtLexicalStorageAdder elsa;
2266 for (auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
2267 cling::Transaction::DelayCallInfo& dci = *dciIt;
2268 for(auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2269 clang::Decl* declPtr = *dit;
2270 elsa.TraverseDecl(declPtr);
2271 }
2272 }
2273 }
2274 }
2275
2276 // Now we register all the headers necessary for the class
2277 // Typical format of the array:
2278 // {"A", "classes.h", "@",
2279 // "vector<A>", "vector", "@",
2280 // "myClass", payloadCode, "@",
2281 // nullptr};
2282
2283 std::string temp;
2284 for (const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2285 temp=*classesHeader;
2286
2287 size_t theTemplateHash = 0;
2288 bool addTemplate = false;
2289 size_t posTemplate = temp.find('<');
2290 if (posTemplate != std::string::npos) {
2291 // Add an entry for the template itself.
2292 std::string templateName = temp.substr(0, posTemplate);
2294 addTemplate = true;
2295 }
2296 size_t theHash = fStringHashFunction(temp);
2297 classesHeader++;
2299 // This is done in order to distinguish headers from files and from the payloadCode
2301 fPayloads.insert(theHash);
2303 }
2304 if (gDebug > 2)
2305 Info("TCling::RegisterModule",
2306 "Adding a header for %s", temp.c_str());
2308 if (addTemplate) {
2311 }
2312 addTemplate = false;
2313 }
2314 }
2315 }
2316 }
2317
2318 clang::Sema &TheSema = fInterpreter->getSema();
2319
2320 bool ModuleWasSuccessfullyLoaded = false;
2321 if (hasCxxModule) {
2322 std::string ModuleName = modulename;
2323 if (llvm::StringRef(modulename).starts_with("lib"))
2324 ModuleName = llvm::StringRef(modulename).substr(3).str();
2325
2326 // In case we are directly loading the library via gSystem->Load() without
2327 // specifying the relevant include paths we should try loading the
2328 // modulemap next to the library location.
2329 clang::Preprocessor &PP = TheSema.getPreprocessor();
2330 std::string ModuleMapName;
2331 if (isACLiC)
2332 ModuleMapName = ModuleName + ".modulemap";
2333 else
2334 ModuleMapName = "module.modulemap";
2335 RegisterPrebuiltModulePath(llvm::sys::path::parent_path(dyLibName).str(),
2337
2338 // FIXME: We should only complain for modules which we know to exist. For example, we should not complain about
2339 // modules such as GenVector32 because it needs to fall back to GenVector.
2340 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2343 // Only report if we found the module in the modulemap.
2344 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2345 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2346 if (moduleMap.findModule(ModuleName))
2347 Info("TCling::RegisterModule", "Module %s in modulemap failed to load.", ModuleName.c_str());
2348 }
2349 }
2350
2352 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2353 // The path dyLibName might not be absolute. This can happen if dyLibName
2354 // is linked to an executable in the same folder.
2355 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2356 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2357 llvm::sys::path::append(pcmFileNameFullPath,
2359 // A library built with C++ modules may ship only its .pcm and no
2360 // <lib>_rdict.pcm (the dictionary payload then lives in the C++ module).
2361 // In that case probing the legacy rootpcm makes LoadPCM emit a spurious
2362 // "ROOT PCM ... file does not exist" error followed by an in-memory
2363 // candidate dump. Skip the probe only when the C++ module was loaded AND
2364 // there is genuinely no rootpcm to load -- neither registered in-memory
2365 // (an embedded rdict, the check mirrors LoadPCM) nor present on disk. For
2366 // libraries without a C++ module the behaviour is unchanged, so a truly
2367 // missing rootpcm is still reported.
2368 std::string pcmPath = pcmFileNameFullPath.str().str();
2369 std::string pcmRealPath = llvm::sys::fs::is_symlink_file(pcmPath)
2371 : pcmPath;
2373 llvm::sys::fs::exists(pcmRealPath))
2375 }
2376
2377 { // scope within which diagnostics are de-activated
2378 // For now we disable diagnostics because we saw them already at
2379 // dictionary generation time. That won't be an issue with the PCMs.
2380
2381 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2382
2383#if defined(R__MUST_REVISIT)
2384#if R__MUST_REVISIT(6,2)
2385 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
2386#endif
2387#endif
2388
2391
2392 const cling::Transaction* watermark = fInterpreter->getLastTransaction();
2393 cling::Interpreter::CompilationResult compRes = fInterpreter->parseForModule(code.Data());
2394 if (isACLiC) {
2395 // Register an unload point.
2396 fMetaProcessor->registerUnloadPoint(watermark, headers[0]);
2397 }
2398
2399 assert(cling::Interpreter::kSuccess == compRes &&
2400 "Payload code of a dictionary could not be parsed correctly.");
2401 if (compRes!=cling::Interpreter::kSuccess) {
2402 Warning("TCling::RegisterModule",
2403 "Problems declaring payload for module %s.", modulename) ;
2404 }
2405 }
2406 }
2407
2408 // Now that all the header have been registered/compiled, let's
2409 // make sure to 'reset' the TClass that have a class init in this module
2410 // but already had their type information available (using information/header
2411 // loaded from other modules or from class rules or from opening a TFile
2412 // or from loading header in a way that did not provoke the loading of
2413 // the library we just loaded).
2415
2417 // __ROOTCLING__ might be pulled in through PCH
2418 fInterpreter->declare("#ifdef __ROOTCLING__\n"
2419 "#undef __ROOTCLING__\n"
2421 "#endif");
2422 }
2423
2424 if (wasDlopened) {
2426 void* dyLibHandle = fRegisterModuleDyLibs.back();
2427 fRegisterModuleDyLibs.pop_back();
2429 }
2430}
2431
2433 clang::CompilerInstance& CI = *GetInterpreterImpl()->getCI();
2434 ASTContext &C = CI.getASTContext();
2435
2436 // Do not do anything if we have no global module index.
2437 // FIXME: This is mostly to real with false positives in the TTabCom
2438 // interface for non-modules.
2439 if (!fCxxModulesEnabled)
2440 return;
2441
2442 if (IdentifierInfoLookup *External = C.Idents.getExternalIdentifierLookup()) {
2443 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2444 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2445 std::string I = Ident.str();
2446 if (!Idents.Contains(I.data()))
2447 Idents.Add(new TObjString(I.c_str()));
2448 }
2449 }
2450}
2451
2452
2453////////////////////////////////////////////////////////////////////////////////
2454/// Register classes that already existed prior to their dictionary loading
2455/// and that already had a ClassInfo (and thus would not be refresh via
2456/// UpdateClassInfo.
2457
2459{
2460 fClassesToUpdate.push_back(std::make_pair(oldcl,dict));
2461}
2462
2463////////////////////////////////////////////////////////////////////////////////
2464/// If the dictionary is loaded, we can remove the class from the list
2465/// (otherwise the class might be loaded twice).
2466
2468{
2469 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2470 iterator stop = fClassesToUpdate.end();
2471 for(iterator i = fClassesToUpdate.begin();
2472 i != stop;
2473 ++i)
2474 {
2475 if ( i->first == oldcl ) {
2476 fClassesToUpdate.erase(i);
2477 return;
2478 }
2479 }
2480}
2481
2482
2483////////////////////////////////////////////////////////////////////////////////
2484/// Let cling process a command line.
2485///
2486/// If the command is executed and the error is 0, then the return value
2487/// is the int value corresponding to the result of the executed command
2488/// (float and double return values will be truncated).
2489///
2490
2491// Method for handling the interpreter exceptions.
2492// the MetaProcessor is passing in as argument to teh function, because
2493// cling::Interpreter::CompilationResult is a nested class and it cannot be
2494// forward declared, thus this method cannot be a static member function
2495// of TCling.
2496
2497static int HandleInterpreterException(cling::MetaProcessor* metaProcessor,
2498 const char* input_line,
2499 cling::Interpreter::CompilationResult& compRes,
2500 cling::Value* result)
2501{
2502 try {
2503 return metaProcessor->process(input_line, compRes, result);
2504 }
2505 catch (cling::InterpreterException& ex)
2506 {
2507 Error("HandleInterpreterException", "%s\n%s", ex.what(), "Execution of your code was aborted.");
2508 ex.diagnose();
2509 compRes = cling::Interpreter::kFailure;
2510 }
2511 return 0;
2512}
2513
2514////////////////////////////////////////////////////////////////////////////////
2515
2516bool TCling::DiagnoseIfInterpreterException(const std::exception &e) const
2517{
2518 if (auto ie = dynamic_cast<const cling::InterpreterException*>(&e)) {
2519 ie->diagnose();
2520 return true;
2521 }
2522 return false;
2523}
2524
2525////////////////////////////////////////////////////////////////////////////////
2526
2528{
2529 // Copy the passed line, it comes from a static buffer in TApplication
2530 // which can be reentered through the Cling evaluation routines,
2531 // which would overwrite the static buffer and we would forget what we
2532 // were doing.
2533 //
2535 if (strstr(line,fantomline)) {
2536 // End-Of-Line action
2537 // See the comment (copied from above):
2538 // It is a "fantom" method to synchronize user keyboard input
2539 // and ROOT prompt line (for WIN32)
2540 // and is implemented by
2541 if (gApplication) {
2542 if (gApplication->IsCmdThread()) {
2544 gROOT->SetLineIsProcessing();
2545
2547
2548 gROOT->SetLineHasBeenProcessed();
2549 }
2550 }
2551 return 0;
2552 }
2553
2555 gGlobalMutex->Lock();
2556 if (!gInterpreterMutex)
2559 }
2561 gROOT->SetLineIsProcessing();
2562
2563 struct InterpreterFlagsRAII {
2564 cling::Interpreter* fInterpreter;
2566
2567 InterpreterFlagsRAII(cling::Interpreter* interp):
2568 fInterpreter(interp),
2569 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2570 {
2571 fInterpreter->enableDynamicLookup(true);
2572 }
2574 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2575 gROOT->SetLineHasBeenProcessed();
2576 }
2578
2579 // A non-zero returned value means the given line was
2580 // not a complete statement.
2581 int indent = 0;
2582 // This will hold the resulting value of the evaluation the given line.
2583 cling::Value result;
2584 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2585 if (!strncmp(sLine.Data(), ".L", 2) || !strncmp(sLine.Data(), ".x", 2) ||
2586 !strncmp(sLine.Data(), ".X", 2)) {
2587 // If there was a trailing "+", then CINT compiled the code above,
2588 // and we will need to strip the "+" before passing the line to cling.
2591 TString arguments;
2592 TString io;
2594 aclicMode, arguments, io);
2595 if (aclicMode.Length()) {
2596 // Remove the leading '+'
2597 R__ASSERT(aclicMode[0]=='+' && "ACLiC mode must start with a +");
2598 aclicMode[0]='k'; // We always want to keep the .so around.
2599 if (aclicMode[1]=='+') {
2600 // We have a 2nd +
2601 aclicMode[1]='f'; // We want to force the recompilation.
2602 }
2604 // ACLiC failed.
2605 compRes = cling::Interpreter::kFailure;
2606 } else {
2607 if (strncmp(sLine.Data(), ".L", 2) != 0) {
2608 // if execution was requested.
2609
2610 if (arguments.Length() == 0) {
2611 arguments = "()";
2612 }
2613 // We need to remove the extension.
2614 Ssiz_t ext = fname.Last('.');
2615 if (ext != kNPOS) {
2616 fname.Remove(ext);
2617 }
2618 const char *function = gSystem->BaseName(fname);
2619 mod_line = function + arguments + io;
2621 }
2622 }
2623 } else if (cling::DynamicLibraryManager::isSharedLibrary(fname.Data()) &&
2624 strncmp(sLine.Data(), ".L", 2) != 0) { // .x *.so or *.dll
2625 if (gSystem->Load(fname) < 0) {
2626 // Loading failed.
2627 compRes = cling::Interpreter::kFailure;
2628 } else {
2629 if (arguments.Length() == 0) {
2630 arguments = "()";
2631 }
2632 // We need to remove the extension. (*.so or *.dll)
2633 Ssiz_t ext = fname.Last('.');
2634 if (ext != kNPOS) {
2635 fname.Remove(ext);
2636 }
2637 // Now we try to find the 'main' function to run within this shared library
2638 // We distinguish two cases: a library.so with a function library(args),
2639 // or a precompiled ACLiC macro (macro_C.so) with a function macro(args).
2640 // Only in the second case, we need to strip the suffix _C or _cpp from fname.
2641 if (!gInterpreter->GetFunction(nullptr, gSystem->BaseName(fname))) { // AcLiC macro
2642 // We need to remove the automatically appended _ extension when compiling (macro_C from macro.C)
2643 ext = fname.Last('_');
2644 if (ext != kNPOS) {
2645 fname.Remove(ext);
2646 }
2647 }
2648 const char *function = gSystem->BaseName(fname);
2649 mod_line = function + arguments + io;
2651 }
2652 } else {
2653 // neither ACLiC nor run shared-library (.x)
2654 size_t unnamedMacroOpenCurly;
2655 {
2656 std::string code;
2657 std::string codeline;
2658 // Windows requires std::ifstream::binary to properly handle
2659 // CRLF and LF line endings
2660 std::ifstream in(fname, std::ifstream::binary);
2661 while (in) {
2662 std::getline(in, codeline);
2663 code += codeline + "\n";
2664 }
2666 = cling::utils::isUnnamedMacro(code, fInterpreter->getCI()->getLangOpts());
2667 }
2668
2669 fCurExecutingMacros.push_back(fname);
2670 if (unnamedMacroOpenCurly != std::string::npos) {
2671 compRes = fMetaProcessor->readInputFromFile(fname.Data(), &result,
2673 } else {
2674 // No DynLookup for .x, .L of named macros.
2675 fInterpreter->enableDynamicLookup(false);
2677 }
2678 fCurExecutingMacros.pop_back();
2679 }
2680 } // .L / .X / .x
2681 else {
2682 if (0!=strncmp(sLine.Data(), ".autodict ",10) && sLine != ".autodict") {
2683 // explicitly ignore .autodict without having to support it
2684 // in cling.
2685
2686 // Turn off autoparsing if this is an include directive
2687 bool isInclusionDirective = sLine.Contains("\n#include") || sLine.BeginsWith("#include");
2691 } else {
2693 }
2694 }
2695 }
2696 if (result.isValid())
2698 if (indent) {
2699 if (error)
2700 *error = kProcessing;
2701 return 0;
2702 }
2703 if (error) {
2704 switch (compRes) {
2705 case cling::Interpreter::kSuccess: *error = kNoError; break;
2706 case cling::Interpreter::kFailure: *error = kRecoverable; break;
2707 case cling::Interpreter::kMoreInputExpected: *error = kProcessing; break;
2708 }
2709 }
2710 if (compRes == cling::Interpreter::kSuccess
2711 && result.isValid()
2712 && !result.isVoid())
2713 {
2714 return result.castAs<Longptr_t>();
2715 }
2716 return 0;
2717}
2718
2719////////////////////////////////////////////////////////////////////////////////
2720/// No-op; see TRint instead.
2721
2723{
2724}
2725
2726////////////////////////////////////////////////////////////////////////////////
2727/// Print information about the interpreter.
2728///\param[in] option Selects the type of information to print.
2729///
2730/// List of currently support options:
2731/// - autoparsed: Print the list of classes that triggered autoparsing.
2732void TCling::Print(Option_t *option) const
2733{
2734 if (option && *option) {
2735 if (!strcmp(option, "autoparsed")) {
2736 std::cout << "Auto parsed classes:" << std::endl;
2737 for (auto & cls : fAutoParseClasses) {
2738 std::cout << " " << cls << std::endl;
2739 }
2740 } else if (!strcmp(option, "autoloaded")) {
2741 std::cout << "Auto loaded libraries:" << std::endl;
2742 for (auto & lib : fAutoLoadedLibraries) {
2743 std::cout << " " << lib << std::endl;
2744 }
2745 } else {
2746 ::Error("TCling::Print", "Unknown option '%s'", option);
2747 }
2748 } else {
2749 ::Info("TCling::Print", "No options specified");
2750 }
2751}
2752
2753
2754////////////////////////////////////////////////////////////////////////////////
2755/// \brief Add a directory to the list of directories in which the
2756/// interpreter looks for include files.
2757/// \param[in] path The path to the directory.
2758/// \note Only one path item can be specified at a time, i.e. "path1:path2" is
2759/// \b NOT supported.
2760/// \warning Only the path to the directory should be specified, without
2761/// prepending the \c -I prefix, i.e.
2762/// <tt>gCling->AddIncludePath("/path/to/my/includes")</tt>. If the
2763/// \c -I prefix is used it will be ignored.
2764void TCling::AddIncludePath(const char *path)
2765{
2767 // Favorite source of annoyance: gSystem->AddIncludePath() needs "-I",
2768 // gCling->AddIncludePath() does not! Work around that inconsistency:
2769 if (path[0] == '-' && path[1] == 'I')
2770 path += 2;
2771 TString sPath(path);
2773#ifdef _MSC_VER
2774 if (sPath.BeginsWith("/")) {
2775 char drive[3];
2776 snprintf(drive, 3, "%c:", _getdrive() + 'A' - 1);
2777 sPath.Prepend(drive);
2778 }
2779#endif
2780 fInterpreter->AddIncludePath(sPath.Data());
2781}
2782
2783////////////////////////////////////////////////////////////////////////////////
2784/// Visit all members over members, recursing over base classes.
2785
2787 const TClass* cl, Bool_t isTransient)
2788{
2789 if (insp.GetObjectValidity() == TMemberInspector::kUnset) {
2790 insp.SetObjectValidity(obj ? TMemberInspector::kValidObjectGiven
2792 }
2793
2794 if (!cl || cl->GetCollectionProxy()) {
2795 // We do not need to investigate the content of the STL
2796 // collection, they are opaque to us (and details are
2797 // uninteresting).
2798 return;
2799 }
2800
2801 static const TClassRef clRefString("std::string");
2802 if (clRefString == cl) {
2803 // We stream std::string without going through members..
2804 return;
2805 }
2806
2807 if (TClassEdit::IsStdArray(cl->GetName())) {
2808 // We treat std arrays as C arrays
2809 return;
2810 }
2811
2812 const char* cobj = (const char*) obj; // for ptr arithmetics
2813
2814 // Treat the case of std::complex in a special manner. We want to enforce
2815 // the layout of a stl implementation independent class, which is the
2816 // complex as implemented in ROOT5.
2817
2818 // A simple lambda to simplify the code
2819 auto inspInspect = [&] (ptrdiff_t offset){
2820 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_real", cobj, isTransient);
2821 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_imag", cobj + offset, isTransient);
2822 };
2823
2825 switch(complexType) {
2827 {
2828 break;
2829 }
2831 {
2832 inspInspect(sizeof(float));
2833 return;
2834 }
2836 {
2837 inspInspect(sizeof(double));
2838 return;
2839 }
2841 {
2842 inspInspect(sizeof(int));
2843 return;
2844 }
2846 {
2847 inspInspect(sizeof(long));
2848 return;
2849 }
2850 }
2851
2852 static clang::PrintingPolicy
2853 printPol(fInterpreter->getCI()->getLangOpts());
2854 if (printPol.Indentation) {
2855 // not yet initialized
2856 printPol.Indentation = 0;
2857 printPol.SuppressInitializers = true;
2858 }
2859
2860 const char* clname = cl->GetName();
2861 // Printf("Inspecting class %s\n", clname);
2862
2863 const clang::ASTContext& astContext = fInterpreter->getCI()->getASTContext();
2864 const clang::Decl *scopeDecl = nullptr;
2865 const clang::Type *recordType = nullptr;
2866
2867 if (cl->GetClassInfo()) {
2869 scopeDecl = clingCI->GetDecl();
2870 recordType = clingCI->GetType();
2871 } else {
2872 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
2873 // Diags will complain about private classes:
2874 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2875 &recordType);
2876 }
2877 if (!scopeDecl) {
2878 Error("InspectMembers", "Cannot find Decl for class %s", clname);
2879 return;
2880 }
2881 const clang::CXXRecordDecl* recordDecl
2882 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2883 if (!recordDecl) {
2884 Error("InspectMembers", "Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2885 return;
2886 }
2887
2888 {
2889 // Force possible deserializations first. We need to have no pending
2890 // Transaction when passing control flow to the inspector below (ROOT-7779).
2891 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2892
2893 astContext.getASTRecordLayout(recordDecl);
2894
2895 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2896 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2897 }
2898
2899 const clang::ASTRecordLayout& recLayout
2900 = astContext.getASTRecordLayout(recordDecl);
2901
2902 // TVirtualCollectionProxy *proxy = cl->GetCollectionProxy();
2903 // if (proxy && ( proxy->GetProperties() & TVirtualCollectionProxy::kIsEmulated ) ) {
2904 // Error("InspectMembers","The TClass for %s has an emulated proxy but we are looking at a compiled version of the collection!\n",
2905 // cl->GetName());
2906 // }
2907 if (cl->Size() != recLayout.getSize().getQuantity()) {
2908 Error("InspectMembers","TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2909 cl->GetName(),cl->Size(),(Long64_t)recLayout.getSize().getQuantity());
2910 }
2911
2912 unsigned iNField = 0;
2913 // iterate over fields
2914 // FieldDecls are non-static, else it would be a VarDecl.
2915 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2916 eField = recordDecl->field_end(); iField != eField;
2917 ++iField, ++iNField) {
2918
2919
2920 clang::QualType memberQT = iField->getType();
2921 if (recordType) {
2922 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2924 }
2925 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2926 if (memberQT.isNull()) {
2927 std::string memberName;
2928 llvm::raw_string_ostream stream(memberName);
2929 // Don't trigger fopen of the source file to count lines:
2930 printPol.AnonymousTagLocations = false;
2931 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2932 stream.flush();
2933 Error("InspectMembers",
2934 "Cannot retrieve QualType for member %s while inspecting class %s",
2935 memberName.c_str(), clname);
2936 continue; // skip member
2937 }
2938 const clang::Type* memType = memberQT.getTypePtr();
2939 if (!memType) {
2940 std::string memberName;
2941 llvm::raw_string_ostream stream(memberName);
2942 // Don't trigger fopen of the source file to count lines:
2943 printPol.AnonymousTagLocations = false;
2944 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2945 stream.flush();
2946 Error("InspectMembers",
2947 "Cannot retrieve Type for member %s while inspecting class %s",
2948 memberName.c_str(), clname);
2949 continue; // skip member
2950 }
2951
2952 const clang::Type* memNonPtrType = memType;
2953 Bool_t ispointer = false;
2954 if (memNonPtrType->isPointerType()) {
2955 ispointer = true;
2956 clang::QualType ptrQT
2957 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2958 if (recordType) {
2959 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2961 }
2962 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2963 if (ptrQT.isNull()) {
2964 std::string memberName;
2965 llvm::raw_string_ostream stream(memberName);
2966 // Don't trigger fopen of the source file to count lines:
2967 printPol.AnonymousTagLocations = false;
2968 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2969 stream.flush();
2970 Error("InspectMembers",
2971 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2972 memberName.c_str(), clname);
2973 continue; // skip member
2974 }
2975 memNonPtrType = ptrQT.getTypePtr();
2976 }
2977
2978 // assemble array size(s): "[12][4][]"
2979 llvm::SmallString<8> arraySize;
2980 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2981 unsigned arrLevel = 0;
2982 bool haveErrorDueToArray = false;
2983 while (arrType) {
2984 ++arrLevel;
2985 arraySize += '[';
2986 const clang::ConstantArrayType* constArrType =
2987 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2988 if (constArrType) {
2989 constArrType->getSize().toStringUnsigned(arraySize);
2990 }
2991 arraySize += ']';
2992 clang::QualType subArrQT = arrType->getElementType();
2993 if (subArrQT.isNull()) {
2994 std::string memberName;
2995 llvm::raw_string_ostream stream(memberName);
2996 // Don't trigger fopen of the source file to count lines:
2997 printPol.AnonymousTagLocations = false;
2998 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2999 stream.flush();
3000 Error("InspectMembers",
3001 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
3002 arrLevel, subArrQT.getAsString(printPol).c_str(),
3003 memberName.c_str(), clname);
3004 haveErrorDueToArray = true;
3005 break;
3006 }
3007 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
3008 }
3009 if (haveErrorDueToArray) {
3010 continue; // skip member
3011 }
3012
3013 // construct member name
3014 std::string fieldName;
3015 if (memType->isPointerType()) {
3016 fieldName = "*";
3017 }
3018
3019 // Check if this field has a custom ioname, if not, just use the one of the decl
3020 std::string ioname(iField->getName());
3022 fieldName += ioname;
3023 fieldName += arraySize;
3024
3025 // get member offset
3026 // NOTE currently we do not support bitfield and do not support
3027 // member that are not aligned on 'bit' boundaries.
3028 clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
3029 ptrdiff_t fieldOffset = offset.getQuantity();
3030
3031 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fBits[2]", fBits);
3032 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fName", &fName);
3033 // R__insp.InspectMember(fName, "fName.");
3034 // R__insp.Inspect(R__cl, R__insp.GetParent(), "*fClass", &fClass);
3035
3036 // If the class has a custom streamer and the type of the filed is a
3037 // private enum, struct or class, skip it.
3038 if (!insp.IsTreatingNonAccessibleTypes()){
3039 auto iFiledQtype = iField->getType();
3040 if (auto tagDecl = iFiledQtype->getAsTagDecl()){
3041 auto declAccess = tagDecl->getAccess();
3043 continue;
3044 }
3045 }
3046 }
3047
3048 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
3049
3050 if (!ispointer) {
3051 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
3052 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
3053 // nested objects get an extra call to InspectMember
3054 // R__insp.InspectMember("FileStat_t", (void*)&fFileStat, "fFileStat.", false);
3055 std::string sFieldRecName;
3058 clang::QualType(memNonPtrType,0),
3059 *fInterpreter,
3061 }
3062
3063 TDataMember* mbr = cl->GetDataMember(ioname.c_str());
3064 // if we can not find the member (which should not really happen),
3065 // let's consider it transient.
3066 Bool_t transient = isTransient || !mbr || !mbr->IsPersistent();
3067 if (!mbr || !mbr->IsPersistent())
3068 insp.IncrementNestedTransient();
3069 insp.InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
3070 (fieldName + '.').c_str(), transient);
3071 if (!mbr || !mbr->IsPersistent())
3072 insp.DecrementNestedTransient();
3073
3074 }
3075 }
3076 } // loop over fields
3077
3078 // inspect bases
3079 // TNamed::ShowMembers(R__insp);
3080 unsigned iNBase = 0;
3081 for (clang::CXXRecordDecl::base_class_const_iterator iBase
3082 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
3083 iBase != eBase; ++iBase, ++iNBase) {
3084 clang::QualType baseQT = iBase->getType();
3085 if (baseQT.isNull()) {
3086 Error("InspectMembers",
3087 "Cannot find QualType for base number %d while inspecting class %s",
3088 iNBase, clname);
3089 continue;
3090 }
3091 const clang::CXXRecordDecl* baseDecl
3092 = baseQT->getAsCXXRecordDecl();
3093 if (!baseDecl) {
3094 Error("InspectMembers",
3095 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
3096 iNBase, clname);
3097 continue;
3098 }
3099 TClass* baseCl=nullptr;
3100 std::string sBaseName;
3101 // Try with the DeclId
3102 std::vector<TClass*> foundClasses;
3104 if (foundClasses.size()==1){
3106 } else {
3107 // Try with the normalised Name, as a fallback
3108 if (!baseCl){
3110 baseQT,
3111 *fInterpreter,
3114 }
3115 }
3116
3117 if (!baseCl){
3118 std::string qualNameForDiag;
3120 Error("InspectMembers",
3121 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
3122 continue;
3123 }
3124
3125 int64_t baseOffset;
3126 if (iBase->isVirtual()) {
3127 if (insp.GetObjectValidity() == TMemberInspector::kNoObjectGiven) {
3128 if (!isTransient) {
3129 Error("InspectMembers",
3130 "Base %s of class %s is virtual but no object provided",
3131 sBaseName.c_str(), clname);
3132 }
3134 } else {
3135 // We have an object to determine the vbase offset.
3137 TClingClassInfo* baseCi = (TClingClassInfo*)baseCl->GetClassInfo();
3138 if (ci && baseCi) {
3139 baseOffset = ci->GetBaseOffset(baseCi, const_cast<void*>(obj),
3140 true /*isDerivedObj*/);
3141 if (baseOffset == -1) {
3142 Error("InspectMembers",
3143 "Error calculating offset of virtual base %s of class %s",
3144 sBaseName.c_str(), clname);
3145 }
3146 } else {
3147 Error("InspectMembers",
3148 "Cannot calculate offset of virtual base %s of class %s",
3149 sBaseName.c_str(), clname);
3150 continue;
3151 }
3152 }
3153 } else {
3154 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3155 }
3156 // TOFIX: baseCl can be null here!
3157 if (baseCl->IsLoaded()) {
3158 // For loaded class, CallShowMember will (especially for TObject)
3159 // call the virtual ShowMember rather than the class specific version
3160 // resulting in an infinite recursion.
3162 } else {
3163 baseCl->CallShowMembers(cobj + baseOffset,
3164 insp, isTransient);
3165 }
3166 } // loop over bases
3167}
3168
3169////////////////////////////////////////////////////////////////////////////////
3170/// Check if constructor exited correctly, ie the instance is in a valid state
3171/// \return true if there is a compiler instance available, false otherwise
3173{
3174 return fInterpreter->getCI() != nullptr;
3175}
3176
3177////////////////////////////////////////////////////////////////////////////////
3178/// Reset the interpreter internal state in case a previous action was not correctly
3179/// terminated.
3180
3182{
3183 // No-op there is not equivalent state (to be cleared) in Cling.
3184}
3185
3186////////////////////////////////////////////////////////////////////////////////
3187/// Delete existing temporary values.
3188
3190{
3191 // No-op for cling due to cling::Value.
3192}
3193
3194namespace {
3195 // Re-enable JIT symbol library autoloading (independently of class/dictionary
3196 // autoloading) for the lifetime of the object. See its use in TCling::Declare
3197 // and #16601.
3198 class EnableAutoLoadingForJITSymbolsRAII {
3199 TClingCallbacks *fCallbacks;
3200 bool fOldValue = false;
3201
3202 public:
3203 EnableAutoLoadingForJITSymbolsRAII(TClingCallbacks *callbacks) : fCallbacks(callbacks)
3204 {
3205 if (fCallbacks) {
3206 fOldValue = fCallbacks->IsAutoLoadingForJITSymbols();
3207 fCallbacks->SetAutoLoadingForJITSymbols(true);
3208 }
3209 }
3211 {
3212 if (fCallbacks)
3213 fCallbacks->SetAutoLoadingForJITSymbols(fOldValue);
3214 }
3215 };
3216}
3217
3218////////////////////////////////////////////////////////////////////////////////
3219/// Declare code to the interpreter, without any of the interpreter actions
3220/// that could trigger a re-interpretation of the code. I.e. make cling
3221/// behave like a compiler: no dynamic lookup, no input wrapping for
3222/// subsequent execution, no automatic provision of declarations but just a
3223/// plain `#include`.
3224/// Returns true on success, false on failure.
3225
3226bool TCling::Declare(const char* code)
3227{
3229
3232
3233 // The suspensions above make parsing behave like a plain compiler, but they also
3234 // gate the JIT's library autoloading - and a declared global's static initializer
3235 // may still need symbols from a not-yet-loaded library (e.g. TVectorT<float> from
3236 // libMatrix). Re-allow autoloading for such genuine JIT symbol resolution. #16601
3237 EnableAutoLoadingForJITSymbolsRAII autoLoadJITOn(fClingCallbacks);
3238
3239 bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
3240 fInterpreter->enableDynamicLookup(false);
3241 bool oldRawInput = fInterpreter->isRawInputEnabled();
3242 fInterpreter->enableRawInput(true);
3243
3244 Bool_t ret = LoadText(code);
3245
3246 fInterpreter->enableRawInput(oldRawInput);
3247 fInterpreter->enableDynamicLookup(oldDynLookup);
3248 return ret;
3249}
3250
3251////////////////////////////////////////////////////////////////////////////////
3252/// It calls a "fantom" method to synchronize user keyboard input
3253/// and ROOT prompt line.
3254
3259
3260// This static function is a hop of TCling::IsLibraryLoaded, which is taking a lock and calling
3261// into this function. This is because we wanted to avoid a duplication in TCling::IsLoaded, which
3262// was already taking a lock.
3263static Bool_t s_IsLibraryLoaded(const char* libname, cling::Interpreter* fInterpreter)
3264{
3265 // Check shared library.
3268 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.Data());
3269 return false;
3270}
3271
3277
3278////////////////////////////////////////////////////////////////////////////////
3279/// Return true if ROOT has cxxmodules pcm for a given library name.
3280// FIXME: We need to be able to support lazy loading of pcm generated by ACLiC.
3282{
3283 llvm::StringRef ModuleName(libname);
3284 ModuleName = llvm::sys::path::stem(ModuleName);
3285 ModuleName.consume_front("lib");
3286
3287 // FIXME: In case when the modulemap is not yet loaded we will return the
3288 // wrong result. Consider a call to HasPCMForLibrary(../test/libEvent.so)
3289 // We will only load the modulemap for libEvent.so after we dlopen libEvent
3290 // which may happen after calling this interface. Maybe we should also check
3291 // if there is a Event.pcm file and a module.modulemap, load it and return
3292 // true.
3293 clang::ModuleMap &moduleMap = fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3294 clang::Module *M = moduleMap.findModule(ModuleName);
3295 return M && !M->IsUnimportable && M->getASTFile();
3296}
3297
3298////////////////////////////////////////////////////////////////////////////////
3299/// Return true if the file has already been loaded by cint.
3300/// We will try in this order:
3301/// actual filename
3302/// filename as a path relative to
3303/// the include path
3304/// the shared library path
3305
3307{
3309
3310 //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
3311 // cling::DynamicLibraryManager.
3312
3313 std::string file_name = filename;
3314 size_t at = std::string::npos;
3315 while ((at = file_name.find("/./")) != std::string::npos)
3316 file_name.replace(at, 3, "/");
3317
3318 std::string filesStr = "";
3319 llvm::raw_string_ostream filesOS(filesStr);
3320 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3321 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3322 filesOS.flush();
3323
3324 llvm::SmallVector<llvm::StringRef, 100> files;
3325 llvm::StringRef(filesStr).split(files, "\n");
3326
3327 std::set<std::string> fileMap;
3328 llvm::StringRef file_name_ref(file_name);
3329 // Fill fileMap; return early on exact match.
3331 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3332 if ((*iF) == file_name_ref) return kTRUE; // exact match
3333 fileMap.insert(iF->str());
3334 }
3335
3336 if (fileMap.empty()) return kFALSE;
3337
3338 // Check MacroPath.
3339 TString sFilename(file_name.c_str());
3341 && fileMap.count(sFilename.Data())) {
3342 return kTRUE;
3343 }
3344
3345 // Check IncludePath.
3346 TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
3347 incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
3348 incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
3349 while (incPath.Index(" :") != -1) {
3350 incPath.ReplaceAll(" :", ":");
3351 }
3352 incPath.Prepend(".:");
3353 sFilename = file_name.c_str();
3355 && fileMap.count(sFilename.Data())) {
3356 return kTRUE;
3357 }
3358
3359 // Check shared library.
3360 if (s_IsLibraryLoaded(file_name.c_str(), GetInterpreterImpl()))
3361 return kTRUE;
3362
3363 //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
3364 clang::ConstSearchDirIterator *CurDir = nullptr;
3365 clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
3366 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3367 auto FE = HS.LookupFile(file_name.c_str(),
3368 clang::SourceLocation(),
3369 /*isAngled*/ false,
3370 /*FromDir*/ nullptr, CurDir,
3371 clang::ArrayRef<std::pair<clang::OptionalFileEntryRef,
3372 clang::DirectoryEntryRef>>(),
3373 /*SearchPath*/ nullptr,
3374 /*RelativePath*/ nullptr,
3375 /*RequestingModule*/ nullptr,
3376 /*SuggestedModule*/ nullptr,
3377 /*IsMapped*/ nullptr,
3378 /*IsFrameworkFound*/ nullptr,
3379 /*SkipCache*/ false,
3380 /*BuildSystemModule*/ false,
3381 /*OpenFile*/ false,
3382 /*CacheFail*/ false);
3383 if (FE) {
3384 // check in the source manager if the file is actually loaded
3385 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3386 // this works only with header (and source) files...
3387 clang::FileID FID = SM.translateFile(*FE);
3388 if (!FID.isInvalid() && FID.getHashValue() == 0)
3389 return kFALSE;
3390 else {
3391 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3392 if (SLocE.isFile() && !SLocE.getFile().getContentCache().getBufferIfLoaded())
3393 return kFALSE;
3394 if (!FID.isInvalid())
3395 return kTRUE;
3396 }
3397 // ...then check shared library again, but with full path now
3398 sFilename = FE->getName().str();
3400 && fileMap.count(sFilename.Data())) {
3401 return kTRUE;
3402 }
3403 }
3404 return kFALSE;
3405}
3406
3407
3408#if defined(R__MACOSX)
3409
3410////////////////////////////////////////////////////////////////////////////////
3411/// Check if lib is in the dynamic linker cache, returns true if it is, and if so,
3412/// modifies the library file name parameter `lib` from `/usr/lib/libFOO.dylib`
3413/// to `-lFOO` such that it can be passed to the linker.
3414/// This is a unique feature of macOS 11.
3415
3416static bool R__UpdateLibFileForLinking(TString &lib)
3417{
3418 const char *mapfile = nullptr;
3419#if __x86_64__
3420 mapfile = "/System/Library/dyld/dyld_shared_cache_x86_64.map";
3421#elif __arm64__
3422 mapfile = "/System/Library/dyld/dyld_shared_cache_arm64e.map";
3423#else
3424 #error unsupported architecture
3425#endif
3426 if (std::ifstream cacheMap{mapfile}) {
3427 std::string line;
3428 while (getline(cacheMap, line)) {
3429 if (line.find(lib) != std::string::npos) {
3430 lib.ReplaceAll("/usr/lib/lib","-l");
3431 lib.ReplaceAll(".dylib","");
3432 return true;
3433 }
3434 }
3435 return false;
3436 }
3437 return false;
3438}
3439#endif // R__MACOSX
3440
3441#if defined (R__LINUX) || defined (R__FBSD)
3442
3443////////////////////////////////////////////////////////////////////////////////
3444/// Callback for dl_iterate_phdr(), see `man dl_iterate_phdr`.
3445/// Collects opened libraries.
3446
3447static int callback_for_dl_iterate_phdr(struct dl_phdr_info *info, size_t size, void *data)
3448{
3449 // This function is called through UpdateListOfLoadedSharedLibraries() which is locked.
3450 static std::unordered_set<decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3451
3452 auto newLibs = static_cast<std::vector<std::string>*>(data);
3453 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3454 // Skip \0, "", and kernel pseudo-libs linux-vdso.so.1 or linux-gate.so.1
3455 if (info->dlpi_name && info->dlpi_name[0]
3456#if defined(R__FBSD)
3457 //skip the executable (with null addr)
3458 && info->dlpi_addr
3459 //has no path
3460 && strncmp(info->dlpi_name, "[vdso]", 6)
3461 //the linker does not like to be mmapped
3462 //causes a crash in cling::DynamicLibraryManager::loadLibrary())
3463 //with error message "mmap of entire address space failed: Cannot allocate memory"
3464 && strncmp(info->dlpi_name, "/libexec/ld-elf.so.1", 20)
3465#endif
3466 && strncmp(info->dlpi_name, "linux-vdso.so", 13)
3467 && strncmp(info->dlpi_name, "linux-vdso32.so", 15)
3468 && strncmp(info->dlpi_name, "linux-vdso64.so", 15)
3469 && strncmp(info->dlpi_name, "linux-gate.so", 13))
3470 newLibs->emplace_back(info->dlpi_name);
3471 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3472 }
3473 // No matter what the doc says, return != 0 means "stop the iteration".
3474 return 0;
3475}
3476
3477#endif // R__LINUX || R__FBSD
3478
3479
3480////////////////////////////////////////////////////////////////////////////////
3481
3483{
3484#if defined(R__WIN32) || defined(__CYGWIN__)
3485 HMODULE hModules[1024];
3486 void *hProcess;
3487 unsigned long cbModules;
3488 unsigned int i;
3489 hProcess = (void *)::GetCurrentProcess();
3491 // start at 1 to skip the executable itself
3492 for (i = 1; i < (cbModules / sizeof(void *)); i++) {
3493 static const int bufsize = 260;
3494 wchar_t winname[bufsize];
3495 char posixname[bufsize];
3497#if defined(__CYGWIN__)
3499#else
3500 std::wstring wpath = winname;
3501 std::replace(wpath.begin(), wpath.end(), '\\', '/');
3502 string path(wpath.begin(), wpath.end());
3503 strncpy(posixname, path.c_str(), bufsize);
3504#endif
3507 }
3508 }
3509#elif defined(R__MACOSX)
3510 // fPrevLoadedDynLibInfo stores the *next* image index to look at
3511 uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
3512
3514 // Skip non-dylibs
3515 if (mh->filetype == MH_DYLIB) {
3516 if (const char* imageName = _dyld_get_image_name(imageIndex)) {
3518 }
3519 }
3520
3521 ++imageIndex;
3522 }
3523 fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
3524#elif defined(R__LINUX) || defined(R__FBSD)
3525 // fPrevLoadedDynLibInfo is unused on Linux.
3526 (void) fPrevLoadedDynLibInfo;
3527
3528 std::vector<std::string> newLibs;
3530 for (auto &&lib: newLibs)
3531 RegisterLoadedSharedLibrary(lib.c_str());
3532#else
3533 Error("TCling::UpdateListOfLoadedSharedLibraries",
3534 "Platform not supported!");
3535#endif
3536}
3537
3538namespace {
3539template <int N>
3540static bool StartsWithStrLit(const char *haystack, const char (&needle)[N]) {
3541 return !strncmp(haystack, needle, N - 1);
3542}
3543}
3544
3545////////////////////////////////////////////////////////////////////////////////
3546/// Register that a library was autoloaded either to provide a 'missing' symbol
3547/// or to provide a class (see TClass::GetClass and TROOT::LoadClass).
3549{
3551}
3552
3553////////////////////////////////////////////////////////////////////////////////
3554/// Register a new shared library name with the interpreter; add it to
3555/// fSharedLibs.
3556
3558{
3559 // Ignore NULL filenames, aka "the process".
3560 if (!filename) return;
3561
3562 // Tell the interpreter that this library is available; all libraries can be
3563 // used to resolve symbols.
3564 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3565 if (!DLM->isLibraryLoaded(filename)) {
3566 DLM->loadLibrary(filename, true /*permanent*/, true /*resolved*/);
3567 }
3568
3569#if defined(R__MACOSX)
3570 // Check that this is not a system library that does not exist on disk.
3571 auto lenFilename = strlen(filename);
3572 auto isInMacOSSystemDir = [](const char *fn) {
3573 return StartsWithStrLit(fn, "/usr/lib/") || StartsWithStrLit(fn, "/System/Library/");
3574 };
3575 if (!strcmp(filename, "cl_kernels") // yepp, no directory
3576
3577 // These we should not link with (e.g. because they forward to .tbd):
3578 || StartsWithStrLit(filename, "/usr/lib/system/")
3579 || StartsWithStrLit(filename, "/usr/lib/libc++")
3580 || StartsWithStrLit(filename, "/System/Library/Frameworks/")
3581 || StartsWithStrLit(filename, "/System/Library/PrivateFrameworks/")
3582 || StartsWithStrLit(filename, "/System/Library/CoreServices/")
3583 || StartsWithStrLit(filename, "/usr/lib/libSystem")
3584 || StartsWithStrLit(filename, "/usr/lib/libstdc++")
3585 || StartsWithStrLit(filename, "/usr/lib/libicucore")
3586 || StartsWithStrLit(filename, "/usr/lib/libbsm")
3587 || StartsWithStrLit(filename, "/usr/lib/libobjc")
3588 || StartsWithStrLit(filename, "/usr/lib/libresolv")
3589 || StartsWithStrLit(filename, "/usr/lib/libauto")
3590 || StartsWithStrLit(filename, "/usr/lib/libcups")
3591 || StartsWithStrLit(filename, "/usr/lib/libDiagnosticMessagesClient")
3592 || StartsWithStrLit(filename, "/usr/lib/liblangid")
3593 || StartsWithStrLit(filename, "/usr/lib/libCRFSuite")
3594 || StartsWithStrLit(filename, "/usr/lib/libpam")
3595 || StartsWithStrLit(filename, "/usr/lib/libOpenScriptingUtil")
3596 || StartsWithStrLit(filename, "/usr/lib/libextension")
3597 || StartsWithStrLit(filename, "/usr/lib/libAudioToolboxUtility")
3598 || StartsWithStrLit(filename, "/usr/lib/liboah")
3599 || StartsWithStrLit(filename, "/usr/lib/libRosetta")
3600 || StartsWithStrLit(filename, "/usr/lib/libCoreEntitlements")
3601 || StartsWithStrLit(filename, "/usr/lib/libssl.")
3602 || StartsWithStrLit(filename, "/usr/lib/libcrypto.")
3603
3604 // The system lib is likely in macOS's blob.
3606
3607 // "Link against the umbrella framework 'System.framework' instead"
3608 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_kernel")
3609 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_platform")
3610 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_pthread")
3611
3612 // "cannot link directly with dylib/framework, your binary is not an allowed client of
3613 // /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/
3614 // SDKs/MacOSX.sdk/usr/lib/libAudioToolboxUtility.tbd for architecture x86_64
3615 || (lenFilename > 4 && !strcmp(filename + lenFilename - 4, ".tbd")))
3616 return;
3619 filename = sFileName.Data();
3620#elif defined(__CYGWIN__)
3621 // Check that this is not a system library
3622 static const int bufsize = 260;
3623 char posixwindir[bufsize];
3624 char *windir = std::getenv("WINDIR");
3625 if (windir)
3627 else
3628 snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
3629 if (strstr(filename, posixwindir) ||
3630 strstr(filename, "/usr/bin/cyg"))
3631 return;
3632#elif defined(R__WIN32)
3633 if (strstr(filename, "/Windows/"))
3634 return;
3635#elif defined (R__LINUX)
3636 if (strstr(filename, "/ld-linux")
3637 || strstr(filename, "linux-gnu/")
3638 || strstr(filename, "/libstdc++.")
3639 || strstr(filename, "/libgcc")
3640 || strstr(filename, "/libc.")
3641 || strstr(filename, "/libdl.")
3642 || strstr(filename, "/libm."))
3643 return;
3644#endif
3645 // Update string of available libraries.
3646 if (!fSharedLibs.IsNull()) {
3647 fSharedLibs.Append(" ");
3648 }
3650}
3651
3652////////////////////////////////////////////////////////////////////////////////
3653/// Load a library file in cling's memory.
3654/// if 'system' is true, the library is never unloaded.
3655/// Return 0 on success, -1 on failure.
3656
3658{
3659 assert(!IsFromRootCling() && "Trying to load library from rootcling!");
3660
3661 // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
3663 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3664 std::string canonLib = DLM->lookupLibrary(filename);
3665 cling::DynamicLibraryManager::LoadLibResult res
3666 = cling::DynamicLibraryManager::kLoadLibNotFound;
3667 if (!canonLib.empty()) {
3668 if (system)
3669 res = DLM->loadLibrary(filename, system, true);
3670 else {
3671 // For the non system libs, we'd like to be able to unload them.
3672 // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
3673 cling::Interpreter::CompilationResult compRes;
3674 HandleInterpreterException(GetMetaProcessorImpl(), Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/nullptr);
3675 if (compRes == cling::Interpreter::kSuccess)
3676 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3677 }
3678 }
3679
3680 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3682 }
3683 switch (res) {
3684 case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
3685 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
3686 default: break;
3687 };
3688 return -1;
3689}
3690
3691////////////////////////////////////////////////////////////////////////////////
3692/// Load a macro file in cling's memory.
3693
3694void TCling::LoadMacro(const char* filename, EErrorCode* error)
3695{
3696 ProcessLine(Form(".L %s", filename), error);
3697}
3698
3699////////////////////////////////////////////////////////////////////////////////
3700/// Let cling process a command line asynch.
3701
3703{
3704 return ProcessLine(line, error);
3705}
3706
3707////////////////////////////////////////////////////////////////////////////////
3708/// Let cling process a command line synchronously, i.e we are waiting
3709/// it will be finished.
3710
3712{
3714 if (gApplication) {
3715 if (gApplication->IsCmdThread()) {
3716 return ProcessLine(line, error);
3717 }
3718 return 0;
3719 }
3720 return ProcessLine(line, error);
3721}
3722
3723////////////////////////////////////////////////////////////////////////////////
3724/// Directly execute an executable statement (e.g. "func()", "3+5", etc.
3725/// however not declarations, like "Int_t x;").
3726
3728{
3729#ifdef R__WIN32
3730 // Test on ApplicationImp not being 0 is needed because only at end of
3731 // TApplication ctor the IsLineProcessing flag is set to 0, so before
3732 // we can not use it.
3734 while (gROOT->IsLineProcessing() && !gApplication) {
3735 Warning("Calc", "waiting for cling thread to free");
3736 gSystem->Sleep(500);
3737 }
3738 gROOT->SetLineIsProcessing();
3739 }
3740#endif // R__WIN32
3742 if (error) {
3743 *error = TInterpreter::kNoError;
3744 }
3745 cling::Value valRef;
3746 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3747 try {
3748 cr = fInterpreter->evaluate(line, valRef);
3749 }
3750 catch (cling::InterpreterException& ex)
3751 {
3752 Error("Calc", "%s.\n%s", ex.what(), "Evaluation of your expression was aborted.");
3753 ex.diagnose();
3754 cr = cling::Interpreter::kFailure;
3755 }
3756
3757 if (cr != cling::Interpreter::kSuccess) {
3758 // Failure in compilation.
3759 if (error) {
3760 // Note: Yes these codes are weird.
3762 }
3763 return 0L;
3764 }
3765 if (!valRef.isValid()) {
3766 // Failure at runtime.
3767 if (error) {
3768 // Note: Yes these codes are weird.
3769 *error = TInterpreter::kDangerous;
3770 }
3771 return 0L;
3772 }
3773
3774 if (valRef.isVoid()) {
3775 return 0;
3776 }
3777
3779#ifdef R__WIN32
3781 gROOT->SetLineHasBeenProcessed();
3782 }
3783#endif // R__WIN32
3784 return valRef.castAs<Longptr_t>();
3785}
3786
3787////////////////////////////////////////////////////////////////////////////////
3788/// Set a getline function to call when input is needed.
3789
3790void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
3791 void (*histaddFunc)(const char* line))
3792{
3793 // If cling offers a replacement for G__pause(), it would need to
3794 // also offer a way to customize at least the history recording.
3795
3796#if defined(R__MUST_REVISIT)
3797#if R__MUST_REVISIT(6,2)
3798 Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3799#endif
3800#endif
3801}
3802
3803////////////////////////////////////////////////////////////////////////////////
3804/// Helper function to increase the internal Cling count of transactions
3805/// that change the AST.
3806
3807Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
3808{
3810
3811 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3812 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3813 || T.macros_begin() != T.macros_end()
3814 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3816 return true;
3817 }
3818 return false;
3819}
3820
3821////////////////////////////////////////////////////////////////////////////////
3822/// Delete object from cling symbol table so it can not be used anymore.
3823/// cling objects are always on the heap.
3824
3826{
3827 // NOTE: When replacing the mutex by a ReadWrite mutex, we **must**
3828 // put in place the Read/Write part here. Keeping the write lock
3829 // here is 'catasptrophic' for scaling as it means that ALL calls
3830 // to RecursiveRemove will take the write lock and performance
3831 // of many threads trying to access the write lock at the same
3832 // time is relatively bad.
3834 // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
3835 // (but isn't at the moment).
3836 if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
3837 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
3838 if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
3840 DeleteGlobal(obj);
3841 ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
3842 }
3843 }
3844}
3845
3846////////////////////////////////////////////////////////////////////////////////
3847/// Pressing Ctrl+C should forward here. In the case where we have had
3848/// continuation requested we must reset it.
3849
3851{
3852 fMetaProcessor->cancelContinuation();
3853 // Reset the Cling state to the state saved by the last call to
3854 // TCling::SaveContext().
3855#if defined(R__MUST_REVISIT)
3856#if R__MUST_REVISIT(6,2)
3858 Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3859#endif
3860#endif
3861}
3862
3863////////////////////////////////////////////////////////////////////////////////
3864/// Reset the Cling state to its initial state.
3865
3867{
3868#if defined(R__MUST_REVISIT)
3869#if R__MUST_REVISIT(6,2)
3871 Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3872#endif
3873#endif
3874}
3875
3876////////////////////////////////////////////////////////////////////////////////
3877/// Reset in Cling the list of global variables to the state saved by the last
3878/// call to TCling::SaveGlobalsContext().
3879///
3880/// Note: Right now, all we do is run the global destructors.
3881
3883{
3885 // TODO:
3886 // Here we should iterate over the transactions (N-3) and revert.
3887 // N-3 because the first three internal to cling.
3888
3889 fInterpreter->runAndRemoveStaticDestructors();
3890}
3891
3892////////////////////////////////////////////////////////////////////////////////
3893/// Reset the Cling 'user' global objects/variables state to the state saved by the last
3894/// call to TCling::SaveGlobalsContext().
3895
3897{
3898#if defined(R__MUST_REVISIT)
3899#if R__MUST_REVISIT(6,2)
3901 Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3902#endif
3903#endif
3904}
3905
3906////////////////////////////////////////////////////////////////////////////////
3907/// Rewind Cling dictionary to the point where it was before executing
3908/// the current macro. This function is typically called after SEGV or
3909/// ctlr-C after doing a longjmp back to the prompt.
3910
3912{
3913#if defined(R__MUST_REVISIT)
3914#if R__MUST_REVISIT(6,2)
3916 Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3917#endif
3918#endif
3919}
3920
3921////////////////////////////////////////////////////////////////////////////////
3922/// Delete obj from Cling symbol table so it cannot be accessed anymore.
3923/// Returns 1 in case of success and 0 in case object was not in table.
3924
3926{
3927#if defined(R__MUST_REVISIT)
3928#if R__MUST_REVISIT(6,2)
3930 Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3931#endif
3932#endif
3933 return 0;
3934}
3935
3936////////////////////////////////////////////////////////////////////////////////
3937/// Undeclare obj called name.
3938/// Returns 1 in case of success, 0 for failure.
3939
3941{
3942#if defined(R__MUST_REVISIT)
3943#if R__MUST_REVISIT(6,2)
3944 Warning("DeleteVariable","should do more that just reseting the value to zero");
3945#endif
3946#endif
3947
3949 llvm::StringRef srName(name);
3950 const char* unscopedName = name;
3951 llvm::StringRef::size_type posScope = srName.rfind("::");
3952 const clang::DeclContext* declCtx = nullptr;
3953 if (posScope != llvm::StringRef::npos) {
3954 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3955 const clang::Decl* scopeDecl
3956 = lh.findScope(srName.substr(0, posScope),
3957 cling::LookupHelper::WithDiagnostics);
3958 if (!scopeDecl) {
3959 Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3960 name);
3961 return 0;
3962 }
3963 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3964 if (!declCtx) {
3965 Error("DeleteVariable",
3966 "Enclosing scope for variable %s is not a declaration context",
3967 name);
3968 return 0;
3969 }
3970 unscopedName += posScope + 2;
3971 }
3972 // Could trigger deserialization of decls.
3973 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
3974 clang::NamedDecl* nVarDecl
3975 = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3976 if (!nVarDecl) {
3977 Error("DeleteVariable", "Unknown variable %s", name);
3978 return 0;
3979 }
3980 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3981 if (!varDecl) {
3982 Error("DeleteVariable", "Entity %s is not a variable", name);
3983 return 0;
3984 }
3985
3986 clang::QualType qType = varDecl->getType();
3987 const clang::Type* type = qType->getUnqualifiedDesugaredType();
3988 // Cannot set a reference's address to nullptr; the JIT can place it
3989 // into read-only memory (ROOT-7100).
3990 if (type->isPointerType()) {
3991 int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3992 // set pointer to invalid.
3993 if (ppInt) *ppInt = nullptr;
3994 }
3995 return 1;
3996}
3997
3998////////////////////////////////////////////////////////////////////////////////
3999/// Save the current Cling state.
4000
4002{
4003#if defined(R__MUST_REVISIT)
4004#if R__MUST_REVISIT(6,2)
4006 Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
4007#endif
4008#endif
4009}
4010
4011////////////////////////////////////////////////////////////////////////////////
4012/// Save the current Cling state of global objects.
4013
4015{
4016#if defined(R__MUST_REVISIT)
4017#if R__MUST_REVISIT(6,2)
4019 Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
4020#endif
4021#endif
4022}
4023
4024////////////////////////////////////////////////////////////////////////////////
4025/// No op: see TClingCallbacks (used to update the list of globals)
4026
4030
4031////////////////////////////////////////////////////////////////////////////////
4032/// No op: see TClingCallbacks (used to update the list of global functions)
4033
4037
4038////////////////////////////////////////////////////////////////////////////////
4039/// No op: see TClingCallbacks (used to update the list of types)
4040
4042{
4043}
4044
4045////////////////////////////////////////////////////////////////////////////////
4046/// Check in what order the member of a tuple are layout.
4047enum class ETupleOrdering {
4048 kAscending,
4051};
4052
4058
4064
4066{
4067 std::tuple<int,double> value;
4070
4071 size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
4072 size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
4073
4074 size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
4075 size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
4076
4077 size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
4078 size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
4079
4080 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
4082 } else if (offset0 == desOffset0 && offset1 == desOffset1) {
4084 } else {
4086 }
4087}
4088
4089static std::string AlternateTuple(const char *classname, const cling::LookupHelper& lh, Bool_t silent)
4090{
4092 std::string alternateName = "TEmulatedTuple";
4093 alternateName.append( classname + 5 );
4094
4095 std::string fullname = "ROOT::Internal::" + alternateName;
4096 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
4097 /*resultType*/nullptr, /* intantiateTemplate= */ false))
4098 return fullname;
4099
4100 {
4101 // Check if we can produce the tuple
4102 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4103 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4104 auto deleter = [](TypeInfo_t *type) {
4105 gInterpreter->TypeInfo_Delete(type);
4106 };
4107 std::unique_ptr<TypeInfo_t, decltype(deleter)> type{ gInterpreter->TypeInfo_Factory(), deleter };
4108 while (iter != theEnd) {
4109 gInterpreter->TypeInfo_Init(type.get(), iter->c_str());
4110 if (gInterpreter->TypeInfo_Property(type.get()) & kIsNotReacheable) {
4111 if (!silent)
4112 Error("Load","Could not declare alternate type for %s since %s (or one of its context) is private or protected",
4113 classname, iter->c_str());
4114 return "";
4115 }
4116 ++iter;
4117 }
4118 }
4119
4120 std::string guard_name;
4122 std::ostringstream guard;
4123 guard << "ROOT_INTERNAL_TEmulated_";
4124 guard << guard_name;
4125
4126 std::ostringstream alternateTuple;
4127 std::ostringstream initializers;
4128
4129 alternateTuple << "#ifndef " << guard.str() << "\n";
4130 alternateTuple << "#define " << guard.str() << "\n";
4131 alternateTuple << "namespace ROOT { namespace Internal {\n";
4132 alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
4133 alternateTuple << "template <> struct " << alternateName << " {\n";
4134
4135 // This could also be a compile time choice ...
4136 switch(IsTupleAscending()) {
4138 unsigned int nMember = 0;
4139 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4140 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4141 auto sep = ':';
4142 while (iter != theEnd) {
4143 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4144 initializers << " " << sep << " _" << nMember << "(std::get<" << nMember << ">(std::forward<Tuple>(t)))\n";
4145 ++iter;
4146 ++nMember;
4147 sep = ',';
4148 }
4149 break;
4150 }
4152 unsigned int nMember = tupleContent.fElements.size() - 3;
4153 auto iter = tupleContent.fElements.rbegin() + 1; // skip the 'stars'.
4154 auto theEnd = tupleContent.fElements.rend() - 1; // Skip the template name (tuple).
4155 auto sep = ':';
4156 while (iter != theEnd) {
4157 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4158 initializers << " " << sep << " _" << nMember << "(std::get<" << nMember << ">(std::forward<Tuple>(t)))\n";
4159 ++iter;
4160 --nMember;
4161 sep = ',';
4162 }
4163 break;
4164 }
4166 Fatal("TCling::SetClassInfo::AlternateTuple",
4167 "Layout of std::tuple on this platform is unexpected.");
4168 break;
4169 }
4170 }
4171
4172 // default constructor
4173 alternateTuple << " TEmulatedTuple() = default;\n";
4174
4175 // constructor from other tuple-like types, like std::tuple
4176 alternateTuple << " template <typename Tuple>\n";
4177 alternateTuple << " TEmulatedTuple(Tuple&& t)\n";
4179 alternateTuple << " {}\n";
4180
4181 alternateTuple << "};\n";
4182 alternateTuple << "}}\n";
4183 alternateTuple << "#endif\n";
4184 if (!gCling->Declare(alternateTuple.str().c_str()))
4185 {
4186 // Declare is not silent (yet?), so add an explicit error message
4187 // to indicate the consequence of the syntax errors.
4188 Error("Load","Could not declare %s",alternateName.c_str());
4189 return "";
4190 }
4191 alternateName = "ROOT::Internal::" + alternateName;
4192 return alternateName;
4193}
4194
4195////////////////////////////////////////////////////////////////////////////////
4196/// Set pointer to the TClingClassInfo in TClass.
4197/// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
4198/// already have one.
4199
4201{
4202 // We are shutting down, there is no point in reloading, it only triggers
4203 // redundant deserializations.
4204 if (fIsShuttingDown) {
4205 // Remove the decl_id from the DeclIdToTClass map
4206 if (cl->fClassInfo) {
4209 // Test again as another thread may have set fClassInfo to nullptr.
4210 if (TClinginfo) {
4212 }
4213 delete TClinginfo;
4214 cl->fClassInfo = nullptr;
4215 }
4216 return;
4217 }
4218
4220 if (cl->fClassInfo && !reload) {
4221 return;
4222 }
4223 //Remove the decl_id from the DeclIdToTClass map
4225 if (TClinginfo) {
4227 }
4228 delete TClinginfo;
4229 cl->fClassInfo = nullptr;
4230 std::string name(cl->GetName());
4231
4232 auto SetWithoutClassInfoState = [](TClass *cl)
4233 {
4234 if (cl->fState != TClass::kHasTClassInit) {
4235 if (cl->fStreamerInfo->GetEntries() != 0) {
4237 } else {
4239 }
4240 }
4241 };
4242 // Handle the special case of 'tuple' where we ignore the real implementation
4243 // details and just overlay a 'simpler'/'simplistic' version that is easy
4244 // for the I/O to understand and handle.
4245 if (strncmp(cl->GetName(),"tuple<",std::char_traits<char>::length("tuple<"))==0) {
4246 if (!reload)
4247 name = AlternateTuple(cl->GetName(), fInterpreter->getLookupHelper(), silent);
4248 if (reload || name.empty()) {
4249 // We could not generate the alternate
4251 return;
4252 }
4253 }
4254
4256 // FIXME: Rather than adding an option to the TClingClassInfo, we should consider combining code
4257 // that is currently in the caller (like SetUnloaded) that disable AutoLoading and AutoParsing and
4258 // code is in the callee (disabling template instantiation) and end up with a more explicit class:
4259 // TClingClassInfoReadOnly.
4261 if (!info->IsValid()) {
4263 delete info;
4264 return;
4265 }
4266 cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
4267 // In case a class contains an external enum, the enum will be seen as a
4268 // class. We must detect this special case and make the class a Zombie.
4269 // Here we assume that a class has at least one method.
4270 // We can NOT call TClass::Property from here, because this method
4271 // assumes that the TClass is well formed to do a lot of information
4272 // caching. The method SetClassInfo (i.e. here) is usually called during
4273 // the building phase of the TClass, hence it is NOT well formed yet.
4275 if (
4276 info->IsValid() &&
4277 !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
4278 ) {
4280 }
4281 if (!info->IsLoaded()) {
4282 if (info->Property() & (kIsNamespace)) {
4283 // Namespaces can have info but no corresponding CINT dictionary
4284 // because they are auto-created if one of their contained
4285 // classes has a dictionary.
4287 }
4288 // this happens when no dictionary is available
4289 delete info;
4290 cl->fClassInfo = nullptr;
4291 }
4292 if (zombieCandidate && !cl->GetCollectionType()) {
4293 cl->MakeZombie();
4294 }
4295 // If we reach here, the info was valid (See early returns).
4296 if (cl->fState != TClass::kHasTClassInit) {
4297 if (cl->fClassInfo) {
4299 } else {
4300// if (TClassEdit::IsSTLCont(cl->GetName()) {
4301// There will be an emulated collection proxy, is that the same?
4302// cl->fState = TClass::kEmulated;
4303// } else {
4304 if (cl->fStreamerInfo->GetEntries() != 0) {
4306 } else {
4308 }
4309// }
4310 }
4311 }
4312 if (cl->fClassInfo) {
4313 TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
4314 }
4315}
4316
4317////////////////////////////////////////////////////////////////////////////////
4318/// Checks if an entity with the specified name is defined in Cling.
4319/// Returns kUnknown if the entity is not defined.
4320/// Returns kWithClassDefInline if the entity exists and has a ClassDefInline
4321/// Returns kKnown if the entity is defined.
4322///
4323/// By default, structs, namespaces, classes, enums and unions are looked for.
4324/// If the flag isClassOrNamespaceOnly is true, classes, structs and
4325/// namespaces only are considered. I.e. if the name is an enum or a union,
4326/// the returned value is false.
4327///
4328/// In the case where the class is not loaded and belongs to a namespace
4329/// or is nested, looking for the full class name is outputting a lots of
4330/// (expected) error messages. Currently the only way to avoid this is to
4331/// specifically check that each level of nesting is already loaded.
4332/// In case of templates the idea is that everything between the outer
4333/// '<' and '>' has to be skipped, e.g.: `aap<pippo<noot>::klaas>::a_class`
4334
4337{
4339 static const char *anonEnum = "anonymous enum ";
4340 static const int cmplen = strlen(anonEnum);
4341
4342 if (fIsShuttingDown || 0 == strncmp(name, anonEnum, cmplen)) {
4343 return kUnknown;
4344 }
4345
4346 // Do not turn on the AutoLoading if it is globally off.
4348
4349 // Avoid the double search below in case the name is a fundamental type
4350 // or typedef to a fundamental type.
4351 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
4352 TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
4353
4355 && fundType->GetType() > 0) {
4356 // Fundamental type, no a class.
4357 return kUnknown;
4358 }
4359
4360 // Migrated from within TClass::GetClass
4361 // If we want to know if a class or a namespace with this name exists in the
4362 // interpreter and this is an enum in the type system, before or after loading
4363 // according to the autoload function argument, return kUnknown.
4365 return kUnknown;
4366
4367 const char *classname = name;
4368
4369 // RAII to suspend and restore auto-loading and auto-parsing based on some external conditions.
4371 int fStoreAutoLoad = 0;
4372 int fStoreAutoParse = 0;
4373 bool fSuspendedAutoParse = false;
4374 public:
4376 fStoreAutoLoad = ((TCling*)gCling)->SetClassAutoLoading(autoload);
4377 }
4378
4379 void SuspendAutoParsing() {
4380 fSuspendedAutoParse = true;
4381 fStoreAutoParse = ((TCling*)gCling)->SetSuspendAutoParsing(true);
4382 }
4383
4386 ((TCling*)gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4387 ((TCling*)gCling)->SetClassAutoLoading(fStoreAutoLoad);
4388 }
4389 };
4390
4392 if (TClassEdit::IsStdPair(classname) || TClassEdit::IsStdPairBase(classname))
4393 autoLoadParseRAII.SuspendAutoParsing();
4394
4395 // First we want to check whether the decl exist, but _without_
4396 // generating any template instantiation. However, the lookup
4397 // still will create a forward declaration of the class template instance
4398 // if it exist. In this case, the return value of findScope will still
4399 // be zero but the type will be initialized.
4400 // Note in the corresponding code in ROOT 5, CINT was not instantiating
4401 // this forward declaration.
4402 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4403 const clang::Type *type = nullptr;
4404 const clang::Decl *decl
4405 = lh.findScope(classname,
4406 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4407 : cling::LookupHelper::NoDiagnostics,
4408 &type, /* intantiateTemplate= */ false );
4409 if (!decl) {
4410 std::string buf = TClassEdit::InsertStd(classname);
4411 decl = lh.findScope(buf,
4412 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4413 : cling::LookupHelper::NoDiagnostics,
4414 &type,false);
4415 }
4416
4417 if (type) {
4418 // If decl==0 and the type is valid, then we have a forward declaration.
4419 if (!decl) {
4420 // If we have a forward declaration for a class template instantiation,
4421 // we want to ignore it if it was produced/induced by the call to
4422 // findScope, however we can not distinguish those from the
4423 // instantiation induce by 'soft' use (and thus also induce by the
4424 // same underlying code paths)
4425 // ['soft' use = use not requiring a complete definition]
4426 // So to reduce the amount of disruption to the existing code we
4427 // would just ignore those for STL collection, for which we really
4428 // need to have the compiled collection proxy (and thus the TClass
4429 // bootstrap).
4430 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4431 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4432 (type->getAsCXXRecordDecl());
4433 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4434 // Since the point of instantiation is invalid, we 'guess' that
4435 // the 'instantiation' of the forwarded type appended in
4436 // findscope.
4438 // For STL Collection we return kUnknown.
4439 return kUnknown;
4440 }
4441 }
4442 }
4444 if (!tci.IsValid()) {
4445 return kUnknown;
4446 }
4449
4450 if (tci.Property() & propertiesMask) {
4451 bool hasClassDefInline = false;
4453 // We do not need to check for ClassDefInline when this is called from
4454 // TClass::Init, we only do it for the call from TClass::GetClass.
4455 auto hasDictionary = tci.GetMethod("Dictionary", "", false, nullptr, ROOT::kExactMatch);
4456 auto implLineFunc = tci.GetMethod("ImplFileLine", "", false, nullptr, ROOT::kExactMatch);
4457
4458 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4459 int lineNumber = 0;
4460 bool success = false;
4461 std::tie(success, lineNumber) =
4464 }
4465 }
4466
4467 // fprintf(stderr,"CheckClassInfo: %s had dict=%d inline=%d\n",name,hasDictionary.IsValid()
4468 // , hasClassDefInline);
4469
4470 // We are now sure that the entry is not in fact an autoload entry.
4472 return kWithClassDefInline;
4473 else
4474 return kKnown;
4475 } else {
4476 // We are now sure that the entry is not in fact an autoload entry.
4477 return kUnknown;
4478 }
4479 }
4480
4481 if (decl)
4482 return kKnown;
4483 else
4484 return kUnknown;
4485
4486 // Setting up iterator part of TClingTypedefInfo is too slow.
4487 // Copy the lookup code instead:
4488 /*
4489 TClingTypedefInfo t(fInterpreter, name);
4490 if (t.IsValid() && !(t.Property() & kIsFundamental)) {
4491 delete[] classname;
4492 return kTRUE;
4493 }
4494 */
4495
4496// const clang::Decl *decl = lh.findScope(name);
4497// if (!decl) {
4498// std::string buf = TClassEdit::InsertStd(name);
4499// decl = lh.findScope(buf);
4500// }
4501
4502// return (decl);
4503}
4504
4505////////////////////////////////////////////////////////////////////////////////
4506/// Return true if there is a class template by the given name ...
4507
4509{
4510 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4511 // Interpreter transaction ahead, needs locking
4513 const clang::Decl *decl
4514 = lh.findClassTemplate(name,
4515 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4516 : cling::LookupHelper::NoDiagnostics);
4517 if (!decl) {
4518 std::string strname = "std::";
4519 strname += name;
4520 decl = lh.findClassTemplate(strname,
4521 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4522 : cling::LookupHelper::NoDiagnostics);
4523 }
4524 return nullptr != decl;
4525}
4526
4527////////////////////////////////////////////////////////////////////////////////
4528/// Create list of pointers to base class(es) for TClass cl.
4529
4531{
4533 if (cl->fBase) {
4534 return;
4535 }
4536 // Ignore the base class (e.g. `std::_Complex_base` on Windows)
4538 cl->fBase = new TList();
4539 return;
4540 }
4542 if (!tci) return;
4544 TList *listOfBase = new TList;
4545 while (t.Next()) {
4546 // if name cannot be obtained no use to put in list
4547 if (t.IsValid() && t.Name()) {
4549 listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
4550 }
4551 }
4552 // Now that is complete, publish it.
4553 cl->fBase = listOfBase;
4554}
4555
4556////////////////////////////////////////////////////////////////////////////////
4557/// Create list of pointers to enums for TClass cl.
4558
4560{
4562
4563 const Decl * D;
4564 TClass* cl = enumList.GetClass();
4565 if (cl) {
4566 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4567 }
4568 else {
4569 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4570 }
4571 // Iterate on the decl of the class and get the enums.
4572 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4573 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4574 // Collect all contexts of the namespace.
4575 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4576 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4578 declIter != declEnd; ++declIter) {
4579 // Iterate on all decls for each context.
4580 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4581 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4582 if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4583 // Get name of the enum type.
4584 std::string buf;
4585 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4586 llvm::raw_string_ostream stream(buf);
4587 // Don't trigger fopen of the source file to count lines:
4588 Policy.AnonymousTagLocations = false;
4589 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
4590 stream.flush();
4591 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
4592 if (!buf.empty()) {
4593 const char* name = buf.c_str();
4594 // Add the enum to the list of loaded enums.
4595 enumList.Get(ED, name);
4596 }
4597 }
4598 }
4599 }
4600 }
4601}
4602
4603////////////////////////////////////////////////////////////////////////////////
4604/// Create list of pointers to function templates for TClass cl.
4605
4607{
4609
4610 const Decl * D;
4612 if (cl) {
4613 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4615 }
4616 else {
4617 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4618 funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
4619 }
4620 // Iterate on the decl of the class and get the enums.
4621 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4622 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4623 // Collect all contexts of the namespace.
4624 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4625 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4628 // Iterate on all decls for each context.
4629 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4630 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4631 if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4632 funcTempList->Get(FTD);
4633 }
4634 }
4635 }
4636 }
4637}
4638
4639////////////////////////////////////////////////////////////////////////////////
4640/// Get the scopes representing using declarations of namespace
4641
4642std::vector<std::string> TCling::GetUsingNamespaces(ClassInfo_t *cl) const
4643{
4645 return ci->GetUsingNamespaces();
4646}
4647
4648////////////////////////////////////////////////////////////////////////////////
4649/// Create list of pointers to data members for TClass cl.
4650/// This is now a nop. The creation and updating is handled in
4651/// TListOfDataMembers.
4652
4654{
4655}
4656
4657////////////////////////////////////////////////////////////////////////////////
4658/// Create list of pointers to methods for TClass cl.
4659/// This is now a nop. The creation and updating is handled in
4660/// TListOfFunctions.
4661
4663{
4664}
4665
4666////////////////////////////////////////////////////////////////////////////////
4667/// Update the list of pointers to method for TClass cl
4668/// This is now a nop. The creation and updating is handled in
4669/// TListOfFunctions.
4670
4672{
4673}
4674
4675////////////////////////////////////////////////////////////////////////////////
4676/// Update the list of pointers to data members for TClass cl
4677/// This is now a nop. The creation and updating is handled in
4678/// TListOfDataMembers.
4679
4681{
4682}
4683
4684////////////////////////////////////////////////////////////////////////////////
4685/// Create list of pointers to method arguments for TMethod m.
4686
4688{
4690 if (m->fMethodArgs) {
4691 return;
4692 }
4693 TList *arglist = new TList;
4695 while (t.Next()) {
4696 if (t.IsValid()) {
4698 arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
4699 }
4700 }
4701 m->fMethodArgs = arglist;
4702}
4703
4704////////////////////////////////////////////////////////////////////////////////
4705/// Return whether we are waiting for more input either because the collected
4706/// input contains unbalanced braces or last seen token was a `\` (backslash-newline)
4707
4709{
4710 return fMetaProcessor->awaitingMoreInput();
4711}
4712
4713////////////////////////////////////////////////////////////////////////////////
4714/// Generate a TClass for the given class.
4715/// Since the caller has already check the ClassInfo, let it give use the
4716/// result (via the value of emulation) rather than recalculate it.
4717
4718TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
4719{
4720// For now the following line would lead to the (unwanted) instantiation
4721// of class template. This could/would need to be resurrected only if
4722// we re-introduce so sort of automatic instantiation. However this would
4723// have to include carefull look at the template parameter to avoid
4724// creating instance we can not really use (if the parameter are only forward
4725// declaration or do not have all the necessary interfaces).
4726
4727 // TClingClassInfo tci(fInterpreter, classname);
4728 // if (1 || !tci.IsValid()) {
4729
4730 Version_t version = 1;
4731 if (TClassEdit::IsSTLCont(classname)) {
4732 version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4733 }
4735 TClass *cl = new TClass(classname, version, silent);
4736 if (!emulation) {
4737 // Set the class version if the class is versioned.
4738 // Note that we cannot just call CLASS::Class_Version() as we might not have
4739 // an execution engine (when invoked from rootcling).
4740
4741 // Do not call cl->GetClassVersion(), it has side effects!
4743 if (oldvers == version && cl->GetClassInfo()) {
4744 // We have a version and it might need an update.
4746 if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
4747 // Namespaces don't have class versions.
4748 return cl;
4749 }
4750 TClingMethodInfo mi = cli->GetMethod("Class_Version", "", nullptr /*poffset*/,
4753 if (!mi.IsValid()) {
4754 if (cl->TestBit(TClass::kIsTObject)) {
4755 Error("GenerateTClass",
4756 "Cannot find %s::Class_Version()! Class version might be wrong.",
4757 cl->GetName());
4758 }
4759 return cl;
4760 }
4761 Version_t newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->GetDecl()),
4762 *fInterpreter);
4763 if (newvers == -1) {
4764 // Didn't manage to determine the class version from the AST.
4765 // Use runtime instead.
4766 if ((mi.Property() & kIsStatic)
4767 && !fInterpreter->isInSyntaxOnlyMode()) {
4768 // This better be a static function.
4770 callfunc.SetFunc(&mi);
4771 newvers = callfunc.ExecInt(nullptr);
4772 } else {
4773 Error("GenerateTClass",
4774 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4775 cl->GetName());
4776 }
4777 }
4778 if (newvers != oldvers) {
4779 cl->fClassVersion = newvers;
4780 cl->fStreamerInfo->Expand(newvers + 2 + 10);
4781 }
4782 }
4783 }
4784
4785 return cl;
4786
4787// } else {
4788// return GenerateTClass(&tci,silent);
4789// }
4790}
4791
4792#if 0
4793////////////////////////////////////////////////////////////////////////////////
4794
4795static void GenerateTClass_GatherInnerIncludes(cling::Interpreter *interp, TString &includes,TClingClassInfo *info)
4796{
4797 includes += info->FileName();
4798
4799 const clang::ClassTemplateSpecializationDecl *templateCl
4800 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->GetDecl());
4801 if (templateCl) {
4802 for(unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
4803 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4804 if (arg.getKind() == clang::TemplateArgument::Type) {
4805 const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
4806
4807 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4808 // We really need a header file.
4809 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4810 if (argdecl) {
4811 includes += ";";
4812 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4814 } else {
4815 std::string Result;
4816 llvm::raw_string_ostream OS(Result);
4817 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4818 Warning("TCling::GenerateTClass","Missing header file for %s",OS.str().c_str());
4819 }
4820 }
4821 }
4822 }
4823 }
4824}
4825#endif
4826
4827////////////////////////////////////////////////////////////////////////////////
4828/// Generate a TClass for the given class.
4829
4831{
4833 if (!info || !info->IsValid()) {
4834 Fatal("GenerateTClass","Requires a valid ClassInfo object");
4835 return nullptr;
4836 }
4837 // We are in the case where we have AST nodes for this class.
4838 TClass *cl = nullptr;
4839 std::string classname;
4840 info->FullName(classname,*fNormalizedCtxt); // Could we use Name()?
4841 if (TClassEdit::IsSTLCont(classname)) {
4842#if 0
4843 Info("GenerateTClass","Will (try to) generate the compiled TClass for %s.",classname.c_str());
4844 // We need to build up the list of required headers, by
4845 // looking at each template arguments.
4846 TString includes;
4848
4849 if (0 == GenerateDictionary(classname.c_str(),includes)) {
4850 // 0 means success.
4851 cl = TClass::LoadClass(classnam.c_str(), silent);
4852 if (cl == 0) {
4853 Error("GenerateTClass","Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4854 }
4855 }
4856#endif
4857 if (cl == nullptr) {
4858 int version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4859 cl = new TClass(classinfo, version, nullptr, nullptr, -1, -1, silent);
4860 }
4861 } else {
4862 // For regular class, just create a TClass on the fly ...
4863 // Not quite useful yet, but that what CINT used to do anyway.
4864 cl = new TClass(classinfo, 1, nullptr, nullptr, -1, -1, silent);
4865 }
4866 // Add the new TClass to the map of declid and TClass*.
4867 if (cl) {
4869 }
4870 return cl;
4871}
4872
4873////////////////////////////////////////////////////////////////////////////////
4874/// Generate the dictionary for the C++ classes listed in the first
4875/// argument (in a semi-colon separated list).
4876/// 'includes' contains a semi-colon separated list of file to
4877/// `#include` in the dictionary.
4878/// For example:
4879/// ~~~ {.cpp}
4880/// gInterpreter->GenerateDictionary("vector<vector<float> >;list<vector<float> >","list;vector");
4881/// ~~~
4882/// or
4883/// ~~~ {.cpp}
4884/// gInterpreter->GenerateDictionary("myclass","myclass.h;myhelper.h");
4885/// ~~~
4886
4887Int_t TCling::GenerateDictionary(const char* classes, const char* includes /* = "" */, const char* /* options = 0 */)
4888{
4889 if (classes == nullptr || classes[0] == 0) {
4890 Error("TCling::GenerateDictionary", "Cannot generate dictionary without passing classes.");
4891 return 0;
4892 }
4893 // Split the input list
4894 std::vector<std::string> listClasses;
4895 for (
4896 const char* current = classes, *prev = classes;
4897 *current != 0;
4898 ++current
4899 ) {
4900 if (*current == ';') {
4901 listClasses.push_back(std::string(prev, current - prev));
4902 prev = current + 1;
4903 }
4904 else if (*(current + 1) == 0) {
4905 listClasses.push_back(std::string(prev, current + 1 - prev));
4906 prev = current + 1;
4907 }
4908 }
4909 std::vector<std::string> listIncludes;
4910 if (!includes)
4911 includes = "";
4912 for (
4913 const char* current = includes, *prev = includes;
4914 *current != 0;
4915 ++current
4916 ) {
4917 if (*current == ';') {
4918 listIncludes.push_back(std::string(prev, current - prev));
4919 prev = current + 1;
4920 }
4921 else if (*(current + 1) == 0) {
4922 listIncludes.push_back(std::string(prev, current + 1 - prev));
4923 prev = current + 1;
4924 }
4925 }
4926 // Generate the temporary dictionary file
4928 std::vector<std::string>(), std::vector<std::string>());
4929}
4930
4931////////////////////////////////////////////////////////////////////////////////
4932/// Return pointer to cling Decl of global/static variable that is located
4933/// at the address given by addr.
4934
4936{
4938 DeclId_t d;
4940
4941 // Could trigger deserialization of decls.
4942 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4943
4944 if (cl) {
4945 d = cl->GetDataMember(name);
4946 // We check if the decl of the data member has an annotation which indicates
4947 // an ioname.
4948 // In case this is true, if the name requested is not the ioname, we
4949 // return 0, as if the member did not exist. In some sense we override
4950 // the information in the TClassInfo instance, isolating the typesystem in
4951 // TClass from the one in the AST.
4952 if (const ValueDecl* decl = (const ValueDecl*) d){
4953 std::string ioName;
4955 if (hasIoName && ioName != name) return nullptr;
4956 }
4957 return d;
4958 }
4959 // We are looking up for something on the TU scope.
4960 // FIXME: We do not want to go through TClingClassInfo(fInterpreter) because of redundant deserializations. That
4961 // interface will actually construct iterators and walk over the decls on the global scope. In would return the first
4962 // occurrence of a decl with the looked up name. However, that's not what C++ lookup would do: if we want to switch
4963 // to a more complete C++ lookup interface we need sift through the found names and pick up the declarations which
4964 // are only fulfilling ROOT's understanding for a Data Member.
4965 // FIXME: We should probably deprecate the TClingClassInfo(fInterpreter) interface and replace it withe something
4966 // similar as below.
4967 using namespace clang;
4968 Sema& SemaR = fInterpreter->getSema();
4969 DeclarationName DName = &SemaR.Context.Idents.get(name);
4970
4971 LookupResult R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4972 RedeclarationKind::ForExternalRedeclaration);
4973
4974 cling::utils::Lookup::Named(&SemaR, R);
4975
4976 LookupResult::Filter F = R.makeFilter();
4977 // Filter the data-member looking decls.
4978 while (F.hasNext()) {
4979 NamedDecl *D = F.next();
4982 continue;
4983 F.erase();
4984 }
4985 F.done();
4986
4987 if (R.isSingleResult())
4988 return R.getFoundDecl();
4989 return nullptr;
4990}
4991
4992////////////////////////////////////////////////////////////////////////////////
4993/// Return pointer to cling Decl of global/static variable that is located
4994/// at the address given by addr.
4995
4997{
4999
5000 const clang::Decl* possibleEnum = nullptr;
5001 // FInd the context of the decl.
5002 if (cl) {
5004 if (cci) {
5005 const clang::DeclContext* dc = nullptr;
5006 if (const clang::Decl* D = cci->GetDecl()) {
5007 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
5009 }
5010 }
5011 if (dc) {
5012 // If it is a data member enum.
5013 // Could trigger deserialization of decls.
5014 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
5015 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name, dc);
5016 } else {
5017 Error("TCling::GetEnum", "DeclContext not found for %s .\n", name);
5018 }
5019 }
5020 } else {
5021 // If it is a global enum.
5022 // Could trigger deserialization of decls.
5023 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
5024 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name);
5025 }
5026 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
5028 return possibleEnum;
5029 }
5030 return nullptr;
5031}
5032
5033////////////////////////////////////////////////////////////////////////////////
5034/// Return pointer to cling DeclId for a global value
5035
5036TInterpreter::DeclId_t TCling::GetDeclId( const llvm::GlobalValue *gv ) const
5037{
5038 if (!gv) return nullptr;
5039
5040 llvm::StringRef mangled_name = gv->getName();
5041
5042 int err = 0;
5043 char* demangled_name_c = TClassEdit::DemangleName(mangled_name.str().c_str(), err);
5044 if (err) {
5045 if (err == -2) {
5046 // It might simply be an unmangled global name.
5047 DeclId_t d;
5049 d = gcl.GetDataMember(mangled_name.str().c_str());
5050 return d;
5051 }
5052 return nullptr;
5053 }
5054
5055 std::string scopename(demangled_name_c);
5057
5058 //
5059 // Separate out the class or namespace part of the
5060 // function name.
5061 //
5062 std::string dataname;
5063
5064 if (!strncmp(scopename.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
5065 scopename.erase(0, sizeof("typeinfo for ")-1);
5066 } else if (!strncmp(scopename.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
5067 scopename.erase(0, sizeof("vtable for ")-1);
5068 } else {
5069 // See if it is a function
5070 std::string::size_type pos = scopename.rfind('(');
5071 if (pos != std::string::npos) {
5072 return nullptr;
5073 }
5074 // Separate the scope and member name
5075 pos = scopename.rfind(':');
5076 if (pos != std::string::npos) {
5077 if ((pos != 0) && (scopename[pos-1] == ':')) {
5078 dataname = scopename.substr(pos+1);
5079 scopename.erase(pos-1);
5080 }
5081 } else {
5082 scopename.clear();
5084 }
5085 }
5086 //fprintf(stderr, "name: '%s'\n", name.c_str());
5087 // Now we have the class or namespace name, so do the lookup.
5088
5089
5090 DeclId_t d;
5091 if (scopename.size()) {
5093 d = cl.GetDataMember(dataname.c_str());
5094 }
5095 else {
5097 d = gcl.GetDataMember(dataname.c_str());
5098 }
5099 return d;
5100}
5101
5102////////////////////////////////////////////////////////////////////////////////
5103/// NOT IMPLEMENTED.
5104
5106{
5107 Error("GetDataMemberWithValue()", "not implemented");
5108 return nullptr;
5109}
5110
5111////////////////////////////////////////////////////////////////////////////////
5112/// Return pointer to cling DeclId for a data member with a given name.
5113
5115{
5116 // NOT IMPLEMENTED.
5117 Error("GetDataMemberAtAddr()", "not implemented");
5118 return nullptr;
5119}
5120
5121////////////////////////////////////////////////////////////////////////////////
5122/// Return the cling mangled name for a method of a class with parameters
5123/// params (params is a string of actual arguments, not formal ones). If the
5124/// class is 0 the global function list will be searched.
5125
5127 const char* params, Bool_t objectIsConst /* = kFALSE */)
5128{
5131 if (cl) {
5134 &offset);
5135 }
5136 else {
5139 func.SetFunc(&gcl, method, params, &offset);
5140 }
5142 if (!mi) return "";
5143 TString mangled_name( mi->GetMangledName() );
5144 delete mi;
5145 return mangled_name;
5146}
5147
5148////////////////////////////////////////////////////////////////////////////////
5149/// Return the cling mangled name for a method of a class with a certain
5150/// prototype, i.e. "char*,int,float". If the class is 0 the global function
5151/// list will be searched.
5152
5154 const char* proto, Bool_t objectIsConst /* = kFALSE */,
5155 EFunctionMatchMode mode /* = kConversionMatch */)
5156{
5158 if (cl) {
5159 return ((TClingClassInfo*)cl->GetClassInfo())->
5160 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5161 }
5163 return gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5164}
5165
5166////////////////////////////////////////////////////////////////////////////////
5167/// Return pointer to cling interface function for a method of a class with
5168/// parameters params (params is a string of actual arguments, not formal
5169/// ones). If the class is 0 the global function list will be searched.
5170
5172 const char* params, Bool_t objectIsConst /* = kFALSE */)
5173{
5176 if (cl) {
5179 &offset);
5180 }
5181 else {
5184 func.SetFunc(&gcl, method, params, &offset);
5185 }
5186 return (void*) func.InterfaceMethod();
5187}
5188
5189////////////////////////////////////////////////////////////////////////////////
5190/// Return pointer to cling interface function for a method of a class with
5191/// a certain name.
5192
5194{
5196 DeclId_t f;
5198 if (cl) {
5199 f = cl->GetMethod(method).GetDeclId();
5200 }
5201 else {
5203 f = gcl.GetMethod(method).GetDeclId();
5204 }
5205 return f;
5206
5207}
5208
5209////////////////////////////////////////////////////////////////////////////////
5210/// Insert overloads of name in cl to res.
5211
5213 std::vector<DeclId_t>& res) const
5214{
5215 clang::Sema& S = fInterpreter->getSema();
5216 clang::ASTContext& Ctx = S.Context;
5217 const clang::Decl* CtxDecl
5218 = cl ? (const clang::Decl*)((TClingClassInfo*)cl)->GetDeclId():
5219 Ctx.getTranslationUnitDecl();
5220 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
5221 const clang::DeclContext* DeclCtx = RecDecl;
5222
5223 if (!DeclCtx)
5225 if (!DeclCtx) return;
5226
5227 clang::DeclarationName DName;
5228 // The DeclarationName is funcname, unless it's a ctor or dtor.
5229 // FIXME: or operator or conversion! See enum clang::DeclarationName::NameKind.
5230
5231 if (RecDecl) {
5232 if (RecDecl->getNameAsString() == funcname) {
5233 clang::CanQualType QT = Ctx.getCanonicalTagType(RecDecl);
5234 DName = Ctx.DeclarationNames.getCXXConstructorName(QT);
5235 } else if (funcname[0] == '~' && RecDecl->getNameAsString() == funcname + 1) {
5236 clang::CanQualType QT = Ctx.getCanonicalTagType(RecDecl);
5237 DName = Ctx.DeclarationNames.getCXXDestructorName(QT);
5238 } else {
5239 DName = &Ctx.Idents.get(funcname);
5240 }
5241 } else {
5242 DName = &Ctx.Idents.get(funcname);
5243 }
5244
5245 // NotForRedeclaration: we want to find names in inline namespaces etc.
5246 clang::LookupResult R(S, DName, clang::SourceLocation(), Sema::LookupOrdinaryName,
5247 RedeclarationKind::NotForRedeclaration);
5248 R.suppressDiagnostics(); // else lookup with NotForRedeclaration will check access etc
5249 S.LookupQualifiedName(R, const_cast<DeclContext*>(DeclCtx));
5250 if (R.empty()) return;
5251 R.resolveKind();
5252 res.reserve(res.size() + (R.end() - R.begin()));
5253 for (clang::LookupResult::iterator IR = R.begin(), ER = R.end();
5254 IR != ER; ++IR) {
5255 if (const clang::FunctionDecl* FD
5256 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5257 if (!FD->getDescribedFunctionTemplate()) {
5258 res.push_back(FD);
5259 }
5260 } else if (const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5261 // FIXME: multi-level using
5262 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5263 res.push_back(USD);
5264 }
5265 }
5266 }
5267}
5268
5269////////////////////////////////////////////////////////////////////////////////
5270/// Return pointer to cling interface function for a method of a class with
5271/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5272/// function list will be searched.
5273
5275 const char* proto,
5276 Bool_t objectIsConst /* = kFALSE */,
5277 EFunctionMatchMode mode /* = kConversionMatch */)
5278{
5280 void* f;
5281 if (cl) {
5282 f = ((TClingClassInfo*)cl->GetClassInfo())->
5283 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5284 }
5285 else {
5287 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5288 }
5289 return f;
5290}
5291
5292////////////////////////////////////////////////////////////////////////////////
5293/// Return pointer to cling DeclId for a method of a class with
5294/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5295/// function list will be searched.
5296
5298 const char* params,
5299 Bool_t objectIsConst /* = kFALSE */)
5300{
5302 DeclId_t f;
5304 if (cl) {
5305 f = cl->GetMethodWithArgs(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5306 }
5307 else {
5309 f = gcl.GetMethod(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5310 }
5311 return f;
5312}
5313
5314////////////////////////////////////////////////////////////////////////////////
5315/// Return pointer to cling interface function for a method of a class with
5316/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5317/// function list will be searched.
5318
5320 const char* proto,
5321 Bool_t objectIsConst /* = kFALSE */,
5322 EFunctionMatchMode mode /* = kConversionMatch */)
5323{
5325 DeclId_t f;
5327 if (cl) {
5328 f = cl->GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5329 }
5330 else {
5332 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5333 }
5334 return f;
5335}
5336
5337////////////////////////////////////////////////////////////////////////////////
5338/// Return pointer to cling interface function for a method of a class with
5339/// a certain name.
5340
5342{
5344 DeclId_t f;
5346 if (cl) {
5347 f = cl->GetFunctionTemplate(name);
5348 }
5349 else {
5351 f = gcl.GetFunctionTemplate(name);
5352 }
5353 return f;
5354
5355}
5356
5357////////////////////////////////////////////////////////////////////////////////
5358/// The 'name' is known to the interpreter, this function returns
5359/// the internal version of this name (usually just resolving typedefs)
5360/// This is used in particular to synchronize between the name used
5361/// by rootcling and by the run-time environment (TClass)
5362/// Return 0 if the name is not known.
5363
5364void TCling::GetInterpreterTypeName(const char* name, std::string &output, Bool_t full)
5365{
5366 output.clear();
5367
5369
5371 if (!cl.IsValid()) {
5372 return ;
5373 }
5374 if (full) {
5375 cl.FullName(output,*fNormalizedCtxt);
5376 return;
5377 }
5378 // Well well well, for backward compatibility we need to act a bit too
5379 // much like CINT.
5381 splitname.ShortType(output, TClassEdit::kDropStd );
5382
5383 return;
5384}
5385
5386////////////////////////////////////////////////////////////////////////////////
5387/// Execute a global function with arguments params.
5388///
5389/// FIXME: The cint-based version of this code does not check if the
5390/// SetFunc() call works, and does not do any real checking
5391/// for errors from the Exec() call. It did fetch the most
5392/// recent cint security error and return that in error, but
5393/// this does not really translate well to cling/clang. We
5394/// should enhance these interfaces so that we can report
5395/// compilation and runtime errors properly.
5396
5397void TCling::Execute(const char* function, const char* params, int* error)
5398{
5400 if (error) {
5401 *error = TInterpreter::kNoError;
5402 }
5404 Longptr_t offset = 0L;
5406 func.SetFunc(&cl, function, params, &offset);
5407 func.Exec(nullptr);
5408}
5409
5410////////////////////////////////////////////////////////////////////////////////
5411/// Execute a method from class cl with arguments params.
5412///
5413/// FIXME: The cint-based version of this code does not check if the
5414/// SetFunc() call works, and does not do any real checking
5415/// for errors from the Exec() call. It did fetch the most
5416/// recent cint security error and return that in error, but
5417/// this does not really translate well to cling/clang. We
5418/// should enhance these interfaces so that we can report
5419/// compilation and runtime errors properly.
5420
5421void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5422 const char* params, Bool_t objectIsConst, int* error)
5423{
5425 if (error) {
5426 *error = TInterpreter::kNoError;
5427 }
5428 // If the actual class of this object inherits 2nd (or more) from TObject,
5429 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5430 // hence gInterpreter->Execute will improperly correct the offset.
5431 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5432 Longptr_t offset = 0L;
5435 void* address = (void*)((Longptr_t)addr + offset);
5436 func.Exec(address);
5437}
5438
5439////////////////////////////////////////////////////////////////////////////////
5440
5441void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5442 const char* params, int* error)
5443{
5444 Execute(obj,cl,method,params,false,error);
5445}
5446
5447////////////////////////////////////////////////////////////////////////////////
5448/// Execute a method from class cl with the arguments in array params
5449/// (params[0] ... params[n] = array of TObjString parameters).
5450/// Convert the TObjArray array of TObjString parameters to a character
5451/// string of comma separated parameters.
5452/// The parameters of type 'char' are enclosed in double quotes and all
5453/// internal quotes are escaped.
5454
5456 TObjArray* params, int* error)
5457{
5458 if (!method) {
5459 Error("Execute", "No method was defined");
5460 return;
5461 }
5462 TList* argList = method->GetListOfMethodArgs();
5463 // Check number of actual parameters against of expected formal ones
5464
5465 Int_t nparms = argList->LastIndex() + 1;
5466 Int_t argc = params ? params->GetEntries() : 0;
5467
5468 if (argc > nparms) {
5469 Error("Execute","Too many parameters to call %s, got %d but expected at most %d.",method->GetName(),argc,nparms);
5470 return;
5471 }
5472 if (nparms != argc) {
5473 // Let's see if the 'missing' argument are all defaulted.
5474 // if nparms==0 then either we stopped earlier either argc is also zero and we can't reach here.
5475 assert(nparms > 0);
5476
5477 TMethodArg *arg = (TMethodArg *) argList->At( 0 );
5478 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5479 // There is a default value for the first missing
5480 // argument, so we are fine.
5481 } else {
5482 Int_t firstDefault = -1;
5483 for (Int_t i = 0; i < nparms; i ++) {
5484 arg = (TMethodArg *) argList->At( i );
5485 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5486 firstDefault = i;
5487 break;
5488 }
5489 }
5490 if (firstDefault >= 0) {
5491 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);
5492 } else {
5493 Error("Execute","Too few arguments to call %s, got only %d but expected %d.",method->GetName(),argc,nparms);
5494 }
5495 return;
5496 }
5497 }
5498
5499 const char* listpar = "";
5500 TString complete(10);
5501 if (params) {
5502 // Create a character string of parameters from TObjArray
5503 TIter next(params);
5504 for (Int_t i = 0; i < argc; i ++) {
5505 TMethodArg* arg = (TMethodArg*) argList->At(i);
5507 TObjString* nxtpar = (TObjString*) next();
5508 if (i) {
5509 complete += ',';
5510 }
5511 if (strstr(type.TrueName(*fNormalizedCtxt), "char")) {
5512 TString chpar('\"');
5513 chpar += (nxtpar->String()).ReplaceAll("\"", "\\\"");
5514 // At this point we have to check if string contains \\"
5515 // and apply some more sophisticated parser. Not implemented yet!
5516 complete += chpar;
5517 complete += '\"';
5518 }
5519 else {
5520 complete += nxtpar->String();
5521 }
5522 }
5523 listpar = complete.Data();
5524 }
5525
5526 // And now execute it.
5528 if (error) {
5529 *error = TInterpreter::kNoError;
5530 }
5531 // If the actual class of this object inherits 2nd (or more) from TObject,
5532 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5533 // hence gInterpreter->Execute will improperly correct the offset.
5534 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5537 func.Init(*minfo);
5538 func.SetArgs(listpar);
5539 // Now calculate the 'this' pointer offset for the method
5540 // when starting from the class described by cl.
5541 const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->GetTargetFunctionDecl());
5542 Longptr_t offset = ((TClingClassInfo*)cl->GetClassInfo())->GetOffset(mdecl);
5543 void* address = (void*)((Longptr_t)addr + offset);
5544 func.Exec(address);
5545}
5546
5547////////////////////////////////////////////////////////////////////////////////
5548
5550 const void* args[] /*=0*/,
5551 int nargs /*=0*/,
5552 void* ret/*= 0*/) const
5553{
5554 if (!method) {
5555 Error("ExecuteWithArgsAndReturn", "No method was defined");
5556 return;
5557 }
5558
5560 TClingCallFunc func(*minfo);
5561 func.ExecWithArgsAndReturn(address, args, nargs, ret);
5562}
5563
5564////////////////////////////////////////////////////////////////////////////////
5565/// Execute a cling macro.
5566
5568{
5570 fCurExecutingMacros.push_back(filename);
5572 fCurExecutingMacros.pop_back();
5573 return result;
5574}
5575
5576////////////////////////////////////////////////////////////////////////////////
5577/// Return the file name of the current un-included interpreted file.
5578/// See the documentation for GetCurrentMacroName().
5579
5581{
5582 Warning("GetTopLevelMacroName", "Must change return type!");
5583 return fCurExecutingMacros.empty() ? nullptr : fCurExecutingMacros.back();
5584}
5585
5586////////////////////////////////////////////////////////////////////////////////
5587/// Return the file name of the currently interpreted file,
5588/// included or not. Example to illustrate the difference between
5589/// GetCurrentMacroName() and GetTopLevelMacroName():
5590/// ~~~ {.cpp}
5591/// void inclfile() {
5592/// std::cout << "In inclfile.C" << std::endl;
5593/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5594/// TCling::GetCurrentMacroName() << std::endl;
5595/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5596/// TCling::GetTopLevelMacroName() << std::endl;
5597/// }
5598/// ~~~
5599/// ~~~ {.cpp}
5600/// void mymacro() {
5601/// std::cout << "In mymacro.C" << std::endl;
5602/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5603/// TCling::GetCurrentMacroName() << std::endl;
5604/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5605/// TCling::GetTopLevelMacroName() << std::endl;
5606/// std::cout << " Now calling inclfile..." << std::endl;
5607/// gInterpreter->ProcessLine(".x inclfile.C");
5608/// }
5609/// ~~~
5610/// Running mymacro.C will print:
5611///
5612/// ~~~ {.cpp}
5613/// root [0] .x mymacro.C
5614/// ~~~
5615/// In mymacro.C
5616/// ~~~ {.cpp}
5617/// TCling::GetCurrentMacroName() returns ./mymacro.C
5618/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5619/// ~~~
5620/// Now calling inclfile...
5621/// In inclfile.h
5622/// ~~~ {.cpp}
5623/// TCling::GetCurrentMacroName() returns inclfile.C
5624/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5625/// ~~~
5626
5628{
5629#if defined(R__MUST_REVISIT)
5630#if R__MUST_REVISIT(6,0)
5631 Warning("GetCurrentMacroName", "Must change return type!");
5632#endif
5633#endif
5634 return fCurExecutingMacros.empty() ? nullptr : fCurExecutingMacros.back();
5635}
5636
5637////////////////////////////////////////////////////////////////////////////////
5638/// Return the absolute type of typeDesc.
5639/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
5640/// You need to use the result immediately before it is being overwritten.
5641
5642const char* TCling::TypeName(const char* typeDesc)
5643{
5644 TTHREAD_TLS_DECL(std::string,t);
5645
5646 if (!strstr(typeDesc, "(*)(")) {
5647 const char *s = strchr(typeDesc, ' ');
5648 const char *template_start = strchr(typeDesc, '<');
5649 if (!strcmp(typeDesc, "long long")) {
5650 t = typeDesc;
5651 }
5652 else if (!strncmp(typeDesc, "unsigned ", s + 1 - typeDesc)) {
5653 t = typeDesc;
5654 }
5655 // s is the position of the second 'word' (if any)
5656 // except in the case of templates where there will be a space
5657 // just before any closing '>': eg.
5658 // TObj<std::vector<UShort_t,__malloc_alloc_template<0> > >*
5659 else if (s && (template_start == nullptr || (s < template_start))) {
5660 t = s + 1;
5661 }
5662 else {
5663 t = typeDesc;
5664 }
5665 }
5666 else {
5667 t = typeDesc;
5668 }
5669 auto l = t.length();
5670 while (l > 0 && (t[l - 1] == '*' || t[l - 1] == '&'))
5671 --l;
5672 t.resize(l);
5673 return t.c_str(); // NOLINT
5674}
5675
5676static bool requiresRootMap(const char* rootmapfile)
5677{
5679
5680 llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5681 libName.consume_back(".rootmap");
5682
5683 return !gInterpreter->HasPCMForLibrary(libName.str().c_str());
5684}
5685
5686////////////////////////////////////////////////////////////////////////////////
5687/// Read and parse a rootmapfile in its new format, and return 0 in case of
5688/// success, -1 if the file has already been read, and -3 in case its format
5689/// is the old one (e.g. containing "Library.ClassName"), -4 in case of syntax
5690/// error.
5691
5693{
5694 if (!(rootmapfile && *rootmapfile))
5695 return 0;
5696
5698 return 0; // success
5699
5700 // For "class ", "namespace ", "typedef ", "header ", "enum ", "var " respectively
5701 const std::map<char, unsigned int> keyLenMap = {{'c',6},{'n',10},{'t',8},{'h',7},{'e',5},{'v',4}};
5702
5704#ifdef _MSC_VER
5705 std::replace(rootmapfileNoBackslash.begin(), rootmapfileNoBackslash.end(), '\\', '/');
5706#endif
5707 // Add content of a specific rootmap file
5709 return -1;
5710
5711 // Line 1 is `{ decls }`
5712 std::string lineDirective = std::string("\n#line 2 \"Forward declarations from ") + rootmapfileNoBackslash + "\"\n";
5713
5714 std::ifstream file(rootmapfileNoBackslash);
5715 std::string line;
5716 line.reserve(200);
5717 std::string lib_name;
5718 line.reserve(100);
5719 bool newFormat = false;
5720 while (getline(file, line, '\n')) {
5721 if (!newFormat && (line.compare(0, 8, "Library.") == 0 || line.compare(0, 8, "Declare.") == 0)) {
5722 file.close();
5723 return -3; // old format
5724 }
5725 newFormat = true;
5726
5727 if (line.compare(0, 9, "{ decls }") == 0) {
5728 // forward declarations
5729
5730 while (getline(file, line, '\n')) {
5731 if (line[0] == '[')
5732 break;
5733 if (!uniqueString) {
5734 Error("ReadRootmapFile", "Cannot handle \"{ decls }\" sections in custom rootmap file %s",
5735 rootmapfileNoBackslash.c_str());
5736 return -4;
5737 }
5738 if (!lineDirective.empty())
5739 uniqueString->Append(lineDirective);
5740 uniqueString->Append(line + '\n');
5741 }
5742 }
5743 const char firstChar = line[0];
5744 if (firstChar == '[') {
5745 // new section (library)
5746 auto brpos = line.find(']');
5747 if (brpos == string::npos)
5748 continue;
5749 lib_name = line.substr(1, brpos - 1);
5750 // Remove spaces at the beginning and at the end of the library name
5751 lib_name.erase(lib_name.find_last_not_of(' ') + 1);
5752 lib_name.erase(0, lib_name.find_first_not_of(' '));
5753 if (gDebug > 3) {
5754 TString lib_nameTstr(lib_name.c_str());
5755 TObjArray *tokens = lib_nameTstr.Tokenize(" ");
5756 const char *lib = ((TObjString *)tokens->At(0))->GetName();
5757 const char *wlib = gSystem->DynamicPathName(lib, kTRUE);
5758 if (wlib) {
5759 Info("ReadRootmapFile", "%s: New section for %s", rootmapfile, lib_nameTstr.Data());
5760 } else {
5761 Info("ReadRootmapFile", "%s: Section for %s (library does not exist)", rootmapfile, lib_nameTstr.Data());
5762 }
5763 delete[] wlib;
5764 delete tokens;
5765 }
5766 } else {
5767 auto keyLenIt = keyLenMap.find(firstChar);
5768 if (keyLenIt == keyLenMap.end())
5769 continue;
5770 unsigned int keyLen = keyLenIt->second;
5771 // Do not make a copy, just start after the key
5772 const char *keyname = line.c_str() + keyLen;
5773 if (gDebug > 6)
5774 Info("ReadRootmapFile", "%s: class %s in %s", rootmapfile, keyname, lib_name.c_str());
5776 if (isThere) {
5777 if (lib_name != isThere->GetValue()) { // the same key for two different libs
5778 if (firstChar == 'n') {
5779 if (gDebug > 3)
5780 Info("ReadRootmapFile",
5781 "While processing %s, namespace %s was found to be associated to %s although it is already "
5782 "associated to %s",
5783 rootmapfile, keyname, lib_name.c_str(), isThere->GetValue());
5784 } else if (firstChar == 'h') { // it is a header: add the libname to the list of libs to be loaded.
5785 lib_name += " ";
5786 lib_name += isThere->GetValue();
5787 fMapfile->SetValue(keyname, lib_name.c_str());
5788 } else if (!TClassEdit::IsSTLCont(keyname)) {
5789 Warning("ReadRootmapFile",
5790 "While processing %s, %s %s was found to be associated to %s although it is already "
5791 "associated to %s",
5792 rootmapfile, line.substr(0, keyLen - 1).c_str(), keyname, lib_name.c_str(),
5793 isThere->GetValue());
5794 }
5795 } else { // the same key for the same lib
5796 if (gDebug > 3)
5797 Info("ReadRootmapFile", "While processing %s, key %s was found to be already defined for %s",
5798 rootmapfile, keyname, lib_name.c_str());
5799 }
5800 } else {
5801 fMapfile->SetValue(keyname, lib_name.c_str());
5802 }
5803 }
5804 }
5805 file.close();
5806 return 0;
5807}
5808
5809////////////////////////////////////////////////////////////////////////////////
5810/// Create a resource table and read the (possibly) three resource files,
5811/// i.e. `$ROOTSYS/etc/system<name>` (or `ROOTETCDIR/system<name>`), `$HOME/<name>`
5812/// and `$PWD/<name>`. ROOT always reads ".rootrc" (in TROOT::InitSystem()). You
5813/// can read additional user defined resource files by creating additional TEnv
5814/// objects. By setting the shell variable ROOTENV_NO_HOME=1 the reading of
5815/// the `$HOME/<name>` resource file will be skipped. This might be useful in
5816/// case the home directory resides on an automounted remote file system
5817/// and one wants to avoid the file system from being mounted.
5818
5820{
5821 assert(requiresRootMap(name) && "We have a module!");
5822
5823 if (!requiresRootMap(name))
5824 return;
5825
5827
5829
5830 TString sname = "system";
5831 sname += name;
5834
5836 if (ret == -3) // old format
5838 if (!gSystem->Getenv("ROOTENV_NO_HOME")) {
5842 if (ret == -3) // old format
5846 if (ret == -3) // old format
5848 }
5849 } else {
5851 if (ret == -3) // old format
5853 }
5855}
5856
5857
5858namespace {
5859 using namespace clang;
5860
5861 class ExtVisibleStorageAdder: public RecursiveASTVisitor<ExtVisibleStorageAdder>{
5862 // This class is to be considered an helper for AutoLoading.
5863 // It is a recursive visitor is used to inspect namespaces and specializations
5864 // coming from forward declarations in rootmaps and to set the external visible
5865 // storage flag for them.
5866 public:
5867 ExtVisibleStorageAdder(std::unordered_set<const NamespaceDecl*>& nsSet): fNSSet(nsSet) {};
5868 bool VisitNamespaceDecl(NamespaceDecl* nsDecl) {
5869 // We want to enable the external lookup for this namespace
5870 // because it may shadow the lookup of other names contained
5871 // in that namespace
5872
5873 nsDecl->setHasExternalVisibleStorage();
5874 fNSSet.insert(nsDecl);
5875 return true;
5876 }
5878 // We want to enable the external lookup for this specialization
5879 // because we can provide a definition for it!
5880 if (specDecl->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
5881 //SpecSet.insert(specDecl);
5882 specDecl->setHasExternalLexicalStorage();
5883
5884 // No need to recurse. On the contrary, recursing is actively harmful:
5885 // NOTE: must not recurse to prevent this visitor from triggering loading from
5886 // the external AST source (i.e. autoloading). This would be triggered right here,
5887 // before autoloading is even set up, as rootmap file parsing happens before that.
5888 // Even if autoloading is off and has no effect, triggering loading from external
5889 // AST source resets the flag setHasExternalLexicalStorage(), hiding this specialization
5890 // from subsequent autoloads!
5891 return false;
5892 }
5893 private:
5894 std::unordered_set<const NamespaceDecl*>& fNSSet;
5895 };
5896}
5897
5898////////////////////////////////////////////////////////////////////////////////
5899/// Load map between class and library. If rootmapfile is specified a
5900/// specific rootmap file can be added (typically used by ACLiC).
5901/// In case of error -1 is returned, 0 otherwise.
5902/// The interpreter uses this information to automatically load the shared
5903/// library for a class (autoload mechanism), see the AutoLoad() methods below.
5904
5906{
5908 return 0;
5909
5911
5912 // open the [system].rootmap files
5913 if (!fMapfile) {
5914 fMapfile = new TEnv();
5918 InitRootmapFile(".rootmap");
5919 }
5920
5921 // Prepare a list of all forward declarations for cling
5922 // For some experiments it is easily as big as 500k characters. To be on the
5923 // safe side, we go for 1M.
5924 TUniqueString uniqueString(1048576);
5925
5926 // Load all rootmap files in the dynamic load path ((DY)LD_LIBRARY_PATH, etc.).
5927 // A rootmap file must end with the string ".rootmap".
5929 if (ldpath != fRootmapLoadPath) {
5931#ifdef WIN32
5932 TObjArray* paths = ldpath.Tokenize(";");
5933#else
5934 TObjArray* paths = ldpath.Tokenize(":");
5935#endif
5936 TString d;
5937 for (Int_t i = 0; i < paths->GetEntriesFast(); i++) {
5938 d = ((TObjString *)paths->At(i))->GetString();
5939 // check if directory already scanned
5940 Int_t skip = 0;
5941 for (Int_t j = 0; j < i; j++) {
5942 TString pd = ((TObjString *)paths->At(j))->GetString();
5943 if (pd == d) {
5944 skip++;
5945 break;
5946 }
5947 }
5948 if (!skip) {
5949 void* dirp = gSystem->OpenDirectory(d);
5950 if (dirp) {
5951 if (gDebug > 3) {
5952 Info("LoadLibraryMap", "%s", d.Data());
5953 }
5954 const char* f1;
5955 while ((f1 = gSystem->GetDirEntry(dirp))) {
5956 TString f = f1;
5957 if (f.EndsWith(".rootmap")) {
5958 TString p;
5959 p = d + "/" + f;
5961 if (!fRootmapFiles->FindObject(f) && f != ".rootmap") {
5962 if (gDebug > 4) {
5963 Info("LoadLibraryMap", " rootmap file: %s", p.Data());
5964 }
5966
5967 if (ret == 0)
5968 fRootmapFiles->Add(new TNamed(gSystem->BaseName(f), p.Data()));
5969 if (ret == -3) {
5970 // old format
5972 fRootmapFiles->Add(new TNamed(f, p));
5973 }
5974 }
5975 // else {
5976 // fprintf(stderr,"Reject %s because %s is already there\n",p.Data(),f.Data());
5977 // fRootmapFiles->FindObject(f)->ls();
5978 // }
5979 }
5980 }
5981 if (f.BeginsWith("rootmap")) {
5982 TString p;
5983 p = d + "/" + f;
5984 FileStat_t stat;
5985 if (gSystem->GetPathInfo(p, stat) == 0 && R_ISREG(stat.fMode)) {
5986 Warning("LoadLibraryMap", "please rename %s to end with \".rootmap\"", p.Data());
5987 }
5988 }
5989 }
5990 }
5992 }
5993 }
5994 delete paths;
5995 if (fMapfile->GetTable() && !fMapfile->GetTable()->GetEntries()) {
5996 return -1;
5997 }
5998 }
5999 if (rootmapfile && *rootmapfile) {
6001 if (res == 0) {
6002 //TString p = gSystem->ConcatFileName(gSystem->pwd(), rootmapfile);
6003 //fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), p.Data()));
6005 }
6006 else if (res == -3) {
6007 // old format
6012 }
6013 }
6014 TEnvRec* rec;
6015 TIter next(fMapfile->GetTable());
6016 while ((rec = (TEnvRec*) next())) {
6017 TString cls = rec->GetName();
6018 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
6019 // get the first lib from the list of lib and dependent libs
6020 TString libs = rec->GetValue();
6021 if (libs == "") {
6022 continue;
6023 }
6024 TString delim(" ");
6025 TObjArray* tokens = libs.Tokenize(delim);
6026 const char* lib = ((TObjString*)tokens->At(0))->GetName();
6027 // convert "@@" to "::", we used "@@" because TEnv
6028 // considers "::" a terminator
6029 cls.Remove(0, 8);
6030 cls.ReplaceAll("@@", "::");
6031 // convert "-" to " ", since class names may have
6032 // blanks and TEnv considers a blank a terminator
6033 cls.ReplaceAll("-", " ");
6034 if (gDebug > 6) {
6035 const char* wlib = gSystem->DynamicPathName(lib, kTRUE);
6036 if (wlib) {
6037 Info("LoadLibraryMap", "class %s in %s", cls.Data(), wlib);
6038 }
6039 else {
6040 Info("LoadLibraryMap", "class %s in %s (library does not exist)", cls.Data(), lib);
6041 }
6042 delete[] wlib;
6043 }
6044 delete tokens;
6045 }
6046 else if (!strncmp(cls.Data(), "Declare.", 8) && cls.Length() > 8) {
6047 cls.Remove(0, 8);
6048 // convert "-" to " ", since class names may have
6049 // blanks and TEnv considers a blank a terminator
6050 cls.ReplaceAll("-", " ");
6051 fInterpreter->declare(cls.Data());
6052 }
6053 }
6054
6055 // Process the forward declarations collected
6056 cling::Transaction* T = nullptr;
6057 auto compRes= fInterpreter->declare(uniqueString.Data(), &T);
6058 assert(cling::Interpreter::kSuccess == compRes && "A declaration in a rootmap could not be compiled");
6059
6060 if (compRes!=cling::Interpreter::kSuccess){
6061 Warning("LoadLibraryMap",
6062 "Problems in %s declaring '%s' were encountered.", rootmapfile, uniqueString.Data()) ;
6063 }
6064
6065 if (T) {
6066 ExtVisibleStorageAdder evsAdder(fNSFromRootmaps);
6067 for (auto declIt = T->decls_begin(); declIt < T->decls_end(); ++declIt) {
6068 if (declIt->m_DGR.isSingleDecl()) {
6069 if (Decl* D = declIt->m_DGR.getSingleDecl()) {
6070 if (clang::isa<TagDecl>(D) || clang::isa<NamespaceDecl>(D)) {
6071 evsAdder.TraverseDecl(D);
6072 }
6073 }
6074 }
6075 }
6076 }
6077
6078 // clear duplicates
6079
6080 return 0;
6081}
6082
6083////////////////////////////////////////////////////////////////////////////////
6084/// Scan again along the dynamic path for library maps. Entries for the loaded
6085/// shared libraries are unloaded first. This can be useful after reseting
6086/// the dynamic path through TSystem::SetDynamicPath()
6087/// In case of error -1 is returned, 0 otherwise.
6088
6095
6096////////////////////////////////////////////////////////////////////////////////
6097/// Reload the library map entries coming from all the loaded shared libraries,
6098/// after first unloading the current ones.
6099/// In case of error -1 is returned, 0 otherwise.
6100
6102{
6104 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6105 const Int_t nrSharedLibs = sharedLibL->GetEntriesFast();
6106 for (Int_t ilib = 0; ilib < nrSharedLibs; ilib++) {
6107 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6110 if (ret < 0) {
6111 continue;
6112 }
6114 if (sharedLibBaseStr.EndsWith(".dll")) {
6115 rootMapBaseStr.ReplaceAll(".dll", "");
6116 }
6117 else if (sharedLibBaseStr.EndsWith(".DLL")) {
6118 rootMapBaseStr.ReplaceAll(".DLL", "");
6119 }
6120 else if (sharedLibBaseStr.EndsWith(".so")) {
6121 rootMapBaseStr.ReplaceAll(".so", "");
6122 }
6123 else if (sharedLibBaseStr.EndsWith(".sl")) {
6124 rootMapBaseStr.ReplaceAll(".sl", "");
6125 }
6126 else if (sharedLibBaseStr.EndsWith(".dl")) {
6127 rootMapBaseStr.ReplaceAll(".dl", "");
6128 }
6129 else if (sharedLibBaseStr.EndsWith(".a")) {
6130 rootMapBaseStr.ReplaceAll(".a", "");
6131 }
6132 else {
6133 Error("ReloadAllSharedLibraryMaps", "Unknown library type %s", sharedLibBaseStr.Data());
6134 delete sharedLibL;
6135 return -1;
6136 }
6137 rootMapBaseStr += ".rootmap";
6139 if (!rootMap) {
6140 Error("ReloadAllSharedLibraryMaps", "Could not find rootmap %s in path", rootMapBaseStr.Data());
6141 delete[] rootMap;
6142 delete sharedLibL;
6143 return -1;
6144 }
6145 const Int_t status = LoadLibraryMap(rootMap);
6146 if (status < 0) {
6147 Error("ReloadAllSharedLibraryMaps", "Error loading map %s", rootMap);
6148 delete[] rootMap;
6149 delete sharedLibL;
6150 return -1;
6151 }
6152 delete[] rootMap;
6153 }
6154 delete sharedLibL;
6155 return 0;
6156}
6157
6158////////////////////////////////////////////////////////////////////////////////
6159/// Unload the library map entries coming from all the loaded shared libraries.
6160/// Returns 0 if succesful
6161
6163{
6165 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6166 for (Int_t ilib = 0; ilib < sharedLibL->GetEntriesFast(); ilib++) {
6167 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6170 }
6171 delete sharedLibL;
6172 return 0;
6173}
6174
6175////////////////////////////////////////////////////////////////////////////////
6176/// Unload library map entries coming from the specified library.
6177/// Returns -1 in case no entries for the specified library were found,
6178/// 0 otherwise.
6179
6181{
6182 if (!fMapfile || !library || !*library) {
6183 return 0;
6184 }
6186 Ssiz_t idx = libname.Last('.');
6187 if (idx != kNPOS) {
6188 libname.Remove(idx);
6189 }
6190 size_t len = libname.Length();
6191 TEnvRec *rec;
6192 TIter next(fMapfile->GetTable());
6194 Int_t ret = 0;
6195 while ((rec = (TEnvRec *) next())) {
6196 TString cls = rec->GetName();
6197 if (cls.Length() > 2) {
6198 // get the first lib from the list of lib and dependent libs
6199 TString libs = rec->GetValue();
6200 if (libs == "") {
6201 continue;
6202 }
6203 TString delim(" ");
6204 TObjArray* tokens = libs.Tokenize(delim);
6205 const char* lib = ((TObjString *)tokens->At(0))->GetName();
6206 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
6207 // convert "@@" to "::", we used "@@" because TEnv
6208 // considers "::" a terminator
6209 cls.Remove(0, 8);
6210 cls.ReplaceAll("@@", "::");
6211 // convert "-" to " ", since class names may have
6212 // blanks and TEnv considers a blank a terminator
6213 cls.ReplaceAll("-", " ");
6214 }
6215 if (!strncmp(lib, libname.Data(), len)) {
6216 if (fMapfile->GetTable()->Remove(rec) == nullptr) {
6217 Error("UnloadLibraryMap", "entry for <%s, %s> not found in library map table", cls.Data(), lib);
6218 ret = -1;
6219 }
6220 }
6221 delete tokens;
6222 }
6223 }
6224 if (ret >= 0) {
6226 if (!library_rootmap.EndsWith(".rootmap"))
6227 library_rootmap.Append(".rootmap");
6228 TNamed* mfile = nullptr;
6231 delete mfile;
6232 }
6234 }
6235 return ret;
6236}
6237
6238////////////////////////////////////////////////////////////////////////////////
6239/// Register the AutoLoading information for a class.
6240/// libs is a space separated list of libraries.
6241
6242Int_t TCling::SetClassSharedLibs(const char *cls, const char *libs)
6243{
6244 if (!cls || !*cls)
6245 return 0;
6246
6247 TString key = TString("Library.") + cls;
6248 // convert "::" to "@@", we used "@@" because TEnv
6249 // considers "::" a terminator
6250 key.ReplaceAll("::", "@@");
6251 // convert "-" to " ", since class names may have
6252 // blanks and TEnv considers a blank a terminator
6253 key.ReplaceAll(" ", "-");
6254
6256 if (!fMapfile) {
6257 fMapfile = new TEnv();
6259
6262
6263 InitRootmapFile(".rootmap");
6264 }
6265 //fMapfile->SetValue(key, libs);
6267 return 1;
6268}
6269
6270////////////////////////////////////////////////////////////////////////////////
6271/// Demangle the name (from the typeinfo) and then request the class
6272/// via the usual name based interface (TClass::GetClass).
6273
6274TClass *TCling::GetClass(const std::type_info& typeinfo, Bool_t load) const
6275{
6276 int err = 0;
6278 if (err) return nullptr;
6281 return theClass;
6282}
6283
6284////////////////////////////////////////////////////////////////////////////////
6285/// Load library containing the specified class. Returns 0 in case of error
6286/// and 1 in case if success.
6287
6288Int_t TCling::AutoLoad(const std::type_info& typeinfo, Bool_t knowDictNotLoaded /* = kFALSE */)
6289{
6290 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6291
6292 int err = 0;
6294 if (err) {
6295 return 0;
6296 }
6297
6298 std::string demangled_name(demangled_name_c);
6300
6301 // AutoLoad expects (because TClass::GetClass already prepares it that way) a
6302 // shortened name.
6305
6306 // No need to worry about typedef, they aren't any ... but there are
6307 // inlined namespaces ...
6308
6310 if (result == 0) {
6313 }
6314
6315 return result;
6316}
6317
6318////////////////////////////////////////////////////////////////////////////////
6319// Get the list of 'published'/'known' library for the class and load them.
6321{
6322 Int_t status = 0;
6323
6324 // lookup class to find list of dependent libraries
6326 if (!deplibs.IsNull()) {
6327 TString delim(" ");
6328 TObjArray* tokens = deplibs.Tokenize(delim);
6329 for (Int_t i = (tokens->GetEntriesFast() - 1); i > 0; --i) {
6330 const char* deplib = ((TObjString*)tokens->At(i))->GetName();
6331 if (gROOT->LoadClass(cls, deplib) == 0) {
6332 if (gDebug > 0) {
6333 gCling->Info("TCling::AutoLoad",
6334 "loaded dependent library %s for %s", deplib, cls);
6335 }
6336 }
6337 else {
6338 gCling->Error("TCling::AutoLoad",
6339 "failure loading dependent library %s for %s",
6340 deplib, cls);
6341 }
6342 }
6343 const char* lib = ((TObjString*)tokens->At(0))->GetName();
6344 if (lib && lib[0]) {
6345 if (gROOT->LoadClass(cls, lib) == 0) {
6346 if (gDebug > 0) {
6347 gCling->Info("TCling::AutoLoad",
6348 "loaded library %s for %s", lib, cls);
6349 }
6350 status = 1;
6351 }
6352 else {
6353 gCling->Error("TCling::AutoLoad",
6354 "failure loading library %s for %s", lib, cls);
6355 }
6356 }
6357 delete tokens;
6358 }
6359
6360 return status;
6361}
6362
6363////////////////////////////////////////////////////////////////////////////////
6364// Iterate through the data member of the class (either through the TProtoClass
6365// or through Cling) and trigger, recursively, the loading the necessary libraries.
6366// \note `cls` is expected to be already normalized!
6367// \returns 1 on success.
6368Int_t TCling::DeepAutoLoadImpl(const char *cls, std::unordered_set<std::string> &visited,
6369 bool nameIsNormalized)
6370{
6371 // Try to insert; if insertion failed because the entry existed, DeepAutoLoadImpl()
6372 // has previously (within the same call to `AutoLoad()`) tried to load this class
6373 // and we are done, whether success or not, as it won't work better now than before,
6374 // because there is no additional information now compared to before.
6375 if (!visited.insert(std::string(cls)).second)
6376 return 1;
6377
6378 if (ShallowAutoLoadImpl(cls) == 0) {
6379 // If ShallowAutoLoadImpl() has an error, we have an error.
6380 return 0;
6381 }
6382
6383 // Now look through the TProtoClass to load the required library/dictionary
6385 for (auto element : proto->GetData()) {
6386 if (element->IsBasic())
6387 continue;
6388 const char *subtypename = element->GetTypeName();
6390 // Failure to load a dictionary is not (quite) a failure load
6391 // the top-level library. If we return false here, then
6392 // we would end up in a situation where the library and thus
6393 // the dictionary is loaded for "cls" but the TClass is
6394 // not created and/or marked as unavailable (in case where
6395 // AutoLoad is called from TClass::GetClass).
6396 DeepAutoLoadImpl(subtypename, visited, true /*normalized*/);
6397 }
6398 }
6399 return 1;
6400 }
6401
6402 // We found no TProtoClass for cls.
6403 auto classinfo = gInterpreter->ClassInfo_Factory(cls);
6404 if (classinfo && gInterpreter->ClassInfo_IsValid(classinfo)
6405 && !(gInterpreter->ClassInfo_Property(classinfo) & kIsEnum))
6406 {
6408 while (gInterpreter->DataMemberInfo_Next(memberinfo)) {
6409 if (gInterpreter->DataMemberInfo_TypeProperty(memberinfo) & ::kIsFundamental)
6410 continue;
6411 auto membertypename = TClassEdit::GetLong64_Name(gInterpreter->TypeName(gInterpreter->DataMemberInfo_TypeTrueName(memberinfo)));
6413 // Failure to load a dictionary is not (quite) a failure load
6414 // the top-level library. See detailed comment in the TProtoClass
6415 // branch (above).
6416 (void)DeepAutoLoadImpl(membertypename.c_str(), visited, true /*normalized*/);
6417 }
6418 }
6419 gInterpreter->DataMemberInfo_Delete(memberinfo);
6420 }
6421 gInterpreter->ClassInfo_Delete(classinfo);
6422 return 1;
6423}
6424
6425////////////////////////////////////////////////////////////////////////////////
6426/// Load library containing the specified class. Returns 0 in case of error
6427/// and 1 in case if success.
6428
6430{
6431 // Prevent update to IsClassAutoloading between our check and our actions.
6433
6434 // TClass::GetClass explicitly calls gInterpreter->AutoLoad. When called from
6435 // rootcling (in *_rdict.pcm file generation) it is a no op.
6436 // FIXME: We should avoid calling autoload when we know we are not supposed
6437 // to and transform this check into an assert.
6439 // Never load any library from rootcling/genreflex.
6440 if (gDebug > 2) {
6441 Info("TCling::AutoLoad", "Explicitly disabled (the class name is %s)", cls);
6442 }
6443 return 0;
6444 }
6445
6446 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6447
6449
6451 // The library is already loaded as the class's dictionary is known.
6452 // Return success.
6453 // Note: the name (cls) is expected to be normalized as it comes either
6454 // from a callbacks (that can/should calculate the normalized name from the
6455 // decl) or from TClass::GetClass (which does also calculate the normalized
6456 // name).
6457 return 1;
6458 }
6459
6460 if (gDebug > 2) {
6461 Info("TCling::AutoLoad",
6462 "Trying to autoload for %s", cls);
6463 }
6464
6465 if (!gROOT || !gInterpreter || gROOT->TestBit(TObject::kInvalidObject)) {
6466 if (gDebug > 2) {
6467 Info("TCling::AutoLoad",
6468 "Disabled due to gROOT or gInterpreter being invalid/not ready (the class name is %s)", cls);
6469 }
6470 return 0;
6471 }
6472 // Prevent the recursion when the library dictionary are loaded.
6474 // Try using externally provided callback first.
6475 if (fAutoLoadCallBack) {
6477 if (success)
6478 return success;
6479 }
6480
6481 // During the 'Deep' part of the search we will call GetClassSharedLibsForModule
6482 // (when module are enabled) which might end up calling AutoParsing but
6483 // that should only be for the cases where the library has no generated pcm
6484 // and in that case a rootmap should be available.
6485 // This avoids a very costly operation (for generally no gain) but reduce the
6486 // quality of the search (i.e. bad in case of library with no pcm and no rootmap
6487 // file).
6489 std::unordered_set<std::string> visited;
6490 return DeepAutoLoadImpl(cls, visited, false /*normalized*/);
6491}
6492
6493////////////////////////////////////////////////////////////////////////////////
6494/// Parse the payload or header.
6495
6496static cling::Interpreter::CompilationResult ExecAutoParse(const char *what,
6497 Bool_t header,
6498 cling::Interpreter *interpreter)
6499{
6500 std::string code = gNonInterpreterClassDef ;
6501 if (!header) {
6502 // This is the complete header file content and not the
6503 // name of a header.
6504 code += what;
6505
6506 } else {
6507 code += ("#include \"");
6508 code += what;
6509 code += "\"\n";
6510 }
6511 code += ("#ifdef __ROOTCLING__\n"
6512 "#undef __ROOTCLING__\n"
6514 "#endif");
6515
6516 cling::Interpreter::CompilationResult cr;
6517 {
6518 // scope within which diagnostics are de-activated
6519 // For now we disable diagnostics because we saw them already at
6520 // dictionary generation time. That won't be an issue with the PCMs.
6521
6522 Sema &SemaR = interpreter->getSema();
6524 clangDiagSuppr diagSuppr(SemaR.getDiagnostics());
6525
6526 #if defined(R__MUST_REVISIT)
6527 #if R__MUST_REVISIT(6,2)
6528 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
6529 #endif
6530 #endif
6531
6532 cr = interpreter->parseForModule(code);
6533 }
6534 return cr;
6535}
6536
6537////////////////////////////////////////////////////////////////////////////////
6538/// Helper routine for TCling::AutoParse implementing the actual call to the
6539/// parser and looping over template parameters (if
6540/// any) and when they don't have a registered header to autoparse,
6541/// recurse over their template parameters.
6542///
6543/// Returns the number of header parsed.
6544
6546{
6547 // We assume the lock has already been taken.
6548 // R__LOCKGUARD(gInterpreterMutex);
6549
6551 unsigned long offset = 0;
6552 if (strncmp(cls, "const ", 6) == 0) {
6553 offset = 6;
6554 }
6555
6556 // Loop on the possible autoparse keys
6557 bool skipFirstEntry = false;
6558 std::vector<std::string> autoparseKeys;
6559 if (strchr(cls, '<')) {
6560 int nestedLoc = 0;
6562 // Check if we can skip the name of the template in the autoparses
6563 // Take all the scopes one by one. If all of them are in the AST, we do not
6564 // need to autoparse for that particular template.
6565 if (!autoparseKeys.empty() && !autoparseKeys[0].empty()) {
6566 // autoparseKeys[0] is empty when the input is not a template instance.
6567 // The case strchr(cls, '<') != 0 but still not a template instance can
6568 // happens 'just' for string (GetSplit replaces the template by the short name
6569 // and then use that for thew splitting)
6571 auto tokens = templateName.Tokenize("::");
6572 clang::NamedDecl* previousScopeAsNamedDecl = nullptr;
6573 clang::DeclContext* previousScopeAsContext = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
6575 previousScopeAsContext = fInterpreter->getSema().getStdNamespace();
6576 auto nTokens = tokens->GetEntriesFast();
6577 for (Int_t tk = 0; tk < nTokens; ++tk) {
6578 auto scopeObj = tokens->UncheckedAt(tk);
6579 auto scopeName = ((TObjString*) scopeObj)->String().Data();
6580 previousScopeAsNamedDecl = cling::utils::Lookup::Named(&fInterpreter->getSema(), scopeName, previousScopeAsContext);
6581 // Check if we have multiple nodes in the AST with this name
6582 if ((clang::NamedDecl*)-1 == previousScopeAsNamedDecl) break;
6583 previousScopeAsContext = llvm::dyn_cast_or_null<clang::DeclContext>(previousScopeAsNamedDecl);
6584 if (!previousScopeAsContext) break; // this is not a context
6585 }
6586 delete tokens;
6587 // Now, let's check if the last scope, the template, has a definition, i.e. it's not a fwd decl
6588 if ((clang::NamedDecl*)-1 != previousScopeAsNamedDecl) {
6589 if (auto templateDecl = llvm::dyn_cast_or_null<clang::ClassTemplateDecl>(previousScopeAsNamedDecl)) {
6590 if (auto templatedDecl = templateDecl->getTemplatedDecl()) {
6591 skipFirstEntry = templatedDecl->hasDefinition();
6592 }
6593 }
6594 }
6595
6596 }
6597 }
6598 if (topLevel) autoparseKeys.emplace_back(cls);
6599
6600 for (const auto & apKeyStr : autoparseKeys) {
6601 if (skipFirstEntry) {
6602 skipFirstEntry=false;
6603 continue;
6604 }
6605 if (apKeyStr.empty()) continue;
6606 const char *apKey = apKeyStr.c_str();
6608 // If the class was not looked up
6609 if (gDebug > 1) {
6610 Info("TCling::AutoParse",
6611 "Starting autoparse for %s\n", apKey);
6612 }
6613 if (fLookedUpClasses.insert(normNameHash).second) {
6614 auto const &iter = fClassesHeadersMap.find(normNameHash);
6615 if (iter != fClassesHeadersMap.end()) {
6616 const cling::Transaction *T = fInterpreter->getCurrentTransaction();
6618 auto const &hNamesPtrs = iter->second;
6619 if (gDebug > 1) {
6620 Info("TCling::AutoParse",
6621 "We can proceed for %s. We have %s headers.", apKey, std::to_string(hNamesPtrs.size()).c_str());
6622 }
6623 for (auto & hName : hNamesPtrs) {
6624 if (fParsedPayloadsAddresses.count(hName) == 1) continue;
6625 if (0 != fPayloads.count(normNameHash)) {
6626 float initRSSval=0.f, initVSIZEval=0.f;
6627 (void) initRSSval; // Avoid unused var warning
6628 (void) initVSIZEval;
6629 if (gDebug > 0) {
6630 Info("AutoParse",
6631 "Parsing full payload for %s", apKey);
6634 initRSSval = 1e-3*info.fMemResident;
6635 initVSIZEval = 1e-3*info.fMemVirtual;
6636 }
6638 if (cRes != cling::Interpreter::kSuccess) {
6639 if (hName[0] == '\n')
6640 Error("AutoParse", "Error parsing payload code for class %s with content:\n%s", apKey, hName);
6641 } else {
6644 if (gDebug > 0){
6647 float endRSSval = 1e-3*info.fMemResident;
6648 float endVSIZEval = 1e-3*info.fMemVirtual;
6649 Info("Autoparse", ">>> RSS key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initRSSval, endRSSval, endRSSval-initRSSval);
6650 Info("Autoparse", ">>> VSIZE key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initVSIZEval, endVSIZEval, endVSIZEval-initVSIZEval);
6651 }
6652 }
6653 } else if (!IsLoaded(hName)) {
6654 if (gDebug > 0) {
6655 Info("AutoParse",
6656 "Parsing single header %s", hName);
6657 }
6659 if (cRes != cling::Interpreter::kSuccess) {
6660 Error("AutoParse", "Error parsing headerfile %s for class %s.", hName, apKey);
6661 } else {
6663 }
6664 }
6665 }
6666 }
6667 else {
6668 // There is no header registered for this class, if this a
6669 // template, it will be instantiated if/when it is requested
6670 // and if we do no load/parse its components we might end up
6671 // not using an eventual specialization.
6672 if (strchr(apKey, '<')) {
6674 }
6675 }
6676 }
6677 }
6678
6679 if (nHheadersParsed) {
6680 // Register that we did autoparsing for this class.
6681 fAutoParseClasses.insert(cls);
6682 if (gDebug)
6683 Info("AutoParse", "Parsed %d headers for %s", nHheadersParsed, cls);
6684 }
6685 return nHheadersParsed;
6686
6687}
6688
6689////////////////////////////////////////////////////////////////////////////////
6690/// Parse the headers relative to the class
6691/// Returns 1 in case of success, 0 in case of failure
6692
6694{
6695 if (llvm::StringRef(cls).contains("(lambda)"))
6696 return 0;
6697
6700 return AutoLoad(cls);
6701 } else {
6702 return 0;
6703 }
6704 }
6705
6707
6708 if (gDebug > 1) {
6709 Info("TCling::AutoParse",
6710 "Trying to autoparse for %s", cls);
6711 }
6712
6713 // The catalogue of headers is in the dictionary
6715 && !gClassTable->GetDictNorm(cls)) {
6716 // Need RAII against recursive (dictionary payload) parsing (ROOT-8445).
6718 fInterpreter->getSema());
6719 AutoLoad(cls, true /*knowDictNotLoaded*/);
6720 }
6721
6722 // Prevent the recursion when the library dictionary are loaded.
6724
6725 // No recursive header parsing on demand; we require headers to be standalone.
6727
6728 Int_t nHheadersParsed = AutoParseImplRecurse(cls,/*topLevel=*/ true);
6729
6731
6732 return nHheadersParsed > 0 ? 1 : 0;
6733}
6734
6735// This is a function which gets callback from cling when DynamicLibraryManager->loadLibrary failed for some reason.
6736// Try to solve the problem by AutoLoading. Return true when AutoLoading success, return
6737// false if not.
6738bool TCling::LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
6739{
6741 if (errMsg.contains("undefined symbol: ")) {
6742 // This branch is taken when the callback was from DynamicLibraryManager::loadLibrary
6743 std::string mangled_name = std::string(errMsg.split("undefined symbol: ").second);
6744 void* res = ((TCling*)gCling)->LazyFunctionCreatorAutoload(mangled_name);
6745 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
6746 if (res && DLM && (DLM->loadLibrary(libStem, permanent, resolved) == cling::DynamicLibraryManager::kLoadLibSuccess))
6747 // Return success when LazyFunctionCreatorAutoload could find mangled_name
6748 return true;
6749 } else {
6750 // The callback is from IncrementalExecutor::diagnoseUnresolvedSymbols
6752 return true;
6753 }
6754
6755 return false;
6756}
6757
6758////////////////////////////////////////////////////////////////////////////////
6759/// Autoload a library based on a missing symbol.
6760
6763
6764 // We have already loaded the library.
6765 if (void* Addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name))
6766 return Addr;
6767
6768 const cling::DynamicLibraryManager &DLM = *GetInterpreterImpl()->getDynamicLibraryManager();
6770
6771 auto LibLoader = [](const std::string& LibName) -> bool {
6772 if (gSystem->Load(LibName.c_str(), "", false) < 0) {
6773 ::Error("TCling__LazyFunctionCreatorAutoloadForModule",
6774 "Failed to load library %s", LibName.c_str());
6775 return false;
6776 }
6777 return true; //success.
6778 };
6779
6780 std::string libName = DLM.searchLibrariesForSymbol(mangled_name,
6781 /*searchSystem=*/ true);
6782
6783 assert(!llvm::StringRef(libName).starts_with("libNew") && "We must not resolve symbols from libNew!");
6784
6785 if (libName.empty())
6786 return nullptr;
6787
6788 if (!LibLoader(libName))
6789 return nullptr;
6790
6792 return llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name);
6793}
6794
6795////////////////////////////////////////////////////////////////////////////////
6796
6798{
6799 return fNSFromRootmaps.count(nsDecl) != 0;
6800}
6801
6802////////////////////////////////////////////////////////////////////////////////
6803/// Internal function. Actually do the update of the ClassInfo when seeing
6804// new TagDecl or NamespaceDecl.
6805void TCling::RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
6806{
6807
6809 if (cci) {
6810 // If we only had a forward declaration then update the
6811 // TClingClassInfo with the definition if we have it now.
6812 const NamedDecl *oldDef = llvm::dyn_cast_or_null<NamedDecl>(cci->GetDecl());
6813 if (!oldDef || (def && def != oldDef)) {
6814 cl->ResetCaches();
6815 TClass::RemoveClassDeclId(cci->GetDeclId());
6816 if (def) {
6817 if (cci->GetType()) {
6818 // It's a tag decl, not a namespace decl.
6819 cci->Init(*cci->GetType());
6820 TClass::AddClassToDeclIdMap(cci->GetDeclId(), cl);
6821 } else {
6822 Error("RefreshClassInfo", "Should not need to update the classInfo a non type decl: %s", oldDef->getNameAsString().c_str());
6823 }
6824 }
6825 }
6826 } else if (!cl->TestBit(TClass::kLoading) && !cl->fHasRootPcmInfo) {
6827 cl->ResetCaches();
6828 if (strncmp(cl->GetName(),"tuple<",strlen("tuple<"))==0) {
6829 // We need to use the Emulated Tuple but we should not trigger parsing
6830 // yet, so delay the creation of the ClassInfo
6831 delete ((TClingClassInfo *)cl->fClassInfo);
6832 cl->fClassInfo = nullptr;
6833 cl->fCanLoadClassInfo = true;
6835 if (cl->fState != TClass::kHasTClassInit) {
6837 }
6838 return;
6839 }
6840 // yes, this is almost a waste of time, but we do need to lookup
6841 // the 'type' corresponding to the TClass anyway in order to
6842 // preserve the opaque typedefs (Double32_t)
6843 if (!alias && def != nullptr)
6845 else
6847 if (((TClingClassInfo *)cl->fClassInfo)->IsValid()) {
6848 // We now need to update the state and bits.
6849 if (cl->fState != TClass::kHasTClassInit) {
6850 // if (!cl->fClassInfo->IsValid()) cl->fState = TClass::kForwardDeclared; else
6852 }
6853 TClass::AddClassToDeclIdMap(((TClingClassInfo *)(cl->fClassInfo))->GetDeclId(), cl);
6854 } else {
6855 delete ((TClingClassInfo *)cl->fClassInfo);
6856 cl->fClassInfo = nullptr;
6857 }
6858 }
6859}
6860
6861////////////////////////////////////////////////////////////////////////////////
6862/// Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
6864{
6865 const TagDecl *td = dyn_cast<TagDecl>(ND);
6867 const NamedDecl *canon = nullptr;
6868
6869 std::string name;
6870 TagDecl* tdDef = nullptr;
6871 if (td) {
6872 canon = tdDef = td->getDefinition();
6873 // Let's pass the decl to the TClass only if it has a definition.
6874 if (!tdDef) return;
6875
6876 if (!tdDef->isCompleteDefinition() || llvm::isa<clang::FunctionDecl>(tdDef->getDeclContext())) {
6877 // Ignore incomplete definition.
6878 // Ignore declaration within a function.
6879 return;
6880 }
6881
6882 auto declName = tdDef->getNameAsString();
6883 // Check if we have registered the unqualified name into the list
6884 // of TClass that are in kNoInfo, kEmulated or kFwdDeclaredState.
6885 // Since this is used as heureutistic to avoid spurrious calls to GetNormalizedName
6886 // the unqualified name is sufficient (and the fully qualified name might be
6887 // 'wrong' if there is difference in spelling in the template paramters (for example)
6889 // fprintf (stderr,"WARNING: Impossible to find a TClassEntry in kNoInfo or kEmulated the decl of which would be called %s. Skip w/o building the normalized name.\n",declName.c_str() );
6890 return;
6891 }
6892
6893 clang::QualType type = tdDef->getASTContext().getCanonicalTagType(tdDef);
6895 } else if (ns) {
6896 canon = ns->getCanonicalDecl();
6897 name = ND->getQualifiedNameAsString();
6898 } else {
6899 name = ND->getQualifiedNameAsString();
6900 }
6901
6902 // Supposedly we are being called while something is being
6903 // loaded ... let's now tell the autoloader to do the work
6904 // yet another time.
6906 // FIXME: There can be more than one TClass for a single decl.
6907 // for example vector<double> and vector<Double32_t>
6908 TClass* cl = (TClass*)gROOT->GetListOfClasses()->FindObject(name.c_str());
6909 if (cl && GetModTClasses().find(cl) == GetModTClasses().end()) {
6910 RefreshClassInfo(cl, canon, false);
6911 }
6912 // And here we should find the other 'aliases' (eg. vector<Double32_t>)
6913 // and update them too:
6914 // foreach(aliascl in gROOT->GetListOfClasses()->FindAliasesOf(name.c_str()))
6915 // RefreshClassInfo(cl, tdDef, true);
6916}
6917
6918////////////////////////////////////////////////////////////////////////////////
6919/// No op: see TClingCallbacks
6920
6924
6925//______________________________________________________________________________
6926//FIXME: Factor out that function in TClass, because TClass does it already twice
6928{
6929 // This is a no-op as part of the API.
6930 // TCling uses UpdateClassInfoWithDecl() instead.
6931}
6932
6933////////////////////////////////////////////////////////////////////////////////
6934/// Update all canvases at end the terminal input command.
6935
6937{
6938 TIter next(gROOT->GetListOfCanvases());
6939 TVirtualPad* canvas;
6940 while ((canvas = (TVirtualPad*)next())) {
6941 canvas->Update();
6942 }
6943}
6944
6945////////////////////////////////////////////////////////////////////////////////
6946
6947void TCling::UpdateListsOnCommitted(const cling::Transaction &T) {
6948 std::set<TClass*> modifiedTClasses; // TClasses that require update after this transaction
6949
6950 // If the transaction does not contain anything we can return earlier.
6951 if (!HandleNewTransaction(T)) return;
6952
6953 bool isTUTransaction = false;
6954 if (!T.empty() && T.decls_begin() + 1 == T.decls_end() && !T.hasNestedTransactions()) {
6955 clang::Decl* FirstDecl = *(T.decls_begin()->m_DGR.begin());
6956 if (llvm::isa<clang::TranslationUnitDecl>(FirstDecl)) {
6957 // The is the first transaction, we have to expose to meta
6958 // what's already in the AST.
6959 isTUTransaction = true;
6960 }
6961 }
6962
6963 std::set<const void*> TransactionDeclSet;
6964 if (!isTUTransaction && T.decls_end() - T.decls_begin()) {
6965 const clang::Decl* WrapperFD = T.getWrapperFD();
6966 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6967 I != E; ++I) {
6968 if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl
6969 && I->m_Call != cling::Transaction::kCCIHandleTagDeclDefinition)
6970 continue;
6971
6972 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6973 DE = I->m_DGR.end(); DI != DE; ++DI) {
6974 if (*DI == WrapperFD)
6975 continue;
6976 TransactionDeclSet.insert(*DI);
6977 ((TCling*)gCling)->HandleNewDecl(*DI, false, modifiedTClasses);
6978 }
6979 }
6980 }
6981
6982 // The above might trigger more decls to be deserialized.
6983 // Thus the iteration over the deserialized decls must be last.
6984 for (cling::Transaction::const_iterator I = T.deserialized_decls_begin(),
6985 E = T.deserialized_decls_end(); I != E; ++I) {
6986 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6987 DE = I->m_DGR.end(); DI != DE; ++DI)
6988 if (TransactionDeclSet.find(*DI) == TransactionDeclSet.end()) {
6989 //FIXME: HandleNewDecl should take DeclGroupRef
6990 ((TCling*)gCling)->HandleNewDecl(*DI, /*isDeserialized*/true,
6992 }
6993 }
6994
6995
6996 // When fully building the reflection info in TClass, a deserialization
6997 // could be triggered, which may result in request for building the
6998 // reflection info for the same TClass. This in turn will clear the caches
6999 // for the TClass in-flight and cause null ptr derefs.
7000 // FIXME: This is a quick fix, solving most of the issues. The actual
7001 // question is: Shouldn't TClass provide a lock mechanism on update or lock
7002 // itself until the update is done.
7003 //
7004 std::vector<TClass*> modifiedTClassesDiff(modifiedTClasses.size());
7005 std::vector<TClass*>::iterator it;
7007 ((TCling*)gCling)->GetModTClasses().begin(),
7008 ((TCling*)gCling)->GetModTClasses().end(),
7011
7012 // Lock the TClass for updates
7013 ((TCling*)gCling)->GetModTClasses().insert(modifiedTClassesDiff.begin(),
7015 for (std::vector<TClass*>::const_iterator I = modifiedTClassesDiff.begin(),
7016 E = modifiedTClassesDiff.end(); I != E; ++I) {
7017 // Make sure the TClass has not been deleted.
7018 if (!gROOT->GetListOfClasses()->FindObject(*I)) {
7019 continue;
7020 }
7021 // Could trigger deserialization of decls.
7022 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
7023 // Unlock the TClass for updates
7024 ((TCling*)gCling)->GetModTClasses().erase(*I);
7025
7026 }
7027}
7028
7029///\brief Invalidate stored TCling state for declarations included in transaction `T'.
7030///
7031void TCling::UpdateListsOnUnloaded(const cling::Transaction &T)
7032{
7034
7035 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
7036 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
7037 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
7038 (TListOfEnums *)gROOT->GetListOfEnums());
7039
7040 cling::Transaction::const_nested_iterator iNested = T.nested_begin();
7041 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
7042 I != E; ++I) {
7043 if (I->m_Call == cling::Transaction::kCCIHandleVTable)
7044 continue;
7045 if (I->m_Call == cling::Transaction::kCCINone) {
7047 ++iNested;
7048 continue;
7049 }
7050
7051 for (auto &D : I->m_DGR)
7053 }
7054}
7055
7056///\brief Invalidate cached TCling information for the given global declaration.
7057///
7059 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
7060 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
7061 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
7062 (TListOfEnums *)gROOT->GetListOfEnums());
7064}
7065
7066///\brief Invalidate cached TCling information for the given declaration, and
7067/// removed it from the appropriate object list.
7068///\param[in] Lists - std::tuple<TListOfDataMembers&, TListOfFunctions&,
7069/// TListOfFunctionTemplates&, TListOfEnums&>
7070/// of pointers to the (global/class) object lists.
7071///\param[in] D - Decl to discard.
7072///
7076 TListOfEnums*> &Lists, const Decl *D) {
7077 if (D->isFromASTFile()) // `D' came from the PCH; ignore
7078 return;
7079
7080 TListOfDataMembers &LODM = *(std::get<0>(Lists));
7081 TListOfFunctions &LOF = *(std::get<1>(Lists));
7082 TListOfFunctionTemplates &LOFT = *(std::get<2>(Lists));
7083 TListOfEnums &LOE = *(std::get<3>(Lists));
7084
7086 TObject *O = LODM.Find((TDictionary::DeclId_t)D);
7087 if (LODM.GetClass())
7088 RemoveAndInvalidateObject(LODM, static_cast<TDataMember *>(O));
7089 else
7090 RemoveAndInvalidateObject(LODM, static_cast<TGlobal *>(O));
7091 } else if (isa<FunctionDecl>(D)) {
7093 } else if (isa<FunctionTemplateDecl>(D)) {
7095 } else if (isa<EnumDecl>(D)) {
7096 TEnum *E = LOE.Find((TDictionary::DeclId_t)D);
7097 if (!E)
7098 return;
7099
7100 // Try to invalidate enumerators (for unscoped enumerations).
7101 for (TIter I = E->GetConstants(); auto EC = (TEnumConstant *)I(); )
7103 (TEnumConstant *)LODM.FindObject(EC->GetName()));
7104
7106 } else if (isa<RecordDecl>(D) || isa<NamespaceDecl>(D)) {
7108 return;
7109
7110 std::vector<TClass *> Classes;
7111 if (!TClass::GetClass(D->getCanonicalDecl(), Classes))
7112 return;
7113 for (auto &C : Classes) {
7114 auto Lists = std::make_tuple((TListOfDataMembers *)C->GetListOfDataMembers(),
7115 (TListOfFunctions *)C->GetListOfMethods(),
7116 (TListOfFunctionTemplates *)C->GetListOfFunctionTemplates(),
7117 (TListOfEnums *)C->GetListOfEnums());
7118 for (auto &I : cast<DeclContext>(D)->decls())
7120
7121 // For NamespaceDecl (redeclarable), only invalidate this redecl.
7122 if (D->getKind() != Decl::Namespace || cast<NamespaceDecl>(D)->isFirstDecl())
7123 C->ResetClassInfo();
7124 }
7125 }
7126}
7127
7128////////////////////////////////////////////////////////////////////////////////
7129// If an autoparse was done during a transaction and that it is rolled back,
7130// we need to make sure the next request for the same autoparse will be
7131// honored.
7132void TCling::TransactionRollback(const cling::Transaction &T) {
7133 auto const &triter = fTransactionHeadersMap.find(&T);
7134 if (triter != fTransactionHeadersMap.end()) {
7135 std::size_t normNameHash = triter->second;
7136
7138
7139 auto const &iter = fClassesHeadersMap.find(normNameHash);
7140 if (iter != fClassesHeadersMap.end()) {
7141 auto const &hNamesPtrs = iter->second;
7142 for (auto &hName : hNamesPtrs) {
7143 if (gDebug > 0) {
7144 Info("TransactionRollback",
7145 "Restoring ability to autoaparse: %s", hName);
7146 }
7148 }
7149 }
7150 }
7151}
7152
7153////////////////////////////////////////////////////////////////////////////////
7154
7155void TCling::LibraryLoaded(const void* dyLibHandle, const char* canonicalName) {
7156// R__LOCKGUARD_CLING(gInterpreterMutex);
7157// UpdateListOfLoadedSharedLibraries();
7158}
7159
7160////////////////////////////////////////////////////////////////////////////////
7161
7162void TCling::LibraryUnloaded(const void* dyLibHandle, const char* canonicalName) {
7163 fPrevLoadedDynLibInfo = nullptr;
7164 fSharedLibs = "";
7165}
7166
7167////////////////////////////////////////////////////////////////////////////////
7168/// Return the list of shared libraries loaded into the process.
7169
7176
7177static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH, bool skipCore)
7178{
7179 if (!cls || !*cls)
7180 return {};
7181
7182 using namespace clang;
7183 if (const Decl *D = LH.findScope(cls, cling::LookupHelper::NoDiagnostics,
7184 /*type*/ nullptr, /*instantiate*/ false)) {
7185 if (!D->isFromASTFile()) {
7186 if (gDebug > 5)
7187 Warning("GetClassSharedLibsForModule", "Decl found for %s is not part of a module", cls);
7188 return {};
7189 }
7190 class ModuleCollector : public ConstDeclVisitor<ModuleCollector> {
7191 llvm::DenseSet<Module *> &m_TopLevelModules;
7192
7193 public:
7194 ModuleCollector(llvm::DenseSet<Module *> &TopLevelModules) : m_TopLevelModules(TopLevelModules) {}
7195 void Collect(const Decl *D) { Visit(D); }
7196
7197 void VisitDecl(const Decl *D)
7198 {
7199 // FIXME: Such case is described ROOT-7765 where
7200 // ROOT_GENERATE_DICTIONARY does not contain the list of headers.
7201 // They are specified as #includes in the LinkDef file. This leads to
7202 // generation of incomplete modulemap files and this logic fails to
7203 // compute the corresponding module of D.
7204 // FIXME: If we want to support such a case, we should not rely on
7205 // the contents of the modulemap but mangle D and look it up in the
7206 // .so files.
7207 if (!D->hasOwningModule())
7208 return;
7209 if (Module *M = D->getOwningModule()->getTopLevelModule())
7210 m_TopLevelModules.insert(M);
7211 }
7212
7214 {
7215 switch (TA.getKind()) {
7216 case TemplateArgument::Null:
7217 case TemplateArgument::Integral:
7218 case TemplateArgument::Pack:
7219 case TemplateArgument::NullPtr:
7220 case TemplateArgument::StructuralValue:
7221 case TemplateArgument::Expression:
7222 case TemplateArgument::Template:
7223 case TemplateArgument::TemplateExpansion: return;
7224 case TemplateArgument::Type:
7225 if (const TagType *TagTy = dyn_cast<TagType>(TA.getAsType()))
7226 return Visit(TagTy->getDecl());
7227 return;
7228 case TemplateArgument::Declaration: return Visit(TA.getAsDecl());
7229 }
7230 llvm_unreachable("Invalid TemplateArgument::Kind!");
7231 }
7232
7234 {
7235 if (CTSD->getOwningModule())
7236 VisitDecl(CTSD);
7237 else
7238 VisitDecl(CTSD->getSpecializedTemplate());
7239 const TemplateArgumentList &ArgList = CTSD->getTemplateArgs();
7240 for (const TemplateArgument *Arg = ArgList.data(), *ArgEnd = Arg + ArgList.size(); Arg != ArgEnd; ++Arg) {
7242 }
7243 }
7244 };
7245
7246 llvm::DenseSet<Module *> TopLevelModules;
7248 m.Collect(D);
7249 std::string result;
7250 for (auto M : TopLevelModules) {
7251 // ROOT-unaware modules (i.e. not processed by rootcling) do not have a
7252 // link declaration.
7253 if (!M->LinkLibraries.size())
7254 continue;
7255 // We have preloaded the Core module thus libCore.so
7256 if (M->Name == "Core" && skipCore)
7257 continue;
7258 assert(M->LinkLibraries.size() == 1);
7259 if (!result.empty())
7260 result += ' ';
7261 result += M->LinkLibraries[0].Library;
7262 }
7263 return result;
7264 }
7265 return {};
7266}
7267
7268////////////////////////////////////////////////////////////////////////////////
7269/// Get the list of shared libraries containing the code for class cls.
7270/// The first library in the list is the one containing the class, the
7271/// others are the libraries the first one depends on. Returns 0
7272/// in case the library is not found.
7273/// \param cls the name of the class
7274/// \param skipCore if true (default), remove "Core" from the returned list
7275
7276const char* TCling::GetClassSharedLibs(const char* cls, bool skipCore)
7277{
7278 if (fCxxModulesEnabled) {
7279 // Lock the interpreter mutex before interacting with cling.
7280 // TODO: Can we move this further deep? In principle the lock should be in
7281 // GetClassSharedLibsForModule, but it might be needed also for
7282 // getLookupHelper?
7284 llvm::StringRef className = cls;
7285 // If we get a class name containing lambda, we cannot parse it and we
7286 // can exit early.
7287 // FIXME: This works around a bug when we are instantiating a template
7288 // make_unique and the substitution fails. Seen in most of the dataframe
7289 // tests.
7290 if (className.contains("(lambda)"))
7291 return nullptr;
7292 // Limit the recursion which can be induced by GetClassSharedLibsForModule.
7294 cling::LookupHelper &LH = fInterpreter->getLookupHelper();
7296 if (!libs.empty()) {
7297 fAutoLoadLibStorage.push_back(libs);
7298 return fAutoLoadLibStorage.back().c_str();
7299 }
7300 }
7301
7302 if (!cls || !*cls) {
7303 return nullptr;
7304 }
7305 // lookup class to find list of libraries
7306 if (fMapfile) {
7307 TEnvRec* libs_record = nullptr;
7309 if (libs_record) {
7310 const char* libs = libs_record->GetValue();
7311 return (*libs) ? libs : nullptr;
7312 }
7313 else {
7314 // Try the old format...
7315 TString c = TString("Library.") + cls;
7316 // convert "::" to "@@", we used "@@" because TEnv
7317 // considers "::" a terminator
7318 c.ReplaceAll("::", "@@");
7319 // convert "-" to " ", since class names may have
7320 // blanks and TEnv considers a blank a terminator
7321 c.ReplaceAll(" ", "-");
7322 // Use TEnv::Lookup here as the rootmap file must start with Library.
7323 // and do not support using any stars (so we do not need to waste time
7324 // with the search made by TEnv::GetValue).
7325 TEnvRec* libs_record = nullptr;
7327 if (libs_record) {
7328 const char* libs = libs_record->GetValue();
7329 return (*libs) ? libs : nullptr;
7330 }
7331 }
7332 }
7333 return nullptr;
7334}
7335
7336/// This interface returns a list of dependent libraries in the form:
7337/// lib libA.so libB.so libC.so. The first library is the library we are
7338/// searching dependencies for.
7339/// Note: In order to speed up the search, we display the dependencies of the
7340/// libraries which are not yet loaded. For instance, if libB.so was already
7341/// loaded the list would contain: lib libA.so libC.so.
7342static std::string GetSharedLibImmediateDepsSlow(std::string lib,
7343 cling::Interpreter *interp,
7344 bool skipLoadedLibs = true)
7345{
7346 TString LibFullPath(lib);
7347 if (!llvm::sys::path::is_absolute(lib)) {
7348 if (!gSystem->FindDynamicLibrary(LibFullPath, /*quiet=*/true)) {
7349 Error("TCling__GetSharedLibImmediateDepsSlow", "Cannot find library '%s'", lib.c_str());
7350 return "";
7351 }
7352 } else {
7353 assert(llvm::sys::fs::exists(lib) && "Must exist!");
7354 lib = llvm::sys::path::filename(lib).str();
7355 }
7356
7357 auto ObjF = llvm::object::ObjectFile::createObjectFile(LibFullPath.Data());
7358 if (!ObjF) {
7359 Warning("TCling__GetSharedLibImmediateDepsSlow", "Failed to read object file %s", lib.c_str());
7360 return "";
7361 }
7362
7363 llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary();
7364
7365 std::set<string> DedupSet;
7366 std::string Result = lib + ' ';
7367 for (const auto &S : BinObjFile->symbols()) {
7368 uint32_t Flags = llvm::cantFail(S.getFlags());
7369 // Skip defined symbols: we have them.
7370 if (!(Flags & llvm::object::SymbolRef::SF_Undefined))
7371 continue;
7372 // Skip undefined weak symbols: if we don't have them we won't need them.
7373 // `__gmon_start__` being a typical example.
7374 if (Flags & llvm::object::SymbolRef::SF_Weak)
7375 continue;
7376 llvm::Expected<StringRef> SymNameErr = S.getName();
7377 if (!SymNameErr) {
7378 Warning("GetSharedLibDepsForModule", "Failed to read symbol");
7379 continue;
7380 }
7381 llvm::StringRef SymName = SymNameErr.get();
7382 if (SymName.empty())
7383 continue;
7384
7385 if (BinObjFile->isELF()) {
7386 // Skip the symbols which are part of the C/C++ runtime and have a
7387 // fixed library version. See binutils ld VERSION. Those reside in
7388 // 'system' libraries, which we avoid in FindLibraryForSymbol.
7389 if (SymName.contains("@GLIBCXX") || SymName.contains("@CXXABI") ||
7390 SymName.contains("@GLIBC") || SymName.contains("@GCC"))
7391 continue;
7392
7393 // Those are 'weak undefined' symbols produced by gcc. We can
7394 // ignore them.
7395 // FIXME: It is unclear whether we can ignore all weak undefined
7396 // symbols:
7397 // http://lists.llvm.org/pipermail/llvm-dev/2017-October/118177.html
7398 static constexpr llvm::StringRef RegisterClasses("_Jv_RegisterClasses");
7399 static constexpr llvm::StringRef RegisterCloneTable("_ITM_registerTMCloneTable");
7400 static constexpr llvm::StringRef DeregisterCloneTable("_ITM_deregisterTMCloneTable");
7401 if (SymName == RegisterClasses ||
7404 continue;
7405 }
7406
7407 // If we can find the address of the symbol, we have loaded it. Skip.
7408 if (skipLoadedLibs) {
7410 if (llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(SymNameForDlsym))
7411 continue;
7412 }
7413
7415 std::string found = interp->getDynamicLibraryManager()->searchLibrariesForSymbol(SymName, /*searchSystem*/false);
7416 // The expected output is just filename without the full path, which
7417 // is not very accurate, because our Dyld implementation might find
7418 // a match in location a/b/c.so and if we return just c.so ROOT might
7419 // resolve it to y/z/c.so and there we might not be ABI compatible.
7420 // FIXME: Teach the users of GetSharedLibDeps to work with full paths.
7421 if (!found.empty()) {
7422 std::string cand = llvm::sys::path::filename(found).str();
7423 if (!DedupSet.insert(cand).second)
7424 continue;
7425
7426 Result += cand + ' ';
7427 }
7428 }
7429
7430 return Result;
7431}
7432
7433static bool hasParsedRootmapForLibrary(llvm::StringRef lib)
7434{
7435 // Check if we have parsed a rootmap file.
7436 llvm::SmallString<256> rootmapName;
7437 if (!lib.starts_with("lib"))
7438 rootmapName.append("lib");
7439
7440 rootmapName.append(llvm::sys::path::filename(lib));
7441 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7442
7443 if (gCling->GetRootMapFiles()->FindObject(rootmapName.c_str()))
7444 return true;
7445
7446 // Perform a last resort by dropping the lib prefix.
7447 llvm::StringRef rootmapNameNoLib = rootmapName.str();
7448 if (rootmapNameNoLib.consume_front("lib"))
7449 return gCling->GetRootMapFiles()->FindObject(rootmapNameNoLib.data());
7450
7451 return false;
7452}
7453
7454static bool hasPrecomputedLibraryDeps(llvm::StringRef lib)
7455{
7456 if (gCling->HasPCMForLibrary(lib.data()))
7457 return true;
7458
7459 return hasParsedRootmapForLibrary(lib);
7460}
7461
7462////////////////////////////////////////////////////////////////////////////////
7463/// Get the list a libraries on which the specified lib depends. The
7464/// returned string contains as first element the lib itself.
7465/// Returns 0 in case the lib does not exist or does not have
7466/// any dependencies. If useDyld is true, we iterate through all available
7467/// libraries and try to construct the dependency chain by resolving each
7468/// symbol.
7469
7470const char* TCling::GetSharedLibDeps(const char* lib, bool useDyld/* = false*/)
7471{
7472 if (llvm::sys::path::is_absolute(lib) && !llvm::sys::fs::exists(lib))
7473 return nullptr;
7474
7475 if (!hasParsedRootmapForLibrary(lib)) {
7476 llvm::SmallString<512> rootmapName(lib);
7477 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7478 if (llvm::sys::fs::exists(rootmapName)) {
7479 if (gDebug > 0)
7480 Info("Load", "loading %s", rootmapName.c_str());
7481 gInterpreter->LoadLibraryMap(rootmapName.c_str());
7482 }
7483 }
7484
7485 if (hasPrecomputedLibraryDeps(lib) && useDyld) {
7486 if (gDebug > 0)
7487 Warning("TCling::GetSharedLibDeps", "Precomputed dependencies available but scanning '%s'", lib);
7488 }
7489
7490 if (useDyld) {
7492 if (!libs.empty()) {
7493 fAutoLoadLibStorage.push_back(libs);
7494 return fAutoLoadLibStorage.back().c_str();
7495 }
7496 }
7497
7498 if (!fMapfile || !lib || !lib[0]) {
7499 return nullptr;
7500 }
7501 TString libname(lib);
7502 Ssiz_t idx = libname.Last('.');
7503 if (idx != kNPOS) {
7504 libname.Remove(idx);
7505 }
7506 TEnvRec* rec;
7507 TIter next(fMapfile->GetTable());
7508 size_t len = libname.Length();
7509 while ((rec = (TEnvRec*) next())) {
7510 const char* libs = rec->GetValue();
7511 if (!strncmp(libs, libname.Data(), len) && strlen(libs) >= len
7512 && (!libs[len] || libs[len] == ' ' || libs[len] == '.')) {
7513 return libs;
7514 }
7515 }
7516 return nullptr;
7517}
7518
7519////////////////////////////////////////////////////////////////////////////////
7520/// If error messages are disabled, the interpreter should suppress its
7521/// failures and warning messages from stdout.
7522
7524{
7525#if defined(R__MUST_REVISIT)
7526#if R__MUST_REVISIT(6,2)
7527 Warning("IsErrorMessagesEnabled", "Interface not available yet.");
7528#endif
7529#endif
7530 return kTRUE;
7531}
7532
7533////////////////////////////////////////////////////////////////////////////////
7534/// If error messages are disabled, the interpreter should suppress its
7535/// failures and warning messages from stdout. Return the previous state.
7536
7538{
7539#if defined(R__MUST_REVISIT)
7540#if R__MUST_REVISIT(6,2)
7541 Warning("SetErrorMessages", "Interface not available yet.");
7542#endif
7543#endif
7545}
7546
7547////////////////////////////////////////////////////////////////////////////////
7548/// Refresh the list of include paths known to the interpreter and return it
7549/// with -I prepended.
7550
7552{
7554
7555 fIncludePath = "";
7556
7557 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7558 //false - no system header, true - with flags.
7559 fInterpreter->GetIncludePaths(includePaths, false, true);
7560 if (const size_t nPaths = includePaths.size()) {
7561 assert(!(nPaths & 1) && "GetIncludePath, number of paths and options is not equal");
7562
7563 for (size_t i = 0; i < nPaths; i += 2) {
7564 if (i)
7565 fIncludePath.Append(' ');
7566 fIncludePath.Append(includePaths[i].c_str());
7567
7568 if (includePaths[i] != "-I")
7569 fIncludePath.Append(' ');
7570 fIncludePath.Append('"');
7572 fIncludePath.Append('"');
7573 }
7574 }
7575
7576 return fIncludePath;
7577}
7578
7579////////////////////////////////////////////////////////////////////////////////
7580/// Return the directory containing CINT's stl cintdlls.
7581
7582const char* TCling::GetSTLIncludePath() const
7583{
7584 return "";
7585}
7586
7587//______________________________________________________________________________
7588// M I S C
7589//______________________________________________________________________________
7590
7591int TCling::DisplayClass(FILE* /*fout*/, const char* /*name*/, int /*base*/, int /*start*/) const
7592{
7593 // Interface to cling function
7594 return 0;
7595}
7596
7597////////////////////////////////////////////////////////////////////////////////
7598/// Interface to cling function
7599
7601{
7602 assert(fout != nullptr && "DisplayIncludePath, 'fout' parameter is null");
7603
7604 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7605 //false - no system header, true - with flags.
7606 fInterpreter->GetIncludePaths(includePaths, false, true);
7607 if (const size_t nPaths = includePaths.size()) {
7608 assert(!(nPaths & 1) && "DisplayIncludePath, number of paths and options is not equal");
7609
7610 std::string allIncludes("include path:");
7611 for (size_t i = 0; i < nPaths; i += 2) {
7612 allIncludes += ' ';
7614
7615 if (includePaths[i] != "-I")
7616 allIncludes += ' ';
7617 allIncludes += includePaths[i + 1];
7618 }
7619
7620 fprintf(fout, "%s\n", allIncludes.c_str());
7621 }
7622
7623 return 0;
7624}
7625
7626////////////////////////////////////////////////////////////////////////////////
7627/// Interface to cling function
7628
7629void* TCling::FindSym(const char* entry) const
7630{
7632 return fInterpreter->getAddressOfGlobal(entry);
7633}
7634
7635////////////////////////////////////////////////////////////////////////////////
7636/// Let the interpreter issue a generic error, and set its error state.
7637
7638void TCling::GenericError(const char* error) const
7639{
7640#if defined(R__MUST_REVISIT)
7641#if R__MUST_REVISIT(6,2)
7642 Warning("GenericError","Interface not available yet.");
7643#endif
7644#endif
7645}
7646
7647////////////////////////////////////////////////////////////////////////////////
7648/// This routines used to return the address of the internal wrapper
7649/// function (of the interpreter) that was used to call *all* the
7650/// interpreted functions that were bytecode compiled (no longer
7651/// interpreted line by line). In Cling, there is no such
7652/// wrapper function.
7653/// In practice this routines was use to decipher whether the
7654/// pointer returns by InterfaceMethod could be used to uniquely
7655/// represent the function. In Cling if the function is in a
7656/// useable state (its compiled version is available), this is
7657/// always the case.
7658/// See TClass::GetMethod.
7659
7661{
7662 return 0;
7663}
7664
7665////////////////////////////////////////////////////////////////////////////////
7666/// Interface to cling function
7667
7669{
7670#if defined(R__MUST_REVISIT)
7671#if R__MUST_REVISIT(6,2)
7672 Warning("GetSecurityError", "Interface not available yet.");
7673#endif
7674#endif
7675 return 0;
7676}
7677
7678////////////////////////////////////////////////////////////////////////////////
7679/// Load a source file or library called path into the interpreter.
7680
7681int TCling::LoadFile(const char* path) const
7682{
7683 // Modifying the interpreter state needs locking.
7685 cling::Interpreter::CompilationResult compRes;
7686 HandleInterpreterException(GetMetaProcessorImpl(), TString::Format(".L %s", path), compRes, /*cling::Value*/nullptr);
7687 return compRes == cling::Interpreter::kFailure;
7688}
7689
7690////////////////////////////////////////////////////////////////////////////////
7691/// Load the declarations from text into the interpreter.
7692/// Note that this cannot be (top level) statements; text must contain
7693/// top level declarations.
7694/// Returns true on success, false on failure.
7695
7696Bool_t TCling::LoadText(const char* text) const
7697{
7698 return (fInterpreter->declare(text) == cling::Interpreter::kSuccess);
7699}
7700
7701////////////////////////////////////////////////////////////////////////////////
7702/// Interface to cling function
7703
7704const char* TCling::MapCppName(const char* name) const
7705{
7706 TTHREAD_TLS_DECL(std::string,buffer);
7708 return buffer.c_str(); // NOLINT
7709}
7710
7711////////////////////////////////////////////////////////////////////////////////
7712/// [Place holder for Mutex Lock]
7713/// Provide the interpreter with a way to
7714/// acquire a lock used to protect critical section
7715/// of its code (non-thread safe parts).
7716
7717void TCling::SetAlloclockfunc(void (* /* p */ )()) const
7718{
7719 // nothing to do for now.
7720}
7721
7722////////////////////////////////////////////////////////////////////////////////
7723/// [Place holder for Mutex Unlock] Provide the interpreter with a way to
7724/// release a lock used to protect critical section
7725/// of its code (non-thread safe parts).
7726
7727void TCling::SetAllocunlockfunc(void (* /* p */ )()) const
7728{
7729 // nothing to do for now.
7730}
7731
7732////////////////////////////////////////////////////////////////////////////////
7733/// Returns if class AutoLoading is currently enabled.
7734
7736{
7737 if (IsFromRootCling())
7738 return false;
7739 if (!fClingCallbacks)
7740 return false;
7742}
7743
7744////////////////////////////////////////////////////////////////////////////////
7745/// Enable/Disable the AutoLoading of libraries.
7746/// Returns the old value, i.e whether it was enabled or not.
7747
7749{
7750 // If no state change is required, exit early.
7751 // FIXME: In future we probably want to complain if we made a request which
7752 // was with the same state as before in order to catch programming errors.
7753 if ((bool) autoload == IsClassAutoLoadingEnabled())
7754 return autoload;
7755
7756 assert(fClingCallbacks && "We must have callbacks!");
7759 return oldVal;
7760}
7761
7762////////////////////////////////////////////////////////////////////////////////
7763/// Enable/Disable the Autoparsing of headers.
7764/// Returns the old value, i.e whether it was enabled or not.
7765
7772
7773////////////////////////////////////////////////////////////////////////////////
7774/// Suspend the Autoparsing of headers.
7775/// Returns the old value, i.e whether it was suspended or not.
7776
7783
7784////////////////////////////////////////////////////////////////////////////////
7785/// Set a callback to receive error messages.
7786
7788{
7789#if defined(R__MUST_REVISIT)
7790#if R__MUST_REVISIT(6,2)
7791 Warning("SetErrmsgcallback", "Interface not available yet.");
7792#endif
7793#endif
7794}
7795
7797{
7798 if (enable) {
7800 &fInterpreter->getDiagnostics().getDiagnosticOptions(),
7801 fInterpreter->getCI()->getLangOpts(),
7802 [] (clang::DiagnosticsEngine::Level Level, const std::string &Info) {
7803 if (Level == clang::DiagnosticsEngine::Warning) {
7804 ::Warning("cling", "%s", Info.c_str());
7805 } else if (Level == clang::DiagnosticsEngine::Error
7806 || Level == clang::DiagnosticsEngine::Fatal) {
7807 ::Error("cling", "%s", Info.c_str());
7808 } else {
7809 ::Info("cling", "%s", Info.c_str());
7810 }
7811 });
7812 fInterpreter->replaceDiagnosticConsumer(consumer, /*Own=*/true);
7813 } else {
7814 fInterpreter->replaceDiagnosticConsumer(nullptr);
7815 }
7816}
7817
7818
7819////////////////////////////////////////////////////////////////////////////////
7820/// Create / close a scope for temporaries. No-op for cling; use
7821/// cling::Value instead.
7822
7823void TCling::SetTempLevel(int val) const
7824{
7825}
7826
7827////////////////////////////////////////////////////////////////////////////////
7828
7829int TCling::UnloadFile(const char* path) const
7830{
7831 // Modifying the interpreter state needs locking.
7833 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
7834 std::string canonical = DLM->lookupLibrary(path);
7835 if (canonical.empty()) {
7836 canonical = path;
7837 }
7838 // Unload a shared library or a source file.
7839 cling::Interpreter::CompilationResult compRes;
7840 HandleInterpreterException(GetMetaProcessorImpl(), Form(".U %s", canonical.c_str()), compRes, /*cling::Value*/nullptr);
7841 return compRes == cling::Interpreter::kFailure;
7842}
7843
7844std::unique_ptr<TInterpreterValue> TCling::MakeInterpreterValue() const {
7845 return std::unique_ptr<TInterpreterValue>(new TClingValue);
7846}
7847
7848////////////////////////////////////////////////////////////////////////////////
7849/// The call to Cling's tab complition.
7850
7851void TCling::CodeComplete(const std::string& line, size_t& cursor,
7852 std::vector<std::string>& completions)
7853{
7854 fInterpreter->codeComplete(line, cursor, completions);
7855}
7856
7857////////////////////////////////////////////////////////////////////////////////
7858/// Get the interpreter value corresponding to the statement.
7860{
7862
7863 auto V = reinterpret_cast<cling::Value*>(value.GetValAddr());
7864 auto compRes = fInterpreter->evaluate(code, *V);
7865 return compRes!=cling::Interpreter::kSuccess ? 0 : 1 ;
7866}
7867
7868////////////////////////////////////////////////////////////////////////////////
7869
7871{
7872 using namespace cling;
7873 const Value* V = reinterpret_cast<const Value*>(value.GetValAddr());
7875}
7876
7877////////////////////////////////////////////////////////////////////////////////
7878/// Register value as a temporary, extending its lifetime to that of the
7879/// interpreter. This is needed for TCling's compatibility interfaces
7880/// returning long - the address of the temporary objects.
7881/// As such, "simple" types don't need to be stored; they are returned by
7882/// value; only pointers / references / objects need to be stored.
7883
7884void TCling::RegisterTemporary(const cling::Value& value)
7885{
7886 if (value.isValid() && value.needsManagedAllocation()) {
7888 fTemporaries->push_back(value);
7889 }
7890}
7891
7892////////////////////////////////////////////////////////////////////////////////
7893/// If the interpreter encounters Name, check whether that is an object ROOT
7894/// could retrieve. To not re-read objects from disk, cache the name/object
7895/// pair for a given LookupCtx.
7896
7898{
7899 // The call to FindSpecialObject might induces any kind of use
7900 // of the interpreter ... (library loading, function calling, etc.)
7901 // ... and we _know_ we are in the middle of parsing, so let's make
7902 // sure to save the state and then restore it.
7903
7904 if (gDirectory) {
7906 if (iSpecObjMap != fSpecialObjectMaps.end()) {
7907 auto iSpecObj = iSpecObjMap->second.find(Name);
7908 if (iSpecObj != iSpecObjMap->second.end()) {
7910 return iSpecObj->second;
7911 }
7912 }
7913 }
7914
7915 // Save state of the PP
7916 Sema &SemaR = fInterpreter->getSema();
7917 ASTContext& C = SemaR.getASTContext();
7918 Preprocessor &PP = SemaR.getPreprocessor();
7919 Parser& P = const_cast<Parser&>(fInterpreter->getParser());
7920 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
7921 Parser::ParserCurTokRestoreRAII savedCurToken(P);
7922 // After we have saved the token reset the current one to something which
7923 // is safe (semi colon usually means empty decl)
7924 Token& Tok = const_cast<Token&>(P.getCurToken());
7925 Tok.setKind(tok::semi);
7926
7927 // We can't PushDeclContext, because we go up and the routine that pops
7928 // the DeclContext assumes that we drill down always.
7929 // We have to be on the global context. At that point we are in a
7930 // wrapper function so the parent context must be the global.
7931 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
7932 SemaR.TUScope);
7933
7934 TObject* specObj = gROOT->FindSpecialObject(Name, LookupCtx);
7935 if (specObj) {
7936 if (!LookupCtx) {
7937 Error("GetObjectAddress", "Got a special object without LookupCtx!");
7938 } else {
7940 }
7941 }
7942 return specObj;
7943}
7944
7945////////////////////////////////////////////////////////////////////////////////
7946/// Inject function as a friend into klass.
7947/// With function being f in void f() {new N::PrivKlass(); } this enables
7948/// I/O of non-public classes.
7949
7950void TCling::AddFriendToClass(clang::FunctionDecl* function,
7951 clang::CXXRecordDecl* klass) const
7952{
7953 using namespace clang;
7954 ASTContext& Ctx = klass->getASTContext();
7955 FriendDecl::FriendUnion friendUnion(function);
7956 // one dummy object for the source location
7958 FriendDecl* friendDecl = FriendDecl::Create(Ctx, klass, sl, friendUnion, sl);
7959 klass->pushFriendDecl(friendDecl);
7960}
7961
7962//______________________________________________________________________________
7963//
7964// DeclId getter.
7965//
7966
7967////////////////////////////////////////////////////////////////////////////////
7968/// Return a unique identifier of the declaration represented by the
7969/// CallFunc
7970
7972{
7973 if (func) return ((TClingCallFunc*)func)->GetDecl()->getCanonicalDecl();
7974 return nullptr;
7975}
7976
7977////////////////////////////////////////////////////////////////////////////////
7978/// Return a (almost) unique identifier of the declaration represented by the
7979/// ClassInfo. In ROOT, this identifier can point to more than one TClass
7980/// when the underlying class is a template instance involving one of the
7981/// opaque typedef.
7982
7984{
7985 if (cinfo) return ((TClingClassInfo*)cinfo)->GetDeclId();
7986 return nullptr;
7987}
7988
7989////////////////////////////////////////////////////////////////////////////////
7990/// Return a unique identifier of the declaration represented by the
7991/// MethodInfo
7992
7994{
7995 if (data) return ((TClingDataMemberInfo*)data)->GetDeclId();
7996 return nullptr;
7997}
7998
7999////////////////////////////////////////////////////////////////////////////////
8000/// Return a unique identifier of the declaration represented by the
8001/// MethodInfo
8002
8004{
8005 if (method) return ((TClingMethodInfo*)method)->GetDeclId();
8006 return nullptr;
8007}
8008
8009////////////////////////////////////////////////////////////////////////////////
8010/// Return a unique identifier of the declaration represented by the
8011/// TypedefInfo
8012
8014{
8015 if (tinfo) return ((TClingTypedefInfo*)tinfo)->GetDecl()->getCanonicalDecl();
8016 return nullptr;
8017}
8018
8019//______________________________________________________________________________
8020//
8021// CallFunc interface
8022//
8023
8024////////////////////////////////////////////////////////////////////////////////
8025
8027{
8028 delete (TClingCallFunc*) func;
8029}
8030
8031////////////////////////////////////////////////////////////////////////////////
8032
8033void TCling::CallFunc_Exec(CallFunc_t* func, void* address) const
8034{
8035 TClingCallFunc* f = (TClingCallFunc*) func;
8036 f->Exec(address);
8037}
8038
8039////////////////////////////////////////////////////////////////////////////////
8040
8041void TCling::CallFunc_Exec(CallFunc_t* func, void* address, TInterpreterValue& val) const
8042{
8043 TClingCallFunc* f = (TClingCallFunc*) func;
8044 f->Exec(address, &val);
8045}
8046
8047////////////////////////////////////////////////////////////////////////////////
8048
8049void TCling::CallFunc_ExecWithReturn(CallFunc_t* func, void* address, void* ret) const
8050{
8051 TClingCallFunc* f = (TClingCallFunc*) func;
8052 f->ExecWithReturn(address, ret);
8053}
8054
8055////////////////////////////////////////////////////////////////////////////////
8056
8058 const void* args[] /*=0*/,
8059 int nargs /*=0*/,
8060 void* ret/*=0*/) const
8061{
8062 TClingCallFunc* f = (TClingCallFunc*) func;
8063 f->ExecWithArgsAndReturn(address, args, nargs, ret);
8064}
8065
8066////////////////////////////////////////////////////////////////////////////////
8067
8069{
8070 TClingCallFunc* f = (TClingCallFunc*) func;
8071 return f->ExecInt(address);
8072}
8073
8074////////////////////////////////////////////////////////////////////////////////
8075
8077{
8078 TClingCallFunc* f = (TClingCallFunc*) func;
8079 return f->ExecInt64(address);
8080}
8081
8082////////////////////////////////////////////////////////////////////////////////
8083
8085{
8086 TClingCallFunc* f = (TClingCallFunc*) func;
8087 return f->ExecDouble(address);
8088}
8089
8090////////////////////////////////////////////////////////////////////////////////
8091
8097
8098////////////////////////////////////////////////////////////////////////////////
8099
8101{
8102 return (CallFunc_t*) new TClingCallFunc(*(TClingCallFunc*)func);
8103}
8104
8105////////////////////////////////////////////////////////////////////////////////
8106
8108{
8109 TClingCallFunc* f = (TClingCallFunc*) func;
8110 return (MethodInfo_t*) f->FactoryMethod();
8111}
8112
8113////////////////////////////////////////////////////////////////////////////////
8114
8116{
8117 TClingCallFunc* f = (TClingCallFunc*) func;
8118 f->IgnoreExtraArgs(ignore);
8119}
8120
8121////////////////////////////////////////////////////////////////////////////////
8122
8124{
8126 TClingCallFunc* f = (TClingCallFunc*) func;
8127 f->Init();
8128}
8129
8130////////////////////////////////////////////////////////////////////////////////
8131
8133{
8134 TClingCallFunc* f = (TClingCallFunc*) func;
8135 return f->IsValid();
8136}
8137
8138////////////////////////////////////////////////////////////////////////////////
8139
8142{
8143 TClingCallFunc* f = (TClingCallFunc*) func;
8144 return f->IFacePtr();
8145}
8146
8147////////////////////////////////////////////////////////////////////////////////
8148
8150{
8151 TClingCallFunc* f = (TClingCallFunc*) func;
8152 f->ResetArg();
8153}
8154
8155////////////////////////////////////////////////////////////////////////////////
8156
8158{
8159 TClingCallFunc* f = (TClingCallFunc*) func;
8160 f->SetArg(param);
8161}
8162
8163////////////////////////////////////////////////////////////////////////////////
8164
8166{
8167 TClingCallFunc* f = (TClingCallFunc*) func;
8168 f->SetArg(param);
8169}
8170
8171////////////////////////////////////////////////////////////////////////////////
8172
8174{
8175 TClingCallFunc* f = (TClingCallFunc*) func;
8176 f->SetArg(param);
8177}
8178
8179////////////////////////////////////////////////////////////////////////////////
8180
8182{
8183 TClingCallFunc* f = (TClingCallFunc*) func;
8184 f->SetArg(param);
8185}
8186
8187////////////////////////////////////////////////////////////////////////////////
8188
8190{
8191 TClingCallFunc* f = (TClingCallFunc*) func;
8192 f->SetArg(param);
8193}
8194
8195////////////////////////////////////////////////////////////////////////////////
8196
8198{
8199 TClingCallFunc* f = (TClingCallFunc*) func;
8200 f->SetArg(param);
8201}
8202
8203////////////////////////////////////////////////////////////////////////////////
8204
8206{
8207 TClingCallFunc* f = (TClingCallFunc*) func;
8208 f->SetArgArray(paramArr, nparam);
8209}
8210
8211////////////////////////////////////////////////////////////////////////////////
8212
8213void TCling::CallFunc_SetArgs(CallFunc_t* func, const char* param) const
8214{
8215 TClingCallFunc* f = (TClingCallFunc*) func;
8216 f->SetArgs(param);
8217}
8218
8219////////////////////////////////////////////////////////////////////////////////
8220
8221void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, Longptr_t* offset) const
8222{
8223 TClingCallFunc* f = (TClingCallFunc*) func;
8225 f->SetFunc(ci, method, params, offset);
8226}
8227
8228////////////////////////////////////////////////////////////////////////////////
8229
8230void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, bool objectIsConst, Longptr_t* offset) const
8231{
8232 TClingCallFunc* f = (TClingCallFunc*) func;
8234 f->SetFunc(ci, method, params, objectIsConst, offset);
8235}
8236////////////////////////////////////////////////////////////////////////////////
8237
8238void TCling::CallFunc_SetFunc(CallFunc_t* func, MethodInfo_t* info) const
8239{
8240 TClingCallFunc* f = (TClingCallFunc*) func;
8242 f->SetFunc(minfo);
8243}
8244
8245////////////////////////////////////////////////////////////////////////////////
8246/// Interface to cling function
8247
8248void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8249{
8250 TClingCallFunc* f = (TClingCallFunc*) func;
8252 f->SetFuncProto(ci, method, proto, offset, mode);
8253}
8254
8255////////////////////////////////////////////////////////////////////////////////
8256/// Interface to cling function
8257
8258void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, bool objectIsConst, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8259{
8260 TClingCallFunc* f = (TClingCallFunc*) func;
8262 f->SetFuncProto(ci, method, proto, objectIsConst, offset, mode);
8263}
8264
8265////////////////////////////////////////////////////////////////////////////////
8266/// Interface to cling function
8267
8268void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const std::vector<TypeInfo_t*> &proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8269{
8270 TClingCallFunc* f = (TClingCallFunc*) func;
8272 llvm::SmallVector<clang::QualType, 4> funcProto;
8273 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8274 iter != end; ++iter) {
8275 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8276 }
8277 f->SetFuncProto(ci, method, funcProto, offset, mode);
8278}
8279
8280////////////////////////////////////////////////////////////////////////////////
8281/// Interface to cling function
8282
8283void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const std::vector<TypeInfo_t*> &proto, bool objectIsConst, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8284{
8285 TClingCallFunc* f = (TClingCallFunc*) func;
8287 llvm::SmallVector<clang::QualType, 4> funcProto;
8288 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8289 iter != end; ++iter) {
8290 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8291 }
8292 f->SetFuncProto(ci, method, funcProto, objectIsConst, offset, mode);
8293}
8294
8296{
8297 TClingCallFunc *f = (TClingCallFunc *)func;
8298 std::string wrapper_name;
8299 std::string wrapper;
8300 f->get_wrapper_code(wrapper_name, wrapper);
8301 return wrapper;
8302}
8303
8304//______________________________________________________________________________
8305//
8306// ClassInfo interface
8307//
8308
8309////////////////////////////////////////////////////////////////////////////////
8310
8312{
8314 return TClinginfo->GetAlignOf();
8315}
8316
8317////////////////////////////////////////////////////////////////////////////////
8318/// Return true if the entity pointed to by 'declid' is declared in
8319/// the context described by 'info'. If info is null, look into the
8320/// global scope (translation unit scope).
8321
8323{
8324 if (!declid)
8325 return kFALSE;
8326
8327 const clang::DeclContext *ctxt = nullptr;
8328 if (info) {
8329 ctxt = clang::Decl::castToDeclContext(((TClingClassInfo*)info)->GetDecl());
8330 } else {
8331 ctxt = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
8332 }
8333 if (!ctxt)
8334 return kFALSE;
8335
8336 const clang::Decl *decl = reinterpret_cast<const clang::Decl*>(declid);
8337 if (!decl)
8338 return kFALSE;
8339
8340 const clang::DeclContext *declDC = decl->getDeclContext();
8341 // ClassInfo_t-s are always "spellable" scopes, never unnamed or inline ones.
8342 while (true) {
8343 if (declDC->isTransparentContext()) {
8344 declDC = declDC->getParent();
8345 continue;
8346 }
8347 if (const auto *declRD = llvm::dyn_cast<clang::RecordDecl>(declDC)) {
8348 if (declRD->isAnonymousStructOrUnion()) {
8349 declDC = declRD->getParent();
8350 continue;
8351 }
8352 }
8353 if (const auto *declNS = llvm::dyn_cast<clang::NamespaceDecl>(declDC)) {
8354 if (declNS->isAnonymousNamespace() || declNS->isInlineNamespace()) {
8355 declDC = declNS->getParent();
8356 continue;
8357 }
8358 }
8359 break;
8360 }
8361
8362 return declDC->Equals(ctxt);
8363}
8364
8365////////////////////////////////////////////////////////////////////////////////
8366
8372
8373////////////////////////////////////////////////////////////////////////////////
8374
8376{
8377 delete (TClingClassInfo*) cinfo;
8378}
8379
8380////////////////////////////////////////////////////////////////////////////////
8381
8387
8388////////////////////////////////////////////////////////////////////////////////
8389
8395
8396////////////////////////////////////////////////////////////////////////////////
8397
8403
8404////////////////////////////////////////////////////////////////////////////////
8405
8411
8412////////////////////////////////////////////////////////////////////////////////
8413
8418
8419////////////////////////////////////////////////////////////////////////////////
8420
8426
8432
8433
8434////////////////////////////////////////////////////////////////////////////////
8435
8436int TCling::ClassInfo_GetMethodNArg(ClassInfo_t* cinfo, const char* method, const char* proto, Bool_t objectIsConst /* = false */, EFunctionMatchMode mode /* = kConversionMatch */) const
8437{
8439 return TClinginfo->GetMethodNArg(method, proto, objectIsConst, mode);
8440}
8441
8442////////////////////////////////////////////////////////////////////////////////
8443
8449
8450////////////////////////////////////////////////////////////////////////////////
8451
8453{
8455 return TClinginfo->HasMethod(name);
8456}
8457
8458////////////////////////////////////////////////////////////////////////////////
8459
8466
8467////////////////////////////////////////////////////////////////////////////////
8468
8475
8476////////////////////////////////////////////////////////////////////////////////
8477
8479{
8481 return TClinginfo->IsBase(name);
8482}
8483
8484////////////////////////////////////////////////////////////////////////////////
8485
8486bool TCling::ClassInfo_IsEnum(const char* name) const
8487{
8489}
8490
8491////////////////////////////////////////////////////////////////////////////////
8492
8498
8499
8500////////////////////////////////////////////////////////////////////////////////
8501
8507
8508
8509////////////////////////////////////////////////////////////////////////////////
8510
8512{
8514 return TClinginfo->IsLoaded();
8515}
8516
8517////////////////////////////////////////////////////////////////////////////////
8518
8520{
8522 return TClinginfo->IsValid();
8523}
8524
8525////////////////////////////////////////////////////////////////////////////////
8526
8527bool TCling::ClassInfo_IsValidMethod(ClassInfo_t* cinfo, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8528{
8530 return TClinginfo->IsValidMethod(method, proto, false, offset, mode);
8531}
8532
8533////////////////////////////////////////////////////////////////////////////////
8534
8536{
8538 return TClinginfo->IsValidMethod(method, proto, objectIsConst, offset, mode);
8539}
8540
8541////////////////////////////////////////////////////////////////////////////////
8542
8548
8549////////////////////////////////////////////////////////////////////////////////
8550
8556
8557////////////////////////////////////////////////////////////////////////////////
8558
8564
8565////////////////////////////////////////////////////////////////////////////////
8566
8568{
8570 return TClinginfo->New(n, arena,*fNormalizedCtxt);
8571}
8572
8573////////////////////////////////////////////////////////////////////////////////
8574
8580
8581////////////////////////////////////////////////////////////////////////////////
8582
8588
8589////////////////////////////////////////////////////////////////////////////////
8590
8596
8597////////////////////////////////////////////////////////////////////////////////
8598
8604
8605////////////////////////////////////////////////////////////////////////////////
8606
8608{
8610 return TClinginfo->FileName();
8611}
8612
8613////////////////////////////////////////////////////////////////////////////////
8614
8616{
8618 TTHREAD_TLS_DECL(std::string,output);
8619 TClinginfo->FullName(output,*fNormalizedCtxt);
8620 return output.c_str(); // NOLINT
8621}
8622
8623////////////////////////////////////////////////////////////////////////////////
8624
8626{
8628 return TClinginfo->Name();
8629}
8630
8631////////////////////////////////////////////////////////////////////////////////
8632
8634{
8636 return TClinginfo->Title();
8637}
8638
8639////////////////////////////////////////////////////////////////////////////////
8640
8642{
8644 return TClinginfo->TmpltName();
8645}
8646
8647
8648
8649//______________________________________________________________________________
8650//
8651// BaseClassInfo interface
8652//
8653
8654////////////////////////////////////////////////////////////////////////////////
8655
8660
8661////////////////////////////////////////////////////////////////////////////////
8662
8669
8670////////////////////////////////////////////////////////////////////////////////
8671
8680
8681////////////////////////////////////////////////////////////////////////////////
8682
8688
8689////////////////////////////////////////////////////////////////////////////////
8690
8696
8697////////////////////////////////////////////////////////////////////////////////
8698
8704
8705////////////////////////////////////////////////////////////////////////////////
8706
8708{
8711 // Offset to the class itself.
8712 if (TClinginfo->GetDecl() == TClinginfoBase->GetDecl()) {
8713 return 0;
8714 }
8715 return TClinginfo->GetBaseOffset(TClinginfoBase, address, isDerivedObject);
8716}
8717
8718////////////////////////////////////////////////////////////////////////////////
8719
8725
8726////////////////////////////////////////////////////////////////////////////////
8727
8733
8734////////////////////////////////////////////////////////////////////////////////
8735
8741
8742////////////////////////////////////////////////////////////////////////////////
8743
8745{
8747 TTHREAD_TLS_DECL(std::string,output);
8748 TClinginfo->FullName(output,*fNormalizedCtxt);
8749 return output.c_str(); // NOLINT
8750}
8751
8752////////////////////////////////////////////////////////////////////////////////
8753
8759
8760////////////////////////////////////////////////////////////////////////////////
8761
8767
8768//______________________________________________________________________________
8769//
8770// DataMemberInfo interface
8771//
8772
8773////////////////////////////////////////////////////////////////////////////////
8774
8780
8781////////////////////////////////////////////////////////////////////////////////
8782
8787
8788////////////////////////////////////////////////////////////////////////////////
8789
8796
8797////////////////////////////////////////////////////////////////////////////////
8798
8800{
8802 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
8803 const clang::ValueDecl* vd = llvm::dyn_cast_or_null<clang::ValueDecl>(decl);
8805}
8806
8807////////////////////////////////////////////////////////////////////////////////
8808
8814
8815////////////////////////////////////////////////////////////////////////////////
8816
8822
8823////////////////////////////////////////////////////////////////////////////////
8824
8830
8831////////////////////////////////////////////////////////////////////////////////
8832
8838
8839////////////////////////////////////////////////////////////////////////////////
8840
8846
8847////////////////////////////////////////////////////////////////////////////////
8848
8854
8855////////////////////////////////////////////////////////////////////////////////
8856
8862
8863////////////////////////////////////////////////////////////////////////////////
8864
8870
8871////////////////////////////////////////////////////////////////////////////////
8872
8878
8879////////////////////////////////////////////////////////////////////////////////
8880
8886
8887////////////////////////////////////////////////////////////////////////////////
8888
8894
8895////////////////////////////////////////////////////////////////////////////////
8896
8902
8903////////////////////////////////////////////////////////////////////////////////
8904
8906{
8907 TTHREAD_TLS_DECL(std::string,result);
8908
8910 result = TClinginfo->ValidArrayIndex().str();
8911 return result.c_str(); // NOLINT
8912}
8913
8914////////////////////////////////////////////////////////////////////////////////
8915
8917{
8918 Decl* decl = static_cast<Decl*>(const_cast<void*>(declId));
8919 ASTContext &C = decl->getASTContext();
8920 decl->addAttr(AnnotateAttr::CreateImplicit(C, attribute, nullptr, 0));
8921}
8922
8923//______________________________________________________________________________
8924//
8925// Function Template interface
8926//
8927
8928////////////////////////////////////////////////////////////////////////////////
8929
8930static void ConstructorName(std::string &name, const clang::Decl *decl,
8931 cling::Interpreter &interp,
8933{
8934 const clang::TypeDecl* td = llvm::dyn_cast<clang::TypeDecl>(decl->getDeclContext());
8935 if (!td) return;
8936
8937 clang::QualType qualType = td->getASTContext().getTypeDeclType(td);
8939 unsigned int level = 0;
8940 for(size_t cursor = name.length()-1; cursor != 0; --cursor) {
8941 if (name[cursor] == '>') ++level;
8942 else if (name[cursor] == '<' && level) --level;
8943 else if (level == 0 && name[cursor] == ':') {
8944 name.erase(0,cursor+1);
8945 break;
8946 }
8947 }
8948}
8949
8950////////////////////////////////////////////////////////////////////////////////
8951
8952void TCling::GetFunctionName(const clang::Decl *decl, std::string &output) const
8953{
8954 output.clear();
8955
8956 const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(decl);
8957 if (const auto *USD = llvm::dyn_cast<clang::UsingShadowDecl>(decl)) {
8958 FD = llvm::dyn_cast<clang::FunctionDecl>(USD->getTargetDecl());
8959 }
8960 if (!FD) {
8961 Error("GetFunctionName", "NULL Decl!");
8962 return;
8963 }
8964
8965 // For using-decls, show "Derived", not "Base", i.e. use the
8966 // name of the decl context of the UsingShadowDecl (aka `decl`)
8967 // not the name of FD's decl context.
8968 if (llvm::isa<clang::CXXConstructorDecl>(FD))
8969 {
8971
8972 } else if (llvm::isa<clang::CXXDestructorDecl>(decl))
8973 {
8975 output.insert(output.begin(), '~');
8976 } else {
8977 llvm::raw_string_ostream stream(output);
8978 auto printPolicy = decl->getASTContext().getPrintingPolicy();
8979 // Don't trigger fopen of the source file to count lines:
8980 printPolicy.AnonymousTagLocations = false;
8981 FD->getNameForDiagnostic(stream, printPolicy, /*Qualified=*/false);
8982 }
8983}
8984
8985////////////////////////////////////////////////////////////////////////////////
8986/// Return a unique identifier of the declaration represented by the
8987/// FuncTempInfo
8988
8993
8994////////////////////////////////////////////////////////////////////////////////
8995/// Delete the FuncTempInfo_t
8996
8998{
8999 // Currently the address of ft_info is actually the decl itself,
9000 // so we have nothing to do.
9001}
9002
9003////////////////////////////////////////////////////////////////////////////////
9004/// Construct a FuncTempInfo_t
9005
9007{
9008 // Currently the address of ft_info is actually the decl itself,
9009 // so we have nothing to do.
9010
9011 return (FuncTempInfo_t*)const_cast<void*>(declid);
9012}
9013
9014////////////////////////////////////////////////////////////////////////////////
9015/// Construct a FuncTempInfo_t
9016
9018{
9019 // Currently the address of ft_info is actually the decl itself,
9020 // so we have nothing to do.
9021
9022 return (FuncTempInfo_t*)ft_info;
9023}
9024
9025////////////////////////////////////////////////////////////////////////////////
9026/// Check validity of a FuncTempInfo_t
9027
9029{
9030 // Currently the address of ft_info is actually the decl itself,
9031 // so we have nothing to do.
9032
9033 return t_info != nullptr;
9034}
9035
9036////////////////////////////////////////////////////////////////////////////////
9037/// Return the maximum number of template arguments of the
9038/// function template described by ft_info.
9039
9041{
9042 if (!ft_info) return 0;
9043 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
9044 return ft->getTemplateParameters()->size();
9045}
9046
9047////////////////////////////////////////////////////////////////////////////////
9048/// Return the number of required template arguments of the
9049/// function template described by ft_info.
9050
9052{
9053 if (!ft_info) return 0;
9054 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9055 return ft->getTemplateParameters()->getMinRequiredArguments();
9056}
9057
9058////////////////////////////////////////////////////////////////////////////////
9059/// Return the property of the function template.
9060
9062{
9063 if (!ft_info) return 0;
9064
9065 long property = 0L;
9066 property |= kIsCompiled;
9067
9068 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9069
9070 switch (ft->getAccess()) {
9071 case clang::AS_public:
9072 property |= kIsPublic;
9073 break;
9074 case clang::AS_protected:
9075 property |= kIsProtected;
9076 break;
9077 case clang::AS_private:
9078 property |= kIsPrivate;
9079 break;
9080 case clang::AS_none:
9081 if (ft->getDeclContext()->isNamespace())
9083 break;
9084 default:
9085 // IMPOSSIBLE
9086 assert(false && "Unexpected value for the access property value in Clang");
9087 break;
9088 }
9089
9090 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
9091
9092 if (fd && fd->getStorageClass() == clang::SC_Static)
9093 property |= kIsStatic;
9094
9095 if (const clang::CXXMethodDecl *md =
9096 llvm::dyn_cast<clang::CXXMethodDecl>(fd)) {
9097 if (md->getMethodQualifiers().hasConst()) {
9098 property |= kIsConstant | kIsConstMethod;
9099 }
9100 if (md->isVirtual()) {
9101 property |= kIsVirtual;
9102 }
9103 if (md->isPureVirtual()) {
9104 property |= kIsPureVirtual;
9105 }
9106 if (const clang::CXXConstructorDecl *cd =
9107 llvm::dyn_cast<clang::CXXConstructorDecl>(md)) {
9108 if (cd->isExplicit()) {
9109 property |= kIsExplicit;
9110 }
9111 }
9112 else if (const clang::CXXConversionDecl *cd =
9113 llvm::dyn_cast<clang::CXXConversionDecl>(md)) {
9114 if (cd->isExplicit()) {
9115 property |= kIsExplicit;
9116 }
9117 }
9118 }
9119 return property;
9120}
9121
9122////////////////////////////////////////////////////////////////////////////////
9123/// Return the property not already defined in Property
9124/// See TDictionary's EFunctionProperty
9125
9127{
9128 if (!ft_info) return 0;
9129
9130 long property = 0L;
9131 property |= kIsCompiled;
9132
9133 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9134 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
9135
9136 if (fd->isOverloadedOperator())
9138 if (llvm::isa<clang::CXXConversionDecl>(fd))
9140 if (llvm::isa<clang::CXXConstructorDecl>(fd))
9142 if (llvm::isa<clang::CXXDestructorDecl>(fd))
9144 if (fd->isInlined())
9146 return property;
9147}
9148
9149////////////////////////////////////////////////////////////////////////////////
9150/// Return the name of this function template.
9151
9153{
9154 output.Clear();
9155 if (!ft_info) return;
9156 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9157 std::string buf;
9158 GetFunctionName(ft->getTemplatedDecl(), buf);
9159 output = buf;
9160}
9161
9162////////////////////////////////////////////////////////////////////////////////
9163/// Return the comments associates with this function template.
9164
9166{
9167 output.Clear();
9168 if (!ft_info) return;
9169 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
9170
9171 // Iterate over the redeclarations, we can have multiple definitions in the
9172 // redecl chain (came from merging of pcms).
9175 if (AnnotateAttr *A = AnnotFD->getAttr<AnnotateAttr>()) {
9176 output = A->getAnnotation().str();
9177 return;
9178 }
9179 }
9180 if (!ft->isFromASTFile()) {
9181 // Try to get the comment from the header file if present
9182 // but not for decls from AST file, where rootcling would have
9183 // created an annotation
9184 output = ROOT::TMetaUtils::GetComment(*ft).str();
9185 }
9186}
9187
9188
9189//______________________________________________________________________________
9190//
9191// MethodInfo interface
9192//
9193
9194////////////////////////////////////////////////////////////////////////////////
9195/// Interface to cling function
9196
9197void TCling::MethodInfo_Delete(MethodInfo_t* minfo) const
9198{
9199 delete(TClingMethodInfo*) minfo;
9200}
9201
9202////////////////////////////////////////////////////////////////////////////////
9203
9205{
9207 // The next call locks the interpreter mutex.
9208 info->CreateSignature(signature);
9209}
9210
9211////////////////////////////////////////////////////////////////////////////////
9212
9213MethodInfo_t* TCling::MethodInfo_Factory() const
9214{
9216 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl());
9217}
9218
9219////////////////////////////////////////////////////////////////////////////////
9220
9222{
9224 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), (TClingClassInfo*)clinfo);
9225}
9226
9227////////////////////////////////////////////////////////////////////////////////
9228
9230{
9231 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
9233 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), decl);
9234}
9235
9236////////////////////////////////////////////////////////////////////////////////
9237
9238MethodInfo_t* TCling::MethodInfo_FactoryCopy(MethodInfo_t* minfo) const
9239{
9240 return (MethodInfo_t*) new TClingMethodInfo(*(TClingMethodInfo*)minfo);
9241}
9242
9243////////////////////////////////////////////////////////////////////////////////
9244
9246{
9248 // The next call locks the interpreter mutex.
9249 return info->InterfaceMethod();
9250}
9251
9252////////////////////////////////////////////////////////////////////////////////
9253
9254bool TCling::MethodInfo_IsValid(MethodInfo_t* minfo) const
9255{
9257 return info->IsValid();
9258}
9259
9260////////////////////////////////////////////////////////////////////////////////
9261
9262int TCling::MethodInfo_NArg(MethodInfo_t* minfo) const
9263{
9265 return info->NArg();
9266}
9267
9268////////////////////////////////////////////////////////////////////////////////
9269
9271{
9273 return info->NDefaultArg();
9274}
9275
9276////////////////////////////////////////////////////////////////////////////////
9277
9278int TCling::MethodInfo_Next(MethodInfo_t* minfo) const
9279{
9281 return info->Next();
9282}
9283
9284////////////////////////////////////////////////////////////////////////////////
9285
9287{
9289 // The next call locks the interpreter mutex.
9290 return info->Property();
9291}
9292
9293////////////////////////////////////////////////////////////////////////////////
9294
9296{
9298 // The next call locks the interpreter mutex.
9299 return info->ExtraProperty();
9300}
9301
9302////////////////////////////////////////////////////////////////////////////////
9303
9305{
9307 // The next call locks the interpreter mutex.
9308 return (TypeInfo_t*)info->Type();
9309}
9310
9311////////////////////////////////////////////////////////////////////////////////
9312
9313const char* TCling::MethodInfo_GetMangledName(MethodInfo_t* minfo) const
9314{
9317 // The next call locks the interpreter mutex.
9318 mangled_name = info->GetMangledName();
9319 return mangled_name;
9320}
9321
9322////////////////////////////////////////////////////////////////////////////////
9323
9324const char* TCling::MethodInfo_GetPrototype(MethodInfo_t* minfo) const
9325{
9327 // The next call locks the interpreter mutex.
9328 return info->GetPrototype();
9329}
9330
9331////////////////////////////////////////////////////////////////////////////////
9332
9333const char* TCling::MethodInfo_Name(MethodInfo_t* minfo) const
9334{
9336 // The next call locks the interpreter mutex.
9337 return info->Name();
9338}
9339
9340////////////////////////////////////////////////////////////////////////////////
9341
9342const char* TCling::MethodInfo_TypeName(MethodInfo_t* minfo) const
9343{
9345 // The next call locks the interpreter mutex.
9346 return info->TypeName();
9347}
9348
9349////////////////////////////////////////////////////////////////////////////////
9350
9351std::string TCling::MethodInfo_TypeNormalizedName(MethodInfo_t* minfo) const
9352{
9354 // The next part locks the interpreter mutex.
9355 if (info && info->IsValid())
9356 return info->Type()->NormalizedName(*fNormalizedCtxt);
9357 else
9358 return "";
9359}
9360
9361////////////////////////////////////////////////////////////////////////////////
9362
9363const char* TCling::MethodInfo_Title(MethodInfo_t* minfo) const
9364{
9366 // The next call locks the interpreter mutex.
9367 return info->Title();
9368}
9369
9370////////////////////////////////////////////////////////////////////////////////
9371
9373{
9374 if (func) {
9375 return MethodInfo_MethodCallReturnType(func->fInfo);
9376 } else {
9377 return EReturnType::kOther;
9378 }
9379}
9380
9381////////////////////////////////////////////////////////////////////////////////
9382
9384{
9386 if (info && info->IsValid()) {
9387 TClingTypeInfo *typeinfo = info->Type();
9388 clang::QualType QT( typeinfo->GetQualType().getCanonicalType() );
9389 if (QT->isEnumeralType()) {
9390 return EReturnType::kLong;
9391 } else if (QT->isPointerType()) {
9392 // Look for char*
9393 QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
9394 if ( QT->isCharType() ) {
9395 return EReturnType::kString;
9396 } else {
9397 return EReturnType::kOther;
9398 }
9399 } else if ( QT->isFloatingType() ) {
9400 int sz = typeinfo->Size();
9401 if (sz == 4 || sz == 8) {
9402 // Support only float and double.
9403 return EReturnType::kDouble;
9404 } else {
9405 return EReturnType::kOther;
9406 }
9407 } else if ( QT->isIntegerType() ) {
9408 int sz = typeinfo->Size();
9409 if (sz <= 8) {
9410 // Support only up to long long ... but
9411 // FIXME the TMethodCall::Execute only
9412 // return long (4 bytes) ...
9413 // The v5 implementation of TMethodCall::ReturnType
9414 // was not making the distinction so we let it go
9415 // as is for now, but we really need to upgrade
9416 // TMethodCall::Execute ...
9417 return EReturnType::kLong;
9418 } else {
9419 return EReturnType::kOther;
9420 }
9421 } else {
9422 return EReturnType::kOther;
9423 }
9424 } else {
9425 return EReturnType::kOther;
9426 }
9427}
9428
9429//______________________________________________________________________________
9430//
9431// MethodArgInfo interface
9432//
9433
9434////////////////////////////////////////////////////////////////////////////////
9435
9440
9441////////////////////////////////////////////////////////////////////////////////
9442
9448
9449////////////////////////////////////////////////////////////////////////////////
9450
9456
9457////////////////////////////////////////////////////////////////////////////////
9458
9464
9465////////////////////////////////////////////////////////////////////////////////
9466
9472
9473////////////////////////////////////////////////////////////////////////////////
9474
9480
9481////////////////////////////////////////////////////////////////////////////////
9482
9488
9489////////////////////////////////////////////////////////////////////////////////
9490
9492{
9494 return info->DefaultValue();
9495}
9496
9497////////////////////////////////////////////////////////////////////////////////
9498
9500{
9502 return info->Name();
9503}
9504
9505////////////////////////////////////////////////////////////////////////////////
9506
9508{
9510 return info->TypeName();
9511}
9512
9513////////////////////////////////////////////////////////////////////////////////
9514
9516{
9518 return info->Type()->NormalizedName(*fNormalizedCtxt);
9519}
9520
9521////////////////////////////////////////////////////////////////////////////////
9522
9528
9529//______________________________________________________________________________
9530//
9531// TypeInfo interface
9532//
9533
9534////////////////////////////////////////////////////////////////////////////////
9535
9537{
9538 delete (TClingTypeInfo*) tinfo;
9539}
9540
9541////////////////////////////////////////////////////////////////////////////////
9542
9548
9549////////////////////////////////////////////////////////////////////////////////
9550
9556
9557////////////////////////////////////////////////////////////////////////////////
9558
9563
9564////////////////////////////////////////////////////////////////////////////////
9565
9572
9573////////////////////////////////////////////////////////////////////////////////
9574
9576{
9578 return TClinginfo->IsValid();
9579}
9580
9581////////////////////////////////////////////////////////////////////////////////
9582
9584{
9586 return TClinginfo->Name();
9587}
9588
9589////////////////////////////////////////////////////////////////////////////////
9590
9596
9597////////////////////////////////////////////////////////////////////////////////
9598
9600{
9602 return TClinginfo->RefType();
9603}
9604
9605////////////////////////////////////////////////////////////////////////////////
9606
9608{
9610 return TClinginfo->Size();
9611}
9612
9613////////////////////////////////////////////////////////////////////////////////
9614
9616{
9618 return TClinginfo->TrueName(*fNormalizedCtxt);
9619}
9620
9621////////////////////////////////////////////////////////////////////////////////
9622
9624{
9626 return TClinginfo->QualTypePtr();
9627}
9628
9629
9630//______________________________________________________________________________
9631//
9632// TypedefInfo interface
9633//
9634
9635////////////////////////////////////////////////////////////////////////////////
9636
9641
9642////////////////////////////////////////////////////////////////////////////////
9643
9649
9650////////////////////////////////////////////////////////////////////////////////
9651
9657
9658////////////////////////////////////////////////////////////////////////////////
9659
9664
9665////////////////////////////////////////////////////////////////////////////////
9666
9674
9675////////////////////////////////////////////////////////////////////////////////
9676
9682
9683////////////////////////////////////////////////////////////////////////////////
9684
9690
9691////////////////////////////////////////////////////////////////////////////////
9692
9698
9699////////////////////////////////////////////////////////////////////////////////
9700
9706
9707////////////////////////////////////////////////////////////////////////////////
9708
9714
9715////////////////////////////////////////////////////////////////////////////////
9716
9718{
9720 return TClinginfo->Name();
9721}
9722
9723////////////////////////////////////////////////////////////////////////////////
9724
9726{
9728 return TClinginfo->Title();
9729}
9730
9731////////////////////////////////////////////////////////////////////////////////
9732
9733bool TCling::IsSameType(const void * QualTypePtr1, const void * QualTypePtr2) const
9734{
9735 clang::QualType QT1 = clang::QualType::getFromOpaquePtr(QualTypePtr1);
9736 clang::QualType QT2 = clang::QualType::getFromOpaquePtr(QualTypePtr2);
9737 return fInterpreter->getCI()->getASTContext().hasSameType(QT1, QT2);
9738}
9739
9740////////////////////////////////////////////////////////////////////////////////
9741
9742bool TCling::IsIntegerType(const void * QualTypePtr) const
9743{
9744 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9745 return QT->hasIntegerRepresentation();
9746}
9747
9748////////////////////////////////////////////////////////////////////////////////
9749
9750bool TCling::IsSignedIntegerType(const void * QualTypePtr) const
9751{
9752 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9753 return QT->hasSignedIntegerRepresentation();
9754}
9755
9756////////////////////////////////////////////////////////////////////////////////
9757
9758bool TCling::IsUnsignedIntegerType(const void * QualTypePtr) const
9759{
9760 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9761 return QT->hasUnsignedIntegerRepresentation();
9762}
9763
9764////////////////////////////////////////////////////////////////////////////////
9765
9766bool TCling::IsFloatingType(const void * QualTypePtr) const
9767{
9768 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9769 return QT->hasFloatingRepresentation();
9770}
9771
9772////////////////////////////////////////////////////////////////////////////////
9773
9774bool TCling::IsPointerType(const void * QualTypePtr) const
9775{
9776 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9777 return QT->hasPointerRepresentation();
9778}
9779
9780////////////////////////////////////////////////////////////////////////////////
9781
9782bool TCling::IsVoidPointerType(const void * QualTypePtr) const
9783{
9784 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9785 return QT->isVoidPointerType();
9786}
9787
9788////////////////////////////////////////////////////////////////////////////////
9789
9791{
9792 if (!fInitialMutex) {
9794 Error("SnapshotMutexState", "fRecurseCount != 0 even though initial mutex state is unset!");
9795 }
9796 fInitialMutex.fState = mtx->GetStateBefore();
9797 }
9798 // We will "forget" this lock once we backed out of all interpreter frames.
9799 // Here we are entering one, so ++.
9801}
9802
9803////////////////////////////////////////////////////////////////////////////////
9804
9806{
9807 if (!fInitialMutex)
9808 return;
9809 if (fInitialMutex.fRecurseCount == 0) {
9810 Error("ForgetMutexState", "mutex state's recurse count already 0!");
9811 }
9812 else if (--fInitialMutex.fRecurseCount == 0) {
9813 // We have returned from all interpreter frames. Reset the initial lock state.
9814 fInitialMutex.fState.reset();
9815 }
9816}
9817
9818////////////////////////////////////////////////////////////////////////////////
9819/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
9820
9822{
9823 if (gInterpreterMutex) {
9824 if (delta) {
9825 auto typedDelta = static_cast<MutexStateAndRecurseCountDelta *>(delta);
9826 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP{typedDelta};
9827 gCoreMutex->Apply(std::move(typedDelta->fDelta));
9828 // Now that we have the lock, update the global
9829 R__ASSERT(fInitialMutex.fRecurseCount == 0 && "Inconsistent state of fInitialMutex! Another thread within Interpreter critical section.");
9830 std::swap(fInitialMutex, typedDelta->fInitialState);
9831 } else {
9832 // This case happens when EnableThreadSafety is first called from
9833 // the interpreter function we just handled.
9834 // Since thread safety was not enabled at the time we rewound, there was
9835 // no lock taken and even-though we should be locking the rest of this
9836 // interpreter handling/modifying code (since there might be threads in
9837 // flight), we can't because there would not be any lock guard to release the
9838 // locks
9840 Error("ApplyToInterpreterMutex",
9841 "After returning from user code that turned on thread safety support, we notice that fInitialMutex is already used ... "
9842 "so the rest of this function/stack execution might have race condition (with the other thread that thinks it has exclusive access to the interpreter state.");
9843 }
9844 }
9845}
9846
9847////////////////////////////////////////////////////////////////////////////////
9848/// Reset the interpreter lock to the state it had before interpreter-related
9849/// calls happened.
9850
9852{
9853 if (fInitialMutex) {
9854 // Need to start a new recurse count.
9855 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP(new MutexStateAndRecurseCountDelta());
9856 std::swap(uniqueP->fInitialState, fInitialMutex);
9857 uniqueP->fDelta = gCoreMutex->Rewind(*uniqueP->fInitialState.fState);
9858 return uniqueP.release();
9859 }
9861 return nullptr;
9862}
#define R__EXTERN
Definition DllImport.h:26
The file contains utilities which are foundational and could be used across the core component of ROO...
#define d(i)
Definition RSha256.hxx:102
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
#define s1(x)
Definition RSha256.hxx:91
#define R(a, b, c, d, e, f, g, h, i)
Definition RSha256.hxx:110
#define e(i)
Definition RSha256.hxx:103
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
bool Bool_t
Boolean (0=false, 1=true) (bool)
Definition RtypesCore.h:78
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
long Longptr_t
Integer large enough to hold a pointer (platform-dependent)
Definition RtypesCore.h:90
short Version_t
Class version identifier (short)
Definition RtypesCore.h:80
unsigned long ULong_t
Unsigned long integer 4 bytes (unsigned long). Size depends on architecture.
Definition RtypesCore.h:70
long Long_t
Signed long integer 4 bytes (long). Size depends on architecture.
Definition RtypesCore.h:69
unsigned int UInt_t
Unsigned integer 4 bytes (unsigned int)
Definition RtypesCore.h:61
constexpr Bool_t kFALSE
Definition RtypesCore.h:109
constexpr Ssiz_t kNPOS
The equivalent of std::string::npos for the ROOT class TString.
Definition RtypesCore.h:132
long long Long64_t
Portable signed long integer 8 bytes.
Definition RtypesCore.h:84
unsigned long long ULong64_t
Portable unsigned long integer 8 bytes.
Definition RtypesCore.h:85
constexpr Bool_t kTRUE
Definition RtypesCore.h:108
const char Option_t
Option string (const char)
Definition RtypesCore.h:81
TClass *(* DictFuncPtr_t)()
Definition Rtypes.h:86
R__EXTERN TApplication * gApplication
R__EXTERN TClassTable * gClassTable
static bool IsFromRootCling()
Definition TClass.cxx:176
static void indent(ostringstream &buf, int indent_level)
The file contains facilities to work with C++ module files extensions used to store rdict files.
void TCling__RestoreInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:358
void TCling__TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:596
static void RegisterPreIncludedHeaders(cling::Interpreter &clingInterp)
Definition TCling.cxx:1334
static bool hasParsedRootmapForLibrary(llvm::StringRef lib)
Definition TCling.cxx:7433
void TCling__InvalidateGlobal(const clang::Decl *D)
Definition TCling.cxx:591
bool TClingLookupHelper__AutoParse(const char *cname)
Allow calling autoparsing from TMetaUtils.
Definition TCling.cxx:911
R__EXTERN int optind
Definition TCling.cxx:333
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
Definition TCling.cxx:385
void TCling__UpdateListsOnUnloaded(const cling::Transaction &T)
Definition TCling.cxx:586
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&normCtxt)
Definition TCling.cxx:574
int TCling__LoadLibrary(const char *library)
Load a library.
Definition TCling.cxx:349
void TCling__DEBUG__dump(clang::DeclContext *DC)
Definition TCling.cxx:226
bool TClingLookupHelper__CheckInClassTable(const std::string &tname, std::string &result)
Check if the class name is present in TClassTable.
Definition TCling.cxx:1020
ETupleOrdering
Check in what order the member of a tuple are layout.
Definition TCling.cxx:4047
bool TCling__LibraryLoadingFailed(const std::string &errmessage, const std::string &libStem, bool permanent, bool resolved)
Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name, which is extracted by er...
Definition TCling.cxx:368
static const std::unordered_set< std::string > gIgnoredPCMNames
List of dicts that have the PCM information already in the PCH.
Definition TCling.cxx:1997
static Bool_t s_IsLibraryLoaded(const char *libname, cling::Interpreter *fInterpreter)
Definition TCling.cxx:3263
const char * TCling__GetClassSharedLibs(const char *className, bool skipCore)
Definition TCling.cxx:650
static GlobalModuleIndex * loadGlobalModuleIndex(cling::Interpreter &interp)
Definition TCling.cxx:1115
bool TClingLookupHelper__ExistingTypeCheck(const std::string &tname, std::string &result)
Try hard to avoid looking up in the Cling database as this could enduce an unwanted autoparsing.
Definition TCling.cxx:920
static bool HasASTFileOnDisk(clang::Module *M, const clang::Preprocessor &PP, std::string *FullFileName=nullptr)
Checks if there is an ASTFile on disk for the given module M.
Definition TCling.cxx:1100
void TCling__UnlockCompilationDuringUserCodeExecution(void *)
Unlock the interpreter.
Definition TCling.cxx:396
static std::string AlternateTuple(const char *classname, const cling::LookupHelper &lh, Bool_t silent)
Definition TCling.cxx:4089
static bool R__InitStreamerInfoFactory()
Helper to initialize TVirtualStreamerInfo's factor early.
Definition TCling.cxx:1720
int TCling__AutoParseCallback(const char *className)
Definition TCling.cxx:645
clang::RecordDecl * TCling__DEBUG__DCtoRecordDecl(clang::DeclContext *DC)
Definition TCling.cxx:223
int TCling_GenerateDictionary(const std::vector< std::string > &classes, const std::vector< std::string > &headers, const std::vector< std::string > &fwdDecls, const std::vector< std::string > &unknown)
Definition TCling.cxx:716
static bool HaveFullGlobalModuleIndex
Definition TCling.cxx:1114
bool TCling__TEST_isInvalidDecl(clang::Decl *D)
Definition TCling.cxx:253
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:610
void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter *)
Definition TCling.cxx:581
const Decl * TCling__GetObjectDecl(TObject *obj)
Definition TCling.cxx:621
static ETupleOrdering IsTupleAscending()
Definition TCling.cxx:4065
void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
Definition TCling.cxx:605
static void TCling__UpdateClassInfo(const NamedDecl *TD)
Update TClingClassInfo for a class (e.g. upon seeing a definition).
Definition TCling.cxx:406
clang::DeclContext * TCling__DEBUG__getDeclContext(clang::Decl *D)
Definition TCling.cxx:217
int TCling__CompileMacro(const char *fileName, const char *options)
Definition TCling.cxx:661
#define R__DLLEXPORT
Definition TCling.cxx:153
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:377
void TCling__DEBUG__decl_dump(void *D)
Definition TCling.cxx:235
int TCling__AutoLoadCallback(const char *className)
Definition TCling.cxx:640
static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
Definition TCling.cxx:1065
static void RegisterCxxModules(cling::Interpreter &clingInterp)
Definition TCling.cxx:1218
static void ConstructorName(std::string &name, const clang::Decl *decl, cling::Interpreter &interp, const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt)
Definition TCling.cxx:8930
void TCling__PrintStackTrace()
Print a StackTrace!
Definition TCling.cxx:342
static int HandleInterpreterException(cling::MetaProcessor *metaProcessor, const char *input_line, cling::Interpreter::CompilationResult &compRes, cling::Value *result)
Let cling process a command line.
Definition TCling.cxx:2497
static std::string GetSharedLibImmediateDepsSlow(std::string lib, cling::Interpreter *interp, bool skipLoadedLibs=true)
This interface returns a list of dependent libraries in the form: lib libA.so libB....
Definition TCling.cxx:7342
void TCling__DEBUG__printName(clang::Decl *D)
Definition TCling.cxx:238
static clang::ClassTemplateDecl * FindTemplateInNamespace(clang::Decl *decl)
Find a template decl within N nested namespaces, 0<=N<inf Assumes 1 and only 1 template present and 1...
Definition TCling.cxx:697
static void PrintDlError(const char *dyLibName, const char *modulename)
Definition TCling.cxx:2022
TInterpreter * CreateInterpreter(void *interpLibHandle, const char *argv[])
Definition TCling.cxx:625
static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH, bool skipCore)
Definition TCling.cxx:7177
const char * fantomline
Definition TCling.cxx:858
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:600
static cling::Interpreter::CompilationResult ExecAutoParse(const char *what, Bool_t header, cling::Interpreter *interpreter)
Parse the payload or header.
Definition TCling.cxx:6496
static bool requiresRootMap(const char *rootmapfile)
Definition TCling.cxx:5676
clang::NamespaceDecl * TCling__DEBUG__DCtoNamespace(clang::DeclContext *DC)
Definition TCling.cxx:220
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
Definition TCling.cxx:617
static void LoadModules(const std::vector< std::string > &modules, cling::Interpreter &interp)
Loads the C++ modules that we require to run any ROOT program.
Definition TCling.cxx:1087
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
Definition TCling.cxx:656
void DestroyInterpreter(TInterpreter *interp)
Definition TCling.cxx:633
static bool hasPrecomputedLibraryDeps(llvm::StringRef lib)
Definition TCling.cxx:7454
void TCling__SplitAclicMode(const char *fileName, string &mode, string &args, string &io, string &fname)
Definition TCling.cxx:668
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
EDataType
Definition TDataType.h:28
@ kULong64_t
Definition TDataType.h:32
@ kLong64_t
Definition TDataType.h:32
@ kIsDestructor
@ kIsConversion
@ kIsInlined
@ kIsConstructor
@ kIsOperator
@ kIsPublic
Definition TDictionary.h:75
@ kIsConstant
Definition TDictionary.h:88
@ kIsConstMethod
Definition TDictionary.h:96
@ kIsClass
Definition TDictionary.h:65
@ kIsEnum
Definition TDictionary.h:68
@ kIsPrivate
Definition TDictionary.h:77
@ kIsFundamental
Definition TDictionary.h:70
@ kIsCompiled
Definition TDictionary.h:86
@ kIsStatic
Definition TDictionary.h:80
@ kIsExplicit
Definition TDictionary.h:94
@ kIsStruct
Definition TDictionary.h:66
@ kIsProtected
Definition TDictionary.h:76
@ kIsVirtual
Definition TDictionary.h:72
@ kIsUnion
Definition TDictionary.h:67
@ kIsPureVirtual
Definition TDictionary.h:73
@ kIsNamespace
Definition TDictionary.h:95
@ kIsNotReacheable
Definition TDictionary.h:87
#define gDirectory
Definition TDirectory.h:385
@ kEnvUser
Definition TEnv.h:26
@ kEnvGlobal
Definition TEnv.h:25
@ kEnvLocal
Definition TEnv.h:27
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:125
void Info(const char *location, const char *msgfmt,...)
Use this function for informational messages.
Definition TError.cxx:241
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:208
Int_t gErrorIgnoreLevel
errors with level below this value will be ignored. Default is kUnset.
Definition TError.cxx:33
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:252
void Fatal(const char *location, const char *msgfmt,...)
Use this function in case of a fatal error. It will abort the program.
Definition TError.cxx:267
#define N
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t option
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t cursor
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h length
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char cname
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t TPoint TPoint const char mode
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t property
Option_t Option_t TPoint TPoint const char text
char name[80]
Definition TGX11.cxx:148
R__EXTERN TVirtualMutex * gInterpreterMutex
#define R__LOCKGUARD_CLING(mutex)
R__EXTERN TInterpreter * gCling
#define gInterpreter
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
Definition TROOT.cxx:777
#define gROOT
Definition TROOT.h:417
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2570
@ kReadPermission
Definition TSystem.h:55
Bool_t R_ISREG(Int_t mode)
Definition TSystem.h:126
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
R__EXTERN TVirtualMutex * gGlobalMutex
#define R__LOCKGUARD(mutex)
#define R__WRITE_LOCKGUARD(mutex)
#define R__READ_LOCKGUARD(mutex)
const char * proto
Definition civetweb.c:18822
#define free
Definition civetweb.c:1578
#define snprintf
Definition civetweb.c:1579
const_iterator begin() const
const_iterator end() const
void AddTemplAndNargsToKeep(const clang::ClassTemplateDecl *templ, unsigned int i)
const Config_t & GetConfig() const
virtual std::unique_ptr< StateDelta > Rewind(const State &earlierState)=0
virtual void Apply(std::unique_ptr< StateDelta > &&delta)=0
static Longptr_t ExecuteFile(const char *file, Int_t *error=nullptr, Bool_t keep=kFALSE)
Execute a file containing a C++ macro (static method).
virtual TApplicationImp * GetApplicationImp()
virtual Bool_t IsCmdThread()
Each class (see TClass) has a linked list of its base class(es).
Definition TBaseClass.h:33
TClassRef is used to implement a permanent reference to a TClass object.
Definition TClassRef.h:29
static DictFuncPtr_t GetDict(const char *cname)
Given the class name returns the Dictionary() function of a class (uses hash of name).
static TProtoClass * GetProtoNorm(const char *cname)
Given the class normalized name returns the TClassProto object for the class.
static DictFuncPtr_t GetDictNorm(const char *cname)
Given the normalized class name returns the Dictionary() function of a class (uses hash of name).
static TProtoClass * GetProto(const char *cname)
Given the class name returns the TClassProto object for the class.
static Bool_t Check(const char *cname, std::string &normname)
static void Add(const char *cname, Version_t id, const std::type_info &info, DictFuncPtr_t dict, Int_t pragmabits)
Add a class to the class table (this is a static function).
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
TDataMember * GetDataMember(const char *datamember) const
Return pointer to datamember object with name "datamember".
Definition TClass.cxx:3501
ROOT::ESTLType GetCollectionType() const
Return the 'type' of the STL the TClass is representing.
Definition TClass.cxx:2907
void RemoveStreamerInfo(Int_t slot)
Remove and delete the StreamerInfo in the given slot.
Definition TClass.cxx:7477
EState fState
!Current 'state' of the class (Emulated,Interpreted,Loaded)
Definition TClass.h:286
std::atomic< TList * > fBase
Definition TClass.h:204
static void AddClassToDeclIdMap(TDictionary::DeclId_t id, TClass *cl)
static: Add a TClass* to the map of classes.
Definition TClass.cxx:578
Version_t fClassVersion
Definition TClass.h:225
TList * GetListOfFunctionTemplates(Bool_t load=kTRUE)
Return TListOfFunctionTemplates for a class.
Definition TClass.cxx:3856
void * DynamicCast(const TClass *base, void *obj, Bool_t up=kTRUE)
Cast obj of this class type up to baseclass cl if up is true.
Definition TClass.cxx:4973
static void RemoveClassDeclId(TDictionary::DeclId_t id)
Definition TClass.cxx:605
static Bool_t HasNoInfoOrEmuOrFwdDeclaredDecl(const char *)
Definition TClass.cxx:3460
static TClass * LoadClass(const char *requestedname, Bool_t silent)
Helper function used by TClass::GetClass().
Definition TClass.cxx:5851
Int_t Size() const
Return size of object of this class.
Definition TClass.cxx:5806
@ kLoading
Definition TClass.h:342
@ kUnloading
Definition TClass.h:342
TObjArray * fStreamerInfo
Definition TClass.h:201
ClassInfo_t * GetClassInfo() const
Definition TClass.h:448
ClassInfo_t * fClassInfo
Definition TClass.h:226
TVirtualCollectionProxy * GetCollectionProxy() const
Return the proxy describing the collection (if any).
Definition TClass.cxx:2918
void ResetCaches()
To clean out all caches.
Definition TClass.cxx:4273
static Int_t ReadRules()
Read the class.rules files from the default location:.
Definition TClass.cxx:1808
@ kInterpreted
Definition TClass.h:129
@ kHasTClassInit
Definition TClass.h:130
@ kEmulated
Definition TClass.h:128
@ kForwardDeclared
Definition TClass.h:127
@ kNamespaceForMeta
Definition TClass.h:134
std::atomic< Bool_t > fCanLoadClassInfo
!Indicates whether the ClassInfo is supposed to be available.
Definition TClass.h:269
std::atomic< Bool_t > fHasRootPcmInfo
!Whether info was loaded from a root pcm.
Definition TClass.h:268
const char * GetDeclFileName() const
Return name of the file containing the declaration of this class.
Definition TClass.cxx:3525
@ kIsTObject
Definition TClass.h:103
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition TClass.cxx:2994
Emulation of the CINT BaseClassInfo class.
const char * Name() const
Emulation of the CINT CallFunc class.
void SetArgs(const char *args)
void SetFunc(const TClingClassInfo *info, const char *method, const char *arglist, Longptr_t *poffset)
void ExecWithArgsAndReturn(void *address, const void *args[]=0, int nargs=0, void *ret=0)
void Exec(void *address, TInterpreterValue *interpVal=0)
TClingMethodInfo * FactoryMethod() const
bool IsAutoLoadingForJITSymbols() const
bool IsAutoLoadingEnabled() const
void SetAutoParsingSuspended(bool val=true)
void SetAutoLoadingForJITSymbols(bool val=true)
void SetAutoLoadingEnabled(bool val=true)
Emulation of the CINT ClassInfo class.
static bool IsEnum(cling::Interpreter *interp, const char *name)
void FullName(std::string &output, const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const
TClingMethodInfo GetMethodWithArgs(const char *fname, const char *arglist, Longptr_t *poffset, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch, EInheritanceMode imode=kWithInheritance) const
const clang::FunctionTemplateDecl * GetFunctionTemplate(const char *fname) const
TClingMethodInfo GetMethod(const char *fname) const
const clang::ValueDecl * GetDataMember(const char *name) const
Emulation of the CINT DataMemberInfo class.
virtual const char * Name() const
virtual bool IsValid() const
Uses clang::TextDiagnosticPrinter to format diagnostics, which are then passed to a user-specified fu...
Emulation of the CINT MethodInfo class.
bool IsValid() const override
Emulation of the CINT MethodInfo class.
TDictionary::DeclId_t GetDeclId() const
Emulation of the CINT TypeInfo class.
Emulation of the CINT TypedefInfo class.
Bridge between cling::Value and ROOT.
Definition TClingValue.h:36
const char * Data()
Definition TCling.cxx:1041
bool Append(const std::string &str)
Append string to the storage if not added already.
Definition TCling.cxx:1049
std::string fContent
Definition TCling.h:625
This class defines an interface to the cling C++ interpreter.
Definition TCling.h:102
static Int_t DeepAutoLoadImpl(const char *cls, std::unordered_set< std::string > &visited, bool nameIsNormalized)
Definition TCling.cxx:6368
const char * MethodArgInfo_DefaultValue(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9491
bool ClassInfo_IsScopedEnum(ClassInfo_t *info) const final
Definition TCling.cxx:8493
const char * TypeInfo_Name(TypeInfo_t *) const final
Definition TCling.cxx:9583
void * MethodInfo_InterfaceMethod(MethodInfo_t *minfo) const final
Definition TCling.cxx:9245
void LoadEnums(TListOfEnums &cl) const final
Create list of pointers to enums for TClass cl.
Definition TCling.cxx:4559
void UpdateListOfGlobals() final
No op: see TClingCallbacks (used to update the list of globals)
Definition TCling.cxx:4027
bool TypedefInfo_IsValid(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9677
Int_t AutoLoad(const char *classname, Bool_t knowDictNotLoaded=kFALSE) final
Load library containing the specified class.
Definition TCling.cxx:6429
void CallFunc_Init(CallFunc_t *func) const final
Definition TCling.cxx:8123
void SetGetline(const char *(*getlineFunc)(const char *prompt), void(*histaddFunc)(const char *line)) final
Set a getline function to call when input is needed.
Definition TCling.cxx:3790
bool LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
Definition TCling.cxx:6738
void GenericError(const char *error) const final
Let the interpreter issue a generic error, and set its error state.
Definition TCling.cxx:7638
std::vector< void * > fRegisterModuleDyLibs
Definition TCling.h:140
void CallFunc_ExecWithReturn(CallFunc_t *func, void *address, void *ret) const final
Definition TCling.cxx:8049
bool IsIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9742
TypeInfo_t * MethodInfo_Type(MethodInfo_t *minfo) const final
Definition TCling.cxx:9304
std::vector< std::string > fAutoLoadLibStorage
Definition TCling.h:118
void CallFunc_Delete(CallFunc_t *func) const final
Definition TCling.cxx:8026
Bool_t fLockProcessLine
Definition TCling.h:129
int LoadFile(const char *path) const final
Load a source file or library called path into the interpreter.
Definition TCling.cxx:7681
void ResetAll() final
Reset the Cling state to its initial state.
Definition TCling.cxx:3866
void SetDeclAttr(DeclId_t, const char *) final
Definition TCling.cxx:8916
void HandleNewDecl(const void *DV, bool isDeserialized, std::set< TClass * > &modifiedClasses)
Definition TCling.cxx:513
void InvalidateCachedDecl(const std::tuple< TListOfDataMembers *, TListOfFunctions *, TListOfFunctionTemplates *, TListOfEnums * > &Lists, const clang::Decl *D)
Invalidate cached TCling information for the given declaration, and removed it from the appropriate o...
Definition TCling.cxx:7073
Long_t MethodInfo_Property(MethodInfo_t *minfo) const final
Definition TCling.cxx:9286
void LoadFunctionTemplates(TClass *cl) const final
Create list of pointers to function templates for TClass cl.
Definition TCling.cxx:4606
bool ClassInfo_IsValidMethod(ClassInfo_t *info, const char *method, const char *proto, Longptr_t *offset, ROOT::EFunctionMatchMode=ROOT::kConversionMatch) const final
Definition TCling.cxx:8527
Long_t DataMemberInfo_Property(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8849
int SetClassAutoparsing(int) final
Enable/Disable the Autoparsing of headers.
Definition TCling.cxx:7766
std::vector< const char * > fCurExecutingMacros
Definition TCling.h:151
void CreateListOfDataMembers(TClass *cl) const final
Create list of pointers to data members for TClass cl.
Definition TCling.cxx:4653
void RewindDictionary() final
Rewind Cling dictionary to the point where it was before executing the current macro.
Definition TCling.cxx:3911
bool ClassInfo_IsValid(ClassInfo_t *info) const final
Definition TCling.cxx:8519
void UpdateListsOnCommitted(const cling::Transaction &T)
Definition TCling.cxx:6947
int TypeInfo_RefType(TypeInfo_t *) const final
Definition TCling.cxx:9599
void CreateListOfBaseClasses(TClass *cl) const final
Create list of pointers to base class(es) for TClass cl.
Definition TCling.cxx:4530
ClassInfo_t * ClassInfo_Factory(Bool_t all=kTRUE) const final
Definition TCling.cxx:8406
const char * MethodInfo_Name(MethodInfo_t *minfo) const final
Definition TCling.cxx:9333
BaseClassInfo_t * BaseClassInfo_Factory(ClassInfo_t *info) const final
Definition TCling.cxx:8663
Bool_t LoadText(const char *text) const final
Load the declarations from text into the interpreter.
Definition TCling.cxx:7696
const char * GetSharedLibDeps(const char *lib, bool tryDyld=false) final
Get the list a libraries on which the specified lib depends.
Definition TCling.cxx:7470
EReturnType MethodInfo_MethodCallReturnType(MethodInfo_t *minfo) const final
Definition TCling.cxx:9383
TObject * GetObjectAddress(const char *Name, void *&LookupCtx)
If the interpreter encounters Name, check whether that is an object ROOT could retrieve.
Definition TCling.cxx:7897
Longptr_t ProcessLineAsynch(const char *line, EErrorCode *error=nullptr)
Let cling process a command line asynch.
Definition TCling.cxx:3702
bool MethodInfo_IsValid(MethodInfo_t *minfo) const final
Definition TCling.cxx:9254
FuncTempInfo_t * FuncTempInfo_Factory(DeclId_t declid) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:9006
TypeInfo_t * TypeInfo_Factory() const final
Definition TCling.cxx:9543
bool IsClassAutoLoadingEnabled() const
Returns if class AutoLoading is currently enabled.
Definition TCling.cxx:7735
void InvalidateGlobal(const clang::Decl *D)
Invalidate cached TCling information for the given global declaration.
Definition TCling.cxx:7058
bool IsSameType(const void *QualTypePtr1, const void *QualTypePtr2) const final
Definition TCling.cxx:9733
int Evaluate(const char *, TInterpreterValue &) final
Get the interpreter value corresponding to the statement.
Definition TCling.cxx:7859
std::unique_ptr< TInterpreterValue > MakeInterpreterValue() const final
Definition TCling.cxx:7844
void UpdateListOfLoadedSharedLibraries()
Definition TCling.cxx:3482
const char * TypedefInfo_Title(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9725
~TCling() final
Destroy the interpreter interface.
Definition TCling.cxx:1672
void CallFunc_SetFuncProto(CallFunc_t *func, ClassInfo_t *info, const char *method, const char *proto, Longptr_t *Offset, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch) const final
Interface to cling function.
Definition TCling.cxx:8248
void InitRootmapFile(const char *name)
Create a resource table and read the (possibly) three resource files, i.e.
Definition TCling.cxx:5819
Int_t AutoParse(const char *cls) final
Parse the headers relative to the class Returns 1 in case of success, 0 in case of failure.
Definition TCling.cxx:6693
void LoadPCM(std::string pcmFileNameFullPath)
Tries to load a rdict PCM, issues diagnostics if it fails.
Definition TCling.cxx:1869
void UpdateListOfMethods(TClass *cl) const final
Update the list of pointers to method for TClass cl This is now a nop.
Definition TCling.cxx:4671
void AddFriendToClass(clang::FunctionDecl *, clang::CXXRecordDecl *) const
Inject function as a friend into klass.
Definition TCling.cxx:7950
void PrintIntro() final
No-op; see TRint instead.
Definition TCling.cxx:2722
Bool_t fCxxModulesEnabled
Definition TCling.h:130
int BaseClassInfo_Next(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8683
void RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
Internal function. Actually do the update of the ClassInfo when seeing.
Definition TCling.cxx:6805
CallFunc_t * CallFunc_FactoryCopy(CallFunc_t *func) const final
Definition TCling.cxx:8100
Double_t CallFunc_ExecDouble(CallFunc_t *func, void *address) const final
Definition TCling.cxx:8084
std::set< std::string > fAutoLoadedLibraries
Definition TCling.h:125
void CallFunc_ResetArg(CallFunc_t *func) const final
Definition TCling.cxx:8149
const char * GetCurrentMacroName() const final
Return the file name of the currently interpreted file, included or not.
Definition TCling.cxx:5627
Bool_t IsLoaded(const char *filename) const final
Return true if the file has already been loaded by cint.
Definition TCling.cxx:3306
void SaveGlobalsContext() final
Save the current Cling state of global objects.
Definition TCling.cxx:4014
void CallFunc_IgnoreExtraArgs(CallFunc_t *func, bool ignore) const final
Definition TCling.cxx:8115
void ApplyToInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:9821
void * LazyFunctionCreatorAutoload(const std::string &mangled_name)
Autoload a library based on a missing symbol.
Definition TCling.cxx:6761
Int_t GenerateDictionary(const char *classes, const char *includes="", const char *options=nullptr) final
Generate the dictionary for the C++ classes listed in the first argument (in a semi-colon separated l...
Definition TCling.cxx:4887
Bool_t ClassInfo_Contains(ClassInfo_t *info, DeclId_t declid) const final
Return true if the entity pointed to by 'declid' is declared in the context described by 'info'.
Definition TCling.cxx:8322
Bool_t IsLibraryLoaded(const char *libname) const final
Definition TCling.cxx:3272
Long_t GetExecByteCode() const final
This routines used to return the address of the internal wrapper function (of the interpreter) that w...
Definition TCling.cxx:7660
int DataMemberInfo_ArrayDim(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8775
DataMemberInfo_t * DataMemberInfo_FactoryCopy(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8809
Bool_t HandleNewTransaction(const cling::Transaction &T)
Helper function to increase the internal Cling count of transactions that change the AST.
Definition TCling.cxx:3807
int ReadRootmapFile(const char *rootmapfile, TUniqueString *uniqueString=nullptr)
Read and parse a rootmapfile in its new format, and return 0 in case of success, -1 if the file has a...
Definition TCling.cxx:5692
std::map< SpecialObjectLookupCtx_t, SpecialObjectMap_t > fSpecialObjectMaps
Definition TCling.h:155
int ClassInfo_Next(ClassInfo_t *info) const final
Definition TCling.cxx:8543
void SetErrmsgcallback(void *p) const final
Set a callback to receive error messages.
Definition TCling.cxx:7787
bool MethodArgInfo_IsValid(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9467
int TypeInfo_Size(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9607
Int_t DeleteGlobal(void *obj) final
Delete obj from Cling symbol table so it cannot be accessed anymore.
Definition TCling.cxx:3925
int GetSecurityError() const final
Interface to cling function.
Definition TCling.cxx:7668
void SetTempLevel(int val) const final
Create / close a scope for temporaries.
Definition TCling.cxx:7823
void Print(Option_t *option="") const final
Print information about the interpreter.
Definition TCling.cxx:2732
std::set< size_t > fPayloads
Definition TCling.h:122
UInt_t FuncTempInfo_TemplateNargs(FuncTempInfo_t *) const final
Return the maximum number of template arguments of the function template described by ft_info.
Definition TCling.cxx:9040
DeclId_t GetFunctionWithPrototype(ClassInfo_t *cl, const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch) final
Return pointer to cling interface function for a method of a class with a certain prototype,...
Definition TCling.cxx:5319
TypedefInfo_t * TypedefInfo_Factory() const final
Definition TCling.cxx:9644
TObjArray * fRootmapFiles
Definition TCling.h:128
Longptr_t ProcessLine(const char *line, EErrorCode *error=nullptr) final
Definition TCling.cxx:2527
int ClassInfo_Size(ClassInfo_t *info) const final
Definition TCling.cxx:8591
const char * MethodArgInfo_TypeName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9507
cling::Interpreter * GetInterpreterImpl() const
Definition TCling.h:650
Longptr_t ExecuteMacro(const char *filename, EErrorCode *error=nullptr) final
Execute a cling macro.
Definition TCling.cxx:5567
std::vector< std::pair< TClass *, DictFuncPtr_t > > fClassesToUpdate
Definition TCling.h:148
int DataMemberInfo_Next(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8833
const char * TypedefInfo_Name(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9717
void BaseClassInfo_Delete(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8656
Long_t MethodInfo_ExtraProperty(MethodInfo_t *minfo) const final
Definition TCling.cxx:9295
void LoadMacro(const char *filename, EErrorCode *error=nullptr) final
Load a macro file in cling's memory.
Definition TCling.cxx:3694
FuncTempInfo_t * FuncTempInfo_FactoryCopy(FuncTempInfo_t *) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:9017
int DataMemberInfo_MaxIndex(DataMemberInfo_t *dminfo, Int_t dim) const final
Definition TCling.cxx:8825
Bool_t FuncTempInfo_IsValid(FuncTempInfo_t *) const final
Check validity of a FuncTempInfo_t.
Definition TCling.cxx:9028
void AddIncludePath(const char *path) final
Add a directory to the list of directories in which the interpreter looks for include files.
Definition TCling.cxx:2764
bool ClassInfo_IsBase(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8478
void RecursiveRemove(TObject *obj) final
Delete object from cling symbol table so it can not be used anymore.
Definition TCling.cxx:3825
const char * DataMemberInfo_TypeName(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8873
DeclId_t GetDataMemberAtAddr(const void *addr) const final
Return pointer to cling DeclId for a data member with a given name.
Definition TCling.cxx:5114
void CallFunc_SetArgArray(CallFunc_t *func, Longptr_t *paramArr, Int_t nparam) const final
Definition TCling.cxx:8205
std::string CallFunc_GetWrapperCode(CallFunc_t *func) const final
Definition TCling.cxx:8295
void * RewindInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:9851
const char * MethodArgInfo_Name(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9499
Bool_t HasPCMForLibrary(const char *libname) const final
Return true if ROOT has cxxmodules pcm for a given library name.
Definition TCling.cxx:3281
void TypedefInfo_Init(TypedefInfo_t *tinfo, const char *name) const final
Definition TCling.cxx:9667
const char * DataMemberInfo_Title(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8897
Longptr_t CallFunc_ExecInt(CallFunc_t *func, void *address) const final
Definition TCling.cxx:8068
void ClearStack() final
Delete existing temporary values.
Definition TCling.cxx:3189
void SetAlloclockfunc(void(*)()) const final
[Place holder for Mutex Lock] Provide the interpreter with a way to acquire a lock used to protect cr...
Definition TCling.cxx:7717
Bool_t SetErrorMessages(Bool_t enable=kTRUE) final
If error messages are disabled, the interpreter should suppress its failures and warning messages fro...
Definition TCling.cxx:7537
MethodInfo_t * CallFunc_FactoryMethod(CallFunc_t *func) const final
Definition TCling.cxx:8107
void RegisterAutoLoadedLibrary(const char *libname) final
Register that a library was autoloaded either to provide a 'missing' symbol or to provide a class (se...
Definition TCling.cxx:3548
TypedefInfo_t * TypedefInfo_FactoryCopy(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9660
void GetFunctionOverloads(ClassInfo_t *cl, const char *funcname, std::vector< DeclId_t > &res) const final
Insert overloads of name in cl to res.
Definition TCling.cxx:5212
void UnRegisterTClassUpdate(const TClass *oldcl) final
If the dictionary is loaded, we can remove the class from the list (otherwise the class might be load...
Definition TCling.cxx:2467
std::string MethodArgInfo_TypeNormalizedName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9515
DeclId_t GetEnum(TClass *cl, const char *name) const final
Return pointer to cling Decl of global/static variable that is located at the address given by addr.
Definition TCling.cxx:4996
Long_t MethodArgInfo_Property(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9483
int TypedefInfo_Size(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9701
void CallFunc_ExecWithArgsAndReturn(CallFunc_t *func, void *address, const void *args[]=nullptr, int nargs=0, void *ret=nullptr) const final
Definition TCling.cxx:8057
void GetInterpreterTypeName(const char *name, std::string &output, Bool_t full=kFALSE) final
The 'name' is known to the interpreter, this function returns the internal version of this name (usua...
Definition TCling.cxx:5364
Int_t fGlobalsListSerial
Definition TCling.h:114
TString fSharedLibs
Definition TCling.h:113
std::map< std::string, llvm::StringRef > fPendingRdicts
Definition TCling.h:640
static void UpdateClassInfoWork(const char *name)
Definition TCling.cxx:6927
Int_t Load(const char *filenam, Bool_t system=kFALSE) final
Load a library file in cling's memory.
Definition TCling.cxx:3657
int TypedefInfo_Next(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9685
void * GetInterfaceMethod(TClass *cl, const char *method, const char *params, Bool_t objectIsConst=kFALSE) final
Return pointer to cling interface function for a method of a class with parameters params (params is ...
Definition TCling.cxx:5171
void TypeInfo_Init(TypeInfo_t *tinfo, const char *funcname) const final
Definition TCling.cxx:9566
Bool_t SetSuspendAutoParsing(Bool_t value) final
Suspend the Autoparsing of headers.
Definition TCling.cxx:7777
int DataMemberInfo_TypeSize(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8865
static void * fgSetOfSpecials
Definition TCling.h:105
const char * ClassInfo_Title(ClassInfo_t *info) const final
Definition TCling.cxx:8633
const char * DataMemberInfo_Name(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8889
const char * TypeName(const char *typeDesc) final
Return the absolute type of typeDesc.
Definition TCling.cxx:5642
ROOT::TMetaUtils::TNormalizedCtxt * fNormalizedCtxt
Definition TCling.h:136
void ForgetMutexState() final
Definition TCling.cxx:9805
int MethodInfo_Next(MethodInfo_t *minfo) const final
Definition TCling.cxx:9278
Long_t ClassInfo_ClassProperty(ClassInfo_t *info) const final
Definition TCling.cxx:8367
void MethodInfo_Delete(MethodInfo_t *minfo) const final
Interface to cling function.
Definition TCling.cxx:9197
bool fIsShuttingDown
Definition TCling.h:189
void MethodArgInfo_Delete(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9436
bool IsSignedIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9750
DataMemberInfo_t * DataMemberInfo_Factory(ClassInfo_t *clinfo, TDictionary::EMemberSelection selection) const final
Definition TCling.cxx:8790
void ClassInfo_Destruct(ClassInfo_t *info, void *arena) const final
Definition TCling.cxx:8398
TClass * GetClass(const std::type_info &typeinfo, Bool_t load) const final
Demangle the name (from the typeinfo) and then request the class via the usual name based interface (...
Definition TCling.cxx:6274
Int_t UnloadAllSharedLibraryMaps() final
Unload the library map entries coming from all the loaded shared libraries.
Definition TCling.cxx:6162
void ClassInfo_Init(ClassInfo_t *info, const char *funcname) const final
Definition TCling.cxx:8460
std::set< TClass * > & GetModTClasses()
Definition TCling.h:585
ClassInfo_t * BaseClassInfo_ClassInfo(BaseClassInfo_t *) const final
Definition TCling.cxx:8728
TClingCallbacks * fClingCallbacks
Definition TCling.h:141
Long64_t CallFunc_ExecInt64(CallFunc_t *func, void *address) const final
Definition TCling.cxx:8076
Long_t ClassInfo_Property(ClassInfo_t *info) const final
Definition TCling.cxx:8583
Longptr_t ClassInfo_GetBaseOffset(ClassInfo_t *fromDerived, ClassInfo_t *toBase, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8707
void UpdateEnumConstants(TEnum *enumObj, TClass *cl) const final
Definition TCling.cxx:438
void ExecuteWithArgsAndReturn(TMethod *method, void *address, const void *args[]=nullptr, int nargs=0, void *ret=nullptr) const final
Definition TCling.cxx:5549
Bool_t IsErrorMessagesEnabled() const final
If error messages are disabled, the interpreter should suppress its failures and warning messages fro...
Definition TCling.cxx:7523
TString fIncludePath
Definition TCling.h:115
int DisplayIncludePath(FILE *fout) const final
Interface to cling function.
Definition TCling.cxx:7600
void TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:7132
Long_t FuncTempInfo_Property(FuncTempInfo_t *) const final
Return the property of the function template.
Definition TCling.cxx:9061
TEnum * CreateEnum(void *VD, TClass *cl) const final
Definition TCling.cxx:486
const char * TypeInfo_TrueName(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9615
Int_t UnloadLibraryMap(const char *library) final
Unload library map entries coming from the specified library.
Definition TCling.cxx:6180
void RegisterTemporary(const TInterpreterValue &value)
Definition TCling.cxx:7870
MutexStateAndRecurseCount fInitialMutex
Definition TCling.h:176
const char * GetSharedLibs() final
Return the list of shared libraries loaded into the process.
Definition TCling.cxx:7170
int MethodArgInfo_Next(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9475
void SnapshotMutexState(ROOT::TVirtualRWMutex *mtx) final
Definition TCling.cxx:9790
Long_t TypeInfo_Property(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9591
const char * MethodInfo_GetPrototype(MethodInfo_t *minfo) const final
Definition TCling.cxx:9324
UInt_t FuncTempInfo_TemplateMinReqArgs(FuncTempInfo_t *) const final
Return the number of required template arguments of the function template described by ft_info.
Definition TCling.cxx:9051
std::vector< cling::Value > * fTemporaries
Definition TCling.h:135
void RegisterModule(const char *modulename, const char **headers, const char **includePaths, const char *payloadCode, const char *fwdDeclsCode, void(*triggerFunc)(), const FwdDeclArgsToKeepCollection_t &fwdDeclsArgToSkip, const char **classesHeaders, Bool_t lateRegistration=false, Bool_t hasCxxModule=false) final
Inject the module named "modulename" into cling; load all headers.
Definition TCling.cxx:2069
static Int_t ShallowAutoLoadImpl(const char *cls)
Definition TCling.cxx:6320
void MethodInfo_CreateSignature(MethodInfo_t *minfo, TString &signature) const final
Definition TCling.cxx:9204
Bool_t CheckClassTemplate(const char *name) final
Return true if there is a class template by the given name ...
Definition TCling.cxx:4508
void LibraryLoaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7155
void RegisterTClassUpdate(TClass *oldcl, DictFuncPtr_t dict) final
Register classes that already existed prior to their dictionary loading and that already had a ClassI...
Definition TCling.cxx:2458
bool IsVoidPointerType(const void *QualTypePtr) const final
Definition TCling.cxx:9782
TObjArray * GetRootMapFiles() const final
Definition TCling.h:226
bool DataMemberInfo_IsValid(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8817
bool ClassInfo_IsEnum(const char *name) const final
Definition TCling.cxx:8486
int MethodInfo_NDefaultArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9270
bool IsFloatingType(const void *QualTypePtr) const final
Definition TCling.cxx:9766
void CreateListOfMethods(TClass *cl) const final
Create list of pointers to methods for TClass cl.
Definition TCling.cxx:4662
Int_t RescanLibraryMap() final
Scan again along the dynamic path for library maps.
Definition TCling.cxx:6089
std::map< const cling::Transaction *, size_t > fTransactionHeadersMap
Definition TCling.h:120
void ReportDiagnosticsToErrorHandler(bool enable=true) final
Report diagnostics to the ROOT error handler (see TError.h).
Definition TCling.cxx:7796
const char * MethodInfo_GetMangledName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9313
TypeInfo_t * MethodArgInfo_TypeInfo(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9523
Bool_t fHeaderParsingOnDemand
Definition TCling.h:183
std::hash< std::string > fStringHashFunction
Definition TCling.h:126
TEnv * fMapfile
Definition TCling.h:117
static void RemoveAndInvalidateObject(List &L, Object *O)
Definition TCling.h:597
void * GetInterfaceMethodWithPrototype(TClass *cl, const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch) final
Return pointer to cling interface function for a method of a class with a certain prototype,...
Definition TCling.cxx:5274
void * ClassInfo_New(ClassInfo_t *info) const final
Definition TCling.cxx:8551
int DisplayClass(FILE *fout, const char *name, int base, int start) const final
Definition TCling.cxx:7591
void GetFunctionName(const clang::Decl *decl, std::string &name) const
Definition TCling.cxx:8952
void CreateListOfMethodArgs(TFunction *m) const final
Create list of pointers to method arguments for TMethod m.
Definition TCling.cxx:4687
const char * GetSTLIncludePath() const final
Return the directory containing CINT's stl cintdlls.
Definition TCling.cxx:7582
MethodArgInfo_t * MethodArgInfo_FactoryCopy(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9459
Longptr_t BaseClassInfo_Offset(BaseClassInfo_t *toBaseClassInfo, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8699
ECheckClassInfo CheckClassInfo(const char *name, Bool_t autoload, Bool_t isClassOrNamespaceOnly=kFALSE) final
Checks if an entity with the specified name is defined in Cling.
Definition TCling.cxx:4336
void * FindSym(const char *entry) const final
Interface to cling function.
Definition TCling.cxx:7629
void RegisterLoadedSharedLibrary(const char *name)
Register a new shared library name with the interpreter; add it to fSharedLibs.
Definition TCling.cxx:3557
void TypeInfo_Delete(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9536
int MethodInfo_NArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9262
DeclId_t GetDataMemberWithValue(const void *ptrvalue) const final
NOT IMPLEMENTED.
Definition TCling.cxx:5105
std::unordered_set< const clang::NamespaceDecl * > fNSFromRootmaps
Definition TCling.h:127
EReturnType MethodCallReturnType(TFunction *func) const final
Definition TCling.cxx:9372
void ProcessClassesToUpdate()
Definition TCling.cxx:2038
DeclId_t GetFunctionWithValues(ClassInfo_t *cl, const char *method, const char *params, Bool_t objectIsConst=kFALSE) final
Return pointer to cling DeclId for a method of a class with a certain prototype, i....
Definition TCling.cxx:5297
TString GetMangledName(TClass *cl, const char *method, const char *params, Bool_t objectIsConst=kFALSE) final
Return the cling mangled name for a method of a class with parameters params (params is a string of a...
Definition TCling.cxx:5126
const char * MethodInfo_Title(MethodInfo_t *minfo) const final
Definition TCling.cxx:9363
TString fRootmapLoadPath
Definition TCling.h:116
const char * BaseClassInfo_TmpltName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8762
Bool_t Declare(const char *code) final
Declare code to the interpreter, without any of the interpreter actions that could trigger a re-inter...
Definition TCling.cxx:3226
const char * BaseClassInfo_FullName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8744
void CallFunc_SetArgs(CallFunc_t *func, const char *param) const final
Definition TCling.cxx:8213
int UnloadFile(const char *path) const final
Definition TCling.cxx:7829
void SetClassInfo(TClass *cl, Bool_t reload=kFALSE, Bool_t silent=kFALSE) final
Set pointer to the TClingClassInfo in TClass.
Definition TCling.cxx:4200
void CallFunc_Exec(CallFunc_t *func, void *address) const final
Definition TCling.cxx:8033
Long_t FuncTempInfo_ExtraProperty(FuncTempInfo_t *) const final
Return the property not already defined in Property See TDictionary's EFunctionProperty.
Definition TCling.cxx:9126
bool CallFunc_IsValid(CallFunc_t *func) const final
Definition TCling.cxx:8132
const char * BaseClassInfo_Name(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8754
ROOT::TMetaUtils::TClingLookupHelper * fLookupHelper
Definition TCling.h:137
const char * DataMemberInfo_ValidArrayIndex(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8905
Int_t GetMore() const final
Return whether we are waiting for more input either because the collected input contains unbalanced b...
Definition TCling.cxx:4708
Bool_t fIsAutoParsingSuspended
Definition TCling.h:184
std::string ToString(const char *type, void *obj) final
Definition TCling.cxx:1058
DeclId_t GetDeclId(const llvm::GlobalValue *gv) const
Return pointer to cling DeclId for a global value.
Definition TCling.cxx:5036
void Execute(const char *function, const char *params, int *error=nullptr) final
Execute a global function with arguments params.
Definition TCling.cxx:5397
bool ClassInfo_IsLoaded(ClassInfo_t *info) const final
Definition TCling.cxx:8511
Longptr_t ClassInfo_Tagnum(ClassInfo_t *info) const final
Definition TCling.cxx:8599
Long_t BaseClassInfo_Property(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8720
void CallFunc_SetFunc(CallFunc_t *func, ClassInfo_t *info, const char *method, const char *params, Longptr_t *Offset) const final
Definition TCling.cxx:8221
std::vector< std::string > GetUsingNamespaces(ClassInfo_t *cl) const final
Get the scopes representing using declarations of namespace.
Definition TCling.cxx:4642
const char * ClassInfo_FileName(ClassInfo_t *info) const final
Definition TCling.cxx:8607
void FuncTempInfo_Title(FuncTempInfo_t *, TString &name) const final
Return the comments associates with this function template.
Definition TCling.cxx:9165
const char * ClassInfo_TmpltName(ClassInfo_t *info) const final
Definition TCling.cxx:8641
void SaveContext() final
Save the current Cling state.
Definition TCling.cxx:4001
void LoadPCMImpl(TFile &pcmFile)
Tries to load a PCM from TFile; returns true on success.
Definition TCling.cxx:1753
Bool_t IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
Definition TCling.cxx:6797
void ResetGlobals() final
Reset in Cling the list of global variables to the state saved by the last call to TCling::SaveGlobal...
Definition TCling.cxx:3882
void CodeComplete(const std::string &, size_t &, std::vector< std::string > &) final
The call to Cling's tab complition.
Definition TCling.cxx:7851
void ResetGlobalVar(void *obj) final
Reset the Cling 'user' global objects/variables state to the state saved by the last call to TCling::...
Definition TCling.cxx:3896
const char * MapCppName(const char *) const final
Interface to cling function.
Definition TCling.cxx:7704
Longptr_t Calc(const char *line, EErrorCode *error=nullptr) final
Directly execute an executable statement (e.g.
Definition TCling.cxx:3727
Int_t ReloadAllSharedLibraryMaps() final
Reload the library map entries coming from all the loaded shared libraries, after first unloading the...
Definition TCling.cxx:6101
void UpdateListOfGlobalFunctions() final
No op: see TClingCallbacks (used to update the list of global functions)
Definition TCling.cxx:4034
void DataMemberInfo_Delete(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8783
char fPrompt[64]
Definition TCling.h:110
const char * GetTopLevelMacroName() const final
Return the file name of the current un-included interpreted file.
Definition TCling.cxx:5580
void * fPrevLoadedDynLibInfo
Definition TCling.h:139
void UpdateListOfDataMembers(TClass *cl) const
Update the list of pointers to data members for TClass cl This is now a nop.
Definition TCling.cxx:4680
void InspectMembers(TMemberInspector &, const void *obj, const TClass *cl, Bool_t isTransient) final
Visit all members over members, recursing over base classes.
Definition TCling.cxx:2786
Int_t SetClassSharedLibs(const char *cls, const char *libs) final
Register the AutoLoading information for a class.
Definition TCling.cxx:6242
MethodInfo_t * MethodInfo_FactoryCopy(MethodInfo_t *minfo) const final
Definition TCling.cxx:9238
std::set< const char * > fParsedPayloadsAddresses
Definition TCling.h:123
CallFuncIFacePtr_t CallFunc_IFacePtr(CallFunc_t *func) const final
Definition TCling.cxx:8141
MethodArgInfo_t * MethodArgInfo_Factory() const final
Definition TCling.cxx:9443
static void UpdateClassInfo(char *name, Long_t tagnum)
No op: see TClingCallbacks.
Definition TCling.cxx:6921
DeclId_t GetFunction(ClassInfo_t *cl, const char *funcname) final
Return pointer to cling interface function for a method of a class with a certain name.
Definition TCling.cxx:5193
void ClassInfo_Delete(ClassInfo_t *info) const final
Definition TCling.cxx:8375
std::unique_ptr< cling::Interpreter > fInterpreter
Definition TCling.h:132
EDataType ClassInfo_GetUnderlyingType(ClassInfo_t *info) const final
Definition TCling.cxx:8502
void FuncTempInfo_Delete(FuncTempInfo_t *) const final
Delete the FuncTempInfo_t.
Definition TCling.cxx:8997
bool IsUnsignedIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9758
DeclId_t GetFunctionTemplate(ClassInfo_t *cl, const char *funcname) final
Return pointer to cling interface function for a method of a class with a certain name.
Definition TCling.cxx:5341
Int_t DeleteVariable(const char *name) final
Undeclare obj called name.
Definition TCling.cxx:3940
const char * GetClassSharedLibs(const char *cls, bool skipCore=true) final
Get the list of shared libraries containing the code for class cls.
Definition TCling.cxx:7276
Longptr_t DataMemberInfo_Offset(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8841
CallFunc_t * CallFunc_Factory() const final
Definition TCling.cxx:8092
MethodInfo_t * MethodInfo_Factory() const final
Definition TCling.cxx:9213
Long_t DataMemberInfo_TypeProperty(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8857
void ClearFileBusy() final
Reset the interpreter internal state in case a previous action was not correctly terminated.
Definition TCling.cxx:3181
cling::MetaProcessor * GetMetaProcessorImpl() const
Definition TCling.h:651
bool DiagnoseIfInterpreterException(const std::exception &e) const final
Definition TCling.cxx:2516
void SetAllocunlockfunc(void(*)()) const final
[Place holder for Mutex Unlock] Provide the interpreter with a way to release a lock used to protect ...
Definition TCling.cxx:7727
std::set< size_t > fLookedUpClasses
Definition TCling.h:121
bool IsValid() const final
Check if constructor exited correctly, ie the instance is in a valid state.
Definition TCling.cxx:3172
void AddAvailableIndentifiers(TSeqCollection &Idents) final
Definition TCling.cxx:2432
void TypedefInfo_Delete(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9637
void Reset() final
Pressing Ctrl+C should forward here.
Definition TCling.cxx:3850
const char * TypedefInfo_TrueName(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9709
int SetClassAutoLoading(int) const final
Enable/Disable the AutoLoading of libraries.
Definition TCling.cxx:7748
const char * ClassInfo_FullName(ClassInfo_t *info) const final
Definition TCling.cxx:8615
UInt_t AutoParseImplRecurse(const char *cls, bool topLevel)
Helper routine for TCling::AutoParse implementing the actual call to the parser and looping over temp...
Definition TCling.cxx:6545
const char * MethodInfo_TypeName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9342
void CallFunc_SetArg(CallFunc_t *func, Long_t param) const final
Definition TCling.cxx:8157
const char * GetIncludePath() final
Refresh the list of include paths known to the interpreter and return it with -I prepended.
Definition TCling.cxx:7551
void UpdateListsOnUnloaded(const cling::Transaction &T)
Invalidate stored TCling state for declarations included in transaction ‘T’.
Definition TCling.cxx:7031
void UpdateClassInfoWithDecl(const clang::NamedDecl *ND)
Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
Definition TCling.cxx:6863
void Initialize() final
Initialize the interpreter, once TROOT::fInterpreter is set.
Definition TCling.cxx:1690
int ClassInfo_GetMethodNArg(ClassInfo_t *info, const char *method, const char *proto, Bool_t objectIsConst=false, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch) const final
Definition TCling.cxx:8436
DeclId_t GetDataMember(ClassInfo_t *cl, const char *name) const final
Return pointer to cling Decl of global/static variable that is located at the address given by addr.
Definition TCling.cxx:4935
void * fAutoLoadCallBack
Definition TCling.h:149
void FuncTempInfo_Name(FuncTempInfo_t *, TString &name) const final
Return the name of this function template.
Definition TCling.cxx:9152
std::unique_ptr< cling::MetaProcessor > fMetaProcessor
Definition TCling.h:133
bool TypeInfo_IsValid(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9575
bool RegisterPrebuiltModulePath(const std::string &FullPath, const std::string &ModuleMapName="module.modulemap") const final
Definition TCling.cxx:1964
std::string MethodInfo_TypeNormalizedName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9351
const char * ClassInfo_Name(ClassInfo_t *info) const final
Definition TCling.cxx:8625
TClass * GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent=kFALSE) final
Generate a TClass for the given class.
Definition TCling.cxx:4718
ULong64_t fTransactionCount
Definition TCling.h:150
std::set< std::string > fAutoParseClasses
Definition TCling.h:124
bool ClassInfo_HasDefaultConstructor(ClassInfo_t *info, Bool_t testio=kFALSE) const final
Definition TCling.cxx:8444
void EndOfLineAction() final
It calls a "fantom" method to synchronize user keyboard input and ROOT prompt line.
Definition TCling.cxx:3255
TypeInfo_t * TypeInfo_FactoryCopy(TypeInfo_t *) const final
Definition TCling.cxx:9559
size_t ClassInfo_AlignOf(ClassInfo_t *info) const final
Definition TCling.cxx:8311
bool ClassInfo_HasMethod(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8452
void ClassInfo_DeleteArray(ClassInfo_t *info, void *arena, bool dtorOnly) const final
Definition TCling.cxx:8390
std::map< size_t, std::vector< const char * > > fClassesHeadersMap
Definition TCling.h:119
const char * DataMemberInfo_TypeTrueName(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8881
void ShutDown() final
Definition TCling.cxx:1711
void UpdateListOfTypes() final
No op: see TClingCallbacks (used to update the list of types)
Definition TCling.cxx:4041
void * TypeInfo_QualTypePtr(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9623
Long_t TypedefInfo_Property(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9693
void RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
Register Rdict data for future loading by LoadPCM;.
Definition TCling.cxx:1734
Longptr_t ProcessLineSynch(const char *line, EErrorCode *error=nullptr) final
Let cling process a command line synchronously, i.e we are waiting it will be finished.
Definition TCling.cxx:3711
TString GetMangledNameWithPrototype(TClass *cl, const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch) final
Return the cling mangled name for a method of a class with a certain prototype, i....
Definition TCling.cxx:5153
static void UpdateAllCanvases()
Update all canvases at end the terminal input command.
Definition TCling.cxx:6936
Int_t LoadLibraryMap(const char *rootmapfile=nullptr) final
Load map between class and library.
Definition TCling.cxx:5905
Longptr_t BaseClassInfo_Tagnum(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8736
void LibraryUnloaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7162
bool IsPointerType(const void *QualTypePtr) const final
Definition TCling.cxx:9774
Collection abstract base class.
Definition TCollection.h:65
virtual Int_t GetEntries() const
virtual void SetOwner(Bool_t enable=kTRUE)
Set whether this collection is the owner (enable==true) of its content.
All ROOT classes may have RTTI (run time type identification) support added.
Definition TDataMember.h:31
Basic data type descriptor (datatype information is obtained from CINT).
Definition TDataType.h:44
EMemberSelection
Kinds of members to include in lists.
const void * DeclId_t
TDirectory::TContext keeps track and restore the current directory.
Definition TDirectory.h:89
The TEnumConstant class implements the constants of the enum type.
The TEnum class implements the enum type.
Definition TEnum.h:33
static TEnum * GetEnum(const std::type_info &ti, ESearchAction sa=kALoadAndInterpLookup)
Definition TEnum.cxx:181
@ kNone
Definition TEnum.h:55
@ kAutoload
Definition TEnum.h:59
Definition TEnv.h:41
The TEnv class reads config files, by default named .rootrc.
Definition TEnv.h:79
THashList * GetTable() const
Definition TEnv.h:96
Bool_t IgnoreDuplicates(Bool_t ignore)
If set to true, no warnings in case of duplicates are issued.
Definition TEnv.cxx:809
virtual void SetRcName(const char *name)
Definition TEnv.h:101
virtual Int_t ReadFile(const char *fname, EEnvLevel level)
Read and parse the resource file for a certain level.
Definition TEnv.cxx:612
virtual void SetValue(const char *name, const char *value, EEnvLevel level=kEnvChange, const char *type=nullptr)
Set the value of a resource or create a new resource.
Definition TEnv.cxx:752
virtual TEnvRec * Lookup(const char *n) const
Loop over all resource records and return the one with name.
Definition TEnv.cxx:567
A file, usually with extension .root, that stores data and code in the form of serialized objects in ...
Definition TFile.h:130
Global functions class (global functions are obtained from CINT).
Definition TFunction.h:30
Global variables class (global variables are obtained from CINT).
Definition TGlobal.h:28
THashList implements a hybrid collection class consisting of a hash table and a list to store TObject...
Definition THashList.h:34
TObject * Remove(TObject *obj) override
Remove object from the list.
THashTable implements a hash table to store TObject's.
Definition THashTable.h:35
This class defines an abstract interface to a generic command line interpreter.
virtual bool RegisterPrebuiltModulePath(const std::string &FullPath, const std::string &ModuleMapName="module.modulemap") const =0
virtual Bool_t HasPCMForLibrary(const char *libname) const =0
virtual Int_t AutoParse(const char *cls)=0
int(* AutoLoadCallBack_t)(const char *)
virtual void RegisterAutoLoadedLibrary(const char *libname)=0
virtual Bool_t Declare(const char *code)=0
virtual const char * GetClassSharedLibs(const char *cls, bool skipCore=true)=0
std::vector< std::pair< std::string, int > > FwdDeclArgsToKeepCollection_t
TDictionary::DeclId_t DeclId_t
virtual TObjArray * GetRootMapFiles() const =0
Book space in a file, create I/O buffers, to fill them, (un)compress them.
Definition TKey.h:28
A collection of TDataMember objects designed for fast access given a DeclId_t and for keep track of T...
A collection of TEnum objects designed for fast access given a DeclId_t and for keep track of TEnum t...
A collection of TEnum objects designed for fast access given a DeclId_t and for keep track of TEnum t...
A collection of TFunction objects designed for fast access given a DeclId_t and for keep track of TFu...
A collection of TFunction objects designed for fast access given a DeclId_t and for keep track of TFu...
A doubly linked list.
Definition TList.h:38
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition TList.cxx:487
A TMemFile is like a normal TFile except that it reads and writes only from memory.
Definition TMemFile.h:27
Abstract base class for accessing the data-members of a class.
Each ROOT method (see TMethod) has a linked list of its arguments.
Definition TMethodArg.h:36
const char * GetFullTypeName() const
Get full type description of method argument, e.g.: "class TDirectory*".
const char * GetDefault() const
Get default value of method argument.
Each ROOT class (see TClass) has a linked list of methods.
Definition TMethod.h:38
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
TNamed()
Definition TNamed.h:38
An array of TObjects.
Definition TObjArray.h:31
virtual void Expand(Int_t newSize)
Expand or shrink the array to newSize elements.
virtual void Compress()
Remove empty slots from array.
Int_t GetEntries() const override
Return the number of objects in array (i.e.
TObject * Remove(TObject *obj) override
Remove object from array.
TObject * FindObject(const char *name) const override
Find an object in this collection using its name.
void Add(TObject *obj) override
Definition TObjArray.h:68
Collectable string class.
Definition TObjString.h:28
Mother of all ROOT objects.
Definition TObject.h:42
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:204
R__ALWAYS_INLINE Bool_t IsOnHeap() const
Definition TObject.h:160
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1082
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition TObject.cxx:424
static TClass * Class()
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1096
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition TObject.cxx:1124
virtual TClass * IsA() const
Definition TObject.h:248
void MakeZombie()
Definition TObject.h:55
@ kInvalidObject
if object ctor succeeded but object should not be used
Definition TObject.h:81
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:1070
Persistent version of a TClass.
Definition TProtoClass.h:38
static const TString & GetIncludeDir()
Get the include directory in the installation. Static utility function.
Definition TROOT.cxx:3347
static const char * GetMacroPath()
Get macro search path. Static utility function.
Definition TROOT.cxx:2917
static const std::vector< std::string > & AddExtraInterpreterArgs(const std::vector< std::string > &args)
Provide command line arguments to the interpreter construction.
Definition TROOT.cxx:3113
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition TROOT.cxx:3381
static const char **& GetExtraInterpreterArgs()
INTERNAL function! Used by rootcling to inject interpreter arguments through a C-interface layer.
Definition TROOT.cxx:3123
static const TString & GetSharedLibDir()
Get the shared libraries directory in the installation.
Definition TROOT.cxx:3208
Sequenceable collection abstract base class.
Int_t LastIndex() const
Describes a persistent version of a class.
Basic string class.
Definition TString.h:138
Ssiz_t Length() const
Definition TString.h:427
void Clear()
Clear string without changing its capacity.
Definition TString.cxx:1241
const char * Data() const
Definition TString.h:386
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:715
Bool_t IsNull() const
Definition TString.h:424
TString & Append(const char *cs)
Definition TString.h:583
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2459
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:643
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1289
virtual void FreeDirectory(void *dirp)
Free a directory.
Definition TSystem.cxx:859
virtual void * OpenDirectory(const char *name)
Open a directory.
Definition TSystem.cxx:850
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1680
virtual const char * GetIncludePath()
Get the list of include path.
Definition TSystem.cxx:4039
virtual TString SplitAclicMode(const char *filename, TString &mode, TString &args, TString &io) const
This method split a filename of the form:
Definition TSystem.cxx:4326
virtual const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1553
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1872
int GetPathInfo(const char *path, Long_t *id, Long_t *size, Long_t *flags, Long_t *modtime)
Get info about a file: id, size, flags, modification time.
Definition TSystem.cxx:1413
virtual const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Definition TSystem.cxx:1096
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition TSystem.cxx:1311
virtual const char * GetDirEntry(void *dirp)
Get a directory entry. Returns 0 if no more entries.
Definition TSystem.cxx:867
virtual int GetProcInfo(ProcInfo_t *info) const
Returns cpu and memory used by this process into the ProcInfo_t structure.
Definition TSystem.cxx:2509
virtual const char * BaseName(const char *pathname)
Base name of a file name. Base name of /user/root is root.
Definition TSystem.cxx:948
virtual const char * GetDynamicPath()
Return the dynamic path (used to find shared libraries).
Definition TSystem.cxx:1810
virtual const char * FindDynamicLibrary(TString &lib, Bool_t quiet=kFALSE)
Find a dynamic library using the system search paths.
Definition TSystem.cxx:2049
virtual void Sleep(UInt_t milliSec)
Sleep milliSec milli seconds.
Definition TSystem.cxx:439
virtual int CompileMacro(const char *filename, Option_t *opt="", const char *library_name="", const char *build_dir="", UInt_t dirmode=0)
This method compiles and loads a shared library containing the code from the file "filename".
Definition TSystem.cxx:2877
virtual const char * WorkingDirectory()
Return working directory.
Definition TSystem.cxx:885
virtual char * Which(const char *search, const char *file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1563
virtual void Setenv(const char *name, const char *value)
Set environment variable.
Definition TSystem.cxx:1664
virtual const char * HomeDirectory(const char *userName=nullptr)
Return the user's home directory.
Definition TSystem.cxx:901
virtual TString GetDirName(const char *pathname)
Return the directory name in pathname.
Definition TSystem.cxx:1046
virtual void StackTrace()
Print a stack trace.
Definition TSystem.cxx:747
char * DynamicPathName(const char *lib, Bool_t quiet=kFALSE)
Find a dynamic library called lib using the system search paths.
Definition TSystem.cxx:2035
virtual Int_t UnLock()=0
virtual Int_t Lock()=0
virtual TVirtualMutex * Factory(Bool_t=kFALSE)=0
TVirtualPad is an abstract base class for the Pad and Canvas classes.
Definition TVirtualPad.h:51
virtual void Update()=0
static void SetFactory(TVirtualStreamerInfo *factory)
static function: Set the StreamerInfo factory
TLine * line
const Int_t n
Definition legend1.C:16
Double_t ex[n]
Definition legend1.C:17
TF1 * f1
Definition legend1.C:11
#define I(x, y, z)
const std::string & GetPathSeparator()
const char & GetEnvPathSeparator()
const T * GetAnnotatedRedeclarable(const T *Redecl)
int GetClassVersion(const clang::RecordDecl *cl, const cling::Interpreter &interp)
Return the version number of the class or -1 if the function Class_Version does not exist.
void GetNormalizedName(std::string &norm_name, const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
Return the type name normalized for ROOT, keeping only the ROOT opaque typedef (Double32_t,...
std::string GetModuleFileName(const char *moduleName)
Return the dictionary file name for a module.
clang::QualType ReSubstTemplateArg(clang::QualType input, const clang::Type *instance)
Check if 'input' or any of its template parameter was substituted when instantiating the class templa...
static std::string DemangleNameForDlsym(const std::string &name)
void GetCppName(std::string &output, const char *input)
Return (in the argument 'output') a valid name of the C++ symbol/type (pass as 'input') that can be u...
std::pair< bool, int > GetTrivialIntegralReturnValue(const clang::FunctionDecl *funcCV, const cling::Interpreter &interp)
If the function contains 'just': return SomeValue; this routine will extract this value and return it...
std::string GetRealPath(const std::string &path)
void GetQualifiedName(std::string &qual_name, const clang::QualType &type, const clang::NamedDecl &forcontext)
Main implementation relying on GetFullyQualifiedTypeName All other GetQualifiedName functions leverag...
llvm::StringRef GetComment(const clang::Decl &decl, clang::SourceLocation *loc=nullptr)
Returns the comment (// striped away), annotating declaration in a meaningful for ROOT IO way.
void SetPathsForRelocatability(std::vector< std::string > &clingArgs)
Organise the parameters for cling in order to guarantee relocatability It treats the gcc toolchain an...
const clang::Type * GetUnderlyingType(clang::QualType type)
Return the base/underlying type of a chain of array or pointers type.
ROOT::ESTLType IsSTLCont(const clang::RecordDecl &cl)
type : type name: vector<list<classA,allocator>,allocator> result: 0 : not stl container abs(result):...
bool ExtractAttrPropertyFromName(const clang::Decl &decl, const std::string &propName, std::string &propValue)
This routine counts on the "propName<separator>propValue" format.
R__EXTERN TVirtualRWMutex * gCoreMutex
@ kWarning
Warnings about likely unexpected behavior.
EFunctionMatchMode
@ kExactMatch
bool IsStdPairBase(std::string_view name)
Definition TClassEdit.h:235
bool IsStdArray(std::string_view name)
Definition TClassEdit.h:230
bool IsStdClass(const char *type)
return true if the class belongs to the std namespace
bool IsStdPair(std::string_view name)
Definition TClassEdit.h:231
std::string InsertStd(const char *tname)
std::string GetLong64_Name(const char *original)
Replace 'long long' and 'unsigned long long' by 'Long64_t' and 'ULong64_t'.
char * DemangleTypeIdName(const std::type_info &ti, int &errorCode)
Demangle in a portable way the type id name.
const char * GetUnqualifiedName(const char *name)
Return the start of the unqualified name include in 'original'.
void Init(TClassEdit::TInterpreterLookupHelper *helper)
ROOT::ESTLType IsSTLCont(std::string_view type)
type : type name: vector<list<classA,allocator>,allocator> result: 0 : not stl container code of cont...
char * DemangleName(const char *mangled_name, int &errorCode)
Definition TClassEdit.h:255
int GetSplit(const char *type, std::vector< std::string > &output, int &nestedLoc, EModType mode=TClassEdit::kNone)
Stores in output (after emptying it) the split type.
@ kDropStlDefault
Definition TClassEdit.h:83
EComplexType GetComplexType(const char *)
static const char * what
Definition stlLoader.cc:5
Int_t fMode
Definition TSystem.h:135
RAII used to store Parser, Sema, Preprocessor state for recursive parsing.
Definition ClingRAII.h:22
std::unique_ptr< ROOT::TVirtualRWMutex::State > fState
State of gCoreMutex when the first interpreter-related function was invoked.
Definition TCling.h:159
Int_t fRecurseCount
Interpreter-related functions will push the "entry" lock state to *this.
Definition TCling.h:164
A read-only memory range which we do not control.
Definition TMemFile.h:33
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4