Use offsets relative to top rather than bottom for stack refs
[bpt/emacs.git] / lisp / emacs-lisp / cconv.el
1 ;;; cconv.el --- Closure conversion for statically scoped Emacs lisp. -*- lexical-binding: t -*-
2
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/>.
24
25 ;;; Commentary:
26
27 ;; This takes a piece of Elisp code, and eliminates all free variables from
28 ;; lambda expressions. The user entry points are cconv-closure-convert and
29 ;; cconv-closure-convert-toplevel(for toplevel forms).
30 ;; All macros should be expanded beforehand.
31 ;;
32 ;; Here is a brief explanation how this code works.
33 ;; Firstly, we 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.
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.
41
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.
45 ;;
46 ;; We do following replacements :
47 ;; (lambda (v1 ...) ... fv1 fv2 ...) => (lambda (v1 ... fv1 fv2 ) ... fv1 fv2 .)
48 ;; if the function is suitable for lambda lifting (if all calls are known)
49 ;;
50 ;; (lambda (v1 ...) ... fv ...) =>
51 ;; (curry (lambda (env v1 ...) ... env ...) env)
52 ;; if the function has only 1 free variable
53 ;;
54 ;; and finally
55 ;; (lambda (v1 ...) ... fv1 fv2 ...) =>
56 ;; (curry (lambda (env v1 ..) .. (aref env 0) (aref env 1) ..) (vector fv1 fv2))
57 ;; if the function has 2 or more free variables.
58 ;;
59 ;; If the function has no free variables, we don't do anything.
60 ;;
61 ;; If a variable is mutated (updated by setq), and it is used in a closure
62 ;; we wrap it's definition with list: (list val) and we also replace
63 ;; var => (car var) wherever this variable is used, and also
64 ;; (setq var value) => (setcar var value) where it is updated.
65 ;;
66 ;; If defun argument is closure mutable, we letbind it and wrap it's
67 ;; definition with list.
68 ;; (defun foo (... mutable-arg ...) ...) =>
69 ;; (defun foo (... m-arg ...) (let ((m-arg (list m-arg))) ...))
70 ;;
71 ;;; Code:
72
73 ;;; TODO:
74 ;; - Change new byte-code representation, so it directly gives the
75 ;; number of mandatory and optional arguments as well as whether or
76 ;; not there's a &rest arg.
77 ;; - Use abstract `make-closure' and `closure-ref' expressions, which bytecomp
78 ;; should turn into building corresponding byte-code function.
79 ;; - don't use `curry', instead build a new compiled-byte-code object
80 ;; (merge the closure env into the static constants pool).
81 ;; - warn about unused lexical vars.
82 ;; - clean up cconv-closure-convert-rec, especially the `let' binding part.
83 ;; - new byte codes for unwind-protect, catch, and condition-case so that
84 ;; closures aren't needed at all.
85
86 (eval-when-compile (require 'cl))
87
88 (defconst cconv-liftwhen 3
89 "Try to do lambda lifting if the number of arguments + free variables
90 is less than this number.")
91 (defvar cconv-mutated nil
92 "List of mutated variables in current form")
93 (defvar cconv-captured nil
94 "List of closure captured variables in current form")
95 (defvar cconv-captured+mutated nil
96 "An intersection between cconv-mutated and cconv-captured lists.")
97 (defvar cconv-lambda-candidates nil
98 "List of candidates for lambda lifting.
99 Each candidate has the form (VAR INCLOSURE BINDER PARENTFORM).")
100
101 (defun cconv-freevars (form &optional fvrs)
102 "Find all free variables of given form.
103 Arguments:
104 -- FORM is a piece of Elisp code after macroexpansion.
105 -- FVRS(optional) is a list of variables already found. Used for recursive tree
106 traversal
107
108 Returns a list of free variables."
109 ;; If a leaf in the tree is a symbol, but it is not a global variable, not a
110 ;; keyword, not 'nil or 't we consider this leaf as a variable.
111 ;; Free variables are the variables that are not declared above in this tree.
112 ;; For example free variables of (lambda (a1 a2 ..) body-forms) are
113 ;; free variables of body-forms excluding a1, a2 ..
114 ;; Free variables of (let ((v1 ..) (v2) ..)) body-forms) are
115 ;; free variables of body-forms excluding v1, v2 ...
116 ;; and so on.
117
118 ;; A list of free variables already found(FVRS) is passed in parameter
119 ;; to try to use cons or push where possible, and to minimize the usage
120 ;; of append.
121
122 ;; This function can return duplicates (because we use 'append instead
123 ;; of union of two sets - for performance reasons).
124 (pcase form
125 (`(let ,varsvalues . ,body-forms) ; let special form
126 (let ((fvrs-1 '()))
127 (dolist (exp body-forms)
128 (setq fvrs-1 (cconv-freevars exp fvrs-1)))
129 (dolist (elm varsvalues)
130 (setq fvrs-1 (delq (if (consp elm) (car elm) elm) fvrs-1)))
131 (setq fvrs (nconc fvrs-1 fvrs))
132 (dolist (exp varsvalues)
133 (when (consp exp) (setq fvrs (cconv-freevars (cadr exp) fvrs))))
134 fvrs))
135
136 (`(let* ,varsvalues . ,body-forms) ; let* special form
137 (let ((vrs '())
138 (fvrs-1 '()))
139 (dolist (exp varsvalues)
140 (if (consp exp)
141 (progn
142 (setq fvrs-1 (cconv-freevars (cadr exp) fvrs-1))
143 (dolist (elm vrs) (setq fvrs-1 (delq elm fvrs-1)))
144 (push (car exp) vrs))
145 (progn
146 (dolist (elm vrs) (setq fvrs-1 (delq elm fvrs-1)))
147 (push exp vrs))))
148 (dolist (exp body-forms)
149 (setq fvrs-1 (cconv-freevars exp fvrs-1)))
150 (dolist (elm vrs) (setq fvrs-1 (delq elm fvrs-1)))
151 (append fvrs fvrs-1)))
152
153 (`((lambda . ,_) . ,_) ; first element is lambda expression
154 (dolist (exp `((function ,(car form)) . ,(cdr form)))
155 (setq fvrs (cconv-freevars exp fvrs))) fvrs)
156
157 (`(cond . ,cond-forms) ; cond special form
158 (dolist (exp1 cond-forms)
159 (dolist (exp2 exp1)
160 (setq fvrs (cconv-freevars exp2 fvrs)))) fvrs)
161
162 (`(quote . ,_) fvrs) ; quote form
163
164 (`(function . ((lambda ,vars . ,body-forms)))
165 (let ((functionform (cadr form)) (fvrs-1 '()))
166 (dolist (exp body-forms)
167 (setq fvrs-1 (cconv-freevars exp fvrs-1)))
168 (dolist (elm vars) (setq fvrs-1 (delq elm fvrs-1)))
169 (append fvrs fvrs-1))) ; function form
170
171 (`(function . ,_) fvrs) ; same as quote
172 ;condition-case
173 (`(condition-case ,var ,protected-form . ,conditions-bodies)
174 (let ((fvrs-1 '()))
175 (dolist (exp conditions-bodies)
176 (setq fvrs-1 (cconv-freevars (cadr exp) fvrs-1)))
177 (setq fvrs-1 (delq var fvrs-1))
178 (setq fvrs-1 (cconv-freevars protected-form fvrs-1))
179 (append fvrs fvrs-1)))
180
181 (`(,(and sym (or `defun `defconst `defvar)) . ,_)
182 ;; We call cconv-freevars only for functions(lambdas)
183 ;; defun, defconst, defvar are not allowed to be inside
184 ;; a function (lambda).
185 ;; FIXME: should be a byte-compile-report-error!
186 (error "Invalid form: %s inside a function" sym))
187
188 (`(,_ . ,body-forms) ; First element is (like) a function.
189 (dolist (exp body-forms)
190 (setq fvrs (cconv-freevars exp fvrs))) fvrs)
191
192 (_ (if (byte-compile-not-lexical-var-p form)
193 fvrs
194 (cons form fvrs)))))
195
196 ;;;###autoload
197 (defun cconv-closure-convert (form)
198 "Main entry point for closure conversion.
199 -- FORM is a piece of Elisp code after macroexpansion.
200 -- TOPLEVEL(optional) is a boolean variable, true if we are at the root of AST
201
202 Returns a form where all lambdas don't have any free variables."
203 ;; (message "Entering cconv-closure-convert...")
204 (let ((cconv-mutated '())
205 (cconv-lambda-candidates '())
206 (cconv-captured '())
207 (cconv-captured+mutated '()))
208 ;; Analyse form - fill these variables with new information.
209 (cconv-analyse-form form '() 0)
210 ;; Calculate an intersection of cconv-mutated and cconv-captured.
211 (dolist (mvr cconv-mutated)
212 (when (memq mvr cconv-captured) ;
213 (push mvr cconv-captured+mutated)))
214 (cconv-closure-convert-rec
215 form ; the tree
216 '() ;
217 '() ; fvrs initially empty
218 '() ; envs initially empty
219 '()
220 )))
221
222 (defun cconv--lookup-let (table var binder form)
223 (let ((res nil))
224 (dolist (elem table)
225 (when (and (eq (nth 2 elem) binder)
226 (eq (nth 3 elem) form))
227 (assert (eq (car elem) var))
228 (setq res elem)))
229 res))
230
231 (defconst cconv--dummy-var (make-symbol "ignored"))
232 (defconst cconv--env-var (make-symbol "env"))
233
234 (defun cconv--set-diff (s1 s2)
235 "Return elements of set S1 that are not in set S2."
236 (let ((res '()))
237 (dolist (x s1)
238 (unless (memq x s2) (push x res)))
239 (nreverse res)))
240
241 (defun cconv--set-diff-map (s m)
242 "Return elements of set S that are not in Dom(M)."
243 (let ((res '()))
244 (dolist (x s)
245 (unless (assq x m) (push x res)))
246 (nreverse res)))
247
248 (defun cconv--map-diff (m1 m2)
249 "Return the submap of map M1 that has Dom(M2) removed."
250 (let ((res '()))
251 (dolist (x m1)
252 (unless (assq (car x) m2) (push x res)))
253 (nreverse res)))
254
255 (defun cconv--map-diff-elem (m x)
256 "Return the map M minus any mapping for X."
257 ;; Here we assume that X appears at most once in M.
258 (let* ((b (assq x m))
259 (res (if b (remq b m) m)))
260 (assert (null (assq x res))) ;; Check the assumption was warranted.
261 res))
262
263 (defun cconv--map-diff-set (m s)
264 "Return the map M minus any mapping for elements of S."
265 ;; Here we assume that X appears at most once in M.
266 (let ((res '()))
267 (dolist (b m)
268 (unless (memq (car b) s) (push b res)))
269 (nreverse res)))
270
271 (defun cconv-closure-convert-rec (form emvrs fvrs envs lmenvs)
272 ;; This function actually rewrites the tree.
273 "Eliminates all free variables of all lambdas in given forms.
274 Arguments:
275 -- FORM is a piece of Elisp code after macroexpansion.
276 -- LMENVS is a list of environments used for lambda-lifting. Initially empty.
277 -- EMVRS is a list that contains mutated variables that are visible
278 within current environment.
279 -- ENVS is an environment(list of free variables) of current closure.
280 Initially empty.
281 -- FVRS is a list of variables to substitute in each context.
282 Initially empty.
283
284 Returns a form where all lambdas don't have any free variables."
285 ;; What's the difference between fvrs and envs?
286 ;; Suppose that we have the code
287 ;; (lambda (..) fvr (let ((fvr 1)) (+ fvr 1)))
288 ;; only the first occurrence of fvr should be replaced by
289 ;; (aref env ...).
290 ;; So initially envs and fvrs are the same thing, but when we descend to
291 ;; the 'let, we delete fvr from fvrs. Why we don't delete fvr from envs?
292 ;; Because in envs the order of variables is important. We use this list
293 ;; to find the number of a specific variable in the environment vector,
294 ;; so we never touch it(unless we enter to the other closure).
295 ;;(if (listp form) (print (car form)) form)
296 (pcase form
297 (`(,(and letsym (or `let* `let)) ,binders . ,body-forms)
298
299 ; let and let* special forms
300 (let ((body-forms-new '())
301 (binders-new '())
302 ;; next for variables needed for delayed push
303 ;; because we should process <value(s)>
304 ;; before we change any arguments
305 (lmenvs-new '()) ;needed only in case of let
306 (emvrs-new '()) ;needed only in case of let
307 (emvr-push) ;needed only in case of let*
308 (lmenv-push)) ;needed only in case of let*
309
310 (dolist (binder binders)
311 (let* ((value nil)
312 (var (if (not (consp binder))
313 binder
314 (setq value (cadr binder))
315 (car binder)))
316 (new-val
317 (cond
318 ;; Check if var is a candidate for lambda lifting.
319 ((cconv--lookup-let cconv-lambda-candidates var binder form)
320
321 (let* ((fv (delete-dups (cconv-freevars value '())))
322 (funargs (cadr (cadr value)))
323 (funcvars (append fv funargs))
324 (funcbodies (cddadr value)) ; function bodies
325 (funcbodies-new '()))
326 ; lambda lifting condition
327 (if (or (not fv) (< cconv-liftwhen (length funcvars)))
328 ; do not lift
329 (cconv-closure-convert-rec
330 value emvrs fvrs envs lmenvs)
331 ; lift
332 (progn
333 (dolist (elm2 funcbodies)
334 (push ; convert function bodies
335 (cconv-closure-convert-rec
336 elm2 emvrs nil envs lmenvs)
337 funcbodies-new))
338 (if (eq letsym 'let*)
339 (setq lmenv-push (cons var fv))
340 (push (cons var fv) lmenvs-new))
341 ; push lifted function
342
343 `(function .
344 ((lambda ,funcvars .
345 ,(reverse funcbodies-new))))))))
346
347 ;; Check if it needs to be turned into a "ref-cell".
348 ((cconv--lookup-let cconv-captured+mutated var binder form)
349 ;; Declared variable is mutated and captured.
350 (prog1
351 `(list ,(cconv-closure-convert-rec
352 value emvrs
353 fvrs envs lmenvs))
354 (if (eq letsym 'let*)
355 (setq emvr-push var)
356 (push var emvrs-new))))
357
358 ;; Normal default case.
359 (t
360 (cconv-closure-convert-rec
361 value emvrs fvrs envs lmenvs)))))
362
363 ;; this piece of code below letbinds free
364 ;; variables of a lambda lifted function
365 ;; if they are redefined in this let
366 ;; example:
367 ;; (let* ((fun (lambda (x) (+ x y))) (y 1)) (funcall fun 1))
368 ;; Here we can not pass y as parameter because it is
369 ;; redefined. We add a (closed-y y) declaration.
370 ;; We do that even if the function is not used inside
371 ;; this let(*). The reason why we ignore this case is
372 ;; that we can't "look forward" to see if the function
373 ;; is called there or not. To treat well this case we
374 ;; need to traverse the tree one more time to collect this
375 ;; data, and I think that it's not worth it.
376
377 (when (eq letsym 'let*)
378 (let ((closedsym '())
379 (new-lmenv '())
380 (old-lmenv '()))
381 (dolist (lmenv lmenvs)
382 (when (memq var (cdr lmenv))
383 (setq closedsym
384 (make-symbol
385 (concat "closed-" (symbol-name var))))
386 (setq new-lmenv (list (car lmenv)))
387 (dolist (frv (cdr lmenv)) (if (eq frv var)
388 (push closedsym new-lmenv)
389 (push frv new-lmenv)))
390 (setq new-lmenv (reverse new-lmenv))
391 (setq old-lmenv lmenv)))
392 (when new-lmenv
393 (setq lmenvs (remq old-lmenv lmenvs))
394 (push new-lmenv lmenvs)
395 (push `(,closedsym ,var) binders-new))))
396 ;; We push the element after redefined free variables are
397 ;; processed. This is important to avoid the bug when free
398 ;; variable and the function have the same name.
399 (push (list var new-val) binders-new)
400
401 (when (eq letsym 'let*) ; update fvrs
402 (setq fvrs (remq var fvrs))
403 (setq emvrs (remq var emvrs)) ; remove if redefined
404 (when emvr-push
405 (push emvr-push emvrs)
406 (setq emvr-push nil))
407 (setq lmenvs (cconv--map-diff-elem lmenvs var))
408 (when lmenv-push
409 (push lmenv-push lmenvs)
410 (setq lmenv-push nil)))
411 )) ; end of dolist over binders
412 (when (eq letsym 'let)
413
414 (let (var fvrs-1 emvrs-1 lmenvs-1)
415 ;; Here we update emvrs, fvrs and lmenvs lists
416 (setq fvrs (cconv--set-diff-map fvrs binders-new))
417 (setq emvrs (cconv--set-diff-map emvrs binders-new))
418 (setq emvrs (append emvrs emvrs-new))
419 (setq lmenvs (cconv--set-diff-map lmenvs binders-new))
420 (setq lmenvs (append lmenvs lmenvs-new)))
421
422 ;; Here we do the same letbinding as for let* above
423 ;; to avoid situation when a free variable of a lambda lifted
424 ;; function got redefined.
425
426 (let ((new-lmenv)
427 (var nil)
428 (closedsym nil)
429 (letbinds '()))
430 (dolist (binder binders)
431 (setq var (if (consp binder) (car binder) binder))
432
433 (let ((lmenvs-1 lmenvs)) ; just to avoid manipulating
434 (dolist (lmenv lmenvs-1) ; the counter inside the loop
435 (when (memq var (cdr lmenv))
436 (setq closedsym (make-symbol
437 (concat "closed-"
438 (symbol-name var))))
439
440 (setq new-lmenv (list (car lmenv)))
441 (dolist (frv (cdr lmenv))
442 (push (if (eq frv var) closedsym frv)
443 new-lmenv))
444 (setq new-lmenv (reverse new-lmenv))
445 (setq lmenvs (remq lmenv lmenvs))
446 (push new-lmenv lmenvs)
447 (push `(,closedsym ,var) letbinds)
448 ))))
449 (setq binders-new (append binders-new letbinds))))
450
451 (dolist (elm body-forms) ; convert body forms
452 (push (cconv-closure-convert-rec
453 elm emvrs fvrs envs lmenvs)
454 body-forms-new))
455 `(,letsym ,(reverse binders-new) . ,(reverse body-forms-new))))
456 ;end of let let* forms
457
458 ; first element is lambda expression
459 (`(,(and `(lambda . ,_) fun) . ,other-body-forms)
460
461 (let ((other-body-forms-new '()))
462 (dolist (elm other-body-forms)
463 (push (cconv-closure-convert-rec
464 elm emvrs fvrs envs lmenvs)
465 other-body-forms-new))
466 `(funcall
467 ,(cconv-closure-convert-rec
468 (list 'function fun) emvrs fvrs envs lmenvs)
469 ,@(nreverse other-body-forms-new))))
470
471 (`(cond . ,cond-forms) ; cond special form
472 (let ((cond-forms-new '()))
473 (dolist (elm cond-forms)
474 (push (let ((elm-new '()))
475 (dolist (elm-2 elm)
476 (push
477 (cconv-closure-convert-rec
478 elm-2 emvrs fvrs envs lmenvs)
479 elm-new))
480 (reverse elm-new))
481 cond-forms-new))
482 (cons 'cond
483 (reverse cond-forms-new))))
484
485 (`(quote . ,_) form)
486
487 (`(function (lambda ,vars . ,body-forms)) ; function form
488 (let* ((fvrs-new (cconv--set-diff fvrs vars)) ; Remove vars from fvrs.
489 (fv (delete-dups (cconv-freevars form '())))
490 (leave fvrs-new) ; leave=non-nil if we should leave env unchanged.
491 (body-forms-new '())
492 (letbind '())
493 (mv nil)
494 (envector nil))
495 (when fv
496 ;; Here we form our environment vector.
497 ;; If outer closure contains all
498 ;; free variables of this function(and nothing else)
499 ;; then we use the same environment vector as for outer closure,
500 ;; i.e. we leave the environment vector unchanged,
501 ;; otherwise we build a new environment vector.
502 (if (eq (length envs) (length fv))
503 (let ((fv-temp fv))
504 (while (and fv-temp leave)
505 (when (not (memq (car fv-temp) fvrs-new)) (setq leave nil))
506 (setq fv-temp (cdr fv-temp))))
507 (setq leave nil))
508
509 (if (not leave)
510 (progn
511 (dolist (elm fv)
512 (push
513 (cconv-closure-convert-rec
514 ;; Remove `elm' from `emvrs' for this call because in case
515 ;; `elm' is a variable that's wrapped in a cons-cell, we
516 ;; want to put the cons-cell itself in the closure, rather
517 ;; than just a copy of its current content.
518 elm (remq elm emvrs) fvrs envs lmenvs)
519 envector)) ; Process vars for closure vector.
520 (setq envector (reverse envector))
521 (setq envs fv))
522 (setq envector `(,cconv--env-var))) ; Leave unchanged.
523 (setq fvrs-new fv)) ; Update substitution list.
524
525 (setq emvrs (cconv--set-diff emvrs vars))
526 (setq lmenvs (cconv--map-diff-set lmenvs vars))
527
528 ;; The difference between envs and fvrs is explained
529 ;; in comment in the beginning of the function.
530 (dolist (elm cconv-captured+mutated) ; Find mutated arguments
531 (setq mv (car elm)) ; used in inner closures.
532 (when (and (memq mv vars) (eq form (caddr elm)))
533 (progn (push mv emvrs)
534 (push `(,mv (list ,mv)) letbind))))
535 (dolist (elm body-forms) ; convert function body
536 (push (cconv-closure-convert-rec
537 elm emvrs fvrs-new envs lmenvs)
538 body-forms-new))
539
540 (setq body-forms-new
541 (if letbind `((let ,letbind . ,(reverse body-forms-new)))
542 (reverse body-forms-new)))
543
544 (cond
545 ;if no freevars - do nothing
546 ((null envector)
547 `(function (lambda ,vars . ,body-forms-new)))
548 ; 1 free variable - do not build vector
549 ((null (cdr envector))
550 `(curry
551 (function (lambda (,cconv--env-var . ,vars) . ,body-forms-new))
552 ,(car envector)))
553 ; >=2 free variables - build vector
554 (t
555 `(curry
556 (function (lambda (,cconv--env-var . ,vars) . ,body-forms-new))
557 (vector . ,envector))))))
558
559 (`(function . ,_) form) ; Same as quote.
560
561 ;defconst, defvar
562 (`(,(and sym (or `defconst `defvar)) ,definedsymbol . ,body-forms)
563
564 (let ((body-forms-new '()))
565 (dolist (elm body-forms)
566 (push (cconv-closure-convert-rec
567 elm emvrs fvrs envs lmenvs)
568 body-forms-new))
569 (setq body-forms-new (reverse body-forms-new))
570 `(,sym ,definedsymbol . ,body-forms-new)))
571
572 ;defun, defmacro
573 (`(,(and sym (or `defun `defmacro))
574 ,func ,vars . ,body-forms)
575 (let ((body-new '()) ; The whole body.
576 (body-forms-new '()) ; Body w\o docstring and interactive.
577 (letbind '()))
578 ; Find mutable arguments.
579 (dolist (elm vars)
580 (let ((lmutated cconv-captured+mutated)
581 (ismutated nil))
582 (while (and lmutated (not ismutated))
583 (when (and (eq (caar lmutated) elm)
584 (eq (caddar lmutated) form))
585 (setq ismutated t))
586 (setq lmutated (cdr lmutated)))
587 (when ismutated
588 (push elm letbind)
589 (push elm emvrs))))
590 ;Transform body-forms.
591 (when (stringp (car body-forms)) ; Treat docstring well.
592 (push (car body-forms) body-new)
593 (setq body-forms (cdr body-forms)))
594 (when (eq (car-safe (car body-forms)) 'interactive)
595 (push (cconv-closure-convert-rec
596 (car body-forms)
597 emvrs fvrs envs lmenvs)
598 body-new)
599 (setq body-forms (cdr body-forms)))
600
601 (dolist (elm body-forms)
602 (push (cconv-closure-convert-rec
603 elm emvrs fvrs envs lmenvs)
604 body-forms-new))
605 (setq body-forms-new (reverse body-forms-new))
606
607 (if letbind
608 ; Letbind mutable arguments.
609 (let ((binders-new '()))
610 (dolist (elm letbind) (push `(,elm (list ,elm))
611 binders-new))
612 (push `(let ,(reverse binders-new) .
613 ,body-forms-new) body-new)
614 (setq body-new (reverse body-new)))
615 (setq body-new (append (reverse body-new) body-forms-new)))
616
617 `(,sym ,func ,vars . ,body-new)))
618
619 ;condition-case
620 (`(condition-case ,var ,protected-form . ,handlers)
621 (let ((handlers-new '())
622 (newform (cconv-closure-convert-rec
623 `(function (lambda () ,protected-form))
624 emvrs fvrs envs lmenvs)))
625 (setq fvrs (remq var fvrs))
626 (dolist (handler handlers)
627 (push (list (car handler)
628 (cconv-closure-convert-rec
629 `(function (lambda (,(or var cconv--dummy-var))
630 ,@(cdr handler)))
631 emvrs fvrs envs lmenvs))
632 handlers-new))
633 `(condition-case :fun-body ,newform
634 ,@(nreverse handlers-new))))
635
636 (`(,(and head (or `catch `unwind-protect)) ,form . ,body)
637 `(,head ,(cconv-closure-convert-rec form emvrs fvrs envs lmenvs)
638 :fun-body
639 ,(cconv-closure-convert-rec `(function (lambda () ,@body))
640 emvrs fvrs envs lmenvs)))
641
642 (`(track-mouse . ,body)
643 `(track-mouse
644 :fun-body
645 ,(cconv-closure-convert-rec `(function (lambda () ,@body))
646 emvrs fvrs envs lmenvs)))
647
648 (`(setq . ,forms) ; setq special form
649 (let (prognlist sym sym-new value)
650 (while forms
651 (setq sym (car forms))
652 (setq sym-new (cconv-closure-convert-rec
653 sym
654 (remq sym emvrs) fvrs envs lmenvs))
655 (setq value
656 (cconv-closure-convert-rec
657 (cadr forms) emvrs fvrs envs lmenvs))
658 (if (memq sym emvrs)
659 (push `(setcar ,sym-new ,value) prognlist)
660 (if (symbolp sym-new)
661 (push `(setq ,sym-new ,value) prognlist)
662 (debug) ;FIXME: When can this be right?
663 (push `(set ,sym-new ,value) prognlist)))
664 (setq forms (cddr forms)))
665 (if (cdr prognlist)
666 `(progn . ,(reverse prognlist))
667 (car prognlist))))
668
669 (`(,(and (or `funcall `apply) callsym) ,fun . ,args)
670 ; funcall is not a special form
671 ; but we treat it separately
672 ; for the needs of lambda lifting
673 (let ((fv (cdr (assq fun lmenvs))))
674 (if fv
675 (let ((args-new '())
676 (processed-fv '()))
677 ;; All args (free variables and actual arguments)
678 ;; should be processed, because they can be fvrs
679 ;; (free variables of another closure)
680 (dolist (fvr fv)
681 (push (cconv-closure-convert-rec
682 fvr (remq fvr emvrs)
683 fvrs envs lmenvs)
684 processed-fv))
685 (setq processed-fv (reverse processed-fv))
686 (dolist (elm args)
687 (push (cconv-closure-convert-rec
688 elm emvrs fvrs envs lmenvs)
689 args-new))
690 (setq args-new (append processed-fv (reverse args-new)))
691 (setq fun (cconv-closure-convert-rec
692 fun emvrs fvrs envs lmenvs))
693 `(,callsym ,fun . ,args-new))
694 (let ((cdr-new '()))
695 (dolist (elm (cdr form))
696 (push (cconv-closure-convert-rec
697 elm emvrs fvrs envs lmenvs)
698 cdr-new))
699 `(,callsym . ,(reverse cdr-new))))))
700
701 (`(,func . ,body-forms) ; first element is function or whatever
702 ; function-like forms are:
703 ; or, and, if, progn, prog1, prog2,
704 ; while, until
705 (let ((body-forms-new '()))
706 (dolist (elm body-forms)
707 (push (cconv-closure-convert-rec
708 elm emvrs fvrs envs lmenvs)
709 body-forms-new))
710 (setq body-forms-new (reverse body-forms-new))
711 `(,func . ,body-forms-new)))
712
713 (_
714 (let ((free (memq form fvrs)))
715 (if free ;form is a free variable
716 (let* ((numero (- (length fvrs) (length free)))
717 (var (if (null (cdr envs))
718 cconv--env-var
719 ;; Replace form => (aref env #)
720 `(aref ,cconv--env-var ,numero))))
721 (if (memq form emvrs) ; form => (car (aref env #)) if mutable
722 `(car ,var)
723 var))
724 (if (memq form emvrs) ; if form is a mutable variable
725 `(car ,form) ; replace form => (car form)
726 form))))))
727
728 (defun cconv-analyse-function (args body env parentform inclosure)
729 (dolist (arg args)
730 (cond
731 ((byte-compile-not-lexical-var-p arg)
732 (byte-compile-report-error
733 (format "Argument %S is not a lexical variable" arg)))
734 ((eq ?& (aref (symbol-name arg) 0)) nil) ;Ignore &rest, &optional, ...
735 (t (push (list arg inclosure parentform) env)))) ;Push vrs to vars.
736 (dolist (form body) ;Analyse body forms.
737 (cconv-analyse-form form env inclosure)))
738
739 (defun cconv-analyse-form (form env inclosure)
740 "Find mutated variables and variables captured by closure. Analyse
741 lambdas if they are suitable for lambda lifting.
742 -- FORM is a piece of Elisp code after macroexpansion.
743 -- ENV is a list of variables visible in current lexical environment.
744 Each entry has the form (VAR INCLOSURE BINDER PARENTFORM)
745 for let-bound vars and (VAR INCLOSURE PARENTFORM) for function arguments.
746 -- INCLOSURE is the nesting level within lambdas."
747 (pcase form
748 ; let special form
749 (`(,(and (or `let* `let) letsym) ,binders . ,body-forms)
750
751 (let ((orig-env env)
752 (var nil)
753 (value nil))
754 (dolist (binder binders)
755 (if (not (consp binder))
756 (progn
757 (setq var binder) ; treat the form (let (x) ...) well
758 (setq value nil))
759 (setq var (car binder))
760 (setq value (cadr binder))
761
762 (cconv-analyse-form value (if (eq letsym 'let*) env orig-env)
763 inclosure))
764
765 (unless (byte-compile-not-lexical-var-p var)
766 (let ((varstruct (list var inclosure binder form)))
767 (push varstruct env) ; Push a new one.
768
769 (pcase value
770 (`(function (lambda . ,_))
771 ;; If var is a function push it to lambda list.
772 (push varstruct cconv-lambda-candidates)))))))
773
774 (dolist (form body-forms) ; Analyse body forms.
775 (cconv-analyse-form form env inclosure)))
776
777 ; defun special form
778 (`(,(or `defun `defmacro) ,func ,vrs . ,body-forms)
779 (when env
780 (byte-compile-log-warning
781 (format "Function %S will ignore its context %S"
782 func (mapcar #'car env))
783 t :warning))
784 (cconv-analyse-function vrs body-forms nil form 0))
785
786 (`(function (lambda ,vrs . ,body-forms))
787 (cconv-analyse-function vrs body-forms env form (1+ inclosure)))
788
789 (`(setq . ,forms)
790 ;; If a local variable (member of env) is modified by setq then
791 ;; it is a mutated variable.
792 (while forms
793 (let ((v (assq (car forms) env))) ; v = non nil if visible
794 (when v
795 (push v cconv-mutated)
796 ;; Delete from candidate list for lambda lifting.
797 (setq cconv-lambda-candidates (delq v cconv-lambda-candidates))
798 (unless (eq inclosure (cadr v)) ;Bound in a different closure level.
799 (push v cconv-captured))))
800 (cconv-analyse-form (cadr forms) env inclosure)
801 (setq forms (cddr forms))))
802
803 (`((lambda . ,_) . ,_) ; first element is lambda expression
804 (dolist (exp `((function ,(car form)) . ,(cdr form)))
805 (cconv-analyse-form exp env inclosure)))
806
807 (`(cond . ,cond-forms) ; cond special form
808 (dolist (forms cond-forms)
809 (dolist (form forms)
810 (cconv-analyse-form form env inclosure))))
811
812 (`(quote . ,_) nil) ; quote form
813 (`(function . ,_) nil) ; same as quote
814
815 (`(condition-case ,var ,protected-form . ,handlers)
816 ;; FIXME: The bytecode for condition-case forces us to wrap the
817 ;; form and handlers in closures (for handlers, it's probably
818 ;; unavoidable, but not for the protected form).
819 (setq inclosure (1+ inclosure))
820 (cconv-analyse-form protected-form env inclosure)
821 (push (list var inclosure form) env)
822 (dolist (handler handlers)
823 (dolist (form (cdr handler))
824 (cconv-analyse-form form env inclosure))))
825
826 ;; FIXME: The bytecode for catch forces us to wrap the body.
827 (`(,(or `catch `unwind-protect) ,form . ,body)
828 (cconv-analyse-form form env inclosure)
829 (setq inclosure (1+ inclosure))
830 (dolist (form body)
831 (cconv-analyse-form form env inclosure)))
832
833 ;; FIXME: The bytecode for save-window-excursion and the lack of
834 ;; bytecode for track-mouse forces us to wrap the body.
835 (`(track-mouse . ,body)
836 (setq inclosure (1+ inclosure))
837 (dolist (form body)
838 (cconv-analyse-form form env inclosure)))
839
840 (`(,(or `defconst `defvar) ,var ,value . ,_)
841 (push var byte-compile-bound-variables)
842 (cconv-analyse-form value env inclosure))
843
844 (`(,(or `funcall `apply) ,fun . ,args)
845 ;; Here we ignore fun because funcall and apply are the only two
846 ;; functions where we can pass a candidate for lambda lifting as
847 ;; argument. So, if we see fun elsewhere, we'll delete it from
848 ;; lambda candidate list.
849 (if (symbolp fun)
850 (let ((lv (assq fun cconv-lambda-candidates)))
851 (when lv
852 (unless (eq (cadr lv) inclosure)
853 (push lv cconv-captured)
854 ;; If this funcall and the definition of fun are in
855 ;; different closures - we delete fun from candidate
856 ;; list, because it is too complicated to manage free
857 ;; variables in this case.
858 (setq cconv-lambda-candidates
859 (delq lv cconv-lambda-candidates)))))
860 (cconv-analyse-form fun env inclosure))
861 (dolist (form args)
862 (cconv-analyse-form form env inclosure)))
863
864 (`(,_ . ,body-forms) ; First element is a function or whatever.
865 (dolist (form body-forms)
866 (cconv-analyse-form form env inclosure)))
867
868 ((pred symbolp)
869 (let ((dv (assq form env))) ; dv = declared and visible
870 (when dv
871 (unless (eq inclosure (cadr dv)) ; capturing condition
872 (push dv cconv-captured))
873 ;; Delete lambda if it is found here, since it escapes.
874 (setq cconv-lambda-candidates
875 (delq dv cconv-lambda-candidates)))))))
876
877 (provide 'cconv)
878 ;;; cconv.el ends here