-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathPythonize.cxx
More file actions
1984 lines (1704 loc) · 78.5 KB
/
Pythonize.cxx
File metadata and controls
1984 lines (1704 loc) · 78.5 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
// Bindings
#include "CPyCppyy.h"
#include "Pythonize.h"
#include "Converters.h"
#include "CPPInstance.h"
#include "CPPFunction.h"
#include "CPPOverload.h"
#include "CustomPyTypes.h"
#include "LowLevelViews.h"
#include "ProxyWrappers.h"
#include "PyCallable.h"
#include "PyStrings.h"
#include "TypeManip.h"
#include "Utility.h"
// Standard
#include <algorithm>
#include <complex>
#include <set>
#include <stdexcept>
#include <sstream>
#include <string>
#include <utility>
//- data and local helpers ---------------------------------------------------
namespace CPyCppyy {
extern PyObject* gThisModule;
std::map<std::string, std::vector<PyObject*>> &pythonizations();
}
namespace {
// for convenience
using namespace CPyCppyy;
//-----------------------------------------------------------------------------
bool HasAttrDirect(PyObject* pyclass, PyObject* pyname, bool mustBeCPyCppyy = false) {
// prevents calls to Py_TYPE(pyclass)->tp_getattr, which is unnecessary for our
// purposes here and could tickle problems w/ spurious lookups into ROOT meta
PyObject* dct = PyObject_GetAttr(pyclass, PyStrings::gDict);
if (dct) {
PyObject* attr = PyObject_GetItem(dct, pyname);
Py_DECREF(dct);
if (attr) {
bool ret = !mustBeCPyCppyy || CPPOverload_Check(attr);
Py_DECREF(attr);
return ret;
}
}
PyErr_Clear();
return false;
}
PyObject* GetAttrDirect(PyObject* pyclass, PyObject* pyname) {
// get an attribute without causing getattr lookups
PyObject* dct = PyObject_GetAttr(pyclass, PyStrings::gDict);
if (dct) {
PyObject* attr = PyObject_GetItem(dct, pyname);
Py_DECREF(dct);
return attr;
}
return nullptr;
}
//-----------------------------------------------------------------------------
inline bool IsTemplatedSTLClass(const std::string& name, const std::string& klass) {
// Scan the name of the class and determine whether it is a template instantiation.
auto pos = name.find(klass);
return pos == 5 && name.rfind("std::", 0, 5) == 0 && name.find("::", name.rfind(">")) == std::string::npos;
}
// to prevent compiler warnings about const char* -> char*
inline PyObject* CallPyObjMethod(PyObject* obj, const char* meth)
{
// Helper; call method with signature: obj->meth().
Py_INCREF(obj);
PyObject* result = PyObject_CallMethod(obj, const_cast<char*>(meth), const_cast<char*>(""));
Py_DECREF(obj);
return result;
}
//-----------------------------------------------------------------------------
inline PyObject* CallPyObjMethod(PyObject* obj, const char* meth, PyObject* arg1)
{
// Helper; call method with signature: obj->meth(arg1).
Py_INCREF(obj);
PyObject* result = PyObject_CallMethod(
obj, const_cast<char*>(meth), const_cast<char*>("O"), arg1);
Py_DECREF(obj);
return result;
}
//-----------------------------------------------------------------------------
PyObject* PyStyleIndex(PyObject* self, PyObject* index)
{
// Helper; converts python index into straight C index.
Py_ssize_t idx = PyInt_AsSsize_t(index);
if (idx == (Py_ssize_t)-1 && PyErr_Occurred())
return nullptr;
Py_ssize_t size = PySequence_Size(self);
if (idx >= size || (idx < 0 && idx < -size)) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return nullptr;
}
PyObject* pyindex = nullptr;
if (idx >= 0) {
Py_INCREF(index);
pyindex = index;
} else
pyindex = PyLong_FromSsize_t(size+idx);
return pyindex;
}
//-----------------------------------------------------------------------------
inline bool AdjustSlice(const Py_ssize_t nlen, Py_ssize_t& start, Py_ssize_t& stop, Py_ssize_t& step)
{
// Helper; modify slice range to match the container.
if ((step > 0 && stop <= start) || (step < 0 && start <= stop))
return false;
if (start < 0) start = 0;
if (start >= nlen) start = nlen-1;
if (step >= nlen) step = nlen;
stop = step > 0 ? std::min(nlen, stop) : (stop >= 0 ? stop : -1);
return true;
}
//-----------------------------------------------------------------------------
inline PyObject* CallSelfIndex(CPPInstance* self, PyObject* idx, PyObject* pymeth)
{
// Helper; call method with signature: meth(pyindex).
Py_INCREF((PyObject*)self);
PyObject* pyindex = PyStyleIndex((PyObject*)self, idx);
if (!pyindex) {
Py_DECREF((PyObject*)self);
return nullptr;
}
PyObject* result = PyObject_CallMethodOneArg((PyObject*)self, pymeth, pyindex);
Py_DECREF(pyindex);
Py_DECREF((PyObject*)self);
return result;
}
//- "smart pointer" behavior ---------------------------------------------------
PyObject* DeRefGetAttr(PyObject* self, PyObject* name)
{
// Follow operator*() if present (available in python as __deref__), so that
// smart pointers behave as expected.
if (name == PyStrings::gTypeCode || name == PyStrings::gCTypesType) {
// TODO: these calls come from TemplateProxy and are unlikely to be needed in practice,
// whereas as-is, they can accidentally dereference the result of end() on some STL
// containers. Obviously, this is a dumb hack that should be resolved more fundamentally.
PyErr_SetString(PyExc_AttributeError, CPyCppyy_PyText_AsString(name));
return nullptr;
}
if (!CPyCppyy_PyText_Check(name))
PyErr_SetString(PyExc_TypeError, "getattr(): attribute name must be string");
PyObject* pyptr = PyObject_CallMethodNoArgs(self, PyStrings::gDeref);
if (!pyptr)
return nullptr;
// prevent a potential infinite loop
if (Py_TYPE(pyptr) == Py_TYPE(self)) {
PyObject* val1 = PyObject_Str(self);
PyObject* val2 = PyObject_Str(name);
PyErr_Format(PyExc_AttributeError, "%s has no attribute \'%s\'",
CPyCppyy_PyText_AsString(val1), CPyCppyy_PyText_AsString(val2));
Py_DECREF(val2);
Py_DECREF(val1);
Py_DECREF(pyptr);
return nullptr;
}
PyObject* result = PyObject_GetAttr(pyptr, name);
Py_DECREF(pyptr);
return result;
}
//-----------------------------------------------------------------------------
PyObject* FollowGetAttr(PyObject* self, PyObject* name)
{
// Follow operator->() if present (available in python as __follow__), so that
// smart pointers behave as expected.
if (!CPyCppyy_PyText_Check(name))
PyErr_SetString(PyExc_TypeError, "getattr(): attribute name must be string");
PyObject* pyptr = PyObject_CallMethodNoArgs(self, PyStrings::gFollow);
if (!pyptr)
return nullptr;
PyObject* result = PyObject_GetAttr(pyptr, name);
Py_DECREF(pyptr);
return result;
}
//- pointer checking bool converter -------------------------------------------
PyObject* NullCheckBool(PyObject* self)
{
if (!CPPInstance_Check(self)) {
PyErr_SetString(PyExc_TypeError, "C++ object proxy expected");
return nullptr;
}
if (!((CPPInstance*)self)->GetObject())
Py_RETURN_FALSE;
return PyObject_CallMethodNoArgs(self, PyStrings::gCppBool);
}
//- vector behavior as primitives ----------------------------------------------
#if PY_VERSION_HEX < 0x03040000
#define PyObject_LengthHint _PyObject_LengthHint
#endif
// TODO: can probably use the below getters in the InitializerListConverter
struct ItemGetter {
ItemGetter(PyObject* pyobj) : fPyObject(pyobj) { Py_INCREF(fPyObject); }
virtual ~ItemGetter() { Py_DECREF(fPyObject); }
virtual Py_ssize_t size() = 0;
virtual PyObject* get() = 0;
PyObject* fPyObject;
};
struct CountedItemGetter : public ItemGetter {
CountedItemGetter(PyObject* pyobj) : ItemGetter(pyobj), fCur(0) {}
Py_ssize_t fCur;
};
struct TupleItemGetter : public CountedItemGetter {
using CountedItemGetter::CountedItemGetter;
Py_ssize_t size() override { return PyTuple_GET_SIZE(fPyObject); }
PyObject* get() override {
if (fCur < PyTuple_GET_SIZE(fPyObject)) {
PyObject* item = PyTuple_GET_ITEM(fPyObject, fCur++);
Py_INCREF(item);
return item;
}
PyErr_SetString(PyExc_StopIteration, "end of tuple");
return nullptr;
}
};
struct ListItemGetter : public CountedItemGetter {
using CountedItemGetter::CountedItemGetter;
Py_ssize_t size() override { return PyList_GET_SIZE(fPyObject); }
PyObject* get() override {
if (fCur < PyList_GET_SIZE(fPyObject)) {
PyObject* item = PyList_GET_ITEM(fPyObject, fCur++);
Py_INCREF(item);
return item;
}
PyErr_SetString(PyExc_StopIteration, "end of list");
return nullptr;
}
};
struct SequenceItemGetter : public CountedItemGetter {
using CountedItemGetter::CountedItemGetter;
Py_ssize_t size() override {
Py_ssize_t sz = PySequence_Size(fPyObject);
if (sz < 0) {
PyErr_Clear();
return PyObject_LengthHint(fPyObject, 8);
}
return sz;
}
PyObject* get() override { return PySequence_GetItem(fPyObject, fCur++); }
};
struct IterItemGetter : public ItemGetter {
using ItemGetter::ItemGetter;
Py_ssize_t size() override { return PyObject_LengthHint(fPyObject, 8); }
PyObject* get() override { return (*(Py_TYPE(fPyObject)->tp_iternext))(fPyObject); }
};
static ItemGetter* GetGetter(PyObject* args)
{
// Create an ItemGetter to loop over the iterable argument, if any.
ItemGetter* getter = nullptr;
if (PyTuple_GET_SIZE(args) == 1) {
PyObject* fi = PyTuple_GET_ITEM(args, 0);
if (CPyCppyy_PyText_Check(fi) || PyBytes_Check(fi))
return nullptr; // do not accept string to fill std::vector<char>
// TODO: this only tests for new-style buffers, which is too strict, but a
// generic check for Py_TYPE(fi)->tp_as_buffer is too loose (note that the
// main use case is numpy, which offers the new interface)
if (PyObject_CheckBuffer(fi))
return nullptr;
if (PyTuple_CheckExact(fi))
getter = new TupleItemGetter(fi);
else if (PyList_CheckExact(fi))
getter = new ListItemGetter(fi);
else if (PySequence_Check(fi))
getter = new SequenceItemGetter(fi);
else {
PyObject* iter = PyObject_GetIter(fi);
if (iter) {
getter = new IterItemGetter{iter};
Py_DECREF(iter);
}
else PyErr_Clear();
}
}
return getter;
}
static bool FillVector(PyObject* vecin, PyObject* args, ItemGetter* getter)
{
Py_ssize_t sz = getter->size();
if (sz < 0)
return false;
// reserve memory as applicable
if (0 < sz) {
PyObject* res = PyObject_CallMethod(vecin, (char*)"reserve", (char*)"n", sz);
Py_DECREF(res);
} else // i.e. sz == 0, so empty container: done
return true;
bool fill_ok = true;
// two main options: a list of lists (or tuples), or a list of objects; the former
// are emplace_back'ed, the latter push_back'ed
PyObject* fi = PySequence_GetItem(PyTuple_GET_ITEM(args, 0), 0);
if (!fi) PyErr_Clear();
if (fi && (PyTuple_CheckExact(fi) || PyList_CheckExact(fi))) {
// use emplace_back to construct the vector entries one by one
PyObject* eb_call = PyObject_GetAttrString(vecin, (char*)"emplace_back");
PyObject* vtype = GetAttrDirect((PyObject*)Py_TYPE(vecin), PyStrings::gValueType);
bool value_is_vector = false;
if (vtype && CPyCppyy_PyText_Check(vtype)) {
// if the value_type is a vector, then allow for initialization from sequences
if (std::string(CPyCppyy_PyText_AsString(vtype)).rfind("std::vector", 0) != std::string::npos)
value_is_vector = true;
} else
PyErr_Clear();
Py_XDECREF(vtype);
if (eb_call) {
PyObject* eb_args;
for (int i = 0; /* until break */; ++i) {
PyObject* item = getter->get();
if (item) {
if (value_is_vector && PySequence_Check(item)) {
eb_args = PyTuple_New(1);
PyTuple_SET_ITEM(eb_args, 0, item);
} else if (PyTuple_CheckExact(item)) {
eb_args = item;
} else if (PyList_CheckExact(item)) {
Py_ssize_t isz = PyList_GET_SIZE(item);
eb_args = PyTuple_New(isz);
for (Py_ssize_t j = 0; j < isz; ++j) {
PyObject* iarg = PyList_GET_ITEM(item, j);
Py_INCREF(iarg);
PyTuple_SET_ITEM(eb_args, j, iarg);
}
Py_DECREF(item);
} else {
Py_DECREF(item);
PyErr_Format(PyExc_TypeError, "argument %d is not a tuple or list", i);
fill_ok = false;
break;
}
PyObject* ebres = PyObject_CallObject(eb_call, eb_args);
Py_DECREF(eb_args);
if (!ebres) {
fill_ok = false;
break;
}
Py_DECREF(ebres);
} else {
if (PyErr_Occurred()) {
if (!(PyErr_ExceptionMatches(PyExc_IndexError) ||
PyErr_ExceptionMatches(PyExc_StopIteration)))
fill_ok = false;
else { PyErr_Clear(); }
}
break;
}
}
Py_DECREF(eb_call);
}
} else {
// use push_back to add the vector entries one by one
PyObject* pb_call = PyObject_GetAttrString(vecin, (char*)"push_back");
if (pb_call) {
for (;;) {
PyObject* item = getter->get();
if (item) {
PyObject* pbres = PyObject_CallFunctionObjArgs(pb_call, item, nullptr);
Py_DECREF(item);
if (!pbres) {
fill_ok = false;
break;
}
Py_DECREF(pbres);
} else {
if (PyErr_Occurred()) {
if (!(PyErr_ExceptionMatches(PyExc_IndexError) ||
PyErr_ExceptionMatches(PyExc_StopIteration)))
fill_ok = false;
else { PyErr_Clear(); }
}
break;
}
}
Py_DECREF(pb_call);
}
}
Py_XDECREF(fi);
return fill_ok;
}
PyObject* VectorIAdd(PyObject* self, PyObject* args, PyObject* /* kwds */)
{
// Implement fast __iadd__ on std::vector (generic __iadd__ is in Python)
ItemGetter* getter = GetGetter(args);
if (getter) {
bool fill_ok = FillVector(self, args, getter);
delete getter;
if (!fill_ok)
return nullptr;
Py_INCREF(self);
return self;
}
// if no getter, it could still be b/c we have a buffer (e.g. numpy); looping over
// a buffer here is slow, so use insert() instead
if (PyTuple_GET_SIZE(args) == 1) {
PyObject* fi = PyTuple_GET_ITEM(args, 0);
if (PyObject_CheckBuffer(fi) && !(CPyCppyy_PyText_Check(fi) || PyBytes_Check(fi))) {
PyObject* vend = PyObject_CallMethodNoArgs(self, PyStrings::gEnd);
if (vend) {
PyObject* result = PyObject_CallMethodObjArgs(self, PyStrings::gInsert, vend, fi, nullptr);
Py_DECREF(vend);
return result;
}
}
}
if (!PyErr_Occurred())
PyErr_SetString(PyExc_TypeError, "argument is not iterable");
return nullptr; // error already set
}
PyObject* VectorInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
{
// Specialized vector constructor to allow construction from containers; allowing
// such construction from initializer_list instead would possible, but can be
// error-prone. This use case is common enough for std::vector to implement it
// directly, except for arrays (which can be passed wholesale) and strings (which
// won't convert properly as they'll be seen as buffers)
ItemGetter* getter = GetGetter(args);
if (getter) {
// construct an empty vector, then back-fill it
PyObject* result = PyObject_CallMethodNoArgs(self, PyStrings::gRealInit);
if (!result) {
delete getter;
return nullptr;
}
bool fill_ok = FillVector(self, args, getter);
delete getter;
if (!fill_ok) {
Py_DECREF(result);
return nullptr;
}
return result;
}
// The given argument wasn't iterable: simply forward to regular constructor
PyObject* realInit = PyObject_GetAttr(self, PyStrings::gRealInit);
if (realInit) {
PyObject* result = PyObject_Call(realInit, args, nullptr);
Py_DECREF(realInit);
return result;
}
return nullptr;
}
//---------------------------------------------------------------------------
PyObject* VectorData(PyObject* self, PyObject*)
{
PyObject* pydata = CallPyObjMethod(self, "__real_data");
if (!LowLevelView_Check(pydata) && !CPPInstance_Check(pydata))
return pydata;
PyObject* pylen = PyObject_CallMethodNoArgs(self, PyStrings::gSize);
if (!pylen) {
PyErr_Clear();
return pydata;
}
long clen = PyInt_AsLong(pylen);
Py_DECREF(pylen);
if (CPPInstance_Check(pydata)) {
((CPPInstance*)pydata)->CastToArray(clen);
return pydata;
}
((LowLevelView*)pydata)->resize((size_t)clen);
return pydata;
}
//---------------------------------------------------------------------------
PyObject* VectorArray(PyObject* self, PyObject* args, PyObject* kwargs)
{
PyObject* pydata = VectorData(self, nullptr);
PyObject* arrcall = PyObject_GetAttr(pydata, PyStrings::gArray);
PyObject* newarr = PyObject_Call(arrcall, args, kwargs);
Py_DECREF(arrcall);
Py_DECREF(pydata);
return newarr;
}
//-----------------------------------------------------------------------------
static PyObject* vector_iter(PyObject* v) {
vectoriterobject* vi = PyObject_GC_New(vectoriterobject, &VectorIter_Type);
if (!vi) return nullptr;
Py_INCREF(v);
vi->ii_container = v;
// tell the iterator code to set a life line if this container is a temporary
vi->vi_flags = vectoriterobject::kDefault;
if (v->ob_refcnt <= 2 || (((CPPInstance*)v)->fFlags & CPPInstance::kIsValue))
vi->vi_flags = vectoriterobject::kNeedLifeLine;
PyObject* pyvalue_type = PyObject_GetAttr((PyObject*)Py_TYPE(v), PyStrings::gValueType);
if (pyvalue_type) {
PyObject* pyvalue_size = GetAttrDirect((PyObject*)Py_TYPE(v), PyStrings::gValueSize);
if (pyvalue_size) {
vi->vi_stride = PyLong_AsLong(pyvalue_size);
Py_DECREF(pyvalue_size);
} else {
PyErr_Clear();
vi->vi_stride = 0;
}
if (CPyCppyy_PyText_Check(pyvalue_type)) {
std::string value_type = CPyCppyy_PyText_AsString(pyvalue_type);
value_type = Cppyy::ResolveName(value_type);
vi->vi_klass = Cppyy::GetScope(value_type);
if (!vi->vi_klass) {
// look for a special case of pointer to a class type (which is a builtin, but it
// is more useful to treat it polymorphically by allowing auto-downcasts)
const std::string& clean_type = TypeManip::clean_type(value_type, false, false);
Cppyy::TCppScope_t c = Cppyy::GetScope(clean_type);
if (c && TypeManip::compound(value_type) == "*") {
vi->vi_klass = c;
vi->vi_flags = vectoriterobject::kIsPolymorphic;
}
}
if (vi->vi_klass) {
vi->vi_converter = nullptr;
if (!vi->vi_flags) {
if (value_type.back() != '*') // meaning, object stored by-value
vi->vi_flags = vectoriterobject::kNeedLifeLine;
}
} else
vi->vi_converter = CPyCppyy::CreateConverter(value_type);
if (!vi->vi_stride) vi->vi_stride = Cppyy::SizeOf(value_type);
} else if (CPPScope_Check(pyvalue_type)) {
vi->vi_klass = ((CPPClass*)pyvalue_type)->fCppType;
vi->vi_converter = nullptr;
if (!vi->vi_stride) vi->vi_stride = Cppyy::SizeOf(vi->vi_klass);
if (!vi->vi_flags) vi->vi_flags = vectoriterobject::kNeedLifeLine;
}
PyObject* pydata = CallPyObjMethod(v, "__real_data");
if (!pydata || Utility::GetBuffer(pydata, '*', 1, vi->vi_data, false) == 0)
vi->vi_data = CPPInstance_Check(pydata) ? ((CPPInstance*)pydata)->GetObjectRaw() : nullptr;
Py_XDECREF(pydata);
} else {
PyErr_Clear();
vi->vi_data = nullptr;
vi->vi_stride = 0;
vi->vi_converter = nullptr;
vi->vi_klass = 0;
vi->vi_flags = 0;
}
Py_XDECREF(pyvalue_type);
vi->ii_pos = 0;
vi->ii_len = PySequence_Size(v);
PyObject_GC_Track(vi);
return (PyObject*)vi;
}
PyObject* VectorGetItem(CPPInstance* self, PySliceObject* index)
{
// Implement python's __getitem__ for std::vector<>s.
if (PySlice_Check(index)) {
if (!self->GetObject()) {
PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
return nullptr;
}
PyObject* pyclass = (PyObject*)Py_TYPE((PyObject*)self);
PyObject* nseq = PyObject_CallObject(pyclass, nullptr);
Py_ssize_t start, stop, step;
PySlice_GetIndices((CPyCppyy_PySliceCast)index, PyObject_Length((PyObject*)self), &start, &stop, &step);
const Py_ssize_t nlen = PySequence_Size((PyObject*)self);
if (!AdjustSlice(nlen, start, stop, step))
return nseq;
const Py_ssize_t sign = step < 0 ? -1 : 1;
for (Py_ssize_t i = start; i*sign < stop*sign; i += step) {
PyObject* pyidx = PyInt_FromSsize_t(i);
PyObject* item = PyObject_CallMethodOneArg((PyObject*)self, PyStrings::gGetNoCheck, pyidx);
CallPyObjMethod(nseq, "push_back", item);
Py_DECREF(item);
Py_DECREF(pyidx);
}
return nseq;
}
return CallSelfIndex(self, (PyObject*)index, PyStrings::gGetNoCheck);
}
static Cppyy::TCppType_t sVectorBoolTypeID = (Cppyy::TCppType_t)0;
PyObject* VectorBoolGetItem(CPPInstance* self, PyObject* idx)
{
// std::vector<bool> is a special-case in C++, and its return type depends on
// the compiler: treat it special here as well
if (!CPPInstance_Check(self) || self->ObjectIsA() != sVectorBoolTypeID) {
PyErr_Format(PyExc_TypeError,
"require object of type std::vector<bool>, but %s given",
Cppyy::GetScopedFinalName(self->ObjectIsA()).c_str());
return nullptr;
}
if (!self->GetObject()) {
PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
return nullptr;
}
if (PySlice_Check(idx)) {
PyObject* pyclass = (PyObject*)Py_TYPE((PyObject*)self);
PyObject* nseq = PyObject_CallObject(pyclass, nullptr);
Py_ssize_t start, stop, step;
PySlice_GetIndices((CPyCppyy_PySliceCast)idx, PyObject_Length((PyObject*)self), &start, &stop, &step);
const Py_ssize_t nlen = PySequence_Size((PyObject*)self);
if (!AdjustSlice(nlen, start, stop, step))
return nseq;
const Py_ssize_t sign = step < 0 ? -1 : 1;
for (Py_ssize_t i = start; i*sign < stop*sign; i += step) {
PyObject* pyidx = PyInt_FromSsize_t(i);
PyObject* item = PyObject_CallMethodOneArg((PyObject*)self, PyStrings::gGetItem, pyidx);
CallPyObjMethod(nseq, "push_back", item);
Py_DECREF(item);
Py_DECREF(pyidx);
}
return nseq;
}
PyObject* pyindex = PyStyleIndex((PyObject*)self, idx);
if (!pyindex)
return nullptr;
int index = (int)PyLong_AsLong(pyindex);
Py_DECREF(pyindex);
// get hold of the actual std::vector<bool> (no cast, as vector is never a base)
std::vector<bool>* vb = (std::vector<bool>*)self->GetObject();
// finally, return the value
if (bool((*vb)[index]))
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
PyObject* VectorBoolSetItem(CPPInstance* self, PyObject* args)
{
// std::vector<bool> is a special-case in C++, and its return type depends on
// the compiler: treat it special here as well
if (!CPPInstance_Check(self) || self->ObjectIsA() != sVectorBoolTypeID) {
PyErr_Format(PyExc_TypeError,
"require object of type std::vector<bool>, but %s given",
Cppyy::GetScopedFinalName(self->ObjectIsA()).c_str());
return nullptr;
}
if (!self->GetObject()) {
PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
return nullptr;
}
int bval = 0; PyObject* idx = nullptr;
if (!PyArg_ParseTuple(args, const_cast<char*>("Oi:__setitem__"), &idx, &bval))
return nullptr;
PyObject* pyindex = PyStyleIndex((PyObject*)self, idx);
if (!pyindex)
return nullptr;
int index = (int)PyLong_AsLong(pyindex);
Py_DECREF(pyindex);
// get hold of the actual std::vector<bool> (no cast, as vector is never a base)
std::vector<bool>* vb = (std::vector<bool>*)self->GetObject();
// finally, set the value
(*vb)[index] = (bool)bval;
Py_RETURN_NONE;
}
//- array behavior as primitives ----------------------------------------------
PyObject* ArrayInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
{
// std::array is normally only constructed using aggregate initialization, which
// is a concept that does not exist in python, so use this custom constructor to
// to fill the array using setitem
if (args && PyTuple_GET_SIZE(args) == 1 && PySequence_Check(PyTuple_GET_ITEM(args, 0))) {
// construct the empty array, then fill it
PyObject* result = PyObject_CallMethodNoArgs(self, PyStrings::gRealInit);
if (!result)
return nullptr;
PyObject* items = PyTuple_GET_ITEM(args, 0);
Py_ssize_t fillsz = PySequence_Size(items);
if (PySequence_Size(self) != fillsz) {
PyErr_Format(PyExc_ValueError, "received sequence of size %zd where %zd expected",
fillsz, PySequence_Size(self));
Py_DECREF(result);
return nullptr;
}
PyObject* si_call = PyObject_GetAttr(self, PyStrings::gSetItem);
for (Py_ssize_t i = 0; i < fillsz; ++i) {
PyObject* item = PySequence_GetItem(items, i);
PyObject* index = PyInt_FromSsize_t(i);
PyObject* sires = PyObject_CallFunctionObjArgs(si_call, index, item, nullptr);
Py_DECREF(index);
Py_DECREF(item);
if (!sires) {
Py_DECREF(si_call);
Py_DECREF(result);
return nullptr;
} else
Py_DECREF(sires);
}
Py_DECREF(si_call);
return result;
} else
PyErr_Clear();
// The given argument wasn't iterable: simply forward to regular constructor
PyObject* realInit = PyObject_GetAttr(self, PyStrings::gRealInit);
if (realInit) {
PyObject* result = PyObject_Call(realInit, args, nullptr);
Py_DECREF(realInit);
return result;
}
return nullptr;
}
//- map behavior as primitives ------------------------------------------------
static PyObject* MapFromPairs(PyObject* self, PyObject* pairs)
{
// construct an empty map, then fill it with the key, value pairs
PyObject* result = PyObject_CallMethodNoArgs(self, PyStrings::gRealInit);
if (!result)
return nullptr;
PyObject* si_call = PyObject_GetAttr(self, PyStrings::gSetItem);
for (Py_ssize_t i = 0; i < PySequence_Size(pairs); ++i) {
PyObject* pair = PySequence_GetItem(pairs, i);
PyObject* sires = nullptr;
if (pair && PySequence_Check(pair) && PySequence_Size(pair) == 2) {
PyObject* key = PySequence_GetItem(pair, 0);
PyObject* value = PySequence_GetItem(pair, 1);
sires = PyObject_CallFunctionObjArgs(si_call, key, value, nullptr);
Py_DECREF(value);
Py_DECREF(key);
}
Py_DECREF(pair);
if (!sires) {
Py_DECREF(si_call);
Py_DECREF(result);
if (!PyErr_Occurred())
PyErr_SetString(PyExc_TypeError, "Failed to fill map (argument not a dict or sequence of pairs)");
return nullptr;
} else
Py_DECREF(sires);
}
Py_DECREF(si_call);
return result;
}
PyObject* MapInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
{
// Specialized map constructor to allow construction from mapping containers and
// from tuples of pairs ("initializer_list style").
// PyMapping_Check is not very discriminatory, as it basically only checks for the
// existence of __getitem__, hence the most common cases of tuple and list are
// dropped straight-of-the-bat (the PyMapping_Items call will fail on them).
if (PyTuple_GET_SIZE(args) == 1 && PyMapping_Check(PyTuple_GET_ITEM(args, 0)) && \
!(PyTuple_Check(PyTuple_GET_ITEM(args, 0)) || PyList_Check(PyTuple_GET_ITEM(args, 0)))) {
PyObject* assoc = PyTuple_GET_ITEM(args, 0);
#if PY_VERSION_HEX < 0x03000000
// to prevent warning about literal string, expand macro
PyObject* items = PyObject_CallMethod(assoc, (char*)"items", nullptr);
#else
// in p3, PyMapping_Items isn't a macro, but a function that short-circuits dict
PyObject* items = PyMapping_Items(assoc);
#endif
if (items && PySequence_Check(items)) {
PyObject* result = MapFromPairs(self, items);
Py_DECREF(items);
return result;
}
Py_XDECREF(items);
PyErr_Clear();
// okay to fall through as long as 'self' has not been created (is done in MapFromPairs)
}
// tuple of pairs case (some mapping types are sequences)
if (PyTuple_GET_SIZE(args) == 1 && PySequence_Check(PyTuple_GET_ITEM(args, 0)))
return MapFromPairs(self, PyTuple_GET_ITEM(args, 0));
// The given argument wasn't a mapping or tuple of pairs: forward to regular constructor
PyObject* realInit = PyObject_GetAttr(self, PyStrings::gRealInit);
if (realInit) {
PyObject* result = PyObject_Call(realInit, args, nullptr);
Py_DECREF(realInit);
return result;
}
return nullptr;
}
PyObject* STLContainsWithFind(PyObject* self, PyObject* obj)
{
// Implement python's __contains__ for std::map/std::set
PyObject* result = nullptr;
PyObject* iter = CallPyObjMethod(self, "find", obj);
if (CPPInstance_Check(iter)) {
PyObject* end = PyObject_CallMethodNoArgs(self, PyStrings::gEnd);
if (CPPInstance_Check(end)) {
if (!PyObject_RichCompareBool(iter, end, Py_EQ)) {
Py_INCREF(Py_True);
result = Py_True;
}
}
Py_XDECREF(end);
}
Py_XDECREF(iter);
if (!result) {
PyErr_Clear(); // e.g. wrong argument type, which should always lead to False
Py_INCREF(Py_False);
result = Py_False;
}
return result;
}
//- set behavior as primitives ------------------------------------------------
PyObject* SetInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
{
// Specialized set constructor to allow construction from Python sets.
if (PyTuple_GET_SIZE(args) == 1 && PySet_Check(PyTuple_GET_ITEM(args, 0))) {
PyObject* pyset = PyTuple_GET_ITEM(args, 0);
// construct an empty set, then fill it
PyObject* result = PyObject_CallMethodNoArgs(self, PyStrings::gRealInit);
if (!result)
return nullptr;
PyObject* iter = PyObject_GetIter(pyset);
if (iter) {
PyObject* ins_call = PyObject_GetAttrString(self, (char*)"insert");
IterItemGetter getter{iter};
Py_DECREF(iter);
PyObject* item = getter.get();
while (item) {
PyObject* insres = PyObject_CallFunctionObjArgs(ins_call, item, nullptr);
Py_DECREF(item);
if (!insres) {
Py_DECREF(ins_call);
Py_DECREF(result);
return nullptr;
} else
Py_DECREF(insres);
item = getter.get();
}
Py_DECREF(ins_call);
}
return result;
}
// The given argument wasn't iterable: simply forward to regular constructor
PyObject* realInit = PyObject_GetAttr(self, PyStrings::gRealInit);
if (realInit) {
PyObject* result = PyObject_Call(realInit, args, nullptr);
Py_DECREF(realInit);
return result;
}
return nullptr;
}
//- STL container iterator support --------------------------------------------
static const ptrdiff_t PS_END_ADDR = 7; // non-aligned address, so no clash
static const ptrdiff_t PS_FLAG_ADDR = 11; // id.
static const ptrdiff_t PS_COLL_ADDR = 13; // id.
PyObject* LLSequenceIter(PyObject* self)
{
// Implement python's __iter__ for low level views used through STL-type begin()/end()
PyObject* iter = PyObject_CallMethodNoArgs(self, PyStrings::gBegin);
if (LowLevelView_Check(iter)) {
// builtin pointer iteration: can only succeed if a size is available
Py_ssize_t sz = PySequence_Size(self);
if (sz == -1) {
Py_DECREF(iter);
return nullptr;
}
PyObject* lliter = Py_TYPE(iter)->tp_iter(iter);
((indexiterobject*)lliter)->ii_len = sz;
Py_DECREF(iter);
return lliter;
}
if (iter) {
Py_DECREF(iter);
PyErr_SetString(PyExc_TypeError, "unrecognized iterator type for low level views");
}
return nullptr;
}
PyObject* STLSequenceIter(PyObject* self)
{
// Implement python's __iter__ for std::iterator<>s
PyObject* iter = PyObject_CallMethodNoArgs(self, PyStrings::gBegin);
if (iter) {
PyObject* end = PyObject_CallMethodNoArgs(self, PyStrings::gEnd);
if (end) {
if (CPPInstance_Check(iter)) {
// use the data member cache to store extra state on the iterator object,
// without it being visible on the Python side
auto& dmc = ((CPPInstance*)iter)->GetDatamemberCache();
dmc.push_back(std::make_pair(PS_END_ADDR, end));