-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathcompiler.lisp
1731 lines (1460 loc) · 58.6 KB
/
compiler.lisp
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
;;; compiler.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
;;;; Compiler
(/debug "loading compiler.lisp!")
;;; Translate the Lisp code to Javascript. It will compile the special
;;; forms. Some primitive functions are compiled as special forms
;;; too. The respective real functions are defined in the target (see
;;; the beginning of this file) as well as some primitive functions.
(define-js-macro selfcall (&body body)
`(call (function () ,@body)))
(define-js-macro method-call (x method &rest args)
`(call (get ,x ,method) ,@args))
(define-js-macro nargs ()
`(- (get |arguments| |length|) 1))
(define-js-macro arg (n)
`(property |arguments| (+ ,n 1)))
;;; Runtime
(define-js-macro internal (x)
`(get |internals| ,x))
(define-js-macro call-internal (name &rest args)
`(method-call |internals| ,name ,@args))
(defun convert-to-bool (expr)
`(if ,expr ,(convert t) ,(convert nil)))
;;; A Form can return a multiple values object calling VALUES, like
;;; values(arg1, arg2, ...). It will work in any context, as well as
;;; returning an individual object. However, if the special variable
;;; `*multiple-value-p*' is NIL, is granted that only the primary
;;; value will be used, so we can optimize to avoid the VALUES
;;; function call.
(defvar *multiple-value-p* nil)
;;; It is bound dynamically to the number of nested calls to
;;; `convert'. Therefore, a form is being compiled as toplevel if it
;;; is zero.
(defvar *convert-level* -1)
;;; Environment
(def!struct binding
name
type
value
declarations)
(def!struct lexenv
variable
function
block
gotag)
(defun lookup-in-lexenv (name lexenv namespace)
(find name (ecase namespace
(variable (lexenv-variable lexenv))
(function (lexenv-function lexenv))
(block (lexenv-block lexenv))
(gotag (lexenv-gotag lexenv)))
:key #'binding-name))
(defun push-to-lexenv (binding lexenv namespace)
(ecase namespace
(variable (push binding (lexenv-variable lexenv)))
(function (push binding (lexenv-function lexenv)))
(block (push binding (lexenv-block lexenv)))
(gotag (push binding (lexenv-gotag lexenv)))))
(defun extend-lexenv (bindings lexenv namespace)
(let ((env (copy-lexenv lexenv)))
(dolist (binding (reverse bindings) env)
(push-to-lexenv binding env namespace))))
(defvar *environment*)
(defvar *variable-counter*)
(defun gvarname (symbol)
(declare (ignore symbol))
(incf *variable-counter*)
(make-symbol (concat "v" (integer-to-string *variable-counter*))))
(defun translate-variable (symbol)
(awhen (lookup-in-lexenv symbol *environment* 'variable)
(binding-value it)))
(defun extend-local-env (args)
(let ((new (copy-lexenv *environment*)))
(dolist (symbol args new)
(let ((b (make-binding :name symbol :type 'variable :value (gvarname symbol))))
(push-to-lexenv b new 'variable)))))
;;; Toplevel compilations
(defvar *toplevel-compilations*)
(defun toplevel-compilation (string)
(push string *toplevel-compilations*))
(defun get-toplevel-compilations ()
(reverse *toplevel-compilations*))
(defun %compile-defmacro (name lambda)
(let ((binding (make-binding :name name :type 'macro :value lambda)))
(push-to-lexenv binding *environment* 'function))
name)
(defun global-binding (name type namespace)
(or (lookup-in-lexenv name *environment* namespace)
(let ((b (make-binding :name name :type type :value nil)))
(push-to-lexenv b *environment* namespace)
b)))
(defun claimp (symbol namespace claim)
(let ((b (lookup-in-lexenv symbol *environment* namespace)))
(and b (member claim (binding-declarations b)))))
(defun !proclaim (decl)
(case (car decl)
(special
(dolist (name (cdr decl))
(let ((b (global-binding name 'variable 'variable)))
(push 'special (binding-declarations b)))))
(notinline
(dolist (name (cdr decl))
(let ((b (global-binding name 'function 'function)))
(push 'notinline (binding-declarations b)))))
(constant
(dolist (name (cdr decl))
(let ((b (global-binding name 'variable 'variable)))
(push 'constant (binding-declarations b)))))))
#+jscl
(fset 'proclaim #'!proclaim)
(defun %define-symbol-macro (name expansion)
(let ((b (make-binding :name name :type 'macro :value expansion)))
(push-to-lexenv b *environment* 'variable)
name))
#+jscl
(defmacro define-symbol-macro (name expansion)
`(%define-symbol-macro ',name ',expansion))
;;; Report functions which are called but not defined
(defvar *fn-info* '())
(def!struct fn-info
symbol
defined
called)
(defun find-fn-info (symbol)
(let ((entry (find symbol *fn-info* :key #'fn-info-symbol)))
(unless entry
(setq entry (make-fn-info :symbol symbol))
(push entry *fn-info*))
entry))
(defun fn-info (symbol &key defined called)
(let ((info (find-fn-info symbol)))
(when defined
(setf (fn-info-defined info) defined))
(when called
(setf (fn-info-called info) called))))
(defun report-undefined-functions ()
(dolist (info *fn-info*)
(let ((symbol (fn-info-symbol info)))
(when (and (fn-info-called info)
(not (fn-info-defined info)))
(warn "The function `~a' is undefined.~%" symbol))))
(setq *fn-info* nil))
;;; Special forms
(defvar *compilations*
(make-hash-table))
(defmacro define-compilation (name args &body body)
;; Creates a new primitive `name' with parameters args and
;; @body. The body can access to the local environment through the
;; variable *ENVIRONMENT*.
`(setf (gethash ',name *compilations*)
(lambda ,args (block ,name ,@body))))
(define-compilation if (condition true &optional false)
`(if (!== ,(convert condition) ,(convert nil))
,(convert true *multiple-value-p*)
,(convert false *multiple-value-p*)))
(defvar *ll-keywords* '(&optional &rest &key))
(defun list-until-keyword (list)
(if (or (null list) (member (car list) *ll-keywords*))
nil
(cons (car list) (list-until-keyword (cdr list)))))
(defun ll-section (keyword ll)
(list-until-keyword (cdr (member keyword ll))))
(defun ll-required-arguments (ll)
(list-until-keyword ll))
(defun ll-optional-arguments-canonical (ll)
(mapcar #'ensure-list (ll-section '&optional ll)))
(defun ll-optional-arguments (ll)
(mapcar #'car (ll-optional-arguments-canonical ll)))
(defun ll-rest-argument (ll)
(let ((rest (ll-section '&rest ll)))
(when (cdr rest)
(error "Bad lambda-list `~S'." ll))
(car rest)))
(defun ll-keyword-arguments-canonical (ll)
(flet ((canonicalize (keyarg)
;; Build a canonical keyword argument descriptor, filling
;; the optional fields. The result is a list of the form
;; ((keyword-name var) init-form svar).
(let ((arg (ensure-list keyarg)))
(cons (if (listp (car arg))
(car arg)
(list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
(cdr arg)))))
(mapcar #'canonicalize (ll-section '&key ll))))
(defun ll-keyword-arguments (ll)
(mapcar (lambda (keyarg) (second (first keyarg)))
(ll-keyword-arguments-canonical ll)))
(defun ll-svars (lambda-list)
(let ((args
(append
(ll-keyword-arguments-canonical lambda-list)
(ll-optional-arguments-canonical lambda-list))))
(remove nil (mapcar #'third args))))
(defun lambda-name/docstring-wrapper (name docstring code)
(if (or name docstring)
`(selfcall
(var (func ,code))
,(when name `(= (get func "fname") ,name))
,(when docstring `(= (get func "docstring") ,docstring))
(return func))
code))
(defun lambda-check-argument-count
(n-required-arguments n-optional-arguments rest-p)
;; Note: Remember that we assume that the number of arguments of a
;; call is at least 1 (the values argument).
(let ((min n-required-arguments)
(max (if rest-p 'n/a (+ n-required-arguments n-optional-arguments))))
(block nil
;; Special case: a positive exact number of arguments.
(when (and (< 0 min) (eql min max))
(return `(call-internal |checkArgs| (nargs) ,min)))
;; General case:
`(progn
,(when (< 0 min) `(call-internal |checkArgsAtLeast| (nargs) ,min))
,(when (numberp max) `(call-internal |checkArgsAtMost| (nargs) ,max))))))
(defun compile-lambda-optional (ll)
(let* ((optional-arguments (ll-optional-arguments-canonical ll))
(n-required-arguments (length (ll-required-arguments ll)))
(n-optional-arguments (length optional-arguments))
(svars (remove nil (mapcar #'third optional-arguments))))
(when optional-arguments
`(progn
,(when svars
`(var ,@(mapcar (lambda (svar)
(list (translate-variable svar)
(convert t)))
svars)))
(switch (nargs)
,@(with-collect
(dotimes (idx n-optional-arguments)
(let ((arg (nth idx optional-arguments)))
(collect `(case ,(+ idx n-required-arguments)))
(collect `(= ,(translate-variable (car arg))
,(convert (cadr arg))))
(collect (when (third arg)
`(= ,(translate-variable (third arg))
,(convert nil))))))
(collect 'default)
(collect '(break))))))))
(defun compile-lambda-rest (ll)
(let ((n-required-arguments (length (ll-required-arguments ll)))
(n-optional-arguments (length (ll-optional-arguments ll)))
(rest-argument (ll-rest-argument ll)))
(when rest-argument
(let ((js!rest (translate-variable rest-argument)))
`(progn
(var (,js!rest ,(convert nil)))
(var i)
(for ((= i (- (nargs) 1))
(>= i ,(+ n-required-arguments n-optional-arguments))
(post-- i))
(= ,js!rest (new (call-internal |Cons| (arg i) ,js!rest)))))))))
(defun compile-lambda-parse-keywords (ll)
(let ((n-required-arguments
(length (ll-required-arguments ll)))
(n-optional-arguments
(length (ll-optional-arguments ll)))
(keyword-arguments
(ll-keyword-arguments-canonical ll)))
`(progn
;; Declare variables
,@(with-collect
(dolist (keyword-argument keyword-arguments)
(destructuring-bind ((keyword-name var) &optional initform svar)
keyword-argument
(declare (ignore keyword-name initform))
(collect `(var ,(translate-variable var)))
(when svar
(collect
`(var (,(translate-variable svar)
,(convert nil))))))))
;; Parse keywords
,(flet ((parse-keyword (keyarg)
(destructuring-bind ((keyword-name var) &optional initform svar) keyarg
;; ((keyword-name var) init-form svar)
`(progn
(for ((= i ,(+ n-required-arguments n-optional-arguments))
(< i (nargs))
(+= i 2))
;; ....
(if (=== (arg i) ,(convert keyword-name))
(progn
(= ,(translate-variable var) (arg (+ i 1)))
,(when svar `(= ,(translate-variable svar)
,(convert t)))
(break))))
(if (== i (nargs))
(= ,(translate-variable var) ,(convert initform)))))))
(when keyword-arguments
`(progn
(var i)
,@(mapcar #'parse-keyword keyword-arguments))))
;; Check for unknown keywords
,(when keyword-arguments
`(progn
(var (start ,(+ n-required-arguments n-optional-arguments)))
(if (== (% (- (nargs) start) 2) 1)
(throw "Odd number of keyword arguments."))
(for ((= i start) (< i (nargs)) (+= i 2))
(if (and ,@(mapcar (lambda (keyword-argument)
(destructuring-bind ((keyword-name var) &optional initform svar)
keyword-argument
(declare (ignore var initform svar))
`(!== (arg i) ,(convert keyword-name))))
keyword-arguments))
(throw (+ "Unknown keyword argument " (property (arg i) "name"))))))))))
(defun parse-lambda-list (ll)
(values (ll-required-arguments ll)
(ll-optional-arguments ll)
(ll-keyword-arguments ll)
(ll-rest-argument ll)))
;;; Process BODY for declarations and/or docstrings. Return as
;;; multiple values the BODY without docstrings or declarations, the
;;; list of declaration forms and the docstring.
(defun parse-body (body &key declarations docstring)
(let ((value-declarations)
(value-docstring)
(end nil))
(while (not end)
(cond
;; Docstring
((and docstring
(stringp (car body))
(not (null (cdr body))))
(when value-docstring
(error "Duplicated docstring ~S" (car body)))
(setq value-docstring (car body))
(setq body (cdr body)))
;; Declaration
((and declarations
(consp (car body))
(eq (caar body) 'declare))
(push (car body) value-declarations)
(setq body (cdr body)))
(t
(setq end t))))
(values body value-declarations value-docstring)))
(defun bind-this ()
(let* ((gvar (gvarname 'this))
(binding (make-binding :name 'this :type 'variable :value gvar)))
(push-to-lexenv binding *environment* 'variable)
`(var (,gvar |this|))))
(defun jsize-symbol (symbol prefix)
(let ((str (string symbol)))
(intern
(with-output-to-string (out)
(format out "~a" (string prefix))
(dotimes (i (length str))
(let ((ch (char str i)))
(when (char<= #\a (char-downcase ch) #\z)
(write-char ch out))))))))
;;; Compile a lambda function with lambda list LL and body BODY. If
;;; NAME is given, it should be a constant string and it will become
;;; the name of the function. If BLOCK is non-NIL, a named block is
;;; created around the body. NOTE: No block (even anonymous) is
;;; created if BLOCK is NIL.
(defun compile-lambda (ll body &key name block)
(multiple-value-bind (required-arguments
optional-arguments
keyword-arguments
rest-argument)
(parse-lambda-list ll)
(multiple-value-bind (body decls documentation)
(parse-body body :declarations t :docstring t)
(declare (ignore decls))
(let ((n-required-arguments (length required-arguments))
(n-optional-arguments (length optional-arguments))
(*environment* (extend-local-env
(append (ensure-list rest-argument)
required-arguments
optional-arguments
keyword-arguments
(ll-svars ll)))))
(lambda-name/docstring-wrapper name documentation
`(named-function ,(jsize-symbol name 'jscl_user_)
(|values| ,@(mapcar (lambda (x)
(translate-variable x))
(append required-arguments optional-arguments)))
;; Check number of arguments
,(lambda-check-argument-count n-required-arguments
n-optional-arguments
(or rest-argument keyword-arguments))
,(compile-lambda-optional ll)
,(compile-lambda-rest ll)
,(compile-lambda-parse-keywords ll)
,(bind-this)
,(let ((*multiple-value-p* t))
(if block
(convert-block `((block ,block ,@body)) t)
(convert-block body t)))))))))
(defun setq-pair (var val)
(unless (symbolp var)
(error "~a is not a symbol" var))
(let ((b (lookup-in-lexenv var *environment* 'variable)))
(cond
((and b
(eq (binding-type b) 'variable)
(not (member 'special (binding-declarations b)))
(not (member 'constant (binding-declarations b))))
`(= ,(binding-value b) ,(convert val)))
((and b (eq (binding-type b) 'macro))
(convert `(setf ,var ,val)))
(t
(convert `(set ',var ,val))))))
(define-compilation setq (&rest pairs)
(when (null pairs)
(return-from setq (convert nil)))
(with-collector (result)
(while t
(cond
((null pairs)
(return))
((null (cdr pairs))
(error "Odd pairs in SETQ"))
(t
(collect-result (setq-pair (car pairs) (cadr pairs)))
(setq pairs (cddr pairs)))))
`(progn ,@result)))
;;; Compilation of literals an object dumping
;;; BOOTSTRAP MAGIC: We record the macro definitions as lists during
;;; the bootstrap. Once everything is compiled, we want to dump the
;;; whole global environment to the output file to reproduce it in the
;;; run-time. However, the environment must contain expander functions
;;; rather than lists. We do not know how to dump function objects
;;; itself, so we mark the list definitions with this object and the
;;; compiler will be called when this object has to be dumped.
;;; Backquote/unquote does a similar magic, but this use is exclusive.
;;;
;;; Indeed, perhaps to compile the object other macros need to be
;;; evaluated. For this reason we define a valid macro-function for
;;; this symbol.
(defvar *magic-unquote-marker* (gensym "MAGIC-UNQUOTE"))
#-jscl
(setf (macro-function *magic-unquote-marker*)
(lambda (form &optional environment)
(declare (ignore environment))
(second form)))
(defvar *literal-table*)
(defvar *literal-counter*)
(defun genlit ()
(incf *literal-counter*)
(make-symbol (concat "l" (integer-to-string *literal-counter*))))
(defun dump-symbol (symbol)
(let ((package (symbol-package symbol)))
(cond
;; Uninterned symbol
((null package)
`(new (call-internal |Symbol| ,(symbol-name symbol))))
;; Special case for bootstrap. For now, we just load all the
;; code with JSCL as the current package. We will compile the
;; JSCL package as CL in the target.
#-jscl
((eq package (find-package "JSCL"))
`(call-internal |intern| ,(symbol-name symbol)))
;; Interned symbol
(t
`(call-internal |intern| ,(symbol-name symbol) ,(package-name package))))))
(defun dump-cons (cons)
(let ((head (butlast cons))
(tail (last cons)))
`(call-internal |QIList|
,@(mapcar (lambda (x) (literal x t)) head)
,(literal (car tail) t)
,(literal (cdr tail) t))))
(defun dump-array (array)
(let ((elements (vector-to-list array)))
(list-to-vector (mapcar #'literal elements))))
(defun dump-string (string)
`(call-internal |make_lisp_string| ,string))
(defun literal (sexp &optional recursive)
(cond
((integerp sexp) sexp)
((floatp sexp) sexp)
((characterp sexp) (string sexp))
(t
(or (cdr (assoc sexp *literal-table* :test #'eql))
(let ((dumped (typecase sexp
(symbol (dump-symbol sexp))
(string (dump-string sexp))
(cons
;; BOOTSTRAP MAGIC: See the root file
;; jscl.lisp and the function
;; `dump-global-environment' for further
;; information.
(if (eq (car sexp) *magic-unquote-marker*)
(convert (second sexp))
(dump-cons sexp)))
(array (dump-array sexp)))))
(if (and recursive (not (symbolp sexp)))
dumped
(let ((jsvar (genlit)))
(push (cons sexp jsvar) *literal-table*)
(toplevel-compilation `(var (,jsvar ,dumped)))
(when (keywordp sexp)
(toplevel-compilation `(= (get ,jsvar "value") ,jsvar)))
jsvar)))))))
(define-compilation quote (sexp)
(literal sexp))
(define-compilation %while (pred &rest body)
`(selfcall
(while (!== ,(convert pred) ,(convert nil))
,(convert-block body))
(return ,(convert nil))))
(define-compilation function (x)
(cond
((and (listp x) (eq (car x) 'lambda))
(compile-lambda (cadr x) (cddr x)))
((and (listp x) (eq (car x) 'named-lambda))
(destructuring-bind (name ll &rest body) (cdr x)
(compile-lambda ll body
:name (symbol-name name)
:block name)))
((symbolp x)
(let ((b (lookup-in-lexenv x *environment* 'function)))
(if b
(binding-value b)
(convert `(symbol-function ',x)))))))
(defun make-function-binding (fname)
(make-binding :name fname :type 'function :value (gvarname fname)))
(defun compile-function-definition (list)
(compile-lambda (car list) (cdr list)))
(defun translate-function (name)
(let ((b (lookup-in-lexenv name *environment* 'function)))
(and b (binding-value b))))
(define-compilation flet (definitions &rest body)
(let* ((fnames (mapcar #'car definitions))
(cfuncs (mapcar (lambda (def)
(compile-lambda (cadr def)
`((block ,(car def)
,@(cddr def)))))
definitions))
(*environment*
(extend-lexenv (mapcar #'make-function-binding fnames)
*environment*
'function)))
`(call (function ,(mapcar #'translate-function fnames)
,(convert-block body t))
,@cfuncs)))
(define-compilation labels (definitions &rest body)
(let* ((fnames (mapcar #'car definitions))
(*environment*
(extend-lexenv (mapcar #'make-function-binding fnames)
*environment*
'function)))
`(selfcall
,@(mapcar (lambda (func)
`(var (,(translate-function (car func))
,(compile-lambda (cadr func)
`((block ,(car func) ,@(cddr func)))))))
definitions)
,(convert-block body t))))
;;; Was the compiler invoked from !compile-file?
(defvar *compiling-file* nil)
;;; NOTE: It is probably wrong in many cases but we will not use this
;;; heavily. Please, do not rely on wrong cases of this
;;; implementation.
(define-compilation eval-when (situations &rest body)
;; TODO: Error checking
(cond
;; Toplevel form compiled by !compile-file.
((and *compiling-file* (zerop *convert-level*))
;; If the situation `compile-toplevel' is given. The form is
;; evaluated at compilation-time.
(when (or (find :compile-toplevel situations)
(find 'compile situations))
(eval (cons 'progn body)))
;; `load-toplevel' is given, then just compile the subforms as usual.
(when (or (find :load-toplevel situations)
(find 'load situations))
(convert-toplevel `(progn ,@body) *multiple-value-p*)))
((or (find :execute situations)
(find 'eval situations))
(convert `(progn ,@body) *multiple-value-p*))
(t
(convert nil))))
(defmacro define-transformation (name args form)
`(define-compilation ,name ,args
(convert ,form)))
(define-compilation progn (&rest body)
`(progn
,@(append (mapcar #'convert (butlast body))
(list (convert (car (last body)) *multiple-value-p*)))))
(define-compilation macrolet (definitions &rest body)
(let ((*environment* (copy-lexenv *environment*)))
(dolist (def definitions)
(destructuring-bind (name lambda-list &body body) def
(let ((binding (make-binding :name name :type 'macro :value
(let ((g!form (gensym)))
`(lambda (,g!form)
(destructuring-bind ,lambda-list ,g!form
,@body))))))
(push-to-lexenv binding *environment* 'function))))
(convert `(progn ,@body) *multiple-value-p*)))
(defun special-variable-p (x)
(and (claimp x 'variable 'special) t))
(defun normalize-bindings (arg)
(destructuring-bind (name &optional value)
(ensure-list arg)
(list name value)))
;;; Given a let-like description of bindings, return:
;;;
;;; 1. A list of lexical
;;; 2. A list of values to bind to the lexical variables
;;; 3. A alist of (special-variable . lexical-variable) to bind.
;;;
(defun process-bindings (bindings)
(let ((bindings (mapcar #'normalize-bindings bindings))
(special-bindings nil))
(values
;; Lexical Variables
(mapcar (lambda (var)
(if (special-variable-p var)
(let ((lexvar (gensym)))
(push (cons var lexvar) special-bindings)
lexvar)
var))
(mapcar #'car bindings))
;; Values
(mapcar #'cadr bindings)
;; Binding special variables to lexical variables
special-bindings)))
;;; Wrap CODE to restore the symbol values of the dynamic
;;; bindings. BINDINGS is a list of pairs of the form
;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
;;; name to initialize the symbol value and where to stored
;;; the old value.
(defun let-bind-dynamic-vars (special-bindings body)
(if (null special-bindings)
(convert-block body t t)
(let ((special-variables (mapcar #'car special-bindings))
(lexical-variables (mapcar #'cdr special-bindings)))
`(return (call-internal
|bindSpecialBindings|
,(list-to-vector (mapcar #'literal special-variables))
,(list-to-vector (mapcar #'translate-variable lexical-variables))
(function () ,(convert-block body t t)))))))
(define-compilation let (bindings &rest body)
(multiple-value-bind (lexical-variables values special-bindings)
(process-bindings bindings)
(let ((compiled-values (mapcar #'convert values))
(*environment* (extend-local-env lexical-variables)))
`(call (function ,(mapcar #'translate-variable lexical-variables)
,(let-bind-dynamic-vars special-bindings body))
,@compiled-values))))
;; LET* compilation
;;
;; (let* ((*var1* value1))
;; (*var2* value2))
;; ...)
;;
;; var sbindings = [];
;;
;; try {
;; // compute value1
;; // bind to var1
;; // add var1 to sbindings
;;
;; // compute value2
;; // bind to var2
;; // add var2 to sbindings
;;
;; // ...
;;
;; } finally {
;; // ...
;; // restore bindings of sbindings
;; // ...
;; }
;;
(define-compilation let* (bindings &rest body)
(let ((bindings (mapcar #'ensure-list bindings))
(*environment* (copy-lexenv *environment*))
(sbindings (gvarname '|bindings|))
(prelude-target nil)
(postlude-target nil))
(dolist (binding bindings)
(destructuring-bind (variable &optional value) binding
(cond
((special-variable-p variable)
;; VALUE is evaluated before the variable is bound.
(let ((s (convert `',variable))
(v (convert value))
(out (gvarname 'value)))
(push `(progn
;; Store the compiled value into the temporary
;; JS variable OUT. Note that this code could
;; throw, so the following code could not run at
;; all.
(var (,out ,v))
;; Create a new binding by pushing the symbol
;; value to the stack, and scheduling the value
;; to be restored (in the postlude). Note that
;; this is done at runtime and not compile-time
;; because we could have 5 variables to bind,
;; but we could see an error for example in the
;; 3rd one only. So we do not always restore all
;; bindings necessarily.
(method-call (get ,s "stack") "push" (get ,s "value"))
(method-call ,sbindings "push" ,s)
;; Assign the value to the recently created
;; binding.
(= (get ,s "value") ,out))
prelude-target)))
(t
(let* ((jsvar (gvarname variable))
(binding (make-binding :name variable :type 'variable :value jsvar)))
(push `(var (,jsvar ,(convert value)))
prelude-target)
(push-to-lexenv binding *environment* 'variable))))))
;; The postlude will undo all the completed bindings from the
;; prelude.
(push `(method-call ,sbindings "forEach"
(function (s)
(= (get s "value")
(method-call (get s "stack") "pop"))))
postlude-target)
(let ((body
`(progn
,@(reverse prelude-target)
,(convert-block body t t))))
(if (find-if #'special-variable-p bindings :key #'first)
`(selfcall
(var (,sbindings #()))
(try ,body)
(finally ,@(reverse postlude-target)))
;; If there is no special variables, we don't need try/catch
`(selfcall ,body)))))
(define-compilation block (name &rest body)
;; We use Javascript exceptions to implement non local control
;; transfer. Exceptions has dynamic scoping, so we use a uniquely
;; generated object to identify the block. The instance of a empty
;; array is used to distinguish between nested dynamic Javascript
;; exceptions. See https://github.com/jscl-project/jscl/issues/64 for
;; further details.
(let* ((idvar (gvarname name))
(b (make-binding :name name :type 'block :value idvar)))
(when *multiple-value-p*
(push 'multiple-value (binding-declarations b)))
(let* ((*environment* (extend-lexenv (list b) *environment* 'block))
(cbody (convert-block body t)))
(if (member 'used (binding-declarations b))
`(selfcall
(try
(var (,idvar #()))
,cbody)
(catch (cf)
(if (and (instanceof cf (internal |BlockNLX|)) (== (get cf "id") ,idvar))
,(if *multiple-value-p*
`(return (method-call |values| "apply" this
(call-internal |forcemv| (get cf "values"))))
`(return (get cf "values")))
(throw cf))))
`(selfcall ,cbody)))))
(define-compilation return-from (name &optional value)
(let* ((b (lookup-in-lexenv name *environment* 'block))
(multiple-value-p (member 'multiple-value (binding-declarations b))))
(when (null b)
(error "Return from unknown block `~S'." (symbol-name name)))
(push 'used (binding-declarations b))
;; The binding value is the name of a variable, whose value is the
;; unique identifier of the block as exception. We can't use the
;; variable name itself, because it could not to be unique, so we
;; capture it in a closure.
`(selfcall
,(when multiple-value-p `(var (|values| (internal |mv|))))
(throw (new (call-internal |BlockNLX|
,(binding-value b)
,(convert value multiple-value-p)
,(symbol-name name)))))))
(define-compilation catch (id &rest body)
(let ((values (if *multiple-value-p* '|values| '(internal |pv|))))
`(selfcall
(var (id ,(convert id)))
(try
,(convert-block body t))
(catch (cf)
(if (and (instanceof cf (internal |CatchNLX|)) (== (get cf "id") id))
(return (method-call ,values "apply" this
(call-internal |forcemv| (get cf "values"))))
(throw cf))))))
(define-compilation throw (id value)
`(selfcall
(var (|values| (internal |mv|)))
(throw (new (call-internal |CatchNLX| ,(convert id) ,(convert value t))))))
(defun go-tag-p (x)
(or (integerp x) (symbolp x)))
(defun declare-tagbody-tags (tbidx body)
(let* ((go-tag-counter 0)
(bindings
(mapcar (lambda (label)
(let ((tagidx (incf go-tag-counter)))
(make-binding :name label :type 'gotag :value (list tbidx tagidx))))
(remove-if-not #'go-tag-p body))))
(extend-lexenv bindings *environment* 'gotag)))
(define-compilation tagbody (&rest body)
;; Ignore the tagbody if it does not contain any go-tag. We do this
;; because 1) it is easy and 2) many built-in forms expand to a
;; implicit tagbody, so we save some space.
(unless (some #'go-tag-p body)
(return-from tagbody (convert `(progn ,@body nil))))
;; The translation assumes the first form in BODY is a label
(unless (go-tag-p (car body))
(push (gensym "START") body))
;; Tagbody compilation
(let ((branch (gvarname 'branch))
(tbidx (gvarname 'tbidx)))
(let ((*environment* (declare-tagbody-tags tbidx body))
initag)
(let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
(setq initag (second (binding-value b))))
`(selfcall
;; TAGBODY branch to take
(var (,branch ,initag))
(var (,tbidx #()))
(label tbloop
(while true
(try
(switch ,branch
,@(with-collect
(collect `(case ,initag))
(dolist (form (cdr body))
(if (go-tag-p form)
(let ((b (lookup-in-lexenv form *environment* 'gotag)))
(collect `(case ,(second (binding-value b)))))
(collect (convert form)))))
default
(break tbloop)))
(catch (jump)
(if (and (instanceof jump (internal |TagNLX|)) (== (get jump "id") ,tbidx))
(= ,branch (get jump "label"))
(throw jump)))))
(return ,(convert nil))))))
(define-compilation go (label)
(let ((b (lookup-in-lexenv label *environment* 'gotag)))
(when (null b)
(error "Unknown tag `~S'" label))
`(selfcall
(throw (new (call-internal |TagNLX|
,(first (binding-value b))
,(second (binding-value b))))))))
(define-compilation unwind-protect (form &rest clean-up)
`(selfcall
(var (ret ,(convert nil)))
(try
(= ret ,(convert form)))
(finally
,(convert-block clean-up))
(return ret)))
(define-compilation multiple-value-call (func-form &rest forms)