Add 2012 to FSF copyright years for Emacs files
[bpt/emacs.git] / lisp / emacs-lisp / cconv.el
1 ;;; cconv.el --- Closure conversion for statically scoped Emacs lisp. -*- lexical-binding: t; coding: utf-8 -*-
2
3 ;; Copyright (C) 2011-2012 Free Software Foundation, Inc.
4
5 ;; Author: Igor Kuzmin <kzuminig@iro.umontreal.ca>
6 ;; Maintainer: FSF
7 ;; Keywords: lisp
8 ;; Package: emacs
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs 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 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This takes a piece of Elisp code, and eliminates all free variables from
28 ;; lambda expressions. The user entry points are cconv-closure-convert and
29 ;; cconv-closure-convert-toplevel (for toplevel forms).
30 ;; All macros should be expanded beforehand.
31 ;;
32 ;; Here is a brief explanation how this code works.
33 ;; Firstly, we analyze the tree by calling cconv-analyse-form.
34 ;; This function finds all mutated variables, all functions that are suitable
35 ;; for lambda lifting and all variables captured by closure. It passes the tree
36 ;; once, returning a list of three lists.
37 ;;
38 ;; Then we calculate the intersection of the first and third lists returned by
39 ;; cconv-analyse form to find all mutated variables that are captured by
40 ;; closure.
41
42 ;; Armed with this data, we call cconv-closure-convert-rec, that rewrites the
43 ;; tree recursively, lifting lambdas where possible, building closures where it
44 ;; is needed and eliminating mutable variables used in closure.
45 ;;
46 ;; We do following replacements :
47 ;; (lambda (v1 ...) ... fv1 fv2 ...) => (lambda (v1 ... fv1 fv2 ) ... fv1 fv2 .)
48 ;; if the function is suitable for lambda lifting (if all calls are known)
49 ;;
50 ;; (lambda (v0 ...) ... fv0 .. fv1 ...) =>
51 ;; (internal-make-closure (v0 ...) (fv1 ...)
52 ;; ... (internal-get-closed-var 0) ... (internal-get-closed-var 1) ...)
53 ;;
54 ;; If the function has no free variables, we don't do anything.
55 ;;
56 ;; If a variable is mutated (updated by setq), and it is used in a closure
57 ;; we wrap its definition with list: (list val) and we also replace
58 ;; var => (car var) wherever this variable is used, and also
59 ;; (setq var value) => (setcar var value) where it is updated.
60 ;;
61 ;; If defun argument is closure mutable, we letbind it and wrap it's
62 ;; definition with list.
63 ;; (defun foo (... mutable-arg ...) ...) =>
64 ;; (defun foo (... m-arg ...) (let ((m-arg (list m-arg))) ...))
65 ;;
66 ;;; Code:
67
68 ;; TODO: (not just for cconv but also for the lexbind changes in general)
69 ;; - let (e)debug find the value of lexical variables from the stack.
70 ;; - make eval-region do the eval-sexp-add-defvars dance.
71 ;; - byte-optimize-form should be applied before cconv.
72 ;; OTOH, the warnings emitted by cconv-analyze need to come before optimize
73 ;; since afterwards they can because obnoxious (warnings about an "unused
74 ;; variable" should not be emitted when the variable use has simply been
75 ;; optimized away).
76 ;; - turn defun and defmacro into macros (and remove special handling of
77 ;; `declare' afterwards).
78 ;; - let macros specify that some let-bindings come from the same source,
79 ;; so the unused warning takes all uses into account.
80 ;; - let interactive specs return a function to build the args (to stash into
81 ;; command-history).
82 ;; - canonize code in macro-expand so we don't have to handle (let (var) body)
83 ;; and other oddities.
84 ;; - new byte codes for unwind-protect, catch, and condition-case so that
85 ;; closures aren't needed at all.
86 ;; - inline source code of different binding mode by first compiling it.
87 ;; - a reference to a var that is known statically to always hold a constant
88 ;; should be turned into a byte-constant rather than a byte-stack-ref.
89 ;; Hmm... right, that's called constant propagation and could be done here,
90 ;; but when that constant is a function, we have to be careful to make sure
91 ;; the bytecomp only compiles it once.
92 ;; - Since we know here when a variable is not mutated, we could pass that
93 ;; info to the byte-compiler, e.g. by using a new `immutable-let'.
94 ;; - add tail-calls to bytecode.c and the byte compiler.
95 ;; - call known non-escaping functions with `goto' rather than `call'.
96 ;; - optimize mapcar to a while loop.
97
98 ;; (defmacro dlet (binders &rest body)
99 ;; ;; Works in both lexical and non-lexical mode.
100 ;; `(progn
101 ;; ,@(mapcar (lambda (binder)
102 ;; `(defvar ,(if (consp binder) (car binder) binder)))
103 ;; binders)
104 ;; (let ,binders ,@body)))
105
106 ;; (defmacro llet (binders &rest body)
107 ;; ;; Only works in lexical-binding mode.
108 ;; `(funcall
109 ;; (lambda ,(mapcar (lambda (binder) (if (consp binder) (car binder) binder))
110 ;; binders)
111 ;; ,@body)
112 ;; ,@(mapcar (lambda (binder) (if (consp binder) (cadr binder)))
113 ;; binders)))
114
115 (eval-when-compile (require 'cl))
116
117 (defconst cconv-liftwhen 6
118 "Try to do lambda lifting if the number of arguments + free variables
119 is less than this number.")
120 ;; List of all the variables that are both captured by a closure
121 ;; and mutated. Each entry in the list takes the form
122 ;; (BINDER . PARENTFORM) where BINDER is the (VAR VAL) that introduces the
123 ;; variable (or is just (VAR) for variables not introduced by let).
124 (defvar cconv-captured+mutated)
125
126 ;; List of candidates for lambda lifting.
127 ;; Each candidate has the form (BINDER . PARENTFORM). A candidate
128 ;; is a variable that is only passed to `funcall' or `apply'.
129 (defvar cconv-lambda-candidates)
130
131 ;; Alist associating to each function body the list of its free variables.
132 (defvar cconv-freevars-alist)
133
134 ;;;###autoload
135 (defun cconv-closure-convert (form)
136 "Main entry point for closure conversion.
137 -- FORM is a piece of Elisp code after macroexpansion.
138 -- TOPLEVEL(optional) is a boolean variable, true if we are at the root of AST
139
140 Returns a form where all lambdas don't have any free variables."
141 ;; (message "Entering cconv-closure-convert...")
142 (let ((cconv-freevars-alist '())
143 (cconv-lambda-candidates '())
144 (cconv-captured+mutated '()))
145 ;; Analyze form - fill these variables with new information.
146 (cconv-analyse-form form '())
147 (setq cconv-freevars-alist (nreverse cconv-freevars-alist))
148 (cconv-convert form nil nil))) ; Env initially empty.
149
150 (defconst cconv--dummy-var (make-symbol "ignored"))
151
152 (defun cconv--set-diff (s1 s2)
153 "Return elements of set S1 that are not in set S2."
154 (let ((res '()))
155 (dolist (x s1)
156 (unless (memq x s2) (push x res)))
157 (nreverse res)))
158
159 (defun cconv--set-diff-map (s m)
160 "Return elements of set S that are not in Dom(M)."
161 (let ((res '()))
162 (dolist (x s)
163 (unless (assq x m) (push x res)))
164 (nreverse res)))
165
166 (defun cconv--map-diff (m1 m2)
167 "Return the submap of map M1 that has Dom(M2) removed."
168 (let ((res '()))
169 (dolist (x m1)
170 (unless (assq (car x) m2) (push x res)))
171 (nreverse res)))
172
173 (defun cconv--map-diff-elem (m x)
174 "Return the map M minus any mapping for X."
175 ;; Here we assume that X appears at most once in M.
176 (let* ((b (assq x m))
177 (res (if b (remq b m) m)))
178 (assert (null (assq x res))) ;; Check the assumption was warranted.
179 res))
180
181 (defun cconv--map-diff-set (m s)
182 "Return the map M minus any mapping for elements of S."
183 ;; Here we assume that X appears at most once in M.
184 (let ((res '()))
185 (dolist (b m)
186 (unless (memq (car b) s) (push b res)))
187 (nreverse res)))
188
189 (defun cconv--convert-function (args body env parentform)
190 (assert (equal body (caar cconv-freevars-alist)))
191 (let* ((fvs (cdr (pop cconv-freevars-alist)))
192 (body-new '())
193 (letbind '())
194 (envector ())
195 (i 0)
196 (new-env ()))
197 ;; Build the "formal and actual envs" for the closure-converted function.
198 (dolist (fv fvs)
199 (let ((exp (or (cdr (assq fv env)) fv)))
200 (pcase exp
201 ;; If `fv' is a variable that's wrapped in a cons-cell,
202 ;; we want to put the cons-cell itself in the closure,
203 ;; rather than just a copy of its current content.
204 (`(car ,iexp . ,_)
205 (push iexp envector)
206 (push `(,fv . (car (internal-get-closed-var ,i))) new-env))
207 (_
208 (push exp envector)
209 (push `(,fv . (internal-get-closed-var ,i)) new-env))))
210 (setq i (1+ i)))
211 (setq envector (nreverse envector))
212 (setq new-env (nreverse new-env))
213
214 (dolist (arg args)
215 (if (not (member (cons (list arg) parentform) cconv-captured+mutated))
216 (if (assq arg new-env) (push `(,arg) new-env))
217 (push `(,arg . (car ,arg)) new-env)
218 (push `(,arg (list ,arg)) letbind)))
219
220 (setq body-new (mapcar (lambda (form)
221 (cconv-convert form new-env nil))
222 body))
223
224 (when letbind
225 (let ((special-forms '()))
226 ;; Keep special forms at the beginning of the body.
227 (while (or (stringp (car body-new)) ;docstring.
228 (memq (car-safe (car body-new)) '(interactive declare)))
229 (push (pop body-new) special-forms))
230 (setq body-new
231 `(,@(nreverse special-forms) (let ,letbind . ,body-new)))))
232
233 (cond
234 ((null envector) ;if no freevars - do nothing
235 `(function (lambda ,args . ,body-new)))
236 (t
237 `(internal-make-closure
238 ,args ,envector . ,body-new)))))
239
240 (defun cconv-convert (form env extend)
241 ;; This function actually rewrites the tree.
242 "Return FORM with all its lambdas changed so they are closed.
243 ENV is a lexical environment mapping variables to the expression
244 used to get its value. This is used for variables that are copied into
245 closures, moved into cons cells, ...
246 ENV is a list where each entry takes the shape either:
247 (VAR . (car EXP)): VAR has been moved into the car of a cons-cell, and EXP
248 is an expression that evaluates to this cons-cell.
249 (VAR . (internal-get-closed-var N)): VAR has been copied into the closure
250 environment's Nth slot.
251 (VAR . (apply-partially F ARG1 ARG2 ..)): VAR has been λ-lifted and takes
252 additional arguments ARGs.
253 EXTEND is a list of variables which might need to be accessed even from places
254 where they are shadowed, because some part of ENV causes them to be used at
255 places where they originally did not directly appear."
256 (assert (not (delq nil (mapcar (lambda (mapping)
257 (if (eq (cadr mapping) 'apply-partially)
258 (cconv--set-diff (cdr (cddr mapping))
259 extend)))
260 env))))
261
262 ;; What's the difference between fvrs and envs?
263 ;; Suppose that we have the code
264 ;; (lambda (..) fvr (let ((fvr 1)) (+ fvr 1)))
265 ;; only the first occurrence of fvr should be replaced by
266 ;; (aref env ...).
267 ;; So initially envs and fvrs are the same thing, but when we descend to
268 ;; the 'let, we delete fvr from fvrs. Why we don't delete fvr from envs?
269 ;; Because in envs the order of variables is important. We use this list
270 ;; to find the number of a specific variable in the environment vector,
271 ;; so we never touch it(unless we enter to the other closure).
272 ;;(if (listp form) (print (car form)) form)
273 (pcase form
274 (`(,(and letsym (or `let* `let)) ,binders . ,body)
275
276 ; let and let* special forms
277 (let ((binders-new '())
278 (new-env env)
279 (new-extend extend))
280
281 (dolist (binder binders)
282 (let* ((value nil)
283 (var (if (not (consp binder))
284 (prog1 binder (setq binder (list binder)))
285 (setq value (cadr binder))
286 (car binder)))
287 (new-val
288 (cond
289 ;; Check if var is a candidate for lambda lifting.
290 ((and (member (cons binder form) cconv-lambda-candidates)
291 (progn
292 (assert (and (eq (car value) 'function)
293 (eq (car (cadr value)) 'lambda)))
294 (assert (equal (cddr (cadr value))
295 (caar cconv-freevars-alist)))
296 ;; Peek at the freevars to decide whether to λ-lift.
297 (let* ((fvs (cdr (car cconv-freevars-alist)))
298 (fun (cadr value))
299 (funargs (cadr fun))
300 (funcvars (append fvs funargs)))
301 ; lambda lifting condition
302 (and fvs (>= cconv-liftwhen (length funcvars))))))
303 ; Lift.
304 (let* ((fvs (cdr (pop cconv-freevars-alist)))
305 (fun (cadr value))
306 (funargs (cadr fun))
307 (funcvars (append fvs funargs))
308 (funcbody (cddr fun))
309 (funcbody-env ()))
310 (push `(,var . (apply-partially ,var . ,fvs)) new-env)
311 (dolist (fv fvs)
312 (pushnew fv new-extend)
313 (if (and (eq 'car (car-safe (cdr (assq fv env))))
314 (not (memq fv funargs)))
315 (push `(,fv . (car ,fv)) funcbody-env)))
316 `(function (lambda ,funcvars .
317 ,(mapcar (lambda (form)
318 (cconv-convert
319 form funcbody-env nil))
320 funcbody)))))
321
322 ;; Check if it needs to be turned into a "ref-cell".
323 ((member (cons binder form) cconv-captured+mutated)
324 ;; Declared variable is mutated and captured.
325 (push `(,var . (car ,var)) new-env)
326 `(list ,(cconv-convert value env extend)))
327
328 ;; Normal default case.
329 (t
330 (if (assq var new-env) (push `(,var) new-env))
331 (cconv-convert value env extend)))))
332
333 ;; The piece of code below letbinds free variables of a λ-lifted
334 ;; function if they are redefined in this let, example:
335 ;; (let* ((fun (lambda (x) (+ x y))) (y 1)) (funcall fun 1))
336 ;; Here we can not pass y as parameter because it is redefined.
337 ;; So we add a (closed-y y) declaration. We do that even if the
338 ;; function is not used inside this let(*). The reason why we
339 ;; ignore this case is that we can't "look forward" to see if the
340 ;; function is called there or not. To treat this case better we'd
341 ;; need to traverse the tree one more time to collect this data, and
342 ;; I think that it's not worth it.
343 (when (memq var new-extend)
344 (let ((closedsym
345 (make-symbol (concat "closed-" (symbol-name var)))))
346 (setq new-env
347 (mapcar (lambda (mapping)
348 (if (not (eq (cadr mapping) 'apply-partially))
349 mapping
350 (assert (eq (car mapping) (nth 2 mapping)))
351 (list* (car mapping)
352 'apply-partially
353 (car mapping)
354 (mapcar (lambda (arg)
355 (if (eq var arg)
356 closedsym arg))
357 (nthcdr 3 mapping)))))
358 new-env))
359 (setq new-extend (remq var new-extend))
360 (push closedsym new-extend)
361 (push `(,closedsym ,var) binders-new)))
362
363 ;; We push the element after redefined free variables are
364 ;; processed. This is important to avoid the bug when free
365 ;; variable and the function have the same name.
366 (push (list var new-val) binders-new)
367
368 (when (eq letsym 'let*)
369 (setq env new-env)
370 (setq extend new-extend))
371 )) ; end of dolist over binders
372
373 `(,letsym ,(nreverse binders-new)
374 . ,(mapcar (lambda (form)
375 (cconv-convert
376 form new-env new-extend))
377 body))))
378 ;end of let let* forms
379
380 ; first element is lambda expression
381 (`(,(and `(lambda . ,_) fun) . ,args)
382 ;; FIXME: it's silly to create a closure just to call it.
383 ;; Running byte-optimize-form earlier will resolve this.
384 `(funcall
385 ,(cconv-convert `(function ,fun) env extend)
386 ,@(mapcar (lambda (form)
387 (cconv-convert form env extend))
388 args)))
389
390 (`(cond . ,cond-forms) ; cond special form
391 `(cond . ,(mapcar (lambda (branch)
392 (mapcar (lambda (form)
393 (cconv-convert form env extend))
394 branch))
395 cond-forms)))
396
397 (`(function (lambda ,args . ,body) . ,_)
398 (cconv--convert-function args body env form))
399
400 (`(internal-make-closure . ,_)
401 (byte-compile-report-error
402 "Internal error in compiler: cconv called twice?"))
403
404 (`(quote . ,_) form)
405 (`(function . ,_) form)
406
407 ;defconst, defvar
408 (`(,(and sym (or `defconst `defvar)) ,definedsymbol . ,forms)
409 `(,sym ,definedsymbol
410 . ,(mapcar (lambda (form) (cconv-convert form env extend))
411 forms)))
412
413 ;defun, defmacro
414 (`(,(and sym (or `defun `defmacro))
415 ,func ,args . ,body)
416 (assert (equal body (caar cconv-freevars-alist)))
417 (assert (null (cdar cconv-freevars-alist)))
418
419 (let ((new (cconv--convert-function args body env form)))
420 (pcase new
421 (`(function (lambda ,newargs . ,new-body))
422 (assert (equal args newargs))
423 `(,sym ,func ,args . ,new-body))
424 (t (byte-compile-report-error
425 (format "Internal error in cconv of (%s %s ...)" sym func))))))
426
427 ;condition-case
428 (`(condition-case ,var ,protected-form . ,handlers)
429 (let ((newform (cconv--convert-function
430 () (list protected-form) env form)))
431 `(condition-case :fun-body ,newform
432 ,@(mapcar (lambda (handler)
433 (list (car handler)
434 (cconv--convert-function
435 (list (or var cconv--dummy-var))
436 (cdr handler) env form)))
437 handlers))))
438
439 (`(,(and head (or `catch `unwind-protect)) ,form . ,body)
440 `(,head ,(cconv-convert form env extend)
441 :fun-body ,(cconv--convert-function () body env form)))
442
443 (`(track-mouse . ,body)
444 `(track-mouse
445 :fun-body ,(cconv--convert-function () body env form)))
446
447 (`(setq . ,forms) ; setq special form
448 (let ((prognlist ()))
449 (while forms
450 (let* ((sym (pop forms))
451 (sym-new (or (cdr (assq sym env)) sym))
452 (value (cconv-convert (pop forms) env extend)))
453 (push (pcase sym-new
454 ((pred symbolp) `(setq ,sym-new ,value))
455 (`(car ,iexp) `(setcar ,iexp ,value))
456 ;; This "should never happen", but for variables which are
457 ;; mutated+captured+unused, we may end up trying to `setq'
458 ;; on a closed-over variable, so just drop the setq.
459 (_ ;; (byte-compile-report-error
460 ;; (format "Internal error in cconv of (setq %s ..)"
461 ;; sym-new))
462 value))
463 prognlist)))
464 (if (cdr prognlist)
465 `(progn . ,(nreverse prognlist))
466 (car prognlist))))
467
468 (`(,(and (or `funcall `apply) callsym) ,fun . ,args)
469 ;; These are not special forms but we treat them separately for the needs
470 ;; of lambda lifting.
471 (let ((mapping (cdr (assq fun env))))
472 (pcase mapping
473 (`(apply-partially ,_ . ,(and fvs `(,_ . ,_)))
474 (assert (eq (cadr mapping) fun))
475 `(,callsym ,fun
476 ,@(mapcar (lambda (fv)
477 (let ((exp (or (cdr (assq fv env)) fv)))
478 (pcase exp
479 (`(car ,iexp . ,_) iexp)
480 (_ exp))))
481 fvs)
482 ,@(mapcar (lambda (arg)
483 (cconv-convert arg env extend))
484 args)))
485 (_ `(,callsym ,@(mapcar (lambda (arg)
486 (cconv-convert arg env extend))
487 (cons fun args)))))))
488
489 (`(interactive . ,forms)
490 `(interactive . ,(mapcar (lambda (form)
491 (cconv-convert form nil nil))
492 forms)))
493
494 (`(declare . ,_) form) ;The args don't contain code.
495
496 (`(,func . ,forms)
497 ;; First element is function or whatever function-like forms are: or, and,
498 ;; if, progn, prog1, prog2, while, until
499 `(,func . ,(mapcar (lambda (form)
500 (cconv-convert form env extend))
501 forms)))
502
503 (_ (or (cdr (assq form env)) form))))
504
505 (unless (fboundp 'byte-compile-not-lexical-var-p)
506 ;; Only used to test the code in non-lexbind Emacs.
507 (defalias 'byte-compile-not-lexical-var-p 'boundp))
508
509 (defun cconv--analyse-use (vardata form varkind)
510 "Analyze the use of a variable.
511 VARDATA should be (BINDER READ MUTATED CAPTURED CALLED).
512 VARKIND is the name of the kind of variable.
513 FORM is the parent form that binds this var."
514 ;; use = `(,binder ,read ,mutated ,captured ,called)
515 (pcase vardata
516 (`(,_ nil nil nil nil) nil)
517 (`((,(and (pred (lambda (var) (eq ?_ (aref (symbol-name var) 0)))) var) . ,_)
518 ,_ ,_ ,_ ,_)
519 (byte-compile-log-warning
520 (format "%s `%S' not left unused" varkind var))))
521 (pcase vardata
522 (`((,var . ,_) nil ,_ ,_ nil)
523 ;; FIXME: This gives warnings in the wrong order, with imprecise line
524 ;; numbers and without function name info.
525 (unless (or ;; Uninterned symbols typically come from macro-expansion, so
526 ;; it is often non-trivial for the programmer to avoid such
527 ;; unused vars.
528 (not (intern-soft var))
529 (eq ?_ (aref (symbol-name var) 0))
530 ;; As a special exception, ignore "ignore".
531 (eq var 'ignored))
532 (byte-compile-log-warning (format "Unused lexical %s `%S'"
533 varkind var))))
534 ;; If it's unused, there's no point converting it into a cons-cell, even if
535 ;; it's captured and mutated.
536 (`(,binder ,_ t t ,_)
537 (push (cons binder form) cconv-captured+mutated))
538 (`(,(and binder `(,_ (function (lambda . ,_)))) nil nil nil t)
539 (push (cons binder form) cconv-lambda-candidates))))
540
541 (defun cconv--analyse-function (args body env parentform)
542 (let* ((newvars nil)
543 (freevars (list body))
544 ;; We analyze the body within a new environment where all uses are
545 ;; nil, so we can distinguish uses within that function from uses
546 ;; outside of it.
547 (envcopy
548 (mapcar (lambda (vdata) (list (car vdata) nil nil nil nil)) env))
549 (newenv envcopy))
550 ;; Push it before recursing, so cconv-freevars-alist contains entries in
551 ;; the order they'll be used by closure-convert-rec.
552 (push freevars cconv-freevars-alist)
553 (dolist (arg args)
554 (cond
555 ((byte-compile-not-lexical-var-p arg)
556 (byte-compile-log-warning
557 (format "Argument %S is not a lexical variable" arg)))
558 ((eq ?& (aref (symbol-name arg) 0)) nil) ;Ignore &rest, &optional, ...
559 (t (let ((varstruct (list arg nil nil nil nil)))
560 (push (cons (list arg) (cdr varstruct)) newvars)
561 (push varstruct newenv)))))
562 (dolist (form body) ;Analyze body forms.
563 (cconv-analyse-form form newenv))
564 ;; Summarize resulting data about arguments.
565 (dolist (vardata newvars)
566 (cconv--analyse-use vardata parentform "argument"))
567 ;; Transfer uses collected in `envcopy' (via `newenv') back to `env';
568 ;; and compute free variables.
569 (while env
570 (assert (and envcopy (eq (caar env) (caar envcopy))))
571 (let ((free nil)
572 (x (cdr (car env)))
573 (y (cdr (car envcopy))))
574 (while x
575 (when (car y) (setcar x t) (setq free t))
576 (setq x (cdr x) y (cdr y)))
577 (when free
578 (push (caar env) (cdr freevars))
579 (setf (nth 3 (car env)) t))
580 (setq env (cdr env) envcopy (cdr envcopy))))))
581
582 (defun cconv-analyse-form (form env)
583 "Find mutated variables and variables captured by closure.
584 Analyze lambdas if they are suitable for lambda lifting.
585 - FORM is a piece of Elisp code after macroexpansion.
586 - ENV is an alist mapping each enclosing lexical variable to its info.
587 I.e. each element has the form (VAR . (READ MUTATED CAPTURED CALLED)).
588 This function does not return anything but instead fills the
589 `cconv-captured+mutated' and `cconv-lambda-candidates' variables
590 and updates the data stored in ENV."
591 (pcase form
592 ; let special form
593 (`(,(and (or `let* `let) letsym) ,binders . ,body-forms)
594
595 (let ((orig-env env)
596 (newvars nil)
597 (var nil)
598 (value nil))
599 (dolist (binder binders)
600 (if (not (consp binder))
601 (progn
602 (setq var binder) ; treat the form (let (x) ...) well
603 (setq binder (list binder))
604 (setq value nil))
605 (setq var (car binder))
606 (setq value (cadr binder))
607
608 (cconv-analyse-form value (if (eq letsym 'let*) env orig-env)))
609
610 (unless (byte-compile-not-lexical-var-p var)
611 (let ((varstruct (list var nil nil nil nil)))
612 (push (cons binder (cdr varstruct)) newvars)
613 (push varstruct env))))
614
615 (dolist (form body-forms) ; Analyze body forms.
616 (cconv-analyse-form form env))
617
618 (dolist (vardata newvars)
619 (cconv--analyse-use vardata form "variable"))))
620
621 ; defun special form
622 (`(,(or `defun `defmacro) ,func ,vrs . ,body-forms)
623 (when env
624 (byte-compile-log-warning
625 (format "Function %S will ignore its context %S"
626 func (mapcar #'car env))
627 t :warning))
628 (cconv--analyse-function vrs body-forms nil form))
629
630 (`(function (lambda ,vrs . ,body-forms))
631 (cconv--analyse-function vrs body-forms env form))
632
633 (`(setq . ,forms)
634 ;; If a local variable (member of env) is modified by setq then
635 ;; it is a mutated variable.
636 (while forms
637 (let ((v (assq (car forms) env))) ; v = non nil if visible
638 (when v (setf (nth 2 v) t)))
639 (cconv-analyse-form (cadr forms) env)
640 (setq forms (cddr forms))))
641
642 (`((lambda . ,_) . ,_) ; first element is lambda expression
643 (dolist (exp `((function ,(car form)) . ,(cdr form)))
644 (cconv-analyse-form exp env)))
645
646 (`(cond . ,cond-forms) ; cond special form
647 (dolist (forms cond-forms)
648 (dolist (form forms) (cconv-analyse-form form env))))
649
650 (`(quote . ,_) nil) ; quote form
651 (`(function . ,_) nil) ; same as quote
652
653 (`(condition-case ,var ,protected-form . ,handlers)
654 ;; FIXME: The bytecode for condition-case forces us to wrap the
655 ;; form and handlers in closures (for handlers, it's understandable
656 ;; but not for the protected form).
657 (cconv--analyse-function () (list protected-form) env form)
658 (dolist (handler handlers)
659 (cconv--analyse-function (if var (list var)) (cdr handler) env form)))
660
661 ;; FIXME: The bytecode for catch forces us to wrap the body.
662 (`(,(or `catch `unwind-protect) ,form . ,body)
663 (cconv-analyse-form form env)
664 (cconv--analyse-function () body env form))
665
666 ;; FIXME: The lack of bytecode for track-mouse forces us to wrap the body.
667 ;; `track-mouse' really should be made into a macro.
668 (`(track-mouse . ,body)
669 (cconv--analyse-function () body env form))
670
671 (`(,(or `defconst `defvar) ,var ,value . ,_)
672 (push var byte-compile-bound-variables)
673 (cconv-analyse-form value env))
674
675 (`(,(or `funcall `apply) ,fun . ,args)
676 ;; Here we ignore fun because funcall and apply are the only two
677 ;; functions where we can pass a candidate for lambda lifting as
678 ;; argument. So, if we see fun elsewhere, we'll delete it from
679 ;; lambda candidate list.
680 (let ((fdata (and (symbolp fun) (assq fun env))))
681 (if fdata
682 (setf (nth 4 fdata) t)
683 (cconv-analyse-form fun env)))
684 (dolist (form args) (cconv-analyse-form form env)))
685
686 (`(interactive . ,forms)
687 ;; These appear within the function body but they don't have access
688 ;; to the function's arguments.
689 ;; We could extend this to allow interactive specs to refer to
690 ;; variables in the function's enclosing environment, but it doesn't
691 ;; seem worth the trouble.
692 (dolist (form forms) (cconv-analyse-form form nil)))
693
694 (`(declare . ,_) nil) ;The args don't contain code.
695
696 (`(,_ . ,body-forms) ; First element is a function or whatever.
697 (dolist (form body-forms) (cconv-analyse-form form env)))
698
699 ((pred symbolp)
700 (let ((dv (assq form env))) ; dv = declared and visible
701 (when dv
702 (setf (nth 1 dv) t))))))
703
704 (provide 'cconv)
705 ;;; cconv.el ends here