forked from mflatt/racket
/
xform.rkt
4155 lines (3903 loc) · 221 KB
/
xform.rkt
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
(module xform racket/base
(require racket/list
(for-syntax racket/base)
racket/system)
(provide xform)
(define (xform quiet?
cpp
file-in
file-out
keep-lines?
palm? pgc? pgc-really?
precompiling-header? precompiled-header
show-info? output-depends-info?
gc-variable-stack-through-funcs?)
(parameterize ([current-output-port (current-output-port)] ; because we mutate these...
[error-escape-handler (error-escape-handler)]
[current-inspector (current-inspector)])
(let ()
(define power-inspector (current-inspector))
(current-inspector (make-inspector))
(define check-arith? #t)
;; Selects whether to reset GC_variable_stack on return,
;; or to just reset it on every call.
(define callee-restore? #t)
(define palm-out #f)
(define (filter-false s)
(if (equal? s "-")
#f
s))
(define source-is-c++? (regexp-match #rx"([.]cc$)|([.]cxx$)" file-in))
(define (change-suffix filename new)
(path-replace-suffix filename new))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; "AST" structures
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-struct tok (n line file) #:inspector (make-inspector))
(define-struct (sysheader-tok tok) ())
(define-struct (seq tok) (close in) #:inspector (make-inspector))
(define-struct (parens seq) () #:inspector (make-inspector))
(define-struct (brackets seq) ())
(define-struct (braces seq) ())
(define-struct (callstage-parens parens) ())
(define-struct (creation-parens parens) ())
(define-struct (nosrc-parens parens) ())
(define-struct (call tok) (func args live tag nonempty?)) ;; a converted function call
(define-struct (block-push tok) (vars tag super-tag top?))
(define-struct (note tok) (s))
(define-struct (nested-setup tok) ())
(define nested-pushable (make-nested-setup 'nested #f #f))
(define no-nested-pushable (make-nested-setup 'no-nested #f #f))
(define undefine-nested-pushable (make-nested-setup 'undefine #f #f))
(define-struct pragma (s file line))
;; For very long lists, it's worth the effort to use a vector instead
;; of a list to save space:
(define (seq->list s) (if (vector? s) (vector->list s) s))
(define (list->seq s) (if (or (null? s) (null? (cdr s)) (null? (cddr s)))
s
(list->vector s)))
(define seqce vector)
;; A cheap way of getting rid of unneeded prototypes:
(define used-symbols (make-hasheq))
(hash-set! used-symbols (string->symbol "GC_variable_stack") 1)
(hash-set! used-symbols (string->symbol "GC_cpp_delete") 1)
(hash-set! used-symbols (string->symbol "GC_get_variable_stack") 1)
(hash-set! used-symbols (string->symbol "GC_set_variable_stack") 1)
(hash-set! used-symbols (string->symbol "memset") 1)
(hash-set! used-symbols (string->symbol "scheme_thread_local_key") 1)
(hash-set! used-symbols (string->symbol "scheme_thread_locals") 1)
(hash-set! used-symbols (string->symbol "pthread_getspecific") 1)
(hash-set! used-symbols (string->symbol "scheme_get_mz_setjmp") 1)
;; For dependency tracking:
(define depends-files (make-hash))
(define (make-triple v src line sysheader?)
(when (symbol? v)
(hash-set! used-symbols v
(add1 (hash-ref
used-symbols
v
(lambda () 0)))))
(when (and src output-depends-info?)
(hash-set! depends-files src #t))
(if sysheader?
(make-sysheader-tok v line src)
(make-tok v line src)))
(define (make-a-seq opener src line body)
((case opener
[(#\() make-parens]
[(#\[) make-brackets]
[(#\{) make-braces])
(case opener
[(#\() "("]
[(#\[) "["]
[(#\{) "{"])
line
src
(case opener
[(#\() ")"]
[(#\[) "]"]
[(#\{) "}"])
(list->seq body)))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Tokenizer
;; Relies on make-triple, make-a-seq, and make-pragma
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (trans pattern)
(byte-regexp (string->bytes/utf-8 (format "^(~a)" pattern))))
(define (translations . t)
(let loop ([t t])
(if (null? t)
null
(let ([pattern (car t)]
[result (cadr t)])
(cons (cons (trans pattern)
result)
(loop (cddr t)))))))
(define (a-regexp-match-positions re s p)
(regexp-match-positions re s p))
(define seqs string-append)
(define startseq seqs)
(define (arbno s) (format "(?:~a)*" s))
(define (arbno/ s) (format "~a*" s))
(define (one+ s) (format "(?:~a)+" s))
(define (one+/ s) (format "~a+" s))
(define (maybe s) (format "(?:~a)?" s))
(define (maybe/ s) (format "~a?" s))
(define (alt a b) (format "~a|~a" a b))
(define (alt* . l)
(let loop ([l l])
(if (null? (cdr l))
(format "(?:~a)" (car l))
(format "(?:~a)|~a" (car l) (loop (cdr l))))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (line-comment s p)
(let loop ([p (add1 p)])
(let ([c (bytes-ref s p)])
(if (or (equal? c 10)
(equal? c 13))
(add1 p)
(loop (add1 p))))))
(define re:line #rx#"^#[^\n\r]* ([0-9]+) \"([^\"]*)\"([^\r\n]*)" )
(define re:pragma #rx#"^#pragma ([^\r\n]*)")
(define (do-cpp s p)
(let ([m (regexp-match re:line s p)])
(when m
(set! source-line (string->number (bytes->string/utf-8 (cadr m))))
(set! source-file (caddr m))
(set! source-sysheader? (regexp-match? #px#"\\b3\\b" (cadddr m)))))
(let ([pragma (regexp-match re:pragma s p)])
(if (and pragma
(not (regexp-match-positions re:boring (car pragma))))
(values (make-pragma (cadr pragma) source-file source-line) (line-comment s p))
(values #f (line-comment s p)))))
(define (result s)
(make-triple
s
source-file
source-line
source-sysheader?))
(define (symbol s)
(result (string->symbol (bytes->string/utf-8 s))))
(define re:octal #rx#"^0[0-9]+$")
(define re:int #rx#"^[0-9]*$")
(define (number s)
(result
(cond
[(regexp-match-positions re:octal s)
(string->number (bytes->string/utf-8 s) 8)]
[(regexp-match-positions re:int s)
(string->number (bytes->string/utf-8 s))]
[else (string->symbol (bytes->string/utf-8 s))])))
(define (character s)
(count-newlines s)
(symbol s))
(define (character? s)
(and (symbol? s)
(regexp-match #rx"'[\\]?.+'" (symbol->string s))))
(define (mk-string s)
(count-newlines s)
(result (bytes->string/utf-8 (subbytes s 1 (sub1 (bytes-length s))))))
(define (start s)
'start)
(define (stop s)
#f)
(define (count-newlines s)
(let loop ([p (sub1 (bytes-length s))])
(unless (= p -1)
(when (= 10 (bytes-ref s p))
(set! source-line (add1 source-line)))
(loop (sub1 p)))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define D "[0-9]")
(define L "[a-zA-Z_]")
(define H "[a-fA-F0-9]")
(define E (format "[Ee][+-]?~a+" D))
(define FS "(?:f|F|l|L)")
(define IS "(?:u|U|l|L)*")
(define symbol-complex (trans (seqs L (arbno (alt L D)))))
;; Accomodate things like 10_1 in `availability` attributes:
(define pseudo-symbol-complex (trans (seqs (arbno D) "_" (arbno D))))
(define number-complex
(trans (alt*
(seqs (arbno/ D) "[.]" (one+/ D) (maybe E) (maybe/ FS))
(seqs (one+/ D) "[.]" (arbno D) (maybe E) (maybe/ FS))
(seqs (one+/ D) E (maybe/ FS))
"0x1[.]0p2047" ;; strange thing in huge_val.h
(seqs "0" "[xX]" (one+/ H) IS) ;; hex
(seqs "0" (one+/ D) IS) ;; octal
(seqs (one+/ D) IS)))) ;; integer
(define char-complex (trans "'([^\\']|\\\\.)+'"))
(define string-complex (trans "\"([^\\\"]|\\\\.)*\""))
(define simple-table (make-vector 256 #f))
(define (simple-translations . l)
(let loop ([l l])
(unless (null? l)
(loop (cddr l))
(let* ([pattern (car l)]
[result (cadr l)]
[n (bytes-ref pattern 0)])
(vector-set! simple-table
n
(cons
(list* pattern (bytes-length pattern)
result)
(or
(vector-ref simple-table n)
null)))))))
(simple-translations
#"#" symbol
#"##" symbol
#"..." symbol
#">>=" symbol
#"<<=" symbol
#"+=" symbol
#"-=" symbol
#"*=" symbol
#"/=" symbol
#"%=" symbol
#"&=" symbol
#"^=" symbol
#"|=" symbol
#">>" symbol
#"<<" symbol
#"++" symbol
#"--" symbol
#"->" symbol
#"&&" symbol
#"||" symbol
#"<=" symbol
#">=" symbol
#"==" symbol
#"!=" symbol
#";" symbol
#"{" start
#"}" stop
#"," symbol
#"::" symbol
#":" symbol
#"=" symbol
#"(" start
#")" stop
#"[" start
#"]" stop
#"." #f ; => symbol/num
#"&" symbol
#"!" symbol
#"~" symbol
#"-" #f ; => symbol/num
#"+" #f ; => symbol/num
#"*" symbol
#"/" symbol
#"%" symbol
#"<" symbol
#">" symbol
#"^" symbol
#"|" symbol
#"?" symbol)
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define source-file #f)
(define source-line 0)
(define source-sysheader? #f)
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (read-all p)
(let loop ([l null])
(let ([s (read-bytes 4096 p)])
(if (eof-object? s)
(apply bytes-append (reverse l))
(loop (cons s l))))))
(define (tokenize)
(let* ([s (read-all (current-input-port))]
[len (bytes-length s)])
(let loop ([p 0][result null])
(if (= p len)
(cons (reverse result) p)
(let ([char (bytes-ref s p)])
(when (eq? char 10)
(set! source-line (add1 source-line)))
(cond
[(char-whitespace? (integer->char char))
(loop (add1 p) result)]
[(eq? char (char->integer #\#)) ;; We assume only #-based preprocessor left
(let-values ([(pragma p) (do-cpp s p)])
(if pragma
(loop p (cons pragma result))
(loop p result)))]
[else
(let ([simple (let ([sl (vector-ref simple-table char)])
(and sl
(ormap
(lambda (t)
(and (or (= 1 (cadr t))
(bytes=? (car t) (subbytes s p (+ p (cadr t)))))
(let ([f (cddr t)])
(if f
(cons (f (car t))
(+ p (cadr t)))
(let ([m (regexp-match-positions number-complex s p)])
(if m
(cons (number (subbytes s (caar m) (cdar m)))
(cdar m))
(cons (symbol (car t))
(+ p (cadr t)))))))))
sl)))])
(cond
[(not simple)
(cond
[(regexp-match-positions symbol-complex s p)
=> (lambda (m)
(loop (cdar m)
(cons (symbol (subbytes s (caar m) (cdar m)))
result)))]
[(regexp-match-positions pseudo-symbol-complex s p)
=> (lambda (m)
(loop (cdar m)
(cons (symbol (subbytes s (caar m) (cdar m)))
result)))]
[(regexp-match-positions number-complex s p)
=> (lambda (m)
(loop (cdar m)
(cons (number (subbytes s (caar m) (cdar m)))
result)))]
[(regexp-match-positions char-complex s p)
=> (lambda (m)
(loop (cdar m)
(cons (character (subbytes s (caar m) (cdar m)))
result)))]
[(regexp-match-positions string-complex s p)
=> (lambda (m)
(loop (cdar m)
(cons (mk-string (subbytes s (caar m) (cdar m)))
result)))]
[else
(error 'c-tokenize "strange: ~e ~e" p (subbytes s p (min len (+ p 100))))])]
[(not (car simple))
(cons (reverse result) (cdr simple))]
[(eq? (car simple) 'start)
(let ([sf source-file]
[sl source-line]
[sub (loop (cdr simple) null)])
(loop (cdr sub) (cons (make-a-seq
(integer->char (bytes-ref s p))
sf
sl
(car sub))
result)))]
[simple
(loop (cdr simple) (cons (car simple) result))]))]))))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Pre-process and S-expr-ize
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (verbose f)
(if quiet?
f
(lambda args
(printf "xform-cpp: ~a\n" args)
(apply f args))))
(define (maybe-add-exe p)
(cond
[(and (eq? 'windows (system-type))
(not (regexp-match? #rx"[.]exe$" p)))
(format "~a.exe" p)]
[else p]))
;; To run cpp:
(define process2
(if (eq? (system-type) 'windows)
(lambda (s)
(let ([split (let loop ([s s])
(let ([m (regexp-match #rx"([^ ]*) +(.*)" s)])
(if m
(cons (cadr m) (loop (caddr m)))
(list s))))])
(apply (verbose process*) (find-executable-path (maybe-add-exe (car split)) #f)
(cdr split))))
(verbose process)))
(define cpp-process
(if (string? cpp)
(process2 (format "~a~a~a ~a"
cpp
(if pgc?
(if pgc-really?
" -DMZ_XFORM -DMZ_PRECISE_GC"
" -DMZ_XFORM")
"")
(if callee-restore? " -DGC_STACK_CALLEE_RESTORE" "")
file-in))
(apply (verbose process*)
(append
cpp
(if pgc-really?
'("-DMZ_XFORM" "-DMZ_PRECISE_GC")
'("-DMZ_XFORM"))
(if callee-restore?
'("-DGC_STACK_CALLEE_RESTORE")
null)
(list file-in)))))
(close-output-port (cadr cpp-process))
(define (mk-error-thread proc)
(thread (lambda ()
(let loop ()
(let ([l (read-bytes-line (list-ref proc 3) 'any)])
(unless (eof-object? l)
(eprintf "~a\n" l)
(loop))))
(close-input-port (list-ref proc 3)))))
(define cpp-error-thread (mk-error-thread cpp-process))
;; Pipe cpp results through here; we insert a filter
;; between the pipe ends.
(define-values (local-ctok-read local-ctok-write)
(make-pipe 100000))
(define recorded-cpp-out
(and precompiling-header?
(open-output-file (change-suffix file-out #".e") #:exists 'truncate)))
(define recorded-cpp-in
(and precompiled-header
(open-input-file (change-suffix precompiled-header #".e"))))
(define re:boring #rx#"^(?:(?:[ \t]*)|(?:# .*)|(?:#line .*)|(?:#pragma implementation.*)|(?:#pragma interface.*)|(?:#pragma once)|(?:#pragma warning.*)|(?:#ident.*))$")
(define re:uninteresting #rx#"^(?:(?:[ \t]*)|(?:# .*)|(?:#line .*)|(?:#pragma implementation.*)|(?:#pragma interface.*)|(?:#pragma once)|(?:#pragma GCC diagnostic.*)|(?:#pragma warning.*)|(?:#ident.*))$")
(define (skip-to-interesting-line p)
(let ([l (read-bytes-line p 'any)])
(cond
[(eof-object? l) l]
[(regexp-match-positions re:uninteresting l) (skip-to-interesting-line p)]
[else l])))
(when recorded-cpp-in
;; Skip over common part:
(let loop ([lpos 1])
(let ([pl (read-bytes-line recorded-cpp-in 'any)])
(unless (eof-object? pl)
(let ([l (skip-to-interesting-line (car cpp-process))])
(unless (equal? pl l)
(error 'precompiled-header "line mismatch with precompiled: ~s (line ~a) versus ~s"
pl
lpos
l))
(loop (add1 lpos))))))
(close-input-port recorded-cpp-in))
;; cpp output to ctok input, also writes filtered lines to
;; cpp-out when reading a recompiled header
(thread (lambda ()
(if recorded-cpp-out
;; line-by-line, so we can filter:
(begin
(let loop ()
(let ([l (read-bytes-line (car cpp-process) 'any)])
(unless (eof-object? l)
(unless (regexp-match-positions re:boring l)
(display l recorded-cpp-out)
(newline recorded-cpp-out))
(display l local-ctok-write)
(newline local-ctok-write)
(loop))))
(close-output-port recorded-cpp-out)
(close-input-port (car cpp-process))
(close-output-port local-ctok-write))
;; block copy:
(let ([s (make-bytes 4096)])
(let loop ()
(let ([l (read-bytes-avail! s (car cpp-process))])
(unless (eof-object? l)
(write-bytes s local-ctok-write 0 l)
(loop))))
(close-input-port (car cpp-process))
(close-output-port local-ctok-write)))))
(define e-raw #f)
(define read-thread
(thread
(lambda ()
(parameterize ([current-input-port local-ctok-read])
(set! e-raw (car (tokenize)))))))
((list-ref cpp-process 4) 'wait)
(thread-wait cpp-error-thread)
(when (eq? ((list-ref cpp-process 4) 'status) 'done-error)
(error 'xform "cpp failed"))
(thread-wait read-thread)
(set! read-thread #f)
(when (exn? e-raw)
(raise e-raw))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Output and error-handling
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(current-output-port (if file-out
(open-output-file file-out #:exists 'truncate)
(make-output-port 'dev/null
always-evt
(lambda (s st ed f?)
(- ed st))
void)))
(let ([eh (error-escape-handler)])
(error-escape-handler
(lambda ()
(close-output-port (current-output-port))
(current-output-port (current-error-port))
(when file-out
(delete-file file-out))
(eh))))
(define exit-with-error? #f)
(define (log-error format . args)
(eprintf "Error ")
(apply eprintf format args)
(newline (current-error-port))
(set! exit-with-error? #t))
(define log-warning log-error)
(define map-port
(if palm-out
(open-output-file palm-out #:exists 'truncate)
#f))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Output common defns
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define per-block-push? #t)
(define gc-var-stack-mode
(let loop ([e-raw e-raw])
(ormap (lambda (e)
(cond
[(and (pragma? e)
(regexp-match #rx"GC_VARIABLE_STACK_THOUGH_TABLE" (pragma-s e)))
'table]
[(and (tok? e)
(eq? (tok-n e) 'XFORM_GC_VARIABLE_STACK_THROUGH_THREAD_LOCAL))
'thread-local]
[(and (tok? e)
(eq? (tok-n e) 'XFORM_GC_VARIABLE_STACK_THROUGH_GETSPECIFIC))
'getspecific]
[(and (tok? e)
(eq? (tok-n e) 'XFORM_GC_VARIABLE_STACK_THROUGH_FUNCTION))
'function]
[(and (tok? e)
(eq? (tok-n e) 'XFORM_GC_VARIABLE_STACK_THROUGH_DIRECT_FUNCTION))
'direct-function]
[(braces? e) (loop (seq->list (seq-in e)))]
[else #f]))
e-raw)))
;; The code produced by xform uses a number of macros. These macros
;; make the transformation about a little easier to debug, and they
;; enable experimentation with different variable-registration
;; strategies without modifying the xform process.
(when (and pgc? (not precompiled-header))
;; Setup GC_variable_stack macro
(printf (case gc-var-stack-mode
[(table)
"#define GC_VARIABLE_STACK (scheme_extension_table->GC_variable_stack)\n"]
[(getspecific)
"#define GC_VARIABLE_STACK (((Thread_Local_Variables *)pthread_getspecific(scheme_thread_local_key))->GC_variable_stack_)\n"]
[(function)
"#define GC_VARIABLE_STACK ((scheme_get_thread_local_variables())->GC_variable_stack_)\n"]
[(thread-local)
"#define GC_VARIABLE_STACK ((&scheme_thread_locals)->GC_variable_stack_)\n"]
[else "#define GC_VARIABLE_STACK GC_variable_stack\n"]))
(if (or gc-variable-stack-through-funcs?
(eq? gc-var-stack-mode 'direct-function))
(begin
(printf "#define GET_GC_VARIABLE_STACK() GC_get_variable_stack()\n")
(printf "#define SET_GC_VARIABLE_STACK(v) GC_set_variable_stack(v)\n"))
(begin
(printf "#define GET_GC_VARIABLE_STACK() GC_VARIABLE_STACK\n")
(printf "#define SET_GC_VARIABLE_STACK(v) (GC_VARIABLE_STACK = (v))\n")))
;; Declare stack-registration record of a particular size:
(printf (string-append
"#define PREPARE_VAR_STACK(size) void *__gc_var_stack__[size+2]; __gc_var_stack__[0] = GET_GC_VARIABLE_STACK();"
(if callee-restore?
" SET_GC_VARIABLE_STACK(__gc_var_stack__);"
"")
"\n"))
;; Same, but in a function where the number of registered variables
;; never changes within the procedure (i.e., in nested blocks):
(printf "#define PREPARE_VAR_STACK_ONCE(size) PREPARE_VAR_STACK(size); __gc_var_stack__[1] = (void *)size;\n")
;; Full setup to use before a function call, normally used with FUNCCALL:
(printf (string-append
"#define SETUP(x) ("
(if callee-restore?
""
"SET_GC_VARIABLE_STACK(__gc_var_stack__), ")
"__gc_var_stack__[1] = (void *)x)\n"))
;; Debugging support:
(printf "#ifdef MZ_3M_CHECK_VAR_STACK\n")
(printf "static int _bad_var_stack_() { *(long *)0x0 = 1; return 0; }\n")
(printf "# define CHECK_GC_V_S ((GC_VARIABLE_STACK == __gc_var_stack__) ? 0 : _bad_var_stack_()),\n")
(printf "#else\n")
(printf "# define CHECK_GC_V_S /*empty*/\n")
(printf "#endif\n")
;; Call a function where the number of registered variables can change in
;; nested blocks:
(printf "#define FUNCCALL_each(setup, x) (CHECK_GC_V_S setup, x)\n")
;; The same, but a "tail" call:
(printf "#define FUNCCALL_EMPTY_each(x) (SET_GC_VARIABLE_STACK((void **)__gc_var_stack__[0]), x)\n")
;; The same, but the number of registered variables for this call is definitely
;; the same as for the previous call:
(printf (if callee-restore?
"#define FUNCCALL_AGAIN_each(x) (CHECK_GC_V_S x)\n"
"#define FUNCCALL_AGAIN_each(x) FUNCCALL_each(SET_GC_VARIABLE_STACK(__gc_var_stack__), x)\n"))
;; As above, but when the number of registered variables never changes
;; within a procedure:
(printf "#define FUNCCALL_once(setup, x) FUNCCALL_AGAIN_each(x)\n")
(printf "#define FUNCCALL_EMPTY_once(x) FUNCCALL_EMPTY_each(x)\n")
(printf "#define FUNCCALL_AGAIN_once(x) FUNCCALL_AGAIN_each(x)\n")
;; Register a particular variable locally:
(printf "#define PUSH(v, x) (__gc_var_stack__[x+2] = (void *)&(v))\n")
;; Register a particular array variable locally:
(printf (string-append
"#define PUSHARRAY(v, l, x) (__gc_var_stack__[x+2] = (void *)0, __gc_var_stack__[x+3] = (void *)&(v), "
"__gc_var_stack__[x+4] = (void *)l)\n"))
;; Wraps code to setup a block's variables:
(printf "#define BLOCK_SETUP_TOP(x) ~a\n" (if per-block-push? "x" "/* skipped */"))
;; Same, but specifically in a function where nested blocks register
;; extra variables:
(printf "#define BLOCK_SETUP_each(x) BLOCK_SETUP_TOP(x)\n")
;; Same, but specifically in a function where nested blocks DO NOT
;; register extra variables:
(printf "#define BLOCK_SETUP_once(x) /* no effect */\n")
;; Wrap a normal return:
(printf (if callee-restore?
"#define RET_VALUE_START return (__ret__val__ = \n"
"#define RET_VALUE_START return\n"))
(printf (if callee-restore?
"#define RET_VALUE_END , SET_GC_VARIABLE_STACK((void **)__gc_var_stack__[0]), __ret__val__)\n"
"#define RET_VALUE_END \n"))
;; Wrap a return where the value is produced by a FUNCCALL_EMPTY expression:
(printf "#define RET_VALUE_EMPTY_START return\n")
(printf "#define RET_VALUE_EMPTY_END \n")
;; Replacement for non-value return:
(printf "#define RET_NOTHING { SET_GC_VARIABLE_STACK((void **)__gc_var_stack__[0]); return; }\n")
;; A non-value return inserted at the end of a void-returning function:
(printf "#define RET_NOTHING_AT_END RET_NOTHING\n")
;; Declare a temp variable to hold the return value of the indicated type:
(printf (if callee-restore?
"#define DECL_RET_SAVE(type) type __ret__val__;\n"
"#define DECL_RET_SAVE(type) /**/\n"))
;; Value used to initialize pointer variables:
(printf "#define NULLED_OUT 0\n")
;; Macro to initialize a pointer array:
(printf "#define NULL_OUT_ARRAY(a) memset(a, 0, sizeof(a))\n")
;; Annotation that normally disappears:
(printf "#define GC_CAN_IGNORE /**/\n")
(printf "#define XFORM_CAN_IGNORE /**/\n")
(printf "#define __xform_nongcing__ /**/\n")
;; Another annotation to protect against GC conversion:
(printf "#define HIDE_FROM_XFORM(x) x\n")
(printf "#define XFORM_HIDE_EXPR(x) x\n")
(printf "#define HIDE_NOTHING_FROM_XFORM() /**/\n")
;; In case a conversion is unnecessary where we have this annotation:
(printf "#define START_XFORM_SKIP /**/\n")
(printf "#define END_XFORM_SKIP /**/\n")
(printf "#define START_XFORM_SUSPEND /**/\n")
(printf "#define END_XFORM_SUSPEND /**/\n")
(printf "#define XFORM_START_SKIP /**/\n")
(printf "#define XFORM_END_SKIP /**/\n")
(printf "#define XFORM_START_SUSPEND /**/\n")
(printf "#define XFORM_END_SUSPEND /**/\n")
(printf "#define XFORM_SKIP_PROC /**/\n")
;; For avoiding warnings:
(printf "#define XFORM_OK_PLUS +\n")
(printf "#define XFORM_OK_MINUS -\n")
(printf "#define XFORM_TRUST_PLUS +\n")
(printf "#define XFORM_TRUST_MINUS -\n")
(printf "#define XFORM_OK_ASSIGN /**/\n")
(printf "\n")
;; C++ cupport:
(printf "#define NEW_OBJ(t) new (UseGC) t\n")
(printf "#define NEW_ARRAY(t, array) (new (UseGC) t array)\n")
(printf "#define NEW_ATOM(t) (new (AtomicGC) t)\n")
(printf "#define NEW_PTR(t) (new (UseGC) t)\n")
(printf "#define NEW_ATOM_ARRAY(t, array) (new (AtomicGC) t array)\n")
(printf "#define NEW_PTR_ARRAY(t, array) (new (UseGC) t* array)\n")
(printf "#define DELETE(x) (delete x)\n")
(printf "#define DELETE_ARRAY(x) (delete[] x)\n")
(printf (if callee-restore?
"#define XFORM_RESET_VAR_STACK /* empty */\n"
"#define XFORM_RESET_VAR_STACK SET_GC_VARIABLE_STACK((void **)__gc_var_stack__[0]);\n"))
;; Indirect setjmp support:
(printf "#define scheme_mz_setjmp_post_xform(s) ((scheme_get_mz_setjmp())(s))\n")
(unless pgc-really?
(printf "#include \"cgc2.h\"\n"))
(printf "\n"))
(when (and pgc? precompiled-header)
(printf "#include \"~a\"\n" (let-values ([(base name dir?) (split-path precompiled-header)])
(path->string name))))
(when palm?
(printf "#include \"segmap.h\"\n"))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Structures and constants
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; vtype and its substructs describe the shape of a local variable:
(define-struct vtype ())
(define-struct (pointer-type vtype) (base stars))
(define-struct (array-type vtype) (count))
(define-struct (struc-type vtype) (struct))
(define-struct (struct-array-type struc-type) (count))
(define-struct (union-type vtype) ())
(define-struct (non-pointer-type vtype) (base))
;; A live-var-info struct is threaded through the conversion process
;; on a function body. It keeps information about which variables
;; are live, which variables were invented along the way, how long
;; the __gc_var_stack__ array needs to be, and so on.
(define-struct live-var-info (tag
maxlive
maxpush
vars
new-vars
pushed-vars
num-calls
num-noreturn-calls
num-empty-calls
nonempty-calls?))
;; A function prototype record:
(define-struct prototype (type args static? pointer? pointer?-determined?) #:mutable)
;; A C++ class record:
(define-struct c++-class (parent parent-name prototyped top-vars) #:mutable)
;; Symbol constants:
(define semi (string->symbol ";"))
(define START_XFORM_SKIP (string->symbol "START_XFORM_SKIP"))
(define END_XFORM_SKIP (string->symbol "END_XFORM_SKIP"))
(define START_XFORM_SUSPEND (string->symbol "START_XFORM_SUSPEND"))
(define END_XFORM_SUSPEND (string->symbol "END_XFORM_SUSPEND"))
(define Scheme_Object (string->symbol "Scheme_Object"))
(define sElF (string->symbol "sElF"))
(define NULLED_OUT (string->symbol "NULLED_OUT"))
(define NULL_OUT_ARRAY (string->symbol "NULL_OUT_ARRAY"))
(define gcMark (string->symbol "gcMark"))
(define gcFixup (string->symbol "gcFixup"))
(define gcMARK_TYPED (string->symbol "gcMARK_TYPED"))
(define gcFIXUP_TYPED (string->symbol "gcFIXUP_TYPED"))
(define Mark_Proc (string->symbol "Mark_Proc"))
(define gcBYTES_TO_WORDS (string->symbol "gcBYTES_TO_WORDS"))
(define GC_cpp_delete (string->symbol "GC_cpp_delete"))
(define PRE_ALLOCATE (string->symbol "PRE_ALLOCATE"))
(define NEW_OBJ (string->symbol "NEW_OBJ"))
(define NEW_ARRAY (string->symbol "NEW_ARRAY"))
(define NEW_ATOM (string->symbol "NEW_ATOM"))
(define NEW_PTR (string->symbol "NEW_PTR"))
(define NEW_ATOM_ARRAY (string->symbol "NEW_ATOM_ARRAY"))
(define NEW_PTR_ARRAY (string->symbol "NEW_PTR_ARRAY"))
(define DELETE (string->symbol "DELETE"))
(define DELETE_ARRAY (string->symbol "DELETE_ARRAY"))
(define CURRENT_NEW_THIS (string->symbol "CURRENT_NEW_THIS"))
(define RESTORE_CURRENT_NEW_VAR_STACK (string->symbol "RESTORE_CURRENT_NEW_VAR_STACK"))
(define XFORM_RESET_VAR_STACK (string->symbol "XFORM_RESET_VAR_STACK"))
(define END_XFORM_ARITH (string->symbol "END_XFORM_ARITH"))
(define START_XFORM_ARITH (string->symbol "START_XFORM_ARITH"))
(define GC_CAN_IGNORE (string->symbol "GC_CAN_IGNORE"))
(define RET_VALUE_START (string->symbol "RET_VALUE_START"))
(define RET_VALUE_END (string->symbol "RET_VALUE_END"))
(define RET_VALUE_EMPTY_START (string->symbol "RET_VALUE_EMPTY_START"))
(define RET_VALUE_EMPTY_END (string->symbol "RET_VALUE_EMPTY_END"))
(define RET_NOTHING (string->symbol "RET_NOTHING"))
(define RET_NOTHING_AT_END (string->symbol "RET_NOTHING_AT_END"))
(define DECL_RET_SAVE (string->symbol "DECL_RET_SAVE"))
(define __attribute__ (string->symbol "__attribute__"))
(define re:_stk_ (regexp "^_stk_"))
;; These don't act like functions, but we need to treat them
;; specially:
(define setjmp-functions
'(setjmp _setjmp scheme_setjmp scheme_mz_setjmp scheme_mz_setjmp_post_xform))
;; The non-functions table identifies symbols to ignore when
;; finding function calls
(define non-functions
'(<= < > >= == != !
\| \|\| & && |:| ? % + - * / ^ >> << ~
#csXFORM_OK_PLUS #csXFORM_OK_MINUS #csXFORM_TRUST_PLUS #csXFORM_TRUST_MINUS
= >>= <<= ^= += *= /= -= %= \|= &= ++ --
return if for while else switch case XFORM_OK_ASSIGN
asm __asm __asm__ __volatile __volatile__ volatile __extension__
__typeof sizeof __builtin_object_size
;; These don't act like functions:
setjmp longjmp _longjmp scheme_longjmp_setjmp scheme_mz_longjmp scheme_jit_longjmp
scheme_jit_setjmp_prepare
scheme_get_thread_local_variables pthread_getspecific
__builtin_frame_address
;; The following are functions, but they don't trigger GC, and
;; they either take one argument or no pointer arguments.
;; So we can ignore them:
__get_errno_ptr ; QNX preprocesses errno to __get_errno_ptr
__getreent ; Cygwin
strlen cos cosl sin sinl exp expl pow powl log logl sqrt sqrtl atan2 atan2l frexp
isnan isinf fpclass signbit _signbit _fpclass __fpclassify __fpclassifyf __fpclassifyl
_isnan __isfinited __isnanl __isnan __signbit __signbitf __signbitd __signbitl
__isinff __isinfl isnanf isinff __isinfd __isnanf __isnand __isinf
__inline_isnanl __inline_isnan __inline_signbitf __inline_signbitd __inline_signbitl
__builtin_popcount __builtin_clz __builtin_isnan __builtin_isinf __builtin_signbit
__builtin_signbitf __builtin_signbitd __builtin_signbitl __builtin_isinf_sign
_Generic
__inline_isinff __inline_isinfl __inline_isinfd __inline_isnanf __inline_isnand __inline_isinf
floor floorl ceil ceill round roundl fmod fmodl modf modfl fabs fabsl __maskrune _errno __errno
isalpha isdigit isspace tolower toupper
fread fwrite socket fcntl setsockopt connect send recv close
__builtin_next_arg __builtin_saveregs
__builtin_constant_p __builtin_choose_expr __builtin_types_compatible_p
__builtin___CFStringMakeConstantString
__error __errno_location __toupper __tolower ___errno
__attribute__ __mode__ ; not really functions in gcc
__iob_func ; VC 8
__acrt_iob_func ; VC 14.0 (2015)
|GetStdHandle| |__CFStringMakeConstantString|
_vswprintf_c
scheme_make_small_bignum scheme_make_small_rational scheme_make_small_complex))
(define non-functions-table
(let ([ht (make-hasheq)])
(for-each (lambda (s)
(hash-set! ht s #f))
non-functions)
ht))
(define args-unevaled '(sizeof __typeof __builtin_object_size))
(define args-unevaled-table
(let ([ht (make-hasheq)])
(for-each (lambda (s)
(hash-set! ht s #t))
args-unevaled)
ht))
(define non-gcing-builtin-functions
;; The following don't need wrappers, but we need to check for
;; nested function calls because it takes more than one argument:
(append
'(memcpy memmove memcmp memset
__builtin___memmove_chk __inline_memmove_chk
__builtin___memcpy_chk __inline_memcpy_chk
__builtin___memset_chk __inline_memset_chk
__builtin___memcmp_chk __inline_memcmp_chk
strcmp strcoll strcpy _mzstrcpy strcat
__builtin_memset
printf sprintf vsprintf vprintf
strncmp
read write)
(map
string->symbol
'("XTextExtents" "XTextExtents16"
"XDrawImageString16" "XDrawImageString"
"XDrawString16" "XDrawString"))))
(define non-gcing-functions (make-hasheq))
(for-each (lambda (name)
(hash-set! non-gcing-functions name #t))
non-gcing-builtin-functions)
(define non-returning-functions
;; The following functions never return, so the wrappers
;; don't need to push any variables:
'(exit
scheme_wrong_type scheme_wrong_number scheme_wrong_syntax
scheme_wrong_count scheme_wrong_count_m scheme_wrong_rator scheme_read_err
scheme_wrong_contract scheme_contract_error
scheme_raise_exn scheme_signal_error
scheme_raise_out_of_memory
))
(define non-pointer-typedef-names
;; Under Windows, things like HANDLE and HWND, are not
;; malloced and could overlap with GCed areas.
;; Mac OS X has similar things.
#cs
'(HANDLE
HWND HDC HMENU
HBITMAP HBRUSH HPEN HFONT HPALETTE HRGN
HICON HINSTANCE
GLOBALHANDLE LOCALHANDLE HGLOBAL HLOCAL
GrafPtr RgnHandle PixMapHandle Handle MenuHandle GDHandle
WindowPtr DialogPtr ControlRef EventRef EventHandlerCallRef
CGContextRef))
(define asm-commands
;; When outputting, add newline before these syms
;; (for __asm blocks in Windows)
'(mov shl shld shr shrd sar lock setc add))
(define (get-constructor v)
(cond
[(creation-parens? v) make-creation-parens]
[(parens? v) make-parens]
[(brackets? v) make-brackets]
[(braces? v) make-braces]))