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