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