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