Quote a few backticks in docstrings.
[emacs.git] / lisp / emacs-lisp / bytecomp.el
blobd1119e1090390c771238d143a7df33603a003cfe
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 (if (file-name-absolute-p target-file)
1942 (make-temp-file target-file)
1943 ;; If target-file is relative and includes
1944 ;; leading directories, make-temp-file will
1945 ;; assume those leading directories exist
1946 ;; under temporary-file-directory, which might
1947 ;; not be true. So strip leading directories
1948 ;; from relative file names before calling
1949 ;; make-temp-file.
1950 (make-temp-file
1951 (file-name-nondirectory target-file))))
1952 (default-modes (default-file-modes))
1953 (temp-modes (logand default-modes #o600))
1954 (desired-modes (logand default-modes #o666))
1955 (kill-emacs-hook
1956 (cons (lambda () (ignore-errors
1957 (delete-file tempfile)))
1958 kill-emacs-hook)))
1959 (unless (= temp-modes desired-modes)
1960 (set-file-modes tempfile desired-modes))
1961 (write-region (point-min) (point-max) tempfile nil 1)
1962 ;; This has the intentional side effect that any
1963 ;; hard-links to target-file continue to
1964 ;; point to the old file (this makes it possible
1965 ;; for installed files to share disk space with
1966 ;; the build tree, without causing problems when
1967 ;; emacs-lisp files in the build tree are
1968 ;; recompiled). Previously this was accomplished by
1969 ;; deleting target-file before writing it.
1970 (rename-file tempfile target-file t))
1971 (or noninteractive (message "Wrote %s" target-file)))
1972 ;; This is just to give a better error message than write-region
1973 (let ((exists (file-exists-p target-file)))
1974 (signal (if exists 'file-error 'file-missing)
1975 (list "Opening output file"
1976 (if exists
1977 "Cannot overwrite file"
1978 "Directory not writable or nonexistent")
1979 target-file))))
1980 (kill-buffer (current-buffer)))
1981 (if (and byte-compile-generate-call-tree
1982 (or (eq t byte-compile-generate-call-tree)
1983 (y-or-n-p (format "Report call tree for %s? "
1984 filename))))
1985 (save-excursion
1986 (display-call-tree filename)))
1987 (if load
1988 (load target-file))
1989 t))))
1991 ;;; compiling a single function
1992 ;;;###autoload
1993 (defun compile-defun (&optional arg)
1994 "Compile and evaluate the current top-level form.
1995 Print the result in the echo area.
1996 With argument ARG, insert value in current buffer after the form."
1997 (interactive "P")
1998 (save-excursion
1999 (end-of-defun)
2000 (beginning-of-defun)
2001 (let* ((byte-compile-current-file nil)
2002 (byte-compile-current-buffer (current-buffer))
2003 (byte-compile-read-position (point))
2004 (byte-compile-last-position byte-compile-read-position)
2005 (byte-compile-last-warned-form 'nothing)
2006 (value (eval
2007 (let ((read-with-symbol-positions (current-buffer))
2008 (read-symbol-positions-list nil))
2009 (displaying-byte-compile-warnings
2010 (byte-compile-sexp
2011 (eval-sexp-add-defvars
2012 (read (current-buffer))
2013 byte-compile-read-position))))
2014 lexical-binding)))
2015 (cond (arg
2016 (message "Compiling from buffer... done.")
2017 (prin1 value (current-buffer))
2018 (insert "\n"))
2019 ((message "%s" (prin1-to-string value)))))))
2021 (defun byte-compile-from-buffer (inbuffer)
2022 (let ((byte-compile-current-buffer inbuffer)
2023 (byte-compile-read-position nil)
2024 (byte-compile-last-position nil)
2025 ;; Prevent truncation of flonums and lists as we read and print them
2026 (float-output-format nil)
2027 (case-fold-search nil)
2028 (print-length nil)
2029 (print-level nil)
2030 ;; Prevent edebug from interfering when we compile
2031 ;; and put the output into a file.
2032 ;; (edebug-all-defs nil)
2033 ;; (edebug-all-forms nil)
2034 ;; Simulate entry to byte-compile-top-level
2035 (byte-compile-jump-tables nil)
2036 (byte-compile-constants nil)
2037 (byte-compile-variables nil)
2038 (byte-compile-tag-number 0)
2039 (byte-compile-depth 0)
2040 (byte-compile-maxdepth 0)
2041 (byte-compile-output nil)
2042 ;; This allows us to get the positions of symbols read; it's
2043 ;; new in Emacs 22.1.
2044 (read-with-symbol-positions inbuffer)
2045 (read-symbol-positions-list nil)
2046 ;; #### This is bound in b-c-close-variables.
2047 ;; (byte-compile-warnings byte-compile-warnings)
2049 (byte-compile-close-variables
2050 (with-current-buffer
2051 (setq byte-compile--outbuffer
2052 (get-buffer-create
2053 (concat " *Compiler Output*"
2054 (if (<= byte-compile-level 1) ""
2055 (format "-%s" (1- byte-compile-level))))))
2056 (set-buffer-multibyte t)
2057 (erase-buffer)
2058 ;; (emacs-lisp-mode)
2059 (setq case-fold-search nil))
2060 (displaying-byte-compile-warnings
2061 (with-current-buffer inbuffer
2062 (and byte-compile-current-file
2063 (byte-compile-insert-header byte-compile-current-file
2064 byte-compile--outbuffer))
2065 (goto-char (point-min))
2066 ;; Should we always do this? When calling multiple files, it
2067 ;; would be useful to delay this warning until all have been
2068 ;; compiled. A: Yes! b-c-u-f might contain dross from a
2069 ;; previous byte-compile.
2070 (setq byte-compile-unresolved-functions nil)
2071 (setq byte-compile-noruntime-functions nil)
2072 (setq byte-compile-new-defuns nil)
2074 ;; Compile the forms from the input buffer.
2075 (while (progn
2076 (while (progn (skip-chars-forward " \t\n\^l")
2077 (= (following-char) ?\;))
2078 (forward-line 1))
2079 (not (eobp)))
2080 (setq byte-compile-read-position (point)
2081 byte-compile-last-position byte-compile-read-position)
2082 (let* ((lread--old-style-backquotes nil)
2083 (lread--unescaped-character-literals nil)
2084 (form (read inbuffer)))
2085 ;; Warn about the use of old-style backquotes.
2086 (when lread--old-style-backquotes
2087 (byte-compile-warn "!! The file uses old-style backquotes !!
2088 This functionality has been obsolete for more than 10 years already
2089 and will be removed soon. See (elisp)Backquote in the manual."))
2090 (when lread--unescaped-character-literals
2091 (byte-compile-warn
2092 "unescaped character literals %s detected!"
2093 (mapconcat (lambda (char) (format "`?%c'" char))
2094 (sort lread--unescaped-character-literals #'<)
2095 ", ")))
2096 (byte-compile-toplevel-file-form form)))
2097 ;; Compile pending forms at end of file.
2098 (byte-compile-flush-pending)
2099 ;; Make warnings about unresolved functions
2100 ;; give the end of the file as their position.
2101 (setq byte-compile-last-position (point-max))
2102 (byte-compile-warn-about-unresolved-functions))
2103 ;; Fix up the header at the front of the output
2104 ;; if the buffer contains multibyte characters.
2105 (and byte-compile-current-file
2106 (with-current-buffer byte-compile--outbuffer
2107 (byte-compile-fix-header byte-compile-current-file))))
2108 byte-compile--outbuffer)))
2110 (defun byte-compile-fix-header (_filename)
2111 "If the current buffer has any multibyte characters, insert a version test."
2112 (when (< (point-max) (position-bytes (point-max)))
2113 (goto-char (point-min))
2114 ;; Find the comment that describes the version condition.
2115 (search-forward "\n;;; This file uses")
2116 (narrow-to-region (line-beginning-position) (point-max))
2117 ;; Find the first line of ballast semicolons.
2118 (search-forward ";;;;;;;;;;")
2119 (beginning-of-line)
2120 (narrow-to-region (point-min) (point))
2121 (let ((old-header-end (point))
2122 (minimum-version "23")
2123 delta)
2124 (delete-region (point-min) (point-max))
2125 (insert
2126 ";;; This file contains utf-8 non-ASCII characters,\n"
2127 ";;; and so cannot be loaded into Emacs 22 or earlier.\n"
2128 ;; Have to check if emacs-version is bound so that this works
2129 ;; in files loaded early in loadup.el.
2130 "(and (boundp 'emacs-version)\n"
2131 ;; If there is a name at the end of emacs-version,
2132 ;; don't try to check the version number.
2133 " (< (aref emacs-version (1- (length emacs-version))) ?A)\n"
2134 (format " (string-lessp emacs-version \"%s\")\n" minimum-version)
2135 ;; Because the header must fit in a fixed width, we cannot
2136 ;; insert arbitrary-length file names (Bug#11585).
2137 " (error \"`%s' was compiled for "
2138 (format "Emacs %s or later\" #$))\n\n" minimum-version))
2139 ;; Now compensate for any change in size, to make sure all
2140 ;; positions in the file remain valid.
2141 (setq delta (- (point-max) old-header-end))
2142 (goto-char (point-max))
2143 (widen)
2144 (delete-char delta))))
2146 (defun byte-compile-insert-header (_filename outbuffer)
2147 "Insert a header at the start of OUTBUFFER.
2148 Call from the source buffer."
2149 (let ((dynamic-docstrings byte-compile-dynamic-docstrings)
2150 (dynamic byte-compile-dynamic)
2151 (optimize byte-optimize))
2152 (with-current-buffer outbuffer
2153 (goto-char (point-min))
2154 ;; The magic number of .elc files is ";ELC", or 0x3B454C43. After
2155 ;; that is the file-format version number (18, 19, 20, or 23) as a
2156 ;; byte, followed by some nulls. The primary motivation for doing
2157 ;; this is to get some binary characters up in the first line of
2158 ;; the file so that `diff' will simply say "Binary files differ"
2159 ;; instead of actually doing a diff of two .elc files. An extra
2160 ;; benefit is that you can add this to /etc/magic:
2161 ;; 0 string ;ELC GNU Emacs Lisp compiled file,
2162 ;; >4 byte x version %d
2163 (insert
2164 ";ELC" 23 "\000\000\000\n"
2165 ";;; Compiled\n"
2166 ";;; in Emacs version " emacs-version "\n"
2167 ";;; with"
2168 (cond
2169 ((eq optimize 'source) " source-level optimization only")
2170 ((eq optimize 'byte) " byte-level optimization only")
2171 (optimize " all optimizations")
2172 (t "out optimization"))
2173 ".\n"
2174 (if dynamic ";;; Function definitions are lazy-loaded.\n"
2176 "\n;;; This file uses "
2177 (if dynamic-docstrings
2178 "dynamic docstrings, first added in Emacs 19.29"
2179 "opcodes that do not exist in Emacs 18")
2180 ".\n\n"
2181 ;; Note that byte-compile-fix-header may change this.
2182 ";;; This file does not contain utf-8 non-ASCII characters,\n"
2183 ";;; and so can be loaded in Emacs versions earlier than 23.\n\n"
2184 ;; Insert semicolons as ballast, so that byte-compile-fix-header
2185 ;; can delete them so as to keep the buffer positions
2186 ;; constant for the actual compiled code.
2187 ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
2188 ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n"))))
2190 (defun byte-compile-output-file-form (form)
2191 ;; Write the given form to the output buffer, being careful of docstrings
2192 ;; in defvar, defvaralias, defconst, autoload and
2193 ;; custom-declare-variable because make-docfile is so amazingly stupid.
2194 ;; defalias calls are output directly by byte-compile-file-form-defmumble;
2195 ;; it does not pay to first build the defalias in defmumble and then parse
2196 ;; it here.
2197 (let ((print-escape-newlines t)
2198 (print-length nil)
2199 (print-level nil)
2200 (print-quoted t)
2201 (print-gensym t)
2202 (print-circle ; Handle circular data structures.
2203 (not byte-compile-disable-print-circle)))
2204 (if (and (memq (car-safe form) '(defvar defvaralias defconst
2205 autoload custom-declare-variable))
2206 (stringp (nth 3 form)))
2207 (byte-compile-output-docform nil nil '("\n(" 3 ")") form nil
2208 (memq (car form)
2209 '(defvaralias autoload
2210 custom-declare-variable)))
2211 (princ "\n" byte-compile--outbuffer)
2212 (prin1 form byte-compile--outbuffer)
2213 nil)))
2215 (defvar byte-compile--for-effect)
2217 (defun byte-compile-output-docform (preface name info form specindex quoted)
2218 "Print a form with a doc string. INFO is (prefix doc-index postfix).
2219 If PREFACE and NAME are non-nil, print them too,
2220 before INFO and the FORM but after the doc string itself.
2221 If SPECINDEX is non-nil, it is the index in FORM
2222 of the function bytecode string. In that case,
2223 we output that argument and the following argument
2224 \(the constants vector) together, for lazy loading.
2225 QUOTED says that we have to put a quote before the
2226 list that represents a doc string reference.
2227 `defvaralias', `autoload' and `custom-declare-variable' need that."
2228 ;; We need to examine byte-compile-dynamic-docstrings
2229 ;; in the input buffer (now current), not in the output buffer.
2230 (let ((dynamic-docstrings byte-compile-dynamic-docstrings))
2231 (with-current-buffer byte-compile--outbuffer
2232 (let (position)
2234 ;; Insert the doc string, and make it a comment with #@LENGTH.
2235 (and (>= (nth 1 info) 0)
2236 dynamic-docstrings
2237 (progn
2238 ;; Make the doc string start at beginning of line
2239 ;; for make-docfile's sake.
2240 (insert "\n")
2241 (setq position
2242 (byte-compile-output-as-comment
2243 (nth (nth 1 info) form) nil))
2244 ;; If the doc string starts with * (a user variable),
2245 ;; negate POSITION.
2246 (if (and (stringp (nth (nth 1 info) form))
2247 (> (length (nth (nth 1 info) form)) 0)
2248 (eq (aref (nth (nth 1 info) form) 0) ?*))
2249 (setq position (- position)))))
2251 (let ((print-continuous-numbering t)
2252 print-number-table
2253 (index 0)
2254 ;; FIXME: The bindings below are only needed for when we're
2255 ;; called from ...-defmumble.
2256 (print-escape-newlines t)
2257 (print-length nil)
2258 (print-level nil)
2259 (print-quoted t)
2260 (print-gensym t)
2261 (print-circle ; Handle circular data structures.
2262 (not byte-compile-disable-print-circle)))
2263 (if preface
2264 (progn
2265 ;; FIXME: We don't handle uninterned names correctly.
2266 ;; E.g. if cl-define-compiler-macro uses uninterned name we get:
2267 ;; (defalias '#1=#:foo--cmacro #[514 ...])
2268 ;; (put 'foo 'compiler-macro '#:foo--cmacro)
2269 (insert preface)
2270 (prin1 name byte-compile--outbuffer)))
2271 (insert (car info))
2272 (prin1 (car form) byte-compile--outbuffer)
2273 (while (setq form (cdr form))
2274 (setq index (1+ index))
2275 (insert " ")
2276 (cond ((and (numberp specindex) (= index specindex)
2277 ;; Don't handle the definition dynamically
2278 ;; if it refers (or might refer)
2279 ;; to objects already output
2280 ;; (for instance, gensyms in the arg list).
2281 (let (non-nil)
2282 (when (hash-table-p print-number-table)
2283 (maphash (lambda (_k v) (if v (setq non-nil t)))
2284 print-number-table))
2285 (not non-nil)))
2286 ;; Output the byte code and constants specially
2287 ;; for lazy dynamic loading.
2288 (let ((position
2289 (byte-compile-output-as-comment
2290 (cons (car form) (nth 1 form))
2291 t)))
2292 (princ (format "(#$ . %d) nil" position)
2293 byte-compile--outbuffer)
2294 (setq form (cdr form))
2295 (setq index (1+ index))))
2296 ((= index (nth 1 info))
2297 (if position
2298 (princ (format (if quoted "'(#$ . %d)" "(#$ . %d)")
2299 position)
2300 byte-compile--outbuffer)
2301 (let ((print-escape-newlines nil))
2302 (goto-char (prog1 (1+ (point))
2303 (prin1 (car form)
2304 byte-compile--outbuffer)))
2305 (insert "\\\n")
2306 (goto-char (point-max)))))
2308 (prin1 (car form) byte-compile--outbuffer)))))
2309 (insert (nth 2 info)))))
2310 nil)
2312 (defun byte-compile-keep-pending (form &optional handler)
2313 (if (memq byte-optimize '(t source))
2314 (setq form (byte-optimize-form form t)))
2315 (if handler
2316 (let ((byte-compile--for-effect t))
2317 ;; To avoid consing up monstrously large forms at load time, we split
2318 ;; the output regularly.
2319 (and (memq (car-safe form) '(fset defalias))
2320 (nthcdr 300 byte-compile-output)
2321 (byte-compile-flush-pending))
2322 (funcall handler form)
2323 (if byte-compile--for-effect
2324 (byte-compile-discard)))
2325 (byte-compile-form form t))
2326 nil)
2328 (defun byte-compile-flush-pending ()
2329 (if byte-compile-output
2330 (let ((form (byte-compile-out-toplevel t 'file)))
2331 (cond ((eq (car-safe form) 'progn)
2332 (mapc 'byte-compile-output-file-form (cdr form)))
2333 (form
2334 (byte-compile-output-file-form form)))
2335 (setq byte-compile-constants nil
2336 byte-compile-variables nil
2337 byte-compile-depth 0
2338 byte-compile-maxdepth 0
2339 byte-compile-output nil
2340 byte-compile-jump-tables nil))))
2342 (defvar byte-compile-force-lexical-warnings nil)
2344 (defun byte-compile-preprocess (form &optional _for-effect)
2345 (setq form (macroexpand-all form byte-compile-macro-environment))
2346 ;; FIXME: We should run byte-optimize-form here, but it currently does not
2347 ;; recurse through all the code, so we'd have to fix this first.
2348 ;; Maybe a good fix would be to merge byte-optimize-form into
2349 ;; macroexpand-all.
2350 ;; (if (memq byte-optimize '(t source))
2351 ;; (setq form (byte-optimize-form form for-effect)))
2352 (cond
2353 (lexical-binding (cconv-closure-convert form))
2354 (byte-compile-force-lexical-warnings (cconv-warnings-only form))
2355 (t form)))
2357 ;; byte-hunk-handlers cannot call this!
2358 (defun byte-compile-toplevel-file-form (top-level-form)
2359 (byte-compile-recurse-toplevel
2360 top-level-form
2361 (lambda (form)
2362 (let ((byte-compile-current-form nil)) ; close over this for warnings.
2363 (byte-compile-file-form (byte-compile-preprocess form t))))))
2365 ;; byte-hunk-handlers can call this.
2366 (defun byte-compile-file-form (form)
2367 (let (handler)
2368 (cond ((and (consp form)
2369 (symbolp (car form))
2370 (setq handler (get (car form) 'byte-hunk-handler)))
2371 (cond ((setq form (funcall handler form))
2372 (byte-compile-flush-pending)
2373 (byte-compile-output-file-form form))))
2375 (byte-compile-keep-pending form)))))
2377 ;; Functions and variables with doc strings must be output separately,
2378 ;; so make-docfile can recognize them. Most other things can be output
2379 ;; as byte-code.
2381 (put 'autoload 'byte-hunk-handler 'byte-compile-file-form-autoload)
2382 (defun byte-compile-file-form-autoload (form)
2383 (and (let ((form form))
2384 (while (if (setq form (cdr form)) (macroexp-const-p (car form))))
2385 (null form)) ;Constants only
2386 (memq (eval (nth 5 form)) '(t macro)) ;Macro
2387 (eval form)) ;Define the autoload.
2388 ;; Avoid undefined function warnings for the autoload.
2389 (pcase (nth 1 form)
2390 (`',(and (pred symbolp) funsym)
2391 ;; Don't add it if it's already defined. Otherwise, it might
2392 ;; hide the actual definition. However, do remove any entry from
2393 ;; byte-compile-noruntime-functions, in case we have an autoload
2394 ;; of foo-func following an (eval-when-compile (require 'foo)).
2395 (unless (fboundp funsym)
2396 (push (cons funsym (cons 'autoload (cdr (cdr form))))
2397 byte-compile-function-environment))
2398 ;; If an autoload occurs _before_ the first call to a function,
2399 ;; byte-compile-callargs-warn does not add an entry to
2400 ;; byte-compile-unresolved-functions. Here we mimic the logic
2401 ;; of byte-compile-callargs-warn so as not to warn if the
2402 ;; autoload comes _after_ the function call.
2403 ;; Alternatively, similar logic could go in
2404 ;; byte-compile-warn-about-unresolved-functions.
2405 (if (memq funsym byte-compile-noruntime-functions)
2406 (setq byte-compile-noruntime-functions
2407 (delq funsym byte-compile-noruntime-functions))
2408 (setq byte-compile-unresolved-functions
2409 (delq (assq funsym byte-compile-unresolved-functions)
2410 byte-compile-unresolved-functions)))))
2411 (if (stringp (nth 3 form))
2412 form
2413 ;; No doc string, so we can compile this as a normal form.
2414 (byte-compile-keep-pending form 'byte-compile-normal-call)))
2416 (put 'defvar 'byte-hunk-handler 'byte-compile-file-form-defvar)
2417 (put 'defconst 'byte-hunk-handler 'byte-compile-file-form-defvar)
2419 (defun byte-compile--declare-var (sym)
2420 (when (and (symbolp sym)
2421 (not (string-match "[-*/:$]" (symbol-name sym)))
2422 (byte-compile-warning-enabled-p 'lexical))
2423 (byte-compile-warn "global/dynamic var `%s' lacks a prefix"
2424 sym))
2425 (when (memq sym byte-compile-lexical-variables)
2426 (setq byte-compile-lexical-variables
2427 (delq sym byte-compile-lexical-variables))
2428 (byte-compile-warn "Variable `%S' declared after its first use" sym))
2429 (push sym byte-compile-bound-variables))
2431 (defun byte-compile-file-form-defvar (form)
2432 (let ((sym (nth 1 form)))
2433 (byte-compile--declare-var sym)
2434 (if (eq (car form) 'defconst)
2435 (push sym byte-compile-const-variables)))
2436 (if (and (null (cddr form)) ;No `value' provided.
2437 (eq (car form) 'defvar)) ;Just a declaration.
2439 (cond ((consp (nth 2 form))
2440 (setq form (copy-sequence form))
2441 (setcar (cdr (cdr form))
2442 (byte-compile-top-level (nth 2 form) nil 'file))))
2443 form))
2445 (put 'define-abbrev-table 'byte-hunk-handler
2446 'byte-compile-file-form-defvar-function)
2447 (put 'defvaralias 'byte-hunk-handler 'byte-compile-file-form-defvar-function)
2449 (defun byte-compile-file-form-defvar-function (form)
2450 (pcase-let (((or `',name (let name nil)) (nth 1 form)))
2451 (if name (byte-compile--declare-var name)))
2452 (byte-compile-keep-pending form))
2454 (put 'custom-declare-variable 'byte-hunk-handler
2455 'byte-compile-file-form-custom-declare-variable)
2456 (defun byte-compile-file-form-custom-declare-variable (form)
2457 (when (byte-compile-warning-enabled-p 'callargs)
2458 (byte-compile-nogroup-warn form))
2459 (byte-compile-file-form-defvar-function form))
2461 (put 'require 'byte-hunk-handler 'byte-compile-file-form-require)
2462 (defun byte-compile-file-form-require (form)
2463 (let ((args (mapcar 'eval (cdr form)))
2464 (hist-orig load-history)
2465 hist-new prov-cons)
2466 (apply 'require args)
2468 ;; Record the functions defined by the require in `byte-compile-new-defuns'.
2469 (setq hist-new load-history)
2470 (setq prov-cons (cons 'provide (car args)))
2471 (while (and hist-new
2472 (not (member prov-cons (car hist-new))))
2473 (setq hist-new (cdr hist-new)))
2474 (when hist-new
2475 (dolist (x (car hist-new))
2476 (when (and (consp x)
2477 (memq (car x) '(defun t)))
2478 (push (cdr x) byte-compile-new-defuns))))
2480 (when (byte-compile-warning-enabled-p 'cl-functions)
2481 ;; Detect (require 'cl) in a way that works even if cl is already loaded.
2482 (if (member (car args) '("cl" cl))
2483 (progn
2484 (byte-compile-warn "cl package required at runtime")
2485 (byte-compile-disable-warning 'cl-functions))
2486 ;; We may have required something that causes cl to be loaded, eg
2487 ;; the uncompiled version of a file that requires cl when compiling.
2488 (setq hist-new load-history)
2489 (while (and (not byte-compile-cl-functions)
2490 hist-new (not (eq hist-new hist-orig)))
2491 (and (byte-compile-cl-file-p (car (pop hist-new)))
2492 (byte-compile-find-cl-functions))))))
2493 (byte-compile-keep-pending form 'byte-compile-normal-call))
2495 (put 'progn 'byte-hunk-handler 'byte-compile-file-form-progn)
2496 (put 'prog1 'byte-hunk-handler 'byte-compile-file-form-progn)
2497 (put 'prog2 'byte-hunk-handler 'byte-compile-file-form-progn)
2498 (defun byte-compile-file-form-progn (form)
2499 (mapc 'byte-compile-file-form (cdr form))
2500 ;; Return nil so the forms are not output twice.
2501 nil)
2503 (put 'with-no-warnings 'byte-hunk-handler
2504 'byte-compile-file-form-with-no-warnings)
2505 (defun byte-compile-file-form-with-no-warnings (form)
2506 ;; cf byte-compile-file-form-progn.
2507 (let (byte-compile-warnings)
2508 (mapc 'byte-compile-file-form (cdr form))
2509 nil))
2511 ;; This handler is not necessary, but it makes the output from dont-compile
2512 ;; and similar macros cleaner.
2513 (put 'eval 'byte-hunk-handler 'byte-compile-file-form-eval)
2514 (defun byte-compile-file-form-eval (form)
2515 (if (eq (car-safe (nth 1 form)) 'quote)
2516 (nth 1 (nth 1 form))
2517 (byte-compile-keep-pending form)))
2519 (defun byte-compile-file-form-defmumble (name macro arglist body rest)
2520 "Process a `defalias' for NAME.
2521 If MACRO is non-nil, the definition is known to be a macro.
2522 ARGLIST is the list of arguments, if it was recognized or t otherwise.
2523 BODY of the definition, or t if not recognized.
2524 Return non-nil if everything went as planned, or nil to imply that it decided
2525 not to take responsibility for the actual compilation of the code."
2526 (let* ((this-kind (if macro 'byte-compile-macro-environment
2527 'byte-compile-function-environment))
2528 (that-kind (if macro 'byte-compile-function-environment
2529 'byte-compile-macro-environment))
2530 (this-one (assq name (symbol-value this-kind)))
2531 (that-one (assq name (symbol-value that-kind)))
2532 (byte-compile-current-form name)) ; For warnings.
2534 (byte-compile-set-symbol-position name)
2535 (push name byte-compile-new-defuns)
2536 ;; When a function or macro is defined, add it to the call tree so that
2537 ;; we can tell when functions are not used.
2538 (if byte-compile-generate-call-tree
2539 (or (assq name byte-compile-call-tree)
2540 (setq byte-compile-call-tree
2541 (cons (list name nil nil) byte-compile-call-tree))))
2543 (if (byte-compile-warning-enabled-p 'redefine)
2544 (byte-compile-arglist-warn name arglist macro))
2546 (if byte-compile-verbose
2547 (message "Compiling %s... (%s)"
2548 (or byte-compile-current-file "") name))
2549 (cond ((not (or macro (listp body)))
2550 ;; We do not know positively if the definition is a macro
2551 ;; or a function, so we shouldn't emit warnings.
2552 ;; This also silences "multiple definition" warnings for defmethods.
2553 nil)
2554 (that-one
2555 (if (and (byte-compile-warning-enabled-p 'redefine)
2556 ;; Don't warn when compiling the stubs in byte-run...
2557 (not (assq name byte-compile-initial-macro-environment)))
2558 (byte-compile-warn
2559 "`%s' defined multiple times, as both function and macro"
2560 name))
2561 (setcdr that-one nil))
2562 (this-one
2563 (when (and (byte-compile-warning-enabled-p 'redefine)
2564 ;; Hack: Don't warn when compiling the magic internal
2565 ;; byte-compiler macros in byte-run.el...
2566 (not (assq name byte-compile-initial-macro-environment)))
2567 (byte-compile-warn "%s `%s' defined multiple times in this file"
2568 (if macro "macro" "function")
2569 name)))
2570 ((eq (car-safe (symbol-function name))
2571 (if macro 'lambda 'macro))
2572 (when (byte-compile-warning-enabled-p 'redefine)
2573 (byte-compile-warn "%s `%s' being redefined as a %s"
2574 (if macro "function" "macro")
2575 name
2576 (if macro "macro" "function")))
2577 ;; Shadow existing definition.
2578 (set this-kind
2579 (cons (cons name nil)
2580 (symbol-value this-kind))))
2583 (when (and (listp body)
2584 (stringp (car body))
2585 (symbolp (car-safe (cdr-safe body)))
2586 (car-safe (cdr-safe body))
2587 (stringp (car-safe (cdr-safe (cdr-safe body)))))
2588 ;; FIXME: We've done that already just above, so this looks wrong!
2589 ;;(byte-compile-set-symbol-position name)
2590 (byte-compile-warn "probable `\"' without `\\' in doc string of %s"
2591 name))
2593 (if (not (listp body))
2594 ;; The precise definition requires evaluation to find out, so it
2595 ;; will only be known at runtime.
2596 ;; For a macro, that means we can't use that macro in the same file.
2597 (progn
2598 (unless macro
2599 (push (cons name (if (listp arglist) `(declared ,arglist) t))
2600 byte-compile-function-environment))
2601 ;; Tell the caller that we didn't compile it yet.
2602 nil)
2604 (let* ((code (byte-compile-lambda (cons arglist body) t)))
2605 (if this-one
2606 ;; A definition in b-c-initial-m-e should always take precedence
2607 ;; during compilation, so don't let it be redefined. (Bug#8647)
2608 (or (and macro
2609 (assq name byte-compile-initial-macro-environment))
2610 (setcdr this-one code))
2611 (set this-kind
2612 (cons (cons name code)
2613 (symbol-value this-kind))))
2615 (if rest
2616 ;; There are additional args to `defalias' (like maybe a docstring)
2617 ;; that the code below can't handle: punt!
2619 ;; Otherwise, we have a bona-fide defun/defmacro definition, and use
2620 ;; special code to allow dynamic docstrings and byte-code.
2621 (byte-compile-flush-pending)
2622 (let ((index
2623 ;; If there's no doc string, provide -1 as the "doc string
2624 ;; index" so that no element will be treated as a doc string.
2625 (if (not (stringp (documentation code t))) -1 4)))
2626 ;; Output the form by hand, that's much simpler than having
2627 ;; b-c-output-file-form analyze the defalias.
2628 (byte-compile-output-docform
2629 "\n(defalias '"
2630 name
2631 (if macro `(" '(macro . #[" ,index "])") `(" #[" ,index "]"))
2632 (append code nil) ; Turn byte-code-function-p into list.
2633 (and (atom code) byte-compile-dynamic
2635 nil))
2636 (princ ")" byte-compile--outbuffer)
2637 t)))))
2639 (defun byte-compile-output-as-comment (exp quoted)
2640 "Print Lisp object EXP in the output file, inside a comment,
2641 and return the file (byte) position it will have.
2642 If QUOTED is non-nil, print with quoting; otherwise, print without quoting."
2643 (with-current-buffer byte-compile--outbuffer
2644 (let ((position (point)))
2646 ;; Insert EXP, and make it a comment with #@LENGTH.
2647 (insert " ")
2648 (if quoted
2649 (prin1 exp byte-compile--outbuffer)
2650 (princ exp byte-compile--outbuffer))
2651 (goto-char position)
2652 ;; Quote certain special characters as needed.
2653 ;; get_doc_string in doc.c does the unquoting.
2654 (while (search-forward "\^A" nil t)
2655 (replace-match "\^A\^A" t t))
2656 (goto-char position)
2657 (while (search-forward "\000" nil t)
2658 (replace-match "\^A0" t t))
2659 (goto-char position)
2660 (while (search-forward "\037" nil t)
2661 (replace-match "\^A_" t t))
2662 (goto-char (point-max))
2663 (insert "\037")
2664 (goto-char position)
2665 (insert "#@" (format "%d" (- (position-bytes (point-max))
2666 (position-bytes position))))
2668 ;; Save the file position of the object.
2669 ;; Note we add 1 to skip the space that we inserted before the actual doc
2670 ;; string, and subtract point-min to convert from an 1-origin Emacs
2671 ;; position to a file position.
2672 (prog1
2673 (- (position-bytes (point)) (point-min) -1)
2674 (goto-char (point-max))))))
2676 (defun byte-compile--reify-function (fun)
2677 "Return an expression which will evaluate to a function value FUN.
2678 FUN should be either a `lambda' value or a `closure' value."
2679 (pcase-let* (((or (and `(lambda ,args . ,body) (let env nil))
2680 `(closure ,env ,args . ,body))
2681 fun)
2682 (preamble nil)
2683 (renv ()))
2684 ;; Split docstring and `interactive' form from body.
2685 (when (stringp (car body))
2686 (push (pop body) preamble))
2687 (when (eq (car-safe (car body)) 'interactive)
2688 (push (pop body) preamble))
2689 ;; Turn the function's closed vars (if any) into local let bindings.
2690 (dolist (binding env)
2691 (cond
2692 ((consp binding)
2693 ;; We check shadowing by the args, so that the `let' can be moved
2694 ;; within the lambda, which can then be unfolded. FIXME: Some of those
2695 ;; bindings might be unused in `body'.
2696 (unless (memq (car binding) args) ;Shadowed.
2697 (push `(,(car binding) ',(cdr binding)) renv)))
2698 ((eq binding t))
2699 (t (push `(defvar ,binding) body))))
2700 (if (null renv)
2701 `(lambda ,args ,@preamble ,@body)
2702 `(lambda ,args ,@preamble (let ,(nreverse renv) ,@body)))))
2704 ;;;###autoload
2705 (defun byte-compile (form)
2706 "If FORM is a symbol, byte-compile its function definition.
2707 If FORM is a lambda or a macro, byte-compile it as a function."
2708 (displaying-byte-compile-warnings
2709 (byte-compile-close-variables
2710 (let* ((lexical-binding lexical-binding)
2711 (fun (if (symbolp form)
2712 (symbol-function form)
2713 form))
2714 (macro (eq (car-safe fun) 'macro)))
2715 (if macro
2716 (setq fun (cdr fun)))
2717 (cond
2718 ;; Up until Emacs-24.1, byte-compile silently did nothing when asked to
2719 ;; compile something invalid. So let's tune down the complaint from an
2720 ;; error to a simple message for the known case where signaling an error
2721 ;; causes problems.
2722 ((byte-code-function-p fun)
2723 (message "Function %s is already compiled"
2724 (if (symbolp form) form "provided"))
2725 fun)
2727 (when (or (symbolp form) (eq (car-safe fun) 'closure))
2728 ;; `fun' is a function *value*, so try to recover its corresponding
2729 ;; source code.
2730 (setq lexical-binding (eq (car fun) 'closure))
2731 (setq fun (byte-compile--reify-function fun)))
2732 ;; Expand macros.
2733 (setq fun (byte-compile-preprocess fun))
2734 (setq fun (byte-compile-top-level fun nil 'eval))
2735 (if macro (push 'macro fun))
2736 (if (symbolp form)
2737 (fset form fun)
2738 fun)))))))
2740 (defun byte-compile-sexp (sexp)
2741 "Compile and return SEXP."
2742 (displaying-byte-compile-warnings
2743 (byte-compile-close-variables
2744 (byte-compile-top-level (byte-compile-preprocess sexp)))))
2746 (defun byte-compile-check-lambda-list (list)
2747 "Check lambda-list LIST for errors."
2748 (let (vars)
2749 (while list
2750 (let ((arg (car list)))
2751 (when (symbolp arg)
2752 (byte-compile-set-symbol-position arg))
2753 (cond ((or (not (symbolp arg))
2754 (macroexp--const-symbol-p arg t))
2755 (error "Invalid lambda variable %s" arg))
2756 ((eq arg '&rest)
2757 (unless (cdr list)
2758 (error "&rest without variable name"))
2759 (when (cddr list)
2760 (error "Garbage following &rest VAR in lambda-list")))
2761 ((eq arg '&optional)
2762 (when (or (null (cdr list))
2763 (memq (cadr list) '(&optional &rest)))
2764 (error "Variable name missing after &optional"))
2765 (when (memq '&optional (cddr list))
2766 (error "Duplicate &optional")))
2767 ((memq arg vars)
2768 (byte-compile-warn "repeated variable %s in lambda-list" arg))
2770 (push arg vars))))
2771 (setq list (cdr list)))))
2774 (defun byte-compile-arglist-vars (arglist)
2775 "Return a list of the variables in the lambda argument list ARGLIST."
2776 (remq '&rest (remq '&optional arglist)))
2778 (defun byte-compile-make-lambda-lexenv (args)
2779 "Return a new lexical environment for a lambda expression FORM."
2780 (let* ((lexenv nil)
2781 (stackpos 0))
2782 ;; Add entries for each argument.
2783 (dolist (arg args)
2784 (push (cons arg stackpos) lexenv)
2785 (setq stackpos (1+ stackpos)))
2786 ;; Return the new lexical environment.
2787 lexenv))
2789 (defun byte-compile-make-args-desc (arglist)
2790 (let ((mandatory 0)
2791 nonrest (rest 0))
2792 (while (and arglist (not (memq (car arglist) '(&optional &rest))))
2793 (setq mandatory (1+ mandatory))
2794 (setq arglist (cdr arglist)))
2795 (setq nonrest mandatory)
2796 (when (eq (car arglist) '&optional)
2797 (setq arglist (cdr arglist))
2798 (while (and arglist (not (eq (car arglist) '&rest)))
2799 (setq nonrest (1+ nonrest))
2800 (setq arglist (cdr arglist))))
2801 (when arglist
2802 (setq rest 1))
2803 (if (> mandatory 127)
2804 (byte-compile-report-error "Too many (>127) mandatory arguments")
2805 (logior mandatory
2806 (lsh nonrest 8)
2807 (lsh rest 7)))))
2810 (defun byte-compile-lambda (fun &optional add-lambda reserved-csts)
2811 "Byte-compile a lambda-expression and return a valid function.
2812 The value is usually a compiled function but may be the original
2813 lambda-expression.
2814 When ADD-LAMBDA is non-nil, the symbol `lambda' is added as head
2815 of the list FUN and `byte-compile-set-symbol-position' is not called.
2816 Use this feature to avoid calling `byte-compile-set-symbol-position'
2817 for symbols generated by the byte compiler itself."
2818 (if add-lambda
2819 (setq fun (cons 'lambda fun))
2820 (unless (eq 'lambda (car-safe fun))
2821 (error "Not a lambda list: %S" fun))
2822 (byte-compile-set-symbol-position 'lambda))
2823 (byte-compile-check-lambda-list (nth 1 fun))
2824 (let* ((arglist (nth 1 fun))
2825 (arglistvars (byte-compile-arglist-vars arglist))
2826 (byte-compile-bound-variables
2827 (append (if (not lexical-binding) arglistvars)
2828 byte-compile-bound-variables))
2829 (body (cdr (cdr fun)))
2830 (doc (if (stringp (car body))
2831 (prog1 (car body)
2832 ;; Discard the doc string
2833 ;; unless it is the last element of the body.
2834 (if (cdr body)
2835 (setq body (cdr body))))))
2836 (int (assq 'interactive body)))
2837 ;; Process the interactive spec.
2838 (when int
2839 (byte-compile-set-symbol-position 'interactive)
2840 ;; Skip (interactive) if it is in front (the most usual location).
2841 (if (eq int (car body))
2842 (setq body (cdr body)))
2843 (cond ((consp (cdr int))
2844 (if (cdr (cdr int))
2845 (byte-compile-warn "malformed interactive spec: %s"
2846 (prin1-to-string int)))
2847 ;; If the interactive spec is a call to `list', don't
2848 ;; compile it, because `call-interactively' looks at the
2849 ;; args of `list'. Actually, compile it to get warnings,
2850 ;; but don't use the result.
2851 (let* ((form (nth 1 int))
2852 (newform (byte-compile-top-level form)))
2853 (while (memq (car-safe form) '(let let* progn save-excursion))
2854 (while (consp (cdr form))
2855 (setq form (cdr form)))
2856 (setq form (car form)))
2857 (if (and (eq (car-safe form) 'list)
2858 ;; The spec is evalled in callint.c in dynamic-scoping
2859 ;; mode, so just leaving the form unchanged would mean
2860 ;; it won't be eval'd in the right mode.
2861 (not lexical-binding))
2863 (setq int `(interactive ,newform)))))
2864 ((cdr int)
2865 (byte-compile-warn "malformed interactive spec: %s"
2866 (prin1-to-string int)))))
2867 ;; Process the body.
2868 (let ((compiled
2869 (byte-compile-top-level (cons 'progn body) nil 'lambda
2870 ;; If doing lexical binding, push a new
2871 ;; lexical environment containing just the
2872 ;; args (since lambda expressions should be
2873 ;; closed by now).
2874 (and lexical-binding
2875 (byte-compile-make-lambda-lexenv
2876 arglistvars))
2877 reserved-csts)))
2878 ;; Build the actual byte-coded function.
2879 (cl-assert (eq 'byte-code (car-safe compiled)))
2880 (apply #'make-byte-code
2881 (if lexical-binding
2882 (byte-compile-make-args-desc arglist)
2883 arglist)
2884 (append
2885 ;; byte-string, constants-vector, stack depth
2886 (cdr compiled)
2887 ;; optionally, the doc string.
2888 (cond ((and lexical-binding arglist)
2889 ;; byte-compile-make-args-desc lost the args's names,
2890 ;; so preserve them in the docstring.
2891 (list (help-add-fundoc-usage doc arglist)))
2892 ((or doc int)
2893 (list doc)))
2894 ;; optionally, the interactive spec.
2895 (if int
2896 (list (nth 1 int))))))))
2898 (defvar byte-compile-reserved-constants 0)
2900 (defun byte-compile-constants-vector ()
2901 ;; Builds the constants-vector from the current variables and constants.
2902 ;; This modifies the constants from (const . nil) to (const . offset).
2903 ;; To keep the byte-codes to look up the vector as short as possible:
2904 ;; First 6 elements are vars, as there are one-byte varref codes for those.
2905 ;; Next up to byte-constant-limit are constants, still with one-byte codes.
2906 ;; Next variables again, to get 2-byte codes for variable lookup.
2907 ;; The rest of the constants and variables need 3-byte byte-codes.
2908 (let* ((i (1- byte-compile-reserved-constants))
2909 (rest (nreverse byte-compile-variables)) ; nreverse because the first
2910 (other (nreverse byte-compile-constants)) ; vars often are used most.
2911 ret tmp
2912 (limits '(5 ; Use the 1-byte varref codes,
2913 63 ; 1-constlim ; 1-byte byte-constant codes,
2914 255 ; 2-byte varref codes,
2915 65535 ; 3-byte codes for the rest.
2916 65535)) ; twice since we step when we swap.
2917 limit)
2918 (while (or rest other)
2919 (setq limit (car limits))
2920 (while (and rest (< i limit))
2921 (cond
2922 ((numberp (car rest))
2923 (cl-assert (< (car rest) byte-compile-reserved-constants)))
2924 ((setq tmp (assq (car (car rest)) ret))
2925 (setcdr (car rest) (cdr tmp)))
2927 (setcdr (car rest) (setq i (1+ i)))
2928 (setq ret (cons (car rest) ret))))
2929 (setq rest (cdr rest)))
2930 (setq limits (cdr limits) ;Step
2931 rest (prog1 other ;&Swap.
2932 (setq other rest))))
2933 (apply 'vector (nreverse (mapcar 'car ret)))))
2935 ;; Given an expression FORM, compile it and return an equivalent byte-code
2936 ;; expression (a call to the function byte-code).
2937 (defun byte-compile-top-level (form &optional for-effect output-type
2938 lexenv reserved-csts)
2939 ;; OUTPUT-TYPE advises about how form is expected to be used:
2940 ;; 'eval or nil -> a single form,
2941 ;; 'progn or t -> a list of forms,
2942 ;; 'lambda -> body of a lambda,
2943 ;; 'file -> used at file-level.
2944 (let ((byte-compile--for-effect for-effect)
2945 (byte-compile-constants nil)
2946 (byte-compile-variables nil)
2947 (byte-compile-tag-number 0)
2948 (byte-compile-depth 0)
2949 (byte-compile-maxdepth 0)
2950 (byte-compile--lexical-environment lexenv)
2951 (byte-compile-reserved-constants (or reserved-csts 0))
2952 (byte-compile-output nil)
2953 (byte-compile-jump-tables nil))
2954 (if (memq byte-optimize '(t source))
2955 (setq form (byte-optimize-form form byte-compile--for-effect)))
2956 (while (and (eq (car-safe form) 'progn) (null (cdr (cdr form))))
2957 (setq form (nth 1 form)))
2958 ;; Set up things for a lexically-bound function.
2959 (when (and lexical-binding (eq output-type 'lambda))
2960 ;; See how many arguments there are, and set the current stack depth
2961 ;; accordingly.
2962 (setq byte-compile-depth (length byte-compile--lexical-environment))
2963 ;; If there are args, output a tag to record the initial
2964 ;; stack-depth for the optimizer.
2965 (when (> byte-compile-depth 0)
2966 (byte-compile-out-tag (byte-compile-make-tag))))
2967 ;; Now compile FORM
2968 (byte-compile-form form byte-compile--for-effect)
2969 (byte-compile-out-toplevel byte-compile--for-effect output-type)))
2971 (defun byte-compile-out-toplevel (&optional for-effect output-type)
2972 (if for-effect
2973 ;; The stack is empty. Push a value to be returned from (byte-code ..).
2974 (if (eq (car (car byte-compile-output)) 'byte-discard)
2975 (setq byte-compile-output (cdr byte-compile-output))
2976 (byte-compile-push-constant
2977 ;; Push any constant - preferably one which already is used, and
2978 ;; a number or symbol - ie not some big sequence. The return value
2979 ;; isn't returned, but it would be a shame if some textually large
2980 ;; constant was not optimized away because we chose to return it.
2981 (and (not (assq nil byte-compile-constants)) ; Nil is often there.
2982 (let ((tmp (reverse byte-compile-constants)))
2983 (while (and tmp (not (or (symbolp (caar tmp))
2984 (numberp (caar tmp)))))
2985 (setq tmp (cdr tmp)))
2986 (caar tmp))))))
2987 (byte-compile-out 'byte-return 0)
2988 (setq byte-compile-output (nreverse byte-compile-output))
2989 (if (memq byte-optimize '(t byte))
2990 (setq byte-compile-output
2991 (byte-optimize-lapcode byte-compile-output)))
2993 ;; Decompile trivial functions:
2994 ;; only constants and variables, or a single funcall except in lambdas.
2995 ;; Except for Lisp_Compiled objects, forms like (foo "hi")
2996 ;; are still quicker than (byte-code "..." [foo "hi"] 2).
2997 ;; Note that even (quote foo) must be parsed just as any subr by the
2998 ;; interpreter, so quote should be compiled into byte-code in some contexts.
2999 ;; What to leave uncompiled:
3000 ;; lambda -> never. we used to leave it uncompiled if the body was
3001 ;; a single atom, but that causes confusion if the docstring
3002 ;; uses the (file . pos) syntax. Besides, now that we have
3003 ;; the Lisp_Compiled type, the compiled form is faster.
3004 ;; eval -> atom, quote or (function atom atom atom)
3005 ;; progn -> as <<same-as-eval>> or (progn <<same-as-eval>> atom)
3006 ;; file -> as progn, but takes both quotes and atoms, and longer forms.
3007 (let (rest
3008 (maycall (not (eq output-type 'lambda))) ; t if we may make a funcall.
3009 tmp body)
3010 (cond
3011 ;; #### This should be split out into byte-compile-nontrivial-function-p.
3012 ((or (eq output-type 'lambda)
3013 (nthcdr (if (eq output-type 'file) 50 8) byte-compile-output)
3014 (assq 'TAG byte-compile-output) ; Not necessary, but speeds up a bit.
3015 (not (setq tmp (assq 'byte-return byte-compile-output)))
3016 (progn
3017 (setq rest (nreverse
3018 (cdr (memq tmp (reverse byte-compile-output)))))
3019 (while
3020 (cond
3021 ((memq (car (car rest)) '(byte-varref byte-constant))
3022 (setq tmp (car (cdr (car rest))))
3023 (if (if (eq (car (car rest)) 'byte-constant)
3024 (or (consp tmp)
3025 (and (symbolp tmp)
3026 (not (macroexp--const-symbol-p tmp)))))
3027 (if maycall
3028 (setq body (cons (list 'quote tmp) body)))
3029 (setq body (cons tmp body))))
3030 ((and maycall
3031 ;; Allow a funcall if at most one atom follows it.
3032 (null (nthcdr 3 rest))
3033 (setq tmp (get (car (car rest)) 'byte-opcode-invert))
3034 (or (null (cdr rest))
3035 (and (memq output-type '(file progn t))
3036 (cdr (cdr rest))
3037 (eq (car (nth 1 rest)) 'byte-discard)
3038 (progn (setq rest (cdr rest)) t))))
3039 (setq maycall nil) ; Only allow one real function call.
3040 (setq body (nreverse body))
3041 (setq body (list
3042 (if (and (eq tmp 'funcall)
3043 (eq (car-safe (car body)) 'quote)
3044 (symbolp (nth 1 (car body))))
3045 (cons (nth 1 (car body)) (cdr body))
3046 (cons tmp body))))
3047 (or (eq output-type 'file)
3048 (not (delq nil (mapcar 'consp (cdr (car body))))))))
3049 (setq rest (cdr rest)))
3050 rest))
3051 (let ((byte-compile-vector (byte-compile-constants-vector)))
3052 (list 'byte-code (byte-compile-lapcode byte-compile-output)
3053 byte-compile-vector byte-compile-maxdepth)))
3054 ;; it's a trivial function
3055 ((cdr body) (cons 'progn (nreverse body)))
3056 ((car body)))))
3058 ;; Given BODY, compile it and return a new body.
3059 (defun byte-compile-top-level-body (body &optional for-effect)
3060 (setq body
3061 (byte-compile-top-level (cons 'progn body) for-effect t))
3062 (cond ((eq (car-safe body) 'progn)
3063 (cdr body))
3064 (body
3065 (list body))))
3067 ;; Special macro-expander used during byte-compilation.
3068 (defun byte-compile-macroexpand-declare-function (fn file &rest args)
3069 (declare (advertised-calling-convention
3070 (fn file &optional arglist fileonly) nil))
3071 (let ((gotargs (and (consp args) (listp (car args))))
3072 (unresolved (assq fn byte-compile-unresolved-functions)))
3073 (when unresolved ; function was called before declaration
3074 (if (and gotargs (byte-compile-warning-enabled-p 'callargs))
3075 (byte-compile-arglist-warn fn (car args) nil)
3076 (setq byte-compile-unresolved-functions
3077 (delq unresolved byte-compile-unresolved-functions))))
3078 (push (cons fn (if gotargs
3079 (list 'declared (car args))
3080 t)) ; Arglist not specified.
3081 byte-compile-function-environment))
3082 ;; We are stating that it _will_ be defined at runtime.
3083 (setq byte-compile-noruntime-functions
3084 (delq fn byte-compile-noruntime-functions))
3085 ;; Delegate the rest to the normal macro definition.
3086 (macroexpand `(declare-function ,fn ,file ,@args)))
3089 ;; This is the recursive entry point for compiling each subform of an
3090 ;; expression.
3091 ;; If for-effect is non-nil, byte-compile-form will output a byte-discard
3092 ;; before terminating (ie no value will be left on the stack).
3093 ;; A byte-compile handler may, when byte-compile--for-effect is non-nil, choose
3094 ;; output code which does not leave a value on the stack, and then set
3095 ;; byte-compile--for-effect to nil (to prevent byte-compile-form from
3096 ;; outputting the byte-discard).
3097 ;; If a handler wants to call another handler, it should do so via
3098 ;; byte-compile-form, or take extreme care to handle byte-compile--for-effect
3099 ;; correctly. (Use byte-compile-form-do-effect to reset the
3100 ;; byte-compile--for-effect flag too.)
3102 (defun byte-compile-form (form &optional for-effect)
3103 (let ((byte-compile--for-effect for-effect))
3104 (cond
3105 ((not (consp form))
3106 (cond ((or (not (symbolp form)) (macroexp--const-symbol-p form))
3107 (when (symbolp form)
3108 (byte-compile-set-symbol-position form))
3109 (byte-compile-constant form))
3110 ((and byte-compile--for-effect byte-compile-delete-errors)
3111 (when (symbolp form)
3112 (byte-compile-set-symbol-position form))
3113 (setq byte-compile--for-effect nil))
3115 (byte-compile-variable-ref form))))
3116 ((symbolp (car form))
3117 (let* ((fn (car form))
3118 (handler (get fn 'byte-compile))
3119 (interactive-only
3120 (or (get fn 'interactive-only)
3121 (memq fn byte-compile-interactive-only-functions))))
3122 (when (memq fn '(set symbol-value run-hooks ;; add-to-list
3123 add-hook remove-hook run-hook-with-args
3124 run-hook-with-args-until-success
3125 run-hook-with-args-until-failure))
3126 (pcase (cdr form)
3127 (`(',var . ,_)
3128 (when (assq var byte-compile-lexical-variables)
3129 (byte-compile-report-error
3130 (format-message "%s cannot use lexical var `%s'" fn var))))))
3131 (when (macroexp--const-symbol-p fn)
3132 (byte-compile-warn "`%s' called as a function" fn))
3133 (when (and (byte-compile-warning-enabled-p 'interactive-only)
3134 interactive-only)
3135 (byte-compile-warn "`%s' is for interactive use only%s"
3137 (cond ((stringp interactive-only)
3138 (format "; %s"
3139 (substitute-command-keys
3140 interactive-only)))
3141 ((and (symbolp 'interactive-only)
3142 (not (eq interactive-only t)))
3143 (format-message "; use `%s' instead."
3144 interactive-only))
3145 (t "."))))
3146 (if (eq (car-safe (symbol-function (car form))) 'macro)
3147 (byte-compile-report-error
3148 (format "Forgot to expand macro %s in %S" (car form) form)))
3149 (if (and handler
3150 ;; Make sure that function exists.
3151 (and (functionp handler)
3152 ;; Ignore obsolete byte-compile function used by former
3153 ;; CL code to handle compiler macros (we do it
3154 ;; differently now).
3155 (not (eq handler 'cl-byte-compile-compiler-macro))))
3156 (funcall handler form)
3157 (byte-compile-normal-call form))
3158 (if (byte-compile-warning-enabled-p 'cl-functions)
3159 (byte-compile-cl-warn form))))
3160 ((and (byte-code-function-p (car form))
3161 (memq byte-optimize '(t lap)))
3162 (byte-compile-unfold-bcf form))
3163 ((and (eq (car-safe (car form)) 'lambda)
3164 ;; if the form comes out the same way it went in, that's
3165 ;; because it was malformed, and we couldn't unfold it.
3166 (not (eq form (setq form (byte-compile-unfold-lambda form)))))
3167 (byte-compile-form form byte-compile--for-effect)
3168 (setq byte-compile--for-effect nil))
3169 ((byte-compile-normal-call form)))
3170 (if byte-compile--for-effect
3171 (byte-compile-discard))))
3173 (defun byte-compile-normal-call (form)
3174 (when (and (byte-compile-warning-enabled-p 'callargs)
3175 (symbolp (car form)))
3176 (if (memq (car form)
3177 '(custom-declare-group custom-declare-variable
3178 custom-declare-face))
3179 (byte-compile-nogroup-warn form))
3180 (byte-compile-callargs-warn form))
3181 (if byte-compile-generate-call-tree
3182 (byte-compile-annotate-call-tree form))
3183 (when (and byte-compile--for-effect (eq (car form) 'mapcar)
3184 (byte-compile-warning-enabled-p 'mapcar))
3185 (byte-compile-set-symbol-position 'mapcar)
3186 (byte-compile-warn
3187 "`mapcar' called for effect; use `mapc' or `dolist' instead"))
3188 (byte-compile-push-constant (car form))
3189 (mapc 'byte-compile-form (cdr form)) ; wasteful, but faster.
3190 (byte-compile-out 'byte-call (length (cdr form))))
3193 ;; Splice the given lap code into the current instruction stream.
3194 ;; If it has any labels in it, you're responsible for making sure there
3195 ;; are no collisions, and that byte-compile-tag-number is reasonable
3196 ;; after this is spliced in. The provided list is destroyed.
3197 (defun byte-compile-inline-lapcode (lap end-depth)
3198 ;; "Replay" the operations: we used to just do
3199 ;; (setq byte-compile-output (nconc (nreverse lap) byte-compile-output))
3200 ;; but that fails to update byte-compile-depth, so we had to assume
3201 ;; that `lap' ends up adding exactly 1 element to the stack. This
3202 ;; happens to be true for byte-code generated by bytecomp.el without
3203 ;; lexical-binding, but it's not true in general, and it's not true for
3204 ;; code output by bytecomp.el with lexical-binding.
3205 ;; We also restore the value of `byte-compile-depth' and remove TAG depths
3206 ;; accordingly when inlining lapcode containing lap-code, exactly as
3207 ;; documented in `byte-compile-cond-jump-table'.
3208 (let ((endtag (byte-compile-make-tag))
3209 last-jump-tag ;; last TAG we have jumped to
3210 last-depth ;; last value of `byte-compile-depth'
3211 last-constant ;; value of the last constant encountered
3212 last-switch ;; whether the last op encountered was byte-switch
3213 switch-tags ;; a list of tags that byte-switch could jump to
3214 ;; a list of tags byte-switch will jump to, if the value doesn't
3215 ;; match any entry in the hash table
3216 switch-default-tags)
3217 (dolist (op lap)
3218 (cond
3219 ((eq (car op) 'TAG)
3220 (when (or (member op switch-tags) (member op switch-default-tags))
3221 ;; This TAG is used in a jump table, this means the last goto
3222 ;; was to a done/default TAG, and thus it's cddr should be set to nil.
3223 (when last-jump-tag
3224 (setcdr (cdr last-jump-tag) nil))
3225 ;; Also, restore the value of `byte-compile-depth' to what it was
3226 ;; before the last goto.
3227 (setq byte-compile-depth last-depth
3228 last-jump-tag nil))
3229 (byte-compile-out-tag op))
3230 ((memq (car op) byte-goto-ops)
3231 (setq last-depth byte-compile-depth
3232 last-jump-tag (cdr op))
3233 (byte-compile-goto (car op) (cdr op))
3234 (when last-switch
3235 ;; The last op was byte-switch, this goto jumps to a "default" TAG
3236 ;; (when no value in the jump table is satisfied).
3237 (push (cdr op) switch-default-tags)
3238 (setcdr (cdr (cdr op)) nil)
3239 (setq byte-compile-depth last-depth
3240 last-switch nil)))
3241 ((eq (car op) 'byte-return)
3242 (byte-compile-discard (- byte-compile-depth end-depth) t)
3243 (byte-compile-goto 'byte-goto endtag))
3245 (when (eq (car op) 'byte-switch)
3246 ;; The last constant is a jump table.
3247 (push last-constant byte-compile-jump-tables)
3248 (setq last-switch t)
3249 ;; Push all TAGs in the jump to switch-tags.
3250 (maphash #'(lambda (_k tag)
3251 (push tag switch-tags))
3252 last-constant))
3253 (setq last-constant (and (eq (car op) 'byte-constant) (cadr op)))
3254 (setq last-depth byte-compile-depth)
3255 (byte-compile-out (car op) (cdr op)))))
3256 (byte-compile-out-tag endtag)))
3258 (defun byte-compile-unfold-bcf (form)
3259 "Inline call to byte-code-functions."
3260 (let* ((byte-compile-bound-variables byte-compile-bound-variables)
3261 (fun (car form))
3262 (fargs (aref fun 0))
3263 (start-depth byte-compile-depth)
3264 (fmax2 (if (numberp fargs) (lsh fargs -7))) ;2*max+rest.
3265 ;; (fmin (if (numberp fargs) (logand fargs 127)))
3266 (alen (length (cdr form)))
3267 (dynbinds ())
3268 lap)
3269 (fetch-bytecode fun)
3270 (setq lap (byte-decompile-bytecode-1 (aref fun 1) (aref fun 2) t))
3271 ;; optimized switch bytecode makes it impossible to guess the correct
3272 ;; `byte-compile-depth', which can result in incorrect inlined code.
3273 ;; therefore, we do not inline code that uses the `byte-switch'
3274 ;; instruction.
3275 (if (assq 'byte-switch lap)
3276 (byte-compile-normal-call form)
3277 (mapc 'byte-compile-form (cdr form))
3278 (unless fmax2
3279 ;; Old-style byte-code.
3280 (cl-assert (listp fargs))
3281 (while fargs
3282 (pcase (car fargs)
3283 (`&optional (setq fargs (cdr fargs)))
3284 (`&rest (setq fmax2 (+ (* 2 (length dynbinds)) 1))
3285 (push (cadr fargs) dynbinds)
3286 (setq fargs nil))
3287 (_ (push (pop fargs) dynbinds))))
3288 (unless fmax2 (setq fmax2 (* 2 (length dynbinds)))))
3289 (cond
3290 ((<= (+ alen alen) fmax2)
3291 ;; Add missing &optional (or &rest) arguments.
3292 (dotimes (_ (- (/ (1+ fmax2) 2) alen))
3293 (byte-compile-push-constant nil)))
3294 ((zerop (logand fmax2 1))
3295 (byte-compile-report-error
3296 (format "Too many arguments for inlined function %S" form))
3297 (byte-compile-discard (- alen (/ fmax2 2))))
3299 ;; Turn &rest args into a list.
3300 (let ((n (- alen (/ (1- fmax2) 2))))
3301 (cl-assert (> n 0) nil "problem: fmax2=%S alen=%S n=%S" fmax2 alen n)
3302 (if (< n 5)
3303 (byte-compile-out
3304 (aref [byte-list1 byte-list2 byte-list3 byte-list4] (1- n))
3306 (byte-compile-out 'byte-listN n)))))
3307 (mapc #'byte-compile-dynamic-variable-bind dynbinds)
3308 (byte-compile-inline-lapcode lap (1+ start-depth))
3309 ;; Unbind dynamic variables.
3310 (when dynbinds
3311 (byte-compile-out 'byte-unbind (length dynbinds)))
3312 (cl-assert (eq byte-compile-depth (1+ start-depth))
3313 nil "Wrong depth start=%s end=%s" start-depth byte-compile-depth))))
3315 (defun byte-compile-check-variable (var access-type)
3316 "Do various error checks before a use of the variable VAR."
3317 (when (symbolp var)
3318 (byte-compile-set-symbol-position var))
3319 (cond ((or (not (symbolp var)) (macroexp--const-symbol-p var))
3320 (when (byte-compile-warning-enabled-p 'constants)
3321 (byte-compile-warn (if (eq access-type 'let-bind)
3322 "attempt to let-bind %s `%s'"
3323 "variable reference to %s `%s'")
3324 (if (symbolp var) "constant" "nonvariable")
3325 (prin1-to-string var))))
3326 ((let ((od (get var 'byte-obsolete-variable)))
3327 (and od
3328 (not (memq var byte-compile-not-obsolete-vars))
3329 (not (memq var byte-compile-global-not-obsolete-vars))
3330 (or (pcase (nth 1 od)
3331 (`set (not (eq access-type 'reference)))
3332 (`get (eq access-type 'reference))
3333 (_ t)))))
3334 (byte-compile-warn-obsolete var))))
3336 (defsubst byte-compile-dynamic-variable-op (base-op var)
3337 (let ((tmp (assq var byte-compile-variables)))
3338 (unless tmp
3339 (setq tmp (list var))
3340 (push tmp byte-compile-variables))
3341 (byte-compile-out base-op tmp)))
3343 (defun byte-compile-dynamic-variable-bind (var)
3344 "Generate code to bind the lexical variable VAR to the top-of-stack value."
3345 (byte-compile-check-variable var 'let-bind)
3346 (push var byte-compile-bound-variables)
3347 (byte-compile-dynamic-variable-op 'byte-varbind var))
3349 (defun byte-compile-variable-ref (var)
3350 "Generate code to push the value of the variable VAR on the stack."
3351 (byte-compile-check-variable var 'reference)
3352 (let ((lex-binding (assq var byte-compile--lexical-environment)))
3353 (if lex-binding
3354 ;; VAR is lexically bound
3355 (byte-compile-stack-ref (cdr lex-binding))
3356 ;; VAR is dynamically bound
3357 (unless (or (not (byte-compile-warning-enabled-p 'free-vars))
3358 (boundp var)
3359 (memq var byte-compile-bound-variables)
3360 (memq var byte-compile-free-references))
3361 (byte-compile-warn "reference to free variable `%S'" var)
3362 (push var byte-compile-free-references))
3363 (byte-compile-dynamic-variable-op 'byte-varref var))))
3365 (defun byte-compile-variable-set (var)
3366 "Generate code to set the variable VAR from the top-of-stack value."
3367 (byte-compile-check-variable var 'assign)
3368 (let ((lex-binding (assq var byte-compile--lexical-environment)))
3369 (if lex-binding
3370 ;; VAR is lexically bound.
3371 (byte-compile-stack-set (cdr lex-binding))
3372 ;; VAR is dynamically bound.
3373 (unless (or (not (byte-compile-warning-enabled-p 'free-vars))
3374 (boundp var)
3375 (memq var byte-compile-bound-variables)
3376 (memq var byte-compile-free-assignments))
3377 (byte-compile-warn "assignment to free variable `%s'" var)
3378 (push var byte-compile-free-assignments))
3379 (byte-compile-dynamic-variable-op 'byte-varset var))))
3381 (defmacro byte-compile-get-constant (const)
3382 `(or (if (stringp ,const)
3383 ;; In a string constant, treat properties as significant.
3384 (let (result)
3385 (dolist (elt byte-compile-constants)
3386 (if (equal-including-properties (car elt) ,const)
3387 (setq result elt)))
3388 result)
3389 (assq ,const byte-compile-constants))
3390 (car (setq byte-compile-constants
3391 (cons (list ,const) byte-compile-constants)))))
3393 ;; Use this when the value of a form is a constant.
3394 ;; This obeys byte-compile--for-effect.
3395 (defun byte-compile-constant (const)
3396 (if byte-compile--for-effect
3397 (setq byte-compile--for-effect nil)
3398 (inline (byte-compile-push-constant const))))
3400 ;; Use this for a constant that is not the value of its containing form.
3401 ;; This ignores byte-compile--for-effect.
3402 (defun byte-compile-push-constant (const)
3403 (when (symbolp const)
3404 (byte-compile-set-symbol-position const))
3405 (byte-compile-out 'byte-constant (byte-compile-get-constant const)))
3407 ;; Compile those primitive ordinary functions
3408 ;; which have special byte codes just for speed.
3410 (defmacro byte-defop-compiler (function &optional compile-handler)
3411 "Add a compiler-form for FUNCTION.
3412 If function is a symbol, then the variable \"byte-SYMBOL\" must name
3413 the opcode to be used. If function is a list, the first element
3414 is the function and the second element is the bytecode-symbol.
3415 The second element may be nil, meaning there is no opcode.
3416 COMPILE-HANDLER is the function to use to compile this byte-op, or
3417 may be the abbreviations 0, 1, 2, 3, 0-1, or 1-2.
3418 If it is nil, then the handler is \"byte-compile-SYMBOL.\""
3419 (let (opcode)
3420 (if (symbolp function)
3421 (setq opcode (intern (concat "byte-" (symbol-name function))))
3422 (setq opcode (car (cdr function))
3423 function (car function)))
3424 (let ((fnform
3425 (list 'put (list 'quote function) ''byte-compile
3426 (list 'quote
3427 (or (cdr (assq compile-handler
3428 '((0 . byte-compile-no-args)
3429 (1 . byte-compile-one-arg)
3430 (2 . byte-compile-two-args)
3431 (2-and . byte-compile-and-folded)
3432 (3 . byte-compile-three-args)
3433 (0-1 . byte-compile-zero-or-one-arg)
3434 (1-2 . byte-compile-one-or-two-args)
3435 (2-3 . byte-compile-two-or-three-args)
3437 compile-handler
3438 (intern (concat "byte-compile-"
3439 (symbol-name function))))))))
3440 (if opcode
3441 (list 'progn fnform
3442 (list 'put (list 'quote function)
3443 ''byte-opcode (list 'quote opcode))
3444 (list 'put (list 'quote opcode)
3445 ''byte-opcode-invert (list 'quote function)))
3446 fnform))))
3448 (defmacro byte-defop-compiler-1 (function &optional compile-handler)
3449 (list 'byte-defop-compiler (list function nil) compile-handler))
3452 (put 'byte-call 'byte-opcode-invert 'funcall)
3453 (put 'byte-list1 'byte-opcode-invert 'list)
3454 (put 'byte-list2 'byte-opcode-invert 'list)
3455 (put 'byte-list3 'byte-opcode-invert 'list)
3456 (put 'byte-list4 'byte-opcode-invert 'list)
3457 (put 'byte-listN 'byte-opcode-invert 'list)
3458 (put 'byte-concat2 'byte-opcode-invert 'concat)
3459 (put 'byte-concat3 'byte-opcode-invert 'concat)
3460 (put 'byte-concat4 'byte-opcode-invert 'concat)
3461 (put 'byte-concatN 'byte-opcode-invert 'concat)
3462 (put 'byte-insertN 'byte-opcode-invert 'insert)
3464 (byte-defop-compiler point 0)
3465 ;;(byte-defop-compiler mark 0) ;; obsolete
3466 (byte-defop-compiler point-max 0)
3467 (byte-defop-compiler point-min 0)
3468 (byte-defop-compiler following-char 0)
3469 (byte-defop-compiler preceding-char 0)
3470 (byte-defop-compiler current-column 0)
3471 (byte-defop-compiler eolp 0)
3472 (byte-defop-compiler eobp 0)
3473 (byte-defop-compiler bolp 0)
3474 (byte-defop-compiler bobp 0)
3475 (byte-defop-compiler current-buffer 0)
3476 ;;(byte-defop-compiler read-char 0) ;; obsolete
3477 ;; (byte-defop-compiler interactive-p 0) ;; Obsolete.
3478 (byte-defop-compiler widen 0)
3479 (byte-defop-compiler end-of-line 0-1)
3480 (byte-defop-compiler forward-char 0-1)
3481 (byte-defop-compiler forward-line 0-1)
3482 (byte-defop-compiler symbolp 1)
3483 (byte-defop-compiler consp 1)
3484 (byte-defop-compiler stringp 1)
3485 (byte-defop-compiler listp 1)
3486 (byte-defop-compiler not 1)
3487 (byte-defop-compiler (null byte-not) 1)
3488 (byte-defop-compiler car 1)
3489 (byte-defop-compiler cdr 1)
3490 (byte-defop-compiler length 1)
3491 (byte-defop-compiler symbol-value 1)
3492 (byte-defop-compiler symbol-function 1)
3493 (byte-defop-compiler (1+ byte-add1) 1)
3494 (byte-defop-compiler (1- byte-sub1) 1)
3495 (byte-defop-compiler goto-char 1)
3496 (byte-defop-compiler char-after 0-1)
3497 (byte-defop-compiler set-buffer 1)
3498 ;;(byte-defop-compiler set-mark 1) ;; obsolete
3499 (byte-defop-compiler forward-word 0-1)
3500 (byte-defop-compiler char-syntax 1)
3501 (byte-defop-compiler nreverse 1)
3502 (byte-defop-compiler car-safe 1)
3503 (byte-defop-compiler cdr-safe 1)
3504 (byte-defop-compiler numberp 1)
3505 (byte-defop-compiler integerp 1)
3506 (byte-defop-compiler skip-chars-forward 1-2)
3507 (byte-defop-compiler skip-chars-backward 1-2)
3508 (byte-defop-compiler eq 2)
3509 (byte-defop-compiler memq 2)
3510 (byte-defop-compiler cons 2)
3511 (byte-defop-compiler aref 2)
3512 (byte-defop-compiler set 2)
3513 (byte-defop-compiler (= byte-eqlsign) 2-and)
3514 (byte-defop-compiler (< byte-lss) 2-and)
3515 (byte-defop-compiler (> byte-gtr) 2-and)
3516 (byte-defop-compiler (<= byte-leq) 2-and)
3517 (byte-defop-compiler (>= byte-geq) 2-and)
3518 (byte-defop-compiler get 2)
3519 (byte-defop-compiler nth 2)
3520 (byte-defop-compiler substring 2-3)
3521 (byte-defop-compiler (move-marker byte-set-marker) 2-3)
3522 (byte-defop-compiler set-marker 2-3)
3523 (byte-defop-compiler match-beginning 1)
3524 (byte-defop-compiler match-end 1)
3525 (byte-defop-compiler upcase 1)
3526 (byte-defop-compiler downcase 1)
3527 (byte-defop-compiler string= 2)
3528 (byte-defop-compiler string< 2)
3529 (byte-defop-compiler (string-equal byte-string=) 2)
3530 (byte-defop-compiler (string-lessp byte-string<) 2)
3531 (byte-defop-compiler equal 2)
3532 (byte-defop-compiler nthcdr 2)
3533 (byte-defop-compiler elt 2)
3534 (byte-defop-compiler member 2)
3535 (byte-defop-compiler assq 2)
3536 (byte-defop-compiler (rplaca byte-setcar) 2)
3537 (byte-defop-compiler (rplacd byte-setcdr) 2)
3538 (byte-defop-compiler setcar 2)
3539 (byte-defop-compiler setcdr 2)
3540 (byte-defop-compiler buffer-substring 2)
3541 (byte-defop-compiler delete-region 2)
3542 (byte-defop-compiler narrow-to-region 2)
3543 (byte-defop-compiler (% byte-rem) 2)
3544 (byte-defop-compiler aset 3)
3546 (byte-defop-compiler max byte-compile-associative)
3547 (byte-defop-compiler min byte-compile-associative)
3548 (byte-defop-compiler (+ byte-plus) byte-compile-associative)
3549 (byte-defop-compiler (* byte-mult) byte-compile-associative)
3551 ;;####(byte-defop-compiler move-to-column 1)
3552 (byte-defop-compiler-1 interactive byte-compile-noop)
3555 (defun byte-compile-subr-wrong-args (form n)
3556 (byte-compile-set-symbol-position (car form))
3557 (byte-compile-warn "`%s' called with %d arg%s, but requires %s"
3558 (car form) (length (cdr form))
3559 (if (= 1 (length (cdr form))) "" "s") n)
3560 ;; Get run-time wrong-number-of-args error.
3561 (byte-compile-normal-call form))
3563 (defun byte-compile-no-args (form)
3564 (if (not (= (length form) 1))
3565 (byte-compile-subr-wrong-args form "none")
3566 (byte-compile-out (get (car form) 'byte-opcode) 0)))
3568 (defun byte-compile-one-arg (form)
3569 (if (not (= (length form) 2))
3570 (byte-compile-subr-wrong-args form 1)
3571 (byte-compile-form (car (cdr form))) ;; Push the argument
3572 (byte-compile-out (get (car form) 'byte-opcode) 0)))
3574 (defun byte-compile-two-args (form)
3575 (if (not (= (length form) 3))
3576 (byte-compile-subr-wrong-args form 2)
3577 (byte-compile-form (car (cdr form))) ;; Push the arguments
3578 (byte-compile-form (nth 2 form))
3579 (byte-compile-out (get (car form) 'byte-opcode) 0)))
3581 (defun byte-compile-and-folded (form)
3582 "Compile calls to functions like `<='.
3583 These implicitly `and' together a bunch of two-arg bytecodes."
3584 (let ((l (length form)))
3585 (cond
3586 ((< l 3) (byte-compile-form `(progn ,(nth 1 form) t)))
3587 ((= l 3) (byte-compile-two-args form))
3588 ((cl-every #'macroexp-copyable-p (nthcdr 2 form))
3589 (byte-compile-form `(and (,(car form) ,(nth 1 form) ,(nth 2 form))
3590 (,(car form) ,@(nthcdr 2 form)))))
3591 (t (byte-compile-normal-call form)))))
3593 (defun byte-compile-three-args (form)
3594 (if (not (= (length form) 4))
3595 (byte-compile-subr-wrong-args form 3)
3596 (byte-compile-form (car (cdr form))) ;; Push the arguments
3597 (byte-compile-form (nth 2 form))
3598 (byte-compile-form (nth 3 form))
3599 (byte-compile-out (get (car form) 'byte-opcode) 0)))
3601 (defun byte-compile-zero-or-one-arg (form)
3602 (let ((len (length form)))
3603 (cond ((= len 1) (byte-compile-one-arg (append form '(nil))))
3604 ((= len 2) (byte-compile-one-arg form))
3605 (t (byte-compile-subr-wrong-args form "0-1")))))
3607 (defun byte-compile-one-or-two-args (form)
3608 (let ((len (length form)))
3609 (cond ((= len 2) (byte-compile-two-args (append form '(nil))))
3610 ((= len 3) (byte-compile-two-args form))
3611 (t (byte-compile-subr-wrong-args form "1-2")))))
3613 (defun byte-compile-two-or-three-args (form)
3614 (let ((len (length form)))
3615 (cond ((= len 3) (byte-compile-three-args (append form '(nil))))
3616 ((= len 4) (byte-compile-three-args form))
3617 (t (byte-compile-subr-wrong-args form "2-3")))))
3619 (defun byte-compile-noop (_form)
3620 (byte-compile-constant nil))
3622 (defun byte-compile-discard (&optional num preserve-tos)
3623 "Output byte codes to discard the NUM entries at the top of the stack.
3624 NUM defaults to 1.
3625 If PRESERVE-TOS is non-nil, preserve the top-of-stack value, as if it were
3626 popped before discarding the num values, and then pushed back again after
3627 discarding."
3628 (if (and (null num) (not preserve-tos))
3629 ;; common case
3630 (byte-compile-out 'byte-discard)
3631 ;; general case
3632 (unless num
3633 (setq num 1))
3634 (when (and preserve-tos (> num 0))
3635 ;; Preserve the top-of-stack value by writing it directly to the stack
3636 ;; location which will be at the top-of-stack after popping.
3637 (byte-compile-stack-set (1- (- byte-compile-depth num)))
3638 ;; Now we actually discard one less value, since we want to keep
3639 ;; the eventual TOS
3640 (setq num (1- num)))
3641 (while (> num 0)
3642 (byte-compile-out 'byte-discard)
3643 (setq num (1- num)))))
3645 (defun byte-compile-stack-ref (stack-pos)
3646 "Output byte codes to push the value at stack position STACK-POS."
3647 (let ((dist (- byte-compile-depth (1+ stack-pos))))
3648 (if (zerop dist)
3649 ;; A simple optimization
3650 (byte-compile-out 'byte-dup)
3651 ;; normal case
3652 (byte-compile-out 'byte-stack-ref dist))))
3654 (defun byte-compile-stack-set (stack-pos)
3655 "Output byte codes to store the TOS value at stack position STACK-POS."
3656 (byte-compile-out 'byte-stack-set (- byte-compile-depth (1+ stack-pos))))
3658 (byte-defop-compiler-1 internal-make-closure byte-compile-make-closure)
3659 (byte-defop-compiler-1 internal-get-closed-var byte-compile-get-closed-var)
3661 (defun byte-compile-make-closure (form)
3662 "Byte-compile the special `internal-make-closure' form."
3663 (if byte-compile--for-effect (setq byte-compile--for-effect nil)
3664 (let* ((vars (nth 1 form))
3665 (env (nth 2 form))
3666 (docstring-exp (nth 3 form))
3667 (body (nthcdr 4 form))
3668 (fun
3669 (byte-compile-lambda `(lambda ,vars . ,body) nil (length env))))
3670 (cl-assert (or (> (length env) 0)
3671 docstring-exp)) ;Otherwise, we don't need a closure.
3672 (cl-assert (byte-code-function-p fun))
3673 (byte-compile-form `(make-byte-code
3674 ',(aref fun 0) ',(aref fun 1)
3675 (vconcat (vector . ,env) ',(aref fun 2))
3676 ,@(let ((rest (nthcdr 3 (mapcar (lambda (x) `',x) fun))))
3677 (if docstring-exp
3678 `(,(car rest)
3679 ,docstring-exp
3680 ,@(cddr rest))
3681 rest)))))))
3683 (defun byte-compile-get-closed-var (form)
3684 "Byte-compile the special `internal-get-closed-var' form."
3685 (if byte-compile--for-effect (setq byte-compile--for-effect nil)
3686 (byte-compile-out 'byte-constant (nth 1 form))))
3688 ;; Compile a function that accepts one or more args and is right-associative.
3689 ;; We do it by left-associativity so that the operations
3690 ;; are done in the same order as in interpreted code.
3691 ;; We treat the one-arg case, as in (+ x), like (+ x 0).
3692 ;; in order to convert markers to numbers, and trigger expected errors.
3693 (defun byte-compile-associative (form)
3694 (if (cdr form)
3695 (let ((opcode (get (car form) 'byte-opcode))
3696 args)
3697 (if (and (< 3 (length form))
3698 (memq opcode (list (get '+ 'byte-opcode)
3699 (get '* 'byte-opcode))))
3700 ;; Don't use binary operations for > 2 operands, as that
3701 ;; may cause overflow/truncation in float operations.
3702 (byte-compile-normal-call form)
3703 (setq args (copy-sequence (cdr form)))
3704 (byte-compile-form (car args))
3705 (setq args (cdr args))
3706 (or args (setq args '(0)
3707 opcode (get '+ 'byte-opcode)))
3708 (dolist (arg args)
3709 (byte-compile-form arg)
3710 (byte-compile-out opcode 0))))
3711 (byte-compile-constant (eval form))))
3714 ;; more complicated compiler macros
3716 (byte-defop-compiler char-before)
3717 (byte-defop-compiler backward-char)
3718 (byte-defop-compiler backward-word)
3719 (byte-defop-compiler list)
3720 (byte-defop-compiler concat)
3721 (byte-defop-compiler fset)
3722 (byte-defop-compiler (indent-to-column byte-indent-to) byte-compile-indent-to)
3723 (byte-defop-compiler indent-to)
3724 (byte-defop-compiler insert)
3725 (byte-defop-compiler-1 function byte-compile-function-form)
3726 (byte-defop-compiler-1 - byte-compile-minus)
3727 (byte-defop-compiler (/ byte-quo) byte-compile-quo)
3728 (byte-defop-compiler nconc)
3730 ;; Is this worth it? Both -before and -after are written in C.
3731 (defun byte-compile-char-before (form)
3732 (cond ((or (= 1 (length form))
3733 (and (= 2 (length form)) (not (nth 1 form))))
3734 (byte-compile-form '(char-after (1- (point)))))
3735 ((= 2 (length form))
3736 (byte-compile-form (list 'char-after (if (numberp (nth 1 form))
3737 (1- (nth 1 form))
3738 `(1- (or ,(nth 1 form)
3739 (point)))))))
3740 (t (byte-compile-subr-wrong-args form "0-1"))))
3742 ;; backward-... ==> forward-... with negated argument.
3743 ;; Is this worth it? Both -backward and -forward are written in C.
3744 (defun byte-compile-backward-char (form)
3745 (cond ((or (= 1 (length form))
3746 (and (= 2 (length form)) (not (nth 1 form))))
3747 (byte-compile-form '(forward-char -1)))
3748 ((= 2 (length form))
3749 (byte-compile-form (list 'forward-char (if (numberp (nth 1 form))
3750 (- (nth 1 form))
3751 `(- (or ,(nth 1 form) 1))))))
3752 (t (byte-compile-subr-wrong-args form "0-1"))))
3754 (defun byte-compile-backward-word (form)
3755 (cond ((or (= 1 (length form))
3756 (and (= 2 (length form)) (not (nth 1 form))))
3757 (byte-compile-form '(forward-word -1)))
3758 ((= 2 (length form))
3759 (byte-compile-form (list 'forward-word (if (numberp (nth 1 form))
3760 (- (nth 1 form))
3761 `(- (or ,(nth 1 form) 1))))))
3762 (t (byte-compile-subr-wrong-args form "0-1"))))
3764 (defun byte-compile-list (form)
3765 (let ((count (length (cdr form))))
3766 (cond ((= count 0)
3767 (byte-compile-constant nil))
3768 ((< count 5)
3769 (mapc 'byte-compile-form (cdr form))
3770 (byte-compile-out
3771 (aref [byte-list1 byte-list2 byte-list3 byte-list4] (1- count)) 0))
3772 ((< count 256)
3773 (mapc 'byte-compile-form (cdr form))
3774 (byte-compile-out 'byte-listN count))
3775 (t (byte-compile-normal-call form)))))
3777 (defun byte-compile-concat (form)
3778 (let ((count (length (cdr form))))
3779 (cond ((and (< 1 count) (< count 5))
3780 (mapc 'byte-compile-form (cdr form))
3781 (byte-compile-out
3782 (aref [byte-concat2 byte-concat3 byte-concat4] (- count 2))
3784 ;; Concat of one arg is not a no-op if arg is not a string.
3785 ((= count 0)
3786 (byte-compile-form ""))
3787 ((< count 256)
3788 (mapc 'byte-compile-form (cdr form))
3789 (byte-compile-out 'byte-concatN count))
3790 ((byte-compile-normal-call form)))))
3792 (defun byte-compile-minus (form)
3793 (let ((len (length form)))
3794 (cond
3795 ((= 1 len) (byte-compile-constant 0))
3796 ((= 2 len)
3797 (byte-compile-form (cadr form))
3798 (byte-compile-out 'byte-negate 0))
3799 ((= 3 len)
3800 (byte-compile-form (nth 1 form))
3801 (byte-compile-form (nth 2 form))
3802 (byte-compile-out 'byte-diff 0))
3803 ;; Don't use binary operations for > 2 operands, as that may
3804 ;; cause overflow/truncation in float operations.
3805 (t (byte-compile-normal-call form)))))
3807 (defun byte-compile-quo (form)
3808 (let ((len (length form)))
3809 (cond ((< len 2)
3810 (byte-compile-subr-wrong-args form "1 or more"))
3811 ((= len 3)
3812 (byte-compile-two-args form))
3814 ;; Don't use binary operations for > 2 operands, as that
3815 ;; may cause overflow/truncation in float operations.
3816 (byte-compile-normal-call form)))))
3818 (defun byte-compile-nconc (form)
3819 (let ((len (length form)))
3820 (cond ((= len 1)
3821 (byte-compile-constant nil))
3822 ((= len 2)
3823 ;; nconc of one arg is a noop, even if that arg isn't a list.
3824 (byte-compile-form (nth 1 form)))
3826 (byte-compile-form (car (setq form (cdr form))))
3827 (while (setq form (cdr form))
3828 (byte-compile-form (car form))
3829 (byte-compile-out 'byte-nconc 0))))))
3831 (defun byte-compile-fset (form)
3832 ;; warn about forms like (fset 'foo '(lambda () ...))
3833 ;; (where the lambda expression is non-trivial...)
3834 (let ((fn (nth 2 form))
3835 body)
3836 (if (and (eq (car-safe fn) 'quote)
3837 (eq (car-safe (setq fn (nth 1 fn))) 'lambda))
3838 (progn
3839 (setq body (cdr (cdr fn)))
3840 (if (stringp (car body)) (setq body (cdr body)))
3841 (if (eq 'interactive (car-safe (car body))) (setq body (cdr body)))
3842 (if (and (consp (car body))
3843 (not (eq 'byte-code (car (car body)))))
3844 (byte-compile-warn
3845 "A quoted lambda form is the second argument of `fset'. This is probably
3846 not what you want, as that lambda cannot be compiled. Consider using
3847 the syntax #'(lambda (...) ...) instead.")))))
3848 (byte-compile-two-args form))
3850 ;; (function foo) must compile like 'foo, not like (symbol-function 'foo).
3851 ;; Otherwise it will be incompatible with the interpreter,
3852 ;; and (funcall (function foo)) will lose with autoloads.
3854 (defun byte-compile-function-form (form)
3855 (let ((f (nth 1 form)))
3856 (when (and (symbolp f)
3857 (byte-compile-warning-enabled-p 'callargs))
3858 (byte-compile-function-warn f t (byte-compile-fdefinition f nil)))
3860 (byte-compile-constant (if (eq 'lambda (car-safe f))
3861 (byte-compile-lambda f)
3862 f))))
3864 (defun byte-compile-indent-to (form)
3865 (let ((len (length form)))
3866 (cond ((= len 2)
3867 (byte-compile-form (car (cdr form)))
3868 (byte-compile-out 'byte-indent-to 0))
3869 ((= len 3)
3870 ;; no opcode for 2-arg case.
3871 (byte-compile-normal-call form))
3873 (byte-compile-subr-wrong-args form "1-2")))))
3875 (defun byte-compile-insert (form)
3876 (cond ((null (cdr form))
3877 (byte-compile-constant nil))
3878 ((<= (length form) 256)
3879 (mapc 'byte-compile-form (cdr form))
3880 (if (cdr (cdr form))
3881 (byte-compile-out 'byte-insertN (length (cdr form)))
3882 (byte-compile-out 'byte-insert 0)))
3883 ((memq t (mapcar 'consp (cdr (cdr form))))
3884 (byte-compile-normal-call form))
3885 ;; We can split it; there is no function call after inserting 1st arg.
3887 (while (setq form (cdr form))
3888 (byte-compile-form (car form))
3889 (byte-compile-out 'byte-insert 0)
3890 (if (cdr form)
3891 (byte-compile-discard))))))
3894 (byte-defop-compiler-1 setq)
3895 (byte-defop-compiler-1 setq-default)
3896 (byte-defop-compiler-1 quote)
3898 (defun byte-compile-setq (form)
3899 (let* ((args (cdr form))
3900 (len (length args)))
3901 (if (= (logand len 1) 1)
3902 (progn
3903 (byte-compile-report-error
3904 (format-message
3905 "missing value for `%S' at end of setq" (car (last args))))
3906 (byte-compile-form
3907 `(signal 'wrong-number-of-arguments '(setq ,len))
3908 byte-compile--for-effect))
3909 (if args
3910 (while args
3911 (byte-compile-form (car (cdr args)))
3912 (or byte-compile--for-effect (cdr (cdr args))
3913 (byte-compile-out 'byte-dup 0))
3914 (byte-compile-variable-set (car args))
3915 (setq args (cdr (cdr args))))
3916 ;; (setq), with no arguments.
3917 (byte-compile-form nil byte-compile--for-effect)))
3918 (setq byte-compile--for-effect nil)))
3920 (defun byte-compile-setq-default (form)
3921 (setq form (cdr form))
3922 (if (null form) ; (setq-default), with no arguments
3923 (byte-compile-form nil byte-compile--for-effect)
3924 (if (> (length form) 2)
3925 (let ((setters ()))
3926 (while (consp form)
3927 (push `(setq-default ,(pop form) ,(pop form)) setters))
3928 (byte-compile-form (cons 'progn (nreverse setters))))
3929 (let ((var (car form)))
3930 (and (or (not (symbolp var))
3931 (macroexp--const-symbol-p var t))
3932 (byte-compile-warning-enabled-p 'constants)
3933 (byte-compile-warn
3934 "variable assignment to %s `%s'"
3935 (if (symbolp var) "constant" "nonvariable")
3936 (prin1-to-string var)))
3937 (byte-compile-normal-call `(set-default ',var ,@(cdr form)))))))
3939 (byte-defop-compiler-1 set-default)
3940 (defun byte-compile-set-default (form)
3941 (let ((varexp (car-safe (cdr-safe form))))
3942 (if (eq (car-safe varexp) 'quote)
3943 ;; If the varexp is constant, compile it as a setq-default
3944 ;; so we get more warnings.
3945 (byte-compile-setq-default `(setq-default ,(car-safe (cdr varexp))
3946 ,@(cddr form)))
3947 (byte-compile-normal-call form))))
3949 (defun byte-compile-quote (form)
3950 (byte-compile-constant (car (cdr form))))
3952 ;;; control structures
3954 (defun byte-compile-body (body &optional for-effect)
3955 (while (cdr body)
3956 (byte-compile-form (car body) t)
3957 (setq body (cdr body)))
3958 (byte-compile-form (car body) for-effect))
3960 (defsubst byte-compile-body-do-effect (body)
3961 (byte-compile-body body byte-compile--for-effect)
3962 (setq byte-compile--for-effect nil))
3964 (defsubst byte-compile-form-do-effect (form)
3965 (byte-compile-form form byte-compile--for-effect)
3966 (setq byte-compile--for-effect nil))
3968 (byte-defop-compiler-1 inline byte-compile-progn)
3969 (byte-defop-compiler-1 progn)
3970 (byte-defop-compiler-1 prog1)
3971 (byte-defop-compiler-1 prog2)
3972 (byte-defop-compiler-1 if)
3973 (byte-defop-compiler-1 cond)
3974 (byte-defop-compiler-1 and)
3975 (byte-defop-compiler-1 or)
3976 (byte-defop-compiler-1 while)
3977 (byte-defop-compiler-1 funcall)
3978 (byte-defop-compiler-1 let)
3979 (byte-defop-compiler-1 let* byte-compile-let)
3981 (defun byte-compile-progn (form)
3982 (byte-compile-body-do-effect (cdr form)))
3984 (defun byte-compile-prog1 (form)
3985 (byte-compile-form-do-effect (car (cdr form)))
3986 (byte-compile-body (cdr (cdr form)) t))
3988 (defun byte-compile-prog2 (form)
3989 (byte-compile-form (nth 1 form) t)
3990 (byte-compile-form-do-effect (nth 2 form))
3991 (byte-compile-body (cdr (cdr (cdr form))) t))
3993 (defmacro byte-compile-goto-if (cond discard tag)
3994 `(byte-compile-goto
3995 (if ,cond
3996 (if ,discard 'byte-goto-if-not-nil 'byte-goto-if-not-nil-else-pop)
3997 (if ,discard 'byte-goto-if-nil 'byte-goto-if-nil-else-pop))
3998 ,tag))
4000 ;; Return the list of items in CONDITION-PARAM that match PRED-LIST.
4001 ;; Only return items that are not in ONLY-IF-NOT-PRESENT.
4002 (defun byte-compile-find-bound-condition (condition-param
4003 pred-list
4004 &optional only-if-not-present)
4005 (let ((result nil)
4006 (nth-one nil)
4007 (cond-list
4008 (if (memq (car-safe condition-param) pred-list)
4009 ;; The condition appears by itself.
4010 (list condition-param)
4011 ;; If the condition is an `and', look for matches among the
4012 ;; `and' arguments.
4013 (when (eq 'and (car-safe condition-param))
4014 (cdr condition-param)))))
4016 (dolist (crt cond-list)
4017 (when (and (memq (car-safe crt) pred-list)
4018 (eq 'quote (car-safe (setq nth-one (nth 1 crt))))
4019 ;; Ignore if the symbol is already on the unresolved
4020 ;; list.
4021 (not (assq (nth 1 nth-one) ; the relevant symbol
4022 only-if-not-present)))
4023 (push (nth 1 (nth 1 crt)) result)))
4024 result))
4026 (defmacro byte-compile-maybe-guarded (condition &rest body)
4027 "Execute forms in BODY, potentially guarded by CONDITION.
4028 CONDITION is a variable whose value is a test in an `if' or `cond'.
4029 BODY is the code to compile in the first arm of the if or the body of
4030 the cond clause. If CONDITION's value is of the form (fboundp \\='foo)
4031 or (boundp \\='foo), the relevant warnings from BODY about foo's
4032 being undefined (or obsolete) will be suppressed.
4034 If CONDITION's value is (not (featurep \\='emacs)) or (featurep \\='xemacs),
4035 that suppresses all warnings during execution of BODY."
4036 (declare (indent 1) (debug t))
4037 `(let* ((fbound-list (byte-compile-find-bound-condition
4038 ,condition '(fboundp functionp)
4039 byte-compile-unresolved-functions))
4040 (bound-list (byte-compile-find-bound-condition
4041 ,condition '(boundp default-boundp)))
4042 ;; Maybe add to the bound list.
4043 (byte-compile-bound-variables
4044 (append bound-list byte-compile-bound-variables)))
4045 (unwind-protect
4046 ;; If things not being bound at all is ok, so must them being
4047 ;; obsolete. Note that we add to the existing lists since Tramp
4048 ;; (ab)uses this feature.
4049 ;; FIXME: If `foo' is obsoleted by `bar', the code below
4050 ;; correctly arranges to silence the warnings after testing
4051 ;; existence of `foo', but the warning should also be
4052 ;; silenced after testing the existence of `bar'.
4053 (let ((byte-compile-not-obsolete-vars
4054 (append byte-compile-not-obsolete-vars bound-list))
4055 (byte-compile-not-obsolete-funcs
4056 (append byte-compile-not-obsolete-funcs fbound-list)))
4057 ,@body)
4058 ;; Maybe remove the function symbol from the unresolved list.
4059 (dolist (fbound fbound-list)
4060 (when fbound
4061 (setq byte-compile-unresolved-functions
4062 (delq (assq fbound byte-compile-unresolved-functions)
4063 byte-compile-unresolved-functions)))))))
4065 (defun byte-compile-if (form)
4066 (byte-compile-form (car (cdr form)))
4067 ;; Check whether we have `(if (fboundp ...' or `(if (boundp ...'
4068 ;; and avoid warnings about the relevant symbols in the consequent.
4069 (let ((clause (nth 1 form))
4070 (donetag (byte-compile-make-tag)))
4071 (if (null (nthcdr 3 form))
4072 ;; No else-forms
4073 (progn
4074 (byte-compile-goto-if nil byte-compile--for-effect donetag)
4075 (byte-compile-maybe-guarded clause
4076 (byte-compile-form (nth 2 form) byte-compile--for-effect))
4077 (byte-compile-out-tag donetag))
4078 (let ((elsetag (byte-compile-make-tag)))
4079 (byte-compile-goto 'byte-goto-if-nil elsetag)
4080 (byte-compile-maybe-guarded clause
4081 (byte-compile-form (nth 2 form) byte-compile--for-effect))
4082 (byte-compile-goto 'byte-goto donetag)
4083 (byte-compile-out-tag elsetag)
4084 (byte-compile-maybe-guarded (list 'not clause)
4085 (byte-compile-body (cdr (cdr (cdr form))) byte-compile--for-effect))
4086 (byte-compile-out-tag donetag))))
4087 (setq byte-compile--for-effect nil))
4089 (defun byte-compile-cond-vars (obj1 obj2)
4090 ;; We make sure that of OBJ1 and OBJ2, one of them is a symbol,
4091 ;; and the other is a constant expression whose value can be
4092 ;; compared with `eq' (with `macroexp-const-p').
4094 (and (symbolp obj1) (macroexp-const-p obj2) (cons obj1 obj2))
4095 (and (symbolp obj2) (macroexp-const-p obj1) (cons obj2 obj1))))
4097 (defun byte-compile-cond-jump-table-info (clauses)
4098 "If CLAUSES is a `cond' form where:
4099 The condition for each clause is of the form (TEST VAR VALUE).
4100 VAR is a variable.
4101 TEST and VAR are the same throughout all conditions.
4102 VALUE satisfies `macroexp-const-p'.
4104 Return a list of the form ((TEST . VAR) ((VALUE BODY) ...))"
4105 (let ((cases '())
4106 (ok t)
4107 prev-var prev-test)
4108 (and (catch 'break
4109 (dolist (clause (cdr clauses) ok)
4110 (let* ((condition (car clause))
4111 (test (car-safe condition))
4112 (vars (when (consp condition)
4113 (byte-compile-cond-vars (cadr condition) (cl-caddr condition))))
4114 (obj1 (car-safe vars))
4115 (obj2 (cdr-safe vars))
4116 (body (cdr-safe clause)))
4117 (unless prev-var
4118 (setq prev-var obj1))
4119 (unless prev-test
4120 (setq prev-test test))
4121 (if (and obj1 (memq test '(eq eql equal))
4122 (consp condition)
4123 (eq test prev-test)
4124 (eq obj1 prev-var)
4125 ;; discard duplicate clauses
4126 (not (assq obj2 cases)))
4127 (push (list (if (consp obj2) (eval obj2) obj2) body) cases)
4128 (if (and (macroexp-const-p condition) condition)
4129 (progn (push (list 'default (or body `(,condition))) cases)
4130 (throw 'break t))
4131 (setq ok nil)
4132 (throw 'break nil))))))
4133 (list (cons prev-test prev-var) (nreverse cases)))))
4135 (defun byte-compile-cond-jump-table (clauses)
4136 (let* ((table-info (byte-compile-cond-jump-table-info clauses))
4137 (test (caar table-info))
4138 (var (cdar table-info))
4139 (cases (cadr table-info))
4140 jump-table test-obj body tag donetag default-tag default-case)
4141 (when (and cases (not (= (length cases) 1)))
4142 ;; TODO: Once :linear-search is implemented for `make-hash-table'
4143 ;; set it to `t' for cond forms with a small number of cases.
4144 (setq jump-table (make-hash-table :test test
4145 :purecopy t
4146 :size (if (assq 'default cases)
4147 (1- (length cases))
4148 (length cases)))
4149 default-tag (byte-compile-make-tag)
4150 donetag (byte-compile-make-tag))
4151 ;; The structure of byte-switch code:
4153 ;; varref var
4154 ;; constant #s(hash-table purecopy t data (val1 (TAG1) val2 (TAG2)))
4155 ;; switch
4156 ;; goto DEFAULT-TAG
4157 ;; TAG1
4158 ;; <clause body>
4159 ;; goto DONETAG
4160 ;; TAG2
4161 ;; <clause body>
4162 ;; goto DONETAG
4163 ;; DEFAULT-TAG
4164 ;; <body for `t' clause, if any (else `constant nil')>
4165 ;; DONETAG
4167 (byte-compile-variable-ref var)
4168 (byte-compile-push-constant jump-table)
4169 (byte-compile-out 'byte-switch)
4171 ;; When the opcode argument is `byte-goto', `byte-compile-goto' sets
4172 ;; `byte-compile-depth' to `nil'. However, we need `byte-compile-depth'
4173 ;; to be non-nil for generating tags for all cases. Since
4174 ;; `byte-compile-depth' will increase by at most 1 after compiling
4175 ;; all of the clause (which is further enforced by cl-assert below)
4176 ;; it should be safe to preserve its value.
4177 (let ((byte-compile-depth byte-compile-depth))
4178 (byte-compile-goto 'byte-goto default-tag))
4180 (when (assq 'default cases)
4181 (setq default-case (cadr (assq 'default cases))
4182 cases (butlast cases 1)))
4184 (dolist (case cases)
4185 (setq tag (byte-compile-make-tag)
4186 test-obj (nth 0 case)
4187 body (nth 1 case))
4188 (byte-compile-out-tag tag)
4189 (puthash test-obj tag jump-table)
4191 (let ((byte-compile-depth byte-compile-depth)
4192 (init-depth byte-compile-depth))
4193 ;; Since `byte-compile-body' might increase `byte-compile-depth'
4194 ;; by 1, not preserving its value will cause it to potentially
4195 ;; increase by one for every clause body compiled, causing
4196 ;; depth/tag conflicts or violating asserts down the road.
4197 ;; To make sure `byte-compile-body' itself doesn't violate this,
4198 ;; we use `cl-assert'.
4199 (if (null body)
4200 (byte-compile-form t byte-compile--for-effect)
4201 (byte-compile-body body byte-compile--for-effect))
4202 (cl-assert (or (= byte-compile-depth init-depth)
4203 (= byte-compile-depth (1+ init-depth))))
4204 (byte-compile-goto 'byte-goto donetag)
4205 (setcdr (cdr donetag) nil)))
4207 (byte-compile-out-tag default-tag)
4208 (if default-case
4209 (byte-compile-body-do-effect default-case)
4210 (byte-compile-constant nil))
4211 (byte-compile-out-tag donetag)
4212 (push jump-table byte-compile-jump-tables))))
4214 (defun byte-compile-cond (clauses)
4215 (or (and byte-compile-cond-use-jump-table
4216 (byte-compile-cond-jump-table clauses))
4217 (let ((donetag (byte-compile-make-tag))
4218 nexttag clause)
4219 (while (setq clauses (cdr clauses))
4220 (setq clause (car clauses))
4221 (cond ((or (eq (car clause) t)
4222 (and (eq (car-safe (car clause)) 'quote)
4223 (car-safe (cdr-safe (car clause)))))
4224 ;; Unconditional clause
4225 (setq clause (cons t clause)
4226 clauses nil))
4227 ((cdr clauses)
4228 (byte-compile-form (car clause))
4229 (if (null (cdr clause))
4230 ;; First clause is a singleton.
4231 (byte-compile-goto-if t byte-compile--for-effect donetag)
4232 (setq nexttag (byte-compile-make-tag))
4233 (byte-compile-goto 'byte-goto-if-nil nexttag)
4234 (byte-compile-maybe-guarded (car clause)
4235 (byte-compile-body (cdr clause) byte-compile--for-effect))
4236 (byte-compile-goto 'byte-goto donetag)
4237 (byte-compile-out-tag nexttag)))))
4238 ;; Last clause
4239 (let ((guard (car clause)))
4240 (and (cdr clause) (not (eq guard t))
4241 (progn (byte-compile-form guard)
4242 (byte-compile-goto-if nil byte-compile--for-effect donetag)
4243 (setq clause (cdr clause))))
4244 (byte-compile-maybe-guarded guard
4245 (byte-compile-body-do-effect clause)))
4246 (byte-compile-out-tag donetag))))
4248 (defun byte-compile-and (form)
4249 (let ((failtag (byte-compile-make-tag))
4250 (args (cdr form)))
4251 (if (null args)
4252 (byte-compile-form-do-effect t)
4253 (byte-compile-and-recursion args failtag))))
4255 ;; Handle compilation of a nontrivial `and' call.
4256 ;; We use tail recursion so we can use byte-compile-maybe-guarded.
4257 (defun byte-compile-and-recursion (rest failtag)
4258 (if (cdr rest)
4259 (progn
4260 (byte-compile-form (car rest))
4261 (byte-compile-goto-if nil byte-compile--for-effect failtag)
4262 (byte-compile-maybe-guarded (car rest)
4263 (byte-compile-and-recursion (cdr rest) failtag)))
4264 (byte-compile-form-do-effect (car rest))
4265 (byte-compile-out-tag failtag)))
4267 (defun byte-compile-or (form)
4268 (let ((wintag (byte-compile-make-tag))
4269 (args (cdr form)))
4270 (if (null args)
4271 (byte-compile-form-do-effect nil)
4272 (byte-compile-or-recursion args wintag))))
4274 ;; Handle compilation of a nontrivial `or' call.
4275 ;; We use tail recursion so we can use byte-compile-maybe-guarded.
4276 (defun byte-compile-or-recursion (rest wintag)
4277 (if (cdr rest)
4278 (progn
4279 (byte-compile-form (car rest))
4280 (byte-compile-goto-if t byte-compile--for-effect wintag)
4281 (byte-compile-maybe-guarded (list 'not (car rest))
4282 (byte-compile-or-recursion (cdr rest) wintag)))
4283 (byte-compile-form-do-effect (car rest))
4284 (byte-compile-out-tag wintag)))
4286 (defun byte-compile-while (form)
4287 (let ((endtag (byte-compile-make-tag))
4288 (looptag (byte-compile-make-tag)))
4289 (byte-compile-out-tag looptag)
4290 (byte-compile-form (car (cdr form)))
4291 (byte-compile-goto-if nil byte-compile--for-effect endtag)
4292 (byte-compile-body (cdr (cdr form)) t)
4293 (byte-compile-goto 'byte-goto looptag)
4294 (byte-compile-out-tag endtag)
4295 (setq byte-compile--for-effect nil)))
4297 (defun byte-compile-funcall (form)
4298 (if (cdr form)
4299 (progn
4300 (mapc 'byte-compile-form (cdr form))
4301 (byte-compile-out 'byte-call (length (cdr (cdr form)))))
4302 (byte-compile-report-error
4303 (format-message "`funcall' called with no arguments"))
4304 (byte-compile-form '(signal 'wrong-number-of-arguments '(funcall 0))
4305 byte-compile--for-effect)))
4308 ;; let binding
4310 (defun byte-compile-push-binding-init (clause)
4311 "Emit byte-codes to push the initialization value for CLAUSE on the stack.
4312 Return the offset in the form (VAR . OFFSET)."
4313 (let* ((var (if (consp clause) (car clause) clause)))
4314 ;; We record the stack position even of dynamic bindings; we'll put
4315 ;; them in the proper place later.
4316 (prog1 (cons var byte-compile-depth)
4317 (if (consp clause)
4318 (byte-compile-form (cadr clause))
4319 (byte-compile-push-constant nil)))))
4321 (defun byte-compile-not-lexical-var-p (var)
4322 (or (not (symbolp var))
4323 (special-variable-p var)
4324 (memq var byte-compile-bound-variables)
4325 (memq var '(nil t))
4326 (keywordp var)))
4328 (defun byte-compile-bind (var init-lexenv)
4329 "Emit byte-codes to bind VAR and update `byte-compile--lexical-environment'.
4330 INIT-LEXENV should be a lexical-environment alist describing the
4331 positions of the init value that have been pushed on the stack.
4332 Return non-nil if the TOS value was popped."
4333 ;; The mix of lexical and dynamic bindings mean that we may have to
4334 ;; juggle things on the stack, to move them to TOS for
4335 ;; dynamic binding.
4336 (if (and lexical-binding (not (byte-compile-not-lexical-var-p var)))
4337 ;; VAR is a simple stack-allocated lexical variable.
4338 (progn (push (assq var init-lexenv)
4339 byte-compile--lexical-environment)
4340 nil)
4341 ;; VAR should be dynamically bound.
4342 (while (assq var byte-compile--lexical-environment)
4343 ;; This dynamic binding shadows a lexical binding.
4344 (setq byte-compile--lexical-environment
4345 (remq (assq var byte-compile--lexical-environment)
4346 byte-compile--lexical-environment)))
4347 (cond
4348 ((eq var (caar init-lexenv))
4349 ;; VAR is dynamic and is on the top of the
4350 ;; stack, so we can just bind it like usual.
4351 (byte-compile-dynamic-variable-bind var)
4354 ;; VAR is dynamic, but we have to get its
4355 ;; value out of the middle of the stack.
4356 (let ((stack-pos (cdr (assq var init-lexenv))))
4357 (byte-compile-stack-ref stack-pos)
4358 (byte-compile-dynamic-variable-bind var)
4359 ;; Now we have to store nil into its temporary
4360 ;; stack position so it doesn't prevent the value from being GC'd.
4361 ;; FIXME: Not worth the trouble.
4362 ;; (byte-compile-push-constant nil)
4363 ;; (byte-compile-stack-set stack-pos)
4365 nil))))
4367 (defun byte-compile-unbind (clauses init-lexenv preserve-body-value)
4368 "Emit byte-codes to unbind the variables bound by CLAUSES.
4369 CLAUSES is a `let'-style variable binding list. INIT-LEXENV should be a
4370 lexical-environment alist describing the positions of the init value that
4371 have been pushed on the stack. If PRESERVE-BODY-VALUE is true,
4372 then an additional value on the top of the stack, above any lexical binding
4373 slots, is preserved, so it will be on the top of the stack after all
4374 binding slots have been popped."
4375 ;; Unbind dynamic variables.
4376 (let ((num-dynamic-bindings 0))
4377 (dolist (clause clauses)
4378 (unless (assq (if (consp clause) (car clause) clause)
4379 byte-compile--lexical-environment)
4380 (setq num-dynamic-bindings (1+ num-dynamic-bindings))))
4381 (unless (zerop num-dynamic-bindings)
4382 (byte-compile-out 'byte-unbind num-dynamic-bindings)))
4383 ;; Pop lexical variables off the stack, possibly preserving the
4384 ;; return value of the body.
4385 (when init-lexenv
4386 ;; INIT-LEXENV contains all init values left on the stack.
4387 (byte-compile-discard (length init-lexenv) preserve-body-value)))
4389 (defun byte-compile-let (form)
4390 "Generate code for the `let' or `let*' form FORM."
4391 (let ((clauses (cadr form))
4392 (init-lexenv nil)
4393 (is-let (eq (car form) 'let)))
4394 (when is-let
4395 ;; First compute the binding values in the old scope.
4396 (dolist (var clauses)
4397 (push (byte-compile-push-binding-init var) init-lexenv)))
4398 ;; New scope.
4399 (let ((byte-compile-bound-variables byte-compile-bound-variables)
4400 (byte-compile--lexical-environment
4401 byte-compile--lexical-environment))
4402 ;; Bind the variables.
4403 ;; For `let', do it in reverse order, because it makes no
4404 ;; semantic difference, but it is a lot more efficient since the
4405 ;; values are now in reverse order on the stack.
4406 (dolist (var (if is-let (reverse clauses) clauses))
4407 (unless is-let
4408 (push (byte-compile-push-binding-init var) init-lexenv))
4409 (let ((var (if (consp var) (car var) var)))
4410 (if (byte-compile-bind var init-lexenv)
4411 (pop init-lexenv))))
4412 ;; Emit the body.
4413 (let ((init-stack-depth byte-compile-depth))
4414 (byte-compile-body-do-effect (cdr (cdr form)))
4415 ;; Unbind both lexical and dynamic variables.
4416 (cl-assert (or (eq byte-compile-depth init-stack-depth)
4417 (eq byte-compile-depth (1+ init-stack-depth))))
4418 (byte-compile-unbind clauses init-lexenv
4419 (> byte-compile-depth init-stack-depth))))))
4423 (byte-defop-compiler-1 /= byte-compile-negated)
4424 (byte-defop-compiler-1 atom byte-compile-negated)
4425 (byte-defop-compiler-1 nlistp byte-compile-negated)
4427 (put '/= 'byte-compile-negated-op '=)
4428 (put 'atom 'byte-compile-negated-op 'consp)
4429 (put 'nlistp 'byte-compile-negated-op 'listp)
4431 (defun byte-compile-negated (form)
4432 (byte-compile-form-do-effect (byte-compile-negation-optimizer form)))
4434 ;; Even when optimization is off, /= is optimized to (not (= ...)).
4435 (defun byte-compile-negation-optimizer (form)
4436 ;; an optimizer for forms where <form1> is less efficient than (not <form2>)
4437 (byte-compile-set-symbol-position (car form))
4438 (list 'not
4439 (cons (or (get (car form) 'byte-compile-negated-op)
4440 (error
4441 "Compiler error: `%s' has no `byte-compile-negated-op' property"
4442 (car form)))
4443 (cdr form))))
4445 ;;; other tricky macro-like special-forms
4447 (byte-defop-compiler-1 catch)
4448 (byte-defop-compiler-1 unwind-protect)
4449 (byte-defop-compiler-1 condition-case)
4450 (byte-defop-compiler-1 save-excursion)
4451 (byte-defop-compiler-1 save-current-buffer)
4452 (byte-defop-compiler-1 save-restriction)
4453 ;; (byte-defop-compiler-1 save-window-excursion) ;Obsolete: now a macro.
4454 ;; (byte-defop-compiler-1 with-output-to-temp-buffer) ;Obsolete: now a macro.
4456 (defvar byte-compile--use-old-handlers nil
4457 "If nil, use new byte codes introduced in Emacs-24.4.")
4459 (defun byte-compile-catch (form)
4460 (byte-compile-form (car (cdr form)))
4461 (if (not byte-compile--use-old-handlers)
4462 (let ((endtag (byte-compile-make-tag)))
4463 (byte-compile-goto 'byte-pushcatch endtag)
4464 (byte-compile-body (cddr form) nil)
4465 (byte-compile-out 'byte-pophandler)
4466 (byte-compile-out-tag endtag))
4467 (pcase (cddr form)
4468 (`(:fun-body ,f)
4469 (byte-compile-form `(list 'funcall ,f)))
4470 (body
4471 (byte-compile-push-constant
4472 (byte-compile-top-level (cons 'progn body) byte-compile--for-effect))))
4473 (byte-compile-out 'byte-catch 0)))
4475 (defun byte-compile-unwind-protect (form)
4476 (pcase (cddr form)
4477 (`(:fun-body ,f)
4478 (byte-compile-form
4479 (if byte-compile--use-old-handlers `(list (list 'funcall ,f)) f)))
4480 (handlers
4481 (if byte-compile--use-old-handlers
4482 (byte-compile-push-constant
4483 (byte-compile-top-level-body handlers t))
4484 (byte-compile-form `#'(lambda () ,@handlers)))))
4485 (byte-compile-out 'byte-unwind-protect 0)
4486 (byte-compile-form-do-effect (car (cdr form)))
4487 (byte-compile-out 'byte-unbind 1))
4489 (defun byte-compile-condition-case (form)
4490 (if byte-compile--use-old-handlers
4491 (byte-compile-condition-case--old form)
4492 (byte-compile-condition-case--new form)))
4494 (defun byte-compile-condition-case--old (form)
4495 (let* ((var (nth 1 form))
4496 (fun-bodies (eq var :fun-body))
4497 (byte-compile-bound-variables
4498 (if (and var (not fun-bodies))
4499 (cons var byte-compile-bound-variables)
4500 byte-compile-bound-variables)))
4501 (byte-compile-set-symbol-position 'condition-case)
4502 (unless (symbolp var)
4503 (byte-compile-warn
4504 "`%s' is not a variable-name or nil (in condition-case)" var))
4505 (if fun-bodies (setq var (make-symbol "err")))
4506 (byte-compile-push-constant var)
4507 (if fun-bodies
4508 (byte-compile-form `(list 'funcall ,(nth 2 form)))
4509 (byte-compile-push-constant
4510 (byte-compile-top-level (nth 2 form) byte-compile--for-effect)))
4511 (let ((compiled-clauses
4512 (mapcar
4513 (lambda (clause)
4514 (let ((condition (car clause)))
4515 (cond ((not (or (symbolp condition)
4516 (and (listp condition)
4517 (let ((ok t))
4518 (dolist (sym condition)
4519 (if (not (symbolp sym))
4520 (setq ok nil)))
4521 ok))))
4522 (byte-compile-warn
4523 "`%S' is not a condition name or list of such (in condition-case)"
4524 condition))
4525 ;; (not (or (eq condition 't)
4526 ;; (and (stringp (get condition 'error-message))
4527 ;; (consp (get condition
4528 ;; 'error-conditions)))))
4529 ;; (byte-compile-warn
4530 ;; "`%s' is not a known condition name
4531 ;; (in condition-case)"
4532 ;; condition))
4534 (if fun-bodies
4535 `(list ',condition (list 'funcall ,(cadr clause) ',var))
4536 (cons condition
4537 (byte-compile-top-level-body
4538 (cdr clause) byte-compile--for-effect)))))
4539 (cdr (cdr (cdr form))))))
4540 (if fun-bodies
4541 (byte-compile-form `(list ,@compiled-clauses))
4542 (byte-compile-push-constant compiled-clauses)))
4543 (byte-compile-out 'byte-condition-case 0)))
4545 (defun byte-compile-condition-case--new (form)
4546 (let* ((var (nth 1 form))
4547 (body (nth 2 form))
4548 (depth byte-compile-depth)
4549 (clauses (mapcar (lambda (clause)
4550 (cons (byte-compile-make-tag) clause))
4551 (nthcdr 3 form)))
4552 (endtag (byte-compile-make-tag)))
4553 (byte-compile-set-symbol-position 'condition-case)
4554 (unless (symbolp var)
4555 (byte-compile-warn
4556 "`%s' is not a variable-name or nil (in condition-case)" var))
4558 (dolist (clause (reverse clauses))
4559 (let ((condition (nth 1 clause)))
4560 (unless (consp condition) (setq condition (list condition)))
4561 (dolist (c condition)
4562 (unless (and c (symbolp c))
4563 (byte-compile-warn
4564 "`%S' is not a condition name (in condition-case)" c))
4565 ;; In reality, the `error-conditions' property is only required
4566 ;; for the argument to `signal', not to `condition-case'.
4567 ;;(unless (consp (get c 'error-conditions))
4568 ;; (byte-compile-warn
4569 ;; "`%s' is not a known condition name (in condition-case)"
4570 ;; c))
4572 (byte-compile-push-constant condition))
4573 (byte-compile-goto 'byte-pushconditioncase (car clause)))
4575 (byte-compile-form body) ;; byte-compile--for-effect
4576 (dolist (_ clauses) (byte-compile-out 'byte-pophandler))
4577 (byte-compile-goto 'byte-goto endtag)
4579 (while clauses
4580 (let ((clause (pop clauses))
4581 (byte-compile-bound-variables byte-compile-bound-variables)
4582 (byte-compile--lexical-environment
4583 byte-compile--lexical-environment))
4584 (setq byte-compile-depth (1+ depth))
4585 (byte-compile-out-tag (pop clause))
4586 (dolist (_ clauses) (byte-compile-out 'byte-pophandler))
4587 (cond
4588 ((null var) (byte-compile-discard))
4589 (lexical-binding
4590 (push (cons var (1- byte-compile-depth))
4591 byte-compile--lexical-environment))
4592 (t (byte-compile-dynamic-variable-bind var)))
4593 (byte-compile-body (cdr clause)) ;; byte-compile--for-effect
4594 (cond
4595 ((null var) nil)
4596 (lexical-binding (byte-compile-discard 1 'preserve-tos))
4597 (t (byte-compile-out 'byte-unbind 1)))
4598 (byte-compile-goto 'byte-goto endtag)))
4600 (byte-compile-out-tag endtag)))
4602 (defun byte-compile-save-excursion (form)
4603 (if (and (eq 'set-buffer (car-safe (car-safe (cdr form))))
4604 (byte-compile-warning-enabled-p 'suspicious))
4605 (byte-compile-warn
4606 "Use `with-current-buffer' rather than save-excursion+set-buffer"))
4607 (byte-compile-out 'byte-save-excursion 0)
4608 (byte-compile-body-do-effect (cdr form))
4609 (byte-compile-out 'byte-unbind 1))
4611 (defun byte-compile-save-restriction (form)
4612 (byte-compile-out 'byte-save-restriction 0)
4613 (byte-compile-body-do-effect (cdr form))
4614 (byte-compile-out 'byte-unbind 1))
4616 (defun byte-compile-save-current-buffer (form)
4617 (byte-compile-out 'byte-save-current-buffer 0)
4618 (byte-compile-body-do-effect (cdr form))
4619 (byte-compile-out 'byte-unbind 1))
4621 ;;; top-level forms elsewhere
4623 (byte-defop-compiler-1 defvar)
4624 (byte-defop-compiler-1 defconst byte-compile-defvar)
4625 (byte-defop-compiler-1 autoload)
4626 (byte-defop-compiler-1 lambda byte-compile-lambda-form)
4628 ;; If foo.el declares `toto' as obsolete, it is likely that foo.el will
4629 ;; actually use `toto' in order for this obsolete variable to still work
4630 ;; correctly, so paradoxically, while byte-compiling foo.el, the presence
4631 ;; of a make-obsolete-variable call for `toto' is an indication that `toto'
4632 ;; should not trigger obsolete-warnings in foo.el.
4633 (byte-defop-compiler-1 make-obsolete-variable)
4634 (defun byte-compile-make-obsolete-variable (form)
4635 (when (eq 'quote (car-safe (nth 1 form)))
4636 (push (nth 1 (nth 1 form)) byte-compile-global-not-obsolete-vars))
4637 (byte-compile-normal-call form))
4639 (defconst byte-compile-tmp-var (make-symbol "def-tmp-var"))
4641 (defun byte-compile-defvar (form)
4642 ;; This is not used for file-level defvar/consts.
4643 (when (and (symbolp (nth 1 form))
4644 (not (string-match "[-*/:$]" (symbol-name (nth 1 form))))
4645 (byte-compile-warning-enabled-p 'lexical))
4646 (byte-compile-warn "global/dynamic var `%s' lacks a prefix"
4647 (nth 1 form)))
4648 (let ((fun (nth 0 form))
4649 (var (nth 1 form))
4650 (value (nth 2 form))
4651 (string (nth 3 form)))
4652 (byte-compile-set-symbol-position fun)
4653 (when (or (> (length form) 4)
4654 (and (eq fun 'defconst) (null (cddr form))))
4655 (let ((ncall (length (cdr form))))
4656 (byte-compile-warn
4657 "`%s' called with %d argument%s, but %s %s"
4658 fun ncall
4659 (if (= 1 ncall) "" "s")
4660 (if (< ncall 2) "requires" "accepts only")
4661 "2-3")))
4662 (push var byte-compile-bound-variables)
4663 (if (eq fun 'defconst)
4664 (push var byte-compile-const-variables))
4665 (when (and string (not (stringp string)))
4666 (byte-compile-warn "third arg to `%s %s' is not a string: %s"
4667 fun var string))
4668 (byte-compile-form-do-effect
4669 (if (cddr form) ; `value' provided
4670 ;; Quote with `quote' to prevent byte-compiling the body,
4671 ;; which would lead to an inf-loop.
4672 `(funcall '(lambda (,byte-compile-tmp-var)
4673 (,fun ,var ,byte-compile-tmp-var ,@(nthcdr 3 form)))
4674 ,value)
4675 (if (eq fun 'defconst)
4676 ;; This will signal an appropriate error at runtime.
4677 `(eval ',form)
4678 ;; A simple (defvar foo) just returns foo.
4679 `',var)))))
4681 (defun byte-compile-autoload (form)
4682 (byte-compile-set-symbol-position 'autoload)
4683 (and (macroexp-const-p (nth 1 form))
4684 (macroexp-const-p (nth 5 form))
4685 (memq (eval (nth 5 form)) '(t macro)) ; macro-p
4686 (not (fboundp (eval (nth 1 form))))
4687 (byte-compile-warn
4688 "The compiler ignores `autoload' except at top level. You should
4689 probably put the autoload of the macro `%s' at top-level."
4690 (eval (nth 1 form))))
4691 (byte-compile-normal-call form))
4693 ;; Lambdas in valid places are handled as special cases by various code.
4694 ;; The ones that remain are errors.
4695 (defun byte-compile-lambda-form (_form)
4696 (byte-compile-set-symbol-position 'lambda)
4697 (error "`lambda' used as function name is invalid"))
4699 ;; Compile normally, but deal with warnings for the function being defined.
4700 (put 'defalias 'byte-hunk-handler 'byte-compile-file-form-defalias)
4701 ;; Used for eieio--defalias as well.
4702 (defun byte-compile-file-form-defalias (form)
4703 ;; For the compilation itself, we could largely get rid of this hunk-handler,
4704 ;; if it weren't for the fact that we need to figure out when a defalias
4705 ;; defines a macro, so as to add it to byte-compile-macro-environment.
4707 ;; FIXME: we also use this hunk-handler to implement the function's dynamic
4708 ;; docstring feature. We could actually implement it more elegantly in
4709 ;; byte-compile-lambda so it applies to all lambdas, but the problem is that
4710 ;; the resulting .elc format will not be recognized by make-docfile, so
4711 ;; either we stop using DOC for the docstrings of preloaded elc files (at the
4712 ;; cost of around 24KB on 32bit hosts, double on 64bit hosts) or we need to
4713 ;; build DOC in a more clever way (e.g. handle anonymous elements).
4714 (let ((byte-compile-free-references nil)
4715 (byte-compile-free-assignments nil))
4716 (pcase form
4717 ;; Decompose `form' into:
4718 ;; - `name' is the name of the defined function.
4719 ;; - `arg' is the expression to which it is defined.
4720 ;; - `rest' is the rest of the arguments.
4721 (`(,_ ',name ,arg . ,rest)
4722 (pcase-let*
4723 ;; `macro' is non-nil if it defines a macro.
4724 ;; `fun' is the function part of `arg' (defaults to `arg').
4725 (((or (and (or `(cons 'macro ,fun) `'(macro . ,fun)) (let macro t))
4726 (and (let fun arg) (let macro nil)))
4727 arg)
4728 ;; `lam' is the lambda expression in `fun' (or nil if not
4729 ;; recognized).
4730 ((or `(,(or `quote `function) ,lam) (let lam nil))
4731 fun)
4732 ;; `arglist' is the list of arguments (or t if not recognized).
4733 ;; `body' is the body of `lam' (or t if not recognized).
4734 ((or `(lambda ,arglist . ,body)
4735 ;; `(closure ,_ ,arglist . ,body)
4736 (and `(internal-make-closure ,arglist . ,_) (let body t))
4737 (and (let arglist t) (let body t)))
4738 lam))
4739 (unless (byte-compile-file-form-defmumble
4740 name macro arglist body rest)
4741 (when macro
4742 (if (null fun)
4743 (message "Macro %s unrecognized, won't work in file" name)
4744 (message "Macro %s partly recognized, trying our luck" name)
4745 (push (cons name (eval fun))
4746 byte-compile-macro-environment)))
4747 (byte-compile-keep-pending form))))
4749 ;; We used to just do: (byte-compile-normal-call form)
4750 ;; But it turns out that this fails to optimize the code.
4751 ;; So instead we now do the same as what other byte-hunk-handlers do,
4752 ;; which is to call back byte-compile-file-form and then return nil.
4753 ;; Except that we can't just call byte-compile-file-form since it would
4754 ;; call us right back.
4755 (_ (byte-compile-keep-pending form)))))
4757 (byte-defop-compiler-1 with-no-warnings byte-compile-no-warnings)
4758 (defun byte-compile-no-warnings (form)
4759 (let (byte-compile-warnings)
4760 (byte-compile-form (cons 'progn (cdr form)))))
4762 ;; Warn about misuses of make-variable-buffer-local.
4763 (byte-defop-compiler-1 make-variable-buffer-local
4764 byte-compile-make-variable-buffer-local)
4765 (defun byte-compile-make-variable-buffer-local (form)
4766 (if (and (eq (car-safe (car-safe (cdr-safe form))) 'quote)
4767 (byte-compile-warning-enabled-p 'make-local))
4768 (byte-compile-warn
4769 "`make-variable-buffer-local' not called at toplevel"))
4770 (byte-compile-normal-call form))
4771 (put 'make-variable-buffer-local
4772 'byte-hunk-handler 'byte-compile-form-make-variable-buffer-local)
4773 (defun byte-compile-form-make-variable-buffer-local (form)
4774 (byte-compile-keep-pending form 'byte-compile-normal-call))
4776 (put 'function-put 'byte-hunk-handler 'byte-compile-define-symbol-prop)
4777 (put 'define-symbol-prop 'byte-hunk-handler 'byte-compile-define-symbol-prop)
4778 (defun byte-compile-define-symbol-prop (form)
4779 (pcase form
4780 ((and `(,op ,fun ,prop ,val)
4781 (guard (and (macroexp-const-p fun)
4782 (macroexp-const-p prop)
4783 (or (macroexp-const-p val)
4784 ;; Also accept anonymous functions, since
4785 ;; we're at top-level which implies they're
4786 ;; also constants.
4787 (pcase val (`(function (lambda . ,_)) t))))))
4788 (byte-compile-push-constant op)
4789 (byte-compile-form fun)
4790 (byte-compile-form prop)
4791 (let* ((fun (eval fun))
4792 (prop (eval prop))
4793 (val (if (macroexp-const-p val)
4794 (eval val)
4795 (byte-compile-lambda (cadr val)))))
4796 (push `(,fun
4797 . (,prop ,val ,@(alist-get fun overriding-plist-environment)))
4798 overriding-plist-environment)
4799 (byte-compile-push-constant val)
4800 (byte-compile-out 'byte-call 3)
4801 nil))
4803 (_ (byte-compile-keep-pending form))))
4805 ;;; tags
4807 ;; Note: Most operations will strip off the 'TAG, but it speeds up
4808 ;; optimization to have the 'TAG as a part of the tag.
4809 ;; Tags will be (TAG . (tag-number . stack-depth)).
4810 (defun byte-compile-make-tag ()
4811 (list 'TAG (setq byte-compile-tag-number (1+ byte-compile-tag-number))))
4814 (defun byte-compile-out-tag (tag)
4815 (setq byte-compile-output (cons tag byte-compile-output))
4816 (if (cdr (cdr tag))
4817 (progn
4818 ;; ## remove this someday
4819 (and byte-compile-depth
4820 (not (= (cdr (cdr tag)) byte-compile-depth))
4821 (error "Compiler bug: depth conflict at tag %d" (car (cdr tag))))
4822 (setq byte-compile-depth (cdr (cdr tag))))
4823 (setcdr (cdr tag) byte-compile-depth)))
4825 (defun byte-compile-goto (opcode tag)
4826 (push (cons opcode tag) byte-compile-output)
4827 (setcdr (cdr tag) (if (memq opcode byte-goto-always-pop-ops)
4828 (1- byte-compile-depth)
4829 byte-compile-depth))
4830 (setq byte-compile-depth (and (not (eq opcode 'byte-goto))
4831 (1- byte-compile-depth))))
4833 (defun byte-compile-stack-adjustment (op operand)
4834 "Return the amount by which an operation adjusts the stack.
4835 OP and OPERAND are as passed to `byte-compile-out'."
4836 (if (memq op '(byte-call byte-discardN byte-discardN-preserve-tos))
4837 ;; For calls, OPERAND is the number of args, so we pop OPERAND + 1
4838 ;; elements, and the push the result, for a total of -OPERAND.
4839 ;; For discardN*, of course, we just pop OPERAND elements.
4840 (- operand)
4841 (or (aref byte-stack+-info (symbol-value op))
4842 ;; Ops with a nil entry in `byte-stack+-info' are byte-codes
4843 ;; that take OPERAND values off the stack and push a result, for
4844 ;; a total of 1 - OPERAND
4845 (- 1 operand))))
4847 (defun byte-compile-out (op &optional operand)
4848 (push (cons op operand) byte-compile-output)
4849 (if (eq op 'byte-return)
4850 ;; This is actually an unnecessary case, because there should be no
4851 ;; more ops behind byte-return.
4852 (setq byte-compile-depth nil)
4853 (setq byte-compile-depth
4854 (+ byte-compile-depth (byte-compile-stack-adjustment op operand)))
4855 (setq byte-compile-maxdepth (max byte-compile-depth byte-compile-maxdepth))
4856 ;;(if (< byte-compile-depth 0) (error "Compiler error: stack underflow"))
4859 ;;; call tree stuff
4861 (defun byte-compile-annotate-call-tree (form)
4862 (let (entry)
4863 ;; annotate the current call
4864 (if (setq entry (assq (car form) byte-compile-call-tree))
4865 (or (memq byte-compile-current-form (nth 1 entry)) ;callers
4866 (setcar (cdr entry)
4867 (cons byte-compile-current-form (nth 1 entry))))
4868 (setq byte-compile-call-tree
4869 (cons (list (car form) (list byte-compile-current-form) nil)
4870 byte-compile-call-tree)))
4871 ;; annotate the current function
4872 (if (setq entry (assq byte-compile-current-form byte-compile-call-tree))
4873 (or (memq (car form) (nth 2 entry)) ;called
4874 (setcar (cdr (cdr entry))
4875 (cons (car form) (nth 2 entry))))
4876 (setq byte-compile-call-tree
4877 (cons (list byte-compile-current-form nil (list (car form)))
4878 byte-compile-call-tree)))
4881 ;; Renamed from byte-compile-report-call-tree
4882 ;; to avoid interfering with completion of byte-compile-file.
4883 ;;;###autoload
4884 (defun display-call-tree (&optional filename)
4885 "Display a call graph of a specified file.
4886 This lists which functions have been called, what functions called
4887 them, and what functions they call. The list includes all functions
4888 whose definitions have been compiled in this Emacs session, as well as
4889 all functions called by those functions.
4891 The call graph does not include macros, inline functions, or
4892 primitives that the byte-code interpreter knows about directly
4893 \(`eq', `cons', etc.).
4895 The call tree also lists those functions which are not known to be called
4896 \(that is, to which no calls have been compiled), and which cannot be
4897 invoked interactively."
4898 (interactive)
4899 (message "Generating call tree...")
4900 (with-output-to-temp-buffer "*Call-Tree*"
4901 (set-buffer "*Call-Tree*")
4902 (erase-buffer)
4903 (message "Generating call tree... (sorting on %s)"
4904 byte-compile-call-tree-sort)
4905 (insert "Call tree for "
4906 (cond ((null byte-compile-current-file) (or filename "???"))
4907 ((stringp byte-compile-current-file)
4908 byte-compile-current-file)
4909 (t (buffer-name byte-compile-current-file)))
4910 " sorted on "
4911 (prin1-to-string byte-compile-call-tree-sort)
4912 ":\n\n")
4913 (if byte-compile-call-tree-sort
4914 (setq byte-compile-call-tree
4915 (sort byte-compile-call-tree
4916 (pcase byte-compile-call-tree-sort
4917 (`callers
4918 (lambda (x y) (< (length (nth 1 x))
4919 (length (nth 1 y)))))
4920 (`calls
4921 (lambda (x y) (< (length (nth 2 x))
4922 (length (nth 2 y)))))
4923 (`calls+callers
4924 (lambda (x y) (< (+ (length (nth 1 x))
4925 (length (nth 2 x)))
4926 (+ (length (nth 1 y))
4927 (length (nth 2 y))))))
4928 (`name
4929 (lambda (x y) (string< (car x) (car y))))
4930 (_ (error "`byte-compile-call-tree-sort': `%s' - unknown sort mode"
4931 byte-compile-call-tree-sort))))))
4932 (message "Generating call tree...")
4933 (let ((rest byte-compile-call-tree)
4934 (b (current-buffer))
4936 callers calls)
4937 (while rest
4938 (prin1 (car (car rest)) b)
4939 (setq callers (nth 1 (car rest))
4940 calls (nth 2 (car rest)))
4941 (insert "\t"
4942 (cond ((not (fboundp (setq f (car (car rest)))))
4943 (if (null f)
4944 " <top level>";; shouldn't insert nil then, actually -sk
4945 " <not defined>"))
4946 ((subrp (setq f (symbol-function f)))
4947 " <subr>")
4948 ((symbolp f)
4949 (format " ==> %s" f))
4950 ((byte-code-function-p f)
4951 "<compiled function>")
4952 ((not (consp f))
4953 "<malformed function>")
4954 ((eq 'macro (car f))
4955 (if (or (byte-code-function-p (cdr f))
4956 (assq 'byte-code (cdr (cdr (cdr f)))))
4957 " <compiled macro>"
4958 " <macro>"))
4959 ((assq 'byte-code (cdr (cdr f)))
4960 "<compiled lambda>")
4961 ((eq 'lambda (car f))
4962 "<function>")
4963 (t "???"))
4964 (format " (%d callers + %d calls = %d)"
4965 ;; Does the optimizer eliminate common subexpressions?-sk
4966 (length callers)
4967 (length calls)
4968 (+ (length callers) (length calls)))
4969 "\n")
4970 (if callers
4971 (progn
4972 (insert " called by:\n")
4973 (setq p (point))
4974 (insert " " (if (car callers)
4975 (mapconcat 'symbol-name callers ", ")
4976 "<top level>"))
4977 (let ((fill-prefix " "))
4978 (fill-region-as-paragraph p (point)))
4979 (unless (= 0 (current-column))
4980 (insert "\n"))))
4981 (if calls
4982 (progn
4983 (insert " calls:\n")
4984 (setq p (point))
4985 (insert " " (mapconcat 'symbol-name calls ", "))
4986 (let ((fill-prefix " "))
4987 (fill-region-as-paragraph p (point)))
4988 (unless (= 0 (current-column))
4989 (insert "\n"))))
4990 (setq rest (cdr rest)))
4992 (message "Generating call tree...(finding uncalled functions...)")
4993 (setq rest byte-compile-call-tree)
4994 (let (uncalled def)
4995 (while rest
4996 (or (nth 1 (car rest))
4997 (null (setq f (caar rest)))
4998 (progn
4999 (setq def (byte-compile-fdefinition f t))
5000 (and (eq (car-safe def) 'macro)
5001 (eq (car-safe (cdr-safe def)) 'lambda)
5002 (setq def (cdr def)))
5003 (functionp def))
5004 (progn
5005 (setq def (byte-compile-fdefinition f nil))
5006 (and (eq (car-safe def) 'macro)
5007 (eq (car-safe (cdr-safe def)) 'lambda)
5008 (setq def (cdr def)))
5009 (commandp def))
5010 (setq uncalled (cons f uncalled)))
5011 (setq rest (cdr rest)))
5012 (if uncalled
5013 (let ((fill-prefix " "))
5014 (insert "Noninteractive functions not known to be called:\n ")
5015 (setq p (point))
5016 (insert (mapconcat 'symbol-name (nreverse uncalled) ", "))
5017 (fill-region-as-paragraph p (point))))))
5018 (message "Generating call tree...done.")))
5021 ;;;###autoload
5022 (defun batch-byte-compile-if-not-done ()
5023 "Like `byte-compile-file' but doesn't recompile if already up to date.
5024 Use this from the command line, with `-batch';
5025 it won't work in an interactive Emacs."
5026 (batch-byte-compile t))
5028 ;;; by crl@newton.purdue.edu
5029 ;;; Only works noninteractively.
5030 ;;;###autoload
5031 (defun batch-byte-compile (&optional noforce)
5032 "Run `byte-compile-file' on the files remaining on the command line.
5033 Use this from the command line, with `-batch';
5034 it won't work in an interactive Emacs.
5035 Each file is processed even if an error occurred previously.
5036 For example, invoke \"emacs -batch -f batch-byte-compile $emacs/ ~/*.el\".
5037 If NOFORCE is non-nil, don't recompile a file that seems to be
5038 already up-to-date."
5039 ;; command-line-args-left is what is left of the command line, from
5040 ;; startup.el.
5041 (defvar command-line-args-left) ;Avoid 'free variable' warning
5042 (if (not noninteractive)
5043 (error "`batch-byte-compile' is to be used only with -batch"))
5044 ;; Better crash loudly than attempting to recover from undefined
5045 ;; behavior.
5046 (setq attempt-stack-overflow-recovery nil
5047 attempt-orderly-shutdown-on-fatal-signal nil)
5048 (let ((error nil))
5049 (while command-line-args-left
5050 (if (file-directory-p (expand-file-name (car command-line-args-left)))
5051 ;; Directory as argument.
5052 (let (source dest)
5053 (dolist (file (directory-files (car command-line-args-left)))
5054 (if (and (string-match emacs-lisp-file-regexp file)
5055 (not (auto-save-file-name-p file))
5056 (setq source
5057 (expand-file-name file
5058 (car command-line-args-left)))
5059 (setq dest (byte-compile-dest-file source))
5060 (file-exists-p dest)
5061 (file-newer-than-file-p source dest))
5062 (if (null (batch-byte-compile-file source))
5063 (setq error t)))))
5064 ;; Specific file argument
5065 (if (or (not noforce)
5066 (let* ((source (car command-line-args-left))
5067 (dest (byte-compile-dest-file source)))
5068 (or (not (file-exists-p dest))
5069 (file-newer-than-file-p source dest))))
5070 (if (null (batch-byte-compile-file (car command-line-args-left)))
5071 (setq error t))))
5072 (setq command-line-args-left (cdr command-line-args-left)))
5073 (kill-emacs (if error 1 0))))
5075 (defun batch-byte-compile-file (file)
5076 (let ((byte-compile-root-dir (or byte-compile-root-dir default-directory)))
5077 (if debug-on-error
5078 (byte-compile-file file)
5079 (condition-case err
5080 (byte-compile-file file)
5081 (file-error
5082 (message (if (cdr err)
5083 ">>Error occurred processing %s: %s (%s)"
5084 ">>Error occurred processing %s: %s")
5085 file
5086 (get (car err) 'error-message)
5087 (prin1-to-string (cdr err)))
5088 (let ((destfile (byte-compile-dest-file file)))
5089 (if (file-exists-p destfile)
5090 (delete-file destfile)))
5091 nil)
5092 (error
5093 (message (if (cdr err)
5094 ">>Error occurred processing %s: %s (%s)"
5095 ">>Error occurred processing %s: %s")
5096 file
5097 (get (car err) 'error-message)
5098 (prin1-to-string (cdr err)))
5099 nil)))))
5101 (defun byte-compile-refresh-preloaded ()
5102 "Reload any Lisp file that was changed since Emacs was dumped.
5103 Use with caution."
5104 (let* ((argv0 (car command-line-args))
5105 (emacs-file (executable-find argv0)))
5106 (if (not (and emacs-file (file-executable-p emacs-file)))
5107 (message "Can't find %s to refresh preloaded Lisp files" argv0)
5108 (dolist (f (reverse load-history))
5109 (setq f (car f))
5110 (if (string-match "elc\\'" f) (setq f (substring f 0 -1)))
5111 (when (and (file-readable-p f)
5112 (file-newer-than-file-p f emacs-file)
5113 ;; Don't reload the source version of the files below
5114 ;; because that causes subsequent byte-compilation to
5115 ;; be a lot slower and need a higher max-lisp-eval-depth,
5116 ;; so it can cause recompilation to fail.
5117 (not (member (file-name-nondirectory f)
5118 '("pcase.el" "bytecomp.el" "macroexp.el"
5119 "cconv.el" "byte-opt.el"))))
5120 (message "Reloading stale %s" (file-name-nondirectory f))
5121 (condition-case nil
5122 (load f 'noerror nil 'nosuffix)
5123 ;; Probably shouldn't happen, but in case of an error, it seems
5124 ;; at least as useful to ignore it as it is to stop compilation.
5125 (error nil)))))))
5127 ;;;###autoload
5128 (defun batch-byte-recompile-directory (&optional arg)
5129 "Run `byte-recompile-directory' on the dirs remaining on the command line.
5130 Must be used only with `-batch', and kills Emacs on completion.
5131 For example, invoke `emacs -batch -f batch-byte-recompile-directory .'.
5133 Optional argument ARG is passed as second argument ARG to
5134 `byte-recompile-directory'; see there for its possible values
5135 and corresponding effects."
5136 ;; command-line-args-left is what is left of the command line (startup.el)
5137 (defvar command-line-args-left) ;Avoid 'free variable' warning
5138 (if (not noninteractive)
5139 (error "batch-byte-recompile-directory is to be used only with -batch"))
5140 ;; Better crash loudly than attempting to recover from undefined
5141 ;; behavior.
5142 (setq attempt-stack-overflow-recovery nil
5143 attempt-orderly-shutdown-on-fatal-signal nil)
5144 (or command-line-args-left
5145 (setq command-line-args-left '(".")))
5146 (while command-line-args-left
5147 (byte-recompile-directory (car command-line-args-left) arg)
5148 (setq command-line-args-left (cdr command-line-args-left)))
5149 (kill-emacs 0))
5151 ;;; Core compiler macros.
5153 (put 'featurep 'compiler-macro
5154 (lambda (form feature &rest _ignore)
5155 ;; Emacs-21's byte-code doesn't run under XEmacs or SXEmacs anyway, so
5156 ;; we can safely optimize away this test.
5157 (if (member feature '('xemacs 'sxemacs 'emacs))
5158 (eval form)
5159 form)))
5161 (provide 'byte-compile)
5162 (provide 'bytecomp)
5165 ;;; report metering (see the hacks in bytecode.c)
5167 (defvar byte-code-meter)
5168 (defun byte-compile-report-ops ()
5169 (or (boundp 'byte-metering-on)
5170 (error "You must build Emacs with -DBYTE_CODE_METER to use this"))
5171 (with-output-to-temp-buffer "*Meter*"
5172 (set-buffer "*Meter*")
5173 (let ((i 0) n op off)
5174 (while (< i 256)
5175 (setq n (aref (aref byte-code-meter 0) i)
5176 off nil)
5177 (if t ;(not (zerop n))
5178 (progn
5179 (setq op i)
5180 (setq off nil)
5181 (cond ((< op byte-nth)
5182 (setq off (logand op 7))
5183 (setq op (logand op 248)))
5184 ((>= op byte-constant)
5185 (setq off (- op byte-constant)
5186 op byte-constant)))
5187 (setq op (aref byte-code-vector op))
5188 (insert (format "%-4d" i))
5189 (insert (symbol-name op))
5190 (if off (insert " [" (int-to-string off) "]"))
5191 (indent-to 40)
5192 (insert (int-to-string n) "\n")))
5193 (setq i (1+ i))))))
5195 ;; To avoid "lisp nesting exceeds max-lisp-eval-depth" when bytecomp compiles
5196 ;; itself, compile some of its most used recursive functions (at load time).
5198 (eval-when-compile
5199 (or (byte-code-function-p (symbol-function 'byte-compile-form))
5200 (assq 'byte-code (symbol-function 'byte-compile-form))
5201 (let ((byte-optimize nil) ; do it fast
5202 (byte-compile-warnings nil))
5203 (mapc (lambda (x)
5204 (or noninteractive (message "compiling %s..." x))
5205 (byte-compile x)
5206 (or noninteractive (message "compiling %s...done" x)))
5207 '(byte-compile-normal-call
5208 byte-compile-form
5209 byte-compile-body
5210 ;; Inserted some more than necessary, to speed it up.
5211 byte-compile-top-level
5212 byte-compile-out-toplevel
5213 byte-compile-constant
5214 byte-compile-variable-ref))))
5215 nil)
5217 (run-hooks 'bytecomp-load-hook)
5219 ;;; bytecomp.el ends here