Fix pcase memoizing; change lexbound byte-code marker.
[emacs.git] / lisp / emacs-lisp / cconv.el
blob5501c13ee4fd009cbdc63c459a97c5612bbdeb15
1 ;;; cconv.el --- Closure conversion for statically scoped Emacs lisp. -*- lexical-binding: t; coding: utf-8 -*-
3 ;; Copyright (C) 2011 Free Software Foundation, Inc.
5 ;; Author: Igor Kuzmin <kzuminig@iro.umontreal.ca>
6 ;; Maintainer: FSF
7 ;; Keywords: lisp
8 ;; Package: emacs
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; This takes a piece of Elisp code, and eliminates all free variables from
28 ;; lambda expressions. The user entry points are cconv-closure-convert and
29 ;; cconv-closure-convert-toplevel(for toplevel forms).
30 ;; All macros should be expanded beforehand.
32 ;; Here is a brief explanation how this code works.
33 ;; Firstly, we analyse the tree by calling cconv-analyse-form.
34 ;; This function finds all mutated variables, all functions that are suitable
35 ;; for lambda lifting and all variables captured by closure. It passes the tree
36 ;; once, returning a list of three lists.
38 ;; Then we calculate the intersection of first and third lists returned by
39 ;; cconv-analyse form to find all mutated variables that are captured by
40 ;; closure.
42 ;; Armed with this data, we call cconv-closure-convert-rec, that rewrites the
43 ;; tree recursivly, lifting lambdas where possible, building closures where it
44 ;; is needed and eliminating mutable variables used in closure.
46 ;; We do following replacements :
47 ;; (lambda (v1 ...) ... fv1 fv2 ...) => (lambda (v1 ... fv1 fv2 ) ... fv1 fv2 .)
48 ;; if the function is suitable for lambda lifting (if all calls are known)
50 ;; (lambda (v0 ...) ... fv0 .. fv1 ...) =>
51 ;; (internal-make-closure (v0 ...) (fv1 ...)
52 ;; ... (internal-get-closed-var 0) ... (internal-get-closed-var 1) ...)
54 ;; If the function has no free variables, we don't do anything.
56 ;; If a variable is mutated (updated by setq), and it is used in a closure
57 ;; we wrap its definition with list: (list val) and we also replace
58 ;; var => (car var) wherever this variable is used, and also
59 ;; (setq var value) => (setcar var value) where it is updated.
61 ;; If defun argument is closure mutable, we letbind it and wrap it's
62 ;; definition with list.
63 ;; (defun foo (... mutable-arg ...) ...) =>
64 ;; (defun foo (... m-arg ...) (let ((m-arg (list m-arg))) ...))
66 ;;; Code:
68 ;; TODO:
69 ;; - byte-optimize-form should be applied before cconv.
70 ;; - maybe unify byte-optimize and compiler-macros.
71 ;; - canonize code in macro-expand so we don't have to handle (let (var) body)
72 ;; and other oddities.
73 ;; - clean up cconv-closure-convert-rec, especially the `let' binding part.
74 ;; - new byte codes for unwind-protect, catch, and condition-case so that
75 ;; closures aren't needed at all.
76 ;; - a reference to a var that is known statically to always hold a constant
77 ;; should be turned into a byte-constant rather than a byte-stack-ref.
78 ;; Hmm... right, that's called constant propagation and could be done here,
79 ;; but when that constant is a function, we have to be careful to make sure
80 ;; the bytecomp only compiles it once.
81 ;; - Since we know here when a variable is not mutated, we could pass that
82 ;; info to the byte-compiler, e.g. by using a new `immutable-let'.
83 ;; - add tail-calls to bytecode.c and the byte compiler.
85 ;; (defmacro dlet (binders &rest body)
86 ;; ;; Works in both lexical and non-lexical mode.
87 ;; `(progn
88 ;; ,@(mapcar (lambda (binder)
89 ;; `(defvar ,(if (consp binder) (car binder) binder)))
90 ;; binders)
91 ;; (let ,binders ,@body)))
93 ;; (defmacro llet (binders &rest body)
94 ;; ;; Only works in lexical-binding mode.
95 ;; `(funcall
96 ;; (lambda ,(mapcar (lambda (binder) (if (consp binder) (car binder) binder))
97 ;; binders)
98 ;; ,@body)
99 ;; ,@(mapcar (lambda (binder) (if (consp binder) (cadr binder)))
100 ;; binders)))
102 ;; (defmacro letrec (binders &rest body)
103 ;; ;; Only useful in lexical-binding mode.
104 ;; ;; As a special-form, we could implement it more efficiently (and cleanly,
105 ;; ;; making the vars actually unbound during evaluation of the binders).
106 ;; `(let ,(mapcar (lambda (binder) (if (consp binder) (car binder) binder))
107 ;; binders)
108 ;; ,@(delq nil (mapcar (lambda (binder) (if (consp binder) `(setq ,@binder)))
109 ;; binders))
110 ;; ,@body))
112 (eval-when-compile (require 'cl))
114 (defconst cconv-liftwhen 6
115 "Try to do lambda lifting if the number of arguments + free variables
116 is less than this number.")
117 ;; List of all the variables that are both captured by a closure
118 ;; and mutated. Each entry in the list takes the form
119 ;; (BINDER . PARENTFORM) where BINDER is the (VAR VAL) that introduces the
120 ;; variable (or is just (VAR) for variables not introduced by let).
121 (defvar cconv-captured+mutated)
123 ;; List of candidates for lambda lifting.
124 ;; Each candidate has the form (BINDER . PARENTFORM). A candidate
125 ;; is a variable that is only passed to `funcall' or `apply'.
126 (defvar cconv-lambda-candidates)
128 ;; Alist associating to each function body the list of its free variables.
129 (defvar cconv-freevars-alist)
131 ;;;###autoload
132 (defun cconv-closure-convert (form)
133 "Main entry point for closure conversion.
134 -- FORM is a piece of Elisp code after macroexpansion.
135 -- TOPLEVEL(optional) is a boolean variable, true if we are at the root of AST
137 Returns a form where all lambdas don't have any free variables."
138 ;; (message "Entering cconv-closure-convert...")
139 (let ((cconv-freevars-alist '())
140 (cconv-lambda-candidates '())
141 (cconv-captured+mutated '()))
142 ;; Analyse form - fill these variables with new information.
143 (cconv-analyse-form form '())
144 (setq cconv-freevars-alist (nreverse cconv-freevars-alist))
145 (cconv-closure-convert-rec
146 form ; the tree
147 '() ;
148 '() ; fvrs initially empty
149 '() ; envs initially empty
153 (defconst cconv--dummy-var (make-symbol "ignored"))
155 (defun cconv--set-diff (s1 s2)
156 "Return elements of set S1 that are not in set S2."
157 (let ((res '()))
158 (dolist (x s1)
159 (unless (memq x s2) (push x res)))
160 (nreverse res)))
162 (defun cconv--set-diff-map (s m)
163 "Return elements of set S that are not in Dom(M)."
164 (let ((res '()))
165 (dolist (x s)
166 (unless (assq x m) (push x res)))
167 (nreverse res)))
169 (defun cconv--map-diff (m1 m2)
170 "Return the submap of map M1 that has Dom(M2) removed."
171 (let ((res '()))
172 (dolist (x m1)
173 (unless (assq (car x) m2) (push x res)))
174 (nreverse res)))
176 (defun cconv--map-diff-elem (m x)
177 "Return the map M minus any mapping for X."
178 ;; Here we assume that X appears at most once in M.
179 (let* ((b (assq x m))
180 (res (if b (remq b m) m)))
181 (assert (null (assq x res))) ;; Check the assumption was warranted.
182 res))
184 (defun cconv--map-diff-set (m s)
185 "Return the map M minus any mapping for elements of S."
186 ;; Here we assume that X appears at most once in M.
187 (let ((res '()))
188 (dolist (b m)
189 (unless (memq (car b) s) (push b res)))
190 (nreverse res)))
192 (defun cconv-closure-convert-function (fvrs vars emvrs envs lmenvs body-forms
193 parentform)
194 (assert (equal body-forms (caar cconv-freevars-alist)))
195 (let* ((fvrs-new (cconv--set-diff fvrs vars)) ; Remove vars from fvrs.
196 (fv (cdr (pop cconv-freevars-alist)))
197 (body-forms-new '())
198 (letbind '())
199 (envector nil))
200 (when fv
201 ;; Here we form our environment vector.
203 (dolist (elm fv)
204 (push
205 (cconv-closure-convert-rec
206 ;; Remove `elm' from `emvrs' for this call because in case
207 ;; `elm' is a variable that's wrapped in a cons-cell, we
208 ;; want to put the cons-cell itself in the closure, rather
209 ;; than just a copy of its current content.
210 elm (remq elm emvrs) fvrs envs lmenvs)
211 envector)) ; Process vars for closure vector.
212 (setq envector (reverse envector))
213 (setq envs fv)
214 (setq fvrs-new fv)) ; Update substitution list.
216 (setq emvrs (cconv--set-diff emvrs vars))
217 (setq lmenvs (cconv--map-diff-set lmenvs vars))
219 ;; The difference between envs and fvrs is explained
220 ;; in comment in the beginning of the function.
221 (dolist (var vars)
222 (when (member (cons (list var) parentform) cconv-captured+mutated)
223 (push var emvrs)
224 (push `(,var (list ,var)) letbind)))
225 (dolist (elm body-forms) ; convert function body
226 (push (cconv-closure-convert-rec
227 elm emvrs fvrs-new envs lmenvs)
228 body-forms-new))
230 (setq body-forms-new
231 (if letbind `((let ,letbind . ,(reverse body-forms-new)))
232 (reverse body-forms-new)))
234 (cond
235 ;if no freevars - do nothing
236 ((null envector)
237 `(function (lambda ,vars . ,body-forms-new)))
238 ; 1 free variable - do not build vector
240 `(internal-make-closure
241 ,vars ,envector . ,body-forms-new)))))
243 (defun cconv-closure-convert-rec (form emvrs fvrs envs lmenvs)
244 ;; This function actually rewrites the tree.
245 "Eliminates all free variables of all lambdas in given forms.
246 Arguments:
247 - FORM is a piece of Elisp code after macroexpansion.
248 - LMENVS is a list of environments used for lambda-lifting. Initially empty.
249 - EMVRS is a list that contains mutated variables that are visible
250 within current environment.
251 - ENVS is an environment(list of free variables) of current closure.
252 Initially empty.
253 - FVRS is a list of variables to substitute in each context.
254 Initially empty.
256 Returns a form where all lambdas don't have any free variables."
257 ;; What's the difference between fvrs and envs?
258 ;; Suppose that we have the code
259 ;; (lambda (..) fvr (let ((fvr 1)) (+ fvr 1)))
260 ;; only the first occurrence of fvr should be replaced by
261 ;; (aref env ...).
262 ;; So initially envs and fvrs are the same thing, but when we descend to
263 ;; the 'let, we delete fvr from fvrs. Why we don't delete fvr from envs?
264 ;; Because in envs the order of variables is important. We use this list
265 ;; to find the number of a specific variable in the environment vector,
266 ;; so we never touch it(unless we enter to the other closure).
267 ;;(if (listp form) (print (car form)) form)
268 (pcase form
269 (`(,(and letsym (or `let* `let)) ,binders . ,body-forms)
271 ; let and let* special forms
272 (let ((body-forms-new '())
273 (binders-new '())
274 ;; next for variables needed for delayed push
275 ;; because we should process <value(s)>
276 ;; before we change any arguments
277 (lmenvs-new '()) ;needed only in case of let
278 (emvrs-new '()) ;needed only in case of let
279 (emvr-push) ;needed only in case of let*
280 (lmenv-push)) ;needed only in case of let*
282 (dolist (binder binders)
283 (let* ((value nil)
284 (var (if (not (consp binder))
285 (prog1 binder (setq binder (list binder)))
286 (setq value (cadr binder))
287 (car binder)))
288 (new-val
289 (cond
290 ;; Check if var is a candidate for lambda lifting.
291 ((member (cons binder form) cconv-lambda-candidates)
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* ((fv (cdr (car cconv-freevars-alist)))
298 (funargs (cadr (cadr value)))
299 (funcvars (append fv funargs))
300 (funcbodies (cddadr value)) ; function bodies
301 (funcbodies-new '()))
302 ; lambda lifting condition
303 (if (or (not fv) (< cconv-liftwhen (length funcvars)))
304 ; do not lift
305 (progn
306 ;; (byte-compile-log-warning
307 ;; (format "Not λ-lifting `%S': %d > %d"
308 ;; var (length funcvars) cconv-liftwhen))
310 (cconv-closure-convert-rec
311 value emvrs fvrs envs lmenvs))
312 ; lift
313 (progn
314 ;; (byte-compile-log-warning
315 ;; (format "λ-lifting `%S'" var))
316 (setq cconv-freevars-alist
317 ;; Now that we know we'll λ-lift, consume the
318 ;; freevar data.
319 (cdr cconv-freevars-alist))
320 (dolist (elm2 funcbodies)
321 (push ; convert function bodies
322 (cconv-closure-convert-rec
323 elm2 emvrs nil envs lmenvs)
324 funcbodies-new))
325 (if (eq letsym 'let*)
326 (setq lmenv-push (cons var fv))
327 (push (cons var fv) lmenvs-new))
328 ; push lifted function
330 `(function .
331 ((lambda ,funcvars .
332 ,(reverse funcbodies-new))))))))
334 ;; Check if it needs to be turned into a "ref-cell".
335 ((member (cons binder form) cconv-captured+mutated)
336 ;; Declared variable is mutated and captured.
337 (prog1
338 `(list ,(cconv-closure-convert-rec
339 value emvrs
340 fvrs envs lmenvs))
341 (if (eq letsym 'let*)
342 (setq emvr-push var)
343 (push var emvrs-new))))
345 ;; Normal default case.
347 (cconv-closure-convert-rec
348 value emvrs fvrs envs lmenvs)))))
350 ;; this piece of code below letbinds free
351 ;; variables of a lambda lifted function
352 ;; if they are redefined in this let
353 ;; example:
354 ;; (let* ((fun (lambda (x) (+ x y))) (y 1)) (funcall fun 1))
355 ;; Here we can not pass y as parameter because it is
356 ;; redefined. We add a (closed-y y) declaration.
357 ;; We do that even if the function is not used inside
358 ;; this let(*). The reason why we ignore this case is
359 ;; that we can't "look forward" to see if the function
360 ;; is called there or not. To treat well this case we
361 ;; need to traverse the tree one more time to collect this
362 ;; data, and I think that it's not worth it.
364 (when (eq letsym 'let*)
365 (let ((closedsym '())
366 (new-lmenv '())
367 (old-lmenv '()))
368 (dolist (lmenv lmenvs)
369 (when (memq var (cdr lmenv))
370 (setq closedsym
371 (make-symbol
372 (concat "closed-" (symbol-name var))))
373 (setq new-lmenv (list (car lmenv)))
374 (dolist (frv (cdr lmenv)) (if (eq frv var)
375 (push closedsym new-lmenv)
376 (push frv new-lmenv)))
377 (setq new-lmenv (reverse new-lmenv))
378 (setq old-lmenv lmenv)))
379 (when new-lmenv
380 (setq lmenvs (remq old-lmenv lmenvs))
381 (push new-lmenv lmenvs)
382 (push `(,closedsym ,var) binders-new))))
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)
388 (when (eq letsym 'let*) ; update fvrs
389 (setq fvrs (remq var fvrs))
390 (setq emvrs (remq var emvrs)) ; remove if redefined
391 (when emvr-push
392 (push emvr-push emvrs)
393 (setq emvr-push nil))
394 (setq lmenvs (cconv--map-diff-elem lmenvs var))
395 (when lmenv-push
396 (push lmenv-push lmenvs)
397 (setq lmenv-push nil)))
398 )) ; end of dolist over binders
399 (when (eq letsym 'let)
401 ;; Here we update emvrs, fvrs and lmenvs lists
402 (setq fvrs (cconv--set-diff-map fvrs binders-new))
403 (setq emvrs (cconv--set-diff-map emvrs binders-new))
404 (setq emvrs (append emvrs emvrs-new))
405 (setq lmenvs (cconv--set-diff-map lmenvs binders-new))
406 (setq lmenvs (append lmenvs lmenvs-new))
408 ;; Here we do the same letbinding as for let* above
409 ;; to avoid situation when a free variable of a lambda lifted
410 ;; function got redefined.
412 (let ((new-lmenv)
413 (var nil)
414 (closedsym nil)
415 (letbinds '()))
416 (dolist (binder binders)
417 (setq var (if (consp binder) (car binder) binder))
419 (let ((lmenvs-1 lmenvs)) ; just to avoid manipulating
420 (dolist (lmenv lmenvs-1) ; the counter inside the loop
421 (when (memq var (cdr lmenv))
422 (setq closedsym (make-symbol
423 (concat "closed-"
424 (symbol-name var))))
426 (setq new-lmenv (list (car lmenv)))
427 (dolist (frv (cdr lmenv))
428 (push (if (eq frv var) closedsym frv)
429 new-lmenv))
430 (setq new-lmenv (reverse new-lmenv))
431 (setq lmenvs (remq lmenv lmenvs))
432 (push new-lmenv lmenvs)
433 (push `(,closedsym ,var) letbinds)
434 ))))
435 (setq binders-new (append binders-new letbinds))))
437 (dolist (elm body-forms) ; convert body forms
438 (push (cconv-closure-convert-rec
439 elm emvrs fvrs envs lmenvs)
440 body-forms-new))
441 `(,letsym ,(reverse binders-new) . ,(reverse body-forms-new))))
442 ;end of let let* forms
444 ; first element is lambda expression
445 (`(,(and `(lambda . ,_) fun) . ,other-body-forms)
447 (let ((other-body-forms-new '()))
448 (dolist (elm other-body-forms)
449 (push (cconv-closure-convert-rec
450 elm emvrs fvrs envs lmenvs)
451 other-body-forms-new))
452 `(funcall
453 ,(cconv-closure-convert-rec
454 (list 'function fun) emvrs fvrs envs lmenvs)
455 ,@(nreverse other-body-forms-new))))
457 (`(cond . ,cond-forms) ; cond special form
458 (let ((cond-forms-new '()))
459 (dolist (elm cond-forms)
460 (push (let ((elm-new '()))
461 (dolist (elm-2 elm)
462 (push
463 (cconv-closure-convert-rec
464 elm-2 emvrs fvrs envs lmenvs)
465 elm-new))
466 (reverse elm-new))
467 cond-forms-new))
468 (cons 'cond
469 (reverse cond-forms-new))))
471 (`(quote . ,_) form)
473 (`(function (lambda ,vars . ,body-forms)) ; function form
474 (cconv-closure-convert-function
475 fvrs vars emvrs envs lmenvs body-forms form))
477 (`(internal-make-closure . ,_)
478 (error "Internal byte-compiler error: cconv called twice"))
480 (`(function . ,_) form) ; Same as quote.
482 ;defconst, defvar
483 (`(,(and sym (or `defconst `defvar)) ,definedsymbol . ,body-forms)
485 (let ((body-forms-new '()))
486 (dolist (elm body-forms)
487 (push (cconv-closure-convert-rec
488 elm emvrs fvrs envs lmenvs)
489 body-forms-new))
490 (setq body-forms-new (reverse body-forms-new))
491 `(,sym ,definedsymbol . ,body-forms-new)))
493 ;defun, defmacro
494 (`(,(and sym (or `defun `defmacro))
495 ,func ,vars . ,body-forms)
497 ;; The freevar data was pushed onto cconv-freevars-alist
498 ;; but we don't need it.
499 (assert (equal body-forms (caar cconv-freevars-alist)))
500 (assert (null (cdar cconv-freevars-alist)))
501 (setq cconv-freevars-alist (cdr cconv-freevars-alist))
503 (let ((body-new '()) ; The whole body.
504 (body-forms-new '()) ; Body w\o docstring and interactive.
505 (letbind '()))
506 ; Find mutable arguments.
507 (dolist (elm vars)
508 (when (member (cons (list elm) form) cconv-captured+mutated)
509 (push elm letbind)
510 (push elm emvrs)))
511 ;Transform body-forms.
512 (when (stringp (car body-forms)) ; Treat docstring well.
513 (push (car body-forms) body-new)
514 (setq body-forms (cdr body-forms)))
515 (when (eq (car-safe (car body-forms)) 'interactive)
516 (push (cconv-closure-convert-rec
517 (car body-forms)
518 emvrs fvrs envs lmenvs)
519 body-new)
520 (setq body-forms (cdr body-forms)))
522 (dolist (elm body-forms)
523 (push (cconv-closure-convert-rec
524 elm emvrs fvrs envs lmenvs)
525 body-forms-new))
526 (setq body-forms-new (reverse body-forms-new))
528 (if letbind
529 ; Letbind mutable arguments.
530 (let ((binders-new '()))
531 (dolist (elm letbind) (push `(,elm (list ,elm))
532 binders-new))
533 (push `(let ,(reverse binders-new) .
534 ,body-forms-new) body-new)
535 (setq body-new (reverse body-new)))
536 (setq body-new (append (reverse body-new) body-forms-new)))
538 `(,sym ,func ,vars . ,body-new)))
540 ;condition-case
541 (`(condition-case ,var ,protected-form . ,handlers)
542 (let ((newform (cconv-closure-convert-rec
543 `(function (lambda () ,protected-form))
544 emvrs fvrs envs lmenvs)))
545 (setq fvrs (remq var fvrs))
546 `(condition-case :fun-body ,newform
547 ,@(mapcar (lambda (handler)
548 (list (car handler)
549 (cconv-closure-convert-rec
550 (let ((arg (or var cconv--dummy-var)))
551 `(function (lambda (,arg) ,@(cdr handler))))
552 emvrs fvrs envs lmenvs)))
553 handlers))))
555 (`(,(and head (or `catch `unwind-protect)) ,form . ,body)
556 `(,head ,(cconv-closure-convert-rec form emvrs fvrs envs lmenvs)
557 :fun-body
558 ,(cconv-closure-convert-rec `(function (lambda () ,@body))
559 emvrs fvrs envs lmenvs)))
561 (`(track-mouse . ,body)
562 `(track-mouse
563 :fun-body
564 ,(cconv-closure-convert-rec `(function (lambda () ,@body))
565 emvrs fvrs envs lmenvs)))
567 (`(setq . ,forms) ; setq special form
568 (let (prognlist sym sym-new value)
569 (while forms
570 (setq sym (car forms))
571 (setq sym-new (cconv-closure-convert-rec
573 (remq sym emvrs) fvrs envs lmenvs))
574 (setq value
575 (cconv-closure-convert-rec
576 (cadr forms) emvrs fvrs envs lmenvs))
577 (cond
578 ((memq sym emvrs) (push `(setcar ,sym-new ,value) prognlist))
579 ((symbolp sym-new) (push `(setq ,sym-new ,value) prognlist))
580 ;; This should never happen, but for variables which are
581 ;; mutated+captured+unused, we may end up trying to `setq'
582 ;; on a closed-over variable, so just drop the setq.
583 (t (push value prognlist)))
584 (setq forms (cddr forms)))
585 (if (cdr prognlist)
586 `(progn . ,(reverse prognlist))
587 (car prognlist))))
589 (`(,(and (or `funcall `apply) callsym) ,fun . ,args)
590 ; funcall is not a special form
591 ; but we treat it separately
592 ; for the needs of lambda lifting
593 (let ((fv (cdr (assq fun lmenvs))))
594 (if fv
595 (let ((args-new '())
596 (processed-fv '()))
597 ;; All args (free variables and actual arguments)
598 ;; should be processed, because they can be fvrs
599 ;; (free variables of another closure)
600 (dolist (fvr fv)
601 (push (cconv-closure-convert-rec
602 fvr (remq fvr emvrs)
603 fvrs envs lmenvs)
604 processed-fv))
605 (setq processed-fv (reverse processed-fv))
606 (dolist (elm args)
607 (push (cconv-closure-convert-rec
608 elm emvrs fvrs envs lmenvs)
609 args-new))
610 (setq args-new (append processed-fv (reverse args-new)))
611 (setq fun (cconv-closure-convert-rec
612 fun emvrs fvrs envs lmenvs))
613 `(,callsym ,fun . ,args-new))
614 (let ((cdr-new '()))
615 (dolist (elm (cdr form))
616 (push (cconv-closure-convert-rec
617 elm emvrs fvrs envs lmenvs)
618 cdr-new))
619 `(,callsym . ,(reverse cdr-new))))))
621 (`(interactive . ,forms)
622 `(interactive
623 ,@(mapcar (lambda (form)
624 (cconv-closure-convert-rec form nil nil nil nil))
625 forms)))
627 (`(,func . ,body-forms) ; first element is function or whatever
628 ; function-like forms are:
629 ; or, and, if, progn, prog1, prog2,
630 ; while, until
631 (let ((body-forms-new '()))
632 (dolist (elm body-forms)
633 (push (cconv-closure-convert-rec
634 elm emvrs fvrs envs lmenvs)
635 body-forms-new))
636 (setq body-forms-new (reverse body-forms-new))
637 `(,func . ,body-forms-new)))
640 (let ((free (memq form fvrs)))
641 (if free ;form is a free variable
642 (let* ((numero (- (length fvrs) (length free)))
643 ;; Replace form => (aref env #)
644 (var `(internal-get-closed-var ,numero)))
645 (if (memq form emvrs) ; form => (car (aref env #)) if mutable
646 `(car ,var)
647 var))
648 (if (memq form emvrs) ; if form is a mutable variable
649 `(car ,form) ; replace form => (car form)
650 form))))))
652 (unless (fboundp 'byte-compile-not-lexical-var-p)
653 ;; Only used to test the code in non-lexbind Emacs.
654 (defalias 'byte-compile-not-lexical-var-p 'boundp))
656 (defun cconv-analyse-use (vardata form varkind)
657 "Analyse the use of a variable.
658 VARDATA should be (BINDER READ MUTATED CAPTURED CALLED).
659 VARKIND is the name of the kind of variable.
660 FORM is the parent form that binds this var."
661 ;; use = `(,binder ,read ,mutated ,captured ,called)
662 (pcase vardata
663 (`(,_ nil nil nil nil) nil)
664 (`((,(and (pred (lambda (var) (eq ?_ (aref (symbol-name var) 0)))) var) . ,_)
665 ,_ ,_ ,_ ,_)
666 (byte-compile-log-warning (format "%s `%S' not left unused" varkind var)))
667 ((or `(,_ ,_ ,_ ,_ ,_) dontcare) nil))
668 (pcase vardata
669 (`((,var . ,_) nil ,_ ,_ nil)
670 ;; FIXME: This gives warnings in the wrong order, with imprecise line
671 ;; numbers and without function name info.
672 (unless (or ;; Uninterned symbols typically come from macro-expansion, so
673 ;; it is often non-trivial for the programmer to avoid such
674 ;; unused vars.
675 (not (intern-soft var))
676 (eq ?_ (aref (symbol-name var) 0)))
677 (byte-compile-log-warning (format "Unused lexical %s `%S'"
678 varkind var))))
679 ;; If it's unused, there's no point converting it into a cons-cell, even if
680 ;; it's captured and mutated.
681 (`(,binder ,_ t t ,_)
682 (push (cons binder form) cconv-captured+mutated))
683 (`(,(and binder `(,_ (function (lambda . ,_)))) nil nil nil t)
684 (push (cons binder form) cconv-lambda-candidates))
685 (`(,_ ,_ ,_ ,_ ,_) nil)
686 (dontcare)))
688 (defun cconv-analyse-function (args body env parentform)
689 (let* ((newvars nil)
690 (freevars (list body))
691 ;; We analyze the body within a new environment where all uses are
692 ;; nil, so we can distinguish uses within that function from uses
693 ;; outside of it.
694 (envcopy
695 (mapcar (lambda (vdata) (list (car vdata) nil nil nil nil)) env))
696 (newenv envcopy))
697 ;; Push it before recursing, so cconv-freevars-alist contains entries in
698 ;; the order they'll be used by closure-convert-rec.
699 (push freevars cconv-freevars-alist)
700 (dolist (arg args)
701 (cond
702 ((byte-compile-not-lexical-var-p arg)
703 (byte-compile-report-error
704 (format "Argument %S is not a lexical variable" arg)))
705 ((eq ?& (aref (symbol-name arg) 0)) nil) ;Ignore &rest, &optional, ...
706 (t (let ((varstruct (list arg nil nil nil nil)))
707 (push (cons (list arg) (cdr varstruct)) newvars)
708 (push varstruct newenv)))))
709 (dolist (form body) ;Analyse body forms.
710 (cconv-analyse-form form newenv))
711 ;; Summarize resulting data about arguments.
712 (dolist (vardata newvars)
713 (cconv-analyse-use vardata parentform "argument"))
714 ;; Transfer uses collected in `envcopy' (via `newenv') back to `env';
715 ;; and compute free variables.
716 (while env
717 (assert (and envcopy (eq (caar env) (caar envcopy))))
718 (let ((free nil)
719 (x (cdr (car env)))
720 (y (cdr (car envcopy))))
721 (while x
722 (when (car y) (setcar x t) (setq free t))
723 (setq x (cdr x) y (cdr y)))
724 (when free
725 (push (caar env) (cdr freevars))
726 (setf (nth 3 (car env)) t))
727 (setq env (cdr env) envcopy (cdr envcopy))))))
729 (defun cconv-analyse-form (form env)
730 "Find mutated variables and variables captured by closure.
731 Analyse lambdas if they are suitable for lambda lifting.
732 - FORM is a piece of Elisp code after macroexpansion.
733 - ENV is an alist mapping each enclosing lexical variable to its info.
734 I.e. each element has the form (VAR . (READ MUTATED CAPTURED CALLED)).
735 This function does not return anything but instead fills the
736 `cconv-captured+mutated' and `cconv-lambda-candidates' variables
737 and updates the data stored in ENV."
738 (pcase form
739 ; let special form
740 (`(,(and (or `let* `let) letsym) ,binders . ,body-forms)
742 (let ((orig-env env)
743 (newvars nil)
744 (var nil)
745 (value nil))
746 (dolist (binder binders)
747 (if (not (consp binder))
748 (progn
749 (setq var binder) ; treat the form (let (x) ...) well
750 (setq binder (list binder))
751 (setq value nil))
752 (setq var (car binder))
753 (setq value (cadr binder))
755 (cconv-analyse-form value (if (eq letsym 'let*) env orig-env)))
757 (unless (byte-compile-not-lexical-var-p var)
758 (let ((varstruct (list var nil nil nil nil)))
759 (push (cons binder (cdr varstruct)) newvars)
760 (push varstruct env))))
762 (dolist (form body-forms) ; Analyse body forms.
763 (cconv-analyse-form form env))
765 (dolist (vardata newvars)
766 (cconv-analyse-use vardata form "variable"))))
768 ; defun special form
769 (`(,(or `defun `defmacro) ,func ,vrs . ,body-forms)
770 (when env
771 (byte-compile-log-warning
772 (format "Function %S will ignore its context %S"
773 func (mapcar #'car env))
774 t :warning))
775 (cconv-analyse-function vrs body-forms nil form))
777 (`(function (lambda ,vrs . ,body-forms))
778 (cconv-analyse-function vrs body-forms env form))
780 (`(setq . ,forms)
781 ;; If a local variable (member of env) is modified by setq then
782 ;; it is a mutated variable.
783 (while forms
784 (let ((v (assq (car forms) env))) ; v = non nil if visible
785 (when v (setf (nth 2 v) t)))
786 (cconv-analyse-form (cadr forms) env)
787 (setq forms (cddr forms))))
789 (`((lambda . ,_) . ,_) ; first element is lambda expression
790 (dolist (exp `((function ,(car form)) . ,(cdr form)))
791 (cconv-analyse-form exp env)))
793 (`(cond . ,cond-forms) ; cond special form
794 (dolist (forms cond-forms)
795 (dolist (form forms) (cconv-analyse-form form env))))
797 (`(quote . ,_) nil) ; quote form
798 (`(function . ,_) nil) ; same as quote
800 (`(condition-case ,var ,protected-form . ,handlers)
801 ;; FIXME: The bytecode for condition-case forces us to wrap the
802 ;; form and handlers in closures (for handlers, it's probably
803 ;; unavoidable, but not for the protected form).
804 (cconv-analyse-function () (list protected-form) env form)
805 (dolist (handler handlers)
806 (cconv-analyse-function (if var (list var)) (cdr handler) env form)))
808 ;; FIXME: The bytecode for catch forces us to wrap the body.
809 (`(,(or `catch `unwind-protect) ,form . ,body)
810 (cconv-analyse-form form env)
811 (cconv-analyse-function () body env form))
813 ;; FIXME: The bytecode for save-window-excursion and the lack of
814 ;; bytecode for track-mouse forces us to wrap the body.
815 (`(track-mouse . ,body)
816 (cconv-analyse-function () body env form))
818 (`(,(or `defconst `defvar) ,var ,value . ,_)
819 (push var byte-compile-bound-variables)
820 (cconv-analyse-form value env))
822 (`(,(or `funcall `apply) ,fun . ,args)
823 ;; Here we ignore fun because funcall and apply are the only two
824 ;; functions where we can pass a candidate for lambda lifting as
825 ;; argument. So, if we see fun elsewhere, we'll delete it from
826 ;; lambda candidate list.
827 (let ((fdata (and (symbolp fun) (assq fun env))))
828 (if fdata
829 (setf (nth 4 fdata) t)
830 (cconv-analyse-form fun env)))
831 (dolist (form args) (cconv-analyse-form form env)))
833 (`(interactive . ,forms)
834 ;; These appear within the function body but they don't have access
835 ;; to the function's arguments.
836 ;; We could extend this to allow interactive specs to refer to
837 ;; variables in the function's enclosing environment, but it doesn't
838 ;; seem worth the trouble.
839 (dolist (form forms) (cconv-analyse-form form nil)))
841 (`(,_ . ,body-forms) ; First element is a function or whatever.
842 (dolist (form body-forms) (cconv-analyse-form form env)))
844 ((pred symbolp)
845 (let ((dv (assq form env))) ; dv = declared and visible
846 (when dv
847 (setf (nth 1 dv) t))))))
849 (provide 'cconv)
850 ;;; cconv.el ends here