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