-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path_arraykit.c
More file actions
4588 lines (4143 loc) · 147 KB
/
_arraykit.c
File metadata and controls
4588 lines (4143 loc) · 147 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
# include "Python.h"
# include "structmember.h"
# include "stdbool.h"
# include "limits.h"
// # include "stdlib.h"
# define PY_ARRAY_UNIQUE_SYMBOL AK_ARRAY_API
# define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
# include "numpy/arrayobject.h"
# include "numpy/arrayscalars.h"
# include "numpy/halffloat.h"
//------------------------------------------------------------------------------
// Macros
//------------------------------------------------------------------------------
// Given a PyObject, raise if not an array.
# define AK_CHECK_NUMPY_ARRAY(O) \
if (!PyArray_Check(O)) { \
return PyErr_Format(PyExc_TypeError, "expected numpy array (got %s)", \
Py_TYPE(O)->tp_name); \
}
// Given a PyObject, raise if not an array or is not one or two dimensional.
# define AK_CHECK_NUMPY_ARRAY_1D_2D(O) \
do {\
AK_CHECK_NUMPY_ARRAY(O)\
int ndim = PyArray_NDIM((PyArrayObject *)O);\
if (ndim != 1 && ndim != 2) {\
return PyErr_Format(PyExc_NotImplementedError,\
"expected 1D or 2D array (got %i)",\
ndim);\
}\
} while (0)
// Placeholder of not implemented pathways / debugging.
# define AK_NOT_IMPLEMENTED(msg)\
do {\
PyErr_SetString(PyExc_NotImplementedError, msg);\
return NULL;\
} while (0)
# define _AK_DEBUG_BEGIN() \
do { \
fprintf(stderr, "--- %s: %i: %s: ", __FILE__, __LINE__, __FUNCTION__);
# define _AK_DEBUG_END() \
fprintf(stderr, "\n"); \
fflush(stderr); \
} while (0)
# define AK_DEBUG_MSG_OBJ(msg, obj) \
_AK_DEBUG_BEGIN(); \
fprintf(stderr, #msg " "); \
PyObject_Print(obj, stderr, 0); \
_AK_DEBUG_END()
# define AK_DEBUG_OBJ(obj) \
_AK_DEBUG_BEGIN(); \
fprintf(stderr, #obj " = "); \
PyObject_Print(obj, stderr, 0); \
_AK_DEBUG_END()
# define AK_DEBUG(msg) \
_AK_DEBUG_BEGIN(); \
fprintf(stderr, #msg); \
_AK_DEBUG_END()
# if defined __GNUC__ || defined __clang__
# define AK_LIKELY(X) __builtin_expect(!!(X), 1)
# define AK_UNLIKELY(X) __builtin_expect(!!(X), 0)
# else
# define AK_LIKELY(X) (!!(X))
# define AK_UNLIKELY(X) (!!(X))
# endif
//------------------------------------------------------------------------------
// C-level utility functions
//------------------------------------------------------------------------------
// Takes and returns a PyArrayObject, optionally copying a mutable array and setting it as immutable
PyArrayObject *
AK_ImmutableFilter(PyArrayObject *a)
{
// https://numpy.org/devdocs/reference/c-api/array.html#array-flags
if (PyArray_FLAGS(a) & NPY_ARRAY_WRITEABLE) {
if ((a = (PyArrayObject *)PyArray_NewCopy(a, NPY_ANYORDER))) {
PyArray_CLEARFLAGS(a, NPY_ARRAY_WRITEABLE);
}
return a;
}
Py_INCREF(a);
return a;
}
PyArray_Descr*
AK_ResolveDTypes(PyArray_Descr *d1, PyArray_Descr *d2)
{
if (PyArray_EquivTypes(d1, d2)) {
Py_INCREF(d1);
return d1;
}
if (PyDataType_ISOBJECT(d1) || PyDataType_ISOBJECT(d2)
|| PyDataType_ISBOOL(d1) || PyDataType_ISBOOL(d2)
|| (PyDataType_ISSTRING(d1) != PyDataType_ISSTRING(d2))
|| ((PyDataType_ISDATETIME(d1) || PyDataType_ISDATETIME(d2))
// PyDataType_ISDATETIME matches NPY_DATETIME or NPY_TIMEDELTA, so
// we need to make sure we didn't get one of each:
&& !PyArray_EquivTypenums(d1->type_num, d2->type_num)))
{
return PyArray_DescrFromType(NPY_OBJECT);
}
PyArray_Descr *d = PyArray_PromoteTypes(d1, d2);
if (!d) {
PyErr_Clear();
return PyArray_DescrFromType(NPY_OBJECT);
}
return d;
}
PyArray_Descr*
AK_ResolveDTypeIter(PyObject *dtypes)
{
PyObject *iterator = PyObject_GetIter(dtypes);
if (iterator == NULL) {
// No need to set exception here. GetIter already sets TypeError
return NULL;
}
PyArray_Descr *resolved = NULL;
PyArray_Descr *dtype;
while ((dtype = (PyArray_Descr*) PyIter_Next(iterator))) {
if (!PyArray_DescrCheck(dtype)) {
PyErr_Format(
PyExc_TypeError, "argument must be an iterable over %s, not %s",
((PyTypeObject *) &PyArrayDescr_Type)->tp_name,
Py_TYPE(dtype)->tp_name
);
Py_DECREF(iterator);
Py_DECREF(dtype);
Py_XDECREF(resolved);
return NULL;
}
if (!resolved) {
resolved = dtype;
continue;
}
Py_SETREF(resolved, AK_ResolveDTypes(resolved, dtype));
Py_DECREF(dtype);
if (!resolved || PyDataType_ISOBJECT(resolved)) {
break;
}
}
Py_DECREF(iterator);
if (PyErr_Occurred()) {
return NULL;
}
if (!resolved) {
// this could happen if this function gets an empty tuple
PyErr_SetString(PyExc_ValueError, "iterable passed to resolve dtypes is empty");
}
return resolved;
}
// Perform a deepcopy on an array, using an optional memo dictionary, and specialized to depend on immutable arrays. This depends on the module object to get the deepcopy method.
PyObject*
AK_ArrayDeepCopy(PyObject* m, PyArrayObject *array, PyObject *memo)
{
PyObject *id = PyLong_FromVoidPtr((PyObject*)array);
if (!id) return NULL;
if (memo) {
PyObject *found = PyDict_GetItemWithError(memo, id);
if (found) { // found will be NULL if not in dict
Py_INCREF(found); // got a borrowed ref, increment first
Py_DECREF(id);
return found;
}
else if (PyErr_Occurred()) {
goto error;
}
}
// if dtype is object, call deepcopy with memo
PyObject *array_new;
PyArray_Descr *dtype = PyArray_DESCR(array); // borrowed ref
if (PyDataType_ISOBJECT(dtype)) {
PyObject *deepcopy = PyObject_GetAttrString(m, "deepcopy");
if (!deepcopy) {
goto error;
}
array_new = PyObject_CallFunctionObjArgs(deepcopy, array, memo, NULL);
Py_DECREF(deepcopy);
if (!array_new) {
goto error;
}
}
else {
// if not a n object dtype, we will force a copy (even if this is an immutable array) so as to not hold on to any references
Py_INCREF(dtype); // PyArray_FromArray steals a reference
array_new = PyArray_FromArray(
array,
dtype,
NPY_ARRAY_ENSURECOPY);
if (!array_new) {
goto error;
}
if (memo && PyDict_SetItem(memo, id, array_new)) {
Py_DECREF(array_new);
goto error;
}
}
// set immutable
PyArray_CLEARFLAGS((PyArrayObject *)array_new, NPY_ARRAY_WRITEABLE);
Py_DECREF(id);
return array_new;
error:
Py_DECREF(id);
return NULL;
}
// Given a dtype_specifier, which might be a dtype, NULL, or None, assign a fresh dtype object (or NULL) to dtype_returned. Returns 0 on success, -1 on failure. This will not interpret a None dtype_specified as a float dtype. This will never set dtype_returned to None (only NULL). Returns a new reference.
static inline int
AK_DTypeFromSpecifier(PyObject *dtype_specifier, PyArray_Descr **dtype_returned)
{
PyArray_Descr* dtype;
if (dtype_specifier == NULL) {
dtype = NULL; // propagate, cannot call into oncverter
}
else if (PyObject_TypeCheck(dtype_specifier, &PyArrayDescr_Type)) {
dtype = (PyArray_Descr* )dtype_specifier;
}
else { // converter2 sets NULL for None
PyArray_DescrConverter2(dtype_specifier, &dtype);
}
// if not NULL, make a copy as we will give ownership to array and might mutate
if (dtype) {
dtype = PyArray_DescrNew(dtype);
if (dtype == NULL) return -1;
}
*dtype_returned = dtype;
return 0;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#define AK_is_digit(c) (((unsigned)(c) - '0') < 10u)
#define AK_is_space(c) (((c) == ' ') || (((unsigned)(c) - '\t') < 5))
#define AK_is_quote(c) (((c) == '"') || ((c) == '\''))
#define AK_is_sign(c) (((c) == '+') || ((c) == '-'))
#define AK_is_paren_open(c) ((c) == '(')
#define AK_is_paren_close(c) ((c) == ')')
#define AK_is_a(c) (((c) == 'a') || ((c) == 'A'))
#define AK_is_e(c) (((c) == 'e') || ((c) == 'E'))
#define AK_is_f(c) (((c) == 'f') || ((c) == 'F'))
#define AK_is_i(c) (((c) == 'i') || ((c) == 'I'))
#define AK_is_j(c) (((c) == 'j') || ((c) == 'J'))
#define AK_is_l(c) (((c) == 'l') || ((c) == 'L'))
#define AK_is_n(c) (((c) == 'n') || ((c) == 'N'))
#define AK_is_r(c) (((c) == 'r') || ((c) == 'R'))
#define AK_is_s(c) (((c) == 's') || ((c) == 'S'))
#define AK_is_t(c) (((c) == 't') || ((c) == 'T'))
#define AK_is_u(c) (((c) == 'u') || ((c) == 'U'))
//------------------------------------------------------------------------------
// Utility setters of C types from possibly NULL PyObject*; all return -1 on error.
static int
AK_set_bool(const char *name,
bool *target,
PyObject *src,
bool dflt)
{
if (src == NULL)
*target = dflt;
else {
int b = PyObject_IsTrue(src);
if (b < 0) return -1;
*target = (char)b;
}
return 0;
}
static int
AK_set_int(const char *name,
int *target,
PyObject *src,
int dflt)
{
if (src == NULL)
*target = dflt;
else {
if (!PyLong_CheckExact(src)) {
PyErr_Format(PyExc_TypeError, "\"%s\" must be an integer", name);
return -1;
}
long value = PyLong_AsLong(src);
if (value == -1 && PyErr_Occurred()) {
return -1;
}
if (value < INT_MIN || value > INT_MAX) {
PyErr_Format(PyExc_TypeError, "\"%s\" overflowed integer", name);
return -1;
}
*target = (int)value;
}
return 0;
}
// Set a character from `src` on `target`; if src is NULL use default. Returns -1 on error, else 0.
static int
AK_set_char(const char *name,
Py_UCS4 *target,
PyObject *src,
Py_UCS4 dflt)
{
if (src == NULL)
*target = dflt;
else {
*target = '\0';
if (src != Py_None) {
Py_ssize_t len;
if (!PyUnicode_Check(src)) {
PyErr_Format(PyExc_TypeError,
"\"%s\" must be string, not %.200s",
name,
Py_TYPE(src)->tp_name);
return -1;
}
len = PyUnicode_GetLength(src);
if (len > 1) {
PyErr_Format(PyExc_TypeError,
"\"%s\" must be a 1-character string",
name);
return -1;
}
if (len > 0)
*target = PyUnicode_READ_CHAR(src, 0);
}
}
return 0;
}
//------------------------------------------------------------------------------
// TypeParser: Type, New, Destructor
// This defines the observed type of each field, or an entire line of fields. Note that TPS_STRING serves as the last resort, the type that needs no conversion (or cannot be converted).
typedef enum AK_TypeParserState {
TPS_UNKNOWN, // for initial state
TPS_BOOL,
TPS_INT,
TPS_FLOAT,
TPS_COMPLEX, // 4
TPS_STRING,
TPS_EMPTY // empty fields
} AK_TypeParserState;
// Given previous and new parser states, return a next parser state. Does not error.
AK_TypeParserState
AK_TPS_Resolve(AK_TypeParserState previous, AK_TypeParserState new) {
// unlikely case
if (new == TPS_UNKNOWN) return TPS_STRING;
// propagate new if previous is unknown or empty
if ((previous == TPS_UNKNOWN) || (previous == TPS_EMPTY)) return new;
// if either are string, go to string
if (previous == TPS_STRING || new == TPS_STRING) return TPS_STRING;
// handle both new, previous bool directly
if (previous == TPS_BOOL) {
if (new == TPS_EMPTY || new == TPS_BOOL) return TPS_BOOL;
else {return TPS_STRING;} // bool found with anything except empty is string
}
if (new == TPS_BOOL) {
if (previous == TPS_EMPTY) return TPS_BOOL;
else return TPS_STRING; // bool found with anything except empty is string
}
// numerical promotion
if (previous == TPS_INT) {
if (new == TPS_EMPTY || new == TPS_INT) return TPS_INT;
if (new == TPS_FLOAT) return TPS_FLOAT;
if (new == TPS_COMPLEX) return TPS_COMPLEX;
}
if (previous == TPS_FLOAT) {
if (new == TPS_EMPTY || new == TPS_INT || new == TPS_FLOAT) return TPS_FLOAT;
if (new == TPS_COMPLEX) return TPS_COMPLEX;
}
// previous == TPS_COMPLEX, new is TPS_EMPTY, TPS_INT, TPS_FLOAT, or TPS_COMPLEX
return TPS_COMPLEX;
}
// Given a TypeParser state, return a dtype. Returns NULL on error.
PyArray_Descr*
AK_TPS_ToDtype(AK_TypeParserState state) {
PyArray_Descr *dtype = NULL;
switch (state) {
case TPS_UNKNOWN:
dtype = PyArray_DescrNewFromType(NPY_UNICODE);
break;
case TPS_EMPTY: // all empty defaults to string
dtype = PyArray_DescrNewFromType(NPY_UNICODE);
break;
case TPS_STRING:
dtype = PyArray_DescrNewFromType(NPY_UNICODE);
break;
case TPS_BOOL:
dtype = PyArray_DescrNewFromType(NPY_BOOL);
break;
case TPS_INT:
dtype = PyArray_DescrNewFromType(NPY_INT64);
break;
case TPS_FLOAT:
dtype = PyArray_DescrNewFromType(NPY_FLOAT64);
break;
case TPS_COMPLEX:
dtype = PyArray_DescrNewFromType(NPY_COMPLEX128);
break;
}
if (dtype == NULL) return NULL; // assume error is set by PyArray_DescrFromType
return dtype;
}
//------------------------------------------------------------------------------
// An AK_TypeParser accumulates the state in parsing a single code point line. It holds both "active" state in the progress of parsing each field as well as finalized state in parsed_line
typedef struct AK_TypeParser {
bool previous_numeric;
bool contiguous_numeric;
bool contiguous_leading_space;
// counting will always stop before 8 or less
npy_int8 count_bool;
npy_int8 count_sign;
npy_int8 count_e;
npy_int8 count_j;
npy_int8 count_decimal;
npy_int8 count_nan;
npy_int8 count_inf;
npy_int8 count_paren_open;
npy_int8 count_paren_close;
// bound by number of chars in field
Py_ssize_t last_sign_pos; // signed
Py_ssize_t count_leading_space;
Py_ssize_t count_digit;
Py_ssize_t count_not_space;
AK_TypeParserState parsed_field; // state of current field
AK_TypeParserState parsed_line; // state of current resolved line type
Py_UCS4 tsep;
Py_UCS4 decc;
} AK_TypeParser;
// Initialize all state. This returns no error. This is called once per field for each field in a code point line: this is why parsed_field is reset, but parsed_line is not.
void AK_TP_reset_field(AK_TypeParser* tp)
{
tp->previous_numeric = false;
tp->contiguous_numeric = false;
tp->contiguous_leading_space = false;
tp->count_bool = 0;
tp->count_sign = 0;
tp->count_e = 0;
tp->count_j = 0;
tp->count_decimal = 0;
tp->count_nan = 0;
tp->count_inf = 0;
tp->count_paren_open = 0;
tp->count_paren_close = 0;
tp->last_sign_pos = -1;
tp->count_leading_space = 0;
tp->count_digit = 0;
tp->count_not_space = 0;
tp->parsed_field = TPS_UNKNOWN;
// NOTE: do not reset parsed_line
}
AK_TypeParser*
AK_TP_New(Py_UCS4 tsep, Py_UCS4 decc)
{
AK_TypeParser *tp = (AK_TypeParser*)PyMem_Malloc(sizeof(AK_TypeParser));
if (tp == NULL) return (AK_TypeParser*)PyErr_NoMemory();
AK_TP_reset_field(tp);
tp->parsed_line = TPS_UNKNOWN;
tp->tsep = tsep; // take tsep into context for auto eval?
tp->decc = decc;
return tp;
}
void
AK_TP_Free(AK_TypeParser* tp)
{
PyMem_Free(tp);
}
//------------------------------------------------------------------------------
// Given a type parse, process a single character and update the type parser state in `parsed_field`. Return true when processing should continue, false when no further processing is necessary. `pos` is the raw position within the current field.
bool
AK_TP_ProcessChar(AK_TypeParser* tp,
Py_UCS4 c,
Py_ssize_t pos)
{
if (tp->parsed_field != TPS_UNKNOWN) {
// if parsed_field is set to anything other than TPS_UNKNOWN, we should not be calling process_char anymore
Py_UNREACHABLE();
}
// evaluate space ..........................................................
bool space = false;
if (AK_is_space(c)) {
if (pos == 0) {
tp->contiguous_leading_space = true;
}
if (tp->contiguous_leading_space) {
++tp->count_leading_space;
return true;
}
space = true;
}
else if (AK_is_quote(c)) {
// any quote, leading or otherwise, defines a string
tp->parsed_field = TPS_STRING;
return false;
}
else if (AK_is_paren_open(c)) {
++tp->count_paren_open;
++tp->count_leading_space;
space = true;
// open paren permitted only in first non-space position
if ((pos > 0 && !tp->contiguous_leading_space) || tp->count_paren_open > 1) {
tp->parsed_field = TPS_STRING;
return false;
}
}
else if (AK_is_paren_close(c)) {
++tp->count_paren_close;
space = true;
// NOTE: might evaluate if previous is contiguous numeric
if (tp->count_paren_close > 1) {
tp->parsed_field = TPS_STRING;
return false;
}
}
else {
++tp->count_not_space;
}
// no longer in contiguous leading space
tp->contiguous_leading_space = false;
// pos_field defines the position within the field less leading space
Py_ssize_t pos_field = pos - tp->count_leading_space;
// evaluate numeric, non-positional ........................................
bool numeric = false;
bool digit = false;
if (space) {}
else if (AK_is_digit(c)) {
++tp->count_digit;
digit = true;
numeric = true;
}
else if (c == tp->decc) { // is decimal
++tp->count_decimal;
if (tp->count_decimal > 2) { // complex can have 2
tp->parsed_field = TPS_STRING;
return false;
}
numeric = true;
}
else if (AK_is_sign(c)) {
++tp->count_sign;
if (tp->count_sign > 4) { // complex can have 4
tp->parsed_field = TPS_STRING;
return false;
}
tp->last_sign_pos = pos_field;
numeric = true;
}
else if (AK_is_e(c)) {
++tp->count_e;
if ((pos_field == 0) || (tp->count_e > 2)) {
// can never lead field; true or false have one E; complex can have 2
tp->parsed_field = TPS_STRING;
return false;
}
numeric = true;
}
else if (AK_is_j(c)) {
++tp->count_j;
if ((pos_field == 0) || (tp->count_j > 1)) {
// can never lead field; complex can have 1
tp->parsed_field = TPS_STRING;
return false;
}
numeric = true;
}
// evaluate contiguous numeric .............................................
if (numeric) {
if (pos_field == 0) {
tp->contiguous_numeric = true;
tp->previous_numeric = true;
}
if (!tp->previous_numeric) {
tp->contiguous_numeric = false;
}
tp->previous_numeric = true; // this char is numeric for next eval
}
else { // not numeric
// only mark as not contiguous_numeric if non space as might be trailing space
if (tp->contiguous_numeric && !space) {
tp->contiguous_numeric = false;
}
tp->previous_numeric = false;
}
// evaluate character positions ............................................
if (space || digit) {
return true;
}
if (tp->last_sign_pos >= 0) { // initialized to -1
pos_field -= tp->last_sign_pos + 1;
}
// given relative positions `pos_field`, map to known character sequences
switch (pos_field) {
case 0:
if (AK_is_t(c)) {++tp->count_bool;}
else if (AK_is_f(c)) {--tp->count_bool;}
else if (AK_is_n(c)) {++tp->count_nan;}
else if (AK_is_i(c)) {++tp->count_inf;}
else if (!numeric) { // if not decimal, sign, e, j
tp->parsed_field = TPS_STRING;
return false;
}
break;
case 1:
if (AK_is_r(c)) {++tp->count_bool;} // true
else if (AK_is_a(c)) {
--tp->count_bool; // false
++tp->count_nan;
}
else if (AK_is_n(c)) {++tp->count_inf;}
else if (!numeric) {
tp->parsed_field = TPS_STRING;
return false;
}
break;
case 2:
if (AK_is_u(c)) {++tp->count_bool;}
else if (AK_is_l(c)) {--tp->count_bool;}
else if (AK_is_n(c)) {++tp->count_nan;}
else if (AK_is_f(c)) {++tp->count_inf;}
else if (!numeric) {
tp->parsed_field = TPS_STRING;
return false;
}
break;
case 3:
if (AK_is_e(c)) {++tp->count_bool;} // true
else if (AK_is_s(c)) {--tp->count_bool;} // false
else if (!numeric) {
tp->parsed_field = TPS_STRING;
return false;
}
break;
case 4:
if (AK_is_e(c)) {--tp->count_bool;} // false
else if (!numeric) {
tp->parsed_field = TPS_STRING;
return false;
}
break;
default: // character positions > 4
if (!numeric) {
tp->parsed_field = TPS_STRING;
return false;
}
}
return true; // continue processing
}
// This private function is used by AK_TP_ResolveLineResetField to evaluate the state of the AK_TypeParser and determine the resolved AK_TypeParserState.
AK_TypeParserState
AK_TP_resolve_field(AK_TypeParser* tp,
Py_ssize_t count)
{
if (count == 0) return TPS_EMPTY;
// if parsed_field is known, return it
if (tp->parsed_field != TPS_UNKNOWN) return tp->parsed_field;
if (tp->count_bool == 4 && tp->count_not_space == 4) {
return TPS_BOOL;
}
if (tp->count_bool == -5 && tp->count_not_space == 5) {
return TPS_BOOL;
}
if (tp->contiguous_numeric) {
if (tp->count_digit == 0) return TPS_STRING;
// int
if (tp->count_j == 0 &&
tp->count_sign <= 1 &&
tp->last_sign_pos <= 0 &&
tp->count_decimal == 0 &&
tp->count_e == 0 &&
tp->count_paren_close == 0 &&
tp->count_paren_open == 0 &&
tp->count_nan == 0 &&
tp->count_inf == 0) {
return TPS_INT;
}
// float
if (tp->count_j == 0 &&
tp->count_sign <= 2 &&
tp->count_paren_close == 0 &&
tp->count_paren_open == 0 &&
(tp->count_decimal == 1 || tp->count_e == 1)
) {
if (tp->count_sign == 2 && tp->count_e == 0) {
return TPS_STRING;
}
return TPS_FLOAT;
}
// complex with j
if ((tp->count_j == 1) &&
((tp->count_paren_close == 0 && tp->count_paren_open == 0) ||
(tp->count_paren_close == 1 && tp->count_paren_open == 1))
) {
if (tp->count_sign > 2 + tp->count_e) {
return TPS_STRING;
}
return TPS_COMPLEX;
}
// complex with parens (no j)
if (tp->count_j == 0 &&
tp->count_paren_close == 1 &&
tp->count_paren_open == 1
) {
if (tp->count_sign > 2 && tp->count_e > 1) {
return TPS_STRING;
}
return TPS_COMPLEX;
}
}
// non contiguous numeric cases
else if (tp->count_j == 0) {
if (tp->count_nan == 3 && tp->count_sign + tp->count_nan == tp->count_not_space) {
return TPS_FLOAT;
}
if (tp->count_inf == 3 && tp->count_sign + tp->count_inf == tp->count_not_space) {
return TPS_FLOAT;
}
}
else if (tp->count_j == 1) {
Py_ssize_t count_numeric = (tp->count_sign +
tp->count_decimal +
tp->count_e +
tp->count_j +
tp->count_digit);
// one inf and one nan
if (tp->count_nan == 3 && tp->count_inf == 3 &&
tp->count_sign + 7 == tp->count_not_space) {
return TPS_COMPLEX;
}
// one nan one number
if (tp->count_nan == 3 &&
tp->count_nan + count_numeric == tp->count_not_space) {
return TPS_COMPLEX;
}
// two nans
if (tp->count_nan == 6 &&
tp->count_sign + tp->count_nan + 1 == tp->count_not_space) {
return TPS_COMPLEX;
}
// one inf one number
if (tp->count_inf == 3 &&
tp->count_inf + count_numeric == tp->count_not_space) {
return TPS_COMPLEX;
}
// two infs
if (tp->count_inf == 6 &&
tp->count_sign + tp->count_inf + 1 == tp->count_not_space) {
return TPS_COMPLEX;
}
}
return TPS_STRING; // default
}
// After field is complete, call AK_TP_ResolveLineResetField to evaluate and set the current parsed_line. All TypeParse field attributes are reset after this is called. Returns true if the line still needs to be evaluated.
bool
AK_TP_ResolveLineResetField(AK_TypeParser* tp,
Py_ssize_t count)
{
if (tp->parsed_line != TPS_STRING) {
// resolve with previous parsed_line (or unkown if just initialized)
tp->parsed_line = AK_TPS_Resolve(tp->parsed_line, AK_TP_resolve_field(tp, count));
}
AK_TP_reset_field(tp);
// if string, return false to stop further line processing
return tp->parsed_line != TPS_STRING;
}
//------------------------------------------------------------------------------
// UCS4 array processors
static char* TRUE_LOWER = "true";
static char* TRUE_UPPER = "TRUE";
#define ERROR_NO_DIGITS 1
#define ERROR_OVERFLOW 2
#define ERROR_INVALID_CHARS 3
// Convert a Py_UCS4 array to a signed integer. Extended from pandas/_libs/src/parser/tokenizer.c. Sets `error` to values greater than 0 on error; never sets error on success.
static inline npy_int64
AK_UCS4_to_int64(Py_UCS4 *p_item, Py_UCS4 *end, int *error, char tsep)
{
npy_int64 int_min = NPY_MIN_INT64;
npy_int64 int_max = NPY_MAX_INT64;
int isneg = 0;
npy_int64 number = 0;
int d;
Py_UCS4 *p = p_item;
while (AK_is_space(*p)) {
++p;
if (p >= end) return number; // NOTE: this means that all space will return zero without error
}
if (*p == '-') {
isneg = 1;
++p;
} else if (*p == '+') {
++p;
}
if (p >= end) return number;
// Check that there is a first digit.
if (!AK_is_digit(*p)) {
*error = ERROR_NO_DIGITS;
return 0;
}
if (isneg) {
// If number is greater than pre_min, at least one more digit can be processed without overflowing.
int dig_pre_min = -(int_min % 10);
npy_int64 pre_min = int_min / 10;
d = *p;
if (tsep != '\0') {
while (1) {
if (d == tsep) {
++p;
if (p >= end) return number;
d = *p;
continue;
} else if (!AK_is_digit(d)) {
break;
}
if ((number > pre_min) ||
((number == pre_min) && (d - '0' <= dig_pre_min))) {
number = number * 10 - (d - '0');
++p;
if (p >= end) return number;
d = *p;
} else {
*error = ERROR_OVERFLOW;
return 0;
}
}
} else {
while (AK_is_digit(d)) {
if ((number > pre_min) ||
((number == pre_min) && (d - '0' <= dig_pre_min))) {
number = number * 10 - (d - '0');
++p;
if (p >= end) return number;
d = *p;
} else {
*error = ERROR_OVERFLOW;
return 0;
}
}
}
} else {
// If number is less than pre_max, at least one more digit can be processed without overflowing.
npy_int64 pre_max = int_max / 10;
int dig_pre_max = int_max % 10;
d = *p;
if (tsep != '\0') {
while (1) {
if (d == tsep) {
++p;
if (p >= end) return number;
d = *p;
continue;
} else if (!AK_is_digit(d)) {
break;
}
if ((number < pre_max) ||
((number == pre_max) && (d - '0' <= dig_pre_max))) {
number = number * 10 + (d - '0');
++p;
if (p >= end) return number;
d = *p;
} else {
*error = ERROR_OVERFLOW;
return 0;
}
}
} else {
while (AK_is_digit(d)) {
if ((number < pre_max) ||
((number == pre_max) && (d - '0' <= dig_pre_max))) {
number = number * 10 + (d - '0');
++p;
if (p >= end) return number;
d = *p;
} else {
*error = ERROR_OVERFLOW;
return 0;
}
}
}
}
while (p < end) {
if (!AK_is_space(*p)) {
*error = ERROR_INVALID_CHARS;
return 0;
}
p++;
}
return number;
}
// Convert a Py_UCS4 array to an unsigned integer. Extended from pandas/_libs/src/parser/tokenizer.c. Sets error to > 0 on error; never sets error on success.
static inline npy_uint64
AK_UCS4_to_uint64(Py_UCS4 *p_item, Py_UCS4 *end, int *error, char tsep)
{
npy_uint64 pre_max = NPY_MAX_UINT64 / 10;
npy_uint64 number = 0;
int dig_pre_max = NPY_MAX_UINT64 % 10;
int d;
Py_UCS4 *p = p_item;
while (AK_is_space(*p)) {
++p;
if (p >= end) return number;
}
if (*p == '-') {
*error = ERROR_INVALID_CHARS;
return 0;
} else if (*p == '+') {
p++;
if (p >= end) return number;
}
// Check that there is a first digit.
if (!AK_is_digit(*p)) {
*error = ERROR_NO_DIGITS;
return 0;
}
// If number is less than pre_max, at least one more digit can be processed without overflowing.
d = *p;
if (tsep != '\0') {
while (1) {
if (d == tsep) {
++p;
if (p >= end) return number;
d = *p;
continue;
} else if (!AK_is_digit(d)) {
break;
}
if ((number < pre_max) ||
((number == pre_max) && (d - '0' <= dig_pre_max))) {
number = number * 10 + (d - '0');
++p;
if (p >= end) return number;
d = *p;
} else {
*error = ERROR_OVERFLOW;
return 0;
}
}
} else {
while (AK_is_digit(d)) {
if ((number < pre_max) ||
((number == pre_max) && (d - '0' <= dig_pre_max))) {
number = number * 10 + (d - '0');
++p;