* fileio.c (Finsert_file_contents): Undo previous change.
[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
c7015153 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.
c7015153 33;; Firstly, we analyze the tree by calling cconv-analyse-form.
d779e73c 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 37;;
c7015153 38;; Then we calculate the intersection of the first and third lists returned by
d779e73c
SM
39;; cconv-analyse form to find all mutated variables that are captured by
40;; closure.
94d11cb5 41
d779e73c 42;; Armed with this data, we call cconv-closure-convert-rec, that rewrites the
c7015153 43;; tree recursively, 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.
7200d79c 70;; - make eval-region do the eval-sexp-add-defvars danse.
e2abe5a1 71;; - byte-optimize-form should be applied before cconv.
ca105506
SM
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).
7200d79c
SM
76;; - turn defun and defmacro into macros (and remove special handling of
77;; `declare' afterwards).
78;; - let macros specify that some let-bindings come from the same source,
79;; so the unused warning takes all uses into account.
80;; - let interactive specs return a function to build the args (to stash into
81;; command-history).
cb9336bd
SM
82;; - canonize code in macro-expand so we don't have to handle (let (var) body)
83;; and other oddities.
3e21b6a7
SM
84;; - new byte codes for unwind-protect, catch, and condition-case so that
85;; closures aren't needed at all.
7200d79c 86;; - inline source code of different binding mode by first compiling it.
d032d5e7
SM
87;; - a reference to a var that is known statically to always hold a constant
88;; should be turned into a byte-constant rather than a byte-stack-ref.
e2abe5a1
SM
89;; Hmm... right, that's called constant propagation and could be done here,
90;; but when that constant is a function, we have to be careful to make sure
d032d5e7
SM
91;; the bytecomp only compiles it once.
92;; - Since we know here when a variable is not mutated, we could pass that
93;; info to the byte-compiler, e.g. by using a new `immutable-let'.
e2abe5a1 94;; - add tail-calls to bytecode.c and the byte compiler.
29a4dcb0 95;; - call known non-escaping functions with `goto' rather than `call'.
6c075cd7 96;; - optimize mapcar to a while loop.
d032d5e7
SM
97
98;; (defmacro dlet (binders &rest body)
99;; ;; Works in both lexical and non-lexical mode.
100;; `(progn
101;; ,@(mapcar (lambda (binder)
102;; `(defvar ,(if (consp binder) (car binder) binder)))
103;; binders)
104;; (let ,binders ,@body)))
105
106;; (defmacro llet (binders &rest body)
107;; ;; Only works in lexical-binding mode.
108;; `(funcall
109;; (lambda ,(mapcar (lambda (binder) (if (consp binder) (car binder) binder))
110;; binders)
111;; ,@body)
112;; ,@(mapcar (lambda (binder) (if (consp binder) (cadr binder)))
113;; binders)))
114
94d11cb5
IK
115(eval-when-compile (require 'cl))
116
d032d5e7 117(defconst cconv-liftwhen 6
d779e73c 118 "Try to do lambda lifting if the number of arguments + free variables
94d11cb5 119is less than this number.")
a9de04fa
SM
120;; List of all the variables that are both captured by a closure
121;; and mutated. Each entry in the list takes the form
122;; (BINDER . PARENTFORM) where BINDER is the (VAR VAL) that introduces the
123;; variable (or is just (VAR) for variables not introduced by let).
124(defvar cconv-captured+mutated)
d779e73c 125
a9de04fa
SM
126;; List of candidates for lambda lifting.
127;; Each candidate has the form (BINDER . PARENTFORM). A candidate
128;; is a variable that is only passed to `funcall' or `apply'.
129(defvar cconv-lambda-candidates)
d779e73c 130
a9de04fa
SM
131;; Alist associating to each function body the list of its free variables.
132(defvar cconv-freevars-alist)
94d11cb5
IK
133
134;;;###autoload
295fb2ac
SM
135(defun cconv-closure-convert (form)
136 "Main entry point for closure conversion.
94d11cb5
IK
137-- FORM is a piece of Elisp code after macroexpansion.
138-- TOPLEVEL(optional) is a boolean variable, true if we are at the root of AST
139
140Returns a form where all lambdas don't have any free variables."
b38b1ec0 141 ;; (message "Entering cconv-closure-convert...")
a9de04fa 142 (let ((cconv-freevars-alist '())
94d11cb5 143 (cconv-lambda-candidates '())
d779e73c 144 (cconv-captured+mutated '()))
c7015153 145 ;; Analyze form - fill these variables with new information.
a9de04fa
SM
146 (cconv-analyse-form form '())
147 (setq cconv-freevars-alist (nreverse cconv-freevars-alist))
6c075cd7 148 (cconv-convert form nil nil))) ; Env initially empty.
94d11cb5 149
295fb2ac 150(defconst cconv--dummy-var (make-symbol "ignored"))
b38b1ec0
SM
151
152(defun cconv--set-diff (s1 s2)
153 "Return elements of set S1 that are not in set S2."
154 (let ((res '()))
155 (dolist (x s1)
156 (unless (memq x s2) (push x res)))
157 (nreverse res)))
158
159(defun cconv--set-diff-map (s m)
160 "Return elements of set S that are not in Dom(M)."
161 (let ((res '()))
162 (dolist (x s)
163 (unless (assq x m) (push x res)))
164 (nreverse res)))
165
166(defun cconv--map-diff (m1 m2)
167 "Return the submap of map M1 that has Dom(M2) removed."
168 (let ((res '()))
169 (dolist (x m1)
170 (unless (assq (car x) m2) (push x res)))
171 (nreverse res)))
172
173(defun cconv--map-diff-elem (m x)
174 "Return the map M minus any mapping for X."
175 ;; Here we assume that X appears at most once in M.
176 (let* ((b (assq x m))
177 (res (if b (remq b m) m)))
178 (assert (null (assq x res))) ;; Check the assumption was warranted.
179 res))
94d11cb5 180
b38b1ec0
SM
181(defun cconv--map-diff-set (m s)
182 "Return the map M minus any mapping for elements of S."
183 ;; Here we assume that X appears at most once in M.
184 (let ((res '()))
185 (dolist (b m)
186 (unless (memq (car b) s) (push b res)))
187 (nreverse res)))
188
6c075cd7
SM
189(defun cconv--convert-function (args body env parentform)
190 (assert (equal body (caar cconv-freevars-alist)))
191 (let* ((fvs (cdr (pop cconv-freevars-alist)))
192 (body-new '())
a9de04fa 193 (letbind '())
6c075cd7
SM
194 (envector ())
195 (i 0)
196 (new-env ()))
197 ;; Build the "formal and actual envs" for the closure-converted function.
198 (dolist (fv fvs)
199 (let ((exp (or (cdr (assq fv env)) fv)))
200 (pcase exp
201 ;; If `fv' is a variable that's wrapped in a cons-cell,
202 ;; we want to put the cons-cell itself in the closure,
203 ;; rather than just a copy of its current content.
204 (`(car ,iexp . ,_)
205 (push iexp envector)
206 (push `(,fv . (car (internal-get-closed-var ,i))) new-env))
207 (_
208 (push exp envector)
209 (push `(,fv . (internal-get-closed-var ,i)) new-env))))
210 (setq i (1+ i)))
211 (setq envector (nreverse envector))
212 (setq new-env (nreverse new-env))
213
214 (dolist (arg args)
215 (if (not (member (cons (list arg) parentform) cconv-captured+mutated))
216 (if (assq arg new-env) (push `(,arg) new-env))
217 (push `(,arg . (car ,arg)) new-env)
218 (push `(,arg (list ,arg)) letbind)))
ca105506 219
6c075cd7
SM
220 (setq body-new (mapcar (lambda (form)
221 (cconv-convert form new-env nil))
222 body))
223
224 (when letbind
225 (let ((special-forms '()))
226 ;; Keep special forms at the beginning of the body.
227 (while (or (stringp (car body-new)) ;docstring.
228 (memq (car-safe (car body-new)) '(interactive declare)))
229 (push (pop body-new) special-forms))
230 (setq body-new
231 `(,@(nreverse special-forms) (let ,letbind . ,body-new)))))
a9de04fa
SM
232
233 (cond
6c075cd7
SM
234 ((null envector) ;if no freevars - do nothing
235 `(function (lambda ,args . ,body-new)))
a9de04fa
SM
236 (t
237 `(internal-make-closure
6c075cd7 238 ,args ,envector . ,body-new)))))
a9de04fa 239
6c075cd7 240(defun cconv-convert (form env extend)
d779e73c 241 ;; This function actually rewrites the tree.
6c075cd7
SM
242 "Return FORM with all its lambdas changed so they are closed.
243ENV is a lexical environment mapping variables to the expression
244used to get its value. This is used for variables that are copied into
245closures, moved into cons cells, ...
246ENV is a list where each entry takes the shape either:
247 (VAR . (car EXP)): VAR has been moved into the car of a cons-cell, and EXP
248 is an expression that evaluates to this cons-cell.
249 (VAR . (internal-get-closed-var N)): VAR has been copied into the closure
250 environment's Nth slot.
251 (VAR . (apply-partially F ARG1 ARG2 ..)): VAR has been λ-lifted and takes
252 additional arguments ARGs.
253EXTEND is a list of variables which might need to be accessed even from places
254where they are shadowed, because some part of ENV causes them to be used at
255places where they originally did not directly appear."
256 (assert (not (delq nil (mapcar (lambda (mapping)
257 (if (eq (cadr mapping) 'apply-partially)
258 (cconv--set-diff (cdr (cddr mapping))
259 extend)))
260 env))))
ca105506 261
d779e73c 262 ;; What's the difference between fvrs and envs?
94d11cb5
IK
263 ;; Suppose that we have the code
264 ;; (lambda (..) fvr (let ((fvr 1)) (+ fvr 1)))
d779e73c
SM
265 ;; only the first occurrence of fvr should be replaced by
266 ;; (aref env ...).
94d11cb5
IK
267 ;; So initially envs and fvrs are the same thing, but when we descend to
268 ;; the 'let, we delete fvr from fvrs. Why we don't delete fvr from envs?
269 ;; Because in envs the order of variables is important. We use this list
d779e73c
SM
270 ;; to find the number of a specific variable in the environment vector,
271 ;; so we never touch it(unless we enter to the other closure).
272 ;;(if (listp form) (print (car form)) form)
273 (pcase form
6c075cd7 274 (`(,(and letsym (or `let* `let)) ,binders . ,body)
94d11cb5
IK
275
276 ; let and let* special forms
6c075cd7
SM
277 (let ((binders-new '())
278 (new-env env)
279 (new-extend extend))
d779e73c 280
295fb2ac
SM
281 (dolist (binder binders)
282 (let* ((value nil)
283 (var (if (not (consp binder))
a9de04fa 284 (prog1 binder (setq binder (list binder)))
295fb2ac
SM
285 (setq value (cadr binder))
286 (car binder)))
287 (new-val
288 (cond
289 ;; Check if var is a candidate for lambda lifting.
6c075cd7
SM
290 ((and (member (cons binder form) cconv-lambda-candidates)
291 (progn
292 (assert (and (eq (car value) 'function)
293 (eq (car (cadr value)) 'lambda)))
294 (assert (equal (cddr (cadr value))
295 (caar cconv-freevars-alist)))
296 ;; Peek at the freevars to decide whether to λ-lift.
297 (let* ((fvs (cdr (car cconv-freevars-alist)))
298 (fun (cadr value))
299 (funargs (cadr fun))
300 (funcvars (append fvs funargs)))
94d11cb5 301 ; lambda lifting condition
6c075cd7
SM
302 (and fvs (>= cconv-liftwhen (length funcvars))))))
303 ; Lift.
304 (let* ((fvs (cdr (pop cconv-freevars-alist)))
305 (fun (cadr value))
306 (funargs (cadr fun))
307 (funcvars (append fvs funargs))
308 (funcbody (cddr fun))
309 (funcbody-env ()))
310 (push `(,var . (apply-partially ,var . ,fvs)) new-env)
311 (dolist (fv fvs)
312 (pushnew fv new-extend)
313 (if (and (eq 'car (car-safe (cdr (assq fv env))))
314 (not (memq fv funargs)))
315 (push `(,fv . (car ,fv)) funcbody-env)))
316 `(function (lambda ,funcvars .
317 ,(mapcar (lambda (form)
318 (cconv-convert
319 form funcbody-env nil))
320 funcbody)))))
295fb2ac
SM
321
322 ;; Check if it needs to be turned into a "ref-cell".
a9de04fa 323 ((member (cons binder form) cconv-captured+mutated)
295fb2ac 324 ;; Declared variable is mutated and captured.
6c075cd7
SM
325 (push `(,var . (car ,var)) new-env)
326 `(list ,(cconv-convert value env extend)))
295fb2ac
SM
327
328 ;; Normal default case.
329 (t
6c075cd7
SM
330 (if (assq var new-env) (push `(,var) new-env))
331 (cconv-convert value env extend)))))
332
333 ;; The piece of code below letbinds free variables of a λ-lifted
334 ;; function if they are redefined in this let, example:
335 ;; (let* ((fun (lambda (x) (+ x y))) (y 1)) (funcall fun 1))
336 ;; Here we can not pass y as parameter because it is redefined.
337 ;; So we add a (closed-y y) declaration. We do that even if the
338 ;; function is not used inside this let(*). The reason why we
339 ;; ignore this case is that we can't "look forward" to see if the
340 ;; function is called there or not. To treat this case better we'd
341 ;; need to traverse the tree one more time to collect this data, and
342 ;; I think that it's not worth it.
343 (when (memq var new-extend)
344 (let ((closedsym
345 (make-symbol (concat "closed-" (symbol-name var)))))
346 (setq new-env
347 (mapcar (lambda (mapping)
348 (if (not (eq (cadr mapping) 'apply-partially))
349 mapping
350 (assert (eq (car mapping) (nth 2 mapping)))
351 (list* (car mapping)
352 'apply-partially
353 (car mapping)
354 (mapcar (lambda (arg)
355 (if (eq var arg)
356 closedsym arg))
357 (nthcdr 3 mapping)))))
358 new-env))
359 (setq new-extend (remq var new-extend))
360 (push closedsym new-extend)
361 (push `(,closedsym ,var) binders-new)))
d779e73c 362
b38b1ec0
SM
363 ;; We push the element after redefined free variables are
364 ;; processed. This is important to avoid the bug when free
365 ;; variable and the function have the same name.
295fb2ac 366 (push (list var new-val) binders-new)
d779e73c 367
6c075cd7
SM
368 (when (eq letsym 'let*)
369 (setq env new-env)
370 (setq extend new-extend))
371 )) ; end of dolist over binders
372
373 `(,letsym ,(nreverse binders-new)
374 . ,(mapcar (lambda (form)
375 (cconv-convert
376 form new-env new-extend))
377 body))))
94d11cb5
IK
378 ;end of let let* forms
379
d779e73c 380 ; first element is lambda expression
6c075cd7
SM
381 (`(,(and `(lambda . ,_) fun) . ,args)
382 ;; FIXME: it's silly to create a closure just to call it.
ca105506 383 ;; Running byte-optimize-form earlier will resolve this.
6c075cd7
SM
384 `(funcall
385 ,(cconv-convert `(function ,fun) env extend)
386 ,@(mapcar (lambda (form)
387 (cconv-convert form env extend))
388 args)))
d779e73c
SM
389
390 (`(cond . ,cond-forms) ; cond special form
6c075cd7
SM
391 `(cond . ,(mapcar (lambda (branch)
392 (mapcar (lambda (form)
393 (cconv-convert form env extend))
394 branch))
395 cond-forms)))
d779e73c 396
6c075cd7
SM
397 (`(function (lambda ,args . ,body) . ,_)
398 (cconv--convert-function args body env form))
d779e73c 399
876c194c 400 (`(internal-make-closure . ,_)
6c075cd7
SM
401 (byte-compile-report-error
402 "Internal error in compiler: cconv called twice?"))
876c194c 403
6c075cd7
SM
404 (`(quote . ,_) form)
405 (`(function . ,_) form)
94d11cb5
IK
406
407 ;defconst, defvar
6c075cd7
SM
408 (`(,(and sym (or `defconst `defvar)) ,definedsymbol . ,forms)
409 `(,sym ,definedsymbol
410 . ,(mapcar (lambda (form) (cconv-convert form env extend))
411 forms)))
d779e73c
SM
412
413 ;defun, defmacro
414 (`(,(and sym (or `defun `defmacro))
6c075cd7
SM
415 ,func ,args . ,body)
416 (assert (equal body (caar cconv-freevars-alist)))
a9de04fa 417 (assert (null (cdar cconv-freevars-alist)))
6c075cd7
SM
418
419 (let ((new (cconv--convert-function args body env form)))
420 (pcase new
421 (`(function (lambda ,newargs . ,new-body))
422 (assert (equal args newargs))
423 `(,sym ,func ,args . ,new-body))
424 (t (byte-compile-report-error
425 (format "Internal error in cconv of (%s %s ...)" sym func))))))
94d11cb5 426
94d11cb5 427 ;condition-case
295fb2ac 428 (`(condition-case ,var ,protected-form . ,handlers)
6c075cd7
SM
429 (let ((newform (cconv--convert-function
430 () (list protected-form) env form)))
295fb2ac 431 `(condition-case :fun-body ,newform
876c194c
SM
432 ,@(mapcar (lambda (handler)
433 (list (car handler)
6c075cd7
SM
434 (cconv--convert-function
435 (list (or var cconv--dummy-var))
436 (cdr handler) env form)))
876c194c 437 handlers))))
295fb2ac
SM
438
439 (`(,(and head (or `catch `unwind-protect)) ,form . ,body)
6c075cd7
SM
440 `(,head ,(cconv-convert form env extend)
441 :fun-body ,(cconv--convert-function () body env form)))
295fb2ac 442
e0f57e65
SM
443 (`(track-mouse . ,body)
444 `(track-mouse
6c075cd7 445 :fun-body ,(cconv--convert-function () body env form)))
d779e73c
SM
446
447 (`(setq . ,forms) ; setq special form
6c075cd7 448 (let ((prognlist ()))
d779e73c 449 (while forms
6c075cd7
SM
450 (let* ((sym (pop forms))
451 (sym-new (or (cdr (assq sym env)) sym))
452 (value (cconv-convert (pop forms) env extend)))
453 (push (pcase sym-new
454 ((pred symbolp) `(setq ,sym-new ,value))
455 (`(car ,iexp) `(setcar ,iexp ,value))
456 ;; This "should never happen", but for variables which are
457 ;; mutated+captured+unused, we may end up trying to `setq'
458 ;; on a closed-over variable, so just drop the setq.
459 (_ ;; (byte-compile-report-error
460 ;; (format "Internal error in cconv of (setq %s ..)"
461 ;; sym-new))
462 value))
463 prognlist)))
d779e73c 464 (if (cdr prognlist)
6c075cd7 465 `(progn . ,(nreverse prognlist))
d779e73c
SM
466 (car prognlist))))
467
468 (`(,(and (or `funcall `apply) callsym) ,fun . ,args)
6c075cd7
SM
469 ;; These are not special forms but we treat them separately for the needs
470 ;; of lambda lifting.
471 (let ((mapping (cdr (assq fun env))))
472 (pcase mapping
473 (`(apply-partially ,_ . ,(and fvs `(,_ . ,_)))
474 (assert (eq (cadr mapping) fun))
475 `(,callsym ,fun
476 ,@(mapcar (lambda (fv)
477 (let ((exp (or (cdr (assq fv env)) fv)))
478 (pcase exp
479 (`(car ,iexp . ,_) iexp)
480 (_ exp))))
481 fvs)
482 ,@(mapcar (lambda (arg)
483 (cconv-convert arg env extend))
484 args)))
485 (_ `(,callsym ,@(mapcar (lambda (arg)
486 (cconv-convert arg env extend))
487 (cons fun args)))))))
d779e73c 488
d032d5e7 489 (`(interactive . ,forms)
6c075cd7
SM
490 `(interactive . ,(mapcar (lambda (form)
491 (cconv-convert form nil nil))
492 forms)))
ca105506 493
ba83908c 494 (`(declare . ,_) form) ;The args don't contain code.
ca105506 495
6c075cd7
SM
496 (`(,func . ,forms)
497 ;; First element is function or whatever function-like forms are: or, and,
498 ;; if, progn, prog1, prog2, while, until
499 `(,func . ,(mapcar (lambda (form)
500 (cconv-convert form env extend))
501 forms)))
502
503 (_ (or (cdr (assq form env)) form))))
43e67019 504
a9de04fa
SM
505(unless (fboundp 'byte-compile-not-lexical-var-p)
506 ;; Only used to test the code in non-lexbind Emacs.
507 (defalias 'byte-compile-not-lexical-var-p 'boundp))
508
6c075cd7 509(defun cconv--analyse-use (vardata form varkind)
e9fce1ac 510 "Analyze the use of a variable.
d032d5e7
SM
511VARDATA should be (BINDER READ MUTATED CAPTURED CALLED).
512VARKIND is the name of the kind of variable.
513FORM is the parent form that binds this var."
a9de04fa
SM
514 ;; use = `(,binder ,read ,mutated ,captured ,called)
515 (pcase vardata
d032d5e7
SM
516 (`(,_ nil nil nil nil) nil)
517 (`((,(and (pred (lambda (var) (eq ?_ (aref (symbol-name var) 0)))) var) . ,_)
518 ,_ ,_ ,_ ,_)
6c075cd7
SM
519 (byte-compile-log-warning
520 (format "%s `%S' not left unused" varkind var))))
d032d5e7
SM
521 (pcase vardata
522 (`((,var . ,_) nil ,_ ,_ nil)
523 ;; FIXME: This gives warnings in the wrong order, with imprecise line
524 ;; numbers and without function name info.
525 (unless (or ;; Uninterned symbols typically come from macro-expansion, so
526 ;; it is often non-trivial for the programmer to avoid such
527 ;; unused vars.
528 (not (intern-soft var))
e67a13ab
CY
529 (eq ?_ (aref (symbol-name var) 0))
530 ;; As a special exception, ignore "ignore".
531 (eq var 'ignored))
d032d5e7
SM
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)))))
e9fce1ac 562 (dolist (form body) ;Analyze body forms.
a9de04fa
SM
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.
c7015153 584Analyze 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
e9fce1ac 615 (dolist (form body-forms) ; Analyze body forms.
a9de04fa 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