-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchibi-ffi.scm
executable file
·2308 lines (2149 loc) · 85.3 KB
/
chibi-ffi.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
#! /usr/bin/env chibi-scheme
;; Copyright (c) 2009-2018 Alex Shinn
;; All rights reserved.
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;; 3. The name of the author may not be used to endorse or promote products
;; derived from this software without specific prior written permission.
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;; Note: this evolved as a throw-away script to provide certain core
;; modules, and so is a mess. Tread carefully.
;; Simple C FFI. "chibi-ffi file.stub" will read in the C function
;; FFI definitions from file.stub and output the appropriate C
;; wrappers into file.c. You can then compile that file with:
;;
;; cc -fPIC -shared file.c -lchibi-scheme
;;
;; (or using whatever flags are appropriate to generate shared libs on
;; your platform) and then the generated .so file can be loaded
;; directly with load, or portably using (include-shared "file") in a
;; module definition (note that include-shared uses no suffix).
;;
;; Passing the -c/--compile option will attempt to compile the .so
;; file in a single step.
;; The goal of this interface is to make access to C types and
;; functions easy, without requiring the user to write any C code.
;; That means the stubber needs to be intelligent about various C
;; calling conventions and idioms, such as return values passed in
;; actual parameters. Writing C by hand is still possible, and
;; several of the core modules provide C interfaces directly without
;; using the stubber.
;; For bootstrapping purposes we depend only on the core language.
(import (chibi))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; globals
(define *ffi-version* "0.4")
(define *types* '())
(define *type-getters* '())
(define *type-setters* '())
(define *typedefs* '())
(define *funcs* '())
(define *methods* '())
(define *consts* '())
(define *inits* '())
(define *clibs* '())
(define *cflags* '())
(define *frameworks* '())
(define *tags* '())
(define *open-namespaces* '())
(define *c++?* #f)
(define wdir ".")
(define *post-init-hook* '())
(define auto-expand-limit (* 10 1024 1024))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; type objects
(define (make-type) (make-vector 18 #f))
(define (type-base type) (vector-ref type 0))
(define (type-free? type) (vector-ref type 1))
(define (type-const? type) (vector-ref type 2))
(define (type-null? type) (vector-ref type 3))
(define (type-pointer? type) (vector-ref type 4))
(define (type-reference? type) (vector-ref type 5))
(define (type-struct? type) (vector-ref type 6))
(define (type-link? type) (vector-ref type 7))
(define (type-result? type) (vector-ref type 8))
(define (type-array type) (vector-ref type 9))
(define (type-value type) (vector-ref type 10))
(define (type-default? type) (vector-ref type 11))
(define (type-template type) (vector-ref type 12))
(define (type-new? type) (vector-ref type 13))
(define (type-error type) (vector-ref type 14))
(define (type-address-of? type) (vector-ref type 15))
(define (type-no-free? type) (vector-ref type 16))
(define (type-index type) (vector-ref type 17))
(define (type-index-set! type i) (vector-set! type 17 i))
(define (add-post-init-hook fn)
(set! *post-init-hook* (cons fn *post-init-hook*)))
(define (spec->type type . o)
(let ((res (make-type)))
(if (pair? o)
(type-index-set! res (car o)))
(let lp ((type type))
(define (next) (if (null? (cddr type)) (cadr type) (cdr type)))
(case (and (pair? type) (car type))
((free)
(vector-set! res 1 #t)
(lp (next)))
((const)
(vector-set! res 2 #t)
(lp (next)))
((maybe-null)
(vector-set! res 3 #t)
(lp (next)))
((pointer)
(vector-set! res 4 #t)
(lp (next)))
((reference)
(vector-set! res 5 #t)
(lp (next)))
((struct)
(vector-set! res 6 #t)
(lp (next)))
((link)
(vector-set! res 7 #t)
(lp (next)))
((result)
(vector-set! res 8 #t)
(lp (next)))
((array)
(vector-set! res 9 (if (pair? (cddr type)) (car (cddr type)) #t))
(lp (cadr type)))
((value)
(vector-set! res 10 (cadr type))
(lp (cddr type)))
((default)
(vector-set! res 10 (cadr type))
(vector-set! res 11 #t)
(lp (cddr type)))
((template)
(vector-set! res 12 (cadr type))
(lp (cddr type)))
((new)
(vector-set! res 13 #t)
(lp (next)))
((error)
(vector-set! res 8 #t)
(vector-set! res 14 (cadr type))
(lp (cddr type)))
((address-of)
(vector-set! res 15 #t)
(lp (next)))
((no-free)
(vector-set! res 16 #t)
(lp (next)))
(else
(let ((base (if (and (pair? type) (null? (cdr type)))
(car type)
type)))
(vector-set! res 0 base)
res))))))
(define (parse-type type . o)
(cond
((vector? type)
(if (and (pair? o) (car o))
(let ((res (vector-copy type)))
(type-index-set! res (car o))
res)
type))
(else
(apply spec->type type o))))
(define (type-auto-expand? type)
(and (pair? (type-array type))
(memq 'auto-expand (type-array type))))
(define (type-index-string type)
(if (integer? (type-index type))
(number->string (type-index type))
""))
(define (struct-fields ls)
(let lp ((ls ls) (res '()))
(cond ((not (pair? ls)) (reverse res))
((symbol? (car ls)) (lp (if (pair? (cdr ls)) (cddr ls) (cdr ls)) res))
(else (lp (cdr ls) (cons (car ls) res))))))
(define (lookup-type type)
(or (assq type *types*)
(assq type *typedefs*)))
(define (type-field-type type field)
(cond
((lookup-type (type-base (parse-type type)))
=> (lambda (x)
(let lp ((ls (struct-fields (cdr x))))
(cond
((null? ls) #f)
((eq? field (caar ls)) (car (cdar ls)))
(else (lp (cdr ls)))))))
(else
#f)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; type predicates
(define *c-int-types* '())
(define *c-enum-types* '())
(define-syntax define-c-int-type
(syntax-rules ()
((define-c-int-type type)
(if (not (memq 'type *c-int-types*))
(set! *c-int-types* (cons 'type *c-int-types*)))
#f)))
(define-syntax define-c-enum
;; TODO: support conversion to/from symbolic names
(syntax-rules ()
((define-c-enum (scheme-name c-name) . args)
(if (not (assq 'scheme-name *c-enum-types*))
(set! *c-enum-types*
`((scheme-name . c-name) ,@*c-enum-types*)))
#f)
((define-c-enum scheme-name . args)
(let ((c-name (mangle 'scheme-name)))
(if (not (assq 'scheme-name *c-enum-types*))
(set! *c-enum-types*
`((scheme-name . ,c-name) ,@*c-enum-types*)))
#f))))
(define (enum-type? type)
(assq type *c-enum-types*))
(define (signed-int-type? type)
(or (memq type '(signed-char short int long s8 s16 s32 s64))
(memq type *c-int-types*)
(enum-type? type)))
(define (unsigned-int-type? type)
(memq type '(unsigned-char unsigned-short unsigned unsigned-int unsigned-long
size_t off_t time_t clock_t dev_t ino_t mode_t nlink_t
uid_t gid_t pid_t blksize_t blkcnt_t sigval_t
u1 u8 u16 u32 u64)))
(define (int-type? type)
(or (signed-int-type? type) (unsigned-int-type? type)))
(define (float-type? type)
(memq type '(float double long-double long-long-double f32 f64)))
(define (string-type? type)
(or (memq type '(char* string env-string non-null-string))
(and (vector? type)
(type-array type)
(not (type-pointer? type))
(eq? 'char (type-base type)))))
(define (port-type? type)
(memq type '(port input-port output-port input-output-port)))
(define (error-type? type)
(or (type-error type)
(memq (type-base type)
'(errno status-bool non-null-string non-null-pointer))))
(define (array-type? type)
(and (type-array type) (not (eq? 'char (type-base type)))))
(define (basic-type? type)
(let ((type (parse-type type)))
(and (not (type-array type))
(not (void-pointer-type? type))
(not (lookup-type (type-base type))))))
(define (void-pointer-type? type)
(or (and (eq? 'void (type-base type)) (type-pointer? type))
(eq? 'void* (type-base type))))
(define (uniform-vector-type-code type)
(case type
((u1vector) 'SEXP_U1)
((u8vector) 'SEXP_U8)
((s8vector) 'SEXP_S8)
((u16vector) 'SEXP_U16)
((s16vector) 'SEXP_S16)
((u32vector) 'SEXP_U32)
((s32vector) 'SEXP_S32)
((u64vector) 'SEXP_U64)
((s64vector) 'SEXP_S64)
((f32vector) 'SEXP_F32)
((f64vector) 'SEXP_F64)
((c64vector) 'SEXP_C64)
((c128vector) 'SEXP_C128)
(else #f)))
(define (uniform-vector-type? type)
(or (eq? type 'uvector)
(and (uniform-vector-type-code type) #t)))
(define (uniform-vector-ctype type)
(case type
((uvector) "sexp")
((u1vector) "char*")
((u8vector) "unsigned char*")
((s8vector) "signed char*")
((u16vector) "unsigned short*")
((s16vector) "signed short*")
((u32vector) "unsigned int*")
((s32vector) "signed int*")
((u64vector) "sexp_uint_t*")
((s64vector) "sexp_sint_t*")
((f32vector) "float*")
((f64vector) "double*")
((c64vector) "float*")
((c128vector) "double*")
(else #f)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; function objects
(define (parse-func func . o)
(if (not (and (= 3 (length func))
(or (identifier? (cadr func))
(and (list? (cadr func))
(<= 1 (length (cadr func)) 3)
(every (lambda (x) (or (identifier? x) (not x) (string? x)))
(cadr func))))
(list? (car (cddr func)))))
(error "bad function definition" func))
(let* ((method? (and (pair? o) (car o)))
(ret-type (parse-type (car func)))
(scheme-name (if (pair? (cadr func)) (car (cadr func)) (cadr func)))
(c-name (if (pair? (cadr func))
(cadr (cadr func))
(mangle scheme-name)))
(stub-name (if (and (pair? (cadr func)) (pair? (cddr (cadr func))))
(car (cddr (cadr func)))
(generate-stub-name scheme-name))))
(let lp ((ls (if (equal? (car (cddr func)) '(void)) '() (car (cddr func))))
(i 0)
(results '())
(c-args '())
(s-args '()))
(cond
((null? ls)
(vector scheme-name c-name stub-name ret-type
(reverse results) (reverse c-args) (reverse s-args)
method?))
(else
(let ((type (parse-type (car ls) i)))
(cond
((type-result? type)
(lp (cdr ls) (+ i 1) (cons type results) (cons type c-args) s-args))
((and (type-value type) (not (type-default? type)))
(lp (cdr ls) (+ i 1) results (cons type c-args) s-args))
(else
(lp (cdr ls) (+ i 1) results (cons type c-args) (cons type s-args)))
)))))))
(define (func-scheme-name func) (vector-ref func 0))
(define (func-c-name func) (vector-ref func 1))
(define (func-stub-name func) (vector-ref func 2))
(define (func-ret-type func) (vector-ref func 3))
(define (func-results func) (vector-ref func 4))
(define (func-c-args func) (vector-ref func 5))
(define (func-scheme-args func) (vector-ref func 6))
(define (func-method? func) (vector-ref func 7))
(define (func-stub-name-set! func x) (vector-set! func 2 x))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; utilities
(define (cat . args)
(for-each (lambda (x) (if (procedure? x) (x) (display x))) args))
(define (join ls . o)
(if (pair? ls)
(let ((sep (if (pair? o) (car o) " ")))
(let lp ((ls ls))
(if (pair? (cdr ls))
(cat (car ls) sep (lambda () (lp (cdr ls))))
(cat (car ls)))))
""))
(define (x->string x)
(cond ((string? x) x)
((symbol? x) (symbol->string x))
((number? x) (number->string x))
(else (error "non-stringable object" x))))
(define (filter pred ls)
(cond ((null? ls) '())
((pred (car ls)) (cons (car ls) (filter pred (cdr ls))))
(else (filter pred (cdr ls)))))
(define (remove pred ls)
(cond ((null? ls) '())
((pred (car ls)) (remove pred (cdr ls)))
(else (cons (car ls) (remove pred (cdr ls))))))
(define (strip-extension path)
(let lp ((i (- (string-length path) 1)))
(cond ((<= i 0) path)
((eq? #\. (string-ref path i)) (substring path 0 i))
(else (lp (- i 1))))))
(define (string-concatenate-reverse ls)
(cond ((null? ls) "")
((null? (cdr ls)) (car ls))
(else (string-concatenate (reverse ls)))))
(define (string-replace str c r)
(let ((len (string-length str)))
(let lp ((from 0) (i 0) (res '()))
(define (collect) (if (= i from) res (cons (substring str from i) res)))
(cond
((>= i len) (string-concatenate-reverse (collect)))
((eqv? c (string-ref str i)) (lp (+ i 1) (+ i 1) (cons r (collect))))
(else (lp from (+ i 1) res))))))
(define (string-split str c . o)
(let ((test?
(if (procedure? c)
c
(lambda (char) (eqv? char c))))
(start (if (pair? o) (car o) 0))
(end (string-length str)))
(let lp ((from start) (i start) (res '()))
(define (collect) (if (= i from) res (cons (substring str from i) res)))
(cond
((>= i end) (reverse (collect)))
((test? (string-ref str i)) (lp (+ i 1) (+ i 1) (collect)))
(else (lp from (+ i 1) res))))))
(define (string-scan c str . o)
(let ((end (string-length str)))
(let lp ((i (if (pair? o) (car o) 0)))
(cond ((>= i end) #f)
((eqv? c (string-ref str i)) i)
(else (lp (+ i 1)))))))
(define (string-downcase str)
(list->string (map char-downcase (string->list str))))
(define (with-output-to-string thunk)
(call-with-output-string
(lambda (out)
(let ((old-out (current-output-port)))
(current-output-port out)
(thunk)
(current-output-port old-out)))))
(define (warn msg . args)
(let ((err (current-error-port)))
(display "WARNING: " err)
(display msg err)
(if (pair? args) (display ":" err))
(for-each (lambda (x) (display " " err) (write x err)) args)
(newline err)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; naming
(define (c-char? c)
(or (char-alphabetic? c) (char-numeric? c) (memv c '(#\_ #\- #\! #\?))))
(define (c-escape str)
(let ((len (string-length str)))
(let lp ((from 0) (i 0) (res '()))
(define (collect) (if (= i from) res (cons (substring str from i) res)))
(cond
((>= i len) (string-concatenate-reverse (collect)))
((not (c-char? (string-ref str i)))
(lp (+ i 1) (+ i 1)
`("_" ,(number->string (char->integer (string-ref str i)) 16)
,@(collect))))
(else (lp from (+ i 1) res))))))
(define (mangle x)
(string-replace
(string-replace (string-replace (c-escape (x->string x)) #\- "_") #\? "_p")
#\! "_x"))
(define (generate-stub-name sym)
(string-append "sexp_" (mangle sym) "_stub"))
(define (type-id-name sym)
(string-append "sexp_" (mangle sym) "_type_obj"))
(define (make-integer x)
(case x
((-1) "SEXP_NEG_ONE") ((0) "SEXP_ZERO") ((1) "SEXP_ONE")
((2) "SEXP_TWO") ((3) "SEXP_THREE") ((4) "SEXP_FOUR")
((5) "SEXP_FIVE") ((6) "SEXP_SIX") ((7) "SEXP_SEVEN")
((8) "SEXP_EIGHT") ((9) "SEXP_NINE") ((10) "SEXP_TEN")
(else (string-append "sexp_make_fixnum(" (x->string x) ")"))))
(define (string-scan-right str ch)
(let lp ((i (string-cursor-end str)))
(let ((i2 (string-cursor-prev str i)))
(cond ((string-cursor<? i2 0) 0)
((eqv? ch (string-cursor-ref str i2)) i)
(else (lp i2))))))
(define (strip-namespace x)
(string->symbol
(let* ((x (x->string x))
(i (string-scan-right x #\:)))
(if (> i 0)
(substring-cursor x i)
x))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; .stub file interface
(define (ffi-include file)
(load file (current-environment)))
(define (c-link lib)
(set! *clibs* (cons lib *clibs*)))
(define (c-framework lib)
(set! *frameworks* (cons lib *frameworks*)))
(define (c-flags-from-script cmd)
(eval '(import (chibi process)) (current-environment))
(let ((string-null? (lambda (str) (equal? str "")))
(process->string (eval 'process->string (current-environment))))
(set! *cflags*
(append *cflags*
(filter
(lambda (x) (not (string-null? x)))
(string-split (process->string cmd) char-whitespace?))))))
(define (c-declare . args)
(apply cat args)
(newline))
(define (c-include header)
(cat "\n#include \"" header "\"\n"))
(define (c-system-include header)
(cat "\n#include <" header ">\n"))
(define (c-include-verbatim file)
(call-with-input-file (if (eqv? #\/ (string-ref file 0))
file
(string-append wdir "/" file))
(lambda (in)
(let lp ()
(let ((c (read-char in)))
(cond
((not (eof-object? c))
(write-char c)
(lp))))))))
(define (c-init x)
(set! *inits* (cons x *inits*)))
(define (parse-struct-like ls)
(let lp ((ls ls) (res '()))
(cond
((null? ls)
(reverse res))
((symbol? (car ls))
(lp (cddr ls) (cons (cadr ls) (cons (car ls) res))))
((pair? (car ls))
(lp (cdr ls) (cons (cons (parse-type (caar ls)) (cdar ls)) res)))
(else
(lp (cdr ls) (cons (car ls) res))))))
(define-syntax define-struct-like
(er-macro-transformer
(lambda (expr rename compare)
(set! *types*
`((,(cadr expr)
,@(parse-struct-like (cddr expr)))
,@*types*))
(set! *tags* `(,(type-id-name (cadr expr)) ,@*tags*))
#f)))
(define-syntax define-c-struct
(er-macro-transformer
(lambda (expr rename compare)
`(define-struct-like ,(cadr expr) type: struct ,@(cddr expr)))))
(define-syntax define-c-class
(er-macro-transformer
(lambda (expr rename compare)
`(define-struct-like ,(cadr expr) type: class ,@(cddr expr)))))
(define-syntax define-c-union
(er-macro-transformer
(lambda (expr rename compare)
`(define-struct-like ,(cadr expr) type: union ,@(cddr expr)))))
(define-syntax define-c-type
(er-macro-transformer
(lambda (expr rename compare)
`(define-struct-like ,(cadr expr) ,@(cddr expr)))))
(define-syntax declare-c-struct
(er-macro-transformer
(lambda (expr rename compare)
`(define-struct-like ,(cadr expr) type: struct imported?: #t))))
(define-syntax declare-c-class
(er-macro-transformer
(lambda (expr rename compare)
`(define-struct-like ,(cadr expr) type: class imported?: #t))))
(define-syntax declare-c-union
(er-macro-transformer
(lambda (expr rename compare)
`(define-struct-like ,(cadr expr) type: union imported?: #t))))
(define-syntax define-c
(er-macro-transformer
(lambda (expr rename compare)
(set! *funcs* (cons (parse-func (cdr expr)) *funcs*))
#f)))
(define-syntax define-c-const
(er-macro-transformer
(lambda (expr rename compare)
(let ((type (parse-type (cadr expr))))
(for-each (lambda (x) (set! *consts* (cons (list type x) *consts*)))
(cddr expr))))))
;; custom strerror which reports constants as their names
(define-syntax define-c-strerror
(er-macro-transformer
(lambda (expr rename compare)
(let ((name (cadr expr))
(errnos (cddr expr)))
`(,(rename 'c-declare)
,(string-concatenate
`("\nchar* " ,(x->string name) "(const int err) {
static char buf[64];
switch (err) {
"
,@(map (lambda (errno)
(let ((e (x->string errno)))
(string-append " case " e ": return \"" e "\";\n")))
errnos)
" }
sprintf(buf, \"unknown error: %d\", err);
return buf;
}")))))))
(define-syntax c-typedef
(er-macro-transformer
(lambda (expr rename compare)
(let ((type (parse-type (cadr expr)))
(name (car (cddr expr))))
(set! *typedefs* `((,name ,@type) ,@*typedefs*))
`(,(rename 'cat) "typedef " ,(type-c-name type) " " ',name ";\n")))))
(define (c++)
(set! *c++?* #t))
(define (ensure-c++ name)
(cond
((not *c++?*)
(display "WARNING: assuming c++ mode from " (current-error-port))
(display name (current-error-port))
(display " - use (c++) to make this explicit\n" (current-error-port))
(c++))))
(define-syntax c++-namespace
(er-macro-transformer
(lambda (expr rename compare)
(ensure-c++ 'c++-namespace)
(let ((namespace (cadr expr)))
(cond
((null? (cddr expr))
(set! *open-namespaces* (cons namespace *open-namespaces*))
`(,(rename 'cat) "namespace " ',namespace ";\n"))
(else
`(,(rename 'begin)
(,(rename 'cat) "namespace " ',namespace " {\n")
,@(cddr expr)
(,(rename 'cat) "} // namespace " ',namespace "\n\n"))))))))
(define-syntax c++-using
(er-macro-transformer
(lambda (expr rename compare)
(ensure-c++ 'c++-using)
`(,(rename 'cat) "using " ',(cadr expr) ";\n"))))
(define-syntax define-c++-method
(er-macro-transformer
(lambda (expr rename compare)
(ensure-c++ 'define-c++-method)
(let* ((class (cadr expr))
(ret-type (car (cddr expr)))
(name (cadr (cddr expr)))
(meths (map (lambda (x)
(parse-func `(,ret-type ,name (,class ,@x)) #t))
(cddr (cddr expr)))))
(set! *methods* (cons (cons name meths) *methods*))))))
(define-syntax define-c++-constructor
(er-macro-transformer
(lambda (expr rename compare)
(ensure-c++ 'define-c++-constructor)
(set! *funcs*
(cons (parse-func `((new ,(if (pair? (cadr expr))
(cadr (cadr expr))
(cadr expr)))
,(cadr expr)
,@(cddr expr)))
*funcs*))
#f)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C code generation
(define (type-predicate type)
(let ((base (type-base (parse-type type))))
(cond
((int-type? base) "sexp_exact_integerp")
((float-type? base) "sexp_flonump")
((string-type? base) "sexp_stringp")
(else
(case base
((bytevector u8vector) "sexp_bytesp")
((char) "sexp_charp")
((bool boolean status-bool) "sexp_booleanp")
((port) "sexp_portp")
((input-port) "sexp_iportp")
((output-port) "sexp_oportp")
((input-output-port) "sexp_ioportp")
((fileno fileno-nonblock) "sexp_filenop")
((uvector) "sexp_uvectorp")
((u1vector) "sexp_u1vectorp")
((s8vector) "sexp_s8vectorp")
((u16vector) "sexp_u16vectorp")
((s16vector) "sexp_s16vectorp")
((u32vector) "sexp_u32vectorp")
((s32vector) "sexp_s32vectorp")
((u64vector) "sexp_u64vectorp")
((s64vector) "sexp_s64vectorp")
((f32vector) "sexp_f32vectorp")
((f64vector) "sexp_f64vectorp")
((c64vector) "sexp_c64vectorp")
((c128vector) "sexp_c128vectorp")
(else #f))))))
(define (type-name type)
(let ((base (type-base (parse-type type))))
(cond
((int-type? base) "integer")
((float-type? base) "flonum")
((memq base '(bool boolean status-bool)) (if *c++?* "bool" "int"))
(else base))))
(define (type-id-number type . o)
(let ((base (type-base type)))
(cond
((int-type? base) "SEXP_FIXNUM")
((float-type? base) "SEXP_FLONUM")
((string-type? base) "SEXP_STRING")
((memq base '(bytevector u8vector)) "SEXP_BYTES")
((eq? base 'char) "SEXP_CHAR")
((memq base '(bool boolean status-bool)) "SEXP_BOOLEAN")
((eq? base 'string) "SEXP_STRING")
((eq? base 'symbol) "SEXP_SYMBOL")
((eq? base 'pair) "SEXP_PAIR")
((eq? base 'port) "SEXP_IPORT")
((eq? base 'input-port) "SEXP_IPORT")
((eq? base 'output-port) "SEXP_OPORT")
((eq? base 'input-output-port) "SEXP_IPORT")
((memq base '(fileno fileno-nonblock)) "SEXP_FILENO")
((uniform-vector-type? base)
"SEXP_UNIFORM_VECTOR")
((void-pointer-type? type) "SEXP_CPOINTER")
((lookup-type base)
;; (string-append "sexp_type_tag(" (type-id-name base) ")")
(let ((i (type-index type)))
(cond
((not i)
;;(warn "type-id-number on unknown arg" type)
(if (and (pair? o) (car o))
"sexp_unbox_fixnum(sexp_opcode_return_type(self))"
(string-append "sexp_type_tag(" (type-id-name base) ")")))
((< i 3)
(string-append
"sexp_unbox_fixnum(sexp_opcode_arg"
(number->string (+ i 1)) "_type(self))"))
(else
(string-append
"sexp_unbox_fixnum(sexp_vector_ref(sexp_opcode_argn_type(self), "
(make-integer (- i 3)) "))")))))
(else "SEXP_OBJECT"))))
(define (type-id-value type . o)
(cond
((eq? 'void (type-base type))
"SEXP_VOID")
(else
(make-integer (apply type-id-number type o)))))
(define (type-id-init-value type)
(cond
((lookup-type (type-base type))
(make-integer
(string-append "sexp_type_tag(" (type-id-name (type-base type)) ")")))
(else
(type-id-value type))))
(define (c-array-length type)
(if (memq 'result (type-array type))
"sexp_unbox_fixnum(res)"
"-1"))
(define (c-type-free? type)
(or (type-free? type)
(type-new? type)
(and (type-result? type)
(not (basic-type? type))
(not (type-no-free? type)))))
(define (c->scheme-converter type val . o)
(let ((base (type-base type)))
(cond
((and (eq? base 'void) (not (type-pointer? type)))
(cat "((" val "), SEXP_VOID)"))
((or (eq? base 'sexp) (error-type? type))
(cat val))
((memq base '(bool boolean status-bool))
(cat "sexp_make_boolean(" val ")"))
((eq? base 'time_t)
(cat "sexp_make_integer(ctx, sexp_shift_epoch(" val "))"))
((unsigned-int-type? base)
(cat "sexp_make_unsigned_integer(ctx, " val ")"))
((signed-int-type? base)
(cat "sexp_make_integer(ctx, " val ")"))
((float-type? base)
(cat "sexp_make_flonum(ctx, " val ")"))
((eq? base 'char)
(if (type-array type)
(cat "sexp_c_string(ctx, " val ", " (c-array-length type) ")")
(cat "sexp_make_character(" val ")")))
((eq? 'env-string base)
(cat "(p=strchr(" val ", '=') ? "
"sexp_cons(ctx, str=sexp_c_string(ctx, " val
", p - " val "), str=sexp_c_string(ctx, p, -1))"
" : sexp_cons(ctx, str=" val ", SEXP_FALSE)"))
((string-type? base)
(if (and *c++?* (eq? 'string base))
(cat "sexp_c_string(ctx, " val ".c_str(), " val ".size())")
(cat "sexp_c_string(ctx, " val ", " (c-array-length type) ")")))
((memq base '(bytevector u8vector))
(if *c++?*
(cat "sexp_string_to_bytes(ctx, sexp_c_string(ctx, "
val ".data(), " val ".size()))")
(cat "sexp_string_to_bytes(ctx, sexp_c_string(ctx, " val ", "
(c-array-length type val) "))")))
((eq? 'input-port base)
(cat "sexp_make_non_null_input_port(ctx, " val ", SEXP_FALSE)"))
((eq? 'output-port base)
(cat "sexp_make_non_null_output_port(ctx, " val ", SEXP_FALSE)"))
((eq? 'input-output-port base)
(cat "sexp_make_non_null_input_output_port(ctx, " val ", SEXP_FALSE)"))
((memq base '(fileno fileno-nonblock))
(cat "sexp_make_fileno(ctx, sexp_make_fixnum(" val "), SEXP_FALSE)"))
((eq? base 'uvector)
val)
((uniform-vector-type? base)
(cat "sexp_make_cuvector(ctx, " (uniform-vector-type-code base) ", "
val ", " (if (c-type-free? type) 1 0) ")"))
(else
(let ((ctype (lookup-type base))
(void*? (void-pointer-type? type)))
(cond
((or ctype void*?)
(cat "sexp_make_cpointer(ctx, "
(if void*?
"SEXP_CPOINTER"
;;(string-append "sexp_type_tag(" (type-id-name base) ")")
(type-id-number type #t))
", "
val ", " (or (and (pair? o) (car o)) "SEXP_FALSE") ", "
(if (c-type-free? type) 1 0)
")"))
(else
(error "unknown type" base))))))))
(define (scheme->c-converter type val)
(let* ((type (parse-type type))
(base (type-base type)))
(cond
((eq? base 'sexp)
(cat val))
((memq base '(bool boolean status-bool))
(cat "sexp_truep(" val ")"))
((eq? base 'time_t)
(cat "sexp_unshift_epoch(sexp_uint_value(" val "))"))
((enum-type? base)
=> (lambda (x) (cat "((" (cdr x) ")sexp_sint_value(" val "))")))
((signed-int-type? base)
(cat "sexp_sint_value(" val ")"))
((unsigned-int-type? base)
(cat "sexp_uint_value(" val ")"))
((float-type? base)
(cat "sexp_flonum_value(" val ")"))
((eq? base 'char)
(cat "sexp_unbox_character(" val ")"))
((eq? base 'env-string)
(cat "sexp_concat_env_string(" val ")"))
((string-type? base)
(cat (if (type-null? type)
"sexp_string_maybe_null_data"
"sexp_string_data")
"(" val ")"))
((memq base '(bytevector u8vector))
(cat (if (type-null? type)
"sexp_bytes_maybe_null_data"
"sexp_bytes_data")
"(" val ")"))
((eq? base 'port-or-fileno)
(cat "(sexp_portp(" val ") ? sexp_port_fileno(" val ")"
" : sexp_filenop(" val ") ? sexp_fileno_fd(" val ")"
" : sexp_unbox_fixnum(" val "))"))
((port-type? base)
(cat "sexp_port_stream(" val ")"))
((memq base '(fileno fileno-nonblock))
(cat "(sexp_filenop(" val ") ? sexp_fileno_fd(" val ")"
" : sexp_unbox_fixnum(" val "))"))
((uniform-vector-type? base)
(cat "((" (uniform-vector-ctype base) ") sexp_uvector_data(" val "))"))
(else
(let ((ctype (lookup-type base))
(void*? (void-pointer-type? type)))
(cond
((or ctype void*?)
(cat (if (or (type-struct? type) (type-reference? type)) "*" "")
"(" (type-c-name type) ")"
(if (type-address-of? type) "&" "")
(if (type-null? type)
"sexp_cpointer_maybe_null_value"
"sexp_cpointer_value")
"(" val ")"))
(else
(error "unknown type" base))))))))
(define (base-type-c-name base)
(case base
((string env-string non-null-string bytevector u8vector)
(if *c++?* "string" "char*"))
((fileno fileno-nonblock) "int")
((u1 u8 u16 u32 u64 s8 s16 s32 s64 f32 f64)
(let ((a
(uniform-vector-ctype
(string->symbol
(string-append (x->string base) "vector")))))
(substring a 0 (- (string-length a) 1))))
(else
(if (uniform-vector-type? base)
(uniform-vector-ctype base)
(string-replace (symbol->string base) #\- " ")))))
(define (type-struct-type type)
(let ((type-spec (lookup-type (if (vector? type) (type-base type) type))))
(cond ((and type-spec (memq 'type: type-spec)) => cadr)
(else #f))))
(define (type-c-name-derefed type)
(let* ((type (parse-type type))
(base (type-base type))
(type-spec (lookup-type base))
(struct-type (type-struct-type type)))
(string-append
(if (type-const? type) "const " "")
(if (and struct-type (not *c++?*))
(string-append (symbol->string struct-type) " ")
"")
(base-type-c-name base)
(if (type-template type)
(string-append
"<"
(string-concatenate (map type-c-name (type-template type)) ", ")
">")
""))))
(define (type-c-name type)
(let ((type (parse-type type)))
(string-append