compilation enviroments are always modules; simplifications & refactorings
[bpt/guile.git] / module / language / objcode / spec.scm
1 ;;; Guile Lowlevel Intermediate Language
2
3 ;; Copyright (C) 2001, 2009 Free Software Foundation, Inc.
4
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 3 of the License, or (at your option) any later version.
9 ;;;;
10 ;;;; This library is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;;; Lesser General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU Lesser General Public
16 ;;;; License along with this library; if not, write to the Free Software
17 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
19 ;;; Code:
20
21 (define-module (language objcode spec)
22 #:use-module (system base language)
23 #:use-module (system vm objcode)
24 #:use-module (system vm program)
25 #:export (objcode))
26
27 (define (objcode->value x e opts)
28 (let ((thunk (make-program x #f #f)))
29 (if (eq? e (current-module))
30 ;; save a cons in this case
31 (values (thunk) e e)
32 (save-module-excursion
33 (lambda ()
34 (set-current-module e)
35 (values (thunk) e e))))))
36
37 ;; since locals are allocated on the stack and can have limited scope,
38 ;; in many cases we use one local for more than one lexical variable. so
39 ;; the returned locals set is a list, where element N of the list is
40 ;; itself a list of bindings for local variable N.
41 (define (collapse-locals locs)
42 (let lp ((ret '()) (locs locs))
43 (if (null? locs)
44 (map cdr (sort! ret
45 (lambda (x y) (< (car x) (car y)))))
46 (let ((b (car locs)))
47 (cond
48 ((assv-ref ret (binding:index b))
49 => (lambda (bindings)
50 (append! bindings (list b))
51 (lp ret (cdr locs))))
52 (else
53 (lp (acons (binding:index b) (list b) ret)
54 (cdr locs))))))))
55
56 (define (decompile-value x env opts)
57 (cond
58 ((program? x)
59 (let ((objs (program-objects x))
60 (meta (program-meta x))
61 (free-vars (program-free-variables x))
62 (binds (program-bindings x))
63 (srcs (program-sources x)))
64 (let ((blocs (and binds (collapse-locals binds))))
65 (values (program-objcode x)
66 `((objects . ,objs)
67 (meta . ,(and meta (meta)))
68 (free-vars . ,free-vars)
69 (blocs . ,blocs)
70 (sources . ,srcs))))))
71 ((objcode? x)
72 (values x #f))
73 (else
74 (error "can't decompile ~A: not a program or objcode" x))))
75
76 (define-language objcode
77 #:title "Guile Object Code"
78 #:version "0.3"
79 #:reader #f
80 #:printer write-objcode
81 #:compilers `((value . ,objcode->value))
82 #:decompilers `((value . ,decompile-value))
83 )