Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 941 lines (804 sloc) 27.294 kb
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
; Copyright 2010 Brian Taylor
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;

; DESCRIPTION:
;
; This is essentially a direct translation of the bytecode compiler
; presented in Peter Norvig's "Paradigms of Artificial Intelligence
; Programming." The bytecode should be identitcal to the bytecode
; produced in the book.
;
; The 'bytecodes' generated by this compiler can be executed on the
; virtual machine defined in vm.c. These bytecodes are also suitable
; for further translation and optimization. The eventual goal is
; to turn them into native assembly so user defined routines can
; execute with the same performance as interpreter primitives.


;; Comment out the second form for loads of function trace
;; information. I should really write a real trace macro at some
;; point.

(define (write-dbg1 . args)
  "display the given forms"
  (display "debug: ")
  (display args)
  (newline)
  args)

(define (write-dbg . args)
  "do nothing."
  #t)

;(define write-dbg write-dbg1)

(define (write-passthrough arg)
  (apply write-dbg arg)
  arg)

(define (write-passthrough arg)
  arg)

(define (comp-bound? sym)
  "is the symbol defined in the compiled global environment?"
  (let* ((sentinal (gensym))
(result (hashtab-ref *vm-global-environment* sym sentinal)))
    (not (eq? result sentinal))))

(define (comp-global-ref sym)
  "return the global from the compiled env. error if not defined."
  (let* ((sentinal (gensym))
(result (cdr (hashtab-ref *vm-global-environment* sym sentinal))))
    (if (eq? result sentinal)
(throw-error "symbol" sym "is not defined in compiled env")
result)))

(define (comp-macro? sym)
  "is a given symbol a macro in the compiled environment?"
  (and (comp-bound? sym)
       (compiled-syntax-procedure? (comp-global-ref sym))))

(define (expression-expander exp)
  "hook that's used by clos to define inliners"
  nil)

(define (comp-macroexpand0 form)
  "expand form using a macro found in the compiled environment"
  (apply (comp-global-ref (car form)) (cdr form)))

(define (comp x env val? more?)
  "compile an expression in the given environment optionally caring
about its value and optionally with more forms following"
  (write-dbg 'comp x 'val? val? 'more? more?)
  (cond
   ((variable-reference? x) (comp-var x env val? more?))
   ((atom? x) (comp-const x val? more?))
   (else
    (record-case x
      (if-compiling (then else)
        (comp then env val? more?))
      (quote (obj)
        (comp-const obj val? more?))
      (begin exps
        (comp-begin exps env val? more?))
      (set! (sym val)
        (seq (comp val env #t #t)
(gen-set sym env)
(when (not val?) (gen 'pop))
(unless more? (seq (gen 'endframe 1)
(gen 'return)))))
      (if (test then . else)
(let ((else (car-else else nil)))
(comp-if test then else env val? more?)))
      (lambda (args . body)
(when val?
(let ((f (comp-lambda args body env)))
(seq (gen 'fn f)
(unless more? (seq (gen 'endframe 1)
(gen 'return)))))))
      (inlined-lambda (args body)
(comp-begin (cdr body) env val? more?))

      ;; generate an invocation
      (else
       (comp-funcall (first x) (rest x)
env val? more?))))))

(define (%<=2 a b)
  (or (%fixnum-less-than a b) (%fixnum-equal a b)))

(define (%<= . values)
  (every-pair? %<=2 values))

(define (%arg-count form min max)
  (let ((n-args (length (rest form))))
    (unless (%<= min n-args max)
(throw-error "wrong number of args"
form
"expected between"
min "and" max))))

(define (comp-begin exps env val? more?)
  (write-dbg 'comp-begin exps 'val? val? 'more? more?)
  (cond ((null? exps) (comp-const nil val? more?))
((length=1 exps) (comp (first exps) env val? more?))
(else (seq (comp (first exps) env #f #t)
(comp-begin (rest exps) env val? more?)))))

(define (comp-list exps env)
  (write-dbg 'comp-list exps)
  (if (null? exps) nil
      (seq (comp (first exps) env #t #t)
(comp-list (rest exps) env))))

(define (comp-const x val? more?)
  (write-dbg 'comp-const x 'val? val? 'more? more?)
  (when val? (seq (gen 'cconst x)
(unless more? (seq (gen 'endframe 1)
(gen 'return))))))

(define (comp-var x env val? more?)
  (write-dbg 'comp-var x 'val? val? 'more? more?)
  (when val? (seq (gen-var x env)
(unless more? (seq (gen 'endframe 1)
(gen 'return))))))

(define (false? exp)
  (or (null? exp) (eq? exp #f) (eq? exp 'nil)))

(define (true? exp)
  (eq? exp #t))

(define (comp-if pred then else env val? more?)
  (write-dbg 'comp-if pred 'then then 'else else
'val? val? 'more? more?)
  (cond
   ((false? pred)
    (comp else env val? more?))
   ((true? pred)
    (comp then env val? more?))
   (else (let ((pcode (comp pred env #t #t))
(tcode (comp then env val? more?))
(ecode (comp else env val? more?)))
(cond
((equal? tcode ecode)
(seq (comp pred env #f #t)
ecode))
((null? tcode)
(let ((l2 (gen-label)))
(seq pcode
(gen 'tjump l2) ecode (list l2)
(unless more? (seq (gen 'endframe 1)
(gen 'return))))))
((null? ecode)
(let ((l1 (gen-label)))
(seq pcode
(gen 'fjump l1) tcode (list l1)
(unless more? (seq (gen 'endframe 1)
(gen 'return))))))
(else
(let ((l1 (gen-label))
(l2 (when more? (gen-label))))
(seq pcode (gen 'fjump l1) tcode
(when more? (gen 'jump l2))
(list l1) ecode
(when more? (list l2))))))))))

(define (gen opcode . args)
  (write-dbg 'gen opcode 'args args)
  (list (cons opcode args)))

(define (seq . code)
  (append-all code))


(set! *bytecode-primitives*
      `((cons 2 ,(gen 'cons))
(car 1 ,(gen 'car))
(first 1 ,(gen 'car))
(cdr 1 ,(gen 'cdr))
(rest 1 ,(gen 'cdr))
(set-car! 2 ,(gen 'setcar))
(set-cdr! 2 ,(gen 'setcdr))
(second 1 ,(seq (gen 'cdr)
(gen 'car)))
(third 1 ,(seq (gen 'cdr)
(gen 'cdr)
(gen 'car)))))


(define (bytecode-primitive? sym)
  (find (lambda (op) (eq? (first op) sym)) *bytecode-primitives*))

(define (primitive-nargs sym)
  (second (bytecode-primitive? sym)))

(define (primitive-bytecode sym)
  (third (bytecode-primitive? sym)))

(define (ref-to-symbol fn)
  "try to convert a variable reference to a symbol"
  (cond
   ((variable-reference? fn)
    (let ((var (variable-reference-variable-ref fn)))
      (cond
       ((global-variable? var)
(global-variable-name-ref var))
       (else fn))))
   (else fn)))

(define (comp-funcall f args env val? more?)
  (write-dbg 'comp-funcall f 'args args
'val? val? 'more? more?)

  (cond
   ;; special case invocations that correspond to bytecode primitives
   ;(display f) (newline)
   ((bytecode-primitive? (ref-to-symbol f))
    (let ((sym (ref-to-symbol f)))
      ;; NOTE: all primitive bytecodes are for value not effect so we
      ;; can skip them entirely if (not val?)
      (unless (%fixnum-equal (length args) (primitive-nargs sym))
(throw-error "primitive" sym "requires exactly" (primitive-nargs sym)
"arguments. You supplied " (length args)))
      (seq (comp-list args env)
(primitive-bytecode sym)
(unless val? (gen 'pop))
(unless more? (seq (gen 'endframe 1)
(gen 'return))))))

   ;; inline calls to no-arg lambda
   ((and (starts-with? f 'lambda eq?) (null? (second f)))
    (unless (null? args) (throw-error "too many arguments"))
    (comp-begin (cdr (cdr f)) env val? more?))

   (more?
    (let ((k (gen-label 'k)))
      (seq (gen 'save k)
(comp-list args env)
(comp f env #t #t)
(gen 'callj (length args) #t)
(list k)
(unless val? (gen 'pop)))))
   (else
    (seq (comp-list args env)
(comp f env #t #t)
(gen 'endframe (%fixnum-add (length args) 1))
(gen 'callj (length args))))))

(define-struct fn
  "a structure representing a compiled function"
  (code
   env
   name
   args))

(define (comp-lambda args body env)
  "generate code for BODY with ARGS in ENV. Only generates a new
chainframe if ARGS is non-nil"
  (write-dbg 'comp-lambda args 'body body)

  ;; compute the set of free variables and the set of stack variables
  (let* ((inline-args (reduce (lambda (found form)
(find-inlined-vars form found))
body nil))
(free-inline (filter variable-is-free-ref inline-args))
(unfree-inline (filter (lambda (f) (not (variable-is-free-ref f))) inline-args))
(free-args (filter variable-is-free-ref (append (make-true-list args) free-inline)))
(stack-idx 0)
(frame-idx 0))

    ;; assign frame positions to the free variables
    (dolist (arg free-args)
      (variable-idx-set! arg frame-idx)
      (%inc! frame-idx))

    ;; assign stack positions to each of the remaining arguments
    (dolist (arg (append (make-true-list args) unfree-inline))
      (unless (variable-is-free-ref arg)
        (variable-idx-set! arg stack-idx))
      (%inc! stack-idx))

    (let ((new-env (if free-args
(cons free-args env)
env)))

      (new-fun (seq (%gen-args args free-inline)
;; make room on stack for unfree
(apply seq
(map (lambda (v)
(gen 'cconst '()))
unfree-inline))
(comp-begin body
new-env
#t #f))
env "unknown" args))))

(define (%count-free-args args)
  (reduce (lambda (count arg)
(if (variable-is-free-ref arg)
(%fixnum-add count 1)
count))
(make-true-list args)
0))

(define (%gen-chainframe args free-inline)
  "generate a chainframe instruction if there are any free variables"
  (let ((n-free-args (%fixnum-add (%count-free-args args)
(%count-free-args free-inline))))
    (when (%fixnum-greater-than n-free-args 0)
      (gen 'chainframe n-free-args))))

(define (%gen-args args free-inline)
  (%gen-args-iter args args free-inline 0))

(define (%gen-args-iter args full-args free-inline n-so-far)
  (write-dbg '%gen-args-iter args n-so-far)
  (cond
   ((null? args)
    (seq (gen 'argcheck n-so-far 0) ; should have exactly n-so-far args
(%gen-chainframe full-args free-inline)))

   ((variable? args)
    (seq (gen 'argcheck n-so-far 1) ; should have at least n-so-far args
(%gen-chainframe full-args free-inline)
(gen 'pushvarargs n-so-far)
(when (variable-is-free-ref args)
(gen 'lset 0 (variable-idx-ref args)))))

   ((and (pair? args)
(variable? (first args)))
    (let ((arg (first args)))
      (if (variable-is-free-ref arg)
(seq (%gen-args-iter (rest args) full-args
free-inline
(%fixnum-add n-so-far 1))
(gen 'spush n-so-far)
(gen 'lset 0 (variable-idx-ref arg))
(gen 'pop))
(%gen-args-iter (rest args) full-args
free-inline
(%fixnum-add n-so-far 1)))))
   (else (throw-error "illegal argument list" args))))

;; this doesn't do error checking like the method before
(define (num-args args)
  (letrec ((iter (lambda (lst count)
(cond
((null? lst) count)
((symbol? lst) (%fixnum-add count 1))
(else (iter (rest lst) (%fixnum-add count 1)))))))
    (iter args 0)))

(define (make-true-list dotted-list)
  (cond
   ((null? dotted-list) nil)
   ((atom? dotted-list) (list dotted-list))
   (else (cons (first dotted-list)
(make-true-list (rest dotted-list))))))

(define (new-fun code env name args)
  (assemble (make-fn 'code (optimize code)
'env env
'name name
'args args)))

(let ((label-num 0))
  (define (compiler x)
    (set! label-num 0)
    (comp-lambda nil (list (variable-usages (alpha-convert x nil nil) nil)) nil))

  (define (gen-label . opt)
    (let ((prefix (if (pair? opt)
(comp-stringify (car opt))
"L")))
      (write-dbg 'gen-label prefix)
      (set! label-num (%fixnum-add label-num 1))
      (string->symbol
       (prim-concat prefix (number->string label-num))))))

(define (comp-stringify obj)
  (cond
   ((string? obj) obj)
   ((symbol? obj) (symbol->string obj))
   (else (throw-error "can't make" obj "a string"))))

(define (update-var-ref ref env)
  (let ((real-var (variable-reference-variable-ref ref)))
    (write-dbg 'update-var-ref 'ref ref 'real real-var 'env env)
    (if (global-variable? real-var)
ref
(let ((new-ref (var-in-env? (variable-name-ref real-var) env)))
(if (not (null? new-ref))
new-ref
(when (variable-is-free-ref real-var)
(throw-error
"ENV: " env
new-ref "not in env and it's marked free")))))))

(define (gen-var var env)
  "given VAR, a variable reference, generate the bytecode to access
that variable given that our environment looks like ENV"
  (write-dbg 'gen-var var)
  (let ((real-var (variable-reference-variable-ref var))
(new-ref (update-var-ref var env)))

    (cond
     ((global-variable? real-var)
      (gen 'gvar (global-variable-name-ref real-var)))

     ;; we did the lookup again to account for skipped frames
     ((variable-is-free-ref real-var)
      (gen 'lvar
(variable-reference-frame-ref new-ref)
(variable-idx-ref real-var) ";" new-ref))
     (else
      (gen 'spush (variable-idx-ref real-var) 0 ";" real-var)))))

(define (gen-set var env)
  "given VAR, a variable reference, generate the bytecode to set that
variable given that our environment looks like ENV"
  (write-dbg 'gen-set var)
  (let ((real-var (variable-reference-variable-ref var))
(new-ref (update-var-ref var env)))

    (cond
     ((global-variable? real-var)
      (gen 'gset (global-variable-name-ref real-var)))

     ((variable-is-free-ref real-var)
      (gen 'lset
(variable-reference-frame-ref new-ref)
(variable-idx-ref real-var) ";" var))

     (else
      (gen 'sset (variable-idx-ref real-var) 0 ";" var)))))

(define (label? obj)
  (symbol? obj))

(define (args instr)
  (if (pair? instr) (rest instr)))

(define (arg1 instr)
  (if (pair? instr) (second instr)))

(define (set-arg1! instr val)
  (set-car! (cdr instr) val))

(define (arg2 instr)
  (if (pair? instr) (third instr)))

(define (is instr op)
  (if (pair? op)
      (member? (opcode instr) op)
      (eq? (opcode instr) op)))

(define (opcode instr)
  (if (label? instr)
      'label
      (first instr)))

(define (instrs-to-bytes instr-vector)
  (let* ((len (vector-length instr-vector))
(result (make-bytecode-array (%fixnum-mul 2 len))))

    (dotimes (idx len)
      (let ((instr (vector-ref instr-vector idx))
(off (%fixnum-mul idx 2)))

(bytecode-set! result off (opcode instr))

(let ((arg1 (if (cdr instr)
(cadr instr)
0))
(arg2 (if (and (cdr instr) (cddr instr))
(caddr instr)
0)))
(bytecode-operands-set! result (%fixnum-add off 1) arg1 arg2))))

    result))

(define (build-const-table instrs)
  (let ((result nil)
(idx 0))

    (dolist (inst instrs)
      (when (is inst '(cconst fn gvar gset))
        (push! (arg1 inst) result)
(set-car! (cdr inst) idx)
(%inc! idx)))

    (apply vector (reverse result))))

(define (assemble fn)
  (let* (;; determine the value of each symbolic label and remove
;; those labels from the instruction stream
(r1 (asm-first-pass (fn-code-ref fn)))

;; while everything is still symbolic we extract the consts
;; and mutate the arg of the old instruction to point into
;; the table
(consts (build-const-table (fn-code-ref fn)))

;; resolve all jumps and convert the instrs into characters
(instrs (asm-second-pass (fn-code-ref fn)
(first r1)
(second r1)))

;; remember the number of instructions in the stream since
;; the alien byte array doesn't store its length
(num-bytes (%fixnum-mul (vector-length instrs) 2))

;; pack the instructions into the final alien byte array
(bytes (instrs-to-bytes instrs)))

    ;; pack the final compiled proc
    (make-compiled-proc (list num-bytes bytes consts)
(fn-env-ref fn))))


(define (asm-first-pass code)
  (let ((length 0)
(labels nil))
    (dolist (instr code)
(if (label? instr)
(push! (cons instr length) labels)
(%inc! length)))
    (list length labels)))

(define (asm-second-pass code length labels)
  (let ((addr 0)
(code-vector (make-vector length nil)))
    (dolist (instr code)
(unless (label? instr)
(if (is instr '(jump tjump fjump save))
(set-arg1! instr
(cdr (assoc (arg1 instr) labels))))

;; if this has a bytecode, convert it
(let ((bytecode (symbol->bytecode (opcode instr))))
(if bytecode
(set-car! instr bytecode)))

(vector-set! code-vector addr instr)
(%inc! addr)))
    code-vector))

(define (fn-opcode? instr)
  (is instr 'fn))

(define (optimize code)
  code)


(define-struct variable
  "maintain information about variable references"
  (name
   is-free
   is-set
   idx))

(define-struct global-variable
  "maintain information about a global variable reference"
  (name))

(define-struct variable-reference
  "a reference to a variable"
  (variable
   frame
   number))

(define (var-in-env? var env)
  (let loop ((frame-number 0)
(var-number 0)
(frame (car env))
(frames (cdr env)))

    (cond
     ((and (null? frame)
(null? frames))
      nil) ;; variable not found in environment
     ((null? frame)
      (loop (%fixnum-add frame-number 1)
0
(car frames)
(cdr frames))) ;; move to next frame
     ((eq? (variable-name-ref (car frame)) var)
      (make-variable-reference
       'variable (car frame)
       'frame frame-number
       'number var-number)) ;; found what we're looking for
     (else
      (loop frame-number
(%fixnum-add var-number 1)
(cdr frame)
frames)))))

(define (set-reference-free! ref)
  (variable-is-free-set! (variable-reference-variable-ref ref) #t))

(define (set-reference-set! ref)
  (variable-is-set-set! (variable-reference-variable-ref ref) #t))

(define (args-to-variables arg-list)
  (cond
   ((null? arg-list) nil)
   ((atom? arg-list) (make-variable 'name arg-list))
   (else (cons (make-variable 'name (car arg-list))
(args-to-variables (cdr arg-list))))))

(define (variable-usages exp env)
  (cond
   ((symbol? exp)
    ;; if the veriable reference is against a frame other than this
    ;; one then mark the variable as free. If it's not found then
    ;; generate a global reference
    (let ((var (var-in-env? exp env)))
      (cond
       ((null? var)
(make-variable-reference 'variable (make-global-variable 'name exp)))
       ((%fixnum-greater-than (variable-reference-frame-ref var) 0)
(set-reference-free! var)
var)
       ;; it's in our frame, no need to change its markings
       (else var))))
   ((atom? exp) exp)
   (else
    (record-case exp
      (if-compiling (then else)
(list 'if-compiling
(variable-usages then env)
(variable-usages else env)))
      (quote (obj) exp)
      (begin exps
        (list* 'begin
(map (lambda (exp)
(variable-usages exp env)) exps)))
      (set! (sym val)
;; if the variable reference is against a frame other than
;; this one, then mark the variable free and set. if it's
;; against this frame, mark the variable set only. If the
;; variable isn't found generate a global set
(let* ((var (var-in-env? sym env))
(ref (cond
((null? var)
(make-variable-reference 'variable
(make-global-variable 'name sym)))
((%fixnum-greater-than (variable-reference-frame-ref var) 0)
(set-reference-free! var)
(set-reference-set! var)
var)
(else
(set-reference-set! var)
var))))
(list 'set! ref (variable-usages val env))))
      (if (test then . else)
(list 'if
            (variable-usages test env)
(variable-usages then env)
(variable-usages (car-else else nil) env)))
      (lambda (args . body)
;; extend the environment with ARGS and then traverse BODY
(let* ((new-args (args-to-variables args))
(new-env (cons (make-true-list new-args) env)))
(list* 'lambda
new-args
(map (lambda (exp)
(variable-usages exp new-env)) body))))

      (inlined-lambda (args body)
;; append ARGS to the current frame of ENV since they will be
;; pulled up in the final stage
(let* ((new-args (args-to-variables (map cdr args)))
(new-env (cons (append new-args (car env)) (cdr env))))
`(inlined-lambda ,new-args ,(variable-usages body new-env))))

      (else
       (map (lambda (exp)
(variable-usages exp env)) exp))))))

(define (make-space spaces)
  (make-string spaces #\space))

(define (%compiled->instructions fn)
  "produce a stream of readable instructions from compiled bytecode"
  (let ((len (/ (car (compiled-bytecode fn)) 2))
(bytes (cadr (compiled-bytecode fn)))
(consts (caddr (compiled-bytecode fn)))
(result nil))
    (dotimes (idx len)
      (let* ((off (* idx 2))
(instr (bytecode-ref bytes off))
(args (bytecode-operands-ref bytes (+ off 1)))
(arg1 (car args))
(arg2 (cdr args))
(instr* (bytecode->symbol instr))
(arg1* (if (member instr* '(fn cconst gvar gset))
(vector-ref consts arg1)
arg1)))
(push! (list instr* arg1* arg2)
result)))
    (reverse result)))

(define (%show-fn fn indent)
  (newline)
  (let ((line-num 0)
(fn (if (meta? fn) (meta-object fn) fn)))
    (dolist (instr (%compiled->instructions fn))
      (if (is instr 'fn)
(begin
(map display (list line-num ": " (make-space indent) "fn "))
(%show-fn (arg1 instr) (%fixnum-add indent 4)))
(begin
(map display (list line-num ": " (make-space indent) instr))
(newline)))
      (inc! line-num))))


(define (comp-show fn)
  (%show-fn (compiler fn) 0))

(define (comp-repl)
  (display "comp-repl> ")
  (let ((result ((compiler (read-port stdin)))))
    (write-port result stdout)
    (newline)
    (unless (eq? result 'quit)
(comp-repl))))

(define (compile-file name)
  "read and compile all forms in file"
  (let ((file (find-library name)))
    (if file
        (letrec ((in (open-input-port file))
                 (iter (lambda (form)
                         (unless (eof-object? form)
                           ((compiler form))
                           (iter (read-port in))))))
          (if (eof-object? in)
              (throw-error "compiler failed to open" file)
              (iter (read-port in)))
          #t)
        (throw-error "failed to find" name))))

(define (make-new-names vars)
  (map (lambda (var) (cons var (gensym))) vars))

(define (make-notepad)
  (cons nil nil))

(define (get-notes notepad)
  (car notepad))

(define (push-note! notepad note)
  (if (null? notepad)
      (throw-error "notepad is null. can't save" note)
      (set-car! notepad (cons note (get-notes notepad)))))

(define (remap-if-defined sym remapped)
  (if-let ((new (assq sym remapped)))
(cdr new)
sym))

(define (find-inlined-vars exp found)
  (cond
   ((atom? exp)
    found)
   (else
    (record-case exp
      (if-compiling (then else)
(find-inlined-vars then (find-inlined-vars else found)))
      (quote (obj) found)
      (begin exps
        (reduce (lambda (found exp)
(find-inlined-vars exp found))
exps
found))
      (set! (sym val)
(find-inlined-vars val found))
      (if (test then . else)
(find-inlined-vars test
(find-inlined-vars then
(if else (find-inlined-vars (car else) found)))))
      (lambda (args . body)
(reduce (lambda (found exp)
(find-inlined-vars exp found))
body
found))
      (inlined-lambda (args body)
;; inlinings always bubble up so no need to search body
(append args found))

      (else
       (reduce (lambda (found exp)
(find-inlined-vars exp found))
exp
found))))))

(define (alpha-convert exp vars inline-notes)
  ;;(write-port (list 'alpha-convert exp vars inline-notes) stdout) (newline)
  (cond
   ((symbol? exp)
    (remap-if-defined exp vars))

   ((atom? exp) exp)

   (else
    (record-case exp
      (if-compiling (then else)
        (list 'if-compiling
(alpha-convert then vars inline-notes)
(alpha-convert else vars inline-notes)))

      (quote (obj) (list 'quote obj))

      (begin exps
(cons 'begin
(map (lambda (exp)
(alpha-convert exp vars inline-notes))
exps)))

      (set! (sym val)
        (list 'set!
(alpha-convert sym vars inline-notes)
(alpha-convert val vars inline-notes)))

      (if (test then . else)
(list 'if
(alpha-convert test vars inline-notes)
(alpha-convert then vars inline-notes)
(if else
(alpha-convert (car else) vars inline-notes))))

      (lambda (largs . body)
(let* ((args-list (make-true-list largs))
(free-args (filter (lambda (var)
(not (member? (car var) args-list)))
vars)))
`(lambda ,largs
. ,(map (lambda (e)
(alpha-convert e free-args nil))
body))))

      (else
       (cond
((expression-expander exp)
(alpha-convert ((expression-expander exp) exp) vars inline-notes))
((comp-macro? (first exp))
(alpha-convert (comp-macroexpand0 exp) vars inline-notes))
;; check for head lambdas
((and (pair? (first exp))
(eq? 'lambda (first (first exp))))
(record (rest (first exp))
(args . body)
(let ((remapped (make-new-names (make-true-list args)))
(parms (rest exp)))

(if inline-notes
;; we're already in an inline block, append to notepad
(begin
(push-note! inline-notes remapped)
(generate-inlined args vars (append remapped vars) parms body inline-notes))
;; we're starting an inline block, make a notepad
(let ((notepad (make-notepad)))
(push-note! notepad remapped)
(let ((inlined (generate-inlined args vars (append remapped vars) parms body notepad)))
`(inlined-lambda ,(append-all (get-notes notepad))
,inlined)))))))
(else
(map (lambda (e)
(alpha-convert e vars inline-notes))
exp))))))))

(define (generate-sets args parms premapped remapped inline-notes)
  ;(printf "generate-sets args: %a parms: %a remapped: %a\n"
  ; args parms remapped)
  (cond
   ((null? args) nil)

   ((symbol? args)
    ;; this is a dotted list
    (list
     `(set! ,(remap-if-defined args remapped)
(list . ,(map (lambda (parm)
(alpha-convert parm premapped inline-notes))
parms)))))
   ((pair? args)
    (cons
     `(set! ,(remap-if-defined (car args) remapped)
,(alpha-convert (car parms) premapped inline-notes))
     (generate-sets (cdr args) (cdr parms) premapped remapped inline-notes)))

   (else (throw-error "unrecognized argument " args))))



(define (generate-inlined args premapped remapped parms body notepad)
  ;;(printf "generate-inlined args: %a body: %a premapped: %a remapped: %a\n" args body premapped remapped)
  `(begin
     ;; generate the sets
     ,@(generate-sets args parms premapped remapped notepad)

     ;; inline the body
     ,@(map (lambda (form)
;;(printf "converting form: %a\n" form)
(alpha-convert form remapped notepad))
body)))

(provide 'compiler)
Something went wrong with that request. Please try again.