Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
clingwrapper.cxx
Go to the documentation of this file.
1#ifndef WIN32
2#ifndef _CRT_SECURE_NO_WARNINGS
3// silence warnings about getenv, strncpy, etc.
4#define _CRT_SECURE_NO_WARNINGS
5#endif
6#endif
7
8// Bindings
9#include "precommondefs.h"
10#include "cpp_cppyy.h"
11#include "callcontext.h"
12
13// ROOT
14#include "TBaseClass.h"
15#include "TClass.h"
16#include "TClassRef.h"
17#include "TClassTable.h"
18#include "TClassEdit.h"
19#include "TCollection.h"
20#include "TDataMember.h"
21#include "TDataType.h"
22#include "TEnum.h"
23#include "TEnumConstant.h"
24#include "TEnv.h"
25#include "TError.h"
26#include "TException.h"
27#include "TFunction.h"
28#include "TFunctionTemplate.h"
29#include "TGlobal.h"
30#include "THashList.h"
31#include "TInterpreter.h"
32#include "TList.h"
33#include "TListOfDataMembers.h"
34#include "TListOfEnums.h"
35#include "TMethod.h"
36#include "TMethodArg.h"
37#include "TROOT.h"
38#include "TSystem.h"
39#include "TThread.h"
40
41// Standard
42#include <cassert>
43#include <algorithm> // for std::count, std::remove
44#include <climits>
45#include <stdexcept>
46#include <map>
47#include <new>
48#include <set>
49#include <sstream>
50#include <csignal>
51#include <cstdlib> // for getenv
52#include <cstring>
53#include <typeinfo>
54
55#if defined(__arm64__)
56#include <exception>
57#include <setjmp.h>
58#define CLING_CATCH_UNCAUGHT_ \
59ARMUncaughtException guard; \
60if (setjmp(gExcJumBuf) == 0) {
61#define _CLING_CATCH_UNCAUGHT \
62} else { \
63 if (!std::getenv("CPPYY_UNCAUGHT_QUIET")) \
64 std::cerr << "Warning: uncaught exception in JIT is rethrown; resources may leak" \
65 << " (suppress with \"CPPYY_UNCAUGHT_QUIET=1\")" << std::endl;\
66 std::rethrow_exception(std::current_exception()); \
67}
68#else
69#define CLING_CATCH_UNCAUGHT_
70#define _CLING_CATCH_UNCAUGHT
71#endif
72
73#if 0
74// force std::string and allocator instantation, otherwise Clang 13+ fails to JIT
75// symbols that rely on some private helpers (e.g. _M_use_local_data) when used in
76// in conjunction with the PCH; hat tip:
77// https://github.com/sxs-collaboration/spectre/pull/5222/files#diff-093aadf224e5fee0d33ae1810f2f1c23304fb5ca398ba6b96c4e7918e0811729
78#if defined(__GLIBCXX__) && __GLIBCXX__ >= 20220506
79template class std::allocator<char>;
80template class std::basic_string<char>;
81template class std::basic_string<wchar_t>;
82#endif
83
84using namespace CppyyLegacy;
85#endif
86
87// temp
88#include <iostream>
90// --temp
91
92#if 0
93#if defined(__arm64__)
94namespace {
95
96// Trap uncaught exceptions and longjump back to the point of JIT wrapper entry
97jmp_buf gExcJumBuf;
98
99void arm_uncaught_exception() {
100 longjmp(gExcJumBuf, 1);
101}
102
103class ARMUncaughtException {
104 std::terminate_handler m_Handler;
105public:
106 ARMUncaughtException() { m_Handler = std::set_terminate(arm_uncaught_exception); }
107 ~ARMUncaughtException() { std::set_terminate(m_Handler); }
108};
109
110} // unnamed namespace
111#endif // __arm64__
112#endif
113
114// small number that allows use of stack for argument passing
115const int SMALL_ARGS_N = 8;
116
117// convention to pass flag for direct calls (similar to Python's vector calls)
118#define DIRECT_CALL ((size_t)1 << (8 * sizeof(size_t) - 1))
119static inline size_t CALL_NARGS(size_t nargs) {
120 return nargs & ~DIRECT_CALL;
121}
122
123// data for life time management ---------------------------------------------
124typedef std::vector<TClassRef> ClassRefs_t;
126static const ClassRefs_t::size_type GLOBAL_HANDLE = 1;
127static const ClassRefs_t::size_type STD_HANDLE = GLOBAL_HANDLE + 1;
128
129typedef std::map<std::string, ClassRefs_t::size_type> Name2ClassRefIndex_t;
131
132static std::map<std::string, std::string> resolved_enum_types;
133
134namespace {
135
136static inline
137Cppyy::TCppType_t find_memoized_scope(const std::string& name)
138{
139 auto icr = g_name2classrefidx.find(name);
140 if (icr != g_name2classrefidx.end())
141 return (Cppyy::TCppType_t)icr->second;
142 return (Cppyy::TCppType_t)0;
143}
144
145static inline
146std::string find_memoized_resolved_name(const std::string& name)
147{
148// resolved class types
149 Cppyy::TCppType_t klass = find_memoized_scope(name);
150 if (klass) return Cppyy::GetScopedFinalName(klass);
151
152// resolved enum types
153 auto res = resolved_enum_types.find(name);
154 if (res != resolved_enum_types.end())
155 return res->second;
156
157// unknown ...
158 return "";
159}
160
161class CallWrapper {
162public:
163 typedef const void* DeclId_t;
164
165public:
166 CallWrapper(TFunction* f) : fDecl(f->GetDeclId()), fName(f->GetName()), fTF(new TFunction(*f)) {}
167 CallWrapper(DeclId_t fid, const std::string& n) : fDecl(fid), fName(n), fTF(nullptr) {}
168 ~CallWrapper() {
169 delete fTF;
170 }
171
172public:
174 DeclId_t fDecl;
175 std::string fName;
176 TFunction* fTF;
177};
178
179}
180
181static std::vector<CallWrapper*> gWrapperHolder;
182
183static inline
185{
186 CallWrapper* wrap = new CallWrapper(f);
187 gWrapperHolder.push_back(wrap);
188 return wrap;
189}
190
191static inline
192CallWrapper* new_CallWrapper(CallWrapper::DeclId_t fid, const std::string& n)
193{
194 CallWrapper* wrap = new CallWrapper(fid, n);
195 gWrapperHolder.push_back(wrap);
196 return wrap;
197}
198
199typedef std::vector<TGlobal*> GlobalVars_t;
200typedef std::map<TGlobal*, GlobalVars_t::size_type> GlobalVarsIndices_t;
201
204
205static std::set<std::string> gSTLNames;
206
207
208// data ----------------------------------------------------------------------
210
211// builtin types (including a few common STL templates as long as they live in
212// the global namespace b/c of choices upstream)
213static std::set<std::string> g_builtins =
214 {"bool", "char", "signed char", "unsigned char", "wchar_t", "short", "unsigned short",
215 "int", "unsigned int", "long", "unsigned long", "long long", "unsigned long long",
216 "float", "double", "long double", "void",
217 "allocator", "array", "basic_string", "complex", "initializer_list", "less", "list",
218 "map", "pair", "set", "vector"};
219
220// smart pointer types
221static std::set<std::string> gSmartPtrTypes =
222 {"auto_ptr", "std::auto_ptr", "shared_ptr", "std::shared_ptr",
223 "unique_ptr", "std::unique_ptr", "weak_ptr", "std::weak_ptr"};
224
225// to filter out ROOT names
226static std::set<std::string> gInitialNames;
227static std::set<std::string> gRootSOs;
228
229// configuration
230static bool gEnableFastPath = true;
231
232
233// global initialization -----------------------------------------------------
234namespace {
235
236// names copied from TUnixSystem
237#ifdef WIN32
238const int SIGBUS = 0; // simple placeholders for ones that don't exist
239const int SIGSYS = 0;
240const int SIGPIPE = 0;
241const int SIGQUIT = 0;
242const int SIGWINCH = 0;
243const int SIGALRM = 0;
244const int SIGCHLD = 0;
245const int SIGURG = 0;
246const int SIGUSR1 = 0;
247const int SIGUSR2 = 0;
248#endif
249
250static struct Signalmap_t {
251 int fCode;
252 const char *fSigName;
253} gSignalMap[kMAXSIGNALS] = { // the order of the signals should be identical
254 { SIGBUS, "bus error" }, // to the one in TSysEvtHandler.h
255 { SIGSEGV, "segmentation violation" },
256 { SIGSYS, "bad argument to system call" },
257 { SIGPIPE, "write on a pipe with no one to read it" },
258 { SIGILL, "illegal instruction" },
259 { SIGABRT, "abort" },
260 { SIGQUIT, "quit" },
261 { SIGINT, "interrupt" },
262 { SIGWINCH, "window size change" },
263 { SIGALRM, "alarm clock" },
264 { SIGCHLD, "death of a child" },
265 { SIGURG, "urgent data arrived on an I/O channel" },
266 { SIGFPE, "floating point exception" },
267 { SIGTERM, "termination signal" },
268 { SIGUSR1, "user-defined signal 1" },
269 { SIGUSR2, "user-defined signal 2" }
270};
271
272static void inline do_trace(int sig) {
273 std::cerr << " *** Break *** " << (sig < kMAXSIGNALS ? gSignalMap[sig].fSigName : "") << std::endl;
275}
276
277class TExceptionHandlerImp : public TExceptionHandler {
278public:
279 void HandleException(Int_t sig) override {
280 if (TROOT::Initialized()) {
281 if (gException) {
282 gInterpreter->RewindDictionary();
283 gInterpreter->ClearFileBusy();
284 }
285
286 if (!std::getenv("CPPYY_CRASH_QUIET"))
287 do_trace(sig);
288
289 // jump back, if catch point set
290 Throw(sig);
291 }
292
293 do_trace(sig);
294 gSystem->Exit(128 + sig);
295 }
296};
297
298class ApplicationStarter {
299public:
300 ApplicationStarter() {
301 // initialize ROOT early to guarantee proper order of shutdown later on (gROOT is a
302 // macro that resolves to the ::CppyyLegacy::GetROOT() function call)
303 (void)gROOT;
304
305 // setup dummy holders for global and std namespaces
306 assert(g_classrefs.size() == GLOBAL_HANDLE);
308 g_classrefs.push_back(TClassRef(""));
309
310 // aliases for std (setup already in pythonify)
312 g_name2classrefidx["::std"] = g_name2classrefidx["std"];
313 g_classrefs.push_back(TClassRef("std"));
314
315 // add a dummy global to refer to as null at index 0
316 g_globalvars.push_back(nullptr);
317 g_globalidx[nullptr] = 0;
318
319 // fill out the builtins
320 std::set<std::string> bi{g_builtins};
321 for (const auto& name : bi) {
322 for (const char* a : {"*", "&", "*&", "[]", "*[]"})
323 g_builtins.insert(name+a);
324 }
325
326 // disable fast path if requested
327 if (std::getenv("CPPYY_DISABLE_FASTPATH")) gEnableFastPath = false;
328
329 // fill the set of STL names
330 const char* stl_names[] = {"allocator", "auto_ptr", "bad_alloc", "bad_cast",
331 "bad_exception", "bad_typeid", "basic_filebuf", "basic_fstream", "basic_ifstream",
332 "basic_ios", "basic_iostream", "basic_istream", "basic_istringstream",
333 "basic_ofstream", "basic_ostream", "basic_ostringstream", "basic_streambuf",
334 "basic_string", "basic_stringbuf", "basic_stringstream", "binary_function",
335 "binary_negate", "bitset", "byte", "char_traits", "codecvt_byname", "codecvt", "collate",
336 "collate_byname", "compare", "complex", "ctype_byname", "ctype", "default_delete",
337 "deque", "divides", "domain_error", "equal_to", "exception", "forward_list", "fpos",
338 "function", "greater_equal", "greater", "gslice_array", "gslice", "hash", "indirect_array",
339 "integer_sequence", "invalid_argument", "ios_base", "istream_iterator", "istreambuf_iterator",
340 "istrstream", "iterator_traits", "iterator", "length_error", "less_equal", "less",
341 "list", "locale", "localedef utility", "locale utility", "logic_error", "logical_and",
342 "logical_not", "logical_or", "map", "mask_array", "mem_fun", "mem_fun_ref", "messages",
343 "messages_byname", "minus", "modulus", "money_get", "money_put", "moneypunct",
344 "moneypunct_byname", "multimap", "multiplies", "multiset", "negate", "not_equal_to",
345 "num_get", "num_put", "numeric_limits", "numpunct", "numpunct_byname",
346 "ostream_iterator", "ostreambuf_iterator", "ostrstream", "out_of_range",
347 "overflow_error", "pair", "plus", "pointer_to_binary_function",
348 "pointer_to_unary_function", "priority_queue", "queue", "range_error",
349 "raw_storage_iterator", "reverse_iterator", "runtime_error", "set", "shared_ptr",
350 "slice_array", "slice", "stack", "string", "strstream", "strstreambuf",
351 "time_get_byname", "time_get", "time_put_byname", "time_put", "unary_function",
352 "unary_negate", "unique_ptr", "underflow_error", "unordered_map", "unordered_multimap",
353 "unordered_multiset", "unordered_set", "valarray", "vector", "weak_ptr", "wstring",
354 "__hash_not_enabled"};
355 for (auto& name : stl_names)
356 gSTLNames.insert(name);
357
358 // set opt level (default to 2 if not given; Cling itself defaults to 0)
359 int optLevel = 2;
360 if (std::getenv("CPPYY_OPT_LEVEL")) optLevel = atoi(std::getenv("CPPYY_OPT_LEVEL"));
361 if (optLevel != 0) {
362 std::ostringstream s;
363 s << "#pragma cling optimize " << optLevel;
364 gInterpreter->ProcessLine(s.str().c_str());
365 }
366
367 // load frequently used headers
368 const char* code =
369 "#include <iostream>\n"
370 "#include <string>\n"
371 "#include <DllImport.h>\n" // defines R__EXTERN
372 "#include <vector>\n"
373 "#include <utility>";
374 gInterpreter->ProcessLine(code);
375
376 // create helpers for comparing thingies
377 gInterpreter->Declare(
378 "namespace __cppyy_internal { template<class C1, class C2>"
379 " bool is_equal(const C1& c1, const C2& c2) { return (bool)(c1 == c2); } }");
380 gInterpreter->Declare(
381 "namespace __cppyy_internal { template<class C1, class C2>"
382 " bool is_not_equal(const C1& c1, const C2& c2) { return (bool)(c1 != c2); } }");
383
384 // helper for multiple inheritance
385 gInterpreter->Declare("namespace __cppyy_internal { struct Sep; }");
386
387 // retrieve all initial (ROOT) C++ names in the global scope to allow filtering later
388 gROOT->GetListOfGlobals(true); // force initialize
389 gROOT->GetListOfGlobalFunctions(true); // id.
390 std::set<std::string> initial;
392 gInitialNames = initial;
393
394#ifndef WIN32
395 gRootSOs.insert("libCore.so ");
396 gRootSOs.insert("libRIO.so ");
397 gRootSOs.insert("libThread.so ");
398 gRootSOs.insert("libMathCore.so ");
399#else
400 gRootSOs.insert("libCore.dll ");
401 gRootSOs.insert("libRIO.dll ");
402 gRootSOs.insert("libThread.dll ");
403 gRootSOs.insert("libMathCore.dll ");
404#endif
405
406 // start off with a reasonable size placeholder for wrappers
407 gWrapperHolder.reserve(1024);
408
409 // create an exception handler to process signals
410 gExceptionHandler = new TExceptionHandlerImp{};
411 }
412
413 ~ApplicationStarter() {
414 for (auto wrap : gWrapperHolder)
415 delete wrap;
416 delete gExceptionHandler; gExceptionHandler = nullptr;
417 }
418} _applicationStarter;
419
420} // unnamed namespace
421
422
423// local helpers -------------------------------------------------------------
424static inline
426{
427 assert((ClassRefs_t::size_type)scope < g_classrefs.size());
428 return g_classrefs[(ClassRefs_t::size_type)scope];
429}
430
431static inline
433 CallWrapper* wrap = ((CallWrapper*)method);
434 if (!wrap->fTF) {
435 MethodInfo_t* mi = gInterpreter->MethodInfo_Factory(wrap->fDecl);
436 wrap->fTF = new TFunction(mi);
437 }
438 return wrap->fTF;
439}
440
441/*
442static inline
443CallWrapper::DeclId_t m2d(Cppyy::TCppMethod_t method) {
444 CallWrapper* wrap = ((CallWrapper*)method);
445 if (!wrap->fTF || wrap->fTF->GetDeclId() != wrap->fDecl) {
446 MethodInfo_t* mi = gInterpreter->MethodInfo_Factory(wrap->fDecl);
447 wrap->fTF = new TFunction(mi);
448 }
449 return wrap->fDecl;
450}
451*/
452
453static inline
454char* cppstring_to_cstring(const std::string& cppstr)
455{
456 char* cstr = (char*)malloc(cppstr.size()+1);
457 memcpy(cstr, cppstr.c_str(), cppstr.size()+1);
458 return cstr;
459}
460
461static inline
462bool match_name(const std::string& tname, const std::string fname)
463{
464// either match exactly, or match the name as template
465 if (fname.rfind(tname, 0) == 0) {
466 if ((tname.size() == fname.size()) ||
467 (tname.size() < fname.size() && fname[tname.size()] == '<'))
468 return true;
469 }
470 return false;
471}
472
473static inline
474bool is_missclassified_stl(const std::string& name)
475{
476 std::string::size_type pos = name.find('<');
477 if (pos != std::string::npos)
478 return gSTLNames.find(name.substr(0, pos)) != gSTLNames.end();
479 return gSTLNames.find(name) != gSTLNames.end();
480}
481
482
483// direct interpreter access -------------------------------------------------
484bool Cppyy::Compile(const std::string& code, bool /*silent*/)
485{
486 return gInterpreter->Declare(code.c_str());
487}
488
490{
491 if (klass && obj && !IsNamespace((TCppScope_t)klass))
492 return gInterpreter->ToString(GetScopedFinalName(klass).c_str(), (void*)obj);
493 return "";
494}
495
496
497// name to opaque C++ scope representation -----------------------------------
498std::string Cppyy::ResolveName(const std::string& cppitem_name)
499{
500// Fully resolve the given name to the final type name.
501
502// try memoized type cache, in case seen before
503 std::string memoized = find_memoized_resolved_name(cppitem_name);
504 if (!memoized.empty()) return memoized;
505
506// remove global scope '::' if present
507 std::string tclean = cppitem_name.compare(0, 2, "::") == 0 ?
508 cppitem_name.substr(2, std::string::npos) : cppitem_name;
509
510// classes (most common)
511 tclean = TClassEdit::CleanType(tclean.c_str());
512 if (tclean.empty() /* unknown, eg. an operator */) return cppitem_name;
513
514// reduce [N] to []
515 if (tclean[tclean.size()-1] == ']')
516 tclean = tclean.substr(0, tclean.rfind('[')) + "[]";
517
518 if (tclean.rfind("byte", 0) == 0 || tclean.rfind("std::byte", 0) == 0)
519 return tclean;
520
521// remove __restrict and __restrict__
522 auto pos = tclean.rfind("__restrict");
523 if (pos != std::string::npos)
524 tclean = tclean.substr(0, pos);
525
526 if (tclean.compare(0, 9, "std::byte") == 0)
527 return tclean;
528
529// check data types list (accept only builtins as typedefs will
530// otherwise not be resolved)
531 if (IsBuiltin(tclean)) return tclean;
532
533// special case for enums
534 if (IsEnum(cppitem_name))
535 return ResolveEnum(cppitem_name);
536
537// special case for clang's builtin __type_pack_element (which does not resolve)
538 pos = cppitem_name.size() > 20 ? \
539 cppitem_name.rfind("__type_pack_element", 5) : std::string::npos;
540 if (pos != std::string::npos) {
541 // shape is "[std::]__type_pack_element<index,type1,type2,...,typeN>cpd": extract
542 // first the index, and from there the indexed type; finally, restore the
543 // qualifiers
544 const char* str = cppitem_name.c_str();
545 char* endptr = nullptr;
546 unsigned long index = strtoul(str+20+pos, &endptr, 0);
547
548 std::string tmplvars{endptr};
549 auto start = tmplvars.find(',') + 1;
550 auto end = tmplvars.find(',', start);
551 while (index != 0) {
552 start = end+1;
553 end = tmplvars.find(',', start);
554 if (end == std::string::npos) end = tmplvars.rfind('>');
555 --index;
556 }
557
558 std::string resolved = tmplvars.substr(start, end-start);
559 auto cpd = tmplvars.rfind('>');
560 if (cpd != std::string::npos && cpd+1 != tmplvars.size())
561 return resolved + tmplvars.substr(cpd+1, std::string::npos);
562 return resolved;
563 }
564
565// typedefs etc. (and a couple of hacks around TClassEdit-isms, fixing of which
566// in ResolveTypedef itself is a TODO ...)
567 tclean = TClassEdit::ResolveTypedef(tclean.c_str(), true);
568 pos = 0;
569 while ((pos = tclean.find("::::", pos)) != std::string::npos) {
570 tclean.replace(pos, 4, "::");
571 pos += 2;
572 }
573
574 if (tclean.compare(0, 6, "const ") != 0)
575 return TClassEdit::ShortType(tclean.c_str(), 2);
576 return "const " + TClassEdit::ShortType(tclean.c_str(), 2);
577}
578
579#if 0
580//----------------------------------------------------------------------------
581static std::string extract_namespace(const std::string& name)
582{
583// Find the namespace the named class lives in, take care of templates
584// Note: this code also lives in CPyCppyy (TODO: refactor?)
585 if (name.empty())
586 return name;
587
588 int tpl_open = 0;
589 for (std::string::size_type pos = name.size()-1; 0 < pos; --pos) {
590 std::string::value_type c = name[pos];
591
592 // count '<' and '>' to be able to skip template contents
593 if (c == '>')
594 ++tpl_open;
595 else if (c == '<')
596 --tpl_open;
597
598 // collect name up to "::"
599 else if (tpl_open == 0 && c == ':' && name[pos-1] == ':') {
600 // found the extend of the scope ... done
601 return name.substr(0, pos-1);
602 }
603 }
604
605// no namespace; assume outer scope
606 return "";
607}
608#endif
609
610std::string Cppyy::ResolveEnum(const std::string& enum_type)
611{
612// The underlying type of a an enum may be any kind of integer.
613// Resolve that type via a workaround (note: this function assumes
614// that the enum_type name is a valid enum type name)
615 auto res = resolved_enum_types.find(enum_type);
616 if (res != resolved_enum_types.end())
617 return res->second;
618
619// desugar the type before resolving
620 std::string et_short = TClassEdit::ShortType(enum_type.c_str(), 1);
621 if (et_short.find("(unnamed") == std::string::npos) {
622 std::ostringstream decl;
623 // TODO: now presumed fixed with https://sft.its.cern.ch/jira/browse/ROOT-6988
624 for (auto& itype : {"unsigned int"}) {
625 decl << "std::is_same<"
626 << itype
627 << ", std::underlying_type<"
628 << et_short
629 << ">::type>::value;";
630 if (gInterpreter->ProcessLine(decl.str().c_str())) {
631 // TODO: "re-sugaring" like this is brittle, but the top
632 // should be re-translated into AST-based code anyway
633 std::string resugared;
634 if (et_short.size() != enum_type.size()) {
635 auto pos = enum_type.find(et_short);
636 if (pos != std::string::npos) {
637 resugared = enum_type.substr(0, pos) + itype;
638 if (pos+et_short.size() < enum_type.size())
639 resugared += enum_type.substr(pos+et_short.size(), std::string::npos);
640 }
641 }
642 if (resugared.empty()) resugared = itype;
643 resolved_enum_types[enum_type] = resugared;
644 return resugared;
645 }
646 }
647 }
648
649// failed or anonymous ... signal upstream to special case this
650 int ipos = (int)enum_type.size()-1;
651 for (; 0 <= ipos; --ipos) {
652 char c = enum_type[ipos];
653 if (isspace(c)) continue;
654 if (isalnum(c) || c == '_' || c == '>' || c == ')') break;
655 }
656 bool isConst = enum_type.find("const ", 6) != std::string::npos;
657 std::string restype = isConst ? "const " : "";
658 restype += "internal_enum_type_t"+enum_type.substr((std::string::size_type)ipos+1, std::string::npos);
659 resolved_enum_types[enum_type] = restype;
660 return restype; // should default to some int variant
661}
662
663#if 0
664static Cppyy::TCppIndex_t ArgSimilarityScore(void *argqtp, void *reqqtp)
665{
666// This scoring is not based on any particular rules
667 if (gInterpreter->IsSameType(argqtp, reqqtp))
668 return 0; // Best match
669 else if ((gInterpreter->IsSignedIntegerType(argqtp) && gInterpreter->IsSignedIntegerType(reqqtp)) ||
670 (gInterpreter->IsUnsignedIntegerType(argqtp) && gInterpreter->IsUnsignedIntegerType(reqqtp)) ||
671 (gInterpreter->IsFloatingType(argqtp) && gInterpreter->IsFloatingType(reqqtp)))
672 return 1;
673 else if ((gInterpreter->IsSignedIntegerType(argqtp) && gInterpreter->IsUnsignedIntegerType(reqqtp)) ||
674 (gInterpreter->IsFloatingType(argqtp) && gInterpreter->IsUnsignedIntegerType(reqqtp)))
675 return 2;
676 else if ((gInterpreter->IsIntegerType(argqtp) && gInterpreter->IsIntegerType(reqqtp)))
677 return 3;
678 else if ((gInterpreter->IsIntegralType(argqtp) && gInterpreter->IsIntegralType(reqqtp)))
679 return 4;
680 else if ((gInterpreter->IsVoidPointerType(argqtp) && gInterpreter->IsPointerType(reqqtp)))
681 return 5;
682 else
683 return 10; // Penalize heavily for no possible match
684}
685#endif
686
687Cppyy::TCppScope_t Cppyy::GetScope(const std::string& sname)
688{
689// First, try cache
690 TCppType_t result = find_memoized_scope(sname);
691 if (result) return result;
692
693// Second, skip builtins before going through the more expensive steps of resolving
694// typedefs and looking up TClass
695 if (g_builtins.find(sname) != g_builtins.end())
696 return (TCppScope_t)0;
697
698// TODO: scope_name should always be final already?
699// Resolve name fully before lookup to make sure all aliases point to the same scope
700 std::string scope_name = ResolveName(sname);
701 bool bHasAlias1 = sname != scope_name;
702 if (bHasAlias1) {
703 result = find_memoized_scope(scope_name);
704 if (result) {
705 g_name2classrefidx[sname] = result;
706 return result;
707 }
708 }
709
710// both failed, but may be STL name that's missing 'std::' now, but didn't before
711 bool b_scope_name_missclassified = is_missclassified_stl(scope_name);
712 if (b_scope_name_missclassified) {
713 result = find_memoized_scope("std::"+scope_name);
714 if (result) g_name2classrefidx["std::"+scope_name] = (ClassRefs_t::size_type)result;
715 }
716 bool b_sname_missclassified = bHasAlias1 ? is_missclassified_stl(sname) : false;
717 if (b_sname_missclassified) {
718 if (!result) result = find_memoized_scope("std::"+sname);
719 if (result) g_name2classrefidx["std::"+sname] = (ClassRefs_t::size_type)result;
720 }
721
722 if (result) return result;
723
724// use TClass directly, to enable auto-loading; class may be stubbed (eg. for
725// function returns) or forward declared, leading to a non-null TClass that is
726// otherwise invalid/unusable
727 TClassRef cr(TClass::GetClass(scope_name.c_str(), true /* load */, true /* silent */));
728 if (!cr.GetClass())
729 return (TCppScope_t)0;
730
731// memoize found/created TClass
732 bool bHasAlias2 = cr->GetName() != scope_name;
733 if (bHasAlias2) {
734 result = find_memoized_scope(cr->GetName());
735 if (result) {
736 g_name2classrefidx[scope_name] = result;
737 if (bHasAlias1) g_name2classrefidx[sname] = result;
738 return result;
739 }
740 }
741
742 ClassRefs_t::size_type sz = g_classrefs.size();
743 g_name2classrefidx[scope_name] = sz;
744 if (bHasAlias1) g_name2classrefidx[sname] = sz;
745 if (bHasAlias2) g_name2classrefidx[cr->GetName()] = sz;
746// TODO: make ROOT/meta NOT remove std :/
747 if (b_scope_name_missclassified)
748 g_name2classrefidx["std::"+scope_name] = sz;
749 if (b_sname_missclassified)
750 g_name2classrefidx["std::"+sname] = sz;
751
752 g_classrefs.push_back(TClassRef(scope_name.c_str()));
753
754 return (TCppScope_t)sz;
755}
756
757bool Cppyy::IsTemplate(const std::string& template_name)
758{
759 return (bool)gInterpreter->CheckClassTemplate(template_name.c_str());
760}
761
762namespace {
763 class AutoCastRTTI {
764 public:
765 virtual ~AutoCastRTTI() {}
766 };
767}
768
770{
771 TClassRef& cr = type_from_handle(klass);
772 if (!cr.GetClass() || !obj) return klass;
773
774 if (!(cr->ClassProperty() & kClassHasVirtual))
775 return klass; // not polymorphic: no RTTI info available
776
777// TODO: ios class casting (ostream, streambuf, etc.) fails with a crash in GetActualClass()
778// below on Mac ARM (it's likely that the found actual class was replaced, maybe because
779// there are duplicates from pcm/pch?); filter them out for now as it's usually unnecessary
780// anyway to autocast these
781 std::string clName = cr->GetName();
782 if (clName.find("std::", 0, 5) == 0 && clName.find("stream") != std::string::npos)
783 return klass;
784
785#ifdef _WIN64
786// Cling does not provide a consistent ImageBase address for calculating relative addresses
787// as used in Windows 64b RTTI. So, check for our own RTTI extension instead. If that fails,
788// see whether the unmangled raw_name is available (e.g. if this is an MSVC compiled rather
789// than JITed class) and pass on if it is.
790 volatile const char* raw = nullptr; // to prevent too aggressive reordering
791 try {
792 // this will filter those objects that do not have RTTI to begin with (throws)
793 AutoCastRTTI* pcst = (AutoCastRTTI*)obj;
794 raw = typeid(*pcst).raw_name();
795
796 // check the signature id (0 == absolute, 1 == relative, 2 == ours)
797 void* vfptr = *(void**)((intptr_t)obj);
798 void* meta = (void*)((intptr_t)*((void**)((intptr_t)vfptr-sizeof(void*))));
799 if (*(intptr_t*)meta == 2) {
800 // access the extra data item which is an absolute pointer to the RTTI
801 void* ptdescr = (void*)((intptr_t)meta + 4*sizeof(unsigned long)+sizeof(void*));
802 if (ptdescr && *(void**)ptdescr) {
803 auto rtti = *(std::type_info**)ptdescr;
804 raw = rtti->raw_name();
805 if (raw && raw[0] != '\0') // likely unnecessary
806 return (TCppType_t)GetScope(rtti->name());
807 }
808
809 return klass; // do not fall through if no RTTI info available
810 }
811
812 // if the raw name is the empty string (no guarantees that this is so as truly, the
813 // address is corrupt, but it is common to be empty), then there is no accessible RTTI
814 // and getting the unmangled name will crash ...
815 if (!raw)
816 return klass;
817 } catch (std::bad_typeid) {
818 return klass; // can't risk passing to ROOT/meta as it may do RTTI
819 }
820#endif
821
822 TClass* clActual = cr->GetActualClass((void*)obj);
823 // The additional check using TClass::GetClassInfo is to prevent returning classes of which the Interpreter has no info (see https://github.com/root-project/root/pull/16177)
824 if (clActual && clActual != cr.GetClass() && clActual->GetClassInfo()) {
825 auto itt = g_name2classrefidx.find(clActual->GetName());
826 if (itt != g_name2classrefidx.end())
827 return (TCppType_t)itt->second;
828 return (TCppType_t)GetScope(clActual->GetName());
829 }
830
831 return klass;
832}
833
835{
836 TClassRef& cr = type_from_handle(klass);
837 if (cr.GetClass() && cr->GetClassInfo())
838 return (size_t)gInterpreter->ClassInfo_Size(cr->GetClassInfo());
839 return (size_t)0;
840}
841
842size_t Cppyy::SizeOf(const std::string& type_name)
843{
844 TDataType* dt = gROOT->GetType(type_name.c_str());
845 if (dt) return dt->Size();
846 return SizeOf(GetScope(type_name));
847}
848
849bool Cppyy::IsBuiltin(const std::string& type_name)
850{
851 if (g_builtins.find(type_name) != g_builtins.end())
852 return true;
853
854 const std::string& tclean = TClassEdit::CleanType(type_name.c_str(), 1);
855 if (g_builtins.find(tclean) != g_builtins.end())
856 return true;
857
858 if (strstr(tclean.c_str(), "std::complex"))
859 return true;
860
861 return false;
862}
863
864bool Cppyy::IsComplete(const std::string& type_name)
865{
866// verify whether the dictionary of this class is fully available
867 bool b = false;
868
869 int oldEIL = gErrorIgnoreLevel;
870 gErrorIgnoreLevel = 3000;
871 TClass* klass = TClass::GetClass(type_name.c_str());
872 if (klass && klass->GetClassInfo()) // works for normal case w/ dict
873 b = gInterpreter->ClassInfo_IsLoaded(klass->GetClassInfo());
874 else { // special case for forward declared classes
875 ClassInfo_t* ci = gInterpreter->ClassInfo_Factory(type_name.c_str());
876 if (ci) {
877 b = gInterpreter->ClassInfo_IsLoaded(ci);
878 gInterpreter->ClassInfo_Delete(ci); // we own the fresh class info
879 }
880 }
881 gErrorIgnoreLevel = oldEIL;
882 return b;
883}
884
885// memory management ---------------------------------------------------------
887{
889 return (TCppObject_t)::operator new(gInterpreter->ClassInfo_Size(cr->GetClassInfo()));
890}
891
893{
894 ::operator delete(instance);
895}
896
898{
900 if (arena)
901 return (TCppObject_t)cr->New(arena, TClass::kRealNew);
902 return (TCppObject_t)cr->New(TClass::kRealNew);
903}
904
905static std::map<Cppyy::TCppType_t, bool> sHasOperatorDelete;
907{
910 cr->Destructor((void*)instance);
911 else {
912 ROOT::DelFunc_t fdel = cr->GetDelete();
913 if (fdel) fdel((void*)instance);
914 else {
915 auto ib = sHasOperatorDelete.find(type);
916 if (ib == sHasOperatorDelete.end()) {
917 TFunction *f = (TFunction *)cr->GetMethodAllAny("operator delete");
918 sHasOperatorDelete[type] = (bool)(f && (f->Property() & kIsPublic));
919 ib = sHasOperatorDelete.find(type);
920 }
921 ib->second ? cr->Destructor((void*)instance) : ::operator delete((void*)instance);
922 }
923 }
924}
925
926
927// method/function dispatching -----------------------------------------------
929{
930// TODO: method should be a callfunc, so that no mapping would be needed.
931 CallWrapper* wrap = (CallWrapper*)method;
932
933 CallFunc_t* callf = gInterpreter->CallFunc_Factory();
934 MethodInfo_t* meth = gInterpreter->MethodInfo_Factory(wrap->fDecl);
935 gInterpreter->CallFunc_SetFunc(callf, meth);
936 gInterpreter->MethodInfo_Delete(meth);
937
938 if (!(callf && gInterpreter->CallFunc_IsValid(callf))) {
939 // TODO: propagate this error to caller w/o use of Python C-API
940 /*
941 PyErr_Format(PyExc_RuntimeError, "could not resolve %s::%s(%s)",
942 const_cast<TClassRef&>(klass).GetClassName(),
943 wrap.fName, callString.c_str()); */
944 std::cerr << "TODO: report unresolved function error to Python\n";
945 if (callf) gInterpreter->CallFunc_Delete(callf);
947 }
948
949// generate the wrapper and JIT it; ignore wrapper generation errors (will simply
950// result in a nullptr that is reported upstream if necessary; often, however,
951// there is a different overload available that will do)
952 auto oldErrLvl = gErrorIgnoreLevel;
954 wrap->fFaceptr = gInterpreter->CallFunc_IFacePtr(callf);
955 gErrorIgnoreLevel = oldErrLvl;
956
957 gInterpreter->CallFunc_Delete(callf); // does not touch IFacePtr
958 return wrap->fFaceptr;
959}
960
961static inline
962bool copy_args(Parameter* args, size_t nargs, void** vargs)
963{
964 bool runRelease = false;
965 for (size_t i = 0; i < nargs; ++i) {
966 switch (args[i].fTypeCode) {
967 case 'X': /* (void*)type& with free */
968 runRelease = true;
969 case 'V': /* (void*)type& */
970 vargs[i] = args[i].fValue.fVoidp;
971 break;
972 case 'r': /* const type& */
973 vargs[i] = args[i].fRef;
974 break;
975 default: /* all other types in union */
976 vargs[i] = (void*)&args[i].fValue.fVoidp;
977 break;
978 }
979 }
980 return runRelease;
981}
982
983static inline
984void release_args(Parameter* args, size_t nargs)
985{
986 for (size_t i = 0; i < nargs; ++i) {
987 if (args[i].fTypeCode == 'X')
988 free(args[i].fValue.fVoidp);
989 }
990}
991
992static inline bool WrapperCall(Cppyy::TCppMethod_t method, size_t nargs, void* args_, void* self, void* result)
993{
994 Parameter* args = (Parameter*)args_;
995 //bool is_direct = nargs & DIRECT_CALL;
996 nargs = CALL_NARGS(nargs);
997
998 CallWrapper* wrap = (CallWrapper*)method;
999 const TInterpreter::CallFuncIFacePtr_t& faceptr = wrap->fFaceptr.fGeneric ? wrap->fFaceptr : GetCallFunc(method);
1000 if (!faceptr.fGeneric)
1001 return false; // happens with compilation error
1002
1004 bool runRelease = false;
1005 if (nargs <= SMALL_ARGS_N) {
1006 void* smallbuf[SMALL_ARGS_N];
1007 if (nargs) runRelease = copy_args(args, nargs, smallbuf);
1008 faceptr.fGeneric(self, (int)nargs, smallbuf, result);
1009 } else {
1010 std::vector<void*> buf(nargs);
1011 runRelease = copy_args(args, nargs, buf.data());
1012 faceptr.fGeneric(self, (int)nargs, buf.data(), result);
1013 }
1014 if (runRelease) release_args(args, nargs);
1015 return true;
1016 }
1017
1019 bool runRelease = false;
1020 if (nargs <= SMALL_ARGS_N) {
1021 void* smallbuf[SMALL_ARGS_N];
1022 if (nargs) runRelease = copy_args(args, nargs, (void**)smallbuf);
1023 faceptr.fCtor((void**)smallbuf, result, (unsigned long)nargs);
1024 } else {
1025 std::vector<void*> buf(nargs);
1026 runRelease = copy_args(args, nargs, buf.data());
1027 faceptr.fCtor(buf.data(), result, (unsigned long)nargs);
1028 }
1029 if (runRelease) release_args(args, nargs);
1030 return true;
1031 }
1032
1034 std::cerr << " DESTRUCTOR NOT IMPLEMENTED YET! " << std::endl;
1035 return false;
1036 }
1037
1038 return false;
1039}
1040
1041template<typename T>
1042static inline
1043T CallT(Cppyy::TCppMethod_t method, Cppyy::TCppObject_t self, size_t nargs, void* args)
1044{
1045 T t{};
1046 if (WrapperCall(method, nargs, args, (void*)self, &t))
1047 return t;
1048 return (T)-1;
1049}
1050
1051#define CPPYY_IMP_CALL(typecode, rtype) \
1052rtype Cppyy::Call##typecode(TCppMethod_t method, TCppObject_t self, size_t nargs, void* args)\
1053{ \
1054 return CallT<rtype>(method, self, nargs, args); \
1055}
1056
1057void Cppyy::CallV(TCppMethod_t method, TCppObject_t self, size_t nargs, void* args)
1058{
1059 if (!WrapperCall(method, nargs, args, (void*)self, nullptr))
1060 return /* TODO ... report error */;
1061}
1062
1063CPPYY_IMP_CALL(B, unsigned char)
1072
1073void* Cppyy::CallR(TCppMethod_t method, TCppObject_t self, size_t nargs, void* args)
1074{
1075 void* r = nullptr;
1076 if (WrapperCall(method, nargs, args, (void*)self, &r))
1077 return r;
1078 return nullptr;
1079}
1080
1082 TCppMethod_t method, TCppObject_t self, size_t nargs, void* args, size_t* length)
1083{
1084 char* cstr = nullptr;
1085 TClassRef cr("std::string");
1086 std::string* cppresult = (std::string*)malloc(sizeof(std::string));
1087 if (WrapperCall(method, nargs, args, self, (void*)cppresult)) {
1088 cstr = cppstring_to_cstring(*cppresult);
1089 *length = cppresult->size();
1090 cppresult->std::string::~basic_string();
1091 } else
1092 *length = 0;
1093 free((void*)cppresult);
1094 return cstr;
1095}
1096
1098 TCppMethod_t method, TCppType_t /* klass */, size_t nargs, void* args)
1099{
1100 void* obj = nullptr;
1101 if (WrapperCall(method, nargs, args, nullptr, &obj))
1102 return (TCppObject_t)obj;
1103 return (TCppObject_t)0;
1104}
1105
1107{
1109 cr->Destructor((void*)self, true);
1110}
1111
1113 TCppObject_t self, size_t nargs, void* args, TCppType_t result_type)
1114{
1115 TClassRef& cr = type_from_handle(result_type);
1116 void* obj = ::operator new(gInterpreter->ClassInfo_Size(cr->GetClassInfo()));
1117 if (WrapperCall(method, nargs, args, self, obj))
1118 return (TCppObject_t)obj;
1119 ::operator delete(obj);
1120 return (TCppObject_t)0;
1121}
1122
1124{
1125 if (check_enabled && !gEnableFastPath) return (TCppFuncAddr_t)nullptr;
1126 TFunction* f = m2f(method);
1127
1128 TCppFuncAddr_t pf = (TCppFuncAddr_t)gInterpreter->FindSym(f->GetMangledName());
1129 if (pf) return pf;
1130
1131 int ierr = 0;
1132 const char* fn = TClassEdit::DemangleName(f->GetMangledName(), ierr);
1133 if (ierr || !fn)
1134 return pf;
1135
1136 // TODO: the following attempts are all brittle and leak transactions, but
1137 // each properly exposes the symbol so subsequent lookups will succeed
1138 if (strstr(f->GetName(), "<")) {
1139 // force explicit instantiation and try again
1140 std::ostringstream sig;
1141 sig << "template " << fn << ";";
1142 gInterpreter->ProcessLine(sig.str().c_str());
1143 } else {
1144 std::ostringstream sig;
1145
1146 std::string sfn = fn;
1147 std::string::size_type pos = sfn.find('(');
1148 if (pos != std::string::npos) sfn = sfn.substr(0, pos);
1149
1150 // start cast
1151 sig << '(' << f->GetReturnTypeName() << " (";
1152
1153 // add scope for methods
1154 pos = sfn.rfind(':');
1155 if (pos != std::string::npos) {
1156 std::string scope_name = sfn.substr(0, pos-1);
1157 TCppScope_t scope = GetScope(scope_name);
1158 if (scope && !IsNamespace(scope))
1159 sig << scope_name << "::";
1160 }
1161
1162 // finalize cast
1163 sig << "*)" << GetMethodSignature(method, false)
1164 << ((f->Property() & kIsConstMethod) ? " const" : "")
1165 << ')';
1166
1167 // load address
1168 sig << '&' << sfn;
1169 gInterpreter->Calc(sig.str().c_str());
1170 }
1171
1172 return (TCppFuncAddr_t)gInterpreter->FindSym(f->GetMangledName());
1173}
1174
1175
1176// handling of function argument buffer --------------------------------------
1178{
1179 return new Parameter[nargs];
1180}
1181
1183{
1184 delete [] (Parameter*)args;
1185}
1186
1188{
1189 return sizeof(Parameter);
1190}
1191
1193{
1194 return offsetof(Parameter, fTypeCode);
1195}
1196
1197
1198// scope reflection information ----------------------------------------------
1200{
1201// Test if this scope represents a namespace.
1202 if (scope == GLOBAL_HANDLE)
1203 return true;
1204 TClassRef& cr = type_from_handle(scope);
1205 if (cr.GetClass())
1206 return cr->Property() & kIsNamespace;
1207 return false;
1208}
1209
1211{
1212// Test if this type may not be instantiated.
1213 TClassRef& cr = type_from_handle(klass);
1214 if (cr.GetClass())
1215 return cr->Property() & kIsAbstract;
1216 return false;
1217}
1218
1219bool Cppyy::IsEnum(const std::string& type_name)
1220{
1221 if (type_name.empty()) return false;
1222
1223 if (type_name.rfind("enum ", 0) == 0)
1224 return true; // by definition (C-style)
1225
1226 std::string tn_short = TClassEdit::ShortType(type_name.c_str(), 1);
1227 if (tn_short.empty()) return false;
1228 return gInterpreter->ClassInfo_IsEnum(tn_short.c_str());
1229}
1230
1232{
1233// Test if this type is a "plain old data" type
1235 if (cr.GetClass())
1236 return cr->ClassProperty() & kClassIsAggregate;
1237 return false;
1238}
1239
1241{
1242// Test if this type has a default constructor or is a "plain old data" type
1244 if (cr.GetClass())
1245 return cr->HasDefaultConstructor() || (cr->ClassProperty() & kClassIsAggregate);
1246 return true;
1247}
1248
1249// helpers for stripping scope names
1250static
1251std::string outer_with_template(const std::string& name)
1252{
1253// Cut down to the outer-most scope from <name>, taking proper care of templates.
1254 int tpl_open = 0;
1255 for (std::string::size_type pos = 0; pos < name.size(); ++pos) {
1256 std::string::value_type c = name[pos];
1257
1258 // count '<' and '>' to be able to skip template contents
1259 if (c == '<')
1260 ++tpl_open;
1261 else if (c == '>')
1262 --tpl_open;
1263
1264 // collect name up to "::"
1265 else if (tpl_open == 0 && \
1266 c == ':' && pos+1 < name.size() && name[pos+1] == ':') {
1267 // found the extend of the scope ... done
1268 return name.substr(0, pos-1);
1269 }
1270 }
1271
1272// whole name is apparently a single scope
1273 return name;
1274}
1275
1276static
1277std::string outer_no_template(const std::string& name)
1278{
1279// Cut down to the outer-most scope from <name>, drop templates
1280 std::string::size_type first_scope = name.find(':');
1281 if (first_scope == std::string::npos)
1282 return name.substr(0, name.find('<'));
1283 std::string::size_type first_templ = name.find('<');
1284 if (first_templ == std::string::npos)
1285 return name.substr(0, first_scope);
1286 return name.substr(0, std::min(first_templ, first_scope));
1287}
1288
1289#define FILL_COLL(type, filter) { \
1290 TIter itr{coll}; \
1291 type* obj = nullptr; \
1292 while ((obj = (type*)itr.Next())) { \
1293 const char* nm = obj->GetName(); \
1294 if (nm && nm[0] != '_' && !(obj->Property() & (filter))) { \
1295 if (gInitialNames.find(nm) == gInitialNames.end()) \
1296 cppnames.insert(nm); \
1297 }}}
1298
1299static inline
1300void cond_add(Cppyy::TCppScope_t scope, const std::string& ns_scope,
1301 std::set<std::string>& cppnames, const char* name, bool nofilter = false)
1302{
1303 if (!name || strstr(name, ".h") != 0)
1304 return;
1305
1306 if (scope == GLOBAL_HANDLE) {
1307 std::string to_add = outer_no_template(name);
1308 if ((nofilter || gInitialNames.find(to_add) == gInitialNames.end()) && !is_missclassified_stl(name))
1309 cppnames.insert(outer_no_template(name));
1310 } else if (scope == STD_HANDLE) {
1311 if (strncmp(name, "std::", 5) == 0) {
1312 name += 5;
1313#ifdef __APPLE__
1314 if (strncmp(name, "__1::", 5) == 0) name += 5;
1315#endif
1316 } else if (!is_missclassified_stl(name))
1317 return;
1318 cppnames.insert(outer_no_template(name));
1319 } else {
1320 if (strncmp(name, ns_scope.c_str(), ns_scope.size()) == 0)
1321 cppnames.insert(outer_with_template(name + ns_scope.size()));
1322 }
1323}
1324
1325void Cppyy::GetAllCppNames(TCppScope_t scope, std::set<std::string>& cppnames)
1326{
1327// Collect all known names of C++ entities under scope. This is useful for IDEs
1328// employing tab-completion, for example. Note that functions names need not be
1329// unique as they can be overloaded.
1330 TClassRef& cr = type_from_handle(scope);
1331 if (scope != GLOBAL_HANDLE && !(cr.GetClass() && cr->Property()))
1332 return;
1333
1334 std::string ns_scope = GetFinalName(scope);
1335 if (scope != GLOBAL_HANDLE) ns_scope += "::";
1336
1337// add existing values from read rootmap files if within this scope
1338 TCollection* coll = gInterpreter->GetMapfile()->GetTable();
1339 {
1340 TIter itr{coll};
1341 TEnvRec* ev = nullptr;
1342 while ((ev = (TEnvRec*)itr.Next())) {
1343 // TEnv contains rootmap entries and user-side rootmap files may be already
1344 // loaded on startup. Thus, filter on file name rather than load time.
1345 if (gRootSOs.find(ev->GetValue()) == gRootSOs.end())
1346 cond_add(scope, ns_scope, cppnames, ev->GetName(), true);
1347 }
1348 }
1349
1350// do we care about the class table or are the rootmap and list of types enough?
1351/*
1352 gClassTable->Init();
1353 const int N = gClassTable->Classes();
1354 for (int i = 0; i < N; ++i)
1355 cond_add(scope, ns_scope, cppnames, gClassTable->Next());
1356*/
1357
1358#if 0
1359// add interpreted classes (no load)
1360 {
1361 ClassInfo_t* ci = gInterpreter->ClassInfo_FactoryWithScope(
1362 false /* all */, scope == GLOBAL_HANDLE ? nullptr : cr->GetName());
1363 while (gInterpreter->ClassInfo_Next(ci)) {
1364 const char* className = gInterpreter->ClassInfo_FullName(ci);
1365 if (strstr(className, "(anonymous)") || strstr(className, "(unnamed)"))
1366 continue;
1367 cond_add(scope, ns_scope, cppnames, className);
1368 }
1369 gInterpreter->ClassInfo_Delete(ci);
1370 }
1371#endif
1372
1373// any other types (e.g. that may have come from parsing headers)
1374 coll = gROOT->GetListOfTypes();
1375 {
1376 TIter itr{coll};
1377 TDataType* dt = nullptr;
1378 while ((dt = (TDataType*)itr.Next())) {
1379 if (!(dt->Property() & kIsFundamental)) {
1380 cond_add(scope, ns_scope, cppnames, dt->GetName());
1381 }
1382 }
1383 }
1384
1385// add functions
1386 coll = (scope == GLOBAL_HANDLE) ?
1387 gROOT->GetListOfGlobalFunctions(true) : cr->GetListOfMethods(true);
1388 {
1389 TIter itr{coll};
1390 TFunction* obj = nullptr;
1391 while ((obj = (TFunction*)itr.Next())) {
1392 const char* nm = obj->GetName();
1393 // skip templated functions, adding only the un-instantiated ones
1394 if (nm && gInitialNames.find(nm) == gInitialNames.end())
1395 cppnames.insert(nm);
1396 }
1397 }
1398
1399// add uninstantiated templates
1400 coll = (scope == GLOBAL_HANDLE) ?
1401 gROOT->GetListOfFunctionTemplates() : cr->GetListOfFunctionTemplates(true);
1403
1404// add (global) data members
1405 if (scope == GLOBAL_HANDLE) {
1406 coll = gROOT->GetListOfGlobals();
1408 } else {
1409 coll = cr->GetListOfDataMembers();
1411 coll = cr->GetListOfUsingDataMembers();
1413 }
1414
1415// add enums values only for user classes/namespaces
1416 if (scope != GLOBAL_HANDLE && scope != STD_HANDLE) {
1417 coll = cr->GetListOfEnums();
1419 }
1420
1421#ifdef __APPLE__
1422// special case for Apple, add version namespace '__1' entries to std
1423 if (scope == STD_HANDLE)
1424 GetAllCppNames(GetScope("std::__1"), cppnames);
1425#endif
1426}
1427
1428
1429// class reflection information ----------------------------------------------
1430std::vector<Cppyy::TCppScope_t> Cppyy::GetUsingNamespaces(TCppScope_t scope)
1431{
1432 std::vector<Cppyy::TCppScope_t> res;
1433 if (!IsNamespace(scope))
1434 return res;
1435
1436#ifdef __APPLE__
1437 if (scope == STD_HANDLE) {
1438 res.push_back(GetScope("__1"));
1439 return res;
1440 }
1441#endif
1442
1443 TClassRef& cr = type_from_handle(scope);
1444 if (!cr.GetClass() || !cr->GetClassInfo())
1445 return res;
1446
1447 const std::vector<std::string>& v = gInterpreter->GetUsingNamespaces(cr->GetClassInfo());
1448 res.reserve(v.size());
1449 for (const auto& uid : v) {
1450 Cppyy::TCppScope_t uscope = GetScope(uid);
1451 if (uscope) res.push_back(uscope);
1452 }
1453
1454 return res;
1455}
1456
1457
1458// class reflection information ----------------------------------------------
1460{
1461 if (klass == GLOBAL_HANDLE)
1462 return "";
1463 TClassRef& cr = type_from_handle(klass);
1464 std::string clName = cr->GetName();
1465// TODO: why is this template splitting needed?
1466 std::string::size_type pos = clName.substr(0, clName.find('<')).rfind("::");
1467 if (pos != std::string::npos)
1468 return clName.substr(pos+2, std::string::npos);
1469 return clName;
1470}
1471
1473{
1474 if (klass == GLOBAL_HANDLE)
1475 return "";
1476 TClassRef& cr = type_from_handle(klass);
1477 if (cr.GetClass()) {
1478 std::string name = cr->GetName();
1480 return std::string("std::")+cr->GetName();
1481 return cr->GetName();
1482 }
1483 return "<unknown>";
1484}
1485
1487{
1488 TClassRef& cr = type_from_handle(klass);
1489 if (!cr.GetClass())
1490 return false;
1491
1492 TFunction* f = cr->GetMethod(("~"+GetFinalName(klass)).c_str(), "");
1493 if (f && (f->Property() & kIsVirtual))
1494 return true;
1495
1496 return false;
1497}
1498
1500{
1501 int is_complex = 1;
1502 size_t nbases = 0;
1503
1504 TClassRef& cr = type_from_handle(klass);
1505 if (cr.GetClass() && cr->GetListOfBases() != 0)
1506 nbases = GetNumBases(klass);
1507
1508 if (1 < nbases)
1509 is_complex = 1;
1510 else if (nbases == 0)
1511 is_complex = 0;
1512 else { // one base class only
1513 TBaseClass* base = (TBaseClass*)cr->GetListOfBases()->At(0);
1514 if (base->Property() & kIsVirtualBase)
1515 is_complex = 1; // TODO: verify; can be complex, need not be.
1516 else
1517 is_complex = HasComplexHierarchy(GetScope(base->GetName()));
1518 }
1519
1520 return is_complex;
1521}
1522
1524{
1525// Get the total number of base classes that this class has.
1526 TClassRef& cr = type_from_handle(klass);
1527 if (cr.GetClass() && cr->GetListOfBases() != 0)
1528 return (TCppIndex_t)cr->GetListOfBases()->GetSize();
1529 return (TCppIndex_t)0;
1530}
1531
1532////////////////////////////////////////////////////////////////////////////////
1533/// \fn Cppyy::TCppIndex_t GetLongestInheritancePath(TClass *klass)
1534/// \brief Retrieve number of base classes in the longest branch of the
1535/// inheritance tree of the input class.
1536/// \param[in] klass The class to start the retrieval process from.
1537///
1538/// This is a helper function for Cppyy::GetNumBasesLongestBranch.
1539/// Given an inheritance tree, the function assigns weight 1 to each class that
1540/// has at least one base. Starting from the input class, the function is
1541/// called recursively on all the bases. For each base the return value is one
1542/// (the weight of the base itself) plus the maximum value retrieved for their
1543/// bases in turn. For example, given the following inheritance tree:
1544///
1545/// ~~~{.cpp}
1546/// class A {}; class B: public A {};
1547/// class X {}; class Y: public X {}; class Z: public Y {};
1548/// class C: public B, Z {};
1549/// ~~~
1550///
1551/// calling this function on an instance of `C` will return 3, the steps
1552/// required to go from C to X.
1554{
1555
1556 auto directbases = klass->GetListOfBases();
1557 if (!directbases) {
1558 // This is a leaf with no bases
1559 return 0;
1560 }
1561 auto ndirectbases = directbases->GetSize();
1562 if (ndirectbases == 0) {
1563 // This is a leaf with no bases
1564 return 0;
1565 } else {
1566 // If there is at least one direct base
1567 std::vector<Cppyy::TCppIndex_t> nbases_branches;
1568 nbases_branches.reserve(ndirectbases);
1569
1570 // Traverse all direct bases of the current class and call the function
1571 // recursively
1572 for (auto baseclass : TRangeDynCast<TBaseClass>(directbases)) {
1573 if (!baseclass)
1574 continue;
1575 if (auto baseclass_tclass = baseclass->GetClassPointer()) {
1577 }
1578 }
1579
1580 // Get longest path among the direct bases of the current class
1581 auto longestbranch = std::max_element(std::begin(nbases_branches), std::end(nbases_branches));
1582
1583 // Add 1 to include the current class in the count
1584 return 1 + *longestbranch;
1585 }
1586}
1587
1588////////////////////////////////////////////////////////////////////////////////
1589/// \fn Cppyy::TCppIndex_t Cppyy::GetNumBasesLongest(TCppType_t klass)
1590/// \brief Retrieve number of base classes in the longest branch of the
1591/// inheritance tree.
1592/// \param[in] klass The class to start the retrieval process from.
1593///
1594/// The function converts the input class to a `TClass *` and calls
1595/// GetLongestInheritancePath.
1597{
1598
1599 const auto &cr = type_from_handle(klass);
1600
1601 if (auto klass_tclass = cr.GetClass()) {
1603 }
1604
1605 // In any other case, return zero
1606 return 0;
1607}
1608
1610{
1612 return ((TBaseClass*)cr->GetListOfBases()->At((int)ibase))->GetName();
1613}
1614
1616{
1617 if (derived == base)
1618 return true;
1621 if (derived_type.GetClass() && base_type.GetClass())
1622 return derived_type->GetBaseClass(base_type) != 0;
1623 return false;
1624}
1625
1627{
1629 const std::string& tn = cr->GetName();
1630 if (gSmartPtrTypes.find(tn.substr(0, tn.find("<"))) != gSmartPtrTypes.end())
1631 return true;
1632 return false;
1633}
1634
1636 const std::string& tname, TCppType_t* raw, TCppMethod_t* deref)
1637{
1638 const std::string& rn = ResolveName(tname);
1639 if (gSmartPtrTypes.find(rn.substr(0, rn.find("<"))) != gSmartPtrTypes.end()) {
1640 if (!raw && !deref) return true;
1641
1643 if (cr.GetClass()) {
1644 TFunction* func = cr->GetMethod("operator->", "");
1645 if (!func)
1646 func = cr->GetMethod("operator->", "");
1647 if (func) {
1648 if (deref) *deref = (TCppMethod_t)new_CallWrapper(func);
1649 if (raw) *raw = GetScope(TClassEdit::ShortType(
1650 func->GetReturnTypeNormalizedName().c_str(), 1));
1651 return (!deref || *deref) && (!raw || *raw);
1652 }
1653 }
1654 }
1655
1656 return false;
1657}
1658
1659void Cppyy::AddSmartPtrType(const std::string& type_name)
1660{
1662}
1663
1664void Cppyy::AddTypeReducer(const std::string& /*reducable*/, const std::string& /*reduced*/)
1665{
1666 // This function is deliberately left empty, because it is not used in
1667 // PyROOT, and synchronizing it with cppyy-backend upstream would require
1668 // patches to ROOT meta.
1669}
1670
1671
1672// type offsets --------------------------------------------------------------
1674 TCppObject_t address, int direction, bool rerror)
1675{
1676// calculate offsets between declared and actual type, up-cast: direction > 0; down-cast: direction < 0
1677 if (derived == base || !(base && derived))
1678 return (ptrdiff_t)0;
1679
1681 TClassRef& cb = type_from_handle(base);
1682
1683 if (!cd.GetClass() || !cb.GetClass())
1684 return (ptrdiff_t)0;
1685
1686 ptrdiff_t offset = -1;
1687 if (!(cd->GetClassInfo() && cb->GetClassInfo())) { // gInterpreter requirement
1688 // would like to warn, but can't quite determine error from intentional
1689 // hiding by developers, so only cover the case where we really should have
1690 // had a class info, but apparently don't:
1691 if (cd->IsLoaded()) {
1692 // warn to allow diagnostics
1693 std::ostringstream msg;
1694 msg << "failed offset calculation between " << cb->GetName() << " and " << cd->GetName();
1695 // TODO: propagate this warning to caller w/o use of Python C-API
1696 // PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(msg.str().c_str()));
1697 std::cerr << "Warning: " << msg.str() << '\n';
1698 }
1699
1700 // return -1 to signal caller NOT to apply offset
1701 return rerror ? (ptrdiff_t)offset : 0;
1702 }
1703
1704 offset = gInterpreter->ClassInfo_GetBaseOffset(
1705 cd->GetClassInfo(), cb->GetClassInfo(), (void*)address, direction > 0);
1706 if (offset == -1) // Cling error, treat silently
1707 return rerror ? (ptrdiff_t)offset : 0;
1708
1709 return (ptrdiff_t)(direction < 0 ? -offset : offset);
1710}
1711
1712
1713// method/function reflection information ------------------------------------
1715{
1717 return (TCppIndex_t)0; // enforce lazy
1718
1719 if (scope == GLOBAL_HANDLE)
1720 return gROOT->GetListOfGlobalFunctions(true)->GetSize();
1721
1723 if (cr.GetClass() && cr->GetListOfMethods(true)) {
1724 Cppyy::TCppIndex_t nMethods = (TCppIndex_t)cr->GetListOfMethods(false)->GetSize();
1725 if (nMethods == (TCppIndex_t)0) {
1726 std::string clName = GetScopedFinalName(scope);
1727 if (clName.find('<') != std::string::npos) {
1728 // chicken-and-egg problem: TClass does not know about methods until
1729 // instantiation, so force it
1730 std::ostringstream stmt;
1731 stmt << "template class " << clName << ";";
1732 gInterpreter->Declare(stmt.str().c_str()/*, silent = true*/);
1733
1734 // now reload the methods
1735 return (TCppIndex_t)cr->GetListOfMethods(true)->GetSize();
1736 }
1737 }
1738 return nMethods;
1739 }
1740
1741 return (TCppIndex_t)0; // unknown class?
1742}
1743
1744std::vector<Cppyy::TCppIndex_t> Cppyy::GetMethodIndicesFromName(
1745 TCppScope_t scope, const std::string& name)
1746{
1747 std::vector<TCppIndex_t> indices;
1749 if (cr.GetClass()) {
1750 gInterpreter->UpdateListOfMethods(cr.GetClass());
1751 int imeth = 0;
1752 TFunction* func = nullptr;
1753 TIter next(cr->GetListOfMethods());
1754 while ((func = (TFunction*)next())) {
1755 if (match_name(name, func->GetName())) {
1756 // C++ functions should be public to allow access; C functions have no access
1757 // specifier and should always be accepted
1758 auto prop = func->Property();
1759 if ((prop & kIsPublic) || !(prop & (kIsPrivate | kIsProtected | kIsPublic)))
1760 indices.push_back((TCppIndex_t)imeth);
1761 }
1762 ++imeth;
1763 }
1764 } else if (scope == GLOBAL_HANDLE) {
1765 TCollection* funcs = gROOT->GetListOfGlobalFunctions(true);
1766
1767 // tickle deserialization
1768 if (!funcs->FindObject(name.c_str()))
1769 return indices;
1770
1771 TFunction* func = nullptr;
1772 TIter ifunc(funcs);
1773 while ((func = (TFunction*)ifunc.Next())) {
1774 if (match_name(name, func->GetName()))
1775 indices.push_back((TCppIndex_t)new_CallWrapper(func));
1776 }
1777 }
1778
1779 return indices;
1780}
1781
1783{
1785 if (cr.GetClass()) {
1786 TFunction* f = (TFunction*)cr->GetListOfMethods(false)->At((int)idx);
1787 if (f) return (Cppyy::TCppMethod_t)new_CallWrapper(f);
1788 return (Cppyy::TCppMethod_t)nullptr;
1789 }
1790
1792 return (Cppyy::TCppMethod_t)idx;
1793}
1794
1796{
1797 if (method) {
1798 const std::string& name = ((CallWrapper*)method)->fName;
1799
1800 if (name.compare(0, 8, "operator") != 0)
1801 // strip template instantiation part, if any
1802 return name.substr(0, name.find('<'));
1803 return name;
1804 }
1805 return "<unknown>";
1806}
1807
1809{
1810 if (method) {
1811 std::string name = ((CallWrapper*)method)->fName;
1812 name.erase(std::remove(name.begin(), name.end(), ' '), name.end());
1813 return name;
1814 }
1815 return "<unknown>";
1816}
1817
1819{
1820 if (method)
1821 return m2f(method)->GetMangledName();
1822 return "<unknown>";
1823}
1824
1826{
1827 if (method) {
1828 TFunction* f = m2f(method);
1829 if (f->ExtraProperty() & kIsConstructor)
1830 return "constructor";
1831 std::string restype = f->GetReturnTypeName();
1832 // TODO: this is ugly; GetReturnTypeName() keeps typedefs, but may miss scopes
1833 // for some reason; GetReturnTypeNormalizedName() has been modified to return
1834 // the canonical type to guarantee correct namespaces. Sometimes typedefs look
1835 // better, sometimes not, sometimes it's debatable (e.g. vector<int>::size_type).
1836 // So, for correctness sake, GetReturnTypeNormalizedName() is used, except for a
1837 // special case of uint8_t/int8_t that must propagate as their typedefs.
1838 if (restype.find("int8_t") != std::string::npos)
1839 return restype;
1840 restype = f->GetReturnTypeNormalizedName();
1841 if (restype == "(lambda)") {
1842 std::ostringstream s;
1843 // TODO: what if there are parameters to the lambda?
1844 s << "__cling_internal::FT<decltype("
1845 << GetMethodFullName(method) << "(";
1846 for (Cppyy::TCppIndex_t i = 0; i < Cppyy::GetMethodNumArgs(method); ++i) {
1847 if (i != 0) s << ", ";
1848 s << Cppyy::GetMethodArgType(method, i) << "{}";
1849 }
1850 s << "))>::F";
1851 TClass* cl = TClass::GetClass(s.str().c_str());
1852 if (cl) return cl->GetName();
1853 // TODO: signal some type of error (or should that be upstream?
1854 }
1855 return restype;
1856 }
1857 return "<unknown>";
1858}
1859
1861{
1862 if (method)
1863 return m2f(method)->GetNargs();
1864 return 0;
1865}
1866
1868{
1869 if (method) {
1870 TFunction* f = m2f(method);
1871 return (TCppIndex_t)(f->GetNargs() - f->GetNargsOpt());
1872 }
1873 return (TCppIndex_t)0;
1874}
1875
1877{
1878 if (method) {
1879 TFunction* f = m2f(method);
1880 TMethodArg* arg = (TMethodArg*)f->GetListOfMethodArgs()->At((int)iarg);
1881 return arg->GetName();
1882 }
1883 return "<unknown>";
1884}
1885
1887{
1888 if (method) {
1889 TFunction* f = m2f(method);
1890 TMethodArg* arg = (TMethodArg*)f->GetListOfMethodArgs()->At((int)iarg);
1891 std::string ft = arg->GetFullTypeName();
1892 if (ft.rfind("enum ", 0) != std::string::npos) { // special case to preserve 'enum' tag
1893 std::string arg_type = arg->GetTypeNormalizedName();
1894 return arg_type.insert(arg_type.rfind("const ", 0) == std::string::npos ? 0 : 6, "enum ");
1895 } else if (g_builtins.find(ft) != g_builtins.end() || ft.find("int8_t") != std::string::npos)
1896 return ft; // do not resolve int8_t and uint8_t typedefs
1897
1898 return arg->GetTypeNormalizedName();
1899 }
1900 return "<unknown>";
1901}
1902
1904{
1905 if (method) {
1906 TFunction* f = m2f(method);
1907 TMethodArg* arg = (TMethodArg *)f->GetListOfMethodArgs()->At((int)iarg);
1908 void *argqtp = gInterpreter->TypeInfo_QualTypePtr(arg->GetTypeInfo());
1909
1910 TypeInfo_t *reqti = gInterpreter->TypeInfo_Factory(req_type.c_str());
1911 void *reqqtp = gInterpreter->TypeInfo_QualTypePtr(reqti);
1912
1913 // This scoring is not based on any particular rules
1914 if (gInterpreter->IsSameType(argqtp, reqqtp))
1915 return 0; // Best match
1916 else if ((gInterpreter->IsSignedIntegerType(argqtp) && gInterpreter->IsSignedIntegerType(reqqtp)) ||
1917 (gInterpreter->IsUnsignedIntegerType(argqtp) && gInterpreter->IsUnsignedIntegerType(reqqtp)) ||
1918 (gInterpreter->IsFloatingType(argqtp) && gInterpreter->IsFloatingType(reqqtp)))
1919 return 1;
1920 else if ((gInterpreter->IsSignedIntegerType(argqtp) && gInterpreter->IsUnsignedIntegerType(reqqtp)) ||
1921 (gInterpreter->IsFloatingType(argqtp) && gInterpreter->IsUnsignedIntegerType(reqqtp)))
1922 return 2;
1923 else if ((gInterpreter->IsIntegerType(argqtp) && gInterpreter->IsIntegerType(reqqtp)))
1924 return 3;
1925 else if ((gInterpreter->IsVoidPointerType(argqtp) && gInterpreter->IsPointerType(reqqtp)))
1926 return 4;
1927 else
1928 return 10; // Penalize heavily for no possible match
1929 }
1930 return INT_MAX; // Method is not valid
1931}
1932
1934{
1935 if (method) {
1936 TFunction* f = m2f(method);
1937 TMethodArg* arg = (TMethodArg*)f->GetListOfMethodArgs()->At((int)iarg);
1938 const char* def = arg->GetDefault();
1939 if (def)
1940 return def;
1941 }
1942
1943 return "";
1944}
1945
1947{
1948 TFunction* f = m2f(method);
1949 if (f) {
1950 std::ostringstream sig;
1951 sig << "(";
1952 int nArgs = f->GetNargs();
1953 if (maxargs != (TCppIndex_t)-1) nArgs = std::min(nArgs, (int)maxargs);
1954 for (int iarg = 0; iarg < nArgs; ++iarg) {
1955 TMethodArg* arg = (TMethodArg*)f->GetListOfMethodArgs()->At(iarg);
1956 sig << arg->GetFullTypeName();
1957 if (show_formalargs) {
1958 const char* argname = arg->GetName();
1959 if (argname && argname[0] != '\0') sig << " " << argname;
1960 const char* defvalue = arg->GetDefault();
1961 if (defvalue && defvalue[0] != '\0') sig << " = " << defvalue;
1962 }
1963 if (iarg != nArgs-1) sig << (show_formalargs ? ", " : ",");
1964 }
1965 sig << ")";
1966 return sig.str();
1967 }
1968 return "<unknown>";
1969}
1970
1972{
1973 std::string scName = GetScopedFinalName(scope);
1974 TFunction* f = m2f(method);
1975 if (f) {
1976 std::ostringstream sig;
1977 sig << f->GetReturnTypeName() << " "
1978 << scName << "::" << f->GetName();
1980 return sig.str();
1981 }
1982 return "<unknown>";
1983}
1984
1986{
1987 if (method) {
1988 TFunction* f = m2f(method);
1989 return f->Property() & kIsConstMethod;
1990 }
1991 return false;
1992}
1993
1995{
1997 return (TCppIndex_t)0; // enforce lazy
1998
1999 if (scope == GLOBAL_HANDLE) {
2000 TCollection* coll = gROOT->GetListOfFunctionTemplates();
2001 if (coll) return (TCppIndex_t)coll->GetSize();
2002 } else {
2004 if (cr.GetClass()) {
2005 TCollection* coll = cr->GetListOfFunctionTemplates(true);
2006 if (coll) return (TCppIndex_t)coll->GetSize();
2007 }
2008 }
2009
2010// failure ...
2011 return (TCppIndex_t)0;
2012}
2013
2015{
2017 return ((THashList*)gROOT->GetListOfFunctionTemplates())->At((int)imeth)->GetName();
2018 else {
2020 if (cr.GetClass())
2021 return cr->GetListOfFunctionTemplates(false)->At((int)imeth)->GetName();
2022 }
2023
2024// failure ...
2025 assert(!"should not be called unless GetNumTemplatedMethods() succeeded");
2026 return "";
2027}
2028
2030{
2032 return false;
2033
2035 if (cr.GetClass()) {
2036 TFunctionTemplate* f = (TFunctionTemplate*)cr->GetListOfFunctionTemplates(false)->At((int)imeth);
2037 return f->ExtraProperty() & kIsConstructor;
2038 }
2039
2040 return false;
2041}
2042
2044{
2046 return (bool)gROOT->GetFunctionTemplate(name.c_str());
2047 else {
2049 if (cr.GetClass())
2050 return (bool)cr->GetFunctionTemplate(name.c_str());
2051 }
2052
2053// failure ...
2054 return false;
2055}
2056
2058{
2059 TFunctionTemplate* tf = nullptr;
2061 tf = gROOT->GetFunctionTemplate(name.c_str());
2062 else {
2064 if (cr.GetClass())
2065 tf = cr->GetFunctionTemplate(name.c_str());
2066 }
2067
2068 if (!tf) return false;
2069
2070 return (bool)(tf->Property() & kIsStatic);
2071}
2072
2074{
2076 if (cr.GetClass()) {
2077 TFunction* f = (TFunction*)cr->GetListOfMethods(false)->At((int)idx);
2078 if (f && strstr(f->GetName(), "<")) return true;
2079 return false;
2080 }
2081
2083 if (((CallWrapper*)idx)->fName.find('<') != std::string::npos) return true;
2084 return false;
2085}
2086
2087// helpers for Cppyy::GetMethodTemplate()
2088static std::map<TDictionary::DeclId_t, CallWrapper*> gMethodTemplates;
2089
2090static inline
2091void remove_space(std::string& n) {
2092 std::string::iterator pos = std::remove_if(n.begin(), n.end(), isspace);
2093 n.erase(pos, n.end());
2094}
2095
2096static inline
2097bool template_compare(std::string n1, std::string n2) {
2098 if (n1.back() == '>') n1 = n1.substr(0, n1.size()-1);
2101 return n2.compare(0, n1.size(), n1) == 0;
2102}
2103
2105 TCppScope_t scope, const std::string& name, const std::string& proto)
2106{
2107// There is currently no clean way of extracting a templated method out of ROOT/meta
2108// for a variety of reasons, none of them fundamental. The game played below is to
2109// first get any pre-existing functions already managed by ROOT/meta, but if that fails,
2110// to do an explicit lookup that ignores the prototype (i.e. the full name should be
2111// enough), and finally to ignore the template arguments part of the name as this fails
2112// in cling if there are default parameters.
2113 TFunction* func = nullptr; ClassInfo_t* cl = nullptr;
2115 func = gROOT->GetGlobalFunctionWithPrototype(name.c_str(), proto.c_str());
2116 if (func && name.back() == '>') {
2117 // make sure that all template parameters match (more are okay, e.g. defaults or
2118 // ones derived from the arguments or variadic templates)
2119 if (!template_compare(name, func->GetName()))
2120 func = nullptr; // happens if implicit conversion matches the overload
2121 }
2122 } else {
2124 if (cr.GetClass()) {
2125 func = cr->GetMethodWithPrototype(name.c_str(), proto.c_str());
2126 if (!func) {
2127 cl = cr->GetClassInfo();
2128 // try base classes to cover a common 'using' case (TODO: this is stupid and misses
2129 // out on base classes; fix that with improved access to Cling)
2131 for (TCppIndex_t i = 0; i < nbases; ++i) {
2133 if (base.GetClass()) {
2134 func = base->GetMethodWithPrototype(name.c_str(), proto.c_str());
2135 if (func) break;
2136 }
2137 }
2138 }
2139 }
2140 }
2141
2142 if (!func && name.back() == '>' && (cl || scope == (TCppScope_t)GLOBAL_HANDLE)) {
2143 // try again, ignoring proto in case full name is complete template
2144 auto declid = gInterpreter->GetFunction(cl, name.c_str());
2145 if (declid) {
2146 auto existing = gMethodTemplates.find(declid);
2147 if (existing == gMethodTemplates.end()) {
2148 auto cw = new_CallWrapper(declid, name);
2149 existing = gMethodTemplates.insert(std::make_pair(declid, cw)).first;
2150 }
2151 return (TCppMethod_t)existing->second;
2152 }
2153 }
2154
2155 if (func) {
2156 // make sure we didn't match a non-templated overload
2157 if (func->ExtraProperty() & kIsTemplateSpec)
2158 return (TCppMethod_t)new_CallWrapper(func);
2159
2160 // disregard this non-templated method as it will be considered when appropriate
2161 return (TCppMethod_t)nullptr;
2162 }
2163
2164// try again with template arguments removed from name, if applicable
2165 if (name.back() == '>') {
2166 auto pos = name.find('<');
2167 if (pos != std::string::npos) {
2169 if (cppmeth) {
2170 // allow if requested template names match up to the result
2171 const std::string& alt = GetMethodFullName(cppmeth);
2172 if (name.size() < alt.size() && alt.find('<') == pos) {
2174 return cppmeth;
2175 }
2176 }
2177 }
2178 }
2179
2180// failure ...
2181 return (TCppMethod_t)nullptr;
2182}
2183
2184static inline
2185std::string type_remap(const std::string& n1, const std::string& n2)
2186{
2187// Operator lookups of (C++ string, Python str) should succeed for the combos of
2188// string/str, wstring/str, string/unicode and wstring/unicode; since C++ does not have a
2189// operator+(std::string, std::wstring), we'll have to look up the same type and rely on
2190// the converters in CPyCppyy/_cppyy.
2191 if (n1 == "str" || n1 == "unicode") {
2192 if (n2 == "std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >")
2193 return n2; // match like for like
2194 return "std::string"; // probably best bet
2195 } else if (n1 == "float") {
2196 return "double"; // debatable, but probably intended
2197 } else if (n1 == "complex") {
2198 return "std::complex<double>";
2199 }
2200 return n1;
2201}
2202
2204 TCppType_t scope, const std::string& lc, const std::string& rc, const std::string& opname)
2205{
2206// Find a global operator function with a matching signature; prefer by-ref, but
2207// fall back on by-value if that fails.
2208 std::string lcname1 = TClassEdit::CleanType(lc.c_str());
2209 const std::string& rcname = rc.empty() ? rc : type_remap(TClassEdit::CleanType(rc.c_str()), lcname1);
2210 const std::string& lcname = type_remap(lcname1, rcname);
2211
2212 std::string proto = lcname + "&" + (rc.empty() ? rc : (", " + rcname + "&"));
2214 TFunction* func = gROOT->GetGlobalFunctionWithPrototype(opname.c_str(), proto.c_str());
2215 if (func) return (TCppIndex_t)new_CallWrapper(func);
2216 proto = lcname + (rc.empty() ? rc : (", " + rcname));
2217 func = gROOT->GetGlobalFunctionWithPrototype(opname.c_str(), proto.c_str());
2218 if (func) return (TCppIndex_t)new_CallWrapper(func);
2219 } else {
2221 if (cr.GetClass()) {
2222 TFunction* func = cr->GetMethodWithPrototype(opname.c_str(), proto.c_str());
2223 if (func) return (TCppIndex_t)cr->GetListOfMethods()->IndexOf(func);
2224 proto = lcname + (rc.empty() ? rc : (", " + rcname));
2225 func = cr->GetMethodWithPrototype(opname.c_str(), proto.c_str());
2226 if (func) return (TCppIndex_t)cr->GetListOfMethods()->IndexOf(func);
2227 }
2228 }
2229
2230// failure ...
2231 return (TCppIndex_t)-1;
2232}
2233
2234// method properties ---------------------------------------------------------
2235
2237{
2238 if (!method)
2239 return false;
2240 TFunction *f = m2f(method);
2241 return f->Property() & prop;
2242}
2243
2245{
2246 if (!method)
2247 return false;
2248 TFunction *f = m2f(method);
2249 return f->ExtraProperty() & prop;
2250}
2251
2256
2261
2266
2271
2276
2281
2282// data member reflection information ----------------------------------------
2284{
2286 return (TCppIndex_t)0; // enforce lazy
2287
2288 if (scope == GLOBAL_HANDLE)
2289 return gROOT->GetListOfGlobals(true)->GetSize();
2290
2292 if (cr.GetClass() && cr->GetListOfDataMembers())
2293 return cr->GetListOfDataMembers()->GetSize();
2294
2295 return (TCppIndex_t)0; // unknown class?
2296}
2297
2299{
2301 if (cr.GetClass()) {
2302 TDataMember* m = (TDataMember*)cr->GetListOfDataMembers()->At((int)idata);
2303 return m->GetName();
2304 }
2307 return gbl->GetName();
2308}
2309
2310static inline
2311int count_scopes(const std::string& tpname)
2312{
2313 int count = 0;
2314 std::string::size_type pos = tpname.find("::", 0);
2315 while (pos != std::string::npos) {
2316 count++;
2317 pos = tpname.find("::", pos+1);
2318 }
2319 return count;
2320}
2321
2323{
2324 if (scope == GLOBAL_HANDLE) {
2326 std::string fullType = gbl->GetFullTypeName();
2327
2328 if ((int)gbl->GetArrayDim()) {
2329 std::ostringstream s;
2330 for (int i = 0; i < (int)gbl->GetArrayDim(); ++i)
2331 s << '[' << gbl->GetMaxIndex(i) << ']';
2332 fullType.append(s.str());
2333 }
2334 return fullType;
2335 }
2336
2338 if (cr.GetClass()) {
2339 TDataMember* m = (TDataMember*)cr->GetListOfDataMembers()->At((int)idata);
2340 // TODO: fix this upstream ... Usually, we want m->GetFullTypeName(), because it
2341 // does not resolve typedefs, but it looses scopes for inner classes/structs, it
2342 // doesn't resolve constexpr (leaving unresolved names), leaves spurious "struct"
2343 // or "union" in the name, and can not handle anonymous unions. In that case
2344 // m->GetTrueTypeName() should be used. W/o clear criteria to determine all these
2345 // cases, the general rules are to prefer the true name if the full type does not
2346 // exist as a type for classes, and the most scoped name otherwise.
2347 const char* ft = m->GetFullTypeName(); std::string fullType = ft ? ft : "";
2348 const char* tn = m->GetTrueTypeName(); std::string trueName = tn ? tn : "";
2349 if (!trueName.empty() && fullType != trueName && !IsBuiltin(trueName)) {
2350 if ( (!TClass::GetClass(fullType.c_str()) && TClass::GetClass(trueName.c_str())) || \
2352 bool is_enum_tag = fullType.rfind("enum ", 0) != std::string::npos;
2354 if (is_enum_tag)
2355 fullType.insert(fullType.rfind("const ", 0) == std::string::npos ? 0 : 6, "enum ");
2356 }
2357 }
2358
2359 if ((int)m->GetArrayDim()) {
2360 std::ostringstream s;
2361 for (int i = 0; i < (int)m->GetArrayDim(); ++i)
2362 s << '[' << m->GetMaxIndex(i) << ']';
2363 fullType.append(s.str());
2364 }
2365
2366#if 0
2367 // this is the only place where anonymous structs are uniquely identified, so setup
2368 // a class if needed, such that subsequent GetScope() and GetScopedFinalName() calls
2369 // return the uniquely named class
2370 auto declid = m->GetTagDeclId(); //GetDeclId();
2371 if (declid && (m->Property() & (kIsClass | kIsStruct | kIsUnion)) &&\
2372 (fullType.find("(anonymous)") != std::string::npos || fullType.find("(unnamed)") != std::string::npos)) {
2373
2374 // use the (fixed) decl id address to guarantee a unique name, even when there
2375 // are multiple anonymous structs in the parent scope
2376 std::ostringstream fulls;
2377 fulls << fullType << "@" << (void*)declid;
2378 fullType = fulls.str();
2379
2381 ClassInfo_t* ci = gInterpreter->ClassInfo_Factory(declid);
2382 TClass* cl = gInterpreter->GenerateTClass(ci, kTRUE /* silent */);
2383 gInterpreter->ClassInfo_Delete(ci);
2384 if (cl) cl->SetName(fullType.c_str());
2386 g_classrefs.emplace_back(cl);
2387 }
2388 }
2389#endif
2390 return fullType;
2391 }
2392
2393 return "<unknown>";
2394}
2395
2397{
2398 if (scope == GLOBAL_HANDLE) {
2400 if (!gbl->GetAddress() || gbl->GetAddress() == (void*)-1) {
2401 // CLING WORKAROUND: make sure variable is loaded
2402 intptr_t addr = (intptr_t)gInterpreter->ProcessLine((std::string("&")+gbl->GetName()+";").c_str());
2403 if (gbl->GetAddress() && gbl->GetAddress() != (void*)-1)
2404 return (intptr_t)gbl->GetAddress(); // now loaded!
2405 return addr; // last resort ...
2406 }
2407 return (intptr_t)gbl->GetAddress();
2408 }
2409
2411 if (cr.GetClass()) {
2412 TDataMember* m = (TDataMember*)cr->GetListOfDataMembers()->At((int)idata);
2413 // CLING WORKAROUND: the following causes templates to be instantiated first within the proper
2414 // scope, making the lookup succeed and preventing spurious duplicate instantiations later. Also,
2415 // if the variable is not yet loaded, pull it in through gInterpreter.
2416 intptr_t offset = (intptr_t)-1;
2417 if (m->Property() & kIsStatic) {
2418 if (strchr(cr->GetName(), '<'))
2419 gInterpreter->ProcessLine(((std::string)cr->GetName()+"::"+m->GetName()+";").c_str());
2420 offset = (intptr_t)m->GetOffsetCint(); // yes, CINT (GetOffset() is both wrong
2421 // and caches that wrong result!
2422 if (offset == (intptr_t)-1)
2423 return (intptr_t)gInterpreter->ProcessLine((std::string("&")+cr->GetName()+"::"+m->GetName()+";").c_str());
2424 } else
2425 offset = (intptr_t)m->GetOffsetCint(); // yes, CINT, see above
2426 return offset;
2427 }
2428
2429 return (intptr_t)-1;
2430}
2431
2432static inline
2434{
2435 if (!gb) return (Cppyy::TCppIndex_t)-1;
2436
2437 auto pidx = g_globalidx.find(gb);
2438 if (pidx == g_globalidx.end()) {
2439 auto idx = g_globalvars.size();
2440 g_globalvars.push_back(gb);
2441 g_globalidx[gb] = idx;
2442 return (Cppyy::TCppIndex_t)idx;
2443 }
2444 return (Cppyy::TCppIndex_t)pidx->second;
2445}
2446
2448{
2449 if (scope == GLOBAL_HANDLE) {
2450 TGlobal* gb = (TGlobal*)gROOT->GetListOfGlobals(false /* load */)->FindObject(name.c_str());
2451 if (!gb) gb = (TGlobal*)gROOT->GetListOfGlobals(true /* load */)->FindObject(name.c_str());
2452 if (!gb) {
2453 // some enums are not loaded as they are not considered part of
2454 // the global scope, but of the enum scope; get them w/o checking
2455 TDictionary::DeclId_t did = gInterpreter->GetDataMember(nullptr, name.c_str());
2456 if (did) {
2457 DataMemberInfo_t* t = gInterpreter->DataMemberInfo_Factory(did, nullptr);
2458 ((TListOfDataMembers*)gROOT->GetListOfGlobals())->Get(t, true);
2459 gb = (TGlobal*)gROOT->GetListOfGlobals(false /* load */)->FindObject(name.c_str());
2460 }
2461 }
2462
2463 if (gb && strcmp(gb->GetFullTypeName(), "(lambda)") == 0) {
2464 // lambdas use a compiler internal closure type, so we wrap
2465 // them, then return the wrapper's type
2466 // TODO: this current leaks the std::function; also, if possible,
2467 // should instantiate through TClass rather then ProcessLine
2468 std::ostringstream s;
2469 s << "auto __cppyy_internal_wrap_" << name << " = "
2470 "new __cling_internal::FT<decltype(" << name << ")>::F"
2471 "{" << name << "};";
2472 gInterpreter->ProcessLine(s.str().c_str());
2473 TGlobal* wrap = (TGlobal*)gROOT->GetListOfGlobals(true)->FindObject(
2474 ("__cppyy_internal_wrap_"+name).c_str());
2475 if (wrap && wrap->GetAddress()) gb = wrap;
2476 }
2477
2478 return gb2idx(gb);
2479
2480 } else {
2482 if (cr.GetClass()) {
2483 TDataMember* dm =
2484 (TDataMember*)cr->GetListOfDataMembers()->FindObject(name.c_str());
2485 // TODO: turning this into an index is silly ...
2486 if (dm) return (TCppIndex_t)cr->GetListOfDataMembers()->IndexOf(dm);
2487 }
2488 }
2489
2490 return (TCppIndex_t)-1;
2491}
2492
2494{
2495 if (scope == GLOBAL_HANDLE) {
2496 TGlobal* gb = (TGlobal*)((THashList*)gROOT->GetListOfGlobals(false /* load */))->At((int)idata);
2497 return gb2idx(gb);
2498 }
2499
2500 return idata;
2501}
2502
2503
2504// data member properties ----------------------------------------------------
2506{
2507 if (scope == GLOBAL_HANDLE)
2508 return true;
2510 if (cr->Property() & kIsNamespace)
2511 return true;
2512 TDataMember* m = (TDataMember*)cr->GetListOfDataMembers()->At((int)idata);
2513 return m->Property() & kIsPublic;
2514}
2515
2517{
2518 if (scope == GLOBAL_HANDLE)
2519 return true;
2521 if (cr->Property() & kIsNamespace)
2522 return true;
2523 TDataMember* m = (TDataMember*)cr->GetListOfDataMembers()->At((int)idata);
2524 return m->Property() & kIsProtected;
2525}
2526
2528{
2529 if (scope == GLOBAL_HANDLE)
2530 return true;
2532 if (cr->Property() & kIsNamespace)
2533 return true;
2534 TDataMember* m = (TDataMember*)cr->GetListOfDataMembers()->At((int)idata);
2535 return m->Property() & kIsStatic;
2536}
2537
2539{
2540 Long_t property = 0;
2541 if (scope == GLOBAL_HANDLE) {
2543 property = gbl->Property();
2544 }
2546 if (cr.GetClass()) {
2547 TDataMember* m = (TDataMember*)cr->GetListOfDataMembers()->At((int)idata);
2548 property = m->Property();
2549 }
2550
2551// if the data type is const, but the data member is a pointer/array, the data member
2552// itself is not const; alternatively it is a pointer that is constant
2554}
2555
2557{
2558// TODO: currently, ROOT/meta does not properly distinguish between variables of enum
2559// type, and values of enums. The latter are supposed to be const. This code relies on
2560// odd features (bugs?) to figure out the difference, but this should really be fixed
2561// upstream and/or deserves a new API.
2562
2563 if (scope == GLOBAL_HANDLE) {
2565
2566 // make use of an oddity: enum global variables do not have their kIsStatic bit
2567 // set, whereas enum global values do
2568 return (gbl->Property() & kIsEnum) && (gbl->Property() & kIsStatic);
2569 }
2570
2572 if (cr.GetClass()) {
2573 TDataMember* m = (TDataMember*)cr->GetListOfDataMembers()->At((int)idata);
2574 std::string ti = m->GetTypeName();
2575
2576 // can't check anonymous enums by type name, so just accept them as enums
2577 if (ti.rfind("(anonymous)") != std::string::npos || ti.rfind("(unnamed)") != std::string::npos)
2578 return m->Property() & kIsEnum;
2579
2580 // since there seems to be no distinction between data of enum type and enum values,
2581 // check the list of constants for the type to see if there's a match
2582 if (ti.rfind(cr->GetName(), 0) != std::string::npos) {
2583 std::string::size_type s = strlen(cr->GetName())+2;
2584 if (s < ti.size()) {
2585 TEnum* ee = ((TListOfEnums*)cr->GetListOfEnums())->GetObject(ti.substr(s, std::string::npos).c_str());
2586 if (ee) return ee->GetConstant(m->GetName());
2587 }
2588 }
2589 }
2590
2591// this default return only means that the data will be writable, not that it will
2592// be unreadable or otherwise misrepresented
2593 return false;
2594}
2595
2597{
2598 if (scope == GLOBAL_HANDLE) {
2600 return gbl->GetMaxIndex(dimension);
2601 }
2603 if (cr.GetClass()) {
2604 TDataMember* m = (TDataMember*)cr->GetListOfDataMembers()->At((int)idata);
2605 return m->GetMaxIndex(dimension);
2606 }
2607 return -1;
2608}
2609
2610
2611// enum properties -----------------------------------------------------------
2613{
2614 if (scope == GLOBAL_HANDLE)
2615 return (TCppEnum_t)gROOT->GetListOfEnums(kTRUE)->FindObject(enum_name.c_str());
2616
2618 if (cr.GetClass())
2619 return (TCppEnum_t)cr->GetListOfEnums(kTRUE)->FindObject(enum_name.c_str());
2620
2621 return (TCppEnum_t)0;
2622}
2623
2625{
2626 return (TCppIndex_t)((TEnum*)etype)->GetConstants()->GetSize();
2627}
2628
2630{
2631 return ((TEnumConstant*)((TEnum*)etype)->GetConstants()->At((int)idata))->GetName();
2632}
2633
2635{
2636 TEnumConstant* ecst = (TEnumConstant*)((TEnum*)etype)->GetConstants()->At((int)idata);
2637 return (long long)ecst->GetValue();
2638}
2639
2640
#define b(i)
Definition RSha256.hxx:100
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
static Roo_reg_AGKInteg1D instance
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:59
long Long_t
Signed long integer 4 bytes (long). Size depends on architecture.
Definition RtypesCore.h:68
long double LongDouble_t
Long Double (not portable)
Definition RtypesCore.h:75
long long Long64_t
Portable signed long integer 8 bytes.
Definition RtypesCore.h:83
constexpr Bool_t kTRUE
Definition RtypesCore.h:107
@ kMAXSIGNALS
Definition Rtypes.h:60
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
EFunctionProperty
@ kIsDestructor
@ kIsTemplateSpec
@ kIsConstructor
@ kClassIsAggregate
@ kClassHasVirtual
@ kClassHasExplicitDtor
@ kClassHasImplicitDtor
EProperty
Definition TDictionary.h:64
@ kIsPublic
Definition TDictionary.h:75
@ kIsPointer
Definition TDictionary.h:78
@ 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
@ kIsConstPointer
Definition TDictionary.h:90
@ kIsFundamental
Definition TDictionary.h:70
@ kIsAbstract
Definition TDictionary.h:71
@ kIsArray
Definition TDictionary.h:79
@ 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
@ kIsNamespace
Definition TDictionary.h:95
@ kIsVirtualBase
Definition TDictionary.h:89
constexpr Int_t kFatal
Definition TError.h:50
Int_t gErrorIgnoreLevel
errors with level below this value will be ignored. Default is kUnset.
Definition TError.cxx:33
R__EXTERN TExceptionHandler * gExceptionHandler
Definition TException.h:79
R__EXTERN ExceptionContext_t * gException
Definition TException.h:69
R__EXTERN void Throw(int code)
If an exception context has been set (using the TRY and RETRY macros) jump back to where it was set.
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 r
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 prop
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 index
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 ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h req_type
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void funcs
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
char name[80]
Definition TGX11.cxx:110
#define gInterpreter
#define gROOT
Definition TROOT.h:411
R__EXTERN TSystem * gSystem
Definition TSystem.h:572
static struct Signalmap_t gSignalMap[kMAXSIGNALS]
const char * proto
Definition civetweb.c:18822
#define free
Definition civetweb.c:1578
#define malloc
Definition civetweb.c:1575
const_iterator begin() const
const_iterator end() const
Each class (see TClass) has a linked list of its base class(es).
Definition TBaseClass.h:33
Long_t Property() const override
Get property description word. For meaning of bits see EProperty.
TClassRef is used to implement a permanent reference to a TClass object.
Definition TClassRef.h:29
TClass * GetClass() const
Definition TClassRef.h:67
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
TList * GetListOfUsingDataMembers(Bool_t load=kTRUE)
Return list containing the TDataMembers of using declarations of a class.
Definition TClass.cxx:3813
void * New(ENewType defConstructor=kClassNew, Bool_t quiet=kFALSE) const
Return a pointer to a newly allocated object of this class.
Definition TClass.cxx:5017
TMethod * GetMethod(const char *method, const char *params, Bool_t objectIsConst=kFALSE)
Find the best method (if there is one) matching the parameters.
Definition TClass.cxx:4438
TMethod * GetMethodWithPrototype(const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch)
Find the method with a given prototype.
Definition TClass.cxx:4483
void Destructor(void *obj, Bool_t dtorOnly=kFALSE)
Explicitly call destructor for object.
Definition TClass.cxx:5439
TList * GetListOfFunctionTemplates(Bool_t load=kTRUE)
Return TListOfFunctionTemplates for a class.
Definition TClass.cxx:3825
TList * GetListOfEnums(Bool_t load=kTRUE)
Return a list containing the TEnums of a class.
Definition TClass.cxx:3713
TList * GetListOfMethods(Bool_t load=kTRUE)
Return list containing the TMethods of a class.
Definition TClass.cxx:3839
TList * GetListOfDataMembers(Bool_t load=kTRUE)
Return list containing the TDataMembers of a class.
Definition TClass.cxx:3797
@ kRealNew
Definition TClass.h:110
TList * GetListOfBases()
Return list containing the TBaseClass(es) of a class.
Definition TClass.cxx:3663
Bool_t IsLoaded() const
Return true if the shared library of this class is currently in the a process's memory.
Definition TClass.cxx:5954
ClassInfo_t * GetClassInfo() const
Definition TClass.h:445
Long_t ClassProperty() const
Return the C++ property of this class, eg.
Definition TClass.cxx:2401
Long_t Property() const override
Returns the properties of the TClass as a bit field stored as a Long_t value.
Definition TClass.cxx:6128
Bool_t HasDefaultConstructor(Bool_t testio=kFALSE) const
Return true if we have access to a constructor usable for I/O.
Definition TClass.cxx:7490
TMethod * GetMethodAllAny(const char *method)
Return pointer to method without looking at parameters.
Definition TClass.cxx:4411
ROOT::DelFunc_t GetDelete() const
Return the wrapper around delete ThisObject.
Definition TClass.cxx:7568
TClass * GetActualClass(const void *object) const
Return a pointer to the real class of the object.
Definition TClass.cxx:2612
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:2973
Collection abstract base class.
Definition TCollection.h:65
virtual Int_t GetSize() const
Return the capacity of the collection, i.e.
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
Int_t GetType() const
Definition TDataType.h:68
Long_t Property() const override
Get property description word. For meaning of bits see EProperty.
Int_t Size() const
Get size of basic typedef'ed type.
const void * DeclId_t
The TEnumConstant class implements the constants of the enum type.
The TEnum class implements the enum type.
Definition TEnum.h:33
Definition TEnv.h:86
const char * GetValue() const
Definition TEnv.h:110
const char * GetName() const override
Returns name of object.
Definition TEnv.h:109
Dictionary for function template This class describes one single function template.
Global functions class (global functions are obtained from CINT).
Definition TFunction.h:30
Long_t Property() const override
Get property description word. For meaning of bits see EProperty.
Long_t ExtraProperty() const
Get property description word. For meaning of bits see EProperty.
std::string GetReturnTypeNormalizedName() const
Get the normalized name of the return type.
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
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...
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition TList.cxx:354
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*".
TypeInfo_t * GetTypeInfo() const
Get the TypeInfo of the method argument.
const char * GetDefault() const
Get default value of method argument.
std::string GetTypeNormalizedName() const
Get the normalized name of the return type.
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition TNamed.cxx:149
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:457
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition TObject.cxx:421
static Bool_t Initialized()
Return kTRUE if the TROOT object has been initialized.
Definition TROOT.cxx:2913
virtual void Exit(int code, Bool_t mode=kTRUE)
Exit the application.
Definition TSystem.cxx:725
virtual void StackTrace()
Print a stack trace.
Definition TSystem.cxx:743
static void cond_add(Cppyy::TCppScope_t scope, const std::string &ns_scope, std::set< std::string > &cppnames, const char *name, bool nofilter=false)
static bool testMethodProperty(Cppyy::TCppMethod_t method, EProperty prop)
static Name2ClassRefIndex_t g_name2classrefidx
#define FILL_COLL(type, filter)
static void remove_space(std::string &n)
const int SMALL_ARGS_N
static std::string outer_with_template(const std::string &name)
static std::string outer_no_template(const std::string &name)
static std::string type_remap(const std::string &n1, const std::string &n2)
static std::map< Cppyy::TCppType_t, bool > sHasOperatorDelete
static std::set< std::string > gRootSOs
static bool template_compare(std::string n1, std::string n2)
static TClassRef & type_from_handle(Cppyy::TCppScope_t scope)
static bool copy_args(Parameter *args, size_t nargs, void **vargs)
static TInterpreter::CallFuncIFacePtr_t GetCallFunc(Cppyy::TCppMethod_t method)
CPyCppyy::Parameter Parameter
static bool is_missclassified_stl(const std::string &name)
std::map< std::string, ClassRefs_t::size_type > Name2ClassRefIndex_t
static const ClassRefs_t::size_type STD_HANDLE
static std::set< std::string > gSmartPtrTypes
static GlobalVars_t g_globalvars
static char * cppstring_to_cstring(const std::string &cppstr)
static void release_args(Parameter *args, size_t nargs)
static std::set< std::string > g_builtins
static std::vector< CallWrapper * > gWrapperHolder
static bool gEnableFastPath
static ClassRefs_t g_classrefs(1)
static bool WrapperCall(Cppyy::TCppMethod_t method, size_t nargs, void *args_, void *self, void *result)
static std::map< std::string, std::string > resolved_enum_types
static Cppyy::TCppIndex_t gb2idx(TGlobal *gb)
static size_t CALL_NARGS(size_t nargs)
static CallWrapper * new_CallWrapper(TFunction *f)
static std::set< std::string > gSTLNames
static const ClassRefs_t::size_type GLOBAL_HANDLE
static GlobalVarsIndices_t g_globalidx
static bool testMethodExtraProperty(Cppyy::TCppMethod_t method, EFunctionProperty prop)
static int count_scopes(const std::string &tpname)
std::vector< TGlobal * > GlobalVars_t
std::map< TGlobal *, GlobalVars_t::size_type > GlobalVarsIndices_t
std::vector< TClassRef > ClassRefs_t
static std::map< TDictionary::DeclId_t, CallWrapper * > gMethodTemplates
static bool match_name(const std::string &tname, const std::string fname)
static TFunction * m2f(Cppyy::TCppMethod_t method)
#define CPPYY_IMP_CALL(typecode, rtype)
static std::set< std::string > gInitialNames
static T CallT(Cppyy::TCppMethod_t method, Cppyy::TCppObject_t self, size_t nargs, void *args)
Cppyy::TCppIndex_t GetLongestInheritancePath(TClass *klass)
Retrieve number of base classes in the longest branch of the inheritance tree of the input class.
const Int_t n
Definition legend1.C:16
#define I(x, y, z)
#define H(x, y, z)
size_t TCppIndex_t
Definition cpp_cppyy.h:40
RPY_EXPORTED TCppIndex_t GetNumTemplatedMethods(TCppScope_t scope, bool accept_namespace=false)
RPY_EXPORTED std::string GetMethodMangledName(TCppMethod_t)
RPY_EXPORTED TCppObject_t CallO(TCppMethod_t method, TCppObject_t self, size_t nargs, void *args, TCppType_t result_type)
RPY_EXPORTED TCppIndex_t CompareMethodArgType(TCppMethod_t, TCppIndex_t iarg, const std::string &req_type)
RPY_EXPORTED ptrdiff_t GetBaseOffset(TCppType_t derived, TCppType_t base, TCppObject_t address, int direction, bool rerror=false)
RPY_EXPORTED void DeallocateFunctionArgs(void *args)
RPY_EXPORTED bool IsEnumData(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED bool IsAbstract(TCppType_t type)
RPY_EXPORTED size_t SizeOf(TCppType_t klass)
RPY_EXPORTED TCppObject_t CallConstructor(TCppMethod_t method, TCppType_t type, size_t nargs, void *args)
intptr_t TCppMethod_t
Definition cpp_cppyy.h:38
RPY_EXPORTED void * AllocateFunctionArgs(size_t nargs)
RPY_EXPORTED bool IsDefaultConstructable(TCppType_t type)
RPY_EXPORTED bool IsTemplate(const std::string &template_name)
RPY_EXPORTED TCppIndex_t GetDatamemberIndexEnumerated(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED TCppIndex_t GetMethodReqArgs(TCppMethod_t)
RPY_EXPORTED bool IsEnum(const std::string &type_name)
RPY_EXPORTED std::vector< TCppIndex_t > GetMethodIndicesFromName(TCppScope_t scope, const std::string &name)
RPY_EXPORTED bool ExistsMethodTemplate(TCppScope_t scope, const std::string &name)
RPY_EXPORTED TCppIndex_t GetNumDatamembers(TCppScope_t scope, bool accept_namespace=false)
RPY_EXPORTED std::string ToString(TCppType_t klass, TCppObject_t obj)
RPY_EXPORTED std::string GetMethodName(TCppMethod_t)
RPY_EXPORTED bool IsConstData(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED void AddSmartPtrType(const std::string &)
RPY_EXPORTED bool Compile(const std::string &code, bool silent=false)
RPY_EXPORTED void CallDestructor(TCppType_t type, TCppObject_t self)
RPY_EXPORTED TCppScope_t gGlobalScope
Definition cpp_cppyy.h:69
RPY_EXPORTED bool IsProtectedData(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED std::string GetMethodSignature(TCppMethod_t, bool show_formalargs, TCppIndex_t maxargs=(TCppIndex_t) -1)
RPY_EXPORTED int GetDimensionSize(TCppScope_t scope, TCppIndex_t idata, int dimension)
RPY_EXPORTED bool IsSubtype(TCppType_t derived, TCppType_t base)
RPY_EXPORTED TCppMethod_t GetMethodTemplate(TCppScope_t scope, const std::string &name, const std::string &proto)
void * TCppObject_t
Definition cpp_cppyy.h:37
RPY_EXPORTED bool IsConstructor(TCppMethod_t method)
RPY_EXPORTED TCppIndex_t GetNumMethods(TCppScope_t scope, bool accept_namespace=false)
RPY_EXPORTED TCppObject_t Construct(TCppType_t type, void *arena=nullptr)
RPY_EXPORTED bool GetSmartPtrInfo(const std::string &, TCppType_t *raw, TCppMethod_t *deref)
RPY_EXPORTED std::string GetMethodArgName(TCppMethod_t, TCppIndex_t iarg)
RPY_EXPORTED size_t GetFunctionArgTypeoffset()
RPY_EXPORTED TCppObject_t Allocate(TCppType_t type)
RPY_EXPORTED void Destruct(TCppType_t type, TCppObject_t instance)
RPY_EXPORTED std::string ResolveName(const std::string &cppitem_name)
TCppScope_t TCppType_t
Definition cpp_cppyy.h:35
RPY_EXPORTED void AddTypeReducer(const std::string &reducable, const std::string &reduced)
RPY_EXPORTED std::string ResolveEnum(const std::string &enum_type)
RPY_EXPORTED long long GetEnumDataValue(TCppEnum_t, TCppIndex_t idata)
RPY_EXPORTED bool IsAggregate(TCppType_t type)
RPY_EXPORTED TCppIndex_t GetMethodNumArgs(TCppMethod_t)
RPY_EXPORTED TCppType_t GetActualClass(TCppType_t klass, TCppObject_t obj)
RPY_EXPORTED std::string GetBaseName(TCppType_t type, TCppIndex_t ibase)
RPY_EXPORTED bool IsNamespace(TCppScope_t scope)
void * TCppEnum_t
Definition cpp_cppyy.h:36
RPY_EXPORTED std::string GetScopedFinalName(TCppType_t type)
RPY_EXPORTED void Deallocate(TCppType_t type, TCppObject_t instance)
RPY_EXPORTED bool IsPublicData(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED std::string GetMethodArgType(TCppMethod_t, TCppIndex_t iarg)
RPY_EXPORTED std::string GetEnumDataName(TCppEnum_t, TCppIndex_t idata)
RPY_EXPORTED void GetAllCppNames(TCppScope_t scope, std::set< std::string > &cppnames)
RPY_EXPORTED bool IsComplete(const std::string &type_name)
RPY_EXPORTED bool IsBuiltin(const std::string &type_name)
RPY_EXPORTED bool IsStaticMethod(TCppMethod_t method)
RPY_EXPORTED TCppIndex_t GetDatamemberIndex(TCppScope_t scope, const std::string &name)
RPY_EXPORTED void CallV(TCppMethod_t method, TCppObject_t self, size_t nargs, void *args)
RPY_EXPORTED bool IsStaticData(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED std::string GetDatamemberType(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED TCppMethod_t GetMethod(TCppScope_t scope, TCppIndex_t imeth)
RPY_EXPORTED bool IsStaticTemplate(TCppScope_t scope, const std::string &name)
RPY_EXPORTED bool IsDestructor(TCppMethod_t method)
RPY_EXPORTED bool IsSmartPtr(TCppType_t type)
RPY_EXPORTED std::string GetTemplatedMethodName(TCppScope_t scope, TCppIndex_t imeth)
RPY_EXPORTED size_t GetFunctionArgSizeof()
RPY_EXPORTED TCppScope_t GetScope(const std::string &scope_name)
RPY_EXPORTED bool HasVirtualDestructor(TCppType_t type)
RPY_EXPORTED bool IsConstMethod(TCppMethod_t)
RPY_EXPORTED bool HasComplexHierarchy(TCppType_t type)
RPY_EXPORTED std::vector< TCppScope_t > GetUsingNamespaces(TCppScope_t)
size_t TCppScope_t
Definition cpp_cppyy.h:34
RPY_EXPORTED bool IsTemplatedConstructor(TCppScope_t scope, TCppIndex_t imeth)
RPY_EXPORTED TCppIndex_t GetGlobalOperator(TCppType_t scope, const std::string &lc, const std::string &rc, const std::string &op)
RPY_EXPORTED TCppFuncAddr_t GetFunctionAddress(TCppMethod_t method, bool check_enabled=true)
RPY_EXPORTED TCppIndex_t GetNumEnumData(TCppEnum_t)
RPY_EXPORTED TCppIndex_t GetNumBases(TCppType_t type)
RPY_EXPORTED TCppIndex_t GetNumBasesLongestBranch(TCppType_t type)
RPY_EXPORTED std::string GetMethodPrototype(TCppScope_t scope, TCppMethod_t, bool show_formalargs)
RPY_EXPORTED std::string GetMethodResultType(TCppMethod_t)
RPY_EXPORTED std::string GetFinalName(TCppType_t type)
RPY_EXPORTED char * CallS(TCppMethod_t method, TCppObject_t self, size_t nargs, void *args, size_t *length)
RPY_EXPORTED bool IsExplicit(TCppMethod_t method)
RPY_EXPORTED std::string GetMethodArgDefault(TCppMethod_t, TCppIndex_t iarg)
RPY_EXPORTED bool IsMethodTemplate(TCppScope_t scope, TCppIndex_t imeth)
RPY_EXPORTED std::string GetDatamemberName(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED bool IsPublicMethod(TCppMethod_t method)
RPY_EXPORTED intptr_t GetDatamemberOffset(TCppScope_t scope, TCppIndex_t idata)
void * TCppFuncAddr_t
Definition cpp_cppyy.h:41
RPY_EXPORTED std::string GetMethodFullName(TCppMethod_t)
RPY_EXPORTED bool IsProtectedMethod(TCppMethod_t method)
RPY_EXPORTED TCppEnum_t GetEnum(TCppScope_t scope, const std::string &enum_name)
void(* DelFunc_t)(void *)
Definition Rtypes.h:117
std::string ResolveTypedef(const char *tname, bool resolveAll=false)
std::string CleanType(const char *typeDesc, int mode=0, const char **tail=nullptr)
Cleanup type description, redundant blanks removed and redundant tail ignored return *tail = pointer ...
std::string ShortType(const char *typeDesc, int mode)
Return the absolute type of typeDesc.
char * DemangleName(const char *mangled_name, int &errorCode)
Definition TClassEdit.h:255
union CPyCppyy::Parameter::Value fValue
const char * fSigName
TMarker m
Definition textangle.C:8