src/: More missing exports.
[sod] / src / codegen-proto.lisp
1 ;;; -*-lisp-*-
2 ;;;
3 ;;; Code generation protocol
4 ;;;
5 ;;; (c) 2009 Straylight/Edgeware
6 ;;;
7
8 ;;;----- Licensing notice ---------------------------------------------------
9 ;;;
10 ;;; This file is part of the Sensble Object Design, an object system for C.
11 ;;;
12 ;;; SOD is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2 of the License, or
15 ;;; (at your option) any later version.
16 ;;;
17 ;;; SOD is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;;; GNU General Public License for more details.
21 ;;;
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with SOD; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26 (cl:in-package #:sod)
27
28 ;;;--------------------------------------------------------------------------
29 ;;; Temporary names.
30
31 ;; Protocol.
32
33 (export 'format-temporary-name)
34 (defgeneric format-temporary-name (var stream)
35 (:documentation
36 "Write the name of a temporary variable VAR to STREAM."))
37
38 (export 'var-in-use-p)
39 (defgeneric var-in-use-p (var)
40 (:documentation
41 "Answer whether VAR is currently being used. See `with-temporary-var'.")
42 (:method (var)
43 "Non-temporary variables are always in use."
44 (declare (ignore var))
45 t))
46 (defgeneric (setf var-in-use-p) (value var)
47 (:documentation
48 "Record whether VAR is currently being used. See `with-temporary-var'."))
49
50 ;; Root class.
51
52 (export '(temporary-name temp-tag))
53 (defclass temporary-name ()
54 ((tag :initarg :tag :reader temp-tag))
55 (:documentation
56 "Base class for temporary variable and argument names."))
57
58 ;; Important variables.
59
60 (defparameter *temporary-index* 0
61 "Index for temporary name generation.
62
63 This is automatically reset to zero before the output functions are
64 invoked to write a file. This way, we can ensure that the same output
65 file is always produced from the same input.")
66
67 (define-clear-the-decks reset-codegen-index
68 (setf *temporary-index* 0))
69
70 ;; Important temporary names.
71
72 (export '(*sod-ap* *sod-master-ap*))
73 (defparameter *sod-ap*
74 (make-instance 'temporary-name :tag "sod__ap"))
75 (defparameter *sod-master-ap*
76 (make-instance 'temporary-name :tag "sod__master_ap"))
77 (defparameter *sod-tmp-ap*
78 (make-instance 'temporary-name :tag "sod__tmp_ap"))
79
80 ;;;--------------------------------------------------------------------------
81 ;;; Instructions.
82
83 ;; Classes.
84
85 (export 'inst)
86 (defclass inst () ()
87 (:documentation
88 "A base class for instructions.
89
90 An `instruction' is anything which might be useful to string into a code
91 generator. Both statements and expressions can be represented by trees of
92 instructions. The `definst' macro is a convenient way of defining new
93 instructions.
94
95 The only important protocol for instructions is output, which is achieved
96 by calling `print-object' with `*print-escape*' nil.
97
98 This doesn't really do very much, but it acts as a handy marker for
99 instruction subclasses."))
100
101 (export 'inst-metric)
102 (defgeneric inst-metric (inst)
103 (:documentation
104 "Returns a `metric' describing how complicated INST is.
105
106 The default metric of an inst node is simply 1; `inst' subclasses
107 generated by `definst' (q.v.) have an automatically generated method which
108 returns one plus the sum of the metrics of the node's children.
109
110 This isn't intended to be a particularly rigorous definition. Its purpose
111 is to allow code generators to make decisions about inlining or calling
112 code fairly simply.")
113 (:method ((inst t))
114 (declare (ignore inst))
115 1)
116 (:method ((inst null))
117 (declare (ignore inst))
118 1)
119 (:method ((inst list))
120 (reduce #'+ inst :key #'inst-metric)))
121
122 ;; Instruction definition.
123
124 (export 'definst)
125 (defmacro definst (code (streamvar &key export) args &body body)
126 "Define an instruction type and describe how to output it.
127
128 An `inst' can represent any structured piece of output syntax: a
129 statement, expression or declaration, for example. This macro defines the
130 following things:
131
132 * A class `CODE-inst' to represent the instruction.
133
134 * Instance slots named after the ARGS, with matching keyword initargs,
135 and `inst-ARG' readers.
136
137 * A constructor `make-CODE-inst' which accepts the ARGS (in order, not
138 with keywords) as arguments and returns a fresh instance.
139
140 * A print method, which prints a diagnostic dump if `*print-escape*' is
141 set, or invokes the BODY (with STREAMVAR bound to the output stream)
142 otherwise. The BODY is expected to produce target code at this
143 point.
144
145 If EXPORT is non-nil, then export the `CODE-inst' and `make-CODE-inst'
146 symbols."
147
148 (let ((inst-var (gensym "INST"))
149 (class-name (symbolicate code '-inst))
150 (constructor-name (symbolicate 'make- code '-inst))
151 (keys (mapcar (lambda (arg) (intern (symbol-name arg) :keyword))
152 args)))
153 `(progn
154 (defclass ,class-name (inst)
155 ,(mapcar (lambda (arg key)
156 `(,arg :initarg ,key :reader ,(symbolicate 'inst- arg)))
157 args keys))
158 (defun ,constructor-name (,@args)
159 (make-instance ',class-name ,@(mappend #'list keys args)))
160 (defmethod inst-metric ((,inst-var ,class-name))
161 (with-slots (,@args) ,inst-var
162 (+ 1 ,@(mapcar (lambda (arg) `(inst-metric ,arg)) args))))
163 (defmethod print-object ((,inst-var ,class-name) ,streamvar)
164 (with-slots (,@args) ,inst-var
165 (if *print-escape*
166 (print-unreadable-object (,inst-var ,streamvar :type t)
167 (format stream "~@<~@{~S ~@_~S~^ ~_~}~:>"
168 ,@(mappend #'list keys args)))
169 (progn ,@body))))
170 ,@(and export `((export '(,class-name ,constructor-name))))
171 ',code)))
172
173 ;; Important instruction classes.
174
175 (definst var (stream :export t) (name type init)
176 (pprint-c-type type stream name)
177 (when init
178 (format stream " = ~A" init))
179 (write-char #\; stream))
180 (definst set (stream :export t) (var expr)
181 (format stream "~@<~A = ~@_~2I~A;~:>" var expr))
182 (definst update (stream :export t) (var op expr)
183 (format stream "~@<~A ~A= ~@_~2I~A;~:>" var op expr))
184 (definst return (stream :export t) (expr)
185 (format stream "return~@[ (~A)~];" expr))
186 (definst break (stream :export t) ()
187 (format stream "break;"))
188 (definst continue (stream :export t) ()
189 (format stream "continue;"))
190 (definst expr (stream :export t) (expr)
191 (format stream "~A;" expr))
192 (definst block (stream :export t) (decls body)
193 (format stream "{~:@_~@< ~2I~@[~{~A~:@_~}~:@_~]~{~A~^~:@_~}~:>~:@_}"
194 decls body))
195 (definst function (stream :export t) (name type body)
196 (pprint-logical-block (stream nil)
197 (princ "static " stream)
198 (pprint-c-type type stream name)
199 (format stream "~:@_~A~:@_~:@_" body)))
200
201 ;; Formatting utilities.
202
203 (defun format-compound-statement* (stream child morep thunk)
204 "Underlying function for `format-compound-statement'."
205 (cond ((typep child 'block-inst)
206 (funcall thunk stream)
207 (write-char #\space stream)
208 (princ child stream)
209 (when morep (write-char #\space stream)))
210 (t
211 (pprint-logical-block (stream nil)
212 (funcall thunk stream)
213 (write-char #\space stream)
214 (pprint-indent :block 2 stream)
215 (pprint-newline :linear stream)
216 (princ child stream)
217 (pprint-indent :block 0 stream)
218 (case morep
219 (:space
220 (write-char #\space stream)
221 (pprint-newline :linear stream))
222 ((t)
223 (pprint-newline :mandatory stream)))))))
224
225 (export 'format-compound-statement)
226 (defmacro format-compound-statement
227 ((stream child &optional morep) &body body)
228 "Format a compound statement to STREAM.
229
230 The introductory material is printed by BODY. The CHILD is formatted
231 properly according to whether it's a `block-inst'. If MOREP is true, then
232 allow for more stuff following the child."
233 `(format-compound-statement* ,stream ,child ,morep
234 (lambda (,stream) ,@body)))
235
236 ;;;--------------------------------------------------------------------------
237 ;;; Code generation.
238
239 ;; Accessors.
240
241 (export 'codegen-functions)
242 (defgeneric codegen-functions (codegen)
243 (:documentation
244 "Return the list of `function-inst's of completed functions."))
245
246 (export 'ensure-var)
247 (defgeneric ensure-var (codegen name type &optional init)
248 (:documentation
249 "Add a variable to CODEGEN's list.
250
251 The variable is called NAME (which should be comparable using `equal' and
252 print to an identifier) and has the given TYPE. If INIT is present and
253 non-nil it is an expression `inst' used to provide the variable with an
254 initial value."))
255
256 (export '(emit-inst emit-insts))
257 (defgeneric emit-inst (codegen inst)
258 (:documentation
259 "Add INST to the end of CODEGEN's list of instructions."))
260 (defgeneric emit-insts (codegen insts)
261 (:documentation
262 "Add a list of INSTS to the end of CODEGEN's list of instructions.")
263 (:method (codegen insts)
264 (dolist (inst insts) (emit-inst codegen inst))))
265
266 (export '(emit-decl emit-decls))
267 (defgeneric emit-decl (codegen inst)
268 (:documentation
269 "Add INST to the end of CODEGEN's list of declarations."))
270 (defgeneric emit-decls (codegen insts)
271 (:documentation
272 "Add a list of INSTS to the end of CODEGEN's list of declarations."))
273
274 (export 'codegen-push)
275 (defgeneric codegen-push (codegen)
276 (:documentation
277 "Pushes the current code generation state onto a stack.
278
279 The state consists of the accumulated variables and instructions."))
280
281 (export 'codegen-pop)
282 (defgeneric codegen-pop (codegen)
283 (:documentation
284 "Pops a saved state off of the CODEGEN's stack.
285
286 Returns the newly accumulated variables and instructions as lists, as
287 separate values."))
288
289 (export 'codegen-add-function)
290 (defgeneric codegen-add-function (codegen function)
291 (:documentation
292 "Adds a function to CODEGEN's list.
293
294 Actually, we're not picky: FUNCTION can be any kind of object that you're
295 willing to find in the list returned by `codegen-functions'."))
296
297 (export 'temporary-var)
298 (defgeneric temporary-var (codegen type)
299 (:documentation
300 "Return the name of a temporary variable.
301
302 The temporary variable will have the given TYPE, and will be marked
303 in-use. You should clear the in-use flag explicitly when you've finished
304 with the variable -- or, better, use `with-temporary-var' to do the
305 cleanup automatically."))
306
307 (export 'codegen-build-function)
308 (defun codegen-build-function (codegen name type vars insts)
309 "Build a function and add it to CODEGEN's list.
310
311 Returns the function's name."
312 (codegen-add-function codegen
313 (make-function-inst name type
314 (make-block-inst vars insts)))
315 name)
316
317 (export 'codegen-pop-block)
318 (defgeneric codegen-pop-block (codegen)
319 (:documentation
320 "Makes a block (`block-inst') out of the completed code in CODEGEN.")
321 (:method (codegen)
322 (multiple-value-bind (vars insts) (codegen-pop codegen)
323 (make-block-inst vars insts))))
324
325 (export 'codegen-pop-function)
326 (defgeneric codegen-pop-function (codegen name type)
327 (:documentation
328 "Makes a function out of the completed code in CODEGEN.
329
330 The NAME can be any object you like. The TYPE should be a function type
331 object which includes argument names. The return value is the NAME.")
332 (:method (codegen name type)
333 (multiple-value-bind (vars insts) (codegen-pop codegen)
334 (codegen-build-function codegen name type vars insts))))
335
336 (export 'with-temporary-var)
337 (defmacro with-temporary-var ((codegen var type) &body body)
338 "Evaluate BODY with VAR bound to a temporary variable name.
339
340 During BODY, VAR will be marked in-use; when BODY ends, VAR will be marked
341 available for re-use."
342 `(let ((,var (temporary-var ,codegen ,type)))
343 (unwind-protect
344 (progn ,@body)
345 (setf (var-in-use-p ,var) nil))))
346
347 ;;;--------------------------------------------------------------------------
348 ;;; Code generation idioms.
349
350 (export 'deliver-expr)
351 (defun deliver-expr (codegen target expr)
352 "Emit code to deliver the value of EXPR to the TARGET.
353
354 The TARGET may be one of the following.
355
356 * `:void', indicating that the value is to be discarded. The expression
357 will still be evaluated.
358
359 * `:void-return', indicating that the value is to be discarded (as for
360 `:void') and furthermore a `return' from the current function should
361 be forced after computing the value.
362
363 * `:return', indicating that the value is to be returned from the
364 current function.
365
366 * A variable name, indicating that the value is to be stored in the
367 variable.
368
369 In the cases of `:return', `:void' and `:void-return' targets, it is valid
370 for EXPR to be nil; this signifies that no computation needs to be
371 performed. Variable-name targets require an expression."
372
373 (case target
374 (:return (emit-inst codegen (make-return-inst expr)))
375 (:void (when expr (emit-inst codegen (make-expr-inst expr))))
376 (:void-return (when expr (emit-inst codegen (make-expr-inst expr)))
377 (emit-inst codegen (make-return-inst nil)))
378 (t (emit-inst codegen (make-set-inst target expr)))))
379
380 (export 'convert-stmts)
381 (defun convert-stmts (codegen target type func)
382 "Invoke FUNC to deliver a value to a non-`:return' target.
383
384 FUNC is a function which accepts a single argument, a non-`:return'
385 target, and generates statements which deliver a value (see
386 `deliver-expr') of the specified TYPE to this target. In general, the
387 generated code will have the form
388
389 setup instructions...
390 (deliver-expr CODEGEN TARGET (compute value...))
391 cleanup instructions...
392
393 where the cleanup instructions are essential to the proper working of the
394 generated program.
395
396 The `convert-stmts' function will call FUNC to generate code, and arrange
397 that its value is correctly delivered to TARGET, regardless of what the
398 TARGET is -- i.e., it lifts the restriction to non-`:return' targets. It
399 does this by inventing a new temporary variable."
400
401 (case target
402 (:return (with-temporary-var (codegen var type)
403 (funcall func var)
404 (deliver-expr codegen target var)))
405 (:void-return (funcall func :void)
406 (emit-inst codegen (make-return-inst nil)))
407 (t (funcall func target))))
408
409 ;;;----- That's all, folks --------------------------------------------------