]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/cconv.el
Merge from trunk.
[gnu-emacs] / 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-2013 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 ;; - 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.
94
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)))
103
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)))
112
113 (eval-when-compile (require 'cl-lib))
114
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)
123
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)
128
129 ;; Alist associating to each function body the list of its free variables.
130 (defvar cconv-freevars-alist)
131
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
137
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 (cconv-convert form nil nil))) ; Env initially empty.
147
148 (defconst cconv--dummy-var (make-symbol "ignored"))
149
150 (defun cconv--set-diff (s1 s2)
151 "Return elements of set S1 that are not in set S2."
152 (let ((res '()))
153 (dolist (x s1)
154 (unless (memq x s2) (push x res)))
155 (nreverse res)))
156
157 (defun cconv--set-diff-map (s m)
158 "Return elements of set S that are not in Dom(M)."
159 (let ((res '()))
160 (dolist (x s)
161 (unless (assq x m) (push x res)))
162 (nreverse res)))
163
164 (defun cconv--map-diff (m1 m2)
165 "Return the submap of map M1 that has Dom(M2) removed."
166 (let ((res '()))
167 (dolist (x m1)
168 (unless (assq (car x) m2) (push x res)))
169 (nreverse res)))
170
171 (defun cconv--map-diff-elem (m x)
172 "Return the map M minus any mapping for X."
173 ;; Here we assume that X appears at most once in M.
174 (let* ((b (assq x m))
175 (res (if b (remq b m) m)))
176 (cl-assert (null (assq x res))) ;; Check the assumption was warranted.
177 res))
178
179 (defun cconv--map-diff-set (m s)
180 "Return the map M minus any mapping for elements of S."
181 ;; Here we assume that X appears at most once in M.
182 (let ((res '()))
183 (dolist (b m)
184 (unless (memq (car b) s) (push b res)))
185 (nreverse res)))
186
187 (defun cconv--convert-function (args body env parentform)
188 (cl-assert (equal body (caar cconv-freevars-alist)))
189 (let* ((fvs (cdr (pop cconv-freevars-alist)))
190 (body-new '())
191 (letbind '())
192 (envector ())
193 (i 0)
194 (new-env ()))
195 ;; Build the "formal and actual envs" for the closure-converted function.
196 (dolist (fv fvs)
197 (let ((exp (or (cdr (assq fv env)) fv)))
198 (pcase exp
199 ;; If `fv' is a variable that's wrapped in a cons-cell,
200 ;; we want to put the cons-cell itself in the closure,
201 ;; rather than just a copy of its current content.
202 (`(car ,iexp . ,_)
203 (push iexp envector)
204 (push `(,fv . (car (internal-get-closed-var ,i))) new-env))
205 (_
206 (push exp envector)
207 (push `(,fv . (internal-get-closed-var ,i)) new-env))))
208 (setq i (1+ i)))
209 (setq envector (nreverse envector))
210 (setq new-env (nreverse new-env))
211
212 (dolist (arg args)
213 (if (not (member (cons (list arg) parentform) cconv-captured+mutated))
214 (if (assq arg new-env) (push `(,arg) new-env))
215 (push `(,arg . (car ,arg)) new-env)
216 (push `(,arg (list ,arg)) letbind)))
217
218 (setq body-new (mapcar (lambda (form)
219 (cconv-convert form new-env nil))
220 body))
221
222 (when letbind
223 (let ((special-forms '()))
224 ;; Keep special forms at the beginning of the body.
225 (while (or (stringp (car body-new)) ;docstring.
226 (memq (car-safe (car body-new)) '(interactive declare)))
227 (push (pop body-new) special-forms))
228 (setq body-new
229 `(,@(nreverse special-forms) (let ,letbind . ,body-new)))))
230
231 (cond
232 ((null envector) ;if no freevars - do nothing
233 `(function (lambda ,args . ,body-new)))
234 (t
235 `(internal-make-closure
236 ,args ,envector . ,body-new)))))
237
238 (defun cconv-convert (form env extend)
239 ;; This function actually rewrites the tree.
240 "Return FORM with all its lambdas changed so they are closed.
241 ENV is a lexical environment mapping variables to the expression
242 used to get its value. This is used for variables that are copied into
243 closures, moved into cons cells, ...
244 ENV is a list where each entry takes the shape either:
245 (VAR . (car EXP)): VAR has been moved into the car of a cons-cell, and EXP
246 is an expression that evaluates to this cons-cell.
247 (VAR . (internal-get-closed-var N)): VAR has been copied into the closure
248 environment's Nth slot.
249 (VAR . (apply-partially F ARG1 ARG2 ..)): VAR has been λ-lifted and takes
250 additional arguments ARGs.
251 EXTEND is a list of variables which might need to be accessed even from places
252 where they are shadowed, because some part of ENV causes them to be used at
253 places where they originally did not directly appear."
254 (cl-assert (not (delq nil (mapcar (lambda (mapping)
255 (if (eq (cadr mapping) 'apply-partially)
256 (cconv--set-diff (cdr (cddr mapping))
257 extend)))
258 env))))
259
260 ;; What's the difference between fvrs and envs?
261 ;; Suppose that we have the code
262 ;; (lambda (..) fvr (let ((fvr 1)) (+ fvr 1)))
263 ;; only the first occurrence of fvr should be replaced by
264 ;; (aref env ...).
265 ;; So initially envs and fvrs are the same thing, but when we descend to
266 ;; the 'let, we delete fvr from fvrs. Why we don't delete fvr from envs?
267 ;; Because in envs the order of variables is important. We use this list
268 ;; to find the number of a specific variable in the environment vector,
269 ;; so we never touch it(unless we enter to the other closure).
270 ;;(if (listp form) (print (car form)) form)
271 (pcase form
272 (`(,(and letsym (or `let* `let)) ,binders . ,body)
273
274 ; let and let* special forms
275 (let ((binders-new '())
276 (new-env env)
277 (new-extend extend))
278
279 (dolist (binder binders)
280 (let* ((value nil)
281 (var (if (not (consp binder))
282 (prog1 binder (setq binder (list binder)))
283 (setq value (cadr binder))
284 (car binder)))
285 (new-val
286 (cond
287 ;; Check if var is a candidate for lambda lifting.
288 ((and (member (cons binder form) cconv-lambda-candidates)
289 (progn
290 (cl-assert (and (eq (car value) 'function)
291 (eq (car (cadr value)) 'lambda)))
292 (cl-assert (equal (cddr (cadr value))
293 (caar cconv-freevars-alist)))
294 ;; Peek at the freevars to decide whether to λ-lift.
295 (let* ((fvs (cdr (car cconv-freevars-alist)))
296 (fun (cadr value))
297 (funargs (cadr fun))
298 (funcvars (append fvs funargs)))
299 ; lambda lifting condition
300 (and fvs (>= cconv-liftwhen (length funcvars))))))
301 ; Lift.
302 (let* ((fvs (cdr (pop cconv-freevars-alist)))
303 (fun (cadr value))
304 (funargs (cadr fun))
305 (funcvars (append fvs funargs))
306 (funcbody (cddr fun))
307 (funcbody-env ()))
308 (push `(,var . (apply-partially ,var . ,fvs)) new-env)
309 (dolist (fv fvs)
310 (cl-pushnew fv new-extend)
311 (if (and (eq 'car (car-safe (cdr (assq fv env))))
312 (not (memq fv funargs)))
313 (push `(,fv . (car ,fv)) funcbody-env)))
314 `(function (lambda ,funcvars .
315 ,(mapcar (lambda (form)
316 (cconv-convert
317 form funcbody-env nil))
318 funcbody)))))
319
320 ;; Check if it needs to be turned into a "ref-cell".
321 ((member (cons binder form) cconv-captured+mutated)
322 ;; Declared variable is mutated and captured.
323 (push `(,var . (car ,var)) new-env)
324 `(list ,(cconv-convert value env extend)))
325
326 ;; Normal default case.
327 (t
328 (if (assq var new-env) (push `(,var) new-env))
329 (cconv-convert value env extend)))))
330
331 ;; The piece of code below letbinds free variables of a λ-lifted
332 ;; function if they are redefined in this let, example:
333 ;; (let* ((fun (lambda (x) (+ x y))) (y 1)) (funcall fun 1))
334 ;; Here we can not pass y as parameter because it is redefined.
335 ;; So we add a (closed-y y) declaration. We do that even if the
336 ;; function is not used inside this let(*). The reason why we
337 ;; ignore this case is that we can't "look forward" to see if the
338 ;; function is called there or not. To treat this case better we'd
339 ;; need to traverse the tree one more time to collect this data, and
340 ;; I think that it's not worth it.
341 (when (memq var new-extend)
342 (let ((closedsym
343 (make-symbol (concat "closed-" (symbol-name var)))))
344 (setq new-env
345 (mapcar (lambda (mapping)
346 (if (not (eq (cadr mapping) 'apply-partially))
347 mapping
348 (cl-assert (eq (car mapping) (nth 2 mapping)))
349 `(,(car mapping)
350 apply-partially
351 ,(car mapping)
352 ,@(mapcar (lambda (arg)
353 (if (eq var arg)
354 closedsym arg))
355 (nthcdr 3 mapping)))))
356 new-env))
357 (setq new-extend (remq var new-extend))
358 (push closedsym new-extend)
359 (push `(,closedsym ,var) binders-new)))
360
361 ;; We push the element after redefined free variables are
362 ;; processed. This is important to avoid the bug when free
363 ;; variable and the function have the same name.
364 (push (list var new-val) binders-new)
365
366 (when (eq letsym 'let*)
367 (setq env new-env)
368 (setq extend new-extend))
369 )) ; end of dolist over binders
370
371 `(,letsym ,(nreverse binders-new)
372 . ,(mapcar (lambda (form)
373 (cconv-convert
374 form new-env new-extend))
375 body))))
376 ;end of let let* forms
377
378 ; first element is lambda expression
379 (`(,(and `(lambda . ,_) fun) . ,args)
380 ;; FIXME: it's silly to create a closure just to call it.
381 ;; Running byte-optimize-form earlier will resolve this.
382 `(funcall
383 ,(cconv-convert `(function ,fun) env extend)
384 ,@(mapcar (lambda (form)
385 (cconv-convert form env extend))
386 args)))
387
388 (`(cond . ,cond-forms) ; cond special form
389 `(cond . ,(mapcar (lambda (branch)
390 (mapcar (lambda (form)
391 (cconv-convert form env extend))
392 branch))
393 cond-forms)))
394
395 (`(function (lambda ,args . ,body) . ,_)
396 (cconv--convert-function args body env form))
397
398 (`(internal-make-closure . ,_)
399 (byte-compile-report-error
400 "Internal error in compiler: cconv called twice?"))
401
402 (`(quote . ,_) form)
403 (`(function . ,_) form)
404
405 ;defconst, defvar
406 (`(,(and sym (or `defconst `defvar)) ,definedsymbol . ,forms)
407 `(,sym ,definedsymbol
408 . ,(mapcar (lambda (form) (cconv-convert form env extend))
409 forms)))
410
411 ;condition-case
412 (`(condition-case ,var ,protected-form . ,handlers)
413 (let ((newform (cconv--convert-function
414 () (list protected-form) env form)))
415 `(condition-case :fun-body ,newform
416 ,@(mapcar (lambda (handler)
417 (list (car handler)
418 (cconv--convert-function
419 (list (or var cconv--dummy-var))
420 (cdr handler) env form)))
421 handlers))))
422
423 (`(,(and head (or `catch `unwind-protect)) ,form . ,body)
424 `(,head ,(cconv-convert form env extend)
425 :fun-body ,(cconv--convert-function () body env form)))
426
427 (`(track-mouse . ,body)
428 `(track-mouse
429 :fun-body ,(cconv--convert-function () body env form)))
430
431 (`(setq . ,forms) ; setq special form
432 (let ((prognlist ()))
433 (while forms
434 (let* ((sym (pop forms))
435 (sym-new (or (cdr (assq sym env)) sym))
436 (value (cconv-convert (pop forms) env extend)))
437 (push (pcase sym-new
438 ((pred symbolp) `(setq ,sym-new ,value))
439 (`(car ,iexp) `(setcar ,iexp ,value))
440 ;; This "should never happen", but for variables which are
441 ;; mutated+captured+unused, we may end up trying to `setq'
442 ;; on a closed-over variable, so just drop the setq.
443 (_ ;; (byte-compile-report-error
444 ;; (format "Internal error in cconv of (setq %s ..)"
445 ;; sym-new))
446 value))
447 prognlist)))
448 (if (cdr prognlist)
449 `(progn . ,(nreverse prognlist))
450 (car prognlist))))
451
452 (`(,(and (or `funcall `apply) callsym) ,fun . ,args)
453 ;; These are not special forms but we treat them separately for the needs
454 ;; of lambda lifting.
455 (let ((mapping (cdr (assq fun env))))
456 (pcase mapping
457 (`(apply-partially ,_ . ,(and fvs `(,_ . ,_)))
458 (cl-assert (eq (cadr mapping) fun))
459 `(,callsym ,fun
460 ,@(mapcar (lambda (fv)
461 (let ((exp (or (cdr (assq fv env)) fv)))
462 (pcase exp
463 (`(car ,iexp . ,_) iexp)
464 (_ exp))))
465 fvs)
466 ,@(mapcar (lambda (arg)
467 (cconv-convert arg env extend))
468 args)))
469 (_ `(,callsym ,@(mapcar (lambda (arg)
470 (cconv-convert arg env extend))
471 (cons fun args)))))))
472
473 (`(interactive . ,forms)
474 `(interactive . ,(mapcar (lambda (form)
475 (cconv-convert form nil nil))
476 forms)))
477
478 (`(declare . ,_) form) ;The args don't contain code.
479
480 (`(,func . ,forms)
481 ;; First element is function or whatever function-like forms are: or, and,
482 ;; if, progn, prog1, prog2, while, until
483 `(,func . ,(mapcar (lambda (form)
484 (cconv-convert form env extend))
485 forms)))
486
487 (_ (or (cdr (assq form env)) form))))
488
489 (unless (fboundp 'byte-compile-not-lexical-var-p)
490 ;; Only used to test the code in non-lexbind Emacs.
491 (defalias 'byte-compile-not-lexical-var-p 'boundp))
492 (defvar byte-compile-lexical-variables)
493
494 (defun cconv--analyse-use (vardata form varkind)
495 "Analyze the use of a variable.
496 VARDATA should be (BINDER READ MUTATED CAPTURED CALLED).
497 VARKIND is the name of the kind of variable.
498 FORM is the parent form that binds this var."
499 ;; use = `(,binder ,read ,mutated ,captured ,called)
500 (pcase vardata
501 (`(,_ nil nil nil nil) nil)
502 (`((,(and (pred (lambda (var) (eq ?_ (aref (symbol-name var) 0)))) var) . ,_)
503 ,_ ,_ ,_ ,_)
504 (byte-compile-log-warning
505 (format "%s `%S' not left unused" varkind var))))
506 (pcase vardata
507 (`((,var . ,_) nil ,_ ,_ nil)
508 ;; FIXME: This gives warnings in the wrong order, with imprecise line
509 ;; numbers and without function name info.
510 (unless (or ;; Uninterned symbols typically come from macro-expansion, so
511 ;; it is often non-trivial for the programmer to avoid such
512 ;; unused vars.
513 (not (intern-soft var))
514 (eq ?_ (aref (symbol-name var) 0))
515 ;; As a special exception, ignore "ignore".
516 (eq var 'ignored))
517 (byte-compile-log-warning (format "Unused lexical %s `%S'"
518 varkind var))))
519 ;; If it's unused, there's no point converting it into a cons-cell, even if
520 ;; it's captured and mutated.
521 (`(,binder ,_ t t ,_)
522 (push (cons binder form) cconv-captured+mutated))
523 (`(,(and binder `(,_ (function (lambda . ,_)))) nil nil nil t)
524 (push (cons binder form) cconv-lambda-candidates))))
525
526 (defun cconv--analyse-function (args body env parentform)
527 (let* ((newvars nil)
528 (freevars (list body))
529 ;; We analyze the body within a new environment where all uses are
530 ;; nil, so we can distinguish uses within that function from uses
531 ;; outside of it.
532 (envcopy
533 (mapcar (lambda (vdata) (list (car vdata) nil nil nil nil)) env))
534 (byte-compile-bound-variables byte-compile-bound-variables)
535 (newenv envcopy))
536 ;; Push it before recursing, so cconv-freevars-alist contains entries in
537 ;; the order they'll be used by closure-convert-rec.
538 (push freevars cconv-freevars-alist)
539 (dolist (arg args)
540 (cond
541 ((byte-compile-not-lexical-var-p arg)
542 (byte-compile-log-warning
543 (format "Argument %S is not a lexical variable" arg)))
544 ((eq ?& (aref (symbol-name arg) 0)) nil) ;Ignore &rest, &optional, ...
545 (t (let ((varstruct (list arg nil nil nil nil)))
546 (cl-pushnew arg byte-compile-lexical-variables)
547 (push (cons (list arg) (cdr varstruct)) newvars)
548 (push varstruct newenv)))))
549 (dolist (form body) ;Analyze body forms.
550 (cconv-analyse-form form newenv))
551 ;; Summarize resulting data about arguments.
552 (dolist (vardata newvars)
553 (cconv--analyse-use vardata parentform "argument"))
554 ;; Transfer uses collected in `envcopy' (via `newenv') back to `env';
555 ;; and compute free variables.
556 (while env
557 (cl-assert (and envcopy (eq (caar env) (caar envcopy))))
558 (let ((free nil)
559 (x (cdr (car env)))
560 (y (cdr (car envcopy))))
561 (while x
562 (when (car y) (setcar x t) (setq free t))
563 (setq x (cdr x) y (cdr y)))
564 (when free
565 (push (caar env) (cdr freevars))
566 (setf (nth 3 (car env)) t))
567 (setq env (cdr env) envcopy (cdr envcopy))))))
568
569 (defun cconv-analyse-form (form env)
570 "Find mutated variables and variables captured by closure.
571 Analyze lambdas if they are suitable for lambda lifting.
572 - FORM is a piece of Elisp code after macroexpansion.
573 - ENV is an alist mapping each enclosing lexical variable to its info.
574 I.e. each element has the form (VAR . (READ MUTATED CAPTURED CALLED)).
575 This function does not return anything but instead fills the
576 `cconv-captured+mutated' and `cconv-lambda-candidates' variables
577 and updates the data stored in ENV."
578 (pcase form
579 ; let special form
580 (`(,(and (or `let* `let) letsym) ,binders . ,body-forms)
581
582 (let ((orig-env env)
583 (newvars nil)
584 (var nil)
585 (byte-compile-bound-variables byte-compile-bound-variables)
586 (value nil))
587 (dolist (binder binders)
588 (if (not (consp binder))
589 (progn
590 (setq var binder) ; treat the form (let (x) ...) well
591 (setq binder (list binder))
592 (setq value nil))
593 (setq var (car binder))
594 (setq value (cadr binder))
595
596 (cconv-analyse-form value (if (eq letsym 'let*) env orig-env)))
597
598 (unless (byte-compile-not-lexical-var-p var)
599 (cl-pushnew var byte-compile-lexical-variables)
600 (let ((varstruct (list var nil nil nil nil)))
601 (push (cons binder (cdr varstruct)) newvars)
602 (push varstruct env))))
603
604 (dolist (form body-forms) ; Analyze body forms.
605 (cconv-analyse-form form env))
606
607 (dolist (vardata newvars)
608 (cconv--analyse-use vardata form "variable"))))
609
610 (`(function (lambda ,vrs . ,body-forms))
611 (cconv--analyse-function vrs body-forms env form))
612
613 (`(setq . ,forms)
614 ;; If a local variable (member of env) is modified by setq then
615 ;; it is a mutated variable.
616 (while forms
617 (let ((v (assq (car forms) env))) ; v = non nil if visible
618 (when v (setf (nth 2 v) t)))
619 (cconv-analyse-form (cadr forms) env)
620 (setq forms (cddr forms))))
621
622 (`((lambda . ,_) . ,_) ; First element is lambda expression.
623 (byte-compile-log-warning
624 (format "Use of deprecated ((lambda %s ...) ...) form" (nth 1 (car form)))
625 t :warning)
626 (dolist (exp `((function ,(car form)) . ,(cdr form)))
627 (cconv-analyse-form exp env)))
628
629 (`(cond . ,cond-forms) ; cond special form
630 (dolist (forms cond-forms)
631 (dolist (form forms) (cconv-analyse-form form env))))
632
633 (`(quote . ,_) nil) ; quote form
634 (`(function . ,_) nil) ; same as quote
635
636 (`(condition-case ,var ,protected-form . ,handlers)
637 ;; FIXME: The bytecode for condition-case forces us to wrap the
638 ;; form and handlers in closures (for handlers, it's understandable
639 ;; but not for the protected form).
640 (cconv--analyse-function () (list protected-form) env form)
641 (dolist (handler handlers)
642 (cconv--analyse-function (if var (list var)) (cdr handler) env form)))
643
644 ;; FIXME: The bytecode for catch forces us to wrap the body.
645 (`(,(or `catch `unwind-protect) ,form . ,body)
646 (cconv-analyse-form form env)
647 (cconv--analyse-function () body env form))
648
649 ;; FIXME: The lack of bytecode for track-mouse forces us to wrap the body.
650 ;; `track-mouse' really should be made into a macro.
651 (`(track-mouse . ,body)
652 (cconv--analyse-function () body env form))
653
654 (`(defvar ,var) (push var byte-compile-bound-variables))
655 (`(,(or `defconst `defvar) ,var ,value . ,_)
656 (push var byte-compile-bound-variables)
657 (cconv-analyse-form value env))
658
659 (`(,(or `funcall `apply) ,fun . ,args)
660 ;; Here we ignore fun because funcall and apply are the only two
661 ;; functions where we can pass a candidate for lambda lifting as
662 ;; argument. So, if we see fun elsewhere, we'll delete it from
663 ;; lambda candidate list.
664 (let ((fdata (and (symbolp fun) (assq fun env))))
665 (if fdata
666 (setf (nth 4 fdata) t)
667 (cconv-analyse-form fun env)))
668 (dolist (form args) (cconv-analyse-form form env)))
669
670 (`(interactive . ,forms)
671 ;; These appear within the function body but they don't have access
672 ;; to the function's arguments.
673 ;; We could extend this to allow interactive specs to refer to
674 ;; variables in the function's enclosing environment, but it doesn't
675 ;; seem worth the trouble.
676 (dolist (form forms) (cconv-analyse-form form nil)))
677
678 ;; `declare' should now be macro-expanded away (and if they're not, we're
679 ;; in trouble because they *can* contain code nowadays).
680 ;; (`(declare . ,_) nil) ;The args don't contain code.
681
682 (`(,_ . ,body-forms) ; First element is a function or whatever.
683 (dolist (form body-forms) (cconv-analyse-form form env)))
684
685 ((pred symbolp)
686 (let ((dv (assq form env))) ; dv = declared and visible
687 (when dv
688 (setf (nth 1 dv) t))))))
689
690 (provide 'cconv)
691 ;;; cconv.el ends here