-
Notifications
You must be signed in to change notification settings - Fork 1
/
pyffi.scm
1541 lines (1220 loc) · 47.5 KB
/
pyffi.scm
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
;;;============================================================================
;;; File: "pyffi.scm"
;;; Copyright (c) 2020-2021 by Marc Feeley, All Rights Reserved.
;;; Copyright (c) 2020-2021 by Marc-André Bélanger, All Rights Reserved.
;;;============================================================================
;;; Python FFI.
(##supply-module github.com/feeley/pyffi)
(##namespace ("github.com/feeley/pyffi#")) ;; in github.com/feeley/pyffi#
(##include "~~lib/gambit/prim/prim#.scm") ;; map fx+ to ##fx+, etc
(##include "~~lib/_gambit#.scm") ;; for macro-check-procedure,
;; macro-absent-obj, etc
(##include "~~lib/gambit#.scm") ;; shell-command
(##include "pyffi#.scm") ;; correctly map pyffi ops
(declare (extended-bindings)) ;; ##fx+ is bound to fixnum addition, etc
;; (declare (not safe)) ;; claim code has no type errors
(declare (block)) ;; claim no global is assigned
;;;----------------------------------------------------------------------------
;; Generate meta information to link to Python libs.
(define-syntax gen-meta-info
(lambda (src)
(define (string-strip-trailing-return! str)
(if (string? str)
(let ((newlen (- (string-length str) 1)))
(if (char=? #\return (string-ref str newlen))
(string-shrink! str newlen))))
str)
(let ((sh
(parameterize ((current-directory
(path-directory (##source-path src))))
(shell-command "python3 python-config.py" #t))))
(if (not (= (car sh) 0))
(error "Error executing python3-config.py" sh))
(let* ((res
(call-with-input-string (cdr sh)
(lambda (port)
(read-all port (lambda (p) (string-strip-trailing-return! (read-line p)))))))
(pyver (list-ref res 0))
;; TODO: Act on Python C compiler?
(pycc (list-ref res 1))
(ldflags (list-ref res 2))
(cflags (list-ref res 3))
(libdir (list-ref res 4)))
;; TODO: Better version handling. Temporary peg to >= 3.
(if (not (eq? (string-ref pyver 0) #\3))
(error "Pyffi only supports CPython 3 and up." pyver))
`(begin
(define PYVER ,pyver)
(define LIBDIR ,libdir)
(##meta-info ld-options ,ldflags)
(##meta-info cc-options ,cflags))))))
(gen-meta-info)
;;;----------------------------------------------------------------------------
;; Get Python C API.
(c-declare #<<end-of-c-declare
#define PY_SSIZE_T_CLEAN
#include <Python.h>
typedef PyObject *PyObjectPtr;
#define DEBUG_PYTHON_REFCNT_not
#ifdef DEBUG_PYTHON_REFCNT
#define PYOBJECTPTR_INCREF(obj, where) \
do { \
Py_INCREF(obj); \
printf(where " REFCNT(%p)=%ld after INCREF\n", obj, Py_REFCNT(obj)); \
fflush(stdout); \
} while (0)
#define PYOBJECTPTR_DECREF(obj, where) \
do { \
printf(where " REFCNT(%p)=%ld before DECREF\n", obj, Py_REFCNT(obj)); \
fflush(stdout); \
Py_DECREF(obj); \
} while (0)
#define PYOBJECTPTR_REFCNT_SHOW(obj, where) \
do { \
if (obj != NULL) { \
printf(where " REFCNT(%p)=%ld\n", obj, Py_REFCNT(obj)); \
fflush(stdout); \
} \
} while (0)
#else
#define PYOBJECTPTR_INCREF(obj, where) Py_INCREF(obj)
#define PYOBJECTPTR_DECREF(obj, where) Py_DECREF(obj)
#define PYOBJECTPTR_REFCNT_SHOW(obj, where)
#endif
___SCMOBJ release_PyObjectPtr(void *obj) {
if (Py_IsInitialized()) // Avoid mem management after Python is shutdown
PYOBJECTPTR_DECREF(___CAST(PyObjectPtr, obj), "release_PyObjectPtr");
return ___FIX(___NO_ERR);
}
end-of-c-declare
)
;;;----------------------------------------------------------------------------
;; Define PyObject* foreign type.
(c-define-type PyObject "PyObject")
(c-define-type _PyObject*
(nonnull-pointer
PyObject
(PyObject*
PyObject*/None
PyObject*/bool
PyObject*/int
PyObject*/float
PyObject*/complex
PyObject*/bytes
PyObject*/bytearray
PyObject*/str
PyObject*/list
PyObject*/dict
PyObject*/frozenset
PyObject*/set
PyObject*/tuple
PyObject*/module
PyObject*/type
PyObject*/function
PyObject*/cell
)))
(c-define-type PyObject*
"void*"
"PYOBJECTPTR_to_SCMOBJ"
"SCMOBJ_to_PYOBJECTPTR"
#t)
(c-define-type PyObject*!own
"void*"
"PYOBJECTPTR_OWN_to_SCMOBJ"
"SCMOBJ_to_PYOBJECTPTR_OWN"
#t)
;;;----------------------------------------------------------------------------
;; Define PyObject* subtypes.
(define-macro (define-python-subtype-type subtype)
(define type (string-append "PyObjectPtr_" subtype))
(define _name (string->symbol (string-append "_PyObject*/" subtype)))
(define name (string->symbol (string-append "PyObject*/" subtype)))
(define name-own (string->symbol (string-append "PyObject*!own/" subtype)))
(define TYPE (string-append "PYOBJECTPTR_" (string-upcase subtype)))
(define TYPE-OWN (string-append "PYOBJECTPTR_OWN_" (string-upcase subtype)))
(define to-scmobj (string-append TYPE "_to_SCMOBJ"))
(define from-scmobj (string-append "SCMOBJ_to_" TYPE))
(define to-scmobj-own (string-append TYPE-OWN "_to_SCMOBJ"))
(define from-scmobj-own (string-append "SCMOBJ_to_" TYPE-OWN))
`(begin
(c-declare ,(string-append "typedef PyObjectPtr " type ";"))
(c-define-type ,_name (nonnull-pointer PyObject ,name))
(c-define-type ,name "void*" ,to-scmobj ,from-scmobj #t)
(c-define-type ,name-own "void*" ,to-scmobj-own ,from-scmobj-own #t)))
(define-python-subtype-type "None")
(define-python-subtype-type "bool")
(define-python-subtype-type "int")
(define-python-subtype-type "float")
(define-python-subtype-type "complex")
(define-python-subtype-type "bytes")
(define-python-subtype-type "bytearray")
(define-python-subtype-type "str")
(define-python-subtype-type "list")
(define-python-subtype-type "dict")
(define-python-subtype-type "frozenset")
(define-python-subtype-type "set")
(define-python-subtype-type "tuple")
(define-python-subtype-type "module")
(define-python-subtype-type "type")
(define-python-subtype-type "function")
(define-python-subtype-type "cell")
;;;----------------------------------------------------------------------------
;; Define PyTypeObject* foreign type.
;; NOTE: Not sure yet if we want to use raw PyTypeObjects.
(c-define-type PyTypeObject "PyTypeObject")
(c-define-type PyTypeObject*
(nonnull-pointer PyTypeObject (PyTypeObject*)))
;;;----------------------------------------------------------------------------
;; Generator of converter macros.
(define-macro (define-converter-macros _SUBTYPE _OWN release)
`(c-declare ,(string-append "
#define ___BEGIN_CFUN_SCMOBJ_to_PYOBJECTPTR" _OWN _SUBTYPE "(src,dst,i) \
if ((___err = SCMOBJ_to_PYOBJECTPTR" _SUBTYPE "(src, &dst, i)) == ___FIX(___NO_ERR)) {
#define ___END_CFUN_SCMOBJ_to_PYOBJECTPTR" _OWN _SUBTYPE "(src,dst,i) " release "}
#define ___BEGIN_CFUN_PYOBJECTPTR" _OWN _SUBTYPE "_to_SCMOBJ(src,dst) \
if ((___err = PYOBJECTPTR" _OWN _SUBTYPE "_to_SCMOBJ(src, &dst, 0)) == ___FIX(___NO_ERR)) {
#define ___END_CFUN_PYOBJECTPTR" _OWN _SUBTYPE "_to_SCMOBJ(src,dst) ___EXT(___release_scmobj)(dst); }
#define ___BEGIN_SFUN_PYOBJECTPTR" _OWN _SUBTYPE "_to_SCMOBJ(src,dst,i) \
if ((___err = PYOBJECTPTR" _OWN _SUBTYPE "_to_SCMOBJ(src, &dst, i)) == ___FIX(___NO_ERR)) {
#define ___END_SFUN_PYOBJECTPTR" _OWN _SUBTYPE "_to_SCMOBJ(src,dst,i) ___EXT(___release_scmobj)(dst); }
#define ___BEGIN_SFUN_SCMOBJ_to_PYOBJECTPTR" _OWN _SUBTYPE "(src,dst) \
if ((___err = SCMOBJ_to_PYOBJECTPTR" _SUBTYPE "(src, &dst, 0)) == ___FIX(___NO_ERR)) {
#define ___END_SFUN_SCMOBJ_to_PYOBJECTPTR" _OWN _SUBTYPE "(src,dst) " release "}
")))
;;;----------------------------------------------------------------------------
;; Converter for Python* type that detects the subtype.
(c-declare #<<end-of-c-declare
___SCMOBJ PYOBJECTPTR_to_SCMOBJ(PyObjectPtr src, ___SCMOBJ *dst, int arg_num) {
___SCMOBJ tag;
if (src == NULL)
return ___FIX(___CTOS_NONNULLPOINTER_ERR+arg_num);
#ifdef ___C_TAG_PyObject_2a__2f_None
if (src == Py_None)
tag = ___C_TAG_PyObject_2a__2f_None;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_bool
if (src == Py_False || src == Py_True)
tag = ___C_TAG_PyObject_2a__2f_bool;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_int
if (PyLong_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_int;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_float
if (PyFloat_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_float;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_complex
if (PyComplex_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_complex;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_bytes
if (PyBytes_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_bytes;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_bytearray
if (PyByteArray_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_bytearray;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_str
if (PyUnicode_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_str;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_list
if (PyList_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_list;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_dict
if (PyDict_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_dict;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_frozenset
if (PyFrozenSet_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_frozenset;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_set
if (PyAnySet_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_set;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_tuple
if (PyTuple_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_tuple;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_module
if (PyModule_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_module;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_type
if (PyType_CheckExact(src))
tag = ___C_TAG_PyObject_2a__2f_type;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_function
if (PyFunction_Check(src))
tag = ___C_TAG_PyObject_2a__2f_function;
else
#endif
#ifdef ___C_TAG_PyObject_2a__2f_cell
if (PyCell_Check(src))
tag = ___C_TAG_PyObject_2a__2f_cell;
else
#endif
tag = ___C_TAG_PyObject_2a_;
PYOBJECTPTR_REFCNT_SHOW(src, "PYOBJECTPTR_to_SCMOBJ");
return ___EXT(___NONNULLPOINTER_to_SCMOBJ)(___PSTATE,
src,
tag,
release_PyObjectPtr,
dst,
arg_num);
}
___SCMOBJ PYOBJECTPTR_OWN_to_SCMOBJ(PyObjectPtr src, ___SCMOBJ *dst, int arg_num) {
if (src == NULL)
return ___FIX(___CTOS_NONNULLPOINTER_ERR+arg_num);
PYOBJECTPTR_INCREF(src, "PYOBJECTPTR_OWN_to_SCMOBJ");
return PYOBJECTPTR_to_SCMOBJ(src, dst, arg_num);
}
___SCMOBJ SCMOBJ_to_PYOBJECTPTR(___SCMOBJ src, void **dst, int arg_num) {
___PSGET
#define CONVERT_TO_NONNULLPOINTER(tag) \
___EXT(___SCMOBJ_to_NONNULLPOINTER)(___PSP src, dst, tag, arg_num)
#define TRY_CONVERT_TO_NONNULLPOINTER(tag) \
if (CONVERT_TO_NONNULLPOINTER(tag) == ___FIX(___NO_ERR)) \
return ___FIX(___NO_ERR)
#ifdef ___C_TAG_PyObject_2a__2f_None
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_None);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_bool
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_bool);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_int
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_int);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_float
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_float);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_complex
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_complex);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_bytes
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_bytes);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_bytearray
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_bytearray);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_str
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_str);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_list
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_list);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_dict
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_dict);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_frozenset
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_frozenset);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_set
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_set);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_tuple
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_tuple);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_module
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_module);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_type
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_type);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_function
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_function);
#endif
#ifdef ___C_TAG_PyObject_2a__2f_cell
TRY_CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a__2f_cell);
#endif
return CONVERT_TO_NONNULLPOINTER(___C_TAG_PyObject_2a_);
}
end-of-c-declare
)
(define-converter-macros "" "" "")
(define-converter-macros "" "_OWN" "___EXT(___release_foreign) (src); ")
;;;----------------------------------------------------------------------------
;; Converters for Python* subtypes.
(define-macro (define-subtype-converters subtype check)
(define _SUBTYPE (string-append "_" (string-upcase subtype)))
(define tag (string-append "___C_TAG_PyObject_2a__2f_" subtype))
`(begin
(c-declare
,(string-append "
#ifdef " tag "
___SCMOBJ PYOBJECTPTR" _SUBTYPE "_to_SCMOBJ(PyObjectPtr_" subtype " src, ___SCMOBJ *dst, int arg_num) {
if (src == NULL || !(" check "))
return ___FIX(___CTOS_NONNULLPOINTER_ERR+arg_num);
PYOBJECTPTR_REFCNT_SHOW(src, \"PYOBJECTPTR" _SUBTYPE "_to_SCMOBJ\");
return ___EXT(___NONNULLPOINTER_to_SCMOBJ)(___PSTATE,
src,
" tag ",
release_PyObjectPtr,
dst,
arg_num);
}
___SCMOBJ PYOBJECTPTR_OWN" _SUBTYPE "_to_SCMOBJ(PyObjectPtr_" subtype " src, ___SCMOBJ *dst, int arg_num) {
if (src == NULL || !(" check "))
return ___FIX(___CTOS_NONNULLPOINTER_ERR+arg_num);
PYOBJECTPTR_INCREF(src, \"PYOBJECTPTR_OWN" _SUBTYPE "_to_SCMOBJ\");
return ___EXT(___NONNULLPOINTER_to_SCMOBJ)(___PSTATE,
src,
" tag ",
release_PyObjectPtr,
dst,
arg_num);
}
___SCMOBJ SCMOBJ_to_PYOBJECTPTR" _SUBTYPE "(___SCMOBJ src, void **dst, int arg_num) {
return ___EXT(___SCMOBJ_to_NONNULLPOINTER)(___PSA(___PSTATE)
src,
dst,
" tag ",
arg_num);
}
#endif
"))
(define-converter-macros ,_SUBTYPE "" "")
(define-converter-macros ,_SUBTYPE "_OWN" "___EXT(___release_foreign) (src); ")))
(define-subtype-converters "None" "src == Py_None")
(define-subtype-converters "bool" "src == Py_False || src == Py_True")
(define-subtype-converters "int" "PyLong_CheckExact(src)")
(define-subtype-converters "float" "PyFloat_CheckExact(src)")
(define-subtype-converters "complex" "PyComplex_CheckExact(src)")
(define-subtype-converters "bytes" "PyBytes_CheckExact(src)")
(define-subtype-converters "bytearray" "PyByteArray_CheckExact(src)")
(define-subtype-converters "str" "PyUnicode_CheckExact(src)")
(define-subtype-converters "list" "PyList_CheckExact(src)")
(define-subtype-converters "dict" "PyDict_CheckExact(src)")
(define-subtype-converters "frozenset" "PyFrozenSet_CheckExact(src)")
(define-subtype-converters "set" "PyAnySet_CheckExact(src) && !PyFrozenSet_CheckExact(src)")
(define-subtype-converters "tuple" "PyTuple_CheckExact(src)")
(define-subtype-converters "module" "PyModule_CheckExact(src)")
(define-subtype-converters "type" "PyType_CheckExact(src)")
(define-subtype-converters "function" "PyFunction_Check(src)")
(define-subtype-converters "cell" "PyCell_Check(src)")
;;;----------------------------------------------------------------------------
(c-declare #<<end-of-c-declare
void set_err(___SCMOBJ *err, ___SCMOBJ *errdata, ___SCMOBJ *errhandler) {
___SCMOBJ e;
___SCMOBJ val_scmobj;
___SCMOBJ tb_scmobj;
PyObjectPtr type;
PyObjectPtr val;
PyObjectPtr tb;
PyErr_Fetch(&type, &val, &tb);
PYOBJECTPTR_INCREF(type, "set_err");
PYOBJECTPTR_INCREF(val, "set_err");
PYOBJECTPTR_INCREF(tb, "set_err");
PyErr_NormalizeException(&type, &val, &tb);
if ((e = PYOBJECTPTR_to_SCMOBJ(val, &val_scmobj, ___RETURN_POS))
== ___FIX(___NO_ERR)) {
if ((e = PYOBJECTPTR_to_SCMOBJ(tb, &tb_scmobj, ___RETURN_POS))
!= ___FIX(___NO_ERR)) {
___EXT(___release_scmobj) (val_scmobj);
} else {
*errdata = ___EXT(___make_pair) (___PSTATE, val_scmobj, tb_scmobj);
___EXT(___release_scmobj) (val_scmobj);
___EXT(___release_scmobj) (tb_scmobj);
if (___FIXNUMP(*errdata)) {
e = *errdata;
}
}
}
PYOBJECTPTR_DECREF(type, "set_err");
if (e != ___FIX(___NO_ERR)) {
PYOBJECTPTR_DECREF(val, "set_err");
PYOBJECTPTR_DECREF(tb, "set_err");
}
*err = e;
*errhandler = ___GLO_github_2e_com_2f_feeley_2f_pyffi_23_pyffi_2d_error_2d_handler;
}
PyObjectPtr check_PyObjectPtr(PyObjectPtr result, ___SCMOBJ *err, ___SCMOBJ *errdata, ___SCMOBJ *errhandler) {
if (result == NULL) set_err(err, errdata, errhandler);
return result;
}
int check_int(int result, ___SCMOBJ *err, ___SCMOBJ *errdata, ___SCMOBJ *errhandler) {
/*TODO*/
return result;
}
ssize_t check_ssize_t(ssize_t result, ___SCMOBJ *err, ___SCMOBJ *errdata, ___SCMOBJ *errhandler) {
/*TODO*/
return result;
}
#define return_with_check_PyObjectPtr(call) \
___return(check_PyObjectPtr(call, &___err, &___errdata, &___errhandler));
#define return_with_check_int(call) \
___return(check_int(call, &___err, &___errdata, &___errhandler));
#define return_with_check_ssize_t(call) \
___return(check_ssize_t(call, &___err, &___errdata, &___errhandler));
#define return_with_check_void(call) \
call; ___return;
end-of-c-declare
)
(define-type python-exception
id: A9EC1C11-A6D8-4357-99E6-655B75ADC09E
type-exhibitor: python-exception-type
data
proc
args)
(##structure-display-exception-handler-register!
(##type-id (python-exception-type))
(lambda (exc port)
(if port
(let* ((val-tb (python-exception-data exc))
(val (car val-tb))
(tb (cdr val-tb)))
(display (string-append "Python raised "
(PyObject*/str->string
(PyObject_Repr val))
"\n"
(PyObject*/str->string
(PyObject_Repr tb))
"\n"
)
port)
)
(cons (python-exception-proc exc)
(python-exception-args exc)))))
(define (pyffi-error-handler code data proc . args)
(raise (make-python-exception data proc args)))
;;;----------------------------------------------------------------------------
;; Interface to Python API.
(define-macro (def-api name result-type arg-types)
(let* ((result-type-str
(symbol->string result-type))
(base-result-type-str
(if (eqv? 0 (##string-contains result-type-str "PyObject*"))
"PyObjectPtr"
result-type-str)))
`(define ,name
(c-lambda ,arg-types
,result-type
,(string-append "return_with_check_"
base-result-type-str
"("
(symbol->string name)
"("
(append-strings
(map (lambda (i)
(string-append "___arg" (number->string i)))
(iota (length arg-types) 1))
",")
"));")))))
(define Py_eval_input ((c-lambda () int "___return(Py_eval_input);")))
(define Py_file_input ((c-lambda () int "___return(Py_file_input);")))
(define Py_single_input ((c-lambda () int "___return(Py_single_input);")))
(def-api Py_Initialize void ())
(def-api Py_Finalize void ())
(def-api PyBool_FromLong PyObject*/bool (long))
(def-api PyLong_FromUnicodeObject PyObject*/int (PyObject*/str int))
(def-api PyUnicode_FromString PyObject*/str (nonnull-UTF-8-string))
(def-api PyRun_SimpleString int (nonnull-UTF-8-string))
(def-api PyRun_String PyObject* (nonnull-UTF-8-string
int
PyObject*/dict
PyObject*/dict))
(def-api PyImport_AddModuleObject PyObject*/module (PyObject*/str))
(def-api PyImport_AddModule PyObject*/module (nonnull-UTF-8-string))
(def-api PyImport_ImportModule PyObject*/module (nonnull-UTF-8-string))
(def-api PyImport_ImportModuleEx PyObject*/module (nonnull-UTF-8-string
PyObject*/dict
PyObject*/dict
PyObject*/list))
(def-api PyModule_GetDict PyObject*/dict (PyObject*/module))
(def-api PyDict_New PyObject*/dict ())
(def-api PyDict_Size ssize_t (PyObject*/dict))
(def-api PyDict_Items PyObject*/list (PyObject*/dict))
(def-api PyDict_Keys PyObject*/list (PyObject*/dict))
(def-api PyDict_Values PyObject*/list (PyObject*/dict))
(def-api PyDict_GetItem PyObject* (PyObject*/dict
PyObject*))
(def-api PyDict_SetItem int (PyObject*/dict
PyObject*
PyObject*))
(def-api PyDict_GetItemString PyObject* (PyObject*/dict
nonnull-UTF-8-string))
(def-api PyDict_SetItemString int (PyObject*/dict
nonnull-UTF-8-string
PyObject*))
(def-api PyCell_New PyObject*/cell (PyObject*))
(def-api PyCell_Get PyObject* (PyObject*/cell))
(def-api PyCell_Set int (PyObject*/cell
PyObject*))
(def-api PyList_New PyObject*/list (int))
(def-api PyTuple_GetItem PyObject* (PyObject*/tuple
ssize_t))
(def-api PyObject_CallObject PyObject* (PyObject*
PyObject*/tuple))
(def-api PyObject_CallMethod PyObject* (PyObject*
nonnull-UTF-8-string
nonnull-UTF-8-string))
(def-api PyObject_GetAttrString PyObject* (PyObject*
nonnull-UTF-8-string))
(def-api PyObject_Length ssize_t (PyObject*))
(def-api PyObject_Repr PyObject*/str (PyObject*))
(def-api Py_SetPath void (nonnull-wchar_t-string))
(def-api Py_SetPythonHome void (nonnull-wchar_t-string))
;; NOTE: Maybe migrate to `def-api'
;; TODO: Sub-interpreters
(c-define-type PyThreadState "PyThreadState")
(c-define-type PyThreadState* (nonnull-pointer PyThreadState))
(define Py_NewInterpreter
(c-lambda () PyThreadState* "Py_NewInterpreter"))
;; Get object type from struct field, no new reference.
(define PyObject*-type
(c-lambda (_PyObject*) PyTypeObject*
"___return(___arg1->ob_type);"))
(define PyObject*-type-name
(c-lambda (_PyObject*) nonnull-UTF-8-string
"___return(___CAST(char*,___arg1->ob_type->tp_name));"))
;; Use for debugging
(define _Py_REFCNT
(c-lambda (PyObject*) ssize_t
"___return(Py_REFCNT(___arg1));"))
;;;----------------------------------------------------------------------------
;; Converters between Scheme and subtypes of Python* foreign objects.
;; TODO: check for errors and implement conversion of other subtypes...
(define PyObject*/None->void
(c-lambda (PyObject*/None) scheme-object "
___return(___VOID);
"))
(define void->PyObject*/None
(c-lambda (scheme-object) PyObject*/None "
___SCMOBJ src = ___arg1;
PyObjectPtr dst = NULL;
if (___EQP(src, ___VOID)) {
dst = Py_None;
PYOBJECTPTR_INCREF(dst, \"void->PyObject*/None\");
}
___return(dst);
"))
(define PyObject*/bool->boolean
(c-lambda (PyObject*/bool) scheme-object "
___return(___BOOLEAN(___arg1 != Py_False));
"))
(define boolean->PyObject*/bool
(c-lambda (scheme-object) PyObject*/bool "
___SCMOBJ src = ___arg1;
PyObjectPtr dst = NULL;
if (___BOOLEANP(src)) {
dst = ___FALSEP(src) ? Py_False : Py_True;
PYOBJECTPTR_INCREF(dst, \"boolean->PyObject*/bool\");
}
___return(dst);
"))
(define (PyObject*/int->exact-integer src)
(let ((dst
((c-lambda (PyObject*/int) scheme-object "
PyObjectPtr src = ___arg1;
___SCMOBJ dst = ___VOID;
int overflow;
___LONGLONG val = PyLong_AsLongLongAndOverflow(src, &overflow);
if (overflow) {
/* TODO: use _PyLong_AsByteArray(...) */
} else {
if (___EXT(___LONGLONG_to_SCMOBJ)(___PSTATE,
val,
&dst,
___RETURN_POS)
!= ___FIX(___NO_ERR))
dst = ___VOID;
}
___return(___EXT(___release_scmobj) (dst));
")
src)))
(if (eq? dst (void))
(error "PyObject*/int->exact-integer conversion error")
dst)))
(define exact-integer->PyObject*/int
(c-lambda (scheme-object) PyObject*/int "
___SCMOBJ src = ___arg1;
PyObjectPtr dst = NULL;
if (___FIXNUMP(src)) {
dst = PyLong_FromLongLong(___INT(src));
} else {
#ifdef ___LITTLE_ENDIAN
/*
* Conversion is simple when words are represented in little endian
* because bignums are also stored with the big digits from the least
* signigicant digit to the most significant digit. So when viewed
* as an array of bytes the bytes are from least significant to most
* significant.
*/
dst = _PyLong_FromByteArray(
___CAST(const unsigned char*,___BODY_AS(src,___tSUBTYPED)),
___HD_BYTES(___SUBTYPED_HEADER(src)),
1, /* little_endian */
1); /* is_signed */
#endif
#ifdef ___BIG_ENDIAN
/* TODO: use _PyLong_FromByteArray(...) after copying bignum */
#endif
}
PYOBJECTPTR_REFCNT_SHOW(dst, \"exact-integer->PyObject*/int\");
___return(dst);
"))
(define PyObject*/float->flonum
(c-lambda (PyObject*/float) double "
___return(PyFloat_AS_DOUBLE(___arg1));
"))
(define flonum->PyObject*/float
(c-lambda (double) PyObject*/float "
PyObjectPtr dst = PyFloat_FromDouble(___arg1);
PYOBJECTPTR_REFCNT_SHOW(dst, \"flonum->PyObject*/float\");
___return(dst);
"))
(define (PyObject*/str->string src)
(let ((dst
((c-lambda (PyObject*/str) scheme-object "
PyObjectPtr src = ___arg1;
___SCMOBJ dst = ___VOID;
if (!PyUnicode_READY(src)) { /* convert to canonical representation */
Py_ssize_t len = PyUnicode_GET_LENGTH(src);
dst = ___EXT(___alloc_scmobj) (___PSTATE, ___sSTRING, len << ___LCS);
if (___FIXNUMP(dst))
dst = ___VOID;
else
switch (PyUnicode_KIND(src)) {
case PyUnicode_1BYTE_KIND:
{
Py_UCS1 *data = PyUnicode_1BYTE_DATA(src);
while (len-- > 0)
___STRINGSET(dst, ___FIX(len), ___CHR(data[len]));
break;
}
case PyUnicode_2BYTE_KIND:
{
Py_UCS2 *data = PyUnicode_2BYTE_DATA(src);
while (len-- > 0)
___STRINGSET(dst, ___FIX(len), ___CHR(data[len]));
break;
}
case PyUnicode_4BYTE_KIND:
{
Py_UCS4 *data = PyUnicode_4BYTE_DATA(src);
while (len-- > 0)
___STRINGSET(dst, ___FIX(len), ___CHR(data[len]));
break;
}
}
}
___return(___EXT(___release_scmobj) (dst));
")
src)))
(if (eq? dst (void))
(error "PyObject*/str->string conversion error")
dst)))
(define string->PyObject*/str
(c-lambda (scheme-object) PyObject*/str "
___SCMOBJ src = ___arg1;
if (!___STRINGP(src)) {
___return(NULL);
} else {
PyObjectPtr dst = PyUnicode_FromKindAndData(___CS_SELECT(
PyUnicode_1BYTE_KIND,
PyUnicode_2BYTE_KIND,
PyUnicode_4BYTE_KIND),
___CAST(void*,
___BODY_AS(src,___tSUBTYPED)),
___INT(___STRINGLENGTH(src)));
PYOBJECTPTR_REFCNT_SHOW(dst, \"string->PyObject*/str\");
___return(dst);
}
"))
(define (PyObject*/list->vector src)
(let ((dst
((c-lambda (PyObject*/list) scheme-object "
PyObjectPtr src = ___arg1;
Py_ssize_t len = PyList_GET_SIZE(src);
___SCMOBJ dst = ___EXT(___make_vector) (___PSTATE, len, ___FIX(0));
if (___FIXNUMP(dst)) {
___return(___VOID);
} else {
Py_ssize_t i;
for (i=0; i<len; i++) {
PyObjectPtr item = PyList_GET_ITEM(src, i);
___SCMOBJ item_scmobj;
if (PYOBJECTPTR_OWN_to_SCMOBJ(item, &item_scmobj, ___RETURN_POS)
== ___FIX(___NO_ERR)) {
___VECTORSET(dst, ___FIX(i), ___EXT(___release_scmobj) (item_scmobj))
} else {
___EXT(___release_scmobj) (dst);
___return(___VOID);
}
}
___return(___EXT(___release_scmobj) (dst));
}
")
src)))
(if (eq? dst (void))
(error "PyObject*/list->vector conversion error")
dst)))