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