Merge branch 'master' into comment-cache
[emacs.git] / lisp / emacs-lisp / cconv.el
blob4507af7a59b38d87b6992cda9e35c779059599f0
1 ;;; cconv.el --- Closure conversion for statically scoped Emacs lisp. -*- lexical-binding: t -*-
3 ;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
5 ;; Author: Igor Kuzmin <kzuminig@iro.umontreal.ca>
6 ;; Maintainer: emacs-devel@gnu.org
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-analyze-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-analyze 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 ...) (fv0 ...) <doc>
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-safe 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 ;; PROBLEM cases found during conversion to lexical binding.
69 ;; We should try and detect and warn about those cases, even
70 ;; for lexical-binding==nil to help prepare the migration.
71 ;; - Uses of run-hooks, and friends.
72 ;; - Cases where we want to apply the same code to different vars depending on
73 ;; some test. These sometimes use a (let ((foo (if bar 'a 'b)))
74 ;; ... (symbol-value foo) ... (set foo ...)).
76 ;; TODO: (not just for cconv but also for the lexbind changes in general)
77 ;; - let (e)debug find the value of lexical variables from the stack.
78 ;; - make eval-region do the eval-sexp-add-defvars dance.
79 ;; - byte-optimize-form should be applied before cconv.
80 ;; OTOH, the warnings emitted by cconv-analyze need to come before optimize
81 ;; since afterwards they can because obnoxious (warnings about an "unused
82 ;; variable" should not be emitted when the variable use has simply been
83 ;; optimized away).
84 ;; - let macros specify that some let-bindings come from the same source,
85 ;; so the unused warning takes all uses into account.
86 ;; - let interactive specs return a function to build the args (to stash into
87 ;; command-history).
88 ;; - canonize code in macro-expand so we don't have to handle (let (var) body)
89 ;; and other oddities.
90 ;; - new byte codes for unwind-protect so that closures aren't needed at all.
91 ;; - a reference to a var that is known statically to always hold a constant
92 ;; should be turned into a byte-constant rather than a byte-stack-ref.
93 ;; Hmm... right, that's called constant propagation and could be done here,
94 ;; but when that constant is a function, we have to be careful to make sure
95 ;; the bytecomp only compiles it once.
96 ;; - Since we know here when a variable is not mutated, we could pass that
97 ;; info to the byte-compiler, e.g. by using a new `immutable-let'.
98 ;; - call known non-escaping functions with `goto' rather than `call'.
99 ;; - optimize mapc to a dolist loop.
101 ;; (defmacro dlet (binders &rest body)
102 ;; ;; Works in both lexical and non-lexical mode.
103 ;; (declare (indent 1) (debug let))
104 ;; `(progn
105 ;; ,@(mapcar (lambda (binder)
106 ;; `(defvar ,(if (consp binder) (car binder) binder)))
107 ;; binders)
108 ;; (let ,binders ,@body)))
110 ;; (defmacro llet (binders &rest body)
111 ;; ;; Only works in lexical-binding mode.
112 ;; `(funcall
113 ;; (lambda ,(mapcar (lambda (binder) (if (consp binder) (car binder) binder))
114 ;; binders)
115 ;; ,@body)
116 ;; ,@(mapcar (lambda (binder) (if (consp binder) (cadr binder)))
117 ;; binders)))
119 (eval-when-compile (require 'cl-lib))
121 (defconst cconv-liftwhen 6
122 "Try to do lambda lifting if the number of arguments + free variables
123 is less than this number.")
124 ;; List of all the variables that are both captured by a closure
125 ;; and mutated. Each entry in the list takes the form
126 ;; (BINDER . PARENTFORM) where BINDER is the (VAR VAL) that introduces the
127 ;; variable (or is just (VAR) for variables not introduced by let).
128 (defvar cconv-captured+mutated)
130 ;; List of candidates for lambda lifting.
131 ;; Each candidate has the form (BINDER . PARENTFORM). A candidate
132 ;; is a variable that is only passed to `funcall' or `apply'.
133 (defvar cconv-lambda-candidates)
135 ;; Alist associating to each function body the list of its free variables.
136 (defvar cconv-freevars-alist)
138 ;;;###autoload
139 (defun cconv-closure-convert (form)
140 "Main entry point for closure conversion.
141 -- FORM is a piece of Elisp code after macroexpansion.
142 -- TOPLEVEL(optional) is a boolean variable, true if we are at the root of AST
144 Returns a form where all lambdas don't have any free variables."
145 ;; (message "Entering cconv-closure-convert...")
146 (let ((cconv-freevars-alist '())
147 (cconv-lambda-candidates '())
148 (cconv-captured+mutated '()))
149 ;; Analyze form - fill these variables with new information.
150 (cconv-analyze-form form '())
151 (setq cconv-freevars-alist (nreverse cconv-freevars-alist))
152 (prog1 (cconv-convert form nil nil) ; Env initially empty.
153 (cl-assert (null cconv-freevars-alist)))))
155 ;;;###autoload
156 (defun cconv-warnings-only (form)
157 "Add the warnings that closure conversion would encounter."
158 (let ((cconv-freevars-alist '())
159 (cconv-lambda-candidates '())
160 (cconv-captured+mutated '()))
161 ;; Analyze form - fill these variables with new information.
162 (cconv-analyze-form form '())
163 ;; But don't perform the closure conversion.
164 form))
166 (defconst cconv--dummy-var (make-symbol "ignored"))
168 (defun cconv--set-diff (s1 s2)
169 "Return elements of set S1 that are not in set S2."
170 (let ((res '()))
171 (dolist (x s1)
172 (unless (memq x s2) (push x res)))
173 (nreverse res)))
175 (defun cconv--set-diff-map (s m)
176 "Return elements of set S that are not in Dom(M)."
177 (let ((res '()))
178 (dolist (x s)
179 (unless (assq x m) (push x res)))
180 (nreverse res)))
182 (defun cconv--map-diff (m1 m2)
183 "Return the submap of map M1 that has Dom(M2) removed."
184 (let ((res '()))
185 (dolist (x m1)
186 (unless (assq (car x) m2) (push x res)))
187 (nreverse res)))
189 (defun cconv--map-diff-elem (m x)
190 "Return the map M minus any mapping for X."
191 ;; Here we assume that X appears at most once in M.
192 (let* ((b (assq x m))
193 (res (if b (remq b m) m)))
194 (cl-assert (null (assq x res))) ;; Check the assumption was warranted.
195 res))
197 (defun cconv--map-diff-set (m s)
198 "Return the map M minus any mapping for elements of S."
199 ;; Here we assume that X appears at most once in M.
200 (let ((res '()))
201 (dolist (b m)
202 (unless (memq (car b) s) (push b res)))
203 (nreverse res)))
205 (defun cconv--convert-function (args body env parentform &optional docstring)
206 (cl-assert (equal body (caar cconv-freevars-alist)))
207 (let* ((fvs (cdr (pop cconv-freevars-alist)))
208 (body-new '())
209 (letbind '())
210 (envector ())
211 (i 0)
212 (new-env ()))
213 ;; Build the "formal and actual envs" for the closure-converted function.
214 (dolist (fv fvs)
215 (let ((exp (or (cdr (assq fv env)) fv)))
216 (pcase exp
217 ;; If `fv' is a variable that's wrapped in a cons-cell,
218 ;; we want to put the cons-cell itself in the closure,
219 ;; rather than just a copy of its current content.
220 (`(car-safe ,iexp . ,_)
221 (push iexp envector)
222 (push `(,fv . (car-safe (internal-get-closed-var ,i))) new-env))
224 (push exp envector)
225 (push `(,fv . (internal-get-closed-var ,i)) new-env))))
226 (setq i (1+ i)))
227 (setq envector (nreverse envector))
228 (setq new-env (nreverse new-env))
230 (dolist (arg args)
231 (if (not (member (cons (list arg) parentform) cconv-captured+mutated))
232 (if (assq arg new-env) (push `(,arg) new-env))
233 (push `(,arg . (car-safe ,arg)) new-env)
234 (push `(,arg (list ,arg)) letbind)))
236 (setq body-new (mapcar (lambda (form)
237 (cconv-convert form new-env nil))
238 body))
240 (when letbind
241 (let ((special-forms '()))
242 ;; Keep special forms at the beginning of the body.
243 (while (or (stringp (car body-new)) ;docstring.
244 (memq (car-safe (car body-new)) '(interactive declare)))
245 (push (pop body-new) special-forms))
246 (setq body-new
247 `(,@(nreverse special-forms) (let ,letbind . ,body-new)))))
249 (cond
250 ((not (or envector docstring)) ;If no freevars - do nothing.
251 `(function (lambda ,args . ,body-new)))
253 `(internal-make-closure
254 ,args ,envector ,docstring . ,body-new)))))
256 (defun cconv--remap-llv (new-env var closedsym)
257 ;; In a case such as:
258 ;; (let* ((fun (lambda (x) (+ x y))) (y 1)) (funcall fun 1))
259 ;; A naive lambda-lifting would return
260 ;; (let* ((fun (lambda (y x) (+ x y))) (y 1)) (funcall fun y 1))
261 ;; Where the external `y' is mistakenly captured by the inner one.
262 ;; So when we detect that case, we rewrite it to:
263 ;; (let* ((closed-y y) (fun (lambda (y x) (+ x y))) (y 1))
264 ;; (funcall fun closed-y 1))
265 ;; We do that even if there's no `funcall' that uses `fun' in the scope
266 ;; where `y' is shadowed by another variable because, to treat
267 ;; this case better, we'd need to traverse the tree one more time to
268 ;; collect this data, and I think that it's not worth it.
269 (mapcar (lambda (mapping)
270 (if (not (eq (cadr mapping) 'apply-partially))
271 mapping
272 (cl-assert (eq (car mapping) (nth 2 mapping)))
273 `(,(car mapping)
274 apply-partially
275 ,(car mapping)
276 ,@(mapcar (lambda (arg)
277 (if (eq var arg)
278 closedsym arg))
279 (nthcdr 3 mapping)))))
280 new-env))
282 (defun cconv-convert (form env extend)
283 ;; This function actually rewrites the tree.
284 "Return FORM with all its lambdas changed so they are closed.
285 ENV is a lexical environment mapping variables to the expression
286 used to get its value. This is used for variables that are copied into
287 closures, moved into cons cells, ...
288 ENV is a list where each entry takes the shape either:
289 (VAR . (car-safe EXP)): VAR has been moved into the car of a cons-cell, and EXP
290 is an expression that evaluates to this cons-cell.
291 (VAR . (internal-get-closed-var N)): VAR has been copied into the closure
292 environment's Nth slot.
293 (VAR . (apply-partially F ARG1 ARG2 ..)): VAR has been λ-lifted and takes
294 additional arguments ARGs.
295 EXTEND is a list of variables which might need to be accessed even from places
296 where they are shadowed, because some part of ENV causes them to be used at
297 places where they originally did not directly appear."
298 (cl-assert (not (delq nil (mapcar (lambda (mapping)
299 (if (eq (cadr mapping) 'apply-partially)
300 (cconv--set-diff (cdr (cddr mapping))
301 extend)))
302 env))))
304 ;; What's the difference between fvrs and envs?
305 ;; Suppose that we have the code
306 ;; (lambda (..) fvr (let ((fvr 1)) (+ fvr 1)))
307 ;; only the first occurrence of fvr should be replaced by
308 ;; (aref env ...).
309 ;; So initially envs and fvrs are the same thing, but when we descend to
310 ;; the 'let, we delete fvr from fvrs. Why we don't delete fvr from envs?
311 ;; Because in envs the order of variables is important. We use this list
312 ;; to find the number of a specific variable in the environment vector,
313 ;; so we never touch it(unless we enter to the other closure).
314 ;;(if (listp form) (print (car form)) form)
315 (pcase form
316 (`(,(and letsym (or `let* `let)) ,binders . ,body)
318 ; let and let* special forms
319 (let ((binders-new '())
320 (new-env env)
321 (new-extend extend))
323 (dolist (binder binders)
324 (let* ((value nil)
325 (var (if (not (consp binder))
326 (prog1 binder (setq binder (list binder)))
327 (when (cddr binder)
328 (byte-compile-warn
329 "Malformed `%S' binding: %S"
330 letsym binder))
331 (setq value (cadr binder))
332 (car binder)))
333 (new-val
334 (cond
335 ;; Check if var is a candidate for lambda lifting.
336 ((and (member (cons binder form) cconv-lambda-candidates)
337 (progn
338 (cl-assert (and (eq (car value) 'function)
339 (eq (car (cadr value)) 'lambda)))
340 (cl-assert (equal (cddr (cadr value))
341 (caar cconv-freevars-alist)))
342 ;; Peek at the freevars to decide whether to λ-lift.
343 (let* ((fvs (cdr (car cconv-freevars-alist)))
344 (fun (cadr value))
345 (funargs (cadr fun))
346 (funcvars (append fvs funargs)))
347 ; lambda lifting condition
348 (and fvs (>= cconv-liftwhen (length funcvars))))))
349 ; Lift.
350 (let* ((fvs (cdr (pop cconv-freevars-alist)))
351 (fun (cadr value))
352 (funargs (cadr fun))
353 (funcvars (append fvs funargs))
354 (funcbody (cddr fun))
355 (funcbody-env ()))
356 (push `(,var . (apply-partially ,var . ,fvs)) new-env)
357 (dolist (fv fvs)
358 (cl-pushnew fv new-extend)
359 (if (and (eq 'car-safe (car-safe (cdr (assq fv env))))
360 (not (memq fv funargs)))
361 (push `(,fv . (car-safe ,fv)) funcbody-env)))
362 `(function (lambda ,funcvars .
363 ,(mapcar (lambda (form)
364 (cconv-convert
365 form funcbody-env nil))
366 funcbody)))))
368 ;; Check if it needs to be turned into a "ref-cell".
369 ((member (cons binder form) cconv-captured+mutated)
370 ;; Declared variable is mutated and captured.
371 (push `(,var . (car-safe ,var)) new-env)
372 `(list ,(cconv-convert value env extend)))
374 ;; Normal default case.
376 (if (assq var new-env) (push `(,var) new-env))
377 (cconv-convert value env extend)))))
379 (when (and (eq letsym 'let*) (memq var new-extend))
380 ;; One of the lambda-lifted vars is shadowed, so add
381 ;; a reference to the outside binding and arrange to use
382 ;; that reference.
383 (let ((closedsym (make-symbol (format "closed-%s" var))))
384 (setq new-env (cconv--remap-llv new-env var closedsym))
385 (setq new-extend (cons closedsym (remq var new-extend)))
386 (push `(,closedsym ,var) binders-new)))
388 ;; We push the element after redefined free variables are
389 ;; processed. This is important to avoid the bug when free
390 ;; variable and the function have the same name.
391 (push (list var new-val) binders-new)
393 (when (eq letsym 'let*)
394 (setq env new-env)
395 (setq extend new-extend))
396 )) ; end of dolist over binders
398 (when (not (eq letsym 'let*))
399 ;; We can't do the cconv--remap-llv at the same place for let and
400 ;; let* because in the case of `let', the shadowing may occur
401 ;; before we know that the var will be in `new-extend' (bug#24171).
402 (dolist (binder binders-new)
403 (when (memq (car-safe binder) new-extend)
404 ;; One of the lambda-lifted vars is shadowed, so add
405 ;; a reference to the outside binding and arrange to use
406 ;; that reference.
407 (let* ((var (car-safe binder))
408 (closedsym (make-symbol (format "closed-%s" var))))
409 (setq new-env (cconv--remap-llv new-env var closedsym))
410 (setq new-extend (cons closedsym (remq var new-extend)))
411 (push `(,closedsym ,var) binders-new)))))
413 `(,letsym ,(nreverse binders-new)
414 . ,(mapcar (lambda (form)
415 (cconv-convert
416 form new-env new-extend))
417 body))))
418 ;end of let let* forms
420 ; first element is lambda expression
421 (`(,(and `(lambda . ,_) fun) . ,args)
422 ;; FIXME: it's silly to create a closure just to call it.
423 ;; Running byte-optimize-form earlier will resolve this.
424 `(funcall
425 ,(cconv-convert `(function ,fun) env extend)
426 ,@(mapcar (lambda (form)
427 (cconv-convert form env extend))
428 args)))
430 (`(cond . ,cond-forms) ; cond special form
431 `(cond . ,(mapcar (lambda (branch)
432 (mapcar (lambda (form)
433 (cconv-convert form env extend))
434 branch))
435 cond-forms)))
437 (`(function (lambda ,args . ,body) . ,_)
438 (let ((docstring (if (eq :documentation (car-safe (car body)))
439 (cconv-convert (cadr (pop body)) env extend))))
440 (cconv--convert-function args body env form docstring)))
442 (`(internal-make-closure . ,_)
443 (byte-compile-report-error
444 "Internal error in compiler: cconv called twice?"))
446 (`(quote . ,_) form)
447 (`(function . ,_) form)
449 ;defconst, defvar
450 (`(,(and sym (or `defconst `defvar)) ,definedsymbol . ,forms)
451 `(,sym ,definedsymbol
452 . ,(mapcar (lambda (form) (cconv-convert form env extend))
453 forms)))
455 ;condition-case
456 ((and `(condition-case ,var ,protected-form . ,handlers)
457 (guard byte-compile--use-old-handlers))
458 (let ((newform (cconv--convert-function
459 () (list protected-form) env form)))
460 `(condition-case :fun-body ,newform
461 ,@(mapcar (lambda (handler)
462 (list (car handler)
463 (cconv--convert-function
464 (list (or var cconv--dummy-var))
465 (cdr handler) env form)))
466 handlers))))
468 ; condition-case with new byte-codes.
469 (`(condition-case ,var ,protected-form . ,handlers)
470 `(condition-case ,var
471 ,(cconv-convert protected-form env extend)
472 ,@(let* ((cm (and var (member (cons (list var) form)
473 cconv-captured+mutated)))
474 (newenv
475 (cond (cm (cons `(,var . (car-save ,var)) env))
476 ((assq var env) (cons `(,var) env))
477 (t env))))
478 (mapcar
479 (lambda (handler)
480 `(,(car handler)
481 ,@(let ((body
482 (mapcar (lambda (form)
483 (cconv-convert form newenv extend))
484 (cdr handler))))
485 (if (not cm) body
486 `((let ((,var (list ,var))) ,@body))))))
487 handlers))))
489 (`(,(and head (or (and `catch (guard byte-compile--use-old-handlers))
490 `unwind-protect))
491 ,form . ,body)
492 `(,head ,(cconv-convert form env extend)
493 :fun-body ,(cconv--convert-function () body env form)))
495 (`(setq . ,forms) ; setq special form
496 (if (= (logand (length forms) 1) 1)
497 ;; With an odd number of args, let bytecomp.el handle the error.
498 form
499 (let ((prognlist ()))
500 (while forms
501 (let* ((sym (pop forms))
502 (sym-new (or (cdr (assq sym env)) sym))
503 (value (cconv-convert (pop forms) env extend)))
504 (push (pcase sym-new
505 ((pred symbolp) `(setq ,sym-new ,value))
506 (`(car-safe ,iexp) `(setcar ,iexp ,value))
507 ;; This "should never happen", but for variables which are
508 ;; mutated+captured+unused, we may end up trying to `setq'
509 ;; on a closed-over variable, so just drop the setq.
510 (_ ;; (byte-compile-report-error
511 ;; (format "Internal error in cconv of (setq %s ..)"
512 ;; sym-new))
513 value))
514 prognlist)))
515 (if (cdr prognlist)
516 `(progn . ,(nreverse prognlist))
517 (car prognlist)))))
519 (`(,(and (or `funcall `apply) callsym) ,fun . ,args)
520 ;; These are not special forms but we treat them separately for the needs
521 ;; of lambda lifting.
522 (let ((mapping (cdr (assq fun env))))
523 (pcase mapping
524 (`(apply-partially ,_ . ,(and fvs `(,_ . ,_)))
525 (cl-assert (eq (cadr mapping) fun))
526 `(,callsym ,fun
527 ,@(mapcar (lambda (fv)
528 (let ((exp (or (cdr (assq fv env)) fv)))
529 (pcase exp
530 (`(car-safe ,iexp . ,_) iexp)
531 (_ exp))))
532 fvs)
533 ,@(mapcar (lambda (arg)
534 (cconv-convert arg env extend))
535 args)))
536 (_ `(,callsym ,@(mapcar (lambda (arg)
537 (cconv-convert arg env extend))
538 (cons fun args)))))))
540 (`(interactive . ,forms)
541 `(interactive . ,(mapcar (lambda (form)
542 (cconv-convert form nil nil))
543 forms)))
545 (`(declare . ,_) form) ;The args don't contain code.
547 (`(,func . ,forms)
548 ;; First element is function or whatever function-like forms are: or, and,
549 ;; if, catch, progn, prog1, prog2, while, until
550 `(,func . ,(mapcar (lambda (form)
551 (cconv-convert form env extend))
552 forms)))
554 (_ (or (cdr (assq form env)) form))))
556 (unless (fboundp 'byte-compile-not-lexical-var-p)
557 ;; Only used to test the code in non-lexbind Emacs.
558 (defalias 'byte-compile-not-lexical-var-p 'boundp))
559 (defvar byte-compile-lexical-variables)
561 (defun cconv--analyze-use (vardata form varkind)
562 "Analyze the use of a variable.
563 VARDATA should be (BINDER READ MUTATED CAPTURED CALLED).
564 VARKIND is the name of the kind of variable.
565 FORM is the parent form that binds this var."
566 ;; use = `(,binder ,read ,mutated ,captured ,called)
567 (pcase vardata
568 (`(,_ nil nil nil nil) nil)
569 (`((,(and var (guard (eq ?_ (aref (symbol-name var) 0)))) . ,_)
570 ,_ ,_ ,_ ,_)
571 (byte-compile-warn
572 "%s `%S' not left unused" varkind var)))
573 (pcase vardata
574 (`((,var . ,_) nil ,_ ,_ nil)
575 ;; FIXME: This gives warnings in the wrong order, with imprecise line
576 ;; numbers and without function name info.
577 (unless (or ;; Uninterned symbols typically come from macro-expansion, so
578 ;; it is often non-trivial for the programmer to avoid such
579 ;; unused vars.
580 (not (intern-soft var))
581 (eq ?_ (aref (symbol-name var) 0))
582 ;; As a special exception, ignore "ignore".
583 (eq var 'ignored))
584 (byte-compile-warn "Unused lexical %s `%S'"
585 varkind var)))
586 ;; If it's unused, there's no point converting it into a cons-cell, even if
587 ;; it's captured and mutated.
588 (`(,binder ,_ t t ,_)
589 (push (cons binder form) cconv-captured+mutated))
590 (`(,(and binder `(,_ (function (lambda . ,_)))) nil nil nil t)
591 (push (cons binder form) cconv-lambda-candidates))))
593 (defun cconv--analyze-function (args body env parentform)
594 (let* ((newvars nil)
595 (freevars (list body))
596 ;; We analyze the body within a new environment where all uses are
597 ;; nil, so we can distinguish uses within that function from uses
598 ;; outside of it.
599 (envcopy
600 (mapcar (lambda (vdata) (list (car vdata) nil nil nil nil)) env))
601 (byte-compile-bound-variables byte-compile-bound-variables)
602 (newenv envcopy))
603 ;; Push it before recursing, so cconv-freevars-alist contains entries in
604 ;; the order they'll be used by closure-convert-rec.
605 (push freevars cconv-freevars-alist)
606 (dolist (arg args)
607 (cond
608 ((byte-compile-not-lexical-var-p arg)
609 (byte-compile-warn
610 "Lexical argument shadows the dynamic variable %S"
611 arg))
612 ((eq ?& (aref (symbol-name arg) 0)) nil) ;Ignore &rest, &optional, ...
613 (t (let ((varstruct (list arg nil nil nil nil)))
614 (cl-pushnew arg byte-compile-lexical-variables)
615 (push (cons (list arg) (cdr varstruct)) newvars)
616 (push varstruct newenv)))))
617 (dolist (form body) ;Analyze body forms.
618 (cconv-analyze-form form newenv))
619 ;; Summarize resulting data about arguments.
620 (dolist (vardata newvars)
621 (cconv--analyze-use vardata parentform "argument"))
622 ;; Transfer uses collected in `envcopy' (via `newenv') back to `env';
623 ;; and compute free variables.
624 (while env
625 (cl-assert (and envcopy (eq (caar env) (caar envcopy))))
626 (let ((free nil)
627 (x (cdr (car env)))
628 (y (cdr (car envcopy))))
629 (while x
630 (when (car y) (setcar x t) (setq free t))
631 (setq x (cdr x) y (cdr y)))
632 (when free
633 (push (caar env) (cdr freevars))
634 (setf (nth 3 (car env)) t))
635 (setq env (cdr env) envcopy (cdr envcopy))))))
637 (defun cconv-analyze-form (form env)
638 "Find mutated variables and variables captured by closure.
639 Analyze lambdas if they are suitable for lambda lifting.
640 - FORM is a piece of Elisp code after macroexpansion.
641 - ENV is an alist mapping each enclosing lexical variable to its info.
642 I.e. each element has the form (VAR . (READ MUTATED CAPTURED CALLED)).
643 This function does not return anything but instead fills the
644 `cconv-captured+mutated' and `cconv-lambda-candidates' variables
645 and updates the data stored in ENV."
646 (pcase form
647 ; let special form
648 (`(,(and (or `let* `let) letsym) ,binders . ,body-forms)
650 (let ((orig-env env)
651 (newvars nil)
652 (var nil)
653 (byte-compile-bound-variables byte-compile-bound-variables)
654 (value nil))
655 (dolist (binder binders)
656 (if (not (consp binder))
657 (progn
658 (setq var binder) ; treat the form (let (x) ...) well
659 (setq binder (list binder))
660 (setq value nil))
661 (setq var (car binder))
662 (setq value (cadr binder))
664 (cconv-analyze-form value (if (eq letsym 'let*) env orig-env)))
666 (unless (byte-compile-not-lexical-var-p var)
667 (cl-pushnew var byte-compile-lexical-variables)
668 (let ((varstruct (list var nil nil nil nil)))
669 (push (cons binder (cdr varstruct)) newvars)
670 (push varstruct env))))
672 (dolist (form body-forms) ; Analyze body forms.
673 (cconv-analyze-form form env))
675 (dolist (vardata newvars)
676 (cconv--analyze-use vardata form "variable"))))
678 (`(function (lambda ,vrs . ,body-forms))
679 (when (eq :documentation (car-safe (car body-forms)))
680 (cconv-analyze-form (cadr (pop body-forms)) env))
681 (cconv--analyze-function vrs body-forms env form))
683 (`(setq . ,forms)
684 ;; If a local variable (member of env) is modified by setq then
685 ;; it is a mutated variable.
686 (while forms
687 (let ((v (assq (car forms) env))) ; v = non nil if visible
688 (when v (setf (nth 2 v) t)))
689 (cconv-analyze-form (cadr forms) env)
690 (setq forms (cddr forms))))
692 (`((lambda . ,_) . ,_) ; First element is lambda expression.
693 (byte-compile-warn
694 "Use of deprecated ((lambda %s ...) ...) form" (nth 1 (car form)))
695 (dolist (exp `((function ,(car form)) . ,(cdr form)))
696 (cconv-analyze-form exp env)))
698 (`(cond . ,cond-forms) ; cond special form
699 (dolist (forms cond-forms)
700 (dolist (form forms) (cconv-analyze-form form env))))
702 ;; ((and `(quote ,v . ,_) (guard (assq v env)))
703 ;; (byte-compile-warn
704 ;; "Possible confusion variable/symbol for `%S'" v))
706 (`(quote . ,_) nil) ; quote form
707 (`(function . ,_) nil) ; same as quote
709 ((and `(condition-case ,var ,protected-form . ,handlers)
710 (guard byte-compile--use-old-handlers))
711 ;; FIXME: The bytecode for condition-case forces us to wrap the
712 ;; form and handlers in closures.
713 (cconv--analyze-function () (list protected-form) env form)
714 (dolist (handler handlers)
715 (cconv--analyze-function (if var (list var)) (cdr handler)
716 env form)))
718 (`(condition-case ,var ,protected-form . ,handlers)
719 (cconv-analyze-form protected-form env)
720 (when (and var (symbolp var) (byte-compile-not-lexical-var-p var))
721 (byte-compile-warn
722 "Lexical variable shadows the dynamic variable %S" var))
723 (let* ((varstruct (list var nil nil nil nil)))
724 (if var (push varstruct env))
725 (dolist (handler handlers)
726 (dolist (form (cdr handler))
727 (cconv-analyze-form form env)))
728 (if var (cconv--analyze-use (cons (list var) (cdr varstruct))
729 form "variable"))))
731 ;; FIXME: The bytecode for unwind-protect forces us to wrap the unwind.
732 (`(,(or (and `catch (guard byte-compile--use-old-handlers))
733 `unwind-protect)
734 ,form . ,body)
735 (cconv-analyze-form form env)
736 (cconv--analyze-function () body env form))
738 (`(defvar ,var) (push var byte-compile-bound-variables))
739 (`(,(or `defconst `defvar) ,var ,value . ,_)
740 (push var byte-compile-bound-variables)
741 (cconv-analyze-form value env))
743 (`(,(or `funcall `apply) ,fun . ,args)
744 ;; Here we ignore fun because funcall and apply are the only two
745 ;; functions where we can pass a candidate for lambda lifting as
746 ;; argument. So, if we see fun elsewhere, we'll delete it from
747 ;; lambda candidate list.
748 (let ((fdata (and (symbolp fun) (assq fun env))))
749 (if fdata
750 (setf (nth 4 fdata) t)
751 (cconv-analyze-form fun env)))
752 (dolist (form args) (cconv-analyze-form form env)))
754 (`(interactive . ,forms)
755 ;; These appear within the function body but they don't have access
756 ;; to the function's arguments.
757 ;; We could extend this to allow interactive specs to refer to
758 ;; variables in the function's enclosing environment, but it doesn't
759 ;; seem worth the trouble.
760 (dolist (form forms) (cconv-analyze-form form nil)))
762 ;; `declare' should now be macro-expanded away (and if they're not, we're
763 ;; in trouble because they *can* contain code nowadays).
764 ;; (`(declare . ,_) nil) ;The args don't contain code.
766 (`(,_ . ,body-forms) ; First element is a function or whatever.
767 (dolist (form body-forms) (cconv-analyze-form form env)))
769 ((pred symbolp)
770 (let ((dv (assq form env))) ; dv = declared and visible
771 (when dv
772 (setf (nth 1 dv) t))))))
773 (define-obsolete-function-alias 'cconv-analyse-form 'cconv-analyze-form "25.1")
775 (provide 'cconv)
776 ;;; cconv.el ends here