File: easyffi.scm

package info (click to toggle)
chicken 1.63-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 27,072 kB
  • ctags: 39,156
  • sloc: ansic: 399,116; lisp: 50,264; sh: 8,206; makefile: 628
file content (949 lines) | stat: -rwxr-xr-x 33,837 bytes parent folder | download
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
;;;; easyffi.scm
;
; Copyright (c) 2000-2004, Felix L. Winkelmann
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
; conditions are met:
;
;   Redistributions of source code must retain the above copyright notice, this list of conditions and the following
;     disclaimer. 
;   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. 
;   Neither the name of the author nor the names of its contributors may be used to endorse or promote
;     products derived from this software without specific prior written permission. 
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDERS OR
; CONTRIBUTORS 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.
;
; Send bugs, suggestions and ideas to: 
;
; felix@call-with-current-continuation.org
;
; Felix L. Winkelmann
; Unter den Gleichen 1
; 37130 Gleichen
; Germany

#{compiler debugging-chicken used-units register-ffi-macro parse-easy-ffi ffi-include-path-list foreign-type-declaration 
	   foreign-declarations explicit-use-flag check-c-syntax no-c-syntax-checks}

(declare
  (unit easyffi)
  (compress-literals)
  (no-bound-checks)
  (no-procedure-checks)
  (export parse-easy-ffi register-ffi-macro used-units foreign-declarations number-type ffi-include-path-list
	  foreign-type-declaration explicit-use-flag debugging-chicken check-c-syntax no-c-syntax-checks) )

(eval-when (compile) (match-error-control #:unspecified))

(include "easyffi.l.silex")

(define use-finalizers #f)
(define exception-handler #f)
(define destructor-name 'destroy)
(define pp-mode #f)
(define processed-output '())
(define macro-table '((|CHICKEN| * ())))
(define pp-conditional-stack '())
(define pp-process #t)
(define type-map '())
(define ffi-include-path-list '("."))
(define export-constants #f)
(define prefix #f)
(define name-substitution-rxs '())
(define name-substitution-repls '())
(define declared-types '())
(define rename-list '())
(define abstract-classes '())
(define full-specialization #f)
(define defined-enums '())
(define parsing-error quit)

(define (pp-token tok)
  (if pp-mode
      tok
      (quit "FFI lexer error: preprocessor-command out of context: ~S" tok) ) )

(define (pp-token2 tok tok2)
  (if pp-mode tok tok2) )

(define (lexer-error)
  (parsing-error "FFI lexer error: illegal character") )

(define (chunkify)
  (let rec ([scope 0])
    (let ([chunks '()])
      (let loop ([mode #f] [tokens '()])
	(let ([t (lexer)])
	  (case t
	    [(stop) (reverse chunks)]
	    [(pp-end)
	     (set! chunks (cons (reverse tokens) chunks))
	     (loop #f '()) ]
	    [(pp-define pp-include pp-if pp-ifdef pp-ifndef pp-else pp-endif pp-undef pp-pragma pp-error)
	     (loop 'pp (list t)) ]
	    [(close-curly)
	     (cond [(not (positive? scope)) (parsing-error "`}' out of context")]
		   [(null? tokens) (reverse chunks)]
		   [else (cons (reverse tokens) chunks)] ) ]
	    [(open-curly)
	     (let ([new (rec (add1 scope))])
	       (set! chunks (cons (append-reverse tokens `((scope . ,new))) chunks))
	       (loop #f '()) ) ]
	    [(close-paren)
	     (if (eq? mode 'declare)
		 (begin
		   (set! chunks (cons (reverse (cons 'close-paren tokens)) chunks))
		   (loop #f '()) )
		 (loop mode (cons t tokens)) ) ]
	    [(declare)
	     (loop 'declare '(declare)) ]
	    [(semicolon)
	     (if mode
		 (parsing-error "unexpected semicolon")
		 (begin
		   (set! chunks (cons (reverse tokens) chunks))
		   (loop #f '()) ) ) ]
	    [else (loop mode (cons t tokens))] ) ) ) ) ) )

(define (parse c)
  (match c
    [() #f]
    [('pp-else)
     (when (null? pp-conditional-stack)
       (parsing-error "unbalanced preprocessor conditionals") )
     (set! pp-process (and (not (car pp-conditional-stack)) (every identity (cdr pp-conditional-stack)))) ]
    [('pp-endif)
     (when (null? pp-conditional-stack)
       (parsing-error "unbalanced preprocessor conditionals") )
     (set! pp-conditional-stack (cdr pp-conditional-stack))
     (set! pp-process (every identity pp-conditional-stack)) ]
    [('pp-ifdef ('id name))
     (set! pp-process (and pp-process (assq (string->symbol name) macro-table)))
     (set! pp-conditional-stack (cons pp-process pp-conditional-stack)) ]
    [('pp-ifndef ('id name))
     (set! pp-process (and pp-process (not (assq (string->symbol name) macro-table))))
     (set! pp-conditional-stack (cons pp-process pp-conditional-stack)) ]
    [('pp-if . _)
     (warning "preprocessor conditional `~A' ignored (assuming false)" c)
     (set! pp-process #f)
     (set! pp-conditional-stack (cons #f pp-conditional-stack)) ]
    [_ (when pp-process
	 (match c
	   [('pp-define ('id name))
	    (let ([s (string->symbol name)])
	      (set! macro-table (cons (list s '* '()) macro-table)) ) ]
	   [('pp-define ('id name) ('num n))
	    (let ([s (string->symbol name)])
	      (set! macro-table (cons (list s (if (exact? n) 'int 'double) `((num ,n))) macro-table))
	      (process-constant-def s n) ) ]
	   [('pp-define ('id name) . more)
	    (let ([t (compute-macro-type more)]
		  [s (string->symbol name)] )
	      (set! macro-table (cons (list s t more) macro-table))
	      (process-macro-def s t) ) ]
	   [('pp-undef ('id name))
	    (set! macro-table (delete (assq (string->symbol name) macro-table) eq?)) ]
	   [('pp-error msgs ...)
	    (parsing-error (string-intersperse (cons "(#error) " (map reparse-item msgs)) "")) ]
	   [('pp-include ((or 'string 'i-string) filename))
	    (let ([fname (resolve-ffi-include-file filename)])
	      (if fname
		  (call-with-input-file fname parse-easy-ffi-rec)
		  (parsing-error "can not open include file `~A'" filename) ) ) ]
	   [('pp-pragma . more) #f]
	   [('declare 'open-paren ('id decl) 'comma val 'close-paren)
	    (parse-declaration decl val) ]
	   [('declare . _)
	    (parsing-error "invalid syntax in pseudo declaration: ~S" c) ]
	   [_ (let ([cb #f] 
		    [ab #f]
		    [sp #f]
		    [dc #f]
		    [ds #f] )
		(let loop ([c (subst-macros c)])
		  (match c
		    [((or 'extern 'static 'volatile 'inline) . more)
		     (loop more) ]
		    [('abstract . more)
		     (set! ab #t)
		     (loop more) ]
		    [('specialize . more)
		     (set! sp #t)
		     (loop more) ]
		    [('callback . more)
		     (set! cb #t) 
		     (loop more) ]
		    [('discard . more)
		     (set! ds #t)
		     (loop more) ]
		    [('const . more)
		     (if (memq 'open-paren more)
			 (parse-prototype c cb sp dc ds)
			 (begin
			   (set! dc #t)
			   (loop more) ) ) ]
		    [('enum ('scope more))
		     (parse-enum-def #f (subst-macros more)) ]
		    [('enum ('id name) ('scope more))
		     (parse-enum-def name (subst-macros more)) ]
		    [('class . more)
		     (parse-class-def more ab) ]
		    [('struct ('id name)) #f]
		    [('using . more) #f]
		    [('typedef . more)
		     (parse-typedef more) ]
		    [(and more (('id name) . _))
		     (parse-prototype more cb sp dc ds) ]
		    [more
		     (parse-prototype more cb sp dc ds)] ) ) ) ] ) ) ] ) )

(define parse-again parse)

(define parse-type-rec
  (match-lambda
    [('const . more) 
     (let-values ([(t0 more) (parse-type-rec more)])
       (values `(const ,t0) more) ) ]
    [('unsigned t 'star . more)
     (let-values ([(t0 more) (parse-type-rec (cons* 'unsigned t more))])
       (values `(pointer ,t0) more) ) ]
    [('signed t 'star . more)
     (let-values ([(t0 more) (parse-type-rec (cons* 'signed t more))])
       (values `(pointer ,t0) more) ) ]
    [(t ('op "<") . more)
     (let*-values ([(ts more) (parse-typelist more)]
		   [(t0 _) (parse-type-rec (list t))] )
       (values `(template ,t0 ,@ts) more) ) ]
    [('signed . more) (parse-type-rec more)]
    [`(unsigned fixnum . ,more) (values 'unsigned-int more)]
    [`(unsigned int . ,more) (values (if (eq? number-type 'fixnum) 'unsigned-int 'unsigned-integer) more)]
    [`(unsigned char . ,more) (values 'unsigned-char more)]
    [`(unsigned short . ,more) (values 'unsigned-short more)]
    [`(unsigned long . ,more) (values 'unsigned-long more)]
    [`(void . ,more) (values 'void more)]
    [`(bool . ,more) (values 'bool more)]
    [`(unsigned byte . ,more) (values 'unsigned-byte more)]
    [`(byte . ,more) (values 'byte more)]
    [`(scheme-value . ,more) (values 'scheme-object more)]
    [`(fixnum . ,more) (values 'int more)]
    [`(int . ,more) (values (if (eq? number-type 'fixnum) 'int 'integer) more)]
    [`(char . ,more) (values 'char more)]
    [`(short . ,more) (values 'short more)]
    [`(long . ,more) (values 'long more)]
    [`(float . ,more) (values 'float more)]
    [`(double . ,more) (values 'double more)]
    [('struct ('id sname) . more) (values `(struct ,sname) more)]
    [('union ('id sname) . more) (values `(union ,sname) more)]
    [('enum ('id sname) . more) (values `(enum ,sname) more)]
    [(('id t) . more)
     (let ([st (string->symbol t)])
       (cond [(assq st type-map) => (lambda (a) (values (cdr a) more))]
	     [(memq st defined-enums) (values `(enum ,t) more)]
	     [(memq st declared-types) (values st more)]
	     [else (values t more)] ) ) ]
    [x (parsing-error "invalid type specifier: ~S" x)] ) )

(define (parse-type ts #!optional return-type discard)
  (let-values ([(t0 more) (parse-type-rec ts)])
    (let loop ([t0 t0] [more more])
      (match more
	[('star . more)
	 (loop `(pointer ,t0) more) ]
	[(('op "&") . more)
	 (loop `(ref ,t0) more) ]
	[('open-paren 'star . (or (('id _) 'close-paren 'open-paren . more) ('close-paren 'open-paren . more)))
	 (let-values ([(ts more) (parse-arglist more)])
	   (values `(function ,t0 ,ts) more) ) ]
	[_ (values (simplify-type t0 return-type discard) more)] ) ) ) )

(define (simplify-type t0 return-type discard)
  (define (strtype) (if discard 'c-string* 'c-string))
  (if return-type
      (match t0
	['(pointer char) (strtype)]
	['(pointer (const char)) (strtype)]
	[`(pointer ,(? string? t))
	 (let ([st (string->symbol t)])
	   (if (memq st defined-classes) 
	       `(instance ,t ,(fix-cname t))
	       t0) ) ] 
	[_ t0] )
      (let loop ([t1 t0])
	(match t1
	  [`(pointer (const ,t2)) (loop `(pointer ,t2))]
	  ['(pointer unsigned-fixnum) 'u32vector]
	  ['(pointer unsigned-integer) 'u32vector]
	  ['(pointer unsigned-short) 'u16vector]
	  ['(pointer unsigned-char) 'u8vector]
	  ['(pointer unsigned-byte) 'u8vector]
	  ['(pointer byte) 's8vector]
	  ['(pointer unsigned-long) 'u32vector]
	  ['(pointer fixnum) 's32vector]
	  ['(pointer integer) 's32vector]
	  ['(pointer int) 's32vector]
	  ['(pointer short) 's16vector]
	  ['(pointer char) (strtype)]
	  ['(pointer long) 's32vector]
	  ['(pointer float) 'f32vector]
	  ['(pointer double) 'f64vector]
	  [`(pointer ,(? string? t))
	   (let ([st (string->symbol t)])
	     (if (memq st defined-classes) 
		 `(instance ,t ,(fix-cname t))
		 t1) ) ] 
	  [_ t1] ) ) ) )

(define (parse-arglist ts)
  (let rec ([more ts] [args '()])
    (match more
      [('close-paren . more)
       (values (reverse args) more) ]
      [('dots . _)
       (parsing-error "varargs are not supported") ]
      [_ (let-values ([(type more) (parse-type more #f)])
	   (match more
	     [(('id str) 'comma . more)
	      (rec more (cons type args)) ]
	     [(('id str) 'close-paren . more)
	      (values (reverse (cons type args)) more) ]
	     [('comma . more) 
	      (rec more (cons type args)) ]
	     [('close-paren . more)
	      (values (reverse (cons type args)) more) ]
	     [_ (parsing-error "bad argument list syntax: ~S" more)] ) ) ] ) ) )

(define (parse-typelist ts)
  (let rec ([more ts] [ts '()])
    (match more
      [(('op ">") . more)
       (values (reverse ts) more) ]
      [_ (let-values ([(type more) (parse-type more #f)])
	   (match more
	     [('comma . more)
	      (rec more (cons type ts)) ]
	     [(('op ">") . more)
	      (values (reverse (cons type ts)) more) ]
	     [_ (parsing-error "bad template type list syntax: ~S" more)] ) ) ] ) ) )

(define (subst-macros chunk)
  (let loop ([c chunk])
    (match c
      [() '()]
      [((and x ('id name)) . more)
	(let ([a (assq (string->symbol name) macro-table)])
	  (if a
	      (loop (append (third a) more))
	      (cons x (loop more)) ) ) ]
      [(x . y) (cons x (loop y))] ) ) )

(define (parse-prototype ts cb sp const discard)
  (fluid-let ([full-specialization (or sp full-specialization)])
    (let-values ([(rtype more) (parse-type ts #t discard)])
      (let loop ([more more])
	(match more
	  [() #f]
	  [(('id str) ('op "::") . more) #f]
	  [(('id str) 'open-paren 'void 'close-paren . more)
	   (process-prototype-def rtype (string->symbol str) '() cb)
	   (match more
	     [(('scope . _) . more) (parse-again more)]
	     [() #f]
	     [_ (parsing-error "unexpected tokens: ~S" more)] ) ]
	  [(('id str) 'open-paren . more)
	   (let-values ([(args more) (parse-arglist more)])
	     (process-prototype-def rtype (string->symbol str) args cb)
	     (match more
	       [(('scope . _) . more) (parse-again more)]
	       [() #f]
	       [_ (parsing-error "unexpected tokens: ~S" more)] ) ) ]
	  [(('id str) 'comma . more)
	   (process-variable-def rtype (string->symbol str) const)
	   (loop more) ]
	  [(('id str))
	   (process-variable-def rtype (string->symbol str) const) ]
	  [(('id str) . (or (('op "=") . _) ()))
	   (process-variable-def rtype (string->symbol str) const) ]
	  [else (parsing-error "bad prototype syntax `~A'" more)] ) ) ) ) )

(define (parse-enum-def ename ts)
  (when ename (set! defined-enums (cons (string->symbol ename) defined-enums)))
  (let loop ([ts ts] [i 0] [items '()])
    (match ts
      [('close-curly) #f]
      [_ (let-values ([(sym val more) (parse-enum-item ts i)])
	   (let ([items (alist-cons sym val items)]
		 [i (add1 val)] )
	     (match more
	       [() (process-enum-def ename items)]
	       [('comma . more) (loop more i items)]
	       [_ (parsing-error "syntax error in enum form `~A'" more)] ) ) ) ] ) ) )

(define (parse-enum-item ts i)
  (match ts
    [(('id name) ('op "=") ('num n) . more)
     (if (integer? n)
	 (values (string->symbol name) n more) 
	 (error "non-exact enum value for `~A'" name) ) ]
    [(('id name) . more)
     (values (string->symbol name) i more) ] 
    [_ (parsing-error "invalid enum syntax `~A'" ts)] ) )

(define (parse-typedef ts)
  (let-values ([(type more) (parse-type ts #t)])
    (let loop ([more more] [type type])
      (match more
	[('star . more)
	 (loop more `(pointer ,type)) ]
	[(('id tname))
	 (set! type-map (alist-cons (string->symbol tname) (simplify-type type #t #f) type-map)) ]
	[_ (parsing-error "invalid typedef syntax `~A'" more)] ) ) ) )

(define has-constructor #f)
(define defined-classes '())

(define (parse-class-def ts ab)
  (match ts
    [(('id name)) 
     (set! defined-classes (cons (string->symbol name) defined-classes)) ]
    [(('id name) . more)
     (let ([sym (string->symbol name)])
       (set! defined-classes (cons sym defined-classes))
       (when ab (set! abstract-classes (cons sym abstract-classes))) )
     (let loop ([more more] [t '(op ":")] [bases '()])
       (if (and (pair? more) (equal? t (car more)))
	   (match more
	     [(_ (or 'public 'protected 'private) ('id bname) . more)
	      (loop more 'comma 
		    (if (memq (string->symbol bname) defined-classes)
			(cons bname bases)
			bases) ) ]
	     [(_ ('id bname) . more)
	      (loop more 'comma
		    (if (memq (string->symbol bname) defined-classes)
			(cons bname bases)
			bases) ) ]
	     [_ (parsing-error "invalid class definition for `~A': ~S" name more)] ) 
	   (match more
	     [(('scope . chunks))
	      (let ([cname (fix-cname name)]
		    [csname (string->symbol name)] )
		(process-class-def name cname bases)
		(fluid-let ([has-constructor #f])
		  (let ([exp #f])
		    (for-each
		     (lambda (chunk)
		       (let loop ([more (subst-macros chunk)])
			 (match more
			   [() #f]
			   [('public ('op ":") . more) 
			    (set! exp #t)
			    (loop more) ]
			   [((or 'private 'protected) ('op ":") . more) 
			    (set! exp #f)
			    (loop more) ]
			   [more 
			    (when exp 
			      (fluid-let ([parse-again loop])
				(parse-member-prototype name cname more #f #f) ) ) ] ) ) )
		     chunks)
		    (when (and (not has-constructor) (not (memq csname abstract-classes)))
		      (process-constructor-def name cname '()) ) ) ) ) ]
	     [_ (parsing-error "invalid class definition for `~A': ~S" name more)] ) ) ) ]
    [_ (parsing-error "invalid class definition: ~S" ts)] ) )

(define (parse-member-prototype name cname ts cb discard)
  (match ts
    [('specialize . more)
     (fluid-let ([full-specialization #t])
       (parse-member-prototype name cname more #t discard) ) ]
    [('callback . more) 
     (parse-member-prototype name cname more #t discard) ]
    [('discard . more)
     (parse-member-prototype name cname more cb #t) ]
    [((or 'explicit 'virtual) . more)
     (parse-member-prototype name cname more cb discard) ]
    [(('id name2) 'open-paren 'void 'close-paren . more)
     (if (string=? name2 name)
	 (begin
	   (process-constructor-def name cname '())
	   (set! has-constructor #t)
	   (match more
	     [(('scope . _) . more) (parse-again more)]
	     [() #f]
	     [_ (parsing-error "unexpected tokens: ~S" more)] ) )
	 (parsing-error "invalid constructor for `~A': ~S" name ts) ) ]
    [(('id name2) 'open-paren . more)
     (if (string=? name2 name)
	 (let-values ([(args more) (parse-arglist more)])
	   (process-constructor-def name cname args) 
	   (set! has-constructor #t)
	   (match more
	     [(('scope . _) . more) (parse-again more)]
	     [() #f]
	     [_ (parsing-error "unexpected tokens: ~S" more)] ) )
	 (parsing-error "invalid constructor for `~A': ~S" name ts) ) ]
    [(('op "~") ('id name2) 'open-paren . (or ('void 'close-paren . more) ('close-paren . more)))
     (if (string=? name2 name)
	 (match more
	   [(('scope . _) . more) (parse-again more)]
	   [() #f]
	   [_ (parsing-error "unexpected tokens: ~S" more)] )
	 (parsing-error "invalid destructor for `~A': ~S" name ts) ) ]
    [('static . more)
     (let-values ([(rtype more) (parse-type more #t)])
       (match more
	 [(('id str) 'open-paren 'void 'close-paren . more)
	    (process-prototype-def rtype (string->symbol (string-append name "::" str)) '() cb)
	    (match more
	      [(('scope . _) . more) (parse-again more)]
	      [() #f]
	      [_ (parsing-error "unexpected tokens: ~S" more)] ) ]
	 [(('id str) 'open-paren . more)
	  (let-values ([(args more) (parse-arglist more)])
	    (process-prototype-def rtype (string->symbol (string-append name "::" str)) args cb)
	    (match more
	      [(('scope . _) . more) (parse-again more)]
	      [() #f]
	      [_ (parsing-error "unexpected tokens: ~S" more)] ) ) ]
	 [_ (parsing-error "bad static member prototype syntax: ~S" more)] ) ) ]
    [_ (let-values ([(rtype more) (parse-type ts #t discard)])
	 (match more
	   [(('id str) 'open-paren 'void 'close-paren . more)
	    (process-member-prototype-def name cname rtype (string->symbol str) '() cb)
	    (parse-member-body more) ]
	   [(('id str) 'open-paren . more)
	    (let-values ([(args more) (parse-arglist more)])
	      (process-member-prototype-def name cname rtype (string->symbol str) args cb)
	      (parse-member-body more) ) ]
	   [(('id str) . (or (('op "=") . _) ()))
	    #f]				; member variables are ignored
	   [_ (parsing-error "bad member prototype syntax: ~S" more)] ) ) ] ) )

(define (parse-member-body ts)
  (let loop ([more ts])
    (match more
      [('const . more) (loop more)]
      [(('op "=") (num 0) . more) 
       (set! has-constructor #t)
       (loop more) ]
      [(('scope . _) . more) (parse-again more)]
      [() #f]
      [_ (parsing-error "unexpected tokens: ~S" more)] ) ) )

(define reparse-item 
  (match-lambda 
   ['pp-define "#define"]
   ['pp-include "#include"]
   ['pp-undef "#undef"]
   ['pp-ifndef "#ifndef"]
   ['pp-ifdef "#ifdef"]
   ['pp-if "#if"]
   ['pp-pragma "#pragma"]
   ['pp-error "#error"]
   ['pp-else "#else"]
   ['pp-endif "#endif"]
   [('id str) str]
   [('num num) num]
   [('op op) op]
   ['star "*"]
   ['open-paren "("]
   ['close-paren ")"]
   ['open-bracket "["]
   ['close-bracket "]"]
   ['open-curly "{"]
   ['close-curly "}"]
   ['fixnum "int"]
   ['comma ","]
   [('string str) (string-append "\"" str "\"")]
   [('i-string str) (string-append "<" str ">")]
   ['class "class"]
   ['protected "protected"]
   ['public "public"]
   ['private "private"]
   [c c] ) )

(define (type-union t1 t2)
  (cond [(eq? '_ t2) t1]
	[(eq? t1 t2) t1]
	[(eq? 'integer t1)
	 (case t2
	   [(double) 'double]
	   [else '*] ) ]
	[(and (eq? 'double t1) (eq? 'integer t2)) 'double]
	[else '*] ) )

(define (compute-macro-type ts)
  (let rec ([ts ts])
    (if (null? ts)
	'_
	(match (car ts)
	  [('num n) (type-union (if (exact? n) 'integer 'double) (rec (cdr ts)))]
	  [('id str)
	   (let ([a (assq (string->symbol str) macro-table)])
	     (if a 
		 (type-union (second a) (rec (cdr ts)))
		 '*) ) ]
	  [_ (rec (cdr ts))] ) ) ) )

(define (emit . xs)
  (when (memq '|F| debugging-chicken)
    (for-each pretty-print xs) )
  (set! processed-output (append-reverse xs processed-output)) )

(define (process-macro-def name type)
  (if (memq type '(* _))
      (warning "can not compute macro type `~A' (ignored)" name)
      (let ([name2 (fix-name name)])
	(emit `(define-foreign-variable ,name2 ,type ,(->string name)))
	(when export-constants (emit `(define ,name2 ,name2))) ) ) )

(define (process-constant-def name val)
  (let ([name (fix-name name)])
    (emit `(define-constant ,name ,val))
    (when export-constants (emit `(define ,name ,name))) ) )

(define (process-prototype-def rtype name args cb)
  (let ([name2 (fix-name name)])
    (emit
     (if (and full-specialization (pair? args))
	 (let ([slist (gen-spec-list args)]
	       [tmp (gensym)] )
	   `(begin
	      (declare (hide ,tmp))
	      (define ,tmp
		(,(if cb 'foreign-callback-lambda 'foreign-lambda)
		 ,rtype ,(->string name) ,@args) )
	      (define-method (,name2 ,@slist)
		(,tmp ,@(unzip1 slist) ) ) ) )
	 `(define ,name2
	    (,(if cb 'foreign-callback-lambda 'foreign-lambda)
	     ,rtype ,(->string name) ,@args))) ) ) )

(define (process-variable-def rtype name const)
  (let ([tmp (gensym)]
	[var (gensym)] 
	[name2 (fix-name name)] )
    (emit `(define-foreign-variable ,tmp ,rtype ,(->string name)))
    (if const
	(emit `(define ,name2 ,tmp))
	(emit `(define (,name2 . ,var)
		 (if (pair? ,var)
		     (set! ,tmp (car ,var))
		     ,tmp) ) ) ) ) )

(define (process-enum-def ename items)
  (for-each
   (match-lambda
     [(name . val)
      (let ([name (fix-name name)])
	(emit `(define-constant ,name ,val))
	(when export-constants (emit `(define ,name ,name))) ) ] )
   (reverse items) ) )

(define (process-class-def name cname basenames)
  (let ([destr (gensym)]
	[name2 (fix-name name)] 
	[csname (string->symbol name)] )
    (emit
     `(declare (hide ,destr))
     `(define-class ,cname
	,(if (null? basenames)
	     `(<c++-object>)
	     (map (lambda (b) (fix-cname b)) (reverse basenames) ) )
	() ) )
    (unless (memq csname abstract-classes)
      (emit
       `(define ,destr (foreign-lambda void "delete " (pointer ,name)))
       `(define-method (,destructor-name (this ,cname))
	  (,destr (slot-ref this 'this)) ) ) ) ) )

(define (process-constructor-def name cname args)
  (let ([constr (gensym)])
    (emit
     `(declare (hide ,constr))
     `(define ,constr (foreign-lambda (pointer ,name) ,(string-append "new " name) ,@args))
     `(define-method (initialize (this ,cname) initargs) 
	;; no CALL-NEXT-METHOD here: we don't want to invoke the base-class constructor.
	,@(if (and use-finalizers (not (memq (string->symbol name) abstract-classes)))
	      `((set-finalizer! this ,destructor-name))
	      '() )
	(slot-set! 
	 this 'this
	 (if (and (pair? initargs) (eq? 'this (##sys#slot initargs 0)))
	     (cadr initargs)
	     (apply ,constr initargs) ) ) ) ) ) )

(define (process-member-prototype-def name cname rtype mname args cb)
  (let* ([stub (gensym)]
	 [this (gensym)] 
	 [vars (map (lambda _ (gensym)) args)] 
	 [fvars (map list args vars)] )
    (emit 
     `(declare (hide ,stub))
     `(define ,stub 
	(,(if cb 'foreign-callback-lambda* 'foreign-lambda*)
	 ,rtype (((pointer ,name) ,this) ,@fvars)
	 ,(sprintf (let ([code (if (eq? 'void rtype) 
				   "~A->~A(~A);"
				   "return(~A->~A(~A));") ] )
		     (if exception-handler
			 (sprintf "try { ~A } ~A;" code exception-handler)
			 code) )
		   this mname
		   (string-intersperse (map ->string vars) ",")) ) )
     (if (and full-specialization (pair? args))
	 (let ([slist (gen-spec-list args)])
	   `(define-method (,(fix-name mname) (this ,cname) ,@slist)
	      (,stub (slot-ref this 'this) ,@(unzip1 slist) ) ) )
	 `(define-method (,(fix-name mname) (this ,cname) . args)
	    (apply ,stub (slot-ref this 'this) args) ) ) ) ) )

(define parse-declaration
  (match-lambda*
    [("export_constants" ('id "yes"))
     (set! export-constants #t) ]
    [("export_constants" _)
     (set! export-constants #f) ]
    [("abstract" ('id cls))
     (set! abstract-classes (cons (string->symbol cls) abstract-classes)) ]
    [("class_finalizers" ('id "yes"))
     (set! use-finalizers #t) ]
    [("class_finalizers" _)
     (set! use-finalizers #f) ]
    [("destructor_name")
     (set! destructor-name 'destroy) ]
    [("destructor_name" ('string name))
     (set! destructor-name (string->symbol name)) ]
    [("exception_handler" ('string code))
     (set! exception-handler code) ]
    [("prefix" ('string str))
     (set! prefix str) ]
    [("prefix" ('id "no"))
     (set! prefix #f) ]
    [("scheme" ('string str))
     (let ([exp (with-input-from-string str read)])
       (emit exp) ) ]
    [("type" ('string str))
     (parse-type-declaration (string-split str ";")) ]
    [("rename" ('string str))
     (match (string-split str ";")
       [(from to) 
	(set! rename-list (alist-cons (string->symbol from) (string->symbol to) rename-list)) ]
       [_ (parsing-error "invalid rename declaration: ~S" str)] ) ]
    [("substitute" ('string str))
     (match (string-split str ";")
       [(from to) 
	(set! name-substitution-rxs (append name-substitution-rxs (list from)))
	(set! name-substitution-repls (append name-substitution-repls (list to))) ]
       [_ (parsing-error "invalid name substitution string: ~S" str)] ) ]
    [("transform" ('string str))
     (match (string-split str ";")
       [(from to)
	(let ([tr (handle-exceptions ex (parsing-error "error in transformation expression: ~S" to)
		    (eval (safe-read-from-string to)) ) ] )
	  (unless (procedure? tr)
	    (parsing-error "transformation expression does not evaluate to procedure: ~S" to) )
	  (set! name-substitution-rxs (append name-substitution-rxs (list from)))
	  (set! name-substitution-repls (append name-substitution-repls (list tr))) ) ]
       [_ (parsing-error "invalid transformation: ~S" str)] ) ]
    [("full_specialization" ('id "yes"))
     (set! full-specialization #t) ]
    [("full_specialization" _)
     (set! full-specialization #f) ]
    [(decl _)
     (parsing-error "invalid pseudo declaration: ~S" decl) ] ) )

(define (safe-read-from-string str)
  (handle-exceptions ex (parsing-error "can not parse expression: ~S" str)
    (with-input-from-string str read) ) )

(define (parse-type-declaration vals)
  (let rec ([vals vals])
    (match vals
      [(tname stype arg ret)
       (let ([stype (safe-read-from-string stype)]
	     [arg (and arg (safe-read-from-string arg))]
	     [ret (and ret (safe-read-from-string ret))] 
	     [stname (string->symbol tname)] )
	 (set! foreign-declarations 
	   (cons (sprintf "#define ~A ~A~%" tname (foreign-type-declaration stype "")) foreign-declarations))
	 (emit 
	  `(define-foreign-type ,stname ,stype ,@(if arg (list arg) '()) ,@(if ret (list ret) '())) )
	 (set! declared-types (cons stname declared-types)) ) ]
      [(tname stype arg) (rec (list tname stype arg #f))]
      [(tname stype) (rec (list tname stype #f #f))]
      [_ (parsing-error "invalid value-syntax in type declaration: ~S" vals)] ) ) )

(define (fix-name str)
  (let ([a (assq (->symbol str) rename-list)])
    (if a 
	(cdr a)
	(let ([n1 (fold 
		   (lambda (rx repl str)
		     (if (procedure? repl)
			 (let ([m (string-match rx str)])
			   (if m (repl m) str) )
			 (string-substitute rx repl str #t) ) )
		   (->string str)
		   name-substitution-rxs
		   name-substitution-repls) ] )
	  (string->symbol
	   (strdowncase
	    (if prefix
		(string-append prefix n1)
		n1) ) ) ) ) ) )

(define (fix-cname str)
  (let ([a (assq (->symbol str) rename-list)])
    (if a 
	(cdr a)
	(string->symbol (string-append "<" (->string (fix-name str)) ">")) ) ) )

(define (->symbol s)
  (if (symbol? s)
      s
      (string->symbol s) ) )

(define (parse-easy-ffi text)
  (lexer-init 'string text)
  (set! processed-output '())
  (set! pp-conditional-stack '())
  (set! pp-process #t)
  (let ([chunks (chunkify)])
    ;;(pretty-print chunks)		
    (for-each parse chunks)
    (when (and (pair? defined-classes) 
	       (not (member "tinyclos" used-units))
	       (not explicit-use-flag) )
      (set! used-units (append used-units '("tinyclos"))) )
    (reverse processed-output) ) )

(define (parse-easy-ffi-rec port)
  (lexer-init 'port port)
  (let* ([output processed-output]
	 [chunks (chunkify)] )
    (set! processed-output '())
    (for-each parse chunks)
    (set! processed-output (append output processed-output)) ) )

(define (register-ffi-macro name)
  (set! macro-table (cons (list (string->symbol name) '* '()) macro-table)) )

(define (resolve-ffi-include-file fname)
  (find file-exists? (map (cut make-pathname <> fname) ffi-include-path-list)) )

(define (foreign-type->class ftype)
  (let rec ([ftype ftype])
    (match ftype
      ['char '<char>]
      ['bool '<boolean>]
      ['c-string '<string>]
      [(or 'unsigned-char 'int 'unsigned-int 'short 'unsigned-short) '<exact>]
      [(or 'long 'unsigned-long 'integer 'unsigned-integer) '<integer>]
      [(or 'float 'double) '<inexact>]
      [('enum _) '<exact>]
      [('const t) (rec t)]
      [('function . _) '<pointer>]
      [('instance _ c) c]
      [((or 'pointer 'c-pointer 'ref) _) '<pointer>]
      ['u8vector '<u8vector>]
      ['s8vector '<s8vector>]
      ['u16vector '<u16vector>]
      ['s16vector '<s16vector>]
      ['u32vector '<u32vector>]
      ['s32vector '<s32vector>]
      ['f32vector '<f32vector>]
      ['f64vector '<f64vector>]
      [_ '<top>] ) ) )

(define (gen-spec-list args)
  (map (lambda (t) (list (gensym) (foreign-type->class t))) args) )

(define strdowncase
  (let ([cs case-sensitive])
    (lambda (str)
      (if (cs)
	  str
	  (let ([s2 (string-copy str)]
		[len (string-length str)] )
	    (do ([i (sub1 len) (sub1 i)])
		((negative? i) s2)
	      (string-set! s2 i (char-downcase (string-ref str i))) ) ) ) ) ) )


;;; C syntax checker:

(define syntax-check-location #f)

(define (check-syntax-error text)
  (lambda (fstr . args)
    (quit #<<EOF
suspicious code fragment~A:
------------------------------------------------------------
~A
------------------------------------------------------------
~?
EOF
	  (if syntax-check-location
	      (sprintf " in `~A' form" syntax-check-location)
	      "")
	  text
	  fstr
	  args) ) )

(define (check-c-syntax text . loc)
  (unless no-c-syntax-checks
    (fluid-let ([parsing-error (check-syntax-error text)]
		[syntax-check-location (:optional loc #f)] )
      (define (checkp p s)
	(cond [(null? s) (parsing-error "unbalanced parantheses - missing match to `~A'" p)]
	      [(not (eq? p (car s)))
	       (parsing-error "unbalanced parantheses - expected `~A', but found `~A'" p (car s)) ] ) )
      (define (checkpp p s)
	(cond [(null? s) (parsing-error "unbalanced parantheses - missing match to `~A'" p)]
	      [(not (equal? p (car s)))
	       (parsing-error "unbalanced preprocessor conditional - expected `~A', but found `~A'" p (car s)) ] ) )
      (lexer-init 'string text)
      (set! pp-process #t)
      (let loop ([pstack '()] [ppstack '()])
	(let ([t (lexer)])
	  (case t
	    [(stop)
	     (when (pair? pstack)
	       (parsing-error "unbalanced parentheses - missing `~A'" (car pstack)) )
	     (when (pair? ppstack)
	       (parsing-error "unbalanced preprocessor command - missing `~A'" (car ppstack)) ) ]
	    [(pp-else)
	     (checkpp "#endif" ppstack) 
	     (loop pstack ppstack) ]
	    [(pp-endif)
	     (checkpp "#endif" ppstack) 
	     (loop pstack (cdr ppstack)) ]
	    [(pp-if pp-ifdef pp-ifndef)
	     (loop pstack (cons "#endif" ppstack)) ]
	    [(open-curly)
	     (loop (cons #\} pstack) ppstack) ]
	    [(close-curly)
	     (checkp #\} pstack) 
	     (loop (cdr pstack) ppstack) ]
	    [(open-paren)
	     (loop (cons #\) pstack) ppstack) ]
	    [(close-paren)
	     (checkp #\) pstack)
	     (loop (cdr pstack) ppstack) ] 
	    [(open-bracket)
	     (loop (cons #\] pstack) ppstack) ]
	    [(close-bracket)
	     (checkp #\] pstack)
	     (loop (cdr pstack) ppstack) ] 
	    [else (loop pstack ppstack)] ) ) ) ) ) )