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