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