New branch for lexbind, losing all history.
[bpt/emacs.git] / lisp / emacs-lisp / bytecomp.el
1 ;;; bytecomp.el --- compilation of Lisp code into byte code
2
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1998, 2000, 2001, 2002,
4 ;; 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 ;; Author: Jamie Zawinski <jwz@lucid.com>
7 ;; Hallvard Furuseth <hbf@ulrik.uio.no>
8 ;; Maintainer: FSF
9 ;; Keywords: lisp
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; The Emacs Lisp byte compiler. This crunches lisp source into a sort
29 ;; of p-code (`lapcode') which takes up less space and can be interpreted
30 ;; faster. [`LAP' == `Lisp Assembly Program'.]
31 ;; The user entry points are byte-compile-file and byte-recompile-directory.
32
33 ;;; Code:
34
35 ;; ========================================================================
36 ;; Entry points:
37 ;; byte-recompile-directory, byte-compile-file,
38 ;; batch-byte-compile, batch-byte-recompile-directory,
39 ;; byte-compile, compile-defun,
40 ;; display-call-tree
41 ;; (byte-compile-buffer and byte-compile-and-load-file were turned off
42 ;; because they are not terribly useful and get in the way of completion.)
43
44 ;; This version of the byte compiler has the following improvements:
45 ;; + optimization of compiled code:
46 ;; - removal of unreachable code;
47 ;; - removal of calls to side-effectless functions whose return-value
48 ;; is unused;
49 ;; - compile-time evaluation of safe constant forms, such as (consp nil)
50 ;; and (ash 1 6);
51 ;; - open-coding of literal lambdas;
52 ;; - peephole optimization of emitted code;
53 ;; - trivial functions are left uncompiled for speed.
54 ;; + support for inline functions;
55 ;; + compile-time evaluation of arbitrary expressions;
56 ;; + compile-time warning messages for:
57 ;; - functions being redefined with incompatible arglists;
58 ;; - functions being redefined as macros, or vice-versa;
59 ;; - functions or macros defined multiple times in the same file;
60 ;; - functions being called with the incorrect number of arguments;
61 ;; - functions being called which are not defined globally, in the
62 ;; file, or as autoloads;
63 ;; - assignment and reference of undeclared free variables;
64 ;; - various syntax errors;
65 ;; + correct compilation of nested defuns, defmacros, defvars and defsubsts;
66 ;; + correct compilation of top-level uses of macros;
67 ;; + the ability to generate a histogram of functions called.
68
69 ;; User customization variables: M-x customize-group bytecomp
70
71 ;; New Features:
72 ;;
73 ;; o The form `defsubst' is just like `defun', except that the function
74 ;; generated will be open-coded in compiled code which uses it. This
75 ;; means that no function call will be generated, it will simply be
76 ;; spliced in. Lisp functions calls are very slow, so this can be a
77 ;; big win.
78 ;;
79 ;; You can generally accomplish the same thing with `defmacro', but in
80 ;; that case, the defined procedure can't be used as an argument to
81 ;; mapcar, etc.
82 ;;
83 ;; o You can also open-code one particular call to a function without
84 ;; open-coding all calls. Use the 'inline' form to do this, like so:
85 ;;
86 ;; (inline (foo 1 2 3)) ;; `foo' will be open-coded
87 ;; or...
88 ;; (inline ;; `foo' and `baz' will be
89 ;; (foo 1 2 3 (bar 5)) ;; open-coded, but `bar' will not.
90 ;; (baz 0))
91 ;;
92 ;; o It is possible to open-code a function in the same file it is defined
93 ;; in without having to load that file before compiling it. The
94 ;; byte-compiler has been modified to remember function definitions in
95 ;; the compilation environment in the same way that it remembers macro
96 ;; definitions.
97 ;;
98 ;; o Forms like ((lambda ...) ...) are open-coded.
99 ;;
100 ;; o The form `eval-when-compile' is like progn, except that the body
101 ;; is evaluated at compile-time. When it appears at top-level, this
102 ;; is analogous to the Common Lisp idiom (eval-when (compile) ...).
103 ;; When it does not appear at top-level, it is similar to the
104 ;; Common Lisp #. reader macro (but not in interpreted code).
105 ;;
106 ;; o The form `eval-and-compile' is similar to eval-when-compile, but
107 ;; the whole form is evalled both at compile-time and at run-time.
108 ;;
109 ;; o The command compile-defun is analogous to eval-defun.
110 ;;
111 ;; o If you run byte-compile-file on a filename which is visited in a
112 ;; buffer, and that buffer is modified, you are asked whether you want
113 ;; to save the buffer before compiling.
114 ;;
115 ;; o byte-compiled files now start with the string `;ELC'.
116 ;; Some versions of `file' can be customized to recognize that.
117
118 (require 'backquote)
119 (require 'macroexp)
120 (eval-when-compile (require 'cl))
121
122 (or (fboundp 'defsubst)
123 ;; This really ought to be loaded already!
124 (load "byte-run"))
125
126 ;; We want to do (require 'byte-lexbind) when compiling, to avoid compilation
127 ;; errors; however that file also wants to do (require 'bytecomp) for the
128 ;; same reason. Since we know it's OK to load byte-lexbind.el second, we
129 ;; have that file require a feature that's provided before at the beginning
130 ;; of this file, to avoid an infinite require loop.
131 ;; `eval-when-compile' is defined in byte-run.el, so it must come after the
132 ;; preceding load expression.
133 (provide 'bytecomp-preload)
134 (eval-when-compile (require 'byte-lexbind))
135
136 ;; The feature of compiling in a specific target Emacs version
137 ;; has been turned off because compile time options are a bad idea.
138 (defmacro byte-compile-single-version () nil)
139 (defmacro byte-compile-version-cond (cond) cond)
140
141 ;; The crud you see scattered through this file of the form
142 ;; (or (and (boundp 'epoch::version) epoch::version)
143 ;; (string-lessp emacs-version "19"))
144 ;; is because the Epoch folks couldn't be bothered to follow the
145 ;; normal emacs version numbering convention.
146
147 ;; (if (byte-compile-version-cond
148 ;; (or (and (boundp 'epoch::version) epoch::version)
149 ;; (string-lessp emacs-version "19")))
150 ;; (progn
151 ;; ;; emacs-18 compatibility.
152 ;; (defvar baud-rate (baud-rate)) ;Define baud-rate if it's undefined
153 ;;
154 ;; (if (byte-compile-single-version)
155 ;; (defmacro byte-code-function-p (x) "Emacs 18 doesn't have these." nil)
156 ;; (defun byte-code-function-p (x) "Emacs 18 doesn't have these." nil))
157 ;;
158 ;; (or (and (fboundp 'member)
159 ;; ;; avoid using someone else's possibly bogus definition of this.
160 ;; (subrp (symbol-function 'member)))
161 ;; (defun member (elt list)
162 ;; "like memq, but uses equal instead of eq. In v19, this is a subr."
163 ;; (while (and list (not (equal elt (car list))))
164 ;; (setq list (cdr list)))
165 ;; list))))
166
167
168 (defgroup bytecomp nil
169 "Emacs Lisp byte-compiler."
170 :group 'lisp)
171
172 (defcustom emacs-lisp-file-regexp "\\.el\\'"
173 "Regexp which matches Emacs Lisp source files.
174 If you change this, you might want to set `byte-compile-dest-file-function'."
175 :group 'bytecomp
176 :type 'regexp)
177
178 (defcustom byte-compile-dest-file-function nil
179 "Function for the function `byte-compile-dest-file' to call.
180 It should take one argument, the name of an Emacs Lisp source
181 file name, and return the name of the compiled file."
182 :group 'bytecomp
183 :type '(choice (const nil) function)
184 :version "23.2")
185
186 ;; This enables file name handlers such as jka-compr
187 ;; to remove parts of the file name that should not be copied
188 ;; through to the output file name.
189 (defun byte-compiler-base-file-name (filename)
190 (let ((handler (find-file-name-handler filename
191 'byte-compiler-base-file-name)))
192 (if handler
193 (funcall handler 'byte-compiler-base-file-name filename)
194 filename)))
195
196 (or (fboundp 'byte-compile-dest-file)
197 ;; The user may want to redefine this along with emacs-lisp-file-regexp,
198 ;; so only define it if it is undefined.
199 ;; Note - redefining this function is obsolete as of 23.2.
200 ;; Customize byte-compile-dest-file-function instead.
201 (defun byte-compile-dest-file (filename)
202 "Convert an Emacs Lisp source file name to a compiled file name.
203 If `byte-compile-dest-file-function' is non-nil, uses that
204 function to do the work. Otherwise, if FILENAME matches
205 `emacs-lisp-file-regexp' (by default, files with the extension `.el'),
206 adds `c' to it; otherwise adds `.elc'."
207 (if byte-compile-dest-file-function
208 (funcall byte-compile-dest-file-function filename)
209 (setq filename (file-name-sans-versions
210 (byte-compiler-base-file-name filename)))
211 (cond ((string-match emacs-lisp-file-regexp filename)
212 (concat (substring filename 0 (match-beginning 0)) ".elc"))
213 (t (concat filename ".elc"))))))
214
215 ;; This can be the 'byte-compile property of any symbol.
216 (autoload 'byte-compile-inline-expand "byte-opt")
217
218 ;; This is the entrypoint to the lapcode optimizer pass1.
219 (autoload 'byte-optimize-form "byte-opt")
220 ;; This is the entrypoint to the lapcode optimizer pass2.
221 (autoload 'byte-optimize-lapcode "byte-opt")
222 (autoload 'byte-compile-unfold-lambda "byte-opt")
223
224 ;; This is the entry point to the decompiler, which is used by the
225 ;; disassembler. The disassembler just requires 'byte-compile, but
226 ;; that doesn't define this function, so this seems to be a reasonable
227 ;; thing to do.
228 (autoload 'byte-decompile-bytecode "byte-opt")
229
230 (defcustom byte-compile-verbose
231 (and (not noninteractive) (> baud-rate search-slow-speed))
232 "Non-nil means print messages describing progress of byte-compiler."
233 :group 'bytecomp
234 :type 'boolean)
235
236 (defcustom byte-optimize t
237 "Enable optimization in the byte compiler.
238 Possible values are:
239 nil - no optimization
240 t - all optimizations
241 `source' - source-level optimizations only
242 `byte' - code-level optimizations only"
243 :group 'bytecomp
244 :type '(choice (const :tag "none" nil)
245 (const :tag "all" t)
246 (const :tag "source-level" source)
247 (const :tag "byte-level" byte)))
248
249 (defcustom byte-compile-delete-errors nil
250 "If non-nil, the optimizer may delete forms that may signal an error.
251 This includes variable references and calls to functions such as `car'."
252 :group 'bytecomp
253 :type 'boolean)
254
255 (defvar byte-compile-dynamic nil
256 "If non-nil, compile function bodies so they load lazily.
257 They are hidden in comments in the compiled file,
258 and each one is brought into core when the
259 function is called.
260
261 To enable this option, make it a file-local variable
262 in the source file you want it to apply to.
263 For example, add -*-byte-compile-dynamic: t;-*- on the first line.
264
265 When this option is true, if you load the compiled file and then move it,
266 the functions you loaded will not be able to run.")
267 ;;;###autoload(put 'byte-compile-dynamic 'safe-local-variable 'booleanp)
268
269 (defvar byte-compile-disable-print-circle nil
270 "If non-nil, disable `print-circle' on printing a byte-compiled code.")
271 ;;;###autoload(put 'byte-compile-disable-print-circle 'safe-local-variable 'booleanp)
272
273 (defcustom byte-compile-dynamic-docstrings t
274 "If non-nil, compile doc strings for lazy access.
275 We bury the doc strings of functions and variables inside comments in
276 the file, and bring them into core only when they are actually needed.
277
278 When this option is true, if you load the compiled file and then move it,
279 you won't be able to find the documentation of anything in that file.
280
281 To disable this option for a certain file, make it a file-local variable
282 in the source file. For example, add this to the first line:
283 -*-byte-compile-dynamic-docstrings:nil;-*-
284 You can also set the variable globally.
285
286 This option is enabled by default because it reduces Emacs memory usage."
287 :group 'bytecomp
288 :type 'boolean)
289 ;;;###autoload(put 'byte-compile-dynamic-docstrings 'safe-local-variable 'booleanp)
290
291 (defcustom byte-optimize-log nil
292 "If true, the byte-compiler will log its optimizations into *Compile-Log*.
293 If this is 'source, then only source-level optimizations will be logged.
294 If it is 'byte, then only byte-level optimizations will be logged."
295 :group 'bytecomp
296 :type '(choice (const :tag "none" nil)
297 (const :tag "all" t)
298 (const :tag "source-level" source)
299 (const :tag "byte-level" byte)))
300
301 (defcustom byte-compile-error-on-warn nil
302 "If true, the byte-compiler reports warnings with `error'."
303 :group 'bytecomp
304 :type 'boolean)
305
306 (defconst byte-compile-warning-types
307 '(redefine callargs free-vars unresolved
308 obsolete noruntime cl-functions interactive-only
309 make-local mapcar constants suspicious)
310 "The list of warning types used when `byte-compile-warnings' is t.")
311 (defcustom byte-compile-warnings t
312 "List of warnings that the byte-compiler should issue (t for all).
313
314 Elements of the list may be:
315
316 free-vars references to variables not in the current lexical scope.
317 unresolved calls to unknown functions.
318 callargs function calls with args that don't match the definition.
319 redefine function name redefined from a macro to ordinary function or vice
320 versa, or redefined to take a different number of arguments.
321 obsolete obsolete variables and functions.
322 noruntime functions that may not be defined at runtime (typically
323 defined only under `eval-when-compile').
324 cl-functions calls to runtime functions from the CL package (as
325 distinguished from macros and aliases).
326 interactive-only
327 commands that normally shouldn't be called from Lisp code.
328 make-local calls to make-variable-buffer-local that may be incorrect.
329 mapcar mapcar called for effect.
330 constants let-binding of, or assignment to, constants/nonvariables.
331 suspicious constructs that usually don't do what the coder wanted.
332
333 If the list begins with `not', then the remaining elements specify warnings to
334 suppress. For example, (not mapcar) will suppress warnings about mapcar."
335 :group 'bytecomp
336 :type `(choice (const :tag "All" t)
337 (set :menu-tag "Some"
338 ,@(mapcar (lambda (x) `(const ,x))
339 byte-compile-warning-types))))
340 ;;;###autoload(put 'byte-compile-warnings 'safe-local-variable 'byte-compile-warnings-safe-p)
341
342 ;;;###autoload
343 (defun byte-compile-warnings-safe-p (x)
344 "Return non-nil if X is valid as a value of `byte-compile-warnings'."
345 (or (booleanp x)
346 (and (listp x)
347 (if (eq (car x) 'not) (setq x (cdr x))
348 t)
349 (equal (mapcar
350 (lambda (e)
351 (when (memq e byte-compile-warning-types)
352 e))
353 x)
354 x))))
355
356 (defun byte-compile-warning-enabled-p (warning)
357 "Return non-nil if WARNING is enabled, according to `byte-compile-warnings'."
358 (or (eq byte-compile-warnings t)
359 (if (eq (car byte-compile-warnings) 'not)
360 (not (memq warning byte-compile-warnings))
361 (memq warning byte-compile-warnings))))
362
363 ;;;###autoload
364 (defun byte-compile-disable-warning (warning)
365 "Change `byte-compile-warnings' to disable WARNING.
366 If `byte-compile-warnings' is t, set it to `(not WARNING)'.
367 Otherwise, if the first element is `not', add WARNING, else remove it.
368 Normally you should let-bind `byte-compile-warnings' before calling this,
369 else the global value will be modified."
370 (setq byte-compile-warnings
371 (cond ((eq byte-compile-warnings t)
372 (list 'not warning))
373 ((eq (car byte-compile-warnings) 'not)
374 (if (memq warning byte-compile-warnings)
375 byte-compile-warnings
376 (append byte-compile-warnings (list warning))))
377 (t
378 (delq warning byte-compile-warnings)))))
379
380 ;;;###autoload
381 (defun byte-compile-enable-warning (warning)
382 "Change `byte-compile-warnings' to enable WARNING.
383 If `byte-compile-warnings' is `t', do nothing. Otherwise, if the
384 first element is `not', remove WARNING, else add it.
385 Normally you should let-bind `byte-compile-warnings' before calling this,
386 else the global value will be modified."
387 (or (eq byte-compile-warnings t)
388 (setq byte-compile-warnings
389 (cond ((eq (car byte-compile-warnings) 'not)
390 (delq warning byte-compile-warnings))
391 ((memq warning byte-compile-warnings)
392 byte-compile-warnings)
393 (t
394 (append byte-compile-warnings (list warning)))))))
395
396 (defvar byte-compile-interactive-only-functions
397 '(beginning-of-buffer end-of-buffer replace-string replace-regexp
398 insert-file insert-buffer insert-file-literally previous-line next-line
399 goto-line comint-run delete-backward-char)
400 "List of commands that are not meant to be called from Lisp.")
401
402 (defvar byte-compile-not-obsolete-vars nil
403 "If non-nil, a list of variables that shouldn't be reported as obsolete.")
404
405 (defvar byte-compile-not-obsolete-funcs nil
406 "If non-nil, a list of functions that shouldn't be reported as obsolete.")
407
408 (defcustom byte-compile-generate-call-tree nil
409 "Non-nil means collect call-graph information when compiling.
410 This records which functions were called and from where.
411 If the value is t, compilation displays the call graph when it finishes.
412 If the value is neither t nor nil, compilation asks you whether to display
413 the graph.
414
415 The call tree only lists functions called, not macros used. Those functions
416 which the byte-code interpreter knows about directly (eq, cons, etc.) are
417 not reported.
418
419 The call tree also lists those functions which are not known to be called
420 \(that is, to which no calls have been compiled). Functions which can be
421 invoked interactively are excluded from this list."
422 :group 'bytecomp
423 :type '(choice (const :tag "Yes" t) (const :tag "No" nil)
424 (other :tag "Ask" lambda)))
425
426 (defvar byte-compile-call-tree nil
427 "Alist of functions and their call tree.
428 Each element looks like
429
430 \(FUNCTION CALLERS CALLS\)
431
432 where CALLERS is a list of functions that call FUNCTION, and CALLS
433 is a list of functions for which calls were generated while compiling
434 FUNCTION.")
435
436 (defcustom byte-compile-call-tree-sort 'name
437 "If non-nil, sort the call tree.
438 The values `name', `callers', `calls', `calls+callers'
439 specify different fields to sort on."
440 :group 'bytecomp
441 :type '(choice (const name) (const callers) (const calls)
442 (const calls+callers) (const nil)))
443
444 ;(defvar byte-compile-debug nil)
445 (defvar byte-compile-debug t)
446
447 ;; (defvar byte-compile-overwrite-file t
448 ;; "If nil, old .elc files are deleted before the new is saved, and .elc
449 ;; files will have the same modes as the corresponding .el file. Otherwise,
450 ;; existing .elc files will simply be overwritten, and the existing modes
451 ;; will not be changed. If this variable is nil, then an .elc file which
452 ;; is a symbolic link will be turned into a normal file, instead of the file
453 ;; which the link points to being overwritten.")
454
455 (defvar byte-compile-constants nil
456 "List of all constants encountered during compilation of this form.")
457 (defvar byte-compile-variables nil
458 "List of all variables encountered during compilation of this form.")
459 (defvar byte-compile-bound-variables nil
460 "List of variables bound in the context of the current form.
461 This list lives partly on the stack.")
462 (defvar byte-compile-const-variables nil
463 "List of variables declared as constants during compilation of this file.")
464 (defvar byte-compile-free-references)
465 (defvar byte-compile-free-assignments)
466
467 (defvar byte-compiler-error-flag)
468
469 (defconst byte-compile-initial-macro-environment
470 '(
471 ;; (byte-compiler-options . (lambda (&rest forms)
472 ;; (apply 'byte-compiler-options-handler forms)))
473 (eval-when-compile . (lambda (&rest body)
474 (list
475 'quote
476 (byte-compile-eval
477 (byte-compile-top-level
478 (macroexpand-all
479 (cons 'progn body)
480 byte-compile-initial-macro-environment))))))
481 (eval-and-compile . (lambda (&rest body)
482 (byte-compile-eval-before-compile
483 (macroexpand-all
484 (cons 'progn body)
485 byte-compile-initial-macro-environment))
486 (cons 'progn body))))
487 "The default macro-environment passed to macroexpand by the compiler.
488 Placing a macro here will cause a macro to have different semantics when
489 expanded by the compiler as when expanded by the interpreter.")
490
491 (defvar byte-compile-macro-environment byte-compile-initial-macro-environment
492 "Alist of macros defined in the file being compiled.
493 Each element looks like (MACRONAME . DEFINITION). It is
494 \(MACRONAME . nil) when a macro is redefined as a function.")
495
496 (defvar byte-compile-function-environment nil
497 "Alist of functions defined in the file being compiled.
498 This is so we can inline them when necessary.
499 Each element looks like (FUNCTIONNAME . DEFINITION). It is
500 \(FUNCTIONNAME . nil) when a function is redefined as a macro.
501 It is \(FUNCTIONNAME . t) when all we know is that it was defined,
502 and we don't know the definition. For an autoloaded function, DEFINITION
503 has the form (autoload . FILENAME).")
504
505 (defvar byte-compile-unresolved-functions nil
506 "Alist of undefined functions to which calls have been compiled.
507 This variable is only significant whilst compiling an entire buffer.
508 Used for warnings when a function is not known to be defined or is later
509 defined with incorrect args.")
510
511 (defvar byte-compile-noruntime-functions nil
512 "Alist of functions called that may not be defined when the compiled code is run.
513 Used for warnings about calling a function that is defined during compilation
514 but won't necessarily be defined when the compiled file is loaded.")
515
516 ;; Variables for lexical binding
517 (defvar byte-compile-lexical-environment nil
518 "The current lexical environment.")
519 (defvar byte-compile-current-heap-environment nil
520 "If non-nil, a descriptor for the current heap-allocated lexical environment.")
521 (defvar byte-compile-current-num-closures 0
522 "The number of lexical closures that close over `byte-compile-current-heap-environment'.")
523
524 (defvar byte-compile-tag-number 0)
525 (defvar byte-compile-output nil
526 "Alist describing contents to put in byte code string.
527 Each element is (INDEX . VALUE)")
528 (defvar byte-compile-depth 0 "Current depth of execution stack.")
529 (defvar byte-compile-maxdepth 0 "Maximum depth of execution stack.")
530
531 \f
532 ;;; The byte codes; this information is duplicated in bytecomp.c
533
534 (defvar byte-code-vector nil
535 "An array containing byte-code names indexed by byte-code values.")
536
537 (defvar byte-stack+-info nil
538 "An array with the stack adjustment for each byte-code.")
539
540 (defmacro byte-defop (opcode stack-adjust opname &optional docstring)
541 ;; This is a speed-hack for building the byte-code-vector at compile-time.
542 ;; We fill in the vector at macroexpand-time, and then after the last call
543 ;; to byte-defop, we write the vector out as a constant instead of writing
544 ;; out a bunch of calls to aset.
545 ;; Actually, we don't fill in the vector itself, because that could make
546 ;; it problematic to compile big changes to this compiler; we store the
547 ;; values on its plist, and remove them later in -extrude.
548 (let ((v1 (or (get 'byte-code-vector 'tmp-compile-time-value)
549 (put 'byte-code-vector 'tmp-compile-time-value
550 (make-vector 256 nil))))
551 (v2 (or (get 'byte-stack+-info 'tmp-compile-time-value)
552 (put 'byte-stack+-info 'tmp-compile-time-value
553 (make-vector 256 nil)))))
554 (aset v1 opcode opname)
555 (aset v2 opcode stack-adjust))
556 (if docstring
557 (list 'defconst opname opcode (concat "Byte code opcode " docstring "."))
558 (list 'defconst opname opcode)))
559
560 (defmacro byte-extrude-byte-code-vectors ()
561 (prog1 (list 'setq 'byte-code-vector
562 (get 'byte-code-vector 'tmp-compile-time-value)
563 'byte-stack+-info
564 (get 'byte-stack+-info 'tmp-compile-time-value))
565 (put 'byte-code-vector 'tmp-compile-time-value nil)
566 (put 'byte-stack+-info 'tmp-compile-time-value nil)))
567
568
569 ;; These opcodes are special in that they pack their argument into the
570 ;; opcode word.
571 ;;
572 (byte-defop 0 1 byte-stack-ref "for stack reference")
573 (byte-defop 8 1 byte-varref "for variable reference")
574 (byte-defop 16 -1 byte-varset "for setting a variable")
575 (byte-defop 24 -1 byte-varbind "for binding a variable")
576 (byte-defop 32 0 byte-call "for calling a function")
577 (byte-defop 40 0 byte-unbind "for unbinding special bindings")
578 ;; codes 8-47 are consumed by the preceding opcodes
579
580 ;; unused: 48-55
581
582 (byte-defop 56 -1 byte-nth)
583 (byte-defop 57 0 byte-symbolp)
584 (byte-defop 58 0 byte-consp)
585 (byte-defop 59 0 byte-stringp)
586 (byte-defop 60 0 byte-listp)
587 (byte-defop 61 -1 byte-eq)
588 (byte-defop 62 -1 byte-memq)
589 (byte-defop 63 0 byte-not)
590 (byte-defop 64 0 byte-car)
591 (byte-defop 65 0 byte-cdr)
592 (byte-defop 66 -1 byte-cons)
593 (byte-defop 67 0 byte-list1)
594 (byte-defop 68 -1 byte-list2)
595 (byte-defop 69 -2 byte-list3)
596 (byte-defop 70 -3 byte-list4)
597 (byte-defop 71 0 byte-length)
598 (byte-defop 72 -1 byte-aref)
599 (byte-defop 73 -2 byte-aset)
600 (byte-defop 74 0 byte-symbol-value)
601 (byte-defop 75 0 byte-symbol-function) ; this was commented out
602 (byte-defop 76 -1 byte-set)
603 (byte-defop 77 -1 byte-fset) ; this was commented out
604 (byte-defop 78 -1 byte-get)
605 (byte-defop 79 -2 byte-substring)
606 (byte-defop 80 -1 byte-concat2)
607 (byte-defop 81 -2 byte-concat3)
608 (byte-defop 82 -3 byte-concat4)
609 (byte-defop 83 0 byte-sub1)
610 (byte-defop 84 0 byte-add1)
611 (byte-defop 85 -1 byte-eqlsign)
612 (byte-defop 86 -1 byte-gtr)
613 (byte-defop 87 -1 byte-lss)
614 (byte-defop 88 -1 byte-leq)
615 (byte-defop 89 -1 byte-geq)
616 (byte-defop 90 -1 byte-diff)
617 (byte-defop 91 0 byte-negate)
618 (byte-defop 92 -1 byte-plus)
619 (byte-defop 93 -1 byte-max)
620 (byte-defop 94 -1 byte-min)
621 (byte-defop 95 -1 byte-mult) ; v19 only
622 (byte-defop 96 1 byte-point)
623 (byte-defop 98 0 byte-goto-char)
624 (byte-defop 99 0 byte-insert)
625 (byte-defop 100 1 byte-point-max)
626 (byte-defop 101 1 byte-point-min)
627 (byte-defop 102 0 byte-char-after)
628 (byte-defop 103 1 byte-following-char)
629 (byte-defop 104 1 byte-preceding-char)
630 (byte-defop 105 1 byte-current-column)
631 (byte-defop 106 0 byte-indent-to)
632 (byte-defop 107 0 byte-scan-buffer-OBSOLETE) ; no longer generated as of v18
633 (byte-defop 108 1 byte-eolp)
634 (byte-defop 109 1 byte-eobp)
635 (byte-defop 110 1 byte-bolp)
636 (byte-defop 111 1 byte-bobp)
637 (byte-defop 112 1 byte-current-buffer)
638 (byte-defop 113 0 byte-set-buffer)
639 (byte-defop 114 0 byte-save-current-buffer
640 "To make a binding to record the current buffer")
641 (byte-defop 115 0 byte-set-mark-OBSOLETE)
642 (byte-defop 116 1 byte-interactive-p)
643
644 ;; These ops are new to v19
645 (byte-defop 117 0 byte-forward-char)
646 (byte-defop 118 0 byte-forward-word)
647 (byte-defop 119 -1 byte-skip-chars-forward)
648 (byte-defop 120 -1 byte-skip-chars-backward)
649 (byte-defop 121 0 byte-forward-line)
650 (byte-defop 122 0 byte-char-syntax)
651 (byte-defop 123 -1 byte-buffer-substring)
652 (byte-defop 124 -1 byte-delete-region)
653 (byte-defop 125 -1 byte-narrow-to-region)
654 (byte-defop 126 1 byte-widen)
655 (byte-defop 127 0 byte-end-of-line)
656
657 ;; unused: 128
658
659 ;; These store their argument in the next two bytes
660 (byte-defop 129 1 byte-constant2
661 "for reference to a constant with vector index >= byte-constant-limit")
662 (byte-defop 130 0 byte-goto "for unconditional jump")
663 (byte-defop 131 -1 byte-goto-if-nil "to pop value and jump if it's nil")
664 (byte-defop 132 -1 byte-goto-if-not-nil "to pop value and jump if it's not nil")
665 (byte-defop 133 -1 byte-goto-if-nil-else-pop
666 "to examine top-of-stack, jump and don't pop it if it's nil,
667 otherwise pop it")
668 (byte-defop 134 -1 byte-goto-if-not-nil-else-pop
669 "to examine top-of-stack, jump and don't pop it if it's non nil,
670 otherwise pop it")
671
672 (byte-defop 135 -1 byte-return "to pop a value and return it from `byte-code'")
673 (byte-defop 136 -1 byte-discard "to discard one value from stack")
674 (byte-defop 137 1 byte-dup "to duplicate the top of the stack")
675
676 (byte-defop 138 0 byte-save-excursion
677 "to make a binding to record the buffer, point and mark")
678 (byte-defop 139 0 byte-save-window-excursion
679 "to make a binding to record entire window configuration")
680 (byte-defop 140 0 byte-save-restriction
681 "to make a binding to record the current buffer clipping restrictions")
682 (byte-defop 141 -1 byte-catch
683 "for catch. Takes, on stack, the tag and an expression for the body")
684 (byte-defop 142 -1 byte-unwind-protect
685 "for unwind-protect. Takes, on stack, an expression for the unwind-action")
686
687 ;; For condition-case. Takes, on stack, the variable to bind,
688 ;; an expression for the body, and a list of clauses.
689 (byte-defop 143 -2 byte-condition-case)
690
691 ;; For entry to with-output-to-temp-buffer.
692 ;; Takes, on stack, the buffer name.
693 ;; Binds standard-output and does some other things.
694 ;; Returns with temp buffer on the stack in place of buffer name.
695 (byte-defop 144 0 byte-temp-output-buffer-setup)
696
697 ;; For exit from with-output-to-temp-buffer.
698 ;; Expects the temp buffer on the stack underneath value to return.
699 ;; Pops them both, then pushes the value back on.
700 ;; Unbinds standard-output and makes the temp buffer visible.
701 (byte-defop 145 -1 byte-temp-output-buffer-show)
702
703 ;; these ops are new to v19
704
705 ;; To unbind back to the beginning of this frame.
706 ;; Not used yet, but will be needed for tail-recursion elimination.
707 (byte-defop 146 0 byte-unbind-all)
708
709 ;; these ops are new to v19
710 (byte-defop 147 -2 byte-set-marker)
711 (byte-defop 148 0 byte-match-beginning)
712 (byte-defop 149 0 byte-match-end)
713 (byte-defop 150 0 byte-upcase)
714 (byte-defop 151 0 byte-downcase)
715 (byte-defop 152 -1 byte-string=)
716 (byte-defop 153 -1 byte-string<)
717 (byte-defop 154 -1 byte-equal)
718 (byte-defop 155 -1 byte-nthcdr)
719 (byte-defop 156 -1 byte-elt)
720 (byte-defop 157 -1 byte-member)
721 (byte-defop 158 -1 byte-assq)
722 (byte-defop 159 0 byte-nreverse)
723 (byte-defop 160 -1 byte-setcar)
724 (byte-defop 161 -1 byte-setcdr)
725 (byte-defop 162 0 byte-car-safe)
726 (byte-defop 163 0 byte-cdr-safe)
727 (byte-defop 164 -1 byte-nconc)
728 (byte-defop 165 -1 byte-quo)
729 (byte-defop 166 -1 byte-rem)
730 (byte-defop 167 0 byte-numberp)
731 (byte-defop 168 0 byte-integerp)
732
733 ;; unused: 169-174
734
735 (byte-defop 175 nil byte-listN)
736 (byte-defop 176 nil byte-concatN)
737 (byte-defop 177 nil byte-insertN)
738
739 (byte-defop 178 -1 byte-stack-set) ; stack offset in following one byte
740 (byte-defop 179 -1 byte-stack-set2) ; stack offset in following two bytes
741 (byte-defop 180 1 byte-vec-ref) ; vector offset in following one byte
742 (byte-defop 181 -1 byte-vec-set) ; vector offset in following one byte
743
744 ;; if (following one byte & 0x80) == 0
745 ;; discard (following one byte & 0x7F) stack entries
746 ;; else
747 ;; discard (following one byte & 0x7F) stack entries _underneath_ the top of stack
748 ;; (that is, if the operand = 0x83, ... X Y Z T => ... T)
749 (byte-defop 182 nil byte-discardN)
750 ;; `byte-discardN-preserve-tos' is a pseudo-op that gets turned into
751 ;; `byte-discardN' with the high bit in the operand set (by
752 ;; `byte-compile-lapcode').
753 (defconst byte-discardN-preserve-tos byte-discardN)
754
755 ;; unused: 182-191
756
757 (byte-defop 192 1 byte-constant "for reference to a constant")
758 ;; codes 193-255 are consumed by byte-constant.
759 (defconst byte-constant-limit 64
760 "Exclusive maximum index usable in the `byte-constant' opcode.")
761
762 (defconst byte-goto-ops '(byte-goto byte-goto-if-nil byte-goto-if-not-nil
763 byte-goto-if-nil-else-pop
764 byte-goto-if-not-nil-else-pop)
765 "List of byte-codes whose offset is a pc.")
766
767 (defconst byte-goto-always-pop-ops '(byte-goto-if-nil byte-goto-if-not-nil))
768
769 (byte-extrude-byte-code-vectors)
770 \f
771 ;;; lapcode generator
772 ;;
773 ;; the byte-compiler now does source -> lapcode -> bytecode instead of
774 ;; source -> bytecode, because it's a lot easier to make optimizations
775 ;; on lapcode than on bytecode.
776 ;;
777 ;; Elements of the lapcode list are of the form (<instruction> . <parameter>)
778 ;; where instruction is a symbol naming a byte-code instruction,
779 ;; and parameter is an argument to that instruction, if any.
780 ;;
781 ;; The instruction can be the pseudo-op TAG, which means that this position
782 ;; in the instruction stream is a target of a goto. (car PARAMETER) will be
783 ;; the PC for this location, and the whole instruction "(TAG pc)" will be the
784 ;; parameter for some goto op.
785 ;;
786 ;; If the operation is varbind, varref, varset or push-constant, then the
787 ;; parameter is (variable/constant . index_in_constant_vector).
788 ;;
789 ;; First, the source code is macroexpanded and optimized in various ways.
790 ;; Then the resultant code is compiled into lapcode. Another set of
791 ;; optimizations are then run over the lapcode. Then the variables and
792 ;; constants referenced by the lapcode are collected and placed in the
793 ;; constants-vector. (This happens now so that variables referenced by dead
794 ;; code don't consume space.) And finally, the lapcode is transformed into
795 ;; compacted byte-code.
796 ;;
797 ;; A distinction is made between variables and constants because the variable-
798 ;; referencing instructions are more sensitive to the variables being near the
799 ;; front of the constants-vector than the constant-referencing instructions.
800 ;; Also, this lets us notice references to free variables.
801
802 (defmacro byte-compile-push-bytecodes (&rest args)
803 "Push BYTE... onto BYTES, and increment PC by the number of bytes pushed.
804 ARGS is of the form (BYTE... BYTES PC), where BYTES and PC are variable names.
805 BYTES and PC are updated after evaluating all the arguments."
806 (let ((byte-exprs (butlast args 2))
807 (bytes-var (car (last args 2)))
808 (pc-var (car (last args))))
809 `(setq ,bytes-var ,(if (null (cdr byte-exprs))
810 `(cons ,@byte-exprs ,bytes-var)
811 `(nconc (list ,@(reverse byte-exprs)) ,bytes-var))
812 ,pc-var (+ ,(length byte-exprs) ,pc-var))))
813
814 (defmacro byte-compile-push-bytecode-const2 (opcode const2 bytes pc)
815 "Push OPCODE and the two-byte constant CONST2 onto BYTES, and add 3 to PC.
816 CONST2 may be evaulated multiple times."
817 `(byte-compile-push-bytecodes ,opcode (logand ,const2 255) (lsh ,const2 -8)
818 ,bytes ,pc))
819
820 (defun byte-compile-lapcode (lap)
821 "Turns lapcode into bytecode. The lapcode is destroyed."
822 ;; Lapcode modifications: changes the ID of a tag to be the tag's PC.
823 (let ((pc 0) ; Program counter
824 op off ; Operation & offset
825 opcode ; numeric value of OP
826 (bytes '()) ; Put the output bytes here
827 (patchlist nil)) ; List of gotos to patch
828 (dolist (lap-entry lap)
829 (setq op (car lap-entry)
830 off (cdr lap-entry))
831 (cond ((not (symbolp op))
832 (error "Non-symbolic opcode `%s'" op))
833 ((eq op 'TAG)
834 (setcar off pc))
835 ((null op)
836 ;; a no-op added by `byte-compile-delay-out'
837 (unless (zerop off)
838 (error
839 "Placeholder added by `byte-compile-delay-out' not filled in.")
840 ))
841 (t
842 (if (eq op 'byte-discardN-preserve-tos)
843 ;; byte-discardN-preserve-tos is a psuedo op, which is actually
844 ;; the same as byte-discardN with a modified argument
845 (setq opcode byte-discardN)
846 (setq opcode (symbol-value op)))
847 (cond ((memq op byte-goto-ops)
848 ;; goto
849 (byte-compile-push-bytecodes opcode nil (cdr off) bytes pc)
850 (push bytes patchlist))
851 ((and (consp off)
852 ;; Variable or constant reference
853 (progn (setq off (cdr off))
854 (eq op 'byte-constant)))
855 ;; constant ref
856 (if (< off byte-constant-limit)
857 (byte-compile-push-bytecodes (+ byte-constant off)
858 bytes pc)
859 (byte-compile-push-bytecode-const2 byte-constant2 off
860 bytes pc)))
861 ((and (= opcode byte-stack-set)
862 (> off 255))
863 ;; Use the two-byte version of byte-stack-set if the
864 ;; offset is too large for the normal version.
865 (byte-compile-push-bytecode-const2 byte-stack-set2 off
866 bytes pc))
867 ((and (>= opcode byte-listN)
868 (< opcode byte-discardN))
869 ;; These insns all put their operand into one extra byte.
870 (byte-compile-push-bytecodes opcode off bytes pc))
871 ((= opcode byte-discardN)
872 ;; byte-discardN is wierd in that it encodes a flag in the
873 ;; top bit of its one-byte argument. If the argument is
874 ;; too large to fit in 7 bits, the opcode can be repeated.
875 (let ((flag (if (eq op 'byte-discardN-preserve-tos) #x80 0)))
876 (while (> off #x7f)
877 (byte-compile-push-bytecodes opcode (logior #x7f flag) bytes pc)
878 (setq off (- off #x7f)))
879 (byte-compile-push-bytecodes opcode (logior off flag) bytes pc)))
880 ((null off)
881 ;; opcode that doesn't use OFF
882 (byte-compile-push-bytecodes opcode bytes pc))
883 ;; The following three cases are for the special
884 ;; insns that encode their operand into 0, 1, or 2
885 ;; extra bytes depending on its magnitude.
886 ((< off 6)
887 (byte-compile-push-bytecodes (+ opcode off) bytes pc))
888 ((< off 256)
889 (byte-compile-push-bytecodes (+ opcode 6) off bytes pc))
890 (t
891 (byte-compile-push-bytecode-const2 (+ opcode 7) off
892 bytes pc))))))
893 ;;(if (not (= pc (length bytes)))
894 ;; (error "Compiler error: pc mismatch - %s %s" pc (length bytes)))
895
896 ;; Patch tag PCs into absolute jumps
897 (dolist (bytes-tail patchlist)
898 (setq pc (caar bytes-tail)) ; Pick PC from goto's tag
899 (setcar (cdr bytes-tail) (logand pc 255))
900 (setcar bytes-tail (lsh pc -8))
901 ;; FIXME: Replace this by some workaround.
902 (if (> (car bytes) 255) (error "Bytecode overflow")))
903
904 (apply 'unibyte-string (nreverse bytes))))
905
906 \f
907 ;;; compile-time evaluation
908
909 (defun byte-compile-cl-file-p (file)
910 "Return non-nil if FILE is one of the CL files."
911 (and (stringp file)
912 (string-match "^cl\\>" (file-name-nondirectory file))))
913
914 (defun byte-compile-eval (form)
915 "Eval FORM and mark the functions defined therein.
916 Each function's symbol gets added to `byte-compile-noruntime-functions'."
917 (let ((hist-orig load-history)
918 (hist-nil-orig current-load-list))
919 (prog1 (eval form)
920 (when (byte-compile-warning-enabled-p 'noruntime)
921 (let ((hist-new load-history)
922 (hist-nil-new current-load-list))
923 ;; Go through load-history, look for newly loaded files
924 ;; and mark all the functions defined therein.
925 (while (and hist-new (not (eq hist-new hist-orig)))
926 (let ((xs (pop hist-new))
927 old-autoloads)
928 ;; Make sure the file was not already loaded before.
929 (unless (or (assoc (car xs) hist-orig)
930 ;; Don't give both the "noruntime" and
931 ;; "cl-functions" warning for the same function.
932 ;; FIXME This seems incorrect - these are two
933 ;; independent warnings. For example, you may be
934 ;; choosing to see the cl warnings but ignore them.
935 ;; You probably don't want to ignore noruntime in the
936 ;; same way.
937 (and (byte-compile-warning-enabled-p 'cl-functions)
938 (byte-compile-cl-file-p (car xs))))
939 (dolist (s xs)
940 (cond
941 ((symbolp s)
942 (unless (memq s old-autoloads)
943 (push s byte-compile-noruntime-functions)))
944 ((and (consp s) (eq t (car s)))
945 (push (cdr s) old-autoloads))
946 ((and (consp s) (eq 'autoload (car s)))
947 (push (cdr s) byte-compile-noruntime-functions)))))))
948 ;; Go through current-load-list for the locally defined funs.
949 (let (old-autoloads)
950 (while (and hist-nil-new (not (eq hist-nil-new hist-nil-orig)))
951 (let ((s (pop hist-nil-new)))
952 (when (and (symbolp s) (not (memq s old-autoloads)))
953 (push s byte-compile-noruntime-functions))
954 (when (and (consp s) (eq t (car s)))
955 (push (cdr s) old-autoloads)))))))
956 (when (byte-compile-warning-enabled-p 'cl-functions)
957 (let ((hist-new load-history))
958 ;; Go through load-history, looking for the cl files.
959 ;; Since new files are added at the start of load-history,
960 ;; we scan the new history until the tail matches the old.
961 (while (and (not byte-compile-cl-functions)
962 hist-new (not (eq hist-new hist-orig)))
963 ;; We used to check if the file had already been loaded,
964 ;; but it is better to check non-nil byte-compile-cl-functions.
965 (and (byte-compile-cl-file-p (car (pop hist-new)))
966 (byte-compile-find-cl-functions))))))))
967
968 (defun byte-compile-eval-before-compile (form)
969 "Evaluate FORM for `eval-and-compile'."
970 (let ((hist-nil-orig current-load-list))
971 (prog1 (eval form)
972 ;; (eval-and-compile (require 'cl) turns off warnings for cl functions.
973 ;; FIXME Why does it do that - just as a hack?
974 ;; There are other ways to do this nowadays.
975 (let ((tem current-load-list))
976 (while (not (eq tem hist-nil-orig))
977 (when (equal (car tem) '(require . cl))
978 (byte-compile-disable-warning 'cl-functions))
979 (setq tem (cdr tem)))))))
980 \f
981 ;;; byte compiler messages
982
983 (defvar byte-compile-current-form nil)
984 (defvar byte-compile-dest-file nil)
985 (defvar byte-compile-current-file nil)
986 (defvar byte-compile-current-group nil)
987 (defvar byte-compile-current-buffer nil)
988
989 ;; Log something that isn't a warning.
990 (defmacro byte-compile-log (format-string &rest args)
991 `(and
992 byte-optimize
993 (memq byte-optimize-log '(t source))
994 (let ((print-escape-newlines t)
995 (print-level 4)
996 (print-length 4))
997 (byte-compile-log-1
998 (format
999 ,format-string
1000 ,@(mapcar
1001 (lambda (x) (if (symbolp x) (list 'prin1-to-string x) x))
1002 args))))))
1003
1004 ;; Log something that isn't a warning.
1005 (defun byte-compile-log-1 (string)
1006 (with-current-buffer "*Compile-Log*"
1007 (let ((inhibit-read-only t))
1008 (goto-char (point-max))
1009 (byte-compile-warning-prefix nil nil)
1010 (cond (noninteractive
1011 (message " %s" string))
1012 (t
1013 (insert (format "%s\n" string)))))))
1014
1015 (defvar byte-compile-read-position nil
1016 "Character position we began the last `read' from.")
1017 (defvar byte-compile-last-position nil
1018 "Last known character position in the input.")
1019
1020 ;; copied from gnus-util.el
1021 (defsubst byte-compile-delete-first (elt list)
1022 (if (eq (car list) elt)
1023 (cdr list)
1024 (let ((total list))
1025 (while (and (cdr list)
1026 (not (eq (cadr list) elt)))
1027 (setq list (cdr list)))
1028 (when (cdr list)
1029 (setcdr list (cddr list)))
1030 total)))
1031
1032 ;; The purpose of this function is to iterate through the
1033 ;; `read-symbol-positions-list'. Each time we process, say, a
1034 ;; function definition (`defun') we remove `defun' from
1035 ;; `read-symbol-positions-list', and set `byte-compile-last-position'
1036 ;; to that symbol's character position. Similarly, if we encounter a
1037 ;; variable reference, like in (1+ foo), we remove `foo' from the
1038 ;; list. If our current position is after the symbol's position, we
1039 ;; assume we've already passed that point, and look for the next
1040 ;; occurrence of the symbol.
1041 ;;
1042 ;; This function should not be called twice for the same occurrence of
1043 ;; a symbol, and it should not be called for symbols generated by the
1044 ;; byte compiler itself; because rather than just fail looking up the
1045 ;; symbol, we may find an occurrence of the symbol further ahead, and
1046 ;; then `byte-compile-last-position' as advanced too far.
1047 ;;
1048 ;; So your're probably asking yourself: Isn't this function a
1049 ;; gross hack? And the answer, of course, would be yes.
1050 (defun byte-compile-set-symbol-position (sym &optional allow-previous)
1051 (when byte-compile-read-position
1052 (let (last entry)
1053 (while (progn
1054 (setq last byte-compile-last-position
1055 entry (assq sym read-symbol-positions-list))
1056 (when entry
1057 (setq byte-compile-last-position
1058 (+ byte-compile-read-position (cdr entry))
1059 read-symbol-positions-list
1060 (byte-compile-delete-first
1061 entry read-symbol-positions-list)))
1062 (or (and allow-previous (not (= last byte-compile-last-position)))
1063 (> last byte-compile-last-position)))))))
1064
1065 (defvar byte-compile-last-warned-form nil)
1066 (defvar byte-compile-last-logged-file nil)
1067
1068 ;; This is used as warning-prefix for the compiler.
1069 ;; It is always called with the warnings buffer current.
1070 (defun byte-compile-warning-prefix (level entry)
1071 (let* ((inhibit-read-only t)
1072 (dir default-directory)
1073 (file (cond ((stringp byte-compile-current-file)
1074 (format "%s:" (file-relative-name byte-compile-current-file dir)))
1075 ((bufferp byte-compile-current-file)
1076 (format "Buffer %s:"
1077 (buffer-name byte-compile-current-file)))
1078 (t "")))
1079 (pos (if (and byte-compile-current-file
1080 (integerp byte-compile-read-position))
1081 (with-current-buffer byte-compile-current-buffer
1082 (format "%d:%d:"
1083 (save-excursion
1084 (goto-char byte-compile-last-position)
1085 (1+ (count-lines (point-min) (point-at-bol))))
1086 (save-excursion
1087 (goto-char byte-compile-last-position)
1088 (1+ (current-column)))))
1089 ""))
1090 (form (if (eq byte-compile-current-form :end) "end of data"
1091 (or byte-compile-current-form "toplevel form"))))
1092 (when (or (and byte-compile-current-file
1093 (not (equal byte-compile-current-file
1094 byte-compile-last-logged-file)))
1095 (and byte-compile-current-form
1096 (not (eq byte-compile-current-form
1097 byte-compile-last-warned-form))))
1098 (insert (format "\nIn %s:\n" form)))
1099 (when level
1100 (insert (format "%s%s" file pos))))
1101 (setq byte-compile-last-logged-file byte-compile-current-file
1102 byte-compile-last-warned-form byte-compile-current-form)
1103 entry)
1104
1105 ;; This no-op function is used as the value of warning-series
1106 ;; to tell inner calls to displaying-byte-compile-warnings
1107 ;; not to bind warning-series.
1108 (defun byte-compile-warning-series (&rest ignore)
1109 nil)
1110
1111 ;; (compile-mode) will cause this to be loaded.
1112 (declare-function compilation-forget-errors "compile" ())
1113
1114 ;; Log the start of a file in *Compile-Log*, and mark it as done.
1115 ;; Return the position of the start of the page in the log buffer.
1116 ;; But do nothing in batch mode.
1117 (defun byte-compile-log-file ()
1118 (and (not (equal byte-compile-current-file byte-compile-last-logged-file))
1119 (not noninteractive)
1120 (with-current-buffer (get-buffer-create "*Compile-Log*")
1121 (goto-char (point-max))
1122 (let* ((inhibit-read-only t)
1123 (dir (and byte-compile-current-file
1124 (file-name-directory byte-compile-current-file)))
1125 (was-same (equal default-directory dir))
1126 pt)
1127 (when dir
1128 (unless was-same
1129 (insert (format "Leaving directory `%s'\n" default-directory))))
1130 (unless (bolp)
1131 (insert "\n"))
1132 (setq pt (point-marker))
1133 (if byte-compile-current-file
1134 (insert "\f\nCompiling "
1135 (if (stringp byte-compile-current-file)
1136 (concat "file " byte-compile-current-file)
1137 (concat "buffer " (buffer-name byte-compile-current-file)))
1138 " at " (current-time-string) "\n")
1139 (insert "\f\nCompiling no file at " (current-time-string) "\n"))
1140 (when dir
1141 (setq default-directory dir)
1142 (unless was-same
1143 (insert (format "Entering directory `%s'\n" default-directory))))
1144 (setq byte-compile-last-logged-file byte-compile-current-file
1145 byte-compile-last-warned-form nil)
1146 ;; Do this after setting default-directory.
1147 (unless (derived-mode-p 'compilation-mode) (compilation-mode))
1148 (compilation-forget-errors)
1149 pt))))
1150
1151 ;; Log a message STRING in *Compile-Log*.
1152 ;; Also log the current function and file if not already done.
1153 (defun byte-compile-log-warning (string &optional fill level)
1154 (let ((warning-prefix-function 'byte-compile-warning-prefix)
1155 (warning-type-format "")
1156 (warning-fill-prefix (if fill " "))
1157 (inhibit-read-only t))
1158 (display-warning 'bytecomp string level "*Compile-Log*")))
1159
1160 (defun byte-compile-warn (format &rest args)
1161 "Issue a byte compiler warning; use (format FORMAT ARGS...) for message."
1162 (setq format (apply 'format format args))
1163 (if byte-compile-error-on-warn
1164 (error "%s" format) ; byte-compile-file catches and logs it
1165 (byte-compile-log-warning format t :warning)))
1166
1167 (defun byte-compile-warn-obsolete (symbol)
1168 "Warn that SYMBOL (a variable or function) is obsolete."
1169 (when (byte-compile-warning-enabled-p 'obsolete)
1170 (let* ((funcp (get symbol 'byte-obsolete-info))
1171 (obsolete (or funcp (get symbol 'byte-obsolete-variable)))
1172 (instead (car obsolete))
1173 (asof (if funcp (nth 2 obsolete) (cdr obsolete))))
1174 (unless (and funcp (memq symbol byte-compile-not-obsolete-funcs))
1175 (byte-compile-warn "`%s' is an obsolete %s%s%s" symbol
1176 (if funcp "function" "variable")
1177 (if asof (concat " (as of Emacs " asof ")") "")
1178 (cond ((stringp instead)
1179 (concat "; " instead))
1180 (instead
1181 (format "; use `%s' instead." instead))
1182 (t ".")))))))
1183
1184 (defun byte-compile-report-error (error-info)
1185 "Report Lisp error in compilation. ERROR-INFO is the error data."
1186 (setq byte-compiler-error-flag t)
1187 (byte-compile-log-warning
1188 (error-message-string error-info)
1189 nil :error))
1190
1191 ;;; Used by make-obsolete.
1192 (defun byte-compile-obsolete (form)
1193 (byte-compile-set-symbol-position (car form))
1194 (byte-compile-warn-obsolete (car form))
1195 (funcall (or (cadr (get (car form) 'byte-obsolete-info)) ; handler
1196 'byte-compile-normal-call) form))
1197 \f
1198 ;;; sanity-checking arglists
1199
1200 (defun byte-compile-fdefinition (name macro-p)
1201 ;; If a function has an entry saying (FUNCTION . t).
1202 ;; that means we know it is defined but we don't know how.
1203 ;; If a function has an entry saying (FUNCTION . nil),
1204 ;; that means treat it as not defined.
1205 (let* ((list (if macro-p
1206 byte-compile-macro-environment
1207 byte-compile-function-environment))
1208 (env (cdr (assq name list))))
1209 (or env
1210 (let ((fn name))
1211 (while (and (symbolp fn)
1212 (fboundp fn)
1213 (or (symbolp (symbol-function fn))
1214 (consp (symbol-function fn))
1215 (and (not macro-p)
1216 (byte-code-function-p (symbol-function fn)))))
1217 (setq fn (symbol-function fn)))
1218 (let ((advertised (gethash (if (and (symbolp fn) (fboundp fn))
1219 ;; Could be a subr.
1220 (symbol-function fn)
1221 fn)
1222 advertised-signature-table t)))
1223 (cond
1224 ((listp advertised)
1225 (if macro-p
1226 `(macro lambda ,advertised)
1227 `(lambda ,advertised)))
1228 ((and (not macro-p) (byte-code-function-p fn)) fn)
1229 ((not (consp fn)) nil)
1230 ((eq 'macro (car fn)) (cdr fn))
1231 (macro-p nil)
1232 ((eq 'autoload (car fn)) nil)
1233 (t fn)))))))
1234
1235 (defun byte-compile-arglist-signature (arglist)
1236 (let ((args 0)
1237 opts
1238 restp)
1239 (while arglist
1240 (cond ((eq (car arglist) '&optional)
1241 (or opts (setq opts 0)))
1242 ((eq (car arglist) '&rest)
1243 (if (cdr arglist)
1244 (setq restp t
1245 arglist nil)))
1246 (t
1247 (if opts
1248 (setq opts (1+ opts))
1249 (setq args (1+ args)))))
1250 (setq arglist (cdr arglist)))
1251 (cons args (if restp nil (if opts (+ args opts) args)))))
1252
1253
1254 (defun byte-compile-arglist-signatures-congruent-p (old new)
1255 (not (or
1256 (> (car new) (car old)) ; requires more args now
1257 (and (null (cdr old)) ; took rest-args, doesn't any more
1258 (cdr new))
1259 (and (cdr new) (cdr old) ; can't take as many args now
1260 (< (cdr new) (cdr old)))
1261 )))
1262
1263 (defun byte-compile-arglist-signature-string (signature)
1264 (cond ((null (cdr signature))
1265 (format "%d+" (car signature)))
1266 ((= (car signature) (cdr signature))
1267 (format "%d" (car signature)))
1268 (t (format "%d-%d" (car signature) (cdr signature)))))
1269
1270
1271 ;; Warn if the form is calling a function with the wrong number of arguments.
1272 (defun byte-compile-callargs-warn (form)
1273 (let* ((def (or (byte-compile-fdefinition (car form) nil)
1274 (byte-compile-fdefinition (car form) t)))
1275 (sig (if (and def (not (eq def t)))
1276 (progn
1277 (and (eq (car-safe def) 'macro)
1278 (eq (car-safe (cdr-safe def)) 'lambda)
1279 (setq def (cdr def)))
1280 (byte-compile-arglist-signature
1281 (if (memq (car-safe def) '(declared lambda))
1282 (nth 1 def)
1283 (if (byte-code-function-p def)
1284 (aref def 0)
1285 '(&rest def)))))
1286 (if (and (fboundp (car form))
1287 (subrp (symbol-function (car form))))
1288 (subr-arity (symbol-function (car form))))))
1289 (ncall (length (cdr form))))
1290 ;; Check many or unevalled from subr-arity.
1291 (if (and (cdr-safe sig)
1292 (not (numberp (cdr sig))))
1293 (setcdr sig nil))
1294 (if sig
1295 (when (or (< ncall (car sig))
1296 (and (cdr sig) (> ncall (cdr sig))))
1297 (byte-compile-set-symbol-position (car form))
1298 (byte-compile-warn
1299 "%s called with %d argument%s, but %s %s"
1300 (car form) ncall
1301 (if (= 1 ncall) "" "s")
1302 (if (< ncall (car sig))
1303 "requires"
1304 "accepts only")
1305 (byte-compile-arglist-signature-string sig))))
1306 (byte-compile-format-warn form)
1307 ;; Check to see if the function will be available at runtime
1308 ;; and/or remember its arity if it's unknown.
1309 (or (and (or def (fboundp (car form))) ; might be a subr or autoload.
1310 (not (memq (car form) byte-compile-noruntime-functions)))
1311 (eq (car form) byte-compile-current-form) ; ## this doesn't work
1312 ; with recursion.
1313 ;; It's a currently-undefined function.
1314 ;; Remember number of args in call.
1315 (let ((cons (assq (car form) byte-compile-unresolved-functions))
1316 (n (length (cdr form))))
1317 (if cons
1318 (or (memq n (cdr cons))
1319 (setcdr cons (cons n (cdr cons))))
1320 (push (list (car form) n)
1321 byte-compile-unresolved-functions))))))
1322
1323 (defun byte-compile-format-warn (form)
1324 "Warn if FORM is `format'-like with inconsistent args.
1325 Applies if head of FORM is a symbol with non-nil property
1326 `byte-compile-format-like' and first arg is a constant string.
1327 Then check the number of format fields matches the number of
1328 extra args."
1329 (when (and (symbolp (car form))
1330 (stringp (nth 1 form))
1331 (get (car form) 'byte-compile-format-like))
1332 (let ((nfields (with-temp-buffer
1333 (insert (nth 1 form))
1334 (goto-char (point-min))
1335 (let ((n 0))
1336 (while (re-search-forward "%." nil t)
1337 (unless (eq ?% (char-after (1+ (match-beginning 0))))
1338 (setq n (1+ n))))
1339 n)))
1340 (nargs (- (length form) 2)))
1341 (unless (= nargs nfields)
1342 (byte-compile-warn
1343 "`%s' called with %d args to fill %d format field(s)" (car form)
1344 nargs nfields)))))
1345
1346 (dolist (elt '(format message error))
1347 (put elt 'byte-compile-format-like t))
1348
1349 ;; Warn if a custom definition fails to specify :group.
1350 (defun byte-compile-nogroup-warn (form)
1351 (if (and (memq (car form) '(custom-declare-face custom-declare-variable))
1352 byte-compile-current-group)
1353 ;; The group will be provided implicitly.
1354 nil
1355 (let ((keyword-args (cdr (cdr (cdr (cdr form)))))
1356 (name (cadr form)))
1357 (or (not (eq (car-safe name) 'quote))
1358 (and (eq (car form) 'custom-declare-group)
1359 (equal name ''emacs))
1360 (plist-get keyword-args :group)
1361 (not (and (consp name) (eq (car name) 'quote)))
1362 (byte-compile-warn
1363 "%s for `%s' fails to specify containing group"
1364 (cdr (assq (car form)
1365 '((custom-declare-group . defgroup)
1366 (custom-declare-face . defface)
1367 (custom-declare-variable . defcustom))))
1368 (cadr name)))
1369 ;; Update the current group, if needed.
1370 (if (and byte-compile-current-file ;Only when byte-compiling a whole file.
1371 (eq (car form) 'custom-declare-group)
1372 (eq (car-safe name) 'quote))
1373 (setq byte-compile-current-group (cadr name))))))
1374
1375 ;; Warn if the function or macro is being redefined with a different
1376 ;; number of arguments.
1377 (defun byte-compile-arglist-warn (form macrop)
1378 (let ((old (byte-compile-fdefinition (nth 1 form) macrop)))
1379 (if (and old (not (eq old t)))
1380 (progn
1381 (and (eq 'macro (car-safe old))
1382 (eq 'lambda (car-safe (cdr-safe old)))
1383 (setq old (cdr old)))
1384 (let ((sig1 (byte-compile-arglist-signature
1385 (if (eq 'lambda (car-safe old))
1386 (nth 1 old)
1387 (if (byte-code-function-p old)
1388 (aref old 0)
1389 '(&rest def)))))
1390 (sig2 (byte-compile-arglist-signature (nth 2 form))))
1391 (unless (byte-compile-arglist-signatures-congruent-p sig1 sig2)
1392 (byte-compile-set-symbol-position (nth 1 form))
1393 (byte-compile-warn
1394 "%s %s used to take %s %s, now takes %s"
1395 (if (eq (car form) 'defun) "function" "macro")
1396 (nth 1 form)
1397 (byte-compile-arglist-signature-string sig1)
1398 (if (equal sig1 '(1 . 1)) "argument" "arguments")
1399 (byte-compile-arglist-signature-string sig2)))))
1400 ;; This is the first definition. See if previous calls are compatible.
1401 (let ((calls (assq (nth 1 form) byte-compile-unresolved-functions))
1402 nums sig min max)
1403 (if calls
1404 (progn
1405 (setq sig (byte-compile-arglist-signature (nth 2 form))
1406 nums (sort (copy-sequence (cdr calls)) (function <))
1407 min (car nums)
1408 max (car (nreverse nums)))
1409 (when (or (< min (car sig))
1410 (and (cdr sig) (> max (cdr sig))))
1411 (byte-compile-set-symbol-position (nth 1 form))
1412 (byte-compile-warn
1413 "%s being defined to take %s%s, but was previously called with %s"
1414 (nth 1 form)
1415 (byte-compile-arglist-signature-string sig)
1416 (if (equal sig '(1 . 1)) " arg" " args")
1417 (byte-compile-arglist-signature-string (cons min max))))
1418
1419 (setq byte-compile-unresolved-functions
1420 (delq calls byte-compile-unresolved-functions)))))
1421 )))
1422
1423 (defvar byte-compile-cl-functions nil
1424 "List of functions defined in CL.")
1425
1426 ;; Can't just add this to cl-load-hook, because that runs just before
1427 ;; the forms from cl.el get added to load-history.
1428 (defun byte-compile-find-cl-functions ()
1429 (unless byte-compile-cl-functions
1430 (dolist (elt load-history)
1431 (and (byte-compile-cl-file-p (car elt))
1432 (dolist (e (cdr elt))
1433 ;; Includes the cl-foo functions that cl autoloads.
1434 (when (memq (car-safe e) '(autoload defun))
1435 (push (cdr e) byte-compile-cl-functions)))))))
1436
1437 (defun byte-compile-cl-warn (form)
1438 "Warn if FORM is a call of a function from the CL package."
1439 (let ((func (car-safe form)))
1440 (if (and byte-compile-cl-functions
1441 (memq func byte-compile-cl-functions)
1442 ;; Aliases which won't have been expanded at this point.
1443 ;; These aren't all aliases of subrs, so not trivial to
1444 ;; avoid hardwiring the list.
1445 (not (memq func
1446 '(cl-block-wrapper cl-block-throw
1447 multiple-value-call nth-value
1448 copy-seq first second rest endp cl-member
1449 ;; These are included in generated code
1450 ;; that can't be called except at compile time
1451 ;; or unless cl is loaded anyway.
1452 cl-defsubst-expand cl-struct-setf-expander
1453 ;; These would sometimes be warned about
1454 ;; but such warnings are never useful,
1455 ;; so don't warn about them.
1456 macroexpand cl-macroexpand-all
1457 cl-compiling-file)))
1458 ;; Avoid warnings for things which are safe because they
1459 ;; have suitable compiler macros, but those aren't
1460 ;; expanded at this stage. There should probably be more
1461 ;; here than caaar and friends.
1462 (not (and (eq (get func 'byte-compile)
1463 'cl-byte-compile-compiler-macro)
1464 (string-match "\\`c[ad]+r\\'" (symbol-name func)))))
1465 (byte-compile-warn "Function `%s' from cl package called at runtime"
1466 func)))
1467 form)
1468
1469 (defun byte-compile-print-syms (str1 strn syms)
1470 (when syms
1471 (byte-compile-set-symbol-position (car syms) t))
1472 (cond ((and (cdr syms) (not noninteractive))
1473 (let* ((str strn)
1474 (L (length str))
1475 s)
1476 (while syms
1477 (setq s (symbol-name (pop syms))
1478 L (+ L (length s) 2))
1479 (if (< L (1- fill-column))
1480 (setq str (concat str " " s (and syms ",")))
1481 (setq str (concat str "\n " s (and syms ","))
1482 L (+ (length s) 4))))
1483 (byte-compile-warn "%s" str)))
1484 ((cdr syms)
1485 (byte-compile-warn "%s %s"
1486 strn
1487 (mapconcat #'symbol-name syms ", ")))
1488
1489 (syms
1490 (byte-compile-warn str1 (car syms)))))
1491
1492 ;; If we have compiled any calls to functions which are not known to be
1493 ;; defined, issue a warning enumerating them.
1494 ;; `unresolved' in the list `byte-compile-warnings' disables this.
1495 (defun byte-compile-warn-about-unresolved-functions ()
1496 (when (byte-compile-warning-enabled-p 'unresolved)
1497 (let ((byte-compile-current-form :end)
1498 (noruntime nil)
1499 (unresolved nil))
1500 ;; Separate the functions that will not be available at runtime
1501 ;; from the truly unresolved ones.
1502 (dolist (f byte-compile-unresolved-functions)
1503 (setq f (car f))
1504 (if (fboundp f) (push f noruntime) (push f unresolved)))
1505 ;; Complain about the no-run-time functions
1506 (byte-compile-print-syms
1507 "the function `%s' might not be defined at runtime."
1508 "the following functions might not be defined at runtime:"
1509 noruntime)
1510 ;; Complain about the unresolved functions
1511 (byte-compile-print-syms
1512 "the function `%s' is not known to be defined."
1513 "the following functions are not known to be defined:"
1514 unresolved)))
1515 nil)
1516
1517 \f
1518 (defsubst byte-compile-const-symbol-p (symbol &optional any-value)
1519 "Non-nil if SYMBOL is constant.
1520 If ANY-VALUE is nil, only return non-nil if the value of the symbol is the
1521 symbol itself."
1522 (or (memq symbol '(nil t))
1523 (keywordp symbol)
1524 (if any-value
1525 (or (memq symbol byte-compile-const-variables)
1526 ;; FIXME: We should provide a less intrusive way to find out
1527 ;; is a variable is "constant".
1528 (and (boundp symbol)
1529 (condition-case nil
1530 (progn (set symbol (symbol-value symbol)) nil)
1531 (setting-constant t)))))))
1532
1533 (defmacro byte-compile-constp (form)
1534 "Return non-nil if FORM is a constant."
1535 `(cond ((consp ,form) (eq (car ,form) 'quote))
1536 ((not (symbolp ,form)))
1537 ((byte-compile-const-symbol-p ,form))))
1538
1539 (defmacro byte-compile-close-variables (&rest body)
1540 (cons 'let
1541 (cons '(;;
1542 ;; Close over these variables to encapsulate the
1543 ;; compilation state
1544 ;;
1545 (byte-compile-macro-environment
1546 ;; Copy it because the compiler may patch into the
1547 ;; macroenvironment.
1548 (copy-alist byte-compile-initial-macro-environment))
1549 (byte-compile-function-environment nil)
1550 (byte-compile-bound-variables nil)
1551 (byte-compile-const-variables nil)
1552 (byte-compile-free-references nil)
1553 (byte-compile-free-assignments nil)
1554 ;;
1555 ;; Close over these variables so that `byte-compiler-options'
1556 ;; can change them on a per-file basis.
1557 ;;
1558 (byte-compile-verbose byte-compile-verbose)
1559 (byte-optimize byte-optimize)
1560 (byte-compile-dynamic byte-compile-dynamic)
1561 (byte-compile-dynamic-docstrings
1562 byte-compile-dynamic-docstrings)
1563 ;; (byte-compile-generate-emacs19-bytecodes
1564 ;; byte-compile-generate-emacs19-bytecodes)
1565 (byte-compile-warnings byte-compile-warnings)
1566 )
1567 body)))
1568
1569 (defmacro displaying-byte-compile-warnings (&rest body)
1570 `(let* ((--displaying-byte-compile-warnings-fn (lambda () ,@body))
1571 (warning-series-started
1572 (and (markerp warning-series)
1573 (eq (marker-buffer warning-series)
1574 (get-buffer "*Compile-Log*")))))
1575 (byte-compile-find-cl-functions)
1576 (if (or (eq warning-series 'byte-compile-warning-series)
1577 warning-series-started)
1578 ;; warning-series does come from compilation,
1579 ;; so don't bind it, but maybe do set it.
1580 (let (tem)
1581 ;; Log the file name. Record position of that text.
1582 (setq tem (byte-compile-log-file))
1583 (unless warning-series-started
1584 (setq warning-series (or tem 'byte-compile-warning-series)))
1585 (if byte-compile-debug
1586 (funcall --displaying-byte-compile-warnings-fn)
1587 (condition-case error-info
1588 (funcall --displaying-byte-compile-warnings-fn)
1589 (error (byte-compile-report-error error-info)))))
1590 ;; warning-series does not come from compilation, so bind it.
1591 (let ((warning-series
1592 ;; Log the file name. Record position of that text.
1593 (or (byte-compile-log-file) 'byte-compile-warning-series)))
1594 (if byte-compile-debug
1595 (funcall --displaying-byte-compile-warnings-fn)
1596 (condition-case error-info
1597 (funcall --displaying-byte-compile-warnings-fn)
1598 (error (byte-compile-report-error error-info))))))))
1599 \f
1600 ;;;###autoload
1601 (defun byte-force-recompile (directory)
1602 "Recompile every `.el' file in DIRECTORY that already has a `.elc' file.
1603 Files in subdirectories of DIRECTORY are processed also."
1604 (interactive "DByte force recompile (directory): ")
1605 (byte-recompile-directory directory nil t))
1606
1607 ;; The `bytecomp-' prefix is applied to all local variables with
1608 ;; otherwise common names in this and similar functions for the sake
1609 ;; of the boundp test in byte-compile-variable-ref.
1610 ;; http://lists.gnu.org/archive/html/emacs-devel/2008-01/msg00237.html
1611 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-02/msg00134.html
1612 ;; Note that similar considerations apply to command-line-1 in startup.el.
1613 ;;;###autoload
1614 (defun byte-recompile-directory (bytecomp-directory &optional bytecomp-arg
1615 bytecomp-force)
1616 "Recompile every `.el' file in BYTECOMP-DIRECTORY that needs recompilation.
1617 This happens when a `.elc' file exists but is older than the `.el' file.
1618 Files in subdirectories of BYTECOMP-DIRECTORY are processed also.
1619
1620 If the `.elc' file does not exist, normally this function *does not*
1621 compile the corresponding `.el' file. However, if the prefix argument
1622 BYTECOMP-ARG is 0, that means do compile all those files. A nonzero
1623 BYTECOMP-ARG means ask the user, for each such `.el' file, whether to
1624 compile it. A nonzero BYTECOMP-ARG also means ask about each subdirectory
1625 before scanning it.
1626
1627 If the third argument BYTECOMP-FORCE is non-nil, recompile every `.el' file
1628 that already has a `.elc' file."
1629 (interactive "DByte recompile directory: \nP")
1630 (if bytecomp-arg
1631 (setq bytecomp-arg (prefix-numeric-value bytecomp-arg)))
1632 (if noninteractive
1633 nil
1634 (save-some-buffers)
1635 (force-mode-line-update))
1636 (with-current-buffer (get-buffer-create "*Compile-Log*")
1637 (setq default-directory (expand-file-name bytecomp-directory))
1638 ;; compilation-mode copies value of default-directory.
1639 (unless (eq major-mode 'compilation-mode)
1640 (compilation-mode))
1641 (let ((bytecomp-directories (list default-directory))
1642 (default-directory default-directory)
1643 (skip-count 0)
1644 (fail-count 0)
1645 (file-count 0)
1646 (dir-count 0)
1647 last-dir)
1648 (displaying-byte-compile-warnings
1649 (while bytecomp-directories
1650 (setq bytecomp-directory (car bytecomp-directories))
1651 (message "Checking %s..." bytecomp-directory)
1652 (let ((bytecomp-files (directory-files bytecomp-directory))
1653 bytecomp-source bytecomp-dest)
1654 (dolist (bytecomp-file bytecomp-files)
1655 (setq bytecomp-source
1656 (expand-file-name bytecomp-file bytecomp-directory))
1657 (if (and (not (member bytecomp-file '("RCS" "CVS")))
1658 (not (eq ?\. (aref bytecomp-file 0)))
1659 (file-directory-p bytecomp-source)
1660 (not (file-symlink-p bytecomp-source)))
1661 ;; This file is a subdirectory. Handle them differently.
1662 (when (or (null bytecomp-arg)
1663 (eq 0 bytecomp-arg)
1664 (y-or-n-p (concat "Check " bytecomp-source "? ")))
1665 (setq bytecomp-directories
1666 (nconc bytecomp-directories (list bytecomp-source))))
1667 ;; It is an ordinary file. Decide whether to compile it.
1668 (if (and (string-match emacs-lisp-file-regexp bytecomp-source)
1669 (file-readable-p bytecomp-source)
1670 (not (auto-save-file-name-p bytecomp-source))
1671 (setq bytecomp-dest
1672 (byte-compile-dest-file bytecomp-source))
1673 (if (file-exists-p bytecomp-dest)
1674 ;; File was already compiled.
1675 (or bytecomp-force
1676 (file-newer-than-file-p bytecomp-source
1677 bytecomp-dest))
1678 ;; No compiled file exists yet.
1679 (and bytecomp-arg
1680 (or (eq 0 bytecomp-arg)
1681 (y-or-n-p (concat "Compile "
1682 bytecomp-source "? "))))))
1683 (progn (if (and noninteractive (not byte-compile-verbose))
1684 (message "Compiling %s..." bytecomp-source))
1685 (let ((bytecomp-res (byte-compile-file
1686 bytecomp-source)))
1687 (cond ((eq bytecomp-res 'no-byte-compile)
1688 (setq skip-count (1+ skip-count)))
1689 ((eq bytecomp-res t)
1690 (setq file-count (1+ file-count)))
1691 ((eq bytecomp-res nil)
1692 (setq fail-count (1+ fail-count)))))
1693 (or noninteractive
1694 (message "Checking %s..." bytecomp-directory))
1695 (if (not (eq last-dir bytecomp-directory))
1696 (setq last-dir bytecomp-directory
1697 dir-count (1+ dir-count)))
1698 )))))
1699 (setq bytecomp-directories (cdr bytecomp-directories))))
1700 (message "Done (Total of %d file%s compiled%s%s%s)"
1701 file-count (if (= file-count 1) "" "s")
1702 (if (> fail-count 0) (format ", %d failed" fail-count) "")
1703 (if (> skip-count 0) (format ", %d skipped" skip-count) "")
1704 (if (> dir-count 1)
1705 (format " in %d directories" dir-count) "")))))
1706
1707 (defvar no-byte-compile nil
1708 "Non-nil to prevent byte-compiling of Emacs Lisp code.
1709 This is normally set in local file variables at the end of the elisp file:
1710
1711 ;; Local Variables:\n;; no-byte-compile: t\n;; End: ")
1712 ;;;###autoload(put 'no-byte-compile 'safe-local-variable 'booleanp)
1713
1714 ;;;###autoload
1715 (defun byte-compile-file (bytecomp-filename &optional load)
1716 "Compile a file of Lisp code named BYTECOMP-FILENAME into a file of byte code.
1717 The output file's name is generated by passing BYTECOMP-FILENAME to the
1718 function `byte-compile-dest-file' (which see).
1719 With prefix arg (noninteractively: 2nd arg), LOAD the file after compiling.
1720 The value is non-nil if there were no errors, nil if errors."
1721 ;; (interactive "fByte compile file: \nP")
1722 (interactive
1723 (let ((bytecomp-file buffer-file-name)
1724 (bytecomp-file-name nil)
1725 (bytecomp-file-dir nil))
1726 (and bytecomp-file
1727 (eq (cdr (assq 'major-mode (buffer-local-variables)))
1728 'emacs-lisp-mode)
1729 (setq bytecomp-file-name (file-name-nondirectory bytecomp-file)
1730 bytecomp-file-dir (file-name-directory bytecomp-file)))
1731 (list (read-file-name (if current-prefix-arg
1732 "Byte compile and load file: "
1733 "Byte compile file: ")
1734 bytecomp-file-dir bytecomp-file-name nil)
1735 current-prefix-arg)))
1736 ;; Expand now so we get the current buffer's defaults
1737 (setq bytecomp-filename (expand-file-name bytecomp-filename))
1738
1739 ;; If we're compiling a file that's in a buffer and is modified, offer
1740 ;; to save it first.
1741 (or noninteractive
1742 (let ((b (get-file-buffer (expand-file-name bytecomp-filename))))
1743 (if (and b (buffer-modified-p b)
1744 (y-or-n-p (format "Save buffer %s first? " (buffer-name b))))
1745 (with-current-buffer b (save-buffer)))))
1746
1747 ;; Force logging of the file name for each file compiled.
1748 (setq byte-compile-last-logged-file nil)
1749 (let ((byte-compile-current-file bytecomp-filename)
1750 (byte-compile-current-group nil)
1751 (set-auto-coding-for-load t)
1752 target-file input-buffer output-buffer
1753 byte-compile-dest-file)
1754 (setq target-file (byte-compile-dest-file bytecomp-filename))
1755 (setq byte-compile-dest-file target-file)
1756 (with-current-buffer
1757 (setq input-buffer (get-buffer-create " *Compiler Input*"))
1758 (erase-buffer)
1759 (setq buffer-file-coding-system nil)
1760 ;; Always compile an Emacs Lisp file as multibyte
1761 ;; unless the file itself forces unibyte with -*-coding: raw-text;-*-
1762 (set-buffer-multibyte t)
1763 (insert-file-contents bytecomp-filename)
1764 ;; Mimic the way after-insert-file-set-coding can make the
1765 ;; buffer unibyte when visiting this file.
1766 (when (or (eq last-coding-system-used 'no-conversion)
1767 (eq (coding-system-type last-coding-system-used) 5))
1768 ;; For coding systems no-conversion and raw-text...,
1769 ;; edit the buffer as unibyte.
1770 (set-buffer-multibyte nil))
1771 ;; Run hooks including the uncompression hook.
1772 ;; If they change the file name, then change it for the output also.
1773 (letf ((buffer-file-name bytecomp-filename)
1774 ((default-value 'major-mode) 'emacs-lisp-mode)
1775 ;; Ignore unsafe local variables.
1776 ;; We only care about a few of them for our purposes.
1777 (enable-local-variables :safe)
1778 (enable-local-eval nil))
1779 ;; Arg of t means don't alter enable-local-variables.
1780 (normal-mode t)
1781 (setq bytecomp-filename buffer-file-name))
1782 ;; Set the default directory, in case an eval-when-compile uses it.
1783 (setq default-directory (file-name-directory bytecomp-filename)))
1784 ;; Check if the file's local variables explicitly specify not to
1785 ;; compile this file.
1786 (if (with-current-buffer input-buffer no-byte-compile)
1787 (progn
1788 ;; (message "%s not compiled because of `no-byte-compile: %s'"
1789 ;; (file-relative-name bytecomp-filename)
1790 ;; (with-current-buffer input-buffer no-byte-compile))
1791 (when (file-exists-p target-file)
1792 (message "%s deleted because of `no-byte-compile: %s'"
1793 (file-relative-name target-file)
1794 (buffer-local-value 'no-byte-compile input-buffer))
1795 (condition-case nil (delete-file target-file) (error nil)))
1796 ;; We successfully didn't compile this file.
1797 'no-byte-compile)
1798 (when byte-compile-verbose
1799 (message "Compiling %s..." bytecomp-filename))
1800 (setq byte-compiler-error-flag nil)
1801 ;; It is important that input-buffer not be current at this call,
1802 ;; so that the value of point set in input-buffer
1803 ;; within byte-compile-from-buffer lingers in that buffer.
1804 (setq output-buffer
1805 (save-current-buffer
1806 (byte-compile-from-buffer input-buffer bytecomp-filename)))
1807 (if byte-compiler-error-flag
1808 nil
1809 (when byte-compile-verbose
1810 (message "Compiling %s...done" bytecomp-filename))
1811 (kill-buffer input-buffer)
1812 (with-current-buffer output-buffer
1813 (goto-char (point-max))
1814 (insert "\n") ; aaah, unix.
1815 (if (file-writable-p target-file)
1816 ;; We must disable any code conversion here.
1817 (let ((coding-system-for-write 'no-conversion))
1818 (if (memq system-type '(ms-dos 'windows-nt))
1819 (setq buffer-file-type t))
1820 (when (file-exists-p target-file)
1821 ;; Remove the target before writing it, so that any
1822 ;; hard-links continue to point to the old file (this makes
1823 ;; it possible for installed files to share disk space with
1824 ;; the build tree, without causing problems when emacs-lisp
1825 ;; files in the build tree are recompiled).
1826 (delete-file target-file))
1827 (write-region (point-min) (point-max) target-file))
1828 ;; This is just to give a better error message than write-region
1829 (signal 'file-error
1830 (list "Opening output file"
1831 (if (file-exists-p target-file)
1832 "cannot overwrite file"
1833 "directory not writable or nonexistent")
1834 target-file)))
1835 (kill-buffer (current-buffer)))
1836 (if (and byte-compile-generate-call-tree
1837 (or (eq t byte-compile-generate-call-tree)
1838 (y-or-n-p (format "Report call tree for %s? "
1839 bytecomp-filename))))
1840 (save-excursion
1841 (display-call-tree bytecomp-filename)))
1842 (if load
1843 (load target-file))
1844 t))))
1845
1846 ;;; compiling a single function
1847 ;;;###autoload
1848 (defun compile-defun (&optional arg)
1849 "Compile and evaluate the current top-level form.
1850 Print the result in the echo area.
1851 With argument ARG, insert value in current buffer after the form."
1852 (interactive "P")
1853 (save-excursion
1854 (end-of-defun)
1855 (beginning-of-defun)
1856 (let* ((byte-compile-current-file nil)
1857 (byte-compile-current-buffer (current-buffer))
1858 (byte-compile-read-position (point))
1859 (byte-compile-last-position byte-compile-read-position)
1860 (byte-compile-last-warned-form 'nothing)
1861 (value (eval
1862 (let ((read-with-symbol-positions (current-buffer))
1863 (read-symbol-positions-list nil))
1864 (displaying-byte-compile-warnings
1865 (byte-compile-sexp (read (current-buffer))))))))
1866 (cond (arg
1867 (message "Compiling from buffer... done.")
1868 (prin1 value (current-buffer))
1869 (insert "\n"))
1870 ((message "%s" (prin1-to-string value)))))))
1871
1872
1873 (defun byte-compile-from-buffer (bytecomp-inbuffer &optional bytecomp-filename)
1874 ;; Filename is used for the loading-into-Emacs-18 error message.
1875 (let (bytecomp-outbuffer
1876 (byte-compile-current-buffer bytecomp-inbuffer)
1877 (byte-compile-read-position nil)
1878 (byte-compile-last-position nil)
1879 ;; Prevent truncation of flonums and lists as we read and print them
1880 (float-output-format nil)
1881 (case-fold-search nil)
1882 (print-length nil)
1883 (print-level nil)
1884 ;; Prevent edebug from interfering when we compile
1885 ;; and put the output into a file.
1886 ;; (edebug-all-defs nil)
1887 ;; (edebug-all-forms nil)
1888 ;; Simulate entry to byte-compile-top-level
1889 (byte-compile-constants nil)
1890 (byte-compile-variables nil)
1891 (byte-compile-tag-number 0)
1892 (byte-compile-depth 0)
1893 (byte-compile-maxdepth 0)
1894 (byte-compile-output nil)
1895 ;; This allows us to get the positions of symbols read; it's
1896 ;; new in Emacs 22.1.
1897 (read-with-symbol-positions bytecomp-inbuffer)
1898 (read-symbol-positions-list nil)
1899 ;; #### This is bound in b-c-close-variables.
1900 ;; (byte-compile-warnings byte-compile-warnings)
1901 )
1902 (byte-compile-close-variables
1903 (with-current-buffer
1904 (setq bytecomp-outbuffer (get-buffer-create " *Compiler Output*"))
1905 (set-buffer-multibyte t)
1906 (erase-buffer)
1907 ;; (emacs-lisp-mode)
1908 (setq case-fold-search nil)
1909 ;; This is a kludge. Some operating systems (OS/2, DOS) need to
1910 ;; write files containing binary information specially.
1911 ;; Under most circumstances, such files will be in binary
1912 ;; overwrite mode, so those OS's use that flag to guess how
1913 ;; they should write their data. Advise them that .elc files
1914 ;; need to be written carefully.
1915 (setq overwrite-mode 'overwrite-mode-binary))
1916 (displaying-byte-compile-warnings
1917 (with-current-buffer bytecomp-inbuffer
1918 (and bytecomp-filename
1919 (byte-compile-insert-header bytecomp-filename bytecomp-outbuffer))
1920 (goto-char (point-min))
1921 ;; Should we always do this? When calling multiple files, it
1922 ;; would be useful to delay this warning until all have been
1923 ;; compiled. A: Yes! b-c-u-f might contain dross from a
1924 ;; previous byte-compile.
1925 (setq byte-compile-unresolved-functions nil)
1926
1927 ;; Compile the forms from the input buffer.
1928 (while (progn
1929 (while (progn (skip-chars-forward " \t\n\^l")
1930 (looking-at ";"))
1931 (forward-line 1))
1932 (not (eobp)))
1933 (setq byte-compile-read-position (point)
1934 byte-compile-last-position byte-compile-read-position)
1935 (let* ((old-style-backquotes nil)
1936 (form (read bytecomp-inbuffer)))
1937 ;; Warn about the use of old-style backquotes.
1938 (when old-style-backquotes
1939 (byte-compile-warn "!! The file uses old-style backquotes !!
1940 This functionality has been obsolete for more than 10 years already
1941 and will be removed soon. See (elisp)Backquote in the manual."))
1942 (byte-compile-file-form form)))
1943 ;; Compile pending forms at end of file.
1944 (byte-compile-flush-pending)
1945 ;; Make warnings about unresolved functions
1946 ;; give the end of the file as their position.
1947 (setq byte-compile-last-position (point-max))
1948 (byte-compile-warn-about-unresolved-functions))
1949 ;; Fix up the header at the front of the output
1950 ;; if the buffer contains multibyte characters.
1951 (and bytecomp-filename
1952 (with-current-buffer bytecomp-outbuffer
1953 (byte-compile-fix-header bytecomp-filename)))))
1954 bytecomp-outbuffer))
1955
1956 (defun byte-compile-fix-header (filename)
1957 "If the current buffer has any multibyte characters, insert a version test."
1958 (when (< (point-max) (position-bytes (point-max)))
1959 (goto-char (point-min))
1960 ;; Find the comment that describes the version condition.
1961 (search-forward "\n;;; This file uses")
1962 (narrow-to-region (line-beginning-position) (point-max))
1963 ;; Find the first line of ballast semicolons.
1964 (search-forward ";;;;;;;;;;")
1965 (beginning-of-line)
1966 (narrow-to-region (point-min) (point))
1967 (let ((old-header-end (point))
1968 (minimum-version "23")
1969 delta)
1970 (delete-region (point-min) (point-max))
1971 (insert
1972 ";;; This file contains utf-8 non-ASCII characters,\n"
1973 ";;; and so cannot be loaded into Emacs 22 or earlier.\n"
1974 ;; Have to check if emacs-version is bound so that this works
1975 ;; in files loaded early in loadup.el.
1976 "(and (boundp 'emacs-version)\n"
1977 ;; If there is a name at the end of emacs-version,
1978 ;; don't try to check the version number.
1979 " (< (aref emacs-version (1- (length emacs-version))) ?A)\n"
1980 (format " (string-lessp emacs-version \"%s\")\n" minimum-version)
1981 " (error \"`"
1982 ;; prin1-to-string is used to quote backslashes.
1983 (substring (prin1-to-string (file-name-nondirectory filename))
1984 1 -1)
1985 (format "' was compiled for Emacs %s or later\"))\n\n"
1986 minimum-version))
1987 ;; Now compensate for any change in size, to make sure all
1988 ;; positions in the file remain valid.
1989 (setq delta (- (point-max) old-header-end))
1990 (goto-char (point-max))
1991 (widen)
1992 (delete-char delta))))
1993
1994 (defun byte-compile-insert-header (filename outbuffer)
1995 "Insert a header at the start of OUTBUFFER.
1996 Call from the source buffer."
1997 (let ((dynamic-docstrings byte-compile-dynamic-docstrings)
1998 (dynamic byte-compile-dynamic)
1999 (optimize byte-optimize))
2000 (with-current-buffer outbuffer
2001 (goto-char (point-min))
2002 ;; The magic number of .elc files is ";ELC", or 0x3B454C43. After
2003 ;; that is the file-format version number (18, 19, 20, or 23) as a
2004 ;; byte, followed by some nulls. The primary motivation for doing
2005 ;; this is to get some binary characters up in the first line of
2006 ;; the file so that `diff' will simply say "Binary files differ"
2007 ;; instead of actually doing a diff of two .elc files. An extra
2008 ;; benefit is that you can add this to /etc/magic:
2009 ;; 0 string ;ELC GNU Emacs Lisp compiled file,
2010 ;; >4 byte x version %d
2011 (insert
2012 ";ELC" 23 "\000\000\000\n"
2013 ";;; Compiled by "
2014 (or (and (boundp 'user-mail-address) user-mail-address)
2015 (concat (user-login-name) "@" (system-name)))
2016 " on " (current-time-string) "\n"
2017 ";;; from file " filename "\n"
2018 ";;; in Emacs version " emacs-version "\n"
2019 ";;; with"
2020 (cond
2021 ((eq optimize 'source) " source-level optimization only")
2022 ((eq optimize 'byte) " byte-level optimization only")
2023 (optimize " all optimizations")
2024 (t "out optimization"))
2025 ".\n"
2026 (if dynamic ";;; Function definitions are lazy-loaded.\n"
2027 "")
2028 "\n;;; This file uses "
2029 (if dynamic-docstrings
2030 "dynamic docstrings, first added in Emacs 19.29"
2031 "opcodes that do not exist in Emacs 18")
2032 ".\n\n"
2033 ;; Note that byte-compile-fix-header may change this.
2034 ";;; This file does not contain utf-8 non-ASCII characters,\n"
2035 ";;; and so can be loaded in Emacs versions earlier than 23.\n\n"
2036 ;; Insert semicolons as ballast, so that byte-compile-fix-header
2037 ;; can delete them so as to keep the buffer positions
2038 ;; constant for the actual compiled code.
2039 ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
2040 ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n"))))
2041
2042 ;; Dynamically bound in byte-compile-from-buffer.
2043 ;; NB also used in cl.el and cl-macs.el.
2044 (defvar bytecomp-outbuffer)
2045
2046 (defun byte-compile-output-file-form (form)
2047 ;; writes the given form to the output buffer, being careful of docstrings
2048 ;; in defun, defmacro, defvar, defvaralias, defconst, autoload and
2049 ;; custom-declare-variable because make-docfile is so amazingly stupid.
2050 ;; defalias calls are output directly by byte-compile-file-form-defmumble;
2051 ;; it does not pay to first build the defalias in defmumble and then parse
2052 ;; it here.
2053 (if (and (memq (car-safe form) '(defun defmacro defvar defvaralias defconst autoload
2054 custom-declare-variable))
2055 (stringp (nth 3 form)))
2056 (byte-compile-output-docform nil nil '("\n(" 3 ")") form nil
2057 (memq (car form)
2058 '(defvaralias autoload
2059 custom-declare-variable)))
2060 (let ((print-escape-newlines t)
2061 (print-length nil)
2062 (print-level nil)
2063 (print-quoted t)
2064 (print-gensym t)
2065 (print-circle ; handle circular data structures
2066 (not byte-compile-disable-print-circle)))
2067 (princ "\n" bytecomp-outbuffer)
2068 (prin1 form bytecomp-outbuffer)
2069 nil)))
2070
2071 (defvar print-gensym-alist) ;Used before print-circle existed.
2072
2073 (defun byte-compile-output-docform (preface name info form specindex quoted)
2074 "Print a form with a doc string. INFO is (prefix doc-index postfix).
2075 If PREFACE and NAME are non-nil, print them too,
2076 before INFO and the FORM but after the doc string itself.
2077 If SPECINDEX is non-nil, it is the index in FORM
2078 of the function bytecode string. In that case,
2079 we output that argument and the following argument
2080 \(the constants vector) together, for lazy loading.
2081 QUOTED says that we have to put a quote before the
2082 list that represents a doc string reference.
2083 `defvaralias', `autoload' and `custom-declare-variable' need that."
2084 ;; We need to examine byte-compile-dynamic-docstrings
2085 ;; in the input buffer (now current), not in the output buffer.
2086 (let ((dynamic-docstrings byte-compile-dynamic-docstrings))
2087 (with-current-buffer bytecomp-outbuffer
2088 (let (position)
2089
2090 ;; Insert the doc string, and make it a comment with #@LENGTH.
2091 (and (>= (nth 1 info) 0)
2092 dynamic-docstrings
2093 (progn
2094 ;; Make the doc string start at beginning of line
2095 ;; for make-docfile's sake.
2096 (insert "\n")
2097 (setq position
2098 (byte-compile-output-as-comment
2099 (nth (nth 1 info) form) nil))
2100 (setq position (- (position-bytes position) (point-min) -1))
2101 ;; If the doc string starts with * (a user variable),
2102 ;; negate POSITION.
2103 (if (and (stringp (nth (nth 1 info) form))
2104 (> (length (nth (nth 1 info) form)) 0)
2105 (eq (aref (nth (nth 1 info) form) 0) ?*))
2106 (setq position (- position)))))
2107
2108 (if preface
2109 (progn
2110 (insert preface)
2111 (prin1 name bytecomp-outbuffer)))
2112 (insert (car info))
2113 (let ((print-escape-newlines t)
2114 (print-quoted t)
2115 ;; For compatibility with code before print-circle,
2116 ;; use a cons cell to say that we want
2117 ;; print-gensym-alist not to be cleared
2118 ;; between calls to print functions.
2119 (print-gensym '(t))
2120 (print-circle ; handle circular data structures
2121 (not byte-compile-disable-print-circle))
2122 print-gensym-alist ; was used before print-circle existed.
2123 (print-continuous-numbering t)
2124 print-number-table
2125 (index 0))
2126 (prin1 (car form) bytecomp-outbuffer)
2127 (while (setq form (cdr form))
2128 (setq index (1+ index))
2129 (insert " ")
2130 (cond ((and (numberp specindex) (= index specindex)
2131 ;; Don't handle the definition dynamically
2132 ;; if it refers (or might refer)
2133 ;; to objects already output
2134 ;; (for instance, gensyms in the arg list).
2135 (let (non-nil)
2136 (dotimes (i (length print-number-table))
2137 (if (aref print-number-table i)
2138 (setq non-nil t)))
2139 (not non-nil)))
2140 ;; Output the byte code and constants specially
2141 ;; for lazy dynamic loading.
2142 (let ((position
2143 (byte-compile-output-as-comment
2144 (cons (car form) (nth 1 form))
2145 t)))
2146 (setq position (- (position-bytes position) (point-min) -1))
2147 (princ (format "(#$ . %d) nil" position) bytecomp-outbuffer)
2148 (setq form (cdr form))
2149 (setq index (1+ index))))
2150 ((= index (nth 1 info))
2151 (if position
2152 (princ (format (if quoted "'(#$ . %d)" "(#$ . %d)")
2153 position)
2154 bytecomp-outbuffer)
2155 (let ((print-escape-newlines nil))
2156 (goto-char (prog1 (1+ (point))
2157 (prin1 (car form) bytecomp-outbuffer)))
2158 (insert "\\\n")
2159 (goto-char (point-max)))))
2160 (t
2161 (prin1 (car form) bytecomp-outbuffer)))))
2162 (insert (nth 2 info)))))
2163 nil)
2164
2165 (defun byte-compile-keep-pending (form &optional bytecomp-handler)
2166 (if (memq byte-optimize '(t source))
2167 (setq form (byte-optimize-form form t)))
2168 (if bytecomp-handler
2169 (let ((for-effect t))
2170 ;; To avoid consing up monstrously large forms at load time, we split
2171 ;; the output regularly.
2172 (and (memq (car-safe form) '(fset defalias))
2173 (nthcdr 300 byte-compile-output)
2174 (byte-compile-flush-pending))
2175 (funcall bytecomp-handler form)
2176 (if for-effect
2177 (byte-compile-discard)))
2178 (byte-compile-form form t))
2179 nil)
2180
2181 (defun byte-compile-flush-pending ()
2182 (if byte-compile-output
2183 (let ((form (byte-compile-out-toplevel t 'file)))
2184 (cond ((eq (car-safe form) 'progn)
2185 (mapc 'byte-compile-output-file-form (cdr form)))
2186 (form
2187 (byte-compile-output-file-form form)))
2188 (setq byte-compile-constants nil
2189 byte-compile-variables nil
2190 byte-compile-depth 0
2191 byte-compile-maxdepth 0
2192 byte-compile-output nil))))
2193
2194 (defun byte-compile-file-form (form)
2195 (let ((byte-compile-current-form nil) ; close over this for warnings.
2196 bytecomp-handler)
2197 (setq form (macroexpand-all form byte-compile-macro-environment))
2198 (cond ((not (consp form))
2199 (byte-compile-keep-pending form))
2200 ((and (symbolp (car form))
2201 (setq bytecomp-handler (get (car form) 'byte-hunk-handler)))
2202 (cond ((setq form (funcall bytecomp-handler form))
2203 (byte-compile-flush-pending)
2204 (byte-compile-output-file-form form))))
2205 (t
2206 (byte-compile-keep-pending form)))))
2207
2208 ;; Functions and variables with doc strings must be output separately,
2209 ;; so make-docfile can recognise them. Most other things can be output
2210 ;; as byte-code.
2211
2212 (put 'defsubst 'byte-hunk-handler 'byte-compile-file-form-defsubst)
2213 (defun byte-compile-file-form-defsubst (form)
2214 (when (assq (nth 1 form) byte-compile-unresolved-functions)
2215 (setq byte-compile-current-form (nth 1 form))
2216 (byte-compile-warn "defsubst `%s' was used before it was defined"
2217 (nth 1 form)))
2218 (byte-compile-file-form form)
2219 ;; Return nil so the form is not output twice.
2220 nil)
2221
2222 (put 'autoload 'byte-hunk-handler 'byte-compile-file-form-autoload)
2223 (defun byte-compile-file-form-autoload (form)
2224 (and (let ((form form))
2225 (while (if (setq form (cdr form)) (byte-compile-constp (car form))))
2226 (null form)) ;Constants only
2227 (eval (nth 5 form)) ;Macro
2228 (eval form)) ;Define the autoload.
2229 ;; Avoid undefined function warnings for the autoload.
2230 (when (and (consp (nth 1 form))
2231 (eq (car (nth 1 form)) 'quote)
2232 (consp (cdr (nth 1 form)))
2233 (symbolp (nth 1 (nth 1 form))))
2234 (push (cons (nth 1 (nth 1 form))
2235 (cons 'autoload (cdr (cdr form))))
2236 byte-compile-function-environment)
2237 ;; If an autoload occurs _before_ the first call to a function,
2238 ;; byte-compile-callargs-warn does not add an entry to
2239 ;; byte-compile-unresolved-functions. Here we mimic the logic
2240 ;; of byte-compile-callargs-warn so as not to warn if the
2241 ;; autoload comes _after_ the function call.
2242 ;; Alternatively, similar logic could go in
2243 ;; byte-compile-warn-about-unresolved-functions.
2244 (or (memq (nth 1 (nth 1 form)) byte-compile-noruntime-functions)
2245 (setq byte-compile-unresolved-functions
2246 (delq (assq (nth 1 (nth 1 form))
2247 byte-compile-unresolved-functions)
2248 byte-compile-unresolved-functions))))
2249 (if (stringp (nth 3 form))
2250 form
2251 ;; No doc string, so we can compile this as a normal form.
2252 (byte-compile-keep-pending form 'byte-compile-normal-call)))
2253
2254 (put 'defvar 'byte-hunk-handler 'byte-compile-file-form-defvar)
2255 (put 'defconst 'byte-hunk-handler 'byte-compile-file-form-defvar)
2256 (defun byte-compile-file-form-defvar (form)
2257 (if (null (nth 3 form))
2258 ;; Since there is no doc string, we can compile this as a normal form,
2259 ;; and not do a file-boundary.
2260 (byte-compile-keep-pending form)
2261 (push (nth 1 form) byte-compile-bound-variables)
2262 (if (eq (car form) 'defconst)
2263 (push (nth 1 form) byte-compile-const-variables))
2264 (cond ((consp (nth 2 form))
2265 (setq form (copy-sequence form))
2266 (setcar (cdr (cdr form))
2267 (byte-compile-top-level (nth 2 form) nil 'file))))
2268 form))
2269
2270 (put 'define-abbrev-table 'byte-hunk-handler 'byte-compile-file-form-define-abbrev-table)
2271 (defun byte-compile-file-form-define-abbrev-table (form)
2272 (if (eq 'quote (car-safe (car-safe (cdr form))))
2273 (push (car-safe (cdr (cadr form))) byte-compile-bound-variables))
2274 (byte-compile-keep-pending form))
2275
2276 (put 'custom-declare-variable 'byte-hunk-handler
2277 'byte-compile-file-form-custom-declare-variable)
2278 (defun byte-compile-file-form-custom-declare-variable (form)
2279 (when (byte-compile-warning-enabled-p 'callargs)
2280 (byte-compile-nogroup-warn form))
2281 (push (nth 1 (nth 1 form)) byte-compile-bound-variables)
2282 ;; Don't compile the expression because it may be displayed to the user.
2283 ;; (when (eq (car-safe (nth 2 form)) 'quote)
2284 ;; ;; (nth 2 form) is meant to evaluate to an expression, so if we have the
2285 ;; ;; final value already, we can byte-compile it.
2286 ;; (setcar (cdr (nth 2 form))
2287 ;; (byte-compile-top-level (cadr (nth 2 form)) nil 'file)))
2288 (let ((tail (nthcdr 4 form)))
2289 (while tail
2290 (unless (keywordp (car tail)) ;No point optimizing keywords.
2291 ;; Compile the keyword arguments.
2292 (setcar tail (byte-compile-top-level (car tail) nil 'file)))
2293 (setq tail (cdr tail))))
2294 form)
2295
2296 (put 'require 'byte-hunk-handler 'byte-compile-file-form-require)
2297 (defun byte-compile-file-form-require (form)
2298 (let ((args (mapcar 'eval (cdr form)))
2299 (hist-orig load-history)
2300 hist-new)
2301 (apply 'require args)
2302 (when (byte-compile-warning-enabled-p 'cl-functions)
2303 ;; Detect (require 'cl) in a way that works even if cl is already loaded.
2304 (if (member (car args) '("cl" cl))
2305 (progn
2306 (byte-compile-warn "cl package required at runtime")
2307 (byte-compile-disable-warning 'cl-functions))
2308 ;; We may have required something that causes cl to be loaded, eg
2309 ;; the uncompiled version of a file that requires cl when compiling.
2310 (setq hist-new load-history)
2311 (while (and (not byte-compile-cl-functions)
2312 hist-new (not (eq hist-new hist-orig)))
2313 (and (byte-compile-cl-file-p (car (pop hist-new)))
2314 (byte-compile-find-cl-functions))))))
2315 (byte-compile-keep-pending form 'byte-compile-normal-call))
2316
2317 (put 'progn 'byte-hunk-handler 'byte-compile-file-form-progn)
2318 (put 'prog1 'byte-hunk-handler 'byte-compile-file-form-progn)
2319 (put 'prog2 'byte-hunk-handler 'byte-compile-file-form-progn)
2320 (defun byte-compile-file-form-progn (form)
2321 (mapc 'byte-compile-file-form (cdr form))
2322 ;; Return nil so the forms are not output twice.
2323 nil)
2324
2325 (put 'with-no-warnings 'byte-hunk-handler
2326 'byte-compile-file-form-with-no-warnings)
2327 (defun byte-compile-file-form-with-no-warnings (form)
2328 ;; cf byte-compile-file-form-progn.
2329 (let (byte-compile-warnings)
2330 (mapc 'byte-compile-file-form (cdr form))
2331 nil))
2332
2333 ;; This handler is not necessary, but it makes the output from dont-compile
2334 ;; and similar macros cleaner.
2335 (put 'eval 'byte-hunk-handler 'byte-compile-file-form-eval)
2336 (defun byte-compile-file-form-eval (form)
2337 (if (eq (car-safe (nth 1 form)) 'quote)
2338 (nth 1 (nth 1 form))
2339 (byte-compile-keep-pending form)))
2340
2341 (put 'defun 'byte-hunk-handler 'byte-compile-file-form-defun)
2342 (defun byte-compile-file-form-defun (form)
2343 (byte-compile-file-form-defmumble form nil))
2344
2345 (put 'defmacro 'byte-hunk-handler 'byte-compile-file-form-defmacro)
2346 (defun byte-compile-file-form-defmacro (form)
2347 (byte-compile-file-form-defmumble form t))
2348
2349 (defun byte-compile-defmacro-declaration (form)
2350 "Generate code for declarations in macro definitions.
2351 Remove declarations from the body of the macro definition
2352 by side-effects."
2353 (let ((tail (nthcdr 2 form))
2354 (res '()))
2355 (when (stringp (car (cdr tail)))
2356 (setq tail (cdr tail)))
2357 (while (and (consp (car (cdr tail)))
2358 (eq (car (car (cdr tail))) 'declare))
2359 (let ((declaration (car (cdr tail))))
2360 (setcdr tail (cdr (cdr tail)))
2361 (push `(if macro-declaration-function
2362 (funcall macro-declaration-function
2363 ',(car (cdr form)) ',declaration))
2364 res)))
2365 res))
2366
2367 (defun byte-compile-file-form-defmumble (form macrop)
2368 (let* ((bytecomp-name (car (cdr form)))
2369 (bytecomp-this-kind (if macrop 'byte-compile-macro-environment
2370 'byte-compile-function-environment))
2371 (bytecomp-that-kind (if macrop 'byte-compile-function-environment
2372 'byte-compile-macro-environment))
2373 (bytecomp-this-one (assq bytecomp-name
2374 (symbol-value bytecomp-this-kind)))
2375 (bytecomp-that-one (assq bytecomp-name
2376 (symbol-value bytecomp-that-kind)))
2377 (byte-compile-free-references nil)
2378 (byte-compile-free-assignments nil))
2379 (byte-compile-set-symbol-position bytecomp-name)
2380 ;; When a function or macro is defined, add it to the call tree so that
2381 ;; we can tell when functions are not used.
2382 (if byte-compile-generate-call-tree
2383 (or (assq bytecomp-name byte-compile-call-tree)
2384 (setq byte-compile-call-tree
2385 (cons (list bytecomp-name nil nil) byte-compile-call-tree))))
2386
2387 (setq byte-compile-current-form bytecomp-name) ; for warnings
2388 (if (byte-compile-warning-enabled-p 'redefine)
2389 (byte-compile-arglist-warn form macrop))
2390 (if byte-compile-verbose
2391 ;; bytecomp-filename is from byte-compile-from-buffer.
2392 (message "Compiling %s... (%s)" (or bytecomp-filename "") (nth 1 form)))
2393 (cond (bytecomp-that-one
2394 (if (and (byte-compile-warning-enabled-p 'redefine)
2395 ;; don't warn when compiling the stubs in byte-run...
2396 (not (assq (nth 1 form)
2397 byte-compile-initial-macro-environment)))
2398 (byte-compile-warn
2399 "`%s' defined multiple times, as both function and macro"
2400 (nth 1 form)))
2401 (setcdr bytecomp-that-one nil))
2402 (bytecomp-this-one
2403 (when (and (byte-compile-warning-enabled-p 'redefine)
2404 ;; hack: don't warn when compiling the magic internal
2405 ;; byte-compiler macros in byte-run.el...
2406 (not (assq (nth 1 form)
2407 byte-compile-initial-macro-environment)))
2408 (byte-compile-warn "%s `%s' defined multiple times in this file"
2409 (if macrop "macro" "function")
2410 (nth 1 form))))
2411 ((and (fboundp bytecomp-name)
2412 (eq (car-safe (symbol-function bytecomp-name))
2413 (if macrop 'lambda 'macro)))
2414 (when (byte-compile-warning-enabled-p 'redefine)
2415 (byte-compile-warn "%s `%s' being redefined as a %s"
2416 (if macrop "function" "macro")
2417 (nth 1 form)
2418 (if macrop "macro" "function")))
2419 ;; shadow existing definition
2420 (set bytecomp-this-kind
2421 (cons (cons bytecomp-name nil)
2422 (symbol-value bytecomp-this-kind))))
2423 )
2424 (let ((body (nthcdr 3 form)))
2425 (when (and (stringp (car body))
2426 (symbolp (car-safe (cdr-safe body)))
2427 (car-safe (cdr-safe body))
2428 (stringp (car-safe (cdr-safe (cdr-safe body)))))
2429 (byte-compile-set-symbol-position (nth 1 form))
2430 (byte-compile-warn "probable `\"' without `\\' in doc string of %s"
2431 (nth 1 form))))
2432
2433 ;; Generate code for declarations in macro definitions.
2434 ;; Remove declarations from the body of the macro definition.
2435 (when macrop
2436 (dolist (decl (byte-compile-defmacro-declaration form))
2437 (prin1 decl bytecomp-outbuffer)))
2438
2439 (let* ((new-one (byte-compile-lambda (nthcdr 2 form) t))
2440 (code (byte-compile-byte-code-maker new-one)))
2441 (if bytecomp-this-one
2442 (setcdr bytecomp-this-one new-one)
2443 (set bytecomp-this-kind
2444 (cons (cons bytecomp-name new-one)
2445 (symbol-value bytecomp-this-kind))))
2446 (if (and (stringp (nth 3 form))
2447 (eq 'quote (car-safe code))
2448 (eq 'lambda (car-safe (nth 1 code))))
2449 (cons (car form)
2450 (cons bytecomp-name (cdr (nth 1 code))))
2451 (byte-compile-flush-pending)
2452 (if (not (stringp (nth 3 form)))
2453 ;; No doc string. Provide -1 as the "doc string index"
2454 ;; so that no element will be treated as a doc string.
2455 (byte-compile-output-docform
2456 "\n(defalias '"
2457 bytecomp-name
2458 (cond ((atom code)
2459 (if macrop '(" '(macro . #[" -1 "])") '(" #[" -1 "]")))
2460 ((eq (car code) 'quote)
2461 (setq code new-one)
2462 (if macrop '(" '(macro " -1 ")") '(" '(" -1 ")")))
2463 ((if macrop '(" (cons 'macro (" -1 "))") '(" (" -1 ")"))))
2464 (append code nil)
2465 (and (atom code) byte-compile-dynamic
2466 1)
2467 nil)
2468 ;; Output the form by hand, that's much simpler than having
2469 ;; b-c-output-file-form analyze the defalias.
2470 (byte-compile-output-docform
2471 "\n(defalias '"
2472 bytecomp-name
2473 (cond ((atom code)
2474 (if macrop '(" '(macro . #[" 4 "])") '(" #[" 4 "]")))
2475 ((eq (car code) 'quote)
2476 (setq code new-one)
2477 (if macrop '(" '(macro " 2 ")") '(" '(" 2 ")")))
2478 ((if macrop '(" (cons 'macro (" 5 "))") '(" (" 5 ")"))))
2479 (append code nil)
2480 (and (atom code) byte-compile-dynamic
2481 1)
2482 nil))
2483 (princ ")" bytecomp-outbuffer)
2484 nil))))
2485
2486 ;; Print Lisp object EXP in the output file, inside a comment,
2487 ;; and return the file position it will have.
2488 ;; If QUOTED is non-nil, print with quoting; otherwise, print without quoting.
2489 (defun byte-compile-output-as-comment (exp quoted)
2490 (let ((position (point)))
2491 (with-current-buffer bytecomp-outbuffer
2492
2493 ;; Insert EXP, and make it a comment with #@LENGTH.
2494 (insert " ")
2495 (if quoted
2496 (prin1 exp bytecomp-outbuffer)
2497 (princ exp bytecomp-outbuffer))
2498 (goto-char position)
2499 ;; Quote certain special characters as needed.
2500 ;; get_doc_string in doc.c does the unquoting.
2501 (while (search-forward "\^A" nil t)
2502 (replace-match "\^A\^A" t t))
2503 (goto-char position)
2504 (while (search-forward "\000" nil t)
2505 (replace-match "\^A0" t t))
2506 (goto-char position)
2507 (while (search-forward "\037" nil t)
2508 (replace-match "\^A_" t t))
2509 (goto-char (point-max))
2510 (insert "\037")
2511 (goto-char position)
2512 (insert "#@" (format "%d" (- (position-bytes (point-max))
2513 (position-bytes position))))
2514
2515 ;; Save the file position of the object.
2516 ;; Note we should add 1 to skip the space
2517 ;; that we inserted before the actual doc string,
2518 ;; and subtract 1 to convert from an 1-origin Emacs position
2519 ;; to a file position; they cancel.
2520 (setq position (point))
2521 (goto-char (point-max)))
2522 position))
2523
2524
2525 \f
2526 ;;;###autoload
2527 (defun byte-compile (form)
2528 "If FORM is a symbol, byte-compile its function definition.
2529 If FORM is a lambda or a macro, byte-compile it as a function."
2530 (displaying-byte-compile-warnings
2531 (byte-compile-close-variables
2532 (let* ((fun (if (symbolp form)
2533 (and (fboundp form) (symbol-function form))
2534 form))
2535 (macro (eq (car-safe fun) 'macro)))
2536 (if macro
2537 (setq fun (cdr fun)))
2538 (cond ((eq (car-safe fun) 'lambda)
2539 ;; expand macros
2540 (setq fun
2541 (macroexpand-all fun
2542 byte-compile-initial-macro-environment))
2543 ;; get rid of the `function' quote added by the `lambda' macro
2544 (setq fun (cadr fun))
2545 (setq fun (if macro
2546 (cons 'macro (byte-compile-lambda fun))
2547 (byte-compile-lambda fun)))
2548 (if (symbolp form)
2549 (defalias form fun)
2550 fun)))))))
2551
2552 (defun byte-compile-sexp (sexp)
2553 "Compile and return SEXP."
2554 (displaying-byte-compile-warnings
2555 (byte-compile-close-variables
2556 (byte-compile-top-level sexp))))
2557
2558 ;; Given a function made by byte-compile-lambda, make a form which produces it.
2559 (defun byte-compile-byte-code-maker (fun)
2560 (cond
2561 ;; ## atom is faster than compiled-func-p.
2562 ((atom fun) ; compiled function.
2563 ;; generate-emacs19-bytecodes must be on, otherwise byte-compile-lambda
2564 ;; would have produced a lambda.
2565 fun)
2566 ;; b-c-lambda didn't produce a compiled-function, so it's either a trivial
2567 ;; function, or this is Emacs 18, or generate-emacs19-bytecodes is off.
2568 ((let (tmp)
2569 (if (and (setq tmp (assq 'byte-code (cdr-safe (cdr fun))))
2570 (null (cdr (memq tmp fun))))
2571 ;; Generate a make-byte-code call.
2572 (let* ((interactive (assq 'interactive (cdr (cdr fun)))))
2573 (nconc (list 'make-byte-code
2574 (list 'quote (nth 1 fun)) ;arglist
2575 (nth 1 tmp) ;bytes
2576 (nth 2 tmp) ;consts
2577 (nth 3 tmp)) ;depth
2578 (cond ((stringp (nth 2 fun))
2579 (list (nth 2 fun))) ;doc
2580 (interactive
2581 (list nil)))
2582 (cond (interactive
2583 (list (if (or (null (nth 1 interactive))
2584 (stringp (nth 1 interactive)))
2585 (nth 1 interactive)
2586 ;; Interactive spec is a list or a variable
2587 ;; (if it is correct).
2588 (list 'quote (nth 1 interactive))))))))
2589 ;; a non-compiled function (probably trivial)
2590 (list 'quote fun))))))
2591
2592 ;; Turn a function into an ordinary lambda. Needed for v18 files.
2593 (defun byte-compile-byte-code-unmake (function)
2594 (if (consp function)
2595 function;;It already is a lambda.
2596 (setq function (append function nil)) ; turn it into a list
2597 (nconc (list 'lambda (nth 0 function))
2598 (and (nth 4 function) (list (nth 4 function)))
2599 (if (nthcdr 5 function)
2600 (list (cons 'interactive (if (nth 5 function)
2601 (nthcdr 5 function)))))
2602 (list (list 'byte-code
2603 (nth 1 function) (nth 2 function)
2604 (nth 3 function))))))
2605
2606
2607 (defun byte-compile-check-lambda-list (list)
2608 "Check lambda-list LIST for errors."
2609 (let (vars)
2610 (while list
2611 (let ((arg (car list)))
2612 (when (symbolp arg)
2613 (byte-compile-set-symbol-position arg))
2614 (cond ((or (not (symbolp arg))
2615 (byte-compile-const-symbol-p arg t))
2616 (error "Invalid lambda variable %s" arg))
2617 ((eq arg '&rest)
2618 (unless (cdr list)
2619 (error "&rest without variable name"))
2620 (when (cddr list)
2621 (error "Garbage following &rest VAR in lambda-list")))
2622 ((eq arg '&optional)
2623 (unless (cdr list)
2624 (error "Variable name missing after &optional")))
2625 ((memq arg vars)
2626 (byte-compile-warn "repeated variable %s in lambda-list" arg))
2627 (t
2628 (push arg vars))))
2629 (setq list (cdr list)))))
2630
2631
2632 (autoload 'byte-compile-make-lambda-lexenv "byte-lexbind")
2633
2634 ;; Byte-compile a lambda-expression and return a valid function.
2635 ;; The value is usually a compiled function but may be the original
2636 ;; lambda-expression.
2637 ;; When ADD-LAMBDA is non-nil, the symbol `lambda' is added as head
2638 ;; of the list FUN and `byte-compile-set-symbol-position' is not called.
2639 ;; Use this feature to avoid calling `byte-compile-set-symbol-position'
2640 ;; for symbols generated by the byte compiler itself.
2641 (defun byte-compile-lambda (bytecomp-fun &optional add-lambda)
2642 (if add-lambda
2643 (setq bytecomp-fun (cons 'lambda bytecomp-fun))
2644 (unless (eq 'lambda (car-safe bytecomp-fun))
2645 (error "Not a lambda list: %S" bytecomp-fun))
2646 (byte-compile-set-symbol-position 'lambda))
2647 (byte-compile-check-lambda-list (nth 1 bytecomp-fun))
2648 (let* ((bytecomp-arglist (nth 1 bytecomp-fun))
2649 (byte-compile-bound-variables
2650 (nconc (and (byte-compile-warning-enabled-p 'free-vars)
2651 (delq '&rest
2652 (delq '&optional (copy-sequence bytecomp-arglist))))
2653 byte-compile-bound-variables))
2654 (bytecomp-body (cdr (cdr bytecomp-fun)))
2655 (bytecomp-doc (if (stringp (car bytecomp-body))
2656 (prog1 (car bytecomp-body)
2657 ;; Discard the doc string
2658 ;; unless it is the last element of the body.
2659 (if (cdr bytecomp-body)
2660 (setq bytecomp-body (cdr bytecomp-body))))))
2661 (bytecomp-int (assq 'interactive bytecomp-body)))
2662 ;; Process the interactive spec.
2663 (when bytecomp-int
2664 (byte-compile-set-symbol-position 'interactive)
2665 ;; Skip (interactive) if it is in front (the most usual location).
2666 (if (eq bytecomp-int (car bytecomp-body))
2667 (setq bytecomp-body (cdr bytecomp-body)))
2668 (cond ((consp (cdr bytecomp-int))
2669 (if (cdr (cdr bytecomp-int))
2670 (byte-compile-warn "malformed interactive spec: %s"
2671 (prin1-to-string bytecomp-int)))
2672 ;; If the interactive spec is a call to `list', don't
2673 ;; compile it, because `call-interactively' looks at the
2674 ;; args of `list'. Actually, compile it to get warnings,
2675 ;; but don't use the result.
2676 (let ((form (nth 1 bytecomp-int)))
2677 (while (memq (car-safe form) '(let let* progn save-excursion))
2678 (while (consp (cdr form))
2679 (setq form (cdr form)))
2680 (setq form (car form)))
2681 (if (eq (car-safe form) 'list)
2682 (byte-compile-top-level (nth 1 bytecomp-int))
2683 (setq bytecomp-int (list 'interactive
2684 (byte-compile-top-level
2685 (nth 1 bytecomp-int)))))))
2686 ((cdr bytecomp-int)
2687 (byte-compile-warn "malformed interactive spec: %s"
2688 (prin1-to-string bytecomp-int)))))
2689 ;; Process the body.
2690 (let* ((byte-compile-lexical-environment
2691 ;; If doing lexical binding, push a new lexical environment
2692 ;; containing the args and any closed-over variables.
2693 (and lexical-binding
2694 (byte-compile-make-lambda-lexenv
2695 fun
2696 byte-compile-lexical-environment)))
2697 (is-closure
2698 ;; This is true if we should be making a closure instead of
2699 ;; a simple lambda (because some variables from the
2700 ;; containing lexical environment are closed over).
2701 (and lexical-binding
2702 (byte-compile-closure-initial-lexenv-p
2703 byte-compile-lexical-environment)))
2704 (byte-compile-current-heap-environment nil)
2705 (byte-compile-current-num-closures 0)
2706 (compiled
2707 (byte-compile-top-level (cons 'progn bytecomp-body) nil 'lambda)))
2708 ;; Build the actual byte-coded function.
2709 (if (eq 'byte-code (car-safe compiled))
2710 (let ((code
2711 (apply 'make-byte-code
2712 (append (list bytecomp-arglist)
2713 ;; byte-string, constants-vector, stack depth
2714 (cdr compiled)
2715 ;; optionally, the doc string.
2716 (if (or bytecomp-doc bytecomp-int
2717 lexical-binding)
2718 (list bytecomp-doc))
2719 ;; optionally, the interactive spec.
2720 (if (or bytecomp-int lexical-binding)
2721 (list (nth 1 bytecomp-int)))
2722 (if lexical-binding
2723 '(t))))))
2724 (if is-closure
2725 (cons 'closure code)
2726 code))
2727 (setq compiled
2728 (nconc (if bytecomp-int (list bytecomp-int))
2729 (cond ((eq (car-safe compiled) 'progn) (cdr compiled))
2730 (compiled (list compiled)))))
2731 (nconc (list 'lambda bytecomp-arglist)
2732 (if (or bytecomp-doc (stringp (car compiled)))
2733 (cons bytecomp-doc (cond (compiled)
2734 (bytecomp-body (list nil))))
2735 compiled))))))
2736
2737 (defun byte-compile-closure-code-p (code)
2738 (eq (car-safe code) 'closure))
2739
2740 (defun byte-compile-make-closure (code)
2741 ;; A real closure requires that the constant be curried with an
2742 ;; environment vector to make a closure object.
2743 (if for-effect
2744 (setq for-effect nil)
2745 (byte-compile-push-constant 'curry)
2746 (byte-compile-push-constant code)
2747 (byte-compile-lexical-variable-ref byte-compile-current-heap-environment)
2748 (byte-compile-out 'byte-call 2)))
2749
2750 (defun byte-compile-closure (form &optional add-lambda)
2751 (let ((code (byte-compile-lambda form add-lambda)))
2752 (if (byte-compile-closure-code-p code)
2753 (byte-compile-make-closure code)
2754 ;; A simple lambda is just a constant
2755 (byte-compile-constant code))))
2756
2757 (defun byte-compile-constants-vector ()
2758 ;; Builds the constants-vector from the current variables and constants.
2759 ;; This modifies the constants from (const . nil) to (const . offset).
2760 ;; To keep the byte-codes to look up the vector as short as possible:
2761 ;; First 6 elements are vars, as there are one-byte varref codes for those.
2762 ;; Next up to byte-constant-limit are constants, still with one-byte codes.
2763 ;; Next variables again, to get 2-byte codes for variable lookup.
2764 ;; The rest of the constants and variables need 3-byte byte-codes.
2765 (let* ((i -1)
2766 (rest (nreverse byte-compile-variables)) ; nreverse because the first
2767 (other (nreverse byte-compile-constants)) ; vars often are used most.
2768 ret tmp
2769 (limits '(5 ; Use the 1-byte varref codes,
2770 63 ; 1-constlim ; 1-byte byte-constant codes,
2771 255 ; 2-byte varref codes,
2772 65535)) ; 3-byte codes for the rest.
2773 limit)
2774 (while (or rest other)
2775 (setq limit (car limits))
2776 (while (and rest (not (eq i limit)))
2777 (if (setq tmp (assq (car (car rest)) ret))
2778 (setcdr (car rest) (cdr tmp))
2779 (setcdr (car rest) (setq i (1+ i)))
2780 (setq ret (cons (car rest) ret)))
2781 (setq rest (cdr rest)))
2782 (setq limits (cdr limits)
2783 rest (prog1 other
2784 (setq other rest))))
2785 (apply 'vector (nreverse (mapcar 'car ret)))))
2786
2787 ;; Given an expression FORM, compile it and return an equivalent byte-code
2788 ;; expression (a call to the function byte-code).
2789 (defun byte-compile-top-level (form &optional for-effect output-type)
2790 ;; OUTPUT-TYPE advises about how form is expected to be used:
2791 ;; 'eval or nil -> a single form,
2792 ;; 'progn or t -> a list of forms,
2793 ;; 'lambda -> body of a lambda,
2794 ;; 'file -> used at file-level.
2795 (let ((byte-compile-constants nil)
2796 (byte-compile-variables nil)
2797 (byte-compile-tag-number 0)
2798 (byte-compile-depth 0)
2799 (byte-compile-maxdepth 0)
2800 (byte-compile-output nil))
2801 (if (memq byte-optimize '(t source))
2802 (setq form (byte-optimize-form form for-effect)))
2803 (while (and (eq (car-safe form) 'progn) (null (cdr (cdr form))))
2804 (setq form (nth 1 form)))
2805 (if (and (eq 'byte-code (car-safe form))
2806 (not (memq byte-optimize '(t byte)))
2807 (stringp (nth 1 form)) (vectorp (nth 2 form))
2808 (natnump (nth 3 form)))
2809 form
2810 ;; Set up things for a lexically-bound function
2811 (when (and lexical-binding (eq output-type 'lambda))
2812 ;; See how many arguments there are, and set the current stack depth
2813 ;; accordingly
2814 (dolist (var byte-compile-lexical-environment)
2815 (when (byte-compile-lexvar-on-stack-p var)
2816 (setq byte-compile-depth (1+ byte-compile-depth))))
2817 ;; If there are args, output a tag to record the initial
2818 ;; stack-depth for the optimizer
2819 (when (> byte-compile-depth 0)
2820 (byte-compile-out-tag (byte-compile-make-tag)))
2821 ;; If this is the top-level of a lexically bound lambda expression,
2822 ;; perhaps some parameters on stack need to be copied into a heap
2823 ;; environment, so check for them, and do so if necessary.
2824 (let ((lforminfo (byte-compile-make-lforminfo)))
2825 ;; Add any lexical variable that's on the stack to the analysis set.
2826 (dolist (var byte-compile-lexical-environment)
2827 (when (byte-compile-lexvar-on-stack-p var)
2828 (byte-compile-lforminfo-add-var lforminfo (car var) t)))
2829 ;; Analyze the body
2830 (unless (null (byte-compile-lforminfo-vars lforminfo))
2831 (byte-compile-lforminfo-analyze lforminfo form nil nil))
2832 ;; If the analysis revealed some argument need to be in a heap
2833 ;; environment (because they're closed over by an embedded
2834 ;; lambda), put them there.
2835 (setq byte-compile-lexical-environment
2836 (nconc (byte-compile-maybe-push-heap-environment lforminfo)
2837 byte-compile-lexical-environment))
2838 (dolist (arginfo (byte-compile-lforminfo-vars lforminfo))
2839 (when (byte-compile-lvarinfo-closed-over-p arginfo)
2840 (byte-compile-bind (car arginfo)
2841 byte-compile-lexical-environment
2842 lforminfo)))))
2843 ;; Now compile FORM
2844 (byte-compile-form form for-effect)
2845 (byte-compile-out-toplevel for-effect output-type))))
2846
2847 (defun byte-compile-out-toplevel (&optional for-effect output-type)
2848 (if for-effect
2849 ;; The stack is empty. Push a value to be returned from (byte-code ..).
2850 (if (eq (car (car byte-compile-output)) 'byte-discard)
2851 (setq byte-compile-output (cdr byte-compile-output))
2852 (byte-compile-push-constant
2853 ;; Push any constant - preferably one which already is used, and
2854 ;; a number or symbol - ie not some big sequence. The return value
2855 ;; isn't returned, but it would be a shame if some textually large
2856 ;; constant was not optimized away because we chose to return it.
2857 (and (not (assq nil byte-compile-constants)) ; Nil is often there.
2858 (let ((tmp (reverse byte-compile-constants)))
2859 (while (and tmp (not (or (symbolp (caar tmp))
2860 (numberp (caar tmp)))))
2861 (setq tmp (cdr tmp)))
2862 (caar tmp))))))
2863 (byte-compile-out 'byte-return 0)
2864 (setq byte-compile-output (nreverse byte-compile-output))
2865 (if (memq byte-optimize '(t byte))
2866 (setq byte-compile-output
2867 (byte-optimize-lapcode byte-compile-output for-effect)))
2868
2869 ;; Decompile trivial functions:
2870 ;; only constants and variables, or a single funcall except in lambdas.
2871 ;; Except for Lisp_Compiled objects, forms like (foo "hi")
2872 ;; are still quicker than (byte-code "..." [foo "hi"] 2).
2873 ;; Note that even (quote foo) must be parsed just as any subr by the
2874 ;; interpreter, so quote should be compiled into byte-code in some contexts.
2875 ;; What to leave uncompiled:
2876 ;; lambda -> never. we used to leave it uncompiled if the body was
2877 ;; a single atom, but that causes confusion if the docstring
2878 ;; uses the (file . pos) syntax. Besides, now that we have
2879 ;; the Lisp_Compiled type, the compiled form is faster.
2880 ;; eval -> atom, quote or (function atom atom atom)
2881 ;; progn -> as <<same-as-eval>> or (progn <<same-as-eval>> atom)
2882 ;; file -> as progn, but takes both quotes and atoms, and longer forms.
2883 (let (rest
2884 (maycall (not (eq output-type 'lambda))) ; t if we may make a funcall.
2885 tmp body)
2886 (cond
2887 ;; #### This should be split out into byte-compile-nontrivial-function-p.
2888 ((or (eq output-type 'lambda)
2889 (nthcdr (if (eq output-type 'file) 50 8) byte-compile-output)
2890 (assq 'TAG byte-compile-output) ; Not necessary, but speeds up a bit.
2891 (not (setq tmp (assq 'byte-return byte-compile-output)))
2892 (progn
2893 (setq rest (nreverse
2894 (cdr (memq tmp (reverse byte-compile-output)))))
2895 (while (cond
2896 ((memq (car (car rest)) '(byte-varref byte-constant))
2897 (setq tmp (car (cdr (car rest))))
2898 (if (if (eq (car (car rest)) 'byte-constant)
2899 (or (consp tmp)
2900 (and (symbolp tmp)
2901 (not (byte-compile-const-symbol-p tmp)))))
2902 (if maycall
2903 (setq body (cons (list 'quote tmp) body)))
2904 (setq body (cons tmp body))))
2905 ((and maycall
2906 ;; Allow a funcall if at most one atom follows it.
2907 (null (nthcdr 3 rest))
2908 (setq tmp (get (car (car rest)) 'byte-opcode-invert))
2909 (or (null (cdr rest))
2910 (and (memq output-type '(file progn t))
2911 (cdr (cdr rest))
2912 (eq (car (nth 1 rest)) 'byte-discard)
2913 (progn (setq rest (cdr rest)) t))))
2914 (setq maycall nil) ; Only allow one real function call.
2915 (setq body (nreverse body))
2916 (setq body (list
2917 (if (and (eq tmp 'funcall)
2918 (eq (car-safe (car body)) 'quote))
2919 (cons (nth 1 (car body)) (cdr body))
2920 (cons tmp body))))
2921 (or (eq output-type 'file)
2922 (not (delq nil (mapcar 'consp (cdr (car body))))))))
2923 (setq rest (cdr rest)))
2924 rest))
2925 (let ((byte-compile-vector (byte-compile-constants-vector)))
2926 (list 'byte-code (byte-compile-lapcode byte-compile-output)
2927 byte-compile-vector byte-compile-maxdepth)))
2928 ;; it's a trivial function
2929 ((cdr body) (cons 'progn (nreverse body)))
2930 ((car body)))))
2931
2932 ;; Given BYTECOMP-BODY, compile it and return a new body.
2933 (defun byte-compile-top-level-body (bytecomp-body &optional for-effect)
2934 (setq bytecomp-body
2935 (byte-compile-top-level (cons 'progn bytecomp-body) for-effect t))
2936 (cond ((eq (car-safe bytecomp-body) 'progn)
2937 (cdr bytecomp-body))
2938 (bytecomp-body
2939 (list bytecomp-body))))
2940
2941 (put 'declare-function 'byte-hunk-handler 'byte-compile-declare-function)
2942 (defun byte-compile-declare-function (form)
2943 (push (cons (nth 1 form)
2944 (if (and (> (length form) 3)
2945 (listp (nth 3 form)))
2946 (list 'declared (nth 3 form))
2947 t)) ; arglist not specified
2948 byte-compile-function-environment)
2949 ;; We are stating that it _will_ be defined at runtime.
2950 (setq byte-compile-noruntime-functions
2951 (delq (nth 1 form) byte-compile-noruntime-functions))
2952 nil)
2953
2954 \f
2955 ;; This is the recursive entry point for compiling each subform of an
2956 ;; expression.
2957 ;; If for-effect is non-nil, byte-compile-form will output a byte-discard
2958 ;; before terminating (ie no value will be left on the stack).
2959 ;; A byte-compile handler may, when for-effect is non-nil, choose output code
2960 ;; which does not leave a value on the stack, and then set for-effect to nil
2961 ;; (to prevent byte-compile-form from outputting the byte-discard).
2962 ;; If a handler wants to call another handler, it should do so via
2963 ;; byte-compile-form, or take extreme care to handle for-effect correctly.
2964 ;; (Use byte-compile-form-do-effect to reset the for-effect flag too.)
2965 ;;
2966 (defun byte-compile-form (form &optional for-effect)
2967 (cond ((not (consp form))
2968 (cond ((or (not (symbolp form)) (byte-compile-const-symbol-p form))
2969 (when (symbolp form)
2970 (byte-compile-set-symbol-position form))
2971 (byte-compile-constant form))
2972 ((and for-effect byte-compile-delete-errors)
2973 (when (symbolp form)
2974 (byte-compile-set-symbol-position form))
2975 (setq for-effect nil))
2976 (t
2977 (byte-compile-variable-ref form))))
2978 ((symbolp (car form))
2979 (let* ((bytecomp-fn (car form))
2980 (bytecomp-handler (get bytecomp-fn 'byte-compile)))
2981 (when (byte-compile-const-symbol-p bytecomp-fn)
2982 (byte-compile-warn "`%s' called as a function" bytecomp-fn))
2983 (and (byte-compile-warning-enabled-p 'interactive-only)
2984 (memq bytecomp-fn byte-compile-interactive-only-functions)
2985 (byte-compile-warn "`%s' used from Lisp code\n\
2986 That command is designed for interactive use only" bytecomp-fn))
2987 (when (byte-compile-warning-enabled-p 'callargs)
2988 (if (memq bytecomp-fn
2989 '(custom-declare-group custom-declare-variable
2990 custom-declare-face))
2991 (byte-compile-nogroup-warn form))
2992 (byte-compile-callargs-warn form))
2993 (if (and bytecomp-handler
2994 ;; Make sure that function exists. This is important
2995 ;; for CL compiler macros since the symbol may be
2996 ;; `cl-byte-compile-compiler-macro' but if CL isn't
2997 ;; loaded, this function doesn't exist.
2998 (or (not (memq bytecomp-handler
2999 '(cl-byte-compile-compiler-macro)))
3000 (functionp bytecomp-handler)))
3001 (funcall bytecomp-handler form)
3002 (byte-compile-normal-call form))
3003 (if (byte-compile-warning-enabled-p 'cl-functions)
3004 (byte-compile-cl-warn form))))
3005 ((and (or (byte-code-function-p (car form))
3006 (eq (car-safe (car form)) 'lambda))
3007 ;; if the form comes out the same way it went in, that's
3008 ;; because it was malformed, and we couldn't unfold it.
3009 (not (eq form (setq form (byte-compile-unfold-lambda form)))))
3010 (byte-compile-form form for-effect)
3011 (setq for-effect nil))
3012 ((byte-compile-normal-call form)))
3013 (if for-effect
3014 (byte-compile-discard)))
3015
3016 (defun byte-compile-normal-call (form)
3017 (if byte-compile-generate-call-tree
3018 (byte-compile-annotate-call-tree form))
3019 (when (and for-effect (eq (car form) 'mapcar)
3020 (byte-compile-warning-enabled-p 'mapcar))
3021 (byte-compile-set-symbol-position 'mapcar)
3022 (byte-compile-warn
3023 "`mapcar' called for effect; use `mapc' or `dolist' instead"))
3024 (byte-compile-push-constant (car form))
3025 (mapc 'byte-compile-form (cdr form)) ; wasteful, but faster.
3026 (byte-compile-out 'byte-call (length (cdr form))))
3027
3028 (defun byte-compile-check-variable (var &optional binding)
3029 "Do various error checks before a use of the variable VAR.
3030 If BINDING is non-nil, VAR is being bound."
3031 (when (symbolp var)
3032 (byte-compile-set-symbol-position var))
3033 (cond ((or (not (symbolp var)) (byte-compile-const-symbol-p var))
3034 (when (byte-compile-warning-enabled-p 'constants)
3035 (byte-compile-warn (if binding
3036 "attempt to let-bind %s `%s`"
3037 "variable reference to %s `%s'")
3038 (if (symbolp var) "constant" "nonvariable")
3039 (prin1-to-string var))))
3040 ((and (get var 'byte-obsolete-variable)
3041 (not (eq var byte-compile-not-obsolete-var)))
3042 (byte-compile-warn-obsolete var))))
3043
3044 (defsubst byte-compile-dynamic-variable-op (base-op var)
3045 (let ((tmp (assq var byte-compile-variables)))
3046 (unless tmp
3047 (setq tmp (list var))
3048 (push tmp byte-compile-variables))
3049 (byte-compile-out base-op tmp)))
3050
3051 (defun byte-compile-dynamic-variable-bind (var)
3052 "Generate code to bind the lexical variable VAR to the top-of-stack value."
3053 (byte-compile-check-variable var t)
3054 (when (byte-compile-warning-enabled-p 'free-vars)
3055 (push var byte-compile-bound-variables))
3056 (byte-compile-dynamic-variable-op 'byte-varbind var))
3057
3058 ;; This is used when it's know that VAR _definitely_ has a lexical
3059 ;; binding, and no error-checking should be done.
3060 (defun byte-compile-lexical-variable-ref (var)
3061 "Generate code to push the value of the lexical variable VAR on the stack."
3062 (let ((binding (assq var byte-compile-lexical-environment)))
3063 (when (null binding)
3064 (error "Lexical binding not found for `%s'" var))
3065 (if (byte-compile-lexvar-on-stack-p binding)
3066 ;; On the stack
3067 (byte-compile-stack-ref (byte-compile-lexvar-offset binding))
3068 ;; In a heap environment vector; first push the vector on the stack
3069 (byte-compile-lexical-variable-ref
3070 (byte-compile-lexvar-environment binding))
3071 ;; Now get the value from it
3072 (byte-compile-out 'byte-vec-ref (byte-compile-lexvar-offset binding)))))
3073
3074 (defun byte-compile-variable-ref (var)
3075 "Generate code to push the value of the variable VAR on the stack."
3076 (byte-compile-check-variable var)
3077 (let ((lex-binding (assq var byte-compile-lexical-environment)))
3078 (if lex-binding
3079 ;; VAR is lexically bound
3080 (if (byte-compile-lexvar-on-stack-p lex-binding)
3081 ;; On the stack
3082 (byte-compile-stack-ref (byte-compile-lexvar-offset lex-binding))
3083 ;; In a heap environment vector
3084 (byte-compile-lexical-variable-ref
3085 (byte-compile-lexvar-environment lex-binding))
3086 (byte-compile-out 'byte-vec-ref
3087 (byte-compile-lexvar-offset lex-binding)))
3088 ;; VAR is dynamically bound
3089 (unless (or (not (byte-compile-warning-enabled-p 'free-vars))
3090 (boundp var)
3091 (memq var byte-compile-bound-variables)
3092 (memq var byte-compile-free-references))
3093 (byte-compile-warn "reference to free variable `%s'" var)
3094 (push var byte-compile-free-references))
3095 (byte-compile-dynamic-variable-op 'byte-varref var))))
3096
3097 (defun byte-compile-variable-set (var)
3098 "Generate code to set the variable VAR from the top-of-stack value."
3099 (byte-compile-check-variable var)
3100 (let ((lex-binding (assq var byte-compile-lexical-environment)))
3101 (if lex-binding
3102 ;; VAR is lexically bound
3103 (if (byte-compile-lexvar-on-stack-p lex-binding)
3104 ;; On the stack
3105 (byte-compile-stack-set (byte-compile-lexvar-offset lex-binding))
3106 ;; In a heap environment vector
3107 (byte-compile-lexical-variable-ref
3108 (byte-compile-lexvar-environment lex-binding))
3109 (byte-compile-out 'byte-vec-set
3110 (byte-compile-lexvar-offset lex-binding)))
3111 ;; VAR is dynamically bound
3112 (unless (or (not (byte-compile-warning-enabled-p 'free-vars))
3113 (boundp var)
3114 (memq var byte-compile-bound-variables)
3115 (memq var byte-compile-free-assignments))
3116 (byte-compile-warn "assignment to free variable `%s'" var)
3117 (push var byte-compile-free-assignments))
3118 (byte-compile-dynamic-variable-op 'byte-varset var))))
3119
3120 (defmacro byte-compile-get-constant (const)
3121 `(or (if (stringp ,const)
3122 ;; In a string constant, treat properties as significant.
3123 (let (result)
3124 (dolist (elt byte-compile-constants)
3125 (if (equal-including-properties (car elt) ,const)
3126 (setq result elt)))
3127 result)
3128 (assq ,const byte-compile-constants))
3129 (car (setq byte-compile-constants
3130 (cons (list ,const) byte-compile-constants)))))
3131
3132 ;; Use this when the value of a form is a constant. This obeys for-effect.
3133 (defun byte-compile-constant (const)
3134 (if for-effect
3135 (setq for-effect nil)
3136 (when (symbolp const)
3137 (byte-compile-set-symbol-position const))
3138 (byte-compile-out 'byte-constant (byte-compile-get-constant const))))
3139
3140 ;; Use this for a constant that is not the value of its containing form.
3141 ;; This ignores for-effect.
3142 (defun byte-compile-push-constant (const)
3143 (let ((for-effect nil))
3144 (inline (byte-compile-constant const))))
3145
3146 (defun byte-compile-push-unknown-constant (&optional id)
3147 "Generate code to push a `constant' who's value isn't known yet.
3148 A tag is returned which may then later be passed to
3149 `byte-compile-resolve-unknown-constant' to finalize the value.
3150 The optional argument ID is a tag returned by an earlier call to
3151 `byte-compile-push-unknown-constant', in which case the same constant is
3152 pushed again."
3153 (unless id
3154 (setq id (list (make-symbol "unknown")))
3155 (push id byte-compile-constants))
3156 (byte-compile-out 'byte-constant id)
3157 id)
3158
3159 (defun byte-compile-resolve-unknown-constant (id value)
3160 "Give an `unknown constant' a value.
3161 ID is the tag returned by `byte-compile-push-unknown-constant'. and VALUE
3162 is the value it should have."
3163 (setcar id value))
3164
3165 \f
3166 ;; Compile those primitive ordinary functions
3167 ;; which have special byte codes just for speed.
3168
3169 (defmacro byte-defop-compiler (function &optional compile-handler)
3170 "Add a compiler-form for FUNCTION.
3171 If function is a symbol, then the variable \"byte-SYMBOL\" must name
3172 the opcode to be used. If function is a list, the first element
3173 is the function and the second element is the bytecode-symbol.
3174 The second element may be nil, meaning there is no opcode.
3175 COMPILE-HANDLER is the function to use to compile this byte-op, or
3176 may be the abbreviations 0, 1, 2, 3, 0-1, or 1-2.
3177 If it is nil, then the handler is \"byte-compile-SYMBOL.\""
3178 (let (opcode)
3179 (if (symbolp function)
3180 (setq opcode (intern (concat "byte-" (symbol-name function))))
3181 (setq opcode (car (cdr function))
3182 function (car function)))
3183 (let ((fnform
3184 (list 'put (list 'quote function) ''byte-compile
3185 (list 'quote
3186 (or (cdr (assq compile-handler
3187 '((0 . byte-compile-no-args)
3188 (1 . byte-compile-one-arg)
3189 (2 . byte-compile-two-args)
3190 (3 . byte-compile-three-args)
3191 (0-1 . byte-compile-zero-or-one-arg)
3192 (1-2 . byte-compile-one-or-two-args)
3193 (2-3 . byte-compile-two-or-three-args)
3194 )))
3195 compile-handler
3196 (intern (concat "byte-compile-"
3197 (symbol-name function))))))))
3198 (if opcode
3199 (list 'progn fnform
3200 (list 'put (list 'quote function)
3201 ''byte-opcode (list 'quote opcode))
3202 (list 'put (list 'quote opcode)
3203 ''byte-opcode-invert (list 'quote function)))
3204 fnform))))
3205
3206 (defmacro byte-defop-compiler-1 (function &optional compile-handler)
3207 (list 'byte-defop-compiler (list function nil) compile-handler))
3208
3209 \f
3210 (put 'byte-call 'byte-opcode-invert 'funcall)
3211 (put 'byte-list1 'byte-opcode-invert 'list)
3212 (put 'byte-list2 'byte-opcode-invert 'list)
3213 (put 'byte-list3 'byte-opcode-invert 'list)
3214 (put 'byte-list4 'byte-opcode-invert 'list)
3215 (put 'byte-listN 'byte-opcode-invert 'list)
3216 (put 'byte-concat2 'byte-opcode-invert 'concat)
3217 (put 'byte-concat3 'byte-opcode-invert 'concat)
3218 (put 'byte-concat4 'byte-opcode-invert 'concat)
3219 (put 'byte-concatN 'byte-opcode-invert 'concat)
3220 (put 'byte-insertN 'byte-opcode-invert 'insert)
3221
3222 (byte-defop-compiler point 0)
3223 ;;(byte-defop-compiler mark 0) ;; obsolete
3224 (byte-defop-compiler point-max 0)
3225 (byte-defop-compiler point-min 0)
3226 (byte-defop-compiler following-char 0)
3227 (byte-defop-compiler preceding-char 0)
3228 (byte-defop-compiler current-column 0)
3229 (byte-defop-compiler eolp 0)
3230 (byte-defop-compiler eobp 0)
3231 (byte-defop-compiler bolp 0)
3232 (byte-defop-compiler bobp 0)
3233 (byte-defop-compiler current-buffer 0)
3234 ;;(byte-defop-compiler read-char 0) ;; obsolete
3235 (byte-defop-compiler interactive-p 0)
3236 (byte-defop-compiler widen 0)
3237 (byte-defop-compiler end-of-line 0-1)
3238 (byte-defop-compiler forward-char 0-1)
3239 (byte-defop-compiler forward-line 0-1)
3240 (byte-defop-compiler symbolp 1)
3241 (byte-defop-compiler consp 1)
3242 (byte-defop-compiler stringp 1)
3243 (byte-defop-compiler listp 1)
3244 (byte-defop-compiler not 1)
3245 (byte-defop-compiler (null byte-not) 1)
3246 (byte-defop-compiler car 1)
3247 (byte-defop-compiler cdr 1)
3248 (byte-defop-compiler length 1)
3249 (byte-defop-compiler symbol-value 1)
3250 (byte-defop-compiler symbol-function 1)
3251 (byte-defop-compiler (1+ byte-add1) 1)
3252 (byte-defop-compiler (1- byte-sub1) 1)
3253 (byte-defop-compiler goto-char 1)
3254 (byte-defop-compiler char-after 0-1)
3255 (byte-defop-compiler set-buffer 1)
3256 ;;(byte-defop-compiler set-mark 1) ;; obsolete
3257 (byte-defop-compiler forward-word 0-1)
3258 (byte-defop-compiler char-syntax 1)
3259 (byte-defop-compiler nreverse 1)
3260 (byte-defop-compiler car-safe 1)
3261 (byte-defop-compiler cdr-safe 1)
3262 (byte-defop-compiler numberp 1)
3263 (byte-defop-compiler integerp 1)
3264 (byte-defop-compiler skip-chars-forward 1-2)
3265 (byte-defop-compiler skip-chars-backward 1-2)
3266 (byte-defop-compiler eq 2)
3267 (byte-defop-compiler memq 2)
3268 (byte-defop-compiler cons 2)
3269 (byte-defop-compiler aref 2)
3270 (byte-defop-compiler set 2)
3271 (byte-defop-compiler (= byte-eqlsign) 2)
3272 (byte-defop-compiler (< byte-lss) 2)
3273 (byte-defop-compiler (> byte-gtr) 2)
3274 (byte-defop-compiler (<= byte-leq) 2)
3275 (byte-defop-compiler (>= byte-geq) 2)
3276 (byte-defop-compiler get 2)
3277 (byte-defop-compiler nth 2)
3278 (byte-defop-compiler substring 2-3)
3279 (byte-defop-compiler (move-marker byte-set-marker) 2-3)
3280 (byte-defop-compiler set-marker 2-3)
3281 (byte-defop-compiler match-beginning 1)
3282 (byte-defop-compiler match-end 1)
3283 (byte-defop-compiler upcase 1)
3284 (byte-defop-compiler downcase 1)
3285 (byte-defop-compiler string= 2)
3286 (byte-defop-compiler string< 2)
3287 (byte-defop-compiler (string-equal byte-string=) 2)
3288 (byte-defop-compiler (string-lessp byte-string<) 2)
3289 (byte-defop-compiler equal 2)
3290 (byte-defop-compiler nthcdr 2)
3291 (byte-defop-compiler elt 2)
3292 (byte-defop-compiler member 2)
3293 (byte-defop-compiler assq 2)
3294 (byte-defop-compiler (rplaca byte-setcar) 2)
3295 (byte-defop-compiler (rplacd byte-setcdr) 2)
3296 (byte-defop-compiler setcar 2)
3297 (byte-defop-compiler setcdr 2)
3298 (byte-defop-compiler buffer-substring 2)
3299 (byte-defop-compiler delete-region 2)
3300 (byte-defop-compiler narrow-to-region 2)
3301 (byte-defop-compiler (% byte-rem) 2)
3302 (byte-defop-compiler aset 3)
3303
3304 (byte-defop-compiler max byte-compile-associative)
3305 (byte-defop-compiler min byte-compile-associative)
3306 (byte-defop-compiler (+ byte-plus) byte-compile-associative)
3307 (byte-defop-compiler (* byte-mult) byte-compile-associative)
3308
3309 ;;####(byte-defop-compiler move-to-column 1)
3310 (byte-defop-compiler-1 interactive byte-compile-noop)
3311
3312 \f
3313 (defun byte-compile-subr-wrong-args (form n)
3314 (byte-compile-set-symbol-position (car form))
3315 (byte-compile-warn "`%s' called with %d arg%s, but requires %s"
3316 (car form) (length (cdr form))
3317 (if (= 1 (length (cdr form))) "" "s") n)
3318 ;; get run-time wrong-number-of-args error.
3319 (byte-compile-normal-call form))
3320
3321 (defun byte-compile-no-args (form)
3322 (if (not (= (length form) 1))
3323 (byte-compile-subr-wrong-args form "none")
3324 (byte-compile-out (get (car form) 'byte-opcode) 0)))
3325
3326 (defun byte-compile-one-arg (form)
3327 (if (not (= (length form) 2))
3328 (byte-compile-subr-wrong-args form 1)
3329 (byte-compile-form (car (cdr form))) ;; Push the argument
3330 (byte-compile-out (get (car form) 'byte-opcode) 0)))
3331
3332 (defun byte-compile-two-args (form)
3333 (if (not (= (length form) 3))
3334 (byte-compile-subr-wrong-args form 2)
3335 (byte-compile-form (car (cdr form))) ;; Push the arguments
3336 (byte-compile-form (nth 2 form))
3337 (byte-compile-out (get (car form) 'byte-opcode) 0)))
3338
3339 (defun byte-compile-three-args (form)
3340 (if (not (= (length form) 4))
3341 (byte-compile-subr-wrong-args form 3)
3342 (byte-compile-form (car (cdr form))) ;; Push the arguments
3343 (byte-compile-form (nth 2 form))
3344 (byte-compile-form (nth 3 form))
3345 (byte-compile-out (get (car form) 'byte-opcode) 0)))
3346
3347 (defun byte-compile-zero-or-one-arg (form)
3348 (let ((len (length form)))
3349 (cond ((= len 1) (byte-compile-one-arg (append form '(nil))))
3350 ((= len 2) (byte-compile-one-arg form))
3351 (t (byte-compile-subr-wrong-args form "0-1")))))
3352
3353 (defun byte-compile-one-or-two-args (form)
3354 (let ((len (length form)))
3355 (cond ((= len 2) (byte-compile-two-args (append form '(nil))))
3356 ((= len 3) (byte-compile-two-args form))
3357 (t (byte-compile-subr-wrong-args form "1-2")))))
3358
3359 (defun byte-compile-two-or-three-args (form)
3360 (let ((len (length form)))
3361 (cond ((= len 3) (byte-compile-three-args (append form '(nil))))
3362 ((= len 4) (byte-compile-three-args form))
3363 (t (byte-compile-subr-wrong-args form "2-3")))))
3364
3365 (defun byte-compile-noop (form)
3366 (byte-compile-constant nil))
3367
3368 (defun byte-compile-discard (&optional num preserve-tos)
3369 "Output byte codes to discard the NUM entries at the top of the stack (NUM defaults to 1).
3370 If PRESERVE-TOS is non-nil, preserve the top-of-stack value, as if it were
3371 popped before discarding the num values, and then pushed back again after
3372 discarding."
3373 (if (and (null num) (not preserve-tos))
3374 ;; common case
3375 (byte-compile-out 'byte-discard)
3376 ;; general case
3377 (unless num
3378 (setq num 1))
3379 (when (and preserve-tos (> num 0))
3380 ;; Preserve the top-of-stack value by writing it directly to the stack
3381 ;; location which will be at the top-of-stack after popping.
3382 (byte-compile-stack-set (1- (- byte-compile-depth num)))
3383 ;; Now we actually discard one less value, since we want to keep
3384 ;; the eventual TOS
3385 (setq num (1- num)))
3386 (while (> num 0)
3387 (byte-compile-out 'byte-discard)
3388 (setq num (1- num)))))
3389
3390 (defun byte-compile-stack-ref (stack-pos)
3391 "Output byte codes to push the value at position STACK-POS in the stack, on the top of the stack."
3392 (if (= byte-compile-depth (1+ stack-pos))
3393 ;; A simple optimization
3394 (byte-compile-out 'byte-dup)
3395 ;; normal case
3396 (byte-compile-out 'byte-stack-ref stack-pos)))
3397
3398 (defun byte-compile-stack-set (stack-pos)
3399 "Output byte codes to store the top-of-stack value at position STACK-POS in the stack."
3400 (byte-compile-out 'byte-stack-set stack-pos))
3401
3402
3403 ;; Compile a function that accepts one or more args and is right-associative.
3404 ;; We do it by left-associativity so that the operations
3405 ;; are done in the same order as in interpreted code.
3406 ;; We treat the one-arg case, as in (+ x), like (+ x 0).
3407 ;; in order to convert markers to numbers, and trigger expected errors.
3408 (defun byte-compile-associative (form)
3409 (if (cdr form)
3410 (let ((opcode (get (car form) 'byte-opcode))
3411 args)
3412 (if (and (< 3 (length form))
3413 (memq opcode (list (get '+ 'byte-opcode)
3414 (get '* 'byte-opcode))))
3415 ;; Don't use binary operations for > 2 operands, as that
3416 ;; may cause overflow/truncation in float operations.
3417 (byte-compile-normal-call form)
3418 (setq args (copy-sequence (cdr form)))
3419 (byte-compile-form (car args))
3420 (setq args (cdr args))
3421 (or args (setq args '(0)
3422 opcode (get '+ 'byte-opcode)))
3423 (dolist (arg args)
3424 (byte-compile-form arg)
3425 (byte-compile-out opcode 0))))
3426 (byte-compile-constant (eval form))))
3427
3428 \f
3429 ;; more complicated compiler macros
3430
3431 (byte-defop-compiler char-before)
3432 (byte-defop-compiler backward-char)
3433 (byte-defop-compiler backward-word)
3434 (byte-defop-compiler list)
3435 (byte-defop-compiler concat)
3436 (byte-defop-compiler fset)
3437 (byte-defop-compiler (indent-to-column byte-indent-to) byte-compile-indent-to)
3438 (byte-defop-compiler indent-to)
3439 (byte-defop-compiler insert)
3440 (byte-defop-compiler-1 function byte-compile-function-form)
3441 (byte-defop-compiler-1 - byte-compile-minus)
3442 (byte-defop-compiler (/ byte-quo) byte-compile-quo)
3443 (byte-defop-compiler nconc)
3444
3445 (defun byte-compile-char-before (form)
3446 (cond ((= 2 (length form))
3447 (byte-compile-form (list 'char-after (if (numberp (nth 1 form))
3448 (1- (nth 1 form))
3449 `(1- ,(nth 1 form))))))
3450 ((= 1 (length form))
3451 (byte-compile-form '(char-after (1- (point)))))
3452 (t (byte-compile-subr-wrong-args form "0-1"))))
3453
3454 ;; backward-... ==> forward-... with negated argument.
3455 (defun byte-compile-backward-char (form)
3456 (cond ((= 2 (length form))
3457 (byte-compile-form (list 'forward-char (if (numberp (nth 1 form))
3458 (- (nth 1 form))
3459 `(- ,(nth 1 form))))))
3460 ((= 1 (length form))
3461 (byte-compile-form '(forward-char -1)))
3462 (t (byte-compile-subr-wrong-args form "0-1"))))
3463
3464 (defun byte-compile-backward-word (form)
3465 (cond ((= 2 (length form))
3466 (byte-compile-form (list 'forward-word (if (numberp (nth 1 form))
3467 (- (nth 1 form))
3468 `(- ,(nth 1 form))))))
3469 ((= 1 (length form))
3470 (byte-compile-form '(forward-word -1)))
3471 (t (byte-compile-subr-wrong-args form "0-1"))))
3472
3473 (defun byte-compile-list (form)
3474 (let ((count (length (cdr form))))
3475 (cond ((= count 0)
3476 (byte-compile-constant nil))
3477 ((< count 5)
3478 (mapc 'byte-compile-form (cdr form))
3479 (byte-compile-out
3480 (aref [byte-list1 byte-list2 byte-list3 byte-list4] (1- count)) 0))
3481 ((< count 256)
3482 (mapc 'byte-compile-form (cdr form))
3483 (byte-compile-out 'byte-listN count))
3484 (t (byte-compile-normal-call form)))))
3485
3486 (defun byte-compile-concat (form)
3487 (let ((count (length (cdr form))))
3488 (cond ((and (< 1 count) (< count 5))
3489 (mapc 'byte-compile-form (cdr form))
3490 (byte-compile-out
3491 (aref [byte-concat2 byte-concat3 byte-concat4] (- count 2))
3492 0))
3493 ;; Concat of one arg is not a no-op if arg is not a string.
3494 ((= count 0)
3495 (byte-compile-form ""))
3496 ((< count 256)
3497 (mapc 'byte-compile-form (cdr form))
3498 (byte-compile-out 'byte-concatN count))
3499 ((byte-compile-normal-call form)))))
3500
3501 (defun byte-compile-minus (form)
3502 (let ((len (length form)))
3503 (cond
3504 ((= 1 len) (byte-compile-constant 0))
3505 ((= 2 len)
3506 (byte-compile-form (cadr form))
3507 (byte-compile-out 'byte-negate 0))
3508 ((= 3 len)
3509 (byte-compile-form (nth 1 form))
3510 (byte-compile-form (nth 2 form))
3511 (byte-compile-out 'byte-diff 0))
3512 ;; Don't use binary operations for > 2 operands, as that may
3513 ;; cause overflow/truncation in float operations.
3514 (t (byte-compile-normal-call form)))))
3515
3516 (defun byte-compile-quo (form)
3517 (let ((len (length form)))
3518 (cond ((<= len 2)
3519 (byte-compile-subr-wrong-args form "2 or more"))
3520 ((= len 3)
3521 (byte-compile-two-args form))
3522 (t
3523 ;; Don't use binary operations for > 2 operands, as that
3524 ;; may cause overflow/truncation in float operations.
3525 (byte-compile-normal-call form)))))
3526
3527 (defun byte-compile-nconc (form)
3528 (let ((len (length form)))
3529 (cond ((= len 1)
3530 (byte-compile-constant nil))
3531 ((= len 2)
3532 ;; nconc of one arg is a noop, even if that arg isn't a list.
3533 (byte-compile-form (nth 1 form)))
3534 (t
3535 (byte-compile-form (car (setq form (cdr form))))
3536 (while (setq form (cdr form))
3537 (byte-compile-form (car form))
3538 (byte-compile-out 'byte-nconc 0))))))
3539
3540 (defun byte-compile-fset (form)
3541 ;; warn about forms like (fset 'foo '(lambda () ...))
3542 ;; (where the lambda expression is non-trivial...)
3543 (let ((fn (nth 2 form))
3544 body)
3545 (if (and (eq (car-safe fn) 'quote)
3546 (eq (car-safe (setq fn (nth 1 fn))) 'lambda))
3547 (progn
3548 (setq body (cdr (cdr fn)))
3549 (if (stringp (car body)) (setq body (cdr body)))
3550 (if (eq 'interactive (car-safe (car body))) (setq body (cdr body)))
3551 (if (and (consp (car body))
3552 (not (eq 'byte-code (car (car body)))))
3553 (byte-compile-warn
3554 "A quoted lambda form is the second argument of `fset'. This is probably
3555 not what you want, as that lambda cannot be compiled. Consider using
3556 the syntax (function (lambda (...) ...)) instead.")))))
3557 (byte-compile-two-args form))
3558
3559 ;; (function foo) must compile like 'foo, not like (symbol-function 'foo).
3560 ;; Otherwise it will be incompatible with the interpreter,
3561 ;; and (funcall (function foo)) will lose with autoloads.
3562
3563 (defun byte-compile-function-form (form)
3564 (if (symbolp (nth 1 form))
3565 (byte-compile-constant (nth 1 form))
3566 (byte-compile-closure (nth 1 form))))
3567
3568 (defun byte-compile-indent-to (form)
3569 (let ((len (length form)))
3570 (cond ((= len 2)
3571 (byte-compile-form (car (cdr form)))
3572 (byte-compile-out 'byte-indent-to 0))
3573 ((= len 3)
3574 ;; no opcode for 2-arg case.
3575 (byte-compile-normal-call form))
3576 (t
3577 (byte-compile-subr-wrong-args form "1-2")))))
3578
3579 (defun byte-compile-insert (form)
3580 (cond ((null (cdr form))
3581 (byte-compile-constant nil))
3582 ((<= (length form) 256)
3583 (mapc 'byte-compile-form (cdr form))
3584 (if (cdr (cdr form))
3585 (byte-compile-out 'byte-insertN (length (cdr form)))
3586 (byte-compile-out 'byte-insert 0)))
3587 ((memq t (mapcar 'consp (cdr (cdr form))))
3588 (byte-compile-normal-call form))
3589 ;; We can split it; there is no function call after inserting 1st arg.
3590 (t
3591 (while (setq form (cdr form))
3592 (byte-compile-form (car form))
3593 (byte-compile-out 'byte-insert 0)
3594 (if (cdr form)
3595 (byte-compile-discard))))))
3596
3597 \f
3598 (byte-defop-compiler-1 setq)
3599 (byte-defop-compiler-1 setq-default)
3600 (byte-defop-compiler-1 quote)
3601 (byte-defop-compiler-1 quote-form)
3602
3603 (defun byte-compile-setq (form)
3604 (let ((bytecomp-args (cdr form)))
3605 (if bytecomp-args
3606 (while bytecomp-args
3607 (byte-compile-form (car (cdr bytecomp-args)))
3608 (or for-effect (cdr (cdr bytecomp-args))
3609 (byte-compile-out 'byte-dup 0))
3610 (byte-compile-variable-set (car bytecomp-args))
3611 (setq bytecomp-args (cdr (cdr bytecomp-args))))
3612 ;; (setq), with no arguments.
3613 (byte-compile-form nil for-effect))
3614 (setq for-effect nil)))
3615
3616 (defun byte-compile-setq-default (form)
3617 (setq form (cdr form))
3618 (if (> (length form) 2)
3619 (let ((setters ()))
3620 (while (consp form)
3621 (push `(setq-default ,(pop form) ,(pop form)) setters))
3622 (byte-compile-form (cons 'progn (nreverse setters))))
3623 (let ((var (car form)))
3624 (and (or (not (symbolp var))
3625 (byte-compile-const-symbol-p var t))
3626 (byte-compile-warning-enabled-p 'constants)
3627 (byte-compile-warn
3628 "variable assignment to %s `%s'"
3629 (if (symbolp var) "constant" "nonvariable")
3630 (prin1-to-string var)))
3631 (byte-compile-normal-call `(set-default ',var ,@(cdr form))))))
3632
3633 (byte-defop-compiler-1 set-default)
3634 (defun byte-compile-set-default (form)
3635 (let ((varexp (car-safe (cdr-safe form))))
3636 (if (eq (car-safe varexp) 'quote)
3637 ;; If the varexp is constant, compile it as a setq-default
3638 ;; so we get more warnings.
3639 (byte-compile-setq-default `(setq-default ,(car-safe (cdr varexp))
3640 ,@(cddr form)))
3641 (byte-compile-normal-call form))))
3642
3643 (defun byte-compile-quote (form)
3644 (byte-compile-constant (car (cdr form))))
3645
3646 (defun byte-compile-quote-form (form)
3647 (byte-compile-constant (byte-compile-top-level (nth 1 form))))
3648
3649 \f
3650 ;;; control structures
3651
3652 (defun byte-compile-body (bytecomp-body &optional for-effect)
3653 (while (cdr bytecomp-body)
3654 (byte-compile-form (car bytecomp-body) t)
3655 (setq bytecomp-body (cdr bytecomp-body)))
3656 (byte-compile-form (car bytecomp-body) for-effect))
3657
3658 (defsubst byte-compile-body-do-effect (bytecomp-body)
3659 (byte-compile-body bytecomp-body for-effect)
3660 (setq for-effect nil))
3661
3662 (defsubst byte-compile-form-do-effect (form)
3663 (byte-compile-form form for-effect)
3664 (setq for-effect nil))
3665
3666 (byte-defop-compiler-1 inline byte-compile-progn)
3667 (byte-defop-compiler-1 progn)
3668 (byte-defop-compiler-1 prog1)
3669 (byte-defop-compiler-1 prog2)
3670 (byte-defop-compiler-1 if)
3671 (byte-defop-compiler-1 cond)
3672 (byte-defop-compiler-1 and)
3673 (byte-defop-compiler-1 or)
3674 (byte-defop-compiler-1 while)
3675 (byte-defop-compiler-1 funcall)
3676 (byte-defop-compiler-1 let)
3677 (byte-defop-compiler-1 let*)
3678
3679 (defun byte-compile-progn (form)
3680 (byte-compile-body-do-effect (cdr form)))
3681
3682 (defun byte-compile-prog1 (form)
3683 (byte-compile-form-do-effect (car (cdr form)))
3684 (byte-compile-body (cdr (cdr form)) t))
3685
3686 (defun byte-compile-prog2 (form)
3687 (byte-compile-form (nth 1 form) t)
3688 (byte-compile-form-do-effect (nth 2 form))
3689 (byte-compile-body (cdr (cdr (cdr form))) t))
3690
3691 (defmacro byte-compile-goto-if (cond discard tag)
3692 `(byte-compile-goto
3693 (if ,cond
3694 (if ,discard 'byte-goto-if-not-nil 'byte-goto-if-not-nil-else-pop)
3695 (if ,discard 'byte-goto-if-nil 'byte-goto-if-nil-else-pop))
3696 ,tag))
3697
3698 ;; Return the list of items in CONDITION-PARAM that match PRED-LIST.
3699 ;; Only return items that are not in ONLY-IF-NOT-PRESENT.
3700 (defun byte-compile-find-bound-condition (condition-param
3701 pred-list
3702 &optional only-if-not-present)
3703 (let ((result nil)
3704 (nth-one nil)
3705 (cond-list
3706 (if (memq (car-safe condition-param) pred-list)
3707 ;; The condition appears by itself.
3708 (list condition-param)
3709 ;; If the condition is an `and', look for matches among the
3710 ;; `and' arguments.
3711 (when (eq 'and (car-safe condition-param))
3712 (cdr condition-param)))))
3713
3714 (dolist (crt cond-list)
3715 (when (and (memq (car-safe crt) pred-list)
3716 (eq 'quote (car-safe (setq nth-one (nth 1 crt))))
3717 ;; Ignore if the symbol is already on the unresolved
3718 ;; list.
3719 (not (assq (nth 1 nth-one) ; the relevant symbol
3720 only-if-not-present)))
3721 (push (nth 1 (nth 1 crt)) result)))
3722 result))
3723
3724 (defmacro byte-compile-maybe-guarded (condition &rest body)
3725 "Execute forms in BODY, potentially guarded by CONDITION.
3726 CONDITION is a variable whose value is a test in an `if' or `cond'.
3727 BODY is the code to compile in the first arm of the if or the body of
3728 the cond clause. If CONDITION's value is of the form (fboundp 'foo)
3729 or (boundp 'foo), the relevant warnings from BODY about foo's
3730 being undefined (or obsolete) will be suppressed.
3731
3732 If CONDITION's value is (not (featurep 'emacs)) or (featurep 'xemacs),
3733 that suppresses all warnings during execution of BODY."
3734 (declare (indent 1) (debug t))
3735 `(let* ((fbound-list (byte-compile-find-bound-condition
3736 ,condition (list 'fboundp)
3737 byte-compile-unresolved-functions))
3738 (bound-list (byte-compile-find-bound-condition
3739 ,condition (list 'boundp 'default-boundp)))
3740 ;; Maybe add to the bound list.
3741 (byte-compile-bound-variables
3742 (if bound-list
3743 (append bound-list byte-compile-bound-variables)
3744 byte-compile-bound-variables)))
3745 (unwind-protect
3746 ;; If things not being bound at all is ok, so must them being obsolete.
3747 ;; Note that we add to the existing lists since Tramp (ab)uses
3748 ;; this feature.
3749 (let ((byte-compile-not-obsolete-vars
3750 (append byte-compile-not-obsolete-vars bound-list))
3751 (byte-compile-not-obsolete-funcs
3752 (append byte-compile-not-obsolete-funcs fbound-list)))
3753 ,@body)
3754 ;; Maybe remove the function symbol from the unresolved list.
3755 (dolist (fbound fbound-list)
3756 (when fbound
3757 (setq byte-compile-unresolved-functions
3758 (delq (assq fbound byte-compile-unresolved-functions)
3759 byte-compile-unresolved-functions)))))))
3760
3761 (defun byte-compile-if (form)
3762 (byte-compile-form (car (cdr form)))
3763 ;; Check whether we have `(if (fboundp ...' or `(if (boundp ...'
3764 ;; and avoid warnings about the relevent symbols in the consequent.
3765 (let ((clause (nth 1 form))
3766 (donetag (byte-compile-make-tag)))
3767 (if (null (nthcdr 3 form))
3768 ;; No else-forms
3769 (progn
3770 (byte-compile-goto-if nil for-effect donetag)
3771 (byte-compile-maybe-guarded clause
3772 (byte-compile-form (nth 2 form) for-effect))
3773 (byte-compile-out-tag donetag))
3774 (let ((elsetag (byte-compile-make-tag)))
3775 (byte-compile-goto 'byte-goto-if-nil elsetag)
3776 (byte-compile-maybe-guarded clause
3777 (byte-compile-form (nth 2 form) for-effect))
3778 (byte-compile-goto 'byte-goto donetag)
3779 (byte-compile-out-tag elsetag)
3780 (byte-compile-maybe-guarded (list 'not clause)
3781 (byte-compile-body (cdr (cdr (cdr form))) for-effect))
3782 (byte-compile-out-tag donetag))))
3783 (setq for-effect nil))
3784
3785 (defun byte-compile-cond (clauses)
3786 (let ((donetag (byte-compile-make-tag))
3787 nexttag clause)
3788 (while (setq clauses (cdr clauses))
3789 (setq clause (car clauses))
3790 (cond ((or (eq (car clause) t)
3791 (and (eq (car-safe (car clause)) 'quote)
3792 (car-safe (cdr-safe (car clause)))))
3793 ;; Unconditional clause
3794 (setq clause (cons t clause)
3795 clauses nil))
3796 ((cdr clauses)
3797 (byte-compile-form (car clause))
3798 (if (null (cdr clause))
3799 ;; First clause is a singleton.
3800 (byte-compile-goto-if t for-effect donetag)
3801 (setq nexttag (byte-compile-make-tag))
3802 (byte-compile-goto 'byte-goto-if-nil nexttag)
3803 (byte-compile-maybe-guarded (car clause)
3804 (byte-compile-body (cdr clause) for-effect))
3805 (byte-compile-goto 'byte-goto donetag)
3806 (byte-compile-out-tag nexttag)))))
3807 ;; Last clause
3808 (let ((guard (car clause)))
3809 (and (cdr clause) (not (eq guard t))
3810 (progn (byte-compile-form guard)
3811 (byte-compile-goto-if nil for-effect donetag)
3812 (setq clause (cdr clause))))
3813 (byte-compile-maybe-guarded guard
3814 (byte-compile-body-do-effect clause)))
3815 (byte-compile-out-tag donetag)))
3816
3817 (defun byte-compile-and (form)
3818 (let ((failtag (byte-compile-make-tag))
3819 (bytecomp-args (cdr form)))
3820 (if (null bytecomp-args)
3821 (byte-compile-form-do-effect t)
3822 (byte-compile-and-recursion bytecomp-args failtag))))
3823
3824 ;; Handle compilation of a nontrivial `and' call.
3825 ;; We use tail recursion so we can use byte-compile-maybe-guarded.
3826 (defun byte-compile-and-recursion (rest failtag)
3827 (if (cdr rest)
3828 (progn
3829 (byte-compile-form (car rest))
3830 (byte-compile-goto-if nil for-effect failtag)
3831 (byte-compile-maybe-guarded (car rest)
3832 (byte-compile-and-recursion (cdr rest) failtag)))
3833 (byte-compile-form-do-effect (car rest))
3834 (byte-compile-out-tag failtag)))
3835
3836 (defun byte-compile-or (form)
3837 (let ((wintag (byte-compile-make-tag))
3838 (bytecomp-args (cdr form)))
3839 (if (null bytecomp-args)
3840 (byte-compile-form-do-effect nil)
3841 (byte-compile-or-recursion bytecomp-args wintag))))
3842
3843 ;; Handle compilation of a nontrivial `or' call.
3844 ;; We use tail recursion so we can use byte-compile-maybe-guarded.
3845 (defun byte-compile-or-recursion (rest wintag)
3846 (if (cdr rest)
3847 (progn
3848 (byte-compile-form (car rest))
3849 (byte-compile-goto-if t for-effect wintag)
3850 (byte-compile-maybe-guarded (list 'not (car rest))
3851 (byte-compile-or-recursion (cdr rest) wintag)))
3852 (byte-compile-form-do-effect (car rest))
3853 (byte-compile-out-tag wintag)))
3854
3855 (defun byte-compile-while (form)
3856 (let ((endtag (byte-compile-make-tag))
3857 (looptag (byte-compile-make-tag))
3858 ;; Heap environments can't be shared between a loop and its
3859 ;; enclosing environment (because any lexical variables bound
3860 ;; inside the loop should have an independent value for each
3861 ;; iteration). Setting `byte-compile-current-num-closures' to
3862 ;; an invalid value causes the code that tries to merge
3863 ;; environments to not do so.
3864 (byte-compile-current-num-closures -1))
3865 (byte-compile-out-tag looptag)
3866 (byte-compile-form (car (cdr form)))
3867 (byte-compile-goto-if nil for-effect endtag)
3868 (byte-compile-body (cdr (cdr form)) t)
3869 (byte-compile-goto 'byte-goto looptag)
3870 (byte-compile-out-tag endtag)
3871 (setq for-effect nil)))
3872
3873 (defun byte-compile-funcall (form)
3874 (mapc 'byte-compile-form (cdr form))
3875 (byte-compile-out 'byte-call (length (cdr (cdr form)))))
3876
3877 \f
3878 ;; let binding
3879
3880 ;; All other lexical-binding functions are guarded by a non-nil return
3881 ;; value from `byte-compile-compute-lforminfo', so they needn't be
3882 ;; autoloaded.
3883 (autoload 'byte-compile-compute-lforminfo "byte-lexbind")
3884
3885 (defun byte-compile-push-binding-init (clause init-lexenv lforminfo)
3886 "Emit byte-codes to push the initialization value for CLAUSE on the stack.
3887 INIT-LEXENV is the lexical environment created for initializations
3888 already done for this form.
3889 LFORMINFO should be information about lexical variables being bound.
3890 Return INIT-LEXENV updated to include the newest initialization, or nil
3891 if LFORMINFO is nil (meaning all bindings are dynamic)."
3892 (let* ((var (if (consp clause) (car clause) clause))
3893 (vinfo
3894 (and lforminfo (assq var (byte-compile-lforminfo-vars lforminfo))))
3895 (unused (and vinfo (zerop (cadr vinfo)))))
3896 (unless (and unused (symbolp clause))
3897 (when (and lforminfo (not unused))
3898 ;; We record the stack position even of dynamic bindings and
3899 ;; variables in non-stack lexical environments; we'll put
3900 ;; them in the proper place below.
3901 (push (byte-compile-make-lexvar var byte-compile-depth) init-lexenv))
3902 (if (consp clause)
3903 (byte-compile-form (cadr clause) unused)
3904 (byte-compile-push-constant nil))))
3905 init-lexenv)
3906
3907 (defun byte-compile-let (form)
3908 "Generate code for the `let' form FORM."
3909 (let ((clauses (cadr form))
3910 (lforminfo (and lexical-binding (byte-compile-compute-lforminfo form)))
3911 (init-lexenv nil)
3912 ;; bind these to restrict the scope of any changes
3913 (byte-compile-current-heap-environment
3914 byte-compile-current-heap-environment)
3915 (byte-compile-current-num-closures byte-compile-current-num-closures))
3916 (when (and lforminfo (byte-compile-non-stack-bindings-p clauses lforminfo))
3917 ;; Some of the variables we're binding are lexical variables on
3918 ;; the stack, but not all. As much as we can, rearrange the list
3919 ;; so that non-stack lexical variables and dynamically bound
3920 ;; variables come last, which allows slightly more optimal
3921 ;; byte-code for binding them.
3922 (setq clauses (byte-compile-rearrange-let-clauses clauses lforminfo)))
3923 ;; If necessary, create a new heap environment to hold some of the
3924 ;; variables bound here.
3925 (when lforminfo
3926 (setq init-lexenv (byte-compile-maybe-push-heap-environment lforminfo)))
3927 ;; First compute the binding values in the old scope.
3928 (dolist (clause clauses)
3929 (setq init-lexenv
3930 (byte-compile-push-binding-init clause init-lexenv lforminfo)))
3931 ;; Now do the bindings, execute the body, and undo the bindings
3932 (let ((byte-compile-bound-variables byte-compile-bound-variables)
3933 (byte-compile-lexical-environment byte-compile-lexical-environment)
3934 (preserve-body-value (not for-effect)))
3935 (dolist (clause (reverse clauses))
3936 (let ((var (if (consp clause) (car clause) clause)))
3937 (cond ((null lforminfo)
3938 ;; If there are no lexical bindings, we can do things simply.
3939 (byte-compile-dynamic-variable-bind var))
3940 ((byte-compile-bind var init-lexenv lforminfo)
3941 (pop init-lexenv)))))
3942 ;; Emit the body
3943 (byte-compile-body-do-effect (cdr (cdr form)))
3944 ;; Unbind the variables
3945 (if lforminfo
3946 ;; Unbind both lexical and dynamic variables
3947 (byte-compile-unbind clauses init-lexenv lforminfo preserve-body-value)
3948 ;; Unbind dynamic variables
3949 (byte-compile-out 'byte-unbind (length clauses))))))
3950
3951 (defun byte-compile-let* (form)
3952 "Generate code for the `let*' form FORM."
3953 (let ((clauses (cadr form))
3954 (lforminfo (and lexical-binding (byte-compile-compute-lforminfo form)))
3955 (init-lexenv nil)
3956 (preserve-body-value (not for-effect))
3957 ;; bind these to restrict the scope of any changes
3958 (byte-compile-bound-variables byte-compile-bound-variables)
3959 (byte-compile-lexical-environment byte-compile-lexical-environment)
3960 (byte-compile-current-heap-environment
3961 byte-compile-current-heap-environment)
3962 (byte-compile-current-num-closures byte-compile-current-num-closures))
3963 ;; If necessary, create a new heap environment to hold some of the
3964 ;; variables bound here.
3965 (when lforminfo
3966 (setq init-lexenv (byte-compile-maybe-push-heap-environment lforminfo)))
3967 ;; Bind the variables
3968 (dolist (clause clauses)
3969 (setq init-lexenv
3970 (byte-compile-push-binding-init clause init-lexenv lforminfo))
3971 (let ((var (if (consp clause) (car clause) clause)))
3972 (cond ((null lforminfo)
3973 ;; If there are no lexical bindings, we can do things simply.
3974 (byte-compile-dynamic-variable-bind var))
3975 ((byte-compile-bind var init-lexenv lforminfo)
3976 (pop init-lexenv)))))
3977 ;; Emit the body
3978 (byte-compile-body-do-effect (cdr (cdr form)))
3979 ;; Unbind the variables
3980 (if lforminfo
3981 ;; Unbind both lexical and dynamic variables
3982 (byte-compile-unbind clauses init-lexenv lforminfo preserve-body-value)
3983 ;; Unbind dynamic variables
3984 (byte-compile-out 'byte-unbind (length clauses)))))
3985
3986 \f
3987
3988 (byte-defop-compiler-1 /= byte-compile-negated)
3989 (byte-defop-compiler-1 atom byte-compile-negated)
3990 (byte-defop-compiler-1 nlistp byte-compile-negated)
3991
3992 (put '/= 'byte-compile-negated-op '=)
3993 (put 'atom 'byte-compile-negated-op 'consp)
3994 (put 'nlistp 'byte-compile-negated-op 'listp)
3995
3996 (defun byte-compile-negated (form)
3997 (byte-compile-form-do-effect (byte-compile-negation-optimizer form)))
3998
3999 ;; Even when optimization is off, /= is optimized to (not (= ...)).
4000 (defun byte-compile-negation-optimizer (form)
4001 ;; an optimizer for forms where <form1> is less efficient than (not <form2>)
4002 (byte-compile-set-symbol-position (car form))
4003 (list 'not
4004 (cons (or (get (car form) 'byte-compile-negated-op)
4005 (error
4006 "Compiler error: `%s' has no `byte-compile-negated-op' property"
4007 (car form)))
4008 (cdr form))))
4009
4010 \f
4011 ;;; other tricky macro-like special-forms
4012
4013 (byte-defop-compiler-1 catch)
4014 (byte-defop-compiler-1 unwind-protect)
4015 (byte-defop-compiler-1 condition-case)
4016 (byte-defop-compiler-1 save-excursion)
4017 (byte-defop-compiler-1 save-current-buffer)
4018 (byte-defop-compiler-1 save-restriction)
4019 (byte-defop-compiler-1 save-window-excursion)
4020 (byte-defop-compiler-1 with-output-to-temp-buffer)
4021 (byte-defop-compiler-1 track-mouse)
4022
4023 (defun byte-compile-catch (form)
4024 (byte-compile-form (car (cdr form)))
4025 (byte-compile-push-constant
4026 (byte-compile-top-level (cons 'progn (cdr (cdr form))) for-effect))
4027 (byte-compile-out 'byte-catch 0))
4028
4029 (defun byte-compile-unwind-protect (form)
4030 (byte-compile-push-constant
4031 (byte-compile-top-level-body (cdr (cdr form)) t))
4032 (byte-compile-out 'byte-unwind-protect 0)
4033 (byte-compile-form-do-effect (car (cdr form)))
4034 (byte-compile-out 'byte-unbind 1))
4035
4036 (defun byte-compile-track-mouse (form)
4037 (byte-compile-form
4038 `(funcall '(lambda nil
4039 (track-mouse ,@(byte-compile-top-level-body (cdr form)))))))
4040
4041 (defun byte-compile-condition-case (form)
4042 (let* ((var (nth 1 form))
4043 (byte-compile-bound-variables
4044 (if var (cons var byte-compile-bound-variables)
4045 byte-compile-bound-variables)))
4046 (byte-compile-set-symbol-position 'condition-case)
4047 (unless (symbolp var)
4048 (byte-compile-warn
4049 "`%s' is not a variable-name or nil (in condition-case)" var))
4050 (byte-compile-push-constant var)
4051 (byte-compile-push-constant (byte-compile-top-level
4052 (nth 2 form) for-effect))
4053 (let ((clauses (cdr (cdr (cdr form))))
4054 compiled-clauses)
4055 (while clauses
4056 (let* ((clause (car clauses))
4057 (condition (car clause)))
4058 (cond ((not (or (symbolp condition)
4059 (and (listp condition)
4060 (let ((syms condition) (ok t))
4061 (while syms
4062 (if (not (symbolp (car syms)))
4063 (setq ok nil))
4064 (setq syms (cdr syms)))
4065 ok))))
4066 (byte-compile-warn
4067 "`%s' is not a condition name or list of such (in condition-case)"
4068 (prin1-to-string condition)))
4069 ;; ((not (or (eq condition 't)
4070 ;; (and (stringp (get condition 'error-message))
4071 ;; (consp (get condition 'error-conditions)))))
4072 ;; (byte-compile-warn
4073 ;; "`%s' is not a known condition name (in condition-case)"
4074 ;; condition))
4075 )
4076 (setq compiled-clauses
4077 (cons (cons condition
4078 (byte-compile-top-level-body
4079 (cdr clause) for-effect))
4080 compiled-clauses)))
4081 (setq clauses (cdr clauses)))
4082 (byte-compile-push-constant (nreverse compiled-clauses)))
4083 (byte-compile-out 'byte-condition-case 0)))
4084
4085
4086 (defun byte-compile-save-excursion (form)
4087 (if (and (eq 'set-buffer (car-safe (car-safe (cdr form))))
4088 (byte-compile-warning-enabled-p 'suspicious))
4089 (byte-compile-warn "`save-excursion' defeated by `set-buffer'"))
4090 (byte-compile-out 'byte-save-excursion 0)
4091 (byte-compile-body-do-effect (cdr form))
4092 (byte-compile-out 'byte-unbind 1))
4093
4094 (defun byte-compile-save-restriction (form)
4095 (byte-compile-out 'byte-save-restriction 0)
4096 (byte-compile-body-do-effect (cdr form))
4097 (byte-compile-out 'byte-unbind 1))
4098
4099 (defun byte-compile-save-current-buffer (form)
4100 (byte-compile-out 'byte-save-current-buffer 0)
4101 (byte-compile-body-do-effect (cdr form))
4102 (byte-compile-out 'byte-unbind 1))
4103
4104 (defun byte-compile-save-window-excursion (form)
4105 (byte-compile-push-constant
4106 (byte-compile-top-level-body (cdr form) for-effect))
4107 (byte-compile-out 'byte-save-window-excursion 0))
4108
4109 (defun byte-compile-with-output-to-temp-buffer (form)
4110 (byte-compile-form (car (cdr form)))
4111 (byte-compile-out 'byte-temp-output-buffer-setup 0)
4112 (byte-compile-body (cdr (cdr form)))
4113 (byte-compile-out 'byte-temp-output-buffer-show 0))
4114 \f
4115 ;;; top-level forms elsewhere
4116
4117 (byte-defop-compiler-1 defun)
4118 (byte-defop-compiler-1 defmacro)
4119 (byte-defop-compiler-1 defvar)
4120 (byte-defop-compiler-1 defconst byte-compile-defvar)
4121 (byte-defop-compiler-1 autoload)
4122 (byte-defop-compiler-1 lambda byte-compile-lambda-form)
4123
4124 (defun byte-compile-defun (form)
4125 ;; This is not used for file-level defuns with doc strings.
4126 (if (symbolp (car form))
4127 (byte-compile-set-symbol-position (car form))
4128 (byte-compile-set-symbol-position 'defun)
4129 (error "defun name must be a symbol, not %s" (car form)))
4130 (let ((for-effect nil))
4131 (byte-compile-push-constant 'defalias)
4132 (byte-compile-push-constant (nth 1 form))
4133 (byte-compile-closure (cdr (cdr form)) t))
4134 (byte-compile-out 'byte-call 2))
4135
4136 (defun byte-compile-defmacro (form)
4137 ;; This is not used for file-level defmacros with doc strings.
4138 ;; FIXME handle decls, use defalias?
4139 (let ((decls (byte-compile-defmacro-declaration form))
4140 (code (byte-compile-lambda (cdr (cdr form)) t))
4141 (for-effect nil))
4142 (byte-compile-push-constant (nth 1 form))
4143 (if (not (byte-compile-closure-code-p code))
4144 ;; simple lambda
4145 (byte-compile-push-constant (cons 'macro code))
4146 (byte-compile-push-constant 'macro)
4147 (byte-compile-make-closure code)
4148 (byte-compile-out 'byte-cons))
4149 (byte-compile-out 'byte-fset)
4150 (byte-compile-discard))
4151 (byte-compile-constant (nth 1 form)))
4152
4153 (defun byte-compile-defvar (form)
4154 ;; This is not used for file-level defvar/consts with doc strings.
4155 (let ((fun (nth 0 form))
4156 (var (nth 1 form))
4157 (value (nth 2 form))
4158 (string (nth 3 form)))
4159 (byte-compile-set-symbol-position fun)
4160 (when (or (> (length form) 4)
4161 (and (eq fun 'defconst) (null (cddr form))))
4162 (let ((ncall (length (cdr form))))
4163 (byte-compile-warn
4164 "`%s' called with %d argument%s, but %s %s"
4165 fun ncall
4166 (if (= 1 ncall) "" "s")
4167 (if (< ncall 2) "requires" "accepts only")
4168 "2-3")))
4169 (push var byte-compile-bound-variables)
4170 (if (eq fun 'defconst)
4171 (push var byte-compile-const-variables))
4172 (byte-compile-body-do-effect
4173 (list
4174 ;; Put the defined variable in this library's load-history entry
4175 ;; just as a real defvar would, but only in top-level forms.
4176 (when (and (cddr form) (null byte-compile-current-form))
4177 `(setq current-load-list (cons ',var current-load-list)))
4178 (when (> (length form) 3)
4179 (when (and string (not (stringp string)))
4180 (byte-compile-warn "third arg to `%s %s' is not a string: %s"
4181 fun var string))
4182 `(put ',var 'variable-documentation ,string))
4183 (if (cddr form) ; `value' provided
4184 (let ((byte-compile-not-obsolete-vars (list var)))
4185 (if (eq fun 'defconst)
4186 ;; `defconst' sets `var' unconditionally.
4187 (let ((tmp (make-symbol "defconst-tmp-var")))
4188 `(funcall '(lambda (,tmp) (defconst ,var ,tmp))
4189 ,value))
4190 ;; `defvar' sets `var' only when unbound.
4191 `(if (not (default-boundp ',var)) (setq-default ,var ,value))))
4192 (when (eq fun 'defconst)
4193 ;; This will signal an appropriate error at runtime.
4194 `(eval ',form)))
4195 `',var))))
4196
4197 (defun byte-compile-autoload (form)
4198 (byte-compile-set-symbol-position 'autoload)
4199 (and (byte-compile-constp (nth 1 form))
4200 (byte-compile-constp (nth 5 form))
4201 (eval (nth 5 form)) ; macro-p
4202 (not (fboundp (eval (nth 1 form))))
4203 (byte-compile-warn
4204 "The compiler ignores `autoload' except at top level. You should
4205 probably put the autoload of the macro `%s' at top-level."
4206 (eval (nth 1 form))))
4207 (byte-compile-normal-call form))
4208
4209 ;; Lambdas in valid places are handled as special cases by various code.
4210 ;; The ones that remain are errors.
4211 (defun byte-compile-lambda-form (form)
4212 (byte-compile-set-symbol-position 'lambda)
4213 (error "`lambda' used as function name is invalid"))
4214
4215 ;; Compile normally, but deal with warnings for the function being defined.
4216 (put 'defalias 'byte-hunk-handler 'byte-compile-file-form-defalias)
4217 (defun byte-compile-file-form-defalias (form)
4218 (if (and (consp (cdr form)) (consp (nth 1 form))
4219 (eq (car (nth 1 form)) 'quote)
4220 (consp (cdr (nth 1 form)))
4221 (symbolp (nth 1 (nth 1 form))))
4222 (let ((constant
4223 (and (consp (nthcdr 2 form))
4224 (consp (nth 2 form))
4225 (eq (car (nth 2 form)) 'quote)
4226 (consp (cdr (nth 2 form)))
4227 (symbolp (nth 1 (nth 2 form))))))
4228 (byte-compile-defalias-warn (nth 1 (nth 1 form)))
4229 (push (cons (nth 1 (nth 1 form))
4230 (if constant (nth 1 (nth 2 form)) t))
4231 byte-compile-function-environment)))
4232 ;; We used to just do: (byte-compile-normal-call form)
4233 ;; But it turns out that this fails to optimize the code.
4234 ;; So instead we now do the same as what other byte-hunk-handlers do,
4235 ;; which is to call back byte-compile-file-form and then return nil.
4236 ;; Except that we can't just call byte-compile-file-form since it would
4237 ;; call us right back.
4238 (byte-compile-keep-pending form)
4239 ;; Return nil so the form is not output twice.
4240 nil)
4241
4242 ;; Turn off warnings about prior calls to the function being defalias'd.
4243 ;; This could be smarter and compare those calls with
4244 ;; the function it is being aliased to.
4245 (defun byte-compile-defalias-warn (new)
4246 (let ((calls (assq new byte-compile-unresolved-functions)))
4247 (if calls
4248 (setq byte-compile-unresolved-functions
4249 (delq calls byte-compile-unresolved-functions)))))
4250
4251 (byte-defop-compiler-1 with-no-warnings byte-compile-no-warnings)
4252 (defun byte-compile-no-warnings (form)
4253 (let (byte-compile-warnings)
4254 (byte-compile-form (cons 'progn (cdr form)))))
4255
4256 ;; Warn about misuses of make-variable-buffer-local.
4257 (byte-defop-compiler-1 make-variable-buffer-local
4258 byte-compile-make-variable-buffer-local)
4259 (defun byte-compile-make-variable-buffer-local (form)
4260 (if (and (eq (car-safe (car-safe (cdr-safe form))) 'quote)
4261 (byte-compile-warning-enabled-p 'make-local))
4262 (byte-compile-warn
4263 "`make-variable-buffer-local' should be called at toplevel"))
4264 (byte-compile-normal-call form))
4265 (put 'make-variable-buffer-local
4266 'byte-hunk-handler 'byte-compile-form-make-variable-buffer-local)
4267 (defun byte-compile-form-make-variable-buffer-local (form)
4268 (byte-compile-keep-pending form 'byte-compile-normal-call))
4269
4270 \f
4271 ;;; tags
4272
4273 ;; Note: Most operations will strip off the 'TAG, but it speeds up
4274 ;; optimization to have the 'TAG as a part of the tag.
4275 ;; Tags will be (TAG . (tag-number . stack-depth)).
4276 (defun byte-compile-make-tag ()
4277 (list 'TAG (setq byte-compile-tag-number (1+ byte-compile-tag-number))))
4278
4279
4280 (defun byte-compile-out-tag (tag)
4281 (setq byte-compile-output (cons tag byte-compile-output))
4282 (if (cdr (cdr tag))
4283 (progn
4284 ;; ## remove this someday
4285 (and byte-compile-depth
4286 (not (= (cdr (cdr tag)) byte-compile-depth))
4287 (error "Compiler bug: depth conflict at tag %d" (car (cdr tag))))
4288 (setq byte-compile-depth (cdr (cdr tag))))
4289 (setcdr (cdr tag) byte-compile-depth)))
4290
4291 (defun byte-compile-goto (opcode tag)
4292 (push (cons opcode tag) byte-compile-output)
4293 (setcdr (cdr tag) (if (memq opcode byte-goto-always-pop-ops)
4294 (1- byte-compile-depth)
4295 byte-compile-depth))
4296 (setq byte-compile-depth (and (not (eq opcode 'byte-goto))
4297 (1- byte-compile-depth))))
4298
4299 (defun byte-compile-stack-adjustment (op operand)
4300 "Return the amount by which an operation adjusts the stack.
4301 OP and OPERAND are as passed to `byte-compile-out'."
4302 (if (memq op '(byte-call byte-discardN byte-discardN-preserve-tos))
4303 ;; For calls, OPERAND is the number of args, so we pop OPERAND + 1
4304 ;; elements, and the push the result, for a total of -OPERAND.
4305 ;; For discardN*, of course, we just pop OPERAND elements.
4306 (- operand)
4307 (or (aref byte-stack+-info (symbol-value op))
4308 ;; Ops with a nil entry in `byte-stack+-info' are byte-codes
4309 ;; that take OPERAND values off the stack and push a result, for
4310 ;; a total of 1 - OPERAND
4311 (- 1 operand))))
4312
4313 (defun byte-compile-out (op &optional operand)
4314 (push (cons op operand) byte-compile-output)
4315 (if (eq op 'byte-return)
4316 ;; This is actually an unnecessary case, because there should be no
4317 ;; more ops behind byte-return.
4318 (setq byte-compile-depth nil)
4319 (setq byte-compile-depth
4320 (+ byte-compile-depth (byte-compile-stack-adjustment op operand)))
4321 (setq byte-compile-maxdepth (max byte-compile-depth byte-compile-maxdepth))
4322 ;;(if (< byte-compile-depth 0) (error "Compiler error: stack underflow"))
4323 ))
4324
4325 (defun byte-compile-delay-out (&optional stack-used stack-adjust)
4326 "Add a placeholder to the output, which can be used to later add byte-codes.
4327 Return a position tag that can be passed to `byte-compile-delayed-out'
4328 to add the delayed byte-codes. STACK-USED is the maximum amount of
4329 stack-spaced used by the delayed byte-codes (defaulting to 0), and
4330 STACK-ADJUST is the amount by which the later-added code will adjust the
4331 stack (defaulting to 0); the byte-codes added later _must_ adjust the
4332 stack by this amount! If STACK-ADJUST is 0, then it's not necessary to
4333 actually add anything later; the effect as if nothing was added at all."
4334 ;; We just add a no-op to `byte-compile-output', and return a pointer to
4335 ;; the tail of the list; `byte-compile-delayed-out' uses list surgery
4336 ;; to add the byte-codes.
4337 (when stack-used
4338 (setq byte-compile-maxdepth
4339 (max byte-compile-depth (+ byte-compile-depth (or stack-used 0)))))
4340 (when stack-adjust
4341 (setq byte-compile-depth
4342 (+ byte-compile-depth stack-adjust)))
4343 (push (cons nil (or stack-adjust 0)) byte-compile-output))
4344
4345 (defun byte-compile-delayed-out (position op &optional operand)
4346 "Add at POSITION the byte-operation OP, with optional numeric arg OPERAND.
4347 POSITION should a position returned by `byte-compile-delay-out'.
4348 Return a new position, which can be used to add further operations."
4349 (unless (null (caar position))
4350 (error "Bad POSITION arg to `byte-compile-delayed-out'"))
4351 ;; This is kind of like `byte-compile-out', but we splice into the list
4352 ;; where POSITION is. We don't bother updating `byte-compile-maxdepth'
4353 ;; because that was already done by `byte-compile-delay-out', but we do
4354 ;; update the relative operand stored in the no-op marker currently at
4355 ;; POSITION; since we insert before that marker, this means that if the
4356 ;; caller doesn't insert a sequence of byte-codes that matches the expected
4357 ;; operand passed to `byte-compile-delay-out', then the nop will still have
4358 ;; a non-zero operand when `byte-compile-lapcode' is called, which will
4359 ;; cause an error to be signaled.
4360
4361 ;; Adjust the cumulative stack-adjustment stored in the cdr of the no-op
4362 (setcdr (car position)
4363 (- (cdar position) (byte-compile-stack-adjustment op operand)))
4364 ;; Add the new operation onto the list tail at POSITION
4365 (setcdr position (cons (cons op operand) (cdr position)))
4366 position)
4367
4368 \f
4369 ;;; call tree stuff
4370
4371 (defun byte-compile-annotate-call-tree (form)
4372 (let (entry)
4373 ;; annotate the current call
4374 (if (setq entry (assq (car form) byte-compile-call-tree))
4375 (or (memq byte-compile-current-form (nth 1 entry)) ;callers
4376 (setcar (cdr entry)
4377 (cons byte-compile-current-form (nth 1 entry))))
4378 (setq byte-compile-call-tree
4379 (cons (list (car form) (list byte-compile-current-form) nil)
4380 byte-compile-call-tree)))
4381 ;; annotate the current function
4382 (if (setq entry (assq byte-compile-current-form byte-compile-call-tree))
4383 (or (memq (car form) (nth 2 entry)) ;called
4384 (setcar (cdr (cdr entry))
4385 (cons (car form) (nth 2 entry))))
4386 (setq byte-compile-call-tree
4387 (cons (list byte-compile-current-form nil (list (car form)))
4388 byte-compile-call-tree)))
4389 ))
4390
4391 ;; Renamed from byte-compile-report-call-tree
4392 ;; to avoid interfering with completion of byte-compile-file.
4393 ;;;###autoload
4394 (defun display-call-tree (&optional filename)
4395 "Display a call graph of a specified file.
4396 This lists which functions have been called, what functions called
4397 them, and what functions they call. The list includes all functions
4398 whose definitions have been compiled in this Emacs session, as well as
4399 all functions called by those functions.
4400
4401 The call graph does not include macros, inline functions, or
4402 primitives that the byte-code interpreter knows about directly \(eq,
4403 cons, etc.\).
4404
4405 The call tree also lists those functions which are not known to be called
4406 \(that is, to which no calls have been compiled\), and which cannot be
4407 invoked interactively."
4408 (interactive)
4409 (message "Generating call tree...")
4410 (with-output-to-temp-buffer "*Call-Tree*"
4411 (set-buffer "*Call-Tree*")
4412 (erase-buffer)
4413 (message "Generating call tree... (sorting on %s)"
4414 byte-compile-call-tree-sort)
4415 (insert "Call tree for "
4416 (cond ((null byte-compile-current-file) (or filename "???"))
4417 ((stringp byte-compile-current-file)
4418 byte-compile-current-file)
4419 (t (buffer-name byte-compile-current-file)))
4420 " sorted on "
4421 (prin1-to-string byte-compile-call-tree-sort)
4422 ":\n\n")
4423 (if byte-compile-call-tree-sort
4424 (setq byte-compile-call-tree
4425 (sort byte-compile-call-tree
4426 (cond ((eq byte-compile-call-tree-sort 'callers)
4427 (function (lambda (x y) (< (length (nth 1 x))
4428 (length (nth 1 y))))))
4429 ((eq byte-compile-call-tree-sort 'calls)
4430 (function (lambda (x y) (< (length (nth 2 x))
4431 (length (nth 2 y))))))
4432 ((eq byte-compile-call-tree-sort 'calls+callers)
4433 (function (lambda (x y) (< (+ (length (nth 1 x))
4434 (length (nth 2 x)))
4435 (+ (length (nth 1 y))
4436 (length (nth 2 y)))))))
4437 ((eq byte-compile-call-tree-sort 'name)
4438 (function (lambda (x y) (string< (car x)
4439 (car y)))))
4440 (t (error "`byte-compile-call-tree-sort': `%s' - unknown sort mode"
4441 byte-compile-call-tree-sort))))))
4442 (message "Generating call tree...")
4443 (let ((rest byte-compile-call-tree)
4444 (b (current-buffer))
4445 f p
4446 callers calls)
4447 (while rest
4448 (prin1 (car (car rest)) b)
4449 (setq callers (nth 1 (car rest))
4450 calls (nth 2 (car rest)))
4451 (insert "\t"
4452 (cond ((not (fboundp (setq f (car (car rest)))))
4453 (if (null f)
4454 " <top level>";; shouldn't insert nil then, actually -sk
4455 " <not defined>"))
4456 ((subrp (setq f (symbol-function f)))
4457 " <subr>")
4458 ((symbolp f)
4459 (format " ==> %s" f))
4460 ((byte-code-function-p f)
4461 "<compiled function>")
4462 ((not (consp f))
4463 "<malformed function>")
4464 ((eq 'macro (car f))
4465 (if (or (byte-code-function-p (cdr f))
4466 (assq 'byte-code (cdr (cdr (cdr f)))))
4467 " <compiled macro>"
4468 " <macro>"))
4469 ((assq 'byte-code (cdr (cdr f)))
4470 "<compiled lambda>")
4471 ((eq 'lambda (car f))
4472 "<function>")
4473 (t "???"))
4474 (format " (%d callers + %d calls = %d)"
4475 ;; Does the optimizer eliminate common subexpressions?-sk
4476 (length callers)
4477 (length calls)
4478 (+ (length callers) (length calls)))
4479 "\n")
4480 (if callers
4481 (progn
4482 (insert " called by:\n")
4483 (setq p (point))
4484 (insert " " (if (car callers)
4485 (mapconcat 'symbol-name callers ", ")
4486 "<top level>"))
4487 (let ((fill-prefix " "))
4488 (fill-region-as-paragraph p (point)))
4489 (unless (= 0 (current-column))
4490 (insert "\n"))))
4491 (if calls
4492 (progn
4493 (insert " calls:\n")
4494 (setq p (point))
4495 (insert " " (mapconcat 'symbol-name calls ", "))
4496 (let ((fill-prefix " "))
4497 (fill-region-as-paragraph p (point)))
4498 (unless (= 0 (current-column))
4499 (insert "\n"))))
4500 (setq rest (cdr rest)))
4501
4502 (message "Generating call tree...(finding uncalled functions...)")
4503 (setq rest byte-compile-call-tree)
4504 (let (uncalled def)
4505 (while rest
4506 (or (nth 1 (car rest))
4507 (null (setq f (caar rest)))
4508 (progn
4509 (setq def (byte-compile-fdefinition f t))
4510 (and (eq (car-safe def) 'macro)
4511 (eq (car-safe (cdr-safe def)) 'lambda)
4512 (setq def (cdr def)))
4513 (functionp def))
4514 (progn
4515 (setq def (byte-compile-fdefinition f nil))
4516 (and (eq (car-safe def) 'macro)
4517 (eq (car-safe (cdr-safe def)) 'lambda)
4518 (setq def (cdr def)))
4519 (commandp def))
4520 (setq uncalled (cons f uncalled)))
4521 (setq rest (cdr rest)))
4522 (if uncalled
4523 (let ((fill-prefix " "))
4524 (insert "Noninteractive functions not known to be called:\n ")
4525 (setq p (point))
4526 (insert (mapconcat 'symbol-name (nreverse uncalled) ", "))
4527 (fill-region-as-paragraph p (point))))))
4528 (message "Generating call tree...done.")))
4529
4530 \f
4531 ;;;###autoload
4532 (defun batch-byte-compile-if-not-done ()
4533 "Like `byte-compile-file' but doesn't recompile if already up to date.
4534 Use this from the command line, with `-batch';
4535 it won't work in an interactive Emacs."
4536 (batch-byte-compile t))
4537
4538 ;;; by crl@newton.purdue.edu
4539 ;;; Only works noninteractively.
4540 ;;;###autoload
4541 (defun batch-byte-compile (&optional noforce)
4542 "Run `byte-compile-file' on the files remaining on the command line.
4543 Use this from the command line, with `-batch';
4544 it won't work in an interactive Emacs.
4545 Each file is processed even if an error occurred previously.
4546 For example, invoke \"emacs -batch -f batch-byte-compile $emacs/ ~/*.el\".
4547 If NOFORCE is non-nil, don't recompile a file that seems to be
4548 already up-to-date."
4549 ;; command-line-args-left is what is left of the command line (from startup.el)
4550 (defvar command-line-args-left) ;Avoid 'free variable' warning
4551 (if (not noninteractive)
4552 (error "`batch-byte-compile' is to be used only with -batch"))
4553 (let ((bytecomp-error nil))
4554 (while command-line-args-left
4555 (if (file-directory-p (expand-file-name (car command-line-args-left)))
4556 ;; Directory as argument.
4557 (let ((bytecomp-files (directory-files (car command-line-args-left)))
4558 bytecomp-source bytecomp-dest)
4559 (dolist (bytecomp-file bytecomp-files)
4560 (if (and (string-match emacs-lisp-file-regexp bytecomp-file)
4561 (not (auto-save-file-name-p bytecomp-file))
4562 (setq bytecomp-source
4563 (expand-file-name bytecomp-file
4564 (car command-line-args-left)))
4565 (setq bytecomp-dest (byte-compile-dest-file
4566 bytecomp-source))
4567 (file-exists-p bytecomp-dest)
4568 (file-newer-than-file-p bytecomp-source bytecomp-dest))
4569 (if (null (batch-byte-compile-file bytecomp-source))
4570 (setq bytecomp-error t)))))
4571 ;; Specific file argument
4572 (if (or (not noforce)
4573 (let* ((bytecomp-source (car command-line-args-left))
4574 (bytecomp-dest (byte-compile-dest-file bytecomp-source)))
4575 (or (not (file-exists-p bytecomp-dest))
4576 (file-newer-than-file-p bytecomp-source bytecomp-dest))))
4577 (if (null (batch-byte-compile-file (car command-line-args-left)))
4578 (setq bytecomp-error t))))
4579 (setq command-line-args-left (cdr command-line-args-left)))
4580 (kill-emacs (if bytecomp-error 1 0))))
4581
4582 (defun batch-byte-compile-file (bytecomp-file)
4583 (if debug-on-error
4584 (byte-compile-file bytecomp-file)
4585 (condition-case err
4586 (byte-compile-file bytecomp-file)
4587 (file-error
4588 (message (if (cdr err)
4589 ">>Error occurred processing %s: %s (%s)"
4590 ">>Error occurred processing %s: %s")
4591 bytecomp-file
4592 (get (car err) 'error-message)
4593 (prin1-to-string (cdr err)))
4594 (let ((bytecomp-destfile (byte-compile-dest-file bytecomp-file)))
4595 (if (file-exists-p bytecomp-destfile)
4596 (delete-file bytecomp-destfile)))
4597 nil)
4598 (error
4599 (message (if (cdr err)
4600 ">>Error occurred processing %s: %s (%s)"
4601 ">>Error occurred processing %s: %s")
4602 bytecomp-file
4603 (get (car err) 'error-message)
4604 (prin1-to-string (cdr err)))
4605 nil))))
4606
4607 (defun byte-compile-refresh-preloaded ()
4608 "Reload any Lisp file that was changed since Emacs was dumped.
4609 Use with caution."
4610 (let* ((argv0 (car command-line-args))
4611 (emacs-file (executable-find argv0)))
4612 (if (not (and emacs-file (file-executable-p emacs-file)))
4613 (message "Can't find %s to refresh preloaded Lisp files" argv0)
4614 (dolist (f (reverse load-history))
4615 (setq f (car f))
4616 (if (string-match "elc\\'" f) (setq f (substring f 0 -1)))
4617 (when (and (file-readable-p f)
4618 (file-newer-than-file-p f emacs-file))
4619 (message "Reloading stale %s" (file-name-nondirectory f))
4620 (condition-case nil
4621 (load f 'noerror nil 'nosuffix)
4622 ;; Probably shouldn't happen, but in case of an error, it seems
4623 ;; at least as useful to ignore it as it is to stop compilation.
4624 (error nil)))))))
4625
4626 ;;;###autoload
4627 (defun batch-byte-recompile-directory (&optional arg)
4628 "Run `byte-recompile-directory' on the dirs remaining on the command line.
4629 Must be used only with `-batch', and kills Emacs on completion.
4630 For example, invoke `emacs -batch -f batch-byte-recompile-directory .'.
4631
4632 Optional argument ARG is passed as second argument ARG to
4633 `byte-recompile-directory'; see there for its possible values
4634 and corresponding effects."
4635 ;; command-line-args-left is what is left of the command line (startup.el)
4636 (defvar command-line-args-left) ;Avoid 'free variable' warning
4637 (if (not noninteractive)
4638 (error "batch-byte-recompile-directory is to be used only with -batch"))
4639 (or command-line-args-left
4640 (setq command-line-args-left '(".")))
4641 (while command-line-args-left
4642 (byte-recompile-directory (car command-line-args-left) arg)
4643 (setq command-line-args-left (cdr command-line-args-left)))
4644 (kill-emacs 0))
4645
4646 (provide 'byte-compile)
4647 (provide 'bytecomp)
4648
4649 \f
4650 ;;; report metering (see the hacks in bytecode.c)
4651
4652 (defvar byte-code-meter)
4653 (defun byte-compile-report-ops ()
4654 (with-output-to-temp-buffer "*Meter*"
4655 (set-buffer "*Meter*")
4656 (let ((i 0) n op off)
4657 (while (< i 256)
4658 (setq n (aref (aref byte-code-meter 0) i)
4659 off nil)
4660 (if t ;(not (zerop n))
4661 (progn
4662 (setq op i)
4663 (setq off nil)
4664 (cond ((< op byte-nth)
4665 (setq off (logand op 7))
4666 (setq op (logand op 248)))
4667 ((>= op byte-constant)
4668 (setq off (- op byte-constant)
4669 op byte-constant)))
4670 (setq op (aref byte-code-vector op))
4671 (insert (format "%-4d" i))
4672 (insert (symbol-name op))
4673 (if off (insert " [" (int-to-string off) "]"))
4674 (indent-to 40)
4675 (insert (int-to-string n) "\n")))
4676 (setq i (1+ i))))))
4677 \f
4678 ;; To avoid "lisp nesting exceeds max-lisp-eval-depth" when bytecomp compiles
4679 ;; itself, compile some of its most used recursive functions (at load time).
4680 ;;
4681 (eval-when-compile
4682 (or (byte-code-function-p (symbol-function 'byte-compile-form))
4683 (assq 'byte-code (symbol-function 'byte-compile-form))
4684 (let ((byte-optimize nil) ; do it fast
4685 (byte-compile-warnings nil))
4686 (mapc (lambda (x)
4687 (or noninteractive (message "compiling %s..." x))
4688 (byte-compile x)
4689 (or noninteractive (message "compiling %s...done" x)))
4690 '(byte-compile-normal-call
4691 byte-compile-form
4692 byte-compile-body
4693 ;; Inserted some more than necessary, to speed it up.
4694 byte-compile-top-level
4695 byte-compile-out-toplevel
4696 byte-compile-constant
4697 byte-compile-variable-ref))))
4698 nil)
4699
4700 (run-hooks 'bytecomp-load-hook)
4701
4702 ;; arch-tag: 9c97b0f0-8745-4571-bfc3-8dceb677292a
4703 ;;; bytecomp.el ends here