compiler.stk 45.6 KB
Newer Older
1
					;bonus;;;
eg's avatar
eg committed
2 3
;;;; c o m p i l e r . s t k			-- STklos Compiler
;;;; 
Erick Gallesio's avatar
.  
Erick Gallesio committed
4
;;;; Copyright  2000-2007 Erick Gallesio - I3S-CNRS/ESSI <[email protected]>
eg's avatar
eg committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
;;;; 
;;;; 
;;;; This program 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 of the License, or
;;;; (at your option) any later version.
;;;; 
;;;; This program 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 this program; if not, write to the Free Software
;;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 
;;;; USA.
;;;; 
;;;;           Author: Erick Gallesio [[email protected]]
;;;;    Creation date: 26-Feb-2000 10:47 (eg)
Erick Gallesio's avatar
Erick Gallesio committed
24
;;;; Last file update: 19-Jan-2007 10:17 (eg)
eg's avatar
eg committed
25 26
;;;;

27 28 29 30
(define-module STKLOS-COMPILER
  (export eval
	  disassemble
	  compiler:time-display
31 32
	  compiler:gen-line-number
	  compiler:warn-use-undefined
33 34
	  compiler:warn-use-undefined-postpone
	  compiler:inline-common-functions))
35
  
36
(select-module STKLOS-COMPILER)
eg's avatar
eg committed
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
(define *compiler-port* #f)

(define *inline-table* `((+ 		 . ,+)
			 (- 		 . ,-)
			 (* 		 . ,*)
			 (/		 . ,/)
			 (=		 . ,=)
			 (<		 . ,<)
			 (<=		 . ,<=)
			 (>		 . ,>)
			 (>=		 . ,>=)
			 (cons	 	 . ,cons)
			 (car	 	 . ,car)
			 (cdr	 	 . ,cdr)
			 (null?	 	 . ,null?)
			 (list	 	 . ,list)
			 (not 	 	 . ,not)
			 (vector-ref	 . ,vector-ref)
			 (vector-set!	 . ,vector-set!)
			 (string-ref	 . ,string-ref)
			 (string-set! 	 . ,string-set!)
			 (eq?	 	 . ,eq?)
			 (eqv?	 	 . ,eqv?)
			 (equal?	 . ,equal?)
			 (void	 	 . ,void)))

(define *inline-symbols* (map car *inline-table*))

eg's avatar
eg committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
(define *always-inlined*   	'(%set-current-module %%set-current-module 
				  %%execute %%execute-handler))

(define *code-instr*		#f)
(define *code-constants*	'())
(define *code-labels*		0)

(include "peephole.stk")
(include "assembler.stk")
(include "computils.stk")


;; ----------------------------------------------------------------------
;; 	Compiler parameters ...
;; ----------------------------------------------------------------------
81 82 83 84
(define compiler:time-display			(make-parameter #t))
(define compiler:gen-line-number		(make-parameter #f))
(define compiler:warn-use-undefined  		(make-parameter #f))
(define compiler:warn-use-undefined-postpone	(make-parameter #f))
85 86 87 88 89 90
(define compiler:inline-common-functions
  (let ((inlined *inline-symbols*))
    (make-parameter #t
		    (lambda (v)
		      (set! *inline-symbols* (if v inlined '()))
		      (not (null? *inline-symbols*))))))
eg's avatar
eg committed
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

(define (new-label)
  (let ((lab *code-labels*))
    (set! *code-labels* (+ *code-labels* 1))
    lab))

(define (emit . args)
  (set! *code-instr* (cons args *code-instr*)))

(define (emit-label lab)
  (set! *code-instr* (cons lab *code-instr*)))


; ======================================================================
;
; 				CONSTANTS
;
; ======================================================================

(define (fetch-constant c)
  (let ((x (member c *code-constants*)))
    (unless x
      ;; This constant was not in the table; add it.
      (set! x (list c))
      (set! *code-constants* (append! *code-constants* x)))
    (- (length *code-constants*) (length x))))

Erick Gallesio's avatar
Erick Gallesio committed
118
(define small-integer-constant?
eg's avatar
eg committed
119 120
  (let ((min-int (- (expt 2 15)))
	(max-int (- (expt 2 15) 1)))
Erick Gallesio's avatar
Erick Gallesio committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    (lambda (v)
      (and (integer? v)
	   (exact? v)
	   (<= min-int v max-int)))))
      
(define (compile-constant v env tail?)
  (cond 
    ((eq? v #t)    		       (emit 'IM-TRUE))
    ((eq? v #f)    		       (emit 'IM-FALSE))
    ((eq? v '())   		       (emit 'IM-NIL))
    ((eq? v -1)    		       (emit 'IM-MINUS1))
    ((eq? v 0)     		       (emit 'IM-ZERO))
    ((eq? v 1)     		       (emit 'IM-ONE))
    ((eq? v (void))		       (emit 'IM-VOID))
    ((small-integer-constant? v)       (emit 'SMALL-INT v))
    (else 			       (emit 'CONSTANT (fetch-constant v)))))
eg's avatar
eg committed
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


#|
<doc syntax quote
 * (quote <datum>)
 * '<datum>
 *
 * The quoting mechanism is identical to R5RS, except that keywords 
 * constants  evaluate "to themselves" as numerical constants, string 
 * constants, character constants, and boolean constants
 * @lisp
 * '"abc"     =>  "abc"
 * "abc"      =>  "abc"
 * '145932    =>  145932
 * 145932     =>  145932
 * '#t        =>  #t
 * #t         =>  #t
 * :foo       =>  :foo
 * ':foo      =>  :foo
 * @end lisp
 * ,(bold "Note:") R5RS requires to quote constant lists and
 * constant vectors. This is not necessary with STklos.
doc>
|#
(define (compile-quote expr env tail?)
  (if (= (length expr) 2)
      (compile-constant (cadr expr) env tail?)
      (compiler-error 'quote expr "bad usage in ~S" expr)))

; ======================================================================
;
;				DEFINE
;
; ======================================================================

(define *known-globals* '())
(define *forward-globals* '())

(define (known-var? symbol)
  (or (symbol-bound? symbol) (memq symbol *known-globals*)))

(define (new-global symbol)
  (unless (memq symbol *known-globals*)
    (set! *known-globals* (cons symbol *known-globals*))))

(define (compiler-warn-undef symbol epair)
  (compiler-warning (void) epair "reference to undefined symbol ~S" symbol))

(define (verify-global symbol epair)
186 187 188 189 190 191 192 193
  (unless (known-var? symbol)
    (cond
      ((compiler:warn-use-undefined-postpone)
       (set! *forward-globals* (cons (cons symbol epair) *forward-globals*)))
      ((compiler:warn-use-undefined)
       (compiler-warn-undef symbol epair)
       (new-global symbol))))) 		; to avoid multiple warnings

eg's avatar
eg committed
194 195 196 197 198 199 200 201 202 203 204

(define (compiler-show-undefined-symbols)
  (for-each (lambda (x)
	      (let ((symbol (car x))
		    (where  (cdr x)))
		(unless (known-var? symbol)
		  (compiler-warn-undef symbol where)
		  (new-global symbol)))) ;; to avoid multiple warnings
	    *forward-globals*)
  (set! *forward-globals* '()))

Erick Gallesio's avatar
.  
Erick Gallesio committed
205 206 207
(define (compiler-known-globals)
  *known-globals*)

208 209


eg's avatar
eg committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
(define (define->lambda l)
  (if (> (length l) 2)
      (let ((bind (cadr l))
	    (body (cddr l)))
	(if (pair? bind)
	    `(define ,(car bind) (lambda ,(cdr bind) ,@body))
	    l))
      (begin
	(compiler-error 'define l "ill formed definition ~S" l)
	l)))

(define (compile-define args env tail?)
  (let* ((l   (define->lambda args))
	 (who (cadr l)))
    (if (not (= (length l) 3))
	(compiler-error 'define args "bad definition")
	(if (null? env)
	    (if (symbol? who)
		(begin
		  (new-global who)
		  (compile (caddr l) '() args #f)
		  (emit 'DEFINE-SYMBOL (fetch-constant who)))
		(compiler-error 'define args "bad variable name ~S" who))
233
	    (compiler-error 'define args "internal define forbidden here ~S" args)))))
eg's avatar
eg committed
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


;;;;
;;;; REFERENCES & ASSIGNMENT
;;;;
(define (symbol-in-env? symb env)
  (let Loop ((l env))
    (cond
      ((null? l) 		#f)
      ((memq symb (car l))	#t)
      (else			(Loop (cdr l))))))


(define (compile-access name env epair ref)

  (define (make-word v1 v2)		  ;; FIXME: Add control 
    (+ (* v1 256) v2))


  (define (em i1 i2 . args)
    (apply emit (if ref i1 i2) args))

  (let loop ((lev 0) (env env))
    (if (null? env) 
	;; name is a global variable
	(begin
	  (verify-global name epair)
	  (em 'GLOBAL-REF 'GLOBAL-SET (fetch-constant name)))
	;; name is a local variable 
	(let loop2 ((idx 0) (l (car env)))
	  (cond 
	    ((null? l) 	
	     (loop (+ lev 1) (cdr env)))
	    ((eq? (car l) name) 
	     (if (zero? lev)
		 ;; variable in  innermost block
		 (case idx
		   ((0)  (em 'LOCAL-REF0 'LOCAL-SET0))
		   ((1)  (em 'LOCAL-REF1 'LOCAL-SET1))
		   ((2)  (em 'LOCAL-REF2 'LOCAL-SET2))
		   ((3)  (em 'LOCAL-REF3 'LOCAL-SET3))
		   ((4)  (em 'LOCAL-REF4 'LOCAL-SET4))
		   (else (em 'LOCAL-REF  'LOCAL-SET  idx)))
		 ;; local variable in a "between" block
		 (em 'DEEP-LOCAL-REF  'DEEP-LOCAL-SET (make-word lev idx))))
	    (else   (loop2 (+ idx 1) (cdr l))))))))


(define (compile-reference name env epair tail?)
  (compile-access name env epair #t))

(define (compile-set! args env tail?)
  (let ((len (length (cdr args))))
    (if (= len 2)
	(let ((var (cadr args))
	      (val (caddr args)))
	  (if (list? var)
	      ;; This is a extended set! usage as in "(set! (f x y z) value)"
	      (compile `((setter ,(car var)) ,@(cdr var) ,val) env args tail?)
	      ;; R5RS usage
	      (if (symbol? var)
		  (begin 
		    (compile val env args #f)
		    (compile-access var env args #f))
		  (compiler-error 'set! args "~S is a bad symbol" var))))
	(compiler-error 'set! args "bad assignment syntax in ~S" args))))

;;;;
;;;; IF
;;;;
(define (compile-if args env tail?)
  (let ((len (length (cdr args)))
	(l1  (new-label))
	(l2  (new-label)))
    (if (<= 2 len 3)
	(begin
	  (compile (cadr args) env args #f)
	  (emit 'JUMP-FALSE l1)
	  (compile (caddr args) env args tail?)
	  (emit 'GOTO l2)
	  (emit-label l1)
	  (if (= len 3)
	      (compile (cadddr args) env args tail?)
	      (emit 'IM-VOID))
	  (emit-label l2))
	(compiler-error 'if args "bad syntax in ~S" args))))

;;
;; DEFINE-MACRO
;;
324 325 326 327 328 329 330 331 332 333 334 335 336
(define (compile-define-macro e env tail?)
  ;; Called for global macros. 
  (if (null? env)
      (let ((l (define->lambda e)))
	(when (= (length l) 3)
	  (let* ((l	       (extended-lambda->lambda l))
		 (name     (cadr l))
		 (proc     (caddr l))
		 (expander `(lambda (form e) (apply ,proc (cdr form)))))
	    ;; Compile code for installing expander
	    (compile expander '() e #f)
	    (emit 'MAKE-EXPANDER (fetch-constant name))
	    ;; Install expander for further compilation
337
	    (install-expander! name (eval expander)))))
338 339 340 341 342 343
      (compiler-error 'define-macro e "internal define-macro forbidden here ~S" e)))


(define (compile-internal-define-macro e env tail?)
  ;; This one is called when we find a define-macro while rewriting a body
  ;; (for internal defines -> letrec)
eg's avatar
eg committed
344 345 346 347 348 349 350
  (let ((l (define->lambda e)))
    (when (= (length l) 3)
      (let* ((l	       (extended-lambda->lambda l))
	     (name     (cadr l))
	     (proc     (caddr l))
	     (expander `(lambda (form e) (apply ,proc (cdr form)))))
	;; Install expander for further compilation
351
	(install-expander! name (eval expander))))))
eg's avatar
eg committed
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


;;;;
;;;; WHEN/UNLESS
;;;;
(define (compile-when args env tail?)
  (let ((len (length (cdr args))))
    (if (> len 1)
	(compile `(if ,(cadr args) (begin ,@(cddr args))) env args tail?)
	(compiler-error 'when args "bad syntax in ~S" args))))

(define (compile-unless args env tail?)
  (let ((len (length (cdr args))))
    (if (> len 1)
	(compile `(if (not ,(cadr args)) (begin ,@(cddr args))) env args tail?)
	(compiler-error 'unless args "bad syntax in ~S" args))))


#|

				A N D

<doc syntax and
 * (and <test1> ...)
 *
 * The |<test>| expressions are evaluated from left to right, and the
 * value of the first expression that evaluates to a false value is
 * returned.  Any remaining expressions are not evaluated.  If all the
 * expressions evaluate to true values, the value of the last expression
 * is returned.  If there are no expressions then |t| is returned.
 * 
 * @lisp
 *   (and (= 2 2) (> 2 1))           =>  #t
 *   (and (= 2 2) (< 2 1))           =>  #f
 *   (and 1 2 'c '(f g))             =>  (f g)
 *   (and)                           =>  #t
 * @end lisp
doc>
|#
(define (compile-and args env tail?)
  (if (null? (cdr args))
      ;; Case (and) ==> #t
      (emit 'IM-TRUE)
      ;; General case
      ;; code for (and x1 x2 .. xn) is
      ;;      x1; jump-false l1; x2; jump-false l1; ... goto l2; l1: im-false; L2:
      (let ((lab1 (new-label))
	    (lab2 (new-label)))	  
	(let Loop ((l (cdr args)))
	  (cond ((null? l) 	     #f)
		((null? (cdr l))     (compile (car l) env args tail?))
		(else  	     	     (compile (car l) env args #f)
				     (emit 'JUMP-FALSE lab1)
				     (Loop (cdr l)))))
	(emit 'GOTO lab2)
	(emit-label lab1)
	(emit 'IM-FALSE)
	(emit-label lab2))))

#|
 
				O R
 *
<doc syntax or
 * (or <test1> ...)
 *
 * The |<test>| expressions are evaluated from left to right, and the
 * value of the first expression that evaluates to a true value is
 * returned.  Any remaining expressions are not evaluated.  If all
 * expressions evaluate to false values, the value of the last expression
 * is returned.  If there are no expressions then |f| is returned.
 * 
 * @lisp
 *   (or (= 2 2) (> 2 1))            =>  #t
 *   (or (= 2 2) (< 2 1))            =>  #t
 *   (or #f #f #f)                   =>  #f
 *   (or (memq 'b '(a b c)) 
 *       (/ 3 0))                    =>  (b c)
 * @end lisp
doc>
|#
(define (compile-or args env tail?)
  ;; General case
  ;; code for (or x1 x2 .. xn) is
  ;;      x1; jump-true l1; x2; jump-true l1; ... ; im-false; L1:
  (let ((lab (new-label)))
    (let Loop ((l (cdr args)))
      (unless (null? l)
	(compile (car l) env args (and tail? (null? (cdr l))))
	(emit 'JUMP-TRUE lab)
	(Loop (cdr l))))
    (emit 'IM-FALSE)
    (emit-label lab)))
      

;;;;
;;;; BEGIN
;;;;
(define (compile-begin args env tail?)
  (let ((len (length (cdr args))))
    (case len
      ((0) ;; Body without form
           (emit 'IM-VOID))
      ((1) ;; A begin with only one sexpr in it
       	   (compile (cadr args) env args tail?))
      (else ;; General case
           (let Loop ((body (cdr args)))
	     (if (null? (cdr body))
		 ;; last expression of the begin
		 (compile (car body) env args tail?)
		 ;; expression in the middle
		 (begin
		   (compile (car body) env args #f)
		   (Loop (cdr body)))))))))

;;;;
;;;; LAMBDA
;;;;
(define (compute-arity l)
  (let loop ((l l) (n 0))
    (cond 
       ((null? l) n)
       ((pair? l) (loop (cdr l) (+ n 1)))
       (else      (- (- n) 1)))))

(define (extend-env env formals)
  (letrec ((aux (lambda (l res)
		  (cond
		     ((null? l) res)
		     ((pair? l) (aux (cdr l) (cons (car l) res)))
		     (else      (cons l res))))))
    (cons (aux formals '()) env)))


(define (extend-current-env env symbol)
  ;; Add just symbol to the current environment (used by let*)
  (cons (append (car env) (list symbol))
	(cdr env)))

;;  (define (valid-lambda? expr)
;;    (define (param-ok? l seen)
;;      (cond 
;;       ((null? l)   #t)
;;       ((symbol? l) (if (memq l seen)
;;  		      (compile-error "duplicate parameter ~S" l)
;;  		      #t))
;;       ((pair? l)   (and (symbol? (car l))
;;  		       (param-ok? (car l) seen)
;;  		       (param-ok? (cdr l) (cons (car l) seen))))
;;       (else	      (compile-error "bad procedure parameter ~S" l))))
;;    
;;    ;; code of valid-lambda? starts here
;;    
;;    (and (> (length expr) 2)
;;         (param-ok? (cadr expr) '())))
;;  

509
(define (rewrite-body body env)
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
  (fluid-let ((*expander-list* *expander-list*))
    (let Loop ((l body) (defs '()))
      (cond
	((and (pair? l) (pair? (car l)) (eq? (caar l) 'begin))
	   ;; Delete useless begin
	    (Loop (append (cdar l) (cdr l))
		  defs))
	((and (pair? l) (pair? (car l)) (eq? (caar l) 'define))
	    ;; This is an internal define 
	    (Loop (cdr l) (cons (cdr (define->lambda (car l))) defs)))
	((and (pair? l) (pair? (car l)) (eq? (caar l) 'define-macro))
	    ;; This is an internal define-macro. Add expander + skip expression
	    (compile-internal-define-macro (car l) env #f)
	    (Loop (cdr l) defs))
	((and (pair? l)
	      (pair? (car l))
	      (symbol?  (caar l))
	      (not (symbol-in-env? (caar l) env))
	      (expander? (caar l)))
	     ;; Macro-call: expand it
	     (Loop (cons (macro-expand (car l))
			 (cdr l))
		  defs))
	(else
	    ;; We have parsed all the (starting) definitions 
	    (if (null? defs)
		`(begin ,@l)
		(let ((defs (reverse! defs)))
		  ;; Generate "similar" to a letrec*
		  `(let ,(map (lambda (x) (list (car x) #f)) defs)
		     ,@(map (lambda (x) `(set! ,@x)) defs)
		     ,@l))))))))
eg's avatar
eg committed
542

543

eg's avatar
eg committed
544 545 546 547
(define (compile-user-lambda formals body arity env)	; i.e R5RS ones
  (let ((env  (extend-env env formals))
	(lab  (new-label)))
    (emit 'CREATE-CLOSURE lab arity)
548
    (compile (rewrite-body body env) env body #t)
eg's avatar
eg committed
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
    (emit 'RETURN)
    (emit-label lab)))



;;; EXTENDED LAMBDAS
;;;
;;; This code is an adaptation of the contribution of Ian Wild <[email protected]> 
;;; which provided Common Lisp style lambda lists for the original STk.
(define ext-lambda-key-get key-get)

(define (build-let* opt key rest-name user-visible-rest body)
  ;; Create a (LET*...) to do the actual bindings

  (define (pop x)
    (let ((pop-local-variable (gensym)))
      `(let ((,pop-local-variable (car ,x)))
	 (set! ,x (cdr ,x))
	 ,pop-local-variable)))


  (define (build-optional-let-header vars rest-name)
    (apply append 
	   (map (lambda (x)
		  (let ((var  (car x))
			(init (cadr x))
			(var? (caddr x)))
		    ;; if we have keywords, the end of optional
		    ;; happens when we encounter the end of the
		    ;; parameter list or the first keyword
		    (if key
			;; function accepts keywords
			(cond
			  (var? `((,var? (and (pair? ,rest-name)
					      (not (keyword? (car ,rest-name)))))
				  (,var ,(if init
					     `(if ,var? ,(pop rest-name) ,init)
					     `(and ,var? ,(pop rest-name))))))
			  (init `((,var (if (or (null? ,rest-name)
						(keyword? (car ,rest-name)))
					    ,init
					    ,(pop rest-name)))))
			  (else `((,var (and (pair? ,rest-name)
					     (not (keyword? (car ,rest-name)))
					     ,(pop rest-name))))))
			;; function has optionals but no keywords
			(cond
			  (var? `((,var? (pair? ,rest-name))
				  (,var ,(if init
					     `(if ,var? ,(pop rest-name) ,init)
					     `(and ,var? ,(pop rest-name))))))
			  (init `((,var (if (null? ,rest-name)
					    ,init
					    ,(pop rest-name)))))
			  (else `((,var (and (pair? ,rest-name)
					     ,(pop rest-name)))))))))
		  vars)))
 
   (define (constant? e)
     (cond
        ((symbol? e) #f)
	((pair? e)   (memq (car e) '(quote lambda)))
	(else 	     #t)))

   (define (build-keyword-let-header vars rest-name)
     (apply append 
	    (map (lambda (x)
		   (let* ((var  (car x))
			  (init (cadr x))
			  (var? (caddr x))
			  (key  (make-keyword var)))
		     (cond
		        (var? (let ((g (gensym)))
				`((,g (key-get ,rest-name ,key ',g))
				  (,var? (not (eq? ,g ',g)))
				  (,var ,(if init
					     `(if ,var? ,g ,init)
					     `(and ,var? ,g))))))
			((constant? init)
			    ;; if evaluating the initform is harmless, just
			    ;; call key-get with it as default
			    `((,var (key-get ,rest-name ,key ,init))))
			(else 
			     ;; only evaluate initform if get-keyword returns
			     ;; our newly gensym'ed symbol
			     (let ((g (gensym)))
			       `((,g (key-get ,rest-name ,key ',g))
				 (,var (if (eq? ,g ',g) ,init ,g))))))))
		 vars)))

  
  (let ((error-check (if (or user-visible-rest key) 
			 '()
			 `((if (pair? ,rest-name)
			       (error "too many optional parameters: ~a"
644 645 646
				      ,rest-name)))))
	(vars (append (if opt (build-optional-let-header opt rest-name) '())
		      (if key (build-keyword-let-header key rest-name) '()))))
eg's avatar
eg committed
647 648 649
    `(let* (,@(if opt (build-optional-let-header opt rest-name) '())
	    ,@(if key (build-keyword-let-header key rest-name) '()))
       ,@error-check
650
       (let () ,@body))))
eg's avatar
eg committed
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

(define (parse-parameter-list method? x)
  ;; Read the incoming lambda (or method) list, return a list of four lists,
  ;; the required, optional, keyword, and rest, in that order.
  ;; The last three elements can be #f if not present.
  ;; (Don't look too closely, this function isn't very nice.)
  (define required '())
  (define optional '())
  (define keywords '())
  (define rest 	   '())
  (define epair    x)


  (define (normalise-parameter-list x optional?)
    ;; Convert optional or keyword parameters to three-element lists: 
    ;; (variable initform supplied-p), providing an  explicit #f 
    ;; initform  if needed, and maybe another #f as supplied-p.
    (and (pair? x)
	 (map (lambda (e)
		(cond 
		  ((symbol? e)		 	(list e #f #f))
		  ((and (pair? e)
			(= (length e) 2)
			(symbol? (car e))) 	(append e (list #f)))
		  ((and (pair? e)
			(= (length e) 3)
			(symbol? (car e))
			(symbol? (caddr e))) 	e)
		  (else (compiler-error 'lambda epair "illegal ~a parameter: ~a" 
					(if optional? "optional" "keyword") e)
			(list (gensym) #f #f))))
	      x)))
  
  (define (collect-sequence)
    (let loop ((seq '()) (still-left x))
      (if (or (null? still-left) (memq (car still-left) '(:optional :key :rest)))
	  (begin
	    (set! x still-left)
	    (reverse seq))
	  (loop (cons (car still-left) seq) (cdr still-left)))))
  
  (define (collect-titled-sequence title)
    (if (and (not (null? x)) (eq? (car x) title))
	(begin
	  (set! x (cdr x))
	  (collect-sequence))
	#f))

  (define (check-formals l seen)
    (unless (null? l)
      (let ((param (car l)))
	(cond
	   ((symbol? param)
		    (if (memq param seen)
			(compiler-error (void) epair "duplicate parameter ~S" param)
			(check-formals (cdr l) (cons param seen))))
	   ((and method? (list? param) (= (length param) 2))
	    	    (if (symbol? (cadr param))
			(and (check-formals (list (car param)) seen)
			     (check-formals (cdr l) (cons (car param) seen)))
			(compiler-error (void) epair "bad class name ~S" param)))
	   (else    (compiler-error (void) epair
				     "bad procedure parameter ~S" param))))))


  ;; If the original lambda list is *not* a proper list, i.e. a symbol
  ;; or a dotted list, add in the implied :rest
  (unless (list? x)
    (set! x (if (pair? x)
		(let* ((new-x (copy-tree x))
		       (last  (last-pair new-x)))
		  (set-cdr! last (list :rest (cdr last)))
		  new-x)
		(list :rest x))))

  (set! required (collect-sequence))
  (set! optional (normalise-parameter-list (collect-titled-sequence :optional) #t))
  (set! rest 	 (collect-titled-sequence :rest))
  (set! keywords (normalise-parameter-list (collect-titled-sequence :key) #f))
  
  ;; Do some checks on the arguments
  ;; 1. no un-analyzed parameter
  (unless (null? x)
    (compiler-error 'lambda epair "illegal lambda list ending with ~a" x))

  ;; 2. Rest is a symbol (collect returns a list)
  (when rest
    (unless (and (= (length rest) 1) (symbol? (car rest)))
      (compiler-error 'lambda epair "rest parameter must be a single symbol"))
    (set! rest (car rest)))

  ;; 3. Every formal is a symbol and there is no duplicate
  (check-formals (append (if optional (map car optional) '())
			 (if keywords (map car keywords) '())
			 (if rest     (list rest)        '())
			 required)
		 '())
  ;; OK, let's go
  (list required optional keywords rest))


(define (rewrite-params-and-body method? formals body)
  ;; Rewrite the extended form as an ordinary (though headless) lambda form.
  ;; In a spurious attempt at efficiency, no LET* is generated
  ;; unless at least one of :optional and :key is used.
  (let* ((params (parse-parameter-list method? formals))
	 (req 	 (car params))
	 (opt 	 (cadr params))
	 (key 	 (caddr params))
	 (rest 	 (cadddr params)))
    (if (or opt key)
	;; We have a :optional or a :key keyword
	(let ((rest-name (or rest (gensym))))
	  (if (null? req)					; FIXME: simpl
	      (set! req rest-name)
	      (set-cdr! (last-pair req) rest-name))
	  `(,req ,(build-let* opt key rest-name rest body)))
	;; "Normal" lambda
	(begin (if rest
		   (if (null? req)
		       (set! req rest)
		       (set-cdr! (last-pair req) rest)))
	       `(,req ,@body)))))
  
(define (extended-lambda->lambda el)	;; STklos lambda => R5RS lambda
  (if (> (length el) 2)
      (let ((method? (eq? (car el) 'method))
	    (formals (cadr el))
	    (body    (cddr el)))
	(cons 'lambda (rewrite-params-and-body method? formals body)))
      (compiler-error 'lambda el "bad definition ~S" el)))


(define (compile-lambda args env tail?)
  (let* ((r5rs-lambda (extended-lambda->lambda args))
	 (formals     (cadr r5rs-lambda))
	 (body        (cddr r5rs-lambda))
	 (arity       (compute-arity formals)))
    (compile-user-lambda formals body arity env)))

;;;;
;;;; APPLICATION
;;;;

(define (compile-args actuals env)
  (unless (null? actuals)
    (compile (car actuals) env actuals #f)
    (emit 'PUSH)
    (compile-args (cdr actuals) env)))


(define (compile-var-args actuals number-of-fix env)
  ;; for a (a b . c), replace (1 2 3 4 5) by (1 2 (list 3 4 5))
  (let loop ((n number-of-fix) (f '()) (rest actuals))
    (if (zero? n)
	(compile-args `(,@(reverse f) (list ,@rest)) env)
	(loop (- n 1) (cons (car rest) f) (cdr rest)))))

(define (generate-PREPARE-CALL epair)
  (emit 'PREPARE-CALL)
  (when (and (compiler:gen-line-number) (%epair? epair))
    ;; Generate a line number for the call
    (compile-constant (%epair-file epair) '() #f)
    (emit 'PUSH)
    (compile-constant (%epair-line epair) '() #f)
    (emit 'DBG-VM 1)))


(define (compile-normal-call fct actuals len env epair tail?)
  (generate-PREPARE-CALL epair)
  (compile-args actuals env)
  (compile fct env actuals #f)
  (emit (if tail? 'TAIL-INVOKE  'INVOKE)
	(length actuals)))

826 827 828 829 830 831 832 833 834
(define can-be-inlined?
  (let ((STklos (find-module 'STklos)))
    (lambda (fct env)
      ;; Avoid to use *inline-table* on all symbols (assoc is too expensive here)
      (if (and (memq fct *inline-symbols*)
	       (not (symbol-in-env? fct env)))
	  (let ((f (assoc fct *inline-table*)))
	    (and f (eq? (symbol-value* fct STklos) (cdr f))))
	  (memq fct *always-inlined*)))))
eg's avatar
eg committed
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856


(define (compile-primitive-call fct actuals len env epair tail?)
  (let ((comp  (lambda (mnemo expr)
		 (compile expr env epair #f)
		 (emit mnemo)))
	(comp1 (lambda (mnemo)
		 (if (= len 1)
		     (begin
		       (compile (car actuals) env epair #f)
		       (emit mnemo))
		     (compiler-error fct epair "1 argument required (~A provided)" 
				    len))))
	(comp2 (lambda (mnemo)
		 (if (= len 2)
		     (begin
		       (compile (car actuals) env epair #f)
		       (emit 'PUSH)
		       (compile (cadr actuals) env epair #f)
		       (emit mnemo))
		     (compiler-error fct epair "2 arguments required (~A provided)"
				    len))))
Erick Gallesio's avatar
Erick Gallesio committed
857 858 859 860 861 862 863 864
	(oper2 (lambda (mnemo a b)
		 (compile a env epair #f)
		 (emit mnemo b)))
	(komp2 (lambda (mnemo a b)
		 (compile a env epair #f)
		 (emit 'PUSH)
		 (compile b env epair #f)
		 (emit mnemo)))
eg's avatar
eg committed
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
	(comp3 (lambda (mnemo)
		 (if (= len 3)
		     (begin 
		       (compile (car actuals) env epair #f)
		       (emit 'PUSH)
		       (compile (cadr actuals) env epair #f)
		       (emit 'PUSH)
		       (compile (caddr actuals) env epair #f)
		       (emit mnemo))
		     (compiler-error fct epair "3 arguments required (~A provided)"
				     len)))))
    (case fct
      ;; Always inlined functions
      ((%%set-current-module)
       	      (if (= len 1)
		  (comp1 'SET-CUR-MOD)
		  (compiler-error '%%set-current-module epair
				   "1 arg. only (~S)" len)))
      ((%%execute-handler)
       	      (comp3 'EXEC-HANDLER))

      ;; User functions 
      ((void) (emit 'IM-VOID))
Erick Gallesio's avatar
Erick Gallesio committed
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
      ((+)  (case len
	      ((0)  (emit 'IM-ZERO))
	      ((1)  (compile (car actuals) env epair tail?))
	      ((2)  (let ((a (car actuals))
			  (b (cadr actuals)))
		      (cond
			((and (number? a) (number? b))
			 (compile-constant (+ a b) env #f))
			((small-integer-constant? a)
			 (oper2 'IN-SINT-ADD2 b a))
			((small-integer-constant? b)
			 (oper2 'IN-SINT-ADD2 a b))
			(else
			 (comp2 'IN-ADD2)))))
	      (else (compile-normal-call fct actuals len env epair #f))))
      ((-)  (case len
		((0)  (compiler-error '- epair "needs at least one argument"))
		((1)  (if (number? (car actuals))
Erick Gallesio's avatar
.  
Erick Gallesio committed
906
			  (compile-constant (- (car actuals)) env #f)
Erick Gallesio's avatar
Erick Gallesio committed
907 908 909 910 911 912 913 914 915 916 917 918 919
			  (compile-normal-call fct actuals len env epair #f)))
		((2)  (let ((a (car actuals))
			    (b (cadr actuals)))
			(cond
			  ((and (number? a) (number? b))
			   (compile-constant (- a b) env tail?))
			  ((small-integer-constant? a)
			   (oper2 'IN-SINT-SUB2 b a))
			  ((and (number? b)
				(small-integer-constant? (- b)))
			   (oper2 'IN-SINT-ADD2 a (- b)))
			  (else
			   (comp2 'IN-SUB2)))))
eg's avatar
eg committed
920 921 922
		(else (compile-normal-call fct actuals len env epair #f))))
      ((*)    (case len
		((0)  (emit 'IM-ONE))
Erick Gallesio's avatar
Erick Gallesio committed
923 924 925 926 927 928 929 930 931
		((1)  (compile (car actuals) env epair tail?))
		((2)  (let ((a (car actuals))
			    (b (cadr actuals)))
			(cond
			  ((and (number? a) (number? b))
			   (compile-constant (* a b) env tail?))
			  ((small-integer-constant? a)
			   (oper2 'IN-SINT-MUL2 b a))
			  ((small-integer-constant? b)
Erick Gallesio's avatar
Erick Gallesio committed
932
			   (oper2 'IN-SINT-MUL2 a b))
Erick Gallesio's avatar
Erick Gallesio committed
933 934
			  (else
			   (comp2 'IN-MUL2)))))
eg's avatar
eg committed
935 936 937
		(else (compile-normal-call fct actuals len env epair #f))))
      ((/)    (case len
		((0)   (compiler-error '/ epair "needs at least one argument"))
Erick Gallesio's avatar
Erick Gallesio committed
938
		((1)   (if (number? (car actuals))
Erick Gallesio's avatar
.  
Erick Gallesio committed
939
			  (compile-constant (/ 1 (car actuals)) env #f)
Erick Gallesio's avatar
Erick Gallesio committed
940 941 942 943 944 945 946
			  (compile-normal-call fct actuals len env epair #f)))
		((2)  (let ((a (car actuals))
			    (b (cadr actuals)))
			(cond
			  ((and (number? a) (number? b))
			   (compile-constant (/ a b) env tail?))
			  ((small-integer-constant? b)
Erick Gallesio's avatar
Erick Gallesio committed
947
			   (oper2 'IN-SINT-DIV2 a b))
Erick Gallesio's avatar
Erick Gallesio committed
948 949
			  (else
			   (comp2 'IN-DIV2)))))
eg's avatar
eg committed
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
		(else  (compile-normal-call fct actuals len env epair #f))))
      ((= < > <= >=)
		(case len
		((O)   (compiler-error fct epair
					"needs at least one argument" fct))
		((2)   (comp2 (case fct
				((=)  'IN-NUMEQ)
				((<)  'IN-NUMLT)
				((>)  'IN-NUMGT)
				((<=) 'IN-NUMLE)
				((>=) 'IN-NUMGE))))
		(else  (compile-normal-call fct actuals len env epair #f))))
      ((cons)   (comp2 'IN-CONS))
      ((car)    (comp1 'IN-CAR))
      ((cdr)    (comp1 'IN-CDR))
      ((null?)  (comp1 'IN-NULLP))
      ((not)    (comp1 'IN-NOT))
      ((list)   (compile-args actuals env)
	        (emit 'IN-LIST len))
;;//      ((apply)  (case len
;;//		  ((0)  (compile-error "no argument given to apply"))
;;//		  ((1)  (compile-primitive-call fct (list (car actuals) '())
;;//						(+ len 1) env tail?))
;;//		  (else (emit 'PREPARE-CALL)
;;//			(compile-args (cdr actuals) env)
;;//			(compile (car actuals) env #f)
;;//			(emit 'IN-APPLY (- len 1) (if tail? 1 0)))))
      ((vector-ref)	(comp2 'IN-VREF))
      ((vector-set!)	(comp3 'IN-VSET))
      ((string-ref)	(comp2 'IN-SREF))
      ((string-set!)	(comp3 'IN-SSET))
      ((eq?)		(comp2 'IN-EQ))
      ((eqv?)		(comp2 'IN-EQV))
      ((equal?)		(comp2 'IN-EQUAL))
      (else     	(panic "unimplemented inline primitive ~S" fct)))))



(define (compile-lambda-call fct actuals len env epair tail?)
  ;; Compilation of ( [LAMBDA(.)...] ..... )
  (let* ((fct     (extended-lambda->lambda fct))
	 (formals (cadr fct))
	 (body    (cddr fct))
	 (arity   (compute-arity formals)))
    (if (or (= arity len)
	    (and (negative? arity) (>= len (- (- arity) 1))))
996 997
	(let ((kind    (if tail? 'ENTER-TAIL-LET 'ENTER-LET))
	      (new-env (extend-env env formals)))
eg's avatar
eg committed
998 999 1000 1001 1002 1003 1004 1005
	  (generate-PREPARE-CALL epair)
	  (if (negative? arity)
	      (begin
		(compile-var-args actuals (- (- arity) 1) env)
		(emit kind (- arity)))
	      (begin
		(compile-args actuals env)
		(emit kind len)))
1006
	  (compile (rewrite-body body new-env) new-env epair tail?)
eg's avatar
eg committed
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
	  (emit (if tail? 'RETURN 'LEAVE-LET)))
	(compiler-error 'lambda epair "bad number of parameters ~S" actuals))))


(define (compile-call args env tail?)
  (let* ((fct 	  (car args))
	 (actuals (cdr args))
	 (len 	  (length actuals)))
    (if (and (pair? fct) (eq? (car fct) 'lambda))
	;; fct is (lambda (...) ...)
	;;    if fct is not an epair, it is probably because it has been
	;;    built programmatically. Anyway its body is probably an epair 
	(let ((ep (cond
		    ((%epair? fct) fct)
		    ((>= (length fct) 3) (cddr fct))
		    (else fct))))
	  (compile-lambda-call fct actuals len env ep tail?))
1024
	(if (can-be-inlined? fct env)
eg's avatar
eg committed
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
	    (compile-primitive-call fct actuals len env args tail?)
	    (compile-normal-call    fct actuals len env args tail?)))))

;;;;
;;;; LET / LET* / LETREC
;;;;
(define (valid-let-bindings? bindings unique?)
  (letrec 
      ((aux (lambda (l seen)
	      (cond 
	       ((null? l) #t)
	       ((pair? l) (let ((b (car l)))
			    (if (and (list? b) 
				     (= (length b) 2)
				     (symbol? (car b)))
				(if (and unique? (memq (car b) seen))
				    (compiler-error 'let bindings
						     "duplicate binding ~S" (car b))
				    (aux (cdr l) (cons (car b) seen)))
				(compiler-error 'let bindings
						 "malformed binding ~S" b))))
	       (else #f)))))
    (aux bindings '())))

;;
;; LETREC
;;

(define (compile-letrec args env tail?)
  (let ((len (length args)))
    (if (< len 3)
	(compiler-error 'letrec args "ill formed letrec ~S" args)
	(let ((bindings (cadr args))
              (body     (cddr args)))
	  (if (null? bindings)
1060
	      (compile (rewrite-body body env) env body tail?)
eg's avatar
eg committed
1061 1062 1063 1064 1065 1066 1067
	      (when (valid-let-bindings? bindings #t)
		(let ((tmps (map (lambda (_) (gensym)) bindings)))
		  (compile `(let ,(map (lambda (x) (list (car x) #f)) bindings)
			      (let ,(map (lambda (x y) (list x (cadr y)))
					 tmps bindings)
				,@(map (lambda (x y) `(set! ,(car y) ,x))
				       tmps bindings))
1068
			      (let () ,@body))
eg's avatar
eg committed
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
			   env args tail?))))))))

;;
;; LET (& named let)
;;

(define (compile-named-let name bindings body len args env tail?)
  (if (< len 4)
      (compiler-error 'let args "ill formed named let ~S" args)
      (when (valid-let-bindings? bindings #t)
	(compile `((letrec ((,name (lambda ,(map car bindings) ,@body)))
		       ,name)
		   ,@(map cadr bindings))
		 env
		 args
		 tail?))))


(define (compile-let args env tail?)
  (let ((len (length args)))
    (if (< len 3)
	(compiler-error 'let args "ill formed let ~S" args)
	(let ((bindings (cadr args))
	      (body	(cddr args)))
	  (if (symbol? bindings)
	      ;; Transform named let in letrec
	      (compile-named-let bindings (car body) (cdr body) len args env tail?)
	      (when (valid-let-bindings? bindings #t)
		(if (null? bindings)
1098
		    (compile (rewrite-body body env) env args tail?)
eg's avatar
eg committed
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
		    (compile `((lambda ,(map car bindings) ,@body)
			       ,@(map cadr bindings))
			     env args tail?))))))))

;;
;; LET*
;;

;; Here is a simple version (inefficient) of compile-let*
;;    
;;    (define (compile-let* args env tail?)
;;      (let ((len (length args)))
;;        (if (< len 3)
;;    	(compiler-error 'let* args "ill formed let* ~S" args)
;;    	(let ((bindings (cadr args))
;;    	      (body	(cddr args)))
;;    	  (when (valid-let-bindings? bindings #f)
;;    	    (compile (if (<= (length bindings) 1)
;;    			 `(let ,bindings ,@body)
;;    			 `(let (,(car bindings))
;;     			    (let* ,(cdr bindings)
;;    			      ,@body)))
;;    		     env args tail?))))))
;;    

(define (compile-let* args env tail?)
  ;; This is a little bit tricky
  ;; We have something like
  ;; (let ((a E1) (b E2)) ...) =>
  ;;              (let ((a #f) (b #f))          [1]
  ;;                (set! a E1) (set! b E2)	[2]
  ;;                 ...)			[3]
  ;;
  ;; For [1], we have 2 special instructions which reserve space on the stack
  ;; For [2], this is a little bit more complicate since E1 must be evaluated
  ;; in an environment without a, E2 must be evaluated in an environment with
  ;; a and without b
  ;; [3] must be evaluated in an environment where a and b are defined;
  ;; 
  ;; If there are multiple definition of the same variable, it is multi-allocated
  ;; but only one slot will be used. Not a big deal, in general
  (let ((len (length args)))
    (if (< len 3)
	(compiler-error 'let* args "ill formed let* ~S" args)
	(let ((bindings (cadr args))
	      (body	(cddr args)))
	  (when (valid-let-bindings? bindings #f)
	    (if (<= (length bindings) 1)
		(compile-let `(let ,bindings ,@body) env tail?)
		(begin 
		  (emit (if tail? 'ENTER-TAIL-LET-STAR 'ENTER-LET-STAR)
			(length bindings))
		  (let Loop ((l bindings)
			     (locals '()))
		    (if (null? l)
			;; Compile body
1155 1156 1157
			(let ((new-env (extend-env env locals)))
			  (compile (rewrite-body body new-env)
				   new-env
eg's avatar
eg committed
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
				   body
				   tail?)
			  (emit (if tail? 'RETURN 'LEAVE-LET)))
			;; Compile an assignment
			(let* ((var (caar l))
			       (val (cadar l))
			       (loc (cons var locals)))
			  (compile val (extend-env env locals) args #f)
			  (compile-access var (extend-env env loc) args #f)
			  (Loop (cdr l)
				loc)))))))))))

Erick Gallesio's avatar
.  
Erick Gallesio committed
1170

eg's avatar
eg committed
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
;;
;; COND
;;
(define (rewrite-cond-clauses c)
  (cond 
   ((null? c) 		      (void))
   ((not (pair? (car c)))     (compiler-error 'cond c "invalid clause ~S" (car c)))
   ((eq? (caar c) 'else)      (if (null? (cdr c))
				  `(begin ,@(cdar c))
				  (compiler-error 'cond
						   c
						   "else not in last clause ~S" 
						   c)))
   ((and (pair? (cdar c)) (eq? (cadar c) '=>))
    			      (if (and (list? (car c)) (= (length (car c)) 3))
				  (let ((test-var (gensym)))
				    `(let ((,test-var ,(caar c)))
				       (if ,test-var
					   (,(caddar c) ,test-var)
					   ,(rewrite-cond-clauses (cdr c)))))
				  (compiler-error 'cond
						   c
						   "bad '=>' clause syntax ~S" 
						   (car c))))
   ((null? (cdar c))	      (let ((test-var (gensym)))
				`(let ((,test-var ,(caar c)))
				   (or ,test-var
				       ,(rewrite-cond-clauses (cdr c))))))
   (else 		      `(if ,(caar c) 
				   (begin ,@(cdar c))
				   ,(rewrite-cond-clauses (cdr c))))))

(define (compile-cond e env tail?)
  (let ((new-form (rewrite-cond-clauses (cdr e))))
    (compile new-form env e tail?)))

;;
;; CASE
;;

(define (rewrite-case-clauses key clauses)
  ;; Some controls on the case form
  (let ((all-values '()))
    (for-each (lambda (clause)
		(if (pair? clause)
		    (cond 
		      ((eq? (car clause) 'else) 
		       	   'ok)
		      ((pair? (car clause))	
		           ;; OK but verify that there are no duplicates 
		       	   (for-each (lambda (x)
				       (if (memv x all-values)
					   (compiler-error
					       'case clause
					       "duplicate case value ~S in ~S" 
					       x clause)))
				     (car clause))
			   (set! all-values (append (car clause) all-values)))
		      (else  
		           (compiler-error 'case clause
					   "ill formed case clause ~S" clause)))
		    (compiler-error 'case clauses
				    "invalid clause syntax in ~S" clause)))
	      clauses))

  ;; Generate equivalent cond form
  `(cond ,@(map (lambda (clause)
		  ;; We are not sure it is a well formed clause since
		  ;; previous checks may not call error (file compilation)
		  (if (pair? clause)
		      (let ((case  (car clause))
			    (exprs (cdr clause)))
			(if (eq? case 'else)
			    `(else ,@exprs)
			    (if (pair? case)
				(if (= (length case) 1)
				    `((eqv? ,key ',(car case)) ,@exprs)
				    `((memv ,key ',case) ,@exprs))
				`(#t (error "invalid case clause")))))
		      `(#t (error "invalid case"))))
		clauses)))

(define (compile-case e env tail?)
  (if (> (length e) 2)
      (let* ((key     (cadr e))
	     (clauses (cddr e))
	     (new-form (if (pair? key)
			   (let ((newkey (gensym)))
			     `(let ((,newkey ,key)) 
				,(rewrite-case-clauses newkey clauses)))
			   (rewrite-case-clauses key clauses))))
	(compile new-form env e tail?))
      (compiler-error 'case e "no key given")))

;;
;; DO 
;;
(define (rewrite-do inits test body)
  (let ((loop-name (gensym)))
    `(letrec ((,loop-name
       (lambda ,(map car inits)
	 (if ,(car test)
	     (begin ,@(if (null? (cdr test)) 
			  (list (void))
			  (cdr test)))
	     (begin ,@body
		    (,loop-name ,@(map (lambda (init)
					 (if (< (length init) 2)
					     (compiler-error 'do
							      init
							      "bad binding ~S"
							      init)
					     (if (null? (cddr init))
						 (car init)
						 (caddr init))))
				       inits)))))))
       (,loop-name ,@(map cadr inits)))))


(define (compile-do e env tail?)
  (if (>= (length e) 3)
      (compile (rewrite-do (cadr e) (caddr e) (cdddr e))
	       env
	       e
	       #f)
      (compiler-error 'do e "bad syntax")))

;;
;; QUASIQUOTE
;;

(define (backquotify e level)
  (cond
     ((vector? e)     (list 'list->vector (backquotify (vector->list e) level)))
     ((not (pair? e)) (list 'quote e))
     ((eq? (car e) 'quasiquote)
      		      (list 'list ''quasiquote 
			    (backquotify (cadr e) (+ level 1))))
     ((eq? (car e) 'unquote)
      		      (if (= level 1)
			  (cadr e)
			  (list 'list ''unquote 
				(backquotify (cadr e) (- level 1)))))
     ((and (pair? (car e)) (eq? (caar e) 'unquote-splicing))
      		       (if (null? (cdr e))
			   (if (> level 1)
			       (list 'quote e) 
			       (cadar e))
			   (list 'append (cadar e)
				 (backquotify (cdr e) level))))
    ((and  (list? e) (not (assv 'unquote-splicing  e)) (not (assv 'unquote e))
	   (not (memv 'unquote e)) (not (memv 'unquote-splicing e)))
     		      ;; This is an optimization to use list when possible
     		      ;; instead of numerous cons For instance `(a ((b ,c)) d)
     		      ;; will give (list 'a (list (list 'b c)) 'd) instead of
     		      ;; (cons 'a (cons (cons (cons 'b (cons c '())) '())
     		      ;;                (cons 'd '())))
      		      (cons 'list (map (lambda (x) (backquotify x level)) e)))
     (else	      (list 'cons 
			    (backquotify (car e) level)
			    (backquotify (cdr e) level)))))

(define (compile-quasiquote e env tail?)
  (if (= (length e) 2)
      (compile (backquotify (cadr e) 1) env e tail?)
      (compiler-error 'quasiquote e "bad syntax")))


;;
;; WITH-HANDLER
;;
(define (compile-with-handler e env tail?)
  (if (> (length e) 2)
      (let ((handler (cadr e))
	    (body    (cddr e))
	    (lab     (new-label)))
	(compile handler env e #f)
	(emit 'PUSH-HANDLER lab)
	(compile `(begin ,@body) env body #f)
	(emit 'POP-HANDLER)
	(emit-label lab))
      (compiler-error 'with-handler e "bad syntax")))


;;
;; INCLUDE
;;

#|
<doc EXT-SYNTAX include
 * (include <file>)
 * 
 * TODO
doc>
|#
(define (include-file name)
  (let ((port (open-input-file name))
	(old  *compiler-port*))
    (with-handler (lambda (c) (set! *compiler-port* old) (raise c))
		  (set! *compiler-port* port)
		  
		  (do ((expr (%read port) (%read port)))
		      ((eof-object? expr))
		    (compile expr '() expr #f))
		  
		  (set! *compiler-port* old))
    (close-port port)))

(define (compile-include e env tail)
  (if (and (= (length e) 2) (string? (cadr e)))
      (include-file (cadr e))
      (compiler-error 'include e "bad include directive ~S" e)))


;;
;; Autoloads management 
;;
(define (compiler-maybe-do-autoload symb)
  (let ((file (autoload-file symb)))
    (when file
      ;; Do the autoload
      (let ((old-code *code-instr*)
	    (old-cst  *code-constants*))
	(remove-autoload! symb)
	(require file)
	(set! *code-instr* old-code)
	(set! *code-constants* old-cst)))))

;;;;======================================================================
;;;;
;;;; 		Special Calls 
;;;; 
;;;;======================================================================
Erick Gallesio's avatar
.  
Erick Gallesio committed
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
(define (compile-require e env tail)
  ;; Require is not really special (it is in fact compiled as a normal call)
  ;; We just try to add the globals of the file to the list of known
  ;; globals. This is very empiric, but it avoids to add too much false
  ;; warning when compiling a file using another one.
  (when (and (= (length e) 2)
	     (string? (cadr e)))
    (let ((infos (let ((path (find-path (cadr e))))
		   (if path
		       (%file-informations path)
		       '()))))
      (when (pair? infos)
	(for-each new-global (key-get infos :globals '())))))

  (compile-normal-call (car e) (cdr e) (length e) env e tail))
eg's avatar
eg committed
1419

1420 1421 1422 1423 1424 1425 1426 1427 1428 1429

(define (compile-require4syntax e env tail)
  ;; No code is produced here, we only load the file for the compiler
  (with-handler
     (lambda (c)
       (eprintf "*** Exception while evaluation of required syntax ~S\n" e)
       (raise c))
     (require (cadr e))))


eg's avatar
eg committed
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
(define (compile-%%label e env tail)
  (if (= (length e) 2)
      (emit-label (cadr e))
      (compiler-error '%%label e "bad usage ~S" e)))

(define (compile-%%goto e env tail)
  (if (= (length e) 2)
      (emit 'GOTO (cadr e))
      (compiler-error '%%goto e "bad usage ~S" e)))


(define (compile-%%source-pos e env tail)
  (compile (if (%epair? e)
	       `(cons ,(%epair-file e) ,(%epair-line e))
	       #f)
	   '()
	   e
	   #f))

;;;;======================================================================
;;;;
;;;; 		The bytecode compiler 
;;;; 
;;;;======================================================================
(define (compile e env epair tail?)
  (if (not (pair? e))
      (if (symbol? e)
	  (begin
	    (compiler-maybe-do-autoload e)
	    (compile-reference e env epair tail?))
	  (compile-constant  e env tail?))
      (begin
	(case (car e)
	  ((quote)		(compile-quote		e env tail?))
	  ((if)			(compile-if		e env tail?))
	  ((define)		(compile-define		e env tail?))
	  ((begin)		(compile-begin		e env tail?))
	  ((lambda)		(compile-lambda		e env tail?))
	  ((let)		(compile-let		e env tail?))
	  ((let*)		(compile-let*		e env tail?))
	  ((letrec)		(compile-letrec		e env tail?))
	  ((set!)		(compile-set!		e env tail?))
	  ((and)		(compile-and		e env tail?))
	  ((or)			(compile-or		e env tail?))
	  ((cond)		(compile-cond		e env tail?))
	  ((case)		(compile-case		e env tail?))
	  ((do)			(compile-do		e env tail?))
	  ((when)		(compile-when		e env tail?))
	  ((unless)		(compile-unless		e env tail?))
	  ((quasiquote)		(compile-quasiquote	e env tail?))
	  ((with-handler) 	(compile-with-handler	e env tail?))
	  ((define-macro) 	(compile-define-macro   e env tail?))
	  
	  ;; Special calls
Erick Gallesio's avatar
.  
Erick Gallesio committed
1484
	  ((require)		(compile-require	e env tail?))
1485
	  ((%%require4syntax)	(compile-require4syntax e env tail?))
eg's avatar
eg committed
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
	  ((%%include)		(compile-include	e env tail?))
	  ((%%source-pos)	(compile-%%source-pos   e env tail?))
	  ((%%label)		(compile-%%label	e env tail?))
	  ((%%goto)		(compile-%%goto		e env tail?))
	  
	  ;; Unmatched cases
	  (else			(let ((first (car e)))
				  (compiler-maybe-do-autoload first)
				  (if (and (symbol? first)
					   (not (symbol-in-env? first env))
					   (expander? first))
				      (compile (macro-expand e) env epair tail?)
				      (compile-call e env tail?))))))))


;=============================================================================
;
1503
; Eval
eg's avatar
eg committed
1504 1505 1506
;
;=============================================================================

1507
(define (eval e :optional env)
eg's avatar
eg committed
1508

1509 1510 1511 1512
  (define (parse-expression e)
    (compile e '() e #f)
    (emit 'END-OF-CODE)
    (assemble (reverse! *code-instr*)))
eg's avatar
eg committed
1513

1514 1515 1516 1517 1518
  (fluid-let ((*code-instr*     '())
	      (*code-constants* '()))
    (let ((code (parse-expression e)))
      ;;(disassemble-code code (current-error-port))
      (%execute code (list->vector *code-constants*) (or env (current-module))))))
eg's avatar
eg committed
1519

1520 1521
;; ======================================================================
(select-module STklos)
1522
(import STKLOS-COMPILER)
1523 1524 1525
(define eval (in-module STKLOS-COMPILER eval))


eg's avatar
eg committed
1526 1527
;;)
; LocalWords:  initform autoload Autoloads