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 "llvm/IR/GlobalValue.h"
119#include "llvm/IR/Module.h"
120
121#include "llvm/Support/DynamicLibrary.h"
122#include "llvm/Support/raw_ostream.h"
123#include "llvm/Support/Path.h"
124#include "llvm/Support/Process.h"
125#include "llvm/Object/ELFObjectFile.h"
126#include "llvm/Object/ObjectFile.h"
127#include "llvm/Object/SymbolicFile.h"
128#include "llvm/Support/FileSystem.h"
129
130#include <algorithm>
131#include <iostream>
132#include <cassert>
133#include <map>
134#include <set>
135#include <stdexcept>
136#include <stdint.h>
137#include <fstream>
138#include <sstream>
139#include <string>
140#include <tuple>
141#include <typeinfo>
142#include <unordered_map>
143#include <unordered_set>
144#include <utility>
145#include <vector>
146#include <functional>
147#include <optional>
148
149#ifndef R__WIN32
150#include <cxxabi.h>
151#define R__DLLEXPORT __attribute__ ((visibility ("default")))
152#include <sys/stat.h>
153#endif
154#include <limits.h>
155#include <stdio.h>
156
157#ifdef __APPLE__
158#include <dlfcn.h>
159#include <mach-o/dyld.h>
160#include <mach-o/loader.h>
161#endif // __APPLE__
162
163#ifdef R__UNIX
164#include <dlfcn.h>
165#endif
166
167#if defined(R__LINUX) || defined(R__FBSD)
168# ifndef _GNU_SOURCE
169# define _GNU_SOURCE
170# endif
171# include <link.h> // dl_iterate_phdr()
172#endif
173
174#if defined(__CYGWIN__)
175#include <sys/cygwin.h>
176#define HMODULE void *
177extern "C" {
179 __declspec(dllimport) bool __stdcall EnumProcessModules(void *, void **, unsigned long, unsigned long *);
180 __declspec(dllimport) unsigned long __stdcall GetModuleFileNameExW(void *, void *, wchar_t *, unsigned long);
181}
182#endif
183
184// Fragment copied from LLVM's raw_ostream.cpp
185#if defined(_MSC_VER)
186#ifndef STDIN_FILENO
187# define STDIN_FILENO 0
188#endif
189#ifndef STDOUT_FILENO
190# define STDOUT_FILENO 1
191#endif
192#ifndef STDERR_FILENO
193# define STDERR_FILENO 2
194#endif
195#ifndef R__WIN32
196//#if defined(HAVE_UNISTD_H)
197# include <unistd.h>
198//#endif
199#else
200#include "Windows4Root.h"
201#include <Psapi.h>
202#include <direct.h>
203#undef GetModuleFileName
204#define RTLD_DEFAULT ((void *)::GetModuleHandle(NULL))
205#define dlsym(library, function_name) ::GetProcAddress((HMODULE)library, function_name)
206#define dlopen(library_name, flags) ::LoadLibraryA(library_name)
207#define dlclose(library) ::FreeLibrary((HMODULE)library)
208#define R__DLLEXPORT __declspec(dllexport)
209#endif
210#endif
211
212//______________________________________________________________________________
213// These functions are helpers for debugging issues with non-LLVMDEV builds.
214//
215R__DLLEXPORT clang::DeclContext* TCling__DEBUG__getDeclContext(clang::Decl* D) {
216 return D->getDeclContext();
217}
218R__DLLEXPORT clang::NamespaceDecl* TCling__DEBUG__DCtoNamespace(clang::DeclContext* DC) {
219 return llvm::dyn_cast<clang::NamespaceDecl>(DC);
220}
221R__DLLEXPORT clang::RecordDecl* TCling__DEBUG__DCtoRecordDecl(clang::DeclContext* DC) {
222 return llvm::dyn_cast<clang::RecordDecl>(DC);
223}
224R__DLLEXPORT void TCling__DEBUG__dump(clang::DeclContext* DC) {
225 return DC->dumpDeclContext();
226}
227R__DLLEXPORT void TCling__DEBUG__dump(clang::Decl* D) {
228 return D->dump();
229}
230R__DLLEXPORT void TCling__DEBUG__dump(clang::FunctionDecl* FD) {
231 return FD->dump();
232}
234 return ((clang::Decl*)D)->dump();
235}
237 if (clang::NamedDecl* ND = llvm::dyn_cast<clang::NamedDecl>(D)) {
238 std::string name;
239 {
240 llvm::raw_string_ostream OS(name);
241 ND->getNameForDiagnostic(OS, D->getASTContext().getPrintingPolicy(),
242 true /*Qualified*/);
243 }
244 printf("%s\n", name.c_str());
245 }
246}
247//______________________________________________________________________________
248// These functions are helpers for testing issues directly rather than
249// relying on side effects.
250// This is used for the test for ROOT-7462/ROOT-6070
252 return D->isInvalidDecl();
253}
256 assert(info && info->IsValid());
257 return info->GetDecl()->isInvalidDecl();
258}
259
260using std::string, std::vector;
261using namespace clang;
262using namespace ROOT;
263
264namespace {
265 static const std::string gInterpreterClassDef = R"ICF(
266#undef ClassDef
267#define ClassDef(name, id) \
268_ClassDefInterp_(name,id,virtual,) \
269static int DeclFileLine() { return __LINE__; }
270#undef ClassDefNV
271#define ClassDefNV(name, id) \
272_ClassDefInterp_(name,id,,) \
273static int DeclFileLine() { return __LINE__; }
274#undef ClassDefOverride
275#define ClassDefOverride(name, id) \
276_ClassDefInterp_(name,id,,override) \
277static int DeclFileLine() { return __LINE__; }
278)ICF";
279
280 static const std::string gNonInterpreterClassDef = R"ICF(
281#define __ROOTCLING__ 1
282#undef ClassDef
283#define ClassDef(name,id) \
284_ClassDefOutline_(name,id,virtual,) \
285static int DeclFileLine() { return __LINE__; }
286#undef ClassDefNV
287#define ClassDefNV(name, id)\
288_ClassDefOutline_(name,id,,)\
289static int DeclFileLine() { return __LINE__; }
290#undef ClassDefOverride
291#define ClassDefOverride(name, id)\
292_ClassDefOutline_(name,id,,override)\
293static int DeclFileLine() { return __LINE__; }
294)ICF";
295
296// The macros below use ::Error, so let's ensure it is included
297 static const std::string gClassDefInterpMacro = R"ICF(
298#include "TError.h"
299
300#define _ClassDefInterp_(name,id,virtual_keyword, overrd) \
301private: \
302public: \
303 static TClass *Class() { static TClass* sIsA = 0; if (!sIsA) sIsA = TClass::GetClass(#name); return sIsA; } \
304 static const char *Class_Name() { return #name; } \
305 virtual_keyword Bool_t CheckTObjectHashConsistency() const overrd { return true; } \
306 static Version_t Class_Version() { return id; } \
307 static TClass *Dictionary() { return 0; } \
308 virtual_keyword TClass *IsA() const overrd { return name::Class(); } \
309 virtual_keyword void ShowMembers(TMemberInspector&insp) const overrd { ::ROOT::Class_ShowMembers(name::Class(), this, insp); } \
310 virtual_keyword void Streamer(TBuffer&) overrd { ::Error("Streamer", "Cannot stream interpreted class."); } \
311 void StreamerNVirtual(TBuffer&ClassDef_StreamerNVirtual_b) { name::Streamer(ClassDef_StreamerNVirtual_b); } \
312 static const char *DeclFileName() { return __FILE__; } \
313 static int ImplFileLine() { return 0; } \
314 static const char *ImplFileName() { return __FILE__; }
315)ICF";
316}
318
319// The functions are used to bridge cling/clang/llvm compiled with no-rtti and
320// ROOT (which uses rtti)
321
322////////////////////////////////////////////////////////////////////////////////
323/// Print a StackTrace!
324
325extern "C"
329
330////////////////////////////////////////////////////////////////////////////////
331/// Load a library.
332
333extern "C" int TCling__LoadLibrary(const char *library)
334{
335 return gSystem->Load(library, "", false);
336}
337
338////////////////////////////////////////////////////////////////////////////////
339/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
340
341extern "C" void TCling__RestoreInterpreterMutex(void *delta)
342{
343 ((TCling*)gCling)->ApplyToInterpreterMutex(delta);
344}
345
346////////////////////////////////////////////////////////////////////////////////
347/// Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name,
348/// which is extracted by error messages we get from callback from cling. Return true
349/// when the missing library was autoloaded.
350
351extern "C" bool TCling__LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
352{
353 return ((TCling*)gCling)->LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
354}
355
356////////////////////////////////////////////////////////////////////////////////
357/// Reset the interpreter lock to the state it had before interpreter-related
358/// calls happened.
359
361{
362 return ((TCling*)gCling)->RewindInterpreterMutex();
363}
364
365////////////////////////////////////////////////////////////////////////////////
366/// Lock the interpreter.
367
369{
370 if (gInterpreterMutex) {
372 }
373 return nullptr;
374}
375
376////////////////////////////////////////////////////////////////////////////////
377/// Unlock the interpreter.
378
380{
381 if (gInterpreterMutex) {
383 }
384}
385
386////////////////////////////////////////////////////////////////////////////////
387/// Update TClingClassInfo for a class (e.g. upon seeing a definition).
388
390{
391 static Bool_t entered = kFALSE;
394
395 if (entered) topLevel = kFALSE;
396 else {
397 entered = kTRUE;
398 topLevel = kTRUE;
399 }
400 if (topLevel) {
401 ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(TD);
402 } else {
403 // If we are called indirectly from within another call to
404 // TCling::UpdateClassInfo, we delay the update until the dictionary loading
405 // is finished (i.e. when we return to the top level TCling::UpdateClassInfo).
406 // This allows for the dictionary to be fully populated when we actually
407 // update the TClass object. The updating of the TClass sometimes
408 // (STL containers and when there is an emulated class) forces the building
409 // of the TClass object's real data (which needs the dictionary info).
410 updateList.push_back(TD);
411 }
412 if (topLevel) {
413 while (!updateList.empty()) {
414 ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(updateList.back());
415 updateList.pop_back();
416 }
417 entered = kFALSE;
418 }
419}
420
422 const clang::Decl* D = static_cast<const clang::Decl*>(enumObj->GetDeclId());
423 if(const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
424 // Add the constants to the enum type.
425 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
426 EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
427 // Get name of the enum type.
428 std::string constbuf;
429 if (const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
430 PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
431 llvm::raw_string_ostream stream(constbuf);
432 // Don't trigger fopen of the source file to count lines:
433 Policy.AnonymousTagLocations = false;
434 (END)->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
435 }
436 const char* constantName = constbuf.c_str();
437
438 // Get value of the constant.
440 const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
441 if (valAPSInt.isSigned()) {
442 value = valAPSInt.getSExtValue();
443 } else {
444 value = valAPSInt.getZExtValue();
445 }
446
447 // Create the TEnumConstant or update it if existing
448 TEnumConstant* enumConstant = nullptr;
449 TClingClassInfo* tcCInfo = (TClingClassInfo*)(cl ? cl->GetClassInfo() : nullptr);
452 if (TObject* encAsTObj = enumObj->GetConstants()->FindObject(constantName)){
453 ((TEnumConstant*)encAsTObj)->Update(dmInfo);
454 } else {
456 }
457
458 // Add the global constants to the list of Globals.
459 if (!cl) {
460 TCollection* globals = gROOT->GetListOfGlobals(false);
461 if (!globals->FindObject(constantName)) {
462 globals->Add(enumConstant);
463 }
464 }
465 }
466 }
467}
468
470{
471 // Handle new enum declaration for either global and nested enums.
472
473 // Create the enum type.
474 TEnum* enumType = nullptr;
475 const clang::Decl* D = static_cast<const clang::Decl*>(VD);
476 std::string buf;
477 if (const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
478 // Get name of the enum type.
479 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
480 llvm::raw_string_ostream stream(buf);
481 // Don't trigger fopen of the source file to count lines:
482 Policy.AnonymousTagLocations = false;
483 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
484 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
485 }
486 if (buf.empty()) {
487 return nullptr;
488 }
489 const char* name = buf.c_str();
490 enumType = new TEnum(name, VD, cl);
492
493 return enumType;
494}
495
496void TCling::HandleNewDecl(const void* DV, bool isDeserialized, std::set<TClass*> &modifiedTClasses) {
497 // Handle new declaration.
498 // Record the modified class, struct and namespaces in 'modifiedTClasses'.
499
500 const clang::Decl* D = static_cast<const clang::Decl*>(DV);
501
502 if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
503 && !dyn_cast<clang::RecordDecl>(D)) return;
504
505 if (isa<clang::FunctionDecl>(D->getDeclContext())
506 || isa<clang::TagDecl>(D->getDeclContext()))
507 return;
508
509 // Don't list templates.
510 if (const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
511 if (RD->getDescribedClassTemplate())
512 return;
513 } else if (const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
514 if (FD->getDescribedFunctionTemplate())
515 return;
516 }
517
518 if (const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
519 if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
521 }
522 else if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
523
524 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
525 // Mostly just for EnumDecl (the other TagDecl are handled
526 // by the 'RecordDecl' if statement.
528 } else if (const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
530 }
531
532 // We care about declarations on the global scope.
533 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
534 return;
535
536 // Enums are lazyly created, thus we don not need to handle them here.
537 if (isa<EnumDecl>(ND))
538 return;
539
540 // ROOT says that global is enum(lazylycreated)/var/field declared on the global
541 // scope.
542 if (!(isa<VarDecl>(ND)))
543 return;
544
545 // Skip if already in the list.
546 if (gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
547 return;
548
549 // Put the global constants and global enums in the corresponding lists.
550 gROOT->GetListOfGlobals()->Add(new TGlobal((DataMemberInfo_t *)
552 cast<ValueDecl>(ND), nullptr)));
553 }
554}
555
556extern "C"
558{
559 // We are sure in this context of the type of the interpreter
560 normCtxt = &( (TCling*) gInterpreter)->GetNormalizedContext();
561}
562
563extern "C"
564void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter*) {
565 ((TCling*)gCling)->UpdateListsOnCommitted(T);
566}
567
568extern "C"
569void TCling__UpdateListsOnUnloaded(const cling::Transaction &T) {
570 ((TCling*)gCling)->UpdateListsOnUnloaded(T);
571}
572
573extern "C"
574void TCling__InvalidateGlobal(const clang::Decl *D) {
575 ((TCling*)gCling)->InvalidateGlobal(D);
576}
577
578extern "C"
579void TCling__TransactionRollback(const cling::Transaction &T) {
580 ((TCling*)gCling)->TransactionRollback(T);
581}
582
583extern "C" void TCling__LibraryLoadedRTTI(const void* dyLibHandle,
584 const char* canonicalName) {
585 ((TCling*)gCling)->LibraryLoaded(dyLibHandle, canonicalName);
586}
587
588extern "C" void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
589{
590 ((TCling *)gCling)->RegisterRdictForLoadPCM(pcmFileNameFullPath, pcmContent);
591}
592
593extern "C" void TCling__LibraryUnloadedRTTI(const void* dyLibHandle,
594 const char* canonicalName) {
595 ((TCling*)gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
596}
597
598
599extern "C"
600TObject* TCling__GetObjectAddress(const char *Name, void *&LookupCtx) {
601 return ((TCling*)gCling)->GetObjectAddress(Name, LookupCtx);
602}
603
604extern "C" const Decl* TCling__GetObjectDecl(TObject *obj) {
605 return ((TClingClassInfo*)obj->IsA()->GetClassInfo())->GetDecl();
606}
607
609 const char* argv[])
610{
611 auto tcling = new TCling("C++", "cling C++ Interpreter", argv, interpLibHandle);
612
613 return tcling;
614}
615
617{
618 delete interp;
619}
620
621// Load library containing specified class. Returns 0 in case of error
622// and 1 in case if success.
623extern "C" int TCling__AutoLoadCallback(const char* className)
624{
625 return ((TCling*)gCling)->AutoLoad(className);
626}
627
628extern "C" int TCling__AutoParseCallback(const char* className)
629{
630 return ((TCling*)gCling)->AutoParse(className);
631}
632
633extern "C" const char* TCling__GetClassSharedLibs(const char* className, bool skipCore)
634{
635 return ((TCling*)gCling)->GetClassSharedLibs(className, skipCore);
636}
637
638// Returns 0 for failure 1 for success
639extern "C" int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* nsDecl)
640{
641 return ((TCling*)gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
642}
643
644extern "C" int TCling__CompileMacro(const char *fileName, const char *options)
645{
646 string file(fileName);
647 string opt(options);
648 return gSystem->CompileMacro(file.c_str(), opt.c_str());
649}
650
651extern "C" void TCling__SplitAclicMode(const char* fileName, string &mode,
652 string &args, string &io, string &fname)
653{
654 string file(fileName);
655 TString f, amode, arguments, aclicio;
656 f = gSystem->SplitAclicMode(file.c_str(), amode, arguments, aclicio);
657 mode = amode.Data(); args = arguments.Data();
658 io = aclicio.Data(); fname = f.Data();
659}
660
661//______________________________________________________________________________
662//
663//
664//
665
666#ifdef R__WIN32
667extern "C" {
668 char *__unDName(char *demangled, const char *mangled, int out_len,
669 void * (* pAlloc )(size_t), void (* pFree )(void *),
670 unsigned short int flags);
671}
672#endif
673
674////////////////////////////////////////////////////////////////////////////////
675/// Find a template decl within N nested namespaces, 0<=N<inf
676/// Assumes 1 and only 1 template present and 1 and only 1 entity contained
677/// by the namespace. Example: `ns1::ns2::..::%nsN::%myTemplate`
678/// Returns nullptr in case of error
679
680static clang::ClassTemplateDecl* FindTemplateInNamespace(clang::Decl* decl)
681{
682 using namespace clang;
683 if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
684 return FindTemplateInNamespace(*nsd->decls_begin());
685 }
686
687 if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
688 return ctd;
689 }
690
691 return nullptr; // something went wrong.
692}
693
694//______________________________________________________________________________
695//
696//
697//
698
699int TCling_GenerateDictionary(const std::vector<std::string> &classes,
700 const std::vector<std::string> &headers,
701 const std::vector<std::string> &fwdDecls,
702 const std::vector<std::string> &unknown)
703{
704 //This function automatically creates the "LinkDef.h" file for templated
705 //classes then executes CompileMacro on it.
706 //The name of the file depends on the class name, and it's not generated again
707 //if the file exist.
708 if (classes.empty()) {
709 return 0;
710 }
711 // Use the name of the first class as the main name.
712 const std::string& className = classes[0];
713 //(0) prepare file name
714 TString fileName = "AutoDict_";
715 std::string::const_iterator sIt;
716 for (sIt = className.begin(); sIt != className.end(); ++sIt) {
717 if (*sIt == '<' || *sIt == '>' ||
718 *sIt == ' ' || *sIt == '*' ||
719 *sIt == ',' || *sIt == '&' ||
720 *sIt == ':') {
721 fileName += '_';
722 }
723 else {
724 fileName += *sIt;
725 }
726 }
727 if (classes.size() > 1) {
728 Int_t chk = 0;
729 std::vector<std::string>::const_iterator it = classes.begin();
730 while ((++it) != classes.end()) {
731 for (UInt_t cursor = 0; cursor != it->length(); ++cursor) {
732 chk = chk * 3 + it->at(cursor);
733 }
734 }
735 fileName += TString::Format("_%u", chk);
736 }
737 fileName += ".cxx";
738 if (gSystem->AccessPathName(fileName) != 0) {
739 //file does not exist
740 //(1) prepare file data
741 // If STL, also request iterators' operators.
742 // vector is special: we need to check whether
743 // vector::iterator is a typedef to pointer or a
744 // class.
745 static const std::set<std::string> sSTLTypes {
746 "vector","list","forward_list","deque","map","unordered_map","multimap",
747 "unordered_multimap","set","unordered_set","multiset","unordered_multiset",
748 "queue","priority_queue","stack","iterator"};
749 std::vector<std::string>::const_iterator it;
750 std::string fileContent("");
751 for (it = headers.begin(); it != headers.end(); ++it) {
752 fileContent += "#include \"" + *it + "\"\n";
753 }
754 for (it = unknown.begin(); it != unknown.end(); ++it) {
755 TClass* cl = TClass::GetClass(it->c_str());
756 if (cl && cl->GetDeclFileName()) {
757 TString header = gSystem->BaseName(cl->GetDeclFileName());
760 while (dirbase.Length() && dirbase != "."
761 && dirbase != "include" && dirbase != "inc"
762 && dirbase != "prec_stl") {
764 dir = gSystem->GetDirName(dir);
765 }
766 fileContent += TString("#include \"") + header + "\"\n";
767 }
768 }
769 for (it = fwdDecls.begin(); it != fwdDecls.end(); ++it) {
770 fileContent += "class " + *it + ";\n";
771 }
772 fileContent += "#ifdef __CLING__ \n";
773 fileContent += "#pragma link C++ nestedclasses;\n";
774 fileContent += "#pragma link C++ nestedtypedefs;\n";
775 for (it = classes.begin(); it != classes.end(); ++it) {
776 std::string n(*it);
777 size_t posTemplate = n.find('<');
778 std::set<std::string>::const_iterator iSTLType = sSTLTypes.end();
779 if (posTemplate != std::string::npos) {
780 n.erase(posTemplate, std::string::npos);
781 if (n.compare(0, 5, "std::") == 0) {
782 n.erase(0, 5);
783 }
784 iSTLType = sSTLTypes.find(n);
785 }
786 fileContent += "#pragma link C++ class ";
787 fileContent += *it + "+;\n" ;
788 if (iSTLType == sSTLTypes.end()) {
789 // Not an STL class; we need to allow the I/O of contained
790 // classes (now that we have a dictionary for them).
791 fileContent += "#pragma link C++ class " + *it + "::*+;\n" ;
792 }
793 }
794 fileContent += "#endif\n";
795 //end(1)
796 //(2) prepare the file
798 filePointer = fopen(fileName, "w");
799 if (filePointer == nullptr) {
800 //can't open a file
801 return 1;
802 }
803 //end(2)
804 //write data into the file
805 fprintf(filePointer, "%s", fileContent.c_str());
807 }
808 //(3) checking if we can compile a macro, if not then cleaning
810 gErrorIgnoreLevel = kWarning; // no "Info: creating library..."
811 Int_t ret = gSystem->CompileMacro(fileName, "k");
813 if (ret == 0) { //can't compile a macro
814 return 2;
815 }
816 //end(3)
817 return 0;
818}
819
820int TCling_GenerateDictionary(const std::string& className,
821 const std::vector<std::string> &headers,
822 const std::vector<std::string> &fwdDecls,
823 const std::vector<std::string> &unknown)
824{
825 //This function automatically creates the "LinkDef.h" file for templated
826 //classes then executes CompileMacro on it.
827 //The name of the file depends on the class name, and it's not generated again
828 //if the file exist.
829 std::vector<std::string> classes;
830 classes.push_back(className);
832}
833
834//______________________________________________________________________________
835//
836//
837//
838
839// It is a "fantom" method to synchronize user keyboard input
840// and ROOT prompt line (for WIN32)
841const char* fantomline = "TRint::EndOfLineAction();";
842
843//______________________________________________________________________________
844//
845//
846//
847
848void* TCling::fgSetOfSpecials = nullptr;
849
850//______________________________________________________________________________
851//
852// llvm error handler through exceptions; see also cling/UserInterface
853//
854namespace {
855 // Handle fatal llvm errors by throwing an exception.
856 // Yes, throwing exceptions in error handlers is bad.
857 // Doing nothing is pretty terrible, too.
858 void exceptionErrorHandler(void * /*user_data*/,
859 const char *reason,
860 bool /*gen_crash_diag*/) {
861 throw std::runtime_error(std::string(">>> Interpreter compilation error:\n") + reason);
862 }
863}
864
865//______________________________________________________________________________
866//
867//
868//
869
870////////////////////////////////////////////////////////////////////////////////
871
872namespace{
873 // An instance of this class causes the diagnostics of clang to be suppressed
874 // during its lifetime
875 class clangDiagSuppr {
876 public:
877 clangDiagSuppr(clang::DiagnosticsEngine& diag): fDiagEngine(diag){
878 fOldDiagValue = fDiagEngine.getIgnoreAllWarnings();
879 fDiagEngine.setIgnoreAllWarnings(true);
880 }
881
883 fDiagEngine.setIgnoreAllWarnings(fOldDiagValue);
884 }
885 private:
886 clang::DiagnosticsEngine& fDiagEngine;
887 bool fOldDiagValue;
888 };
889
890}
891
892////////////////////////////////////////////////////////////////////////////////
893/// Allow calling autoparsing from TMetaUtils
895{
896 return gCling->AutoParse(cname);
897}
898
899////////////////////////////////////////////////////////////////////////////////
900/// Try hard to avoid looking up in the Cling database as this could enduce
901/// an unwanted autoparsing.
902
904 std::string &result)
905{
906 result.clear();
907
908 unsigned long offset = 0;
909 if (strncmp(tname.c_str(), "const ", 6) == 0) {
910 offset = 6;
911 }
912 unsigned long end = tname.length();
913 while( end && (tname[end-1]=='&' || tname[end-1]=='*' || tname[end-1]==']') ) {
914 if ( tname[end-1]==']' ) {
915 --end;
916 while ( end && tname[end-1]!='[' ) --end;
917 }
918 --end;
919 }
920 std::string innerbuf;
921 const char *inner;
922 if (end != tname.length()) {
923 innerbuf = tname.substr(offset,end-offset);
924 inner = innerbuf.c_str();
925 } else {
926 inner = tname.c_str()+offset;
927 }
928
929 //if (strchr(tname.c_str(),'[')!=0) fprintf(stderr,"DEBUG: checking on %s vs %s %lu %lu\n",tname.c_str(),inner,offset,end);
930 if (gROOT->GetListOfClasses()->FindObject(inner)
932 // This is a known class.
933 return true;
934 }
935
936 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
937 TDataType *type = (TDataType *)typeTable->THashTable::FindObject( inner );
938 if (type) {
939 // This is a raw type and an already loaded typedef.
940 const char *newname = type->GetFullTypeName();
941 if (type->GetType() == kLong64_t) {
942 newname = "Long64_t";
943 } else if (type->GetType() == kULong64_t) {
944 newname = "ULong64_t";
945 }
946 if (strcmp(inner,newname) == 0) {
947 return true;
948 }
949 if (offset) result = "const ";
950 result += newname;
951 if ( end != tname.length() ) {
952 result += tname.substr(end,tname.length()-end);
953 }
954 if (result == tname) result.clear();
955 return true;
956 }
957
958 // Check if the name is an enumerator
960 if (lastPos != inner) // Main switch: case 1 - scoped enum, case 2 global enum
961 {
962 // We have a scope
963 const auto enName = lastPos;
964 const auto scopeNameSize = (lastPos - inner) / sizeof(decltype(*lastPos)) - 2;
965 std::string scopeName{inner, scopeNameSize};
966 // Check if the scope is in the list of classes
967 if (auto scope = static_cast<TClass *>(gROOT->GetListOfClasses()->FindObject(scopeName.c_str()))) {
968 auto enumTable = dynamic_cast<const THashList *>(scope->GetListOfEnums(false));
969 if (enumTable && enumTable->THashList::FindObject(enName))
970 return true;
971 }
972 // It may still be in one of the loaded protoclasses
973 else if (auto scope = static_cast<TProtoClass *>(gClassTable->GetProtoNorm(scopeName.c_str()))) {
974 auto listOfEnums = scope->GetListOfEnums();
975 if (listOfEnums) { // it could be null: no enumerators in the protoclass
976 auto enumTable = dynamic_cast<const THashList *>(listOfEnums);
977 if (enumTable && enumTable->THashList::FindObject(enName))
978 return true;
979 }
980 }
981 } else
982 {
983 // We don't have any scope: this could only be a global enum
984 auto enumTable = dynamic_cast<const THashList *>(gROOT->GetListOfEnums());
985 if (enumTable && enumTable->THashList::FindObject(inner)) return true;
986 }
987
989 {
990 // This is a class name.
991 return true;
992 }
993
994 return false;
995}
996
997////////////////////////////////////////////////////////////////////////////////
998
1003
1004////////////////////////////////////////////////////////////////////////////////
1005
1007{
1008 return fContent.c_str();
1009}
1010
1011////////////////////////////////////////////////////////////////////////////////
1012/// Append string to the storage if not added already.
1013
1014inline bool TCling::TUniqueString::Append(const std::string& str)
1015{
1016 bool notPresent = fLinesHashSet.emplace(fHashFunc(str)).second;
1017 if (notPresent){
1018 fContent+=str;
1019 }
1020 return notPresent;
1021}
1022
1023std::string TCling::ToString(const char* type, void* obj)
1024{
1025 return fInterpreter->toString(type, obj);
1026}
1027
1028////////////////////////////////////////////////////////////////////////////////
1029///\returns true if the module was loaded.
1030static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
1031{
1032 // When starting up ROOT, cling would load all modulemap files on the include
1033 // paths. However, in a ROOT session, it is very common to run aclic which
1034 // will invoke rootcling and possibly produce a modulemap and a module in
1035 // the current folder.
1036 //
1037 // Before failing, try loading the modulemap in the current folder and try
1038 // loading the requested module from it.
1039 std::string currentDir = gSystem->WorkingDirectory();
1040 assert(!currentDir.empty());
1042 if (gDebug > 2)
1043 ::Info("TCling::__LoadModule", "Preloading module %s. \n",
1044 ModuleName.c_str());
1045
1046 return interp.loadModule(ModuleName, /*Complain=*/true);
1047}
1048
1049////////////////////////////////////////////////////////////////////////////////
1050/// Loads the C++ modules that we require to run any ROOT program. This is just
1051/// supposed to make a C++ module from a modulemap available to the interpreter.
1052static void LoadModules(const std::vector<std::string> &modules, cling::Interpreter &interp)
1053{
1054 for (const auto &modName : modules)
1056}
1057
1058static bool IsFromRootCling() {
1059 // rootcling also uses TCling for generating the dictionary ROOT files.
1060 const static bool foundSymbol = dlsym(RTLD_DEFAULT, "usedToIdentifyRootClingByDlSym");
1061 return foundSymbol;
1062}
1063
1064/// Checks if there is an ASTFile on disk for the given module \c M.
1065static bool HasASTFileOnDisk(clang::Module *M, const clang::Preprocessor &PP, std::string *FullFileName = nullptr)
1066{
1067 const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1068
1069 std::string ModuleFileName;
1070 if (!HSOpts.PrebuiltModulePaths.empty())
1071 // Load the module from *only* in the prebuilt module path.
1072 ModuleFileName = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(M->Name);
1073 if (FullFileName)
1075
1076 return !ModuleFileName.empty();
1077}
1078
1079static bool HaveFullGlobalModuleIndex = false;
1081{
1082 CompilerInstance &CI = *interp.getCI();
1083 Preprocessor &PP = CI.getPreprocessor();
1084 auto ModuleManager = CI.getASTReader();
1086 // StringRef ModuleIndexPath = HSI.getModuleCachePath();
1087 // HeaderSearch& HSI = PP.getHeaderSearchInfo();
1088 // HSI.setModuleCachePath(TROOT::GetSharedLibDir().Data());
1089 std::string ModuleIndexPath = TROOT::GetSharedLibDir().Data();
1090 if (ModuleIndexPath.empty())
1091 return nullptr;
1092 // Get an existing global index. This loads it if not already loaded.
1093 ModuleManager->resetForReload();
1094 ModuleManager->loadGlobalIndex();
1095 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1096
1097 // For finding modules needing to be imported for fixit messages,
1098 // we need to make the global index cover all modules, so we do that here.
1100 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1101 bool RecreateIndex = false;
1102 for (ModuleMap::module_iterator I = MMap.module_begin(), E = MMap.module_end(); I != E; ++I) {
1103 Module *TheModule = I->second;
1104 // We want the index only of the prebuilt modules.
1106 continue;
1107 LoadModule(TheModule->Name, interp);
1108 RecreateIndex = true;
1109 }
1110 if (RecreateIndex) {
1111 cling::Interpreter::PushTransactionRAII deserRAII(&interp);
1112 clang::GlobalModuleIndex::UserDefinedInterestingIDs IDs;
1113
1114 struct DefinitionFinder : public RecursiveASTVisitor<DefinitionFinder> {
1115 DefinitionFinder(clang::GlobalModuleIndex::UserDefinedInterestingIDs& IDs,
1116 clang::TranslationUnitDecl* TU) : DefinitionIDs(IDs) {
1118 }
1119 bool VisitNamedDecl(NamedDecl *ND) {
1120 if (!ND->isFromASTFile())
1121 return true;
1122 if (!ND->getIdentifier())
1123 return true;
1124
1125 if (ND->getAccess() == AS_protected || ND->getAccess() == AS_private)
1126 return true;
1127
1128 if (TagDecl *TD = llvm::dyn_cast<TagDecl>(ND)) {
1129 if (TD->isCompleteDefinition())
1130 Register(TD);
1131 } else if (NamespaceDecl *NSD = llvm::dyn_cast<NamespaceDecl>(ND)) {
1132 Register(NSD, /*AddSingleEntry=*/ false);
1133 }
1135 Register(TND);
1136 // FIXME: Add the rest...
1137 return true; // continue decending
1138 }
1139 private:
1140 clang::GlobalModuleIndex::UserDefinedInterestingIDs &DefinitionIDs;
1141 void Register(const NamedDecl* ND, bool AddSingleEntry = true) {
1142 assert(ND->isFromASTFile());
1143 // FIXME: All decls should have an owning module once rootcling
1144 // updates its generated decls from within the LookupHelper & co.
1145 if (!ND->hasOwningModule()) {
1146#ifndef NDEBUG
1147 SourceManager &SM = ND->getASTContext().getSourceManager();
1148 SourceLocation Loc = ND->getLocation();
1149 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
1150 (void)FE;
1151 assert(FE->getName().contains("input_line_"));
1152#endif
1153 return;
1154 }
1155
1156 Module *OwningModule = ND->getOwningModule()->getTopLevelModule();
1158 assert(!ND->getName().empty() && "Empty name");
1159 if (AddSingleEntry && DefinitionIDs.count(ND->getName()))
1160 return;
1161 // FIXME: The FileEntry in not stable to serialize.
1162 // FIXME: We might end up with many times with the same module.
1163 // FIXME: We might end up two modules containing a definition.
1164 // FIXME: What do we do if no definition is found.
1165 DefinitionIDs[ND->getName()].push_back(OwningModule->getASTFile());
1166 }
1167 };
1168 DefinitionFinder defFinder(IDs, CI.getASTContext().getTranslationUnitDecl());
1169
1170 llvm::cantFail(GlobalModuleIndex::writeIndex(CI.getFileManager(),
1171 CI.getPCHContainerReader(),
1173 &IDs));
1174 ModuleManager->resetForReload();
1175 ModuleManager->loadGlobalIndex();
1176 GlobalIndex = ModuleManager->getGlobalIndex();
1177 }
1179 }
1180 return GlobalIndex;
1181}
1182
1183static void RegisterCxxModules(cling::Interpreter &clingInterp)
1184{
1185 if (!clingInterp.getCI()->getLangOpts().Modules)
1186 return;
1187
1188 // Loading of a module might deserialize.
1189 cling::Interpreter::PushTransactionRAII deserRAII(&clingInterp);
1190
1191 // Setup core C++ modules if we have any to setup.
1192
1193 // Load libc and stl first.
1194 // Load vcruntime module for windows
1195#ifdef R__WIN32
1196 LoadModule("vcruntime", clingInterp);
1197 LoadModule("services", clingInterp);
1198#endif
1199
1200#ifdef R__MACOSX
1201 LoadModule("Darwin", clingInterp);
1202#else
1203 LoadModule("libc", clingInterp);
1204#endif
1205 LoadModule("std", clingInterp);
1206
1207 LoadModule("_Builtin_intrinsics", clingInterp);
1208
1209 // Load core modules
1210 // This should be vector in order to be able to pass it to LoadModules
1211 std::vector<std::string> CoreModules = {"ROOT_Foundation_C",
1212 "ROOT_Config",
1213 "ROOT_Rtypes",
1214 "ROOT_Foundation_Stage1_NoRTTI",
1215 "Core",
1216 "Rint",
1217 "RIO"};
1218
1220
1221 // Take this branch only from ROOT because we don't need to preload modules in rootcling
1222 if (!IsFromRootCling()) {
1223 std::vector<std::string> CommonModules = {"MathCore"};
1225
1226 // These modules should not be preloaded but they fix issues.
1227 // FIXME: Hist is not a core module but is very entangled to MathCore and
1228 // causes issues.
1229 std::vector<std::string> FIXMEModules = {"Hist"};
1230 clang::CompilerInstance &CI = *clingInterp.getCI();
1231 clang::Preprocessor &PP = CI.getPreprocessor();
1232 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1233 if (MMap.findModule("RInterface"))
1234 FIXMEModules.push_back("RInterface");
1235
1237
1238 GlobalModuleIndex *GlobalIndex = nullptr;
1240 // FIXME: The ASTReader still calls loadGlobalIndex and loads the file
1241 // We should investigate how to suppress it completely.
1242 GlobalIndex = CI.getASTReader()->getGlobalIndex();
1243
1244 llvm::StringSet<> KnownModuleFileNames;
1245 if (GlobalIndex)
1246 GlobalIndex->getKnownModuleFileNames(KnownModuleFileNames);
1247
1248 std::vector<std::string> PendingModules;
1249 PendingModules.reserve(256);
1250 for (auto I = MMap.module_begin(), E = MMap.module_end(); I != E; ++I) {
1251 clang::Module *M = I->second;
1252 assert(M);
1253
1254 // We want to load only already created modules.
1255 std::string FullASTFilePath;
1257 continue;
1258
1260 continue;
1261
1262 if (M->IsUnimportable)
1263 continue;
1264
1265 if (GlobalIndex)
1266 LoadModule(M->Name, clingInterp);
1267 else {
1268 // FIXME: We may be able to remove those checks as cling::loadModule
1269 // checks if a module was alredy loaded.
1270 if (std::find(CoreModules.begin(), CoreModules.end(), M->Name) != CoreModules.end())
1271 continue; // This is a core module which was already loaded.
1272
1273 // Load system modules now and delay the other modules after we have
1274 // loaded all system ones.
1275 if (M->IsSystem)
1276 LoadModule(M->Name, clingInterp);
1277 else
1278 PendingModules.push_back(M->Name);
1279 }
1280 }
1282 }
1283
1284 // Check that the gROOT macro was exported by any core module.
1285 assert(clingInterp.getMacro("gROOT") && "Couldn't load gROOT macro?");
1286
1287 // `ERROR` and `PI` are from loading R related modules, which conflict with
1288 // user's code.
1289 clingInterp.declare(R"CODE(
1290#ifdef PI
1291# undef PI
1292#endif
1293#ifdef ERROR
1294# undef ERROR
1295#endif
1296 )CODE");
1297}
1298
1299static void RegisterPreIncludedHeaders(cling::Interpreter &clingInterp)
1300{
1301 std::string PreIncludes;
1302 bool hasCxxModules = clingInterp.getCI()->getLangOpts().Modules;
1303
1304 // For the list to also include string, we have to include it now.
1305 // rootcling does parts already if needed, e.g. genreflex does not want using
1306 // namespace std.
1307 if (IsFromRootCling()) {
1308 PreIncludes += "#include \"RtypesCore.h\"\n";
1309 } else {
1310 if (!hasCxxModules)
1311 PreIncludes += "#include \"Rtypes.h\"\n";
1312
1314 + gInterpreterClassDef + "\n"
1315 "#undef ClassImp\n"
1316 "#define ClassImp(X);\n";
1317 }
1318 if (!hasCxxModules)
1319 PreIncludes += "#include <string>\n";
1320
1321 // We must include it even when we have modules because it is marked as
1322 // textual in the modulemap due to the nature of the assert header.
1323#ifndef R__WIN32
1324 PreIncludes += "#include <cassert>\n";
1325#endif
1326 PreIncludes += "using namespace std;\n";
1327 clingInterp.declare(PreIncludes);
1328}
1329
1330////////////////////////////////////////////////////////////////////////////////
1331/// Initialize the cling interpreter interface.
1332/// \param name name for TInterpreter
1333/// \param title title for TInterpreter
1334/// \param argv - array of arguments passed to the cling::Interpreter constructor
1335/// e.g. `-DFOO=bar`. The last element of the array must be `nullptr`.
1336
1337TCling::TCling(const char *name, const char *title, const char* const argv[], void *interpLibHandle)
1338: TInterpreter(name, title), fGlobalsListSerial(-1), fMapfile(nullptr),
1340 fPrevLoadedDynLibInfo(nullptr), fClingCallbacks(nullptr), fAutoLoadCallBack(nullptr),
1342{
1343 fPrompt[0] = 0;
1344 const bool fromRootCling = IsFromRootCling();
1345
1346 fCxxModulesEnabled = false;
1347#ifdef R__USE_CXXMODULES
1348 fCxxModulesEnabled = true;
1349#endif
1350
1351 llvm::install_fatal_error_handler(&exceptionErrorHandler);
1352
1353 fTemporaries = new std::vector<cling::Value>();
1354
1355 std::vector<std::string> clingArgsStorage;
1356 clingArgsStorage.push_back("cling4root");
1357 for (const char* const* arg = argv; *arg; ++arg)
1358 clingArgsStorage.push_back(*arg);
1359
1360 // rootcling sets its arguments through TROOT::GetExtraInterpreterArgs().
1361 if (!fromRootCling) {
1363
1364 // Add -I early so ASTReader can find the headers.
1365 std::string interpInclude(TROOT::GetEtcDir().Data());
1366 clingArgsStorage.push_back("-I" + interpInclude);
1367
1368 // Add include path to etc/cling.
1369 clingArgsStorage.push_back("-I" + interpInclude + "/cling");
1370
1371 // Add include path to etc/cling.
1372 clingArgsStorage.push_back("-I" + interpInclude + "/cling/plugins/include");
1373
1374 // Add the root include directory and etc/ to list searched by default.
1375 clingArgsStorage.push_back(std::string(("-I" + TROOT::GetIncludeDir()).Data()));
1376
1377 // Add the current path to the include path
1378 // TCling::AddIncludePath(".");
1379
1380 // Attach the PCH (unless we have C++ modules enabled which provide the
1381 // same functionality).
1382 if (!fCxxModulesEnabled) {
1383 std::string pchFilename = interpInclude + "/allDict.cxx.pch";
1384 if (gSystem->Getenv("ROOT_PCH")) {
1385 pchFilename = gSystem->Getenv("ROOT_PCH");
1386 }
1387
1388 clingArgsStorage.push_back("-include-pch");
1389 clingArgsStorage.push_back(pchFilename);
1390 }
1391
1392 clingArgsStorage.push_back("-Wno-undefined-inline");
1393 clingArgsStorage.push_back("-fsigned-char");
1394 // The -O1 optimization flag has nasty side effects on Windows (32 and 64 bit)
1395 // See the GitHub issues #9809 and #9944
1396 // TODO: to be reviewed after the upgrade of LLVM & Clang
1397#ifndef _MSC_VER
1398 clingArgsStorage.push_back("-O1");
1399 // Disable optimized register allocation which is turned on automatically
1400 // by -O1, but seems to require -O2 to not explode in run time.
1401 clingArgsStorage.push_back("-mllvm");
1402 clingArgsStorage.push_back("-optimize-regalloc=0");
1403#endif
1404 }
1405
1406 // Process externally passed arguments if present.
1407 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv("EXTRA_CLING_ARGS");
1408 if (EnvOpt.has_value()) {
1410 while (!Env.empty()) {
1411 StringRef Arg;
1412 std::tie(Arg, Env) = Env.split(' ');
1413 clingArgsStorage.push_back(Arg.str());
1414 }
1415 }
1416
1417 auto GetEnvVarPath = [](const std::string &EnvVar, std::vector<std::string> &Paths) {
1418 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1419 if (EnvOpt.has_value()) {
1421 while (!Env.empty()) {
1422 StringRef Arg;
1423 std::tie(Arg, Env) = Env.split(ROOT::FoundationUtils::GetEnvPathSeparator());
1424 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1425 Paths.push_back(Arg.str());
1426 }
1427 }
1428 };
1429
1430 if (fCxxModulesEnabled) {
1431 std::vector<std::string> Paths;
1432 // ROOT usually knows better where its libraries are. This way we can
1433 // discover modules without having to should thisroot.sh and should fix
1434 // gnuinstall.
1435 Paths.push_back(TROOT::GetSharedLibDir().Data());
1436 GetEnvVarPath("CLING_PREBUILT_MODULE_PATH", Paths);
1437 std::string EnvVarPath;
1438 for (const std::string& P : Paths)
1440 // FIXME: We should make cling -fprebuilt-module-path work.
1441 gSystem->Setenv("CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1442 }
1443
1444 // FIXME: This only will enable frontend timing reports.
1445 EnvOpt = llvm::sys::Process::GetEnv("ROOT_CLING_TIMING");
1446 if (EnvOpt.has_value())
1447 clingArgsStorage.push_back("-ftime-report");
1448
1449 // Add the overlay file. Note that we cannot factor it out for both root
1450 // and rootcling because rootcling activates modules only if -cxxmodule
1451 // flag is passed.
1453 // For now we prefer rootcling to enumerate explicitly its modulemaps.
1454 std::vector<std::string> ModuleMaps;
1455 std::string ModuleMapSuffix = ROOT::FoundationUtils::GetPathSeparator() + "ROOT.modulemap";
1456 ModuleMaps.push_back(TROOT::GetIncludeDir().Data() + ModuleMapSuffix);
1457 GetEnvVarPath("CLING_MODULEMAP_FILES", ModuleMaps);
1458
1459 std::string cwd = gSystem->WorkingDirectory();
1460 // Give highest precedence of the modulemap in the cwd if any.
1461 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1462 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1463
1464 for (const std::string& M : ModuleMaps)
1465 clingArgsStorage.push_back("-fmodule-map-file=" + M);
1466
1467 std::string ModulesCachePath;
1468 EnvOpt = llvm::sys::Process::GetEnv("CLING_MODULES_CACHE_PATH");
1469 if (EnvOpt.has_value()){
1471 assert(llvm::sys::fs::exists(Env) && "Path does not exist!");
1472 ModulesCachePath = Env.str();
1473 } else {
1475 }
1476
1477 clingArgsStorage.push_back("-fmodules-cache-path=" + ModulesCachePath);
1478 }
1479
1480 std::vector<const char*> interpArgs;
1481 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1483 interpArgs.push_back(iArg->c_str());
1484
1485 // Activate C++ modules support. If we are running within rootcling, it's up
1486 // to rootcling to set this flag depending on whether it wants to produce
1487 // C++ modules.
1489 if (fCxxModulesEnabled) {
1490 if (!fromRootCling) {
1491 // We only set this flag, rest is done by the CIFactory.
1492 interpArgs.push_back("-fmodules");
1493 interpArgs.push_back("-fno-implicit-module-maps");
1494 // We should never build modules during runtime, so let's enable the
1495 // module build remarks from clang to make it easier to spot when we do
1496 // this by accident.
1497 interpArgs.push_back("-Rmodule-build");
1498 }
1499 // ROOT implements its AutoLoading upon module's link directives. We
1500 // generate module A { header "A.h" link "A.so" export * } where ROOT's
1501 // facilities use the link directive to dynamically load the relevant
1502 // library. So, we need to suppress clang's default autolink behavior.
1503 interpArgs.push_back("-fno-autolink");
1504 }
1505
1506#ifdef R__FAST_MATH
1507 // Same setting as in rootcling_impl.cxx.
1508 interpArgs.push_back("-ffast-math");
1509#endif
1510
1512 // Add statically injected extra arguments, usually coming from rootcling.
1513 for (const char** extraArgs = TROOT::GetExtraInterpreterArgs();
1514 extraArgs && *extraArgs; ++extraArgs) {
1515 if (!strcmp(*extraArgs, "-resource-dir")) {
1516 // Take the next arg as the llvm resource directory.
1518 } else {
1519 interpArgs.push_back(*extraArgs);
1520 }
1521 }
1522
1523 std::vector<std::string> _empty;
1525 for (const auto &arg: args)
1526 interpArgs.emplace_back(arg.c_str());
1527
1528 // Add the Rdict module file extension.
1529 cling::Interpreter::ModuleFileExtensions extensions;
1530 EnvOpt = llvm::sys::Process::GetEnv("ROOTDEBUG_RDICT");
1531 if (!EnvOpt.has_value())
1532 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1533
1534 fInterpreter = std::make_unique<cling::Interpreter>(interpArgs.size(),
1535 &(interpArgs[0]),
1538
1539 // Don't check whether modules' files exist.
1540 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHOrModuleValidation =
1541 DisableValidationForModuleKind::All;
1542
1543 // Until we can disable AutoLoading during Sema::CorrectTypo() we have
1544 // to disable spell checking.
1545 fInterpreter->getCI()->getLangOpts().SpellChecking = false;
1546
1547 // Sync modules on/off between clang and us: clang turns it on for C++ >= 20.
1548 auto isModulesArg = [](const char* arg) { return !strcmp(arg, "-fmodules"); };
1549 bool hasModulesArg = std::find_if(interpArgs.begin(), interpArgs.end(), isModulesArg) != interpArgs.end();
1550 fInterpreter->getCI()->getLangOpts().Modules = hasModulesArg;
1551
1552 // We need stream that doesn't close its file descriptor, thus we are not
1553 // using llvm::outs. Keeping file descriptor open we will be able to use
1554 // the results in pipes (Savannah #99234).
1555 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO, /*ShouldClose*/false);
1556 fMetaProcessor = std::make_unique<cling::MetaProcessor>(*fInterpreter, fMPOuts);
1557
1560
1561 // We are now ready (enough is loaded) to init the list of opaque typedefs.
1568
1569 // Disallow auto-parsing in rootcling
1571
1572 ResetAll();
1573
1574 // Enable dynamic lookup
1575 if (!fromRootCling) {
1576 fInterpreter->enableDynamicLookup();
1577 }
1578
1579 // Enable ClinG's DefinitionShadower for ROOT.
1580 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1581 auto &Policy = const_cast<clang::PrintingPolicy &>(fInterpreter->getCI()->getASTContext().getPrintingPolicy());
1582 // Print 'a<b<c> >' rather than 'a<b<c>>'.
1583 // FIXME: We should probably switch to the default printing policy setting
1584 // after adjusting tons of reference files.
1585 Policy.SplitTemplateClosers = true;
1586 // Keep default templare arguments, required for dictionary generation.
1587 Policy.SuppressDefaultTemplateArgs = false;
1588
1589
1590 // Attach cling callbacks last; they might need TROOT::fInterpreter
1591 // and should thus not be triggered during the equivalent of
1592 // TROOT::fInterpreter = new TCling;
1593 std::unique_ptr<TClingCallbacks>
1597 fInterpreter->setCallbacks(std::move(clingCallbacks));
1598
1599 if (!fromRootCling) {
1600 cling::DynamicLibraryManager& DLM = *fInterpreter->getDynamicLibraryManager();
1601 // Make sure cling looks into ROOT's libdir, even if not part of LD_LIBRARY_PATH
1602 // e.g. because of an RPATH build.
1603 DLM.addSearchPath(TROOT::GetSharedLibDir().Data(), /*isUser=*/true,
1604 /*prepend=*/true);
1605 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) -> bool{
1606 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1607 return stem.startswith("libNew") || stem.startswith("libcppyy_backend");
1608 };
1609 // Initialize the dyld for AutoloadLibraryGenerator.
1610 DLM.initializeDyld(ShouldPermanentlyIgnore);
1611 }
1612}
1613
1614
1615////////////////////////////////////////////////////////////////////////////////
1616/// Destroy the interpreter interface.
1617
1619{
1620 // ROOT's atexit functions require the interepreter to be available.
1621 // Run them before shutting down.
1622 if (!IsFromRootCling())
1623 GetInterpreterImpl()->runAtExitFuncs();
1624 fIsShuttingDown = true;
1625 delete fMapfile;
1626 delete fRootmapFiles;
1627 delete fTemporaries;
1628 delete fNormalizedCtxt;
1629 delete fLookupHelper;
1630 gCling = nullptr;
1631}
1632
1633////////////////////////////////////////////////////////////////////////////////
1634/// Initialize the interpreter, once TROOT::fInterpreter is set.
1635
1637{
1639
1640 // We are set up. Enable ROOT's AutoLoading.
1641 if (IsFromRootCling())
1642 return;
1643
1644 // Read the rules before enabling the auto loading to not inadvertently
1645 // load the libraries for the classes concerned even-though the user is
1646 // *not* using them.
1647 // Note this call must happen before the first call to LoadLibraryMap.
1648 assert(GetRootMapFiles() == nullptr && "Must be called before LoadLibraryMap!");
1649 TClass::ReadRules(); // Read the default customization rules ...
1650
1652 SetClassAutoLoading(true);
1653}
1654
1656{
1657 fIsShuttingDown = true;
1658 ResetGlobals();
1659}
1660
1661////////////////////////////////////////////////////////////////////////////////
1662/// Helper to initialize TVirtualStreamerInfo's factor early.
1663/// Use static initialization to insure only one TStreamerInfo is created.
1665{
1666 // Use lambda since SetFactory return void.
1667 auto setFactory = []() {
1669 return kTRUE;
1670 };
1671 static bool doneFactory = setFactory();
1672 return doneFactory; // avoid unused variable warning.
1673}
1674
1675////////////////////////////////////////////////////////////////////////////////
1676/// Register Rdict data for future loading by LoadPCM;
1677
1678void TCling::RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
1679{
1680 if (IsFromRootCling())
1681 return;
1682
1683 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1684 ::Error("TCling::RegisterRdictForLoadPCM", "Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1685 return;
1686 }
1687
1688 // The pcmFileNameFullPath must be resolved already because we cannot resolve
1689 // a link to a non-existent file.
1691}
1692
1693////////////////////////////////////////////////////////////////////////////////
1694/// Tries to load a PCM from TFile; returns true on success.
1695/// The caller of this function should be holding the ROOT Write lock.
1696
1698{
1699 auto listOfKeys = pcmFile.GetListOfKeys();
1700
1701 // This is an empty pcm
1702 if (listOfKeys && ((listOfKeys->GetSize() == 0) || // Nothing here, or
1703 ((listOfKeys->GetSize() == 1) && // only one, and
1704 !strcmp(((TKey *)listOfKeys->At(0))->GetName(), "EMPTY") // name is EMPTY
1705 ))) {
1706 return;
1707 }
1708
1710 if (gDebug > 1)
1711 ::Info("TCling::LoadPCMImpl", "reading protoclasses for %s \n", pcmFile.GetName());
1712
1714 pcmFile.GetObject("__Enums", enums);
1715 if (enums) {
1716 // Cache the pointers
1717 auto listOfGlobals = gROOT->GetListOfGlobals();
1718 auto listOfEnums = dynamic_cast<THashList *>(gROOT->GetListOfEnums());
1719 // Loop on enums and then on enum constants
1720 for (auto selEnum : *enums) {
1721 const char *enumScope = selEnum->GetTitle();
1722 const char *enumName = selEnum->GetName();
1723 if (strcmp(enumScope, "") == 0) {
1724 // This is a global enum and is added to the
1725 // list of enums and its constants to the list of globals
1726 if (!listOfEnums->THashList::FindObject(enumName)) {
1727 ((TEnum *)selEnum)->SetClass(nullptr);
1728 listOfEnums->Add(selEnum);
1729 }
1730 for (auto enumConstant : *static_cast<TEnum *>(selEnum)->GetConstants()) {
1731 if (!listOfGlobals->FindObject(enumConstant)) {
1733 }
1734 }
1735 } else {
1736 // This enum is in a namespace. A TClass entry is bootstrapped if
1737 // none exists yet and the enum is added to it
1739 if (!nsTClassEntry) {
1741 }
1742 auto listOfEnums = nsTClassEntry->fEnums.load();
1743 if (!listOfEnums) {
1744 if ((kIsClass | kIsStruct | kIsUnion) & nsTClassEntry->Property()) {
1745 // For this case, the list will be immutable once constructed
1746 // (i.e. in this case, by the end of this routine).
1748 } else {
1749 // namespaces can have enums added to them
1751 }
1752 }
1753 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1754 ((TEnum *)selEnum)->SetClass(nsTClassEntry);
1755 listOfEnums->Add(selEnum);
1756 }
1757 }
1758 }
1759 enums->Clear();
1760 delete enums;
1761 }
1762
1763 pcmFile.GetObject("__ProtoClasses", protoClasses);
1764
1765 if (protoClasses) {
1766 for (auto obj : *protoClasses) {
1767 TProtoClass *proto = (TProtoClass *)obj;
1769 }
1770 // Now that all TClass-es know how to set them up we can update
1771 // existing TClasses, which might cause the creation of e.g. TBaseClass
1772 // objects which in turn requires the creation of TClasses, that could
1773 // come from the PCH, but maybe later in the loop. Instead of resolving
1774 // a dependency graph the addition to the TClassTable above allows us
1775 // to create these dependent TClasses as needed below.
1776 for (auto proto : *protoClasses) {
1777 if (TClass *existingCl = (TClass *)gROOT->GetListOfClasses()->FindObject(proto->GetName())) {
1778 // We have an existing TClass object. It might be emulated
1779 // or interpreted; we now have more information available.
1780 // Make that available.
1781 if (existingCl->GetState() != TClass::kHasTClassInit) {
1782 DictFuncPtr_t dict = gClassTable->GetDict(proto->GetName());
1783 if (!dict) {
1784 ::Error("TCling::LoadPCM", "Inconsistent TClassTable for %s", proto->GetName());
1785 } else {
1786 // This will replace the existing TClass.
1787 TClass *ncl = (*dict)();
1788 if (ncl)
1789 ncl->PostLoadCheck();
1790 }
1791 }
1792 }
1793 }
1794
1795 protoClasses->Clear(); // Ownership was transfered to TClassTable.
1796 delete protoClasses;
1797 }
1798
1800 pcmFile.GetObject("__Typedefs", dataTypes);
1801 if (dataTypes) {
1802 for (auto typedf : *dataTypes)
1803 gROOT->GetListOfTypes()->Add(typedf);
1804 dataTypes->Clear(); // Ownership was transfered to TListOfTypes.
1805 delete dataTypes;
1806 }
1807}
1808
1809////////////////////////////////////////////////////////////////////////////////
1810/// Tries to load a rdict PCM, issues diagnostics if it fails.
1811/// The caller of this function should be holding the ROOT Write lock.
1812
1814{
1817 assert(!pcmFileNameFullPath.empty());
1818 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1819
1820 // Easier to work with the ROOT interfaces.
1822
1823 // Prevent the ROOT-PCMs hitting this during auto-load during
1824 // JITting - which will cause recursive compilation.
1825 // Avoid to call the plugin manager at all.
1827
1829 llvm::SaveAndRestore<Int_t> SaveGDebug(gDebug);
1830 if (gDebug > 5) {
1831 gDebug -= 5;
1832 ::Info("TCling::LoadPCM", "Loading ROOT PCM %s", pcmFileName.Data());
1833 } else {
1834 gDebug = 0;
1835 }
1836
1837 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1839
1841 if (pendingRdict != fPendingRdicts.end()) {
1842 llvm::StringRef pcmContent = pendingRdict->second;
1844 std::string RDictFileOpts = pcmFileNameFullPath + "?filetype=pcm";
1846
1847 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
1849 // Currently the module file are never unloaded (even if the library is
1850 // unloaded) and, of course, never reloaded.
1851 // Consequently, we must NOT remove the `pendingRdict` from the list
1852 // of pending dictionary, otherwise if a library is unloaded and then
1853 // reload we will be unable to update properly the TClass object
1854 // (because we wont be able to load the rootpcm file by executing the
1855 // above lines)
1856
1857 return;
1858 }
1859
1860 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1861 ::Error("TCling::LoadPCM", "ROOT PCM %s file does not exist",
1862 pcmFileNameFullPath.data());
1863 if (!fPendingRdicts.empty())
1864 for (const auto &rdict : fPendingRdicts)
1865 ::Info("TCling::LoadPCM", "In-memory ROOT PCM candidate %s\n",
1866 rdict.first.c_str());
1867 return;
1868 }
1869
1870 if (!gROOT->IsRootFile(pcmFileName)) {
1871 Fatal("LoadPCM", "The file %s is not a ROOT as was expected\n", pcmFileName.Data());
1872 return;
1873 }
1874 TFile pcmFile(pcmFileName + "?filetype=pcm", "READ");
1876}
1877
1878//______________________________________________________________________________
1879
1880namespace {
1881 using namespace clang;
1882
1883 class ExtLexicalStorageAdder: public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1884 // This class is to be considered an helper for autoparsing.
1885 // It visits the AST and marks all classes (in all of their redeclarations)
1886 // with the setHasExternalLexicalStorage method.
1887 public:
1888 bool VisitRecordDecl(clang::RecordDecl* rcd){
1889 if (gDebug > 2)
1890 Info("ExtLexicalStorageAdder",
1891 "Adding external lexical storage to class %s",
1892 rcd->getNameAsString().c_str());
1893 auto reDeclPtr = rcd->getMostRecentDecl();
1894 do {
1895 reDeclPtr->setHasExternalLexicalStorage();
1896 } while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1897
1898 return false;
1899 }
1900 };
1901
1902
1903}
1904
1905////////////////////////////////////////////////////////////////////////////////
1906///\returns true if the module map was loaded, false on error or if the map was
1907/// already loaded.
1909 const std::string &ModuleMapName /*= "module.modulemap"*/) const
1910{
1911 assert(llvm::sys::path::is_absolute(FullPath));
1912 Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
1913 FileManager &FM = PP.getFileManager();
1914 // FIXME: In a ROOT session we can add an include path (through .I /inc/path)
1915 // We should look for modulemap files there too.
1916 if (auto DE = FM.getOptionalDirectoryRef(FullPath)) {
1917 HeaderSearch &HS = PP.getHeaderSearchInfo();
1918 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1919 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1920 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1921 if (!pathExists)
1922 HSOpts.AddPrebuiltModulePath(FullPath);
1923 // We cannot use HS.lookupModuleMapFile(DE, /*IsFramework*/ false);
1924 // because its internal call to getFile has CacheFailure set to true.
1925 // In our case, modulemaps can appear any time due to ACLiC.
1926 // Code copied from HS.lookupModuleMapFile.
1927 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1928 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1929 if (auto FE = FM.getOptionalFileRef(ModuleMapFileName, /*openFile*/ false,
1930 /*CacheFailure*/ false)) {
1931 if (!HS.loadModuleMapFile(*FE, /*IsSystem*/ false))
1932 return true;
1933 Error("RegisterPrebuiltModulePath", "Could not load modulemap in %s", ModuleMapFileName.c_str());
1934 }
1935 }
1936 return false;
1937}
1938
1939////////////////////////////////////////////////////////////////////////////////
1940/// List of dicts that have the PCM information already in the PCH.
1941static const std::unordered_set<std::string> gIgnoredPCMNames = {"libCore",
1942 "libRint",
1943 "libThread",
1944 "libRIO",
1945 "libImt",
1946 "libMultiProc",
1947 "libcomplexDict",
1948 "libdequeDict",
1949 "liblistDict",
1950 "libforward_listDict",
1951 "libvectorDict",
1952 "libmapDict",
1953 "libmultimap2Dict",
1954 "libmap2Dict",
1955 "libmultimapDict",
1956 "libsetDict",
1957 "libmultisetDict",
1958 "libunordered_setDict",
1959 "libunordered_multisetDict",
1960 "libunordered_mapDict",
1961 "libunordered_multimapDict",
1962 "libvalarrayDict",
1963 "G__GenVector32",
1964 "G__Smatrix32"};
1965
1966static void PrintDlError(const char *dyLibName, const char *modulename)
1967{
1968#ifdef R__WIN32
1969 char dyLibError[1000];
1971 dyLibError, sizeof(dyLibError), NULL);
1972#else
1973 const char *dyLibError = dlerror();
1974#endif
1975 ::Error("TCling::RegisterModule", "Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
1976 (dyLibError) ? dyLibError : "");
1977}
1978
1979////////////////////////////////////////////////////////////////////////////////
1980// Update all the TClass registered in fClassesToUpdate
1981
1983{
1984 while (!fClassesToUpdate.empty()) {
1985 TClass *oldcl = fClassesToUpdate.back().first;
1986 // If somehow the TClass has already been loaded (maybe it was registered several time),
1987 // we skip it. Otherwise, the existing TClass is in mode kInterpreted, kEmulated or
1988 // maybe even kForwardDeclared and needs to replaced.
1989 if (oldcl->GetState() != TClass::kHasTClassInit) {
1990 // if (gDebug > 2) Info("RegisterModule", "Forcing TClass init for %s", oldcl->GetName());
1991 DictFuncPtr_t dict = fClassesToUpdate.back().second;
1992 fClassesToUpdate.pop_back();
1993 // Calling func could manipulate the list so, let maintain the list
1994 // then call the dictionary function.
1995 TClass *ncl = dict();
1996 if (ncl) ncl->PostLoadCheck();
1997 } else {
1998 fClassesToUpdate.pop_back();
1999 }
2000 }
2001}
2002////////////////////////////////////////////////////////////////////////////////
2003/// Inject the module named "modulename" into cling; load all headers.
2004/// headers is a 0-terminated array of header files to `#include` after
2005/// loading the module. The module is searched for in all $LD_LIBRARY_PATH
2006/// entries (or %PATH% on Windows).
2007/// This function gets called by the static initialization of dictionary
2008/// libraries.
2009/// The payload code is injected "as is" in the interpreter.
2010/// The value of 'triggerFunc' is used to find the shared library location.
2011/// The caller of this function should be holding the ROOT Write lock.
2012
2014 const char** headers,
2015 const char** includePaths,
2016 const char* payloadCode,
2017 const char* fwdDeclsCode,
2018 void (*triggerFunc)(),
2020 const char** classesHeaders,
2021 Bool_t lateRegistration /*=false*/,
2022 Bool_t hasCxxModule /*=false*/)
2023{
2024 const bool fromRootCling = IsFromRootCling();
2025 // We need the dictionary initialization but we don't want to inject the
2026 // declarations into the interpreter, except for those we really need for
2027 // I/O; see rootcling.cxx after the call to TCling__GetInterpreter().
2028 if (fromRootCling) return;
2029
2030 // When we cannot provide a module for the library we should enable header
2031 // parsing. This 'mixed' mode ensures gradual migration to modules.
2032 llvm::SaveAndRestore<bool> SaveHeaderParsing(fHeaderParsingOnDemand);
2034
2035 // Treat Aclic Libs in a special way. Do not delay the parsing.
2037 bool isACLiC = strstr(modulename, "_ACLiC_dict") != nullptr;
2039 if (gDebug>1)
2040 Info("TCling::RegisterModule",
2041 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2043 }
2044
2045
2046 // Make sure we relookup symbols that were search for before we loaded
2047 // their autoparse information. We could be more subtil and remove only
2048 // the failed one or only the one in this module, but for now this is
2049 // better than nothing.
2050 fLookedUpClasses.clear();
2051
2052 // Make sure we do not set off AutoLoading or autoparsing during the
2053 // module registration!
2055
2056 for (const char** inclPath = includePaths; *inclPath; ++inclPath) {
2058 }
2059 cling::Transaction* T = nullptr;
2060 // Put the template decls and the number of arguments to skip in the TNormalizedCtxt
2062 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2063 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2064 auto compRes = fInterpreter->declare(fwdDecl.c_str(), &T);
2065 assert(cling::Interpreter::kSuccess == compRes &&
2066 "A fwd declaration could not be compiled");
2067 if (compRes!=cling::Interpreter::kSuccess){
2068 Warning("TCling::RegisterModule",
2069 "Problems in declaring string '%s' were encountered.",
2070 fwdDecl.c_str()) ;
2071 continue;
2072 }
2073
2074 // Drill through namespaces recursively until the template is found
2075 if(ClassTemplateDecl* TD = FindTemplateInNamespace(T->getFirstDecl().getSingleDecl())){
2077 }
2078
2079 }
2080
2081 // FIXME: Remove #define __ROOTCLING__ once PCMs are there.
2082 // This is used to give Sema the same view on ACLiC'ed files (which
2083 // are then #included through the dictionary) as rootcling had.
2085 if (payloadCode)
2086 code += payloadCode;
2087
2088 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2089 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2090
2091 if (dyLibName.empty()) {
2092 ::Error("TCling::RegisterModule", "Dictionary trigger function for %s not found", modulename);
2093 return;
2094 }
2095
2096 // The triggerFunc may not be in a shared object but in an executable.
2097 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2098
2099 bool wasDlopened = false;
2100
2101 // If this call happens after dlopen has finished (i.e. late registration)
2102 // there is no need to dlopen the library recursively. See ROOT-8437 where
2103 // the dyLibName would correspond to the binary.
2104 if (!lateRegistration) {
2105
2106 if (isSharedLib) {
2107 // We need to open the dictionary shared library, to resolve symbols
2108 // requested by the JIT from it: as the library is currently being dlopen'ed,
2109 // its symbols are not yet reachable from the process.
2110 // Recursive dlopen seems to work just fine.
2111 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2112 if (dyLibHandle) {
2114 wasDlopened = true;
2115 } else {
2117 }
2118 }
2119 } // if (!lateRegistration)
2120
2122 // We now parse the forward declarations. All the classes are then modified
2123 // in order for them to have an external lexical storage.
2124 std::string fwdDeclsCodeLessEnums;
2125 {
2126 // Search for enum forward decls and only declare them if no
2127 // declaration exists yet.
2128 std::string fwdDeclsLine;
2129 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2130 std::vector<std::string> scopes;
2131 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2132 const auto enumPos = fwdDeclsLine.find("enum __attribute__((annotate(\"");
2133 // We check if the line contains a fwd declaration of an enum
2134 if (enumPos != std::string::npos) {
2135 // We clear the scopes which we may have carried from a previous iteration
2136 scopes.clear();
2137 // We check if the enum is not in a scope. If yes, save its name
2138 // and the names of the enclosing scopes.
2139 if (enumPos != 0) {
2140 // it's enclosed in namespaces. We need to understand what they are
2141 auto nsPos = fwdDeclsLine.find("namespace");
2142 R__ASSERT(nsPos < enumPos && "Inconsistent enum and enclosing scope parsing!");
2143 while (nsPos < enumPos && nsPos != std::string::npos) {
2144 // we have a namespace, let's put it in the collection of scopes
2145 const auto nsNameStart = nsPos + 10;
2146 const auto nsNameEnd = fwdDeclsLine.find('{', nsNameStart);
2147 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2148 scopes.push_back(nsName);
2149 nsPos = fwdDeclsLine.find("namespace", nsNameEnd);
2150 }
2151 }
2152 clang::DeclContext* DC = nullptr;
2153 for (auto &&aScope: scopes) {
2154 DC = cling::utils::Lookup::Namespace(&fInterpreter->getSema(), aScope.c_str(), DC);
2155 if (!DC) {
2156 // No decl context means we have to fwd declare the enum.
2157 break;
2158 }
2159 }
2160 if (scopes.empty() || DC) {
2161 // We know the scope; let's look for the enum. For that, look
2162 // for the *last* closing parentheses of an attribute because
2163 // there can be multiple.
2164 size_t posEnumName = fwdDeclsLine.rfind("\"))) ");
2165 R__ASSERT(posEnumName != std::string::npos && "Inconsistent enum fwd decl!");
2166 posEnumName += 5; // skip "\"))) "
2168 ++posEnumName;
2169 size_t posEnumNameEnd = fwdDeclsLine.find(" : ", posEnumName);
2170 R__ASSERT(posEnumNameEnd != std::string::npos && "Inconsistent enum fwd decl (end)!");
2173 // posEnumNameEnd now points to the last character of the name.
2174
2175 std::string enumName = fwdDeclsLine.substr(posEnumName,
2177
2178 if (clang::NamedDecl* enumDecl
2179 = cling::utils::Lookup::Named(&fInterpreter->getSema(),
2180 enumName.c_str(), DC)) {
2181 // We have an existing enum decl (forward or definition);
2182 // skip this.
2183 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) && "not an enum decl!");
2184 (void)enumDecl;
2185 continue;
2186 }
2187 }
2188 }
2189
2191 }
2192 }
2193
2194 if (!fwdDeclsCodeLessEnums.empty()){ // Avoid the overhead if nothing is to be declared
2195 auto compRes = fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
2196 assert(cling::Interpreter::kSuccess == compRes &&
2197 "The forward declarations could not be compiled");
2198 if (compRes!=cling::Interpreter::kSuccess){
2199 Warning("TCling::RegisterModule",
2200 "Problems in compiling forward declarations for module %s: '%s'",
2202 }
2203 else if (T){
2204 // Loop over all decls in the transaction and go through them all
2205 // to mark them properly.
2206 // In order to do that, we first iterate over all the DelayedCallInfos
2207 // within the transaction. Then we loop over all Decls in the DeclGroupRef
2208 // contained in the DelayedCallInfos. For each decl, we traverse.
2209 ExtLexicalStorageAdder elsa;
2210 for (auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
2211 cling::Transaction::DelayCallInfo& dci = *dciIt;
2212 for(auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2213 clang::Decl* declPtr = *dit;
2214 elsa.TraverseDecl(declPtr);
2215 }
2216 }
2217 }
2218 }
2219
2220 // Now we register all the headers necessary for the class
2221 // Typical format of the array:
2222 // {"A", "classes.h", "@",
2223 // "vector<A>", "vector", "@",
2224 // "myClass", payloadCode, "@",
2225 // nullptr};
2226
2227 std::string temp;
2228 for (const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2229 temp=*classesHeader;
2230
2231 size_t theTemplateHash = 0;
2232 bool addTemplate = false;
2233 size_t posTemplate = temp.find('<');
2234 if (posTemplate != std::string::npos) {
2235 // Add an entry for the template itself.
2236 std::string templateName = temp.substr(0, posTemplate);
2238 addTemplate = true;
2239 }
2240 size_t theHash = fStringHashFunction(temp);
2241 classesHeader++;
2243 // This is done in order to distinguish headers from files and from the payloadCode
2245 fPayloads.insert(theHash);
2247 }
2248 if (gDebug > 2)
2249 Info("TCling::RegisterModule",
2250 "Adding a header for %s", temp.c_str());
2252 if (addTemplate) {
2255 }
2256 addTemplate = false;
2257 }
2258 }
2259 }
2260 }
2261
2262 clang::Sema &TheSema = fInterpreter->getSema();
2263
2264 bool ModuleWasSuccessfullyLoaded = false;
2265 if (hasCxxModule) {
2266 std::string ModuleName = modulename;
2267 if (llvm::StringRef(modulename).startswith("lib"))
2268 ModuleName = llvm::StringRef(modulename).substr(3).str();
2269
2270 // In case we are directly loading the library via gSystem->Load() without
2271 // specifying the relevant include paths we should try loading the
2272 // modulemap next to the library location.
2273 clang::Preprocessor &PP = TheSema.getPreprocessor();
2274 std::string ModuleMapName;
2275 if (isACLiC)
2276 ModuleMapName = ModuleName + ".modulemap";
2277 else
2278 ModuleMapName = "module.modulemap";
2279 RegisterPrebuiltModulePath(llvm::sys::path::parent_path(dyLibName).str(),
2281
2282 // FIXME: We should only complain for modules which we know to exist. For example, we should not complain about
2283 // modules such as GenVector32 because it needs to fall back to GenVector.
2284 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2287 // Only report if we found the module in the modulemap.
2288 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2289 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2290 if (moduleMap.findModule(ModuleName))
2291 Info("TCling::RegisterModule", "Module %s in modulemap failed to load.", ModuleName.c_str());
2292 }
2293 }
2294
2296 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2297 // The path dyLibName might not be absolute. This can happen if dyLibName
2298 // is linked to an executable in the same folder.
2299 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2300 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2301 llvm::sys::path::append(pcmFileNameFullPath,
2303 LoadPCM(pcmFileNameFullPath.str().str());
2304 }
2305
2306 { // scope within which diagnostics are de-activated
2307 // For now we disable diagnostics because we saw them already at
2308 // dictionary generation time. That won't be an issue with the PCMs.
2309
2310 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2311
2312#if defined(R__MUST_REVISIT)
2313#if R__MUST_REVISIT(6,2)
2314 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
2315#endif
2316#endif
2317
2320
2321 const cling::Transaction* watermark = fInterpreter->getLastTransaction();
2322 cling::Interpreter::CompilationResult compRes = fInterpreter->parseForModule(code.Data());
2323 if (isACLiC) {
2324 // Register an unload point.
2325 fMetaProcessor->registerUnloadPoint(watermark, headers[0]);
2326 }
2327
2328 assert(cling::Interpreter::kSuccess == compRes &&
2329 "Payload code of a dictionary could not be parsed correctly.");
2330 if (compRes!=cling::Interpreter::kSuccess) {
2331 Warning("TCling::RegisterModule",
2332 "Problems declaring payload for module %s.", modulename) ;
2333 }
2334 }
2335 }
2336
2337 // Now that all the header have been registered/compiled, let's
2338 // make sure to 'reset' the TClass that have a class init in this module
2339 // but already had their type information available (using information/header
2340 // loaded from other modules or from class rules or from opening a TFile
2341 // or from loading header in a way that did not provoke the loading of
2342 // the library we just loaded).
2344
2346 // __ROOTCLING__ might be pulled in through PCH
2347 fInterpreter->declare("#ifdef __ROOTCLING__\n"
2348 "#undef __ROOTCLING__\n"
2350 "#endif");
2351 }
2352
2353 if (wasDlopened) {
2355 void* dyLibHandle = fRegisterModuleDyLibs.back();
2356 fRegisterModuleDyLibs.pop_back();
2358 }
2359}
2360
2362 clang::CompilerInstance& CI = *GetInterpreterImpl()->getCI();
2363 ASTContext &C = CI.getASTContext();
2364
2365 // Do not do anything if we have no global module index.
2366 // FIXME: This is mostly to real with false positives in the TTabCom
2367 // interface for non-modules.
2368 if (!fCxxModulesEnabled)
2369 return;
2370
2371 if (IdentifierInfoLookup *External = C.Idents.getExternalIdentifierLookup()) {
2372 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2373 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2374 std::string I = Ident.str();
2375 if (!Idents.Contains(I.data()))
2376 Idents.Add(new TObjString(I.c_str()));
2377 }
2378 }
2379}
2380
2381
2382////////////////////////////////////////////////////////////////////////////////
2383/// Register classes that already existed prior to their dictionary loading
2384/// and that already had a ClassInfo (and thus would not be refresh via
2385/// UpdateClassInfo.
2386
2388{
2389 fClassesToUpdate.push_back(std::make_pair(oldcl,dict));
2390}
2391
2392////////////////////////////////////////////////////////////////////////////////
2393/// If the dictionary is loaded, we can remove the class from the list
2394/// (otherwise the class might be loaded twice).
2395
2397{
2398 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2399 iterator stop = fClassesToUpdate.end();
2400 for(iterator i = fClassesToUpdate.begin();
2401 i != stop;
2402 ++i)
2403 {
2404 if ( i->first == oldcl ) {
2405 fClassesToUpdate.erase(i);
2406 return;
2407 }
2408 }
2409}
2410
2411
2412////////////////////////////////////////////////////////////////////////////////
2413/// Let cling process a command line.
2414///
2415/// If the command is executed and the error is 0, then the return value
2416/// is the int value corresponding to the result of the executed command
2417/// (float and double return values will be truncated).
2418///
2419
2420// Method for handling the interpreter exceptions.
2421// the MetaProcessor is passing in as argument to teh function, because
2422// cling::Interpreter::CompilationResult is a nested class and it cannot be
2423// forward declared, thus this method cannot be a static member function
2424// of TCling.
2425
2426static int HandleInterpreterException(cling::MetaProcessor* metaProcessor,
2427 const char* input_line,
2428 cling::Interpreter::CompilationResult& compRes,
2429 cling::Value* result)
2430{
2431 try {
2432 return metaProcessor->process(input_line, compRes, result);
2433 }
2434 catch (cling::InterpreterException& ex)
2435 {
2436 Error("HandleInterpreterException", "%s\n%s", ex.what(), "Execution of your code was aborted.");
2437 ex.diagnose();
2438 compRes = cling::Interpreter::kFailure;
2439 }
2440 return 0;
2441}
2442
2443////////////////////////////////////////////////////////////////////////////////
2444
2445bool TCling::DiagnoseIfInterpreterException(const std::exception &e) const
2446{
2447 if (auto ie = dynamic_cast<const cling::InterpreterException*>(&e)) {
2448 ie->diagnose();
2449 return true;
2450 }
2451 return false;
2452}
2453
2454////////////////////////////////////////////////////////////////////////////////
2455
2457{
2458 // Copy the passed line, it comes from a static buffer in TApplication
2459 // which can be reentered through the Cling evaluation routines,
2460 // which would overwrite the static buffer and we would forget what we
2461 // were doing.
2462 //
2464 if (strstr(line,fantomline)) {
2465 // End-Of-Line action
2466 // See the comment (copied from above):
2467 // It is a "fantom" method to synchronize user keyboard input
2468 // and ROOT prompt line (for WIN32)
2469 // and is implemented by
2470 if (gApplication) {
2471 if (gApplication->IsCmdThread()) {
2473 gROOT->SetLineIsProcessing();
2474
2476
2477 gROOT->SetLineHasBeenProcessed();
2478 }
2479 }
2480 return 0;
2481 }
2482
2484 gGlobalMutex->Lock();
2485 if (!gInterpreterMutex)
2488 }
2490 gROOT->SetLineIsProcessing();
2491
2492 struct InterpreterFlagsRAII {
2493 cling::Interpreter* fInterpreter;
2495
2496 InterpreterFlagsRAII(cling::Interpreter* interp):
2497 fInterpreter(interp),
2498 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2499 {
2500 fInterpreter->enableDynamicLookup(true);
2501 }
2503 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2504 gROOT->SetLineHasBeenProcessed();
2505 }
2507
2508 // A non-zero returned value means the given line was
2509 // not a complete statement.
2510 int indent = 0;
2511 // This will hold the resulting value of the evaluation the given line.
2512 cling::Value result;
2513 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2514 if (!strncmp(sLine.Data(), ".L", 2) || !strncmp(sLine.Data(), ".x", 2) ||
2515 !strncmp(sLine.Data(), ".X", 2)) {
2516 // If there was a trailing "+", then CINT compiled the code above,
2517 // and we will need to strip the "+" before passing the line to cling.
2520 TString arguments;
2521 TString io;
2523 aclicMode, arguments, io);
2524 if (aclicMode.Length()) {
2525 // Remove the leading '+'
2526 R__ASSERT(aclicMode[0]=='+' && "ACLiC mode must start with a +");
2527 aclicMode[0]='k'; // We always want to keep the .so around.
2528 if (aclicMode[1]=='+') {
2529 // We have a 2nd +
2530 aclicMode[1]='f'; // We want to force the recompilation.
2531 }
2533 // ACLiC failed.
2534 compRes = cling::Interpreter::kFailure;
2535 } else {
2536 if (strncmp(sLine.Data(), ".L", 2) != 0) {
2537 // if execution was requested.
2538
2539 if (arguments.Length() == 0) {
2540 arguments = "()";
2541 }
2542 // We need to remove the extension.
2543 Ssiz_t ext = fname.Last('.');
2544 if (ext != kNPOS) {
2545 fname.Remove(ext);
2546 }
2547 const char *function = gSystem->BaseName(fname);
2548 mod_line = function + arguments + io;
2550 }
2551 }
2552 } else if (cling::DynamicLibraryManager::isSharedLibrary(fname.Data()) &&
2553 strncmp(sLine.Data(), ".L", 2) != 0) { // .x *.so or *.dll
2554 if (gSystem->Load(fname) < 0) {
2555 // Loading failed.
2556 compRes = cling::Interpreter::kFailure;
2557 } else {
2558 if (arguments.Length() == 0) {
2559 arguments = "()";
2560 }
2561 // We need to remove the extension. (*.so or *.dll)
2562 Ssiz_t ext = fname.Last('.');
2563 if (ext != kNPOS) {
2564 fname.Remove(ext);
2565 }
2566 // Now we try to find the 'main' function to run within this shared library
2567 // We distinguish two cases: a library.so with a function library(args),
2568 // or a precompiled ACLiC macro (macro_C.so) with a function macro(args).
2569 // Only in the second case, we need to strip the suffix _C or _cpp from fname.
2570 if (!gInterpreter->GetFunction(nullptr, gSystem->BaseName(fname))) { // AcLiC macro
2571 // We need to remove the automatically appended _ extension when compiling (macro_C from macro.C)
2572 ext = fname.Last('_');
2573 if (ext != kNPOS) {
2574 fname.Remove(ext);
2575 }
2576 }
2577 const char *function = gSystem->BaseName(fname);
2578 mod_line = function + arguments + io;
2580 }
2581 } else {
2582 // neither ACLiC nor run shared-library (.x)
2583 size_t unnamedMacroOpenCurly;
2584 {
2585 std::string code;
2586 std::string codeline;
2587 // Windows requires std::ifstream::binary to properly handle
2588 // CRLF and LF line endings
2589 std::ifstream in(fname, std::ifstream::binary);
2590 while (in) {
2591 std::getline(in, codeline);
2592 code += codeline + "\n";
2593 }
2595 = cling::utils::isUnnamedMacro(code, fInterpreter->getCI()->getLangOpts());
2596 }
2597
2598 fCurExecutingMacros.push_back(fname);
2599 if (unnamedMacroOpenCurly != std::string::npos) {
2600 compRes = fMetaProcessor->readInputFromFile(fname.Data(), &result,
2602 } else {
2603 // No DynLookup for .x, .L of named macros.
2604 fInterpreter->enableDynamicLookup(false);
2606 }
2607 fCurExecutingMacros.pop_back();
2608 }
2609 } // .L / .X / .x
2610 else {
2611 if (0!=strncmp(sLine.Data(), ".autodict ",10) && sLine != ".autodict") {
2612 // explicitly ignore .autodict without having to support it
2613 // in cling.
2614
2615 // Turn off autoparsing if this is an include directive
2616 bool isInclusionDirective = sLine.Contains("\n#include") || sLine.BeginsWith("#include");
2620 } else {
2622 }
2623 }
2624 }
2625 if (result.isValid())
2627 if (indent) {
2628 if (error)
2629 *error = kProcessing;
2630 return 0;
2631 }
2632 if (error) {
2633 switch (compRes) {
2634 case cling::Interpreter::kSuccess: *error = kNoError; break;
2635 case cling::Interpreter::kFailure: *error = kRecoverable; break;
2636 case cling::Interpreter::kMoreInputExpected: *error = kProcessing; break;
2637 }
2638 }
2639 if (compRes == cling::Interpreter::kSuccess
2640 && result.isValid()
2641 && !result.isVoid())
2642 {
2643 return result.castAs<Longptr_t>();
2644 }
2645 return 0;
2646}
2647
2648////////////////////////////////////////////////////////////////////////////////
2649/// No-op; see TRint instead.
2650
2652{
2653}
2654
2655////////////////////////////////////////////////////////////////////////////////
2656/// \brief Add a directory to the list of directories in which the
2657/// interpreter looks for include files.
2658/// \param[in] path The path to the directory.
2659/// \note Only one path item can be specified at a time, i.e. "path1:path2" is
2660/// \b NOT supported.
2661/// \warning Only the path to the directory should be specified, without
2662/// prepending the \c -I prefix, i.e.
2663/// <tt>gCling->AddIncludePath("/path/to/my/includes")</tt>. If the
2664/// \c -I prefix is used it will be ignored.
2665void TCling::AddIncludePath(const char *path)
2666{
2668 // Favorite source of annoyance: gSystem->AddIncludePath() needs "-I",
2669 // gCling->AddIncludePath() does not! Work around that inconsistency:
2670 if (path[0] == '-' && path[1] == 'I')
2671 path += 2;
2672 TString sPath(path);
2674#ifdef _MSC_VER
2675 if (sPath.BeginsWith("/")) {
2676 char drive[3];
2677 snprintf(drive, 3, "%c:", _getdrive() + 'A' - 1);
2678 sPath.Prepend(drive);
2679 }
2680#endif
2681 fInterpreter->AddIncludePath(sPath.Data());
2682}
2683
2684////////////////////////////////////////////////////////////////////////////////
2685/// Visit all members over members, recursing over base classes.
2686
2688 const TClass* cl, Bool_t isTransient)
2689{
2690 if (insp.GetObjectValidity() == TMemberInspector::kUnset) {
2691 insp.SetObjectValidity(obj ? TMemberInspector::kValidObjectGiven
2693 }
2694
2695 if (!cl || cl->GetCollectionProxy()) {
2696 // We do not need to investigate the content of the STL
2697 // collection, they are opaque to us (and details are
2698 // uninteresting).
2699 return;
2700 }
2701
2702 static const TClassRef clRefString("std::string");
2703 if (clRefString == cl) {
2704 // We stream std::string without going through members..
2705 return;
2706 }
2707
2708 if (TClassEdit::IsStdArray(cl->GetName())) {
2709 // We treat std arrays as C arrays
2710 return;
2711 }
2712
2713 if (TClassEdit::IsUniquePtr(cl->GetName())) {
2714 // Ignore error caused by the inside of std::unique_ptr
2715 // This is needed solely because of rootclingIO's IsUnsupportedUniquePointer
2716 // which checks the number of elements in the GetListOfRealData.
2717 // If this usage is removed, this can be replaced with a return statement.
2718 // See https://github.com/root-project/root/issues/13574
2719 isTransient = true;
2720 }
2721
2722 const char* cobj = (const char*) obj; // for ptr arithmetics
2723
2724 // Treat the case of std::complex in a special manner. We want to enforce
2725 // the layout of a stl implementation independent class, which is the
2726 // complex as implemented in ROOT5.
2727
2728 // A simple lambda to simplify the code
2729 auto inspInspect = [&] (ptrdiff_t offset){
2730 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_real", cobj, isTransient);
2731 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_imag", cobj + offset, isTransient);
2732 };
2733
2735 switch(complexType) {
2737 {
2738 break;
2739 }
2741 {
2742 inspInspect(sizeof(float));
2743 return;
2744 }
2746 {
2747 inspInspect(sizeof(double));
2748 return;
2749 }
2751 {
2752 inspInspect(sizeof(int));
2753 return;
2754 }
2756 {
2757 inspInspect(sizeof(long));
2758 return;
2759 }
2760 }
2761
2762 static clang::PrintingPolicy
2763 printPol(fInterpreter->getCI()->getLangOpts());
2764 if (printPol.Indentation) {
2765 // not yet initialized
2766 printPol.Indentation = 0;
2767 printPol.SuppressInitializers = true;
2768 }
2769
2770 const char* clname = cl->GetName();
2771 // Printf("Inspecting class %s\n", clname);
2772
2773 const clang::ASTContext& astContext = fInterpreter->getCI()->getASTContext();
2774 const clang::Decl *scopeDecl = nullptr;
2775 const clang::Type *recordType = nullptr;
2776
2777 if (cl->GetClassInfo()) {
2779 scopeDecl = clingCI->GetDecl();
2780 recordType = clingCI->GetType();
2781 } else {
2782 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
2783 // Diags will complain about private classes:
2784 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2785 &recordType);
2786 }
2787 if (!scopeDecl) {
2788 Error("InspectMembers", "Cannot find Decl for class %s", clname);
2789 return;
2790 }
2791 const clang::CXXRecordDecl* recordDecl
2792 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2793 if (!recordDecl) {
2794 Error("InspectMembers", "Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2795 return;
2796 }
2797
2798 {
2799 // Force possible deserializations first. We need to have no pending
2800 // Transaction when passing control flow to the inspector below (ROOT-7779).
2801 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2802
2803 astContext.getASTRecordLayout(recordDecl);
2804
2805 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2806 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2807 }
2808
2809 const clang::ASTRecordLayout& recLayout
2810 = astContext.getASTRecordLayout(recordDecl);
2811
2812 // TVirtualCollectionProxy *proxy = cl->GetCollectionProxy();
2813 // if (proxy && ( proxy->GetProperties() & TVirtualCollectionProxy::kIsEmulated ) ) {
2814 // Error("InspectMembers","The TClass for %s has an emulated proxy but we are looking at a compiled version of the collection!\n",
2815 // cl->GetName());
2816 // }
2817 if (cl->Size() != recLayout.getSize().getQuantity()) {
2818 Error("InspectMembers","TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2819 cl->GetName(),cl->Size(),(Long64_t)recLayout.getSize().getQuantity());
2820 }
2821
2822 unsigned iNField = 0;
2823 // iterate over fields
2824 // FieldDecls are non-static, else it would be a VarDecl.
2825 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2826 eField = recordDecl->field_end(); iField != eField;
2827 ++iField, ++iNField) {
2828
2829
2830 clang::QualType memberQT = iField->getType();
2831 if (recordType) {
2832 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2834 }
2835 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2836 if (memberQT.isNull()) {
2837 std::string memberName;
2838 llvm::raw_string_ostream stream(memberName);
2839 // Don't trigger fopen of the source file to count lines:
2840 printPol.AnonymousTagLocations = false;
2841 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2842 stream.flush();
2843 Error("InspectMembers",
2844 "Cannot retrieve QualType for member %s while inspecting class %s",
2845 memberName.c_str(), clname);
2846 continue; // skip member
2847 }
2848 const clang::Type* memType = memberQT.getTypePtr();
2849 if (!memType) {
2850 std::string memberName;
2851 llvm::raw_string_ostream stream(memberName);
2852 // Don't trigger fopen of the source file to count lines:
2853 printPol.AnonymousTagLocations = false;
2854 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2855 stream.flush();
2856 Error("InspectMembers",
2857 "Cannot retrieve Type for member %s while inspecting class %s",
2858 memberName.c_str(), clname);
2859 continue; // skip member
2860 }
2861
2862 const clang::Type* memNonPtrType = memType;
2863 Bool_t ispointer = false;
2864 if (memNonPtrType->isPointerType()) {
2865 ispointer = true;
2866 clang::QualType ptrQT
2867 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2868 if (recordType) {
2869 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2871 }
2872 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2873 if (ptrQT.isNull()) {
2874 std::string memberName;
2875 llvm::raw_string_ostream stream(memberName);
2876 // Don't trigger fopen of the source file to count lines:
2877 printPol.AnonymousTagLocations = false;
2878 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2879 stream.flush();
2880 Error("InspectMembers",
2881 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2882 memberName.c_str(), clname);
2883 continue; // skip member
2884 }
2885 memNonPtrType = ptrQT.getTypePtr();
2886 }
2887
2888 // assemble array size(s): "[12][4][]"
2889 llvm::SmallString<8> arraySize;
2890 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2891 unsigned arrLevel = 0;
2892 bool haveErrorDueToArray = false;
2893 while (arrType) {
2894 ++arrLevel;
2895 arraySize += '[';
2896 const clang::ConstantArrayType* constArrType =
2897 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2898 if (constArrType) {
2899 constArrType->getSize().toStringUnsigned(arraySize);
2900 }
2901 arraySize += ']';
2902 clang::QualType subArrQT = arrType->getElementType();
2903 if (subArrQT.isNull()) {
2904 std::string memberName;
2905 llvm::raw_string_ostream stream(memberName);
2906 // Don't trigger fopen of the source file to count lines:
2907 printPol.AnonymousTagLocations = false;
2908 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2909 stream.flush();
2910 Error("InspectMembers",
2911 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2912 arrLevel, subArrQT.getAsString(printPol).c_str(),
2913 memberName.c_str(), clname);
2914 haveErrorDueToArray = true;
2915 break;
2916 }
2917 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2918 }
2919 if (haveErrorDueToArray) {
2920 continue; // skip member
2921 }
2922
2923 // construct member name
2924 std::string fieldName;
2925 if (memType->isPointerType()) {
2926 fieldName = "*";
2927 }
2928
2929 // Check if this field has a custom ioname, if not, just use the one of the decl
2930 std::string ioname(iField->getName());
2932 fieldName += ioname;
2933 fieldName += arraySize;
2934
2935 // get member offset
2936 // NOTE currently we do not support bitfield and do not support
2937 // member that are not aligned on 'bit' boundaries.
2938 clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2939 ptrdiff_t fieldOffset = offset.getQuantity();
2940
2941 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fBits[2]", fBits);
2942 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fName", &fName);
2943 // R__insp.InspectMember(fName, "fName.");
2944 // R__insp.Inspect(R__cl, R__insp.GetParent(), "*fClass", &fClass);
2945
2946 // If the class has a custom streamer and the type of the filed is a
2947 // private enum, struct or class, skip it.
2948 if (!insp.IsTreatingNonAccessibleTypes()){
2949 auto iFiledQtype = iField->getType();
2950 if (auto tagDecl = iFiledQtype->getAsTagDecl()){
2951 auto declAccess = tagDecl->getAccess();
2953 continue;
2954 }
2955 }
2956 }
2957
2958 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2959
2960 if (!ispointer) {
2961 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2962 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
2963 // nested objects get an extra call to InspectMember
2964 // R__insp.InspectMember("FileStat_t", (void*)&fFileStat, "fFileStat.", false);
2965 std::string sFieldRecName;
2968 clang::QualType(memNonPtrType,0),
2969 *fInterpreter,
2971 }
2972
2973 TDataMember* mbr = cl->GetDataMember(ioname.c_str());
2974 // if we can not find the member (which should not really happen),
2975 // let's consider it transient.
2976 Bool_t transient = isTransient || !mbr || !mbr->IsPersistent();
2977
2978 insp.InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
2979 (fieldName + '.').c_str(), transient);
2980
2981 }
2982 }
2983 } // loop over fields
2984
2985 // inspect bases
2986 // TNamed::ShowMembers(R__insp);
2987 unsigned iNBase = 0;
2988 for (clang::CXXRecordDecl::base_class_const_iterator iBase
2989 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
2990 iBase != eBase; ++iBase, ++iNBase) {
2991 clang::QualType baseQT = iBase->getType();
2992 if (baseQT.isNull()) {
2993 Error("InspectMembers",
2994 "Cannot find QualType for base number %d while inspecting class %s",
2995 iNBase, clname);
2996 continue;
2997 }
2998 const clang::CXXRecordDecl* baseDecl
2999 = baseQT->getAsCXXRecordDecl();
3000 if (!baseDecl) {
3001 Error("InspectMembers",
3002 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
3003 iNBase, clname);
3004 continue;
3005 }
3006 TClass* baseCl=nullptr;
3007 std::string sBaseName;
3008 // Try with the DeclId
3009 std::vector<TClass*> foundClasses;
3011 if (foundClasses.size()==1){
3013 } else {
3014 // Try with the normalised Name, as a fallback
3015 if (!baseCl){
3017 baseQT,
3018 *fInterpreter,
3021 }
3022 }
3023
3024 if (!baseCl){
3025 std::string qualNameForDiag;
3027 Error("InspectMembers",
3028 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
3029 continue;
3030 }
3031
3032 int64_t baseOffset;
3033 if (iBase->isVirtual()) {
3034 if (insp.GetObjectValidity() == TMemberInspector::kNoObjectGiven) {
3035 if (!isTransient) {
3036 Error("InspectMembers",
3037 "Base %s of class %s is virtual but no object provided",
3038 sBaseName.c_str(), clname);
3039 }
3041 } else {
3042 // We have an object to determine the vbase offset.
3044 TClingClassInfo* baseCi = (TClingClassInfo*)baseCl->GetClassInfo();
3045 if (ci && baseCi) {
3046 baseOffset = ci->GetBaseOffset(baseCi, const_cast<void*>(obj),
3047 true /*isDerivedObj*/);
3048 if (baseOffset == -1) {
3049 Error("InspectMembers",
3050 "Error calculating offset of virtual base %s of class %s",
3051 sBaseName.c_str(), clname);
3052 }
3053 } else {
3054 Error("InspectMembers",
3055 "Cannot calculate offset of virtual base %s of class %s",
3056 sBaseName.c_str(), clname);
3057 continue;
3058 }
3059 }
3060 } else {
3061 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3062 }
3063 // TOFIX: baseCl can be null here!
3064 if (baseCl->IsLoaded()) {
3065 // For loaded class, CallShowMember will (especially for TObject)
3066 // call the virtual ShowMember rather than the class specific version
3067 // resulting in an infinite recursion.
3069 } else {
3070 baseCl->CallShowMembers(cobj + baseOffset,
3071 insp, isTransient);
3072 }
3073 } // loop over bases
3074}
3075
3076////////////////////////////////////////////////////////////////////////////////
3077/// Reset the interpreter internal state in case a previous action was not correctly
3078/// terminated.
3079
3081{
3082 // No-op there is not equivalent state (to be cleared) in Cling.
3083}
3084
3085////////////////////////////////////////////////////////////////////////////////
3086/// Delete existing temporary values.
3087
3089{
3090 // No-op for cling due to cling::Value.
3091}
3092
3093////////////////////////////////////////////////////////////////////////////////
3094/// Declare code to the interpreter, without any of the interpreter actions
3095/// that could trigger a re-interpretation of the code. I.e. make cling
3096/// behave like a compiler: no dynamic lookup, no input wrapping for
3097/// subsequent execution, no automatic provision of declarations but just a
3098/// plain `#include`.
3099/// Returns true on success, false on failure.
3100
3101bool TCling::Declare(const char* code)
3102{
3104
3107
3108 bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
3109 fInterpreter->enableDynamicLookup(false);
3110 bool oldRawInput = fInterpreter->isRawInputEnabled();
3111 fInterpreter->enableRawInput(true);
3112
3113 Bool_t ret = LoadText(code);
3114
3115 fInterpreter->enableRawInput(oldRawInput);
3116 fInterpreter->enableDynamicLookup(oldDynLookup);
3117 return ret;
3118}
3119
3120////////////////////////////////////////////////////////////////////////////////
3121/// It calls a "fantom" method to synchronize user keyboard input
3122/// and ROOT prompt line.
3123
3128
3129// This static function is a hop of TCling::IsLibraryLoaded, which is taking a lock and calling
3130// into this function. This is because we wanted to avoid a duplication in TCling::IsLoaded, which
3131// was already taking a lock.
3132static Bool_t s_IsLibraryLoaded(const char* libname, cling::Interpreter* fInterpreter)
3133{
3134 // Check shared library.
3137 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.Data());
3138 return false;
3139}
3140
3146
3147////////////////////////////////////////////////////////////////////////////////
3148/// Return true if ROOT has cxxmodules pcm for a given library name.
3149// FIXME: We need to be able to support lazy loading of pcm generated by ACLiC.
3151{
3152 llvm::StringRef ModuleName(libname);
3153 ModuleName = llvm::sys::path::stem(ModuleName);
3154 ModuleName.consume_front("lib");
3155
3156 // FIXME: In case when the modulemap is not yet loaded we will return the
3157 // wrong result. Consider a call to HasPCMForLibrary(../test/libEvent.so)
3158 // We will only load the modulemap for libEvent.so after we dlopen libEvent
3159 // which may happen after calling this interface. Maybe we should also check
3160 // if there is a Event.pcm file and a module.modulemap, load it and return
3161 // true.
3162 clang::ModuleMap &moduleMap = fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3163 clang::Module *M = moduleMap.findModule(ModuleName);
3164 return M && !M->IsUnimportable && M->getASTFile();
3165}
3166
3167////////////////////////////////////////////////////////////////////////////////
3168/// Return true if the file has already been loaded by cint.
3169/// We will try in this order:
3170/// actual filename
3171/// filename as a path relative to
3172/// the include path
3173/// the shared library path
3174
3176{
3178
3179 //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
3180 // cling::DynamicLibraryManager.
3181
3182 std::string file_name = filename;
3183 size_t at = std::string::npos;
3184 while ((at = file_name.find("/./")) != std::string::npos)
3185 file_name.replace(at, 3, "/");
3186
3187 std::string filesStr = "";
3188 llvm::raw_string_ostream filesOS(filesStr);
3189 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3190 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3191 filesOS.flush();
3192
3193 llvm::SmallVector<llvm::StringRef, 100> files;
3194 llvm::StringRef(filesStr).split(files, "\n");
3195
3196 std::set<std::string> fileMap;
3197 llvm::StringRef file_name_ref(file_name);
3198 // Fill fileMap; return early on exact match.
3200 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3201 if ((*iF) == file_name_ref) return kTRUE; // exact match
3202 fileMap.insert(iF->str());
3203 }
3204
3205 if (fileMap.empty()) return kFALSE;
3206
3207 // Check MacroPath.
3208 TString sFilename(file_name.c_str());
3210 && fileMap.count(sFilename.Data())) {
3211 return kTRUE;
3212 }
3213
3214 // Check IncludePath.
3215 TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
3216 incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
3217 incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
3218 while (incPath.Index(" :") != -1) {
3219 incPath.ReplaceAll(" :", ":");
3220 }
3221 incPath.Prepend(".:");
3222 sFilename = file_name.c_str();
3224 && fileMap.count(sFilename.Data())) {
3225 return kTRUE;
3226 }
3227
3228 // Check shared library.
3229 if (s_IsLibraryLoaded(file_name.c_str(), GetInterpreterImpl()))
3230 return kTRUE;
3231
3232 //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
3233 clang::ConstSearchDirIterator *CurDir = nullptr;
3234 clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
3235 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3236 auto FE = HS.LookupFile(file_name.c_str(),
3237 clang::SourceLocation(),
3238 /*isAngled*/ false,
3239 /*FromDir*/ nullptr, CurDir,
3240 clang::ArrayRef<std::pair<clang::OptionalFileEntryRef,
3241 clang::DirectoryEntryRef>>(),
3242 /*SearchPath*/ nullptr,
3243 /*RelativePath*/ nullptr,
3244 /*RequestingModule*/ nullptr,
3245 /*SuggestedModule*/ nullptr,
3246 /*IsMapped*/ nullptr,
3247 /*IsFrameworkFound*/ nullptr,
3248 /*SkipCache*/ false,
3249 /*BuildSystemModule*/ false,
3250 /*OpenFile*/ false,
3251 /*CacheFail*/ false);
3252 if (FE) {
3253 // check in the source manager if the file is actually loaded
3254 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3255 // this works only with header (and source) files...
3256 clang::FileID FID = SM.translateFile(*FE);
3257 if (!FID.isInvalid() && FID.getHashValue() == 0)
3258 return kFALSE;
3259 else {
3260 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3261 if (SLocE.isFile() && !SLocE.getFile().getContentCache().getBufferIfLoaded())
3262 return kFALSE;
3263 if (!FID.isInvalid())
3264 return kTRUE;
3265 }
3266 // ...then check shared library again, but with full path now
3267 sFilename = FE->getName().str();
3269 && fileMap.count(sFilename.Data())) {
3270 return kTRUE;
3271 }
3272 }
3273 return kFALSE;
3274}
3275
3276
3277#if defined(R__MACOSX)
3278
3279////////////////////////////////////////////////////////////////////////////////
3280/// Check if lib is in the dynamic linker cache, returns true if it is, and if so,
3281/// modifies the library file name parameter `lib` from `/usr/lib/libFOO.dylib`
3282/// to `-lFOO` such that it can be passed to the linker.
3283/// This is a unique feature of macOS 11.
3284
3285static bool R__UpdateLibFileForLinking(TString &lib)
3286{
3287 const char *mapfile = nullptr;
3288#if __x86_64__
3289 mapfile = "/System/Library/dyld/dyld_shared_cache_x86_64.map";
3290#elif __arm64__
3291 mapfile = "/System/Library/dyld/dyld_shared_cache_arm64e.map";
3292#else
3293 #error unsupported architecture
3294#endif
3295 if (std::ifstream cacheMap{mapfile}) {
3296 std::string line;
3297 while (getline(cacheMap, line)) {
3298 if (line.find(lib) != std::string::npos) {
3299 lib.ReplaceAll("/usr/lib/lib","-l");
3300 lib.ReplaceAll(".dylib","");
3301 return true;
3302 }
3303 }
3304 return false;
3305 }
3306 return false;
3307}
3308#endif // R__MACOSX
3309
3310#if defined (R__LINUX) || defined (R__FBSD)
3311
3312////////////////////////////////////////////////////////////////////////////////
3313/// Callback for dl_iterate_phdr(), see `man dl_iterate_phdr`.
3314/// Collects opened libraries.
3315
3316static int callback_for_dl_iterate_phdr(struct dl_phdr_info *info, size_t size, void *data)
3317{
3318 // This function is called through UpdateListOfLoadedSharedLibraries() which is locked.
3319 static std::unordered_set<decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3320
3321 auto newLibs = static_cast<std::vector<std::string>*>(data);
3322 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3323 // Skip \0, "", and kernel pseudo-libs linux-vdso.so.1 or linux-gate.so.1
3324 if (info->dlpi_name && info->dlpi_name[0]
3325#if defined(R__FBSD)
3326 //skip the executable (with null addr)
3327 && info->dlpi_addr
3328 //has no path
3329 && strncmp(info->dlpi_name, "[vdso]", 6)
3330 //the linker does not like to be mmapped
3331 //causes a crash in cling::DynamicLibraryManager::loadLibrary())
3332 //with error message "mmap of entire address space failed: Cannot allocate memory"
3333 && strncmp(info->dlpi_name, "/libexec/ld-elf.so.1", 20)
3334#endif
3335 && strncmp(info->dlpi_name, "linux-vdso.so", 13)
3336 && strncmp(info->dlpi_name, "linux-vdso32.so", 15)
3337 && strncmp(info->dlpi_name, "linux-vdso64.so", 15)
3338 && strncmp(info->dlpi_name, "linux-gate.so", 13))
3339 newLibs->emplace_back(info->dlpi_name);
3340 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3341 }
3342 // No matter what the doc says, return != 0 means "stop the iteration".
3343 return 0;
3344}
3345
3346#endif // R__LINUX || R__FBSD
3347
3348
3349////////////////////////////////////////////////////////////////////////////////
3350
3352{
3353#if defined(R__WIN32) || defined(__CYGWIN__)
3354 HMODULE hModules[1024];
3355 void *hProcess;
3356 unsigned long cbModules;
3357 unsigned int i;
3358 hProcess = (void *)::GetCurrentProcess();
3360 // start at 1 to skip the executable itself
3361 for (i = 1; i < (cbModules / sizeof(void *)); i++) {
3362 static const int bufsize = 260;
3363 wchar_t winname[bufsize];
3364 char posixname[bufsize];
3366#if defined(__CYGWIN__)
3368#else
3369 std::wstring wpath = winname;
3370 std::replace(wpath.begin(), wpath.end(), '\\', '/');
3371 string path(wpath.begin(), wpath.end());
3372 strncpy(posixname, path.c_str(), bufsize);
3373#endif
3376 }
3377 }
3378#elif defined(R__MACOSX)
3379 // fPrevLoadedDynLibInfo stores the *next* image index to look at
3380 uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
3381
3383 // Skip non-dylibs
3384 if (mh->filetype == MH_DYLIB) {
3385 if (const char* imageName = _dyld_get_image_name(imageIndex)) {
3387 }
3388 }
3389
3390 ++imageIndex;
3391 }
3392 fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
3393#elif defined(R__LINUX) || defined(R__FBSD)
3394 // fPrevLoadedDynLibInfo is unused on Linux.
3395 (void) fPrevLoadedDynLibInfo;
3396
3397 std::vector<std::string> newLibs;
3399 for (auto &&lib: newLibs)
3400 RegisterLoadedSharedLibrary(lib.c_str());
3401#else
3402 Error("TCling::UpdateListOfLoadedSharedLibraries",
3403 "Platform not supported!");
3404#endif
3405}
3406
3407namespace {
3408template <int N>
3409static bool StartsWithStrLit(const char *haystack, const char (&needle)[N]) {
3410 return !strncmp(haystack, needle, N - 1);
3411}
3412}
3413
3414////////////////////////////////////////////////////////////////////////////////
3415/// Register a new shared library name with the interpreter; add it to
3416/// fSharedLibs.
3417
3419{
3420 // Ignore NULL filenames, aka "the process".
3421 if (!filename) return;
3422
3423 // Tell the interpreter that this library is available; all libraries can be
3424 // used to resolve symbols.
3425 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3426 if (!DLM->isLibraryLoaded(filename)) {
3427 DLM->loadLibrary(filename, true /*permanent*/, true /*resolved*/);
3428 }
3429
3430#if defined(R__MACOSX)
3431 // Check that this is not a system library that does not exist on disk.
3432 auto lenFilename = strlen(filename);
3433 auto isInMacOSSystemDir = [](const char *fn) {
3434 return StartsWithStrLit(fn, "/usr/lib/") || StartsWithStrLit(fn, "/System/Library/");
3435 };
3436 if (!strcmp(filename, "cl_kernels") // yepp, no directory
3437
3438 // These we should not link with (e.g. because they forward to .tbd):
3439 || StartsWithStrLit(filename, "/usr/lib/system/")
3440 || StartsWithStrLit(filename, "/usr/lib/libc++")
3441 || StartsWithStrLit(filename, "/System/Library/Frameworks/")
3442 || StartsWithStrLit(filename, "/System/Library/PrivateFrameworks/")
3443 || StartsWithStrLit(filename, "/System/Library/CoreServices/")
3444 || StartsWithStrLit(filename, "/usr/lib/libSystem")
3445 || StartsWithStrLit(filename, "/usr/lib/libstdc++")
3446 || StartsWithStrLit(filename, "/usr/lib/libicucore")
3447 || StartsWithStrLit(filename, "/usr/lib/libbsm")
3448 || StartsWithStrLit(filename, "/usr/lib/libobjc")
3449 || StartsWithStrLit(filename, "/usr/lib/libresolv")
3450 || StartsWithStrLit(filename, "/usr/lib/libauto")
3451 || StartsWithStrLit(filename, "/usr/lib/libcups")
3452 || StartsWithStrLit(filename, "/usr/lib/libDiagnosticMessagesClient")
3453 || StartsWithStrLit(filename, "/usr/lib/liblangid")
3454 || StartsWithStrLit(filename, "/usr/lib/libCRFSuite")
3455 || StartsWithStrLit(filename, "/usr/lib/libpam")
3456 || StartsWithStrLit(filename, "/usr/lib/libOpenScriptingUtil")
3457 || StartsWithStrLit(filename, "/usr/lib/libextension")
3458 || StartsWithStrLit(filename, "/usr/lib/libAudioToolboxUtility")
3459 || StartsWithStrLit(filename, "/usr/lib/liboah")
3460 || StartsWithStrLit(filename, "/usr/lib/libRosetta")
3461 || StartsWithStrLit(filename, "/usr/lib/libCoreEntitlements")
3462 || StartsWithStrLit(filename, "/usr/lib/libssl.")
3463 || StartsWithStrLit(filename, "/usr/lib/libcrypto.")
3464
3465 // The system lib is likely in macOS's blob.
3467
3468 // "Link against the umbrella framework 'System.framework' instead"
3469 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_kernel")
3470 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_platform")
3471 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_pthread")
3472
3473 // "cannot link directly with dylib/framework, your binary is not an allowed client of
3474 // /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/
3475 // SDKs/MacOSX.sdk/usr/lib/libAudioToolboxUtility.tbd for architecture x86_64
3476 || (lenFilename > 4 && !strcmp(filename + lenFilename - 4, ".tbd")))
3477 return;
3480 filename = sFileName.Data();
3481#elif defined(__CYGWIN__)
3482 // Check that this is not a system library
3483 static const int bufsize = 260;
3484 char posixwindir[bufsize];
3485 char *windir = getenv("WINDIR");
3486 if (windir)
3488 else
3489 snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
3490 if (strstr(filename, posixwindir) ||
3491 strstr(filename, "/usr/bin/cyg"))
3492 return;
3493#elif defined(R__WIN32)
3494 if (strstr(filename, "/Windows/"))
3495 return;
3496#elif defined (R__LINUX)
3497 if (strstr(filename, "/ld-linux")
3498 || strstr(filename, "linux-gnu/")
3499 || strstr(filename, "/libstdc++.")
3500 || strstr(filename, "/libgcc")
3501 || strstr(filename, "/libc.")
3502 || strstr(filename, "/libdl.")
3503 || strstr(filename, "/libm."))
3504 return;
3505#endif
3506 // Update string of available libraries.
3507 if (!fSharedLibs.IsNull()) {
3508 fSharedLibs.Append(" ");
3509 }
3511}
3512
3513////////////////////////////////////////////////////////////////////////////////
3514/// Load a library file in cling's memory.
3515/// if 'system' is true, the library is never unloaded.
3516/// Return 0 on success, -1 on failure.
3517
3519{
3520 assert(!IsFromRootCling() && "Trying to load library from rootcling!");
3521
3522 // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
3524 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3525 std::string canonLib = DLM->lookupLibrary(filename);
3526 cling::DynamicLibraryManager::LoadLibResult res
3527 = cling::DynamicLibraryManager::kLoadLibNotFound;
3528 if (!canonLib.empty()) {
3529 if (system)
3530 res = DLM->loadLibrary(filename, system, true);
3531 else {
3532 // For the non system libs, we'd like to be able to unload them.
3533 // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
3534 cling::Interpreter::CompilationResult compRes;
3535 HandleInterpreterException(GetMetaProcessorImpl(), Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/nullptr);
3536 if (compRes == cling::Interpreter::kSuccess)
3537 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3538 }
3539 }
3540
3541 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3543 }
3544 switch (res) {
3545 case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
3546 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
3547 default: break;
3548 };
3549 return -1;
3550}
3551
3552////////////////////////////////////////////////////////////////////////////////
3553/// Load a macro file in cling's memory.
3554
3555void TCling::LoadMacro(const char* filename, EErrorCode* error)
3556{
3557 ProcessLine(Form(".L %s", filename), error);
3558}
3559
3560////////////////////////////////////////////////////////////////////////////////
3561/// Let cling process a command line asynch.
3562
3564{
3565 return ProcessLine(line, error);
3566}
3567
3568////////////////////////////////////////////////////////////////////////////////
3569/// Let cling process a command line synchronously, i.e we are waiting
3570/// it will be finished.
3571
3573{
3575 if (gApplication) {
3576 if (gApplication->IsCmdThread()) {
3577 return ProcessLine(line, error);
3578 }
3579 return 0;
3580 }
3581 return ProcessLine(line, error);
3582}
3583
3584////////////////////////////////////////////////////////////////////////////////
3585/// Directly execute an executable statement (e.g. "func()", "3+5", etc.
3586/// however not declarations, like "Int_t x;").
3587
3589{
3590#ifdef R__WIN32
3591 // Test on ApplicationImp not being 0 is needed because only at end of
3592 // TApplication ctor the IsLineProcessing flag is set to 0, so before
3593 // we can not use it.
3595 while (gROOT->IsLineProcessing() && !gApplication) {
3596 Warning("Calc", "waiting for cling thread to free");
3597 gSystem->Sleep(500);
3598 }
3599 gROOT->SetLineIsProcessing();
3600 }
3601#endif // R__WIN32
3603 if (error) {
3604 *error = TInterpreter::kNoError;
3605 }
3606 cling::Value valRef;
3607 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3608 try {
3609 cr = fInterpreter->evaluate(line, valRef);
3610 }
3611 catch (cling::InterpreterException& ex)
3612 {
3613 Error("Calc", "%s.\n%s", ex.what(), "Evaluation of your expression was aborted.");
3614 ex.diagnose();
3615 cr = cling::Interpreter::kFailure;
3616 }
3617
3618 if (cr != cling::Interpreter::kSuccess) {
3619 // Failure in compilation.
3620 if (error) {
3621 // Note: Yes these codes are weird.
3623 }
3624 return 0L;
3625 }
3626 if (!valRef.isValid()) {
3627 // Failure at runtime.
3628 if (error) {
3629 // Note: Yes these codes are weird.
3630 *error = TInterpreter::kDangerous;
3631 }
3632 return 0L;
3633 }
3634
3635 if (valRef.isVoid()) {
3636 return 0;
3637 }
3638
3640#ifdef R__WIN32
3642 gROOT->SetLineHasBeenProcessed();
3643 }
3644#endif // R__WIN32
3645 return valRef.castAs<Longptr_t>();
3646}
3647
3648////////////////////////////////////////////////////////////////////////////////
3649/// Set a getline function to call when input is needed.
3650
3651void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
3652 void (*histaddFunc)(const char* line))
3653{
3654 // If cling offers a replacement for G__pause(), it would need to
3655 // also offer a way to customize at least the history recording.
3656
3657#if defined(R__MUST_REVISIT)
3658#if R__MUST_REVISIT(6,2)
3659 Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3660#endif
3661#endif
3662}
3663
3664////////////////////////////////////////////////////////////////////////////////
3665/// Helper function to increase the internal Cling count of transactions
3666/// that change the AST.
3667
3668Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
3669{
3671
3672 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3673 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3674 || T.macros_begin() != T.macros_end()
3675 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3677 return true;
3678 }
3679 return false;
3680}
3681
3682////////////////////////////////////////////////////////////////////////////////
3683/// Delete object from cling symbol table so it can not be used anymore.
3684/// cling objects are always on the heap.
3685
3687{
3688 // NOTE: When replacing the mutex by a ReadWrite mutex, we **must**
3689 // put in place the Read/Write part here. Keeping the write lock
3690 // here is 'catasptrophic' for scaling as it means that ALL calls
3691 // to RecursiveRemove will take the write lock and performance
3692 // of many threads trying to access the write lock at the same
3693 // time is relatively bad.
3695 // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
3696 // (but isn't at the moment).
3697 if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
3698 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
3699 if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
3701 DeleteGlobal(obj);
3702 ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
3703 }
3704 }
3705}
3706
3707////////////////////////////////////////////////////////////////////////////////
3708/// Pressing Ctrl+C should forward here. In the case where we have had
3709/// continuation requested we must reset it.
3710
3712{
3713 fMetaProcessor->cancelContinuation();
3714 // Reset the Cling state to the state saved by the last call to
3715 // TCling::SaveContext().
3716#if defined(R__MUST_REVISIT)
3717#if R__MUST_REVISIT(6,2)
3719 Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3720#endif
3721#endif
3722}
3723
3724////////////////////////////////////////////////////////////////////////////////
3725/// Reset the Cling state to its initial state.
3726
3728{
3729#if defined(R__MUST_REVISIT)
3730#if R__MUST_REVISIT(6,2)
3732 Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3733#endif
3734#endif
3735}
3736
3737////////////////////////////////////////////////////////////////////////////////
3738/// Reset in Cling the list of global variables to the state saved by the last
3739/// call to TCling::SaveGlobalsContext().
3740///
3741/// Note: Right now, all we do is run the global destructors.
3742
3744{
3746 // TODO:
3747 // Here we should iterate over the transactions (N-3) and revert.
3748 // N-3 because the first three internal to cling.
3749
3750 fInterpreter->runAndRemoveStaticDestructors();
3751}
3752
3753////////////////////////////////////////////////////////////////////////////////
3754/// Reset the Cling 'user' global objects/variables state to the state saved by the last
3755/// call to TCling::SaveGlobalsContext().
3756
3758{
3759#if defined(R__MUST_REVISIT)
3760#if R__MUST_REVISIT(6,2)
3762 Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3763#endif
3764#endif
3765}
3766
3767////////////////////////////////////////////////////////////////////////////////
3768/// Rewind Cling dictionary to the point where it was before executing
3769/// the current macro. This function is typically called after SEGV or
3770/// ctlr-C after doing a longjmp back to the prompt.
3771
3773{
3774#if defined(R__MUST_REVISIT)
3775#if R__MUST_REVISIT(6,2)
3777 Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3778#endif
3779#endif
3780}
3781
3782////////////////////////////////////////////////////////////////////////////////
3783/// Delete obj from Cling symbol table so it cannot be accessed anymore.
3784/// Returns 1 in case of success and 0 in case object was not in table.
3785
3787{
3788#if defined(R__MUST_REVISIT)
3789#if R__MUST_REVISIT(6,2)
3791 Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3792#endif
3793#endif
3794 return 0;
3795}
3796
3797////////////////////////////////////////////////////////////////////////////////
3798/// Undeclare obj called name.
3799/// Returns 1 in case of success, 0 for failure.
3800
3802{
3803#if defined(R__MUST_REVISIT)
3804#if R__MUST_REVISIT(6,2)
3805 Warning("DeleteVariable","should do more that just reseting the value to zero");
3806#endif
3807#endif
3808
3810 llvm::StringRef srName(name);
3811 const char* unscopedName = name;
3812 llvm::StringRef::size_type posScope = srName.rfind("::");
3813 const clang::DeclContext* declCtx = nullptr;
3814 if (posScope != llvm::StringRef::npos) {
3815 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3816 const clang::Decl* scopeDecl
3817 = lh.findScope(srName.substr(0, posScope),
3818 cling::LookupHelper::WithDiagnostics);
3819 if (!scopeDecl) {
3820 Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3821 name);
3822 return 0;
3823 }
3824 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3825 if (!declCtx) {
3826 Error("DeleteVariable",
3827 "Enclosing scope for variable %s is not a declaration context",
3828 name);
3829 return 0;
3830 }
3831 unscopedName += posScope + 2;
3832 }
3833 // Could trigger deserialization of decls.
3834 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
3835 clang::NamedDecl* nVarDecl
3836 = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3837 if (!nVarDecl) {
3838 Error("DeleteVariable", "Unknown variable %s", name);
3839 return 0;
3840 }
3841 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3842 if (!varDecl) {
3843 Error("DeleteVariable", "Entity %s is not a variable", name);
3844 return 0;
3845 }
3846
3847 clang::QualType qType = varDecl->getType();
3848 const clang::Type* type = qType->getUnqualifiedDesugaredType();
3849 // Cannot set a reference's address to nullptr; the JIT can place it
3850 // into read-only memory (ROOT-7100).
3851 if (type->isPointerType()) {
3852 int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3853 // set pointer to invalid.
3854 if (ppInt) *ppInt = nullptr;
3855 }
3856 return 1;
3857}
3858
3859////////////////////////////////////////////////////////////////////////////////
3860/// Save the current Cling state.
3861
3863{
3864#if defined(R__MUST_REVISIT)
3865#if R__MUST_REVISIT(6,2)
3867 Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3868#endif
3869#endif
3870}
3871
3872////////////////////////////////////////////////////////////////////////////////
3873/// Save the current Cling state of global objects.
3874
3876{
3877#if defined(R__MUST_REVISIT)
3878#if R__MUST_REVISIT(6,2)
3880 Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3881#endif
3882#endif
3883}
3884
3885////////////////////////////////////////////////////////////////////////////////
3886/// No op: see TClingCallbacks (used to update the list of globals)
3887
3891
3892////////////////////////////////////////////////////////////////////////////////
3893/// No op: see TClingCallbacks (used to update the list of global functions)
3894
3898
3899////////////////////////////////////////////////////////////////////////////////
3900/// No op: see TClingCallbacks (used to update the list of types)
3901
3903{
3904}
3905
3906////////////////////////////////////////////////////////////////////////////////
3907/// Check in what order the member of a tuple are layout.
3908enum class ETupleOrdering {
3909 kAscending,
3912};
3913
3919
3925
3927{
3928 std::tuple<int,double> value;
3931
3932 size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
3933 size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
3934
3935 size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
3936 size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
3937
3938 size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
3939 size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
3940
3941 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3943 } else if (offset0 == desOffset0 && offset1 == desOffset1) {
3945 } else {
3947 }
3948}
3949
3950static std::string AlternateTuple(const char *classname, const cling::LookupHelper& lh, Bool_t silent)
3951{
3953 std::string alternateName = "TEmulatedTuple";
3954 alternateName.append( classname + 5 );
3955
3956 std::string fullname = "ROOT::Internal::" + alternateName;
3957 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
3958 /*resultType*/nullptr, /* intantiateTemplate= */ false))
3959 return fullname;
3960
3961 {
3962 // Check if we can produce the tuple
3963 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
3964 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
3965 auto deleter = [](TypeInfo_t *type) {
3966 gInterpreter->TypeInfo_Delete(type);
3967 };
3968 std::unique_ptr<TypeInfo_t, decltype(deleter)> type{ gInterpreter->TypeInfo_Factory(), deleter };
3969 while (iter != theEnd) {
3970 gInterpreter->TypeInfo_Init(type.get(), iter->c_str());
3971 if (gInterpreter->TypeInfo_Property(type.get()) & kIsNotReacheable) {
3972 if (!silent)
3973 Error("Load","Could not declare alternate type for %s since %s (or one of its context) is private or protected",
3974 classname, iter->c_str());
3975 return "";
3976 }
3977 ++iter;
3978 }
3979 }
3980
3981 std::string guard_name;
3983 std::ostringstream guard;
3984 guard << "ROOT_INTERNAL_TEmulated_";
3985 guard << guard_name;
3986
3987 std::ostringstream alternateTuple;
3988 alternateTuple << "#ifndef " << guard.str() << "\n";
3989 alternateTuple << "#define " << guard.str() << "\n";
3990 alternateTuple << "namespace ROOT { namespace Internal {\n";
3991 alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
3992 alternateTuple << "template <> struct " << alternateName << " {\n";
3993
3994 // This could also be a compile time choice ...
3995 switch(IsTupleAscending()) {
3997 unsigned int nMember = 0;
3998 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
3999 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4000 while (iter != theEnd) {
4001 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4002 ++iter;
4003 ++nMember;
4004 }
4005 break;
4006 }
4008 unsigned int nMember = tupleContent.fElements.size() - 3;
4009 auto iter = tupleContent.fElements.rbegin() + 1; // skip the 'stars'.
4010 auto theEnd = tupleContent.fElements.rend() - 1; // Skip the template name (tuple).
4011 while (iter != theEnd) {
4012 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4013 ++iter;
4014 --nMember;
4015 }
4016 break;
4017 }
4019 Fatal("TCling::SetClassInfo::AlternateTuple",
4020 "Layout of std::tuple on this platform is unexpected.");
4021 break;
4022 }
4023 }
4024
4025 alternateTuple << "};\n";
4026 alternateTuple << "}}\n";
4027 alternateTuple << "#endif\n";
4028 if (!gCling->Declare(alternateTuple.str().c_str()))
4029 {
4030 // Declare is not silent (yet?), so add an explicit error message
4031 // to indicate the consequence of the syntax errors.
4032 Error("Load","Could not declare %s",alternateName.c_str());
4033 return "";
4034 }
4035 alternateName = "ROOT::Internal::" + alternateName;
4036 return alternateName;
4037}
4038
4039////////////////////////////////////////////////////////////////////////////////
4040/// Set pointer to the TClingClassInfo in TClass.
4041/// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
4042/// already have one.
4043
4045{
4046 // We are shutting down, there is no point in reloading, it only triggers
4047 // redundant deserializations.
4048 if (fIsShuttingDown) {
4049 // Remove the decl_id from the DeclIdToTClass map
4050 if (cl->fClassInfo) {
4053 // Test again as another thread may have set fClassInfo to nullptr.
4054 if (TClinginfo) {
4056 }
4057 delete TClinginfo;
4058 cl->fClassInfo = nullptr;
4059 }
4060 return;
4061 }
4062
4064 if (cl->fClassInfo && !reload) {
4065 return;
4066 }
4067 //Remove the decl_id from the DeclIdToTClass map
4069 if (TClinginfo) {
4071 }
4072 delete TClinginfo;
4073 cl->fClassInfo = nullptr;
4074 std::string name(cl->GetName());
4075
4076 auto SetWithoutClassInfoState = [](TClass *cl)
4077 {
4078 if (cl->fState != TClass::kHasTClassInit) {
4079 if (cl->fStreamerInfo->GetEntries() != 0) {
4081 } else {
4083 }
4084 }
4085 };
4086 // Handle the special case of 'tuple' where we ignore the real implementation
4087 // details and just overlay a 'simpler'/'simplistic' version that is easy
4088 // for the I/O to understand and handle.
4089 if (strncmp(cl->GetName(),"tuple<",strlen("tuple<"))==0) {
4090 if (!reload)
4091 name = AlternateTuple(cl->GetName(), fInterpreter->getLookupHelper(), silent);
4092 if (reload || name.empty()) {
4093 // We could not generate the alternate
4095 return;
4096 }
4097 }
4098
4100 // FIXME: Rather than adding an option to the TClingClassInfo, we should consider combining code
4101 // that is currently in the caller (like SetUnloaded) that disable AutoLoading and AutoParsing and
4102 // code is in the callee (disabling template instantiation) and end up with a more explicit class:
4103 // TClingClassInfoReadOnly.
4105 if (!info->IsValid()) {
4107 delete info;
4108 return;
4109 }
4110 cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
4111 // In case a class contains an external enum, the enum will be seen as a
4112 // class. We must detect this special case and make the class a Zombie.
4113 // Here we assume that a class has at least one method.
4114 // We can NOT call TClass::Property from here, because this method
4115 // assumes that the TClass is well formed to do a lot of information
4116 // caching. The method SetClassInfo (i.e. here) is usually called during
4117 // the building phase of the TClass, hence it is NOT well formed yet.
4119 if (
4120 info->IsValid() &&
4121 !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
4122 ) {
4124 }
4125 if (!info->IsLoaded()) {
4126 if (info->Property() & (kIsNamespace)) {
4127 // Namespaces can have info but no corresponding CINT dictionary
4128 // because they are auto-created if one of their contained
4129 // classes has a dictionary.
4131 }
4132 // this happens when no dictionary is available
4133 delete info;
4134 cl->fClassInfo = nullptr;
4135 }
4136 if (zombieCandidate && !cl->GetCollectionType()) {
4137 cl->MakeZombie();
4138 }
4139 // If we reach here, the info was valid (See early returns).
4140 if (cl->fState != TClass::kHasTClassInit) {
4141 if (cl->fClassInfo) {
4143 } else {
4144// if (TClassEdit::IsSTLCont(cl->GetName()) {
4145// There will be an emulated collection proxy, is that the same?
4146// cl->fState = TClass::kEmulated;
4147// } else {
4148 if (cl->fStreamerInfo->GetEntries() != 0) {
4150 } else {
4152 }
4153// }
4154 }
4155 }
4156 if (cl->fClassInfo) {
4157 TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
4158 }
4159}
4160
4161////////////////////////////////////////////////////////////////////////////////
4162/// Checks if an entity with the specified name is defined in Cling.
4163/// Returns kUnknown if the entity is not defined.
4164/// Returns kWithClassDefInline if the entity exists and has a ClassDefInline
4165/// Returns kKnown if the entity is defined.
4166///
4167/// By default, structs, namespaces, classes, enums and unions are looked for.
4168/// If the flag isClassOrNamespaceOnly is true, classes, structs and
4169/// namespaces only are considered. I.e. if the name is an enum or a union,
4170/// the returned value is false.
4171///
4172/// In the case where the class is not loaded and belongs to a namespace
4173/// or is nested, looking for the full class name is outputting a lots of
4174/// (expected) error messages. Currently the only way to avoid this is to
4175/// specifically check that each level of nesting is already loaded.
4176/// In case of templates the idea is that everything between the outer
4177/// '<' and '>' has to be skipped, e.g.: `aap<pippo<noot>::klaas>::a_class`
4178
4181{
4183 static const char *anonEnum = "anonymous enum ";
4184 static const int cmplen = strlen(anonEnum);
4185
4186 if (fIsShuttingDown || 0 == strncmp(name, anonEnum, cmplen)) {
4187 return kUnknown;
4188 }
4189
4190 // Do not turn on the AutoLoading if it is globally off.
4192
4193 // Avoid the double search below in case the name is a fundamental type
4194 // or typedef to a fundamental type.
4195 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
4196 TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
4197
4199 && fundType->GetType() > 0) {
4200 // Fundamental type, no a class.
4201 return kUnknown;
4202 }
4203
4204 // Migrated from within TClass::GetClass
4205 // If we want to know if a class or a namespace with this name exists in the
4206 // interpreter and this is an enum in the type system, before or after loading
4207 // according to the autoload function argument, return kUnknown.
4209 return kUnknown;
4210
4211 const char *classname = name;
4212
4213 // RAII to suspend and restore auto-loading and auto-parsing based on some external conditions.
4215 int fStoreAutoLoad = 0;
4216 int fStoreAutoParse = 0;
4217 bool fSuspendedAutoParse = false;
4218 public:
4220 fStoreAutoLoad = ((TCling*)gCling)->SetClassAutoLoading(autoload);
4221 }
4222
4223 void SuspendAutoParsing() {
4224 fSuspendedAutoParse = true;
4225 fStoreAutoParse = ((TCling*)gCling)->SetSuspendAutoParsing(true);
4226 }
4227
4230 ((TCling*)gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4231 ((TCling*)gCling)->SetClassAutoLoading(fStoreAutoLoad);
4232 }
4233 };
4234
4236 if (TClassEdit::IsStdPair(classname) || TClassEdit::IsStdPairBase(classname))
4237 autoLoadParseRAII.SuspendAutoParsing();
4238
4239 // First we want to check whether the decl exist, but _without_
4240 // generating any template instantiation. However, the lookup
4241 // still will create a forward declaration of the class template instance
4242 // if it exist. In this case, the return value of findScope will still
4243 // be zero but the type will be initialized.
4244 // Note in the corresponding code in ROOT 5, CINT was not instantiating
4245 // this forward declaration.
4246 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4247 const clang::Type *type = nullptr;
4248 const clang::Decl *decl
4249 = lh.findScope(classname,
4250 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4251 : cling::LookupHelper::NoDiagnostics,
4252 &type, /* intantiateTemplate= */ false );
4253 if (!decl) {
4254 std::string buf = TClassEdit::InsertStd(classname);
4255 decl = lh.findScope(buf,
4256 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4257 : cling::LookupHelper::NoDiagnostics,
4258 &type,false);
4259 }
4260
4261 if (type) {
4262 // If decl==0 and the type is valid, then we have a forward declaration.
4263 if (!decl) {
4264 // If we have a forward declaration for a class template instantiation,
4265 // we want to ignore it if it was produced/induced by the call to
4266 // findScope, however we can not distinguish those from the
4267 // instantiation induce by 'soft' use (and thus also induce by the
4268 // same underlying code paths)
4269 // ['soft' use = use not requiring a complete definition]
4270 // So to reduce the amount of disruption to the existing code we
4271 // would just ignore those for STL collection, for which we really
4272 // need to have the compiled collection proxy (and thus the TClass
4273 // bootstrap).
4274 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4275 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4276 (type->getAsCXXRecordDecl());
4277 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4278 // Since the point of instantiation is invalid, we 'guess' that
4279 // the 'instantiation' of the forwarded type appended in
4280 // findscope.
4282 // For STL Collection we return kUnknown.
4283 return kUnknown;
4284 }
4285 }
4286 }
4288 if (!tci.IsValid()) {
4289 return kUnknown;
4290 }
4293
4294 if (tci.Property() & propertiesMask) {
4295 bool hasClassDefInline = false;
4297 // We do not need to check for ClassDefInline when this is called from
4298 // TClass::Init, we only do it for the call from TClass::GetClass.
4299 auto hasDictionary = tci.GetMethod("Dictionary", "", false, nullptr, ROOT::kExactMatch);
4300 auto implLineFunc = tci.GetMethod("ImplFileLine", "", false, nullptr, ROOT::kExactMatch);
4301
4302 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4303 int lineNumber = 0;
4304 bool success = false;
4305 std::tie(success, lineNumber) =
4308 }
4309 }
4310
4311 // fprintf(stderr,"CheckClassInfo: %s had dict=%d inline=%d\n",name,hasDictionary.IsValid()
4312 // , hasClassDefInline);
4313
4314 // We are now sure that the entry is not in fact an autoload entry.
4316 return kWithClassDefInline;
4317 else
4318 return kKnown;
4319 } else {
4320 // We are now sure that the entry is not in fact an autoload entry.
4321 return kUnknown;
4322 }
4323 }
4324
4325 if (decl)
4326 return kKnown;
4327 else
4328 return kUnknown;
4329
4330 // Setting up iterator part of TClingTypedefInfo is too slow.
4331 // Copy the lookup code instead:
4332 /*
4333 TClingTypedefInfo t(fInterpreter, name);
4334 if (t.IsValid() && !(t.Property() & kIsFundamental)) {
4335 delete[] classname;
4336 return kTRUE;
4337 }
4338 */
4339
4340// const clang::Decl *decl = lh.findScope(name);
4341// if (!decl) {
4342// std::string buf = TClassEdit::InsertStd(name);
4343// decl = lh.findScope(buf);
4344// }
4345
4346// return (decl);
4347}
4348
4349////////////////////////////////////////////////////////////////////////////////
4350/// Return true if there is a class template by the given name ...
4351
4353{
4354 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4355 // Interpreter transaction ahead, needs locking
4357 const clang::Decl *decl
4358 = lh.findClassTemplate(name,
4359 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4360 : cling::LookupHelper::NoDiagnostics);
4361 if (!decl) {
4362 std::string strname = "std::";
4363 strname += name;
4364 decl = lh.findClassTemplate(strname,
4365 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4366 : cling::LookupHelper::NoDiagnostics);
4367 }
4368 return nullptr != decl;
4369}
4370
4371////////////////////////////////////////////////////////////////////////////////
4372/// Create list of pointers to base class(es) for TClass cl.
4373
4375{
4377 if (cl->fBase) {
4378 return;
4379 }
4381 if (!tci) return;
4383 TList *listOfBase = new TList;
4384 while (t.Next()) {
4385 // if name cannot be obtained no use to put in list
4386 if (t.IsValid() && t.Name()) {
4388 listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
4389 }
4390 }
4391 // Now that is complete, publish it.
4392 cl->fBase = listOfBase;
4393}
4394
4395////////////////////////////////////////////////////////////////////////////////
4396/// Create list of pointers to enums for TClass cl.
4397
4399{
4401
4402 const Decl * D;
4403 TClass* cl = enumList.GetClass();
4404 if (cl) {
4405 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4406 }
4407 else {
4408 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4409 }
4410 // Iterate on the decl of the class and get the enums.
4411 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4412 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4413 // Collect all contexts of the namespace.
4414 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4415 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4417 declIter != declEnd; ++declIter) {
4418 // Iterate on all decls for each context.
4419 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4420 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4421 if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4422 // Get name of the enum type.
4423 std::string buf;
4424 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4425 llvm::raw_string_ostream stream(buf);
4426 // Don't trigger fopen of the source file to count lines:
4427 Policy.AnonymousTagLocations = false;
4428 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
4429 stream.flush();
4430 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
4431 if (!buf.empty()) {
4432 const char* name = buf.c_str();
4433 // Add the enum to the list of loaded enums.
4434 enumList.Get(ED, name);
4435 }
4436 }
4437 }
4438 }
4439 }
4440}
4441
4442////////////////////////////////////////////////////////////////////////////////
4443/// Create list of pointers to function templates for TClass cl.
4444
4446{
4448
4449 const Decl * D;
4451 if (cl) {
4452 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4454 }
4455 else {
4456 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4457 funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
4458 }
4459 // Iterate on the decl of the class and get the enums.
4460 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4461 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4462 // Collect all contexts of the namespace.
4463 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4464 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4467 // Iterate on all decls for each context.
4468 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4469 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4470 if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4471 funcTempList->Get(FTD);
4472 }
4473 }
4474 }
4475 }
4476}
4477
4478////////////////////////////////////////////////////////////////////////////////
4479/// Get the scopes representing using declarations of namespace
4480
4481std::vector<std::string> TCling::GetUsingNamespaces(ClassInfo_t *cl) const
4482{
4484 return ci->GetUsingNamespaces();
4485}
4486
4487////////////////////////////////////////////////////////////////////////////////
4488/// Create list of pointers to data members for TClass cl.
4489/// This is now a nop. The creation and updating is handled in
4490/// TListOfDataMembers.
4491
4493{
4494}
4495
4496////////////////////////////////////////////////////////////////////////////////
4497/// Create list of pointers to methods for TClass cl.
4498/// This is now a nop. The creation and updating is handled in
4499/// TListOfFunctions.
4500
4502{
4503}
4504
4505////////////////////////////////////////////////////////////////////////////////
4506/// Update the list of pointers to method for TClass cl
4507/// This is now a nop. The creation and updating is handled in
4508/// TListOfFunctions.
4509
4511{
4512}
4513
4514////////////////////////////////////////////////////////////////////////////////
4515/// Update the list of pointers to data members for TClass cl
4516/// This is now a nop. The creation and updating is handled in
4517/// TListOfDataMembers.
4518
4520{
4521}
4522
4523////////////////////////////////////////////////////////////////////////////////
4524/// Create list of pointers to method arguments for TMethod m.
4525
4527{
4529 if (m->fMethodArgs) {
4530 return;
4531 }
4532 TList *arglist = new TList;
4534 while (t.Next()) {
4535 if (t.IsValid()) {
4537 arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
4538 }
4539 }
4540 m->fMethodArgs = arglist;
4541}
4542
4543////////////////////////////////////////////////////////////////////////////////
4544/// Return whether we are waiting for more input either because the collected
4545/// input contains unbalanced braces or last seen token was a `\` (backslash-newline)
4546
4548{
4549 return fMetaProcessor->awaitingMoreInput();
4550}
4551
4552////////////////////////////////////////////////////////////////////////////////
4553/// Generate a TClass for the given class.
4554/// Since the caller has already check the ClassInfo, let it give use the
4555/// result (via the value of emulation) rather than recalculate it.
4556
4557TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
4558{
4559// For now the following line would lead to the (unwanted) instantiation
4560// of class template. This could/would need to be resurrected only if
4561// we re-introduce so sort of automatic instantiation. However this would
4562// have to include carefull look at the template parameter to avoid
4563// creating instance we can not really use (if the parameter are only forward
4564// declaration or do not have all the necessary interfaces).
4565
4566 // TClingClassInfo tci(fInterpreter, classname);
4567 // if (1 || !tci.IsValid()) {
4568
4569 Version_t version = 1;
4570 if (TClassEdit::IsSTLCont(classname)) {
4571 version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4572 }
4574 TClass *cl = new TClass(classname, version, silent);
4575 if (!emulation) {
4576 // Set the class version if the class is versioned.
4577 // Note that we cannot just call CLASS::Class_Version() as we might not have
4578 // an execution engine (when invoked from rootcling).
4579
4580 // Do not call cl->GetClassVersion(), it has side effects!
4582 if (oldvers == version && cl->GetClassInfo()) {
4583 // We have a version and it might need an update.
4585 if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
4586 // Namespaces don't have class versions.
4587 return cl;
4588 }
4589 TClingMethodInfo mi = cli->GetMethod("Class_Version", "", nullptr /*poffset*/,
4592 if (!mi.IsValid()) {
4593 if (cl->TestBit(TClass::kIsTObject)) {
4594 Error("GenerateTClass",
4595 "Cannot find %s::Class_Version()! Class version might be wrong.",
4596 cl->GetName());
4597 }
4598 return cl;
4599 }
4600 Version_t newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->GetDecl()),
4601 *fInterpreter);
4602 if (newvers == -1) {
4603 // Didn't manage to determine the class version from the AST.
4604 // Use runtime instead.
4605 if ((mi.Property() & kIsStatic)
4606 && !fInterpreter->isInSyntaxOnlyMode()) {
4607 // This better be a static function.
4609 callfunc.SetFunc(&mi);
4610 newvers = callfunc.ExecInt(nullptr);
4611 } else {
4612 Error("GenerateTClass",
4613 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4614 cl->GetName());
4615 }
4616 }
4617 if (newvers != oldvers) {
4618 cl->fClassVersion = newvers;
4619 cl->fStreamerInfo->Expand(newvers + 2 + 10);
4620 }
4621 }
4622 }
4623
4624 return cl;
4625
4626// } else {
4627// return GenerateTClass(&tci,silent);
4628// }
4629}
4630
4631#if 0
4632////////////////////////////////////////////////////////////////////////////////
4633
4635{
4636 includes += info->FileName();
4637
4638 const clang::ClassTemplateSpecializationDecl *templateCl
4639 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->GetDecl());
4640 if (templateCl) {
4641 for(unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
4642 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4643 if (arg.getKind() == clang::TemplateArgument::Type) {
4644 const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
4645
4646 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4647 // We really need a header file.
4648 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4649 if (argdecl) {
4650 includes += ";";
4651 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4653 } else {
4654 std::string Result;
4655 llvm::raw_string_ostream OS(Result);
4656 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4657 Warning("TCling::GenerateTClass","Missing header file for %s",OS.str().c_str());
4658 }
4659 }
4660 }
4661 }
4662 }
4663}
4664#endif
4665
4666////////////////////////////////////////////////////////////////////////////////
4667/// Generate a TClass for the given class.
4668
4670{
4672 if (!info || !info->IsValid()) {
4673 Fatal("GenerateTClass","Requires a valid ClassInfo object");
4674 return nullptr;
4675 }
4676 // We are in the case where we have AST nodes for this class.
4677 TClass *cl = nullptr;
4678 std::string classname;
4679 info->FullName(classname,*fNormalizedCtxt); // Could we use Name()?
4680 if (TClassEdit::IsSTLCont(classname)) {
4681#if 0
4682 Info("GenerateTClass","Will (try to) generate the compiled TClass for %s.",classname.c_str());
4683 // We need to build up the list of required headers, by
4684 // looking at each template arguments.
4687
4688 if (0 == GenerateDictionary(classname.c_str(),includes)) {
4689 // 0 means success.
4690 cl = TClass::LoadClass(classnam.c_str(), silent);
4691 if (cl == 0) {
4692 Error("GenerateTClass","Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4693 }
4694 }
4695#endif
4696 if (cl == nullptr) {
4697 int version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4698 cl = new TClass(classinfo, version, nullptr, nullptr, -1, -1, silent);
4699 }
4700 } else {
4701 // For regular class, just create a TClass on the fly ...
4702 // Not quite useful yet, but that what CINT used to do anyway.
4703 cl = new TClass(classinfo, 1, nullptr, nullptr, -1, -1, silent);
4704 }
4705 // Add the new TClass to the map of declid and TClass*.
4706 if (cl) {
4708 }
4709 return cl;
4710}
4711
4712////////////////////////////////////////////////////////////////////////////////
4713/// Generate the dictionary for the C++ classes listed in the first
4714/// argument (in a semi-colon separated list).
4715/// 'includes' contains a semi-colon separated list of file to
4716/// `#include` in the dictionary.
4717/// For example:
4718/// ~~~ {.cpp}
4719/// gInterpreter->GenerateDictionary("vector<vector<float> >;list<vector<float> >","list;vector");
4720/// ~~~
4721/// or
4722/// ~~~ {.cpp}
4723/// gInterpreter->GenerateDictionary("myclass","myclass.h;myhelper.h");
4724/// ~~~
4725
4726Int_t TCling::GenerateDictionary(const char* classes, const char* includes /* = "" */, const char* /* options = 0 */)
4727{
4728 if (classes == nullptr || classes[0] == 0) {
4729 Error("TCling::GenerateDictionary", "Cannot generate dictionary without passing classes.");
4730 return 0;
4731 }
4732 // Split the input list
4733 std::vector<std::string> listClasses;
4734 for (
4735 const char* current = classes, *prev = classes;
4736 *current != 0;
4737 ++current
4738 ) {
4739 if (*current == ';') {
4740 listClasses.push_back(std::string(prev, current - prev));
4741 prev = current + 1;
4742 }
4743 else if (*(current + 1) == 0) {
4744 listClasses.push_back(std::string(prev, current + 1 - prev));
4745 prev = current + 1;
4746 }
4747 }
4748 std::vector<std::string> listIncludes;
4749 if (!includes)
4750 includes = "";
4751 for (
4752 const char* current = includes, *prev = includes;
4753 *current != 0;
4754 ++current
4755 ) {
4756 if (*current == ';') {
4757 listIncludes.push_back(std::string(prev, current - prev));
4758 prev = current + 1;
4759 }
4760 else if (*(current + 1) == 0) {
4761 listIncludes.push_back(std::string(prev, current + 1 - prev));
4762 prev = current + 1;
4763 }
4764 }
4765 // Generate the temporary dictionary file
4767 std::vector<std::string>(), std::vector<std::string>());
4768}
4769
4770////////////////////////////////////////////////////////////////////////////////
4771/// Return pointer to cling Decl of global/static variable that is located
4772/// at the address given by addr.
4773
4775{
4777 DeclId_t d;
4779
4780 // Could trigger deserialization of decls.
4781 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4782
4783 if (cl) {
4784 d = cl->GetDataMember(name);
4785 // We check if the decl of the data member has an annotation which indicates
4786 // an ioname.
4787 // In case this is true, if the name requested is not the ioname, we
4788 // return 0, as if the member did not exist. In some sense we override
4789 // the information in the TClassInfo instance, isolating the typesystem in
4790 // TClass from the one in the AST.
4791 if (const ValueDecl* decl = (const ValueDecl*) d){
4792 std::string ioName;
4794 if (hasIoName && ioName != name) return nullptr;
4795 }
4796 return d;
4797 }
4798 // We are looking up for something on the TU scope.
4799 // FIXME: We do not want to go through TClingClassInfo(fInterpreter) because of redundant deserializations. That
4800 // interface will actually construct iterators and walk over the decls on the global scope. In would return the first
4801 // occurrence of a decl with the looked up name. However, that's not what C++ lookup would do: if we want to switch
4802 // to a more complete C++ lookup interface we need sift through the found names and pick up the declarations which
4803 // are only fulfilling ROOT's understanding for a Data Member.
4804 // FIXME: We should probably deprecate the TClingClassInfo(fInterpreter) interface and replace it withe something
4805 // similar as below.
4806 using namespace clang;
4807 Sema& SemaR = fInterpreter->getSema();
4808 DeclarationName DName = &SemaR.Context.Idents.get(name);
4809
4810 LookupResult R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4811 Sema::ForExternalRedeclaration);
4812
4813 cling::utils::Lookup::Named(&SemaR, R);
4814
4815 LookupResult::Filter F = R.makeFilter();
4816 // Filter the data-member looking decls.
4817 while (F.hasNext()) {
4818 NamedDecl *D = F.next();
4821 continue;
4822 F.erase();
4823 }
4824 F.done();
4825
4826 if (R.isSingleResult())
4827 return R.getFoundDecl();
4828 return nullptr;
4829}
4830
4831////////////////////////////////////////////////////////////////////////////////
4832/// Return pointer to cling Decl of global/static variable that is located
4833/// at the address given by addr.
4834
4836{
4838
4839 const clang::Decl* possibleEnum = nullptr;
4840 // FInd the context of the decl.
4841 if (cl) {
4843 if (cci) {
4844 const clang::DeclContext* dc = nullptr;
4845 if (const clang::Decl* D = cci->GetDecl()) {
4846 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4848 }
4849 }
4850 if (dc) {
4851 // If it is a data member enum.
4852 // Could trigger deserialization of decls.
4853 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4854 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name, dc);
4855 } else {
4856 Error("TCling::GetEnum", "DeclContext not found for %s .\n", name);
4857 }
4858 }
4859 } else {
4860 // If it is a global enum.
4861 // Could trigger deserialization of decls.
4862 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4863 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name);
4864 }
4865 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4867 return possibleEnum;
4868 }
4869 return nullptr;
4870}
4871
4872////////////////////////////////////////////////////////////////////////////////
4873/// Return pointer to cling DeclId for a global value
4874
4875TInterpreter::DeclId_t TCling::GetDeclId( const llvm::GlobalValue *gv ) const
4876{
4877 if (!gv) return nullptr;
4878
4879 llvm::StringRef mangled_name = gv->getName();
4880
4881 int err = 0;
4882 char* demangled_name_c = TClassEdit::DemangleName(mangled_name.str().c_str(), err);
4883 if (err) {
4884 if (err == -2) {
4885 // It might simply be an unmangled global name.
4886 DeclId_t d;
4888 d = gcl.GetDataMember(mangled_name.str().c_str());
4889 return d;
4890 }
4891 return nullptr;
4892 }
4893
4894 std::string scopename(demangled_name_c);
4896
4897 //
4898 // Separate out the class or namespace part of the
4899 // function name.
4900 //
4901 std::string dataname;
4902
4903 if (!strncmp(scopename.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
4904 scopename.erase(0, sizeof("typeinfo for ")-1);
4905 } else if (!strncmp(scopename.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
4906 scopename.erase(0, sizeof("vtable for ")-1);
4907 } else {
4908 // See if it is a function
4909 std::string::size_type pos = scopename.rfind('(');
4910 if (pos != std::string::npos) {
4911 return nullptr;
4912 }
4913 // Separate the scope and member name
4914 pos = scopename.rfind(':');
4915 if (pos != std::string::npos) {
4916 if ((pos != 0) && (scopename[pos-1] == ':')) {
4917 dataname = scopename.substr(pos+1);
4918 scopename.erase(pos-1);
4919 }
4920 } else {
4921 scopename.clear();
4923 }
4924 }
4925 //fprintf(stderr, "name: '%s'\n", name.c_str());
4926 // Now we have the class or namespace name, so do the lookup.
4927
4928
4929 DeclId_t d;
4930 if (scopename.size()) {
4932 d = cl.GetDataMember(dataname.c_str());
4933 }
4934 else {
4936 d = gcl.GetDataMember(dataname.c_str());
4937 }
4938 return d;
4939}
4940
4941////////////////////////////////////////////////////////////////////////////////
4942/// NOT IMPLEMENTED.
4943
4945{
4946 Error("GetDataMemberWithValue()", "not implemented");
4947 return nullptr;
4948}
4949
4950////////////////////////////////////////////////////////////////////////////////
4951/// Return pointer to cling DeclId for a data member with a given name.
4952
4954{
4955 // NOT IMPLEMENTED.
4956 Error("GetDataMemberAtAddr()", "not implemented");
4957 return nullptr;
4958}
4959
4960////////////////////////////////////////////////////////////////////////////////
4961/// Return the cling mangled name for a method of a class with parameters
4962/// params (params is a string of actual arguments, not formal ones). If the
4963/// class is 0 the global function list will be searched.
4964
4966 const char* params, Bool_t objectIsConst /* = kFALSE */)
4967{
4970 if (cl) {
4973 &offset);
4974 }
4975 else {
4978 func.SetFunc(&gcl, method, params, &offset);
4979 }
4981 if (!mi) return "";
4982 TString mangled_name( mi->GetMangledName() );
4983 delete mi;
4984 return mangled_name;
4985}
4986
4987////////////////////////////////////////////////////////////////////////////////
4988/// Return the cling mangled name for a method of a class with a certain
4989/// prototype, i.e. "char*,int,float". If the class is 0 the global function
4990/// list will be searched.
4991
4993 const char* proto, Bool_t objectIsConst /* = kFALSE */,
4994 EFunctionMatchMode mode /* = kConversionMatch */)
4995{
4997 if (cl) {
4998 return ((TClingClassInfo*)cl->GetClassInfo())->
4999 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5000 }
5002 return gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5003}
5004
5005////////////////////////////////////////////////////////////////////////////////
5006/// Return pointer to cling interface function for a method of a class with
5007/// parameters params (params is a string of actual arguments, not formal
5008/// ones). If the class is 0 the global function list will be searched.
5009
5011 const char* params, Bool_t objectIsConst /* = kFALSE */)
5012{
5015 if (cl) {
5018 &offset);
5019 }
5020 else {
5023 func.SetFunc(&gcl, method, params, &offset);
5024 }
5025 return (void*) func.InterfaceMethod();
5026}
5027
5028////////////////////////////////////////////////////////////////////////////////
5029/// Return pointer to cling interface function for a method of a class with
5030/// a certain name.
5031
5033{
5035 DeclId_t f;
5037 if (cl) {
5038 f = cl->GetMethod(method).GetDeclId();
5039 }
5040 else {
5042 f = gcl.GetMethod(method).GetDeclId();
5043 }
5044 return f;
5045
5046}
5047
5048////////////////////////////////////////////////////////////////////////////////
5049/// Insert overloads of name in cl to res.
5050
5052 std::vector<DeclId_t>& res) const
5053{
5054 clang::Sema& S = fInterpreter->getSema();
5055 clang::ASTContext& Ctx = S.Context;
5056 const clang::Decl* CtxDecl
5057 = cl ? (const clang::Decl*)((TClingClassInfo*)cl)->GetDeclId():
5058 Ctx.getTranslationUnitDecl();
5059 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
5060 const clang::DeclContext* DeclCtx = RecDecl;
5061
5062 if (!DeclCtx)
5064 if (!DeclCtx) return;
5065
5066 clang::DeclarationName DName;
5067 // The DeclarationName is funcname, unless it's a ctor or dtor.
5068 // FIXME: or operator or conversion! See enum clang::DeclarationName::NameKind.
5069
5070 if (RecDecl) {
5071 if (RecDecl->getNameAsString() == funcname) {
5072 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5073 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
5074 } else if (funcname[0] == '~' && RecDecl->getNameAsString() == funcname + 1) {
5075 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5076 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
5077 } else {
5078 DName = &Ctx.Idents.get(funcname);
5079 }
5080 } else {
5081 DName = &Ctx.Idents.get(funcname);
5082 }
5083
5084 // NotForRedeclaration: we want to find names in inline namespaces etc.
5085 clang::LookupResult R(S, DName, clang::SourceLocation(),
5086 Sema::LookupOrdinaryName, clang::Sema::NotForRedeclaration);
5087 R.suppressDiagnostics(); // else lookup with NotForRedeclaration will check access etc
5088 S.LookupQualifiedName(R, const_cast<DeclContext*>(DeclCtx));
5089 if (R.empty()) return;
5090 R.resolveKind();
5091 res.reserve(res.size() + (R.end() - R.begin()));
5092 for (clang::LookupResult::iterator IR = R.begin(), ER = R.end();
5093 IR != ER; ++IR) {
5094 if (const clang::FunctionDecl* FD
5095 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5096 if (!FD->getDescribedFunctionTemplate()) {
5097 res.push_back(FD);
5098 }
5099 } else if (const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5100 // FIXME: multi-level using
5101 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5102 res.push_back(USD);
5103 }
5104 }
5105 }
5106}
5107
5108////////////////////////////////////////////////////////////////////////////////
5109/// Return pointer to cling interface function for a method of a class with
5110/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5111/// function list will be searched.
5112
5114 const char* proto,
5115 Bool_t objectIsConst /* = kFALSE */,
5116 EFunctionMatchMode mode /* = kConversionMatch */)
5117{
5119 void* f;
5120 if (cl) {
5121 f = ((TClingClassInfo*)cl->GetClassInfo())->
5122 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5123 }
5124 else {
5126 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5127 }
5128 return f;
5129}
5130
5131////////////////////////////////////////////////////////////////////////////////
5132/// Return pointer to cling DeclId for a method of a class with
5133/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5134/// function list will be searched.
5135
5137 const char* params,
5138 Bool_t objectIsConst /* = kFALSE */)
5139{
5141 DeclId_t f;
5143 if (cl) {
5144 f = cl->GetMethodWithArgs(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5145 }
5146 else {
5148 f = gcl.GetMethod(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5149 }
5150 return f;
5151}
5152
5153////////////////////////////////////////////////////////////////////////////////
5154/// Return pointer to cling interface function for a method of a class with
5155/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5156/// function list will be searched.
5157
5159 const char* proto,
5160 Bool_t objectIsConst /* = kFALSE */,
5161 EFunctionMatchMode mode /* = kConversionMatch */)
5162{
5164 DeclId_t f;
5166 if (cl) {
5167 f = cl->GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5168 }
5169 else {
5171 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5172 }
5173 return f;
5174}
5175
5176////////////////////////////////////////////////////////////////////////////////
5177/// Return pointer to cling interface function for a method of a class with
5178/// a certain name.
5179
5181{
5183 DeclId_t f;
5185 if (cl) {
5186 f = cl->GetFunctionTemplate(name);
5187 }
5188 else {
5190 f = gcl.GetFunctionTemplate(name);
5191 }
5192 return f;
5193
5194}
5195
5196////////////////////////////////////////////////////////////////////////////////
5197/// The 'name' is known to the interpreter, this function returns
5198/// the internal version of this name (usually just resolving typedefs)
5199/// This is used in particular to synchronize between the name used
5200/// by rootcling and by the run-time environment (TClass)
5201/// Return 0 if the name is not known.
5202
5203void TCling::GetInterpreterTypeName(const char* name, std::string &output, Bool_t full)
5204{
5205 output.clear();
5206
5208
5210 if (!cl.IsValid()) {
5211 return ;
5212 }
5213 if (full) {
5215 return;
5216 }
5217 // Well well well, for backward compatibility we need to act a bit too
5218 // much like CINT.
5221
5222 return;
5223}
5224
5225////////////////////////////////////////////////////////////////////////////////
5226/// Execute a global function with arguments params.
5227///
5228/// FIXME: The cint-based version of this code does not check if the
5229/// SetFunc() call works, and does not do any real checking
5230/// for errors from the Exec() call. It did fetch the most
5231/// recent cint security error and return that in error, but
5232/// this does not really translate well to cling/clang. We
5233/// should enhance these interfaces so that we can report
5234/// compilation and runtime errors properly.
5235
5236void TCling::Execute(const char* function, const char* params, int* error)
5237{
5239 if (error) {
5240 *error = TInterpreter::kNoError;
5241 }
5243 Longptr_t offset = 0L;
5245 func.SetFunc(&cl, function, params, &offset);
5246 func.Exec(nullptr);
5247}
5248
5249////////////////////////////////////////////////////////////////////////////////
5250/// Execute a method from class cl with arguments params.
5251///
5252/// FIXME: The cint-based version of this code does not check if the
5253/// SetFunc() call works, and does not do any real checking
5254/// for errors from the Exec() call. It did fetch the most
5255/// recent cint security error and return that in error, but
5256/// this does not really translate well to cling/clang. We
5257/// should enhance these interfaces so that we can report
5258/// compilation and runtime errors properly.
5259
5260void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5261 const char* params, Bool_t objectIsConst, int* error)
5262{
5264 if (error) {
5265 *error = TInterpreter::kNoError;
5266 }
5267 // If the actual class of this object inherits 2nd (or more) from TObject,
5268 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5269 // hence gInterpreter->Execute will improperly correct the offset.
5270 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5271 Longptr_t offset = 0L;
5274 void* address = (void*)((Longptr_t)addr + offset);
5275 func.Exec(address);
5276}
5277
5278////////////////////////////////////////////////////////////////////////////////
5279
5280void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5281 const char* params, int* error)
5282{
5283 Execute(obj,cl,method,params,false,error);
5284}
5285
5286////////////////////////////////////////////////////////////////////////////////
5287/// Execute a method from class cl with the arguments in array params
5288/// (params[0] ... params[n] = array of TObjString parameters).
5289/// Convert the TObjArray array of TObjString parameters to a character
5290/// string of comma separated parameters.
5291/// The parameters of type 'char' are enclosed in double quotes and all
5292/// internal quotes are escaped.
5293
5295 TObjArray* params, int* error)
5296{
5297 if (!method) {
5298 Error("Execute", "No method was defined");
5299 return;
5300 }
5301 TList* argList = method->GetListOfMethodArgs();
5302 // Check number of actual parameters against of expected formal ones
5303
5304 Int_t nparms = argList->LastIndex() + 1;
5305 Int_t argc = params ? params->GetEntries() : 0;
5306
5307 if (argc > nparms) {
5308 Error("Execute","Too many parameters to call %s, got %d but expected at most %d.",method->GetName(),argc,nparms);
5309 return;
5310 }
5311 if (nparms != argc) {
5312 // Let's see if the 'missing' argument are all defaulted.
5313 // if nparms==0 then either we stopped earlier either argc is also zero and we can't reach here.
5314 assert(nparms > 0);
5315
5316 TMethodArg *arg = (TMethodArg *) argList->At( 0 );
5317 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5318 // There is a default value for the first missing
5319 // argument, so we are fine.
5320 } else {
5321 Int_t firstDefault = -1;
5322 for (Int_t i = 0; i < nparms; i ++) {
5323 arg = (TMethodArg *) argList->At( i );
5324 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5325 firstDefault = i;
5326 break;
5327 }
5328 }
5329 if (firstDefault >= 0) {
5330 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);
5331 } else {
5332 Error("Execute","Too few arguments to call %s, got only %d but expected %d.",method->GetName(),argc,nparms);
5333 }
5334 return;
5335 }
5336 }
5337
5338 const char* listpar = "";
5339 TString complete(10);
5340 if (params) {
5341 // Create a character string of parameters from TObjArray
5342 TIter next(params);
5343 for (Int_t i = 0; i < argc; i ++) {
5344 TMethodArg* arg = (TMethodArg*) argList->At(i);
5346 TObjString* nxtpar = (TObjString*) next();
5347 if (i) {
5348 complete += ',';
5349 }
5350 if (strstr(type.TrueName(*fNormalizedCtxt), "char")) {
5351 TString chpar('\"');
5352 chpar += (nxtpar->String()).ReplaceAll("\"", "\\\"");
5353 // At this point we have to check if string contains \\"
5354 // and apply some more sophisticated parser. Not implemented yet!
5355 complete += chpar;
5356 complete += '\"';
5357 }
5358 else {
5359 complete += nxtpar->String();
5360 }
5361 }
5362 listpar = complete.Data();
5363 }
5364
5365 // And now execute it.
5367 if (error) {
5368 *error = TInterpreter::kNoError;
5369 }
5370 // If the actual class of this object inherits 2nd (or more) from TObject,
5371 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5372 // hence gInterpreter->Execute will improperly correct the offset.
5373 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5376 func.Init(*minfo);
5377 func.SetArgs(listpar);
5378 // Now calculate the 'this' pointer offset for the method
5379 // when starting from the class described by cl.
5380 const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->GetTargetFunctionDecl());
5381 Longptr_t offset = ((TClingClassInfo*)cl->GetClassInfo())->GetOffset(mdecl);
5382 void* address = (void*)((Longptr_t)addr + offset);
5383 func.Exec(address);
5384}
5385
5386////////////////////////////////////////////////////////////////////////////////
5387
5389 const void* args[] /*=0*/,
5390 int nargs /*=0*/,
5391 void* ret/*= 0*/) const
5392{
5393 if (!method) {
5394 Error("ExecuteWithArgsAndReturn", "No method was defined");
5395 return;
5396 }
5397
5399 TClingCallFunc func(*minfo);
5400 func.ExecWithArgsAndReturn(address, args, nargs, ret);
5401}
5402
5403////////////////////////////////////////////////////////////////////////////////
5404/// Execute a cling macro.
5405
5407{
5409 fCurExecutingMacros.push_back(filename);
5411 fCurExecutingMacros.pop_back();
5412 return result;
5413}
5414
5415////////////////////////////////////////////////////////////////////////////////
5416/// Return the file name of the current un-included interpreted file.
5417/// See the documentation for GetCurrentMacroName().
5418
5420{
5421 Warning("GetTopLevelMacroName", "Must change return type!");
5422 return fCurExecutingMacros.back();
5423}
5424
5425////////////////////////////////////////////////////////////////////////////////
5426/// Return the file name of the currently interpreted file,
5427/// included or not. Example to illustrate the difference between
5428/// GetCurrentMacroName() and GetTopLevelMacroName():
5429/// ~~~ {.cpp}
5430/// void inclfile() {
5431/// std::cout << "In inclfile.C" << std::endl;
5432/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5433/// TCling::GetCurrentMacroName() << std::endl;
5434/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5435/// TCling::GetTopLevelMacroName() << std::endl;
5436/// }
5437/// ~~~
5438/// ~~~ {.cpp}
5439/// void mymacro() {
5440/// std::cout << "In mymacro.C" << std::endl;
5441/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5442/// TCling::GetCurrentMacroName() << std::endl;
5443/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5444/// TCling::GetTopLevelMacroName() << std::endl;
5445/// std::cout << " Now calling inclfile..." << std::endl;
5446/// gInterpreter->ProcessLine(".x inclfile.C");
5447/// }
5448/// ~~~
5449/// Running mymacro.C will print:
5450///
5451/// ~~~ {.cpp}
5452/// root [0] .x mymacro.C
5453/// ~~~
5454/// In mymacro.C
5455/// ~~~ {.cpp}
5456/// TCling::GetCurrentMacroName() returns ./mymacro.C
5457/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5458/// ~~~
5459/// Now calling inclfile...
5460/// In inclfile.h
5461/// ~~~ {.cpp}
5462/// TCling::GetCurrentMacroName() returns inclfile.C
5463/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5464/// ~~~
5465
5467{
5468#if defined(R__MUST_REVISIT)
5469#if R__MUST_REVISIT(6,0)
5470 Warning("GetCurrentMacroName", "Must change return type!");
5471#endif
5472#endif
5473 return fCurExecutingMacros.back();
5474}
5475
5476////////////////////////////////////////////////////////////////////////////////
5477/// Return the absolute type of typeDesc.
5478/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
5479/// You need to use the result immediately before it is being overwritten.
5480
5481const char* TCling::TypeName(const char* typeDesc)
5482{
5483 TTHREAD_TLS_DECL(std::string,t);
5484
5485 if (!strstr(typeDesc, "(*)(")) {
5486 const char *s = strchr(typeDesc, ' ');
5487 const char *template_start = strchr(typeDesc, '<');
5488 if (!strcmp(typeDesc, "long long")) {
5489 t = typeDesc;
5490 }
5491 else if (!strncmp(typeDesc, "unsigned ", s + 1 - typeDesc)) {
5492 t = typeDesc;
5493 }
5494 // s is the position of the second 'word' (if any)
5495 // except in the case of templates where there will be a space
5496 // just before any closing '>': eg.
5497 // TObj<std::vector<UShort_t,__malloc_alloc_template<0> > >*
5498 else if (s && (template_start == nullptr || (s < template_start))) {
5499 t = s + 1;
5500 }
5501 else {
5502 t = typeDesc;
5503 }
5504 }
5505 else {
5506 t = typeDesc;
5507 }
5508 auto l = t.length();
5509 while (l > 0 && (t[l - 1] == '*' || t[l - 1] == '&'))
5510 --l;
5511 t.resize(l);
5512 return t.c_str(); // NOLINT
5513}
5514
5515static bool requiresRootMap(const char* rootmapfile)
5516{
5518
5519 llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5520 libName.consume_back(".rootmap");
5521
5522 return !gInterpreter->HasPCMForLibrary(libName.str().c_str());
5523}
5524
5525////////////////////////////////////////////////////////////////////////////////
5526/// Read and parse a rootmapfile in its new format, and return 0 in case of
5527/// success, -1 if the file has already been read, and -3 in case its format
5528/// is the old one (e.g. containing "Library.ClassName"), -4 in case of syntax
5529/// error.
5530
5532{
5533 if (!(rootmapfile && *rootmapfile))
5534 return 0;
5535
5537 return 0; // success
5538
5539 // For "class ", "namespace ", "typedef ", "header ", "enum ", "var " respectively
5540 const std::map<char, unsigned int> keyLenMap = {{'c',6},{'n',10},{'t',8},{'h',7},{'e',5},{'v',4}};
5541
5543#ifdef _MSC_VER
5544 std::replace(rootmapfileNoBackslash.begin(), rootmapfileNoBackslash.end(), '\\', '/');
5545#endif
5546 // Add content of a specific rootmap file
5548 return -1;
5549
5550 // Line 1 is `{ decls }`
5551 std::string lineDirective = std::string("\n#line 2 \"Forward declarations from ") + rootmapfileNoBackslash + "\"\n";
5552
5553 std::ifstream file(rootmapfileNoBackslash);
5554 std::string line;
5555 line.reserve(200);
5556 std::string lib_name;
5557 line.reserve(100);
5558 bool newFormat = false;
5559 while (getline(file, line, '\n')) {
5560 if (!newFormat && (line.compare(0, 8, "Library.") == 0 || line.compare(0, 8, "Declare.") == 0)) {
5561 file.close();
5562 return -3; // old format
5563 }
5564 newFormat = true;
5565
5566 if (line.compare(0, 9, "{ decls }") == 0) {
5567 // forward declarations
5568
5569 while (getline(file, line, '\n')) {
5570 if (line[0] == '[')
5571 break;
5572 if (!uniqueString) {
5573 Error("ReadRootmapFile", "Cannot handle \"{ decls }\" sections in custom rootmap file %s",
5574 rootmapfileNoBackslash.c_str());
5575 return -4;
5576 }
5577 if (!lineDirective.empty())
5578 uniqueString->Append(lineDirective);
5579 uniqueString->Append(line + '\n');
5580 }
5581 }
5582 const char firstChar = line[0];
5583 if (firstChar == '[') {
5584 // new section (library)
5585 auto brpos = line.find(']');
5586 if (brpos == string::npos)
5587 continue;
5588 lib_name = line.substr(1, brpos - 1);
5589 // Remove spaces at the beginning and at the end of the library name
5590 lib_name.erase(lib_name.find_last_not_of(' ') + 1);
5591 lib_name.erase(0, lib_name.find_first_not_of(' '));
5592 if (gDebug > 3) {
5593 TString lib_nameTstr(lib_name.c_str());
5594 TObjArray *tokens = lib_nameTstr.Tokenize(" ");
5595 const char *lib = ((TObjString *)tokens->At(0))->GetName();
5596 const char *wlib = gSystem->DynamicPathName(lib, kTRUE);
5597 if (wlib) {
5598 Info("ReadRootmapFile", "%s: New section for %s", rootmapfile, lib_nameTstr.Data());
5599 } else {
5600 Info("ReadRootmapFile", "%s: Section for %s (library does not exist)", rootmapfile, lib_nameTstr.Data());
5601 }
5602 delete[] wlib;
5603 delete tokens;
5604 }
5605 } else {
5606 auto keyLenIt = keyLenMap.find(firstChar);
5607 if (keyLenIt == keyLenMap.end())
5608 continue;
5609 unsigned int keyLen = keyLenIt->second;
5610 // Do not make a copy, just start after the key
5611 const char *keyname = line.c_str() + keyLen;
5612 if (gDebug > 6)
5613 Info("ReadRootmapFile", "%s: class %s in %s", rootmapfile, keyname, lib_name.c_str());
5615 if (isThere) {
5616 if (lib_name != isThere->GetValue()) { // the same key for two different libs
5617 if (firstChar == 'n') {
5618 if (gDebug > 3)
5619 Info("ReadRootmapFile",
5620 "While processing %s, namespace %s was found to be associated to %s although it is already "
5621 "associated to %s",
5622 rootmapfile, keyname, lib_name.c_str(), isThere->GetValue());
5623 } else if (firstChar == 'h') { // it is a header: add the libname to the list of libs to be loaded.
5624 lib_name += " ";
5625 lib_name += isThere->GetValue();
5626 fMapfile->SetValue(keyname, lib_name.c_str());
5627 } else if (!TClassEdit::IsSTLCont(keyname)) {
5628 Warning("ReadRootmapFile",
5629 "While processing %s, %s %s was found to be associated to %s although it is already "
5630 "associated to %s",
5631 rootmapfile, line.substr(0, keyLen - 1).c_str(), keyname, lib_name.c_str(),
5632 isThere->GetValue());
5633 }
5634 } else { // the same key for the same lib
5635 if (gDebug > 3)
5636 Info("ReadRootmapFile", "While processing %s, key %s was found to be already defined for %s",
5637 rootmapfile, keyname, lib_name.c_str());
5638 }
5639 } else {
5640 fMapfile->SetValue(keyname, lib_name.c_str());
5641 }
5642 }
5643 }
5644 file.close();
5645 return 0;
5646}
5647
5648////////////////////////////////////////////////////////////////////////////////
5649/// Create a resource table and read the (possibly) three resource files,
5650/// i.e. `$ROOTSYS/etc/system<name>` (or `ROOTETCDIR/system<name>`), `$HOME/<name>`
5651/// and `$PWD/<name>`. ROOT always reads ".rootrc" (in TROOT::InitSystem()). You
5652/// can read additional user defined resource files by creating additional TEnv
5653/// objects. By setting the shell variable ROOTENV_NO_HOME=1 the reading of
5654/// the `$HOME/<name>` resource file will be skipped. This might be useful in
5655/// case the home directory resides on an automounted remote file system
5656/// and one wants to avoid the file system from being mounted.
5657
5659{
5660 assert(requiresRootMap(name) && "We have a module!");
5661
5662 if (!requiresRootMap(name))
5663 return;
5664
5666
5668
5669 TString sname = "system";
5670 sname += name;
5672
5674 if (ret == -3) // old format
5676 delete [] s;
5677 if (!gSystem->Getenv("ROOTENV_NO_HOME")) {
5679 ret = ReadRootmapFile(s);
5680 if (ret == -3) // old format
5682 delete [] s;
5685 if (ret == -3) // old format
5687 }
5688 } else {
5690 if (ret == -3) // old format
5692 }
5694}
5695
5696
5697namespace {
5698 using namespace clang;
5699
5700 class ExtVisibleStorageAdder: public RecursiveASTVisitor<ExtVisibleStorageAdder>{
5701 // This class is to be considered an helper for AutoLoading.
5702 // It is a recursive visitor is used to inspect namespaces and specializations
5703 // coming from forward declarations in rootmaps and to set the external visible
5704 // storage flag for them.
5705 public:
5706 ExtVisibleStorageAdder(std::unordered_set<const NamespaceDecl*>& nsSet): fNSSet(nsSet) {};
5707 bool VisitNamespaceDecl(NamespaceDecl* nsDecl) {
5708 // We want to enable the external lookup for this namespace
5709 // because it may shadow the lookup of other names contained
5710 // in that namespace
5711
5712 nsDecl->setHasExternalVisibleStorage();
5713 fNSSet.insert(nsDecl);
5714 return true;
5715 }
5717 // We want to enable the external lookup for this specialization
5718 // because we can provide a definition for it!
5719 if (specDecl->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
5720 //SpecSet.insert(specDecl);
5721 specDecl->setHasExternalLexicalStorage();
5722
5723 // No need to recurse. On the contrary, recursing is actively harmful:
5724 // NOTE: must not recurse to prevent this visitor from triggering loading from
5725 // the external AST source (i.e. autoloading). This would be triggered right here,
5726 // before autoloading is even set up, as rootmap file parsing happens before that.
5727 // Even if autoloading is off and has no effect, triggering loading from external
5728 // AST source resets the flag setHasExternalLexicalStorage(), hiding this specialization
5729 // from subsequent autoloads!
5730 return false;
5731 }
5732 private:
5733 std::unordered_set<const NamespaceDecl*>& fNSSet;
5734 };
5735}
5736
5737////////////////////////////////////////////////////////////////////////////////
5738/// Load map between class and library. If rootmapfile is specified a
5739/// specific rootmap file can be added (typically used by ACLiC).
5740/// In case of error -1 is returned, 0 otherwise.
5741/// The interpreter uses this information to automatically load the shared
5742/// library for a class (autoload mechanism), see the AutoLoad() methods below.
5743
5745{
5747 return 0;
5748
5750
5751 // open the [system].rootmap files
5752 if (!fMapfile) {
5753 fMapfile = new TEnv();
5757 InitRootmapFile(".rootmap");
5758 }
5759
5760 // Prepare a list of all forward declarations for cling
5761 // For some experiments it is easily as big as 500k characters. To be on the
5762 // safe side, we go for 1M.
5763 TUniqueString uniqueString(1048576);
5764
5765 // Load all rootmap files in the dynamic load path ((DY)LD_LIBRARY_PATH, etc.).
5766 // A rootmap file must end with the string ".rootmap".
5768 if (ldpath != fRootmapLoadPath) {
5770#ifdef WIN32
5771 TObjArray* paths = ldpath.Tokenize(";");
5772#else
5773 TObjArray* paths = ldpath.Tokenize(":");
5774#endif
5775 TString d;
5776 for (Int_t i = 0; i < paths->GetEntriesFast(); i++) {
5777 d = ((TObjString *)paths->At(i))->GetString();
5778 // check if directory already scanned
5779 Int_t skip = 0;
5780 for (Int_t j = 0; j < i; j++) {
5781 TString pd = ((TObjString *)paths->At(j))->GetString();
5782 if (pd == d) {
5783 skip++;
5784 break;
5785 }
5786 }
5787 if (!skip) {
5788 void* dirp = gSystem->OpenDirectory(d);
5789 if (dirp) {
5790 if (gDebug > 3) {
5791 Info("LoadLibraryMap", "%s", d.Data());
5792 }
5793 const char* f1;
5794 while ((f1 = gSystem->GetDirEntry(dirp))) {
5795 TString f = f1;
5796 if (f.EndsWith(".rootmap")) {
5797 TString p;
5798 p = d + "/" + f;
5800 if (!fRootmapFiles->FindObject(f) && f != ".rootmap") {
5801 if (gDebug > 4) {
5802 Info("LoadLibraryMap", " rootmap file: %s", p.Data());
5803 }
5805
5806 if (ret == 0)
5807 fRootmapFiles->Add(new TNamed(gSystem->BaseName(f), p.Data()));
5808 if (ret == -3) {
5809 // old format
5811 fRootmapFiles->Add(new TNamed(f, p));
5812 }
5813 }
5814 // else {
5815 // fprintf(stderr,"Reject %s because %s is already there\n",p.Data(),f.Data());
5816 // fRootmapFiles->FindObject(f)->ls();
5817 // }
5818 }
5819 }
5820 if (f.BeginsWith("rootmap")) {
5821 TString p;
5822 p = d + "/" + f;
5823 FileStat_t stat;
5824 if (gSystem->GetPathInfo(p, stat) == 0 && R_ISREG(stat.fMode)) {
5825 Warning("LoadLibraryMap", "please rename %s to end with \".rootmap\"", p.Data());
5826 }
5827 }
5828 }
5829 }
5831 }
5832 }
5833 delete paths;
5834 if (fMapfile->GetTable() && !fMapfile->GetTable()->GetEntries()) {
5835 return -1;
5836 }
5837 }
5838 if (rootmapfile && *rootmapfile) {
5840 if (res == 0) {
5841 //TString p = gSystem->ConcatFileName(gSystem->pwd(), rootmapfile);
5842 //fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), p.Data()));
5844 }
5845 else if (res == -3) {
5846 // old format
5851 }
5852 }
5853 TEnvRec* rec;
5854 TIter next(fMapfile->GetTable());
5855 while ((rec = (TEnvRec*) next())) {
5856 TString cls = rec->GetName();
5857 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
5858 // get the first lib from the list of lib and dependent libs
5859 TString libs = rec->GetValue();
5860 if (libs == "") {
5861 continue;
5862 }
5863 TString delim(" ");
5864 TObjArray* tokens = libs.Tokenize(delim);
5865 const char* lib = ((TObjString*)tokens->At(0))->GetName();
5866 // convert "@@" to "::", we used "@@" because TEnv
5867 // considers "::" a terminator
5868 cls.Remove(0, 8);
5869 cls.ReplaceAll("@@", "::");
5870 // convert "-" to " ", since class names may have
5871 // blanks and TEnv considers a blank a terminator
5872 cls.ReplaceAll("-", " ");
5873 if (gDebug > 6) {
5874 const char* wlib = gSystem->DynamicPathName(lib, kTRUE);
5875 if (wlib) {
5876 Info("LoadLibraryMap", "class %s in %s", cls.Data(), wlib);
5877 }
5878 else {
5879 Info("LoadLibraryMap", "class %s in %s (library does not exist)", cls.Data(), lib);
5880 }
5881 delete[] wlib;
5882 }
5883 delete tokens;
5884 }
5885 else if (!strncmp(cls.Data(), "Declare.", 8) && cls.Length() > 8) {
5886 cls.Remove(0, 8);
5887 // convert "-" to " ", since class names may have
5888 // blanks and TEnv considers a blank a terminator
5889 cls.ReplaceAll("-", " ");
5890 fInterpreter->declare(cls.Data());
5891 }
5892 }
5893
5894 // Process the forward declarations collected
5895 cling::Transaction* T = nullptr;
5896 auto compRes= fInterpreter->declare(uniqueString.Data(), &T);
5897 assert(cling::Interpreter::kSuccess == compRes && "A declaration in a rootmap could not be compiled");
5898
5899 if (compRes!=cling::Interpreter::kSuccess){
5900 Warning("LoadLibraryMap",
5901 "Problems in %s declaring '%s' were encountered.", rootmapfile, uniqueString.Data()) ;
5902 }
5903
5904 if (T) {
5905 ExtVisibleStorageAdder evsAdder(fNSFromRootmaps);
5906 for (auto declIt = T->decls_begin(); declIt < T->decls_end(); ++declIt) {
5907 if (declIt->m_DGR.isSingleDecl()) {
5908 if (Decl* D = declIt->m_DGR.getSingleDecl()) {
5909 if (clang::isa<TagDecl>(D) || clang::isa<NamespaceDecl>(D)) {
5910 evsAdder.TraverseDecl(D);
5911 }
5912 }
5913 }
5914 }
5915 }
5916
5917 // clear duplicates
5918
5919 return 0;
5920}
5921
5922////////////////////////////////////////////////////////////////////////////////
5923/// Scan again along the dynamic path for library maps. Entries for the loaded
5924/// shared libraries are unloaded first. This can be useful after reseting
5925/// the dynamic path through TSystem::SetDynamicPath()
5926/// In case of error -1 is returned, 0 otherwise.
5927
5934
5935////////////////////////////////////////////////////////////////////////////////
5936/// Reload the library map entries coming from all the loaded shared libraries,
5937/// after first unloading the current ones.
5938/// In case of error -1 is returned, 0 otherwise.
5939
5941{
5943 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
5944 const Int_t nrSharedLibs = sharedLibL->GetEntriesFast();
5945 for (Int_t ilib = 0; ilib < nrSharedLibs; ilib++) {
5946 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
5949 if (ret < 0) {
5950 continue;
5951 }
5953 if (sharedLibBaseStr.EndsWith(".dll")) {
5954 rootMapBaseStr.ReplaceAll(".dll", "");
5955 }
5956 else if (sharedLibBaseStr.EndsWith(".DLL")) {
5957 rootMapBaseStr.ReplaceAll(".DLL", "");
5958 }
5959 else if (sharedLibBaseStr.EndsWith(".so")) {
5960 rootMapBaseStr.ReplaceAll(".so", "");
5961 }
5962 else if (sharedLibBaseStr.EndsWith(".sl")) {
5963 rootMapBaseStr.ReplaceAll(".sl", "");
5964 }
5965 else if (sharedLibBaseStr.EndsWith(".dl")) {
5966 rootMapBaseStr.ReplaceAll(".dl", "");
5967 }
5968 else if (sharedLibBaseStr.EndsWith(".a")) {
5969 rootMapBaseStr.ReplaceAll(".a", "");
5970 }
5971 else {
5972 Error("ReloadAllSharedLibraryMaps", "Unknown library type %s", sharedLibBaseStr.Data());
5973 delete sharedLibL;
5974 return -1;
5975 }
5976 rootMapBaseStr += ".rootmap";
5978 if (!rootMap) {
5979 Error("ReloadAllSharedLibraryMaps", "Could not find rootmap %s in path", rootMapBaseStr.Data());
5980 delete[] rootMap;
5981 delete sharedLibL;
5982 return -1;
5983 }
5984 const Int_t status = LoadLibraryMap(rootMap);
5985 if (status < 0) {
5986 Error("ReloadAllSharedLibraryMaps", "Error loading map %s", rootMap);
5987 delete[] rootMap;
5988 delete sharedLibL;
5989 return -1;
5990 }
5991 delete[] rootMap;
5992 }
5993 delete sharedLibL;
5994 return 0;
5995}
5996
5997////////////////////////////////////////////////////////////////////////////////
5998/// Unload the library map entries coming from all the loaded shared libraries.
5999/// Returns 0 if succesful
6000
6002{
6004 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6005 for (Int_t ilib = 0; ilib < sharedLibL->GetEntriesFast(); ilib++) {
6006 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6009 }
6010 delete sharedLibL;
6011 return 0;
6012}
6013
6014////////////////////////////////////////////////////////////////////////////////
6015/// Unload library map entries coming from the specified library.
6016/// Returns -1 in case no entries for the specified library were found,
6017/// 0 otherwise.
6018
6020{
6021 if (!fMapfile || !library || !*library) {
6022 return 0;
6023 }
6025 Ssiz_t idx = libname.Last('.');
6026 if (idx != kNPOS) {
6027 libname.Remove(idx);
6028 }
6029 size_t len = libname.Length();
6030 TEnvRec *rec;
6031 TIter next(fMapfile->GetTable());
6033 Int_t ret = 0;
6034 while ((rec = (TEnvRec *) next())) {
6035 TString cls = rec->GetName();
6036 if (cls.Length() > 2) {
6037 // get the first lib from the list of lib and dependent libs
6038 TString libs = rec->GetValue();
6039 if (libs == "") {
6040 continue;
6041 }
6042 TString delim(" ");
6043 TObjArray* tokens = libs.Tokenize(delim);
6044 const char* lib = ((TObjString *)tokens->At(0))->GetName();
6045 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
6046 // convert "@@" to "::", we used "@@" because TEnv
6047 // considers "::" a terminator
6048 cls.Remove(0, 8);
6049 cls.ReplaceAll("@@", "::");
6050 // convert "-" to " ", since class names may have
6051 // blanks and TEnv considers a blank a terminator
6052 cls.ReplaceAll("-", " ");
6053 }
6054 if (!strncmp(lib, libname.Data(), len)) {
6055 if (fMapfile->GetTable()->Remove(rec) == nullptr) {
6056 Error("UnloadLibraryMap", "entry for <%s, %s> not found in library map table", cls.Data(), lib);
6057 ret = -1;
6058 }
6059 }
6060 delete tokens;
6061 }
6062 }
6063 if (ret >= 0) {
6065 if (!library_rootmap.EndsWith(".rootmap"))
6066 library_rootmap.Append(".rootmap");
6067 TNamed* mfile = nullptr;
6070 delete mfile;
6071 }
6073 }
6074 return ret;
6075}
6076
6077////////////////////////////////////////////////////////////////////////////////
6078/// Register the AutoLoading information for a class.
6079/// libs is a space separated list of libraries.
6080
6081Int_t TCling::SetClassSharedLibs(const char *cls, const char *libs)
6082{
6083 if (!cls || !*cls)
6084 return 0;
6085
6086 TString key = TString("Library.") + cls;
6087 // convert "::" to "@@", we used "@@" because TEnv
6088 // considers "::" a terminator
6089 key.ReplaceAll("::", "@@");
6090 // convert "-" to " ", since class names may have
6091 // blanks and TEnv considers a blank a terminator
6092 key.ReplaceAll(" ", "-");
6093
6095 if (!fMapfile) {
6096 fMapfile = new TEnv();
6098
6101
6102 InitRootmapFile(".rootmap");
6103 }
6104 //fMapfile->SetValue(key, libs);
6106 return 1;
6107}
6108
6109////////////////////////////////////////////////////////////////////////////////
6110/// Demangle the name (from the typeinfo) and then request the class
6111/// via the usual name based interface (TClass::GetClass).
6112
6113TClass *TCling::GetClass(const std::type_info& typeinfo, Bool_t load) const
6114{
6115 int err = 0;
6117 if (err) return nullptr;
6120 return theClass;
6121}
6122
6123////////////////////////////////////////////////////////////////////////////////
6124/// Load library containing the specified class. Returns 0 in case of error
6125/// and 1 in case if success.
6126
6127Int_t TCling::AutoLoad(const std::type_info& typeinfo, Bool_t knowDictNotLoaded /* = kFALSE */)
6128{
6129 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6130
6131 int err = 0;
6133 if (err) {
6134 return 0;
6135 }
6136
6137 std::string demangled_name(demangled_name_c);
6139
6140 // AutoLoad expects (because TClass::GetClass already prepares it that way) a
6141 // shortened name.
6144
6145 // No need to worry about typedef, they aren't any ... but there are
6146 // inlined namespaces ...
6147
6149 if (result == 0) {
6152 }
6153
6154 return result;
6155}
6156
6157////////////////////////////////////////////////////////////////////////////////
6158// Get the list of 'published'/'known' library for the class and load them.
6160{
6161 Int_t status = 0;
6162
6163 // lookup class to find list of dependent libraries
6165 if (!deplibs.IsNull()) {
6166 TString delim(" ");
6167 TObjArray* tokens = deplibs.Tokenize(delim);
6168 for (Int_t i = (tokens->GetEntriesFast() - 1); i > 0; --i) {
6169 const char* deplib = ((TObjString*)tokens->At(i))->GetName();
6170 if (gROOT->LoadClass(cls, deplib) == 0) {
6171 if (gDebug > 0) {
6172 gCling->Info("TCling::AutoLoad",
6173 "loaded dependent library %s for %s", deplib, cls);
6174 }
6175 }
6176 else {
6177 gCling->Error("TCling::AutoLoad",
6178 "failure loading dependent library %s for %s",
6179 deplib, cls);
6180 }
6181 }
6182 const char* lib = ((TObjString*)tokens->At(0))->GetName();
6183 if (lib && lib[0]) {
6184 if (gROOT->LoadClass(cls, lib) == 0) {
6185 if (gDebug > 0) {
6186 gCling->Info("TCling::AutoLoad",
6187 "loaded library %s for %s", lib, cls);
6188 }
6189 status = 1;
6190 }
6191 else {
6192 gCling->Error("TCling::AutoLoad",
6193 "failure loading library %s for %s", lib, cls);
6194 }
6195 }
6196 delete tokens;
6197 }
6198
6199 return status;
6200}
6201
6202////////////////////////////////////////////////////////////////////////////////
6203// Iterate through the data member of the class (either through the TProtoClass
6204// or through Cling) and trigger, recursively, the loading the necessary libraries.
6205// \note `cls` is expected to be already normalized!
6206// \returns 1 on success.
6207Int_t TCling::DeepAutoLoadImpl(const char *cls, std::unordered_set<std::string> &visited,
6208 bool nameIsNormalized)
6209{
6210 // Try to insert; if insertion failed because the entry existed, DeepAutoLoadImpl()
6211 // has previously (within the same call to `AutoLoad()`) tried to load this class
6212 // and we are done, whether success or not, as it won't work better now than before,
6213 // because there is no additional information now compared to before.
6214 if (!visited.insert(std::string(cls)).second)
6215 return 1;
6216
6217 if (ShallowAutoLoadImpl(cls) == 0) {
6218 // If ShallowAutoLoadImpl() has an error, we have an error.
6219 return 0;
6220 }
6221
6222 // Now look through the TProtoClass to load the required library/dictionary
6224 for (auto element : proto->GetData()) {
6225 if (element->IsBasic())
6226 continue;
6227 const char *subtypename = element->GetTypeName();
6229 // Failure to load a dictionary is not (quite) a failure load
6230 // the top-level library. If we return false here, then
6231 // we would end up in a situation where the library and thus
6232 // the dictionary is loaded for "cls" but the TClass is
6233 // not created and/or marked as unavailable (in case where
6234 // AutoLoad is called from TClass::GetClass).
6235 DeepAutoLoadImpl(subtypename, visited, true /*normalized*/);
6236 }
6237 }
6238 return 1;
6239 }
6240
6241 // We found no TProtoClass for cls.
6242 auto classinfo = gInterpreter->ClassInfo_Factory(cls);
6243 if (classinfo && gInterpreter->ClassInfo_IsValid(classinfo)
6244 && !(gInterpreter->ClassInfo_Property(classinfo) & kIsEnum))
6245 {
6247 while (gInterpreter->DataMemberInfo_Next(memberinfo)) {
6248 if (gInterpreter->DataMemberInfo_TypeProperty(memberinfo) & ::kIsFundamental)
6249 continue;
6250 auto membertypename = TClassEdit::GetLong64_Name(gInterpreter->TypeName(gInterpreter->DataMemberInfo_TypeTrueName(memberinfo)));
6252 // Failure to load a dictionary is not (quite) a failure load
6253 // the top-level library. See detailed comment in the TProtoClass
6254 // branch (above).
6255 (void)DeepAutoLoadImpl(membertypename.c_str(), visited, true /*normalized*/);
6256 }
6257 }
6258 gInterpreter->DataMemberInfo_Delete(memberinfo);
6259 }
6260 gInterpreter->ClassInfo_Delete(classinfo);
6261 return 1;
6262}
6263
6264////////////////////////////////////////////////////////////////////////////////
6265/// Load library containing the specified class. Returns 0 in case of error
6266/// and 1 in case if success.
6267
6269{
6270 // Prevent update to IsClassAutoloading between our check and our actions.
6272
6273 // TClass::GetClass explicitly calls gInterpreter->AutoLoad. When called from
6274 // rootcling (in *_rdict.pcm file generation) it is a no op.
6275 // FIXME: We should avoid calling autoload when we know we are not supposed
6276 // to and transform this check into an assert.
6278 // Never load any library from rootcling/genreflex.
6279 if (gDebug > 2) {
6280 Info("TCling::AutoLoad", "Explicitly disabled (the class name is %s)", cls);
6281 }
6282 return 0;
6283 }
6284
6285 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6286
6288
6290 // The library is already loaded as the class's dictionary is known.
6291 // Return success.
6292 // Note: the name (cls) is expected to be normalized as it comes either
6293 // from a callbacks (that can/should calculate the normalized name from the
6294 // decl) or from TClass::GetClass (which does also calculate the normalized
6295 // name).
6296 return 1;
6297 }
6298
6299 if (gDebug > 2) {
6300 Info("TCling::AutoLoad",
6301 "Trying to autoload for %s", cls);
6302 }
6303
6304 if (!gROOT || !gInterpreter || gROOT->TestBit(TObject::kInvalidObject)) {
6305 if (gDebug > 2) {
6306 Info("TCling::AutoLoad",
6307 "Disabled due to gROOT or gInterpreter being invalid/not ready (the class name is %s)", cls);
6308 }
6309 return 0;
6310 }
6311 // Prevent the recursion when the library dictionary are loaded.
6313 // Try using externally provided callback first.
6314 if (fAutoLoadCallBack) {
6316 if (success)
6317 return success;
6318 }
6319
6320 // During the 'Deep' part of the search we will call GetClassSharedLibsForModule
6321 // (when module are enabled) which might end up calling AutoParsing but
6322 // that should only be for the cases where the library has no generated pcm
6323 // and in that case a rootmap should be available.
6324 // This avoids a very costly operation (for generally no gain) but reduce the
6325 // quality of the search (i.e. bad in case of library with no pcm and no rootmap
6326 // file).
6328 std::unordered_set<std::string> visited;
6329 return DeepAutoLoadImpl(cls, visited, false /*normalized*/);
6330}
6331
6332////////////////////////////////////////////////////////////////////////////////
6333/// Parse the payload or header.
6334
6335static cling::Interpreter::CompilationResult ExecAutoParse(const char *what,
6336 Bool_t header,
6337 cling::Interpreter *interpreter)
6338{
6339 std::string code = gNonInterpreterClassDef ;
6340 if (!header) {
6341 // This is the complete header file content and not the
6342 // name of a header.
6343 code += what;
6344
6345 } else {
6346 code += ("#include \"");
6347 code += what;
6348 code += "\"\n";
6349 }
6350 code += ("#ifdef __ROOTCLING__\n"
6351 "#undef __ROOTCLING__\n"
6353 "#endif");
6354
6355 cling::Interpreter::CompilationResult cr;
6356 {
6357 // scope within which diagnostics are de-activated
6358 // For now we disable diagnostics because we saw them already at
6359 // dictionary generation time. That won't be an issue with the PCMs.
6360
6361 Sema &SemaR = interpreter->getSema();
6363 clangDiagSuppr diagSuppr(SemaR.getDiagnostics());
6364
6365 #if defined(R__MUST_REVISIT)
6366 #if R__MUST_REVISIT(6,2)
6367 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
6368 #endif
6369 #endif
6370
6371 cr = interpreter->parseForModule(code);
6372 }
6373 return cr;
6374}
6375
6376////////////////////////////////////////////////////////////////////////////////
6377/// Helper routine for TCling::AutoParse implementing the actual call to the
6378/// parser and looping over template parameters (if
6379/// any) and when they don't have a registered header to autoparse,
6380/// recurse over their template parameters.
6381///
6382/// Returns the number of header parsed.
6383
6385{
6386 // We assume the lock has already been taken.
6387 // R__LOCKGUARD(gInterpreterMutex);
6388
6390 unsigned long offset = 0;
6391 if (strncmp(cls, "const ", 6) == 0) {
6392 offset = 6;
6393 }
6394
6395 // Loop on the possible autoparse keys
6396 bool skipFirstEntry = false;
6397 std::vector<std::string> autoparseKeys;
6398 if (strchr(cls, '<')) {
6399 int nestedLoc = 0;
6401 // Check if we can skip the name of the template in the autoparses
6402 // Take all the scopes one by one. If all of them are in the AST, we do not
6403 // need to autoparse for that particular template.
6404 if (!autoparseKeys.empty() && !autoparseKeys[0].empty()) {
6405 // autoparseKeys[0] is empty when the input is not a template instance.
6406 // The case strchr(cls, '<') != 0 but still not a template instance can
6407 // happens 'just' for string (GetSplit replaces the template by the short name
6408 // and then use that for thew splitting)
6410 auto tokens = templateName.Tokenize("::");
6411 clang::NamedDecl* previousScopeAsNamedDecl = nullptr;
6412 clang::DeclContext* previousScopeAsContext = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
6414 previousScopeAsContext = fInterpreter->getSema().getStdNamespace();
6415 auto nTokens = tokens->GetEntriesFast();
6416 for (Int_t tk = 0; tk < nTokens; ++tk) {
6417 auto scopeObj = tokens->UncheckedAt(tk);
6418 auto scopeName = ((TObjString*) scopeObj)->String().Data();
6419 previousScopeAsNamedDecl = cling::utils::Lookup::Named(&fInterpreter->getSema(), scopeName, previousScopeAsContext);
6420 // Check if we have multiple nodes in the AST with this name
6421 if ((clang::NamedDecl*)-1 == previousScopeAsNamedDecl) break;
6422 previousScopeAsContext = llvm::dyn_cast_or_null<clang::DeclContext>(previousScopeAsNamedDecl);
6423 if (!previousScopeAsContext) break; // this is not a context
6424 }
6425 delete tokens;
6426 // Now, let's check if the last scope, the template, has a definition, i.e. it's not a fwd decl
6427 if ((clang::NamedDecl*)-1 != previousScopeAsNamedDecl) {
6428 if (auto templateDecl = llvm::dyn_cast_or_null<clang::ClassTemplateDecl>(previousScopeAsNamedDecl)) {
6429 if (auto templatedDecl = templateDecl->getTemplatedDecl()) {
6430 skipFirstEntry = templatedDecl->hasDefinition();
6431 }
6432 }
6433 }
6434
6435 }
6436 }
6437 if (topLevel) autoparseKeys.emplace_back(cls);
6438
6439 for (const auto & apKeyStr : autoparseKeys) {
6440 if (skipFirstEntry) {
6441 skipFirstEntry=false;
6442 continue;
6443 }
6444 if (apKeyStr.empty()) continue;
6445 const char *apKey = apKeyStr.c_str();
6447 // If the class was not looked up
6448 if (gDebug > 1) {
6449 Info("TCling::AutoParse",
6450 "Starting autoparse for %s\n", apKey);
6451 }
6452 if (fLookedUpClasses.insert(normNameHash).second) {
6453 auto const &iter = fClassesHeadersMap.find(normNameHash);
6454 if (iter != fClassesHeadersMap.end()) {
6455 const cling::Transaction *T = fInterpreter->getCurrentTransaction();
6457 auto const &hNamesPtrs = iter->second;
6458 if (gDebug > 1) {
6459 Info("TCling::AutoParse",
6460 "We can proceed for %s. We have %s headers.", apKey, std::to_string(hNamesPtrs.size()).c_str());
6461 }
6462 for (auto & hName : hNamesPtrs) {
6463 if (fParsedPayloadsAddresses.count(hName) == 1) continue;
6464 if (0 != fPayloads.count(normNameHash)) {
6465 float initRSSval=0.f, initVSIZEval=0.f;
6466 (void) initRSSval; // Avoid unused var warning
6467 (void) initVSIZEval;
6468 if (gDebug > 0) {
6469 Info("AutoParse",
6470 "Parsing full payload for %s", apKey);
6473 initRSSval = 1e-3*info.fMemResident;
6474 initVSIZEval = 1e-3*info.fMemVirtual;
6475 }
6477 if (cRes != cling::Interpreter::kSuccess) {
6478 if (hName[0] == '\n')
6479 Error("AutoParse", "Error parsing payload code for class %s with content:\n%s", apKey, hName);
6480 } else {
6483 if (gDebug > 0){
6486 float endRSSval = 1e-3*info.fMemResident;
6487 float endVSIZEval = 1e-3*info.fMemVirtual;
6488 Info("Autoparse", ">>> RSS key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initRSSval, endRSSval, endRSSval-initRSSval);
6489 Info("Autoparse", ">>> VSIZE key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initVSIZEval, endVSIZEval, endVSIZEval-initVSIZEval);
6490 }
6491 }
6492 } else if (!IsLoaded(hName)) {
6493 if (gDebug > 0) {
6494 Info("AutoParse",
6495 "Parsing single header %s", hName);
6496 }
6498 if (cRes != cling::Interpreter::kSuccess) {
6499 Error("AutoParse", "Error parsing headerfile %s for class %s.", hName, apKey);
6500 } else {
6502 }
6503 }
6504 }
6505 }
6506 else {
6507 // There is no header registered for this class, if this a
6508 // template, it will be instantiated if/when it is requested
6509 // and if we do no load/parse its components we might end up
6510 // not using an eventual specialization.
6511 if (strchr(apKey, '<')) {
6513 }
6514 }
6515 }
6516 }
6517
6518 return nHheadersParsed;
6519
6520}
6521
6522////////////////////////////////////////////////////////////////////////////////
6523/// Parse the headers relative to the class
6524/// Returns 1 in case of success, 0 in case of failure
6525
6527{
6528 if (llvm::StringRef(cls).contains("(lambda)"))
6529 return 0;
6530
6533 return AutoLoad(cls);
6534 } else {
6535 return 0;
6536 }
6537 }
6538
6540
6541 if (gDebug > 1) {
6542 Info("TCling::AutoParse",
6543 "Trying to autoparse for %s", cls);
6544 }
6545
6546 // The catalogue of headers is in the dictionary
6548 && !gClassTable->GetDictNorm(cls)) {
6549 // Need RAII against recursive (dictionary payload) parsing (ROOT-8445).
6551 fInterpreter->getSema());
6552 AutoLoad(cls, true /*knowDictNotLoaded*/);
6553 }
6554
6555 // Prevent the recursion when the library dictionary are loaded.
6557
6558 // No recursive header parsing on demand; we require headers to be standalone.
6560
6561 Int_t nHheadersParsed = AutoParseImplRecurse(cls,/*topLevel=*/ true);
6562
6564
6565 return nHheadersParsed > 0 ? 1 : 0;
6566}
6567
6568// This is a function which gets callback from cling when DynamicLibraryManager->loadLibrary failed for some reason.
6569// Try to solve the problem by AutoLoading. Return true when AutoLoading success, return
6570// false if not.
6571bool TCling::LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
6572{
6574 if (errMsg.contains("undefined symbol: ")) {
6575 // This branch is taken when the callback was from DynamicLibraryManager::loadLibrary
6576 std::string mangled_name = std::string(errMsg.split("undefined symbol: ").second);
6577 void* res = ((TCling*)gCling)->LazyFunctionCreatorAutoload(mangled_name);
6578 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
6579 if (res && DLM && (DLM->loadLibrary(libStem, permanent, resolved) == cling::DynamicLibraryManager::kLoadLibSuccess))
6580 // Return success when LazyFunctionCreatorAutoload could find mangled_name
6581 return true;
6582 } else {
6583 // The callback is from IncrementalExecutor::diagnoseUnresolvedSymbols
6585 return true;
6586 }
6587
6588 return false;
6589}
6590
6591////////////////////////////////////////////////////////////////////////////////
6592/// Autoload a library based on a missing symbol.
6593
6596
6597 // We have already loaded the library.
6598 if (void* Addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name))
6599 return Addr;
6600
6601 const cling::DynamicLibraryManager &DLM = *GetInterpreterImpl()->getDynamicLibraryManager();
6603
6604 auto LibLoader = [](const std::string& LibName) -> bool {
6605 if (gSystem->Load(LibName.c_str(), "", false) < 0) {
6606 ::Error("TCling__LazyFunctionCreatorAutoloadForModule",
6607 "Failed to load library %s", LibName.c_str());
6608 return false;
6609 }
6610 return true; //success.
6611 };
6612
6613 std::string libName = DLM.searchLibrariesForSymbol(mangled_name,
6614 /*searchSystem=*/ true);
6615
6616 assert(!llvm::StringRef(libName).startswith("libNew") &&
6617 "We must not resolve symbols from libNew!");
6618
6619 if (libName.empty())
6620 return nullptr;
6621
6622 if (!LibLoader(libName))
6623 return nullptr;
6624
6625 return llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name);
6626}
6627
6628////////////////////////////////////////////////////////////////////////////////
6629
6631{
6632 return fNSFromRootmaps.count(nsDecl) != 0;
6633}
6634
6635////////////////////////////////////////////////////////////////////////////////
6636/// Internal function. Actually do the update of the ClassInfo when seeing
6637// new TagDecl or NamespaceDecl.
6638void TCling::RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
6639{
6640
6642 if (cci) {
6643 // If we only had a forward declaration then update the
6644 // TClingClassInfo with the definition if we have it now.
6645 const NamedDecl *oldDef = llvm::dyn_cast_or_null<NamedDecl>(cci->GetDecl());
6646 if (!oldDef || (def && def != oldDef)) {
6647 cl->ResetCaches();
6648 TClass::RemoveClassDeclId(cci->GetDeclId());
6649 if (def) {
6650 if (cci->GetType()) {
6651 // It's a tag decl, not a namespace decl.
6652 cci->Init(*cci->GetType());
6653 TClass::AddClassToDeclIdMap(cci->GetDeclId(), cl);
6654 } else {
6655 Error("RefreshClassInfo", "Should not need to update the classInfo a non type decl: %s", oldDef->getNameAsString().c_str());
6656 }
6657 }
6658 }
6659 } else if (!cl->TestBit(TClass::kLoading) && !cl->fHasRootPcmInfo) {
6660 cl->ResetCaches();
6661 // yes, this is almost a waste of time, but we do need to lookup
6662 // the 'type' corresponding to the TClass anyway in order to
6663 // preserve the opaque typedefs (Double32_t)
6664 if (!alias && def != nullptr)
6666 else
6668 if (((TClingClassInfo *)cl->fClassInfo)->IsValid()) {
6669 // We now need to update the state and bits.
6670 if (cl->fState != TClass::kHasTClassInit) {
6671 // if (!cl->fClassInfo->IsValid()) cl->fState = TClass::kForwardDeclared; else
6673 }
6674 TClass::AddClassToDeclIdMap(((TClingClassInfo *)(cl->fClassInfo))->GetDeclId(), cl);
6675 } else {
6676 delete ((TClingClassInfo *)cl->fClassInfo);
6677 cl->fClassInfo = nullptr;
6678 }
6679 }
6680}
6681
6682////////////////////////////////////////////////////////////////////////////////
6683/// Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
6685{
6686 const TagDecl *td = dyn_cast<TagDecl>(ND);
6688 const NamedDecl *canon = nullptr;
6689
6690 std::string name;
6691 TagDecl* tdDef = nullptr;
6692 if (td) {
6693 canon = tdDef = td->getDefinition();
6694 // Let's pass the decl to the TClass only if it has a definition.
6695 if (!tdDef) return;
6696
6697 if (!tdDef->isCompleteDefinition() || llvm::isa<clang::FunctionDecl>(tdDef->getDeclContext())) {
6698 // Ignore incomplete definition.
6699 // Ignore declaration within a function.
6700 return;
6701 }
6702
6703 auto declName = tdDef->getNameAsString();
6704 // Check if we have registered the unqualified name into the list
6705 // of TClass that are in kNoInfo, kEmulated or kFwdDeclaredState.
6706 // Since this is used as heureutistic to avoid spurrious calls to GetNormalizedName
6707 // the unqualified name is sufficient (and the fully qualified name might be
6708 // 'wrong' if there is difference in spelling in the template paramters (for example)
6710 // 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() );
6711 return;
6712 }
6713
6714 clang::QualType type(tdDef->getTypeForDecl(), 0);
6716 } else if (ns) {
6717 canon = ns->getCanonicalDecl();
6718 name = ND->getQualifiedNameAsString();
6719 } else {
6720 name = ND->getQualifiedNameAsString();
6721 }
6722
6723 // Supposedly we are being called while something is being
6724 // loaded ... let's now tell the autoloader to do the work
6725 // yet another time.
6727 // FIXME: There can be more than one TClass for a single decl.
6728 // for example vector<double> and vector<Double32_t>
6729 TClass* cl = (TClass*)gROOT->GetListOfClasses()->FindObject(name.c_str());
6730 if (cl && GetModTClasses().find(cl) == GetModTClasses().end()) {
6731 RefreshClassInfo(cl, canon, false);
6732 }
6733 // And here we should find the other 'aliases' (eg. vector<Double32_t>)
6734 // and update them too:
6735 // foreach(aliascl in gROOT->GetListOfClasses()->FindAliasesOf(name.c_str()))
6736 // RefreshClassInfo(cl, tdDef, true);
6737}
6738
6739////////////////////////////////////////////////////////////////////////////////
6740/// No op: see TClingCallbacks
6741
6742void TCling::UpdateClassInfo(char* item, Long_t tagnum)
6743{
6744}
6745
6746//______________________________________________________________________________
6747//FIXME: Factor out that function in TClass, because TClass does it already twice
6748void TCling::UpdateClassInfoWork(const char* item)
6749{
6750 // This is a no-op as part of the API.
6751 // TCling uses UpdateClassInfoWithDecl() instead.
6752}
6753
6754////////////////////////////////////////////////////////////////////////////////
6755/// Update all canvases at end the terminal input command.
6756
6758{
6759 TIter next(gROOT->GetListOfCanvases());
6760 TVirtualPad* canvas;
6761 while ((canvas = (TVirtualPad*)next())) {
6762 canvas->Update();
6763 }
6764}
6765
6766////////////////////////////////////////////////////////////////////////////////
6767
6768void TCling::UpdateListsOnCommitted(const cling::Transaction &T) {
6769 std::set<TClass*> modifiedTClasses; // TClasses that require update after this transaction
6770
6771 // If the transaction does not contain anything we can return earlier.
6772 if (!HandleNewTransaction(T)) return;
6773
6774 bool isTUTransaction = false;
6775 if (!T.empty() && T.decls_begin() + 1 == T.decls_end() && !T.hasNestedTransactions()) {
6776 clang::Decl* FirstDecl = *(T.decls_begin()->m_DGR.begin());
6777 if (llvm::isa<clang::TranslationUnitDecl>(FirstDecl)) {
6778 // The is the first transaction, we have to expose to meta
6779 // what's already in the AST.
6780 isTUTransaction = true;
6781 }
6782 }
6783
6784 std::set<const void*> TransactionDeclSet;
6785 if (!isTUTransaction && T.decls_end() - T.decls_begin()) {
6786 const clang::Decl* WrapperFD = T.getWrapperFD();
6787 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6788 I != E; ++I) {
6789 if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl
6790 && I->m_Call != cling::Transaction::kCCIHandleTagDeclDefinition)
6791 continue;
6792
6793 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6794 DE = I->m_DGR.end(); DI != DE; ++DI) {
6795 if (*DI == WrapperFD)
6796 continue;
6797 TransactionDeclSet.insert(*DI);
6798 ((TCling*)gCling)->HandleNewDecl(*DI, false, modifiedTClasses);
6799 }
6800 }
6801 }
6802
6803 // The above might trigger more decls to be deserialized.
6804 // Thus the iteration over the deserialized decls must be last.
6805 for (cling::Transaction::const_iterator I = T.deserialized_decls_begin(),
6806 E = T.deserialized_decls_end(); I != E; ++I) {
6807 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6808 DE = I->m_DGR.end(); DI != DE; ++DI)
6809 if (TransactionDeclSet.find(*DI) == TransactionDeclSet.end()) {
6810 //FIXME: HandleNewDecl should take DeclGroupRef
6811 ((TCling*)gCling)->HandleNewDecl(*DI, /*isDeserialized*/true,
6813 }
6814 }
6815
6816
6817 // When fully building the reflection info in TClass, a deserialization
6818 // could be triggered, which may result in request for building the
6819 // reflection info for the same TClass. This in turn will clear the caches
6820 // for the TClass in-flight and cause null ptr derefs.
6821 // FIXME: This is a quick fix, solving most of the issues. The actual
6822 // question is: Shouldn't TClass provide a lock mechanism on update or lock
6823 // itself until the update is done.
6824 //
6825 std::vector<TClass*> modifiedTClassesDiff(modifiedTClasses.size());
6826 std::vector<TClass*>::iterator it;
6828 ((TCling*)gCling)->GetModTClasses().begin(),
6829 ((TCling*)gCling)->GetModTClasses().end(),
6832
6833 // Lock the TClass for updates
6834 ((TCling*)gCling)->GetModTClasses().insert(modifiedTClassesDiff.begin(),
6836 for (std::vector<TClass*>::const_iterator I = modifiedTClassesDiff.begin(),
6837 E = modifiedTClassesDiff.end(); I != E; ++I) {
6838 // Make sure the TClass has not been deleted.
6839 if (!gROOT->GetListOfClasses()->FindObject(*I)) {
6840 continue;
6841 }
6842 // Could trigger deserialization of decls.
6843 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
6844 // Unlock the TClass for updates
6845 ((TCling*)gCling)->GetModTClasses().erase(*I);
6846
6847 }
6848}
6849
6850///\brief Invalidate stored TCling state for declarations included in transaction `T'.
6851///
6852void TCling::UpdateListsOnUnloaded(const cling::Transaction &T)
6853{
6855
6856 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6857 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6858 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6859 (TListOfEnums *)gROOT->GetListOfEnums());
6860
6861 cling::Transaction::const_nested_iterator iNested = T.nested_begin();
6862 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6863 I != E; ++I) {
6864 if (I->m_Call == cling::Transaction::kCCIHandleVTable)
6865 continue;
6866 if (I->m_Call == cling::Transaction::kCCINone) {
6868 ++iNested;
6869 continue;
6870 }
6871
6872 for (auto &D : I->m_DGR)
6874 }
6875}
6876
6877///\brief Invalidate cached TCling information for the given global declaration.
6878///
6880 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6881 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6882 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6883 (TListOfEnums *)gROOT->GetListOfEnums());
6885}
6886
6887///\brief Invalidate cached TCling information for the given declaration, and
6888/// removed it from the appropriate object list.
6889///\param[in] Lists - std::tuple<TListOfDataMembers&, TListOfFunctions&,
6890/// TListOfFunctionTemplates&, TListOfEnums&>
6891/// of pointers to the (global/class) object lists.
6892///\param[in] D - Decl to discard.
6893///
6897 TListOfEnums*> &Lists, const Decl *D) {
6898 if (D->isFromASTFile()) // `D' came from the PCH; ignore
6899 return;
6900
6901 TListOfDataMembers &LODM = *(std::get<0>(Lists));
6902 TListOfFunctions &LOF = *(std::get<1>(Lists));
6903 TListOfFunctionTemplates &LOFT = *(std::get<2>(Lists));
6904 TListOfEnums &LOE = *(std::get<3>(Lists));
6905
6907 TObject *O = LODM.Find((TDictionary::DeclId_t)D);
6908 if (LODM.GetClass())
6909 RemoveAndInvalidateObject(LODM, static_cast<TDataMember *>(O));
6910 else
6911 RemoveAndInvalidateObject(LODM, static_cast<TGlobal *>(O));
6912 } else if (isa<FunctionDecl>(D)) {
6914 } else if (isa<FunctionTemplateDecl>(D)) {
6916 } else if (isa<EnumDecl>(D)) {
6917 TEnum *E = LOE.Find((TDictionary::DeclId_t)D);
6918 if (!E)
6919 return;
6920
6921 // Try to invalidate enumerators (for unscoped enumerations).
6922 for (TIter I = E->GetConstants(); auto EC = (TEnumConstant *)I(); )
6924 (TEnumConstant *)LODM.FindObject(EC->GetName()));
6925
6927 } else if (isa<RecordDecl>(D) || isa<NamespaceDecl>(D)) {
6929 return;
6930
6931 std::vector<TClass *> Classes;
6932 if (!TClass::GetClass(D->getCanonicalDecl(), Classes))
6933 return;
6934 for (auto &C : Classes) {
6935 auto Lists = std::make_tuple((TListOfDataMembers *)C->GetListOfDataMembers(),
6936 (TListOfFunctions *)C->GetListOfMethods(),
6937 (TListOfFunctionTemplates *)C->GetListOfFunctionTemplates(),
6938 (TListOfEnums *)C->GetListOfEnums());
6939 for (auto &I : cast<DeclContext>(D)->decls())
6941
6942 // For NamespaceDecl (redeclarable), only invalidate this redecl.
6943 if (D->getKind() != Decl::Namespace
6944 || cast<NamespaceDecl>(D)->isOriginalNamespace())
6945 C->ResetClassInfo();
6946 }
6947 }
6948}
6949
6950////////////////////////////////////////////////////////////////////////////////
6951// If an autoparse was done during a transaction and that it is rolled back,
6952// we need to make sure the next request for the same autoparse will be
6953// honored.
6954void TCling::TransactionRollback(const cling::Transaction &T) {
6955 auto const &triter = fTransactionHeadersMap.find(&T);
6956 if (triter != fTransactionHeadersMap.end()) {
6957 std::size_t normNameHash = triter->second;
6958
6960
6961 auto const &iter = fClassesHeadersMap.find(normNameHash);
6962 if (iter != fClassesHeadersMap.end()) {
6963 auto const &hNamesPtrs = iter->second;
6964 for (auto &hName : hNamesPtrs) {
6965 if (gDebug > 0) {
6966 Info("TransactionRollback",
6967 "Restoring ability to autoaparse: %s", hName);
6968 }
6970 }
6971 }
6972 }
6973}
6974
6975////////////////////////////////////////////////////////////////////////////////
6976
6977void TCling::LibraryLoaded(const void* dyLibHandle, const char* canonicalName) {
6978// R__LOCKGUARD_CLING(gInterpreterMutex);
6979// UpdateListOfLoadedSharedLibraries();
6980}
6981
6982////////////////////////////////////////////////////////////////////////////////
6983
6984void TCling::LibraryUnloaded(const void* dyLibHandle, const char* canonicalName) {
6985 fPrevLoadedDynLibInfo = nullptr;
6986 fSharedLibs = "";
6987}
6988
6989////////////////////////////////////////////////////////////////////////////////
6990/// Return the list of shared libraries loaded into the process.
6991
6998
6999static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH, bool skipCore)
7000{
7001 if (!cls || !*cls)
7002 return {};
7003
7004 using namespace clang;
7005 if (const Decl *D = LH.findScope(cls, cling::LookupHelper::NoDiagnostics,
7006 /*type*/ nullptr, /*instantiate*/ false)) {
7007 if (!D->isFromASTFile()) {
7008 if (gDebug > 5)
7009 Warning("GetClassSharedLibsForModule", "Decl found for %s is not part of a module", cls);
7010 return {};
7011 }
7012 class ModuleCollector : public ConstDeclVisitor<ModuleCollector> {
7013 llvm::DenseSet<Module *> &m_TopLevelModules;
7014
7015 public:
7016 ModuleCollector(llvm::DenseSet<Module *> &TopLevelModules) : m_TopLevelModules(TopLevelModules) {}
7017 void Collect(const Decl *D) { Visit(D); }
7018
7019 void VisitDecl(const Decl *D)
7020 {
7021 // FIXME: Such case is described ROOT-7765 where
7022 // ROOT_GENERATE_DICTIONARY does not contain the list of headers.
7023 // They are specified as #includes in the LinkDef file. This leads to
7024 // generation of incomplete modulemap files and this logic fails to
7025 // compute the corresponding module of D.
7026 // FIXME: If we want to support such a case, we should not rely on
7027 // the contents of the modulemap but mangle D and look it up in the
7028 // .so files.
7029 if (!D->hasOwningModule())
7030 return;
7031 if (Module *M = D->getOwningModule()->getTopLevelModule())
7032 m_TopLevelModules.insert(M);
7033 }
7034
7036 {
7037 switch (TA.getKind()) {
7038 case TemplateArgument::Null:
7039 case TemplateArgument::Integral:
7040 case TemplateArgument::Pack:
7041 case TemplateArgument::NullPtr:
7042 case TemplateArgument::StructuralValue:
7043 case TemplateArgument::Expression:
7044 case TemplateArgument::Template:
7045 case TemplateArgument::TemplateExpansion: return;
7046 case TemplateArgument::Type:
7047 if (const TagType *TagTy = dyn_cast<TagType>(TA.getAsType()))
7048 return Visit(TagTy->getDecl());
7049 return;
7050 case TemplateArgument::Declaration: return Visit(TA.getAsDecl());
7051 }
7052 llvm_unreachable("Invalid TemplateArgument::Kind!");
7053 }
7054
7056 {
7057 if (CTSD->getOwningModule())
7058 VisitDecl(CTSD);
7059 else
7060 VisitDecl(CTSD->getSpecializedTemplate());
7061 const TemplateArgumentList &ArgList = CTSD->getTemplateArgs();
7062 for (const TemplateArgument *Arg = ArgList.data(), *ArgEnd = Arg + ArgList.size(); Arg != ArgEnd; ++Arg) {
7064 }
7065 }
7066 };
7067
7068 llvm::DenseSet<Module *> TopLevelModules;
7070 m.Collect(D);
7071 std::string result;
7072 for (auto M : TopLevelModules) {
7073 // ROOT-unaware modules (i.e. not processed by rootcling) do not have a
7074 // link declaration.
7075 if (!M->LinkLibraries.size())
7076 continue;
7077 // We have preloaded the Core module thus libCore.so
7078 if (M->Name == "Core" && skipCore)
7079 continue;
7080 assert(M->LinkLibraries.size() == 1);
7081 if (!result.empty())
7082 result += ' ';
7083 result += M->LinkLibraries[0].Library;
7084 }
7085 return result;
7086 }
7087 return {};
7088}
7089
7090////////////////////////////////////////////////////////////////////////////////
7091/// Get the list of shared libraries containing the code for class cls.
7092/// The first library in the list is the one containing the class, the
7093/// others are the libraries the first one depends on. Returns 0
7094/// in case the library is not found.
7095/// \param cls the name of the class
7096/// \param skipCore if true (default), remove "Core" from the returned list
7097
7098const char* TCling::GetClassSharedLibs(const char* cls, bool skipCore)
7099{
7100 if (fCxxModulesEnabled) {
7101 // Lock the interpreter mutex before interacting with cling.
7102 // TODO: Can we move this further deep? In principle the lock should be in
7103 // GetClassSharedLibsForModule, but it might be needed also for
7104 // getLookupHelper?
7106 llvm::StringRef className = cls;
7107 // If we get a class name containing lambda, we cannot parse it and we
7108 // can exit early.
7109 // FIXME: This works around a bug when we are instantiating a template
7110 // make_unique and the substitution fails. Seen in most of the dataframe
7111 // tests.
7112 if (className.contains("(lambda)"))
7113 return nullptr;
7114 // Limit the recursion which can be induced by GetClassSharedLibsForModule.
7116 cling::LookupHelper &LH = fInterpreter->getLookupHelper();
7118 if (!libs.empty()) {
7119 fAutoLoadLibStorage.push_back(libs);
7120 return fAutoLoadLibStorage.back().c_str();
7121 }
7122 }
7123
7124 if (!cls || !*cls) {
7125 return nullptr;
7126 }
7127 // lookup class to find list of libraries
7128 if (fMapfile) {
7129 TEnvRec* libs_record = nullptr;
7131 if (libs_record) {
7132 const char* libs = libs_record->GetValue();
7133 return (*libs) ? libs : nullptr;
7134 }
7135 else {
7136 // Try the old format...
7137 TString c = TString("Library.") + cls;
7138 // convert "::" to "@@", we used "@@" because TEnv
7139 // considers "::" a terminator
7140 c.ReplaceAll("::", "@@");
7141 // convert "-" to " ", since class names may have
7142 // blanks and TEnv considers a blank a terminator
7143 c.ReplaceAll(" ", "-");
7144 // Use TEnv::Lookup here as the rootmap file must start with Library.
7145 // and do not support using any stars (so we do not need to waste time
7146 // with the search made by TEnv::GetValue).
7147 TEnvRec* libs_record = nullptr;
7149 if (libs_record) {
7150 const char* libs = libs_record->GetValue();
7151 return (*libs) ? libs : nullptr;
7152 }
7153 }
7154 }
7155 return nullptr;
7156}
7157
7158/// This interface returns a list of dependent libraries in the form:
7159/// lib libA.so libB.so libC.so. The first library is the library we are
7160/// searching dependencies for.
7161/// Note: In order to speed up the search, we display the dependencies of the
7162/// libraries which are not yet loaded. For instance, if libB.so was already
7163/// loaded the list would contain: lib libA.so libC.so.
7164static std::string GetSharedLibImmediateDepsSlow(std::string lib,
7165 cling::Interpreter *interp,
7166 bool skipLoadedLibs = true)
7167{
7168 TString LibFullPath(lib);
7169 if (!llvm::sys::path::is_absolute(lib)) {
7170 if (!gSystem->FindDynamicLibrary(LibFullPath, /*quiet=*/true)) {
7171 Error("TCling__GetSharedLibImmediateDepsSlow", "Cannot find library '%s'", lib.c_str());
7172 return "";
7173 }
7174 } else {
7175 assert(llvm::sys::fs::exists(lib) && "Must exist!");
7176 lib = llvm::sys::path::filename(lib).str();
7177 }
7178
7179 auto ObjF = llvm::object::ObjectFile::createObjectFile(LibFullPath.Data());
7180 if (!ObjF) {
7181 Warning("TCling__GetSharedLibImmediateDepsSlow", "Failed to read object file %s", lib.c_str());
7182 return "";
7183 }
7184
7185 llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary();
7186
7187 std::set<string> DedupSet;
7188 std::string Result = lib + ' ';
7189 for (const auto &S : BinObjFile->symbols()) {
7190 uint32_t Flags = llvm::cantFail(S.getFlags());
7191 // Skip defined symbols: we have them.
7192 if (!(Flags & llvm::object::SymbolRef::SF_Undefined))
7193 continue;
7194 // Skip undefined weak symbols: if we don't have them we won't need them.
7195 // `__gmon_start__` being a typical example.
7196 if (Flags & llvm::object::SymbolRef::SF_Weak)
7197 continue;
7198 llvm::Expected<StringRef> SymNameErr = S.getName();
7199 if (!SymNameErr) {
7200 Warning("GetSharedLibDepsForModule", "Failed to read symbol");
7201 continue;
7202 }
7203 llvm::StringRef SymName = SymNameErr.get();
7204 if (SymName.empty())
7205 continue;
7206
7207 if (BinObjFile->isELF()) {
7208 // Skip the symbols which are part of the C/C++ runtime and have a
7209 // fixed library version. See binutils ld VERSION. Those reside in
7210 // 'system' libraries, which we avoid in FindLibraryForSymbol.
7211 if (SymName.contains("@GLIBCXX") || SymName.contains("@CXXABI") ||
7212 SymName.contains("@GLIBC") || SymName.contains("@GCC"))
7213 continue;
7214
7215 // Those are 'weak undefined' symbols produced by gcc. We can
7216 // ignore them.
7217 // FIXME: It is unclear whether we can ignore all weak undefined
7218 // symbols:
7219 // http://lists.llvm.org/pipermail/llvm-dev/2017-October/118177.html
7220 static constexpr llvm::StringRef RegisterClasses("_Jv_RegisterClasses");
7221 static constexpr llvm::StringRef RegisterCloneTable("_ITM_registerTMCloneTable");
7222 static constexpr llvm::StringRef DeregisterCloneTable("_ITM_deregisterTMCloneTable");
7223 if (SymName == RegisterClasses ||
7226 continue;
7227 }
7228
7229 // If we can find the address of the symbol, we have loaded it. Skip.
7230 if (skipLoadedLibs) {
7232 if (llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(SymNameForDlsym))
7233 continue;
7234 }
7235
7237 std::string found = interp->getDynamicLibraryManager()->searchLibrariesForSymbol(SymName, /*searchSystem*/false);
7238 // The expected output is just filename without the full path, which
7239 // is not very accurate, because our Dyld implementation might find
7240 // a match in location a/b/c.so and if we return just c.so ROOT might
7241 // resolve it to y/z/c.so and there we might not be ABI compatible.
7242 // FIXME: Teach the users of GetSharedLibDeps to work with full paths.
7243 if (!found.empty()) {
7244 std::string cand = llvm::sys::path::filename(found).str();
7245 if (!DedupSet.insert(cand).second)
7246 continue;
7247
7248 Result += cand + ' ';
7249 }
7250 }
7251
7252 return Result;
7253}
7254
7255static bool hasParsedRootmapForLibrary(llvm::StringRef lib)
7256{
7257 // Check if we have parsed a rootmap file.
7258 llvm::SmallString<256> rootmapName;
7259 if (!lib.startswith("lib"))
7260 rootmapName.append("lib");
7261
7262 rootmapName.append(llvm::sys::path::filename(lib));
7263 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7264
7265 if (gCling->GetRootMapFiles()->FindObject(rootmapName.c_str()))
7266 return true;
7267
7268 // Perform a last resort by dropping the lib prefix.
7269 llvm::StringRef rootmapNameNoLib = rootmapName.str();
7270 if (rootmapNameNoLib.consume_front("lib"))
7271 return gCling->GetRootMapFiles()->FindObject(rootmapNameNoLib.data());
7272
7273 return false;
7274}
7275
7276static bool hasPrecomputedLibraryDeps(llvm::StringRef lib)
7277{
7278 if (gCling->HasPCMForLibrary(lib.data()))
7279 return true;
7280
7281 return hasParsedRootmapForLibrary(lib);
7282}
7283
7284////////////////////////////////////////////////////////////////////////////////
7285/// Get the list a libraries on which the specified lib depends. The
7286/// returned string contains as first element the lib itself.
7287/// Returns 0 in case the lib does not exist or does not have
7288/// any dependencies. If useDyld is true, we iterate through all available
7289/// libraries and try to construct the dependency chain by resolving each
7290/// symbol.
7291
7292const char* TCling::GetSharedLibDeps(const char* lib, bool useDyld/* = false*/)
7293{
7294 if (llvm::sys::path::is_absolute(lib) && !llvm::sys::fs::exists(lib))
7295 return nullptr;
7296
7297 if (!hasParsedRootmapForLibrary(lib)) {
7298 llvm::SmallString<512> rootmapName(lib);
7299 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7300 if (llvm::sys::fs::exists(rootmapName)) {
7301 if (gDebug > 0)
7302 Info("Load", "loading %s", rootmapName.c_str());
7303 gInterpreter->LoadLibraryMap(rootmapName.c_str());
7304 }
7305 }
7306
7307 if (hasPrecomputedLibraryDeps(lib) && useDyld) {
7308 if (gDebug > 0)
7309 Warning("TCling::GetSharedLibDeps", "Precomputed dependencies available but scanning '%s'", lib);
7310 }
7311
7312 if (useDyld) {
7314 if (!libs.empty()) {
7315 fAutoLoadLibStorage.push_back(libs);
7316 return fAutoLoadLibStorage.back().c_str();
7317 }
7318 }
7319
7320 if (!fMapfile || !lib || !lib[0]) {
7321 return nullptr;
7322 }
7323 TString libname(lib);
7324 Ssiz_t idx = libname.Last('.');
7325 if (idx != kNPOS) {
7326 libname.Remove(idx);
7327 }
7328 TEnvRec* rec;
7329 TIter next(fMapfile->GetTable());
7330 size_t len = libname.Length();
7331 while ((rec = (TEnvRec*) next())) {
7332 const char* libs = rec->GetValue();
7333 if (!strncmp(libs, libname.Data(), len) && strlen(libs) >= len
7334 && (!libs[len] || libs[len] == ' ' || libs[len] == '.')) {
7335 return libs;
7336 }
7337 }
7338 return nullptr;
7339}
7340
7341////////////////////////////////////////////////////////////////////////////////
7342/// If error messages are disabled, the interpreter should suppress its
7343/// failures and warning messages from stdout.
7344
7346{
7347#if defined(R__MUST_REVISIT)
7348#if R__MUST_REVISIT(6,2)
7349 Warning("IsErrorMessagesEnabled", "Interface not available yet.");
7350#endif
7351#endif
7352 return kTRUE;
7353}
7354
7355////////////////////////////////////////////////////////////////////////////////
7356/// If error messages are disabled, the interpreter should suppress its
7357/// failures and warning messages from stdout. Return the previous state.
7358
7360{
7361#if defined(R__MUST_REVISIT)
7362#if R__MUST_REVISIT(6,2)
7363 Warning("SetErrorMessages", "Interface not available yet.");
7364#endif
7365#endif
7367}
7368
7369////////////////////////////////////////////////////////////////////////////////
7370/// Refresh the list of include paths known to the interpreter and return it
7371/// with -I prepended.
7372
7374{
7376
7377 fIncludePath = "";
7378
7379 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7380 //false - no system header, true - with flags.
7381 fInterpreter->GetIncludePaths(includePaths, false, true);
7382 if (const size_t nPaths = includePaths.size()) {
7383 assert(!(nPaths & 1) && "GetIncludePath, number of paths and options is not equal");
7384
7385 for (size_t i = 0; i < nPaths; i += 2) {
7386 if (i)
7387 fIncludePath.Append(' ');
7388 fIncludePath.Append(includePaths[i].c_str());
7389
7390 if (includePaths[i] != "-I")
7391 fIncludePath.Append(' ');
7392 fIncludePath.Append('"');
7394 fIncludePath.Append('"');
7395 }
7396 }
7397
7398 return fIncludePath;
7399}
7400
7401////////////////////////////////////////////////////////////////////////////////
7402/// Return the directory containing CINT's stl cintdlls.
7403
7404const char* TCling::GetSTLIncludePath() const
7405{
7406 return "";
7407}
7408
7409//______________________________________________________________________________
7410// M I S C
7411//______________________________________________________________________________
7412
7413int TCling::DisplayClass(FILE* /*fout*/, const char* /*name*/, int /*base*/, int /*start*/) const
7414{
7415 // Interface to cling function
7416 return 0;
7417}
7418
7419////////////////////////////////////////////////////////////////////////////////
7420/// Interface to cling function
7421
7423{
7424 assert(fout != nullptr && "DisplayIncludePath, 'fout' parameter is null");
7425
7426 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7427 //false - no system header, true - with flags.
7428 fInterpreter->GetIncludePaths(includePaths, false, true);
7429 if (const size_t nPaths = includePaths.size()) {
7430 assert(!(nPaths & 1) && "DisplayIncludePath, number of paths and options is not equal");
7431
7432 std::string allIncludes("include path:");
7433 for (size_t i = 0; i < nPaths; i += 2) {
7434 allIncludes += ' ';
7436
7437 if (includePaths[i] != "-I")
7438 allIncludes += ' ';
7439 allIncludes += includePaths[i + 1];
7440 }
7441
7442 fprintf(fout, "%s\n", allIncludes.c_str());
7443 }
7444
7445 return 0;
7446}
7447
7448////////////////////////////////////////////////////////////////////////////////
7449/// Interface to cling function
7450
7451void* TCling::FindSym(const char* entry) const
7452{
7454 return fInterpreter->getAddressOfGlobal(entry);
7455}
7456
7457////////////////////////////////////////////////////////////////////////////////
7458/// Let the interpreter issue a generic error, and set its error state.
7459
7460void TCling::GenericError(const char* error) const
7461{
7462#if defined(R__MUST_REVISIT)
7463#if R__MUST_REVISIT(6,2)
7464 Warning("GenericError","Interface not available yet.");
7465#endif
7466#endif
7467}
7468
7469////////////////////////////////////////////////////////////////////////////////
7470/// This routines used to return the address of the internal wrapper
7471/// function (of the interpreter) that was used to call *all* the
7472/// interpreted functions that were bytecode compiled (no longer
7473/// interpreted line by line). In Cling, there is no such
7474/// wrapper function.
7475/// In practice this routines was use to decipher whether the
7476/// pointer returns by InterfaceMethod could be used to uniquely
7477/// represent the function. In Cling if the function is in a
7478/// useable state (its compiled version is available), this is
7479/// always the case.
7480/// See TClass::GetMethod.
7481
7483{
7484 return 0;
7485}
7486
7487////////////////////////////////////////////////////////////////////////////////
7488/// Interface to cling function
7489
7491{
7492#if defined(R__MUST_REVISIT)
7493#if R__MUST_REVISIT(6,2)
7494 Warning("GetSecurityError", "Interface not available yet.");
7495#endif
7496#endif
7497 return 0;
7498}
7499
7500////////////////////////////////////////////////////////////////////////////////
7501/// Load a source file or library called path into the interpreter.
7502
7503int TCling::LoadFile(const char* path) const
7504{
7505 // Modifying the interpreter state needs locking.
7507 cling::Interpreter::CompilationResult compRes;
7508 HandleInterpreterException(GetMetaProcessorImpl(), TString::Format(".L %s", path), compRes, /*cling::Value*/nullptr);
7509 return compRes == cling::Interpreter::kFailure;
7510}
7511
7512////////////////////////////////////////////////////////////////////////////////
7513/// Load the declarations from text into the interpreter.
7514/// Note that this cannot be (top level) statements; text must contain
7515/// top level declarations.
7516/// Returns true on success, false on failure.
7517
7518Bool_t TCling::LoadText(const char* text) const
7519{
7520 return (fInterpreter->declare(text) == cling::Interpreter::kSuccess);
7521}
7522
7523////////////////////////////////////////////////////////////////////////////////
7524/// Interface to cling function
7525
7526const char* TCling::MapCppName(const char* name) const
7527{
7528 TTHREAD_TLS_DECL(std::string,buffer);
7530 return buffer.c_str(); // NOLINT
7531}
7532
7533////////////////////////////////////////////////////////////////////////////////
7534/// [Place holder for Mutex Lock]
7535/// Provide the interpreter with a way to
7536/// acquire a lock used to protect critical section
7537/// of its code (non-thread safe parts).
7538
7539void TCling::SetAlloclockfunc(void (* /* p */ )()) const
7540{
7541 // nothing to do for now.
7542}
7543
7544////////////////////////////////////////////////////////////////////////////////
7545/// [Place holder for Mutex Unlock] Provide the interpreter with a way to
7546/// release a lock used to protect critical section
7547/// of its code (non-thread safe parts).
7548
7549void TCling::SetAllocunlockfunc(void (* /* p */ )()) const
7550{
7551 // nothing to do for now.
7552}
7553
7554////////////////////////////////////////////////////////////////////////////////
7555/// Returns if class AutoLoading is currently enabled.
7556
7558{
7559 if (IsFromRootCling())
7560 return false;
7561 if (!fClingCallbacks)
7562 return false;
7564}
7565
7566////////////////////////////////////////////////////////////////////////////////
7567/// Enable/Disable the AutoLoading of libraries.
7568/// Returns the old value, i.e whether it was enabled or not.
7569
7571{
7572 // If no state change is required, exit early.
7573 // FIXME: In future we probably want to complain if we made a request which
7574 // was with the same state as before in order to catch programming errors.
7575 if ((bool) autoload == IsClassAutoLoadingEnabled())
7576 return autoload;
7577
7578 assert(fClingCallbacks && "We must have callbacks!");
7581 return oldVal;
7582}
7583
7584////////////////////////////////////////////////////////////////////////////////
7585/// Enable/Disable the Autoparsing of headers.
7586/// Returns the old value, i.e whether it was enabled or not.
7587
7594
7595////////////////////////////////////////////////////////////////////////////////
7596/// Suspend the Autoparsing of headers.
7597/// Returns the old value, i.e whether it was suspended or not.
7598
7605
7606////////////////////////////////////////////////////////////////////////////////
7607/// Set a callback to receive error messages.
7608
7610{
7611#if defined(R__MUST_REVISIT)
7612#if R__MUST_REVISIT(6,2)
7613 Warning("SetErrmsgcallback", "Interface not available yet.");
7614#endif
7615#endif
7616}
7617
7619{
7620 if (enable) {
7622 &fInterpreter->getDiagnostics().getDiagnosticOptions(),
7623 fInterpreter->getCI()->getLangOpts(),
7624 [] (clang::DiagnosticsEngine::Level Level, const std::string &Info) {
7625 if (Level == clang::DiagnosticsEngine::Warning) {
7626 ::Warning("cling", "%s", Info.c_str());
7627 } else if (Level == clang::DiagnosticsEngine::Error
7628 || Level == clang::DiagnosticsEngine::Fatal) {
7629 ::Error("cling", "%s", Info.c_str());
7630 } else {
7631 ::Info("cling", "%s", Info.c_str());
7632 }
7633 });
7634 fInterpreter->replaceDiagnosticConsumer(consumer, /*Own=*/true);
7635 } else {
7636 fInterpreter->replaceDiagnosticConsumer(nullptr);
7637 }
7638}
7639
7640
7641////////////////////////////////////////////////////////////////////////////////
7642/// Create / close a scope for temporaries. No-op for cling; use
7643/// cling::Value instead.
7644
7645void TCling::SetTempLevel(int val) const
7646{
7647}
7648
7649////////////////////////////////////////////////////////////////////////////////
7650
7651int TCling::UnloadFile(const char* path) const
7652{
7653 // Modifying the interpreter state needs locking.
7655 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
7656 std::string canonical = DLM->lookupLibrary(path);
7657 if (canonical.empty()) {
7658 canonical = path;
7659 }
7660 // Unload a shared library or a source file.
7661 cling::Interpreter::CompilationResult compRes;
7662 HandleInterpreterException(GetMetaProcessorImpl(), Form(".U %s", canonical.c_str()), compRes, /*cling::Value*/nullptr);
7663 return compRes == cling::Interpreter::kFailure;
7664}
7665
7666std::unique_ptr<TInterpreterValue> TCling::MakeInterpreterValue() const {
7667 return std::unique_ptr<TInterpreterValue>(new TClingValue);
7668}
7669
7670////////////////////////////////////////////////////////////////////////////////
7671/// The call to Cling's tab complition.
7672
7673void TCling::CodeComplete(const std::string& line, size_t& cursor,
7674 std::vector<std::string>& completions)
7675{
7676 fInterpreter->codeComplete(line, cursor, completions);
7677}
7678
7679////////////////////////////////////////////////////////////////////////////////
7680/// Get the interpreter value corresponding to the statement.
7682{
7684
7685 auto V = reinterpret_cast<cling::Value*>(value.GetValAddr());
7686 auto compRes = fInterpreter->evaluate(code, *V);
7687 return compRes!=cling::Interpreter::kSuccess ? 0 : 1 ;
7688}
7689
7690////////////////////////////////////////////////////////////////////////////////
7691
7693{
7694 using namespace cling;
7695 const Value* V = reinterpret_cast<const Value*>(value.GetValAddr());
7697}
7698
7699////////////////////////////////////////////////////////////////////////////////
7700/// Register value as a temporary, extending its lifetime to that of the
7701/// interpreter. This is needed for TCling's compatibility interfaces
7702/// returning long - the address of the temporary objects.
7703/// As such, "simple" types don't need to be stored; they are returned by
7704/// value; only pointers / references / objects need to be stored.
7705
7706void TCling::RegisterTemporary(const cling::Value& value)
7707{
7708 if (value.isValid() && value.needsManagedAllocation()) {
7710 fTemporaries->push_back(value);
7711 }
7712}
7713
7714////////////////////////////////////////////////////////////////////////////////
7715/// If the interpreter encounters Name, check whether that is an object ROOT
7716/// could retrieve. To not re-read objects from disk, cache the name/object
7717/// pair for a given LookupCtx.
7718
7720{
7721 // The call to FindSpecialObject might induces any kind of use
7722 // of the interpreter ... (library loading, function calling, etc.)
7723 // ... and we _know_ we are in the middle of parsing, so let's make
7724 // sure to save the state and then restore it.
7725
7726 if (gDirectory) {
7728 if (iSpecObjMap != fSpecialObjectMaps.end()) {
7729 auto iSpecObj = iSpecObjMap->second.find(Name);
7730 if (iSpecObj != iSpecObjMap->second.end()) {
7732 return iSpecObj->second;
7733 }
7734 }
7735 }
7736
7737 // Save state of the PP
7738 Sema &SemaR = fInterpreter->getSema();
7739 ASTContext& C = SemaR.getASTContext();
7740 Preprocessor &PP = SemaR.getPreprocessor();
7741 Parser& P = const_cast<Parser&>(fInterpreter->getParser());
7742 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
7743 Parser::ParserCurTokRestoreRAII savedCurToken(P);
7744 // After we have saved the token reset the current one to something which
7745 // is safe (semi colon usually means empty decl)
7746 Token& Tok = const_cast<Token&>(P.getCurToken());
7747 Tok.setKind(tok::semi);
7748
7749 // We can't PushDeclContext, because we go up and the routine that pops
7750 // the DeclContext assumes that we drill down always.
7751 // We have to be on the global context. At that point we are in a
7752 // wrapper function so the parent context must be the global.
7753 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
7754 SemaR.TUScope);
7755
7756 TObject* specObj = gROOT->FindSpecialObject(Name, LookupCtx);
7757 if (specObj) {
7758 if (!LookupCtx) {
7759 Error("GetObjectAddress", "Got a special object without LookupCtx!");
7760 } else {
7762 }
7763 }
7764 return specObj;
7765}
7766
7767////////////////////////////////////////////////////////////////////////////////
7768/// Inject function as a friend into klass.
7769/// With function being f in void f() {new N::PrivKlass(); } this enables
7770/// I/O of non-public classes.
7771
7772void TCling::AddFriendToClass(clang::FunctionDecl* function,
7773 clang::CXXRecordDecl* klass) const
7774{
7775 using namespace clang;
7776 ASTContext& Ctx = klass->getASTContext();
7777 FriendDecl::FriendUnion friendUnion(function);
7778 // one dummy object for the source location
7780 FriendDecl* friendDecl = FriendDecl::Create(Ctx, klass, sl, friendUnion, sl);
7781 klass->pushFriendDecl(friendDecl);
7782}
7783
7784//______________________________________________________________________________
7785//
7786// DeclId getter.
7787//
7788
7789////////////////////////////////////////////////////////////////////////////////
7790/// Return a unique identifier of the declaration represented by the
7791/// CallFunc
7792
7794{
7795 if (func) return ((TClingCallFunc*)func)->GetDecl()->getCanonicalDecl();
7796 return nullptr;
7797}
7798
7799////////////////////////////////////////////////////////////////////////////////
7800/// Return a (almost) unique identifier of the declaration represented by the
7801/// ClassInfo. In ROOT, this identifier can point to more than one TClass
7802/// when the underlying class is a template instance involving one of the
7803/// opaque typedef.
7804
7806{
7807 if (cinfo) return ((TClingClassInfo*)cinfo)->GetDeclId();
7808 return nullptr;
7809}
7810
7811////////////////////////////////////////////////////////////////////////////////
7812/// Return a unique identifier of the declaration represented by the
7813/// MethodInfo
7814
7816{
7817 if (data) return ((TClingDataMemberInfo*)data)->GetDeclId();
7818 return nullptr;
7819}
7820
7821////////////////////////////////////////////////////////////////////////////////
7822/// Return a unique identifier of the declaration represented by the
7823/// MethodInfo
7824
7826{
7827 if (method) return ((TClingMethodInfo*)method)->GetDeclId();
7828 return nullptr;
7829}
7830
7831////////////////////////////////////////////////////////////////////////////////
7832/// Return a unique identifier of the declaration represented by the
7833/// TypedefInfo
7834
7836{
7837 if (tinfo) return ((TClingTypedefInfo*)tinfo)->GetDecl()->getCanonicalDecl();
7838 return nullptr;
7839}
7840
7841//______________________________________________________________________________
7842//
7843// CallFunc interface
7844//
7845
7846////////////////////////////////////////////////////////////////////////////////
7847
7849{
7850 delete (TClingCallFunc*) func;
7851}
7852
7853////////////////////////////////////////////////////////////////////////////////
7854
7855void TCling::CallFunc_Exec(CallFunc_t* func, void* address) const
7856{
7857 TClingCallFunc* f = (TClingCallFunc*) func;
7858 f->Exec(address);
7859}
7860
7861////////////////////////////////////////////////////////////////////////////////
7862
7863void TCling::CallFunc_Exec(CallFunc_t* func, void* address, TInterpreterValue& val) const
7864{
7865 TClingCallFunc* f = (TClingCallFunc*) func;
7866 f->Exec(address, &val);
7867}
7868
7869////////////////////////////////////////////////////////////////////////////////
7870
7871void TCling::CallFunc_ExecWithReturn(CallFunc_t* func, void* address, void* ret) const
7872{
7873 TClingCallFunc* f = (TClingCallFunc*) func;
7874 f->ExecWithReturn(address, ret);
7875}
7876
7877////////////////////////////////////////////////////////////////////////////////
7878
7880 const void* args[] /*=0*/,
7881 int nargs /*=0*/,
7882 void* ret/*=0*/) const
7883{
7884 TClingCallFunc* f = (TClingCallFunc*) func;
7885 f->ExecWithArgsAndReturn(address, args, nargs, ret);
7886}
7887
7888////////////////////////////////////////////////////////////////////////////////
7889
7891{
7892 TClingCallFunc* f = (TClingCallFunc*) func;
7893 return f->ExecInt(address);
7894}
7895
7896////////////////////////////////////////////////////////////////////////////////
7897
7899{
7900 TClingCallFunc* f = (TClingCallFunc*) func;
7901 return f->ExecInt64(address);
7902}
7903
7904////////////////////////////////////////////////////////////////////////////////
7905
7907{
7908 TClingCallFunc* f = (TClingCallFunc*) func;
7909 return f->ExecDouble(address);
7910}
7911
7912////////////////////////////////////////////////////////////////////////////////
7913
7919
7920////////////////////////////////////////////////////////////////////////////////
7921
7923{
7924 return (CallFunc_t*) new TClingCallFunc(*(TClingCallFunc*)func);
7925}
7926
7927////////////////////////////////////////////////////////////////////////////////
7928
7930{
7931 TClingCallFunc* f = (TClingCallFunc*) func;
7932 return (MethodInfo_t*) f->FactoryMethod();
7933}
7934
7935////////////////////////////////////////////////////////////////////////////////
7936
7938{
7939 TClingCallFunc* f = (TClingCallFunc*) func;
7940 f->IgnoreExtraArgs(ignore);
7941}
7942
7943////////////////////////////////////////////////////////////////////////////////
7944
7946{
7948 TClingCallFunc* f = (TClingCallFunc*) func;
7949 f->Init();
7950}
7951
7952////////////////////////////////////////////////////////////////////////////////
7953
7955{
7956 TClingCallFunc* f = (TClingCallFunc*) func;
7957 return f->IsValid();
7958}
7959
7960////////////////////////////////////////////////////////////////////////////////
7961
7964{
7965 TClingCallFunc* f = (TClingCallFunc*) func;
7966 return f->IFacePtr();
7967}
7968
7969////////////////////////////////////////////////////////////////////////////////
7970
7972{
7973 TClingCallFunc* f = (TClingCallFunc*) func;
7974 f->ResetArg();
7975}
7976
7977////////////////////////////////////////////////////////////////////////////////
7978
7980{
7981 TClingCallFunc* f = (TClingCallFunc*) func;
7982 f->SetArg(param);
7983}
7984
7985////////////////////////////////////////////////////////////////////////////////
7986
7988{
7989 TClingCallFunc* f = (TClingCallFunc*) func;
7990 f->SetArg(param);
7991}
7992
7993////////////////////////////////////////////////////////////////////////////////
7994
7996{
7997 TClingCallFunc* f = (TClingCallFunc*) func;
7998 f->SetArg(param);
7999}
8000
8001////////////////////////////////////////////////////////////////////////////////
8002
8004{
8005 TClingCallFunc* f = (TClingCallFunc*) func;
8006 f->SetArg(param);
8007}
8008
8009////////////////////////////////////////////////////////////////////////////////
8010
8012{
8013 TClingCallFunc* f = (TClingCallFunc*) func;
8014 f->SetArg(param);
8015}
8016
8017////////////////////////////////////////////////////////////////////////////////
8018
8020{
8021 TClingCallFunc* f = (TClingCallFunc*) func;
8022 f->SetArg(param);
8023}
8024
8025////////////////////////////////////////////////////////////////////////////////
8026
8028{
8029 TClingCallFunc* f = (TClingCallFunc*) func;
8030 f->SetArgArray(paramArr, nparam);
8031}
8032
8033////////////////////////////////////////////////////////////////////////////////
8034
8035void TCling::CallFunc_SetArgs(CallFunc_t* func, const char* param) const
8036{
8037 TClingCallFunc* f = (TClingCallFunc*) func;
8038 f->SetArgs(param);
8039}
8040
8041////////////////////////////////////////////////////////////////////////////////
8042
8043void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, Longptr_t* offset) const
8044{
8045 TClingCallFunc* f = (TClingCallFunc*) func;
8047 f->SetFunc(ci, method, params, offset);
8048}
8049
8050////////////////////////////////////////////////////////////////////////////////
8051
8052void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, bool objectIsConst, Longptr_t* offset) const
8053{
8054 TClingCallFunc* f = (TClingCallFunc*) func;
8056 f->SetFunc(ci, method, params, objectIsConst, offset);
8057}
8058////////////////////////////////////////////////////////////////////////////////
8059
8060void TCling::CallFunc_SetFunc(CallFunc_t* func, MethodInfo_t* info) const
8061{
8062 TClingCallFunc* f = (TClingCallFunc*) func;
8064 f->SetFunc(minfo);
8065}
8066
8067////////////////////////////////////////////////////////////////////////////////
8068/// Interface to cling function
8069
8070void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8071{
8072 TClingCallFunc* f = (TClingCallFunc*) func;
8074 f->SetFuncProto(ci, method, proto, offset, mode);
8075}
8076
8077////////////////////////////////////////////////////////////////////////////////
8078/// Interface to cling function
8079
8080void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, bool objectIsConst, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8081{
8082 TClingCallFunc* f = (TClingCallFunc*) func;
8084 f->SetFuncProto(ci, method, proto, objectIsConst, offset, mode);
8085}
8086
8087////////////////////////////////////////////////////////////////////////////////
8088/// Interface to cling function
8089
8090void 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
8091{
8092 TClingCallFunc* f = (TClingCallFunc*) func;
8094 llvm::SmallVector<clang::QualType, 4> funcProto;
8095 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8096 iter != end; ++iter) {
8097 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8098 }
8099 f->SetFuncProto(ci, method, funcProto, offset, mode);
8100}
8101
8102////////////////////////////////////////////////////////////////////////////////
8103/// Interface to cling function
8104
8105void 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
8106{
8107 TClingCallFunc* f = (TClingCallFunc*) func;
8109 llvm::SmallVector<clang::QualType, 4> funcProto;
8110 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8111 iter != end; ++iter) {
8112 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8113 }
8114 f->SetFuncProto(ci, method, funcProto, objectIsConst, offset, mode);
8115}
8116
8118{
8119 TClingCallFunc *f = (TClingCallFunc *)func;
8120 std::string wrapper_name;
8121 std::string wrapper;
8122 f->get_wrapper_code(wrapper_name, wrapper);
8123 return wrapper;
8124}
8125
8126//______________________________________________________________________________
8127//
8128// ClassInfo interface
8129//
8130
8131////////////////////////////////////////////////////////////////////////////////
8132/// Return true if the entity pointed to by 'declid' is declared in
8133/// the context described by 'info'. If info is null, look into the
8134/// global scope (translation unit scope).
8135
8137{
8138 if (!declid)
8139 return kFALSE;
8140
8141 const clang::DeclContext *ctxt = nullptr;
8142 if (info) {
8143 ctxt = clang::Decl::castToDeclContext(((TClingClassInfo*)info)->GetDecl());
8144 } else {
8145 ctxt = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
8146 }
8147 if (!ctxt)
8148 return kFALSE;
8149
8150 const clang::Decl *decl = reinterpret_cast<const clang::Decl*>(declid);
8151 if (!decl)
8152 return kFALSE;
8153
8154 const clang::DeclContext *declDC = decl->getDeclContext();
8155 // ClassInfo_t-s are always "spellable" scopes, never unnamed or inline ones.
8156 while (true) {
8157 if (declDC->isTransparentContext()) {
8158 declDC = declDC->getParent();
8159 continue;
8160 }
8161 if (const auto *declRD = llvm::dyn_cast<clang::RecordDecl>(declDC)) {
8162 if (declRD->isAnonymousStructOrUnion()) {
8163 declDC = declRD->getParent();
8164 continue;
8165 }
8166 }
8167 if (const auto *declNS = llvm::dyn_cast<clang::NamespaceDecl>(declDC)) {
8168 if (declNS->isAnonymousNamespace() || declNS->isInlineNamespace()) {
8169 declDC = declNS->getParent();
8170 continue;
8171 }
8172 }
8173 break;
8174 }
8175
8176 return declDC->Equals(ctxt);
8177}
8178
8179////////////////////////////////////////////////////////////////////////////////
8180
8186
8187////////////////////////////////////////////////////////////////////////////////
8188
8190{
8191 delete (TClingClassInfo*) cinfo;
8192}
8193
8194////////////////////////////////////////////////////////////////////////////////
8195
8201
8202////////////////////////////////////////////////////////////////////////////////
8203
8209
8210////////////////////////////////////////////////////////////////////////////////
8211
8217
8218////////////////////////////////////////////////////////////////////////////////
8219
8225
8226////////////////////////////////////////////////////////////////////////////////
8227
8232
8233////////////////////////////////////////////////////////////////////////////////
8234
8240
8246
8247
8248////////////////////////////////////////////////////////////////////////////////
8249
8250int TCling::ClassInfo_GetMethodNArg(ClassInfo_t* cinfo, const char* method, const char* proto, Bool_t objectIsConst /* = false */, EFunctionMatchMode mode /* = kConversionMatch */) const
8251{
8253 return TClinginfo->GetMethodNArg(method, proto, objectIsConst, mode);
8254}
8255
8256////////////////////////////////////////////////////////////////////////////////
8257
8263
8264////////////////////////////////////////////////////////////////////////////////
8265
8267{
8269 return TClinginfo->HasMethod(name);
8270}
8271
8272////////////////////////////////////////////////////////////////////////////////
8273
8280
8281////////////////////////////////////////////////////////////////////////////////
8282
8284{
8287 TClinginfo->Init(tagnum);
8288}
8289
8290////////////////////////////////////////////////////////////////////////////////
8291
8293{
8295 return TClinginfo->IsBase(name);
8296}
8297
8298////////////////////////////////////////////////////////////////////////////////
8299
8300bool TCling::ClassInfo_IsEnum(const char* name) const
8301{
8303}
8304
8305////////////////////////////////////////////////////////////////////////////////
8306
8312
8313
8314////////////////////////////////////////////////////////////////////////////////
8315
8321
8322
8323////////////////////////////////////////////////////////////////////////////////
8324
8326{
8328 return TClinginfo->IsLoaded();
8329}
8330
8331////////////////////////////////////////////////////////////////////////////////
8332
8334{
8336 return TClinginfo->IsValid();
8337}
8338
8339////////////////////////////////////////////////////////////////////////////////
8340
8341bool TCling::ClassInfo_IsValidMethod(ClassInfo_t* cinfo, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8342{
8344 return TClinginfo->IsValidMethod(method, proto, false, offset, mode);
8345}
8346
8347////////////////////////////////////////////////////////////////////////////////
8348
8350{
8352 return TClinginfo->IsValidMethod(method, proto, objectIsConst, offset, mode);
8353}
8354
8355////////////////////////////////////////////////////////////////////////////////
8356
8362
8363////////////////////////////////////////////////////////////////////////////////
8364
8370
8371////////////////////////////////////////////////////////////////////////////////
8372
8378
8379////////////////////////////////////////////////////////////////////////////////
8380
8382{
8384 return TClinginfo->New(n, arena,*fNormalizedCtxt);
8385}
8386
8387////////////////////////////////////////////////////////////////////////////////
8388
8394
8395////////////////////////////////////////////////////////////////////////////////
8396
8402
8403////////////////////////////////////////////////////////////////////////////////
8404
8410
8411////////////////////////////////////////////////////////////////////////////////
8412
8418
8419////////////////////////////////////////////////////////////////////////////////
8420
8422{
8424 return TClinginfo->FileName();
8425}
8426
8427////////////////////////////////////////////////////////////////////////////////
8428
8430{
8432 TTHREAD_TLS_DECL(std::string,output);
8433 TClinginfo->FullName(output,*fNormalizedCtxt);
8434 return output.c_str(); // NOLINT
8435}
8436
8437////////////////////////////////////////////////////////////////////////////////
8438
8440{
8442 return TClinginfo->Name();
8443}
8444
8445////////////////////////////////////////////////////////////////////////////////
8446
8448{
8450 return TClinginfo->Title();
8451}
8452
8453////////////////////////////////////////////////////////////////////////////////
8454
8456{
8458 return TClinginfo->TmpltName();
8459}
8460
8461
8462
8463//______________________________________________________________________________
8464//
8465// BaseClassInfo interface
8466//
8467
8468////////////////////////////////////////////////////////////////////////////////
8469
8474
8475////////////////////////////////////////////////////////////////////////////////
8476
8483
8484////////////////////////////////////////////////////////////////////////////////
8485
8494
8495////////////////////////////////////////////////////////////////////////////////
8496
8502
8503////////////////////////////////////////////////////////////////////////////////
8504
8510
8511////////////////////////////////////////////////////////////////////////////////
8512
8518
8519////////////////////////////////////////////////////////////////////////////////
8520
8522{
8525 // Offset to the class itself.
8526 if (TClinginfo->GetDecl() == TClinginfoBase->GetDecl()) {
8527 return 0;
8528 }
8529 return TClinginfo->GetBaseOffset(TClinginfoBase, address, isDerivedObject);
8530}
8531
8532////////////////////////////////////////////////////////////////////////////////
8533
8539
8540////////////////////////////////////////////////////////////////////////////////
8541
8547
8548////////////////////////////////////////////////////////////////////////////////
8549
8555
8556////////////////////////////////////////////////////////////////////////////////
8557
8559{
8561 TTHREAD_TLS_DECL(std::string,output);
8562 TClinginfo->FullName(output,*fNormalizedCtxt);
8563 return output.c_str(); // NOLINT
8564}
8565
8566////////////////////////////////////////////////////////////////////////////////
8567
8573
8574////////////////////////////////////////////////////////////////////////////////
8575
8581
8582//______________________________________________________________________________
8583//
8584// DataMemberInfo interface
8585//
8586
8587////////////////////////////////////////////////////////////////////////////////
8588
8594
8595////////////////////////////////////////////////////////////////////////////////
8596
8601
8602////////////////////////////////////////////////////////////////////////////////
8603
8610
8611////////////////////////////////////////////////////////////////////////////////
8612
8614{
8616 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
8617 const clang::ValueDecl* vd = llvm::dyn_cast_or_null<clang::ValueDecl>(decl);
8619}
8620
8621////////////////////////////////////////////////////////////////////////////////
8622
8628
8629////////////////////////////////////////////////////////////////////////////////
8630
8636
8637////////////////////////////////////////////////////////////////////////////////
8638
8644
8645////////////////////////////////////////////////////////////////////////////////
8646
8652
8653////////////////////////////////////////////////////////////////////////////////
8654
8660
8661////////////////////////////////////////////////////////////////////////////////
8662
8668
8669////////////////////////////////////////////////////////////////////////////////
8670
8676
8677////////////////////////////////////////////////////////////////////////////////
8678
8684
8685////////////////////////////////////////////////////////////////////////////////
8686
8692
8693////////////////////////////////////////////////////////////////////////////////
8694
8700
8701////////////////////////////////////////////////////////////////////////////////
8702
8708
8709////////////////////////////////////////////////////////////////////////////////
8710
8716
8717////////////////////////////////////////////////////////////////////////////////
8718
8720{
8721 TTHREAD_TLS_DECL(std::string,result);
8722
8724 result = TClinginfo->ValidArrayIndex().str();
8725 return result.c_str(); // NOLINT
8726}
8727
8728////////////////////////////////////////////////////////////////////////////////
8729
8731{
8732 Decl* decl = static_cast<Decl*>(const_cast<void*>(declId));
8733 ASTContext &C = decl->getASTContext();
8734 decl->addAttr(AnnotateAttr::CreateImplicit(C, attribute, nullptr, 0));
8735}
8736
8737//______________________________________________________________________________
8738//
8739// Function Template interface
8740//
8741
8742////////////////////////////////////////////////////////////////////////////////
8743
8744static void ConstructorName(std::string &name, const clang::Decl *decl,
8745 cling::Interpreter &interp,
8747{
8748 const clang::TypeDecl* td = llvm::dyn_cast<clang::TypeDecl>(decl->getDeclContext());
8749 if (!td) return;
8750
8751 clang::QualType qualType(td->getTypeForDecl(),0);
8753 unsigned int level = 0;
8754 for(size_t cursor = name.length()-1; cursor != 0; --cursor) {
8755 if (name[cursor] == '>') ++level;
8756 else if (name[cursor] == '<' && level) --level;
8757 else if (level == 0 && name[cursor] == ':') {
8758 name.erase(0,cursor+1);
8759 break;
8760 }
8761 }
8762}
8763
8764////////////////////////////////////////////////////////////////////////////////
8765
8766void TCling::GetFunctionName(const clang::Decl *decl, std::string &output) const
8767{
8768 output.clear();
8769
8770 const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(decl);
8771 if (const auto *USD = llvm::dyn_cast<clang::UsingShadowDecl>(decl)) {
8772 FD = llvm::dyn_cast<clang::FunctionDecl>(USD->getTargetDecl());
8773 }
8774 if (!FD) {
8775 Error("GetFunctionName", "NULL Decl!");
8776 return;
8777 }
8778
8779 // For using-decls, show "Derived", not "Base", i.e. use the
8780 // name of the decl context of the UsingShadowDecl (aka `decl`)
8781 // not the name of FD's decl context.
8782 if (llvm::isa<clang::CXXConstructorDecl>(FD))
8783 {
8785
8786 } else if (llvm::isa<clang::CXXDestructorDecl>(decl))
8787 {
8789 output.insert(output.begin(), '~');
8790 } else {
8791 llvm::raw_string_ostream stream(output);
8792 auto printPolicy = decl->getASTContext().getPrintingPolicy();
8793 // Don't trigger fopen of the source file to count lines:
8794 printPolicy.AnonymousTagLocations = false;
8795 FD->getNameForDiagnostic(stream, printPolicy, /*Qualified=*/false);
8796 }
8797}
8798
8799////////////////////////////////////////////////////////////////////////////////
8800/// Return a unique identifier of the declaration represented by the
8801/// FuncTempInfo
8802
8807
8808////////////////////////////////////////////////////////////////////////////////
8809/// Delete the FuncTempInfo_t
8810
8812{
8813 // Currently the address of ft_info is actually the decl itself,
8814 // so we have nothing to do.
8815}
8816
8817////////////////////////////////////////////////////////////////////////////////
8818/// Construct a FuncTempInfo_t
8819
8821{
8822 // Currently the address of ft_info is actually the decl itself,
8823 // so we have nothing to do.
8824
8825 return (FuncTempInfo_t*)const_cast<void*>(declid);
8826}
8827
8828////////////////////////////////////////////////////////////////////////////////
8829/// Construct a FuncTempInfo_t
8830
8832{
8833 // Currently the address of ft_info is actually the decl itself,
8834 // so we have nothing to do.
8835
8836 return (FuncTempInfo_t*)ft_info;
8837}
8838
8839////////////////////////////////////////////////////////////////////////////////
8840/// Check validity of a FuncTempInfo_t
8841
8843{
8844 // Currently the address of ft_info is actually the decl itself,
8845 // so we have nothing to do.
8846
8847 return t_info != nullptr;
8848}
8849
8850////////////////////////////////////////////////////////////////////////////////
8851/// Return the maximum number of template arguments of the
8852/// function template described by ft_info.
8853
8855{
8856 if (!ft_info) return 0;
8857 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
8858 return ft->getTemplateParameters()->size();
8859}
8860
8861////////////////////////////////////////////////////////////////////////////////
8862/// Return the number of required template arguments of the
8863/// function template described by ft_info.
8864
8866{
8867 if (!ft_info) return 0;
8868 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8869 return ft->getTemplateParameters()->getMinRequiredArguments();
8870}
8871
8872////////////////////////////////////////////////////////////////////////////////
8873/// Return the property of the function template.
8874
8876{
8877 if (!ft_info) return 0;
8878
8879 long property = 0L;
8880 property |= kIsCompiled;
8881
8882 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8883
8884 switch (ft->getAccess()) {
8885 case clang::AS_public:
8886 property |= kIsPublic;
8887 break;
8888 case clang::AS_protected:
8889 property |= kIsProtected;
8890 break;
8891 case clang::AS_private:
8892 property |= kIsPrivate;
8893 break;
8894 case clang::AS_none:
8895 if (ft->getDeclContext()->isNamespace())
8897 break;
8898 default:
8899 // IMPOSSIBLE
8900 assert(false && "Unexpected value for the access property value in Clang");
8901 break;
8902 }
8903
8904 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
8905 if (const clang::CXXMethodDecl *md =
8906 llvm::dyn_cast<clang::CXXMethodDecl>(fd)) {
8907 if (md->getMethodQualifiers().hasConst()) {
8908 property |= kIsConstant | kIsConstMethod;
8909 }
8910 if (md->isVirtual()) {
8911 property |= kIsVirtual;
8912 }
8913 if (md->isPureVirtual()) {
8914 property |= kIsPureVirtual;
8915 }
8916 if (const clang::CXXConstructorDecl *cd =
8917 llvm::dyn_cast<clang::CXXConstructorDecl>(md)) {
8918 if (cd->isExplicit()) {
8919 property |= kIsExplicit;
8920 }
8921 }
8922 else if (const clang::CXXConversionDecl *cd =
8923 llvm::dyn_cast<clang::CXXConversionDecl>(md)) {
8924 if (cd->isExplicit()) {
8925 property |= kIsExplicit;
8926 }
8927 }
8928 }
8929 return property;
8930}
8931
8932////////////////////////////////////////////////////////////////////////////////
8933/// Return the property not already defined in Property
8934/// See TDictionary's EFunctionProperty
8935
8937{
8938 if (!ft_info) return 0;
8939
8940 long property = 0L;
8941 property |= kIsCompiled;
8942
8943 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8944 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
8945
8946 if (fd->isOverloadedOperator())
8948 if (llvm::isa<clang::CXXConversionDecl>(fd))
8950 if (llvm::isa<clang::CXXConstructorDecl>(fd))
8952 if (llvm::isa<clang::CXXDestructorDecl>(fd))
8954 if (fd->isInlined())
8956 return property;
8957}
8958
8959////////////////////////////////////////////////////////////////////////////////
8960/// Return the name of this function template.
8961
8963{
8964 output.Clear();
8965 if (!ft_info) return;
8966 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8967 std::string buf;
8968 GetFunctionName(ft->getTemplatedDecl(), buf);
8969 output = buf;
8970}
8971
8972////////////////////////////////////////////////////////////////////////////////
8973/// Return the comments associates with this function template.
8974
8976{
8977 output.Clear();
8978 if (!ft_info) return;
8979 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
8980
8981 // Iterate over the redeclarations, we can have multiple definitions in the
8982 // redecl chain (came from merging of pcms).
8985 if (AnnotateAttr *A = AnnotFD->getAttr<AnnotateAttr>()) {
8986 output = A->getAnnotation().str();
8987 return;
8988 }
8989 }
8990 if (!ft->isFromASTFile()) {
8991 // Try to get the comment from the header file if present
8992 // but not for decls from AST file, where rootcling would have
8993 // created an annotation
8995 }
8996}
8997
8998
8999//______________________________________________________________________________
9000//
9001// MethodInfo interface
9002//
9003
9004////////////////////////////////////////////////////////////////////////////////
9005/// Interface to cling function
9006
9007void TCling::MethodInfo_Delete(MethodInfo_t* minfo) const
9008{
9009 delete(TClingMethodInfo*) minfo;
9010}
9011
9012////////////////////////////////////////////////////////////////////////////////
9013
9015{
9017 // The next call locks the interpreter mutex.
9018 info->CreateSignature(signature);
9019}
9020
9021////////////////////////////////////////////////////////////////////////////////
9022
9023MethodInfo_t* TCling::MethodInfo_Factory() const
9024{
9026 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl());
9027}
9028
9029////////////////////////////////////////////////////////////////////////////////
9030
9032{
9034 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), (TClingClassInfo*)clinfo);
9035}
9036
9037////////////////////////////////////////////////////////////////////////////////
9038
9040{
9041 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
9043 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), decl);
9044}
9045
9046////////////////////////////////////////////////////////////////////////////////
9047
9048MethodInfo_t* TCling::MethodInfo_FactoryCopy(MethodInfo_t* minfo) const
9049{
9050 return (MethodInfo_t*) new TClingMethodInfo(*(TClingMethodInfo*)minfo);
9051}
9052
9053////////////////////////////////////////////////////////////////////////////////
9054
9056{
9058 // The next call locks the interpreter mutex.
9059 return info->InterfaceMethod();
9060}
9061
9062////////////////////////////////////////////////////////////////////////////////
9063
9064bool TCling::MethodInfo_IsValid(MethodInfo_t* minfo) const
9065{
9067 return info->IsValid();
9068}
9069
9070////////////////////////////////////////////////////////////////////////////////
9071
9072int TCling::MethodInfo_NArg(MethodInfo_t* minfo) const
9073{
9075 return info->NArg();
9076}
9077
9078////////////////////////////////////////////////////////////////////////////////
9079
9081{
9083 return info->NDefaultArg();
9084}
9085
9086////////////////////////////////////////////////////////////////////////////////
9087
9088int TCling::MethodInfo_Next(MethodInfo_t* minfo) const
9089{
9091 return info->Next();
9092}
9093
9094////////////////////////////////////////////////////////////////////////////////
9095
9097{
9099 // The next call locks the interpreter mutex.
9100 return info->Property();
9101}
9102
9103////////////////////////////////////////////////////////////////////////////////
9104
9106{
9108 // The next call locks the interpreter mutex.
9109 return info->ExtraProperty();
9110}
9111
9112////////////////////////////////////////////////////////////////////////////////
9113
9115{
9117 // The next call locks the interpreter mutex.
9118 return (TypeInfo_t*)info->Type();
9119}
9120
9121////////////////////////////////////////////////////////////////////////////////
9122
9123const char* TCling::MethodInfo_GetMangledName(MethodInfo_t* minfo) const
9124{
9127 // The next call locks the interpreter mutex.
9128 mangled_name = info->GetMangledName();
9129 return mangled_name;
9130}
9131
9132////////////////////////////////////////////////////////////////////////////////
9133
9134const char* TCling::MethodInfo_GetPrototype(MethodInfo_t* minfo) const
9135{
9137 // The next call locks the interpreter mutex.
9138 return info->GetPrototype();
9139}
9140
9141////////////////////////////////////////////////////////////////////////////////
9142
9143const char* TCling::MethodInfo_Name(MethodInfo_t* minfo) const
9144{
9146 // The next call locks the interpreter mutex.
9147 return info->Name();
9148}
9149
9150////////////////////////////////////////////////////////////////////////////////
9151
9152const char* TCling::MethodInfo_TypeName(MethodInfo_t* minfo) const
9153{
9155 // The next call locks the interpreter mutex.
9156 return info->TypeName();
9157}
9158
9159////////////////////////////////////////////////////////////////////////////////
9160
9161std::string TCling::MethodInfo_TypeNormalizedName(MethodInfo_t* minfo) const
9162{
9164 // The next part locks the interpreter mutex.
9165 if (info && info->IsValid())
9166 return info->Type()->NormalizedName(*fNormalizedCtxt);
9167 else
9168 return "";
9169}
9170
9171////////////////////////////////////////////////////////////////////////////////
9172
9173const char* TCling::MethodInfo_Title(MethodInfo_t* minfo) const
9174{
9176 // The next call locks the interpreter mutex.
9177 return info->Title();
9178}
9179
9180////////////////////////////////////////////////////////////////////////////////
9181
9183{
9184 if (func) {
9185 return MethodInfo_MethodCallReturnType(func->fInfo);
9186 } else {
9187 return EReturnType::kOther;
9188 }
9189}
9190
9191////////////////////////////////////////////////////////////////////////////////
9192
9194{
9196 if (info && info->IsValid()) {
9197 TClingTypeInfo *typeinfo = info->Type();
9198 clang::QualType QT( typeinfo->GetQualType().getCanonicalType() );
9199 if (QT->isEnumeralType()) {
9200 return EReturnType::kLong;
9201 } else if (QT->isPointerType()) {
9202 // Look for char*
9203 QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
9204 if ( QT->isCharType() ) {
9205 return EReturnType::kString;
9206 } else {
9207 return EReturnType::kOther;
9208 }
9209 } else if ( QT->isFloatingType() ) {
9210 int sz = typeinfo->Size();
9211 if (sz == 4 || sz == 8) {
9212 // Support only float and double.
9213 return EReturnType::kDouble;
9214 } else {
9215 return EReturnType::kOther;
9216 }
9217 } else if ( QT->isIntegerType() ) {
9218 int sz = typeinfo->Size();
9219 if (sz <= 8) {
9220 // Support only up to long long ... but
9221 // FIXME the TMethodCall::Execute only
9222 // return long (4 bytes) ...
9223 // The v5 implementation of TMethodCall::ReturnType
9224 // was not making the distinction so we let it go
9225 // as is for now, but we really need to upgrade
9226 // TMethodCall::Execute ...
9227 return EReturnType::kLong;
9228 } else {
9229 return EReturnType::kOther;
9230 }
9231 } else {
9232 return EReturnType::kOther;
9233 }
9234 } else {
9235 return EReturnType::kOther;
9236 }
9237}
9238
9239//______________________________________________________________________________
9240//
9241// MethodArgInfo interface
9242//
9243
9244////////////////////////////////////////////////////////////////////////////////
9245
9250
9251////////////////////////////////////////////////////////////////////////////////
9252
9258
9259////////////////////////////////////////////////////////////////////////////////
9260
9266
9267////////////////////////////////////////////////////////////////////////////////
9268
9274
9275////////////////////////////////////////////////////////////////////////////////
9276
9282
9283////////////////////////////////////////////////////////////////////////////////
9284
9290
9291////////////////////////////////////////////////////////////////////////////////
9292
9298
9299////////////////////////////////////////////////////////////////////////////////
9300
9302{
9304 return info->DefaultValue();
9305}
9306
9307////////////////////////////////////////////////////////////////////////////////
9308
9310{
9312 return info->Name();
9313}
9314
9315////////////////////////////////////////////////////////////////////////////////
9316
9318{
9320 return info->TypeName();
9321}
9322
9323////////////////////////////////////////////////////////////////////////////////
9324
9326{
9328 return info->Type()->NormalizedName(*fNormalizedCtxt);
9329}
9330
9331////////////////////////////////////////////////////////////////////////////////
9332
9338
9339//______________________________________________________________________________
9340//
9341// TypeInfo interface
9342//
9343
9344////////////////////////////////////////////////////////////////////////////////
9345
9347{
9348 delete (TClingTypeInfo*) tinfo;
9349}
9350
9351////////////////////////////////////////////////////////////////////////////////
9352
9358
9359////////////////////////////////////////////////////////////////////////////////
9360
9366
9367////////////////////////////////////////////////////////////////////////////////
9368
9373
9374////////////////////////////////////////////////////////////////////////////////
9375
9382
9383////////////////////////////////////////////////////////////////////////////////
9384
9386{
9388 return TClinginfo->IsValid();
9389}
9390
9391////////////////////////////////////////////////////////////////////////////////
9392
9394{
9396 return TClinginfo->Name();
9397}
9398
9399////////////////////////////////////////////////////////////////////////////////
9400
9406
9407////////////////////////////////////////////////////////////////////////////////
9408
9410{
9412 return TClinginfo->RefType();
9413}
9414
9415////////////////////////////////////////////////////////////////////////////////
9416
9418{
9420 return TClinginfo->Size();
9421}
9422
9423////////////////////////////////////////////////////////////////////////////////
9424
9426{
9428 return TClinginfo->TrueName(*fNormalizedCtxt);
9429}
9430
9431////////////////////////////////////////////////////////////////////////////////
9432
9434{
9436 return TClinginfo->QualTypePtr();
9437}
9438
9439
9440//______________________________________________________________________________
9441//
9442// TypedefInfo interface
9443//
9444
9445////////////////////////////////////////////////////////////////////////////////
9446
9451
9452////////////////////////////////////////////////////////////////////////////////
9453
9459
9460////////////////////////////////////////////////////////////////////////////////
9461
9467
9468////////////////////////////////////////////////////////////////////////////////
9469
9474
9475////////////////////////////////////////////////////////////////////////////////
9476
9484
9485////////////////////////////////////////////////////////////////////////////////
9486
9492
9493////////////////////////////////////////////////////////////////////////////////
9494
9500
9501////////////////////////////////////////////////////////////////////////////////
9502
9508
9509////////////////////////////////////////////////////////////////////////////////
9510
9516
9517////////////////////////////////////////////////////////////////////////////////
9518
9524
9525////////////////////////////////////////////////////////////////////////////////
9526
9528{
9530 return TClinginfo->Name();
9531}
9532
9533////////////////////////////////////////////////////////////////////////////////
9534
9536{
9538 return TClinginfo->Title();
9539}
9540
9541////////////////////////////////////////////////////////////////////////////////
9542
9543bool TCling::IsSameType(const void * QualTypePtr1, const void * QualTypePtr2) const
9544{
9545 clang::QualType QT1 = clang::QualType::getFromOpaquePtr(QualTypePtr1);
9546 clang::QualType QT2 = clang::QualType::getFromOpaquePtr(QualTypePtr2);
9547 return fInterpreter->getCI()->getASTContext().hasSameType(QT1, QT2);
9548}
9549
9550////////////////////////////////////////////////////////////////////////////////
9551
9552bool TCling::IsIntegerType(const void * QualTypePtr) const
9553{
9554 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9555 return QT->hasIntegerRepresentation();
9556}
9557
9558////////////////////////////////////////////////////////////////////////////////
9559
9560bool TCling::IsSignedIntegerType(const void * QualTypePtr) const
9561{
9562 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9563 return QT->hasSignedIntegerRepresentation();
9564}
9565
9566////////////////////////////////////////////////////////////////////////////////
9567
9568bool TCling::IsUnsignedIntegerType(const void * QualTypePtr) const
9569{
9570 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9571 return QT->hasUnsignedIntegerRepresentation();
9572}
9573
9574////////////////////////////////////////////////////////////////////////////////
9575
9576bool TCling::IsFloatingType(const void * QualTypePtr) const
9577{
9578 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9579 return QT->hasFloatingRepresentation();
9580}
9581
9582////////////////////////////////////////////////////////////////////////////////
9583
9584bool TCling::IsPointerType(const void * QualTypePtr) const
9585{
9586 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9587 return QT->hasPointerRepresentation();
9588}
9589
9590////////////////////////////////////////////////////////////////////////////////
9591
9592bool TCling::IsVoidPointerType(const void * QualTypePtr) const
9593{
9594 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9595 return QT->isVoidPointerType();
9596}
9597
9598////////////////////////////////////////////////////////////////////////////////
9599
9601{
9602 clang::FunctionDecl *FD = (clang::FunctionDecl *) fdeclid;
9603 return llvm::isa_and_nonnull<clang::CXXMethodDecl>(FD);
9604}
9605
9606////////////////////////////////////////////////////////////////////////////////
9607
9609{
9610 if (!fInitialMutex) {
9612 Error("SnapshotMutexState", "fRecurseCount != 0 even though initial mutex state is unset!");
9613 }
9614 fInitialMutex.fState = mtx->GetStateBefore();
9615 }
9616 // We will "forget" this lock once we backed out of all interpreter frames.
9617 // Here we are entering one, so ++.
9619}
9620
9621////////////////////////////////////////////////////////////////////////////////
9622
9624{
9625 if (!fInitialMutex)
9626 return;
9627 if (fInitialMutex.fRecurseCount == 0) {
9628 Error("ForgetMutexState", "mutex state's recurse count already 0!");
9629 }
9630 else if (--fInitialMutex.fRecurseCount == 0) {
9631 // We have returned from all interpreter frames. Reset the initial lock state.
9632 fInitialMutex.fState.reset();
9633 }
9634}
9635
9636////////////////////////////////////////////////////////////////////////////////
9637/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
9638
9640{
9641 if (gInterpreterMutex) {
9642 if (delta) {
9643 auto typedDelta = static_cast<MutexStateAndRecurseCountDelta *>(delta);
9644 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP{typedDelta};
9645 gCoreMutex->Apply(std::move(typedDelta->fDelta));
9646 // Now that we have the lock, update the global
9647 R__ASSERT(fInitialMutex.fRecurseCount == 0 && "Inconsistent state of fInitialMutex! Another thread within Interpreter critical section.");
9648 std::swap(fInitialMutex, typedDelta->fInitialState);
9649 } else {
9650 // This case happens when EnableThreadSafety is first called from
9651 // the interpreter function we just handled.
9652 // Since thread safety was not enabled at the time we rewound, there was
9653 // no lock taken and even-though we should be locking the rest of this
9654 // interpreter handling/modifying code (since there might be threads in
9655 // flight), we can't because there would not be any lock guard to release the
9656 // locks
9658 Error("ApplyToInterpreterMutex",
9659 "After returning from user code that turned on thread safety support, we notice that fInitialMutex is already used ... "
9660 "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.");
9661 }
9662 }
9663}
9664
9665////////////////////////////////////////////////////////////////////////////////
9666/// Reset the interpreter lock to the state it had before interpreter-related
9667/// calls happened.
9668
9670{
9671 if (fInitialMutex) {
9672 // Need to start a new recurse count.
9673 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP(new MutexStateAndRecurseCountDelta());
9674 std::swap(uniqueP->fInitialState, fInitialMutex);
9675 uniqueP->fDelta = gCoreMutex->Rewind(*uniqueP->fInitialState.fState);
9676 return uniqueP.release();
9677 }
9679 return nullptr;
9680}
#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 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
Definition RtypesCore.h:63
int Int_t
Definition RtypesCore.h:45
long Longptr_t
Definition RtypesCore.h:75
short Version_t
Definition RtypesCore.h:65
unsigned long ULong_t
Definition RtypesCore.h:55
long Long_t
Definition RtypesCore.h:54
unsigned int UInt_t
Definition RtypesCore.h:46
constexpr Bool_t kFALSE
Definition RtypesCore.h:94
constexpr Ssiz_t kNPOS
Definition RtypesCore.h:117
long long Long64_t
Definition RtypesCore.h:69
unsigned long long ULong64_t
Definition RtypesCore.h:70
constexpr Bool_t kTRUE
Definition RtypesCore.h:93
TClass *(* DictFuncPtr_t)()
Definition Rtypes.h:85
R__EXTERN TApplication * gApplication
R__EXTERN TClassTable * gClassTable
static bool IsFromRootCling()
Definition TClass.cxx:174
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:341
void TCling__TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:579
static void RegisterPreIncludedHeaders(cling::Interpreter &clingInterp)
Definition TCling.cxx:1299
static bool hasParsedRootmapForLibrary(llvm::StringRef lib)
Definition TCling.cxx:7255
void TCling__InvalidateGlobal(const clang::Decl *D)
Definition TCling.cxx:574
bool TClingLookupHelper__AutoParse(const char *cname)
Allow calling autoparsing from TMetaUtils.
Definition TCling.cxx:894
R__EXTERN int optind
Definition TCling.cxx:317
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
Definition TCling.cxx:368
void TCling__UpdateListsOnUnloaded(const cling::Transaction &T)
Definition TCling.cxx:569
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&normCtxt)
Definition TCling.cxx:557
int TCling__LoadLibrary(const char *library)
Load a library.
Definition TCling.cxx:333
void TCling__DEBUG__dump(clang::DeclContext *DC)
Definition TCling.cxx:224
ETupleOrdering
Check in what order the member of a tuple are layout.
Definition TCling.cxx:3908
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:351
static const std::unordered_set< std::string > gIgnoredPCMNames
List of dicts that have the PCM information already in the PCH.
Definition TCling.cxx:1941
static Bool_t s_IsLibraryLoaded(const char *libname, cling::Interpreter *fInterpreter)
Definition TCling.cxx:3132
const char * TCling__GetClassSharedLibs(const char *className, bool skipCore)
Definition TCling.cxx:633
static GlobalModuleIndex * loadGlobalModuleIndex(cling::Interpreter &interp)
Definition TCling.cxx:1080
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:903
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:1065
void TCling__UnlockCompilationDuringUserCodeExecution(void *)
Unlock the interpreter.
Definition TCling.cxx:379
static std::string AlternateTuple(const char *classname, const cling::LookupHelper &lh, Bool_t silent)
Definition TCling.cxx:3950
static bool R__InitStreamerInfoFactory()
Helper to initialize TVirtualStreamerInfo's factor early.
Definition TCling.cxx:1664
int TCling__AutoParseCallback(const char *className)
Definition TCling.cxx:628
clang::RecordDecl * TCling__DEBUG__DCtoRecordDecl(clang::DeclContext *DC)
Definition TCling.cxx:221
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:699
static bool HaveFullGlobalModuleIndex
Definition TCling.cxx:1079
bool TCling__TEST_isInvalidDecl(clang::Decl *D)
Definition TCling.cxx:251
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:593
void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter *)
Definition TCling.cxx:564
const Decl * TCling__GetObjectDecl(TObject *obj)
Definition TCling.cxx:604
static ETupleOrdering IsTupleAscending()
Definition TCling.cxx:3926
void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
Definition TCling.cxx:588
static void TCling__UpdateClassInfo(const NamedDecl *TD)
Update TClingClassInfo for a class (e.g. upon seeing a definition).
Definition TCling.cxx:389
clang::DeclContext * TCling__DEBUG__getDeclContext(clang::Decl *D)
Definition TCling.cxx:215
int TCling__CompileMacro(const char *fileName, const char *options)
Definition TCling.cxx:644
#define R__DLLEXPORT
Definition TCling.cxx:151
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:360
void TCling__DEBUG__decl_dump(void *D)
Definition TCling.cxx:233
int TCling__AutoLoadCallback(const char *className)
Definition TCling.cxx:623
static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
Definition TCling.cxx:1030
static void RegisterCxxModules(cling::Interpreter &clingInterp)
Definition TCling.cxx:1183
static void ConstructorName(std::string &name, const clang::Decl *decl, cling::Interpreter &interp, const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt)
Definition TCling.cxx:8744
void TCling__PrintStackTrace()
Print a StackTrace!
Definition TCling.cxx:326
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:2426
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:7164
void TCling__DEBUG__printName(clang::Decl *D)
Definition TCling.cxx:236
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:680
static void PrintDlError(const char *dyLibName, const char *modulename)
Definition TCling.cxx:1966
TInterpreter * CreateInterpreter(void *interpLibHandle, const char *argv[])
Definition TCling.cxx:608
static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH, bool skipCore)
Definition TCling.cxx:6999
const char * fantomline
Definition TCling.cxx:841
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:583
static cling::Interpreter::CompilationResult ExecAutoParse(const char *what, Bool_t header, cling::Interpreter *interpreter)
Parse the payload or header.
Definition TCling.cxx:6335
static bool requiresRootMap(const char *rootmapfile)
Definition TCling.cxx:5515
clang::NamespaceDecl * TCling__DEBUG__DCtoNamespace(clang::DeclContext *DC)
Definition TCling.cxx:218
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
Definition TCling.cxx:600
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:1052
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
Definition TCling.cxx:639
void DestroyInterpreter(TInterpreter *interp)
Definition TCling.cxx:616
static bool hasPrecomputedLibraryDeps(llvm::StringRef lib)
Definition TCling.cxx:7276
void TCling__SplitAclicMode(const char *fileName, string &mode, string &args, string &io, string &fname)
Definition TCling.cxx:651
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:384
@ kEnvUser
Definition TEnv.h:71
@ kEnvGlobal
Definition TEnv.h:70
@ kEnvLocal
Definition TEnv.h:72
#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:218
constexpr Int_t kWarning
Definition TError.h:46
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:185
Int_t gErrorIgnoreLevel
Error handling routines.
Definition TError.cxx:31
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:229
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:244
#define N
winID h TVirtualViewer3D TVirtualGLPainter p
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:110
R__EXTERN TVirtualMutex * gInterpreterMutex
#define R__LOCKGUARD_CLING(mutex)
R__EXTERN TInterpreter * gCling
#define gInterpreter
Int_t gDebug
Definition TROOT.cxx:622
#define gROOT
Definition TROOT.h:414
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2489
@ kReadPermission
Definition TSystem.h:55
Bool_t R_ISREG(Int_t mode)
Definition TSystem.h:126
R__EXTERN TSystem * gSystem
Definition TSystem.h:572
R__EXTERN TVirtualMutex * gGlobalMutex
#define R__LOCKGUARD(mutex)
#define R__WRITE_LOCKGUARD(mutex)
#define R__READ_LOCKGUARD(mutex)
const char * proto
Definition civetweb.c:17535
#define free
Definition civetweb.c:1539
#define snprintf
Definition civetweb.c:1540
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:28
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:81
TDataMember * GetDataMember(const char *datamember) const
Return pointer to datamember object with name "datamember".
Definition TClass.cxx:3535
ROOT::ESTLType GetCollectionType() const
Return the 'type' of the STL the TClass is representing.
Definition TClass.cxx:2956
EState fState
cached of the streaming method to use
Definition TClass.h:277
std::atomic< TList * > fBase
Definition TClass.h:201
static void AddClassToDeclIdMap(TDictionary::DeclId_t id, TClass *cl)
static: Add a TClass* to the map of classes.
Definition TClass.cxx:576
Version_t fClassVersion
Definition TClass.h:221
TList * GetListOfFunctionTemplates(Bool_t load=kTRUE)
Return TListOfFunctionTemplates for a class.
Definition TClass.cxx:3894
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:5011
static void RemoveClassDeclId(TDictionary::DeclId_t id)
Definition TClass.cxx:603
static Bool_t HasNoInfoOrEmuOrFwdDeclaredDecl(const char *)
Definition TClass.cxx:3494
static TClass * LoadClass(const char *requestedname, Bool_t silent)
Helper function used by TClass::GetClass().
Definition TClass.cxx:5845
Int_t Size() const
Return size of object of this class.
Definition TClass.cxx:5800
@ kLoading
Definition TClass.h:332
@ kUnloading
Definition TClass.h:332
TObjArray * fStreamerInfo
Definition TClass.h:198
ClassInfo_t * GetClassInfo() const
Definition TClass.h:433
ClassInfo_t * fClassInfo
Definition TClass.h:222
TVirtualCollectionProxy * GetCollectionProxy() const
Return the proxy describing the collection (if any).
Definition TClass.cxx:2967
void ResetCaches()
To clean out all caches.
Definition TClass.cxx:4311
static Int_t ReadRules()
Read the class.rules files from the default location:.
Definition TClass.cxx:1890
@ kInterpreted
Definition TClass.h:126
@ kHasTClassInit
Definition TClass.h:127
@ kEmulated
Definition TClass.h:125
@ kForwardDeclared
Definition TClass.h:124
@ kNamespaceForMeta
Definition TClass.h:131
std::atomic< Bool_t > fHasRootPcmInfo
C++ Property of the class (is abstract, has virtual table, etc.)
Definition TClass.h:259
const char * GetDeclFileName() const
Return name of the file containing the declaration of this class.
Definition TClass.cxx:3559
@ kIsTObject
Definition TClass.h:100
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:3038
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:1006
bool Append(const std::string &str)
Append string to the storage if not added already.
Definition TCling.cxx:1014
std::string fContent
Definition TCling.h:619
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:6207
const char * MethodArgInfo_DefaultValue(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9301
bool ClassInfo_IsScopedEnum(ClassInfo_t *info) const final
Definition TCling.cxx:8307
const char * TypeInfo_Name(TypeInfo_t *) const final
Definition TCling.cxx:9393
void * MethodInfo_InterfaceMethod(MethodInfo_t *minfo) const final
Definition TCling.cxx:9055
void LoadEnums(TListOfEnums &cl) const final
Create list of pointers to enums for TClass cl.
Definition TCling.cxx:4398
void UpdateListOfGlobals() final
No op: see TClingCallbacks (used to update the list of globals)
Definition TCling.cxx:3888
bool TypedefInfo_IsValid(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9487
Int_t AutoLoad(const char *classname, Bool_t knowDictNotLoaded=kFALSE) final
Load library containing the specified class.
Definition TCling.cxx:6268
void CallFunc_Init(CallFunc_t *func) const final
Definition TCling.cxx:7945
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:3651
bool LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
Definition TCling.cxx:6571
void GenericError(const char *error) const final
Let the interpreter issue a generic error, and set its error state.
Definition TCling.cxx:7460
std::vector< void * > fRegisterModuleDyLibs
Definition TCling.h:138
void CallFunc_ExecWithReturn(CallFunc_t *func, void *address, void *ret) const final
Definition TCling.cxx:7871
TypeInfo_t * MethodInfo_Type(MethodInfo_t *minfo) const final
Definition TCling.cxx:9114
std::vector< std::string > fAutoLoadLibStorage
Definition TCling.h:118
void CallFunc_Delete(CallFunc_t *func) const final
Definition TCling.cxx:7848
Bool_t fLockProcessLine
Definition TCling.h:127
int LoadFile(const char *path) const final
Load a source file or library called path into the interpreter.
Definition TCling.cxx:7503
void ResetAll() final
Reset the Cling state to its initial state.
Definition TCling.cxx:3727
void SetDeclAttr(DeclId_t, const char *) final
Definition TCling.cxx:8730
void HandleNewDecl(const void *DV, bool isDeserialized, std::set< TClass * > &modifiedClasses)
Definition TCling.cxx:496
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:6894
Long_t MethodInfo_Property(MethodInfo_t *minfo) const final
Definition TCling.cxx:9096
virtual void LoadFunctionTemplates(TClass *cl) const final
Create list of pointers to function templates for TClass cl.
Definition TCling.cxx:4445
bool ClassInfo_IsValidMethod(ClassInfo_t *info, const char *method, const char *proto, Longptr_t *offset, ROOT::EFunctionMatchMode=ROOT::kConversionMatch) const final
Definition TCling.cxx:8341
Long_t DataMemberInfo_Property(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8663
int SetClassAutoparsing(int) final
Enable/Disable the Autoparsing of headers.
Definition TCling.cxx:7588
std::vector< const char * > fCurExecutingMacros
Definition TCling.h:149
void CreateListOfDataMembers(TClass *cl) const final
Create list of pointers to data members for TClass cl.
Definition TCling.cxx:4492
void RewindDictionary() final
Rewind Cling dictionary to the point where it was before executing the current macro.
Definition TCling.cxx:3772
bool ClassInfo_IsValid(ClassInfo_t *info) const final
Definition TCling.cxx:8333
void UpdateListsOnCommitted(const cling::Transaction &T)
Definition TCling.cxx:6768
int TypeInfo_RefType(TypeInfo_t *) const final
Definition TCling.cxx:9409
void CreateListOfBaseClasses(TClass *cl) const final
Create list of pointers to base class(es) for TClass cl.
Definition TCling.cxx:4374
ClassInfo_t * ClassInfo_Factory(Bool_t all=kTRUE) const final
Definition TCling.cxx:8220
const char * MethodInfo_Name(MethodInfo_t *minfo) const final
Definition TCling.cxx:9143
BaseClassInfo_t * BaseClassInfo_Factory(ClassInfo_t *info) const final
Definition TCling.cxx:8477
Bool_t LoadText(const char *text) const final
Load the declarations from text into the interpreter.
Definition TCling.cxx:7518
const char * GetSharedLibDeps(const char *lib, bool tryDyld=false) final
Get the list a libraries on which the specified lib depends.
Definition TCling.cxx:7292
EReturnType MethodInfo_MethodCallReturnType(MethodInfo_t *minfo) const final
Definition TCling.cxx:9193
TObject * GetObjectAddress(const char *Name, void *&LookupCtx)
If the interpreter encounters Name, check whether that is an object ROOT could retrieve.
Definition TCling.cxx:7719
Longptr_t ProcessLineAsynch(const char *line, EErrorCode *error=nullptr)
Let cling process a command line asynch.
Definition TCling.cxx:3563
bool MethodInfo_IsValid(MethodInfo_t *minfo) const final
Definition TCling.cxx:9064
FuncTempInfo_t * FuncTempInfo_Factory(DeclId_t declid) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8820
TypeInfo_t * TypeInfo_Factory() const final
Definition TCling.cxx:9353
bool IsClassAutoLoadingEnabled() const
Returns if class AutoLoading is currently enabled.
Definition TCling.cxx:7557
void InvalidateGlobal(const clang::Decl *D)
Invalidate cached TCling information for the given global declaration.
Definition TCling.cxx:6879
int Evaluate(const char *, TInterpreterValue &) final
Get the interpreter value corresponding to the statement.
Definition TCling.cxx:7681
std::unique_ptr< TInterpreterValue > MakeInterpreterValue() const final
Definition TCling.cxx:7666
void UpdateListOfLoadedSharedLibraries()
Definition TCling.cxx:3351
const char * TypedefInfo_Title(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9535
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:8070
void InitRootmapFile(const char *name)
Create a resource table and read the (possibly) three resource files, i.e.
Definition TCling.cxx:5658
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:6526
bool FunctionDeclId_IsMethod(DeclId_t fdeclid) const
Definition TCling.cxx:9600
void LoadPCM(std::string pcmFileNameFullPath)
Tries to load a rdict PCM, issues diagnostics if it fails.
Definition TCling.cxx:1813
void UpdateListOfMethods(TClass *cl) const final
Update the list of pointers to method for TClass cl This is now a nop.
Definition TCling.cxx:4510
virtual ~TCling()
Destroy the interpreter interface.
Definition TCling.cxx:1618
void AddFriendToClass(clang::FunctionDecl *, clang::CXXRecordDecl *) const
Inject function as a friend into klass.
Definition TCling.cxx:7772
void PrintIntro() final
No-op; see TRint instead.
Definition TCling.cxx:2651
Bool_t fCxxModulesEnabled
Definition TCling.h:128
int BaseClassInfo_Next(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8497
void RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
Internal function. Actually do the update of the ClassInfo when seeing.
Definition TCling.cxx:6638
CallFunc_t * CallFunc_FactoryCopy(CallFunc_t *func) const final
Definition TCling.cxx:7922
Double_t CallFunc_ExecDouble(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7906
void CallFunc_ResetArg(CallFunc_t *func) const final
Definition TCling.cxx:7971
const char * GetCurrentMacroName() const final
Return the file name of the currently interpreted file, included or not.
Definition TCling.cxx:5466
Bool_t IsLoaded(const char *filename) const final
Return true if the file has already been loaded by cint.
Definition TCling.cxx:3175
void SaveGlobalsContext() final
Save the current Cling state of global objects.
Definition TCling.cxx:3875
void CallFunc_IgnoreExtraArgs(CallFunc_t *func, bool ignore) const final
Definition TCling.cxx:7937
void ApplyToInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:9639
void * LazyFunctionCreatorAutoload(const std::string &mangled_name)
Autoload a library based on a missing symbol.
Definition TCling.cxx:6594
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:4726
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:8136
Bool_t IsLibraryLoaded(const char *libname) const final
Definition TCling.cxx:3141
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:7482
int DataMemberInfo_ArrayDim(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8589
TypeInfo_t * MethodArgInfo_TypeInfo(MethodArgInfo_t *marginfo) const
Definition TCling.cxx:9333
DataMemberInfo_t * DataMemberInfo_FactoryCopy(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8623
Bool_t HandleNewTransaction(const cling::Transaction &T)
Helper function to increase the internal Cling count of transactions that change the AST.
Definition TCling.cxx:3668
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:5531
std::map< SpecialObjectLookupCtx_t, SpecialObjectMap_t > fSpecialObjectMaps
Definition TCling.h:153
int ClassInfo_Next(ClassInfo_t *info) const final
Definition TCling.cxx:8357
void SetErrmsgcallback(void *p) const final
Set a callback to receive error messages.
Definition TCling.cxx:7609
bool MethodArgInfo_IsValid(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9277
int TypeInfo_Size(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9417
Int_t DeleteGlobal(void *obj) final
Delete obj from Cling symbol table so it cannot be accessed anymore.
Definition TCling.cxx:3786
int GetSecurityError() const final
Interface to cling function.
Definition TCling.cxx:7490
void SetTempLevel(int val) const final
Create / close a scope for temporaries.
Definition TCling.cxx:7645
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:8854
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:5158
TypedefInfo_t * TypedefInfo_Factory() const final
Definition TCling.cxx:9454
TObjArray * fRootmapFiles
Definition TCling.h:126
bool IsVoidPointerType(const void *QualTypePtr) const
Definition TCling.cxx:9592
Longptr_t ProcessLine(const char *line, EErrorCode *error=nullptr) final
Definition TCling.cxx:2456
int ClassInfo_Size(ClassInfo_t *info) const final
Definition TCling.cxx:8405
const char * MethodArgInfo_TypeName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9317
cling::Interpreter * GetInterpreterImpl() const
Definition TCling.h:644
Longptr_t ExecuteMacro(const char *filename, EErrorCode *error=nullptr) final
Execute a cling macro.
Definition TCling.cxx:5406
std::vector< std::pair< TClass *, DictFuncPtr_t > > fClassesToUpdate
Definition TCling.h:146
int DataMemberInfo_Next(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8647
const char * TypedefInfo_Name(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9527
void BaseClassInfo_Delete(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8470
Long_t MethodInfo_ExtraProperty(MethodInfo_t *minfo) const final
Definition TCling.cxx:9105
void LoadMacro(const char *filename, EErrorCode *error=nullptr) final
Load a macro file in cling's memory.
Definition TCling.cxx:3555
FuncTempInfo_t * FuncTempInfo_FactoryCopy(FuncTempInfo_t *) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8831
int DataMemberInfo_MaxIndex(DataMemberInfo_t *dminfo, Int_t dim) const final
Definition TCling.cxx:8639
Bool_t FuncTempInfo_IsValid(FuncTempInfo_t *) const final
Check validity of a FuncTempInfo_t.
Definition TCling.cxx:8842
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:2665
bool ClassInfo_IsBase(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8292
void RecursiveRemove(TObject *obj) final
Delete object from cling symbol table so it can not be used anymore.
Definition TCling.cxx:3686
const char * DataMemberInfo_TypeName(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8687
DeclId_t GetDataMemberAtAddr(const void *addr) const final
Return pointer to cling DeclId for a data member with a given name.
Definition TCling.cxx:4953
void CallFunc_SetArgArray(CallFunc_t *func, Longptr_t *paramArr, Int_t nparam) const final
Definition TCling.cxx:8027
std::string CallFunc_GetWrapperCode(CallFunc_t *func) const final
Definition TCling.cxx:8117
void * RewindInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:9669
const char * MethodArgInfo_Name(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9309
Bool_t HasPCMForLibrary(const char *libname) const final
Return true if ROOT has cxxmodules pcm for a given library name.
Definition TCling.cxx:3150
void TypedefInfo_Init(TypedefInfo_t *tinfo, const char *name) const final
Definition TCling.cxx:9477
const char * DataMemberInfo_Title(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8711
Longptr_t CallFunc_ExecInt(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7890
void ClearStack() final
Delete existing temporary values.
Definition TCling.cxx:3088
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:7539
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:7359
MethodInfo_t * CallFunc_FactoryMethod(CallFunc_t *func) const final
Definition TCling.cxx:7929
bool IsUnsignedIntegerType(const void *QualTypePtr) const
Definition TCling.cxx:9568
TypedefInfo_t * TypedefInfo_FactoryCopy(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9470
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:5051
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:2396
std::string MethodArgInfo_TypeNormalizedName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9325
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:4835
Long_t MethodArgInfo_Property(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9293
int TypedefInfo_Size(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9511
void CallFunc_ExecWithArgsAndReturn(CallFunc_t *func, void *address, const void *args[]=nullptr, int nargs=0, void *ret=nullptr) const final
Definition TCling.cxx:7879
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:5203
Int_t fGlobalsListSerial
Definition TCling.h:114
TString fSharedLibs
Definition TCling.h:113
std::map< std::string, llvm::StringRef > fPendingRdicts
Definition TCling.h:634
static void UpdateClassInfoWork(const char *name)
Definition TCling.cxx:6748
Int_t Load(const char *filenam, Bool_t system=kFALSE) final
Load a library file in cling's memory.
Definition TCling.cxx:3518
int TypedefInfo_Next(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9495
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:5010
void TypeInfo_Init(TypeInfo_t *tinfo, const char *funcname) const final
Definition TCling.cxx:9376
Bool_t SetSuspendAutoParsing(Bool_t value) final
Suspend the Autoparsing of headers.
Definition TCling.cxx:7599
int DataMemberInfo_TypeSize(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8679
static void * fgSetOfSpecials
Definition TCling.h:105
const char * ClassInfo_Title(ClassInfo_t *info) const final
Definition TCling.cxx:8447
const char * DataMemberInfo_Name(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8703
const char * TypeName(const char *typeDesc) final
Return the absolute type of typeDesc.
Definition TCling.cxx:5481
ROOT::TMetaUtils::TNormalizedCtxt * fNormalizedCtxt
Definition TCling.h:134
bool IsSignedIntegerType(const void *QualTypePtr) const
Definition TCling.cxx:9560
void ForgetMutexState() final
Definition TCling.cxx:9623
int MethodInfo_Next(MethodInfo_t *minfo) const final
Definition TCling.cxx:9088
Long_t ClassInfo_ClassProperty(ClassInfo_t *info) const final
Definition TCling.cxx:8181
void MethodInfo_Delete(MethodInfo_t *minfo) const final
Interface to cling function.
Definition TCling.cxx:9007
bool fIsShuttingDown
Definition TCling.h:187
void MethodArgInfo_Delete(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9246
DataMemberInfo_t * DataMemberInfo_Factory(ClassInfo_t *clinfo, TDictionary::EMemberSelection selection) const final
Definition TCling.cxx:8604
void ClassInfo_Destruct(ClassInfo_t *info, void *arena) const final
Definition TCling.cxx:8212
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:6113
Int_t UnloadAllSharedLibraryMaps() final
Unload the library map entries coming from all the loaded shared libraries.
Definition TCling.cxx:6001
void ClassInfo_Init(ClassInfo_t *info, const char *funcname) const final
Definition TCling.cxx:8274
std::set< TClass * > & GetModTClasses()
Definition TCling.h:579
ClassInfo_t * BaseClassInfo_ClassInfo(BaseClassInfo_t *) const final
Definition TCling.cxx:8542
TClingCallbacks * fClingCallbacks
Definition TCling.h:139
Long64_t CallFunc_ExecInt64(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7898
Long_t ClassInfo_Property(ClassInfo_t *info) const final
Definition TCling.cxx:8397
Longptr_t ClassInfo_GetBaseOffset(ClassInfo_t *fromDerived, ClassInfo_t *toBase, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8521
void UpdateEnumConstants(TEnum *enumObj, TClass *cl) const final
Definition TCling.cxx:421
void ExecuteWithArgsAndReturn(TMethod *method, void *address, const void *args[]=nullptr, int nargs=0, void *ret=nullptr) const final
Definition TCling.cxx:5388
Bool_t IsErrorMessagesEnabled() const final
If error messages are disabled, the interpreter should suppress its failures and warning messages fro...
Definition TCling.cxx:7345
TString fIncludePath
Definition TCling.h:115
int DisplayIncludePath(FILE *fout) const final
Interface to cling function.
Definition TCling.cxx:7422
void TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:6954
Long_t FuncTempInfo_Property(FuncTempInfo_t *) const final
Return the property of the function template.
Definition TCling.cxx:8875
TEnum * CreateEnum(void *VD, TClass *cl) const final
Definition TCling.cxx:469
const char * TypeInfo_TrueName(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9425
Int_t UnloadLibraryMap(const char *library) final
Unload library map entries coming from the specified library.
Definition TCling.cxx:6019
void RegisterTemporary(const TInterpreterValue &value)
Definition TCling.cxx:7692
MutexStateAndRecurseCount fInitialMutex
Definition TCling.h:174
const char * GetSharedLibs() final
Return the list of shared libraries loaded into the process.
Definition TCling.cxx:6992
int MethodArgInfo_Next(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9285
void SnapshotMutexState(ROOT::TVirtualRWMutex *mtx) final
Definition TCling.cxx:9608
Long_t TypeInfo_Property(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9401
const char * MethodInfo_GetPrototype(MethodInfo_t *minfo) const final
Definition TCling.cxx:9134
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:8865
std::vector< cling::Value > * fTemporaries
Definition TCling.h:133
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:2013
static Int_t ShallowAutoLoadImpl(const char *cls)
Definition TCling.cxx:6159
void MethodInfo_CreateSignature(MethodInfo_t *minfo, TString &signature) const final
Definition TCling.cxx:9014
Bool_t CheckClassTemplate(const char *name) final
Return true if there is a class template by the given name ...
Definition TCling.cxx:4352
void LibraryLoaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:6977
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:2387
TObjArray * GetRootMapFiles() const final
Definition TCling.h:223
bool DataMemberInfo_IsValid(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8631
bool ClassInfo_IsEnum(const char *name) const final
Definition TCling.cxx:8300
int MethodInfo_NDefaultArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9080
void CreateListOfMethods(TClass *cl) const final
Create list of pointers to methods for TClass cl.
Definition TCling.cxx:4501
Int_t RescanLibraryMap() final
Scan again along the dynamic path for library maps.
Definition TCling.cxx:5928
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:7618
const char * MethodInfo_GetMangledName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9123
Bool_t fHeaderParsingOnDemand
Definition TCling.h:181
bool IsIntegerType(const void *QualTypePtr) const
Definition TCling.cxx:9552
std::hash< std::string > fStringHashFunction
Definition TCling.h:124
TEnv * fMapfile
Definition TCling.h:117
static void RemoveAndInvalidateObject(List &L, Object *O)
Definition TCling.h:591
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:5113
void * ClassInfo_New(ClassInfo_t *info) const final
Definition TCling.cxx:8365
int DisplayClass(FILE *fout, const char *name, int base, int start) const final
Definition TCling.cxx:7413
virtual void GetFunctionName(const clang::Decl *decl, std::string &name) const
Definition TCling.cxx:8766
void CreateListOfMethodArgs(TFunction *m) const final
Create list of pointers to method arguments for TMethod m.
Definition TCling.cxx:4526
virtual const char * GetSTLIncludePath() const final
Return the directory containing CINT's stl cintdlls.
Definition TCling.cxx:7404
MethodArgInfo_t * MethodArgInfo_FactoryCopy(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9269
Longptr_t BaseClassInfo_Offset(BaseClassInfo_t *toBaseClassInfo, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8513
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:4180
void * FindSym(const char *entry) const final
Interface to cling function.
Definition TCling.cxx:7451
void RegisterLoadedSharedLibrary(const char *name)
Register a new shared library name with the interpreter; add it to fSharedLibs.
Definition TCling.cxx:3418
void TypeInfo_Delete(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9346
int MethodInfo_NArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9072
DeclId_t GetDataMemberWithValue(const void *ptrvalue) const final
NOT IMPLEMENTED.
Definition TCling.cxx:4944
std::unordered_set< const clang::NamespaceDecl * > fNSFromRootmaps
Definition TCling.h:125
EReturnType MethodCallReturnType(TFunction *func) const final
Definition TCling.cxx:9182
void ProcessClassesToUpdate()
Definition TCling.cxx:1982
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:5136
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:4965
const char * MethodInfo_Title(MethodInfo_t *minfo) const final
Definition TCling.cxx:9173
TString fRootmapLoadPath
Definition TCling.h:116
const char * BaseClassInfo_TmpltName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8576
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:3101
const char * BaseClassInfo_FullName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8558
void CallFunc_SetArgs(CallFunc_t *func, const char *param) const final
Definition TCling.cxx:8035
int UnloadFile(const char *path) const final
Definition TCling.cxx:7651
void SetClassInfo(TClass *cl, Bool_t reload=kFALSE, Bool_t silent=kFALSE) final
Set pointer to the TClingClassInfo in TClass.
Definition TCling.cxx:4044
void CallFunc_Exec(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7855
bool IsPointerType(const void *QualTypePtr) const
Definition TCling.cxx:9584
bool IsFloatingType(const void *QualTypePtr) const
Definition TCling.cxx:9576
Long_t FuncTempInfo_ExtraProperty(FuncTempInfo_t *) const final
Return the property not already defined in Property See TDictionary's EFunctionProperty.
Definition TCling.cxx:8936
bool CallFunc_IsValid(CallFunc_t *func) const final
Definition TCling.cxx:7954
const char * BaseClassInfo_Name(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8568
ROOT::TMetaUtils::TClingLookupHelper * fLookupHelper
Definition TCling.h:135
const char * DataMemberInfo_ValidArrayIndex(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8719
Int_t GetMore() const final
Return whether we are waiting for more input either because the collected input contains unbalanced b...
Definition TCling.cxx:4547
Bool_t fIsAutoParsingSuspended
Definition TCling.h:182
std::string ToString(const char *type, void *obj) final
Definition TCling.cxx:1023
DeclId_t GetDeclId(const llvm::GlobalValue *gv) const
Return pointer to cling DeclId for a global value.
Definition TCling.cxx:4875
void Execute(const char *function, const char *params, int *error=nullptr) final
Execute a global function with arguments params.
Definition TCling.cxx:5236
bool ClassInfo_IsLoaded(ClassInfo_t *info) const final
Definition TCling.cxx:8325
Longptr_t ClassInfo_Tagnum(ClassInfo_t *info) const final
Definition TCling.cxx:8413
Long_t BaseClassInfo_Property(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8534
void CallFunc_SetFunc(CallFunc_t *func, ClassInfo_t *info, const char *method, const char *params, Longptr_t *Offset) const final
Definition TCling.cxx:8043
std::vector< std::string > GetUsingNamespaces(ClassInfo_t *cl) const final
Get the scopes representing using declarations of namespace.
Definition TCling.cxx:4481
const char * ClassInfo_FileName(ClassInfo_t *info) const final
Definition TCling.cxx:8421
void FuncTempInfo_Title(FuncTempInfo_t *, TString &name) const final
Return the comments associates with this function template.
Definition TCling.cxx:8975
const char * ClassInfo_TmpltName(ClassInfo_t *info) const final
Definition TCling.cxx:8455
void SaveContext() final
Save the current Cling state.
Definition TCling.cxx:3862
void LoadPCMImpl(TFile &pcmFile)
Tries to load a PCM from TFile; returns true on success.
Definition TCling.cxx:1697
Bool_t IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
Definition TCling.cxx:6630
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:3743
void CodeComplete(const std::string &, size_t &, std::vector< std::string > &) final
The call to Cling's tab complition.
Definition TCling.cxx:7673
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:3757
const char * MapCppName(const char *) const final
Interface to cling function.
Definition TCling.cxx:7526
Longptr_t Calc(const char *line, EErrorCode *error=nullptr) final
Directly execute an executable statement (e.g.
Definition TCling.cxx:3588
Int_t ReloadAllSharedLibraryMaps() final
Reload the library map entries coming from all the loaded shared libraries, after first unloading the...
Definition TCling.cxx:5940
void UpdateListOfGlobalFunctions() final
No op: see TClingCallbacks (used to update the list of global functions)
Definition TCling.cxx:3895
void DataMemberInfo_Delete(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8597
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:5419
void * fPrevLoadedDynLibInfo
Definition TCling.h:137
void UpdateListOfDataMembers(TClass *cl) const
Update the list of pointers to data members for TClass cl This is now a nop.
Definition TCling.cxx:4519
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:2687
Int_t SetClassSharedLibs(const char *cls, const char *libs) final
Register the AutoLoading information for a class.
Definition TCling.cxx:6081
MethodInfo_t * MethodInfo_FactoryCopy(MethodInfo_t *minfo) const final
Definition TCling.cxx:9048
std::set< const char * > fParsedPayloadsAddresses
Definition TCling.h:123
CallFuncIFacePtr_t CallFunc_IFacePtr(CallFunc_t *func) const final
Definition TCling.cxx:7963
MethodArgInfo_t * MethodArgInfo_Factory() const final
Definition TCling.cxx:9253
static void UpdateClassInfo(char *name, Long_t tagnum)
No op: see TClingCallbacks.
Definition TCling.cxx:6742
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:5032
void ClassInfo_Delete(ClassInfo_t *info) const final
Definition TCling.cxx:8189
std::unique_ptr< cling::Interpreter > fInterpreter
Definition TCling.h:130
EDataType ClassInfo_GetUnderlyingType(ClassInfo_t *info) const final
Definition TCling.cxx:8316
void FuncTempInfo_Delete(FuncTempInfo_t *) const final
Delete the FuncTempInfo_t.
Definition TCling.cxx:8811
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:5180
Int_t DeleteVariable(const char *name) final
Undeclare obj called name.
Definition TCling.cxx:3801
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:7098
Longptr_t DataMemberInfo_Offset(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8655
CallFunc_t * CallFunc_Factory() const final
Definition TCling.cxx:7914
MethodInfo_t * MethodInfo_Factory() const final
Definition TCling.cxx:9023
Long_t DataMemberInfo_TypeProperty(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8671
void ClearFileBusy() final
Reset the interpreter internal state in case a previous action was not correctly terminated.
Definition TCling.cxx:3080
cling::MetaProcessor * GetMetaProcessorImpl() const
Definition TCling.h:645
bool DiagnoseIfInterpreterException(const std::exception &e) const final
Definition TCling.cxx:2445
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:7549
std::set< size_t > fLookedUpClasses
Definition TCling.h:121
virtual void AddAvailableIndentifiers(TSeqCollection &Idents) final
Definition TCling.cxx:2361
void TypedefInfo_Delete(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9447
void Reset() final
Pressing Ctrl+C should forward here.
Definition TCling.cxx:3711
const char * TypedefInfo_TrueName(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9519
int SetClassAutoLoading(int) const final
Enable/Disable the AutoLoading of libraries.
Definition TCling.cxx:7570
const char * ClassInfo_FullName(ClassInfo_t *info) const final
Definition TCling.cxx:8429
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:6384
const char * MethodInfo_TypeName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9152
void CallFunc_SetArg(CallFunc_t *func, Long_t param) const final
Definition TCling.cxx:7979
const char * GetIncludePath() final
Refresh the list of include paths known to the interpreter and return it with -I prepended.
Definition TCling.cxx:7373
void UpdateListsOnUnloaded(const cling::Transaction &T)
Invalidate stored TCling state for declarations included in transaction ‘T’.
Definition TCling.cxx:6852
void UpdateClassInfoWithDecl(const clang::NamedDecl *ND)
Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
Definition TCling.cxx:6684
bool IsSameType(const void *QualTypePtr1, const void *QualTypePtr2) const
Definition TCling.cxx:9543
virtual void Initialize() final
Initialize the interpreter, once TROOT::fInterpreter is set.
Definition TCling.cxx:1636
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:8250
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:4774
void * fAutoLoadCallBack
Definition TCling.h:147
void FuncTempInfo_Name(FuncTempInfo_t *, TString &name) const final
Return the name of this function template.
Definition TCling.cxx:8962
std::unique_ptr< cling::MetaProcessor > fMetaProcessor
Definition TCling.h:131
bool TypeInfo_IsValid(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9385
bool RegisterPrebuiltModulePath(const std::string &FullPath, const std::string &ModuleMapName="module.modulemap") const final
Definition TCling.cxx:1908
std::string MethodInfo_TypeNormalizedName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9161
const char * ClassInfo_Name(ClassInfo_t *info) const final
Definition TCling.cxx:8439
TClass * GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent=kFALSE) final
Generate a TClass for the given class.
Definition TCling.cxx:4557
ULong64_t fTransactionCount
Definition TCling.h:148
bool ClassInfo_HasDefaultConstructor(ClassInfo_t *info, Bool_t testio=kFALSE) const final
Definition TCling.cxx:8258
void EndOfLineAction() final
It calls a "fantom" method to synchronize user keyboard input and ROOT prompt line.
Definition TCling.cxx:3124
TypeInfo_t * TypeInfo_FactoryCopy(TypeInfo_t *) const final
Definition TCling.cxx:9369
void * TypeInfo_QualTypePtr(TypeInfo_t *tinfo) const
Definition TCling.cxx:9433
bool ClassInfo_HasMethod(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8266
void ClassInfo_DeleteArray(ClassInfo_t *info, void *arena, bool dtorOnly) const final
Definition TCling.cxx:8204
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:8695
virtual void ShutDown() final
Definition TCling.cxx:1655
void UpdateListOfTypes() final
No op: see TClingCallbacks (used to update the list of types)
Definition TCling.cxx:3902
Long_t TypedefInfo_Property(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9503
void RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
Register Rdict data for future loading by LoadPCM;.
Definition TCling.cxx:1678
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:3572
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:4992
static void UpdateAllCanvases()
Update all canvases at end the terminal input command.
Definition TCling.cxx:6757
Int_t LoadLibraryMap(const char *rootmapfile=nullptr) final
Load map between class and library.
Definition TCling.cxx:5744
Longptr_t BaseClassInfo_Tagnum(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8550
void LibraryUnloaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:6984
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:175
@ kNone
Definition TEnum.h:48
@ kAutoload
Definition TEnum.h:49
Definition TEnv.h:86
The TEnv class reads config files, by default named .rootrc.
Definition TEnv.h:124
THashList * GetTable() const
Definition TEnv.h:140
Bool_t IgnoreDuplicates(Bool_t ignore)
If set to true, no warnings in case of duplicates are issued.
Definition TEnv.cxx:793
virtual void SetRcName(const char *name)
Definition TEnv.h:145
virtual Int_t ReadFile(const char *fname, EEnvLevel level)
Read and parse the resource file for a certain level.
Definition TEnv.cxx:592
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:736
virtual TEnvRec * Lookup(const char *n) const
Loop over all resource records and return the one with name.
Definition TEnv.cxx:547
A ROOT file is an on-disk file, usually with extension .root, that stores objects in a file-system-li...
Definition TFile.h:53
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 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:355
A TMemFile is like a normal TFile except that it reads and writes only from memory.
Definition TMemFile.h:19
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:47
TNamed()
Definition TNamed.h:36
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:41
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:199
R__ALWAYS_INLINE Bool_t IsOnHeap() const
Definition TObject.h:152
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:979
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition TObject.cxx:408
static TClass * Class()
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:993
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition TObject.cxx:1021
virtual TClass * IsA() const
Definition TObject.h:243
void MakeZombie()
Definition TObject.h:53
@ kInvalidObject
if object ctor succeeded but object should not be used
Definition TObject.h:72
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:967
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:3073
static const char * GetMacroPath()
Get macro search path. Static utility function.
Definition TROOT.cxx:2790
static const std::vector< std::string > & AddExtraInterpreterArgs(const std::vector< std::string > &args)
Provide command line arguments to the interpreter construction.
Definition TROOT.cxx:2983
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition TROOT.cxx:3083
static const char **& GetExtraInterpreterArgs()
INTERNAL function! Used by rootcling to inject interpreter arguments through a C-interface layer.
Definition TROOT.cxx:2993
static const TString & GetSharedLibDir()
Get the shared libraries directory in the installation. Static utility function.
Definition TROOT.cxx:3062
Sequenceable collection abstract base class.
Int_t LastIndex() const
Describes a persistent version of a class.
Basic string class.
Definition TString.h:139
Ssiz_t Length() const
Definition TString.h:417
const char * Data() const
Definition TString.h:376
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:704
Bool_t IsNull() const
Definition TString.h:414
TString & Append(const char *cs)
Definition TString.h:572
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:2378
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:632
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1274
virtual void FreeDirectory(void *dirp)
Free a directory.
Definition TSystem.cxx:845
virtual void * OpenDirectory(const char *name)
Open a directory. Returns 0 if directory does not exist.
Definition TSystem.cxx:836
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1665
virtual const char * GetIncludePath()
Get the list of include path.
Definition TSystem.cxx:3973
virtual TString SplitAclicMode(const char *filename, TString &mode, TString &args, TString &io) const
This method split a filename of the form:
Definition TSystem.cxx:4258
virtual char * ConcatFileName(const char *dir, const char *name)
Concatenate a directory and a file name. User must delete returned string.
Definition TSystem.cxx:1071
virtual const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1538
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1857
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:1398
virtual const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Definition TSystem.cxx:1081
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:1296
virtual const char * GetDirEntry(void *dirp)
Get a directory entry. Returns 0 if no more entries.
Definition TSystem.cxx:853
virtual int GetProcInfo(ProcInfo_t *info) const
Returns cpu and memory used by this process into the ProcInfo_t structure.
Definition TSystem.cxx:2489
virtual const char * BaseName(const char *pathname)
Base name of a file name. Base name of /user/root is root.
Definition TSystem.cxx:934
virtual const char * GetDynamicPath()
Return the dynamic path (used to find shared libraries).
Definition TSystem.cxx:1795
virtual const char * FindDynamicLibrary(TString &lib, Bool_t quiet=kFALSE)
Find a dynamic library using the system search paths.
Definition TSystem.cxx:2034
virtual void Sleep(UInt_t milliSec)
Sleep milliSec milli seconds.
Definition TSystem.cxx:437
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:2836
virtual const char * WorkingDirectory()
Return working directory.
Definition TSystem.cxx:871
virtual char * Which(const char *search, const char *file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1548
virtual void Setenv(const char *name, const char *value)
Set environment variable.
Definition TSystem.cxx:1649
virtual const char * HomeDirectory(const char *userName=nullptr)
Return the user's home directory.
Definition TSystem.cxx:887
virtual TString GetDirName(const char *pathname)
Return the directory name in pathname.
Definition TSystem.cxx:1032
virtual void StackTrace()
Print a stack trace.
Definition TSystem.cxx:734
char * DynamicPathName(const char *lib, Bool_t quiet=kFALSE)
Find a dynamic library called lib using the system search paths.
Definition TSystem.cxx:2020
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.
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
R__EXTERN TVirtualRWMutex * gCoreMutex
EFunctionMatchMode
@ kExactMatch
bool IsStdPairBase(std::string_view name)
Definition TClassEdit.h:188
bool IsStdArray(std::string_view name)
Definition TClassEdit.h:183
bool IsStdClass(const char *type)
return true if the class belongs to the std namespace
bool IsStdPair(std::string_view name)
Definition TClassEdit.h:184
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:208
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.
bool IsUniquePtr(std::string_view name)
Definition TClassEdit.h:182
@ kDropStlDefault
Definition TClassEdit.h:82
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:157
Int_t fRecurseCount
Interpreter-related functions will push the "entry" lock state to *this.
Definition TCling.h:162
A read-only memory range which we do not control.
Definition TMemFile.h:23
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
static void output()