Repository navigation
Expand file tree
/
Copy pathvm.c
More file actions
1698 lines (1558 loc) · 60.1 KB
/
Copy pathvm.c
File metadata and controls
1698 lines (1558 loc) · 60.1 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 <pynter/config.h>
#include <math.h>
#include <inttypes.h>
#include <stdbool.h>
#include <string.h>
#include <pynter.h>
#include <pynter/opcode.h>
#include <pynter/fault.h>
#include <pynter/nanbox.h>
#include <pynter/heap.h>
#include <pynter/heap_obj.h>
#include <pynter/vm.h>
#include <pynter/stack.h>
#include <pynter/debug.h>
#include <pynter/program.h>
struct sistate sistate;
const sivmfnptr_t *sivmfn_vminternals = NULL;
size_t sivmfn_vminternal_count = 0;
pynter_printfn_string pynter_printer_string = NULL;
pynter_printfn_integer pynter_printer_integer = NULL;
pynter_printfn_float pynter_printer_float = NULL;
pynter_printfn_flush pynter_printer_flush = NULL;
#if 0
static inline void unimpl_instr() {
SIBUGV("Unimplemented instruction %02x at address 0x%tx\n", *sistate.pc, SISTATE_CURADDR);
sifault(pynter_fault_invalid_program);
}
#endif
/**
* Coerces a boolean nanbox to the int (0 or 1) it represents for `==`/`!=`/
* ordering purposes (Python's bool is an int subtype: `True == 1` is true).
* Every other type passes through unchanged.
*
* Deliberately NOT used by `is`/`is not` (op_eq_p/op_neq_p below): identity
* must keep bool and int distinct types (`1 is True` is false), unlike `==`.
*/
static inline sinanbox_t nanbox_int_if_bool(sinanbox_t v) {
return NANBOX_ISBOOL(v) ? NANBOX_OFINT(NANBOX_BOOL(v)) : v;
}
// Nanbox-level convenience over siheap_is_complex (heap_obj.h) — shared with
// primitives.c, which checks the same predicate for is_complex()/real()/
// imag()/abs().
static inline bool sivm_is_complex(sinanbox_t v) {
return NANBOX_ISPTR(v) && siheap_is_complex((siheap_header_t *) SIHEAP_NANBOXTOPTR(v));
}
/**
* Promotes a plain numeric (int/float) or complex value into a (real, imag)
* pair — used by every arithmetic/equality opcode's complex branch to treat
* a mixed int/float/complex operand pair uniformly, matching Python's
* numeric tower (int|float|complex) @ complex -> complex, per
* docs/specs/python_typing.tex. Returns false (outputs untouched) for
* anything else. `NANBOX_ISNUMERIC` alone doesn't cover `bool` (a distinct
* nanbox tag) — that's fine here, since none of the plain-arithmetic
* opcodes this feeds into (op_add_g etc.) coerce bool either; only
* op_eq_g/op_neq_g's shared macro already applies `nanbox_int_if_bool` to
* its operands before calling sivm_equal, so by the time this runs there a
* bool has already become a plain int.
*/
static inline bool sivm_numeric_to_complex_parts(sinanbox_t v, sifloat_t *out_real, sifloat_t *out_imag) {
if (NANBOX_ISNUMERIC(v)) {
*out_real = NANBOX_TOFLOAT(v);
*out_imag = 0.0;
return true;
}
if (sivm_is_complex(v)) {
siheap_complex_t *c = (siheap_complex_t *) SIHEAP_NANBOXTOPTR(v);
*out_real = c->real;
*out_imag = c->imag;
return true;
}
return false;
}
static inline void sivm_push_complex_result(sifloat_t real, sifloat_t imag) {
siheap_complex_t *result = sicomplex_new(real, imag);
sistack_push(SIHEAP_PTRTONANBOX(result));
}
bool sivm_equal(sinanbox_t l, sinanbox_t r) {
l = nanbox_int_if_bool(l);
r = nanbox_int_if_bool(r);
if (NANBOX_IDENTICAL(l, r)) {
// if they are *identical* then they are equal provided they are not NaN.
// A complex value is a heap pointer, never bit-identical to
// NANBOX_CANONICAL_NAN (that's a plain-float bit pattern) even when its
// own real/imag component is NaN, so it needs its own check here rather
// than falling through to the plain-float comparison below.
if (sivm_is_complex(l)) {
siheap_complex_t *c = (siheap_complex_t *) SIHEAP_NANBOXTOPTR(l);
return !(isnan(c->real) || isnan(c->imag));
}
return !NANBOX_IDENTICAL(l, NANBOX_CANONICAL_NAN);
} else if (sivm_is_complex(l) || sivm_is_complex(r)) {
// Python's numeric tower: complex compares equal to a plain int/float
// with the same real part and zero imaginary part (component-wise,
// matching PyComplexNumber.equals() in py-slang's value-types.ts) —
// covers complex==complex and complex==int/float either way round.
sifloat_t lr, li, rr, ri;
if (!sivm_numeric_to_complex_parts(l, &lr, &li) || !sivm_numeric_to_complex_parts(r, &rr, &ri)) {
return false;
}
return lr == rr && li == ri;
} else if (NANBOX_ISNUMERIC(l) && NANBOX_ISNUMERIC(r)) {
switch (NANBOX_ISFLOAT(r) << 1 | NANBOX_ISFLOAT(l)) {
case 0: /* neither are floats */
return NANBOX_INT(l) == NANBOX_INT(r);
case 1: /* v0 is float */
return NANBOX_FLOAT(l) == NANBOX_INT(r);
case 2: /* r is float */
return NANBOX_INT(l) == NANBOX_FLOAT(r);
case 3: /* both are float */
return NANBOX_FLOAT(l) == NANBOX_FLOAT(r);
default:
SIBUG();
sifault(pynter_fault_internal_error);
return false;
}
} else if (NANBOX_ISPTR(l) & NANBOX_ISPTR(r)) {
siheap_header_t *hv0 = SIHEAP_NANBOXTOPTR(l);
siheap_header_t *hv1 = SIHEAP_NANBOXTOPTR(r);
if (hv0 == hv1) {
// Same object: equal outright, and (for arrays) avoids infinite
// recursion on a self-referential array (mirrors CPython's `x is y`
// identity-first shortcut in container comparison).
return true;
} else if (siheap_is_string(hv0) && siheap_is_string(hv1)) {
return strcmp(sistrobj_tocharptr(hv0), sistrobj_tocharptr(hv1)) == 0;
} else if (hv0->type == sitype_array && hv1->type == sitype_array) {
// Python lists compare structurally, element-wise (unlike Source
// pairs/arrays, which only ever compared by reference here before).
siheap_array_t *la = (siheap_array_t *) hv0;
siheap_array_t *ra = (siheap_array_t *) hv1;
if (la->count != ra->count) {
return false;
}
for (address_t i = 0; i < la->count; i++) {
sinanbox_t le = siarray_get(la, i);
sinanbox_t re = siarray_get(ra, i);
// Python's list/container equality checks each element's identity
// FIRST (PyObject_RichCompareBool's own optimization), bypassing the
// "NaN != NaN" rule a bare `==` between the same two NaN-bearing
// values would otherwise hit -- e.g. `x = float('nan'); [x] == [x]`
// is True in real Python even though `x == x` alone is False. A
// plain sivm_equal() call here (which applies that rule
// unconditionally, matching top-level `==`) would wrongly return
// False for a list holding a NaN/NaN-complex element compared
// against itself.
if (!NANBOX_IDENTICAL(le, re) && !sivm_equal(le, re)) {
return false;
}
}
return true;
} else {
// functions (and any other non-array, non-string heap object):
// identical only if they are the SAME object.
return false;
}
} else {
// different types, so not equal
return false;
}
}
// Python list subscript (read via LDAG, write via STAG) semantics — see
// py-slang issue #299: index must be a genuine int (bool and float are both
// TypeErrors, even though a bool is numerically an int and a whole-valued
// float looks integral — matches docs/specs/python_typing_middle_34.tex and
// the TS reference's ListIndexTypeError), valid range is -len..len-1 with
// real negative wraparound (`i % len`, not auto-clamped), and out-of-range
// is always an IndexError — never silently returns undefined (read) or
// auto-grows the array (write, issue #294's original bug). This relies on
// `array->count` already being the list's true Python length at every call
// site: op_new_a now pre-sizes a list literal's array to its final element
// count up front (see that case below), so by the time any LDAG/STAG runs —
// whether finishing that same literal's construction or a later, genuinely
// separate subscript access — `count` is already correct and this check
// applies uniformly, with no separate "still under construction" case to
// special-case here.
static inline void pop_array_args(siheap_array_t **array, address_t *index) {
sinanbox_t indexv = sistack_pop();
sinanbox_t arrayv = sistack_pop();
*array = SIHEAP_NANBOXTOPTR(arrayv);
if (!NANBOX_ISPTR(arrayv) || (*array)->header.type != sitype_array) {
sifault(pynter_fault_type);
return;
}
if (!NANBOX_ISINT(indexv)) {
sifault(pynter_fault_type);
return;
}
int32_t idx = NANBOX_INT(indexv);
int32_t len = (int32_t) (*array)->count;
if (idx < 0) {
idx += len;
}
if (idx < 0 || idx >= len) {
sifault(pynter_fault_index_error);
return;
}
*index = (address_t) idx;
}
/** Length in bytes of the UTF-8 sequence starting at a given lead byte. */
static inline size_t utf8_char_len(unsigned char lead) {
if ((lead & 0x80) == 0x00) return 1;
if ((lead & 0xE0) == 0xC0) return 2;
if ((lead & 0xF0) == 0xE0) return 3;
if ((lead & 0xF8) == 0xF0) return 4;
return 1; // malformed lead byte -- advance by one to avoid an infinite loop
}
/**
* Python str subscripting (`s[i]`) reads by Unicode code point, not UTF-8
* byte -- pynter's own strings are stored as raw UTF-8 (see
* sistrobj_tocharptr), so this walks lead bytes to find code point
* boundaries rather than indexing the byte array directly (a family emoji
* like a ZWJ sequence is several code points long; `s[1]` must land on the
* second one, not the second byte). Two passes: first to get the code
* point count (needed for negative-index wraparound and the range check,
* mirroring pop_array_args' own array-length logic just above), then to
* find the idx-th code point's own byte span. Faults the same way
* pop_array_args does, for the same reasons (bad index type, out of
* range) -- LDAG is the only caller (see its own case below); STAG never
* reaches here, since Python strings are immutable and pop_array_args
* (which STAG still uses unchanged) already rejects a non-array target.
*/
static inline sinanbox_t string_index(siheap_header_t *str_obj, sinanbox_t indexv) {
if (!NANBOX_ISINT(indexv)) {
sifault(pynter_fault_type);
return NANBOX_OFEMPTY();
}
const char *s = sistrobj_tocharptr(str_obj);
int32_t len = 0;
for (const char *p = s; *p; p += utf8_char_len((unsigned char) *p)) {
len++;
}
int32_t idx = NANBOX_INT(indexv);
if (idx < 0) {
idx += len;
}
if (idx < 0 || idx >= len) {
sifault(pynter_fault_index_error);
return NANBOX_OFEMPTY();
}
const char *p = s;
for (int32_t i = 0; i < idx; ++i) {
p += utf8_char_len((unsigned char) *p);
}
size_t char_len = utf8_char_len((unsigned char) *p);
siheap_string_t *result = sistring_new((address_t) (char_len + 1));
memcpy(result->string, p, char_len);
result->string[char_len] = '\0';
// A bare sitype_string is an internal-only flattening cache
// (sistrpair_flatten's own output) -- siheap_is_string() faults on one
// reaching the stack directly (see make_string_value() in primitives.c,
// fixed for the same reason). Wrap it in a degenerate strpair (right =
// NULL), taking over its existing refcount as `left` rather than via
// sistrpair_new (which would add a second, unwanted ref).
siheap_strpair_t *pair = (siheap_strpair_t *) siheap_malloc(sizeof(siheap_strpair_t), sitype_strpair);
pair->left = &result->header;
pair->right = NULL;
return SIHEAP_PTRTONANBOX(pair);
}
static inline bool do_internal_function(
const uint8_t id,
const uint8_t num_args,
size_t sizeof_instr,
const bool is_primitive,
const bool is_tailcall,
const bool pop_fn) {
if ((is_primitive && id >= SIVMFN_PRIMITIVE_COUNT) || (!is_primitive && id >= sivmfn_vminternal_count)) {
SIDEBUG("Invalid %s function index %d\n", is_primitive ? "primitive" : "VM-internal", id);
sifault(pynter_fault_invalid_program);
return false;
}
// check that there are enough items on the stack
if (num_args > 0) {
sistack_peek(num_args - 1);
}
// call the function
sinanbox_t retv = (is_primitive ? sivmfn_primitives : sivmfn_vminternals)[id](num_args, sistack_top - num_args);
// pop the arguments off the stack
for (unsigned int i = 0; i < num_args; ++i) {
siheap_derefbox(sistack_pop());
}
// pop the function off the stack, if needed
if (pop_fn) {
siheap_derefbox(sistack_pop());
}
// if tail call, we destroy the caller's stack now, and "return" to the caller's caller
if (is_tailcall) {
siheap_deref(sistate.env);
sistack_destroy(&sistate.pc, &sistate.env);
} else {
// otherwise we advance to the return address
sistate.pc += sizeof_instr;
}
sistack_push(retv);
// tail call from main
if (is_tailcall && !sistate.pc) {
return true;
}
return false;
}
#define DECLOPSTRUCT(type) const struct type *instr = (const struct type *) sistate.pc
#define ADVANCE_PCONE() sistate.pc += sizeof(opcode_t); continue
#define ADVANCE_PCI() sistate.pc += sizeof(*instr); continue
#ifdef PYNTER_SHORT_DOUBLE_WORKAROUND
/**
* For systems (e.g. Arduino AVR) where double is actually an alias of float:
* manually converts the bits of an IEEE 754 double into a float.
*/
static float sivm_float_of_f64_bits(uint64_t bits) {
union {
float value;
uint32_t bits;
} float_value;
_Static_assert(sizeof(float_value) == 4, "union of float and uint32_t is not 32-bit");
float_value.bits = 0;
// sign bit
if (bits & (((uint64_t)1) << 63)) {
float_value.bits |= ((uint32_t)1) << 31;
}
const uint32_t offset_exponent = (bits >> 52) & 0x7FFu;
const int32_t real_exponent = ((int32_t)offset_exponent) - 1023;
const uint64_t f64_mantissa = bits & 0xFFFFFFFFFFFFFu;
// lop off the bottom 29 bits..
const uint32_t f32_mantissa = (bits >> 29) & 0x7FFFFFu;
if (offset_exponent == 0x7FF) {
// NaN or infinity
// set all the exponent bits
float_value.bits |= 0x7F800000u;
if (f64_mantissa) {
// NaN, just set this to canonical NaN
float_value.bits = 0x7FC00000u;
}
} else if (offset_exponent == 0) {
// f64 zero/subnormal: far below the f32 range, so a signed zero
} else if (real_exponent >= -126 && real_exponent <= 127) {
float_value.bits |= (real_exponent + 127) << 23;
float_value.bits |= f32_mantissa;
} else if (real_exponent < -126) {
// underflow (flushes f32 subnormals to zero); keeps the sign bit
} else {
float_value.bits |= 0x7F800000u; // overflow: signed infinity
}
return float_value.value;
}
#endif
/**
* Runs the main interpreter loop.
*/
static void main_loop(void) {
#ifdef PYNTER_DEBUG
const opcode_t *previous_pc = NULL;
(void) previous_pc;
#endif
while (1) {
if (!sistate.running) {
SIDEBUG("The program has been stopped by the user.\n");
sifault(pynter_fault_stopped);
return;
}
#ifdef PYNTER_DEBUG_MEMORY_CHECK
debug_memorycheck();
#endif
#ifdef PYNTER_DEBUG
if (sistate.pc >= sistate.program_end) {
SIBUGV("Jumped out of bounds to 0x%tx after instruction at address 0x%tx\n", SISTATE_CURADDR, previous_pc - sistate.program);
sifault(pynter_fault_internal_error);
return;
}
previous_pc = sistate.pc;
SITRACE("PC: 0x%tx; opcode: %02x (%s)\n", SISTATE_CURADDR, *sistate.pc, get_opcode_name(*sistate.pc));
#endif
const opcode_t this_opcode = *sistate.pc;
switch (this_opcode) {
case op_nop:
ADVANCE_PCONE();
case op_ldc_i:
case op_lgc_i: {
DECLOPSTRUCT(op_i32);
sistack_push(NANBOX_WRAP_INT(instr->operand));
ADVANCE_PCI();
}
case op_ldc_f32:
case op_lgc_f32: {
DECLOPSTRUCT(op_f32);
sistack_push(NANBOX_OFFLOAT(instr->operand));
ADVANCE_PCI();
}
case op_ldc_f64:
case op_lgc_f64: {
DECLOPSTRUCT(op_f64);
#ifdef PYNTER_SHORT_DOUBLE_WORKAROUND
sistack_push(NANBOX_OFFLOAT(sivm_float_of_f64_bits(instr->operand_u64)));
#else
sistack_push(NANBOX_OFFLOAT((sifloat_t)instr->operand));
#endif
ADVANCE_PCI();
}
case op_ldc_b_0:
case op_lgc_b_0:
sistack_push(NANBOX_OFBOOL(false));
ADVANCE_PCONE();
case op_ldc_b_1:
case op_lgc_b_1:
sistack_push(NANBOX_OFBOOL(true));
ADVANCE_PCONE();
case op_lgc_u:
sistack_push(NANBOX_OFUNDEF());
ADVANCE_PCONE();
case op_lgc_n:
sistack_push(NANBOX_OFNULL());
ADVANCE_PCONE();
case op_lgc_s: {
DECLOPSTRUCT(op_address);
const pvm_constant_t *string = (const pvm_constant_t *) (sistate.program + instr->address);
siheap_strconst_t *obj = sistrconst_new(string);
sistack_push(SIHEAP_PTRTONANBOX(obj));
ADVANCE_PCI();
}
case op_lgc_c: {
DECLOPSTRUCT(op_complex);
#ifdef PYNTER_SHORT_DOUBLE_WORKAROUND
siheap_complex_t *obj = sicomplex_new(
sivm_float_of_f64_bits(instr->real_u64), sivm_float_of_f64_bits(instr->imag_u64));
#else
siheap_complex_t *obj = sicomplex_new((sifloat_t) instr->real, (sifloat_t) instr->imag);
#endif
sistack_push(SIHEAP_PTRTONANBOX(obj));
ADVANCE_PCI();
}
case op_pop_g:
case op_pop_b:
case op_pop_f:
siheap_derefbox(sistack_pop());
ADVANCE_PCONE();
#define ARITHMETIC_TYPECHECK() do { if (!NANBOX_ISNUMERIC(v0) || !NANBOX_ISNUMERIC(v1)) {\
sifault(pynter_fault_type); \
return; \
} } while (0)
// TODO: optimised _f variants
case op_add_g:
case op_add_f: {
sinanbox_t v1 = sistack_pop();
sinanbox_t v0 = sistack_pop();
sinanbox_t r;
if (NANBOX_ISNUMERIC(v0) && NANBOX_ISNUMERIC(v1)) {
switch (NANBOX_ISFLOAT(v1) << 1 | NANBOX_ISFLOAT(v0)) {
case 0: /* neither are floats */
/* the sum of 2 small integers can overflow their type, use int64 instead */
r = NANBOX_WRAP_INT(((int64_t) NANBOX_INT(v0)) + ((int64_t) NANBOX_INT(v1)));
break;
case 1: /* v0 is float */
r = NANBOX_OFFLOAT(NANBOX_FLOAT(v0) + NANBOX_INT(v1));
break;
case 2: /* v1 is float */
r = NANBOX_OFFLOAT(NANBOX_INT(v0) + NANBOX_FLOAT(v1));
break;
case 3: /* both are float */
r = NANBOX_OFFLOAT(NANBOX_FLOAT(v0) + NANBOX_FLOAT(v1));
break;
default:
SIBUG();
sifault(pynter_fault_internal_error);
break;
}
} else if (sivm_is_complex(v0) || sivm_is_complex(v1)) {
sifloat_t r0, i0, r1, i1;
if (!sivm_numeric_to_complex_parts(v0, &r0, &i0) || !sivm_numeric_to_complex_parts(v1, &r1, &i1)) {
SIDEBUG("Invalid operands to add.\n");
sifault(pynter_fault_type);
return;
}
siheap_complex_t *result = sicomplex_new(r0 + r1, i0 + i1);
r = SIHEAP_PTRTONANBOX(result);
} else if (NANBOX_ISPTR(v0) & NANBOX_ISPTR(v1)) {
siheap_header_t *hv0 = SIHEAP_NANBOXTOPTR(v0);
siheap_header_t *hv1 = SIHEAP_NANBOXTOPTR(v1);
if (siheap_is_string(hv0) && siheap_is_string(hv1)) {
// if either are empty string, no-op
if (hv0->type == sitype_strconst && *(((siheap_strconst_t *) hv0)->string->data) == '\0') {
siheap_ref(hv1);
r = v1;
} else if (hv1->type == sitype_strconst && *(((siheap_strconst_t *) hv1)->string->data) == '\0') {
siheap_ref(hv0);
r = v0;
} else {
siheap_strpair_t *obj = sistrpair_new(hv0, hv1);
r = SIHEAP_PTRTONANBOX(obj);
}
} else {
SIDEBUG("Invalid operands to add.\n");
sifault(pynter_fault_type);
return;
}
} else {
SIDEBUG("Invalid operands to add.\n");
sifault(pynter_fault_type);
return;
}
sistack_push(r);
siheap_derefbox(v0);
siheap_derefbox(v1);
ADVANCE_PCONE();
}
break;
case op_sub_g:
case op_sub_f: {
sinanbox_t v1 = sistack_pop();
sinanbox_t v0 = sistack_pop();
// Checked before ARITHMETIC_TYPECHECK(), which faults on any
// non-NANBOX_ISNUMERIC operand — a complex operand is a heap pointer,
// not numeric, so would otherwise incorrectly fault type error before
// this branch gets a chance to run (same pattern as op_mul_g's list-
// repetition special case above).
if (sivm_is_complex(v0) || sivm_is_complex(v1)) {
sifloat_t r0, i0, r1, i1;
if (!sivm_numeric_to_complex_parts(v0, &r0, &i0) || !sivm_numeric_to_complex_parts(v1, &r1, &i1)) {
sifault(pynter_fault_type);
return;
}
sivm_push_complex_result(r0 - r1, i0 - i1);
siheap_derefbox(v0);
siheap_derefbox(v1);
ADVANCE_PCONE();
}
ARITHMETIC_TYPECHECK();
sinanbox_t r;
switch (NANBOX_ISFLOAT(v1) << 1 | NANBOX_ISFLOAT(v0)) {
case 0: /* neither are floats */
/* the difference of 2 small integers can overflow their type, use int64 instead */
r = NANBOX_WRAP_INT(((int64_t) NANBOX_INT(v0)) - ((int64_t) NANBOX_INT(v1)));
break;
case 1: /* v0 is float */
r = NANBOX_OFFLOAT(NANBOX_FLOAT(v0) - NANBOX_INT(v1));
break;
case 2: /* v1 is float */
r = NANBOX_OFFLOAT(NANBOX_INT(v0) - NANBOX_FLOAT(v1));
break;
case 3: /* both are float */
r = NANBOX_OFFLOAT(NANBOX_FLOAT(v0) - NANBOX_FLOAT(v1));
break;
default:
SIBUG();
sifault(pynter_fault_internal_error);
return;
}
sistack_push(r);
/* No need to deref v0 and v1; they are either numbers (which are not on the heap) */
/* or they are not (in which case we would have faulted) */
ADVANCE_PCONE();
}
case op_mul_g:
case op_mul_f: {
sinanbox_t v1 = sistack_pop();
sinanbox_t v0 = sistack_pop();
// Python list repetition (list * int / int * list) — see py-slang
// issue #299. Checked before ARITHMETIC_TYPECHECK() since an array
// operand isn't NANBOX_ISNUMERIC and would otherwise incorrectly fault
// as a type error before this special case gets a chance to run.
bool v0_is_array = NANBOX_ISPTR(v0) && ((siheap_array_t *) SIHEAP_NANBOXTOPTR(v0))->header.type == sitype_array;
bool v1_is_array = NANBOX_ISPTR(v1) && ((siheap_array_t *) SIHEAP_NANBOXTOPTR(v1))->header.type == sitype_array;
if (v0_is_array || v1_is_array) {
// list * list is never valid, and the non-list operand must be a
// genuine int — bool and float are both TypeErrors (matches
// docs/specs/python_typing_middle_34.tex's ListMultiplyTypeError),
// even though a bool is numerically an int and a whole-valued float
// looks integral.
if (v0_is_array == v1_is_array || !NANBOX_ISINT(v0_is_array ? v1 : v0)) {
sifault(pynter_fault_type);
return;
}
siheap_array_t *src = (siheap_array_t *) SIHEAP_NANBOXTOPTR(v0_is_array ? v0 : v1);
int32_t n = NANBOX_INT(v0_is_array ? v1 : v0);
address_t srclen = src->count;
// n and srclen are each individually bounded (by NANBOX_INTMAX and
// the heap size), but their product isn't -- computed in uint64_t first so an
// unreasonably large repeat count/list can't silently wrap the
// 32-bit address_t result into a too-small allocation.
uint64_t newlen64 = n > 0 ? (uint64_t) n * srclen : 0;
if (newlen64 > UINT32_MAX) {
sifault(pynter_fault_out_of_memory);
return;
}
address_t newlen = (address_t) newlen64;
siheap_array_t *result = siarray_new(newlen);
result->count = newlen;
for (address_t i = 0; i < newlen; ++i) {
sinanbox_t elem = siarray_get(src, i % srclen);
siheap_refbox(elem);
result->data->data[i] = elem;
}
siheap_derefbox(v0_is_array ? v0 : v1);
sistack_push(SIHEAP_PTRTONANBOX(result));
ADVANCE_PCONE();
}
// Complex multiplication — same "check before ARITHMETIC_TYPECHECK()"
// reasoning as the array case above.
if (sivm_is_complex(v0) || sivm_is_complex(v1)) {
sifloat_t r0, i0, r1, i1;
if (!sivm_numeric_to_complex_parts(v0, &r0, &i0) || !sivm_numeric_to_complex_parts(v1, &r1, &i1)) {
sifault(pynter_fault_type);
return;
}
// (a+bi)*(c+di) = (ac - bd) + (bc + ad)i
sivm_push_complex_result(r0 * r1 - i0 * i1, i0 * r1 + r0 * i1);
siheap_derefbox(v0);
siheap_derefbox(v1);
ADVANCE_PCONE();
}
ARITHMETIC_TYPECHECK();
sinanbox_t r;
switch (NANBOX_ISFLOAT(v1) << 1 | NANBOX_ISFLOAT(v0)) {
case 0: /* neither are floats */
/* this can overflow, use int64 instead */
r = NANBOX_WRAP_INT(((int64_t) NANBOX_INT(v0)) * ((int64_t) NANBOX_INT(v1)));
break;
case 1: /* v0 is float */
r = NANBOX_OFFLOAT(NANBOX_FLOAT(v0) * NANBOX_INT(v1));
break;
case 2: /* v1 is float */
r = NANBOX_OFFLOAT(NANBOX_INT(v0) * NANBOX_FLOAT(v1));
break;
case 3: /* both are float */
r = NANBOX_OFFLOAT(NANBOX_FLOAT(v0) * NANBOX_FLOAT(v1));
break;
default:
SIBUG();
sifault(pynter_fault_internal_error);
return;
}
sistack_push(r);
/* No need to deref v0 and v1; they are either numbers (which are not on the heap) */
/* or they are not (in which case we would have faulted) */
ADVANCE_PCONE();
}
case op_div_g:
case op_div_f: {
sinanbox_t v1 = sistack_pop();
sinanbox_t v0 = sistack_pop();
if (sivm_is_complex(v0) || sivm_is_complex(v1)) {
sifloat_t a, b, c, d;
if (!sivm_numeric_to_complex_parts(v0, &a, &b) || !sivm_numeric_to_complex_parts(v1, &c, &d)) {
sifault(pynter_fault_type);
return;
}
if (c == 0 && d == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
// Smith's algorithm (scale by the larger-magnitude component first)
// to avoid premature overflow/underflow — matches
// PyComplexNumber.divBy() in py-slang's value-types.ts exactly,
// itself a port of CPython's own complexobject.c division.
sifloat_t absC = SIFL(fabs)(c);
sifloat_t absD = SIFL(fabs)(d);
sifloat_t real, imag;
if (absD < absC) {
sifloat_t ratio = d / c;
sifloat_t denom = c + d * ratio;
real = (a + b * ratio) / denom;
imag = (b - a * ratio) / denom;
} else {
sifloat_t ratio = c / d;
sifloat_t denom = d + c * ratio;
real = (a * ratio + b) / denom;
imag = (b * ratio - a) / denom;
}
sivm_push_complex_result(real, imag);
siheap_derefbox(v0);
siheap_derefbox(v1);
ADVANCE_PCONE();
}
ARITHMETIC_TYPECHECK();
sinanbox_t r;
switch (NANBOX_ISFLOAT(v1) << 1 | NANBOX_ISFLOAT(v0)) {
case 0: /* neither are floats */
if (NANBOX_INT(v1) == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
r = NANBOX_OFFLOAT(((sifloat_t) NANBOX_INT(v0)) / NANBOX_INT(v1));
break;
case 1: /* v0 is float */
if (NANBOX_INT(v1) == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
r = NANBOX_OFFLOAT(NANBOX_FLOAT(v0) / NANBOX_INT(v1));
break;
case 2: /* v1 is float */
if (NANBOX_FLOAT(v1) == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
r = NANBOX_OFFLOAT(NANBOX_INT(v0) / NANBOX_FLOAT(v1));
break;
case 3: /* both are float */
if (NANBOX_FLOAT(v1) == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
r = NANBOX_OFFLOAT(NANBOX_FLOAT(v0) / NANBOX_FLOAT(v1));
break;
default:
SIBUG();
sifault(pynter_fault_internal_error);
return;
}
sistack_push(r);
/* No need to deref v0 and v1; they are either numbers (which are not on the heap) */
/* or they are not (in which case we would have faulted) */
ADVANCE_PCONE();
}
// Python `%` is floored modulo (result takes the divisor's sign, e.g.
// -7 % 3 == 2) unlike C's fmod/fmodf (which takes the dividend's sign,
// e.g. fmodf(-7, 3) == -1) — see py-slang's own reference semantics,
// engines/cse/utils.ts's pythonMod. It also preserves int-ness when both
// operands are ints (2 % 2 is the int 0, not the float 0.0), matching
// op_add_g/op_sub_g/op_mul_g's case-0 int branch just above, not
// op_div_g's "always float" true-division behavior.
//
// The int/int branch below needs an explicit zero-divisor check that the
// float branches don't: C's `%` on ints is undefined behaviour (a SIGFPE
// crash on most platforms) for a zero divisor, unlike fmodf(x, 0.0),
// which is well-defined (NaN) — the previous version of this opcode
// never crashed here only because it (incorrectly) ran every case
// through fmodf, floats included; preserving int-ness in the fix means
// this case now takes the real `%` operator, so it needs the guard
// fmodf was accidentally providing for free before.
case op_mod_g:
case op_mod_f: {
sinanbox_t v1 = sistack_pop();
sinanbox_t v0 = sistack_pop();
ARITHMETIC_TYPECHECK();
sinanbox_t r;
switch (NANBOX_ISFLOAT(v1) << 1 | NANBOX_ISFLOAT(v0)) {
case 0: { /* neither are floats */
// int64_t, so that INT32_MIN % -1 doesn't overflow (and trap)
int64_t divisor = NANBOX_INT(v1);
if (divisor == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
int64_t m = ((int64_t) NANBOX_INT(v0)) % divisor;
if (m != 0 && (m < 0) != (divisor < 0)) {
m += divisor;
}
r = NANBOX_WRAP_INT(m);
break;
}
case 1: { /* v0 is float */
sifloat_t divisor = (sifloat_t) NANBOX_INT(v1);
if (divisor == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
sifloat_t m = SIFL(fmod)(NANBOX_FLOAT(v0), divisor);
if (m != 0 && (m < 0) != (divisor < 0)) {
m += divisor;
}
r = NANBOX_OFFLOAT(m);
break;
}
case 2: { /* v1 is float */
sifloat_t divisor = NANBOX_FLOAT(v1);
if (divisor == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
sifloat_t m = SIFL(fmod)(NANBOX_INT(v0), divisor);
if (m != 0 && (m < 0) != (divisor < 0)) {
m += divisor;
}
r = NANBOX_OFFLOAT(m);
break;
}
case 3: { /* both are float */
sifloat_t divisor = NANBOX_FLOAT(v1);
if (divisor == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
sifloat_t m = SIFL(fmod)(NANBOX_FLOAT(v0), divisor);
if (m != 0 && (m < 0) != (divisor < 0)) {
m += divisor;
}
r = NANBOX_OFFLOAT(m);
break;
}
default:
SIBUG();
sifault(pynter_fault_internal_error);
break;
}
sistack_push(r);
/* No need to deref v0 and v1; they are either numbers (which are not on the heap) */
/* or they are not (in which case we would have faulted) */
ADVANCE_PCONE();
}
// Python `//` floors toward negative infinity (result takes the
// divisor's sign, e.g. -7 // 3 == -3), unlike C's `/` on ints (truncates
// toward zero, e.g. -7 / 3 == -2 in C) — same floored-division family as
// `%` just above (indeed floor(a/b)*b + (a mod b) == a always holds).
// Stays int-typed when both operands are ints, matching op_mod_g's
// case-0 branch, not op_div_g's "always float" true division. Raises
// Python's actual ZeroDivisionError (pynter_fault_divide_by_zero) on a
// zero divisor, in every int/float combination, matching op_div_g/
// op_mod_g just above (pynter#31 — op_div_g's own check was missing
// this until then, silently producing IEEE `inf`/`nan` instead).
case op_floordiv_g:
case op_floordiv_f: {
sinanbox_t v1 = sistack_pop();
sinanbox_t v0 = sistack_pop();
ARITHMETIC_TYPECHECK();
sinanbox_t r;
switch (NANBOX_ISFLOAT(v1) << 1 | NANBOX_ISFLOAT(v0)) {
case 0: { /* neither are floats */
// int64_t, so that INT32_MIN // -1 (2**31) doesn't overflow (and trap)
int64_t divisor = NANBOX_INT(v1);
if (divisor == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
int64_t dividend = NANBOX_INT(v0);
int64_t q = dividend / divisor;
int64_t rem = dividend % divisor;
if (rem != 0 && (rem < 0) != (divisor < 0)) {
q -= 1;
}
r = NANBOX_WRAP_INT(q);
break;
}
case 1: { /* v0 is float */
sifloat_t divisor = (sifloat_t) NANBOX_INT(v1);
if (divisor == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
r = NANBOX_OFFLOAT(SIFL(floor)(NANBOX_FLOAT(v0) / divisor));
break;
}
case 2: { /* v1 is float */
sifloat_t divisor = NANBOX_FLOAT(v1);
if (divisor == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
r = NANBOX_OFFLOAT(SIFL(floor)(NANBOX_INT(v0) / divisor));
break;
}
case 3: { /* both are float */
sifloat_t divisor = NANBOX_FLOAT(v1);
if (divisor == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
r = NANBOX_OFFLOAT(SIFL(floor)(NANBOX_FLOAT(v0) / divisor));
break;
}
default:
SIBUG();
sifault(pynter_fault_internal_error);
break;
}
sistack_push(r);
/* No need to deref v0 and v1; they are either numbers (which are not on the heap) */
/* or they are not (in which case we would have faulted) */
ADVANCE_PCONE();
}
// `**`, matching py-slang's own reference semantics (PVMLInterpreter's
// powArith): int**int stays int for a non-negative exponent, a negative
// exponent (or any float operand) always promotes to float. Python's
// ints are arbitrary-precision, but this VM's aren't — like op_mul_g
// above, an int result outside the small-int range gracefully degrades to
// float, computed via double (not a manual integer power loop) since
// anything in range is comfortably exact in a double's 52-bit mantissa
// (the range of a small int is at most 32 bits).
// `0 ** negative` is Python's ZeroDivisionError, checked explicitly
// since C's pow/powf would otherwise happily return +inf.
case op_pow_g: {
sinanbox_t v1 = sistack_pop();
sinanbox_t v0 = sistack_pop();
if (sivm_is_complex(v0) || sivm_is_complex(v1)) {
sifloat_t a, b, A, B;
if (!sivm_numeric_to_complex_parts(v0, &a, &b) || !sivm_numeric_to_complex_parts(v1, &A, &B)) {
sifault(pynter_fault_type);
return;
}
// Polar form: z**w = exp(w * log(z)) — matches PyComplexNumber.pow()
// in py-slang's value-types.ts exactly. z == 0 with a negative-real
// or non-real exponent is a ZeroDivisionError in real Python (e.g.
// `0**(-1)`, `0**1j`), same as plain 0**negative below.
sifloat_t mag = SIFL(hypot)(a, b);
sifloat_t theta = SIFL(atan2)(b, a);
sifloat_t real, imag;
if (mag == 0.0) {
if (A < 0.0 || B != 0.0) {
sifault(pynter_fault_divide_by_zero);
return;
}
real = 0.0;
imag = 0.0;
} else {
sifloat_t logMag = SIFL(log)(mag);
sifloat_t realExpPart = A * logMag - B * theta;
sifloat_t imagExpPart = B * logMag + A * theta;
sifloat_t expOfReal = SIFL(exp)(realExpPart);
real = expOfReal * SIFL(cos)(imagExpPart);
imag = expOfReal * SIFL(sin)(imagExpPart);
}
sivm_push_complex_result(real, imag);
siheap_derefbox(v0);
siheap_derefbox(v1);
ADVANCE_PCONE();
}
ARITHMETIC_TYPECHECK();
sinanbox_t r;
switch (NANBOX_ISFLOAT(v1) << 1 | NANBOX_ISFLOAT(v0)) {
case 0: { /* neither are floats: base ** exponent, both int */
int32_t base = NANBOX_INT(v0);
int32_t exponent = NANBOX_INT(v1);
if (exponent < 0) {
if (base == 0) {
sifault(pynter_fault_divide_by_zero);
return;
}
r = NANBOX_OFFLOAT(SIFL(pow)((sifloat_t) base, (sifloat_t) exponent));
} else {
// Bounds-check the double result *before* any llround/int64
// conversion, not after (unlike NANBOX_WRAP_INT's usual
// int64-then-compare pattern, used elsewhere for op_mul_g): a huge
// exponent can send pow() to +inf or any magnitude vastly beyond
// what long long can hold, and llround() on an out-of-range double
// is undefined behaviour per the C standard — checking the range
// on the double itself is always well-defined, so it must come
// first.
double result = pow((double) base, (double) exponent);
if (result >= NANBOX_INTMIN && result <= NANBOX_INTMAX) {
r = NANBOX_OFINT((int32_t) llround(result));