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