Vars and labels are separate namespaces
[bpt/guile.git] / module / language / cps.scm
1 ;;; Continuation-passing style (CPS) intermediate language (IL)
2
3 ;; Copyright (C) 2013, 2014 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 ;;; Commentary:
20 ;;;
21 ;;; This is the continuation-passing style (CPS) intermediate language
22 ;;; (IL) for Guile.
23 ;;;
24 ;;; There are two kinds of terms in CPS: terms that bind continuations,
25 ;;; and terms that call continuations.
26 ;;;
27 ;;; $letk binds a set of mutually recursive continuations, each one an
28 ;;; instance of $cont. A $cont declares the name of a continuation, and
29 ;;; then contains as a subterm the particular continuation instance:
30 ;;; $kif for test continuations, $kargs for continuations that bind
31 ;;; values, etc.
32 ;;;
33 ;;; $continue nodes call continuations. The expression contained in the
34 ;;; $continue node determines the value or values that are passed to the
35 ;;; target continuation: $const to pass a constant value, $values to
36 ;;; pass multiple named values, etc. $continue nodes also record the source at which
37 ;;;
38 ;;; Additionally there is $letrec, a term that binds mutually recursive
39 ;;; functions. The contification pass will turn $letrec into $letk if
40 ;;; it can do so. Otherwise, the closure conversion pass will desugar
41 ;;; $letrec into an equivalent sequence of make-closure primcalls and
42 ;;; subsequent initializations of the captured variables of the
43 ;;; closures. You can think of $letrec as pertaining to "high CPS",
44 ;;; whereas later passes will only see "low CPS", which does not have
45 ;;; $letrec.
46 ;;;
47 ;;; This particular formulation of CPS was inspired by Andrew Kennedy's
48 ;;; 2007 paper, "Compiling with Continuations, Continued". All Guile
49 ;;; hackers should read that excellent paper! As in Kennedy's paper,
50 ;;; continuations are second-class, and may be thought of as basic block
51 ;;; labels. All values are bound to variables using continuation calls:
52 ;;; even constants!
53 ;;;
54 ;;; There are some Guile-specific quirks as well:
55 ;;;
56 ;;; - $kreceive represents a continuation that receives multiple values,
57 ;;; but which truncates them to some number of required values,
58 ;;; possibly with a rest list.
59 ;;;
60 ;;; - $kentry labels an entry point for a $fun (a function), and
61 ;;; contains a $ktail representing the formal argument which is the
62 ;;; function's continuation.
63 ;;;
64 ;;; - $kentry also contains $kclause continuations, corresponding to
65 ;;; the case-lambda clauses of the function. $kclause actually
66 ;;; contains the clause body. This is because the $kclause
67 ;;; logically matches or doesn't match a given set of actual
68 ;;; arguments against a formal arity, then proceeds to a "body"
69 ;;; continuation (which is a $kargs).
70 ;;;
71 ;;; That's to say that a $fun can be matched like this:
72 ;;;
73 ;;; (match f
74 ;;; (($ $fun src meta free
75 ;;; ($ $cont kentry
76 ;;; ($ $kentry self ($ $cont ktail _ ($ $ktail))
77 ;;; (($ $kclause arity
78 ;;; ($ $cont kbody _ ($ $kargs names syms body)))
79 ;;; ...))))
80 ;;; #t))
81 ;;;
82 ;;; A $continue to ktail is in tail position. $kentry, $kclause,
83 ;;; and $ktail will never be seen elsewhere in a CPS term.
84 ;;;
85 ;;; - $prompt continues to the body of the prompt, having pushed on a
86 ;;; prompt whose handler will continue at its "handler"
87 ;;; continuation. The continuation of the prompt is responsible for
88 ;;; popping the prompt.
89 ;;;
90 ;;; In summary:
91 ;;;
92 ;;; - $letk, $letrec, and $continue are terms.
93 ;;;
94 ;;; - $cont is a continuation, containing a continuation body ($kargs,
95 ;;; $kif, etc).
96 ;;;
97 ;;; - $continue terms contain an expression ($call, $const, $fun,
98 ;;; etc).
99 ;;;
100 ;;; See (language tree-il compile-cps) for details on how Tree-IL
101 ;;; converts to CPS.
102 ;;;
103 ;;; Code:
104
105 (define-module (language cps)
106 #:use-module (ice-9 match)
107 #:use-module ((srfi srfi-1) #:select (fold))
108 #:use-module (srfi srfi-9)
109 #:use-module (srfi srfi-9 gnu)
110 #:use-module (srfi srfi-11)
111 #:export (;; Helper.
112 $arity
113 make-$arity
114
115 ;; Terms.
116 $letk $continue $letrec
117
118 ;; Continuations.
119 $cont
120
121 ;; Continuation bodies.
122 $kif $kreceive $kargs $kentry $ktail $kclause
123
124 ;; Expressions.
125 $void $const $prim $fun $call $callk $primcall $values $prompt
126
127 ;; Fresh names.
128 label-counter var-counter
129 fresh-label fresh-var
130 with-fresh-name-state compute-max-label-and-var
131 let-fresh
132
133 ;; Building macros.
134 build-cps-term build-cps-cont build-cps-exp
135 rewrite-cps-term rewrite-cps-cont rewrite-cps-exp
136
137 ;; Misc.
138 parse-cps unparse-cps
139 fold-conts fold-local-conts))
140
141 ;; FIXME: Use SRFI-99, when Guile adds it.
142 (define-syntax define-record-type*
143 (lambda (x)
144 (define (id-append ctx . syms)
145 (datum->syntax ctx (apply symbol-append (map syntax->datum syms))))
146 (syntax-case x ()
147 ((_ name field ...)
148 (and (identifier? #'name) (and-map identifier? #'(field ...)))
149 (with-syntax ((cons (id-append #'name #'make- #'name))
150 (pred (id-append #'name #'name #'?))
151 ((getter ...) (map (lambda (f)
152 (id-append f #'name #'- f))
153 #'(field ...))))
154 #'(define-record-type name
155 (cons field ...)
156 pred
157 (field getter)
158 ...))))))
159
160 (define-syntax-rule (define-cps-type name field ...)
161 (begin
162 (define-record-type* name field ...)
163 (set-record-type-printer! name print-cps)))
164
165 (define (print-cps exp port)
166 (format port "#<cps ~S>" (unparse-cps exp)))
167
168 ;; Helper.
169 (define-record-type* $arity req opt rest kw allow-other-keys?)
170
171 ;; Terms.
172 (define-cps-type $letk conts body)
173 (define-cps-type $continue k src exp)
174 (define-cps-type $letrec names syms funs body)
175
176 ;; Continuations
177 (define-cps-type $cont k cont)
178 (define-cps-type $kif kt kf)
179 (define-cps-type $kreceive arity k)
180 (define-cps-type $kargs names syms body)
181 (define-cps-type $kentry self tail clauses)
182 (define-cps-type $ktail)
183 (define-cps-type $kclause arity cont)
184
185 ;; Expressions.
186 (define-cps-type $void)
187 (define-cps-type $const val)
188 (define-cps-type $prim name)
189 (define-cps-type $fun src meta free body)
190 (define-cps-type $call proc args)
191 (define-cps-type $callk k proc args)
192 (define-cps-type $primcall name args)
193 (define-cps-type $values args)
194 (define-cps-type $prompt escape? tag handler)
195
196 (define label-counter (make-parameter #f))
197 (define var-counter (make-parameter #f))
198
199 (define (fresh-label)
200 (let ((count (or (label-counter)
201 (error "fresh-label outside with-fresh-name-state"))))
202 (label-counter (1+ count))
203 count))
204
205 (define (fresh-var)
206 (let ((count (or (var-counter)
207 (error "fresh-var outside with-fresh-name-state"))))
208 (var-counter (1+ count))
209 count))
210
211 (define-syntax-rule (let-fresh (label ...) (var ...) body ...)
212 (let ((label (fresh-label)) ...
213 (var (fresh-var)) ...)
214 body ...))
215
216 (define-syntax-rule (with-fresh-name-state fun body ...)
217 (begin
218 (when (or (label-counter) (var-counter))
219 (error "with-fresh-name-state should not be called recursively"))
220 (call-with-values (lambda ()
221 (compute-max-label-and-var fun))
222 (lambda (max-label max-var)
223 (parameterize ((label-counter (1+ max-label))
224 (var-counter (1+ max-var)))
225 body ...)))))
226
227 (define-syntax build-arity
228 (syntax-rules (unquote)
229 ((_ (unquote exp)) exp)
230 ((_ (req opt rest kw allow-other-keys?))
231 (make-$arity req opt rest kw allow-other-keys?))))
232
233 (define-syntax build-cont-body
234 (syntax-rules (unquote $kif $kreceive $kargs $kentry $ktail $kclause)
235 ((_ (unquote exp))
236 exp)
237 ((_ ($kif kt kf))
238 (make-$kif kt kf))
239 ((_ ($kreceive req rest kargs))
240 (make-$kreceive (make-$arity req '() rest '() #f) kargs))
241 ((_ ($kargs (name ...) (sym ...) body))
242 (make-$kargs (list name ...) (list sym ...) (build-cps-term body)))
243 ((_ ($kargs names syms body))
244 (make-$kargs names syms (build-cps-term body)))
245 ((_ ($kentry self tail (unquote clauses)))
246 (make-$kentry self (build-cps-cont tail) clauses))
247 ((_ ($kentry self tail (clause ...)))
248 (make-$kentry self (build-cps-cont tail) (list (build-cps-cont clause) ...)))
249 ((_ ($ktail))
250 (make-$ktail))
251 ((_ ($kclause arity cont))
252 (make-$kclause (build-arity arity) (build-cps-cont cont)))))
253
254 (define-syntax build-cps-cont
255 (syntax-rules (unquote)
256 ((_ (unquote exp)) exp)
257 ((_ (k cont)) (make-$cont k (build-cont-body cont)))))
258
259 (define-syntax build-cps-exp
260 (syntax-rules (unquote
261 $void $const $prim $fun $call $callk $primcall $values $prompt)
262 ((_ (unquote exp)) exp)
263 ((_ ($void)) (make-$void))
264 ((_ ($const val)) (make-$const val))
265 ((_ ($prim name)) (make-$prim name))
266 ((_ ($fun src meta free body))
267 (make-$fun src meta free (build-cps-cont body)))
268 ((_ ($call proc (arg ...))) (make-$call proc (list arg ...)))
269 ((_ ($call proc args)) (make-$call proc args))
270 ((_ ($callk k proc (arg ...))) (make-$callk k proc (list arg ...)))
271 ((_ ($callk k proc args)) (make-$callk k proc args))
272 ((_ ($primcall name (arg ...))) (make-$primcall name (list arg ...)))
273 ((_ ($primcall name args)) (make-$primcall name args))
274 ((_ ($values (arg ...))) (make-$values (list arg ...)))
275 ((_ ($values args)) (make-$values args))
276 ((_ ($prompt escape? tag handler))
277 (make-$prompt escape? tag handler))))
278
279 (define-syntax build-cps-term
280 (syntax-rules (unquote $letk $letk* $letconst $letrec $continue)
281 ((_ (unquote exp))
282 exp)
283 ((_ ($letk (unquote conts) body))
284 (make-$letk conts (build-cps-term body)))
285 ((_ ($letk (cont ...) body))
286 (make-$letk (list (build-cps-cont cont) ...)
287 (build-cps-term body)))
288 ((_ ($letk* () body))
289 (build-cps-term body))
290 ((_ ($letk* (cont conts ...) body))
291 (build-cps-term ($letk (cont) ($letk* (conts ...) body))))
292 ((_ ($letconst () body))
293 (build-cps-term body))
294 ((_ ($letconst ((name sym val) tail ...) body))
295 (let-fresh (kconst) ()
296 (build-cps-term
297 ($letk ((kconst ($kargs (name) (sym) ($letconst (tail ...) body))))
298 ($continue kconst (let ((props (source-properties val)))
299 (and (pair? props) props))
300 ($const val))))))
301 ((_ ($letrec names gensyms funs body))
302 (make-$letrec names gensyms funs (build-cps-term body)))
303 ((_ ($continue k src exp))
304 (make-$continue k src (build-cps-exp exp)))))
305
306 (define-syntax-rule (rewrite-cps-term x (pat body) ...)
307 (match x
308 (pat (build-cps-term body)) ...))
309 (define-syntax-rule (rewrite-cps-cont x (pat body) ...)
310 (match x
311 (pat (build-cps-cont body)) ...))
312 (define-syntax-rule (rewrite-cps-exp x (pat body) ...)
313 (match x
314 (pat (build-cps-exp body)) ...))
315
316 (define (parse-cps exp)
317 (define (src exp)
318 (let ((props (source-properties exp)))
319 (and (pair? props) props)))
320 (match exp
321 ;; Continuations.
322 (('letconst k (name sym c) body)
323 (build-cps-term
324 ($letk ((k ($kargs (name) (sym)
325 ,(parse-cps body))))
326 ($continue k (src exp) ($const c)))))
327 (('let k (name sym val) body)
328 (build-cps-term
329 ($letk ((k ($kargs (name) (sym)
330 ,(parse-cps body))))
331 ,(parse-cps val))))
332 (('letk (cont ...) body)
333 (build-cps-term
334 ($letk ,(map parse-cps cont) ,(parse-cps body))))
335 (('k sym body)
336 (build-cps-cont
337 (sym ,(parse-cps body))))
338 (('kif kt kf)
339 (build-cont-body ($kif kt kf)))
340 (('kreceive req rest k)
341 (build-cont-body ($kreceive req rest k)))
342 (('kargs names syms body)
343 (build-cont-body ($kargs names syms ,(parse-cps body))))
344 (('kentry self tail clauses)
345 (build-cont-body
346 ($kentry self ,(parse-cps tail) ,(map parse-cps clauses))))
347 (('ktail)
348 (build-cont-body
349 ($ktail)))
350 (('kclause (req opt rest kw allow-other-keys?) body)
351 (build-cont-body
352 ($kclause (req opt rest kw allow-other-keys?)
353 ,(parse-cps body))))
354 (('kseq body)
355 (build-cont-body ($kargs () () ,(parse-cps body))))
356
357 ;; Calls.
358 (('continue k exp)
359 (build-cps-term ($continue k (src exp) ,(parse-cps exp))))
360 (('void)
361 (build-cps-exp ($void)))
362 (('const exp)
363 (build-cps-exp ($const exp)))
364 (('prim name)
365 (build-cps-exp ($prim name)))
366 (('fun meta free body)
367 (build-cps-exp ($fun (src exp) meta free ,(parse-cps body))))
368 (('letrec ((name sym fun) ...) body)
369 (build-cps-term
370 ($letrec name sym (map parse-cps fun) ,(parse-cps body))))
371 (('call proc arg ...)
372 (build-cps-exp ($call proc arg)))
373 (('callk k proc arg ...)
374 (build-cps-exp ($callk k proc arg)))
375 (('primcall name arg ...)
376 (build-cps-exp ($primcall name arg)))
377 (('values arg ...)
378 (build-cps-exp ($values arg)))
379 (('prompt escape? tag handler)
380 (build-cps-exp ($prompt escape? tag handler)))
381 (_
382 (error "unexpected cps" exp))))
383
384 (define (unparse-cps exp)
385 (match exp
386 ;; Continuations.
387 (($ $letk (($ $cont k ($ $kargs (name) (sym) body)))
388 ($ $continue k src ($ $const c)))
389 `(letconst ,k (,name ,sym ,c)
390 ,(unparse-cps body)))
391 (($ $letk (($ $cont k ($ $kargs (name) (sym) body))) val)
392 `(let ,k (,name ,sym ,(unparse-cps val))
393 ,(unparse-cps body)))
394 (($ $letk conts body)
395 `(letk ,(map unparse-cps conts) ,(unparse-cps body)))
396 (($ $cont sym body)
397 `(k ,sym ,(unparse-cps body)))
398 (($ $kif kt kf)
399 `(kif ,kt ,kf))
400 (($ $kreceive ($ $arity req () rest '() #f) k)
401 `(kreceive ,req ,rest ,k))
402 (($ $kargs () () body)
403 `(kseq ,(unparse-cps body)))
404 (($ $kargs names syms body)
405 `(kargs ,names ,syms ,(unparse-cps body)))
406 (($ $kentry self tail clauses)
407 `(kentry ,self ,(unparse-cps tail) ,(map unparse-cps clauses)))
408 (($ $ktail)
409 `(ktail))
410 (($ $kclause ($ $arity req opt rest kw allow-other-keys?) body)
411 `(kclause (,req ,opt ,rest ,kw ,allow-other-keys?) ,(unparse-cps body)))
412
413 ;; Calls.
414 (($ $continue k src exp)
415 `(continue ,k ,(unparse-cps exp)))
416 (($ $void)
417 `(void))
418 (($ $const val)
419 `(const ,val))
420 (($ $prim name)
421 `(prim ,name))
422 (($ $fun src meta free body)
423 `(fun ,meta ,free ,(unparse-cps body)))
424 (($ $letrec names syms funs body)
425 `(letrec ,(map (lambda (name sym fun)
426 (list name sym (unparse-cps fun)))
427 names syms funs)
428 ,(unparse-cps body)))
429 (($ $call proc args)
430 `(call ,proc ,@args))
431 (($ $callk k proc args)
432 `(callk ,k ,proc ,@args))
433 (($ $primcall name args)
434 `(primcall ,name ,@args))
435 (($ $values args)
436 `(values ,@args))
437 (($ $prompt escape? tag handler)
438 `(prompt ,escape? ,tag ,handler))
439 (_
440 (error "unexpected cps" exp))))
441
442 (define-syntax-rule (make-cont-folder seed ...)
443 (lambda (proc fun seed ...)
444 (define (fold-values proc in seed ...)
445 (if (null? in)
446 (values seed ...)
447 (let-values (((seed ...) (proc (car in) seed ...)))
448 (fold-values proc (cdr in) seed ...))))
449
450 (define (cont-folder cont seed ...)
451 (match cont
452 (($ $cont k cont)
453 (let-values (((seed ...) (proc k cont seed ...)))
454 (match cont
455 (($ $kargs names syms body)
456 (term-folder body seed ...))
457
458 (($ $kentry self tail clauses)
459 (let-values (((seed ...) (cont-folder tail seed ...)))
460 (fold-values cont-folder clauses seed ...)))
461
462 (($ $kclause arity body)
463 (cont-folder body seed ...))
464
465 (_ (values seed ...)))))))
466
467 (define (fun-folder fun seed ...)
468 (match fun
469 (($ $fun src meta free body)
470 (cont-folder body seed ...))))
471
472 (define (term-folder term seed ...)
473 (match term
474 (($ $letk conts body)
475 (let-values (((seed ...) (term-folder body seed ...)))
476 (fold-values cont-folder conts seed ...)))
477
478 (($ $continue k src exp)
479 (match exp
480 (($ $fun) (fun-folder exp seed ...))
481 (_ (values seed ...))))
482
483 (($ $letrec names syms funs body)
484 (let-values (((seed ...) (term-folder body seed ...)))
485 (fold-values fun-folder funs seed ...)))))
486
487 (fun-folder fun seed ...)))
488
489 (define (compute-max-label-and-var fun)
490 ((make-cont-folder max-label max-var)
491 (lambda (label cont max-label max-var)
492 (values (max label max-label)
493 (match cont
494 (($ $kargs names vars)
495 (fold max max-var vars))
496 (($ $kentry self)
497 (max self max-var))
498 (_ max-var))))
499 fun
500 -1
501 -1))
502
503 (define (fold-conts proc seed fun)
504 ((make-cont-folder seed) proc fun seed))
505
506 (define (fold-local-conts proc seed cont)
507 (define (cont-folder cont seed)
508 (match cont
509 (($ $cont k cont)
510 (let ((seed (proc k cont seed)))
511 (match cont
512 (($ $kargs names syms body)
513 (term-folder body seed))
514
515 (($ $kentry self tail clauses)
516 (fold cont-folder (cont-folder tail seed) clauses))
517
518 (($ $kclause arity body)
519 (cont-folder body seed))
520
521 (_ seed))))))
522
523 (define (term-folder term seed)
524 (match term
525 (($ $letk conts body)
526 (fold cont-folder (term-folder body seed) conts))
527
528 (($ $continue) seed)
529
530 (($ $letrec names syms funs body) (term-folder body seed))))
531
532 (cont-folder cont seed))