Repository navigation
Expand file tree
/
Copy pathscalartypes.c.src
More file actions
4993 lines (4409 loc) · 141 KB
/
Copy pathscalartypes.c.src
File metadata and controls
4993 lines (4409 loc) · 141 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
/* -*- c -*- */
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <structmember.h>
#include <ctype.h>
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#ifndef _MULTIARRAYMODULE
#define _MULTIARRAYMODULE
#endif
#include "numpy/arrayobject.h"
#include "numpy/npy_math.h"
#include "numpy/halffloat.h"
#include "numpy/arrayscalars.h"
#include "npy_pycompat.h"
#include "arraytypes.h"
#include "array_coercion.h"
#include "npy_config.h"
#include "mapping.h"
#include "ctors.h"
#include "dtypemeta.h"
#include "descriptor.h"
#include "usertypes.h"
#include "number.h"
#include "numpyos.h"
#include "can_cast_table.h"
#include "common.h"
#include "conversion_utils.h"
#include "flagsobject.h"
#include "scalartypes.h"
#include "_datetime.h"
#include "datetime_strings.h"
#include "alloc.h"
#include "npy_import.h"
#include "dragon4.h"
#include "npy_longdouble.h"
#include "npy_buffer.h"
#include "npy_dlpack.h"
#include "npy_static_data.h"
#include "module_state.h"
#include "multiarraymodule.h"
#include "array_api_standard.h"
#include <stdlib.h>
#include "binop_override.h"
/*
* used for allocating a single scalar, so use the default numpy
* memory allocators instead of the (maybe) user overrides
*/
NPY_NO_EXPORT void *
npy_alloc_cache_zero(size_t nmemb, size_t size);
NPY_NO_EXPORT void
npy_free_cache(void * p, npy_uintp sz);
NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[] = {
{PyObject_HEAD_INIT(&PyBoolArrType_Type) 0},
{PyObject_HEAD_INIT(&PyBoolArrType_Type) 1},
};
/* TimeInteger is deleted, but still here to fill the API slot */
NPY_NO_EXPORT PyTypeObject PyTimeIntegerArrType_Type;
/*
* Inheritance is established later when tp_bases is set (or tp_base for
* single inheritance)
*/
/**begin repeat
* #name = number, integer, signedinteger, unsignedinteger, inexact,
* floating, complexfloating, flexible, character#
* #NAME = Number, Integer, SignedInteger, UnsignedInteger, Inexact,
* Floating, ComplexFloating, Flexible, Character#
*/
NPY_NO_EXPORT PyTypeObject Py@NAME@ArrType_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "numpy.@name@",
.tp_basicsize = sizeof(PyObject),
};
/**end repeat**/
static void
gentype_dealloc(PyObject *v)
{
Py_TYPE(v)->tp_free(v);
}
static void
gentype_free(PyObject *v)
{
/*
* have an explicit tp_free to enforce inheritance from it.
* PyObject_Free is also the tp_free of PyBaseObject so python does not
* COPYSLOT it, instead it takes the next parent PyInt which has a
* different allocator
*/
PyObject_Free(v);
}
/* Interned name of a method the scalars forward to the 0-d array. */
#define NPY_SCALAR_METHOD_NAME(name) \
(_npy_module_state->interned_str \
.scalar_method_names[NPY_SCALAR_METHOD_##name])
/* Forwarded arguments passed on the C stack; longer calls get a heap buffer. */
#define NPY_SCALAR_FORWARD_STACK_SIZE 10
/*
* Forward a scalar method to the equivalent 0-d array. The object goes in
* `stack[0]`, which `PY_VECTORCALL_ARGUMENTS_OFFSET` allows the callee to
* overwrite temporarily, so the arguments are copied one slot up.
*/
static PyObject *
gentype_generic_vectorcall(PyObject *self, PyObject *const *args,
Py_ssize_t len_args, PyObject *kwnames, PyObject *name)
{
PyObject *arr = PyArray_FromScalar(self, NULL);
if (arr == NULL) {
return NULL;
}
Py_ssize_t nargs = len_args;
if (kwnames != NULL) {
nargs += PyTuple_GET_SIZE(kwnames);
}
NPY_ALLOC_WORKSPACE(stack, PyObject *, NPY_SCALAR_FORWARD_STACK_SIZE,
nargs + 1);
if (stack == NULL) {
Py_DECREF(arr);
return NULL;
}
stack[0] = arr;
if (nargs > 0) {
memcpy(stack + 1, args, nargs * sizeof(PyObject *));
}
PyObject *ret = PyObject_VectorcallMethod(name, stack,
((size_t)len_args + 1) | PY_VECTORCALL_ARGUMENTS_OFFSET, kwnames);
npy_free_workspace(stack);
Py_DECREF(arr);
if (ret != NULL && PyArray_Check(ret)) {
return PyArray_Return((PyArrayObject *)ret);
}
return ret;
}
/*
* Helper function to deal with binary operator deferral. Must be passed a
* valid self (a generic scalar) and an other item.
* May fill self_item and/or other_arr (but not both) with non-NULL values.
*
* Why this dance? When the other object is exactly a Python scalar something
* awkward happens historically in NumPy.
* NumPy doesn't define a result, but the ufunc would cast to `astype(object)`
* which is the same as `scalar.item()`. And that operation converts e.g.
* float32 or float64 to Python floats.
* It then retries. And because it is a builtin type now the operation may
* succeed.
*
* This retrying pass only makes sense if the other object is a Python
* scalar (otherwise we fill in `other_arr` which can be used to call the
* ufunc).
* Additionally, if `self.item()` has the same type as `self` we would end up
* in an infinite recursion.
*
* So the result of this function means the following:
* - < 0 error return.
* - self_op is filled in: Retry the Python operator.
* - other_op is filled in: Use the array operator (goes into ufuncs)
* (This may be the original generic if it is one.)
* - neither is filled in: Return NotImplemented.
*
* It is not possible for both to be filled. If `other` is also a generics,
* it is returned.
*/
static inline int
find_binary_operation_path(
PyObject *self, PyObject *other, PyObject **self_op, PyObject **other_op)
{
multiarray_umath_state *state = _npy_module_state;
*other_op = NULL;
*self_op = NULL;
if (PyArray_IsScalar(other, Generic) ||
PyLong_CheckExact(other) ||
PyFloat_CheckExact(other) ||
PyComplex_CheckExact(other) ||
PyBool_Check(other) ||
PyArray_Check(other)) {
/*
* The other operand is ready for the operation already. Must pass on
* on float/long/complex mainly for weak promotion (NEP 50).
*/
*other_op = Py_NewRef(other);
return 0;
}
/*
* If other has __array_ufunc__ always use ufunc. If array-ufunc was None
* we already deferred. And any custom object with array-ufunc cannot call
* our ufuncs without preventing recursion.
* It may be nice to avoid double lookup in `BINOP_GIVE_UP_IF_NEEDED`.
*/
PyObject *attr;
if (PyArray_LookupSpecial(other, state->interned_str.array_ufunc, &attr) < 0) {
PyErr_Clear(); /* TODO[gh-14801]: propagate crashes during attribute access? */
}
else if (attr != NULL) {
Py_DECREF(attr);
*other_op = Py_NewRef(other);
return 0;
}
/*
* Now check `other`. We want to know whether it is an object scalar
* and the easiest way is by converting to an array here.
*/
int was_scalar;
PyArrayObject *arr = (PyArrayObject *)PyArray_FromAny_int(
other, NULL, NULL, 0, NPY_MAXDIMS, 0, &was_scalar);
if (arr == NULL) {
return -1;
}
if (!was_scalar || PyArray_DESCR(arr)->type_num != NPY_OBJECT) {
/*
* The array is OK for usage and we can simply forward it. There
* is a theoretical subtlety here: If the other object implements
* `__array_wrap__`, we may ignore that. However, this only matters
* if the other object has the identical `__array_priority__` and
* additionally already deferred back to us.
* (`obj + scalar` and `scalar + obj` are not symmetric.)
*
* NOTE: Future NumPy may need to distinguish scalars here, one option
* could be marking the array.
*/
*other_op = (PyObject *)arr;
return 0;
}
Py_DECREF(arr);
/*
* If we are here, we need to operate on Python scalars. In general
* that would just fails since NumPy doesn't know the other object!
*
* However, NumPy (historically) made this often work magically because
* ufuncs for object dtype end up casting to object with `.item()`. This in
* turn often returns a Python type (e.g. float for float32, float64)!
* Retrying then succeeds. So if (and only if) `self.item()` returns a new
* type, we can safely attempt the operation (again) with that.
*/
PyObject *self_item = PyObject_VectorcallMethod(
state->interned_str.item, &self, 1, NULL);
if (self_item == NULL) {
return -1;
}
if (Py_TYPE(self_item) != Py_TYPE(self)) {
/* self_item can be used to retry the operation */
*self_op = self_item;
return 0;
}
/* The operation can't work and we will return NotImplemented */
Py_DECREF(self_item);
return 0;
}
/*
* These are defined below as they require special handling, we still define
* a _gen version here. `power` is special as it has three arguments.
*/
static PyObject *
gentype_add(PyObject *m1, PyObject *m2);
static PyObject *
gentype_multiply(PyObject *m1, PyObject *m2);
/**begin repeat
*
* #name = add, multiply, subtract, remainder, divmod,
* lshift, rshift, and, xor, or, floor_divide, true_divide#
* #ufunc = add, multiply, subtract, remainder, divmod,
* left_shift, right_shift, bitwise_and, bitwise_xor, bitwise_or,
* floor_divide, true_divide#
* #func = Add, Multiply, Subtract, Remainder, Divmod,
* Lshift, Rshift, And, Xor, Or, FloorDivide, TrueDivide#
* #suff = _gen, _gen,,,,,,,,,,#
*/
/* NOTE: We suffix the name for functions requiring special handling first. */
static PyObject *
gentype_@name@@suff@(PyObject *m1, PyObject *m2)
{
multiarray_umath_state *state = _npy_module_state;
BINOP_GIVE_UP_IF_NEEDED(m1, m2, nb_@name@, gentype_@name@);
PyObject *self = NULL;
PyObject *other = NULL;
PyObject *self_op, *other_op;
if (!PyArray_IsScalar(m2, Generic)) {
self = m1;
other = m2;
}
else {
self = m2;
other = m1;
}
if (find_binary_operation_path(self, other, &self_op, &other_op) < 0) {
return NULL;
}
if (self_op != NULL) {
PyObject *res;
if (self == m1) {
res = PyNumber_@func@(self_op, m2);
}
else {
res = PyNumber_@func@(m1, self_op);
}
Py_DECREF(self_op);
return res;
}
else if (other_op != NULL) {
/* Call the corresponding ufunc (with the array) */
PyObject *res;
if (self == m1) {
res = PyArray_GenericBinaryFunction(m1, other_op, state->n_ops.@ufunc@);
}
else {
res = PyArray_GenericBinaryFunction(other_op, m2, state->n_ops.@ufunc@);
}
Py_DECREF(other_op);
return res;
}
else {
assert(other_op == NULL);
Py_RETURN_NOTIMPLEMENTED;
}
}
/**end repeat**/
/*
* The following operators use the above, but require specialization.
*/
static PyObject *
gentype_add(PyObject *m1, PyObject *m2)
{
/* special case str.__radd__, which should not call array_add */
if (PyBytes_Check(m1) || PyUnicode_Check(m1)) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
return gentype_add_gen(m1, m2);
}
/* Get a nested slot, or NULL if absent (for multiply implementation) */
#define GET_NESTED_SLOT(type, group, slot) \
((type)->group == NULL ? NULL : (type)->group->slot)
static PyObject *
gentype_multiply(PyObject *m1, PyObject *m2)
{
/*
* If the other object supports sequence repeat and not number multiply
* we fall back on the python builtin to invoke the sequence repeat, rather
* than promoting both arguments to ndarray.
* This covers a list repeat by numpy scalars.
* A python defined class will always only have the nb_multiply slot and
* some classes may have neither defined. For the latter we want need
* to give the normal case a chance to convert the object to ndarray.
* Probably no class has both defined, but if they do, prefer number.
*/
if (!PyArray_IsScalar(m1, Generic) &&
GET_NESTED_SLOT(Py_TYPE(m1), tp_as_sequence, sq_repeat) != NULL &&
GET_NESTED_SLOT(Py_TYPE(m1), tp_as_number, nb_multiply) == NULL) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
if (!PyArray_IsScalar(m2, Generic) &&
GET_NESTED_SLOT(Py_TYPE(m2), tp_as_sequence, sq_repeat) != NULL &&
GET_NESTED_SLOT(Py_TYPE(m2), tp_as_number, nb_multiply) == NULL) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
return gentype_multiply_gen(m1, m2);
}
/*
* NOTE: The three argument nature of power requires code duplication here.
*/
static PyObject *
gentype_power(PyObject *m1, PyObject *m2, PyObject *modulo)
{
multiarray_umath_state *state = _npy_module_state;
if (modulo != Py_None) {
/* modular exponentiation is not implemented (gh-8804) */
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
BINOP_GIVE_UP_IF_NEEDED(m1, m2, nb_power, gentype_power);
PyObject *self = NULL;
PyObject *other = NULL;
PyObject *self_op, *other_op;
if (!PyArray_IsScalar(m2, Generic)) {
self = m1;
other = m2;
}
else {
self = m2;
other = m1;
}
if (find_binary_operation_path(self, other, &self_op, &other_op) < 0) {
return NULL;
}
if (self_op != NULL) {
PyObject *res;
if (self == m1) {
res = PyNumber_Power(self_op, m2, Py_None);
}
else {
res = PyNumber_Power(m1, self_op, Py_None);
}
Py_DECREF(self_op);
return res;
}
else if (other_op != NULL) {
/* Call the corresponding ufunc (with the array)
* NOTE: As of NumPy 2.0 there are inconsistencies in array_power
* calling it would fail a (niche) test because an array is
* returned in one of the fast-paths.
* (once NumPy propagates 0-D arrays, this is irrelevant)
*/
PyObject *res;
if (self == m1) {
res = PyArray_GenericBinaryFunction(m1, other_op, state->n_ops.power);
}
else {
res = PyArray_GenericBinaryFunction(other_op, m2, state->n_ops.power);
}
Py_DECREF(other_op);
return res;
}
else {
assert(other_op == NULL);
Py_RETURN_NOTIMPLEMENTED;
}
}
/**begin repeat
* #TYPE = BYTE, UBYTE, SHORT, USHORT, INT, UINT,
* LONG, ULONG, LONGLONG, ULONGLONG#
* #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint,
* npy_long, npy_ulong, npy_longlong, npy_ulonglong#
* #c = hh, uhh, h, uh,, u, l, ul, ll, ull#
* #Name = Byte, UByte, Short, UShort, Int, UInt,
* Long, ULong, LongLong, ULongLong#
* #convert = Long*8, LongLong*2#
*/
static PyObject *
@type@_bit_count(PyObject *self, PyObject *NPY_UNUSED(args))
{
@type@ scalar = PyArrayScalar_VAL(self, @Name@);
uint8_t count = npy_popcount@c@(scalar);
PyObject *result = PyLong_From@convert@(count);
return result;
}
/**end repeat**/
/**begin repeat
*
* #name = positive, negative, absolute, invert, int, float#
*/
static PyObject *
gentype_@name@(PyObject *m1)
{
PyObject *arr, *ret;
arr = PyArray_FromScalar(m1, NULL);
if (arr == NULL) {
return NULL;
}
ret = Py_TYPE(arr)->tp_as_number->nb_@name@(arr);
Py_DECREF(arr);
return ret;
}
/**end repeat**/
static int
gentype_nonzero_number(PyObject *m1)
{
PyObject *arr;
int ret;
arr = PyArray_FromScalar(m1, NULL);
if (arr == NULL) {
return -1;
}
ret = Py_TYPE(arr)->tp_as_number->nb_bool(arr);
Py_DECREF(arr);
return ret;
}
static PyObject *
genint_type_str(PyObject *self)
{
PyObject *item, *item_str;
PyArray_Descr *dtype = PyArray_DescrFromTypeObject((PyObject *)Py_TYPE(self));
void *val = scalar_value(self, dtype);
switch (dtype->type_num) {
case NPY_BYTE:
item = PyLong_FromLong(*(npy_byte *)val);
break;
case NPY_UBYTE:
item = PyLong_FromUnsignedLong(*(npy_ubyte *)val);
break;
case NPY_SHORT:
item = PyLong_FromLong(*(npy_short *)val);
break;
case NPY_USHORT:
item = PyLong_FromUnsignedLong(*(npy_ushort *)val);
break;
case NPY_INT:
item = PyLong_FromLong(*(npy_int *)val);
break;
case NPY_UINT:
item = PyLong_FromUnsignedLong(*(npy_uint *)val);
break;
case NPY_LONG:
item = PyLong_FromLong(*(npy_long *)val);
break;
case NPY_ULONG:
item = PyLong_FromUnsignedLong(*(npy_ulong *)val);
break;
case NPY_LONGLONG:
item = PyLong_FromLongLong(*(npy_longlong *)val);
break;
case NPY_ULONGLONG:
item = PyLong_FromUnsignedLongLong(*(npy_ulonglong *)val);
break;
default:
item = gentype_generic_vectorcall(self, NULL, 0, NULL,
NPY_SCALAR_METHOD_NAME(item));
break;
}
Py_DECREF(dtype);
if (item == NULL) {
return NULL;
}
item_str = PyObject_Str(item);
Py_DECREF(item);
return item_str;
}
static PyObject *
genint_type_repr(PyObject *self)
{
PyObject *value_string = genint_type_str(self);
if (value_string == NULL) {
return NULL;
}
int legacy_print_mode = get_legacy_print_mode();
if (legacy_print_mode == -1) {
return NULL;
}
if (legacy_print_mode <= 125) {
return value_string;
}
int num = _typenum_fromtypeobj((PyObject *)Py_TYPE(self), 0);
PyObject *repr;
if (num == NPY_NOTYPE) {
/* Not a builtin scalar (presumably), just use the name */
repr = PyUnicode_FromFormat("%s(%S)", Py_TYPE(self)->tp_name, value_string);
Py_DECREF(value_string);
return repr;
}
PyArray_Descr *descr = PyArray_DescrFromType(num); /* cannot fail */
int bitsize = descr->elsize * 8;
Py_DECREF(descr);
if (PyTypeNum_ISUNSIGNED(num)) {
repr = PyUnicode_FromFormat("np.uint%d(%S)", bitsize, value_string);
}
else {
repr = PyUnicode_FromFormat("np.int%d(%S)", bitsize, value_string);
}
Py_DECREF(value_string);
return repr;
}
static PyObject *
genbool_type_str(PyObject *self)
{
return PyUnicode_FromString(
((PyBoolScalarObject *)self)->obval ? "True" : "False");
}
static PyObject *
genbool_type_repr(PyObject *self)
{
int legacy_print_mode = get_legacy_print_mode();
if (legacy_print_mode == -1) {
return NULL;
}
if (legacy_print_mode <= 125) {
return genbool_type_str(self);
}
return PyUnicode_FromString(
((PyBoolScalarObject *)self)->obval ? "np.True_" : "np.False_");
}
/*
* The __format__ method for PEP 3101.
*/
static PyObject *
gentype_format(PyObject *self, PyObject *args)
{
PyObject *format_spec;
PyObject *obj, *ret;
if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) {
return NULL;
}
/*
* Convert to an appropriate Python type and call its format.
* TODO: For some types, like long double, this isn't right,
* because it throws away precision.
*/
if (Py_TYPE(self) == &PyBoolArrType_Type) {
obj = PyBool_FromLong(PyArrayScalar_VAL(self, Bool));
}
else if (PyArray_IsScalar(self, Integer)
&& !PyArray_IsScalar(self, Timedelta)) {
obj = Py_TYPE(self)->tp_as_number->nb_int(self);
}
else if (PyArray_IsScalar(self, Floating)) {
obj = Py_TYPE(self)->tp_as_number->nb_float(self);
}
else if (PyArray_IsScalar(self, ComplexFloating)) {
double val[2];
PyArray_Descr *dtype = PyArray_DescrFromScalar(self);
if (dtype == NULL) {
return NULL;
}
if (PyArray_CastScalarDirect(self, dtype, &val[0], NPY_CDOUBLE) < 0) {
Py_DECREF(dtype);
return NULL;
}
obj = PyComplex_FromDoubles(val[0], val[1]);
Py_DECREF(dtype);
}
else {
obj = PyObject_Str(self);
}
if (obj == NULL) {
return NULL;
}
ret = PyObject_Format(obj, format_spec);
Py_DECREF(obj);
return ret;
}
#ifdef FORCE_NO_LONG_DOUBLE_FORMATTING
#undef NPY_LONGDOUBLE_FMT
#define NPY_LONGDOUBLE_FMT NPY_DOUBLE_FMT
#endif
/**begin repeat
* #name = half, float, double, longdouble#
* #Name = Half, Float, Double, LongDouble#
* #NAME = HALF, FLOAT, DOUBLE, LONGDOUBLE#
* #type = npy_half, npy_float, npy_double, npy_longdouble#
* #suff = h, f, d, l#
*/
NPY_NO_EXPORT PyObject *
format_@name@(@type@ val, npy_bool scientific,
int precision, int sign, TrimMode trim,
int pad_left, int pad_right, int exp_digits)
{
if (scientific) {
return Dragon4_Scientific_@Name@(&val,
DigitMode_Unique, precision, -1,
sign, trim, pad_left, exp_digits);
}
else {
return Dragon4_Positional_@Name@(&val,
DigitMode_Unique, CutoffMode_TotalLength, precision,
-1, sign, trim, pad_left, pad_right);
}
}
/**end repeat**/
/*
* Over-ride repr and str of array-scalar byte strings to remove NULL bytes and
* then call the corresponding functions of PyBytes_Type to generate the string
*/
/**begin repeat
* #form = repr, str#
*/
#define IS_@form@
static PyObject *
stringtype_@form@(PyObject *self)
{
const npy_char *dptr, *ip;
Py_ssize_t len;
PyObject *new;
PyObject *ret;
ip = PyBytes_AS_STRING(self);
len = PyBytes_GET_SIZE(self);
for(dptr = ip + len - 1; len > 0 && *dptr == 0; len--, dptr--);
new = PyBytes_FromStringAndSize(ip, len);
if (new == NULL) {
return NULL;
}
ret = PyBytes_Type.tp_@form@(new);
Py_DECREF(new);
#ifdef IS_repr
if (ret == NULL) {
return NULL;
}
int legacy_print_mode = get_legacy_print_mode();
if (legacy_print_mode == -1) {
return NULL;
}
if (legacy_print_mode > 125) {
Py_SETREF(ret, PyUnicode_FromFormat("np.bytes_(%S)", ret));
}
#endif /* IS_repr */
return ret;
}
#undef IS_@form@
/**end repeat**/
/*
* Over-ride repr and str of array-scalar strings to remove NULL code points and
* then call the corresponding functions of PyUnicode_Type to generate the string
*/
/**begin repeat
* #form = repr, str#
*/
#define IS_@form@
static PyObject *
unicodetype_@form@(PyObject *self)
{
Py_UCS4 *dptr, *ip;
Py_ssize_t len;
PyObject *new;
PyObject *ret;
/* PyUnicode_READY is called by PyUnicode_GetLength */
len = PyUnicode_GetLength(self);
ip = PyUnicode_AsUCS4Copy(self);
if (ip == NULL) {
return NULL;
}
for(dptr = ip + len - 1; len > 0 && *dptr == 0; len--, dptr--);
new = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, ip, len);
if (new == NULL) {
PyMem_Free(ip);
return NULL;
}
ret = PyUnicode_Type.tp_@form@(new);
Py_DECREF(new);
PyMem_Free(ip);
#ifdef IS_repr
if (ret == NULL) {
return NULL;
}
int legacy_print_mode = get_legacy_print_mode();
if (legacy_print_mode == -1) {
return NULL;
}
if (legacy_print_mode > 125) {
Py_SETREF(ret, PyUnicode_FromFormat("np.str_(%S)", ret));
}
#endif /* IS_repr */
return ret;
}
#undef IS_@form@
/**end repeat**/
/*
* Convert array of bytes to a string representation much like bytes.__repr__,
* but convert all bytes (including ASCII) to the `\x00` notation with
* uppercase hex codes (FF not ff).
*
* Largely copied from _Py_strhex_impl in CPython implementation
*/
static inline PyObject *
_void_to_hex(const char* argbuf, const Py_ssize_t arglen,
const char *schars, const char *bprefix, const char *echars)
{
PyObject *retval;
Py_ssize_t i, j, extrachars, slen;
char *retbuf;
char const *hexdigits = "0123456789ABCDEF";
extrachars = strlen(schars) + strlen(echars);
slen = extrachars + arglen*(2 + strlen(bprefix));
if (arglen > (PY_SSIZE_T_MAX / 2) - extrachars) {
return PyErr_NoMemory();
}
retbuf = (char *)PyMem_Malloc(slen);
if (!retbuf) {
return PyErr_NoMemory();
}
memcpy(retbuf, schars, strlen(schars));
j = strlen(schars);
for (i = 0; i < arglen; i++) {
unsigned char c;
memcpy(&retbuf[j], bprefix, strlen(bprefix));
j += strlen(bprefix);
c = (argbuf[i] >> 4) & 0xf;
retbuf[j++] = hexdigits[c];
c = argbuf[i] & 0xf;
retbuf[j++] = hexdigits[c];
}
memcpy(&retbuf[j], echars, strlen(echars));
retval = PyUnicode_FromStringAndSize(retbuf, slen);
PyMem_Free(retbuf);
return retval;
}
static PyObject *
_void_scalar_to_string(PyObject *obj, int repr) {
multiarray_umath_state *state = _npy_module_state;
if (npy_cache_import_runtime(
"numpy._core.arrayprint", "_void_scalar_to_string",
&state->runtime_imports._void_scalar_to_string) == -1) {
return NULL;
}
PyObject *is_repr = repr ? Py_True : Py_False;
return PyObject_CallFunctionObjArgs(
state->runtime_imports._void_scalar_to_string, obj, is_repr, NULL);
}
static PyObject *
voidtype_repr(PyObject *self)
{
PyVoidScalarObject *s = (PyVoidScalarObject*) self;
if (PyDataType_HASFIELDS(s->descr)) {
/* Python helper checks for the legacy mode printing */
return _void_scalar_to_string(self, 1);
}
int legacy_print_mode = get_legacy_print_mode();
if (legacy_print_mode == -1) {
return NULL;
}
if (legacy_print_mode > 125) {
return _void_to_hex(s->obval, s->descr->elsize, "np.void(b'", "\\x", "')");
}
else {
return _void_to_hex(s->obval, s->descr->elsize, "void(b'", "\\x", "')");
}
}
static PyObject *
voidtype_str(PyObject *self)
{
PyVoidScalarObject *s = (PyVoidScalarObject*) self;
if (PyDataType_HASFIELDS(s->descr)) {
return _void_scalar_to_string(self, 0);
}
return _void_to_hex(s->obval, s->descr->elsize, "b'", "\\x", "'");
}
static PyObject *
datetimetype_repr(PyObject *self)
{
PyDatetimeScalarObject *scal;
npy_datetimestruct dts;
PyObject *ret;
char iso[NPY_DATETIME_MAX_ISO8601_STRLEN];
NPY_DATETIMEUNIT unit;
if (!PyArray_IsScalar(self, Datetime)) {
PyErr_SetString(PyExc_RuntimeError,
"Called NumPy datetime repr on a non-datetime type");
return NULL;
}
scal = (PyDatetimeScalarObject *)self;
if (NpyDatetime_ConvertDatetime64ToDatetimeStruct(&scal->obmeta,
scal->obval, &dts) < 0) {
return NULL;
}
unit = scal->obmeta.base;
if (NpyDatetime_MakeISO8601Datetime(&dts, iso, sizeof(iso), 0, 0,
unit, -1, NPY_SAFE_CASTING) < 0) {
return NULL;
}
/*
* For straight units or generic units, the unit will be deduced
* from the string, so it's not necessary to specify it.
*/
if ((scal->obmeta.num == 1 && scal->obmeta.base != NPY_FR_h) ||
scal->obmeta.base == NPY_FR_GENERIC) {
int legacy_print_mode = get_legacy_print_mode();
if (legacy_print_mode == -1) {
return NULL;
}
PyObject *meta = metastr_to_unicode(&scal->obmeta, 1);
if((scal->obval == NPY_DATETIME_NAT) && (meta != NULL)){
if (legacy_print_mode > 125) {
ret = PyUnicode_FromFormat("np.datetime64('%s','%S')", iso, meta);
} else {
ret = PyUnicode_FromFormat("numpy.datetime64('%s','%S')", iso, meta);
}
} else {
if (legacy_print_mode > 125) {
ret = PyUnicode_FromFormat("np.datetime64('%s')", iso);
}
else {
ret = PyUnicode_FromFormat("numpy.datetime64('%s')", iso);
}
}
Py_DECREF(meta);
}
else {
PyObject *meta = metastr_to_unicode(&scal->obmeta, 1);
if (meta == NULL) {
return NULL;
}
int legacy_print_mode = get_legacy_print_mode();
if (legacy_print_mode == -1) {
return NULL;
}
if (legacy_print_mode > 125) {
ret = PyUnicode_FromFormat("np.datetime64('%s','%S')", iso, meta);
}
else {
ret = PyUnicode_FromFormat("numpy.datetime64('%s','%S')", iso, meta);
}
Py_DECREF(meta);
}
return ret;
}
static PyObject *
timedeltatype_repr(PyObject *self)
{
PyTimedeltaScalarObject *scal;
PyObject *val, *ret;
if (!PyArray_IsScalar(self, Timedelta)) {
PyErr_SetString(PyExc_RuntimeError,
"Called NumPy timedelta repr on a non-datetime type");
return NULL;
}
scal = (PyTimedeltaScalarObject *)self;
/* The value */
if (scal->obval == NPY_DATETIME_NAT) {
val = PyUnicode_FromString("'NaT'");
}