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