cconv.el 30 KB

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