raz / sbcl / src / comp.lisp

221 lines · 9.2 KiB · raw · history · last change cfa2bc20

1;;;; comp.lisp -- what the parts of the compiler share: modules, the
2;;;; names they declare, the items an expression compiles to, procedures'
3;;;; frames, the data block and reading tokens.
4;;;;
5;;;; The compiler reads each module once, from front to back, checking it
6;;;; and turning it into Lisp as it goes, as Wirth's compilers do: an
7;;;; expression becomes an ITEM, which says what it is (a constant, a
8;;;; variable, a value, a procedure...) and holds the Lisp form that
9;;;; computes it. Each procedure becomes a DEFUN, kept in *FORMS*; the
10;;;; driver compiles them all with SBCL and saves the result as the
11;;;; executable.
12
13(in-package :raz)
14
15;;; Modules.
16;;;
17;;; A generic module (section 3) is read only up to its parameters when
18;;; it is imported; each distinct list of arguments then makes an
19;;; INSTANCE, a module of its own, compiled from the same tokens with the
20;;; parameters standing for the arguments.
21
22(defstruct module
23 name ; as written, "Out"
24 file toks ; its file and tokens
25 (exports (make-hash-table :test 'equal)) ; name -> obj, the exported names
26 scope ; its scope, for its own code
27 imports ; IMPORTs, in order, which decide the order of bodies
28 generic ; for a generic module: its parameters, (names . proc-params)
29 (instances '()) ; for a generic module: (args . module) for each instance
30 args ; for an instance: its arguments
31 lisp-name ; the prefix of its procedures' Lisp names, "Out" or "List(2)"
32 check-off ; it says `check off;`
33 static ; it says `link static;`
34 uses-c ; it has an extern or links a library
35 links ; the libraries it links
36 body ; the Lisp symbol of its body's function, if it has a body
37 (state :new)) ; :compiling while its declarations are read, then :done
38
39;;; An import: ALIAS is the name the importer uses; TARGET the module,
40;;; or the generic module; ARGS the position of its arguments' tokens,
41;;; read when the instance is made; INSTANCE then the instance.
42(defstruct import alias target args instance tok)
43
44;;; A declared name. KIND is :const :type :var :proc :module :builtin or
45;;; :case. For a :var, WHERE says where it lives:
46;;; (:global address) a module variable, in the data block
47;;; (:local offset) a procedure's, in its frame
48;;; (:var-param offset) a var parameter: its frame holds the address
49;;; (:at form) a match arm's name: FORM is the address
50;;; (:extern name) a C variable
51;;; For a :const, VAL is its value (for an array or record constant, its
52;;; address in the data block). For a :proc, SYM is its Lisp function,
53;;; SIG its signature, and EXTERN, CODE and FORWARD say what kind it is.
54
55(defstruct obj
56 name kind type val where exported module
57 sym sig extern code forward defined (handle nil) tok import)
58
59;;; The state of the compilation. Each is rebound while a module is read,
60;;; since an instance of a generic module may be read in the middle of
61;;; another module's procedure.
62
63(defvar *module* nil "The module being read.")
64(defvar *scope* nil "The innermost scope.")
65(defvar *toks* #() "The tokens of the module being read.")
66(defvar *pos* 0 "The index of the next token.")
67(defvar *proc* nil "The PROC being compiled, or nil outside procedures.")
68(defvar *forms* '() "The program's top-level Lisp forms, the last first.")
69(defvar *modules* (make-hash-table :test 'equal) "Every module read, by name.")
70
71;;; Scopes: a table of names and the scope around it.
72
73(defstruct scope (table (make-hash-table :test 'equal)) parent)
74
75(defvar *universe* nil "The scope around every module: the predeclared names.")
76
77(defun lookup (name &optional (scope *scope*))
78 (loop for s = scope then (scope-parent s) while s
79 do (let ((o (gethash name (scope-table s)))) (when o (return o)))))
80
81(defun declare-name (obj &optional (scope *scope*))
82 (when (gethash (obj-name obj) (scope-table scope))
83 (fail-tok (obj-tok obj) "~a is declared twice" (obj-name obj)))
84 (setf (gethash (obj-name obj) (scope-table scope)) obj)
85 obj)
86
87;;; A procedure (or a module body) being compiled. Its frame grows by
88;;; ALLOC as variables and temporaries are given places in it. DEFERS
89;;; holds, for each statement list it is in, the innermost first, the
90;;; forms of the statements deferred there, the last first (section 7.7).
91;;; LOOPS holds, for each loop it is in, its block name and the DEFERS
92;;; outside it.
93
94(defstruct proc
95 obj sig (size 0) block (defers '()) (loops '()) dests in-defer results)
96
97(defun alloc (size align)
98 "A place of SIZE bytes in the current frame: the form of its address."
99 (let ((off (round-up (proc-size *proc*) (max align 1))))
100 (setf (proc-size *proc*) (+ off size))
101 `(+ fp ,off)))
102
103(defun temp (ty) (alloc (ty-size ty) (ty-align ty)))
104
105;;; Items. MODE is
106;;; :const a constant; VAL is its value
107;;; :var a variable; FORM is its address
108;;; :val a value; FORM computes it (the address of a copy, for an aggregate)
109;;; :literal an array, record or set literal, waiting for the type it
110;;; must have (6.5): VAL is (kind elements)
111;;; :proc a procedure, OBJ; :builtin, VAL its name; :type, TYPE;
112;;; :case a variant's case, VAL; :module, OBJ the import
113;;; :multi a call with several results, TYPE their list
114;;; :none a call with no result
115;;; RO says why a variable can't be changed: :export (another module's,
116;;; section 3), :const (a constant's part or a string's byte) or :value
117;;; (a part of a value). VOL marks a volatile variable (7.6); NOADDR a
118;;; field of a packed record that has no address (5.5).
119
120(defstruct item mode type form val ro vol noaddr obj tok)
121
122;;; Reading tokens.
123
124(defun tok (&optional (k 0)) (aref *toks* (min (+ *pos* k) (1- (length *toks*)))))
125(defun kind (&optional (k 0)) (tok-kind (tok k)))
126(defun next-tok () (prog1 (tok) (incf *pos*)))
127
128(defun fail-tok (tok fmt &rest args)
129 (apply #'fail-at (tok-line tok) (tok-col tok) fmt args))
130
131(defun fail-here (fmt &rest args) (apply #'fail-tok (tok) fmt args))
132
133(defun accept (kind) (when (eq (kind) kind) (next-tok)))
134
135(defun describe-tok (tok)
136 (case (tok-kind tok)
137 (:ident (format nil "~a" (tok-val tok)))
138 (:eof "the end of the file")
139 ((:int :real :char) "a number")
140 (:string "a string")
141 (:blank "_")
142 (t (format nil "~(~a~)" (tok-kind tok)))))
143
144(defun expect (kind &optional what)
145 (or (accept kind)
146 (fail-here "~a expected, not ~a" (or what (format nil "~(~a~)" kind)) (describe-tok (tok)))))
147
148(defun ident ()
149 (let ((tk (tok)))
150 (unless (eq (tok-kind tk) :ident)
151 (fail-here "a name expected, not ~a" (describe-tok tk)))
152 (next-tok)
153 (tok-val tk)))
154
155(defun where (tok)
156 "TOK's place, as a stopping program says it."
157 (format nil "~a:~d:~d" *file* (tok-line tok) (tok-col tok)))
158
159;;; The data block (rt.lisp): the module variables, strings, constants
160;;; and errors' messages, each at an address the compiler gives.
161
162(defvar *data* (make-array 0 :element-type '(unsigned-byte 8) :adjustable t :fill-pointer 0))
163(defvar *strings* (make-hash-table :test 'equalp) "Bytes -> the address of a copy, with a 0 after it.")
164(defvar *string-slices* (make-hash-table :test 'equalp) "Bytes -> the address of a slice of them.")
165
166(defun data-alloc (size align)
167 (loop until (zerop (mod (fill-pointer *data*) (max align 1))) do (vector-push-extend 0 *data*))
168 (prog1 (+ +data-base+ (fill-pointer *data*))
169 (loop repeat size do (vector-push-extend 0 *data*))))
170
171(defun data-put (addr bytes)
172 (loop for b across bytes for i from (- addr +data-base+) do (setf (aref *data* i) b)))
173
174(defun data-put-int (addr value size)
175 (loop for i below size do (setf (aref *data* (+ (- addr +data-base+) i)) (ldb (byte 8 (* 8 i)) value))))
176
177(defun string-address (bytes)
178 "The address of BYTES in the data block, followed by a zero byte, as C wants."
179 (or (gethash bytes *strings*)
180 (let ((a (data-alloc (1+ (length bytes)) 1)))
181 (data-put a bytes)
182 (setf (gethash bytes *strings*) a))))
183
184(defun string-slice (bytes)
185 "The address of a slice of BYTES."
186 (or (gethash bytes *string-slices*)
187 (let ((s (data-alloc 16 8)))
188 (data-put-int s (string-address bytes) 8)
189 (data-put-int (+ s 8) (length bytes) 8)
190 (setf (gethash bytes *string-slices*) s))))
191
192(defun error-value (message)
193 "A new ERROR (5.8): the address of a slice of its message, unique to
194the declaration that makes it, so that MSG reads it there."
195 (let ((s (data-alloc 16 8)))
196 (data-put-int s (string-address message) 8)
197 (data-put-int (+ s 8) (length message) 8)
198 s))
199
200;;; Procedure values: each procedure used as a value gets its index in
201;;; the run time's *PROCS*.
202
203(defvar *proc-values* '() "(index . symbol) for each procedure value, the last first.")
204
205(defun proc-handle (obj)
206 (or (obj-handle obj)
207 (setf (obj-handle obj)
208 (let ((h (1+ (length *proc-values*))))
209 (push (cons h (obj-sym obj)) *proc-values*)
210 h))))
211
212;;; Emitting.
213
214(defun emit (form) (push form *forms*))
215
216(defun lisp-name (name)
217 "The Lisp symbol of the current module's NAME."
218 (intern (format nil "~a.~a" (module-lisp-name *module*) name) :razp))
219
220(defvar *gensym-count* 0)
221(defun var-sym (prefix) (make-symbol (format nil "~a~d" prefix (incf *gensym-count*))))