File: compiler.jl

package info (click to toggle)
librep 0.9-2
  • links: PTS
  • area: main
  • in suites: potato
  • size: 2,576 kB
  • ctags: 1,928
  • sloc: ansic: 21,612; sh: 7,386; lisp: 5,331; makefile: 392; sed: 93
file content (1973 lines) | stat: -rw-r--r-- 65,816 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
;;;; compiler.jl -- Simple compiler for Lisp files/forms
;;;  Copyright (C) 1993, 1994 John Harper <john@dcs.warwick.ac.uk>
;;;  $Id: compiler.jl,v 1.58 1999/12/11 11:37:23 john Exp $

;;; This file is part of Jade.

;;; Jade 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 2, or (at your option)
;;; any later version.

;;; Jade 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 Jade; see the file COPYING.  If not, write to
;;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

(require 'bytecodes)
(provide 'compiler)


;;; Notes:
;;;
;;; Instruction Encoding
;;; ====================
;;; Instructions which get an argument (with opcodes of zero up to
;;; `op-last-with-args') encode the type of argument in the low 3 bits
;;; of their opcode (this is why these instructions take up 8 opcodes).
;;; A value of 0 to 5 (inclusive) is the literal argument, value of
;;; 6 means the next byte holds the argument, or a value of 7 says
;;; that the next two bytes are used to encode the argument (in big-
;;; endian form, i.e. first extra byte has the high 8 bits)
;;;
;;; All instructions greater than the `op-last-before-jmps' are branches,
;;; currently only absolute destinations are supported, all branch
;;; instructions encode their destination in the following two bytes (also
;;; in big-endian form).
;;;
;;; Any opcode between `op-last-with-args' and `op-last-before-jmps' is
;;; a straightforward single-byte instruction.
;;;
;;; The machine simulated by lispmach.c is a simple stack-machine, each
;;; call to the byte-code interpreter gets its own stack; the size of
;;; stack needed is calculated by the compiler.
;;;
;;; If you hadn't already noticed I based this on the Emacs version 18
;;; byte-compiler.
;;;
;;; Constants
;;; =========
;;; `defconst' forms have to be used with some care. The compiler assumes
;;; that the value of the constant is always the same, whenever it is
;;; evaluated. It may even be evaluated more than once.
;;;
;;; In general, any symbols declared as constants (by defconst) have their
;;; values set in stone. These values are hard-coded into the compiled
;;; byte-code.
;;;
;;; Also, the value of a constant-symbol is *not* likely to be eq to itself!
;;;
;;; Use constants as you would use macros in C, i.e. to define values which
;;; have to be the same throughout a module. For example, this compiler uses
;;; defconst forms to declare the instruction opcodes.
;;;
;;; If you have doubts about whether or not to use constants -- don't; it may
;;; lead to subtle bugs.
;;;
;;; Inline Functions
;;; ================
;;; The defsubst macro allows functions to be defined which will be open-
;;; coded into any callers at compile-time. Of course, this can have a
;;; similar effect to using a macro, with some differences:
;;;
;;;	* Macros can be more efficient, since the formal parameters
;;;	  are only bound at compile time. But, this means that the
;;;	  arguments may be evaluated more than once, unlike a defsubst
;;;	  where applied forms will only ever be evaluated once, when
;;;	  they are bound to a formal parameter
;;;
;;;	* Macros are more complex to write; though the backquote mechanism
;;;	  can help a lot with this
;;;
;;;	* defsubst's are more efficient in uncompiled code, but this
;;;	  shouldn't really be a consideration, unless code is being
;;;	  generated on the fly
;;;
;;; Warnings
;;; ========
;;; Currently warnings are generated for the following situations:
;;;
;;;	* Functions or special variables are multiply defined
;;;	* Undefined variables are referenced or set ("undefined" means
;;;	  not defined by defvar, not currently (lexically) bound, and
;;;	  not boundp at compile-time)
;;;	* Undefined functions are referenced, that is, not defun'd and
;;;	  not fboundp at compile-time
;;;	* Functions are called with an incorrect number of arguments,
;;;	  either too few required parameters, or too many supplied
;;;	  to a function without a &rest keyword
;;;	* Unreachable code in conditional statements
;;;	* Possibly some other things...
;;;
;;; TODO
;;; ====

;;; Obviously, more optimisation of output code. This isdone in two
;;; stages, (1) source code transformations, (2) optimisation of
;;; intermediate form (basically bytecode, but as a list of operations
;;; and symbolic labels, i.e. the basic blocks)
;;;
;;; Both (1) and (2) are already being done, but there's probably
;;; scope for being more aggressive, especially at the source code
;;; (parse tree) level.
;;;
;;; Optimisation would be a lot more profitable if variables were
;;; lexically scoped, perhaps I should switch to lexical scoping. It
;;; shouldn't break anything much, since the compiler will give
;;; warnings if any funky dynamic-scope tricks are used without the
;;; symbols being defvar'd (and therefore declared special/dynamic)
;;;
;;; The constant folding code is a bit simplistic. For example the form
;;; (+ 1 2 3) would be folded to 6, but (+ 1 2 x) *isn't* folded to
;;; (+ 3 x) as we would like. This is due to the view of folded functions
;;; as ``side-effect-free constant black boxes''.

;; 8/11/99: lexical scoping has arrived.. and it works.. and the
;; performance hit is minimal :-)

;; so I need to do all those funky lexical scope optimisation now..


;; Options

(defvar comp-write-docs nil
  "When t all doc-strings are appended to the doc file and replaced with
their position in that file.")

(defvar comp-max-inline-depth 8
  "The maximum nesting of open-coded function applications.")

(defvar comp-no-low-level-optimisations nil)
(defvar comp-debug nil)

(defvar comp-constant-functions
  '(+ - * / % mod max min 1+ 1- car cdr assoc assq rassoc rassq nth nthcdr
    last member memq arrayp aref substring concat length elt lognot not
    logior logxor logand equal = /= > < >= <= lsh ash zerop null atom consp
    listp numberp integerp stringp vectorp bytecodep functionp macrop
    special-form-p subrp sequencep)
  "List of side-effect-free functions. They should always return the same
value when given the same inputs. Used when constant folding.")

(defvar comp-nth-insns (list (cons 0 op-car)
			     (cons 1 op-cadr)
			     (cons 2 op-caddr)
			     (cons 3 op-cadddr)
			     (cons 4 op-caddddr)
			     (cons 5 op-cadddddr)
			     (cons 6 op-caddddddr)
			     (cons 7 op-cadddddddr)))

(defvar comp-nthcdr-insns (list (cons 0 nil)
				(cons 1 op-cdr)
				(cons 2 op-cddr)))


;; Environment of this byte code sequence being compiled

;; Output state
(defvar comp-constant-alist '())	;list of (VALUE . INDEX)
(defvar comp-constant-index 0)		;next free constant index number
(defvar comp-current-stack 0)		;current stack requirement
(defvar comp-max-stack 0)		;highest possible stack
(defvar comp-output nil)		;list of (BYTE . INDEX)
(defvar comp-output-pc 0)		;INDEX of next byte
(defvar comp-intermediate-code nil)	;list of (INSN . [ARG]), (TAG . REFS)

;; Compilation "environment"
(defvar comp-macro-env '())		;alist of (NAME . MACRO-DEF)
(defvar comp-const-env '())		;alist of (NAME . CONST-DEF)
(defvar comp-inline-env '())		;alist of (NAME . FUNCTION-VALUE)
(defvar comp-defuns nil)		;alist of (NAME REQ OPT RESTP)
					; for all functions/macros in the file
(defvar comp-defvars nil)		;all variables declared at top-level
(defvar comp-bindings '())		;list of currently bound variables
(defvar comp-current-file nil)		;the file being compiled
(defvar comp-current-fun nil)		;the function being compiled
(defvar comp-inline-depth 0)		;depth of lambda-inlining

(defvar comp-output-stream nil)		;stream for compiler output


;; Message output

(defun comp-message (fmt &rest args)
  (when (null comp-output-stream)
    (if (or batch-mode (not (featurep 'jade)))
	(setq comp-output-stream (stdout-file))
      (setq comp-output-stream (open-buffer "*compilation-output*"))))
  (when (and (featurep 'jade)
	     (bufferp comp-output-stream)
	     (not (eq (current-buffer) comp-output-stream)))
    (goto-buffer comp-output-stream)
    (goto (end-of-buffer)))
; (when comp-current-file
;   (format comp-output-stream "%s:" comp-current-file))
  (when comp-current-fun
    (format comp-output-stream "%s:" comp-current-fun))
  (apply format comp-output-stream fmt args))

(put 'compile-error 'error-message "Compilation mishap")
(defun comp-error (&rest data)
  (signal 'compile-error data))

(defun comp-warning (fmt &rest args)
  (apply comp-message fmt args)
  (write comp-output-stream "\n"))


;; Code to handle warning tests

;; Note that there's a function or macro NAME with lambda-list ARGS
;; in the current file
(defun comp-remember-fun (name args)
  (if (assq name comp-defuns)
      (comp-warning "Multiply defined function or macro: %s" name)
    (let
	((required 0)
	 (optional nil)
	 (rest nil)
	 (state 'required))
      ;; Scan the lambda-list for the number of required and optional
      ;; arguments, and whether there's a &rest clause
      (while args
	(if (memq (car args) '(&optional &rest &aux))
	    (cond
	     ((eq (car args) '&optional)
	      (setq state 'optional
		    optional 0
		    args (cdr args)))
	     ((eq (car args) '&rest)
	      (setq args nil
		    rest t))
	     ((eq (car args) '&aux)
	      (setq args nil)))
	  (set state (1+ (symbol-value state)))
	  (setq args (cdr args))))
      (setq comp-defuns (cons (list name required optional rest)
			      comp-defuns)))))

;; Similar for variables
(defun comp-remember-var (name)
  (if (memq name comp-defvars)
      (comp-warning "Multiply defined variable: %s" name)
    (setq comp-defvars (cons name comp-defvars))))

;; Test that a reference to variable NAME appears valid
(defun comp-test-varref (name)
  (when (and (symbolp name)
	     (null (memq name comp-defvars))
	     (null (memq name comp-bindings))
	     (null (assq name comp-defuns))
	     (not (boundp name)))
    (comp-warning "Reference to undeclared free variable: %s" name)))

;; Test that binding to variable NAME appears valid
(defun comp-test-varbind (name)
  (cond ((assq name comp-defuns)
	 (comp-warning "Binding to %s shadows function" name))
	;((memq name comp-defvars)
	; (comp-warning "Binding to %s shadows special variable" name))
	((memq name comp-bindings)
	 (comp-warning "Binding to %s shadows earlier binding" name))
	((and (boundp name) (functionp (symbol-value name)))
	 (comp-warning "Binding to %s shadows pre-defined value" name))))

;; Test a call to NAME with NARGS arguments
;; XXX functions in comp-fun-bindings aren't type-checked
(defun comp-test-funcall (name nargs)
  (when (symbolp name)
    (catch 'return
      (let
	  ((decl (assq name comp-defuns)))
	(when (and (null decl) (boundp name))
	  (setq decl (symbol-value name))
	  (when (or (subrp decl)
		    (and (closurep decl)
			 (eq (car (closure-function decl)) 'autoload)))
	    (throw 'return))
	  (when (eq (car decl) 'macro)
	    (setq decl (cdr decl)))
	  (when (closurep decl)
	    (setq decl (closure-function decl)))
	  (if (bytecodep decl)
	      (comp-remember-fun name (aref decl 0))
	    (comp-remember-fun name (nth 1 decl)))
	  (setq decl (assq name comp-defuns)))
	(if (null decl)
	    (unless (or (memq name comp-bindings)
			(memq name comp-defvars))
	      (comp-warning "Call to undeclared function: %s" name))
	  (let
	      ((required (nth 1 decl))
	       (optional (nth 2 decl))
	       (rest (nth 3 decl)))
	    (if (< nargs required)
		(comp-warning "%d arguments required by %s; %d supplied"
			      required name nargs)
	      (when (and (null rest) (> nargs (+ required (or optional 0))))
		(comp-warning "Too many arguments to %s (%d given, %d used)"
			      name nargs (+ required (or optional 0)))))))))))


;; Top level entrypoints

(defvar comp-top-level-compiled
  '(if cond when unless let let* catch unwind-protect condition-case
    progn prog1 prog2 while and or)
  "List of symbols, when the name of the function called by a top-level form
is one of these that form is compiled.")

;;;###autoload
(defun compile-file (file-name)
  "Compiles the file of jade-lisp code FILE-NAME into a new file called
`(concat FILE-NAME ?c)' (ie, `foo.jl' => `foo.jlc')."
  (interactive "fLisp file to compile:")
  (let
      ((comp-current-file file-name)
       (comp-macro-env comp-macro-env)
       (comp-const-env '())
       (comp-inline-env '())
       (comp-defuns '())
       (comp-defvars '())
       (comp-bindings '())
       (comp-output-stream nil)
       (temp-file (make-temp-name))
       src-file dst-file form)
    (unwind-protect
	(progn
	  (message (concat "Compiling " file-name "...") t)
	  (when (setq src-file (open-file file-name 'read))
	    (unwind-protect
		;; Pass 1. Scan for top-level definitions in the file.
		(condition-case nil
		    (while t
		      (setq form (read src-file))
		      (cond
		       ((eq (car form) 'defun)
			(comp-remember-fun (nth 1 form) (nth 2 form)))
		       ((eq (car form) 'defmacro)
			(comp-remember-fun (nth 1 form) (nth 2 form))
			(setq comp-macro-env
			      (cons (cons (nth 1 form)
					  (make-closure
					   (cons 'lambda (nthcdr 2 form))))
				    comp-macro-env)))
		       ((eq (car form) 'defsubst)
			(comp-remember-fun (nth 1 form) (nth 2 form))
			(setq comp-inline-env
			      (cons (cons (nth 1 form)
					  (cons 'lambda (nthcdr 2 form)))
				    comp-inline-env)))
		       ((eq (car form) 'defvar)
			(comp-remember-var (nth 1 form)))
		       ((eq (car form) 'defconst)
			(comp-remember-var (nth 1 form))
			(setq comp-const-env (cons (cons (nth 1 form)
							 (nth 2 form))
						   comp-const-env)))))
		  (end-of-stream))
	      (close-file src-file))
	    (when (and (setq src-file (open-file file-name 'read))
		       (setq dst-file (open-file temp-file 'write)))
	      (condition-case error-info
		  (unwind-protect
		      (progn
			;; Pass 2. The actual compile
			;; First check for `#! .. !#' at start of file
			(if (and (= (read-char src-file) ?#)
				 (= (read-char src-file) ?!))
			    (let
				(tem)
			      (write dst-file "#!")
			      (catch 'done
				(while (setq tem (read-char src-file))
				  (write dst-file tem)
				  (when (and (= tem ?!)
					     (setq tem (read-char src-file)))
				    (write dst-file tem)
				    (when (= tem ?#)
				      (throw 'done t))))))
			  (seek-file src-file 0 'start))
			(format dst-file
				";; Source file: %s\n(validate-byte-code %d %d)\n"
				file-name bytecode-major bytecode-minor)
			(condition-case nil
			    (while t
			      (when (setq form (read src-file))
				(setq form (macroexpand form comp-macro-env))
				(cond
				 ((memq (car form)
					'(defun defmacro defvar
					  defconst defsubst require))
				  (setq form (comp-compile-top-form form)))
				 ((memq (car form) comp-top-level-compiled)
				  ;; Compile this form
				  (setq form (compile-form form))))
				(when form
				  (print form dst-file))))
			  (end-of-stream)))
		    (close-file dst-file)
		    (close-file src-file))
		(error
		 ;; Be sure to remove any partially written dst-file.
		 ;; Also, signal the error again so that the user sees it.
		 (delete-file temp-file)
		 ;; Hack to signal error without entering the debugger (again)
		 (throw 'error error-info)))
	      ;; Copy the file to its correct location
	      (copy-file temp-file (concat file-name (if (string-match
							  "\\.jl$" file-name)
							 ?c ".jlc")))
	      t)))
      (when (file-exists-p temp-file)
	(delete-file temp-file)))))

;;;###autoload
(defun compile-directory (dir-name &optional force-p exclude-list)
  "Compiles all jade-lisp files in the directory DIRECTORY-NAME whose object
files are either older than their source file or don't exist. If FORCE-P
is non-nil every lisp file is recompiled.
EXCLUDE-LIST is a list of files which shouldn't be compiled."
  (interactive "DDirectory of Lisp files to compile:\nP")
  (let
      ((dir (directory-files dir-name)))
    (while (consp dir)
      (when (and (string-match "\\.jl$" (car dir))
		 (null (member (car dir) exclude-list)))
	(let*
	    ((file (expand-file-name (car dir) dir-name))
	     (cfile (concat file ?c)))
	  (when (or (not (file-exists-p cfile))
		    (file-newer-than-file-p file cfile))
	    (compile-file file))))
      (setq dir (cdr dir)))
    t))

(defvar compile-lib-exclude-list
  '("autoload.jl"))

;;;###autoload
(defun compile-lisp-lib (&optional directory force-p)
  "Recompile all out of date files in the lisp library directory. If FORCE-P
is non-nil it's as though all files were out of date.
This makes sure that all doc strings are written to their special file and
that files which shouldn't be compiled aren't."
  (interactive "\nP")
  (let
      ((comp-write-docs t))
    (compile-directory (or directory lisp-lib-directory)
		       force-p compile-lib-exclude-list)))

;; Call like `rep --batch -l compiler -f compile-lib-batch [--force] DIR'
(defun compile-lib-batch ()
  (let
      ((force (when (equal (car command-line-args) "--force")
		(setq command-line-args (cdr command-line-args))
		t))
       (dir (car command-line-args)))
    (setq command-line-args (cdr command-line-args))
    (compile-lisp-lib dir force)))

;; Call like `rep --batch -l compiler -f compile-batch [--write-docs] FILES...'
(defun compile-batch ()
  (when (get-command-line-option "--write-docs")
    (setq comp-write-docs t))
  (while command-line-args
    (compile-file (car command-line-args))
    (setq command-line-args (cdr command-line-args))))

;; Used when bootstrapping from the Makefile, recompiles compiler.jl if
;; it's out of date
(defun compile-compiler ()
  (let
      ((comp-write-docs t))
    (mapc (lambda (file)
	    (setq file (expand-file-name file lisp-lib-directory))
	    (when (or (not (file-exists-p (concat file ?c)))
		      (file-newer-than-file-p file (concat file ?c)))
	      (compile-file file)))
	  '("compiler.jl" "compiler-opt.jl"))))

;;;###autoload
(defun compile-function (function)
  "Compiles the body of the function FUNCTION."
  (interactive "aFunction to compile:")
  (let*
      ((fbody (if (symbolp function)
		  (symbol-value function)
		function))
       (body (if (closurep fbody) (closure-function fbody) fbody))
       (comp-current-fun function)
       (comp-defuns nil)
       (comp-defvars nil)
       (comp-output-stream nil))
    (when (assq 'jade-byte-code body)
      (comp-error "Function already compiled" function))
    (setq body (comp-compile-lambda body function))
    (if (closurep fbody)
	(set-closure-function fbody body)
      (set function body))
    function))
    

;; Low level compilation

;; Compile a form which occurred at the `top-level' into a byte code form.
;; defuns, defmacros, defvars, etc... are treated specially.
;; require forms are evaluated before being output uncompiled; this is so
;; any macros are brought in before they're used.
(defun comp-compile-top-form (form)
  (let
      ((fun (car form)))
    (cond
     ((eq fun 'defun)
      (let
	  ((tmp (assq (nth 1 form) comp-macro-env))
	   (comp-current-fun (nth 1 form)))
	(when tmp
	  (rplaca tmp nil)
	  (rplacd tmp nil))
	(list 'defun (nth 1 form)
	      (comp-compile-lambda (cons 'lambda (nthcdr 2 form))
				   (nth 1 form)))))
     ((eq fun 'defmacro)
      (let
	  ((code (comp-compile-lambda (cons 'lambda (nthcdr 2 form))
				      (nth 1 form)))
	   (tmp (assq (nth 1 form) comp-macro-env))
	   (comp-current-fun (nth 1 form)))
	(if tmp
	    (rplacd tmp (make-closure code))
	  (comp-error "Compiled macro wasn't in environment" (nth 1 form)))
	(list 'defmacro (nth 1 form) code)))
     ((eq fun 'defsubst)
      (when comp-write-docs
	(cond
	 ((stringp (nth 3 form))
	  (add-documentation (nth 1 form) (nth 3 form))
	  (setq form (delq (nth 3 form) form)))
	 ((stringp (nth 4 form))
	  (add-documentation (nth 1 form) (nth 4 form))
	  (setq form (delq (nth 4 form) form)))))
      (unless (assq (nth 1 form) comp-inline-env)
	(comp-error "Inline function wasn't in environment" (nth 1 form)))
      form)
     ((eq fun 'defconst)
      (let
	  ((value (eval (nth 2 form)))
	   (doc (nth 3 form)))
	(when (and comp-write-docs (stringp doc))
	  (add-documentation (nth 1 form) doc)
	  (setq form (delq (nth 3 form) form)))
	(unless (memq (nth 1 form) comp-defvars)
	  (comp-remember-var (nth 1 form)))
	(unless (assq (nth 1 form) comp-const-env)
	  (comp-warning "Constant wasn't in environment" (nth 1 form))))
      form)
     ((eq fun 'defvar)
      (let
	  ((value (nth 2 form))
	   (doc (nth 3 form)))
	(when (and (listp value)
		   (not (comp-constant-p value)))
	  ;; Compile the definition. A good idea?
	  (rplaca (nthcdr 2 form) (compile-form (nth 2 form))))
	(when (and comp-write-docs (stringp doc))
	  (add-documentation (nth 1 form) doc)
	  (setq form (delq (nth 3 form) form)))
	(unless (memq (nth 1 form) comp-defvars)
	  (comp-remember-var (nth 1 form))))
      form)
     ((eq fun 'require)
      (eval form)
      form)
     (t
      (comp-error "Shouldn't have got here!")))))

;;;###autoload
(defun compile-form (form)
  "Compile the Lisp form FORM into a byte code form."
  (let
      (comp-constant-alist
       (comp-constant-index 0)
       (comp-current-stack 0)
       (comp-max-stack 0)
       comp-output
       (comp-output-pc 0)
       (comp-intermediate-code nil))

    ;; Do the high-level compilation
    (if comp-current-file
	(comp-compile-form form)
      ;; Setup comp-defuns and comp-defvars if compile-file hasn't already
      (let
	  ((comp-defuns '())
	   (comp-defvars '())
	   (comp-output-stream nil))
	(comp-compile-form form)))

    ;; Now we have a [reversed] list of intermediate code
    (setq comp-intermediate-code (nreverse comp-intermediate-code))

    ;; Unless disabled, run the peephole optimiser
    (unless comp-no-low-level-optimisations
      (require 'compiler-opt)
      (when comp-debug
	(format standard-error "lap-0 code: %S\n\n" comp-intermediate-code))
      (setq comp-intermediate-code (comp-peephole-opt comp-intermediate-code)))
    (when comp-debug
      (format standard-error "lap-1 code: %S\n\n" comp-intermediate-code))

    ;; Then optimise the constant layout
    (unless comp-no-low-level-optimisations
      (require 'compiler-opt)
      (when comp-debug
	(format standard-error
		"original-constants: %S\n\n" comp-constant-alist))
      (setq comp-intermediate-code
	    (comp-optimise-constants comp-intermediate-code))
      (when comp-debug
	(format standard-error
		"final-constants: %S\n\n" comp-constant-alist)))

    ;; Now transform the intermediate code to byte codes
    (comp-assemble-bytecodes)
    (when comp-debug
      (format standard-error "lap-2 code: %S\n\n" comp-intermediate-code))
    (when comp-output
      (list 'jade-byte-code (comp-make-code-string) (comp-make-const-vec)
	    comp-max-stack))))

;; Turn the alist of byte codes into a string
(defun comp-make-code-string ()
  (let
      ((code-string (make-string comp-output-pc ?*))
       (data comp-output))
    (while (consp data)
      (aset code-string (cdr (car data)) (car (car data)))
      (setq data (cdr data)))
    code-string))

;; Turn the alist of constants into a vector
(defun comp-make-const-vec ()
  (let
      ((vec (make-vector comp-constant-index))
       (consts comp-constant-alist))
    (while (consp consts)
      (aset vec (cdr (car consts)) (car (car consts)))
      (setq consts (cdr consts)))
    vec))

;; Increment the current stack size, setting the maximum stack size if
;; necessary
(defmacro comp-inc-stack (&optional n)
  (list 'when (list '> (list 'setq 'comp-current-stack
			     (if n
				 (list '+ 'comp-current-stack n)
			       (list '1+ 'comp-current-stack)))
		       'comp-max-stack)
	'(setq comp-max-stack comp-current-stack)))

;; Decrement the current stack usage
(defmacro comp-dec-stack (&optional n)
  (list 'setq 'comp-current-stack 
	(if n
	    (list '- 'comp-current-stack n)
	  (list '1- 'comp-current-stack))))

;; Compile one form so that its value ends up on the stack when interpreted
(defun comp-compile-form (form)
  (cond
    ((eq form nil)
      (comp-write-op op-nil)
      (comp-inc-stack))
    ((eq form t)
      (comp-write-op op-t)
      (comp-inc-stack))
    ((symbolp form)
     ;; A variable reference
     (let
	 (val)
       (comp-test-varref form)
       (cond
	((const-variable-p form)
	 ;; A constant already interned
	 (comp-compile-constant (symbol-value form)))
	((setq val (assq form comp-const-env))
	 ;; A constant from this file
	 (comp-compile-constant (cdr val)))
	(t
	 ;; Not a constant
	 (comp-write-op op-refq (comp-add-constant form))
	 (comp-inc-stack)))))
    ((consp form)
     (when (and (memq (car form) comp-constant-functions)
		(not (memq (car form) comp-bindings)))
       ;; See if this form can be folded
       (setq form (comp-fold-constants form))
       ;; If the form is still a function application, avoid the
       ;; extra recursion
       (unless (consp form)
	 (comp-compile-form form)
	 (setq form nil)))
     (unless (null form)
       ;; A subroutine application of some sort
       (comp-test-funcall (car form) (length (cdr form)))
       (let
	   (fun)
	 (cond
	  ;; Check if there's a source code transformation
	  ((and (symbolp (car form))
		(setq fun (get (car form) 'compile-transform)))
	   ;; Yes, there is, so call it.
	   (comp-compile-form (funcall fun form)))

	  ;; Check if there's a special handler for this function
	  ((and (symbolp (car form))
		(setq fun (get (car form) 'compile-fun))
		(not (memq (car form) comp-bindings)))
	   (funcall fun form))

	  ;; Is it a function to be inlined?
	  ((and (symbolp (car form)) (get (car form) 'compile-inline))
	   (comp-compile-inline-function form))

	  (t
	   ;; Expand macros
	   (if (not (eq (setq fun (macroexpand form comp-macro-env)) form))
	       ;; The macro did something, so start again
	       (comp-compile-form fun)
	     ;; No special handler, so do it ourselves
	     (setq fun (car form))
	     (cond
	      ((and (consp fun) (eq (car fun) 'lambda))
	       ;; An inline lambda expression
	       (comp-compile-lambda-inline (car form) (cdr form)))
	      ((and (symbolp fun) (assq fun comp-inline-env))
	       ;; A call to a function that should be open-coded
	       (comp-compile-lambda-inline (cdr (assq fun comp-inline-env))
					   (cdr form)))
	      (t
	       ;; Assume a normal function call
	       (comp-compile-form fun)
	       (setq form (cdr form))
	       (let
		   ((i 0))
		 (while (consp form)
		   (comp-compile-form (car form))
		   (setq i (1+ i)
			 form (cdr form)))
		 (comp-write-op op-call i)
		 (comp-dec-stack i))))))))))
    (t
     ;; Not a variable reference or a function call; so what is it?
     (comp-compile-constant form))))

;; Push a constant onto the stack
(defun comp-compile-constant (form)
  (cond
   ((eq form nil)
    (comp-write-op op-nil))
   ((eq form t)
    (comp-write-op op-t))
   ((and (integerp form) (<= form 65535) (>= form -65535))
    ;; use one of the pushi instructions
    (cond ((zerop form)
	   (comp-write-op op-pushi-0))
	  ((= form 1)
	   (comp-write-op op-pushi-1))
	  ((= form 2)
	   (comp-write-op op-pushi-2))
	  ((= form -1)
	   (comp-write-op op-pushi-minus-1))
	  ((= form -2)
	   (comp-write-op op-pushi-minus-2))
	  ((and (<= form 127) (>= form -128))
	   (comp-write-op op-pushi (logand form 255)))
	  ((and (< form 0) (>= form -65535))
	   (comp-write-op op-pushi-pair-neg (- form)))
	  (t
	   (comp-write-op op-pushi-pair-pos form))))
   (t
    (comp-write-op op-push (comp-add-constant form))))
  (comp-inc-stack))

;; Put a constant into the alist of constants, returning its index number.
;; It won't be added twice if it's already there.
(defun comp-add-constant (const)
  (or (cdr (assoc const comp-constant-alist))
      (progn
	(setq comp-constant-alist (cons (cons const comp-constant-index)
					comp-constant-alist)
	      comp-constant-index (1+ comp-constant-index))
	(1- comp-constant-index))))

;; Compile a list of forms, the last form's evaluated value is left on
;; the stack. If the list is empty nil is pushed.
(defun comp-compile-body (body)
  (if (null body)
      (progn
	(comp-write-op op-nil)
	(comp-inc-stack))
    (while (consp body)
      (comp-compile-form (car body))
      (when (cdr body)
	(comp-write-op op-pop)
	(comp-dec-stack))
      (setq body (cdr body)))))

;; Remove all keywords from a lambda list ARGS, returning the list of
;; variables that would be bound
(defmacro comp-get-lambda-vars (args)
  (list 'filter '(lambda (x)
		   (not (memq x '(&optional &rest &aux))))
	args))

;; From LST, `(lambda (ARGS) [DOC-STRING] BODY ...)' returns a byte-code
;; vector
(defun comp-compile-lambda (lst &optional name)
  (let
      ((args (nth 1 lst))
       (body (nthcdr 2 lst))
       doc interactive form)
    (when (stringp (car body))
      (setq doc (car body))
      (setq body (cdr body)))
    (when (eq (car (car body)) 'interactive)
      ;; If we have (interactive), set the interactive spec to t
      ;; so that it's not ignored
      (setq interactive (or (car (cdr (car body))) t)
	    body (cdr body))
      ;; See if it might be a good idea to compile the interactive decl
      (when (and (consp interactive)
		 (memq (car interactive) comp-top-level-compiled))
	(setq interactive (compile-form interactive))))
    (when (and comp-write-docs doc name)
      (add-documentation name doc))
    (let
	((vars (comp-get-lambda-vars args)))
      (mapc comp-test-varbind vars)
      (when (setq form (let
			   ((comp-bindings
			     (nconc vars comp-bindings)))
			 (compile-form (cons 'progn body))))
	(make-byte-code-subr args (nth 1 form) (nth 2 form) (nth 3 form)
			     (and (not comp-write-docs) doc) interactive)))))

;; Return t if FORM is a constant
(defun comp-constant-p (form)
  (cond
   ((or (integerp form) (stringp form)
	(vectorp form) (bytecodep form)
	(eq form t) (eq form nil)))
   ((consp form)
    (eq (car form) 'quote))
   ((symbolp form)
    (or (const-variable-p form)
	(assq form comp-const-env)))
   ;; What other constant forms have I missed..?
   (t
    nil)))

;; If FORM is a constant, return its value
(defun comp-constant-value (form)
  (cond
   ((or (integerp form) (stringp form)
	(vectorp form) (bytecodep form)
	(eq form t) (eq form nil))
    ;; Self-evaluating types
    form)
   ((consp form)
    ;; only quote
    (nth 1 form))
   ((symbolp form)
    (if (const-variable-p form)
	(symbol-value form)
      (cdr (assq form comp-const-env))))))

(defun comp-constant-function-p (form)
  (or (memq (car form) '(lambda function))))

(defun comp-constant-function-value (form)
  (cond ((eq (car form) 'lambda)
	 form)
	((eq (car form) 'function)
	 (nth 1 form))))


;; Managing the output code

;; Output one byte
(defsubst comp-byte-out (byte)
  (setq comp-output (cons (cons byte comp-output-pc) comp-output))
  (setq comp-output-pc (1+ comp-output-pc)))

(defun comp-insn-out (insn)
  (let
      ((opcode (car insn))
       (arg (cdr insn)))
    (cond
     ((eq opcode 'label)
      ;; backpatch already output instructions referrring to this label
      (mapc (lambda (addr)
	      (setq comp-output (cons (cons (lsh comp-output-pc -8) addr)
				      comp-output))
	      (setq comp-output (cons (cons (logand comp-output-pc 255)
					    (1+ addr)) comp-output)))
	    arg)
      ;; set the address of the label
      (rplacd insn comp-output-pc))
     ((>= opcode op-last-with-args)
      ;; ``normal'' one-byte insn encoding
      (comp-byte-out opcode)
      (when arg
	(when (and (eq (car arg) 'label) (numberp (cdr arg)))
	  ;; label whose address is already known
	  (setq arg (cdr arg)))
	(cond ((eq (car arg) 'label)
	       ;; label whose address isn't yet known
	       ;; add the address for backpatching
	       (rplacd arg (cons comp-output-pc (cdr arg)))
	       ;; step over waiting slot
	       (setq comp-output-pc (+ comp-output-pc 2)))
	      ((memq opcode comp-two-byte-insns)
	       (if (< arg 256)
		   (comp-byte-out arg)
		 (error "Argument overflow in two-byte insn: %d" opcode)))
	      ((memq opcode comp-three-byte-insns)
	       (if (< arg 65536)
		   (progn
		     (comp-byte-out (lsh arg -8))
		     (comp-byte-out (logand arg 255)))
		 (error "Argument overflow in three-byte insn: %d" opcode)))
	      (t
	       (error "Spurious argument given to insn: %d" opcode)))))
     (t
      ;; insn with encoded argument
      (cond ((<= arg comp-max-1-byte-arg)
	     (comp-byte-out (+ opcode arg)))
	    ((<= arg comp-max-2-byte-arg)
	     (comp-byte-out (+ opcode 6))
	     (comp-byte-out arg))
	    ((<= arg comp-max-3-byte-arg)
	     (comp-byte-out (+ opcode 7))
	     (comp-byte-out (lsh arg -8))
	     (comp-byte-out (logand arg 255)))
	    (t
	     (error "Argument overflow in insn: %d" opcode)))))))

(defun comp-assemble-bytecodes ()
  (mapc comp-insn-out comp-intermediate-code))
    

;; Managing the intermediate codes
  
;; Output one opcode and its optional argument
(defmacro comp-write-op (opcode &optional arg)
  `(setq comp-intermediate-code (cons (cons ,opcode ,arg)
				      comp-intermediate-code)))

;; Create a new label
(defmacro comp-make-label ()
  ;; a label is either (label . nil) or (label . (CODE-REFS...))
  ;; or (label BYTE-ADDRESS)
  `(cons 'label nil))

;; Arrange for the address of LABEL to be pushed onto the stack
(defmacro comp-push-label-addr (label)
  `(progn
     (comp-write-op op-pushi-pair-pos ,label)
     (comp-inc-stack)))

(defun comp-compile-jmp (opcode label)
  (comp-write-op opcode label))

;; Set the address of the label LABEL to the current pc
(defmacro comp-set-label (label)
  `(setq comp-intermediate-code (cons ,label comp-intermediate-code)))


;; Constant folding

;; This assumes that FORM is a list, and its car is one of the functions
;; in the comp-constant-functions list
(defun comp-fold-constants (form)
  (catch 'exit
    (let
	((args (mapcar (lambda (arg)
			 (when (consp arg)
			   (setq arg (macroexpand arg comp-macro-env)))
			 (when (and (consp arg)
				    (memq (car arg) comp-constant-functions)
				    (not (memq (car arg) comp-bindings)))
			   (setq arg (comp-fold-constants arg)))
			 (if (comp-constant-p arg)
			     (comp-constant-value arg)
			   ;; Not a constant, abort, abort
			   (throw 'exit form)))
		       (cdr form))))
      ;; Now we have ARGS, the constant [folded] arguments from FORM
      (setq form (apply (eval (car form)) args))
      ;; If the folded version is a symbol or a list, quote it to preserve
      ;; its constant-ness
      (if (or (symbolp form) (consp form))
	  (setq form (list 'quote form))
	form))))

;; Source code transformations. These are basically macros that are only
;; used at compile-time.

(defun comp-trans-eval-when-compile (form)
  `(quote ,(eval (nth 1 form))))
(put 'eval-when-compile 'compile-transform comp-trans-eval-when-compile)

(defun comp-trans-if (form)
  (let
      ((condition (nth 1 form))
       (then-form (nth 2 form))
       (else-forms (nthcdr 3 form)))
    (if (null else-forms)
	(list 'cond (list condition then-form))
      (list 'cond (list condition then-form) (cons 't else-forms)))))
(put 'if 'compile-transform comp-trans-if)

(defun comp-trans-and (form)
  (setq form (cdr form))
  (let
      (lst slot)
    (while form
      (if slot
	  (progn
	    (setcdr slot (cons (list 'cond (list (car form))) nil))
	    (setq slot (car (cdr (car (cdr slot))))))
	(setq lst (list 'cond (list (car form))))
	(setq slot (car (cdr lst))))
      (setq form (cdr form)))
    lst))
(put 'and 'compile-transform comp-trans-and)

(defun comp-trans-or (form)
  (cons 'cond (mapcar list (cdr form))))
(put 'or 'compile-transform comp-trans-or)

(defun comp-trans-setq-default (form)
  (let
      (lst)
    (setq form (cdr form))
    (while form
      (setq lst (cons `(set-default ',(car form) ,(nth 1 form)) lst))
      (setq form (nthcdr 2 form)))
    (cons 'progn (nreverse lst))))
(put 'setq-default 'compile-transform comp-trans-setq-default)

(defun comp-trans-setq (form)
  (let
      (lst)
    (setq form (cdr form))
    (while form
      (setq lst (cons `(set ',(car form) ,(nth 1 form)) lst))
      (setq form (nthcdr 2 form)))
    (cons 'progn (nreverse lst))))
(put 'setq 'compile-transform comp-trans-setq)

(defun comp-trans-defvar (form)
  (let
      ((name (nth 1 form))
       (value (nth 2 form))
       (doc (nth 3 form)))
    (comp-remember-var name)
    `(progn
       (when ,doc
	 (put ',name 'variable-documentation ,doc))
       (unless (boundp ',name)
	 (setq ,name ,value)))))
(put 'defvar 'compile-transform comp-trans-defvar)

(defun comp-trans-require (form)
  (let
      ((feature (nth 1 form)))
    (when (comp-constant-p feature)
      (require (comp-constant-value feature)))
    ;; Must transform to something other than (require FEATURE) to
    ;; prevent infinite regress
    `(funcall require ,feature)))
(put 'require 'compile-transform comp-trans-require)


;; Functions which compile non-standard functions (ie special-forms)

(defun comp-compile-quote (form)
  (comp-compile-constant (car (cdr form))))
(put 'quote 'compile-fun comp-compile-quote)

(defun comp-compile-function (form)
  (setq form (car (cdr form)))
  (if (symbolp form)
      (comp-compile-constant form)
    (comp-compile-constant (comp-compile-lambda form)))
  (comp-write-op op-enclose))
(put 'function 'compile-fun comp-compile-function)

(defun comp-compile-lambda-form (form)
  (comp-compile-constant (comp-compile-lambda form))
  (comp-write-op op-enclose))
(put 'lambda 'compile-fun comp-compile-lambda-form)

(defun comp-compile-while (form)
  (let
      ((top-label (comp-make-label))
       (test-label (comp-make-label)))
    (comp-compile-jmp op-jmp test-label)
    (comp-set-label top-label)
    (comp-compile-body (nthcdr 2 form))
    (comp-write-op op-pop)
    (comp-dec-stack)
    (comp-set-label test-label)
    (comp-compile-form (nth 1 form))
    (comp-compile-jmp op-jpt top-label)))
(put 'while 'compile-fun comp-compile-while)

;; Compile mapc specially if we can open code the function call
(defun comp-compile-mapc (form)
  (let
      ((fun (nth 1 form))
       (lst (nth 2 form)))
    (if (comp-constant-function-p fun)
	;; We can open code the function
	(let
	    ((top-label (comp-make-label))
	     (test-label (comp-make-label)))
	  (setq fun (comp-constant-function-value fun))
	  (comp-compile-form lst)
	  (comp-compile-jmp op-jmp test-label)
	  (comp-set-label top-label)
	  (comp-write-op op-dup)
	  (comp-inc-stack)
	  (comp-write-op op-car)
	  (comp-compile-lambda-inline fun nil 1)
	  (comp-write-op op-pop)
	  (comp-dec-stack)
	  (comp-write-op op-cdr)
	  (comp-set-label test-label)
	  ;; I don't have a jump-if-t-but-never-pop instruction, so
	  ;; make one out of "jpt TOP; nil". If I ever get a peep hole
	  ;; optimiser working, the nil should be fodder for it..
	  (comp-compile-jmp op-jtp top-label)
	  (comp-write-op op-nil))
      ;; The function must be called, so just use the mapc opcode
      (comp-compile-form fun)
      (comp-compile-form lst)
      (comp-write-op op-mapc)
      (comp-dec-stack))))
(put 'mapc 'compile-fun comp-compile-mapc)
      
(defun comp-compile-progn (form)
  (comp-compile-body (cdr form)))
(put 'progn 'compile-fun comp-compile-progn)

(defun comp-compile-prog1 (form)
  (comp-compile-form (nth 1 form))
  (comp-compile-body (nthcdr 2 form))
  (comp-write-op op-pop)
  (comp-dec-stack))
(put 'prog1 'compile-fun comp-compile-prog1)

(defun comp-compile-prog2 (form)
  (comp-compile-form (nth 1 form))
  (comp-write-op op-pop)
  (comp-dec-stack)
  (comp-compile-form (nth 2 form))
  (comp-compile-body (nthcdr 3 form))
  (comp-write-op op-pop)
  (comp-dec-stack))
(put 'prog2 'compile-fun comp-compile-prog2)

(defun comp-compile-set (form)
  (let
      ((fun (car form))
       (sym (nth 1 form))
       (val (nth 2 form)))
    (if (comp-constant-p sym)
	;; use setq
	(progn
	  (setq sym (comp-constant-value sym))
	  (comp-test-varref sym)
	  (comp-compile-form val)
	  (comp-write-op op-dup)
	  (comp-inc-stack)
	  (comp-write-op op-setq (comp-add-constant sym))
	  (comp-dec-stack))
      (comp-compile-form sym)
      (comp-compile-form val)
      (comp-write-op op-set)
      (comp-dec-stack))))
(put 'set 'compile-fun comp-compile-set)

;; This compiles an inline lambda, i.e. FUN is something like
;; (lambda (LAMBDA-LIST...) BODY...)
;; If PUSHED-ARGS-ALREADY is non-nil it should be a count of the number
;; of arguments pushed onto the stack (in reverse order). In this case,
;; ARGS is ignored
(defun comp-compile-lambda-inline (fun args &optional pushed-args-already)
  (when (>= (setq comp-inline-depth (1+ comp-inline-depth))
	    comp-max-inline-depth)
    (setq comp-inline-depth 0)
    (comp-error "Won't inline more than %d nested functions"
		comp-max-inline-depth))
  (let*
      ((lambda-list (nth 1 fun))
       (body (nthcdr 2 fun))
       (arg-count 0))
    (if (not pushed-args-already)
	;; First of all, evaluate each argument onto the stack
	(while (consp args)
	  (comp-compile-form (car args))
	  (setq args (cdr args)
		arg-count (1+ arg-count)))
      ;; Args already on stack
      (setq args nil
	    arg-count pushed-args-already))
    ;; Now the interesting bit. The args are on the stack, in
    ;; reverse order. So now we have to scan the lambda-list to
    ;; see what they should be bound to.
    (let
	((state 'required)
	 (args-left arg-count)
	 (bind-stack '())
	 (vars (comp-get-lambda-vars lambda-list))
	 (comp-bindings comp-bindings))
      (mapc comp-test-varbind vars)
      (setq comp-bindings (nconc vars comp-bindings))
      (while (consp lambda-list)
	(if (memq (car lambda-list) '(&optional &rest &aux))
	    (setq state (car lambda-list))
	  (cond
	   ((eq state 'required)
	    (if (zerop args-left)
		(comp-error "Required arg missing" (car lambda-list))
	      (setq bind-stack (cons (car lambda-list) bind-stack)
		    args-left (1- args-left))))
	   ((eq state '&optional)
	    (if (zerop args-left)
		(progn
		  (comp-write-op op-nil)
		  (comp-inc-stack))
	      (setq args-left (1- args-left)))
	    (setq bind-stack (cons (car lambda-list) bind-stack)))
	   ((eq state '&rest)
	    (setq bind-stack (cons (cons (car lambda-list) args-left)
				   bind-stack)
		  args-left 0
		  state '&aux))
	   ((eq state '&aux)
	    (setq bind-stack (cons (cons (car lambda-list) nil)
				   bind-stack)))))
	(setq lambda-list (cdr lambda-list)))
      (when (> args-left 0)
	(comp-warning "%d unused parameters to inline lambda" args-left))
      ;; Set up the body for compiling, skip any interactive form or
      ;; doc string
      (while (and (consp body) (or (stringp (car body))
				   (and (consp (car body))
					(eq (car (car body)) 'interactive))))
	(setq body (cdr body)))
      ;; Now we have a list of things to bind to, in the same order
      ;; as the stack of evaluated arguments. The list has items
      ;; SYMBOL, (SYMBOL . ARGS-TO-BIND), or (SYMBOL . nil)
      (if bind-stack
	  (progn
	    (comp-write-op op-init-bind)
	    ;; Bind all variables
	    (while bind-stack
	      (if (consp (car bind-stack))
		  (progn
		    (if (null (cdr (car bind-stack)))
			(progn
			  (comp-write-op op-nil)
			  (comp-inc-stack))
		      (comp-write-op op-list (cdr (car bind-stack)))
		      (comp-inc-stack)		;in case of a zero-length list
		      (comp-dec-stack (cdr (car bind-stack))))
		    (comp-write-op op-bind (comp-add-constant
					    (car (car bind-stack)))))
		(comp-write-op op-bind (comp-add-constant (car bind-stack))))
	      (comp-dec-stack)
	      (setq bind-stack (cdr bind-stack)))
	    ;; Then pop any args that weren't used.
	    (while (> args-left 0)
	      (comp-write-op op-pop)
	      (comp-dec-stack)
	      (setq args-left (1- args-left)))
	    (comp-compile-body body)
	    (comp-write-op op-unbind))
	;; Nothing to bind to. Just pop the evaluated args and
	;; evaluate the body
	(while (> args-left 0)
	  (comp-write-op op-pop)
	  (comp-dec-stack)
	  (setq args-left (1- args-left)))
	(comp-compile-body body))))
  (setq comp-inline-depth (1- comp-inline-depth)))

;; The defsubst form stuffs this into the compile-fun property of
;; all defsubst declared functions
(defun comp-compile-inline-function (form)
  (comp-compile-lambda-inline
   (closure-function (symbol-value (car form))) (cdr form)))

(defun comp-compile-let* (form)
  (let
      ((lst (car (cdr form)))
       (comp-bindings comp-bindings))
    (comp-write-op op-init-bind)
    (while (consp lst)
      (cond
	((consp (car lst))
	  (let
	      ((tmp (car lst)))
	    (comp-compile-body (cdr tmp))
	    (comp-test-varbind (car tmp))
	    (setq comp-bindings (cons (car tmp) comp-bindings))
	    (comp-write-op op-bind (comp-add-constant (car tmp)))))
	(t
	  (comp-write-op op-nil)
	  (comp-inc-stack)
	  (comp-test-varbind (car lst))
	  (setq comp-bindings (cons (car lst) comp-bindings))
	  (comp-write-op op-bind (comp-add-constant (car lst)))))
      (comp-dec-stack)
      (setq lst (cdr lst)))
    (comp-compile-body (nthcdr 2 form))
    (comp-write-op op-unbind)))
(put 'let* 'compile-fun comp-compile-let*)

(defun comp-compile-let (form)
  (let
      ((lst (car (cdr form)))
       (sym-stk nil)
       bindings)
    (comp-write-op op-init-bind)
    (while (consp lst)
      (cond
	((consp (car lst))
	  (setq sym-stk (cons (car (car lst)) sym-stk))
	  (comp-compile-body (cdr (car lst))))
	(t
	  (setq sym-stk (cons (car lst) sym-stk))
	  (comp-write-op op-nil)
	  (comp-inc-stack)))
      (setq lst (cdr lst)))
    (mapc comp-test-varbind sym-stk)
    (let
	((comp-bindings (append sym-stk comp-bindings)))
      (while (consp sym-stk)
	(comp-write-op op-bind (comp-add-constant (car sym-stk)))
	(comp-dec-stack)
	(setq sym-stk (cdr sym-stk)))
      (comp-compile-body (nthcdr 2 form)))
    (comp-write-op op-unbind)))
(put 'let 'compile-fun comp-compile-let)

(defun comp-compile-save-environment (form)
  (comp-write-op op-bindenv)
  (comp-compile-body (cdr form))
  (comp-write-op op-unbind))
(put 'save-environment 'compile-fun comp-compile-save-environment)

(defun comp-compile-defun (form)
  (comp-compile-constant (nth 1 form))
  (comp-write-op op-dup)
  (comp-inc-stack)
  (comp-compile-constant (comp-compile-lambda (cons 'lambda (nthcdr 2 form))))
  (comp-write-op op-enclose)
  (comp-write-op op-dset)
  (comp-write-op op-pop)
  (comp-dec-stack 2))
(put 'defun 'compile-fun comp-compile-defun)

(defun comp-compile-defmacro (form)
  (comp-compile-constant (nth 1 form))
  (comp-write-op op-dup)
  (comp-inc-stack)
  (comp-compile-constant (cons 'macro (comp-compile-lambda
				       (cons 'lambda (nthcdr 2 form)))))
  (comp-write-op op-enclose)
  (comp-write-op op-dset)
  (comp-write-op op-pop)
  (comp-dec-stack 2))
(put 'defmacro 'compile-fun comp-compile-defmacro)

(defun comp-compile-cond (form)
  (let
      ((end-label (comp-make-label))
       (need-trailing-nil t))
    (setq form (cdr form))
    (while (consp form)
      (let*
	  ((subl (car form))
	   (condition (car subl))
	   (next-label (comp-make-label)))
	;; See if we can squash a constant condition to t or nil
	(when (comp-constant-p condition)
	  (setq condition (not (not (comp-constant-value condition)))))
	(cond
	 ((eq condition t)
	  ;; condition t -- always taken
	  (if (consp (cdr subl))
	      ;; There's something besides the condition
	      (progn
		(comp-compile-body (cdr subl))
		(comp-dec-stack))
	    (if (eq condition (car subl))
		(comp-write-op op-t)
	      (comp-compile-form (car subl))
	      (comp-dec-stack)))
	  (when (consp (cdr form))
	    (comp-warning "Unreachable conditions after t in cond statement")
	    ;; Ignore the rest of the statement
	    (setq form nil))
	  (setq need-trailing-nil nil))
	 ((eq condition nil)
	  ;; condition nil -- never taken
	  (when (cdr subl)
	    (comp-warning "Unreachable forms after nil in cond statement")))
	 (t
	  ;; non t-or-nil condition
	  (comp-compile-form (car subl))
	  (comp-dec-stack)
	  (if (consp (cdr subl))
	      ;; Something besides the condition
	      (if (cdr form)
		  ;; This isn't the last condition list
		  (progn
		    (comp-compile-jmp op-jn next-label)
		    (comp-compile-body (cdr subl))
		    (comp-dec-stack)
		    (comp-compile-jmp op-jmp end-label)
		    (comp-set-label next-label))
		;; It is the last condition list, use the result
		;; of this condition for the return value when it's
		;; nil
		(comp-compile-jmp op-jnp end-label)
		(comp-compile-body (cdr subl))
		(comp-dec-stack)
		(setq need-trailing-nil nil))
	    ;; No action to take
	    (if (cdr form)
		;; This isn't the last condition list
		(comp-compile-jmp op-jtp end-label)
	      ;; This is the last condition list, since there's no
	      ;; action to take, just fall out the bottom, with the
	      ;; condition as value.
	      (setq need-trailing-nil nil))))))
      (setq form (cdr form)))
    (when need-trailing-nil
      (comp-write-op op-nil))
    (comp-inc-stack)
    (comp-set-label end-label)))
(put 'cond 'compile-fun comp-compile-cond)

(defun comp-compile-catch (form)
  (let
      ((catch-label (comp-make-label))
       (start-label (comp-make-label))
       (end-label (comp-make-label)))
    ;;		jmp start
    (comp-compile-jmp op-jmp start-label)

    ;; catch:
    ;;		catch TAG
    ;;		ejmp end
    (comp-inc-stack)			;enter with one arg on stack
    (comp-set-label catch-label)
    (comp-compile-form (nth 1 form))
    (comp-write-op op-catch)
    (comp-dec-stack)
    (comp-compile-jmp op-ejmp end-label)
    (comp-dec-stack)

    ;; start:
    ;;		push #catch
    ;;		binderr
    ;;		FORMS...
    ;;		unbind
    ;; end:
    (comp-set-label start-label)
    (comp-push-label-addr catch-label)
    (comp-write-op op-binderr)
    (comp-dec-stack)
    (comp-compile-body (nthcdr 2 form))
    (comp-write-op op-unbind)
    (comp-set-label end-label)))
(put 'catch 'compile-fun comp-compile-catch)

(defun comp-compile-unwind-pro (form)
  (let
      ((cleanup-label (comp-make-label))
       (start-label (comp-make-label))
       (end-label (comp-make-label)))

    ;;		jmp start
    (comp-compile-jmp op-jmp start-label)

    ;; cleanup:
    ;;		CLEANUP-FORMS
    ;;		pop
    ;;		ejmp end
    ;; [overall, stack +1]
    (comp-inc-stack 2)
    (comp-set-label cleanup-label)
    (comp-compile-body (nthcdr 2 form))
    (comp-write-op op-pop)
    (comp-compile-jmp op-ejmp end-label)
    (comp-dec-stack 2)

    ;; start:
    ;;		push #cleanup
    ;;		binderr
    ;;		FORM
    ;;		unbind
    ;;		nil
    ;;		jmp cleanup
    ;; [overall, stack +2]
    (comp-set-label start-label)
    (comp-push-label-addr cleanup-label)
    (comp-write-op op-binderr)
    (comp-dec-stack)
    (comp-compile-form (nth 1 form))
    (comp-write-op op-unbind)
    (comp-write-op op-nil)
    (comp-dec-stack)
    (comp-compile-jmp op-jmp cleanup-label)

    ;; end:
    (comp-set-label end-label)))
(put 'unwind-protect 'compile-fun comp-compile-unwind-pro)

(defun comp-compile-condition-case (form)
  (let
      ((cleanup-label (comp-make-label))
       (start-label (comp-make-label))
       (end-label (comp-make-label))
       (handlers (nthcdr 3 form)))

    ;;		jmp start
    ;; cleanup:
    (comp-compile-jmp op-jmp start-label)
    (comp-set-label cleanup-label)

    (comp-inc-stack 2)			;reach here with two items on stack
    (if (consp handlers)
	(let
	    ((comp-bindings (if (nth 1 form)
				(progn
				  (comp-test-varbind (nth 1 form))
				  (nconc (list (nth 1 form)) comp-bindings))
			      comp-bindings)))
	  ;; Loop over all but the last handler
	  (while (consp (cdr handlers))
	    (if (consp (car handlers))
		(let
		    ((next-label (comp-make-label)))
		  ;;		push CONDITIONS
		  ;;		errorpro
		  ;;		jtp next
		  ;;		HANDLER
		  ;;		jmp end
		  ;; next:
		  (comp-compile-constant (car (car handlers)))
		  (comp-write-op op-errorpro)
		  (comp-dec-stack)
		  (comp-compile-jmp op-jtp next-label)
		  (comp-dec-stack)
		  (comp-compile-body (cdr (car handlers)))
		  (comp-compile-jmp op-jmp end-label)
		  (comp-set-label next-label))
	      (comp-error "Badly formed condition-case handler"))
	    (setq handlers (cdr handlers)))
	  ;; The last handler
	  (if (consp (car handlers))
	      (let
		  ((pc-label (comp-make-label)))
		;;		push CONDITIONS
		;;		errorpro
		;;		ejmp pc
		;; pc:		HANDLER
		;;		jmp end
		(comp-compile-constant (car (car handlers)))
		(comp-write-op op-errorpro)
		(comp-dec-stack)
		(comp-compile-jmp op-ejmp pc-label)
		(comp-set-label pc-label)
		(comp-dec-stack)
		(comp-compile-body (cdr (car handlers)))
		(comp-compile-jmp op-jmp end-label))
	    (comp-error "Badly formed condition-case handler")))
      (comp-error "No handlers in condition-case"))
    (comp-dec-stack)
    (comp-dec-stack)

    ;; start:
    ;;		push VAR
    ;;		push cleanup
    ;;		binderr
    ;;		FORM
    (comp-set-label start-label)
    (comp-compile-constant (nth 1 form))
    (comp-push-label-addr cleanup-label)
    (comp-write-op op-binderr)
    (comp-dec-stack)
    (comp-compile-form (nth 2 form))

    ;; end:
    ;;		unbind			;unbind error handler or VAR
    ;;		swap			;result<->VAR
    ;;		pop			;pop VAR
    (comp-set-label end-label)
    (comp-write-op op-unbind)
    (comp-write-op op-swap)
    (comp-write-op op-pop)
    (comp-dec-stack)))
(put 'condition-case 'compile-fun comp-compile-condition-case)

(defun comp-compile-with-object (form)
  (comp-compile-form (nth 1 form))
  (comp-write-op op-bindobj)
  (comp-dec-stack)
  (comp-compile-body (nthcdr 2 form))
  (comp-write-op op-unbind))
(put 'with-object 'compile-fun comp-compile-with-object)

(defun comp-compile-list (form)
  (let
      ((count 0))
    (setq form (cdr form))
    (while (consp form)
      (comp-compile-form (car form))
      (setq
       count (1+ count)
       form (cdr form)))
    (comp-write-op op-list count)
    (comp-dec-stack (1- count))))
(put 'list 'compile-fun comp-compile-list)

;; Funcall normally translates to a single call instruction. However,
;; if the function being called is a constant lambda expression, open
;; code it.
(defun comp-compile-funcall (form)
  (let*
      ((fun (nth 1 form))
       (args (nthcdr 2 form))
       (arg-count 0)
       (open-code (comp-constant-function-p fun)))
    (unless open-code
      (comp-compile-form fun))
    (while args
      (comp-compile-form (car args))
      (setq args (cdr args)
	    arg-count (1+ arg-count)))
    (if open-code
	(progn
	  (comp-compile-lambda-inline
	   (comp-constant-function-value fun) nil arg-count)
	  ;; We push one less value than when using op-call
	  (if (zerop arg-count)
	      (comp-inc-stack)
	    (comp-dec-stack (1- arg-count))))
      (comp-write-op op-call arg-count)
      (comp-dec-stack arg-count))))
(put 'funcall 'compile-fun comp-compile-funcall)

;; Handles (with-X X FORMS...)
(defun comp-compile-with-form (form)
  (let
      ((swap-opcode (get (car form) 'compile-opcode)))
    (comp-compile-form (nth 1 form))
    (comp-write-op swap-opcode)
    (comp-dec-stack)
    (comp-compile-body (nthcdr 2 form))
    (comp-write-op op-unbind)))

(defun comp-compile-nth (form)
  (let
      ((insn (cdr (assq (nth 1 form) comp-nth-insns))))
    (if insn
	(progn
	  (comp-compile-form (nth 2 form))
	  (comp-write-op insn))
      (comp-compile-2-args form))))
(put 'nth 'compile-fun comp-compile-nth)
(put 'nth 'compile-opcode op-nth)

(defun comp-compile-nthcdr (form)
  (let
      ((insn (assq (nth 1 form) comp-nthcdr-insns)))
    (if insn
	(progn
	  (comp-compile-form (nth 2 form))
	  (when (cdr insn)
	    (comp-write-op (cdr insn))))
      (comp-compile-2-args form))))
(put 'nthcdr 'compile-fun comp-compile-nthcdr)
(put 'nthcdr 'compile-opcode op-nthcdr)

(defun comp-compile-minus (form)
  (if (/= (length form) 2)
      (comp-compile-binary-op form)
    (comp-compile-form (car (cdr form)))
    (comp-write-op op-neg)))
(put '- 'compile-fun comp-compile-minus)
(put '- 'compile-opcode op-sub)

;; Instruction with no arguments
(defun comp-compile-0-args (form)
  (when (cdr form)
    (comp-warning "All parameters to %s ignored" (car form)))
  (comp-write-op (get (car form) 'compile-opcode))
  (comp-inc-stack))

;; Instruction taking 1 arg on the stack
(defun comp-compile-1-args (form)
  (when (nthcdr 2 form)
    (comp-warning "More than one parameter to %s; rest ignored" (car form)))
  (comp-compile-form (nth 1 form))
  (comp-write-op (get (car form) 'compile-opcode)))

;; Instruction taking 2 args on the stack
(defun comp-compile-2-args (form)
  (when (nthcdr 3 form)
    (comp-warning "More than two parameters to %s; rest ignored" (car form)))
  (comp-compile-form (nth 1 form))
  (comp-compile-form (nth 2 form))
  (comp-write-op (get (car form) 'compile-opcode))
  (comp-dec-stack))

;; Instruction taking 3 args on the stack
(defun comp-compile-3-args (form)
  (when (nthcdr 4 form)
    (comp-warning "More than three parameters to %s; rest ignored" (car form)))
  (comp-compile-form (nth 1 form))
  (comp-compile-form (nth 2 form))
  (comp-compile-form (nth 3 form))
  (comp-write-op (get (car form) 'compile-opcode))
  (comp-dec-stack 2))

;; Compile a form `(OP ARG1 ARG2 ARG3 ...)' into as many two argument
;; instructions as needed (PUSH ARG1; PUSH ARG2; OP; PUSH ARG3; OP; ...)
(defun comp-compile-binary-op (form)
  (let
      ((opcode (get (car form) 'compile-opcode)))
    (setq form (cdr form))
    (unless (>= (length form) 2)
      (comp-error "Too few args to binary operator" form))
    (comp-compile-form (car form))
    (setq form (cdr form))
    (while (consp form)
      (comp-compile-form (car form))
      (comp-write-op opcode)
      (comp-dec-stack)
      (setq form (cdr form)))))

;; Used for >, >=, < and <=
(defun comp-compile-transitive-relation (form)
  (let
      ((opcode (get (car form) 'compile-opcode)))
    (setq form (cdr form))
    (cond
     ((<= (length form) 1)
      (comp-error "Too few args to relation" form))
     ((= (length form) 2)
      ;; Simple case, only two arguments, i.e. `(OP ARG1 ARG2)' into:
      ;;  PUSH ARG1; PUSH ARG2; OP;
      (comp-compile-form (car form))
      (comp-compile-form (nth 1 form))
      (comp-write-op opcode)
      (comp-dec-stack))
     (t
      ;; Tricky case, >2 args,
      ;; Eg. `(OP ARG1 ARG2 ARG3... ARGN)' into something like,
      ;;  PUSH ARG1; PUSH ARG2; DUP; SWAP2; OP; JNP Fail;
      ;;  PUSH ARG3; DUP; SWAP2; OP; JNP Fail;
      ;;  ...
      ;;  PUSH ARGN; OP; JMP End;
      ;; Fail:
      ;;  SWAP; POP;
      ;; End:
      (let
	  ((fail-label (comp-make-label))
	   (end-label (comp-make-label)))
	(comp-compile-form (car form))
	(setq form (cdr form))
	(while (>= (length form) 2)
	  (comp-compile-form (car form))
	  (comp-write-op op-dup)
	  (comp-inc-stack)
	  (comp-write-op op-swap2)
	  (comp-write-op opcode)
	  (comp-dec-stack)
	  (comp-compile-jmp op-jnp fail-label)
	  (comp-dec-stack)
	  (setq form (cdr form)))
	;; Last arg coming up.
	(comp-compile-form (car form))
	(comp-write-op opcode)
	(comp-dec-stack)
	(comp-compile-jmp op-jmp end-label)
	(comp-set-label fail-label)
	(comp-write-op op-swap)
	(comp-write-op op-pop)
	(comp-dec-stack)
	(comp-set-label end-label))))))


;; Opcode properties for the generic instructions, in a progn for compiled
;; speed

(progn
  (put 'cons 'compile-fun comp-compile-2-args)
  (put 'cons 'compile-opcode op-cons)
  (put 'car 'compile-fun comp-compile-1-args)
  (put 'car 'compile-opcode op-car)
  (put 'cdr 'compile-fun comp-compile-1-args)
  (put 'cdr 'compile-opcode op-cdr)
  (put 'rplaca 'compile-fun comp-compile-2-args)
  (put 'rplaca 'compile-opcode op-rplaca)
  (put 'rplacd 'compile-fun comp-compile-2-args)
  (put 'rplacd 'compile-opcode op-rplacd)
  (put 'aset 'compile-fun comp-compile-3-args)
  (put 'aset 'compile-opcode op-aset)
  (put 'aref 'compile-fun comp-compile-2-args)
  (put 'aref 'compile-opcode op-aref)
  (put 'length 'compile-fun comp-compile-1-args)
  (put 'length 'compile-opcode op-length)
  (put 'eval 'compile-fun comp-compile-1-args)
  (put 'eval 'compile-opcode op-eval)
  (put '+ 'compile-fun comp-compile-binary-op)
  (put '+ 'compile-opcode op-add)
  (put '* 'compile-fun comp-compile-binary-op)
  (put '* 'compile-opcode op-mul)
  (put '/ 'compile-fun comp-compile-binary-op)
  (put '/ 'compile-opcode op-div)
  (put '% 'compile-fun comp-compile-2-args)
  (put '% 'compile-opcode op-rem)
  (put 'mod 'compile-fun comp-compile-2-args)
  (put 'mod 'compile-opcode op-mod)
  (put 'lognot 'compile-fun comp-compile-1-args)
  (put 'lognot 'compile-opcode op-lnot)
  (put 'not 'compile-fun comp-compile-1-args)
  (put 'not 'compile-opcode op-not)
  (put 'logior 'compile-fun comp-compile-binary-op)
  (put 'logior 'compile-opcode op-lor)
  (put 'logxor 'compile-fun comp-compile-binary-op)
  (put 'logxor 'compile-opcode op-lxor)
  (put 'logand 'compile-fun comp-compile-binary-op)
  (put 'logand 'compile-opcode op-land)
  (put 'equal 'compile-fun comp-compile-2-args)
  (put 'equal 'compile-opcode op-equal)
  (put 'eq 'compile-fun comp-compile-2-args)
  (put 'eq 'compile-opcode op-eq)
  (put '= 'compile-fun comp-compile-2-args)
  (put '= 'compile-opcode op-num-eq)
  (put '/= 'compile-fun comp-compile-2-args)
  (put '/= 'compile-opcode op-num-noteq)
  (put '> 'compile-fun comp-compile-transitive-relation)
  (put '> 'compile-opcode op-gt)
  (put '< 'compile-fun comp-compile-transitive-relation)
  (put '< 'compile-opcode op-lt)
  (put '>= 'compile-fun comp-compile-transitive-relation)
  (put '>= 'compile-opcode op-ge)
  (put '<= 'compile-fun comp-compile-transitive-relation)
  (put '<= 'compile-opcode op-le)
  (put '1+ 'compile-fun comp-compile-1-args)
  (put '1+ 'compile-opcode op-inc)
  (put '1- 'compile-fun comp-compile-1-args)
  (put '1- 'compile-opcode op-dec)
  (put 'lsh 'compile-fun comp-compile-2-args)
  (put 'lsh 'compile-opcode op-lsh)
  (put 'zerop 'compile-fun comp-compile-1-args)
  (put 'zerop 'compile-opcode op-zerop)
  (put 'null 'compile-fun comp-compile-1-args)
  (put 'null 'compile-opcode op-null)
  (put 'atom 'compile-fun comp-compile-1-args)
  (put 'atom 'compile-opcode op-atom)
  (put 'consp 'compile-fun comp-compile-1-args)
  (put 'consp 'compile-opcode op-consp)
  (put 'listp 'compile-fun comp-compile-1-args)
  (put 'listp 'compile-opcode op-listp)
  (put 'numberp 'compile-fun comp-compile-1-args)
  (put 'numberp 'compile-opcode op-numberp)
  (put 'stringp 'compile-fun comp-compile-1-args)
  (put 'stringp 'compile-opcode op-stringp)
  (put 'vectorp 'compile-fun comp-compile-1-args)
  (put 'vectorp 'compile-opcode op-vectorp)
  (put 'throw 'compile-fun comp-compile-2-args)
  (put 'throw 'compile-opcode op-throw)
  (put 'boundp 'compile-fun comp-compile-1-args)
  (put 'boundp 'compile-opcode op-boundp)
  (put 'symbolp 'compile-fun comp-compile-1-args)
  (put 'symbolp 'compile-opcode op-symbolp)
  (put 'get 'compile-fun comp-compile-2-args)
  (put 'get 'compile-opcode op-get)
  (put 'put 'compile-fun comp-compile-3-args)
  (put 'put 'compile-opcode op-put)
  (put 'signal 'compile-fun comp-compile-2-args)
  (put 'signal 'compile-opcode op-signal)
  (put 'reverse 'compile-fun comp-compile-1-args) ; new 12/7/94
  (put 'reverse 'compile-opcode op-reverse)
  (put 'nreverse 'compile-fun comp-compile-1-args)
  (put 'nreverse 'compile-opcode op-nreverse)
  (put 'assoc 'compile-fun comp-compile-2-args)
  (put 'assoc 'compile-opcode op-assoc)
  (put 'assq 'compile-fun comp-compile-2-args)
  (put 'assq 'compile-opcode op-assq)
  (put 'rassoc 'compile-fun comp-compile-2-args)
  (put 'rassoc 'compile-opcode op-rassoc)
  (put 'rassq 'compile-fun comp-compile-2-args)
  (put 'rassq 'compile-opcode op-rassq)
  (put 'last 'compile-fun comp-compile-1-args)
  (put 'last 'compile-opcode op-last)
  (put 'mapcar 'compile-fun comp-compile-2-args)
  (put 'mapcar 'compile-opcode op-mapcar)
  (put 'member 'compile-fun comp-compile-2-args)
  (put 'member 'compile-opcode op-member)
  (put 'memq 'compile-fun comp-compile-2-args)
  (put 'memq 'compile-opcode op-memq)
  (put 'delete 'compile-fun comp-compile-2-args)
  (put 'delete 'compile-opcode op-delete)
  (put 'delq 'compile-fun comp-compile-2-args)
  (put 'delq 'compile-opcode op-delq)
  (put 'delete-if 'compile-fun comp-compile-2-args)
  (put 'delete-if 'compile-opcode op-delete-if)
  (put 'delete-if-not 'compile-fun comp-compile-2-args)
  (put 'delete-if-not 'compile-opcode op-delete-if-not)
  (put 'copy-sequence 'compile-fun comp-compile-1-args)
  (put 'copy-sequence 'compile-opcode op-copy-sequence)
  (put 'sequencep 'compile-fun comp-compile-1-args)
  (put 'sequencep 'compile-opcode op-sequencep)
  (put 'functionp 'compile-fun comp-compile-1-args)
  (put 'functionp 'compile-opcode op-functionp)
  (put 'special-form-p 'compile-fun comp-compile-1-args)
  (put 'special-form-p 'compile-opcode op-special-form-p)
  (put 'subrp 'compile-fun comp-compile-1-args)
  (put 'subrp 'compile-opcode op-subrp)
  (put 'eql 'compile-fun comp-compile-2-args)
  (put 'eql 'compile-opcode op-eql)
  (put 'max 'compile-fun comp-compile-binary-op)
  (put 'max 'compile-opcode op-max)
  (put 'min 'compile-fun comp-compile-binary-op)
  (put 'min 'compile-opcode op-min)
  (put 'filter 'compile-fun comp-compile-2-args)
  (put 'filter 'compile-opcode op-filter)
  (put 'macrop 'compile-fun comp-compile-1-args)
  (put 'macrop 'compile-opcode op-macrop)
  (put 'bytecodep 'compile-fun comp-compile-1-args)
  (put 'bytecodep 'compile-opcode op-bytecodep)
  (put 'make-closure 'compile-fun comp-compile-2-args)
  (put 'make-closure 'compile-opcode op-make-closure)
  (put 'closurep 'compile-fun comp-compile-1-args)
  (put 'closurep 'compile-opcode op-closurep))