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 = 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.loadModuleMapFile(*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
3194////////////////////////////////////////////////////////////////////////////////
3195/// Declare code to the interpreter, without any of the interpreter actions
3196/// that could trigger a re-interpretation of the code. I.e. make cling
3197/// behave like a compiler: no dynamic lookup, no input wrapping for
3198/// subsequent execution, no automatic provision of declarations but just a
3199/// plain `#include`.
3200/// Returns true on success, false on failure.
3201
3202bool TCling::Declare(const char* code)
3203{
3205
3208
3209 bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
3210 fInterpreter->enableDynamicLookup(false);
3211 bool oldRawInput = fInterpreter->isRawInputEnabled();
3212 fInterpreter->enableRawInput(true);
3213
3214 Bool_t ret = LoadText(code);
3215
3216 fInterpreter->enableRawInput(oldRawInput);
3217 fInterpreter->enableDynamicLookup(oldDynLookup);
3218 return ret;
3219}
3220
3221////////////////////////////////////////////////////////////////////////////////
3222/// It calls a "fantom" method to synchronize user keyboard input
3223/// and ROOT prompt line.
3224
3229
3230// This static function is a hop of TCling::IsLibraryLoaded, which is taking a lock and calling
3231// into this function. This is because we wanted to avoid a duplication in TCling::IsLoaded, which
3232// was already taking a lock.
3233static Bool_t s_IsLibraryLoaded(const char* libname, cling::Interpreter* fInterpreter)
3234{
3235 // Check shared library.
3238 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.Data());
3239 return false;
3240}
3241
3247
3248////////////////////////////////////////////////////////////////////////////////
3249/// Return true if ROOT has cxxmodules pcm for a given library name.
3250// FIXME: We need to be able to support lazy loading of pcm generated by ACLiC.
3252{
3253 llvm::StringRef ModuleName(libname);
3254 ModuleName = llvm::sys::path::stem(ModuleName);
3255 ModuleName.consume_front("lib");
3256
3257 // FIXME: In case when the modulemap is not yet loaded we will return the
3258 // wrong result. Consider a call to HasPCMForLibrary(../test/libEvent.so)
3259 // We will only load the modulemap for libEvent.so after we dlopen libEvent
3260 // which may happen after calling this interface. Maybe we should also check
3261 // if there is a Event.pcm file and a module.modulemap, load it and return
3262 // true.
3263 clang::ModuleMap &moduleMap = fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3264 clang::Module *M = moduleMap.findModule(ModuleName);
3265 return M && !M->IsUnimportable && M->getASTFile();
3266}
3267
3268////////////////////////////////////////////////////////////////////////////////
3269/// Return true if the file has already been loaded by cint.
3270/// We will try in this order:
3271/// actual filename
3272/// filename as a path relative to
3273/// the include path
3274/// the shared library path
3275
3277{
3279
3280 //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
3281 // cling::DynamicLibraryManager.
3282
3283 std::string file_name = filename;
3284 size_t at = std::string::npos;
3285 while ((at = file_name.find("/./")) != std::string::npos)
3286 file_name.replace(at, 3, "/");
3287
3288 std::string filesStr = "";
3289 llvm::raw_string_ostream filesOS(filesStr);
3290 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3291 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3292 filesOS.flush();
3293
3294 llvm::SmallVector<llvm::StringRef, 100> files;
3295 llvm::StringRef(filesStr).split(files, "\n");
3296
3297 std::set<std::string> fileMap;
3298 llvm::StringRef file_name_ref(file_name);
3299 // Fill fileMap; return early on exact match.
3301 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3302 if ((*iF) == file_name_ref) return kTRUE; // exact match
3303 fileMap.insert(iF->str());
3304 }
3305
3306 if (fileMap.empty()) return kFALSE;
3307
3308 // Check MacroPath.
3309 TString sFilename(file_name.c_str());
3311 && fileMap.count(sFilename.Data())) {
3312 return kTRUE;
3313 }
3314
3315 // Check IncludePath.
3316 TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
3317 incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
3318 incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
3319 while (incPath.Index(" :") != -1) {
3320 incPath.ReplaceAll(" :", ":");
3321 }
3322 incPath.Prepend(".:");
3323 sFilename = file_name.c_str();
3325 && fileMap.count(sFilename.Data())) {
3326 return kTRUE;
3327 }
3328
3329 // Check shared library.
3330 if (s_IsLibraryLoaded(file_name.c_str(), GetInterpreterImpl()))
3331 return kTRUE;
3332
3333 //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
3334 clang::ConstSearchDirIterator *CurDir = nullptr;
3335 clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
3336 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3337 auto FE = HS.LookupFile(file_name.c_str(),
3338 clang::SourceLocation(),
3339 /*isAngled*/ false,
3340 /*FromDir*/ nullptr, CurDir,
3341 clang::ArrayRef<std::pair<clang::OptionalFileEntryRef,
3342 clang::DirectoryEntryRef>>(),
3343 /*SearchPath*/ nullptr,
3344 /*RelativePath*/ nullptr,
3345 /*RequestingModule*/ nullptr,
3346 /*SuggestedModule*/ nullptr,
3347 /*IsMapped*/ nullptr,
3348 /*IsFrameworkFound*/ nullptr,
3349 /*SkipCache*/ false,
3350 /*BuildSystemModule*/ false,
3351 /*OpenFile*/ false,
3352 /*CacheFail*/ false);
3353 if (FE) {
3354 // check in the source manager if the file is actually loaded
3355 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3356 // this works only with header (and source) files...
3357 clang::FileID FID = SM.translateFile(*FE);
3358 if (!FID.isInvalid() && FID.getHashValue() == 0)
3359 return kFALSE;
3360 else {
3361 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3362 if (SLocE.isFile() && !SLocE.getFile().getContentCache().getBufferIfLoaded())
3363 return kFALSE;
3364 if (!FID.isInvalid())
3365 return kTRUE;
3366 }
3367 // ...then check shared library again, but with full path now
3368 sFilename = FE->getName().str();
3370 && fileMap.count(sFilename.Data())) {
3371 return kTRUE;
3372 }
3373 }
3374 return kFALSE;
3375}
3376
3377
3378#if defined(R__MACOSX)
3379
3380////////////////////////////////////////////////////////////////////////////////
3381/// Check if lib is in the dynamic linker cache, returns true if it is, and if so,
3382/// modifies the library file name parameter `lib` from `/usr/lib/libFOO.dylib`
3383/// to `-lFOO` such that it can be passed to the linker.
3384/// This is a unique feature of macOS 11.
3385
3386static bool R__UpdateLibFileForLinking(TString &lib)
3387{
3388 const char *mapfile = nullptr;
3389#if __x86_64__
3390 mapfile = "/System/Library/dyld/dyld_shared_cache_x86_64.map";
3391#elif __arm64__
3392 mapfile = "/System/Library/dyld/dyld_shared_cache_arm64e.map";
3393#else
3394 #error unsupported architecture
3395#endif
3396 if (std::ifstream cacheMap{mapfile}) {
3397 std::string line;
3398 while (getline(cacheMap, line)) {
3399 if (line.find(lib) != std::string::npos) {
3400 lib.ReplaceAll("/usr/lib/lib","-l");
3401 lib.ReplaceAll(".dylib","");
3402 return true;
3403 }
3404 }
3405 return false;
3406 }
3407 return false;
3408}
3409#endif // R__MACOSX
3410
3411#if defined (R__LINUX) || defined (R__FBSD)
3412
3413////////////////////////////////////////////////////////////////////////////////
3414/// Callback for dl_iterate_phdr(), see `man dl_iterate_phdr`.
3415/// Collects opened libraries.
3416
3417static int callback_for_dl_iterate_phdr(struct dl_phdr_info *info, size_t size, void *data)
3418{
3419 // This function is called through UpdateListOfLoadedSharedLibraries() which is locked.
3420 static std::unordered_set<decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3421
3422 auto newLibs = static_cast<std::vector<std::string>*>(data);
3423 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3424 // Skip \0, "", and kernel pseudo-libs linux-vdso.so.1 or linux-gate.so.1
3425 if (info->dlpi_name && info->dlpi_name[0]
3426#if defined(R__FBSD)
3427 //skip the executable (with null addr)
3428 && info->dlpi_addr
3429 //has no path
3430 && strncmp(info->dlpi_name, "[vdso]", 6)
3431 //the linker does not like to be mmapped
3432 //causes a crash in cling::DynamicLibraryManager::loadLibrary())
3433 //with error message "mmap of entire address space failed: Cannot allocate memory"
3434 && strncmp(info->dlpi_name, "/libexec/ld-elf.so.1", 20)
3435#endif
3436 && strncmp(info->dlpi_name, "linux-vdso.so", 13)
3437 && strncmp(info->dlpi_name, "linux-vdso32.so", 15)
3438 && strncmp(info->dlpi_name, "linux-vdso64.so", 15)
3439 && strncmp(info->dlpi_name, "linux-gate.so", 13))
3440 newLibs->emplace_back(info->dlpi_name);
3441 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3442 }
3443 // No matter what the doc says, return != 0 means "stop the iteration".
3444 return 0;
3445}
3446
3447#endif // R__LINUX || R__FBSD
3448
3449
3450////////////////////////////////////////////////////////////////////////////////
3451
3453{
3454#if defined(R__WIN32) || defined(__CYGWIN__)
3455 HMODULE hModules[1024];
3456 void *hProcess;
3457 unsigned long cbModules;
3458 unsigned int i;
3459 hProcess = (void *)::GetCurrentProcess();
3461 // start at 1 to skip the executable itself
3462 for (i = 1; i < (cbModules / sizeof(void *)); i++) {
3463 static const int bufsize = 260;
3464 wchar_t winname[bufsize];
3465 char posixname[bufsize];
3467#if defined(__CYGWIN__)
3469#else
3470 std::wstring wpath = winname;
3471 std::replace(wpath.begin(), wpath.end(), '\\', '/');
3472 string path(wpath.begin(), wpath.end());
3473 strncpy(posixname, path.c_str(), bufsize);
3474#endif
3477 }
3478 }
3479#elif defined(R__MACOSX)
3480 // fPrevLoadedDynLibInfo stores the *next* image index to look at
3481 uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
3482
3484 // Skip non-dylibs
3485 if (mh->filetype == MH_DYLIB) {
3486 if (const char* imageName = _dyld_get_image_name(imageIndex)) {
3488 }
3489 }
3490
3491 ++imageIndex;
3492 }
3493 fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
3494#elif defined(R__LINUX) || defined(R__FBSD)
3495 // fPrevLoadedDynLibInfo is unused on Linux.
3496 (void) fPrevLoadedDynLibInfo;
3497
3498 std::vector<std::string> newLibs;
3500 for (auto &&lib: newLibs)
3501 RegisterLoadedSharedLibrary(lib.c_str());
3502#else
3503 Error("TCling::UpdateListOfLoadedSharedLibraries",
3504 "Platform not supported!");
3505#endif
3506}
3507
3508namespace {
3509template <int N>
3510static bool StartsWithStrLit(const char *haystack, const char (&needle)[N]) {
3511 return !strncmp(haystack, needle, N - 1);
3512}
3513}
3514
3515////////////////////////////////////////////////////////////////////////////////
3516/// Register that a library was autoloaded either to provide a 'missing' symbol
3517/// or to provide a class (see TClass::GetClass and TROOT::LoadClass).
3519{
3521}
3522
3523////////////////////////////////////////////////////////////////////////////////
3524/// Register a new shared library name with the interpreter; add it to
3525/// fSharedLibs.
3526
3528{
3529 // Ignore NULL filenames, aka "the process".
3530 if (!filename) return;
3531
3532 // Tell the interpreter that this library is available; all libraries can be
3533 // used to resolve symbols.
3534 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3535 if (!DLM->isLibraryLoaded(filename)) {
3536 DLM->loadLibrary(filename, true /*permanent*/, true /*resolved*/);
3537 }
3538
3539#if defined(R__MACOSX)
3540 // Check that this is not a system library that does not exist on disk.
3541 auto lenFilename = strlen(filename);
3542 auto isInMacOSSystemDir = [](const char *fn) {
3543 return StartsWithStrLit(fn, "/usr/lib/") || StartsWithStrLit(fn, "/System/Library/");
3544 };
3545 if (!strcmp(filename, "cl_kernels") // yepp, no directory
3546
3547 // These we should not link with (e.g. because they forward to .tbd):
3548 || StartsWithStrLit(filename, "/usr/lib/system/")
3549 || StartsWithStrLit(filename, "/usr/lib/libc++")
3550 || StartsWithStrLit(filename, "/System/Library/Frameworks/")
3551 || StartsWithStrLit(filename, "/System/Library/PrivateFrameworks/")
3552 || StartsWithStrLit(filename, "/System/Library/CoreServices/")
3553 || StartsWithStrLit(filename, "/usr/lib/libSystem")
3554 || StartsWithStrLit(filename, "/usr/lib/libstdc++")
3555 || StartsWithStrLit(filename, "/usr/lib/libicucore")
3556 || StartsWithStrLit(filename, "/usr/lib/libbsm")
3557 || StartsWithStrLit(filename, "/usr/lib/libobjc")
3558 || StartsWithStrLit(filename, "/usr/lib/libresolv")
3559 || StartsWithStrLit(filename, "/usr/lib/libauto")
3560 || StartsWithStrLit(filename, "/usr/lib/libcups")
3561 || StartsWithStrLit(filename, "/usr/lib/libDiagnosticMessagesClient")
3562 || StartsWithStrLit(filename, "/usr/lib/liblangid")
3563 || StartsWithStrLit(filename, "/usr/lib/libCRFSuite")
3564 || StartsWithStrLit(filename, "/usr/lib/libpam")
3565 || StartsWithStrLit(filename, "/usr/lib/libOpenScriptingUtil")
3566 || StartsWithStrLit(filename, "/usr/lib/libextension")
3567 || StartsWithStrLit(filename, "/usr/lib/libAudioToolboxUtility")
3568 || StartsWithStrLit(filename, "/usr/lib/liboah")
3569 || StartsWithStrLit(filename, "/usr/lib/libRosetta")
3570 || StartsWithStrLit(filename, "/usr/lib/libCoreEntitlements")
3571 || StartsWithStrLit(filename, "/usr/lib/libssl.")
3572 || StartsWithStrLit(filename, "/usr/lib/libcrypto.")
3573
3574 // The system lib is likely in macOS's blob.
3576
3577 // "Link against the umbrella framework 'System.framework' instead"
3578 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_kernel")
3579 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_platform")
3580 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_pthread")
3581
3582 // "cannot link directly with dylib/framework, your binary is not an allowed client of
3583 // /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/
3584 // SDKs/MacOSX.sdk/usr/lib/libAudioToolboxUtility.tbd for architecture x86_64
3585 || (lenFilename > 4 && !strcmp(filename + lenFilename - 4, ".tbd")))
3586 return;
3589 filename = sFileName.Data();
3590#elif defined(__CYGWIN__)
3591 // Check that this is not a system library
3592 static const int bufsize = 260;
3593 char posixwindir[bufsize];
3594 char *windir = std::getenv("WINDIR");
3595 if (windir)
3597 else
3598 snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
3599 if (strstr(filename, posixwindir) ||
3600 strstr(filename, "/usr/bin/cyg"))
3601 return;
3602#elif defined(R__WIN32)
3603 if (strstr(filename, "/Windows/"))
3604 return;
3605#elif defined (R__LINUX)
3606 if (strstr(filename, "/ld-linux")
3607 || strstr(filename, "linux-gnu/")
3608 || strstr(filename, "/libstdc++.")
3609 || strstr(filename, "/libgcc")
3610 || strstr(filename, "/libc.")
3611 || strstr(filename, "/libdl.")
3612 || strstr(filename, "/libm."))
3613 return;
3614#endif
3615 // Update string of available libraries.
3616 if (!fSharedLibs.IsNull()) {
3617 fSharedLibs.Append(" ");
3618 }
3620}
3621
3622////////////////////////////////////////////////////////////////////////////////
3623/// Load a library file in cling's memory.
3624/// if 'system' is true, the library is never unloaded.
3625/// Return 0 on success, -1 on failure.
3626
3628{
3629 assert(!IsFromRootCling() && "Trying to load library from rootcling!");
3630
3631 // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
3633 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3634 std::string canonLib = DLM->lookupLibrary(filename);
3635 cling::DynamicLibraryManager::LoadLibResult res
3636 = cling::DynamicLibraryManager::kLoadLibNotFound;
3637 if (!canonLib.empty()) {
3638 if (system)
3639 res = DLM->loadLibrary(filename, system, true);
3640 else {
3641 // For the non system libs, we'd like to be able to unload them.
3642 // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
3643 cling::Interpreter::CompilationResult compRes;
3644 HandleInterpreterException(GetMetaProcessorImpl(), Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/nullptr);
3645 if (compRes == cling::Interpreter::kSuccess)
3646 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3647 }
3648 }
3649
3650 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3652 }
3653 switch (res) {
3654 case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
3655 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
3656 default: break;
3657 };
3658 return -1;
3659}
3660
3661////////////////////////////////////////////////////////////////////////////////
3662/// Load a macro file in cling's memory.
3663
3664void TCling::LoadMacro(const char* filename, EErrorCode* error)
3665{
3666 ProcessLine(Form(".L %s", filename), error);
3667}
3668
3669////////////////////////////////////////////////////////////////////////////////
3670/// Let cling process a command line asynch.
3671
3673{
3674 return ProcessLine(line, error);
3675}
3676
3677////////////////////////////////////////////////////////////////////////////////
3678/// Let cling process a command line synchronously, i.e we are waiting
3679/// it will be finished.
3680
3682{
3684 if (gApplication) {
3685 if (gApplication->IsCmdThread()) {
3686 return ProcessLine(line, error);
3687 }
3688 return 0;
3689 }
3690 return ProcessLine(line, error);
3691}
3692
3693////////////////////////////////////////////////////////////////////////////////
3694/// Directly execute an executable statement (e.g. "func()", "3+5", etc.
3695/// however not declarations, like "Int_t x;").
3696
3698{
3699#ifdef R__WIN32
3700 // Test on ApplicationImp not being 0 is needed because only at end of
3701 // TApplication ctor the IsLineProcessing flag is set to 0, so before
3702 // we can not use it.
3704 while (gROOT->IsLineProcessing() && !gApplication) {
3705 Warning("Calc", "waiting for cling thread to free");
3706 gSystem->Sleep(500);
3707 }
3708 gROOT->SetLineIsProcessing();
3709 }
3710#endif // R__WIN32
3712 if (error) {
3713 *error = TInterpreter::kNoError;
3714 }
3715 cling::Value valRef;
3716 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3717 try {
3718 cr = fInterpreter->evaluate(line, valRef);
3719 }
3720 catch (cling::InterpreterException& ex)
3721 {
3722 Error("Calc", "%s.\n%s", ex.what(), "Evaluation of your expression was aborted.");
3723 ex.diagnose();
3724 cr = cling::Interpreter::kFailure;
3725 }
3726
3727 if (cr != cling::Interpreter::kSuccess) {
3728 // Failure in compilation.
3729 if (error) {
3730 // Note: Yes these codes are weird.
3732 }
3733 return 0L;
3734 }
3735 if (!valRef.isValid()) {
3736 // Failure at runtime.
3737 if (error) {
3738 // Note: Yes these codes are weird.
3739 *error = TInterpreter::kDangerous;
3740 }
3741 return 0L;
3742 }
3743
3744 if (valRef.isVoid()) {
3745 return 0;
3746 }
3747
3749#ifdef R__WIN32
3751 gROOT->SetLineHasBeenProcessed();
3752 }
3753#endif // R__WIN32
3754 return valRef.castAs<Longptr_t>();
3755}
3756
3757////////////////////////////////////////////////////////////////////////////////
3758/// Set a getline function to call when input is needed.
3759
3760void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
3761 void (*histaddFunc)(const char* line))
3762{
3763 // If cling offers a replacement for G__pause(), it would need to
3764 // also offer a way to customize at least the history recording.
3765
3766#if defined(R__MUST_REVISIT)
3767#if R__MUST_REVISIT(6,2)
3768 Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3769#endif
3770#endif
3771}
3772
3773////////////////////////////////////////////////////////////////////////////////
3774/// Helper function to increase the internal Cling count of transactions
3775/// that change the AST.
3776
3777Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
3778{
3780
3781 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3782 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3783 || T.macros_begin() != T.macros_end()
3784 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3786 return true;
3787 }
3788 return false;
3789}
3790
3791////////////////////////////////////////////////////////////////////////////////
3792/// Delete object from cling symbol table so it can not be used anymore.
3793/// cling objects are always on the heap.
3794
3796{
3797 // NOTE: When replacing the mutex by a ReadWrite mutex, we **must**
3798 // put in place the Read/Write part here. Keeping the write lock
3799 // here is 'catasptrophic' for scaling as it means that ALL calls
3800 // to RecursiveRemove will take the write lock and performance
3801 // of many threads trying to access the write lock at the same
3802 // time is relatively bad.
3804 // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
3805 // (but isn't at the moment).
3806 if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
3807 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
3808 if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
3810 DeleteGlobal(obj);
3811 ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
3812 }
3813 }
3814}
3815
3816////////////////////////////////////////////////////////////////////////////////
3817/// Pressing Ctrl+C should forward here. In the case where we have had
3818/// continuation requested we must reset it.
3819
3821{
3822 fMetaProcessor->cancelContinuation();
3823 // Reset the Cling state to the state saved by the last call to
3824 // TCling::SaveContext().
3825#if defined(R__MUST_REVISIT)
3826#if R__MUST_REVISIT(6,2)
3828 Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3829#endif
3830#endif
3831}
3832
3833////////////////////////////////////////////////////////////////////////////////
3834/// Reset the Cling state to its initial state.
3835
3837{
3838#if defined(R__MUST_REVISIT)
3839#if R__MUST_REVISIT(6,2)
3841 Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3842#endif
3843#endif
3844}
3845
3846////////////////////////////////////////////////////////////////////////////////
3847/// Reset in Cling the list of global variables to the state saved by the last
3848/// call to TCling::SaveGlobalsContext().
3849///
3850/// Note: Right now, all we do is run the global destructors.
3851
3853{
3855 // TODO:
3856 // Here we should iterate over the transactions (N-3) and revert.
3857 // N-3 because the first three internal to cling.
3858
3859 fInterpreter->runAndRemoveStaticDestructors();
3860}
3861
3862////////////////////////////////////////////////////////////////////////////////
3863/// Reset the Cling 'user' global objects/variables state to the state saved by the last
3864/// call to TCling::SaveGlobalsContext().
3865
3867{
3868#if defined(R__MUST_REVISIT)
3869#if R__MUST_REVISIT(6,2)
3871 Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3872#endif
3873#endif
3874}
3875
3876////////////////////////////////////////////////////////////////////////////////
3877/// Rewind Cling dictionary to the point where it was before executing
3878/// the current macro. This function is typically called after SEGV or
3879/// ctlr-C after doing a longjmp back to the prompt.
3880
3882{
3883#if defined(R__MUST_REVISIT)
3884#if R__MUST_REVISIT(6,2)
3886 Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3887#endif
3888#endif
3889}
3890
3891////////////////////////////////////////////////////////////////////////////////
3892/// Delete obj from Cling symbol table so it cannot be accessed anymore.
3893/// Returns 1 in case of success and 0 in case object was not in table.
3894
3896{
3897#if defined(R__MUST_REVISIT)
3898#if R__MUST_REVISIT(6,2)
3900 Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3901#endif
3902#endif
3903 return 0;
3904}
3905
3906////////////////////////////////////////////////////////////////////////////////
3907/// Undeclare obj called name.
3908/// Returns 1 in case of success, 0 for failure.
3909
3911{
3912#if defined(R__MUST_REVISIT)
3913#if R__MUST_REVISIT(6,2)
3914 Warning("DeleteVariable","should do more that just reseting the value to zero");
3915#endif
3916#endif
3917
3919 llvm::StringRef srName(name);
3920 const char* unscopedName = name;
3921 llvm::StringRef::size_type posScope = srName.rfind("::");
3922 const clang::DeclContext* declCtx = nullptr;
3923 if (posScope != llvm::StringRef::npos) {
3924 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3925 const clang::Decl* scopeDecl
3926 = lh.findScope(srName.substr(0, posScope),
3927 cling::LookupHelper::WithDiagnostics);
3928 if (!scopeDecl) {
3929 Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3930 name);
3931 return 0;
3932 }
3933 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3934 if (!declCtx) {
3935 Error("DeleteVariable",
3936 "Enclosing scope for variable %s is not a declaration context",
3937 name);
3938 return 0;
3939 }
3940 unscopedName += posScope + 2;
3941 }
3942 // Could trigger deserialization of decls.
3943 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
3944 clang::NamedDecl* nVarDecl
3945 = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3946 if (!nVarDecl) {
3947 Error("DeleteVariable", "Unknown variable %s", name);
3948 return 0;
3949 }
3950 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3951 if (!varDecl) {
3952 Error("DeleteVariable", "Entity %s is not a variable", name);
3953 return 0;
3954 }
3955
3956 clang::QualType qType = varDecl->getType();
3957 const clang::Type* type = qType->getUnqualifiedDesugaredType();
3958 // Cannot set a reference's address to nullptr; the JIT can place it
3959 // into read-only memory (ROOT-7100).
3960 if (type->isPointerType()) {
3961 int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3962 // set pointer to invalid.
3963 if (ppInt) *ppInt = nullptr;
3964 }
3965 return 1;
3966}
3967
3968////////////////////////////////////////////////////////////////////////////////
3969/// Save the current Cling state.
3970
3972{
3973#if defined(R__MUST_REVISIT)
3974#if R__MUST_REVISIT(6,2)
3976 Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3977#endif
3978#endif
3979}
3980
3981////////////////////////////////////////////////////////////////////////////////
3982/// Save the current Cling state of global objects.
3983
3985{
3986#if defined(R__MUST_REVISIT)
3987#if R__MUST_REVISIT(6,2)
3989 Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3990#endif
3991#endif
3992}
3993
3994////////////////////////////////////////////////////////////////////////////////
3995/// No op: see TClingCallbacks (used to update the list of globals)
3996
4000
4001////////////////////////////////////////////////////////////////////////////////
4002/// No op: see TClingCallbacks (used to update the list of global functions)
4003
4007
4008////////////////////////////////////////////////////////////////////////////////
4009/// No op: see TClingCallbacks (used to update the list of types)
4010
4012{
4013}
4014
4015////////////////////////////////////////////////////////////////////////////////
4016/// Check in what order the member of a tuple are layout.
4017enum class ETupleOrdering {
4018 kAscending,
4021};
4022
4028
4034
4036{
4037 std::tuple<int,double> value;
4040
4041 size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
4042 size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
4043
4044 size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
4045 size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
4046
4047 size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
4048 size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
4049
4050 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
4052 } else if (offset0 == desOffset0 && offset1 == desOffset1) {
4054 } else {
4056 }
4057}
4058
4059static std::string AlternateTuple(const char *classname, const cling::LookupHelper& lh, Bool_t silent)
4060{
4062 std::string alternateName = "TEmulatedTuple";
4063 alternateName.append( classname + 5 );
4064
4065 std::string fullname = "ROOT::Internal::" + alternateName;
4066 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
4067 /*resultType*/nullptr, /* intantiateTemplate= */ false))
4068 return fullname;
4069
4070 {
4071 // Check if we can produce the tuple
4072 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4073 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4074 auto deleter = [](TypeInfo_t *type) {
4075 gInterpreter->TypeInfo_Delete(type);
4076 };
4077 std::unique_ptr<TypeInfo_t, decltype(deleter)> type{ gInterpreter->TypeInfo_Factory(), deleter };
4078 while (iter != theEnd) {
4079 gInterpreter->TypeInfo_Init(type.get(), iter->c_str());
4080 if (gInterpreter->TypeInfo_Property(type.get()) & kIsNotReacheable) {
4081 if (!silent)
4082 Error("Load","Could not declare alternate type for %s since %s (or one of its context) is private or protected",
4083 classname, iter->c_str());
4084 return "";
4085 }
4086 ++iter;
4087 }
4088 }
4089
4090 std::string guard_name;
4092 std::ostringstream guard;
4093 guard << "ROOT_INTERNAL_TEmulated_";
4094 guard << guard_name;
4095
4096 std::ostringstream alternateTuple;
4097 std::ostringstream initializers;
4098
4099 alternateTuple << "#ifndef " << guard.str() << "\n";
4100 alternateTuple << "#define " << guard.str() << "\n";
4101 alternateTuple << "namespace ROOT { namespace Internal {\n";
4102 alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
4103 alternateTuple << "template <> struct " << alternateName << " {\n";
4104
4105 // This could also be a compile time choice ...
4106 switch(IsTupleAscending()) {
4108 unsigned int nMember = 0;
4109 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4110 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4111 auto sep = ':';
4112 while (iter != theEnd) {
4113 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4114 initializers << " " << sep << " _" << nMember << "(std::get<" << nMember << ">(std::forward<Tuple>(t)))\n";
4115 ++iter;
4116 ++nMember;
4117 sep = ',';
4118 }
4119 break;
4120 }
4122 unsigned int nMember = tupleContent.fElements.size() - 3;
4123 auto iter = tupleContent.fElements.rbegin() + 1; // skip the 'stars'.
4124 auto theEnd = tupleContent.fElements.rend() - 1; // Skip the template name (tuple).
4125 auto sep = ':';
4126 while (iter != theEnd) {
4127 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4128 initializers << " " << sep << " _" << nMember << "(std::get<" << nMember << ">(std::forward<Tuple>(t)))\n";
4129 ++iter;
4130 --nMember;
4131 sep = ',';
4132 }
4133 break;
4134 }
4136 Fatal("TCling::SetClassInfo::AlternateTuple",
4137 "Layout of std::tuple on this platform is unexpected.");
4138 break;
4139 }
4140 }
4141
4142 // default constructor
4143 alternateTuple << " TEmulatedTuple() = default;\n";
4144
4145 // constructor from other tuple-like types, like std::tuple
4146 alternateTuple << " template <typename Tuple>\n";
4147 alternateTuple << " TEmulatedTuple(Tuple&& t)\n";
4149 alternateTuple << " {}\n";
4150
4151 alternateTuple << "};\n";
4152 alternateTuple << "}}\n";
4153 alternateTuple << "#endif\n";
4154 if (!gCling->Declare(alternateTuple.str().c_str()))
4155 {
4156 // Declare is not silent (yet?), so add an explicit error message
4157 // to indicate the consequence of the syntax errors.
4158 Error("Load","Could not declare %s",alternateName.c_str());
4159 return "";
4160 }
4161 alternateName = "ROOT::Internal::" + alternateName;
4162 return alternateName;
4163}
4164
4165////////////////////////////////////////////////////////////////////////////////
4166/// Set pointer to the TClingClassInfo in TClass.
4167/// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
4168/// already have one.
4169
4171{
4172 // We are shutting down, there is no point in reloading, it only triggers
4173 // redundant deserializations.
4174 if (fIsShuttingDown) {
4175 // Remove the decl_id from the DeclIdToTClass map
4176 if (cl->fClassInfo) {
4179 // Test again as another thread may have set fClassInfo to nullptr.
4180 if (TClinginfo) {
4182 }
4183 delete TClinginfo;
4184 cl->fClassInfo = nullptr;
4185 }
4186 return;
4187 }
4188
4190 if (cl->fClassInfo && !reload) {
4191 return;
4192 }
4193 //Remove the decl_id from the DeclIdToTClass map
4195 if (TClinginfo) {
4197 }
4198 delete TClinginfo;
4199 cl->fClassInfo = nullptr;
4200 std::string name(cl->GetName());
4201
4202 auto SetWithoutClassInfoState = [](TClass *cl)
4203 {
4204 if (cl->fState != TClass::kHasTClassInit) {
4205 if (cl->fStreamerInfo->GetEntries() != 0) {
4207 } else {
4209 }
4210 }
4211 };
4212 // Handle the special case of 'tuple' where we ignore the real implementation
4213 // details and just overlay a 'simpler'/'simplistic' version that is easy
4214 // for the I/O to understand and handle.
4215 if (strncmp(cl->GetName(),"tuple<",std::char_traits<char>::length("tuple<"))==0) {
4216 if (!reload)
4217 name = AlternateTuple(cl->GetName(), fInterpreter->getLookupHelper(), silent);
4218 if (reload || name.empty()) {
4219 // We could not generate the alternate
4221 return;
4222 }
4223 }
4224
4226 // FIXME: Rather than adding an option to the TClingClassInfo, we should consider combining code
4227 // that is currently in the caller (like SetUnloaded) that disable AutoLoading and AutoParsing and
4228 // code is in the callee (disabling template instantiation) and end up with a more explicit class:
4229 // TClingClassInfoReadOnly.
4231 if (!info->IsValid()) {
4233 delete info;
4234 return;
4235 }
4236 cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
4237 // In case a class contains an external enum, the enum will be seen as a
4238 // class. We must detect this special case and make the class a Zombie.
4239 // Here we assume that a class has at least one method.
4240 // We can NOT call TClass::Property from here, because this method
4241 // assumes that the TClass is well formed to do a lot of information
4242 // caching. The method SetClassInfo (i.e. here) is usually called during
4243 // the building phase of the TClass, hence it is NOT well formed yet.
4245 if (
4246 info->IsValid() &&
4247 !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
4248 ) {
4250 }
4251 if (!info->IsLoaded()) {
4252 if (info->Property() & (kIsNamespace)) {
4253 // Namespaces can have info but no corresponding CINT dictionary
4254 // because they are auto-created if one of their contained
4255 // classes has a dictionary.
4257 }
4258 // this happens when no dictionary is available
4259 delete info;
4260 cl->fClassInfo = nullptr;
4261 }
4262 if (zombieCandidate && !cl->GetCollectionType()) {
4263 cl->MakeZombie();
4264 }
4265 // If we reach here, the info was valid (See early returns).
4266 if (cl->fState != TClass::kHasTClassInit) {
4267 if (cl->fClassInfo) {
4269 } else {
4270// if (TClassEdit::IsSTLCont(cl->GetName()) {
4271// There will be an emulated collection proxy, is that the same?
4272// cl->fState = TClass::kEmulated;
4273// } else {
4274 if (cl->fStreamerInfo->GetEntries() != 0) {
4276 } else {
4278 }
4279// }
4280 }
4281 }
4282 if (cl->fClassInfo) {
4283 TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
4284 }
4285}
4286
4287////////////////////////////////////////////////////////////////////////////////
4288/// Checks if an entity with the specified name is defined in Cling.
4289/// Returns kUnknown if the entity is not defined.
4290/// Returns kWithClassDefInline if the entity exists and has a ClassDefInline
4291/// Returns kKnown if the entity is defined.
4292///
4293/// By default, structs, namespaces, classes, enums and unions are looked for.
4294/// If the flag isClassOrNamespaceOnly is true, classes, structs and
4295/// namespaces only are considered. I.e. if the name is an enum or a union,
4296/// the returned value is false.
4297///
4298/// In the case where the class is not loaded and belongs to a namespace
4299/// or is nested, looking for the full class name is outputting a lots of
4300/// (expected) error messages. Currently the only way to avoid this is to
4301/// specifically check that each level of nesting is already loaded.
4302/// In case of templates the idea is that everything between the outer
4303/// '<' and '>' has to be skipped, e.g.: `aap<pippo<noot>::klaas>::a_class`
4304
4307{
4309 static const char *anonEnum = "anonymous enum ";
4310 static const int cmplen = strlen(anonEnum);
4311
4312 if (fIsShuttingDown || 0 == strncmp(name, anonEnum, cmplen)) {
4313 return kUnknown;
4314 }
4315
4316 // Do not turn on the AutoLoading if it is globally off.
4318
4319 // Avoid the double search below in case the name is a fundamental type
4320 // or typedef to a fundamental type.
4321 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
4322 TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
4323
4325 && fundType->GetType() > 0) {
4326 // Fundamental type, no a class.
4327 return kUnknown;
4328 }
4329
4330 // Migrated from within TClass::GetClass
4331 // If we want to know if a class or a namespace with this name exists in the
4332 // interpreter and this is an enum in the type system, before or after loading
4333 // according to the autoload function argument, return kUnknown.
4335 return kUnknown;
4336
4337 const char *classname = name;
4338
4339 // RAII to suspend and restore auto-loading and auto-parsing based on some external conditions.
4341 int fStoreAutoLoad = 0;
4342 int fStoreAutoParse = 0;
4343 bool fSuspendedAutoParse = false;
4344 public:
4346 fStoreAutoLoad = ((TCling*)gCling)->SetClassAutoLoading(autoload);
4347 }
4348
4349 void SuspendAutoParsing() {
4350 fSuspendedAutoParse = true;
4351 fStoreAutoParse = ((TCling*)gCling)->SetSuspendAutoParsing(true);
4352 }
4353
4356 ((TCling*)gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4357 ((TCling*)gCling)->SetClassAutoLoading(fStoreAutoLoad);
4358 }
4359 };
4360
4362 if (TClassEdit::IsStdPair(classname) || TClassEdit::IsStdPairBase(classname))
4363 autoLoadParseRAII.SuspendAutoParsing();
4364
4365 // First we want to check whether the decl exist, but _without_
4366 // generating any template instantiation. However, the lookup
4367 // still will create a forward declaration of the class template instance
4368 // if it exist. In this case, the return value of findScope will still
4369 // be zero but the type will be initialized.
4370 // Note in the corresponding code in ROOT 5, CINT was not instantiating
4371 // this forward declaration.
4372 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4373 const clang::Type *type = nullptr;
4374 const clang::Decl *decl
4375 = lh.findScope(classname,
4376 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4377 : cling::LookupHelper::NoDiagnostics,
4378 &type, /* intantiateTemplate= */ false );
4379 if (!decl) {
4380 std::string buf = TClassEdit::InsertStd(classname);
4381 decl = lh.findScope(buf,
4382 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4383 : cling::LookupHelper::NoDiagnostics,
4384 &type,false);
4385 }
4386
4387 if (type) {
4388 // If decl==0 and the type is valid, then we have a forward declaration.
4389 if (!decl) {
4390 // If we have a forward declaration for a class template instantiation,
4391 // we want to ignore it if it was produced/induced by the call to
4392 // findScope, however we can not distinguish those from the
4393 // instantiation induce by 'soft' use (and thus also induce by the
4394 // same underlying code paths)
4395 // ['soft' use = use not requiring a complete definition]
4396 // So to reduce the amount of disruption to the existing code we
4397 // would just ignore those for STL collection, for which we really
4398 // need to have the compiled collection proxy (and thus the TClass
4399 // bootstrap).
4400 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4401 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4402 (type->getAsCXXRecordDecl());
4403 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4404 // Since the point of instantiation is invalid, we 'guess' that
4405 // the 'instantiation' of the forwarded type appended in
4406 // findscope.
4408 // For STL Collection we return kUnknown.
4409 return kUnknown;
4410 }
4411 }
4412 }
4414 if (!tci.IsValid()) {
4415 return kUnknown;
4416 }
4419
4420 if (tci.Property() & propertiesMask) {
4421 bool hasClassDefInline = false;
4423 // We do not need to check for ClassDefInline when this is called from
4424 // TClass::Init, we only do it for the call from TClass::GetClass.
4425 auto hasDictionary = tci.GetMethod("Dictionary", "", false, nullptr, ROOT::kExactMatch);
4426 auto implLineFunc = tci.GetMethod("ImplFileLine", "", false, nullptr, ROOT::kExactMatch);
4427
4428 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4429 int lineNumber = 0;
4430 bool success = false;
4431 std::tie(success, lineNumber) =
4434 }
4435 }
4436
4437 // fprintf(stderr,"CheckClassInfo: %s had dict=%d inline=%d\n",name,hasDictionary.IsValid()
4438 // , hasClassDefInline);
4439
4440 // We are now sure that the entry is not in fact an autoload entry.
4442 return kWithClassDefInline;
4443 else
4444 return kKnown;
4445 } else {
4446 // We are now sure that the entry is not in fact an autoload entry.
4447 return kUnknown;
4448 }
4449 }
4450
4451 if (decl)
4452 return kKnown;
4453 else
4454 return kUnknown;
4455
4456 // Setting up iterator part of TClingTypedefInfo is too slow.
4457 // Copy the lookup code instead:
4458 /*
4459 TClingTypedefInfo t(fInterpreter, name);
4460 if (t.IsValid() && !(t.Property() & kIsFundamental)) {
4461 delete[] classname;
4462 return kTRUE;
4463 }
4464 */
4465
4466// const clang::Decl *decl = lh.findScope(name);
4467// if (!decl) {
4468// std::string buf = TClassEdit::InsertStd(name);
4469// decl = lh.findScope(buf);
4470// }
4471
4472// return (decl);
4473}
4474
4475////////////////////////////////////////////////////////////////////////////////
4476/// Return true if there is a class template by the given name ...
4477
4479{
4480 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4481 // Interpreter transaction ahead, needs locking
4483 const clang::Decl *decl
4484 = lh.findClassTemplate(name,
4485 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4486 : cling::LookupHelper::NoDiagnostics);
4487 if (!decl) {
4488 std::string strname = "std::";
4489 strname += name;
4490 decl = lh.findClassTemplate(strname,
4491 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4492 : cling::LookupHelper::NoDiagnostics);
4493 }
4494 return nullptr != decl;
4495}
4496
4497////////////////////////////////////////////////////////////////////////////////
4498/// Create list of pointers to base class(es) for TClass cl.
4499
4501{
4503 if (cl->fBase) {
4504 return;
4505 }
4506 // Ignore the base class (e.g. `std::_Complex_base` on Windows)
4508 cl->fBase = new TList();
4509 return;
4510 }
4512 if (!tci) return;
4514 TList *listOfBase = new TList;
4515 while (t.Next()) {
4516 // if name cannot be obtained no use to put in list
4517 if (t.IsValid() && t.Name()) {
4519 listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
4520 }
4521 }
4522 // Now that is complete, publish it.
4523 cl->fBase = listOfBase;
4524}
4525
4526////////////////////////////////////////////////////////////////////////////////
4527/// Create list of pointers to enums for TClass cl.
4528
4530{
4532
4533 const Decl * D;
4534 TClass* cl = enumList.GetClass();
4535 if (cl) {
4536 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4537 }
4538 else {
4539 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4540 }
4541 // Iterate on the decl of the class and get the enums.
4542 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4543 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4544 // Collect all contexts of the namespace.
4545 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4546 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4548 declIter != declEnd; ++declIter) {
4549 // Iterate on all decls for each context.
4550 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4551 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4552 if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4553 // Get name of the enum type.
4554 std::string buf;
4555 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4556 llvm::raw_string_ostream stream(buf);
4557 // Don't trigger fopen of the source file to count lines:
4558 Policy.AnonymousTagLocations = false;
4559 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
4560 stream.flush();
4561 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
4562 if (!buf.empty()) {
4563 const char* name = buf.c_str();
4564 // Add the enum to the list of loaded enums.
4565 enumList.Get(ED, name);
4566 }
4567 }
4568 }
4569 }
4570 }
4571}
4572
4573////////////////////////////////////////////////////////////////////////////////
4574/// Create list of pointers to function templates for TClass cl.
4575
4577{
4579
4580 const Decl * D;
4582 if (cl) {
4583 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4585 }
4586 else {
4587 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4588 funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
4589 }
4590 // Iterate on the decl of the class and get the enums.
4591 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4592 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4593 // Collect all contexts of the namespace.
4594 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4595 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4598 // Iterate on all decls for each context.
4599 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4600 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4601 if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4602 funcTempList->Get(FTD);
4603 }
4604 }
4605 }
4606 }
4607}
4608
4609////////////////////////////////////////////////////////////////////////////////
4610/// Get the scopes representing using declarations of namespace
4611
4612std::vector<std::string> TCling::GetUsingNamespaces(ClassInfo_t *cl) const
4613{
4615 return ci->GetUsingNamespaces();
4616}
4617
4618////////////////////////////////////////////////////////////////////////////////
4619/// Create list of pointers to data members for TClass cl.
4620/// This is now a nop. The creation and updating is handled in
4621/// TListOfDataMembers.
4622
4624{
4625}
4626
4627////////////////////////////////////////////////////////////////////////////////
4628/// Create list of pointers to methods for TClass cl.
4629/// This is now a nop. The creation and updating is handled in
4630/// TListOfFunctions.
4631
4633{
4634}
4635
4636////////////////////////////////////////////////////////////////////////////////
4637/// Update the list of pointers to method for TClass cl
4638/// This is now a nop. The creation and updating is handled in
4639/// TListOfFunctions.
4640
4642{
4643}
4644
4645////////////////////////////////////////////////////////////////////////////////
4646/// Update the list of pointers to data members for TClass cl
4647/// This is now a nop. The creation and updating is handled in
4648/// TListOfDataMembers.
4649
4651{
4652}
4653
4654////////////////////////////////////////////////////////////////////////////////
4655/// Create list of pointers to method arguments for TMethod m.
4656
4658{
4660 if (m->fMethodArgs) {
4661 return;
4662 }
4663 TList *arglist = new TList;
4665 while (t.Next()) {
4666 if (t.IsValid()) {
4668 arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
4669 }
4670 }
4671 m->fMethodArgs = arglist;
4672}
4673
4674////////////////////////////////////////////////////////////////////////////////
4675/// Return whether we are waiting for more input either because the collected
4676/// input contains unbalanced braces or last seen token was a `\` (backslash-newline)
4677
4679{
4680 return fMetaProcessor->awaitingMoreInput();
4681}
4682
4683////////////////////////////////////////////////////////////////////////////////
4684/// Generate a TClass for the given class.
4685/// Since the caller has already check the ClassInfo, let it give use the
4686/// result (via the value of emulation) rather than recalculate it.
4687
4688TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
4689{
4690// For now the following line would lead to the (unwanted) instantiation
4691// of class template. This could/would need to be resurrected only if
4692// we re-introduce so sort of automatic instantiation. However this would
4693// have to include carefull look at the template parameter to avoid
4694// creating instance we can not really use (if the parameter are only forward
4695// declaration or do not have all the necessary interfaces).
4696
4697 // TClingClassInfo tci(fInterpreter, classname);
4698 // if (1 || !tci.IsValid()) {
4699
4700 Version_t version = 1;
4701 if (TClassEdit::IsSTLCont(classname)) {
4702 version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4703 }
4705 TClass *cl = new TClass(classname, version, silent);
4706 if (!emulation) {
4707 // Set the class version if the class is versioned.
4708 // Note that we cannot just call CLASS::Class_Version() as we might not have
4709 // an execution engine (when invoked from rootcling).
4710
4711 // Do not call cl->GetClassVersion(), it has side effects!
4713 if (oldvers == version && cl->GetClassInfo()) {
4714 // We have a version and it might need an update.
4716 if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
4717 // Namespaces don't have class versions.
4718 return cl;
4719 }
4720 TClingMethodInfo mi = cli->GetMethod("Class_Version", "", nullptr /*poffset*/,
4723 if (!mi.IsValid()) {
4724 if (cl->TestBit(TClass::kIsTObject)) {
4725 Error("GenerateTClass",
4726 "Cannot find %s::Class_Version()! Class version might be wrong.",
4727 cl->GetName());
4728 }
4729 return cl;
4730 }
4731 Version_t newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->GetDecl()),
4732 *fInterpreter);
4733 if (newvers == -1) {
4734 // Didn't manage to determine the class version from the AST.
4735 // Use runtime instead.
4736 if ((mi.Property() & kIsStatic)
4737 && !fInterpreter->isInSyntaxOnlyMode()) {
4738 // This better be a static function.
4740 callfunc.SetFunc(&mi);
4741 newvers = callfunc.ExecInt(nullptr);
4742 } else {
4743 Error("GenerateTClass",
4744 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4745 cl->GetName());
4746 }
4747 }
4748 if (newvers != oldvers) {
4749 cl->fClassVersion = newvers;
4750 cl->fStreamerInfo->Expand(newvers + 2 + 10);
4751 }
4752 }
4753 }
4754
4755 return cl;
4756
4757// } else {
4758// return GenerateTClass(&tci,silent);
4759// }
4760}
4761
4762#if 0
4763////////////////////////////////////////////////////////////////////////////////
4764
4766{
4767 includes += info->FileName();
4768
4769 const clang::ClassTemplateSpecializationDecl *templateCl
4770 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->GetDecl());
4771 if (templateCl) {
4772 for(unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
4773 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4774 if (arg.getKind() == clang::TemplateArgument::Type) {
4775 const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
4776
4777 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4778 // We really need a header file.
4779 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4780 if (argdecl) {
4781 includes += ";";
4782 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4784 } else {
4785 std::string Result;
4786 llvm::raw_string_ostream OS(Result);
4787 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4788 Warning("TCling::GenerateTClass","Missing header file for %s",OS.str().c_str());
4789 }
4790 }
4791 }
4792 }
4793 }
4794}
4795#endif
4796
4797////////////////////////////////////////////////////////////////////////////////
4798/// Generate a TClass for the given class.
4799
4801{
4803 if (!info || !info->IsValid()) {
4804 Fatal("GenerateTClass","Requires a valid ClassInfo object");
4805 return nullptr;
4806 }
4807 // We are in the case where we have AST nodes for this class.
4808 TClass *cl = nullptr;
4809 std::string classname;
4810 info->FullName(classname,*fNormalizedCtxt); // Could we use Name()?
4811 if (TClassEdit::IsSTLCont(classname)) {
4812#if 0
4813 Info("GenerateTClass","Will (try to) generate the compiled TClass for %s.",classname.c_str());
4814 // We need to build up the list of required headers, by
4815 // looking at each template arguments.
4818
4819 if (0 == GenerateDictionary(classname.c_str(),includes)) {
4820 // 0 means success.
4821 cl = TClass::LoadClass(classnam.c_str(), silent);
4822 if (cl == 0) {
4823 Error("GenerateTClass","Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4824 }
4825 }
4826#endif
4827 if (cl == nullptr) {
4828 int version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4829 cl = new TClass(classinfo, version, nullptr, nullptr, -1, -1, silent);
4830 }
4831 } else {
4832 // For regular class, just create a TClass on the fly ...
4833 // Not quite useful yet, but that what CINT used to do anyway.
4834 cl = new TClass(classinfo, 1, nullptr, nullptr, -1, -1, silent);
4835 }
4836 // Add the new TClass to the map of declid and TClass*.
4837 if (cl) {
4839 }
4840 return cl;
4841}
4842
4843////////////////////////////////////////////////////////////////////////////////
4844/// Generate the dictionary for the C++ classes listed in the first
4845/// argument (in a semi-colon separated list).
4846/// 'includes' contains a semi-colon separated list of file to
4847/// `#include` in the dictionary.
4848/// For example:
4849/// ~~~ {.cpp}
4850/// gInterpreter->GenerateDictionary("vector<vector<float> >;list<vector<float> >","list;vector");
4851/// ~~~
4852/// or
4853/// ~~~ {.cpp}
4854/// gInterpreter->GenerateDictionary("myclass","myclass.h;myhelper.h");
4855/// ~~~
4856
4857Int_t TCling::GenerateDictionary(const char* classes, const char* includes /* = "" */, const char* /* options = 0 */)
4858{
4859 if (classes == nullptr || classes[0] == 0) {
4860 Error("TCling::GenerateDictionary", "Cannot generate dictionary without passing classes.");
4861 return 0;
4862 }
4863 // Split the input list
4864 std::vector<std::string> listClasses;
4865 for (
4866 const char* current = classes, *prev = classes;
4867 *current != 0;
4868 ++current
4869 ) {
4870 if (*current == ';') {
4871 listClasses.push_back(std::string(prev, current - prev));
4872 prev = current + 1;
4873 }
4874 else if (*(current + 1) == 0) {
4875 listClasses.push_back(std::string(prev, current + 1 - prev));
4876 prev = current + 1;
4877 }
4878 }
4879 std::vector<std::string> listIncludes;
4880 if (!includes)
4881 includes = "";
4882 for (
4883 const char* current = includes, *prev = includes;
4884 *current != 0;
4885 ++current
4886 ) {
4887 if (*current == ';') {
4888 listIncludes.push_back(std::string(prev, current - prev));
4889 prev = current + 1;
4890 }
4891 else if (*(current + 1) == 0) {
4892 listIncludes.push_back(std::string(prev, current + 1 - prev));
4893 prev = current + 1;
4894 }
4895 }
4896 // Generate the temporary dictionary file
4898 std::vector<std::string>(), std::vector<std::string>());
4899}
4900
4901////////////////////////////////////////////////////////////////////////////////
4902/// Return pointer to cling Decl of global/static variable that is located
4903/// at the address given by addr.
4904
4906{
4908 DeclId_t d;
4910
4911 // Could trigger deserialization of decls.
4912 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4913
4914 if (cl) {
4915 d = cl->GetDataMember(name);
4916 // We check if the decl of the data member has an annotation which indicates
4917 // an ioname.
4918 // In case this is true, if the name requested is not the ioname, we
4919 // return 0, as if the member did not exist. In some sense we override
4920 // the information in the TClassInfo instance, isolating the typesystem in
4921 // TClass from the one in the AST.
4922 if (const ValueDecl* decl = (const ValueDecl*) d){
4923 std::string ioName;
4925 if (hasIoName && ioName != name) return nullptr;
4926 }
4927 return d;
4928 }
4929 // We are looking up for something on the TU scope.
4930 // FIXME: We do not want to go through TClingClassInfo(fInterpreter) because of redundant deserializations. That
4931 // interface will actually construct iterators and walk over the decls on the global scope. In would return the first
4932 // occurrence of a decl with the looked up name. However, that's not what C++ lookup would do: if we want to switch
4933 // to a more complete C++ lookup interface we need sift through the found names and pick up the declarations which
4934 // are only fulfilling ROOT's understanding for a Data Member.
4935 // FIXME: We should probably deprecate the TClingClassInfo(fInterpreter) interface and replace it withe something
4936 // similar as below.
4937 using namespace clang;
4938 Sema& SemaR = fInterpreter->getSema();
4939 DeclarationName DName = &SemaR.Context.Idents.get(name);
4940
4941 LookupResult R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4942 RedeclarationKind::ForExternalRedeclaration);
4943
4944 cling::utils::Lookup::Named(&SemaR, R);
4945
4946 LookupResult::Filter F = R.makeFilter();
4947 // Filter the data-member looking decls.
4948 while (F.hasNext()) {
4949 NamedDecl *D = F.next();
4952 continue;
4953 F.erase();
4954 }
4955 F.done();
4956
4957 if (R.isSingleResult())
4958 return R.getFoundDecl();
4959 return nullptr;
4960}
4961
4962////////////////////////////////////////////////////////////////////////////////
4963/// Return pointer to cling Decl of global/static variable that is located
4964/// at the address given by addr.
4965
4967{
4969
4970 const clang::Decl* possibleEnum = nullptr;
4971 // FInd the context of the decl.
4972 if (cl) {
4974 if (cci) {
4975 const clang::DeclContext* dc = nullptr;
4976 if (const clang::Decl* D = cci->GetDecl()) {
4977 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4979 }
4980 }
4981 if (dc) {
4982 // If it is a data member enum.
4983 // Could trigger deserialization of decls.
4984 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4985 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name, dc);
4986 } else {
4987 Error("TCling::GetEnum", "DeclContext not found for %s .\n", name);
4988 }
4989 }
4990 } else {
4991 // If it is a global enum.
4992 // Could trigger deserialization of decls.
4993 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4994 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name);
4995 }
4996 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4998 return possibleEnum;
4999 }
5000 return nullptr;
5001}
5002
5003////////////////////////////////////////////////////////////////////////////////
5004/// Return pointer to cling DeclId for a global value
5005
5006TInterpreter::DeclId_t TCling::GetDeclId( const llvm::GlobalValue *gv ) const
5007{
5008 if (!gv) return nullptr;
5009
5010 llvm::StringRef mangled_name = gv->getName();
5011
5012 int err = 0;
5013 char* demangled_name_c = TClassEdit::DemangleName(mangled_name.str().c_str(), err);
5014 if (err) {
5015 if (err == -2) {
5016 // It might simply be an unmangled global name.
5017 DeclId_t d;
5019 d = gcl.GetDataMember(mangled_name.str().c_str());
5020 return d;
5021 }
5022 return nullptr;
5023 }
5024
5025 std::string scopename(demangled_name_c);
5027
5028 //
5029 // Separate out the class or namespace part of the
5030 // function name.
5031 //
5032 std::string dataname;
5033
5034 if (!strncmp(scopename.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
5035 scopename.erase(0, sizeof("typeinfo for ")-1);
5036 } else if (!strncmp(scopename.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
5037 scopename.erase(0, sizeof("vtable for ")-1);
5038 } else {
5039 // See if it is a function
5040 std::string::size_type pos = scopename.rfind('(');
5041 if (pos != std::string::npos) {
5042 return nullptr;
5043 }
5044 // Separate the scope and member name
5045 pos = scopename.rfind(':');
5046 if (pos != std::string::npos) {
5047 if ((pos != 0) && (scopename[pos-1] == ':')) {
5048 dataname = scopename.substr(pos+1);
5049 scopename.erase(pos-1);
5050 }
5051 } else {
5052 scopename.clear();
5054 }
5055 }
5056 //fprintf(stderr, "name: '%s'\n", name.c_str());
5057 // Now we have the class or namespace name, so do the lookup.
5058
5059
5060 DeclId_t d;
5061 if (scopename.size()) {
5063 d = cl.GetDataMember(dataname.c_str());
5064 }
5065 else {
5067 d = gcl.GetDataMember(dataname.c_str());
5068 }
5069 return d;
5070}
5071
5072////////////////////////////////////////////////////////////////////////////////
5073/// NOT IMPLEMENTED.
5074
5076{
5077 Error("GetDataMemberWithValue()", "not implemented");
5078 return nullptr;
5079}
5080
5081////////////////////////////////////////////////////////////////////////////////
5082/// Return pointer to cling DeclId for a data member with a given name.
5083
5085{
5086 // NOT IMPLEMENTED.
5087 Error("GetDataMemberAtAddr()", "not implemented");
5088 return nullptr;
5089}
5090
5091////////////////////////////////////////////////////////////////////////////////
5092/// Return the cling mangled name for a method of a class with parameters
5093/// params (params is a string of actual arguments, not formal ones). If the
5094/// class is 0 the global function list will be searched.
5095
5097 const char* params, Bool_t objectIsConst /* = kFALSE */)
5098{
5101 if (cl) {
5104 &offset);
5105 }
5106 else {
5109 func.SetFunc(&gcl, method, params, &offset);
5110 }
5112 if (!mi) return "";
5113 TString mangled_name( mi->GetMangledName() );
5114 delete mi;
5115 return mangled_name;
5116}
5117
5118////////////////////////////////////////////////////////////////////////////////
5119/// Return the cling mangled name for a method of a class with a certain
5120/// prototype, i.e. "char*,int,float". If the class is 0 the global function
5121/// list will be searched.
5122
5124 const char* proto, Bool_t objectIsConst /* = kFALSE */,
5125 EFunctionMatchMode mode /* = kConversionMatch */)
5126{
5128 if (cl) {
5129 return ((TClingClassInfo*)cl->GetClassInfo())->
5130 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5131 }
5133 return gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5134}
5135
5136////////////////////////////////////////////////////////////////////////////////
5137/// Return pointer to cling interface function for a method of a class with
5138/// parameters params (params is a string of actual arguments, not formal
5139/// ones). If the class is 0 the global function list will be searched.
5140
5142 const char* params, Bool_t objectIsConst /* = kFALSE */)
5143{
5146 if (cl) {
5149 &offset);
5150 }
5151 else {
5154 func.SetFunc(&gcl, method, params, &offset);
5155 }
5156 return (void*) func.InterfaceMethod();
5157}
5158
5159////////////////////////////////////////////////////////////////////////////////
5160/// Return pointer to cling interface function for a method of a class with
5161/// a certain name.
5162
5164{
5166 DeclId_t f;
5168 if (cl) {
5169 f = cl->GetMethod(method).GetDeclId();
5170 }
5171 else {
5173 f = gcl.GetMethod(method).GetDeclId();
5174 }
5175 return f;
5176
5177}
5178
5179////////////////////////////////////////////////////////////////////////////////
5180/// Insert overloads of name in cl to res.
5181
5183 std::vector<DeclId_t>& res) const
5184{
5185 clang::Sema& S = fInterpreter->getSema();
5186 clang::ASTContext& Ctx = S.Context;
5187 const clang::Decl* CtxDecl
5188 = cl ? (const clang::Decl*)((TClingClassInfo*)cl)->GetDeclId():
5189 Ctx.getTranslationUnitDecl();
5190 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
5191 const clang::DeclContext* DeclCtx = RecDecl;
5192
5193 if (!DeclCtx)
5195 if (!DeclCtx) return;
5196
5197 clang::DeclarationName DName;
5198 // The DeclarationName is funcname, unless it's a ctor or dtor.
5199 // FIXME: or operator or conversion! See enum clang::DeclarationName::NameKind.
5200
5201 if (RecDecl) {
5202 if (RecDecl->getNameAsString() == funcname) {
5203 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5204 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
5205 } else if (funcname[0] == '~' && RecDecl->getNameAsString() == funcname + 1) {
5206 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5207 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
5208 } else {
5209 DName = &Ctx.Idents.get(funcname);
5210 }
5211 } else {
5212 DName = &Ctx.Idents.get(funcname);
5213 }
5214
5215 // NotForRedeclaration: we want to find names in inline namespaces etc.
5216 clang::LookupResult R(S, DName, clang::SourceLocation(), Sema::LookupOrdinaryName,
5217 RedeclarationKind::NotForRedeclaration);
5218 R.suppressDiagnostics(); // else lookup with NotForRedeclaration will check access etc
5219 S.LookupQualifiedName(R, const_cast<DeclContext*>(DeclCtx));
5220 if (R.empty()) return;
5221 R.resolveKind();
5222 res.reserve(res.size() + (R.end() - R.begin()));
5223 for (clang::LookupResult::iterator IR = R.begin(), ER = R.end();
5224 IR != ER; ++IR) {
5225 if (const clang::FunctionDecl* FD
5226 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5227 if (!FD->getDescribedFunctionTemplate()) {
5228 res.push_back(FD);
5229 }
5230 } else if (const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5231 // FIXME: multi-level using
5232 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5233 res.push_back(USD);
5234 }
5235 }
5236 }
5237}
5238
5239////////////////////////////////////////////////////////////////////////////////
5240/// Return pointer to cling interface function for a method of a class with
5241/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5242/// function list will be searched.
5243
5245 const char* proto,
5246 Bool_t objectIsConst /* = kFALSE */,
5247 EFunctionMatchMode mode /* = kConversionMatch */)
5248{
5250 void* f;
5251 if (cl) {
5252 f = ((TClingClassInfo*)cl->GetClassInfo())->
5253 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5254 }
5255 else {
5257 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5258 }
5259 return f;
5260}
5261
5262////////////////////////////////////////////////////////////////////////////////
5263/// Return pointer to cling DeclId for a method of a class with
5264/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5265/// function list will be searched.
5266
5268 const char* params,
5269 Bool_t objectIsConst /* = kFALSE */)
5270{
5272 DeclId_t f;
5274 if (cl) {
5275 f = cl->GetMethodWithArgs(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5276 }
5277 else {
5279 f = gcl.GetMethod(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5280 }
5281 return f;
5282}
5283
5284////////////////////////////////////////////////////////////////////////////////
5285/// Return pointer to cling interface function for a method of a class with
5286/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5287/// function list will be searched.
5288
5290 const char* proto,
5291 Bool_t objectIsConst /* = kFALSE */,
5292 EFunctionMatchMode mode /* = kConversionMatch */)
5293{
5295 DeclId_t f;
5297 if (cl) {
5298 f = cl->GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5299 }
5300 else {
5302 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5303 }
5304 return f;
5305}
5306
5307////////////////////////////////////////////////////////////////////////////////
5308/// Return pointer to cling interface function for a method of a class with
5309/// a certain name.
5310
5312{
5314 DeclId_t f;
5316 if (cl) {
5317 f = cl->GetFunctionTemplate(name);
5318 }
5319 else {
5321 f = gcl.GetFunctionTemplate(name);
5322 }
5323 return f;
5324
5325}
5326
5327////////////////////////////////////////////////////////////////////////////////
5328/// The 'name' is known to the interpreter, this function returns
5329/// the internal version of this name (usually just resolving typedefs)
5330/// This is used in particular to synchronize between the name used
5331/// by rootcling and by the run-time environment (TClass)
5332/// Return 0 if the name is not known.
5333
5334void TCling::GetInterpreterTypeName(const char* name, std::string &output, Bool_t full)
5335{
5336 output.clear();
5337
5339
5341 if (!cl.IsValid()) {
5342 return ;
5343 }
5344 if (full) {
5345 cl.FullName(output,*fNormalizedCtxt);
5346 return;
5347 }
5348 // Well well well, for backward compatibility we need to act a bit too
5349 // much like CINT.
5351 splitname.ShortType(output, TClassEdit::kDropStd );
5352
5353 return;
5354}
5355
5356////////////////////////////////////////////////////////////////////////////////
5357/// Execute a global function with arguments params.
5358///
5359/// FIXME: The cint-based version of this code does not check if the
5360/// SetFunc() call works, and does not do any real checking
5361/// for errors from the Exec() call. It did fetch the most
5362/// recent cint security error and return that in error, but
5363/// this does not really translate well to cling/clang. We
5364/// should enhance these interfaces so that we can report
5365/// compilation and runtime errors properly.
5366
5367void TCling::Execute(const char* function, const char* params, int* error)
5368{
5370 if (error) {
5371 *error = TInterpreter::kNoError;
5372 }
5374 Longptr_t offset = 0L;
5376 func.SetFunc(&cl, function, params, &offset);
5377 func.Exec(nullptr);
5378}
5379
5380////////////////////////////////////////////////////////////////////////////////
5381/// Execute a method from class cl with arguments params.
5382///
5383/// FIXME: The cint-based version of this code does not check if the
5384/// SetFunc() call works, and does not do any real checking
5385/// for errors from the Exec() call. It did fetch the most
5386/// recent cint security error and return that in error, but
5387/// this does not really translate well to cling/clang. We
5388/// should enhance these interfaces so that we can report
5389/// compilation and runtime errors properly.
5390
5391void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5392 const char* params, Bool_t objectIsConst, int* error)
5393{
5395 if (error) {
5396 *error = TInterpreter::kNoError;
5397 }
5398 // If the actual class of this object inherits 2nd (or more) from TObject,
5399 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5400 // hence gInterpreter->Execute will improperly correct the offset.
5401 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5402 Longptr_t offset = 0L;
5405 void* address = (void*)((Longptr_t)addr + offset);
5406 func.Exec(address);
5407}
5408
5409////////////////////////////////////////////////////////////////////////////////
5410
5411void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5412 const char* params, int* error)
5413{
5414 Execute(obj,cl,method,params,false,error);
5415}
5416
5417////////////////////////////////////////////////////////////////////////////////
5418/// Execute a method from class cl with the arguments in array params
5419/// (params[0] ... params[n] = array of TObjString parameters).
5420/// Convert the TObjArray array of TObjString parameters to a character
5421/// string of comma separated parameters.
5422/// The parameters of type 'char' are enclosed in double quotes and all
5423/// internal quotes are escaped.
5424
5426 TObjArray* params, int* error)
5427{
5428 if (!method) {
5429 Error("Execute", "No method was defined");
5430 return;
5431 }
5432 TList* argList = method->GetListOfMethodArgs();
5433 // Check number of actual parameters against of expected formal ones
5434
5435 Int_t nparms = argList->LastIndex() + 1;
5436 Int_t argc = params ? params->GetEntries() : 0;
5437
5438 if (argc > nparms) {
5439 Error("Execute","Too many parameters to call %s, got %d but expected at most %d.",method->GetName(),argc,nparms);
5440 return;
5441 }
5442 if (nparms != argc) {
5443 // Let's see if the 'missing' argument are all defaulted.
5444 // if nparms==0 then either we stopped earlier either argc is also zero and we can't reach here.
5445 assert(nparms > 0);
5446
5447 TMethodArg *arg = (TMethodArg *) argList->At( 0 );
5448 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5449 // There is a default value for the first missing
5450 // argument, so we are fine.
5451 } else {
5452 Int_t firstDefault = -1;
5453 for (Int_t i = 0; i < nparms; i ++) {
5454 arg = (TMethodArg *) argList->At( i );
5455 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5456 firstDefault = i;
5457 break;
5458 }
5459 }
5460 if (firstDefault >= 0) {
5461 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);
5462 } else {
5463 Error("Execute","Too few arguments to call %s, got only %d but expected %d.",method->GetName(),argc,nparms);
5464 }
5465 return;
5466 }
5467 }
5468
5469 const char* listpar = "";
5470 TString complete(10);
5471 if (params) {
5472 // Create a character string of parameters from TObjArray
5473 TIter next(params);
5474 for (Int_t i = 0; i < argc; i ++) {
5475 TMethodArg* arg = (TMethodArg*) argList->At(i);
5477 TObjString* nxtpar = (TObjString*) next();
5478 if (i) {
5479 complete += ',';
5480 }
5481 if (strstr(type.TrueName(*fNormalizedCtxt), "char")) {
5482 TString chpar('\"');
5483 chpar += (nxtpar->String()).ReplaceAll("\"", "\\\"");
5484 // At this point we have to check if string contains \\"
5485 // and apply some more sophisticated parser. Not implemented yet!
5486 complete += chpar;
5487 complete += '\"';
5488 }
5489 else {
5490 complete += nxtpar->String();
5491 }
5492 }
5493 listpar = complete.Data();
5494 }
5495
5496 // And now execute it.
5498 if (error) {
5499 *error = TInterpreter::kNoError;
5500 }
5501 // If the actual class of this object inherits 2nd (or more) from TObject,
5502 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5503 // hence gInterpreter->Execute will improperly correct the offset.
5504 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5507 func.Init(*minfo);
5508 func.SetArgs(listpar);
5509 // Now calculate the 'this' pointer offset for the method
5510 // when starting from the class described by cl.
5511 const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->GetTargetFunctionDecl());
5512 Longptr_t offset = ((TClingClassInfo*)cl->GetClassInfo())->GetOffset(mdecl);
5513 void* address = (void*)((Longptr_t)addr + offset);
5514 func.Exec(address);
5515}
5516
5517////////////////////////////////////////////////////////////////////////////////
5518
5520 const void* args[] /*=0*/,
5521 int nargs /*=0*/,
5522 void* ret/*= 0*/) const
5523{
5524 if (!method) {
5525 Error("ExecuteWithArgsAndReturn", "No method was defined");
5526 return;
5527 }
5528
5530 TClingCallFunc func(*minfo);
5531 func.ExecWithArgsAndReturn(address, args, nargs, ret);
5532}
5533
5534////////////////////////////////////////////////////////////////////////////////
5535/// Execute a cling macro.
5536
5538{
5540 fCurExecutingMacros.push_back(filename);
5542 fCurExecutingMacros.pop_back();
5543 return result;
5544}
5545
5546////////////////////////////////////////////////////////////////////////////////
5547/// Return the file name of the current un-included interpreted file.
5548/// See the documentation for GetCurrentMacroName().
5549
5551{
5552 Warning("GetTopLevelMacroName", "Must change return type!");
5553 return fCurExecutingMacros.empty() ? nullptr : fCurExecutingMacros.back();
5554}
5555
5556////////////////////////////////////////////////////////////////////////////////
5557/// Return the file name of the currently interpreted file,
5558/// included or not. Example to illustrate the difference between
5559/// GetCurrentMacroName() and GetTopLevelMacroName():
5560/// ~~~ {.cpp}
5561/// void inclfile() {
5562/// std::cout << "In inclfile.C" << std::endl;
5563/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5564/// TCling::GetCurrentMacroName() << std::endl;
5565/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5566/// TCling::GetTopLevelMacroName() << std::endl;
5567/// }
5568/// ~~~
5569/// ~~~ {.cpp}
5570/// void mymacro() {
5571/// std::cout << "In mymacro.C" << std::endl;
5572/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5573/// TCling::GetCurrentMacroName() << std::endl;
5574/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5575/// TCling::GetTopLevelMacroName() << std::endl;
5576/// std::cout << " Now calling inclfile..." << std::endl;
5577/// gInterpreter->ProcessLine(".x inclfile.C");
5578/// }
5579/// ~~~
5580/// Running mymacro.C will print:
5581///
5582/// ~~~ {.cpp}
5583/// root [0] .x mymacro.C
5584/// ~~~
5585/// In mymacro.C
5586/// ~~~ {.cpp}
5587/// TCling::GetCurrentMacroName() returns ./mymacro.C
5588/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5589/// ~~~
5590/// Now calling inclfile...
5591/// In inclfile.h
5592/// ~~~ {.cpp}
5593/// TCling::GetCurrentMacroName() returns inclfile.C
5594/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5595/// ~~~
5596
5598{
5599#if defined(R__MUST_REVISIT)
5600#if R__MUST_REVISIT(6,0)
5601 Warning("GetCurrentMacroName", "Must change return type!");
5602#endif
5603#endif
5604 return fCurExecutingMacros.empty() ? nullptr : fCurExecutingMacros.back();
5605}
5606
5607////////////////////////////////////////////////////////////////////////////////
5608/// Return the absolute type of typeDesc.
5609/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
5610/// You need to use the result immediately before it is being overwritten.
5611
5612const char* TCling::TypeName(const char* typeDesc)
5613{
5614 TTHREAD_TLS_DECL(std::string,t);
5615
5616 if (!strstr(typeDesc, "(*)(")) {
5617 const char *s = strchr(typeDesc, ' ');
5618 const char *template_start = strchr(typeDesc, '<');
5619 if (!strcmp(typeDesc, "long long")) {
5620 t = typeDesc;
5621 }
5622 else if (!strncmp(typeDesc, "unsigned ", s + 1 - typeDesc)) {
5623 t = typeDesc;
5624 }
5625 // s is the position of the second 'word' (if any)
5626 // except in the case of templates where there will be a space
5627 // just before any closing '>': eg.
5628 // TObj<std::vector<UShort_t,__malloc_alloc_template<0> > >*
5629 else if (s && (template_start == nullptr || (s < template_start))) {
5630 t = s + 1;
5631 }
5632 else {
5633 t = typeDesc;
5634 }
5635 }
5636 else {
5637 t = typeDesc;
5638 }
5639 auto l = t.length();
5640 while (l > 0 && (t[l - 1] == '*' || t[l - 1] == '&'))
5641 --l;
5642 t.resize(l);
5643 return t.c_str(); // NOLINT
5644}
5645
5646static bool requiresRootMap(const char* rootmapfile)
5647{
5649
5650 llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5651 libName.consume_back(".rootmap");
5652
5653 return !gInterpreter->HasPCMForLibrary(libName.str().c_str());
5654}
5655
5656////////////////////////////////////////////////////////////////////////////////
5657/// Read and parse a rootmapfile in its new format, and return 0 in case of
5658/// success, -1 if the file has already been read, and -3 in case its format
5659/// is the old one (e.g. containing "Library.ClassName"), -4 in case of syntax
5660/// error.
5661
5663{
5664 if (!(rootmapfile && *rootmapfile))
5665 return 0;
5666
5668 return 0; // success
5669
5670 // For "class ", "namespace ", "typedef ", "header ", "enum ", "var " respectively
5671 const std::map<char, unsigned int> keyLenMap = {{'c',6},{'n',10},{'t',8},{'h',7},{'e',5},{'v',4}};
5672
5674#ifdef _MSC_VER
5675 std::replace(rootmapfileNoBackslash.begin(), rootmapfileNoBackslash.end(), '\\', '/');
5676#endif
5677 // Add content of a specific rootmap file
5679 return -1;
5680
5681 // Line 1 is `{ decls }`
5682 std::string lineDirective = std::string("\n#line 2 \"Forward declarations from ") + rootmapfileNoBackslash + "\"\n";
5683
5684 std::ifstream file(rootmapfileNoBackslash);
5685 std::string line;
5686 line.reserve(200);
5687 std::string lib_name;
5688 line.reserve(100);
5689 bool newFormat = false;
5690 while (getline(file, line, '\n')) {
5691 if (!newFormat && (line.compare(0, 8, "Library.") == 0 || line.compare(0, 8, "Declare.") == 0)) {
5692 file.close();
5693 return -3; // old format
5694 }
5695 newFormat = true;
5696
5697 if (line.compare(0, 9, "{ decls }") == 0) {
5698 // forward declarations
5699
5700 while (getline(file, line, '\n')) {
5701 if (line[0] == '[')
5702 break;
5703 if (!uniqueString) {
5704 Error("ReadRootmapFile", "Cannot handle \"{ decls }\" sections in custom rootmap file %s",
5705 rootmapfileNoBackslash.c_str());
5706 return -4;
5707 }
5708 if (!lineDirective.empty())
5709 uniqueString->Append(lineDirective);
5710 uniqueString->Append(line + '\n');
5711 }
5712 }
5713 const char firstChar = line[0];
5714 if (firstChar == '[') {
5715 // new section (library)
5716 auto brpos = line.find(']');
5717 if (brpos == string::npos)
5718 continue;
5719 lib_name = line.substr(1, brpos - 1);
5720 // Remove spaces at the beginning and at the end of the library name
5721 lib_name.erase(lib_name.find_last_not_of(' ') + 1);
5722 lib_name.erase(0, lib_name.find_first_not_of(' '));
5723 if (gDebug > 3) {
5724 TString lib_nameTstr(lib_name.c_str());
5725 TObjArray *tokens = lib_nameTstr.Tokenize(" ");
5726 const char *lib = ((TObjString *)tokens->At(0))->GetName();
5727 const char *wlib = gSystem->DynamicPathName(lib, kTRUE);
5728 if (wlib) {
5729 Info("ReadRootmapFile", "%s: New section for %s", rootmapfile, lib_nameTstr.Data());
5730 } else {
5731 Info("ReadRootmapFile", "%s: Section for %s (library does not exist)", rootmapfile, lib_nameTstr.Data());
5732 }
5733 delete[] wlib;
5734 delete tokens;
5735 }
5736 } else {
5737 auto keyLenIt = keyLenMap.find(firstChar);
5738 if (keyLenIt == keyLenMap.end())
5739 continue;
5740 unsigned int keyLen = keyLenIt->second;
5741 // Do not make a copy, just start after the key
5742 const char *keyname = line.c_str() + keyLen;
5743 if (gDebug > 6)
5744 Info("ReadRootmapFile", "%s: class %s in %s", rootmapfile, keyname, lib_name.c_str());
5746 if (isThere) {
5747 if (lib_name != isThere->GetValue()) { // the same key for two different libs
5748 if (firstChar == 'n') {
5749 if (gDebug > 3)
5750 Info("ReadRootmapFile",
5751 "While processing %s, namespace %s was found to be associated to %s although it is already "
5752 "associated to %s",
5753 rootmapfile, keyname, lib_name.c_str(), isThere->GetValue());
5754 } else if (firstChar == 'h') { // it is a header: add the libname to the list of libs to be loaded.
5755 lib_name += " ";
5756 lib_name += isThere->GetValue();
5757 fMapfile->SetValue(keyname, lib_name.c_str());
5758 } else if (!TClassEdit::IsSTLCont(keyname)) {
5759 Warning("ReadRootmapFile",
5760 "While processing %s, %s %s was found to be associated to %s although it is already "
5761 "associated to %s",
5762 rootmapfile, line.substr(0, keyLen - 1).c_str(), keyname, lib_name.c_str(),
5763 isThere->GetValue());
5764 }
5765 } else { // the same key for the same lib
5766 if (gDebug > 3)
5767 Info("ReadRootmapFile", "While processing %s, key %s was found to be already defined for %s",
5768 rootmapfile, keyname, lib_name.c_str());
5769 }
5770 } else {
5771 fMapfile->SetValue(keyname, lib_name.c_str());
5772 }
5773 }
5774 }
5775 file.close();
5776 return 0;
5777}
5778
5779////////////////////////////////////////////////////////////////////////////////
5780/// Create a resource table and read the (possibly) three resource files,
5781/// i.e. `$ROOTSYS/etc/system<name>` (or `ROOTETCDIR/system<name>`), `$HOME/<name>`
5782/// and `$PWD/<name>`. ROOT always reads ".rootrc" (in TROOT::InitSystem()). You
5783/// can read additional user defined resource files by creating additional TEnv
5784/// objects. By setting the shell variable ROOTENV_NO_HOME=1 the reading of
5785/// the `$HOME/<name>` resource file will be skipped. This might be useful in
5786/// case the home directory resides on an automounted remote file system
5787/// and one wants to avoid the file system from being mounted.
5788
5790{
5791 assert(requiresRootMap(name) && "We have a module!");
5792
5793 if (!requiresRootMap(name))
5794 return;
5795
5797
5799
5800 TString sname = "system";
5801 sname += name;
5804
5806 if (ret == -3) // old format
5808 if (!gSystem->Getenv("ROOTENV_NO_HOME")) {
5812 if (ret == -3) // old format
5816 if (ret == -3) // old format
5818 }
5819 } else {
5821 if (ret == -3) // old format
5823 }
5825}
5826
5827
5828namespace {
5829 using namespace clang;
5830
5831 class ExtVisibleStorageAdder: public RecursiveASTVisitor<ExtVisibleStorageAdder>{
5832 // This class is to be considered an helper for AutoLoading.
5833 // It is a recursive visitor is used to inspect namespaces and specializations
5834 // coming from forward declarations in rootmaps and to set the external visible
5835 // storage flag for them.
5836 public:
5837 ExtVisibleStorageAdder(std::unordered_set<const NamespaceDecl*>& nsSet): fNSSet(nsSet) {};
5838 bool VisitNamespaceDecl(NamespaceDecl* nsDecl) {
5839 // We want to enable the external lookup for this namespace
5840 // because it may shadow the lookup of other names contained
5841 // in that namespace
5842
5843 nsDecl->setHasExternalVisibleStorage();
5844 fNSSet.insert(nsDecl);
5845 return true;
5846 }
5848 // We want to enable the external lookup for this specialization
5849 // because we can provide a definition for it!
5850 if (specDecl->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
5851 //SpecSet.insert(specDecl);
5852 specDecl->setHasExternalLexicalStorage();
5853
5854 // No need to recurse. On the contrary, recursing is actively harmful:
5855 // NOTE: must not recurse to prevent this visitor from triggering loading from
5856 // the external AST source (i.e. autoloading). This would be triggered right here,
5857 // before autoloading is even set up, as rootmap file parsing happens before that.
5858 // Even if autoloading is off and has no effect, triggering loading from external
5859 // AST source resets the flag setHasExternalLexicalStorage(), hiding this specialization
5860 // from subsequent autoloads!
5861 return false;
5862 }
5863 private:
5864 std::unordered_set<const NamespaceDecl*>& fNSSet;
5865 };
5866}
5867
5868////////////////////////////////////////////////////////////////////////////////
5869/// Load map between class and library. If rootmapfile is specified a
5870/// specific rootmap file can be added (typically used by ACLiC).
5871/// In case of error -1 is returned, 0 otherwise.
5872/// The interpreter uses this information to automatically load the shared
5873/// library for a class (autoload mechanism), see the AutoLoad() methods below.
5874
5876{
5878 return 0;
5879
5881
5882 // open the [system].rootmap files
5883 if (!fMapfile) {
5884 fMapfile = new TEnv();
5888 InitRootmapFile(".rootmap");
5889 }
5890
5891 // Prepare a list of all forward declarations for cling
5892 // For some experiments it is easily as big as 500k characters. To be on the
5893 // safe side, we go for 1M.
5894 TUniqueString uniqueString(1048576);
5895
5896 // Load all rootmap files in the dynamic load path ((DY)LD_LIBRARY_PATH, etc.).
5897 // A rootmap file must end with the string ".rootmap".
5899 if (ldpath != fRootmapLoadPath) {
5901#ifdef WIN32
5902 TObjArray* paths = ldpath.Tokenize(";");
5903#else
5904 TObjArray* paths = ldpath.Tokenize(":");
5905#endif
5906 TString d;
5907 for (Int_t i = 0; i < paths->GetEntriesFast(); i++) {
5908 d = ((TObjString *)paths->At(i))->GetString();
5909 // check if directory already scanned
5910 Int_t skip = 0;
5911 for (Int_t j = 0; j < i; j++) {
5912 TString pd = ((TObjString *)paths->At(j))->GetString();
5913 if (pd == d) {
5914 skip++;
5915 break;
5916 }
5917 }
5918 if (!skip) {
5919 void* dirp = gSystem->OpenDirectory(d);
5920 if (dirp) {
5921 if (gDebug > 3) {
5922 Info("LoadLibraryMap", "%s", d.Data());
5923 }
5924 const char* f1;
5925 while ((f1 = gSystem->GetDirEntry(dirp))) {
5926 TString f = f1;
5927 if (f.EndsWith(".rootmap")) {
5928 TString p;
5929 p = d + "/" + f;
5931 if (!fRootmapFiles->FindObject(f) && f != ".rootmap") {
5932 if (gDebug > 4) {
5933 Info("LoadLibraryMap", " rootmap file: %s", p.Data());
5934 }
5936
5937 if (ret == 0)
5938 fRootmapFiles->Add(new TNamed(gSystem->BaseName(f), p.Data()));
5939 if (ret == -3) {
5940 // old format
5942 fRootmapFiles->Add(new TNamed(f, p));
5943 }
5944 }
5945 // else {
5946 // fprintf(stderr,"Reject %s because %s is already there\n",p.Data(),f.Data());
5947 // fRootmapFiles->FindObject(f)->ls();
5948 // }
5949 }
5950 }
5951 if (f.BeginsWith("rootmap")) {
5952 TString p;
5953 p = d + "/" + f;
5954 FileStat_t stat;
5955 if (gSystem->GetPathInfo(p, stat) == 0 && R_ISREG(stat.fMode)) {
5956 Warning("LoadLibraryMap", "please rename %s to end with \".rootmap\"", p.Data());
5957 }
5958 }
5959 }
5960 }
5962 }
5963 }
5964 delete paths;
5965 if (fMapfile->GetTable() && !fMapfile->GetTable()->GetEntries()) {
5966 return -1;
5967 }
5968 }
5969 if (rootmapfile && *rootmapfile) {
5971 if (res == 0) {
5972 //TString p = gSystem->ConcatFileName(gSystem->pwd(), rootmapfile);
5973 //fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), p.Data()));
5975 }
5976 else if (res == -3) {
5977 // old format
5982 }
5983 }
5984 TEnvRec* rec;
5985 TIter next(fMapfile->GetTable());
5986 while ((rec = (TEnvRec*) next())) {
5987 TString cls = rec->GetName();
5988 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
5989 // get the first lib from the list of lib and dependent libs
5990 TString libs = rec->GetValue();
5991 if (libs == "") {
5992 continue;
5993 }
5994 TString delim(" ");
5995 TObjArray* tokens = libs.Tokenize(delim);
5996 const char* lib = ((TObjString*)tokens->At(0))->GetName();
5997 // convert "@@" to "::", we used "@@" because TEnv
5998 // considers "::" a terminator
5999 cls.Remove(0, 8);
6000 cls.ReplaceAll("@@", "::");
6001 // convert "-" to " ", since class names may have
6002 // blanks and TEnv considers a blank a terminator
6003 cls.ReplaceAll("-", " ");
6004 if (gDebug > 6) {
6005 const char* wlib = gSystem->DynamicPathName(lib, kTRUE);
6006 if (wlib) {
6007 Info("LoadLibraryMap", "class %s in %s", cls.Data(), wlib);
6008 }
6009 else {
6010 Info("LoadLibraryMap", "class %s in %s (library does not exist)", cls.Data(), lib);
6011 }
6012 delete[] wlib;
6013 }
6014 delete tokens;
6015 }
6016 else if (!strncmp(cls.Data(), "Declare.", 8) && cls.Length() > 8) {
6017 cls.Remove(0, 8);
6018 // convert "-" to " ", since class names may have
6019 // blanks and TEnv considers a blank a terminator
6020 cls.ReplaceAll("-", " ");
6021 fInterpreter->declare(cls.Data());
6022 }
6023 }
6024
6025 // Process the forward declarations collected
6026 cling::Transaction* T = nullptr;
6027 auto compRes= fInterpreter->declare(uniqueString.Data(), &T);
6028 assert(cling::Interpreter::kSuccess == compRes && "A declaration in a rootmap could not be compiled");
6029
6030 if (compRes!=cling::Interpreter::kSuccess){
6031 Warning("LoadLibraryMap",
6032 "Problems in %s declaring '%s' were encountered.", rootmapfile, uniqueString.Data()) ;
6033 }
6034
6035 if (T) {
6036 ExtVisibleStorageAdder evsAdder(fNSFromRootmaps);
6037 for (auto declIt = T->decls_begin(); declIt < T->decls_end(); ++declIt) {
6038 if (declIt->m_DGR.isSingleDecl()) {
6039 if (Decl* D = declIt->m_DGR.getSingleDecl()) {
6040 if (clang::isa<TagDecl>(D) || clang::isa<NamespaceDecl>(D)) {
6041 evsAdder.TraverseDecl(D);
6042 }
6043 }
6044 }
6045 }
6046 }
6047
6048 // clear duplicates
6049
6050 return 0;
6051}
6052
6053////////////////////////////////////////////////////////////////////////////////
6054/// Scan again along the dynamic path for library maps. Entries for the loaded
6055/// shared libraries are unloaded first. This can be useful after reseting
6056/// the dynamic path through TSystem::SetDynamicPath()
6057/// In case of error -1 is returned, 0 otherwise.
6058
6065
6066////////////////////////////////////////////////////////////////////////////////
6067/// Reload the library map entries coming from all the loaded shared libraries,
6068/// after first unloading the current ones.
6069/// In case of error -1 is returned, 0 otherwise.
6070
6072{
6074 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6075 const Int_t nrSharedLibs = sharedLibL->GetEntriesFast();
6076 for (Int_t ilib = 0; ilib < nrSharedLibs; ilib++) {
6077 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6080 if (ret < 0) {
6081 continue;
6082 }
6084 if (sharedLibBaseStr.EndsWith(".dll")) {
6085 rootMapBaseStr.ReplaceAll(".dll", "");
6086 }
6087 else if (sharedLibBaseStr.EndsWith(".DLL")) {
6088 rootMapBaseStr.ReplaceAll(".DLL", "");
6089 }
6090 else if (sharedLibBaseStr.EndsWith(".so")) {
6091 rootMapBaseStr.ReplaceAll(".so", "");
6092 }
6093 else if (sharedLibBaseStr.EndsWith(".sl")) {
6094 rootMapBaseStr.ReplaceAll(".sl", "");
6095 }
6096 else if (sharedLibBaseStr.EndsWith(".dl")) {
6097 rootMapBaseStr.ReplaceAll(".dl", "");
6098 }
6099 else if (sharedLibBaseStr.EndsWith(".a")) {
6100 rootMapBaseStr.ReplaceAll(".a", "");
6101 }
6102 else {
6103 Error("ReloadAllSharedLibraryMaps", "Unknown library type %s", sharedLibBaseStr.Data());
6104 delete sharedLibL;
6105 return -1;
6106 }
6107 rootMapBaseStr += ".rootmap";
6109 if (!rootMap) {
6110 Error("ReloadAllSharedLibraryMaps", "Could not find rootmap %s in path", rootMapBaseStr.Data());
6111 delete[] rootMap;
6112 delete sharedLibL;
6113 return -1;
6114 }
6115 const Int_t status = LoadLibraryMap(rootMap);
6116 if (status < 0) {
6117 Error("ReloadAllSharedLibraryMaps", "Error loading map %s", rootMap);
6118 delete[] rootMap;
6119 delete sharedLibL;
6120 return -1;
6121 }
6122 delete[] rootMap;
6123 }
6124 delete sharedLibL;
6125 return 0;
6126}
6127
6128////////////////////////////////////////////////////////////////////////////////
6129/// Unload the library map entries coming from all the loaded shared libraries.
6130/// Returns 0 if succesful
6131
6133{
6135 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6136 for (Int_t ilib = 0; ilib < sharedLibL->GetEntriesFast(); ilib++) {
6137 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6140 }
6141 delete sharedLibL;
6142 return 0;
6143}
6144
6145////////////////////////////////////////////////////////////////////////////////
6146/// Unload library map entries coming from the specified library.
6147/// Returns -1 in case no entries for the specified library were found,
6148/// 0 otherwise.
6149
6151{
6152 if (!fMapfile || !library || !*library) {
6153 return 0;
6154 }
6156 Ssiz_t idx = libname.Last('.');
6157 if (idx != kNPOS) {
6158 libname.Remove(idx);
6159 }
6160 size_t len = libname.Length();
6161 TEnvRec *rec;
6162 TIter next(fMapfile->GetTable());
6164 Int_t ret = 0;
6165 while ((rec = (TEnvRec *) next())) {
6166 TString cls = rec->GetName();
6167 if (cls.Length() > 2) {
6168 // get the first lib from the list of lib and dependent libs
6169 TString libs = rec->GetValue();
6170 if (libs == "") {
6171 continue;
6172 }
6173 TString delim(" ");
6174 TObjArray* tokens = libs.Tokenize(delim);
6175 const char* lib = ((TObjString *)tokens->At(0))->GetName();
6176 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
6177 // convert "@@" to "::", we used "@@" because TEnv
6178 // considers "::" a terminator
6179 cls.Remove(0, 8);
6180 cls.ReplaceAll("@@", "::");
6181 // convert "-" to " ", since class names may have
6182 // blanks and TEnv considers a blank a terminator
6183 cls.ReplaceAll("-", " ");
6184 }
6185 if (!strncmp(lib, libname.Data(), len)) {
6186 if (fMapfile->GetTable()->Remove(rec) == nullptr) {
6187 Error("UnloadLibraryMap", "entry for <%s, %s> not found in library map table", cls.Data(), lib);
6188 ret = -1;
6189 }
6190 }
6191 delete tokens;
6192 }
6193 }
6194 if (ret >= 0) {
6196 if (!library_rootmap.EndsWith(".rootmap"))
6197 library_rootmap.Append(".rootmap");
6198 TNamed* mfile = nullptr;
6201 delete mfile;
6202 }
6204 }
6205 return ret;
6206}
6207
6208////////////////////////////////////////////////////////////////////////////////
6209/// Register the AutoLoading information for a class.
6210/// libs is a space separated list of libraries.
6211
6212Int_t TCling::SetClassSharedLibs(const char *cls, const char *libs)
6213{
6214 if (!cls || !*cls)
6215 return 0;
6216
6217 TString key = TString("Library.") + cls;
6218 // convert "::" to "@@", we used "@@" because TEnv
6219 // considers "::" a terminator
6220 key.ReplaceAll("::", "@@");
6221 // convert "-" to " ", since class names may have
6222 // blanks and TEnv considers a blank a terminator
6223 key.ReplaceAll(" ", "-");
6224
6226 if (!fMapfile) {
6227 fMapfile = new TEnv();
6229
6232
6233 InitRootmapFile(".rootmap");
6234 }
6235 //fMapfile->SetValue(key, libs);
6237 return 1;
6238}
6239
6240////////////////////////////////////////////////////////////////////////////////
6241/// Demangle the name (from the typeinfo) and then request the class
6242/// via the usual name based interface (TClass::GetClass).
6243
6244TClass *TCling::GetClass(const std::type_info& typeinfo, Bool_t load) const
6245{
6246 int err = 0;
6248 if (err) return nullptr;
6251 return theClass;
6252}
6253
6254////////////////////////////////////////////////////////////////////////////////
6255/// Load library containing the specified class. Returns 0 in case of error
6256/// and 1 in case if success.
6257
6258Int_t TCling::AutoLoad(const std::type_info& typeinfo, Bool_t knowDictNotLoaded /* = kFALSE */)
6259{
6260 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6261
6262 int err = 0;
6264 if (err) {
6265 return 0;
6266 }
6267
6268 std::string demangled_name(demangled_name_c);
6270
6271 // AutoLoad expects (because TClass::GetClass already prepares it that way) a
6272 // shortened name.
6275
6276 // No need to worry about typedef, they aren't any ... but there are
6277 // inlined namespaces ...
6278
6280 if (result == 0) {
6283 }
6284
6285 return result;
6286}
6287
6288////////////////////////////////////////////////////////////////////////////////
6289// Get the list of 'published'/'known' library for the class and load them.
6291{
6292 Int_t status = 0;
6293
6294 // lookup class to find list of dependent libraries
6296 if (!deplibs.IsNull()) {
6297 TString delim(" ");
6298 TObjArray* tokens = deplibs.Tokenize(delim);
6299 for (Int_t i = (tokens->GetEntriesFast() - 1); i > 0; --i) {
6300 const char* deplib = ((TObjString*)tokens->At(i))->GetName();
6301 if (gROOT->LoadClass(cls, deplib) == 0) {
6302 if (gDebug > 0) {
6303 gCling->Info("TCling::AutoLoad",
6304 "loaded dependent library %s for %s", deplib, cls);
6305 }
6306 }
6307 else {
6308 gCling->Error("TCling::AutoLoad",
6309 "failure loading dependent library %s for %s",
6310 deplib, cls);
6311 }
6312 }
6313 const char* lib = ((TObjString*)tokens->At(0))->GetName();
6314 if (lib && lib[0]) {
6315 if (gROOT->LoadClass(cls, lib) == 0) {
6316 if (gDebug > 0) {
6317 gCling->Info("TCling::AutoLoad",
6318 "loaded library %s for %s", lib, cls);
6319 }
6320 status = 1;
6321 }
6322 else {
6323 gCling->Error("TCling::AutoLoad",
6324 "failure loading library %s for %s", lib, cls);
6325 }
6326 }
6327 delete tokens;
6328 }
6329
6330 return status;
6331}
6332
6333////////////////////////////////////////////////////////////////////////////////
6334// Iterate through the data member of the class (either through the TProtoClass
6335// or through Cling) and trigger, recursively, the loading the necessary libraries.
6336// \note `cls` is expected to be already normalized!
6337// \returns 1 on success.
6338Int_t TCling::DeepAutoLoadImpl(const char *cls, std::unordered_set<std::string> &visited,
6339 bool nameIsNormalized)
6340{
6341 // Try to insert; if insertion failed because the entry existed, DeepAutoLoadImpl()
6342 // has previously (within the same call to `AutoLoad()`) tried to load this class
6343 // and we are done, whether success or not, as it won't work better now than before,
6344 // because there is no additional information now compared to before.
6345 if (!visited.insert(std::string(cls)).second)
6346 return 1;
6347
6348 if (ShallowAutoLoadImpl(cls) == 0) {
6349 // If ShallowAutoLoadImpl() has an error, we have an error.
6350 return 0;
6351 }
6352
6353 // Now look through the TProtoClass to load the required library/dictionary
6355 for (auto element : proto->GetData()) {
6356 if (element->IsBasic())
6357 continue;
6358 const char *subtypename = element->GetTypeName();
6360 // Failure to load a dictionary is not (quite) a failure load
6361 // the top-level library. If we return false here, then
6362 // we would end up in a situation where the library and thus
6363 // the dictionary is loaded for "cls" but the TClass is
6364 // not created and/or marked as unavailable (in case where
6365 // AutoLoad is called from TClass::GetClass).
6366 DeepAutoLoadImpl(subtypename, visited, true /*normalized*/);
6367 }
6368 }
6369 return 1;
6370 }
6371
6372 // We found no TProtoClass for cls.
6373 auto classinfo = gInterpreter->ClassInfo_Factory(cls);
6374 if (classinfo && gInterpreter->ClassInfo_IsValid(classinfo)
6375 && !(gInterpreter->ClassInfo_Property(classinfo) & kIsEnum))
6376 {
6378 while (gInterpreter->DataMemberInfo_Next(memberinfo)) {
6379 if (gInterpreter->DataMemberInfo_TypeProperty(memberinfo) & ::kIsFundamental)
6380 continue;
6381 auto membertypename = TClassEdit::GetLong64_Name(gInterpreter->TypeName(gInterpreter->DataMemberInfo_TypeTrueName(memberinfo)));
6383 // Failure to load a dictionary is not (quite) a failure load
6384 // the top-level library. See detailed comment in the TProtoClass
6385 // branch (above).
6386 (void)DeepAutoLoadImpl(membertypename.c_str(), visited, true /*normalized*/);
6387 }
6388 }
6389 gInterpreter->DataMemberInfo_Delete(memberinfo);
6390 }
6391 gInterpreter->ClassInfo_Delete(classinfo);
6392 return 1;
6393}
6394
6395////////////////////////////////////////////////////////////////////////////////
6396/// Load library containing the specified class. Returns 0 in case of error
6397/// and 1 in case if success.
6398
6400{
6401 // Prevent update to IsClassAutoloading between our check and our actions.
6403
6404 // TClass::GetClass explicitly calls gInterpreter->AutoLoad. When called from
6405 // rootcling (in *_rdict.pcm file generation) it is a no op.
6406 // FIXME: We should avoid calling autoload when we know we are not supposed
6407 // to and transform this check into an assert.
6409 // Never load any library from rootcling/genreflex.
6410 if (gDebug > 2) {
6411 Info("TCling::AutoLoad", "Explicitly disabled (the class name is %s)", cls);
6412 }
6413 return 0;
6414 }
6415
6416 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6417
6419
6421 // The library is already loaded as the class's dictionary is known.
6422 // Return success.
6423 // Note: the name (cls) is expected to be normalized as it comes either
6424 // from a callbacks (that can/should calculate the normalized name from the
6425 // decl) or from TClass::GetClass (which does also calculate the normalized
6426 // name).
6427 return 1;
6428 }
6429
6430 if (gDebug > 2) {
6431 Info("TCling::AutoLoad",
6432 "Trying to autoload for %s", cls);
6433 }
6434
6435 if (!gROOT || !gInterpreter || gROOT->TestBit(TObject::kInvalidObject)) {
6436 if (gDebug > 2) {
6437 Info("TCling::AutoLoad",
6438 "Disabled due to gROOT or gInterpreter being invalid/not ready (the class name is %s)", cls);
6439 }
6440 return 0;
6441 }
6442 // Prevent the recursion when the library dictionary are loaded.
6444 // Try using externally provided callback first.
6445 if (fAutoLoadCallBack) {
6447 if (success)
6448 return success;
6449 }
6450
6451 // During the 'Deep' part of the search we will call GetClassSharedLibsForModule
6452 // (when module are enabled) which might end up calling AutoParsing but
6453 // that should only be for the cases where the library has no generated pcm
6454 // and in that case a rootmap should be available.
6455 // This avoids a very costly operation (for generally no gain) but reduce the
6456 // quality of the search (i.e. bad in case of library with no pcm and no rootmap
6457 // file).
6459 std::unordered_set<std::string> visited;
6460 return DeepAutoLoadImpl(cls, visited, false /*normalized*/);
6461}
6462
6463////////////////////////////////////////////////////////////////////////////////
6464/// Parse the payload or header.
6465
6466static cling::Interpreter::CompilationResult ExecAutoParse(const char *what,
6467 Bool_t header,
6468 cling::Interpreter *interpreter)
6469{
6470 std::string code = gNonInterpreterClassDef ;
6471 if (!header) {
6472 // This is the complete header file content and not the
6473 // name of a header.
6474 code += what;
6475
6476 } else {
6477 code += ("#include \"");
6478 code += what;
6479 code += "\"\n";
6480 }
6481 code += ("#ifdef __ROOTCLING__\n"
6482 "#undef __ROOTCLING__\n"
6484 "#endif");
6485
6486 cling::Interpreter::CompilationResult cr;
6487 {
6488 // scope within which diagnostics are de-activated
6489 // For now we disable diagnostics because we saw them already at
6490 // dictionary generation time. That won't be an issue with the PCMs.
6491
6492 Sema &SemaR = interpreter->getSema();
6494 clangDiagSuppr diagSuppr(SemaR.getDiagnostics());
6495
6496 #if defined(R__MUST_REVISIT)
6497 #if R__MUST_REVISIT(6,2)
6498 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
6499 #endif
6500 #endif
6501
6502 cr = interpreter->parseForModule(code);
6503 }
6504 return cr;
6505}
6506
6507////////////////////////////////////////////////////////////////////////////////
6508/// Helper routine for TCling::AutoParse implementing the actual call to the
6509/// parser and looping over template parameters (if
6510/// any) and when they don't have a registered header to autoparse,
6511/// recurse over their template parameters.
6512///
6513/// Returns the number of header parsed.
6514
6516{
6517 // We assume the lock has already been taken.
6518 // R__LOCKGUARD(gInterpreterMutex);
6519
6521 unsigned long offset = 0;
6522 if (strncmp(cls, "const ", 6) == 0) {
6523 offset = 6;
6524 }
6525
6526 // Loop on the possible autoparse keys
6527 bool skipFirstEntry = false;
6528 std::vector<std::string> autoparseKeys;
6529 if (strchr(cls, '<')) {
6530 int nestedLoc = 0;
6532 // Check if we can skip the name of the template in the autoparses
6533 // Take all the scopes one by one. If all of them are in the AST, we do not
6534 // need to autoparse for that particular template.
6535 if (!autoparseKeys.empty() && !autoparseKeys[0].empty()) {
6536 // autoparseKeys[0] is empty when the input is not a template instance.
6537 // The case strchr(cls, '<') != 0 but still not a template instance can
6538 // happens 'just' for string (GetSplit replaces the template by the short name
6539 // and then use that for thew splitting)
6541 auto tokens = templateName.Tokenize("::");
6542 clang::NamedDecl* previousScopeAsNamedDecl = nullptr;
6543 clang::DeclContext* previousScopeAsContext = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
6545 previousScopeAsContext = fInterpreter->getSema().getStdNamespace();
6546 auto nTokens = tokens->GetEntriesFast();
6547 for (Int_t tk = 0; tk < nTokens; ++tk) {
6548 auto scopeObj = tokens->UncheckedAt(tk);
6549 auto scopeName = ((TObjString*) scopeObj)->String().Data();
6550 previousScopeAsNamedDecl = cling::utils::Lookup::Named(&fInterpreter->getSema(), scopeName, previousScopeAsContext);
6551 // Check if we have multiple nodes in the AST with this name
6552 if ((clang::NamedDecl*)-1 == previousScopeAsNamedDecl) break;
6553 previousScopeAsContext = llvm::dyn_cast_or_null<clang::DeclContext>(previousScopeAsNamedDecl);
6554 if (!previousScopeAsContext) break; // this is not a context
6555 }
6556 delete tokens;
6557 // Now, let's check if the last scope, the template, has a definition, i.e. it's not a fwd decl
6558 if ((clang::NamedDecl*)-1 != previousScopeAsNamedDecl) {
6559 if (auto templateDecl = llvm::dyn_cast_or_null<clang::ClassTemplateDecl>(previousScopeAsNamedDecl)) {
6560 if (auto templatedDecl = templateDecl->getTemplatedDecl()) {
6561 skipFirstEntry = templatedDecl->hasDefinition();
6562 }
6563 }
6564 }
6565
6566 }
6567 }
6568 if (topLevel) autoparseKeys.emplace_back(cls);
6569
6570 for (const auto & apKeyStr : autoparseKeys) {
6571 if (skipFirstEntry) {
6572 skipFirstEntry=false;
6573 continue;
6574 }
6575 if (apKeyStr.empty()) continue;
6576 const char *apKey = apKeyStr.c_str();
6578 // If the class was not looked up
6579 if (gDebug > 1) {
6580 Info("TCling::AutoParse",
6581 "Starting autoparse for %s\n", apKey);
6582 }
6583 if (fLookedUpClasses.insert(normNameHash).second) {
6584 auto const &iter = fClassesHeadersMap.find(normNameHash);
6585 if (iter != fClassesHeadersMap.end()) {
6586 const cling::Transaction *T = fInterpreter->getCurrentTransaction();
6588 auto const &hNamesPtrs = iter->second;
6589 if (gDebug > 1) {
6590 Info("TCling::AutoParse",
6591 "We can proceed for %s. We have %s headers.", apKey, std::to_string(hNamesPtrs.size()).c_str());
6592 }
6593 for (auto & hName : hNamesPtrs) {
6594 if (fParsedPayloadsAddresses.count(hName) == 1) continue;
6595 if (0 != fPayloads.count(normNameHash)) {
6596 float initRSSval=0.f, initVSIZEval=0.f;
6597 (void) initRSSval; // Avoid unused var warning
6598 (void) initVSIZEval;
6599 if (gDebug > 0) {
6600 Info("AutoParse",
6601 "Parsing full payload for %s", apKey);
6604 initRSSval = 1e-3*info.fMemResident;
6605 initVSIZEval = 1e-3*info.fMemVirtual;
6606 }
6608 if (cRes != cling::Interpreter::kSuccess) {
6609 if (hName[0] == '\n')
6610 Error("AutoParse", "Error parsing payload code for class %s with content:\n%s", apKey, hName);
6611 } else {
6614 if (gDebug > 0){
6617 float endRSSval = 1e-3*info.fMemResident;
6618 float endVSIZEval = 1e-3*info.fMemVirtual;
6619 Info("Autoparse", ">>> RSS key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initRSSval, endRSSval, endRSSval-initRSSval);
6620 Info("Autoparse", ">>> VSIZE key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initVSIZEval, endVSIZEval, endVSIZEval-initVSIZEval);
6621 }
6622 }
6623 } else if (!IsLoaded(hName)) {
6624 if (gDebug > 0) {
6625 Info("AutoParse",
6626 "Parsing single header %s", hName);
6627 }
6629 if (cRes != cling::Interpreter::kSuccess) {
6630 Error("AutoParse", "Error parsing headerfile %s for class %s.", hName, apKey);
6631 } else {
6633 }
6634 }
6635 }
6636 }
6637 else {
6638 // There is no header registered for this class, if this a
6639 // template, it will be instantiated if/when it is requested
6640 // and if we do no load/parse its components we might end up
6641 // not using an eventual specialization.
6642 if (strchr(apKey, '<')) {
6644 }
6645 }
6646 }
6647 }
6648
6649 if (nHheadersParsed) {
6650 // Register that we did autoparsing for this class.
6651 fAutoParseClasses.insert(cls);
6652 if (gDebug)
6653 Info("AutoParse", "Parsed %d headers for %s", nHheadersParsed, cls);
6654 }
6655 return nHheadersParsed;
6656
6657}
6658
6659////////////////////////////////////////////////////////////////////////////////
6660/// Parse the headers relative to the class
6661/// Returns 1 in case of success, 0 in case of failure
6662
6664{
6665 if (llvm::StringRef(cls).contains("(lambda)"))
6666 return 0;
6667
6670 return AutoLoad(cls);
6671 } else {
6672 return 0;
6673 }
6674 }
6675
6677
6678 if (gDebug > 1) {
6679 Info("TCling::AutoParse",
6680 "Trying to autoparse for %s", cls);
6681 }
6682
6683 // The catalogue of headers is in the dictionary
6685 && !gClassTable->GetDictNorm(cls)) {
6686 // Need RAII against recursive (dictionary payload) parsing (ROOT-8445).
6688 fInterpreter->getSema());
6689 AutoLoad(cls, true /*knowDictNotLoaded*/);
6690 }
6691
6692 // Prevent the recursion when the library dictionary are loaded.
6694
6695 // No recursive header parsing on demand; we require headers to be standalone.
6697
6698 Int_t nHheadersParsed = AutoParseImplRecurse(cls,/*topLevel=*/ true);
6699
6701
6702 return nHheadersParsed > 0 ? 1 : 0;
6703}
6704
6705// This is a function which gets callback from cling when DynamicLibraryManager->loadLibrary failed for some reason.
6706// Try to solve the problem by AutoLoading. Return true when AutoLoading success, return
6707// false if not.
6708bool TCling::LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
6709{
6711 if (errMsg.contains("undefined symbol: ")) {
6712 // This branch is taken when the callback was from DynamicLibraryManager::loadLibrary
6713 std::string mangled_name = std::string(errMsg.split("undefined symbol: ").second);
6714 void* res = ((TCling*)gCling)->LazyFunctionCreatorAutoload(mangled_name);
6715 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
6716 if (res && DLM && (DLM->loadLibrary(libStem, permanent, resolved) == cling::DynamicLibraryManager::kLoadLibSuccess))
6717 // Return success when LazyFunctionCreatorAutoload could find mangled_name
6718 return true;
6719 } else {
6720 // The callback is from IncrementalExecutor::diagnoseUnresolvedSymbols
6722 return true;
6723 }
6724
6725 return false;
6726}
6727
6728////////////////////////////////////////////////////////////////////////////////
6729/// Autoload a library based on a missing symbol.
6730
6733
6734 // We have already loaded the library.
6735 if (void* Addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name))
6736 return Addr;
6737
6738 const cling::DynamicLibraryManager &DLM = *GetInterpreterImpl()->getDynamicLibraryManager();
6740
6741 auto LibLoader = [](const std::string& LibName) -> bool {
6742 if (gSystem->Load(LibName.c_str(), "", false) < 0) {
6743 ::Error("TCling__LazyFunctionCreatorAutoloadForModule",
6744 "Failed to load library %s", LibName.c_str());
6745 return false;
6746 }
6747 return true; //success.
6748 };
6749
6750 std::string libName = DLM.searchLibrariesForSymbol(mangled_name,
6751 /*searchSystem=*/ true);
6752
6753 assert(!llvm::StringRef(libName).starts_with("libNew") && "We must not resolve symbols from libNew!");
6754
6755 if (libName.empty())
6756 return nullptr;
6757
6758 if (!LibLoader(libName))
6759 return nullptr;
6760
6762 return llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name);
6763}
6764
6765////////////////////////////////////////////////////////////////////////////////
6766
6768{
6769 return fNSFromRootmaps.count(nsDecl) != 0;
6770}
6771
6772////////////////////////////////////////////////////////////////////////////////
6773/// Internal function. Actually do the update of the ClassInfo when seeing
6774// new TagDecl or NamespaceDecl.
6775void TCling::RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
6776{
6777
6779 if (cci) {
6780 // If we only had a forward declaration then update the
6781 // TClingClassInfo with the definition if we have it now.
6782 const NamedDecl *oldDef = llvm::dyn_cast_or_null<NamedDecl>(cci->GetDecl());
6783 if (!oldDef || (def && def != oldDef)) {
6784 cl->ResetCaches();
6785 TClass::RemoveClassDeclId(cci->GetDeclId());
6786 if (def) {
6787 if (cci->GetType()) {
6788 // It's a tag decl, not a namespace decl.
6789 cci->Init(*cci->GetType());
6790 TClass::AddClassToDeclIdMap(cci->GetDeclId(), cl);
6791 } else {
6792 Error("RefreshClassInfo", "Should not need to update the classInfo a non type decl: %s", oldDef->getNameAsString().c_str());
6793 }
6794 }
6795 }
6796 } else if (!cl->TestBit(TClass::kLoading) && !cl->fHasRootPcmInfo) {
6797 cl->ResetCaches();
6798 if (strncmp(cl->GetName(),"tuple<",strlen("tuple<"))==0) {
6799 // We need to use the Emulated Tuple but we should not trigger parsing
6800 // yet, so delay the creation of the ClassInfo
6801 delete ((TClingClassInfo *)cl->fClassInfo);
6802 cl->fClassInfo = nullptr;
6803 cl->fCanLoadClassInfo = true;
6805 if (cl->fState != TClass::kHasTClassInit) {
6807 }
6808 return;
6809 }
6810 // yes, this is almost a waste of time, but we do need to lookup
6811 // the 'type' corresponding to the TClass anyway in order to
6812 // preserve the opaque typedefs (Double32_t)
6813 if (!alias && def != nullptr)
6815 else
6817 if (((TClingClassInfo *)cl->fClassInfo)->IsValid()) {
6818 // We now need to update the state and bits.
6819 if (cl->fState != TClass::kHasTClassInit) {
6820 // if (!cl->fClassInfo->IsValid()) cl->fState = TClass::kForwardDeclared; else
6822 }
6823 TClass::AddClassToDeclIdMap(((TClingClassInfo *)(cl->fClassInfo))->GetDeclId(), cl);
6824 } else {
6825 delete ((TClingClassInfo *)cl->fClassInfo);
6826 cl->fClassInfo = nullptr;
6827 }
6828 }
6829}
6830
6831////////////////////////////////////////////////////////////////////////////////
6832/// Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
6834{
6835 const TagDecl *td = dyn_cast<TagDecl>(ND);
6837 const NamedDecl *canon = nullptr;
6838
6839 std::string name;
6840 TagDecl* tdDef = nullptr;
6841 if (td) {
6842 canon = tdDef = td->getDefinition();
6843 // Let's pass the decl to the TClass only if it has a definition.
6844 if (!tdDef) return;
6845
6846 if (!tdDef->isCompleteDefinition() || llvm::isa<clang::FunctionDecl>(tdDef->getDeclContext())) {
6847 // Ignore incomplete definition.
6848 // Ignore declaration within a function.
6849 return;
6850 }
6851
6852 auto declName = tdDef->getNameAsString();
6853 // Check if we have registered the unqualified name into the list
6854 // of TClass that are in kNoInfo, kEmulated or kFwdDeclaredState.
6855 // Since this is used as heureutistic to avoid spurrious calls to GetNormalizedName
6856 // the unqualified name is sufficient (and the fully qualified name might be
6857 // 'wrong' if there is difference in spelling in the template paramters (for example)
6859 // 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() );
6860 return;
6861 }
6862
6863 clang::QualType type(tdDef->getTypeForDecl(), 0);
6865 } else if (ns) {
6866 canon = ns->getCanonicalDecl();
6867 name = ND->getQualifiedNameAsString();
6868 } else {
6869 name = ND->getQualifiedNameAsString();
6870 }
6871
6872 // Supposedly we are being called while something is being
6873 // loaded ... let's now tell the autoloader to do the work
6874 // yet another time.
6876 // FIXME: There can be more than one TClass for a single decl.
6877 // for example vector<double> and vector<Double32_t>
6878 TClass* cl = (TClass*)gROOT->GetListOfClasses()->FindObject(name.c_str());
6879 if (cl && GetModTClasses().find(cl) == GetModTClasses().end()) {
6880 RefreshClassInfo(cl, canon, false);
6881 }
6882 // And here we should find the other 'aliases' (eg. vector<Double32_t>)
6883 // and update them too:
6884 // foreach(aliascl in gROOT->GetListOfClasses()->FindAliasesOf(name.c_str()))
6885 // RefreshClassInfo(cl, tdDef, true);
6886}
6887
6888////////////////////////////////////////////////////////////////////////////////
6889/// No op: see TClingCallbacks
6890
6894
6895//______________________________________________________________________________
6896//FIXME: Factor out that function in TClass, because TClass does it already twice
6898{
6899 // This is a no-op as part of the API.
6900 // TCling uses UpdateClassInfoWithDecl() instead.
6901}
6902
6903////////////////////////////////////////////////////////////////////////////////
6904/// Update all canvases at end the terminal input command.
6905
6907{
6908 TIter next(gROOT->GetListOfCanvases());
6909 TVirtualPad* canvas;
6910 while ((canvas = (TVirtualPad*)next())) {
6911 canvas->Update();
6912 }
6913}
6914
6915////////////////////////////////////////////////////////////////////////////////
6916
6917void TCling::UpdateListsOnCommitted(const cling::Transaction &T) {
6918 std::set<TClass*> modifiedTClasses; // TClasses that require update after this transaction
6919
6920 // If the transaction does not contain anything we can return earlier.
6921 if (!HandleNewTransaction(T)) return;
6922
6923 bool isTUTransaction = false;
6924 if (!T.empty() && T.decls_begin() + 1 == T.decls_end() && !T.hasNestedTransactions()) {
6925 clang::Decl* FirstDecl = *(T.decls_begin()->m_DGR.begin());
6926 if (llvm::isa<clang::TranslationUnitDecl>(FirstDecl)) {
6927 // The is the first transaction, we have to expose to meta
6928 // what's already in the AST.
6929 isTUTransaction = true;
6930 }
6931 }
6932
6933 std::set<const void*> TransactionDeclSet;
6934 if (!isTUTransaction && T.decls_end() - T.decls_begin()) {
6935 const clang::Decl* WrapperFD = T.getWrapperFD();
6936 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6937 I != E; ++I) {
6938 if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl
6939 && I->m_Call != cling::Transaction::kCCIHandleTagDeclDefinition)
6940 continue;
6941
6942 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6943 DE = I->m_DGR.end(); DI != DE; ++DI) {
6944 if (*DI == WrapperFD)
6945 continue;
6946 TransactionDeclSet.insert(*DI);
6947 ((TCling*)gCling)->HandleNewDecl(*DI, false, modifiedTClasses);
6948 }
6949 }
6950 }
6951
6952 // The above might trigger more decls to be deserialized.
6953 // Thus the iteration over the deserialized decls must be last.
6954 for (cling::Transaction::const_iterator I = T.deserialized_decls_begin(),
6955 E = T.deserialized_decls_end(); I != E; ++I) {
6956 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6957 DE = I->m_DGR.end(); DI != DE; ++DI)
6958 if (TransactionDeclSet.find(*DI) == TransactionDeclSet.end()) {
6959 //FIXME: HandleNewDecl should take DeclGroupRef
6960 ((TCling*)gCling)->HandleNewDecl(*DI, /*isDeserialized*/true,
6962 }
6963 }
6964
6965
6966 // When fully building the reflection info in TClass, a deserialization
6967 // could be triggered, which may result in request for building the
6968 // reflection info for the same TClass. This in turn will clear the caches
6969 // for the TClass in-flight and cause null ptr derefs.
6970 // FIXME: This is a quick fix, solving most of the issues. The actual
6971 // question is: Shouldn't TClass provide a lock mechanism on update or lock
6972 // itself until the update is done.
6973 //
6974 std::vector<TClass*> modifiedTClassesDiff(modifiedTClasses.size());
6975 std::vector<TClass*>::iterator it;
6977 ((TCling*)gCling)->GetModTClasses().begin(),
6978 ((TCling*)gCling)->GetModTClasses().end(),
6981
6982 // Lock the TClass for updates
6983 ((TCling*)gCling)->GetModTClasses().insert(modifiedTClassesDiff.begin(),
6985 for (std::vector<TClass*>::const_iterator I = modifiedTClassesDiff.begin(),
6986 E = modifiedTClassesDiff.end(); I != E; ++I) {
6987 // Make sure the TClass has not been deleted.
6988 if (!gROOT->GetListOfClasses()->FindObject(*I)) {
6989 continue;
6990 }
6991 // Could trigger deserialization of decls.
6992 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
6993 // Unlock the TClass for updates
6994 ((TCling*)gCling)->GetModTClasses().erase(*I);
6995
6996 }
6997}
6998
6999///\brief Invalidate stored TCling state for declarations included in transaction `T'.
7000///
7001void TCling::UpdateListsOnUnloaded(const cling::Transaction &T)
7002{
7004
7005 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
7006 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
7007 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
7008 (TListOfEnums *)gROOT->GetListOfEnums());
7009
7010 cling::Transaction::const_nested_iterator iNested = T.nested_begin();
7011 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
7012 I != E; ++I) {
7013 if (I->m_Call == cling::Transaction::kCCIHandleVTable)
7014 continue;
7015 if (I->m_Call == cling::Transaction::kCCINone) {
7017 ++iNested;
7018 continue;
7019 }
7020
7021 for (auto &D : I->m_DGR)
7023 }
7024}
7025
7026///\brief Invalidate cached TCling information for the given global declaration.
7027///
7029 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
7030 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
7031 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
7032 (TListOfEnums *)gROOT->GetListOfEnums());
7034}
7035
7036///\brief Invalidate cached TCling information for the given declaration, and
7037/// removed it from the appropriate object list.
7038///\param[in] Lists - std::tuple<TListOfDataMembers&, TListOfFunctions&,
7039/// TListOfFunctionTemplates&, TListOfEnums&>
7040/// of pointers to the (global/class) object lists.
7041///\param[in] D - Decl to discard.
7042///
7046 TListOfEnums*> &Lists, const Decl *D) {
7047 if (D->isFromASTFile()) // `D' came from the PCH; ignore
7048 return;
7049
7050 TListOfDataMembers &LODM = *(std::get<0>(Lists));
7051 TListOfFunctions &LOF = *(std::get<1>(Lists));
7052 TListOfFunctionTemplates &LOFT = *(std::get<2>(Lists));
7053 TListOfEnums &LOE = *(std::get<3>(Lists));
7054
7056 TObject *O = LODM.Find((TDictionary::DeclId_t)D);
7057 if (LODM.GetClass())
7058 RemoveAndInvalidateObject(LODM, static_cast<TDataMember *>(O));
7059 else
7060 RemoveAndInvalidateObject(LODM, static_cast<TGlobal *>(O));
7061 } else if (isa<FunctionDecl>(D)) {
7063 } else if (isa<FunctionTemplateDecl>(D)) {
7065 } else if (isa<EnumDecl>(D)) {
7066 TEnum *E = LOE.Find((TDictionary::DeclId_t)D);
7067 if (!E)
7068 return;
7069
7070 // Try to invalidate enumerators (for unscoped enumerations).
7071 for (TIter I = E->GetConstants(); auto EC = (TEnumConstant *)I(); )
7073 (TEnumConstant *)LODM.FindObject(EC->GetName()));
7074
7076 } else if (isa<RecordDecl>(D) || isa<NamespaceDecl>(D)) {
7078 return;
7079
7080 std::vector<TClass *> Classes;
7081 if (!TClass::GetClass(D->getCanonicalDecl(), Classes))
7082 return;
7083 for (auto &C : Classes) {
7084 auto Lists = std::make_tuple((TListOfDataMembers *)C->GetListOfDataMembers(),
7085 (TListOfFunctions *)C->GetListOfMethods(),
7086 (TListOfFunctionTemplates *)C->GetListOfFunctionTemplates(),
7087 (TListOfEnums *)C->GetListOfEnums());
7088 for (auto &I : cast<DeclContext>(D)->decls())
7090
7091 // For NamespaceDecl (redeclarable), only invalidate this redecl.
7092 if (D->getKind() != Decl::Namespace || cast<NamespaceDecl>(D)->isFirstDecl())
7093 C->ResetClassInfo();
7094 }
7095 }
7096}
7097
7098////////////////////////////////////////////////////////////////////////////////
7099// If an autoparse was done during a transaction and that it is rolled back,
7100// we need to make sure the next request for the same autoparse will be
7101// honored.
7102void TCling::TransactionRollback(const cling::Transaction &T) {
7103 auto const &triter = fTransactionHeadersMap.find(&T);
7104 if (triter != fTransactionHeadersMap.end()) {
7105 std::size_t normNameHash = triter->second;
7106
7108
7109 auto const &iter = fClassesHeadersMap.find(normNameHash);
7110 if (iter != fClassesHeadersMap.end()) {
7111 auto const &hNamesPtrs = iter->second;
7112 for (auto &hName : hNamesPtrs) {
7113 if (gDebug > 0) {
7114 Info("TransactionRollback",
7115 "Restoring ability to autoaparse: %s", hName);
7116 }
7118 }
7119 }
7120 }
7121}
7122
7123////////////////////////////////////////////////////////////////////////////////
7124
7125void TCling::LibraryLoaded(const void* dyLibHandle, const char* canonicalName) {
7126// R__LOCKGUARD_CLING(gInterpreterMutex);
7127// UpdateListOfLoadedSharedLibraries();
7128}
7129
7130////////////////////////////////////////////////////////////////////////////////
7131
7132void TCling::LibraryUnloaded(const void* dyLibHandle, const char* canonicalName) {
7133 fPrevLoadedDynLibInfo = nullptr;
7134 fSharedLibs = "";
7135}
7136
7137////////////////////////////////////////////////////////////////////////////////
7138/// Return the list of shared libraries loaded into the process.
7139
7146
7147static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH, bool skipCore)
7148{
7149 if (!cls || !*cls)
7150 return {};
7151
7152 using namespace clang;
7153 if (const Decl *D = LH.findScope(cls, cling::LookupHelper::NoDiagnostics,
7154 /*type*/ nullptr, /*instantiate*/ false)) {
7155 if (!D->isFromASTFile()) {
7156 if (gDebug > 5)
7157 Warning("GetClassSharedLibsForModule", "Decl found for %s is not part of a module", cls);
7158 return {};
7159 }
7160 class ModuleCollector : public ConstDeclVisitor<ModuleCollector> {
7161 llvm::DenseSet<Module *> &m_TopLevelModules;
7162
7163 public:
7164 ModuleCollector(llvm::DenseSet<Module *> &TopLevelModules) : m_TopLevelModules(TopLevelModules) {}
7165 void Collect(const Decl *D) { Visit(D); }
7166
7167 void VisitDecl(const Decl *D)
7168 {
7169 // FIXME: Such case is described ROOT-7765 where
7170 // ROOT_GENERATE_DICTIONARY does not contain the list of headers.
7171 // They are specified as #includes in the LinkDef file. This leads to
7172 // generation of incomplete modulemap files and this logic fails to
7173 // compute the corresponding module of D.
7174 // FIXME: If we want to support such a case, we should not rely on
7175 // the contents of the modulemap but mangle D and look it up in the
7176 // .so files.
7177 if (!D->hasOwningModule())
7178 return;
7179 if (Module *M = D->getOwningModule()->getTopLevelModule())
7180 m_TopLevelModules.insert(M);
7181 }
7182
7184 {
7185 switch (TA.getKind()) {
7186 case TemplateArgument::Null:
7187 case TemplateArgument::Integral:
7188 case TemplateArgument::Pack:
7189 case TemplateArgument::NullPtr:
7190 case TemplateArgument::StructuralValue:
7191 case TemplateArgument::Expression:
7192 case TemplateArgument::Template:
7193 case TemplateArgument::TemplateExpansion: return;
7194 case TemplateArgument::Type:
7195 if (const TagType *TagTy = dyn_cast<TagType>(TA.getAsType()))
7196 return Visit(TagTy->getDecl());
7197 return;
7198 case TemplateArgument::Declaration: return Visit(TA.getAsDecl());
7199 }
7200 llvm_unreachable("Invalid TemplateArgument::Kind!");
7201 }
7202
7204 {
7205 if (CTSD->getOwningModule())
7206 VisitDecl(CTSD);
7207 else
7208 VisitDecl(CTSD->getSpecializedTemplate());
7209 const TemplateArgumentList &ArgList = CTSD->getTemplateArgs();
7210 for (const TemplateArgument *Arg = ArgList.data(), *ArgEnd = Arg + ArgList.size(); Arg != ArgEnd; ++Arg) {
7212 }
7213 }
7214 };
7215
7216 llvm::DenseSet<Module *> TopLevelModules;
7218 m.Collect(D);
7219 std::string result;
7220 for (auto M : TopLevelModules) {
7221 // ROOT-unaware modules (i.e. not processed by rootcling) do not have a
7222 // link declaration.
7223 if (!M->LinkLibraries.size())
7224 continue;
7225 // We have preloaded the Core module thus libCore.so
7226 if (M->Name == "Core" && skipCore)
7227 continue;
7228 assert(M->LinkLibraries.size() == 1);
7229 if (!result.empty())
7230 result += ' ';
7231 result += M->LinkLibraries[0].Library;
7232 }
7233 return result;
7234 }
7235 return {};
7236}
7237
7238////////////////////////////////////////////////////////////////////////////////
7239/// Get the list of shared libraries containing the code for class cls.
7240/// The first library in the list is the one containing the class, the
7241/// others are the libraries the first one depends on. Returns 0
7242/// in case the library is not found.
7243/// \param cls the name of the class
7244/// \param skipCore if true (default), remove "Core" from the returned list
7245
7246const char* TCling::GetClassSharedLibs(const char* cls, bool skipCore)
7247{
7248 if (fCxxModulesEnabled) {
7249 // Lock the interpreter mutex before interacting with cling.
7250 // TODO: Can we move this further deep? In principle the lock should be in
7251 // GetClassSharedLibsForModule, but it might be needed also for
7252 // getLookupHelper?
7254 llvm::StringRef className = cls;
7255 // If we get a class name containing lambda, we cannot parse it and we
7256 // can exit early.
7257 // FIXME: This works around a bug when we are instantiating a template
7258 // make_unique and the substitution fails. Seen in most of the dataframe
7259 // tests.
7260 if (className.contains("(lambda)"))
7261 return nullptr;
7262 // Limit the recursion which can be induced by GetClassSharedLibsForModule.
7264 cling::LookupHelper &LH = fInterpreter->getLookupHelper();
7266 if (!libs.empty()) {
7267 fAutoLoadLibStorage.push_back(libs);
7268 return fAutoLoadLibStorage.back().c_str();
7269 }
7270 }
7271
7272 if (!cls || !*cls) {
7273 return nullptr;
7274 }
7275 // lookup class to find list of libraries
7276 if (fMapfile) {
7277 TEnvRec* libs_record = nullptr;
7279 if (libs_record) {
7280 const char* libs = libs_record->GetValue();
7281 return (*libs) ? libs : nullptr;
7282 }
7283 else {
7284 // Try the old format...
7285 TString c = TString("Library.") + cls;
7286 // convert "::" to "@@", we used "@@" because TEnv
7287 // considers "::" a terminator
7288 c.ReplaceAll("::", "@@");
7289 // convert "-" to " ", since class names may have
7290 // blanks and TEnv considers a blank a terminator
7291 c.ReplaceAll(" ", "-");
7292 // Use TEnv::Lookup here as the rootmap file must start with Library.
7293 // and do not support using any stars (so we do not need to waste time
7294 // with the search made by TEnv::GetValue).
7295 TEnvRec* libs_record = nullptr;
7297 if (libs_record) {
7298 const char* libs = libs_record->GetValue();
7299 return (*libs) ? libs : nullptr;
7300 }
7301 }
7302 }
7303 return nullptr;
7304}
7305
7306/// This interface returns a list of dependent libraries in the form:
7307/// lib libA.so libB.so libC.so. The first library is the library we are
7308/// searching dependencies for.
7309/// Note: In order to speed up the search, we display the dependencies of the
7310/// libraries which are not yet loaded. For instance, if libB.so was already
7311/// loaded the list would contain: lib libA.so libC.so.
7312static std::string GetSharedLibImmediateDepsSlow(std::string lib,
7313 cling::Interpreter *interp,
7314 bool skipLoadedLibs = true)
7315{
7316 TString LibFullPath(lib);
7317 if (!llvm::sys::path::is_absolute(lib)) {
7318 if (!gSystem->FindDynamicLibrary(LibFullPath, /*quiet=*/true)) {
7319 Error("TCling__GetSharedLibImmediateDepsSlow", "Cannot find library '%s'", lib.c_str());
7320 return "";
7321 }
7322 } else {
7323 assert(llvm::sys::fs::exists(lib) && "Must exist!");
7324 lib = llvm::sys::path::filename(lib).str();
7325 }
7326
7327 auto ObjF = llvm::object::ObjectFile::createObjectFile(LibFullPath.Data());
7328 if (!ObjF) {
7329 Warning("TCling__GetSharedLibImmediateDepsSlow", "Failed to read object file %s", lib.c_str());
7330 return "";
7331 }
7332
7333 llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary();
7334
7335 std::set<string> DedupSet;
7336 std::string Result = lib + ' ';
7337 for (const auto &S : BinObjFile->symbols()) {
7338 uint32_t Flags = llvm::cantFail(S.getFlags());
7339 // Skip defined symbols: we have them.
7340 if (!(Flags & llvm::object::SymbolRef::SF_Undefined))
7341 continue;
7342 // Skip undefined weak symbols: if we don't have them we won't need them.
7343 // `__gmon_start__` being a typical example.
7344 if (Flags & llvm::object::SymbolRef::SF_Weak)
7345 continue;
7346 llvm::Expected<StringRef> SymNameErr = S.getName();
7347 if (!SymNameErr) {
7348 Warning("GetSharedLibDepsForModule", "Failed to read symbol");
7349 continue;
7350 }
7351 llvm::StringRef SymName = SymNameErr.get();
7352 if (SymName.empty())
7353 continue;
7354
7355 if (BinObjFile->isELF()) {
7356 // Skip the symbols which are part of the C/C++ runtime and have a
7357 // fixed library version. See binutils ld VERSION. Those reside in
7358 // 'system' libraries, which we avoid in FindLibraryForSymbol.
7359 if (SymName.contains("@GLIBCXX") || SymName.contains("@CXXABI") ||
7360 SymName.contains("@GLIBC") || SymName.contains("@GCC"))
7361 continue;
7362
7363 // Those are 'weak undefined' symbols produced by gcc. We can
7364 // ignore them.
7365 // FIXME: It is unclear whether we can ignore all weak undefined
7366 // symbols:
7367 // http://lists.llvm.org/pipermail/llvm-dev/2017-October/118177.html
7368 static constexpr llvm::StringRef RegisterClasses("_Jv_RegisterClasses");
7369 static constexpr llvm::StringRef RegisterCloneTable("_ITM_registerTMCloneTable");
7370 static constexpr llvm::StringRef DeregisterCloneTable("_ITM_deregisterTMCloneTable");
7371 if (SymName == RegisterClasses ||
7374 continue;
7375 }
7376
7377 // If we can find the address of the symbol, we have loaded it. Skip.
7378 if (skipLoadedLibs) {
7380 if (llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(SymNameForDlsym))
7381 continue;
7382 }
7383
7385 std::string found = interp->getDynamicLibraryManager()->searchLibrariesForSymbol(SymName, /*searchSystem*/false);
7386 // The expected output is just filename without the full path, which
7387 // is not very accurate, because our Dyld implementation might find
7388 // a match in location a/b/c.so and if we return just c.so ROOT might
7389 // resolve it to y/z/c.so and there we might not be ABI compatible.
7390 // FIXME: Teach the users of GetSharedLibDeps to work with full paths.
7391 if (!found.empty()) {
7392 std::string cand = llvm::sys::path::filename(found).str();
7393 if (!DedupSet.insert(cand).second)
7394 continue;
7395
7396 Result += cand + ' ';
7397 }
7398 }
7399
7400 return Result;
7401}
7402
7403static bool hasParsedRootmapForLibrary(llvm::StringRef lib)
7404{
7405 // Check if we have parsed a rootmap file.
7406 llvm::SmallString<256> rootmapName;
7407 if (!lib.starts_with("lib"))
7408 rootmapName.append("lib");
7409
7410 rootmapName.append(llvm::sys::path::filename(lib));
7411 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7412
7413 if (gCling->GetRootMapFiles()->FindObject(rootmapName.c_str()))
7414 return true;
7415
7416 // Perform a last resort by dropping the lib prefix.
7417 llvm::StringRef rootmapNameNoLib = rootmapName.str();
7418 if (rootmapNameNoLib.consume_front("lib"))
7419 return gCling->GetRootMapFiles()->FindObject(rootmapNameNoLib.data());
7420
7421 return false;
7422}
7423
7424static bool hasPrecomputedLibraryDeps(llvm::StringRef lib)
7425{
7426 if (gCling->HasPCMForLibrary(lib.data()))
7427 return true;
7428
7429 return hasParsedRootmapForLibrary(lib);
7430}
7431
7432////////////////////////////////////////////////////////////////////////////////
7433/// Get the list a libraries on which the specified lib depends. The
7434/// returned string contains as first element the lib itself.
7435/// Returns 0 in case the lib does not exist or does not have
7436/// any dependencies. If useDyld is true, we iterate through all available
7437/// libraries and try to construct the dependency chain by resolving each
7438/// symbol.
7439
7440const char* TCling::GetSharedLibDeps(const char* lib, bool useDyld/* = false*/)
7441{
7442 if (llvm::sys::path::is_absolute(lib) && !llvm::sys::fs::exists(lib))
7443 return nullptr;
7444
7445 if (!hasParsedRootmapForLibrary(lib)) {
7446 llvm::SmallString<512> rootmapName(lib);
7447 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7448 if (llvm::sys::fs::exists(rootmapName)) {
7449 if (gDebug > 0)
7450 Info("Load", "loading %s", rootmapName.c_str());
7451 gInterpreter->LoadLibraryMap(rootmapName.c_str());
7452 }
7453 }
7454
7455 if (hasPrecomputedLibraryDeps(lib) && useDyld) {
7456 if (gDebug > 0)
7457 Warning("TCling::GetSharedLibDeps", "Precomputed dependencies available but scanning '%s'", lib);
7458 }
7459
7460 if (useDyld) {
7462 if (!libs.empty()) {
7463 fAutoLoadLibStorage.push_back(libs);
7464 return fAutoLoadLibStorage.back().c_str();
7465 }
7466 }
7467
7468 if (!fMapfile || !lib || !lib[0]) {
7469 return nullptr;
7470 }
7471 TString libname(lib);
7472 Ssiz_t idx = libname.Last('.');
7473 if (idx != kNPOS) {
7474 libname.Remove(idx);
7475 }
7476 TEnvRec* rec;
7477 TIter next(fMapfile->GetTable());
7478 size_t len = libname.Length();
7479 while ((rec = (TEnvRec*) next())) {
7480 const char* libs = rec->GetValue();
7481 if (!strncmp(libs, libname.Data(), len) && strlen(libs) >= len
7482 && (!libs[len] || libs[len] == ' ' || libs[len] == '.')) {
7483 return libs;
7484 }
7485 }
7486 return nullptr;
7487}
7488
7489////////////////////////////////////////////////////////////////////////////////
7490/// If error messages are disabled, the interpreter should suppress its
7491/// failures and warning messages from stdout.
7492
7494{
7495#if defined(R__MUST_REVISIT)
7496#if R__MUST_REVISIT(6,2)
7497 Warning("IsErrorMessagesEnabled", "Interface not available yet.");
7498#endif
7499#endif
7500 return kTRUE;
7501}
7502
7503////////////////////////////////////////////////////////////////////////////////
7504/// If error messages are disabled, the interpreter should suppress its
7505/// failures and warning messages from stdout. Return the previous state.
7506
7508{
7509#if defined(R__MUST_REVISIT)
7510#if R__MUST_REVISIT(6,2)
7511 Warning("SetErrorMessages", "Interface not available yet.");
7512#endif
7513#endif
7515}
7516
7517////////////////////////////////////////////////////////////////////////////////
7518/// Refresh the list of include paths known to the interpreter and return it
7519/// with -I prepended.
7520
7522{
7524
7525 fIncludePath = "";
7526
7527 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7528 //false - no system header, true - with flags.
7529 fInterpreter->GetIncludePaths(includePaths, false, true);
7530 if (const size_t nPaths = includePaths.size()) {
7531 assert(!(nPaths & 1) && "GetIncludePath, number of paths and options is not equal");
7532
7533 for (size_t i = 0; i < nPaths; i += 2) {
7534 if (i)
7535 fIncludePath.Append(' ');
7536 fIncludePath.Append(includePaths[i].c_str());
7537
7538 if (includePaths[i] != "-I")
7539 fIncludePath.Append(' ');
7540 fIncludePath.Append('"');
7542 fIncludePath.Append('"');
7543 }
7544 }
7545
7546 return fIncludePath;
7547}
7548
7549////////////////////////////////////////////////////////////////////////////////
7550/// Return the directory containing CINT's stl cintdlls.
7551
7552const char* TCling::GetSTLIncludePath() const
7553{
7554 return "";
7555}
7556
7557//______________________________________________________________________________
7558// M I S C
7559//______________________________________________________________________________
7560
7561int TCling::DisplayClass(FILE* /*fout*/, const char* /*name*/, int /*base*/, int /*start*/) const
7562{
7563 // Interface to cling function
7564 return 0;
7565}
7566
7567////////////////////////////////////////////////////////////////////////////////
7568/// Interface to cling function
7569
7571{
7572 assert(fout != nullptr && "DisplayIncludePath, 'fout' parameter is null");
7573
7574 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7575 //false - no system header, true - with flags.
7576 fInterpreter->GetIncludePaths(includePaths, false, true);
7577 if (const size_t nPaths = includePaths.size()) {
7578 assert(!(nPaths & 1) && "DisplayIncludePath, number of paths and options is not equal");
7579
7580 std::string allIncludes("include path:");
7581 for (size_t i = 0; i < nPaths; i += 2) {
7582 allIncludes += ' ';
7584
7585 if (includePaths[i] != "-I")
7586 allIncludes += ' ';
7587 allIncludes += includePaths[i + 1];
7588 }
7589
7590 fprintf(fout, "%s\n", allIncludes.c_str());
7591 }
7592
7593 return 0;
7594}
7595
7596////////////////////////////////////////////////////////////////////////////////
7597/// Interface to cling function
7598
7599void* TCling::FindSym(const char* entry) const
7600{
7602 return fInterpreter->getAddressOfGlobal(entry);
7603}
7604
7605////////////////////////////////////////////////////////////////////////////////
7606/// Let the interpreter issue a generic error, and set its error state.
7607
7608void TCling::GenericError(const char* error) const
7609{
7610#if defined(R__MUST_REVISIT)
7611#if R__MUST_REVISIT(6,2)
7612 Warning("GenericError","Interface not available yet.");
7613#endif
7614#endif
7615}
7616
7617////////////////////////////////////////////////////////////////////////////////
7618/// This routines used to return the address of the internal wrapper
7619/// function (of the interpreter) that was used to call *all* the
7620/// interpreted functions that were bytecode compiled (no longer
7621/// interpreted line by line). In Cling, there is no such
7622/// wrapper function.
7623/// In practice this routines was use to decipher whether the
7624/// pointer returns by InterfaceMethod could be used to uniquely
7625/// represent the function. In Cling if the function is in a
7626/// useable state (its compiled version is available), this is
7627/// always the case.
7628/// See TClass::GetMethod.
7629
7631{
7632 return 0;
7633}
7634
7635////////////////////////////////////////////////////////////////////////////////
7636/// Interface to cling function
7637
7639{
7640#if defined(R__MUST_REVISIT)
7641#if R__MUST_REVISIT(6,2)
7642 Warning("GetSecurityError", "Interface not available yet.");
7643#endif
7644#endif
7645 return 0;
7646}
7647
7648////////////////////////////////////////////////////////////////////////////////
7649/// Load a source file or library called path into the interpreter.
7650
7651int TCling::LoadFile(const char* path) const
7652{
7653 // Modifying the interpreter state needs locking.
7655 cling::Interpreter::CompilationResult compRes;
7656 HandleInterpreterException(GetMetaProcessorImpl(), TString::Format(".L %s", path), compRes, /*cling::Value*/nullptr);
7657 return compRes == cling::Interpreter::kFailure;
7658}
7659
7660////////////////////////////////////////////////////////////////////////////////
7661/// Load the declarations from text into the interpreter.
7662/// Note that this cannot be (top level) statements; text must contain
7663/// top level declarations.
7664/// Returns true on success, false on failure.
7665
7666Bool_t TCling::LoadText(const char* text) const
7667{
7668 return (fInterpreter->declare(text) == cling::Interpreter::kSuccess);
7669}
7670
7671////////////////////////////////////////////////////////////////////////////////
7672/// Interface to cling function
7673
7674const char* TCling::MapCppName(const char* name) const
7675{
7676 TTHREAD_TLS_DECL(std::string,buffer);
7678 return buffer.c_str(); // NOLINT
7679}
7680
7681////////////////////////////////////////////////////////////////////////////////
7682/// [Place holder for Mutex Lock]
7683/// Provide the interpreter with a way to
7684/// acquire a lock used to protect critical section
7685/// of its code (non-thread safe parts).
7686
7687void TCling::SetAlloclockfunc(void (* /* p */ )()) const
7688{
7689 // nothing to do for now.
7690}
7691
7692////////////////////////////////////////////////////////////////////////////////
7693/// [Place holder for Mutex Unlock] Provide the interpreter with a way to
7694/// release a lock used to protect critical section
7695/// of its code (non-thread safe parts).
7696
7697void TCling::SetAllocunlockfunc(void (* /* p */ )()) const
7698{
7699 // nothing to do for now.
7700}
7701
7702////////////////////////////////////////////////////////////////////////////////
7703/// Returns if class AutoLoading is currently enabled.
7704
7706{
7707 if (IsFromRootCling())
7708 return false;
7709 if (!fClingCallbacks)
7710 return false;
7712}
7713
7714////////////////////////////////////////////////////////////////////////////////
7715/// Enable/Disable the AutoLoading of libraries.
7716/// Returns the old value, i.e whether it was enabled or not.
7717
7719{
7720 // If no state change is required, exit early.
7721 // FIXME: In future we probably want to complain if we made a request which
7722 // was with the same state as before in order to catch programming errors.
7723 if ((bool) autoload == IsClassAutoLoadingEnabled())
7724 return autoload;
7725
7726 assert(fClingCallbacks && "We must have callbacks!");
7729 return oldVal;
7730}
7731
7732////////////////////////////////////////////////////////////////////////////////
7733/// Enable/Disable the Autoparsing of headers.
7734/// Returns the old value, i.e whether it was enabled or not.
7735
7742
7743////////////////////////////////////////////////////////////////////////////////
7744/// Suspend the Autoparsing of headers.
7745/// Returns the old value, i.e whether it was suspended or not.
7746
7753
7754////////////////////////////////////////////////////////////////////////////////
7755/// Set a callback to receive error messages.
7756
7758{
7759#if defined(R__MUST_REVISIT)
7760#if R__MUST_REVISIT(6,2)
7761 Warning("SetErrmsgcallback", "Interface not available yet.");
7762#endif
7763#endif
7764}
7765
7767{
7768 if (enable) {
7770 &fInterpreter->getDiagnostics().getDiagnosticOptions(),
7771 fInterpreter->getCI()->getLangOpts(),
7772 [] (clang::DiagnosticsEngine::Level Level, const std::string &Info) {
7773 if (Level == clang::DiagnosticsEngine::Warning) {
7774 ::Warning("cling", "%s", Info.c_str());
7775 } else if (Level == clang::DiagnosticsEngine::Error
7776 || Level == clang::DiagnosticsEngine::Fatal) {
7777 ::Error("cling", "%s", Info.c_str());
7778 } else {
7779 ::Info("cling", "%s", Info.c_str());
7780 }
7781 });
7782 fInterpreter->replaceDiagnosticConsumer(consumer, /*Own=*/true);
7783 } else {
7784 fInterpreter->replaceDiagnosticConsumer(nullptr);
7785 }
7786}
7787
7788
7789////////////////////////////////////////////////////////////////////////////////
7790/// Create / close a scope for temporaries. No-op for cling; use
7791/// cling::Value instead.
7792
7793void TCling::SetTempLevel(int val) const
7794{
7795}
7796
7797////////////////////////////////////////////////////////////////////////////////
7798
7799int TCling::UnloadFile(const char* path) const
7800{
7801 // Modifying the interpreter state needs locking.
7803 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
7804 std::string canonical = DLM->lookupLibrary(path);
7805 if (canonical.empty()) {
7806 canonical = path;
7807 }
7808 // Unload a shared library or a source file.
7809 cling::Interpreter::CompilationResult compRes;
7810 HandleInterpreterException(GetMetaProcessorImpl(), Form(".U %s", canonical.c_str()), compRes, /*cling::Value*/nullptr);
7811 return compRes == cling::Interpreter::kFailure;
7812}
7813
7814std::unique_ptr<TInterpreterValue> TCling::MakeInterpreterValue() const {
7815 return std::unique_ptr<TInterpreterValue>(new TClingValue);
7816}
7817
7818////////////////////////////////////////////////////////////////////////////////
7819/// The call to Cling's tab complition.
7820
7821void TCling::CodeComplete(const std::string& line, size_t& cursor,
7822 std::vector<std::string>& completions)
7823{
7824 fInterpreter->codeComplete(line, cursor, completions);
7825}
7826
7827////////////////////////////////////////////////////////////////////////////////
7828/// Get the interpreter value corresponding to the statement.
7830{
7832
7833 auto V = reinterpret_cast<cling::Value*>(value.GetValAddr());
7834 auto compRes = fInterpreter->evaluate(code, *V);
7835 return compRes!=cling::Interpreter::kSuccess ? 0 : 1 ;
7836}
7837
7838////////////////////////////////////////////////////////////////////////////////
7839
7841{
7842 using namespace cling;
7843 const Value* V = reinterpret_cast<const Value*>(value.GetValAddr());
7845}
7846
7847////////////////////////////////////////////////////////////////////////////////
7848/// Register value as a temporary, extending its lifetime to that of the
7849/// interpreter. This is needed for TCling's compatibility interfaces
7850/// returning long - the address of the temporary objects.
7851/// As such, "simple" types don't need to be stored; they are returned by
7852/// value; only pointers / references / objects need to be stored.
7853
7854void TCling::RegisterTemporary(const cling::Value& value)
7855{
7856 if (value.isValid() && value.needsManagedAllocation()) {
7858 fTemporaries->push_back(value);
7859 }
7860}
7861
7862////////////////////////////////////////////////////////////////////////////////
7863/// If the interpreter encounters Name, check whether that is an object ROOT
7864/// could retrieve. To not re-read objects from disk, cache the name/object
7865/// pair for a given LookupCtx.
7866
7868{
7869 // The call to FindSpecialObject might induces any kind of use
7870 // of the interpreter ... (library loading, function calling, etc.)
7871 // ... and we _know_ we are in the middle of parsing, so let's make
7872 // sure to save the state and then restore it.
7873
7874 if (gDirectory) {
7876 if (iSpecObjMap != fSpecialObjectMaps.end()) {
7877 auto iSpecObj = iSpecObjMap->second.find(Name);
7878 if (iSpecObj != iSpecObjMap->second.end()) {
7880 return iSpecObj->second;
7881 }
7882 }
7883 }
7884
7885 // Save state of the PP
7886 Sema &SemaR = fInterpreter->getSema();
7887 ASTContext& C = SemaR.getASTContext();
7888 Preprocessor &PP = SemaR.getPreprocessor();
7889 Parser& P = const_cast<Parser&>(fInterpreter->getParser());
7890 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
7891 Parser::ParserCurTokRestoreRAII savedCurToken(P);
7892 // After we have saved the token reset the current one to something which
7893 // is safe (semi colon usually means empty decl)
7894 Token& Tok = const_cast<Token&>(P.getCurToken());
7895 Tok.setKind(tok::semi);
7896
7897 // We can't PushDeclContext, because we go up and the routine that pops
7898 // the DeclContext assumes that we drill down always.
7899 // We have to be on the global context. At that point we are in a
7900 // wrapper function so the parent context must be the global.
7901 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
7902 SemaR.TUScope);
7903
7904 TObject* specObj = gROOT->FindSpecialObject(Name, LookupCtx);
7905 if (specObj) {
7906 if (!LookupCtx) {
7907 Error("GetObjectAddress", "Got a special object without LookupCtx!");
7908 } else {
7910 }
7911 }
7912 return specObj;
7913}
7914
7915////////////////////////////////////////////////////////////////////////////////
7916/// Inject function as a friend into klass.
7917/// With function being f in void f() {new N::PrivKlass(); } this enables
7918/// I/O of non-public classes.
7919
7920void TCling::AddFriendToClass(clang::FunctionDecl* function,
7921 clang::CXXRecordDecl* klass) const
7922{
7923 using namespace clang;
7924 ASTContext& Ctx = klass->getASTContext();
7925 FriendDecl::FriendUnion friendUnion(function);
7926 // one dummy object for the source location
7928 FriendDecl* friendDecl = FriendDecl::Create(Ctx, klass, sl, friendUnion, sl);
7929 klass->pushFriendDecl(friendDecl);
7930}
7931
7932//______________________________________________________________________________
7933//
7934// DeclId getter.
7935//
7936
7937////////////////////////////////////////////////////////////////////////////////
7938/// Return a unique identifier of the declaration represented by the
7939/// CallFunc
7940
7942{
7943 if (func) return ((TClingCallFunc*)func)->GetDecl()->getCanonicalDecl();
7944 return nullptr;
7945}
7946
7947////////////////////////////////////////////////////////////////////////////////
7948/// Return a (almost) unique identifier of the declaration represented by the
7949/// ClassInfo. In ROOT, this identifier can point to more than one TClass
7950/// when the underlying class is a template instance involving one of the
7951/// opaque typedef.
7952
7954{
7955 if (cinfo) return ((TClingClassInfo*)cinfo)->GetDeclId();
7956 return nullptr;
7957}
7958
7959////////////////////////////////////////////////////////////////////////////////
7960/// Return a unique identifier of the declaration represented by the
7961/// MethodInfo
7962
7964{
7965 if (data) return ((TClingDataMemberInfo*)data)->GetDeclId();
7966 return nullptr;
7967}
7968
7969////////////////////////////////////////////////////////////////////////////////
7970/// Return a unique identifier of the declaration represented by the
7971/// MethodInfo
7972
7974{
7975 if (method) return ((TClingMethodInfo*)method)->GetDeclId();
7976 return nullptr;
7977}
7978
7979////////////////////////////////////////////////////////////////////////////////
7980/// Return a unique identifier of the declaration represented by the
7981/// TypedefInfo
7982
7984{
7985 if (tinfo) return ((TClingTypedefInfo*)tinfo)->GetDecl()->getCanonicalDecl();
7986 return nullptr;
7987}
7988
7989//______________________________________________________________________________
7990//
7991// CallFunc interface
7992//
7993
7994////////////////////////////////////////////////////////////////////////////////
7995
7997{
7998 delete (TClingCallFunc*) func;
7999}
8000
8001////////////////////////////////////////////////////////////////////////////////
8002
8003void TCling::CallFunc_Exec(CallFunc_t* func, void* address) const
8004{
8005 TClingCallFunc* f = (TClingCallFunc*) func;
8006 f->Exec(address);
8007}
8008
8009////////////////////////////////////////////////////////////////////////////////
8010
8011void TCling::CallFunc_Exec(CallFunc_t* func, void* address, TInterpreterValue& val) const
8012{
8013 TClingCallFunc* f = (TClingCallFunc*) func;
8014 f->Exec(address, &val);
8015}
8016
8017////////////////////////////////////////////////////////////////////////////////
8018
8019void TCling::CallFunc_ExecWithReturn(CallFunc_t* func, void* address, void* ret) const
8020{
8021 TClingCallFunc* f = (TClingCallFunc*) func;
8022 f->ExecWithReturn(address, ret);
8023}
8024
8025////////////////////////////////////////////////////////////////////////////////
8026
8028 const void* args[] /*=0*/,
8029 int nargs /*=0*/,
8030 void* ret/*=0*/) const
8031{
8032 TClingCallFunc* f = (TClingCallFunc*) func;
8033 f->ExecWithArgsAndReturn(address, args, nargs, ret);
8034}
8035
8036////////////////////////////////////////////////////////////////////////////////
8037
8039{
8040 TClingCallFunc* f = (TClingCallFunc*) func;
8041 return f->ExecInt(address);
8042}
8043
8044////////////////////////////////////////////////////////////////////////////////
8045
8047{
8048 TClingCallFunc* f = (TClingCallFunc*) func;
8049 return f->ExecInt64(address);
8050}
8051
8052////////////////////////////////////////////////////////////////////////////////
8053
8055{
8056 TClingCallFunc* f = (TClingCallFunc*) func;
8057 return f->ExecDouble(address);
8058}
8059
8060////////////////////////////////////////////////////////////////////////////////
8061
8067
8068////////////////////////////////////////////////////////////////////////////////
8069
8071{
8072 return (CallFunc_t*) new TClingCallFunc(*(TClingCallFunc*)func);
8073}
8074
8075////////////////////////////////////////////////////////////////////////////////
8076
8078{
8079 TClingCallFunc* f = (TClingCallFunc*) func;
8080 return (MethodInfo_t*) f->FactoryMethod();
8081}
8082
8083////////////////////////////////////////////////////////////////////////////////
8084
8086{
8087 TClingCallFunc* f = (TClingCallFunc*) func;
8088 f->IgnoreExtraArgs(ignore);
8089}
8090
8091////////////////////////////////////////////////////////////////////////////////
8092
8094{
8096 TClingCallFunc* f = (TClingCallFunc*) func;
8097 f->Init();
8098}
8099
8100////////////////////////////////////////////////////////////////////////////////
8101
8103{
8104 TClingCallFunc* f = (TClingCallFunc*) func;
8105 return f->IsValid();
8106}
8107
8108////////////////////////////////////////////////////////////////////////////////
8109
8112{
8113 TClingCallFunc* f = (TClingCallFunc*) func;
8114 return f->IFacePtr();
8115}
8116
8117////////////////////////////////////////////////////////////////////////////////
8118
8120{
8121 TClingCallFunc* f = (TClingCallFunc*) func;
8122 f->ResetArg();
8123}
8124
8125////////////////////////////////////////////////////////////////////////////////
8126
8128{
8129 TClingCallFunc* f = (TClingCallFunc*) func;
8130 f->SetArg(param);
8131}
8132
8133////////////////////////////////////////////////////////////////////////////////
8134
8136{
8137 TClingCallFunc* f = (TClingCallFunc*) func;
8138 f->SetArg(param);
8139}
8140
8141////////////////////////////////////////////////////////////////////////////////
8142
8144{
8145 TClingCallFunc* f = (TClingCallFunc*) func;
8146 f->SetArg(param);
8147}
8148
8149////////////////////////////////////////////////////////////////////////////////
8150
8152{
8153 TClingCallFunc* f = (TClingCallFunc*) func;
8154 f->SetArg(param);
8155}
8156
8157////////////////////////////////////////////////////////////////////////////////
8158
8160{
8161 TClingCallFunc* f = (TClingCallFunc*) func;
8162 f->SetArg(param);
8163}
8164
8165////////////////////////////////////////////////////////////////////////////////
8166
8168{
8169 TClingCallFunc* f = (TClingCallFunc*) func;
8170 f->SetArg(param);
8171}
8172
8173////////////////////////////////////////////////////////////////////////////////
8174
8176{
8177 TClingCallFunc* f = (TClingCallFunc*) func;
8178 f->SetArgArray(paramArr, nparam);
8179}
8180
8181////////////////////////////////////////////////////////////////////////////////
8182
8183void TCling::CallFunc_SetArgs(CallFunc_t* func, const char* param) const
8184{
8185 TClingCallFunc* f = (TClingCallFunc*) func;
8186 f->SetArgs(param);
8187}
8188
8189////////////////////////////////////////////////////////////////////////////////
8190
8191void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, Longptr_t* offset) const
8192{
8193 TClingCallFunc* f = (TClingCallFunc*) func;
8195 f->SetFunc(ci, method, params, offset);
8196}
8197
8198////////////////////////////////////////////////////////////////////////////////
8199
8200void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, bool objectIsConst, Longptr_t* offset) const
8201{
8202 TClingCallFunc* f = (TClingCallFunc*) func;
8204 f->SetFunc(ci, method, params, objectIsConst, offset);
8205}
8206////////////////////////////////////////////////////////////////////////////////
8207
8208void TCling::CallFunc_SetFunc(CallFunc_t* func, MethodInfo_t* info) const
8209{
8210 TClingCallFunc* f = (TClingCallFunc*) func;
8212 f->SetFunc(minfo);
8213}
8214
8215////////////////////////////////////////////////////////////////////////////////
8216/// Interface to cling function
8217
8218void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8219{
8220 TClingCallFunc* f = (TClingCallFunc*) func;
8222 f->SetFuncProto(ci, method, proto, offset, mode);
8223}
8224
8225////////////////////////////////////////////////////////////////////////////////
8226/// Interface to cling function
8227
8228void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, bool objectIsConst, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8229{
8230 TClingCallFunc* f = (TClingCallFunc*) func;
8232 f->SetFuncProto(ci, method, proto, objectIsConst, offset, mode);
8233}
8234
8235////////////////////////////////////////////////////////////////////////////////
8236/// Interface to cling function
8237
8238void 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
8239{
8240 TClingCallFunc* f = (TClingCallFunc*) func;
8242 llvm::SmallVector<clang::QualType, 4> funcProto;
8243 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8244 iter != end; ++iter) {
8245 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8246 }
8247 f->SetFuncProto(ci, method, funcProto, offset, mode);
8248}
8249
8250////////////////////////////////////////////////////////////////////////////////
8251/// Interface to cling function
8252
8253void 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
8254{
8255 TClingCallFunc* f = (TClingCallFunc*) func;
8257 llvm::SmallVector<clang::QualType, 4> funcProto;
8258 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8259 iter != end; ++iter) {
8260 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8261 }
8262 f->SetFuncProto(ci, method, funcProto, objectIsConst, offset, mode);
8263}
8264
8266{
8267 TClingCallFunc *f = (TClingCallFunc *)func;
8268 std::string wrapper_name;
8269 std::string wrapper;
8270 f->get_wrapper_code(wrapper_name, wrapper);
8271 return wrapper;
8272}
8273
8274//______________________________________________________________________________
8275//
8276// ClassInfo interface
8277//
8278
8279////////////////////////////////////////////////////////////////////////////////
8280
8282{
8284 return TClinginfo->GetAlignOf();
8285}
8286
8287////////////////////////////////////////////////////////////////////////////////
8288/// Return true if the entity pointed to by 'declid' is declared in
8289/// the context described by 'info'. If info is null, look into the
8290/// global scope (translation unit scope).
8291
8293{
8294 if (!declid)
8295 return kFALSE;
8296
8297 const clang::DeclContext *ctxt = nullptr;
8298 if (info) {
8299 ctxt = clang::Decl::castToDeclContext(((TClingClassInfo*)info)->GetDecl());
8300 } else {
8301 ctxt = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
8302 }
8303 if (!ctxt)
8304 return kFALSE;
8305
8306 const clang::Decl *decl = reinterpret_cast<const clang::Decl*>(declid);
8307 if (!decl)
8308 return kFALSE;
8309
8310 const clang::DeclContext *declDC = decl->getDeclContext();
8311 // ClassInfo_t-s are always "spellable" scopes, never unnamed or inline ones.
8312 while (true) {
8313 if (declDC->isTransparentContext()) {
8314 declDC = declDC->getParent();
8315 continue;
8316 }
8317 if (const auto *declRD = llvm::dyn_cast<clang::RecordDecl>(declDC)) {
8318 if (declRD->isAnonymousStructOrUnion()) {
8319 declDC = declRD->getParent();
8320 continue;
8321 }
8322 }
8323 if (const auto *declNS = llvm::dyn_cast<clang::NamespaceDecl>(declDC)) {
8324 if (declNS->isAnonymousNamespace() || declNS->isInlineNamespace()) {
8325 declDC = declNS->getParent();
8326 continue;
8327 }
8328 }
8329 break;
8330 }
8331
8332 return declDC->Equals(ctxt);
8333}
8334
8335////////////////////////////////////////////////////////////////////////////////
8336
8342
8343////////////////////////////////////////////////////////////////////////////////
8344
8346{
8347 delete (TClingClassInfo*) cinfo;
8348}
8349
8350////////////////////////////////////////////////////////////////////////////////
8351
8357
8358////////////////////////////////////////////////////////////////////////////////
8359
8365
8366////////////////////////////////////////////////////////////////////////////////
8367
8373
8374////////////////////////////////////////////////////////////////////////////////
8375
8381
8382////////////////////////////////////////////////////////////////////////////////
8383
8388
8389////////////////////////////////////////////////////////////////////////////////
8390
8396
8402
8403
8404////////////////////////////////////////////////////////////////////////////////
8405
8406int TCling::ClassInfo_GetMethodNArg(ClassInfo_t* cinfo, const char* method, const char* proto, Bool_t objectIsConst /* = false */, EFunctionMatchMode mode /* = kConversionMatch */) const
8407{
8409 return TClinginfo->GetMethodNArg(method, proto, objectIsConst, mode);
8410}
8411
8412////////////////////////////////////////////////////////////////////////////////
8413
8419
8420////////////////////////////////////////////////////////////////////////////////
8421
8423{
8425 return TClinginfo->HasMethod(name);
8426}
8427
8428////////////////////////////////////////////////////////////////////////////////
8429
8436
8437////////////////////////////////////////////////////////////////////////////////
8438
8445
8446////////////////////////////////////////////////////////////////////////////////
8447
8449{
8451 return TClinginfo->IsBase(name);
8452}
8453
8454////////////////////////////////////////////////////////////////////////////////
8455
8456bool TCling::ClassInfo_IsEnum(const char* name) const
8457{
8459}
8460
8461////////////////////////////////////////////////////////////////////////////////
8462
8468
8469
8470////////////////////////////////////////////////////////////////////////////////
8471
8477
8478
8479////////////////////////////////////////////////////////////////////////////////
8480
8482{
8484 return TClinginfo->IsLoaded();
8485}
8486
8487////////////////////////////////////////////////////////////////////////////////
8488
8490{
8492 return TClinginfo->IsValid();
8493}
8494
8495////////////////////////////////////////////////////////////////////////////////
8496
8497bool TCling::ClassInfo_IsValidMethod(ClassInfo_t* cinfo, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8498{
8500 return TClinginfo->IsValidMethod(method, proto, false, offset, mode);
8501}
8502
8503////////////////////////////////////////////////////////////////////////////////
8504
8506{
8508 return TClinginfo->IsValidMethod(method, proto, objectIsConst, offset, mode);
8509}
8510
8511////////////////////////////////////////////////////////////////////////////////
8512
8518
8519////////////////////////////////////////////////////////////////////////////////
8520
8526
8527////////////////////////////////////////////////////////////////////////////////
8528
8534
8535////////////////////////////////////////////////////////////////////////////////
8536
8538{
8540 return TClinginfo->New(n, arena,*fNormalizedCtxt);
8541}
8542
8543////////////////////////////////////////////////////////////////////////////////
8544
8550
8551////////////////////////////////////////////////////////////////////////////////
8552
8558
8559////////////////////////////////////////////////////////////////////////////////
8560
8566
8567////////////////////////////////////////////////////////////////////////////////
8568
8574
8575////////////////////////////////////////////////////////////////////////////////
8576
8578{
8580 return TClinginfo->FileName();
8581}
8582
8583////////////////////////////////////////////////////////////////////////////////
8584
8586{
8588 TTHREAD_TLS_DECL(std::string,output);
8589 TClinginfo->FullName(output,*fNormalizedCtxt);
8590 return output.c_str(); // NOLINT
8591}
8592
8593////////////////////////////////////////////////////////////////////////////////
8594
8596{
8598 return TClinginfo->Name();
8599}
8600
8601////////////////////////////////////////////////////////////////////////////////
8602
8604{
8606 return TClinginfo->Title();
8607}
8608
8609////////////////////////////////////////////////////////////////////////////////
8610
8612{
8614 return TClinginfo->TmpltName();
8615}
8616
8617
8618
8619//______________________________________________________________________________
8620//
8621// BaseClassInfo interface
8622//
8623
8624////////////////////////////////////////////////////////////////////////////////
8625
8630
8631////////////////////////////////////////////////////////////////////////////////
8632
8639
8640////////////////////////////////////////////////////////////////////////////////
8641
8650
8651////////////////////////////////////////////////////////////////////////////////
8652
8658
8659////////////////////////////////////////////////////////////////////////////////
8660
8666
8667////////////////////////////////////////////////////////////////////////////////
8668
8674
8675////////////////////////////////////////////////////////////////////////////////
8676
8678{
8681 // Offset to the class itself.
8682 if (TClinginfo->GetDecl() == TClinginfoBase->GetDecl()) {
8683 return 0;
8684 }
8685 return TClinginfo->GetBaseOffset(TClinginfoBase, address, isDerivedObject);
8686}
8687
8688////////////////////////////////////////////////////////////////////////////////
8689
8695
8696////////////////////////////////////////////////////////////////////////////////
8697
8703
8704////////////////////////////////////////////////////////////////////////////////
8705
8711
8712////////////////////////////////////////////////////////////////////////////////
8713
8715{
8717 TTHREAD_TLS_DECL(std::string,output);
8718 TClinginfo->FullName(output,*fNormalizedCtxt);
8719 return output.c_str(); // NOLINT
8720}
8721
8722////////////////////////////////////////////////////////////////////////////////
8723
8729
8730////////////////////////////////////////////////////////////////////////////////
8731
8737
8738//______________________________________________________________________________
8739//
8740// DataMemberInfo interface
8741//
8742
8743////////////////////////////////////////////////////////////////////////////////
8744
8750
8751////////////////////////////////////////////////////////////////////////////////
8752
8757
8758////////////////////////////////////////////////////////////////////////////////
8759
8766
8767////////////////////////////////////////////////////////////////////////////////
8768
8770{
8772 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
8773 const clang::ValueDecl* vd = llvm::dyn_cast_or_null<clang::ValueDecl>(decl);
8775}
8776
8777////////////////////////////////////////////////////////////////////////////////
8778
8784
8785////////////////////////////////////////////////////////////////////////////////
8786
8792
8793////////////////////////////////////////////////////////////////////////////////
8794
8800
8801////////////////////////////////////////////////////////////////////////////////
8802
8808
8809////////////////////////////////////////////////////////////////////////////////
8810
8816
8817////////////////////////////////////////////////////////////////////////////////
8818
8824
8825////////////////////////////////////////////////////////////////////////////////
8826
8832
8833////////////////////////////////////////////////////////////////////////////////
8834
8840
8841////////////////////////////////////////////////////////////////////////////////
8842
8848
8849////////////////////////////////////////////////////////////////////////////////
8850
8856
8857////////////////////////////////////////////////////////////////////////////////
8858
8864
8865////////////////////////////////////////////////////////////////////////////////
8866
8872
8873////////////////////////////////////////////////////////////////////////////////
8874
8876{
8877 TTHREAD_TLS_DECL(std::string,result);
8878
8880 result = TClinginfo->ValidArrayIndex().str();
8881 return result.c_str(); // NOLINT
8882}
8883
8884////////////////////////////////////////////////////////////////////////////////
8885
8887{
8888 Decl* decl = static_cast<Decl*>(const_cast<void*>(declId));
8889 ASTContext &C = decl->getASTContext();
8890 decl->addAttr(AnnotateAttr::CreateImplicit(C, attribute, nullptr, 0));
8891}
8892
8893//______________________________________________________________________________
8894//
8895// Function Template interface
8896//
8897
8898////////////////////////////////////////////////////////////////////////////////
8899
8900static void ConstructorName(std::string &name, const clang::Decl *decl,
8901 cling::Interpreter &interp,
8903{
8904 const clang::TypeDecl* td = llvm::dyn_cast<clang::TypeDecl>(decl->getDeclContext());
8905 if (!td) return;
8906
8907 clang::QualType qualType(td->getTypeForDecl(),0);
8909 unsigned int level = 0;
8910 for(size_t cursor = name.length()-1; cursor != 0; --cursor) {
8911 if (name[cursor] == '>') ++level;
8912 else if (name[cursor] == '<' && level) --level;
8913 else if (level == 0 && name[cursor] == ':') {
8914 name.erase(0,cursor+1);
8915 break;
8916 }
8917 }
8918}
8919
8920////////////////////////////////////////////////////////////////////////////////
8921
8922void TCling::GetFunctionName(const clang::Decl *decl, std::string &output) const
8923{
8924 output.clear();
8925
8926 const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(decl);
8927 if (const auto *USD = llvm::dyn_cast<clang::UsingShadowDecl>(decl)) {
8928 FD = llvm::dyn_cast<clang::FunctionDecl>(USD->getTargetDecl());
8929 }
8930 if (!FD) {
8931 Error("GetFunctionName", "NULL Decl!");
8932 return;
8933 }
8934
8935 // For using-decls, show "Derived", not "Base", i.e. use the
8936 // name of the decl context of the UsingShadowDecl (aka `decl`)
8937 // not the name of FD's decl context.
8938 if (llvm::isa<clang::CXXConstructorDecl>(FD))
8939 {
8941
8942 } else if (llvm::isa<clang::CXXDestructorDecl>(decl))
8943 {
8945 output.insert(output.begin(), '~');
8946 } else {
8947 llvm::raw_string_ostream stream(output);
8948 auto printPolicy = decl->getASTContext().getPrintingPolicy();
8949 // Don't trigger fopen of the source file to count lines:
8950 printPolicy.AnonymousTagLocations = false;
8951 FD->getNameForDiagnostic(stream, printPolicy, /*Qualified=*/false);
8952 }
8953}
8954
8955////////////////////////////////////////////////////////////////////////////////
8956/// Return a unique identifier of the declaration represented by the
8957/// FuncTempInfo
8958
8963
8964////////////////////////////////////////////////////////////////////////////////
8965/// Delete the FuncTempInfo_t
8966
8968{
8969 // Currently the address of ft_info is actually the decl itself,
8970 // so we have nothing to do.
8971}
8972
8973////////////////////////////////////////////////////////////////////////////////
8974/// Construct a FuncTempInfo_t
8975
8977{
8978 // Currently the address of ft_info is actually the decl itself,
8979 // so we have nothing to do.
8980
8981 return (FuncTempInfo_t*)const_cast<void*>(declid);
8982}
8983
8984////////////////////////////////////////////////////////////////////////////////
8985/// Construct a FuncTempInfo_t
8986
8988{
8989 // Currently the address of ft_info is actually the decl itself,
8990 // so we have nothing to do.
8991
8992 return (FuncTempInfo_t*)ft_info;
8993}
8994
8995////////////////////////////////////////////////////////////////////////////////
8996/// Check validity of a FuncTempInfo_t
8997
8999{
9000 // Currently the address of ft_info is actually the decl itself,
9001 // so we have nothing to do.
9002
9003 return t_info != nullptr;
9004}
9005
9006////////////////////////////////////////////////////////////////////////////////
9007/// Return the maximum number of template arguments of the
9008/// function template described by ft_info.
9009
9011{
9012 if (!ft_info) return 0;
9013 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
9014 return ft->getTemplateParameters()->size();
9015}
9016
9017////////////////////////////////////////////////////////////////////////////////
9018/// Return the number of required template arguments of the
9019/// function template described by ft_info.
9020
9022{
9023 if (!ft_info) return 0;
9024 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9025 return ft->getTemplateParameters()->getMinRequiredArguments();
9026}
9027
9028////////////////////////////////////////////////////////////////////////////////
9029/// Return the property of the function template.
9030
9032{
9033 if (!ft_info) return 0;
9034
9035 long property = 0L;
9036 property |= kIsCompiled;
9037
9038 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9039
9040 switch (ft->getAccess()) {
9041 case clang::AS_public:
9042 property |= kIsPublic;
9043 break;
9044 case clang::AS_protected:
9045 property |= kIsProtected;
9046 break;
9047 case clang::AS_private:
9048 property |= kIsPrivate;
9049 break;
9050 case clang::AS_none:
9051 if (ft->getDeclContext()->isNamespace())
9053 break;
9054 default:
9055 // IMPOSSIBLE
9056 assert(false && "Unexpected value for the access property value in Clang");
9057 break;
9058 }
9059
9060 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
9061
9062 if (fd && fd->getStorageClass() == clang::SC_Static)
9063 property |= kIsStatic;
9064
9065 if (const clang::CXXMethodDecl *md =
9066 llvm::dyn_cast<clang::CXXMethodDecl>(fd)) {
9067 if (md->getMethodQualifiers().hasConst()) {
9068 property |= kIsConstant | kIsConstMethod;
9069 }
9070 if (md->isVirtual()) {
9071 property |= kIsVirtual;
9072 }
9073 if (md->isPureVirtual()) {
9074 property |= kIsPureVirtual;
9075 }
9076 if (const clang::CXXConstructorDecl *cd =
9077 llvm::dyn_cast<clang::CXXConstructorDecl>(md)) {
9078 if (cd->isExplicit()) {
9079 property |= kIsExplicit;
9080 }
9081 }
9082 else if (const clang::CXXConversionDecl *cd =
9083 llvm::dyn_cast<clang::CXXConversionDecl>(md)) {
9084 if (cd->isExplicit()) {
9085 property |= kIsExplicit;
9086 }
9087 }
9088 }
9089 return property;
9090}
9091
9092////////////////////////////////////////////////////////////////////////////////
9093/// Return the property not already defined in Property
9094/// See TDictionary's EFunctionProperty
9095
9097{
9098 if (!ft_info) return 0;
9099
9100 long property = 0L;
9101 property |= kIsCompiled;
9102
9103 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9104 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
9105
9106 if (fd->isOverloadedOperator())
9108 if (llvm::isa<clang::CXXConversionDecl>(fd))
9110 if (llvm::isa<clang::CXXConstructorDecl>(fd))
9112 if (llvm::isa<clang::CXXDestructorDecl>(fd))
9114 if (fd->isInlined())
9116 return property;
9117}
9118
9119////////////////////////////////////////////////////////////////////////////////
9120/// Return the name of this function template.
9121
9123{
9124 output.Clear();
9125 if (!ft_info) return;
9126 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9127 std::string buf;
9128 GetFunctionName(ft->getTemplatedDecl(), buf);
9129 output = buf;
9130}
9131
9132////////////////////////////////////////////////////////////////////////////////
9133/// Return the comments associates with this function template.
9134
9136{
9137 output.Clear();
9138 if (!ft_info) return;
9139 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
9140
9141 // Iterate over the redeclarations, we can have multiple definitions in the
9142 // redecl chain (came from merging of pcms).
9145 if (AnnotateAttr *A = AnnotFD->getAttr<AnnotateAttr>()) {
9146 output = A->getAnnotation().str();
9147 return;
9148 }
9149 }
9150 if (!ft->isFromASTFile()) {
9151 // Try to get the comment from the header file if present
9152 // but not for decls from AST file, where rootcling would have
9153 // created an annotation
9154 output = ROOT::TMetaUtils::GetComment(*ft).str();
9155 }
9156}
9157
9158
9159//______________________________________________________________________________
9160//
9161// MethodInfo interface
9162//
9163
9164////////////////////////////////////////////////////////////////////////////////
9165/// Interface to cling function
9166
9167void TCling::MethodInfo_Delete(MethodInfo_t* minfo) const
9168{
9169 delete(TClingMethodInfo*) minfo;
9170}
9171
9172////////////////////////////////////////////////////////////////////////////////
9173
9175{
9177 // The next call locks the interpreter mutex.
9178 info->CreateSignature(signature);
9179}
9180
9181////////////////////////////////////////////////////////////////////////////////
9182
9183MethodInfo_t* TCling::MethodInfo_Factory() const
9184{
9186 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl());
9187}
9188
9189////////////////////////////////////////////////////////////////////////////////
9190
9192{
9194 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), (TClingClassInfo*)clinfo);
9195}
9196
9197////////////////////////////////////////////////////////////////////////////////
9198
9200{
9201 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
9203 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), decl);
9204}
9205
9206////////////////////////////////////////////////////////////////////////////////
9207
9208MethodInfo_t* TCling::MethodInfo_FactoryCopy(MethodInfo_t* minfo) const
9209{
9210 return (MethodInfo_t*) new TClingMethodInfo(*(TClingMethodInfo*)minfo);
9211}
9212
9213////////////////////////////////////////////////////////////////////////////////
9214
9216{
9218 // The next call locks the interpreter mutex.
9219 return info->InterfaceMethod();
9220}
9221
9222////////////////////////////////////////////////////////////////////////////////
9223
9224bool TCling::MethodInfo_IsValid(MethodInfo_t* minfo) const
9225{
9227 return info->IsValid();
9228}
9229
9230////////////////////////////////////////////////////////////////////////////////
9231
9232int TCling::MethodInfo_NArg(MethodInfo_t* minfo) const
9233{
9235 return info->NArg();
9236}
9237
9238////////////////////////////////////////////////////////////////////////////////
9239
9241{
9243 return info->NDefaultArg();
9244}
9245
9246////////////////////////////////////////////////////////////////////////////////
9247
9248int TCling::MethodInfo_Next(MethodInfo_t* minfo) const
9249{
9251 return info->Next();
9252}
9253
9254////////////////////////////////////////////////////////////////////////////////
9255
9257{
9259 // The next call locks the interpreter mutex.
9260 return info->Property();
9261}
9262
9263////////////////////////////////////////////////////////////////////////////////
9264
9266{
9268 // The next call locks the interpreter mutex.
9269 return info->ExtraProperty();
9270}
9271
9272////////////////////////////////////////////////////////////////////////////////
9273
9275{
9277 // The next call locks the interpreter mutex.
9278 return (TypeInfo_t*)info->Type();
9279}
9280
9281////////////////////////////////////////////////////////////////////////////////
9282
9283const char* TCling::MethodInfo_GetMangledName(MethodInfo_t* minfo) const
9284{
9287 // The next call locks the interpreter mutex.
9288 mangled_name = info->GetMangledName();
9289 return mangled_name;
9290}
9291
9292////////////////////////////////////////////////////////////////////////////////
9293
9294const char* TCling::MethodInfo_GetPrototype(MethodInfo_t* minfo) const
9295{
9297 // The next call locks the interpreter mutex.
9298 return info->GetPrototype();
9299}
9300
9301////////////////////////////////////////////////////////////////////////////////
9302
9303const char* TCling::MethodInfo_Name(MethodInfo_t* minfo) const
9304{
9306 // The next call locks the interpreter mutex.
9307 return info->Name();
9308}
9309
9310////////////////////////////////////////////////////////////////////////////////
9311
9312const char* TCling::MethodInfo_TypeName(MethodInfo_t* minfo) const
9313{
9315 // The next call locks the interpreter mutex.
9316 return info->TypeName();
9317}
9318
9319////////////////////////////////////////////////////////////////////////////////
9320
9321std::string TCling::MethodInfo_TypeNormalizedName(MethodInfo_t* minfo) const
9322{
9324 // The next part locks the interpreter mutex.
9325 if (info && info->IsValid())
9326 return info->Type()->NormalizedName(*fNormalizedCtxt);
9327 else
9328 return "";
9329}
9330
9331////////////////////////////////////////////////////////////////////////////////
9332
9333const char* TCling::MethodInfo_Title(MethodInfo_t* minfo) const
9334{
9336 // The next call locks the interpreter mutex.
9337 return info->Title();
9338}
9339
9340////////////////////////////////////////////////////////////////////////////////
9341
9343{
9344 if (func) {
9345 return MethodInfo_MethodCallReturnType(func->fInfo);
9346 } else {
9347 return EReturnType::kOther;
9348 }
9349}
9350
9351////////////////////////////////////////////////////////////////////////////////
9352
9354{
9356 if (info && info->IsValid()) {
9357 TClingTypeInfo *typeinfo = info->Type();
9358 clang::QualType QT( typeinfo->GetQualType().getCanonicalType() );
9359 if (QT->isEnumeralType()) {
9360 return EReturnType::kLong;
9361 } else if (QT->isPointerType()) {
9362 // Look for char*
9363 QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
9364 if ( QT->isCharType() ) {
9365 return EReturnType::kString;
9366 } else {
9367 return EReturnType::kOther;
9368 }
9369 } else if ( QT->isFloatingType() ) {
9370 int sz = typeinfo->Size();
9371 if (sz == 4 || sz == 8) {
9372 // Support only float and double.
9373 return EReturnType::kDouble;
9374 } else {
9375 return EReturnType::kOther;
9376 }
9377 } else if ( QT->isIntegerType() ) {
9378 int sz = typeinfo->Size();
9379 if (sz <= 8) {
9380 // Support only up to long long ... but
9381 // FIXME the TMethodCall::Execute only
9382 // return long (4 bytes) ...
9383 // The v5 implementation of TMethodCall::ReturnType
9384 // was not making the distinction so we let it go
9385 // as is for now, but we really need to upgrade
9386 // TMethodCall::Execute ...
9387 return EReturnType::kLong;
9388 } else {
9389 return EReturnType::kOther;
9390 }
9391 } else {
9392 return EReturnType::kOther;
9393 }
9394 } else {
9395 return EReturnType::kOther;
9396 }
9397}
9398
9399//______________________________________________________________________________
9400//
9401// MethodArgInfo interface
9402//
9403
9404////////////////////////////////////////////////////////////////////////////////
9405
9410
9411////////////////////////////////////////////////////////////////////////////////
9412
9418
9419////////////////////////////////////////////////////////////////////////////////
9420
9426
9427////////////////////////////////////////////////////////////////////////////////
9428
9434
9435////////////////////////////////////////////////////////////////////////////////
9436
9442
9443////////////////////////////////////////////////////////////////////////////////
9444
9450
9451////////////////////////////////////////////////////////////////////////////////
9452
9458
9459////////////////////////////////////////////////////////////////////////////////
9460
9462{
9464 return info->DefaultValue();
9465}
9466
9467////////////////////////////////////////////////////////////////////////////////
9468
9470{
9472 return info->Name();
9473}
9474
9475////////////////////////////////////////////////////////////////////////////////
9476
9478{
9480 return info->TypeName();
9481}
9482
9483////////////////////////////////////////////////////////////////////////////////
9484
9486{
9488 return info->Type()->NormalizedName(*fNormalizedCtxt);
9489}
9490
9491////////////////////////////////////////////////////////////////////////////////
9492
9498
9499//______________________________________________________________________________
9500//
9501// TypeInfo interface
9502//
9503
9504////////////////////////////////////////////////////////////////////////////////
9505
9507{
9508 delete (TClingTypeInfo*) tinfo;
9509}
9510
9511////////////////////////////////////////////////////////////////////////////////
9512
9518
9519////////////////////////////////////////////////////////////////////////////////
9520
9526
9527////////////////////////////////////////////////////////////////////////////////
9528
9533
9534////////////////////////////////////////////////////////////////////////////////
9535
9542
9543////////////////////////////////////////////////////////////////////////////////
9544
9546{
9548 return TClinginfo->IsValid();
9549}
9550
9551////////////////////////////////////////////////////////////////////////////////
9552
9554{
9556 return TClinginfo->Name();
9557}
9558
9559////////////////////////////////////////////////////////////////////////////////
9560
9566
9567////////////////////////////////////////////////////////////////////////////////
9568
9570{
9572 return TClinginfo->RefType();
9573}
9574
9575////////////////////////////////////////////////////////////////////////////////
9576
9578{
9580 return TClinginfo->Size();
9581}
9582
9583////////////////////////////////////////////////////////////////////////////////
9584
9586{
9588 return TClinginfo->TrueName(*fNormalizedCtxt);
9589}
9590
9591////////////////////////////////////////////////////////////////////////////////
9592
9594{
9596 return TClinginfo->QualTypePtr();
9597}
9598
9599
9600//______________________________________________________________________________
9601//
9602// TypedefInfo interface
9603//
9604
9605////////////////////////////////////////////////////////////////////////////////
9606
9611
9612////////////////////////////////////////////////////////////////////////////////
9613
9619
9620////////////////////////////////////////////////////////////////////////////////
9621
9627
9628////////////////////////////////////////////////////////////////////////////////
9629
9634
9635////////////////////////////////////////////////////////////////////////////////
9636
9644
9645////////////////////////////////////////////////////////////////////////////////
9646
9652
9653////////////////////////////////////////////////////////////////////////////////
9654
9660
9661////////////////////////////////////////////////////////////////////////////////
9662
9668
9669////////////////////////////////////////////////////////////////////////////////
9670
9676
9677////////////////////////////////////////////////////////////////////////////////
9678
9684
9685////////////////////////////////////////////////////////////////////////////////
9686
9688{
9690 return TClinginfo->Name();
9691}
9692
9693////////////////////////////////////////////////////////////////////////////////
9694
9696{
9698 return TClinginfo->Title();
9699}
9700
9701////////////////////////////////////////////////////////////////////////////////
9702
9703bool TCling::IsSameType(const void * QualTypePtr1, const void * QualTypePtr2) const
9704{
9705 clang::QualType QT1 = clang::QualType::getFromOpaquePtr(QualTypePtr1);
9706 clang::QualType QT2 = clang::QualType::getFromOpaquePtr(QualTypePtr2);
9707 return fInterpreter->getCI()->getASTContext().hasSameType(QT1, QT2);
9708}
9709
9710////////////////////////////////////////////////////////////////////////////////
9711
9712bool TCling::IsIntegerType(const void * QualTypePtr) const
9713{
9714 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9715 return QT->hasIntegerRepresentation();
9716}
9717
9718////////////////////////////////////////////////////////////////////////////////
9719
9720bool TCling::IsSignedIntegerType(const void * QualTypePtr) const
9721{
9722 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9723 return QT->hasSignedIntegerRepresentation();
9724}
9725
9726////////////////////////////////////////////////////////////////////////////////
9727
9728bool TCling::IsUnsignedIntegerType(const void * QualTypePtr) const
9729{
9730 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9731 return QT->hasUnsignedIntegerRepresentation();
9732}
9733
9734////////////////////////////////////////////////////////////////////////////////
9735
9736bool TCling::IsFloatingType(const void * QualTypePtr) const
9737{
9738 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9739 return QT->hasFloatingRepresentation();
9740}
9741
9742////////////////////////////////////////////////////////////////////////////////
9743
9744bool TCling::IsPointerType(const void * QualTypePtr) const
9745{
9746 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9747 return QT->hasPointerRepresentation();
9748}
9749
9750////////////////////////////////////////////////////////////////////////////////
9751
9752bool TCling::IsVoidPointerType(const void * QualTypePtr) const
9753{
9754 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9755 return QT->isVoidPointerType();
9756}
9757
9758////////////////////////////////////////////////////////////////////////////////
9759
9761{
9762 if (!fInitialMutex) {
9764 Error("SnapshotMutexState", "fRecurseCount != 0 even though initial mutex state is unset!");
9765 }
9766 fInitialMutex.fState = mtx->GetStateBefore();
9767 }
9768 // We will "forget" this lock once we backed out of all interpreter frames.
9769 // Here we are entering one, so ++.
9771}
9772
9773////////////////////////////////////////////////////////////////////////////////
9774
9776{
9777 if (!fInitialMutex)
9778 return;
9779 if (fInitialMutex.fRecurseCount == 0) {
9780 Error("ForgetMutexState", "mutex state's recurse count already 0!");
9781 }
9782 else if (--fInitialMutex.fRecurseCount == 0) {
9783 // We have returned from all interpreter frames. Reset the initial lock state.
9784 fInitialMutex.fState.reset();
9785 }
9786}
9787
9788////////////////////////////////////////////////////////////////////////////////
9789/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
9790
9792{
9793 if (gInterpreterMutex) {
9794 if (delta) {
9795 auto typedDelta = static_cast<MutexStateAndRecurseCountDelta *>(delta);
9796 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP{typedDelta};
9797 gCoreMutex->Apply(std::move(typedDelta->fDelta));
9798 // Now that we have the lock, update the global
9799 R__ASSERT(fInitialMutex.fRecurseCount == 0 && "Inconsistent state of fInitialMutex! Another thread within Interpreter critical section.");
9800 std::swap(fInitialMutex, typedDelta->fInitialState);
9801 } else {
9802 // This case happens when EnableThreadSafety is first called from
9803 // the interpreter function we just handled.
9804 // Since thread safety was not enabled at the time we rewound, there was
9805 // no lock taken and even-though we should be locking the rest of this
9806 // interpreter handling/modifying code (since there might be threads in
9807 // flight), we can't because there would not be any lock guard to release the
9808 // locks
9810 Error("ApplyToInterpreterMutex",
9811 "After returning from user code that turned on thread safety support, we notice that fInitialMutex is already used ... "
9812 "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.");
9813 }
9814 }
9815}
9816
9817////////////////////////////////////////////////////////////////////////////////
9818/// Reset the interpreter lock to the state it had before interpreter-related
9819/// calls happened.
9820
9822{
9823 if (fInitialMutex) {
9824 // Need to start a new recurse count.
9825 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP(new MutexStateAndRecurseCountDelta());
9826 std::swap(uniqueP->fInitialState, fInitialMutex);
9827 uniqueP->fDelta = gCoreMutex->Rewind(*uniqueP->fInitialState.fState);
9828 return uniqueP.release();
9829 }
9831 return nullptr;
9832}
#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:7403
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:4017
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:3233
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:4059
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:4035
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:8900
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:7312
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:7147
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:6466
static bool requiresRootMap(const char *rootmapfile)
Definition TCling.cxx:5646
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:7424
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 IsAutoLoadingEnabled() const
void SetAutoParsingSuspended(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:6338
const char * MethodArgInfo_DefaultValue(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9461
bool ClassInfo_IsScopedEnum(ClassInfo_t *info) const final
Definition TCling.cxx:8463
const char * TypeInfo_Name(TypeInfo_t *) const final
Definition TCling.cxx:9553
void * MethodInfo_InterfaceMethod(MethodInfo_t *minfo) const final
Definition TCling.cxx:9215
void LoadEnums(TListOfEnums &cl) const final
Create list of pointers to enums for TClass cl.
Definition TCling.cxx:4529
void UpdateListOfGlobals() final
No op: see TClingCallbacks (used to update the list of globals)
Definition TCling.cxx:3997
bool TypedefInfo_IsValid(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9647
Int_t AutoLoad(const char *classname, Bool_t knowDictNotLoaded=kFALSE) final
Load library containing the specified class.
Definition TCling.cxx:6399
void CallFunc_Init(CallFunc_t *func) const final
Definition TCling.cxx:8093
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:3760
bool LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
Definition TCling.cxx:6708
void GenericError(const char *error) const final
Let the interpreter issue a generic error, and set its error state.
Definition TCling.cxx:7608
std::vector< void * > fRegisterModuleDyLibs
Definition TCling.h:140
void CallFunc_ExecWithReturn(CallFunc_t *func, void *address, void *ret) const final
Definition TCling.cxx:8019
bool IsIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9712
TypeInfo_t * MethodInfo_Type(MethodInfo_t *minfo) const final
Definition TCling.cxx:9274
std::vector< std::string > fAutoLoadLibStorage
Definition TCling.h:118
void CallFunc_Delete(CallFunc_t *func) const final
Definition TCling.cxx:7996
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:7651
void ResetAll() final
Reset the Cling state to its initial state.
Definition TCling.cxx:3836
void SetDeclAttr(DeclId_t, const char *) final
Definition TCling.cxx:8886
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:7043
Long_t MethodInfo_Property(MethodInfo_t *minfo) const final
Definition TCling.cxx:9256
void LoadFunctionTemplates(TClass *cl) const final
Create list of pointers to function templates for TClass cl.
Definition TCling.cxx:4576
bool ClassInfo_IsValidMethod(ClassInfo_t *info, const char *method, const char *proto, Longptr_t *offset, ROOT::EFunctionMatchMode=ROOT::kConversionMatch) const final
Definition TCling.cxx:8497
Long_t DataMemberInfo_Property(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8819
int SetClassAutoparsing(int) final
Enable/Disable the Autoparsing of headers.
Definition TCling.cxx:7736
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:4623
void RewindDictionary() final
Rewind Cling dictionary to the point where it was before executing the current macro.
Definition TCling.cxx:3881
bool ClassInfo_IsValid(ClassInfo_t *info) const final
Definition TCling.cxx:8489
void UpdateListsOnCommitted(const cling::Transaction &T)
Definition TCling.cxx:6917
int TypeInfo_RefType(TypeInfo_t *) const final
Definition TCling.cxx:9569
void CreateListOfBaseClasses(TClass *cl) const final
Create list of pointers to base class(es) for TClass cl.
Definition TCling.cxx:4500
ClassInfo_t * ClassInfo_Factory(Bool_t all=kTRUE) const final
Definition TCling.cxx:8376
const char * MethodInfo_Name(MethodInfo_t *minfo) const final
Definition TCling.cxx:9303
BaseClassInfo_t * BaseClassInfo_Factory(ClassInfo_t *info) const final
Definition TCling.cxx:8633
Bool_t LoadText(const char *text) const final
Load the declarations from text into the interpreter.
Definition TCling.cxx:7666
const char * GetSharedLibDeps(const char *lib, bool tryDyld=false) final
Get the list a libraries on which the specified lib depends.
Definition TCling.cxx:7440
EReturnType MethodInfo_MethodCallReturnType(MethodInfo_t *minfo) const final
Definition TCling.cxx:9353
TObject * GetObjectAddress(const char *Name, void *&LookupCtx)
If the interpreter encounters Name, check whether that is an object ROOT could retrieve.
Definition TCling.cxx:7867
Longptr_t ProcessLineAsynch(const char *line, EErrorCode *error=nullptr)
Let cling process a command line asynch.
Definition TCling.cxx:3672
bool MethodInfo_IsValid(MethodInfo_t *minfo) const final
Definition TCling.cxx:9224
FuncTempInfo_t * FuncTempInfo_Factory(DeclId_t declid) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8976
TypeInfo_t * TypeInfo_Factory() const final
Definition TCling.cxx:9513
bool IsClassAutoLoadingEnabled() const
Returns if class AutoLoading is currently enabled.
Definition TCling.cxx:7705
void InvalidateGlobal(const clang::Decl *D)
Invalidate cached TCling information for the given global declaration.
Definition TCling.cxx:7028
bool IsSameType(const void *QualTypePtr1, const void *QualTypePtr2) const final
Definition TCling.cxx:9703
int Evaluate(const char *, TInterpreterValue &) final
Get the interpreter value corresponding to the statement.
Definition TCling.cxx:7829
std::unique_ptr< TInterpreterValue > MakeInterpreterValue() const final
Definition TCling.cxx:7814
void UpdateListOfLoadedSharedLibraries()
Definition TCling.cxx:3452
const char * TypedefInfo_Title(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9695
~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:8218
void InitRootmapFile(const char *name)
Create a resource table and read the (possibly) three resource files, i.e.
Definition TCling.cxx:5789
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:6663
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:4641
void AddFriendToClass(clang::FunctionDecl *, clang::CXXRecordDecl *) const
Inject function as a friend into klass.
Definition TCling.cxx:7920
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:8653
void RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
Internal function. Actually do the update of the ClassInfo when seeing.
Definition TCling.cxx:6775
CallFunc_t * CallFunc_FactoryCopy(CallFunc_t *func) const final
Definition TCling.cxx:8070
Double_t CallFunc_ExecDouble(CallFunc_t *func, void *address) const final
Definition TCling.cxx:8054
std::set< std::string > fAutoLoadedLibraries
Definition TCling.h:125
void CallFunc_ResetArg(CallFunc_t *func) const final
Definition TCling.cxx:8119
const char * GetCurrentMacroName() const final
Return the file name of the currently interpreted file, included or not.
Definition TCling.cxx:5597
Bool_t IsLoaded(const char *filename) const final
Return true if the file has already been loaded by cint.
Definition TCling.cxx:3276
void SaveGlobalsContext() final
Save the current Cling state of global objects.
Definition TCling.cxx:3984
void CallFunc_IgnoreExtraArgs(CallFunc_t *func, bool ignore) const final
Definition TCling.cxx:8085
void ApplyToInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:9791
void * LazyFunctionCreatorAutoload(const std::string &mangled_name)
Autoload a library based on a missing symbol.
Definition TCling.cxx:6731
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:4857
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:8292
Bool_t IsLibraryLoaded(const char *libname) const final
Definition TCling.cxx:3242
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:7630
int DataMemberInfo_ArrayDim(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8745
DataMemberInfo_t * DataMemberInfo_FactoryCopy(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8779
Bool_t HandleNewTransaction(const cling::Transaction &T)
Helper function to increase the internal Cling count of transactions that change the AST.
Definition TCling.cxx:3777
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:5662
std::map< SpecialObjectLookupCtx_t, SpecialObjectMap_t > fSpecialObjectMaps
Definition TCling.h:155
int ClassInfo_Next(ClassInfo_t *info) const final
Definition TCling.cxx:8513
void SetErrmsgcallback(void *p) const final
Set a callback to receive error messages.
Definition TCling.cxx:7757
bool MethodArgInfo_IsValid(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9437
int TypeInfo_Size(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9577
Int_t DeleteGlobal(void *obj) final
Delete obj from Cling symbol table so it cannot be accessed anymore.
Definition TCling.cxx:3895
int GetSecurityError() const final
Interface to cling function.
Definition TCling.cxx:7638
void SetTempLevel(int val) const final
Create / close a scope for temporaries.
Definition TCling.cxx:7793
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:9010
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:5289
TypedefInfo_t * TypedefInfo_Factory() const final
Definition TCling.cxx:9614
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:8561
const char * MethodArgInfo_TypeName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9477
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:5537
std::vector< std::pair< TClass *, DictFuncPtr_t > > fClassesToUpdate
Definition TCling.h:148
int DataMemberInfo_Next(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8803
const char * TypedefInfo_Name(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9687
void BaseClassInfo_Delete(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8626
Long_t MethodInfo_ExtraProperty(MethodInfo_t *minfo) const final
Definition TCling.cxx:9265
void LoadMacro(const char *filename, EErrorCode *error=nullptr) final
Load a macro file in cling's memory.
Definition TCling.cxx:3664
FuncTempInfo_t * FuncTempInfo_FactoryCopy(FuncTempInfo_t *) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8987
int DataMemberInfo_MaxIndex(DataMemberInfo_t *dminfo, Int_t dim) const final
Definition TCling.cxx:8795
Bool_t FuncTempInfo_IsValid(FuncTempInfo_t *) const final
Check validity of a FuncTempInfo_t.
Definition TCling.cxx:8998
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:8448
void RecursiveRemove(TObject *obj) final
Delete object from cling symbol table so it can not be used anymore.
Definition TCling.cxx:3795
const char * DataMemberInfo_TypeName(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8843
DeclId_t GetDataMemberAtAddr(const void *addr) const final
Return pointer to cling DeclId for a data member with a given name.
Definition TCling.cxx:5084
void CallFunc_SetArgArray(CallFunc_t *func, Longptr_t *paramArr, Int_t nparam) const final
Definition TCling.cxx:8175
std::string CallFunc_GetWrapperCode(CallFunc_t *func) const final
Definition TCling.cxx:8265
void * RewindInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:9821
const char * MethodArgInfo_Name(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9469
Bool_t HasPCMForLibrary(const char *libname) const final
Return true if ROOT has cxxmodules pcm for a given library name.
Definition TCling.cxx:3251
void TypedefInfo_Init(TypedefInfo_t *tinfo, const char *name) const final
Definition TCling.cxx:9637
const char * DataMemberInfo_Title(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8867
Longptr_t CallFunc_ExecInt(CallFunc_t *func, void *address) const final
Definition TCling.cxx:8038
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:7687
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:7507
MethodInfo_t * CallFunc_FactoryMethod(CallFunc_t *func) const final
Definition TCling.cxx:8077
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:3518
TypedefInfo_t * TypedefInfo_FactoryCopy(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9630
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:5182
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:9485
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:4966
Long_t MethodArgInfo_Property(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9453
int TypedefInfo_Size(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9671
void CallFunc_ExecWithArgsAndReturn(CallFunc_t *func, void *address, const void *args[]=nullptr, int nargs=0, void *ret=nullptr) const final
Definition TCling.cxx:8027
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:5334
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:6897
Int_t Load(const char *filenam, Bool_t system=kFALSE) final
Load a library file in cling's memory.
Definition TCling.cxx:3627
int TypedefInfo_Next(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9655
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:5141
void TypeInfo_Init(TypeInfo_t *tinfo, const char *funcname) const final
Definition TCling.cxx:9536
Bool_t SetSuspendAutoParsing(Bool_t value) final
Suspend the Autoparsing of headers.
Definition TCling.cxx:7747
int DataMemberInfo_TypeSize(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8835
static void * fgSetOfSpecials
Definition TCling.h:105
const char * ClassInfo_Title(ClassInfo_t *info) const final
Definition TCling.cxx:8603
const char * DataMemberInfo_Name(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8859
const char * TypeName(const char *typeDesc) final
Return the absolute type of typeDesc.
Definition TCling.cxx:5612
ROOT::TMetaUtils::TNormalizedCtxt * fNormalizedCtxt
Definition TCling.h:136
void ForgetMutexState() final
Definition TCling.cxx:9775
int MethodInfo_Next(MethodInfo_t *minfo) const final
Definition TCling.cxx:9248
Long_t ClassInfo_ClassProperty(ClassInfo_t *info) const final
Definition TCling.cxx:8337
void MethodInfo_Delete(MethodInfo_t *minfo) const final
Interface to cling function.
Definition TCling.cxx:9167
bool fIsShuttingDown
Definition TCling.h:189
void MethodArgInfo_Delete(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9406
bool IsSignedIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9720
DataMemberInfo_t * DataMemberInfo_Factory(ClassInfo_t *clinfo, TDictionary::EMemberSelection selection) const final
Definition TCling.cxx:8760
void ClassInfo_Destruct(ClassInfo_t *info, void *arena) const final
Definition TCling.cxx:8368
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:6244
Int_t UnloadAllSharedLibraryMaps() final
Unload the library map entries coming from all the loaded shared libraries.
Definition TCling.cxx:6132
void ClassInfo_Init(ClassInfo_t *info, const char *funcname) const final
Definition TCling.cxx:8430
std::set< TClass * > & GetModTClasses()
Definition TCling.h:585
ClassInfo_t * BaseClassInfo_ClassInfo(BaseClassInfo_t *) const final
Definition TCling.cxx:8698
TClingCallbacks * fClingCallbacks
Definition TCling.h:141
Long64_t CallFunc_ExecInt64(CallFunc_t *func, void *address) const final
Definition TCling.cxx:8046
Long_t ClassInfo_Property(ClassInfo_t *info) const final
Definition TCling.cxx:8553
Longptr_t ClassInfo_GetBaseOffset(ClassInfo_t *fromDerived, ClassInfo_t *toBase, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8677
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:5519
Bool_t IsErrorMessagesEnabled() const final
If error messages are disabled, the interpreter should suppress its failures and warning messages fro...
Definition TCling.cxx:7493
TString fIncludePath
Definition TCling.h:115
int DisplayIncludePath(FILE *fout) const final
Interface to cling function.
Definition TCling.cxx:7570
void TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:7102
Long_t FuncTempInfo_Property(FuncTempInfo_t *) const final
Return the property of the function template.
Definition TCling.cxx:9031
TEnum * CreateEnum(void *VD, TClass *cl) const final
Definition TCling.cxx:486
const char * TypeInfo_TrueName(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9585
Int_t UnloadLibraryMap(const char *library) final
Unload library map entries coming from the specified library.
Definition TCling.cxx:6150
void RegisterTemporary(const TInterpreterValue &value)
Definition TCling.cxx:7840
MutexStateAndRecurseCount fInitialMutex
Definition TCling.h:176
const char * GetSharedLibs() final
Return the list of shared libraries loaded into the process.
Definition TCling.cxx:7140
int MethodArgInfo_Next(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9445
void SnapshotMutexState(ROOT::TVirtualRWMutex *mtx) final
Definition TCling.cxx:9760
Long_t TypeInfo_Property(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9561
const char * MethodInfo_GetPrototype(MethodInfo_t *minfo) const final
Definition TCling.cxx:9294
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:9021
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:6290
void MethodInfo_CreateSignature(MethodInfo_t *minfo, TString &signature) const final
Definition TCling.cxx:9174
Bool_t CheckClassTemplate(const char *name) final
Return true if there is a class template by the given name ...
Definition TCling.cxx:4478
void LibraryLoaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7125
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:9752
TObjArray * GetRootMapFiles() const final
Definition TCling.h:226
bool DataMemberInfo_IsValid(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8787
bool ClassInfo_IsEnum(const char *name) const final
Definition TCling.cxx:8456
int MethodInfo_NDefaultArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9240
bool IsFloatingType(const void *QualTypePtr) const final
Definition TCling.cxx:9736
void CreateListOfMethods(TClass *cl) const final
Create list of pointers to methods for TClass cl.
Definition TCling.cxx:4632
Int_t RescanLibraryMap() final
Scan again along the dynamic path for library maps.
Definition TCling.cxx:6059
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:7766
const char * MethodInfo_GetMangledName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9283
TypeInfo_t * MethodArgInfo_TypeInfo(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9493
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:5244
void * ClassInfo_New(ClassInfo_t *info) const final
Definition TCling.cxx:8521
int DisplayClass(FILE *fout, const char *name, int base, int start) const final
Definition TCling.cxx:7561
void GetFunctionName(const clang::Decl *decl, std::string &name) const
Definition TCling.cxx:8922
void CreateListOfMethodArgs(TFunction *m) const final
Create list of pointers to method arguments for TMethod m.
Definition TCling.cxx:4657
const char * GetSTLIncludePath() const final
Return the directory containing CINT's stl cintdlls.
Definition TCling.cxx:7552
MethodArgInfo_t * MethodArgInfo_FactoryCopy(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9429
Longptr_t BaseClassInfo_Offset(BaseClassInfo_t *toBaseClassInfo, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8669
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:4306
void * FindSym(const char *entry) const final
Interface to cling function.
Definition TCling.cxx:7599
void RegisterLoadedSharedLibrary(const char *name)
Register a new shared library name with the interpreter; add it to fSharedLibs.
Definition TCling.cxx:3527
void TypeInfo_Delete(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9506
int MethodInfo_NArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9232
DeclId_t GetDataMemberWithValue(const void *ptrvalue) const final
NOT IMPLEMENTED.
Definition TCling.cxx:5075
std::unordered_set< const clang::NamespaceDecl * > fNSFromRootmaps
Definition TCling.h:127
EReturnType MethodCallReturnType(TFunction *func) const final
Definition TCling.cxx:9342
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:5267
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:5096
const char * MethodInfo_Title(MethodInfo_t *minfo) const final
Definition TCling.cxx:9333
TString fRootmapLoadPath
Definition TCling.h:116
const char * BaseClassInfo_TmpltName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8732
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:3202
const char * BaseClassInfo_FullName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8714
void CallFunc_SetArgs(CallFunc_t *func, const char *param) const final
Definition TCling.cxx:8183
int UnloadFile(const char *path) const final
Definition TCling.cxx:7799
void SetClassInfo(TClass *cl, Bool_t reload=kFALSE, Bool_t silent=kFALSE) final
Set pointer to the TClingClassInfo in TClass.
Definition TCling.cxx:4170
void CallFunc_Exec(CallFunc_t *func, void *address) const final
Definition TCling.cxx:8003
Long_t FuncTempInfo_ExtraProperty(FuncTempInfo_t *) const final
Return the property not already defined in Property See TDictionary's EFunctionProperty.
Definition TCling.cxx:9096
bool CallFunc_IsValid(CallFunc_t *func) const final
Definition TCling.cxx:8102
const char * BaseClassInfo_Name(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8724
ROOT::TMetaUtils::TClingLookupHelper * fLookupHelper
Definition TCling.h:137
const char * DataMemberInfo_ValidArrayIndex(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8875
Int_t GetMore() const final
Return whether we are waiting for more input either because the collected input contains unbalanced b...
Definition TCling.cxx:4678
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:5006
void Execute(const char *function, const char *params, int *error=nullptr) final
Execute a global function with arguments params.
Definition TCling.cxx:5367
bool ClassInfo_IsLoaded(ClassInfo_t *info) const final
Definition TCling.cxx:8481
Longptr_t ClassInfo_Tagnum(ClassInfo_t *info) const final
Definition TCling.cxx:8569
Long_t BaseClassInfo_Property(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8690
void CallFunc_SetFunc(CallFunc_t *func, ClassInfo_t *info, const char *method, const char *params, Longptr_t *Offset) const final
Definition TCling.cxx:8191
std::vector< std::string > GetUsingNamespaces(ClassInfo_t *cl) const final
Get the scopes representing using declarations of namespace.
Definition TCling.cxx:4612
const char * ClassInfo_FileName(ClassInfo_t *info) const final
Definition TCling.cxx:8577
void FuncTempInfo_Title(FuncTempInfo_t *, TString &name) const final
Return the comments associates with this function template.
Definition TCling.cxx:9135
const char * ClassInfo_TmpltName(ClassInfo_t *info) const final
Definition TCling.cxx:8611
void SaveContext() final
Save the current Cling state.
Definition TCling.cxx:3971
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:6767
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:3852
void CodeComplete(const std::string &, size_t &, std::vector< std::string > &) final
The call to Cling's tab complition.
Definition TCling.cxx:7821
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:3866
const char * MapCppName(const char *) const final
Interface to cling function.
Definition TCling.cxx:7674
Longptr_t Calc(const char *line, EErrorCode *error=nullptr) final
Directly execute an executable statement (e.g.
Definition TCling.cxx:3697
Int_t ReloadAllSharedLibraryMaps() final
Reload the library map entries coming from all the loaded shared libraries, after first unloading the...
Definition TCling.cxx:6071
void UpdateListOfGlobalFunctions() final
No op: see TClingCallbacks (used to update the list of global functions)
Definition TCling.cxx:4004
void DataMemberInfo_Delete(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8753
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:5550
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:4650
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:6212
MethodInfo_t * MethodInfo_FactoryCopy(MethodInfo_t *minfo) const final
Definition TCling.cxx:9208
std::set< const char * > fParsedPayloadsAddresses
Definition TCling.h:123
CallFuncIFacePtr_t CallFunc_IFacePtr(CallFunc_t *func) const final
Definition TCling.cxx:8111
MethodArgInfo_t * MethodArgInfo_Factory() const final
Definition TCling.cxx:9413
static void UpdateClassInfo(char *name, Long_t tagnum)
No op: see TClingCallbacks.
Definition TCling.cxx:6891
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:5163
void ClassInfo_Delete(ClassInfo_t *info) const final
Definition TCling.cxx:8345
std::unique_ptr< cling::Interpreter > fInterpreter
Definition TCling.h:132
EDataType ClassInfo_GetUnderlyingType(ClassInfo_t *info) const final
Definition TCling.cxx:8472
void FuncTempInfo_Delete(FuncTempInfo_t *) const final
Delete the FuncTempInfo_t.
Definition TCling.cxx:8967
bool IsUnsignedIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9728
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:5311
Int_t DeleteVariable(const char *name) final
Undeclare obj called name.
Definition TCling.cxx:3910
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:7246
Longptr_t DataMemberInfo_Offset(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8811
CallFunc_t * CallFunc_Factory() const final
Definition TCling.cxx:8062
MethodInfo_t * MethodInfo_Factory() const final
Definition TCling.cxx:9183
Long_t DataMemberInfo_TypeProperty(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8827
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:7697
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:9607
void Reset() final
Pressing Ctrl+C should forward here.
Definition TCling.cxx:3820
const char * TypedefInfo_TrueName(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9679
int SetClassAutoLoading(int) const final
Enable/Disable the AutoLoading of libraries.
Definition TCling.cxx:7718
const char * ClassInfo_FullName(ClassInfo_t *info) const final
Definition TCling.cxx:8585
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:6515
const char * MethodInfo_TypeName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9312
void CallFunc_SetArg(CallFunc_t *func, Long_t param) const final
Definition TCling.cxx:8127
const char * GetIncludePath() final
Refresh the list of include paths known to the interpreter and return it with -I prepended.
Definition TCling.cxx:7521
void UpdateListsOnUnloaded(const cling::Transaction &T)
Invalidate stored TCling state for declarations included in transaction ‘T’.
Definition TCling.cxx:7001
void UpdateClassInfoWithDecl(const clang::NamedDecl *ND)
Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
Definition TCling.cxx:6833
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:8406
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:4905
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:9122
std::unique_ptr< cling::MetaProcessor > fMetaProcessor
Definition TCling.h:133
bool TypeInfo_IsValid(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9545
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:9321
const char * ClassInfo_Name(ClassInfo_t *info) const final
Definition TCling.cxx:8595
TClass * GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent=kFALSE) final
Generate a TClass for the given class.
Definition TCling.cxx:4688
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:8414
void EndOfLineAction() final
It calls a "fantom" method to synchronize user keyboard input and ROOT prompt line.
Definition TCling.cxx:3225
TypeInfo_t * TypeInfo_FactoryCopy(TypeInfo_t *) const final
Definition TCling.cxx:9529
size_t ClassInfo_AlignOf(ClassInfo_t *info) const final
Definition TCling.cxx:8281
bool ClassInfo_HasMethod(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8422
void ClassInfo_DeleteArray(ClassInfo_t *info, void *arena, bool dtorOnly) const final
Definition TCling.cxx:8360
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:8851
void ShutDown() final
Definition TCling.cxx:1711
void UpdateListOfTypes() final
No op: see TClingCallbacks (used to update the list of types)
Definition TCling.cxx:4011
void * TypeInfo_QualTypePtr(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9593
Long_t TypedefInfo_Property(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9663
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:3681
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:5123
static void UpdateAllCanvases()
Update all canvases at end the terminal input command.
Definition TCling.cxx:6906
Int_t LoadLibraryMap(const char *rootmapfile=nullptr) final
Load map between class and library.
Definition TCling.cxx:5875
Longptr_t BaseClassInfo_Tagnum(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8706
void LibraryUnloaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7132
bool IsPointerType(const void *QualTypePtr) const final
Definition TCling.cxx:9744
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:1084
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition TObject.cxx:425
static TClass * Class()
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1098
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition TObject.cxx:1126
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:1072
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:4034
virtual TString SplitAclicMode(const char *filename, TString &mode, TString &args, TString &io) const
This method split a filename of the form:
Definition TSystem.cxx:4321
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:2504
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:2872
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