]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/cconv.el
Add new function dom-remove-node
[gnu-emacs] / lisp / emacs-lisp / cconv.el
1 ;;; cconv.el --- Closure conversion for statically scoped Emacs lisp. -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2011-2016 Free Software Foundation, Inc.
4
5 ;; Author: Igor Kuzmin <kzuminig@iro.umontreal.ca>
6 ;; Maintainer: emacs-devel@gnu.org
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-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.
37 ;;
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.
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 ...) (fv0 ...) <doc>
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-safe 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 ;; 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 ...)).
75
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.
100
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)))
109
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)))
118
119 (eval-when-compile (require 'cl-lib))
120
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)
129
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)
134
135 ;; Alist associating to each function body the list of its free variables.
136 (defvar cconv-freevars-alist)
137
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
143
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)))))
154
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))
165
166 (defconst cconv--dummy-var (make-symbol "ignored"))
167
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)))
174
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)))
181
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)))
188
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))
196
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)))
204
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))
223 (_
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))
229
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)))
235
236 (setq body-new (mapcar (lambda (form)
237 (cconv-convert form new-env nil))
238 body))
239
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)))))
248
249 (cond
250 ((not (or envector docstring)) ;If no freevars - do nothing.
251 `(function (lambda ,args . ,body-new)))
252 (t
253 `(internal-make-closure
254 ,args ,envector ,docstring . ,body-new)))))
255
256 (defun cconv-convert (form env extend)
257 ;; This function actually rewrites the tree.
258 "Return FORM with all its lambdas changed so they are closed.
259 ENV is a lexical environment mapping variables to the expression
260 used to get its value. This is used for variables that are copied into
261 closures, moved into cons cells, ...
262 ENV is a list where each entry takes the shape either:
263 (VAR . (car-safe EXP)): VAR has been moved into the car of a cons-cell, and EXP
264 is an expression that evaluates to this cons-cell.
265 (VAR . (internal-get-closed-var N)): VAR has been copied into the closure
266 environment's Nth slot.
267 (VAR . (apply-partially F ARG1 ARG2 ..)): VAR has been λ-lifted and takes
268 additional arguments ARGs.
269 EXTEND is a list of variables which might need to be accessed even from places
270 where they are shadowed, because some part of ENV causes them to be used at
271 places where they originally did not directly appear."
272 (cl-assert (not (delq nil (mapcar (lambda (mapping)
273 (if (eq (cadr mapping) 'apply-partially)
274 (cconv--set-diff (cdr (cddr mapping))
275 extend)))
276 env))))
277
278 ;; What's the difference between fvrs and envs?
279 ;; Suppose that we have the code
280 ;; (lambda (..) fvr (let ((fvr 1)) (+ fvr 1)))
281 ;; only the first occurrence of fvr should be replaced by
282 ;; (aref env ...).
283 ;; So initially envs and fvrs are the same thing, but when we descend to
284 ;; the 'let, we delete fvr from fvrs. Why we don't delete fvr from envs?
285 ;; Because in envs the order of variables is important. We use this list
286 ;; to find the number of a specific variable in the environment vector,
287 ;; so we never touch it(unless we enter to the other closure).
288 ;;(if (listp form) (print (car form)) form)
289 (pcase form
290 (`(,(and letsym (or `let* `let)) ,binders . ,body)
291
292 ; let and let* special forms
293 (let ((binders-new '())
294 (new-env env)
295 (new-extend extend))
296
297 (dolist (binder binders)
298 (let* ((value nil)
299 (var (if (not (consp binder))
300 (prog1 binder (setq binder (list binder)))
301 (when (cddr binder)
302 (byte-compile-log-warning
303 (format-message "Malformed `%S' binding: %S"
304 letsym binder)))
305 (setq value (cadr binder))
306 (car binder)))
307 (new-val
308 (cond
309 ;; Check if var is a candidate for lambda lifting.
310 ((and (member (cons binder form) cconv-lambda-candidates)
311 (progn
312 (cl-assert (and (eq (car value) 'function)
313 (eq (car (cadr value)) 'lambda)))
314 (cl-assert (equal (cddr (cadr value))
315 (caar cconv-freevars-alist)))
316 ;; Peek at the freevars to decide whether to λ-lift.
317 (let* ((fvs (cdr (car cconv-freevars-alist)))
318 (fun (cadr value))
319 (funargs (cadr fun))
320 (funcvars (append fvs funargs)))
321 ; lambda lifting condition
322 (and fvs (>= cconv-liftwhen (length funcvars))))))
323 ; Lift.
324 (let* ((fvs (cdr (pop cconv-freevars-alist)))
325 (fun (cadr value))
326 (funargs (cadr fun))
327 (funcvars (append fvs funargs))
328 (funcbody (cddr fun))
329 (funcbody-env ()))
330 (push `(,var . (apply-partially ,var . ,fvs)) new-env)
331 (dolist (fv fvs)
332 (cl-pushnew fv new-extend)
333 (if (and (eq 'car-safe (car-safe (cdr (assq fv env))))
334 (not (memq fv funargs)))
335 (push `(,fv . (car-safe ,fv)) funcbody-env)))
336 `(function (lambda ,funcvars .
337 ,(mapcar (lambda (form)
338 (cconv-convert
339 form funcbody-env nil))
340 funcbody)))))
341
342 ;; Check if it needs to be turned into a "ref-cell".
343 ((member (cons binder form) cconv-captured+mutated)
344 ;; Declared variable is mutated and captured.
345 (push `(,var . (car-safe ,var)) new-env)
346 `(list ,(cconv-convert value env extend)))
347
348 ;; Normal default case.
349 (t
350 (if (assq var new-env) (push `(,var) new-env))
351 (cconv-convert value env extend)))))
352
353 ;; The piece of code below letbinds free variables of a λ-lifted
354 ;; function if they are redefined in this let, example:
355 ;; (let* ((fun (lambda (x) (+ x y))) (y 1)) (funcall fun 1))
356 ;; Here we can not pass y as parameter because it is redefined.
357 ;; So we add a (closed-y y) declaration. We do that even if the
358 ;; function is not used inside this let(*). The reason why we
359 ;; ignore this case is that we can't "look forward" to see if the
360 ;; function is called there or not. To treat this case better we'd
361 ;; need to traverse the tree one more time to collect this data, and
362 ;; I think that it's not worth it.
363 (when (memq var new-extend)
364 (let ((closedsym
365 (make-symbol (concat "closed-" (symbol-name var)))))
366 (setq new-env
367 (mapcar (lambda (mapping)
368 (if (not (eq (cadr mapping) 'apply-partially))
369 mapping
370 (cl-assert (eq (car mapping) (nth 2 mapping)))
371 `(,(car mapping)
372 apply-partially
373 ,(car mapping)
374 ,@(mapcar (lambda (arg)
375 (if (eq var arg)
376 closedsym arg))
377 (nthcdr 3 mapping)))))
378 new-env))
379 (setq new-extend (remq var new-extend))
380 (push closedsym new-extend)
381 (push `(,closedsym ,var) binders-new)))
382
383 ;; We push the element after redefined free variables are
384 ;; processed. This is important to avoid the bug when free
385 ;; variable and the function have the same name.
386 (push (list var new-val) binders-new)
387
388 (when (eq letsym 'let*)
389 (setq env new-env)
390 (setq extend new-extend))
391 )) ; end of dolist over binders
392
393 `(,letsym ,(nreverse binders-new)
394 . ,(mapcar (lambda (form)
395 (cconv-convert
396 form new-env new-extend))
397 body))))
398 ;end of let let* forms
399
400 ; first element is lambda expression
401 (`(,(and `(lambda . ,_) fun) . ,args)
402 ;; FIXME: it's silly to create a closure just to call it.
403 ;; Running byte-optimize-form earlier will resolve this.
404 `(funcall
405 ,(cconv-convert `(function ,fun) env extend)
406 ,@(mapcar (lambda (form)
407 (cconv-convert form env extend))
408 args)))
409
410 (`(cond . ,cond-forms) ; cond special form
411 `(cond . ,(mapcar (lambda (branch)
412 (mapcar (lambda (form)
413 (cconv-convert form env extend))
414 branch))
415 cond-forms)))
416
417 (`(function (lambda ,args . ,body) . ,_)
418 (let ((docstring (if (eq :documentation (car-safe (car body)))
419 (cconv-convert (cadr (pop body)) env extend))))
420 (cconv--convert-function args body env form docstring)))
421
422 (`(internal-make-closure . ,_)
423 (byte-compile-report-error
424 "Internal error in compiler: cconv called twice?"))
425
426 (`(quote . ,_) form)
427 (`(function . ,_) form)
428
429 ;defconst, defvar
430 (`(,(and sym (or `defconst `defvar)) ,definedsymbol . ,forms)
431 `(,sym ,definedsymbol
432 . ,(mapcar (lambda (form) (cconv-convert form env extend))
433 forms)))
434
435 ;condition-case
436 ((and `(condition-case ,var ,protected-form . ,handlers)
437 (guard byte-compile--use-old-handlers))
438 (let ((newform (cconv--convert-function
439 () (list protected-form) env form)))
440 `(condition-case :fun-body ,newform
441 ,@(mapcar (lambda (handler)
442 (list (car handler)
443 (cconv--convert-function
444 (list (or var cconv--dummy-var))
445 (cdr handler) env form)))
446 handlers))))
447
448 ; condition-case with new byte-codes.
449 (`(condition-case ,var ,protected-form . ,handlers)
450 `(condition-case ,var
451 ,(cconv-convert protected-form env extend)
452 ,@(let* ((cm (and var (member (cons (list var) form)
453 cconv-captured+mutated)))
454 (newenv
455 (cond (cm (cons `(,var . (car-save ,var)) env))
456 ((assq var env) (cons `(,var) env))
457 (t env))))
458 (mapcar
459 (lambda (handler)
460 `(,(car handler)
461 ,@(let ((body
462 (mapcar (lambda (form)
463 (cconv-convert form newenv extend))
464 (cdr handler))))
465 (if (not cm) body
466 `((let ((,var (list ,var))) ,@body))))))
467 handlers))))
468
469 (`(,(and head (or (and `catch (guard byte-compile--use-old-handlers))
470 `unwind-protect))
471 ,form . ,body)
472 `(,head ,(cconv-convert form env extend)
473 :fun-body ,(cconv--convert-function () body env form)))
474
475 (`(setq . ,forms) ; setq special form
476 (if (= (logand (length forms) 1) 1)
477 ;; With an odd number of args, let bytecomp.el handle the error.
478 form
479 (let ((prognlist ()))
480 (while forms
481 (let* ((sym (pop forms))
482 (sym-new (or (cdr (assq sym env)) sym))
483 (value (cconv-convert (pop forms) env extend)))
484 (push (pcase sym-new
485 ((pred symbolp) `(setq ,sym-new ,value))
486 (`(car-safe ,iexp) `(setcar ,iexp ,value))
487 ;; This "should never happen", but for variables which are
488 ;; mutated+captured+unused, we may end up trying to `setq'
489 ;; on a closed-over variable, so just drop the setq.
490 (_ ;; (byte-compile-report-error
491 ;; (format "Internal error in cconv of (setq %s ..)"
492 ;; sym-new))
493 value))
494 prognlist)))
495 (if (cdr prognlist)
496 `(progn . ,(nreverse prognlist))
497 (car prognlist)))))
498
499 (`(,(and (or `funcall `apply) callsym) ,fun . ,args)
500 ;; These are not special forms but we treat them separately for the needs
501 ;; of lambda lifting.
502 (let ((mapping (cdr (assq fun env))))
503 (pcase mapping
504 (`(apply-partially ,_ . ,(and fvs `(,_ . ,_)))
505 (cl-assert (eq (cadr mapping) fun))
506 `(,callsym ,fun
507 ,@(mapcar (lambda (fv)
508 (let ((exp (or (cdr (assq fv env)) fv)))
509 (pcase exp
510 (`(car-safe ,iexp . ,_) iexp)
511 (_ exp))))
512 fvs)
513 ,@(mapcar (lambda (arg)
514 (cconv-convert arg env extend))
515 args)))
516 (_ `(,callsym ,@(mapcar (lambda (arg)
517 (cconv-convert arg env extend))
518 (cons fun args)))))))
519
520 (`(interactive . ,forms)
521 `(interactive . ,(mapcar (lambda (form)
522 (cconv-convert form nil nil))
523 forms)))
524
525 (`(declare . ,_) form) ;The args don't contain code.
526
527 (`(,func . ,forms)
528 ;; First element is function or whatever function-like forms are: or, and,
529 ;; if, catch, progn, prog1, prog2, while, until
530 `(,func . ,(mapcar (lambda (form)
531 (cconv-convert form env extend))
532 forms)))
533
534 (_ (or (cdr (assq form env)) form))))
535
536 (unless (fboundp 'byte-compile-not-lexical-var-p)
537 ;; Only used to test the code in non-lexbind Emacs.
538 (defalias 'byte-compile-not-lexical-var-p 'boundp))
539 (defvar byte-compile-lexical-variables)
540
541 (defun cconv--analyze-use (vardata form varkind)
542 "Analyze the use of a variable.
543 VARDATA should be (BINDER READ MUTATED CAPTURED CALLED).
544 VARKIND is the name of the kind of variable.
545 FORM is the parent form that binds this var."
546 ;; use = `(,binder ,read ,mutated ,captured ,called)
547 (pcase vardata
548 (`(,_ nil nil nil nil) nil)
549 (`((,(and var (guard (eq ?_ (aref (symbol-name var) 0)))) . ,_)
550 ,_ ,_ ,_ ,_)
551 (byte-compile-log-warning
552 (format-message "%s `%S' not left unused" varkind var))))
553 (pcase vardata
554 (`((,var . ,_) nil ,_ ,_ nil)
555 ;; FIXME: This gives warnings in the wrong order, with imprecise line
556 ;; numbers and without function name info.
557 (unless (or ;; Uninterned symbols typically come from macro-expansion, so
558 ;; it is often non-trivial for the programmer to avoid such
559 ;; unused vars.
560 (not (intern-soft var))
561 (eq ?_ (aref (symbol-name var) 0))
562 ;; As a special exception, ignore "ignore".
563 (eq var 'ignored))
564 (byte-compile-log-warning (format-message "Unused lexical %s `%S'"
565 varkind var))))
566 ;; If it's unused, there's no point converting it into a cons-cell, even if
567 ;; it's captured and mutated.
568 (`(,binder ,_ t t ,_)
569 (push (cons binder form) cconv-captured+mutated))
570 (`(,(and binder `(,_ (function (lambda . ,_)))) nil nil nil t)
571 (push (cons binder form) cconv-lambda-candidates))))
572
573 (defun cconv--analyze-function (args body env parentform)
574 (let* ((newvars nil)
575 (freevars (list body))
576 ;; We analyze the body within a new environment where all uses are
577 ;; nil, so we can distinguish uses within that function from uses
578 ;; outside of it.
579 (envcopy
580 (mapcar (lambda (vdata) (list (car vdata) nil nil nil nil)) env))
581 (byte-compile-bound-variables byte-compile-bound-variables)
582 (newenv envcopy))
583 ;; Push it before recursing, so cconv-freevars-alist contains entries in
584 ;; the order they'll be used by closure-convert-rec.
585 (push freevars cconv-freevars-alist)
586 (dolist (arg args)
587 (cond
588 ((byte-compile-not-lexical-var-p arg)
589 (byte-compile-log-warning
590 (format "Lexical argument shadows the dynamic variable %S"
591 arg)))
592 ((eq ?& (aref (symbol-name arg) 0)) nil) ;Ignore &rest, &optional, ...
593 (t (let ((varstruct (list arg nil nil nil nil)))
594 (cl-pushnew arg byte-compile-lexical-variables)
595 (push (cons (list arg) (cdr varstruct)) newvars)
596 (push varstruct newenv)))))
597 (dolist (form body) ;Analyze body forms.
598 (cconv-analyze-form form newenv))
599 ;; Summarize resulting data about arguments.
600 (dolist (vardata newvars)
601 (cconv--analyze-use vardata parentform "argument"))
602 ;; Transfer uses collected in `envcopy' (via `newenv') back to `env';
603 ;; and compute free variables.
604 (while env
605 (cl-assert (and envcopy (eq (caar env) (caar envcopy))))
606 (let ((free nil)
607 (x (cdr (car env)))
608 (y (cdr (car envcopy))))
609 (while x
610 (when (car y) (setcar x t) (setq free t))
611 (setq x (cdr x) y (cdr y)))
612 (when free
613 (push (caar env) (cdr freevars))
614 (setf (nth 3 (car env)) t))
615 (setq env (cdr env) envcopy (cdr envcopy))))))
616
617 (defun cconv-analyze-form (form env)
618 "Find mutated variables and variables captured by closure.
619 Analyze lambdas if they are suitable for lambda lifting.
620 - FORM is a piece of Elisp code after macroexpansion.
621 - ENV is an alist mapping each enclosing lexical variable to its info.
622 I.e. each element has the form (VAR . (READ MUTATED CAPTURED CALLED)).
623 This function does not return anything but instead fills the
624 `cconv-captured+mutated' and `cconv-lambda-candidates' variables
625 and updates the data stored in ENV."
626 (pcase form
627 ; let special form
628 (`(,(and (or `let* `let) letsym) ,binders . ,body-forms)
629
630 (let ((orig-env env)
631 (newvars nil)
632 (var nil)
633 (byte-compile-bound-variables byte-compile-bound-variables)
634 (value nil))
635 (dolist (binder binders)
636 (if (not (consp binder))
637 (progn
638 (setq var binder) ; treat the form (let (x) ...) well
639 (setq binder (list binder))
640 (setq value nil))
641 (setq var (car binder))
642 (setq value (cadr binder))
643
644 (cconv-analyze-form value (if (eq letsym 'let*) env orig-env)))
645
646 (unless (byte-compile-not-lexical-var-p var)
647 (cl-pushnew var byte-compile-lexical-variables)
648 (let ((varstruct (list var nil nil nil nil)))
649 (push (cons binder (cdr varstruct)) newvars)
650 (push varstruct env))))
651
652 (dolist (form body-forms) ; Analyze body forms.
653 (cconv-analyze-form form env))
654
655 (dolist (vardata newvars)
656 (cconv--analyze-use vardata form "variable"))))
657
658 (`(function (lambda ,vrs . ,body-forms))
659 (when (eq :documentation (car-safe (car body-forms)))
660 (cconv-analyze-form (cadr (pop body-forms)) env))
661 (cconv--analyze-function vrs body-forms env form))
662
663 (`(setq . ,forms)
664 ;; If a local variable (member of env) is modified by setq then
665 ;; it is a mutated variable.
666 (while forms
667 (let ((v (assq (car forms) env))) ; v = non nil if visible
668 (when v (setf (nth 2 v) t)))
669 (cconv-analyze-form (cadr forms) env)
670 (setq forms (cddr forms))))
671
672 (`((lambda . ,_) . ,_) ; First element is lambda expression.
673 (byte-compile-log-warning
674 (format "Use of deprecated ((lambda %s ...) ...) form" (nth 1 (car form)))
675 t :warning)
676 (dolist (exp `((function ,(car form)) . ,(cdr form)))
677 (cconv-analyze-form exp env)))
678
679 (`(cond . ,cond-forms) ; cond special form
680 (dolist (forms cond-forms)
681 (dolist (form forms) (cconv-analyze-form form env))))
682
683 ;; ((and `(quote ,v . ,_) (guard (assq v env)))
684 ;; (byte-compile-log-warning
685 ;; (format-message "Possible confusion variable/symbol for `%S'" v)))
686
687 (`(quote . ,_) nil) ; quote form
688 (`(function . ,_) nil) ; same as quote
689
690 ((and `(condition-case ,var ,protected-form . ,handlers)
691 (guard byte-compile--use-old-handlers))
692 ;; FIXME: The bytecode for condition-case forces us to wrap the
693 ;; form and handlers in closures.
694 (cconv--analyze-function () (list protected-form) env form)
695 (dolist (handler handlers)
696 (cconv--analyze-function (if var (list var)) (cdr handler)
697 env form)))
698
699 (`(condition-case ,var ,protected-form . ,handlers)
700 (cconv-analyze-form protected-form env)
701 (when (and var (symbolp var) (byte-compile-not-lexical-var-p var))
702 (byte-compile-log-warning
703 (format "Lexical variable shadows the dynamic variable %S" var)))
704 (let* ((varstruct (list var nil nil nil nil)))
705 (if var (push varstruct env))
706 (dolist (handler handlers)
707 (dolist (form (cdr handler))
708 (cconv-analyze-form form env)))
709 (if var (cconv--analyze-use (cons (list var) (cdr varstruct))
710 form "variable"))))
711
712 ;; FIXME: The bytecode for unwind-protect forces us to wrap the unwind.
713 (`(,(or (and `catch (guard byte-compile--use-old-handlers))
714 `unwind-protect)
715 ,form . ,body)
716 (cconv-analyze-form form env)
717 (cconv--analyze-function () body env form))
718
719 (`(defvar ,var) (push var byte-compile-bound-variables))
720 (`(,(or `defconst `defvar) ,var ,value . ,_)
721 (push var byte-compile-bound-variables)
722 (cconv-analyze-form value env))
723
724 (`(,(or `funcall `apply) ,fun . ,args)
725 ;; Here we ignore fun because funcall and apply are the only two
726 ;; functions where we can pass a candidate for lambda lifting as
727 ;; argument. So, if we see fun elsewhere, we'll delete it from
728 ;; lambda candidate list.
729 (let ((fdata (and (symbolp fun) (assq fun env))))
730 (if fdata
731 (setf (nth 4 fdata) t)
732 (cconv-analyze-form fun env)))
733 (dolist (form args) (cconv-analyze-form form env)))
734
735 (`(interactive . ,forms)
736 ;; These appear within the function body but they don't have access
737 ;; to the function's arguments.
738 ;; We could extend this to allow interactive specs to refer to
739 ;; variables in the function's enclosing environment, but it doesn't
740 ;; seem worth the trouble.
741 (dolist (form forms) (cconv-analyze-form form nil)))
742
743 ;; `declare' should now be macro-expanded away (and if they're not, we're
744 ;; in trouble because they *can* contain code nowadays).
745 ;; (`(declare . ,_) nil) ;The args don't contain code.
746
747 (`(,_ . ,body-forms) ; First element is a function or whatever.
748 (dolist (form body-forms) (cconv-analyze-form form env)))
749
750 ((pred symbolp)
751 (let ((dv (assq form env))) ; dv = declared and visible
752 (when dv
753 (setf (nth 1 dv) t))))))
754 (define-obsolete-function-alias 'cconv-analyse-form 'cconv-analyze-form "25.1")
755
756 (provide 'cconv)
757 ;;; cconv.el ends here