forked from wlav/cppyy-backend
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathclingwrapper.cxx
More file actions
2240 lines (1959 loc) · 74.4 KB
/
Copy pathclingwrapper.cxx
File metadata and controls
2240 lines (1959 loc) · 74.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef _WIN32
#ifndef _CRT_SECURE_NO_WARNINGS
// silence warnings about getenv, strncpy, etc.
#define _CRT_SECURE_NO_WARNINGS
#endif
#endif
#include "precommondefs.h" // This defines several system feature macros and should be included before any system header.
// Bindings
#include "cpp_cppyy.h"
#include "callcontext.h"
#ifndef _WIN32
#include <dlfcn.h>
#endif
// Standard
#include <cassert>
#include <algorithm> // for std::count, std::remove
#include <stdexcept>
#include <map>
#include <new>
#include <regex>
#include <set>
#include <sstream>
#include <csignal>
#include <cstdlib> // for getenv
#include <cstring>
#include <typeinfo>
#include <iostream>
#include <vector>
#include <mutex>
// data for life time management ---------------------------------------------
// typedef std::vector<TClassRef> ClassRefs_t;
// static ClassRefs_t g_classrefs(1);
// static const ClassRefs_t::size_type GLOBAL_HANDLE = 1;
// static const ClassRefs_t::size_type STD_HANDLE = GLOBAL_HANDLE + 1;
// typedef std::map<std::string, ClassRefs_t::size_type> Name2ClassRefIndex_t;
// static Name2ClassRefIndex_t g_name2classrefidx;
// namespace {
// static inline
// Cppyy::TCppType_t find_memoized(const std::string& name)
// {
// auto icr = g_name2classrefidx.find(name);
// if (icr != g_name2classrefidx.end())
// return (Cppyy::TCppType_t)icr->second;
// return (Cppyy::TCppType_t)0;
// }
//
// } // namespace
//
// static inline
// CallWrapper* new_CallWrapper(CppyyLegacy::TFunction* f)
// {
// CallWrapper* wrap = new CallWrapper(f);
// gWrapperHolder.push_back(wrap);
// return wrap;
// }
//
// typedef std::vector<TGlobal*> GlobalVars_t;
// typedef std::map<TGlobal*, GlobalVars_t::size_type> GlobalVarsIndices_t;
// static GlobalVars_t g_globalvars;
// static GlobalVarsIndices_t g_globalidx;
std::recursive_mutex InterOpMutex;
// builtin types
static std::set<std::string> g_builtins =
{"bool", "char", "signed char", "unsigned char", "wchar_t", "short", "unsigned short",
"int", "unsigned int", "long", "unsigned long", "long long", "unsigned long long",
"float", "double", "long double", "void"};
// to filter out ROOT names
static std::set<std::string> gInitialNames;
static std::set<std::string> gRootSOs;
// configuration
static bool gEnableFastPath = true;
// global initialization -----------------------------------------------------
namespace {
const int kMAXSIGNALS = 16;
// names copied from TUnixSystem
#ifdef WIN32
const int SIGBUS = 0; // simple placeholders for ones that don't exist
const int SIGSYS = 0;
const int SIGPIPE = 0;
const int SIGQUIT = 0;
const int SIGWINCH = 0;
const int SIGALRM = 0;
const int SIGCHLD = 0;
const int SIGURG = 0;
const int SIGUSR1 = 0;
const int SIGUSR2 = 0;
#endif
static struct Signalmap_t {
int fCode;
const char *fSigName;
} gSignalMap[kMAXSIGNALS] = { // the order of the signals should be identical
{ SIGBUS, "bus error" }, // to the one in TSysEvtHandler.h
{ SIGSEGV, "segmentation violation" },
{ SIGSYS, "bad argument to system call" },
{ SIGPIPE, "write on a pipe with no one to read it" },
{ SIGILL, "illegal instruction" },
{ SIGABRT, "abort" },
{ SIGQUIT, "quit" },
{ SIGINT, "interrupt" },
{ SIGWINCH, "window size change" },
{ SIGALRM, "alarm clock" },
{ SIGCHLD, "death of a child" },
{ SIGURG, "urgent data arrived on an I/O channel" },
{ SIGFPE, "floating point exception" },
{ SIGTERM, "termination signal" },
{ SIGUSR1, "user-defined signal 1" },
{ SIGUSR2, "user-defined signal 2" }
};
// static void inline do_trace(int sig) {
// std::cerr << " *** Break *** " << (sig < kMAXSIGNALS ? gSignalMap[sig].fSigName : "") << std::endl;
// gSystem->StackTrace();
// }
// class TExceptionHandlerImp : public TExceptionHandler {
// public:
// virtual void HandleException(Int_t sig) {
// if (TROOT::Initialized()) {
// if (gException) {
// gInterpreter->RewindDictionary();
// gInterpreter->ClearFileBusy();
// }
//
// if (!getenv("CPPYY_CRASH_QUIET"))
// do_trace(sig);
//
// // jump back, if catch point set
// Throw(sig);
// }
//
// do_trace(sig);
// gSystem->Exit(128 + sig);
// }
// };
static inline
void push_tokens_from_string(char *s, std::vector <const char*> &tokens) {
char *token = strtok(s, " ");
while (token) {
tokens.push_back(token);
token = strtok(NULL, " ");
}
}
static inline
bool is_integral(std::string& s)
{
if (s == "false") { s = "0"; return true; }
else if (s == "true") { s = "1"; return true; }
return !s.empty() && std::find_if(s.begin(),
s.end(), [](unsigned char c) { return !std::isdigit(c); }) == s.end();
}
class ApplicationStarter {
Cpp::TInterp_t Interp;
public:
ApplicationStarter() {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
if (!Cpp::LoadDispatchAPI(
CPPINTEROP_DIR
"/lib/libclangCppInterOp" CMAKE_SHARED_LIBRARY_SUFFIX)) {
std::cerr << "[cppyy-backend] Failed to load CppInterOp" << std::endl;
return;
}
// Check if somebody already loaded CppInterOp and created an
// interpreter for us.
if (auto * existingInterp = Cpp::GetInterpreter()) {
Interp = existingInterp;
}
else {
#ifdef __arm64__
#ifdef __APPLE__
// If on apple silicon don't use -march=native
std::vector<const char *> InterpArgs({"-std=c++17"});
#else
std::vector<const char *> InterpArgs(
{"-std=c++17", "-march=native"});
#endif
#else
std::vector <const char *> InterpArgs({"-std=c++17", "-march=native"});
#endif
char *InterpArgString = getenv("CPPINTEROP_EXTRA_INTERPRETER_ARGS");
if (InterpArgString)
push_tokens_from_string(InterpArgString, InterpArgs);
#ifdef __arm64__
#ifdef __APPLE__
// If on apple silicon don't use -march=native
Interp = Cpp::CreateInterpreter({"-std=c++17"}, /*GpuArgs=*/{});
#else
Interp = Cpp::CreateInterpreter({"-std=c++17", "-march=native"},
/*GpuArgs=*/{});
#endif
#else
Interp = Cpp::CreateInterpreter({"-std=c++17", "-march=native"},
/*GpuArgs=*/{});
#endif
}
// fill out the builtins
std::set<std::string> bi{g_builtins};
for (const auto& name : bi) {
for (const char* a : {"*", "&", "*&", "[]", "*[]"})
g_builtins.insert(name+a);
}
// disable fast path if requested
if (getenv("CPPYY_DISABLE_FASTPATH")) gEnableFastPath = false;
// set opt level (default to 2 if not given; Cling itself defaults to 0)
int optLevel = 2;
if (getenv("CPPYY_OPT_LEVEL")) optLevel = atoi(getenv("CPPYY_OPT_LEVEL"));
if (optLevel != 0) {
std::ostringstream s;
s << "#pragma cling optimize " << optLevel;
Cpp::Process(s.str().c_str());
}
// This would give us something like:
// /home/vvassilev/workspace/builds/scratch/cling-build/builddir/lib/clang/13.0.0
const char * ResourceDir = Cpp::GetResourceDir();
std::string ClingSrc = std::string(ResourceDir) + "/../../../../cling-src";
std::string ClingBuildDir = std::string(ResourceDir) + "/../../../";
Cpp::AddIncludePath((ClingSrc + "/tools/cling/include").c_str());
Cpp::AddIncludePath((ClingSrc + "/include").c_str());
Cpp::AddIncludePath((ClingBuildDir + "/include").c_str());
Cpp::AddIncludePath((std::string(CPPINTEROP_DIR) + "/include").c_str());
Cpp::LoadLibrary("libstdc++", /* lookup= */ true);
// load frequently used headers
const char* code =
"#include <algorithm>\n"
"#include <numeric>\n"
"#include <complex>\n"
"#include <iostream>\n"
"#include <string.h>\n" // for strcpy
"#include <string>\n"
// "#include <DllImport.h>\n" // defines R__EXTERN
"#include <vector>\n"
"#include <utility>\n"
"#include <memory>\n"
"#include <functional>\n" // for the dispatcher code to use
// std::function
"#include <map>\n" // FIXME: Replace with modules
"#include <sstream>\n" // FIXME: Replace with modules
"#include <array>\n" // FIXME: Replace with modules
"#include <list>\n" // FIXME: Replace with modules
"#include <deque>\n" // FIXME: Replace with modules
"#include <tuple>\n" // FIXME: Replace with modules
"#include <set>\n" // FIXME: Replace with modules
"#include <chrono>\n" // FIXME: Replace with modules
"#include <cmath>\n" // FIXME: Replace with modules
"#if __has_include(<optional>)\n"
"#include <optional>\n"
"#endif\n"
"#include <CppInterOp/Dispatch.h>\n";
Cpp::Process(code);
// create helpers for comparing thingies
Cpp::Declare("namespace __cppyy_internal { template<class C1, class C2>"
" bool is_equal(const C1& c1, const C2& c2) { return "
"(bool)(c1 == c2); } }",
/*silent=*/false);
Cpp::Declare("namespace __cppyy_internal { template<class C1, class C2>"
" bool is_not_equal(const C1& c1, const C2& c2) { return "
"(bool)(c1 != c2); } }",
/*silent=*/false);
// Define gCling when we run with clang-repl.
// FIXME: We should get rid of all the uses of gCling as this seems to
// break encapsulation.
std::stringstream InterpPtrSS;
InterpPtrSS << "#ifndef __CLING__\n"
<< "namespace cling { namespace runtime {\n"
<< "void* gCling=(void*)" << static_cast<void*>(Interp)
<< ";\n }}\n"
<< "#endif \n";
Cpp::Process(InterpPtrSS.str().c_str());
// helper for multiple inheritance
Cpp::Declare("namespace __cppyy_internal { struct Sep; }",
/*silent=*/false);
// std::string libInterOp = I->getDynamicLibraryManager()->lookupLibrary("libcling");
// void *interopDL = dlopen(libInterOp.c_str(), RTLD_LAZY);
// if (!interopDL) {
// std::cerr << "libInterop could not be opened!\n";
// exit(1);
// }
// start off with a reasonable size placeholder for wrappers
// gWrapperHolder.reserve(1024);
// create an exception handler to process signals
// gExceptionHandler = new TExceptionHandlerImp{};
}
~ApplicationStarter() {
//Cpp::DeleteInterpreter(Interp);
// for (auto wrap : gWrapperHolder)
// delete wrap;
// delete gExceptionHandler; gExceptionHandler = nullptr;
}
} _applicationStarter;
} // unnamed namespace
// // local helpers -------------------------------------------------------------
// static inline
// TClassRef& type_from_handle(Cppyy::TCppScope_t scope)
// {
// assert((ClassRefs_t::size_type)scope < g_classrefs.size());
// return g_classrefs[(ClassRefs_t::size_type)scope];
// }
//
// static inline
// TFunction* m2f(Cppyy::TCppMethod_t method) {
// CallWrapper *wrap = (CallWrapper *)method;
//
// if (!wrap->fTF) {
// MethodInfo_t* mi = gInterpreter->MethodInfo_Factory(wrap->fDecl);
// wrap->fTF = new TFunction(mi);
// }
// return (TFunction *) wrap->fTF;
// }
//
static inline
char* cppstring_to_cstring(const std::string& cppstr)
{
char* cstr = (char*)malloc(cppstr.size()+1);
memcpy(cstr, cppstr.c_str(), cppstr.size()+1);
return cstr;
}
//
// static inline
// bool match_name(const std::string& tname, const std::string fname)
// {
// // either match exactly, or match the name as template
// if (fname.rfind(tname, 0) == 0) {
// if ((tname.size() == fname.size()) ||
// (tname.size() < fname.size() && fname[tname.size()] == '<'))
// return true;
// }
// return false;
// }
//
//
// // direct interpreter access -------------------------------------------------
// Returns false on failure and true on success
bool Cppyy::Compile(const std::string& code, bool silent)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
// Declare returns an enum which equals 0 on success
return !Cpp::Declare(code.c_str(), silent);
}
std::string Cppyy::ToString(TCppType_t klass, TCppObject_t obj)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
if (klass && obj && !Cpp::IsNamespace((TCppScope_t)klass))
return Cpp::ObjToString(Cpp::GetQualifiedCompleteName(klass).c_str(),
(void*)obj);
return "";
}
// // name to opaque C++ scope representation -----------------------------------
std::string Cppyy::ResolveName(const std::string& name) {
if (!name.empty()) {
if (Cppyy::TCppType_t type =
Cppyy::GetType(name, /*enable_slow_lookup=*/true))
return Cppyy::GetTypeAsString(Cppyy::ResolveType(type));
return name;
}
return "";
}
// // Fully resolve the given name to the final type name.
//
// // try memoized type cache, in case seen before
// TCppType_t klass = find_memoized(cppitem_name);
// if (klass) return GetScopedFinalName(klass);
//
// // remove global scope '::' if present
// std::string tclean = cppitem_name.compare(0, 2, "::") == 0 ?
// cppitem_name.substr(2, std::string::npos) : cppitem_name;
//
// // classes (most common)
// tclean = TClassEdit::CleanType(tclean.c_str());
// if (tclean.empty() [> unknown, eg. an operator <]) return cppitem_name;
//
// // reduce [N] to []
// if (tclean[tclean.size()-1] == ']')
// tclean = tclean.substr(0, tclean.rfind('[')) + "[]";
//
// // remove __restrict and __restrict__
// auto pos = tclean.rfind("__restrict");
// if (pos != std::string::npos)
// tclean = tclean.substr(0, pos);
//
// if (tclean.compare(0, 9, "std::byte") == 0)
// return tclean;
//
// // check data types list (accept only builtins as typedefs will
// // otherwise not be resolved)
// if (IsBuiltin(tclean)) return tclean;
//
// // special case for enums
// if (IsEnum(cppitem_name))
// return ResolveEnum(cppitem_name);
//
// // special case for clang's builtin __type_pack_element (which does not resolve)
// pos = cppitem_name.size() > 20 ? \
// cppitem_name.rfind("__type_pack_element", 5) : std::string::npos;
// if (pos != std::string::npos) {
// // shape is "[std::]__type_pack_element<index,type1,type2,...,typeN>cpd": extract
// // first the index, and from there the indexed type; finally, restore the
// // qualifiers
// const char* str = cppitem_name.c_str();
// char* endptr = nullptr;
// unsigned long index = strtoul(str+20+pos, &endptr, 0);
//
// std::string tmplvars{endptr};
// auto start = tmplvars.find(',') + 1;
// auto end = tmplvars.find(',', start);
// while (index != 0) {
// start = end+1;
// end = tmplvars.find(',', start);
// if (end == std::string::npos) end = tmplvars.rfind('>');
// --index;
// }
//
// std::string resolved = tmplvars.substr(start, end-start);
// auto cpd = tmplvars.rfind('>');
// if (cpd != std::string::npos && cpd+1 != tmplvars.size())
// return resolved + tmplvars.substr(cpd+1, std::string::npos);
// return resolved;
// }
//
// // typedefs etc. (and a couple of hacks around TClassEdit-isms, fixing of which
// // in ResolveTypedef itself is a TODO ...)
// tclean = TClassEdit::ResolveTypedef(tclean.c_str(), true);
// pos = 0;
// while ((pos = tclean.find("::::", pos)) != std::string::npos) {
// tclean.replace(pos, 4, "::");
// pos += 2;
// }
//
// if (tclean.compare(0, 6, "const ") != 0)
// return TClassEdit::ShortType(tclean.c_str(), 2);
// return "const " + TClassEdit::ShortType(tclean.c_str(), 2);
// }
Cppyy::TCppType_t Cppyy::ResolveEnumReferenceType(TCppType_t type) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
if (Cpp::GetValueKind(type) != Cpp::ValueKind::LValue)
return type;
TCppType_t nonReferenceType = Cpp::GetNonReferenceType(type);
if (Cpp::IsEnumType(nonReferenceType)) {
TCppType_t underlying_type = Cpp::GetIntegerTypeFromEnumType(nonReferenceType);
return Cpp::GetReferencedType(underlying_type, /*rvalue=*/false);
}
return type;
}
Cppyy::TCppType_t Cppyy::ResolveEnumPointerType(TCppType_t type) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
if (!Cpp::IsPointerType(type))
return type;
TCppType_t PointeeType = Cpp::GetPointeeType(type);
if (Cpp::IsEnumType(PointeeType)) {
TCppType_t underlying_type = Cpp::GetIntegerTypeFromEnumType(PointeeType);
return Cpp::GetPointerType(underlying_type);
}
return type;
}
Cppyy::TCppType_t int_like_type(Cppyy::TCppType_t type) {
Cppyy::TCppType_t check_int_typedefs = type;
if (Cpp::IsPointerType(check_int_typedefs))
check_int_typedefs = Cpp::GetPointeeType(check_int_typedefs);
if (Cpp::IsReferenceType(check_int_typedefs))
check_int_typedefs =
Cpp::GetReferencedType(check_int_typedefs, /*rvalue=*/false);
if (Cpp::GetTypeAsString(check_int_typedefs) == "int8_t" || Cpp::GetTypeAsString(check_int_typedefs) == "uint8_t")
return check_int_typedefs;
return nullptr;
}
Cppyy::TCppType_t Cppyy::ResolveType(TCppType_t type) {
if (!type) return type;
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
TCppType_t check_int_typedefs = int_like_type(type);
if (check_int_typedefs)
return type;
Cppyy::TCppType_t canonType = Cpp::GetCanonicalType(type);
if (Cpp::IsEnumType(canonType)) {
if (Cpp::GetTypeAsString(type) != "std::byte")
return Cpp::GetIntegerTypeFromEnumType(canonType);
}
if (Cpp::HasTypeQualifier(canonType, Cpp::QualKind::Restrict)) {
return Cpp::RemoveTypeQualifier(canonType, Cpp::QualKind::Restrict);
}
return canonType;
}
Cppyy::TCppType_t Cppyy::GetRealType(TCppType_t type) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
TCppType_t check_int_typedefs = int_like_type(type);
if (check_int_typedefs)
return check_int_typedefs;
return Cpp::GetUnderlyingType(type);
}
Cppyy::TCppType_t Cppyy::GetPointerType(TCppType_t type) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetPointerType(type);
}
Cppyy::TCppType_t Cppyy::GetReferencedType(TCppType_t type, bool rvalue) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetReferencedType(type, rvalue);
}
bool Cppyy::IsRValueReferenceType(TCppType_t type) {
return Cpp::GetValueKind(type) == Cpp::ValueKind::RValue;
}
bool Cppyy::IsLValueReferenceType(TCppType_t type) {
return Cpp::GetValueKind(type) == Cpp::ValueKind::LValue;
}
bool Cppyy::IsClassType(TCppType_t type) {
return Cpp::IsRecordType(type);
}
bool Cppyy::IsIntegerType(TCppType_t type, bool* is_signed /*= nullptr*/) {
if (is_signed) {
Cpp::Signedness sign;
bool res = Cpp::IsIntegerType(type, &sign);
*is_signed = (sign == Cpp::Signedness::kSigned);
return res;
}
return Cpp::IsIntegerType(type, nullptr);
}
bool Cppyy::IsPointerType(TCppType_t type) {
return Cpp::IsPointerType(type);
}
bool Cppyy::IsFunctionPointerType(TCppType_t type) {
return Cpp::IsFunctionPointerType(type);
}
std::string trim(const std::string& line)
{
if (line.empty()) return "";
const char* WhiteSpace = " \t\v\r\n";
std::size_t start = line.find_first_not_of(WhiteSpace);
std::size_t end = line.find_last_not_of(WhiteSpace);
return line.substr(start, end - start + 1);
}
// returns false of angular brackets dont match, else true
bool split_comma_saparated_types(const std::string& name,
std::vector<std::string>& types) {
std::string trimed_name = trim(name);
size_t start_pos = 0;
size_t end_pos = 0;
int matching_angular_brackets = 0;
while (end_pos < trimed_name.size()) {
switch (trimed_name[end_pos]) {
case ',': {
if (!matching_angular_brackets) {
if(end_pos > start_pos)
types.push_back(
trim(trimed_name.substr(start_pos, end_pos - start_pos)));
start_pos = end_pos + 1;
}
break;
}
case '<': {
matching_angular_brackets++;
break;
}
case '>': {
if (matching_angular_brackets == 1) {
types.push_back(
trim(trimed_name.substr(start_pos, end_pos - start_pos + 1)));
start_pos = end_pos + 1;
} else if (matching_angular_brackets < 1) {
types.clear();
return false;
}
matching_angular_brackets--;
break;
}
}
end_pos++;
}
if (start_pos < trimed_name.size())
types.push_back(trim(trimed_name.substr(start_pos, end_pos - start_pos)));
return true;
}
Cpp::TCppScope_t GetEnumFromCompleteName(const std::string &name) {
std::string delim = "::";
size_t start = 0;
size_t end = name.find(delim);
Cpp::TCppScope_t curr_scope = 0;
while (end != std::string::npos) {
curr_scope = Cpp::GetNamed(name.substr(start, end - start), curr_scope);
start = end + delim.length();
end = name.find(delim, start);
}
return Cpp::GetNamed(name.substr(start, end), curr_scope);
}
// returns true if no new type was added.
bool Cppyy::AppendTypesSlow(const std::string& name,
std::vector<Cpp::TemplateArgInfo>& types, Cppyy::TCppScope_t parent) {
// Add no new type if string is empty
if (name.empty())
return true;
auto replace_all = [](std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return;
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
};
std::string resolved_name = name;
replace_all(resolved_name, "std::initializer_list<", "std::vector<"); // replace initializer_list with vector
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
// We might have an entire expression such as int, double.
static unsigned long long struct_count = 0;
std::string code = "template<typename ...T> struct __Cppyy_AppendTypesSlow {};\n";
if (!struct_count)
Cpp::Declare(code.c_str(), /*silent=*/true); // initialize the trampoline
std::string var = "__Cppyy_s" + std::to_string(struct_count++);
if (!Cpp::Declare(("__Cppyy_AppendTypesSlow<" + resolved_name + "> " + var +";\n").c_str(), /*silent=*/true)) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
TCppType_t varN =
Cpp::GetVariableType(Cpp::GetNamed(var.c_str(), /*parent=*/nullptr));
TCppScope_t instance_class = Cpp::GetScopeFromType(varN);
size_t oldSize = types.size();
Cpp::GetClassTemplateInstantiationArgs(instance_class, types);
return oldSize == types.size();
}
// We split each individual types based on , and resolve it
// FIXME: see discussion on should we support template instantiation with string:
// https://github.com/compiler-research/cppyy-backend/pull/137#discussion_r2079357491
// We should consider eliminating the `split_comma_saparated_types` and `is_integral`
// string parsing.
std::vector<std::string> individual_types;
if (!split_comma_saparated_types(resolved_name, individual_types))
return true;
for (std::string& i : individual_types) {
// Try going via Cppyy::GetType first.
const char* integral_value = nullptr;
Cppyy::TCppType_t type = nullptr;
type = GetType(i, /*enable_slow_lookup=*/true);
if (!type && parent && (Cppyy::IsNamespace(parent) || Cppyy::IsClass(parent))) {
type = Cppyy::GetTypeFromScope(Cppyy::GetNamed(resolved_name, parent));
}
if (!type) {
types.clear();
return true;
}
if (is_integral(i))
integral_value = strdup(i.c_str());
if (Cpp::TCppScope_t scope = GetEnumFromCompleteName(i))
if (Cpp::IsEnumConstant(scope))
integral_value =
strdup(std::to_string(Cpp::GetEnumConstantValue(scope)).c_str());
types.emplace_back(type, integral_value);
}
return false;
}
Cppyy::TCppType_t Cppyy::GetType(const std::string &name, bool enable_slow_lookup /* = false */) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
static unsigned long long var_count = 0;
if (auto type = Cpp::GetType(name))
return type;
if (!enable_slow_lookup) {
if (name.find("::") != std::string::npos)
throw std::runtime_error("Calling Cppyy::GetType with qualified name '"
+ name + "'\n");
return nullptr;
}
// Here we might need to deal with integral types such as 3.14.
std::string id = "__Cppyy_GetType_" + std::to_string(var_count++);
std::string using_clause = "using " + id + " = __typeof__(" + name + ");\n";
if (!Cpp::Declare(using_clause.c_str(), /*silent=*/true)) {
TCppScope_t lookup = Cpp::GetNamed(id, 0);
TCppType_t lookup_ty = Cpp::GetTypeFromScope(lookup);
return Cpp::GetCanonicalType(lookup_ty);
}
return nullptr;
}
Cppyy::TCppType_t Cppyy::GetComplexType(const std::string &name) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetComplexType(Cpp::GetType(name));
}
// //----------------------------------------------------------------------------
// static std::string extract_namespace(const std::string& name)
// {
// // Find the namespace the named class lives in, take care of templates
// // Note: this code also lives in CPyCppyy (TODO: refactor?)
// if (name.empty())
// return name;
//
// int tpl_open = 0;
// for (std::string::size_type pos = name.size()-1; 0 < pos; --pos) {
// std::string::value_type c = name[pos];
//
// // count '<' and '>' to be able to skip template contents
// if (c == '>')
// ++tpl_open;
// else if (c == '<')
// --tpl_open;
//
// // collect name up to "::"
// else if (tpl_open == 0 && c == ':' && name[pos-1] == ':') {
// // found the extend of the scope ... done
// return name.substr(0, pos-1);
// }
// }
//
// // no namespace; assume outer scope
// return "";
// }
//
std::string Cppyy::ResolveEnum(TCppScope_t handle)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
std::string type = Cpp::GetTypeAsString(
Cpp::GetIntegerTypeFromEnumScope(handle));
if (type == "signed char")
return "char";
return type;
}
Cppyy::TCppScope_t Cppyy::GetUnderlyingScope(TCppScope_t scope)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetUnderlyingScope(scope);
}
Cppyy::TCppScope_t Cppyy::GetScope(const std::string& name,
TCppScope_t parent_scope)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
if (Cppyy::TCppScope_t scope = Cpp::GetScope(name, parent_scope))
return scope;
if (!parent_scope || parent_scope == Cpp::GetGlobalScope())
if (Cppyy::TCppScope_t scope = Cpp::GetScopeFromCompleteName(name))
return scope;
// FIXME: avoid string parsing here
if (name.find('<') != std::string::npos) {
// Templated Type; May need instantiation
size_t start = name.find('<');
size_t end = name.rfind('>');
std::string params = name.substr(start + 1, end - start - 1);
std::string pure_name = name.substr(0, start);
Cppyy::TCppScope_t scope = Cpp::GetScope(pure_name, parent_scope);
if (!scope && (!parent_scope || parent_scope == Cpp::GetGlobalScope()))
scope = Cpp::GetScopeFromCompleteName(pure_name);
if (Cppyy::IsTemplate(scope)) {
std::vector<Cpp::TemplateArgInfo> templ_params;
InterOpMutex.unlock(); // unlock to allow AppendTypesSlow
if (!Cppyy::AppendTypesSlow(params, templ_params)) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::InstantiateTemplate(scope, templ_params.data(),
templ_params.size(),
/*instantiate_body=*/false);
}
}
}
return nullptr;
}
Cppyy::TCppScope_t Cppyy::GetFullScope(const std::string& name)
{
return Cppyy::GetScope(name);
}
Cppyy::TCppScope_t Cppyy::GetTypeScope(TCppScope_t var)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetScopeFromType(
Cpp::GetVariableType(var));
}
Cppyy::TCppScope_t Cppyy::GetNamed(const std::string& name,
TCppScope_t parent_scope)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetNamed(name, parent_scope);
}
Cppyy::TCppScope_t Cppyy::GetParentScope(TCppScope_t scope)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetParentScope(scope);
}
Cppyy::TCppScope_t Cppyy::GetScopeFromType(TCppType_t type)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetScopeFromType(type);
}
Cppyy::TCppType_t Cppyy::GetTypeFromScope(TCppScope_t klass)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetTypeFromScope(klass);
}
Cppyy::TCppScope_t Cppyy::GetGlobalScope()
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetGlobalScope();
}
bool Cppyy::IsTemplate(TCppScope_t handle)
{
return Cpp::IsTemplate(handle);
}
bool Cppyy::IsTemplateInstantiation(TCppScope_t handle)
{
return Cpp::IsTemplateSpecialization(handle);
}
bool Cppyy::IsTypedefed(TCppScope_t handle)
{
return Cpp::IsTypedefed(handle);
}
namespace {
class AutoCastRTTI {
public:
virtual ~AutoCastRTTI() {}
};
} // namespace
Cppyy::TCppScope_t Cppyy::GetActualClass(TCppScope_t klass, TCppObject_t obj) {
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
if (!Cpp::IsClassPolymorphic(klass))
return klass;
const std::type_info *typ = &typeid(*(AutoCastRTTI *)obj);
std::string mangled_name = typ->name();
std::string demangled_name = Cpp::Demangle(mangled_name);
if (TCppScope_t scope = Cppyy::GetScope(demangled_name))
return scope;
return klass;
}
size_t Cppyy::SizeOf(TCppScope_t klass)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::SizeOf(klass);
}
size_t Cppyy::SizeOfType(TCppType_t klass)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::GetSizeOfType(klass);
}
// size_t Cppyy::SizeOf(const std::string& type_name)
// {
// TDataType* dt = gROOT->GetType(type_name.c_str());
// if (dt) return dt->Size();
// return SizeOf(GetScope(type_name));
// }
bool Cppyy::IsBuiltin(const std::string& type_name)
{
static std::set<std::string> s_builtins =
{"bool", "char", "signed char", "unsigned char", "wchar_t", "short",
"unsigned short", "int", "unsigned int", "long", "unsigned long",
"long long", "unsigned long long", "float", "double", "long double",
"void"};
if (s_builtins.find(trim(type_name)) != s_builtins.end())
return true;
if (strstr(type_name.c_str(), "std::complex"))
return true;
return false;
}
bool Cppyy::IsBuiltin(TCppType_t type)
{
return Cpp::IsBuiltin(type);
}
bool Cppyy::IsComplete(TCppScope_t scope)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::IsComplete(scope);
}
// // memory management ---------------------------------------------------------
Cppyy::TCppObject_t Cppyy::Allocate(TCppScope_t scope)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
return Cpp::Allocate(scope, /*count=*/1);
}
void Cppyy::Deallocate(TCppScope_t scope, TCppObject_t instance)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex);
Cpp::Deallocate(scope, instance, /*count=*/1);
}
Cppyy::TCppObject_t Cppyy::Construct(TCppScope_t scope, void* arena/*=nullptr*/)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex); // TODO: this shouldn't locks the JIT call
return Cpp::Construct(scope, arena, /*count=*/1);
}
void Cppyy::Destruct(TCppScope_t scope, TCppObject_t instance)
{
std::lock_guard<std::recursive_mutex> Lock(InterOpMutex); // TODO: this shouldn't locks the JIT call
Cpp::Destruct(instance, scope, true, /*count=*/0);
}
static inline
bool copy_args(Parameter* args, size_t nargs, void** vargs)
{
bool runRelease = false;
for (size_t i = 0; i < nargs; ++i) {
switch (args[i].fTypeCode) {