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