Initial git import
[sxemacs] / lisp / bytecomp.el
1 ;;; bytecomp.el --- compilation of Lisp code into byte code.
2
3 ;;; Copyright (C) 1985-1987, 1991-1994 Free Software Foundation, Inc.
4 ;;; Copyright (C) 1996 Ben Wing.
5
6 ;; Authors: Jamie Zawinski <jwz@jwz.org>
7 ;;      Hallvard Furuseth <hbf@ulrik.uio.no>
8 ;;      Ben Wing <ben@xemacs.org>
9 ;;      Martin Buchholz <martin@xemacs.org>
10 ;;      Richard Stallman <rms@gnu.org>
11 ;; Keywords: internal lisp
12
13 (defconst byte-compile-version "2.27 XEmacs; 2000-09-12.")
14
15 ;; This file is part of SXEmacs.
16
17 ;; SXEmacs is free software: you can redistribute it and/or modify
18 ;; it under the terms of the GNU General Public License as published by
19 ;; the Free Software Foundation, either version 3 of the License, or
20 ;; (at your option) any later version.
21
22 ;; SXEmacs is distributed in the hope that it will be useful,
23 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
24 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 ;; GNU General Public License for more details.
26
27 ;; You should have received a copy of the GNU General Public License
28 ;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
29
30 ;;; Synched up with: FSF 19.30.
31
32 ;;; Commentary:
33
34 ;; The Emacs Lisp byte compiler.  This crunches lisp source into a
35 ;; sort of p-code (`bytecode') which takes up less space and can be
36 ;; interpreted faster.  First, the source code forms are converted to
37 ;; an intermediate form, `lapcode' [`LAP' == `Lisp Assembly Program']
38 ;; which is much easier to manipulate than bytecode.  Then the lapcode
39 ;; is converted to bytecode, which can be considered to be actual
40 ;; machine language.  Optimizations can occur at either the source
41 ;; level or the lapcode level.
42
43 ;; The user entry points are byte-compile-file,
44 ;; byte-recompile-directory and byte-compile-buffer.
45
46 ;;; Code:
47
48 ;;; ========================================================================
49 ;;; Entry points:
50 ;;;     byte-recompile-directory, byte-compile-file,
51 ;;;     batch-byte-compile, batch-byte-recompile-directory,
52 ;;;     byte-compile, compile-defun,
53 ;;;     display-call-tree
54 ;;;  RMS says:
55 ;;; (byte-compile-buffer and byte-compile-and-load-file were turned off
56 ;;;  because they are not terribly useful and get in the way of completion.)
57 ;;; But I'm leaving them. --ben
58
59 ;;; This version of the byte compiler has the following improvements:
60 ;;;  + optimization of compiled code:
61 ;;;    - removal of unreachable code;
62 ;;;    - removal of calls to side-effectless functions whose return-value
63 ;;;      is unused;
64 ;;;    - compile-time evaluation of safe constant forms, such as (consp nil)
65 ;;;      and (ash 1 6);
66 ;;;    - open-coding of literal lambdas;
67 ;;;    - peephole optimization of emitted code;
68 ;;;    - trivial functions are left uncompiled for speed.
69 ;;;  + support for inline functions;
70 ;;;  + compile-time evaluation of arbitrary expressions;
71 ;;;  + compile-time warning messages for:
72 ;;;    - functions being redefined with incompatible arglists;
73 ;;;    - functions being redefined as macros, or vice-versa;
74 ;;;    - functions or macros defined multiple times in the same file;
75 ;;;    - functions being called with the incorrect number of arguments;
76 ;;;    - functions being called which are not defined globally, in the
77 ;;;      file, or as autoloads;
78 ;;;    - assignment and reference of undeclared free variables;
79 ;;;    - various syntax errors;
80 ;;;  + correct compilation of nested defuns, defmacros, defvars and defsubsts;
81 ;;;  + correct compilation of top-level uses of macros;
82 ;;;  + the ability to generate a histogram of functions called.
83
84 ;;; User customization variables:
85 ;;;
86 ;;; byte-compile-verbose        Whether to report the function currently being
87 ;;;                             compiled in the minibuffer;
88 ;;; byte-optimize               Whether to do optimizations; this may be
89 ;;;                             t, nil, 'source, or 'byte;
90 ;;; byte-optimize-log           Whether to report (in excruciating detail)
91 ;;;                             exactly which optimizations have been made.
92 ;;;                             This may be t, nil, 'source, or 'byte;
93 ;;; byte-compile-error-on-warn  Whether to stop compilation when a warning is
94 ;;;                             produced;
95 ;;; byte-compile-delete-errors  Whether the optimizer may delete calls or
96 ;;;                             variable references that are side-effect-free
97 ;;;                             except that they may return an error.
98 ;;; byte-compile-generate-call-tree     Whether to generate a histogram of
99 ;;;                             function calls.  This can be useful for
100 ;;;                             finding unused functions, as well as simple
101 ;;;                             performance metering.
102 ;;; byte-compile-warnings       List of warnings to issue, or t.  May contain
103 ;;;                             'free-vars (references to variables not in the
104 ;;;                                         current lexical scope)
105 ;;;                             'unused-vars (non-global variables bound but
106 ;;;                                           not referenced)
107 ;;;                             'unresolved (calls to unknown functions)
108 ;;;                             'callargs  (lambda calls with args that don't
109 ;;;                                         match the lambda's definition)
110 ;;;                             'subr-callargs (calls to subrs with args that
111 ;;;                                         don't match the subr's definition)
112 ;;;                             'redefine  (function cell redefined from
113 ;;;                                         a macro to a lambda or vice versa,
114 ;;;                                         or redefined to take other args)
115 ;;;                             'obsolete  (obsolete variables and functions)
116 ;;;                             'pedantic  (references to Emacs-compatible
117 ;;;                                         symbols)
118 ;;; byte-compile-emacs19-compatibility  Whether the compiler should
119 ;;;                             generate .elc files which can be loaded into
120 ;;;                             generic emacs 19.
121 ;;; emacs-lisp-file-regexp      Regexp for the extension of source-files;
122 ;;;                             see also the function `byte-compile-dest-file'.
123 ;;; byte-compile-overwrite-file If nil, delete old .elc files before saving.
124 ;;;
125 ;;; Most of the above parameters can also be set on a file-by-file basis; see
126 ;;; the documentation of the `byte-compiler-options' macro.
127
128 ;;; New Features:
129 ;;;
130 ;;;  o  The form `defsubst' is just like `defun', except that the function
131 ;;;     generated will be open-coded in compiled code which uses it.  This
132 ;;;     means that no function call will be generated, it will simply be
133 ;;;     spliced in.  Lisp functions calls are very slow, so this can be a
134 ;;;     big win.
135 ;;;
136 ;;;     You can generally accomplish the same thing with `defmacro', but in
137 ;;;     that case, the defined procedure can't be used as an argument to
138 ;;;     mapcar, etc.
139 ;;;
140 ;;;  o  You can make a given function be inline even if it has already been
141 ;;;     defined with `defun' by using the `proclaim-inline' form like so:
142 ;;;             (proclaim-inline my-function)
143 ;;;     This is, in fact, exactly what `defsubst' does.  To make a function no
144 ;;;     longer be inline, you must use `proclaim-notinline'.  Beware that if
145 ;;;     you define a function with `defsubst' and later redefine it with
146 ;;;     `defun', it will still be open-coded until you use `proclaim-notinline'.
147 ;;;
148 ;;;  o  You can also open-code one particular call to a function without
149 ;;;     open-coding all calls.  Use the 'inline' form to do this, like so:
150 ;;;
151 ;;;             (inline (foo 1 2 3))    ;; `foo' will be open-coded
152 ;;;     or...
153 ;;;             (inline                 ;;  `foo' and `baz' will be
154 ;;;              (foo 1 2 3 (bar 5))    ;; open-coded, but `bar' will not.
155 ;;;              (baz 0))
156 ;;;
157 ;;;  o  It is possible to open-code a function in the same file it is defined
158 ;;;     in without having to load that file before compiling it.  the
159 ;;;     byte-compiler has been modified to remember function definitions in
160 ;;;     the compilation environment in the same way that it remembers macro
161 ;;;     definitions.
162 ;;;
163 ;;;  o  Forms like ((lambda ...) ...) are open-coded.
164 ;;;
165 ;;;  o  The form `eval-when-compile' is like `progn', except that the body
166 ;;;     is evaluated at compile-time.  When it appears at top-level, this
167 ;;;     is analogous to the Common Lisp idiom (eval-when (compile) ...).
168 ;;;     When it does not appear at top-level, it is similar to the
169 ;;;     Common Lisp #. reader macro (but not in interpreted code).
170 ;;;
171 ;;;  o  The form `eval-and-compile' is similar to `eval-when-compile',
172 ;;;     but the whole form is evalled both at compile-time and at run-time.
173 ;;;
174 ;;;  o  The command M-x byte-compile-and-load-file does what you'd think.
175 ;;;
176 ;;;  o  The command `compile-defun' is analogous to `eval-defun'.
177 ;;;
178 ;;;  o  If you run `byte-compile-file' on a filename which is visited in a
179 ;;;     buffer, and that buffer is modified, you are asked whether you want
180 ;;;     to save the buffer before compiling.
181 ;;;
182 ;;;  o  You can add this to /etc/magic to make file(1) recognize the files
183 ;;;     generated by this compiler:
184 ;;;
185 ;;;       0     string          ;ELC            GNU Emacs Lisp compiled file,
186 ;;;       >4    byte            x               version %d
187 ;;;
188 ;;; TO DO:
189 ;;;
190 ;;;  o  Should implement declarations and proclamations, notably special,
191 ;;;     unspecial, and ignore.  Do this in such a way as to not break cl.el.
192 ;;;  o  The bound-but-not-used warnings are not issued for variables whose
193 ;;;     bindings were established in the arglist, due to the lack of an
194 ;;;     ignore declaration.  Once ignore exists, this should be turned on.
195 ;;;  o  Warn about functions and variables defined but not used?
196 ;;;     Maybe add some kind of `export' declaration for this?
197 ;;;     (With interactive functions being automatically exported?)
198 ;;;  o  Any reference to a variable, even one which is a no-op, will cause
199 ;;;     the warning not to be given.  Possibly we could use the for-effect
200 ;;;     flag to determine when this reference is useless; possibly more
201 ;;;     complex flow analysis would be necessary.
202 ;;;  o  If the optimizer deletes a variable reference, we might be left with
203 ;;;     a bound-but-not-referenced warning.  Generally this is ok, but not if
204 ;;;     it's a synergistic result of macroexpansion.  Need some way to note
205 ;;;     that a varref is being optimized away?  Of course it would be nice to
206 ;;;     optimize away the binding too, someday, but it's unsafe today.
207 ;;;  o  (See byte-optimize.el for the optimization TODO list.)
208
209 (require 'backquote)
210 (when purify-flag
211   (require 'bytecomp-runtime)
212   (require 'subr)
213   (require 'replace)
214   (require 'version)
215   (require 'cl)
216   (require 'cl-extra)
217   (require 'custom)
218   (require 'keymap)
219   (require 'console)
220   (require 'keydefs)
221   (require 'lib-complete))
222
223 (or (fboundp 'defsubst)
224     ;; This really ought to be loaded already!
225     (load-library "bytecomp-runtime"))
226
227 (eval-when-compile
228   (defvar byte-compile-single-version nil
229     "If this is true, the choice of emacs version (v19 or v20) byte-codes will
230 be hard-coded into bytecomp when it compiles itself.  If the compiler itself
231 is compiled with optimization, this causes a speedup.")
232
233   (cond
234    (byte-compile-single-version
235     (defmacro byte-compile-single-version () t)
236     (defmacro byte-compile-version-cond (cond) (list 'quote (eval cond))))
237    (t
238     (defmacro byte-compile-single-version () nil)
239     (defmacro byte-compile-version-cond (cond) cond)))
240   )
241
242 (unless (fboundp #'compile-regexp)
243   (defalias 'compile-regexp #'identity))
244
245 (defvar emacs-lisp-file-regexp (compile-regexp "\\.el$")
246   "*Regexp which matches Emacs Lisp source files.
247 You may want to redefine `byte-compile-dest-file' if you change this.")
248
249 ;; This enables file name handlers such as jka-compr
250 ;; to remove parts of the file name that should not be copied
251 ;; through to the output file name.
252 (defun byte-compiler-base-file-name (filename)
253   (let ((handler (find-file-name-handler filename
254                                          'byte-compiler-base-file-name)))
255     (if handler
256         (funcall handler 'byte-compiler-base-file-name filename)
257       filename)))
258
259 (unless (fboundp 'byte-compile-dest-file)
260   ;; The user may want to redefine this along with emacs-lisp-file-regexp,
261   ;; so only define it if it is undefined.
262   (defun byte-compile-dest-file (filename)
263     "Convert an Emacs Lisp source file name to a compiled file name."
264     (setq filename (byte-compiler-base-file-name filename))
265     (setq filename (file-name-sans-versions filename))
266     (if (string-match emacs-lisp-file-regexp filename)
267         (concat (substring filename 0 (match-beginning 0)) ".elc")
268       (concat filename ".elc"))))
269
270 ;; This can be the 'byte-compile property of any symbol.
271 (autoload 'byte-compile-inline-expand "byte-optimize")
272
273 ;; This is the entrypoint to the lapcode optimizer pass1.
274 (autoload 'byte-optimize-form "byte-optimize")
275 ;; This is the entrypoint to the lapcode optimizer pass2.
276 (autoload 'byte-optimize-lapcode "byte-optimize")
277 (autoload 'byte-compile-unfold-lambda "byte-optimize")
278
279 ;; This is the entry point to the decompiler, which is used by the
280 ;; disassembler.  The disassembler just requires 'byte-compile, but
281 ;; that doesn't define this function, so this seems to be a reasonable
282 ;; thing to do.
283 (autoload 'byte-decompile-bytecode "byte-optimize")
284
285 (defvar byte-compile-verbose
286   (and (not noninteractive) (> (device-baud-rate) search-slow-speed))
287   "*Non-nil means print messages describing progress of byte-compiler.")
288
289 (defvar byte-compile-emacs19-compatibility
290   (not (emacs-version>= 20))
291   "*Non-nil means generate output that can run in Emacs 19.")
292
293 (defvar byte-compile-print-gensym t
294   "*Non-nil means generate code that creates unique symbols at run-time.
295 This is achieved by printing uninterned symbols using the `#:SYMBOL'
296 notation, so that they will be read uninterned when run.
297
298 With this feature, code that uses uninterned symbols in macros will
299 not be runnable under pre-21.0 XEmacsen.
300
301 When `byte-compile-emacs19-compatibility' is non-nil, this variable is
302 ignored and considered to be nil.")
303
304 (defvar byte-optimize t
305   "*Enables optimization in the byte compiler.
306 nil means don't do any optimization.
307 t means do all optimizations.
308 `source' means do source-level optimizations only.
309 `byte' means do code-level optimizations only.")
310
311 (defvar byte-compile-delete-errors t
312   "*If non-nil, the optimizer may delete forms that may signal an error.
313 This includes variable references and calls to functions such as `car'.")
314
315 ;; XEmacs addition
316 (defvar byte-compile-new-bytecodes nil
317   "This is completely ignored.  It is only around for backwards
318 compatibility.")
319
320
321 ;; FSF enables byte-compile-dynamic-docstrings but not byte-compile-dynamic
322 ;; by default.  This would be a reasonable conservative approach except
323 ;; for the fact that if you enable either of these, you get incompatible
324 ;; byte code that can't be read by XEmacs 19.13 or before or FSF 19.28 or
325 ;; before.
326 ;;
327 ;; Therefore, neither is enabled for 19.14.  Both are enabled for 20.0
328 ;; because we have no reason to be conservative about changing the
329 ;; way things work. (Ben)
330
331 ;; However, I don't think that defaulting byte-compile-dynamic to nil
332 ;; is a compatibility issue - rather it is a performance issue.
333 ;; Therefore I am setting byte-compile-dynamic back to nil. (mrb)
334
335 (defvar byte-compile-dynamic nil
336   "*If non-nil, compile function bodies so they load lazily.
337 They are hidden comments in the compiled file, and brought into core when the
338 function is called.
339
340 To enable this option, make it a file-local variable
341 in the source file you want it to apply to.
342 For example, add  -*-byte-compile-dynamic: t;-*- on the first line.
343
344 When this option is true, if you load the compiled file and then move it,
345 the functions you loaded will not be able to run.")
346
347 (defvar byte-compile-dynamic-docstrings (emacs-version>= 20)
348   "*If non-nil, compile doc strings for lazy access.
349 We bury the doc strings of functions and variables
350 inside comments in the file, and bring them into core only when they
351 are actually needed.
352
353 When this option is true, if you load the compiled file and then move it,
354 you won't be able to find the documentation of anything in that file.
355
356 To disable this option for a certain file, make it a file-local variable
357 in the source file.  For example, add this to the first line:
358   -*-byte-compile-dynamic-docstrings:nil;-*-
359 You can also set the variable globally.
360
361 This option is enabled by default because it reduces Emacs memory usage.")
362
363 (defvar byte-optimize-log nil
364   "*If true, the byte-compiler will log its optimizations into *Compile-Log*.
365 If this is 'source, then only source-level optimizations will be logged.
366 If it is 'byte, then only byte-level optimizations will be logged.")
367
368 (defvar byte-compile-error-on-warn nil
369   "*If true, the byte-compiler reports warnings with `error'.")
370
371 ;; byte-compile-warning-types in FSF.
372 (defvar byte-compile-default-warnings
373   '(redefine callargs subr-callargs free-vars unresolved unused-vars obsolete)
374   "*The warnings used when byte-compile-warnings is t.")
375
376 (defvar byte-compile-warnings t
377   "*List of warnings that the compiler should issue (t for the default set).
378 Elements of the list may be:
379
380   free-vars     references to variables not in the current lexical scope.
381   unused-vars   references to non-global variables bound but not referenced.
382   unresolved    calls to unknown functions.
383   callargs      lambda calls with args that don't match the definition.
384   subr-callargs calls to subrs with args that don't match the definition.
385   redefine      function cell redefined from a macro to a lambda or vice
386                 versa, or redefined to take a different number of arguments.
387   obsolete      use of an obsolete function or variable.
388   pedantic      warn of use of compatible symbols.
389
390 The default set is specified by `byte-compile-default-warnings' and
391 normally encompasses all possible warnings.
392
393 See also the macro `byte-compiler-options'.")
394
395 (defvar byte-compile-generate-call-tree nil
396   "*Non-nil means collect call-graph information when compiling.
397 This records functions that were called and from where.
398 If the value is t, compilation displays the call graph when it finishes.
399 If the value is neither t nor nil, compilation asks you whether to display
400 the graph.
401
402 The call tree only lists functions called, not macros used. Those functions
403 which the byte-code interpreter knows about directly (eq, cons, etc.) are
404 not reported.
405
406 The call tree also lists those functions which are not known to be called
407 \(that is, to which no calls have been compiled).  Functions which can be
408 invoked interactively are excluded from this list.")
409
410 (defconst byte-compile-call-tree nil "Alist of functions and their call tree.
411 Each element looks like
412
413   \(FUNCTION CALLERS CALLS\)
414
415 where CALLERS is a list of functions that call FUNCTION, and CALLS
416 is a list of functions for which calls were generated while compiling
417 FUNCTION.")
418
419 (defvar byte-compile-call-tree-sort 'name
420   "*If non-nil, sort the call tree.
421 The values `name', `callers', `calls', `calls+callers'
422 specify different fields to sort on.")
423
424 (defvar byte-compile-overwrite-file t
425   "If nil, old .elc files are deleted before the new is saved, and .elc
426 files will have the same modes as the corresponding .el file.  Otherwise,
427 existing .elc files will simply be overwritten, and the existing modes
428 will not be changed.  If this variable is nil, then an .elc file which
429 is a symbolic link will be turned into a normal file, instead of the file
430 which the link points to being overwritten.")
431
432 (defvar byte-recompile-directory-ignore-errors-p nil
433   "If true, then `byte-recompile-directory' will continue compiling even
434 when an error occurs in a file.  This is bound to t by
435 `batch-byte-recompile-directory'.")
436
437 (defvar byte-recompile-directory-recursively t
438   "*If true, then `byte-recompile-directory' will recurse on subdirectories.")
439
440 (defvar byte-compile-constants nil
441   "list of all constants encountered during compilation of this form")
442 (defvar byte-compile-variables nil
443   "list of all variables encountered during compilation of this form")
444 (defvar byte-compile-bound-variables nil
445   "Alist of variables bound in the context of the current form,
446 that is, the current lexical environment.  This list lives partly
447 on the specbind stack.  The cdr of each cell is an integer bitmask.")
448
449 (defconst byte-compile-referenced-bit 1)
450 (defconst byte-compile-assigned-bit 2)
451 (defconst byte-compile-arglist-bit 4)
452 (defconst byte-compile-global-bit 8)
453
454 (defvar byte-compile-free-references)
455 (defvar byte-compile-free-assignments)
456
457 (defvar byte-compiler-error-flag)
458
459 ;;; A form of eval that includes the currently defined macro definitions.
460 ;;; This helps implement the promise made in the Lispref:
461 ;;;
462 ;;; "If a file being compiled contains a `defmacro' form, the macro is
463 ;;; defined temporarily for the rest of the compilation of that file."
464 (defun byte-compile-eval (form)
465   (let ((save-macro-environment nil))
466     (unwind-protect
467         (loop for (sym . def) in byte-compile-macro-environment do
468           (push
469            (if (fboundp sym) (cons sym (symbol-function sym)) sym)
470            save-macro-environment)
471           (fset sym (cons 'macro def))
472           finally return (eval form))
473       (dolist (elt save-macro-environment)
474         (if (symbolp elt)
475             (fmakunbound elt)
476           (fset (car elt) (cdr elt)))))))
477
478 (defconst byte-compile-initial-macro-environment
479   '((byte-compiler-options . (lambda (&rest forms)
480                                (apply 'byte-compiler-options-handler forms)))
481     (eval-when-compile . (lambda (&rest body)
482                            (list 'quote (byte-compile-eval (cons 'progn body)))))
483     (eval-and-compile . (lambda (&rest body)
484                           (byte-compile-eval (cons 'progn body))
485                           (cons 'progn body))))
486   "The default macro-environment passed to macroexpand by the compiler.
487 Placing a macro here will cause a macro to have different semantics when
488 expanded by the compiler as when expanded by the interpreter.")
489
490 (defvar byte-compile-macro-environment byte-compile-initial-macro-environment
491   "Alist of macros defined in the file being compiled.
492 Each element looks like (MACRONAME . DEFINITION).  It is
493 \(MACRONAME . nil) when a macro is redefined as a function.")
494
495 (defvar byte-compile-function-environment nil
496   "Alist of functions defined in the file being compiled.
497 This is so we can inline them when necessary.
498 Each element looks like (FUNCTIONNAME . DEFINITION).  It is
499 \(FUNCTIONNAME . nil) when a function is redefined as a macro.")
500
501 (defvar byte-compile-autoload-environment nil
502  "Alist of functions and macros defined by autoload in the file being compiled.
503 This is so we can suppress warnings about calls to these functions, even though
504 they do not have `real' definitions.
505 Each element looks like (FUNCTIONNAME . CALL-TO-AUTOLOAD).")
506
507 (defvar byte-compile-unresolved-functions nil
508   "Alist of undefined functions to which calls have been compiled (used for
509 warnings when the function is later defined with incorrect args).")
510
511 (defvar byte-compile-file-domain) ; domain of file being compiled
512
513 (defvar byte-compile-tag-number 0)
514 (defvar byte-compile-output nil
515   "Alist describing contents to put in byte code string.
516 Each element is (INDEX . VALUE)")
517 (defvar byte-compile-depth 0 "Current depth of execution stack.")
518 (defvar byte-compile-maxdepth 0 "Maximum depth of execution stack.")
519
520 \f
521 ;;; The byte codes; this information is duplicated in bytecode.c
522
523 (defconst byte-code-vector nil
524   "An array containing byte-code names indexed by byte-code values.")
525
526 (defconst byte-stack+-info nil
527   "An array with the stack adjustment for each byte-code.")
528
529 (defmacro byte-defop (opcode stack-adjust opname &optional docstring)
530   ;; This is a speed-hack for building the byte-code-vector at compile-time.
531   ;; We fill in the vector at macroexpand-time, and then after the last call
532   ;; to byte-defop, we write the vector out as a constant instead of writing
533   ;; out a bunch of calls to aset.
534   ;; Actually, we don't fill in the vector itself, because that could make
535   ;; it problematic to compile big changes to this compiler; we store the
536   ;; values on its plist, and remove them later in -extrude.
537   (let ((v1 (or (get 'byte-code-vector 'tmp-compile-time-value)
538                 (put 'byte-code-vector 'tmp-compile-time-value
539                      (make-vector 256 nil))))
540         (v2 (or (get 'byte-stack+-info 'tmp-compile-time-value)
541                 (put 'byte-stack+-info 'tmp-compile-time-value
542                      (make-vector 256 nil)))))
543     (aset v1 opcode opname)
544     (aset v2 opcode stack-adjust))
545   (if docstring
546       (list 'defconst opname opcode (concat "Byte code opcode " docstring "."))
547       (list 'defconst opname opcode)))
548
549 (defmacro byte-extrude-byte-code-vectors ()
550   (prog1 (list 'setq 'byte-code-vector
551                      (get 'byte-code-vector 'tmp-compile-time-value)
552                      'byte-stack+-info
553                      (get 'byte-stack+-info 'tmp-compile-time-value))
554     (remprop 'byte-code-vector 'tmp-compile-time-value)
555     (remprop 'byte-stack+-info 'tmp-compile-time-value)))
556
557
558 ;; unused: 0-7
559
560 ;; These opcodes are special in that they pack their argument into the
561 ;; opcode word.
562 ;;
563 (byte-defop   8  1 byte-varref  "for variable reference")
564 (byte-defop  16 -1 byte-varset  "for setting a variable")
565 (byte-defop  24 -1 byte-varbind "for binding a variable")
566 (byte-defop  32  0 byte-call    "for calling a function")
567 (byte-defop  40  0 byte-unbind  "for unbinding special bindings")
568 ;; codes 8-47 are consumed by the preceding opcodes
569
570 ;; unused: 48-55
571
572 (byte-defop  56 -1 byte-nth)
573 (byte-defop  57  0 byte-symbolp)
574 (byte-defop  58  0 byte-consp)
575 (byte-defop  59  0 byte-stringp)
576 (byte-defop  60  0 byte-listp)
577 (byte-defop  61 -1 byte-old-eq)
578 (byte-defop  62 -1 byte-old-memq)
579 (byte-defop  63  0 byte-not)
580 (byte-defop  64  0 byte-car)
581 (byte-defop  65  0 byte-cdr)
582 (byte-defop  66 -1 byte-cons)
583 (byte-defop  67  0 byte-list1)
584 (byte-defop  68 -1 byte-list2)
585 (byte-defop  69 -2 byte-list3)
586 (byte-defop  70 -3 byte-list4)
587 (byte-defop  71  0 byte-length)
588 (byte-defop  72 -1 byte-aref)
589 (byte-defop  73 -2 byte-aset)
590 (byte-defop  74  0 byte-symbol-value)
591 (byte-defop  75  0 byte-symbol-function) ; this was commented out
592 (byte-defop  76 -1 byte-set)
593 (byte-defop  77 -1 byte-fset) ; this was commented out
594 (byte-defop  78 -1 byte-get)
595 (byte-defop  79 -2 byte-substring)
596 (byte-defop  80 -1 byte-concat2)
597 (byte-defop  81 -2 byte-concat3)
598 (byte-defop  82 -3 byte-concat4)
599 (byte-defop  83  0 byte-sub1)
600 (byte-defop  84  0 byte-add1)
601 (byte-defop  85 -1 byte-eqlsign)
602 (byte-defop  86 -1 byte-gtr)
603 (byte-defop  87 -1 byte-lss)
604 (byte-defop  88 -1 byte-leq)
605 (byte-defop  89 -1 byte-geq)
606 (byte-defop  90 -1 byte-diff)
607 (byte-defop  91  0 byte-negate)
608 (byte-defop  92 -1 byte-plus)
609 (byte-defop  93 -1 byte-max)
610 (byte-defop  94 -1 byte-min)
611 (byte-defop  95 -1 byte-mult)
612 (byte-defop  96  1 byte-point)
613 (byte-defop  97 -1 byte-eq) ; new as of v20
614 (byte-defop  98  0 byte-goto-char)
615 (byte-defop  99  0 byte-insert)
616 (byte-defop 100  1 byte-point-max)
617 (byte-defop 101  1 byte-point-min)
618 (byte-defop 102  0 byte-char-after)
619 (byte-defop 103  1 byte-following-char)
620 (byte-defop 104  1 byte-preceding-char)
621 (byte-defop 105  1 byte-current-column)
622 (byte-defop 106  0 byte-indent-to)
623 (byte-defop 107 -1 byte-equal) ; new as of v20
624 (byte-defop 108  1 byte-eolp)
625 (byte-defop 109  1 byte-eobp)
626 (byte-defop 110  1 byte-bolp)
627 (byte-defop 111  1 byte-bobp)
628 (byte-defop 112  1 byte-current-buffer)
629 (byte-defop 113  0 byte-set-buffer)
630 (byte-defop 114  0 byte-save-current-buffer
631   "To make a binding to record the current buffer.")
632 ;;(byte-defop 114  1 byte-read-char-OBSOLETE) ;obsolete as of v19
633 (byte-defop 115 -1 byte-memq) ; new as of v20
634 (byte-defop 116  1 byte-interactive-p)
635
636 (byte-defop 117  0 byte-forward-char)
637 (byte-defop 118  0 byte-forward-word)
638 (byte-defop 119 -1 byte-skip-chars-forward)
639 (byte-defop 120 -1 byte-skip-chars-backward)
640 (byte-defop 121  0 byte-forward-line)
641 (byte-defop 122  0 byte-char-syntax)
642 (byte-defop 123 -1 byte-buffer-substring)
643 (byte-defop 124 -1 byte-delete-region)
644 (byte-defop 125 -1 byte-narrow-to-region)
645 (byte-defop 126  1 byte-widen)
646 (byte-defop 127  0 byte-end-of-line)
647
648 ;; unused: 128
649
650 ;; These store their argument in the next two bytes
651 (byte-defop 129  1 byte-constant2
652    "for reference to a constant with vector index >= byte-constant-limit")
653 (byte-defop 130  0 byte-goto "for unconditional jump")
654 (byte-defop 131 -1 byte-goto-if-nil "to pop value and jump if it's nil")
655 (byte-defop 132 -1 byte-goto-if-not-nil
656             "to pop value and jump if it's not nil")
657 (byte-defop 133 -1 byte-goto-if-nil-else-pop
658   "to examine top-of-stack, jump and don't pop it if it's nil,
659 otherwise pop it")
660 (byte-defop 134 -1 byte-goto-if-not-nil-else-pop
661   "to examine top-of-stack, jump and don't pop it if it's non-nil,
662 otherwise pop it")
663
664 (byte-defop 135 -1 byte-return "to pop a value and return it from `byte-code'")
665 (byte-defop 136 -1 byte-discard "to discard one value from stack")
666 (byte-defop 137  1 byte-dup     "to duplicate the top of the stack")
667
668 (byte-defop 138  0 byte-save-excursion
669   "to make a binding to record the buffer, point and mark")
670 (byte-defop 139  0 byte-save-window-excursion
671   "to make a binding to record entire window configuration")
672 (byte-defop 140  0 byte-save-restriction
673   "to make a binding to record the current buffer clipping restrictions")
674 (byte-defop 141 -1 byte-catch
675   "for catch.  Takes, on stack, the tag and an expression for the body")
676 (byte-defop 142 -1 byte-unwind-protect
677   "for unwind-protect.  Takes, on stack, an expression for the unwind-action")
678
679 ;; For condition-case.  Takes, on stack, the variable to bind,
680 ;; an expression for the body, and a list of clauses.
681 (byte-defop 143 -2 byte-condition-case)
682
683 ;; For entry to with-output-to-temp-buffer.
684 ;; Takes, on stack, the buffer name.
685 ;; Binds standard-output and does some other things.
686 ;; Returns with temp buffer on the stack in place of buffer name.
687 (byte-defop 144  0 byte-temp-output-buffer-setup)
688
689 ;; For exit from with-output-to-temp-buffer.
690 ;; Expects the temp buffer on the stack underneath value to return.
691 ;; Pops them both, then pushes the value back on.
692 ;; Unbinds standard-output and makes the temp buffer visible.
693 (byte-defop 145 -1 byte-temp-output-buffer-show)
694
695 ;; To unbind back to the beginning of this frame.
696 ;; Not used yet, but will be needed for tail-recursion elimination.
697 (byte-defop 146  0 byte-unbind-all)
698
699 (byte-defop 147 -2 byte-set-marker)
700 (byte-defop 148  0 byte-match-beginning)
701 (byte-defop 149  0 byte-match-end)
702 (byte-defop 150  0 byte-upcase)
703 (byte-defop 151  0 byte-downcase)
704 (byte-defop 152 -1 byte-string=)
705 (byte-defop 153 -1 byte-string<)
706 (byte-defop 154 -1 byte-old-equal)
707 (byte-defop 155 -1 byte-nthcdr)
708 (byte-defop 156 -1 byte-elt)
709 (byte-defop 157 -1 byte-old-member)
710 (byte-defop 158 -1 byte-old-assq)
711 (byte-defop 159  0 byte-nreverse)
712 (byte-defop 160 -1 byte-setcar)
713 (byte-defop 161 -1 byte-setcdr)
714 (byte-defop 162  0 byte-car-safe)
715 (byte-defop 163  0 byte-cdr-safe)
716 (byte-defop 164 -1 byte-nconc)
717 (byte-defop 165 -1 byte-quo)
718 (byte-defop 166 -1 byte-rem)
719 (byte-defop 167  0 byte-numberp)
720 (byte-defop 168  0 byte-integerp)
721
722 ;; unused: 169
723
724 ;; These are not present in FSF.
725 ;;
726 (byte-defop 170  0 byte-rel-goto)
727 (byte-defop 171 -1 byte-rel-goto-if-nil)
728 (byte-defop 172 -1 byte-rel-goto-if-not-nil)
729 (byte-defop 173 -1 byte-rel-goto-if-nil-else-pop)
730 (byte-defop 174 -1 byte-rel-goto-if-not-nil-else-pop)
731
732 (byte-defop 175 nil byte-listN)
733 (byte-defop 176 nil byte-concatN)
734 (byte-defop 177 nil byte-insertN)
735
736 ;; unused: 178-181
737
738 ;; these ops are new to v20
739 (byte-defop 182 -1 byte-member)
740 (byte-defop 183 -1 byte-assq)
741
742 ;; unused: 184-191
743 (byte-defop #o0270 0 byte-cl:macro)     ;; think 184 is used now
744
745 (byte-defop 192  1 byte-constant        "for reference to a constant")
746 ;; codes 193-255 are consumed by byte-constant.
747 (defconst byte-constant-limit 64
748   "Exclusive maximum index usable in the `byte-constant' opcode.")
749
750 (defconst byte-goto-ops
751   '(byte-goto byte-goto-if-nil byte-goto-if-not-nil
752               byte-goto-if-nil-else-pop
753               byte-goto-if-not-nil-else-pop)
754   "List of byte-codes whose offset is a pc.")
755
756 (defconst byte-goto-always-pop-ops
757   '(byte-goto-if-nil byte-goto-if-not-nil))
758
759 (defconst byte-rel-goto-ops
760   '(byte-rel-goto byte-rel-goto-if-nil byte-rel-goto-if-not-nil
761                   byte-rel-goto-if-nil-else-pop byte-rel-goto-if-not-nil-else-pop)
762   "byte-codes for relative jumps.")
763
764 (byte-extrude-byte-code-vectors)
765 \f
766 ;;; lapcode generator
767 ;;;
768 ;;; the byte-compiler now does source -> lapcode -> bytecode instead of
769 ;;; source -> bytecode, because it's a lot easier to make optimizations
770 ;;; on lapcode than on bytecode.
771 ;;;
772 ;;; Elements of the lapcode list are of the form (<instruction> . <parameter>)
773 ;;; where instruction is a symbol naming a byte-code instruction,
774 ;;; and parameter is an argument to that instruction, if any.
775 ;;;
776 ;;; The instruction can be the pseudo-op TAG, which means that this position
777 ;;; in the instruction stream is a target of a goto.  (car PARAMETER) will be
778 ;;; the PC for this location, and the whole instruction "(TAG pc)" will be the
779 ;;; parameter for some goto op.
780 ;;;
781 ;;; If the operation is varbind, varref, varset or push-constant, then the
782 ;;; parameter is (variable/constant . index_in_constant_vector).
783 ;;;
784 ;;; First, the source code is macroexpanded and optimized in various ways.
785 ;;; Then the resultant code is compiled into lapcode.  Another set of
786 ;;; optimizations are then run over the lapcode.  Then the variables and
787 ;;; constants referenced by the lapcode are collected and placed in the
788 ;;; constants-vector.  (This happens now so that variables referenced by dead
789 ;;; code don't consume space.)  And finally, the lapcode is transformed into
790 ;;; compacted byte-code.
791 ;;;
792 ;;; A distinction is made between variables and constants because the variable-
793 ;;; referencing instructions are more sensitive to the variables being near the
794 ;;; front of the constants-vector than the constant-referencing instructions.
795 ;;; Also, this lets us notice references to free variables.
796
797 (defun byte-compile-lapcode (lap)
798   "Turns lapcode into bytecode.  The lapcode is destroyed."
799   ;; Lapcode modifications: changes the ID of a tag to be the tag's PC.
800   (let ((pc 0)                  ; Program counter
801         op off                  ; Operation & offset
802         (bytes '())             ; Put the output bytes here
803         (patchlist nil)         ; List of tags and goto's to patch
804         rest rel tmp)
805     (while lap
806       (setq op (car (car lap))
807             off (cdr (car lap)))
808       (cond ((not (symbolp op))
809              (error "Non-symbolic opcode `%s'" op))
810             ((eq op 'TAG)
811              (setcar off pc)
812              (push off patchlist))
813             ((memq op byte-goto-ops)
814              (setq pc (+ pc 3))
815              (setq bytes (cons (cons pc (cdr off))
816                                (cons nil
817                                      (cons (symbol-value op) bytes))))
818              (push bytes patchlist))
819             (t
820              (setq bytes
821                    (cond ((cond ((consp off)
822                                  ;; Variable or constant reference
823                                  (setq off (cdr off))
824                                  (eq op 'byte-constant)))
825                           (cond ((< off byte-constant-limit)
826                                  (setq pc (1+ pc))
827                                  (cons (+ byte-constant off) bytes))
828                                 (t
829                                  (setq pc (+ 3 pc))
830                                  (cons (lsh off -8)
831                                        (cons (logand off 255)
832                                              (cons byte-constant2 bytes))))))
833                          ((and (<= byte-listN (symbol-value op))
834                                (<= (symbol-value op) byte-insertN))
835                           (setq pc (+ 2 pc))
836                           (cons off (cons (symbol-value op) bytes)))
837                          ((< off 6)
838                           (setq pc (1+ pc))
839                           (cons (+ (symbol-value op) off) bytes))
840                          ((< off 256)
841                           (setq pc (+ 2 pc))
842                           (cons off (cons (+ (symbol-value op) 6) bytes)))
843                          (t
844                           (setq pc (+ 3 pc))
845                           (cons (lsh off -8)
846                                 (cons (logand off 255)
847                                       (cons (+ (symbol-value op) 7)
848                                             bytes))))))))
849       (setq lap (cdr lap)))
850     ;;(if (not (= pc (length bytes)))
851     ;;    (error "Compiler error: pc mismatch - %s %s" pc (length bytes)))
852     (cond (t ;; starting with Emacs 19.
853            ;; Make relative jumps
854            (setq patchlist (nreverse patchlist))
855            (while (progn
856                     (setq off 0)        ; PC change because of deleted bytes
857                     (setq rest patchlist)
858                     (while rest
859                       (setq tmp (car rest))
860                       (and (consp (car tmp)) ; Jump
861                            (prog1 (null (nth 1 tmp)) ; Absolute jump
862                              (setq tmp (car tmp)))
863                            (progn
864                              (setq rel (- (car (cdr tmp)) (car tmp)))
865                              (and (<= -129 rel) (< rel 128)))
866                            (progn
867                              ;; Convert to relative jump.
868                              (setcdr (car rest) (cdr (cdr (car rest))))
869                              (setcar (cdr (car rest))
870                                      (+ (car (cdr (car rest)))
871                                         (- byte-rel-goto byte-goto)))
872                              (setq off (1- off))))
873                       (setcar tmp (+ (car tmp) off)) ; Adjust PC
874                       (setq rest (cdr rest)))
875                     ;; If optimizing, repeat until no change.
876                     (and byte-optimize
877                          (not (zerop off)))))))
878     ;; Patch PC into jumps
879     (let (bytes)
880       (while patchlist
881         (setq bytes (car patchlist))
882         (cond ((atom (car bytes)))      ; Tag
883               ((nth 1 bytes)            ; Relative jump
884                (setcar bytes (+ (- (car (cdr (car bytes))) (car (car bytes)))
885                                 128)))
886               (t                        ; Absolute jump
887                (setq pc (car (cdr (car bytes))))        ; Pick PC from tag
888                (setcar (cdr bytes) (logand pc 255))
889                (setcar bytes (lsh pc -8))))
890         (setq patchlist (cdr patchlist))))
891     (concat (nreverse bytes))))
892
893 \f
894 ;;; byte compiler messages
895
896 (defvar byte-compile-current-form nil)
897 (defvar byte-compile-current-file nil)
898 (defvar byte-compile-dest-file nil)
899
900 (defmacro byte-compile-log (format-string &rest args)
901   `(when (and byte-optimize (memq byte-optimize-log '(t source)))
902       (let ((print-escape-newlines t)
903             (print-level 4)
904             (print-length 4))
905         (byte-compile-log-1 (format ,format-string ,@args)))))
906
907 (defconst byte-compile-last-warned-form 'nothing)
908
909 ;; Log a message STRING in *Compile-Log*.
910 ;; Also log the current function and file if not already done.
911 (defun byte-compile-log-1 (string &optional fill)
912   (let* ((this-form (or byte-compile-current-form "toplevel forms"))
913          (while-compiling-msg
914           (when (or byte-compile-current-file
915                     (not (eq this-form byte-compile-last-warned-form)))
916             (format
917              "While compiling %s%s:"
918              this-form
919              (cond
920               ((stringp byte-compile-current-file)
921                (concat " in file " byte-compile-current-file))
922               ((bufferp byte-compile-current-file)
923                (concat " in buffer "
924                        (buffer-name byte-compile-current-file)))
925               (""))))))
926     (if noninteractive
927         (progn
928           (when while-compiling-msg (message "%s" while-compiling-msg))
929           (message "  %s" string))
930       (with-current-buffer (get-buffer-create "*Compile-Log*")
931         (goto-char (point-max))
932         (when byte-compile-current-file
933           (when (> (point-max) (point-min))
934             (insert "\n\^L\n"))
935           (insert (current-time-string) "\n"))
936         (when while-compiling-msg (insert while-compiling-msg "\n"))
937         (insert "  " string "\n")
938         (when (and fill (not (string-match "\n" string)))
939           (let ((fill-prefix "     ")
940                 (fill-column 78))
941             (fill-paragraph nil)))))
942     (setq byte-compile-current-file nil)
943     (setq byte-compile-last-warned-form this-form)))
944
945 ;; Log the start of a file in *Compile-Log*, and mark it as done.
946 ;; But do nothing in batch mode.
947 (defun byte-compile-log-file ()
948   (when (and byte-compile-current-file (not noninteractive))
949     (with-current-buffer (get-buffer-create "*Compile-Log*")
950       (when (> (point-max) (point-min))
951         (goto-char (point-max))
952         (insert "\n\^L\n"))
953       (insert "Compiling "
954               (if (stringp byte-compile-current-file)
955                   (concat "file " byte-compile-current-file)
956                 (concat "buffer " (buffer-name byte-compile-current-file)))
957               " at " (current-time-string) "\n")
958       (setq byte-compile-current-file nil))))
959
960 (defun byte-compile-warn (format &rest args)
961   (setq format (apply 'format format args))
962   (if byte-compile-error-on-warn
963       (error "%s" format)               ; byte-compile-file catches and logs it
964     (byte-compile-log-1 (concat "** " format) t)
965 ;;; RMS says:
966 ;;; It is useless to flash warnings too fast to be read.
967 ;;; Besides, they will all be shown at the end.
968 ;;; and comments out the next two lines.
969     (or noninteractive  ; already written on stdout.
970         (message "Warning: %s" format))))
971
972 ;;; This function should be used to report errors that have halted
973 ;;; compilation of the current file.
974 (defun byte-compile-report-error (error-info)
975   (setq byte-compiler-error-flag t)
976   (byte-compile-log-1
977    (concat "!! "
978            (format (if (cdr error-info) "%s (%s)" "%s")
979                    (get (car error-info) 'error-message)
980                    (prin1-to-string (cdr error-info)))))
981   (if stack-trace-on-error
982       (backtrace nil t)))
983
984 ;;; Used by make-obsolete.
985 (defun byte-compile-obsolete (form)
986   (let ((new (get (car form) 'byte-obsolete-info)))
987     (if (memq 'obsolete byte-compile-warnings)
988         (byte-compile-warn "%s is an obsolete function; %s" (car form)
989                            (if (stringp (car new))
990                                (car new)
991                              (format "use %s instead." (car new)))))
992     (funcall (or (cdr new) 'byte-compile-normal-call) form)))
993
994 ;;; Used by make-obsolete.
995 (defun byte-compile-compatible (form)
996   (let ((new (get (car form) 'byte-compatible-info)))
997     (if (memq 'pedantic byte-compile-warnings)
998         (byte-compile-warn "%s is provided for compatibility; %s" (car form)
999                            (if (stringp (car new))
1000                                (car new)
1001                              (format "use %s instead." (car new)))))
1002     (funcall (or (cdr new) 'byte-compile-normal-call) form)))
1003 \f
1004 ;; Compiler options
1005
1006 (defconst byte-compiler-legal-options
1007   '((optimize byte-optimize (t nil source byte) val)
1008     (file-format byte-compile-emacs19-compatibility (emacs19 emacs20)
1009                  (eq val 'emacs19))
1010     (delete-errors byte-compile-delete-errors (t nil) val)
1011     (verbose byte-compile-verbose (t nil) val)
1012     (new-bytecodes byte-compile-new-bytecodes (t nil) val)
1013     (warnings byte-compile-warnings
1014               ((callargs subr-callargs redefine free-vars unused-vars unresolved))
1015               val)))
1016
1017 ;; XEmacs addition
1018 (defconst byte-compiler-obsolete-options
1019   '((new-bytecodes t)))
1020
1021 ;; Inhibit v19/v20 selectors if the version is hardcoded.
1022 ;; #### This should print a warning if the user tries to change something
1023 ;; than can't be changed because the running compiler doesn't support it.
1024 (cond
1025  ((byte-compile-single-version)
1026   (setcar (cdr (cdr (assq 'file-format byte-compiler-legal-options)))
1027           (if (byte-compile-version-cond byte-compile-emacs19-compatibility)
1028               '(emacs19) '(emacs20)))))
1029
1030 ;; now we can copy it.
1031 (setq byte-compiler-legal-options byte-compiler-legal-options)
1032
1033 (defun byte-compiler-options-handler (&rest args)
1034   (let (key val desc choices)
1035     (while args
1036       (if (or (atom (car args)) (nthcdr 2 (car args)) (null (cdr (car args))))
1037           (error "malformed byte-compiler-option %s" (car args)))
1038       (setq key (car (car args))
1039             val (car (cdr (car args)))
1040             desc (assq key byte-compiler-legal-options))
1041       (or desc
1042           (error "unknown byte-compiler option %s" key))
1043       (if (assq key byte-compiler-obsolete-options)
1044           (byte-compile-warn "%s is an obsolete byte-compiler option." key))
1045       (setq choices (nth 2 desc))
1046       (if (consp (car choices))
1047           (let* (this
1048                  (handler 'cons)
1049                  (var (nth 1 desc))
1050                  (ret (and (memq (car val) '(+ -))
1051                            (copy-sequence (if (eq t (symbol-value var))
1052                                               (car choices)
1053                                             (symbol-value var))))))
1054             (setq choices (car  choices))
1055             (while val
1056               (setq this (car val))
1057               (cond ((memq this choices)
1058                      (setq ret (funcall handler this ret)))
1059                     ((eq this '+) (setq handler 'cons))
1060                     ((eq this '-) (setq handler 'delq))
1061                     ((error "%s only accepts %s." key choices)))
1062               (setq val (cdr val)))
1063             (set (nth 1 desc) ret))
1064         (or (memq val choices)
1065             (error "%s must be one of %s." key choices))
1066         (set (nth 1 desc) (eval (nth 3 desc))))
1067       (setq args (cdr args)))
1068     nil))
1069 \f
1070 ;;; sanity-checking arglists
1071
1072 (defun byte-compile-fdefinition (name macro-p)
1073   (let* ((list (if (memq macro-p '(nil subr))
1074                    byte-compile-function-environment
1075                  byte-compile-macro-environment))
1076          (env (cdr (assq name list))))
1077     (or env
1078         (let ((fn name))
1079           (while (and (symbolp fn)
1080                       (fboundp fn)
1081                       (or (symbolp (symbol-function fn))
1082                           (consp (symbol-function fn))
1083                           (and (not macro-p)
1084                                (compiled-function-p (symbol-function fn)))
1085                           (and (eq macro-p 'subr) (subrp fn))))
1086             (setq fn (symbol-function fn)))
1087           (if (or (and (not macro-p) (compiled-function-p fn))
1088                   (and (eq macro-p 'subr) (subrp fn)))
1089               fn
1090             (and (consp fn)
1091                  (not (eq macro-p 'subr))
1092                  (if (eq 'macro (car fn))
1093                      (cdr fn)
1094                    (if macro-p
1095                        nil
1096                      (if (eq 'autoload (car fn))
1097                          nil
1098                        fn)))))))))
1099
1100 (defun byte-compile-arglist-signature (arglist)
1101   (let ((args 0)
1102         opts
1103         restp)
1104     (while arglist
1105       (cond ((eq (car arglist) '&optional)
1106              (or opts (setq opts 0)))
1107             ((eq (car arglist) '&rest)
1108              (if (cdr arglist)
1109                  (setq restp t
1110                        arglist nil)))
1111             (t
1112              (if opts
1113                  (setq opts (1+ opts))
1114                  (setq args (1+ args)))))
1115       (setq arglist (cdr arglist)))
1116     (cons args (if restp nil (if opts (+ args opts) args)))))
1117
1118
1119 (defun byte-compile-arglist-signatures-congruent-p (old new)
1120   (not (or
1121          (> (car new) (car old))  ; requires more args now
1122          (and (null (cdr old))    ; tooks rest-args, doesn't any more
1123               (cdr new))
1124          (and (cdr new) (cdr old) ; can't take as many args now
1125               (< (cdr new) (cdr old)))
1126          )))
1127
1128 (defun byte-compile-arglist-signature-string (signature)
1129   (cond ((null (cdr signature))
1130          (format "%d+" (car signature)))
1131         ((= (car signature) (cdr signature))
1132          (format "%d" (car signature)))
1133         (t (format "%d-%d" (car signature) (cdr signature)))))
1134
1135
1136 ;; Warn if the form is calling a function with the wrong number of arguments.
1137 (defun byte-compile-callargs-warn (form)
1138   (let* ((def (or (byte-compile-fdefinition (car form) nil)
1139                   (byte-compile-fdefinition (car form) t)))
1140          (sig (and def (byte-compile-arglist-signature
1141                          (if (eq 'lambda (car-safe def))
1142                              (nth 1 def)
1143                            (if (compiled-function-p def)
1144                                (compiled-function-arglist def)
1145                              '(&rest def))))))
1146          (ncall (length (cdr form))))
1147     (if (and (null def)
1148              (fboundp 'subr-min-args)
1149              (setq def (byte-compile-fdefinition (car form) 'subr)))
1150         (setq sig (cons (subr-min-args def) (subr-max-args def))))
1151     (if sig
1152         (if (or (< ncall (car sig))
1153                 (and (cdr sig) (> ncall (cdr sig))))
1154             (byte-compile-warn
1155               "%s called with %d argument%s, but %s %s"
1156               (car form) ncall
1157               (if (= 1 ncall) "" "s")
1158               (if (< ncall (car sig))
1159                   "requires"
1160                   "accepts only")
1161               (byte-compile-arglist-signature-string sig)))
1162       (or (fboundp (car form)) ; might be a subr or autoload.
1163           ;; ## this doesn't work with recursion.
1164           (eq (car form) byte-compile-current-form)
1165           ;; It's a currently-undefined function.
1166           ;; Remember number of args in call.
1167           (let ((cons (assq (car form) byte-compile-unresolved-functions))
1168                 (n (length (cdr form))))
1169             (if cons
1170                 (or (memq n (cdr cons))
1171                     (setcdr cons (cons n (cdr cons))))
1172                 (setq byte-compile-unresolved-functions
1173                       (cons (list (car form) n)
1174                             byte-compile-unresolved-functions))))))))
1175
1176 ;; Warn if the function or macro is being redefined with a different
1177 ;; number of arguments.
1178 (defun byte-compile-arglist-warn (form macrop)
1179   (let ((old (byte-compile-fdefinition (nth 1 form) macrop)))
1180     (if old
1181         (let ((sig1 (byte-compile-arglist-signature
1182                       (if (eq 'lambda (car-safe old))
1183                           (nth 1 old)
1184                         (if (compiled-function-p old)
1185                             (compiled-function-arglist old)
1186                           '(&rest def)))))
1187               (sig2 (byte-compile-arglist-signature (nth 2 form))))
1188           (or (byte-compile-arglist-signatures-congruent-p sig1 sig2)
1189               (byte-compile-warn "%s %s used to take %s %s, now takes %s"
1190                 (if (eq (car form) 'defun) "function" "macro")
1191                 (nth 1 form)
1192                 (byte-compile-arglist-signature-string sig1)
1193                 (if (equal sig1 '(1 . 1)) "argument" "arguments")
1194                 (byte-compile-arglist-signature-string sig2))))
1195       ;; This is the first definition.  See if previous calls are compatible.
1196       (let ((calls (assq (nth 1 form) byte-compile-unresolved-functions))
1197             nums sig min max)
1198         (if calls
1199             (progn
1200               (setq sig (byte-compile-arglist-signature (nth 2 form))
1201                     nums (sort (copy-sequence (cdr calls)) (function <))
1202                     min (car nums)
1203                     max (car (nreverse nums)))
1204               (if (or (< min (car sig))
1205                       (and (cdr sig) (> max (cdr sig))))
1206                   (byte-compile-warn
1207             "%s being defined to take %s%s, but was previously called with %s"
1208                     (nth 1 form)
1209                     (byte-compile-arglist-signature-string sig)
1210                     (if (equal sig '(1 . 1)) " arg" " args")
1211                     (byte-compile-arglist-signature-string (cons min max))))
1212
1213               (setq byte-compile-unresolved-functions
1214                     (delq calls byte-compile-unresolved-functions)))))
1215       )))
1216
1217 ;; If we have compiled any calls to functions which are not known to be
1218 ;; defined, issue a warning enumerating them.
1219 ;; `unresolved' in the list `byte-compile-warnings' disables this.
1220 (defun byte-compile-warn-about-unresolved-functions (&optional msg)
1221   (if (memq 'unresolved byte-compile-warnings)
1222    (let ((byte-compile-current-form (or msg "the end of the data")))
1223      ;; First delete the autoloads from the list.
1224      (if byte-compile-autoload-environment
1225          (let ((rest byte-compile-unresolved-functions))
1226            (while rest
1227              (if (assq (car (car rest)) byte-compile-autoload-environment)
1228                  (setq byte-compile-unresolved-functions
1229                        (delq (car rest) byte-compile-unresolved-functions)))
1230              (setq rest (cdr rest)))))
1231      ;; Now warn.
1232      (if (cdr byte-compile-unresolved-functions)
1233          (let* ((str "The following functions are not known to be defined: ")
1234                 (L (+ (length str) 5))
1235                 (rest (reverse byte-compile-unresolved-functions))
1236                 s)
1237            (while rest
1238              (setq s (symbol-name (car (car rest)))
1239                    L (+ L (length s) 2)
1240                    rest (cdr rest))
1241              (if (<= L (1- fill-column))
1242                  (setq str (concat str " " s (and rest ",")))
1243                (setq str (concat str "\n    " s (and rest ","))
1244                      L (+ (length s) 4))))
1245            (byte-compile-warn "%s" str))
1246        (if byte-compile-unresolved-functions
1247            (byte-compile-warn "the function %s is not known to be defined."
1248             (car (car byte-compile-unresolved-functions)))))))
1249   nil)
1250
1251 (defun byte-compile-defvar-p (var)
1252   ;; Whether the byte compiler thinks that non-lexical references to this
1253   ;; variable are ok.
1254   (or (globally-boundp var)
1255       (let ((rest byte-compile-bound-variables))
1256         (while (and rest var)
1257           (if (and (eq var (car-safe (car rest)))
1258                    (not (= 0 (logand (cdr (car rest))
1259                                      byte-compile-global-bit))))
1260               (setq var nil))
1261           (setq rest (cdr rest)))
1262         ;; if var is nil at this point, it's a defvar in this file.
1263         (not var))
1264       ;; Perhaps (eval-when-compile (defvar foo))
1265       (and (boundp 'current-load-list)
1266            (memq var current-load-list))))
1267
1268
1269 ;;; If we have compiled bindings of variables which have no referents, warn.
1270 (defun byte-compile-warn-about-unused-variables ()
1271   (let ((rest byte-compile-bound-variables)
1272         (unreferenced '())
1273         cell)
1274     (while (and rest
1275                 ;; only warn about variables whose lifetime is now ending,
1276                 ;; that is, variables from the lexical scope that is now
1277                 ;; terminating.  (Think nested lets.)
1278                 (not (eq (car rest) 'new-scope)))
1279       (setq cell (car rest))
1280       (if (and (= 0 (logand byte-compile-referenced-bit (cdr cell)))
1281                ;; Don't warn about declared-but-unused arguments,
1282                ;; for two reasons: first, the arglist structure
1283                ;; might be imposed by external forces, and we don't
1284                ;; have (declare (ignore x)) yet; and second, inline
1285                ;; expansion produces forms like
1286                ;;   ((lambda (arg) (byte-code "..." [arg])) x)
1287                ;; which we can't (ok, well, don't) recognize as
1288                ;; containing a reference to arg, so every inline
1289                ;; expansion would generate a warning.  (If we had
1290                ;; `ignore' then inline expansion could emit an
1291                ;; ignore declaration.)
1292                (= 0 (logand byte-compile-arglist-bit (cdr cell)))
1293                ;; Don't warn about defvars because this is a
1294                ;; legitimate special binding.
1295                (not (byte-compile-defvar-p (car cell))))
1296           (setq unreferenced (cons (car cell) unreferenced)))
1297       (setq rest (cdr rest)))
1298     (setq unreferenced (nreverse unreferenced))
1299     (while unreferenced
1300       (byte-compile-warn
1301        "variable %s bound but not referenced" (car unreferenced))
1302       (setq unreferenced (cdr unreferenced)))))
1303
1304 \f
1305 (defmacro byte-compile-constant-symbol-p (symbol)
1306   `(or (keywordp ,symbol) (memq ,symbol '(nil t))))
1307
1308 (defmacro byte-compile-constp (form)
1309   ;; Returns non-nil if FORM is a constant.
1310   `(cond ((consp ,form) (eq (car ,form) 'quote))
1311          ((symbolp ,form) (byte-compile-constant-symbol-p ,form))
1312          (t)))
1313
1314 (defmacro byte-compile-close-variables (&rest body)
1315   `(let
1316        (;;
1317         ;; Close over these variables to encapsulate the
1318         ;; compilation state
1319         ;;
1320         (byte-compile-macro-environment
1321          ;; Copy it because the compiler may patch into the
1322          ;; macroenvironment.
1323          (copy-alist byte-compile-initial-macro-environment))
1324         (byte-compile-function-environment nil)
1325         (byte-compile-autoload-environment nil)
1326         (byte-compile-unresolved-functions nil)
1327         (byte-compile-bound-variables nil)
1328         (byte-compile-free-references nil)
1329         (byte-compile-free-assignments nil)
1330         ;;
1331         ;; Close over these variables so that `byte-compiler-options'
1332         ;; can change them on a per-file basis.
1333         ;;
1334         (byte-compile-verbose byte-compile-verbose)
1335         (byte-optimize byte-optimize)
1336         (byte-compile-emacs19-compatibility
1337          byte-compile-emacs19-compatibility)
1338         (byte-compile-dynamic byte-compile-dynamic)
1339         (byte-compile-dynamic-docstrings
1340          byte-compile-dynamic-docstrings)
1341         (byte-compile-warnings (if (eq byte-compile-warnings t)
1342                                    byte-compile-default-warnings
1343                                  byte-compile-warnings))
1344         (byte-compile-file-domain nil))
1345      (prog1
1346          (progn ,@body)
1347        (if (memq 'unused-vars byte-compile-warnings)
1348            ;; done compiling in this scope, warn now.
1349            (byte-compile-warn-about-unused-variables)))))
1350
1351
1352 (defmacro displaying-byte-compile-warnings (&rest body)
1353   `(let* ((byte-compile-log-buffer (get-buffer-create "*Compile-Log*"))
1354           (byte-compile-point-max-prev (point-max byte-compile-log-buffer)))
1355      ;; Log the file name or buffer name.
1356      (byte-compile-log-file)
1357      ;; Record how much is logged now.
1358      ;; We will display the log buffer if anything more is logged
1359      ;; before the end of BODY.
1360      (defvar byte-compile-warnings-beginning)
1361      (let ((byte-compile-warnings-beginning
1362             (if (boundp 'byte-compile-warnings-beginning)
1363                 byte-compile-warnings-beginning
1364               (point-max byte-compile-log-buffer))))
1365
1366        (unwind-protect
1367            (call-with-condition-handler
1368                #'(lambda (error-info)
1369                    (byte-compile-report-error error-info))
1370                #'(lambda ()
1371                    (progn ,@body)))
1372          ;; Always set point in log to start of interesting output.
1373          (with-current-buffer byte-compile-log-buffer
1374            (let ((show-begin
1375                   (progn (goto-char byte-compile-point-max-prev)
1376                          (skip-chars-forward "\^L\n")
1377                          (point))))
1378              ;; If there were compilation warnings, display them.
1379              (if temp-buffer-show-function
1380                  (let ((show-buffer (get-buffer-create "*Compile-Log-Show*")))
1381                    ;; Always clean show-buffer, even when not displaying it,
1382                    ;; so that misleading previous messages aren't left around.
1383                    (with-current-buffer show-buffer
1384                      (setq buffer-read-only nil)
1385                      (erase-buffer))
1386                    (copy-to-buffer show-buffer show-begin (point-max))
1387                    (when (< byte-compile-warnings-beginning (point-max))
1388                      (funcall temp-buffer-show-function show-buffer)))
1389                (when (< byte-compile-warnings-beginning (point-max))
1390                  (select-window
1391                   (prog1 (selected-window)
1392                     (select-window (display-buffer (current-buffer)))
1393                     (goto-char show-begin)
1394                     (recenter 1)))))))))))
1395
1396 \f
1397 ;;;###autoload
1398 (defun byte-force-recompile (directory)
1399   "Recompile every `.el' file in DIRECTORY that already has a `.elc' file.
1400 Files in subdirectories of DIRECTORY are processed also."
1401   (interactive "DByte force recompile (directory): ")
1402   (byte-recompile-directory directory nil nil t))
1403
1404 ;;;###autoload
1405 (defun byte-recompile-directory (directory &optional arg norecursion force)
1406   "Recompile every `.el' file in DIRECTORY that needs recompilation.
1407 This is if a `.elc' file exists but is older than the `.el' file.
1408 Files in subdirectories of DIRECTORY are also processed unless
1409 optional argument NORECURSION is non-nil.
1410
1411 If the `.elc' file does not exist, normally the `.el' file is *not* compiled.
1412 But a prefix argument (optional second arg) means ask user,
1413 for each such `.el' file, whether to compile it.  Prefix argument 0 means
1414 don't ask and compile the file anyway.
1415
1416 A nonzero prefix argument also means ask about each subdirectory.
1417
1418 If the fourth optional argument FORCE is non-nil,
1419 recompile every `.el' file that already has a `.elc' file."
1420   (interactive "DByte recompile directory: \nP")
1421   (if arg
1422       (setq arg (prefix-numeric-value arg)))
1423   (if noninteractive
1424       nil
1425     (save-some-buffers)
1426     (redraw-modeline))
1427   (let ((directories (list (expand-file-name directory)))
1428         (file-count 0)
1429         (dir-count 0)
1430         last-dir)
1431     (displaying-byte-compile-warnings
1432      (while directories
1433        (setq directory (file-name-as-directory (car directories)))
1434        (or noninteractive (message "Checking %s..." directory))
1435        (let ((files (directory-files directory))
1436              source dest)
1437          (while files
1438            (setq source (expand-file-name (car files) directory))
1439            (if (and (not (member (car files) '("." ".." "RCS" "CVS" "SCCS")))
1440                     ;; Stay away from directory back-links, etc:
1441                     (not (file-symlink-p source))
1442                     (file-directory-p source)
1443                     byte-recompile-directory-recursively)
1444                ;; This file is a subdirectory.  Handle them differently.
1445                (if (or (null arg)
1446                        (eq arg 0)
1447                        (y-or-n-p (concat "Check " source "? ")))
1448                    (setq directories
1449                          (nconc directories (list source))))
1450              ;; It is an ordinary file.  Decide whether to compile it.
1451              (if (and (string-match emacs-lisp-file-regexp source)
1452                       (not (auto-save-file-name-p source))
1453                       (setq dest (byte-compile-dest-file source))
1454                       (if (file-exists-p dest)
1455                           ;; File was already compiled.
1456                           (or force (file-newer-than-file-p source dest))
1457                         ;; No compiled file exists yet.
1458                         (and arg
1459                              (or (eq 0 arg)
1460                                  (y-or-n-p (concat "Compile " source "? "))))))
1461                  (progn ;(if (and noninteractive (not byte-compile-verbose))
1462                         ;    (message "Compiling %s..." source))
1463                         ; we do this in byte-compile-file.
1464                         (if byte-recompile-directory-ignore-errors-p
1465                              (batch-byte-compile-1 source)
1466                           (byte-compile-file source))
1467                         (or noninteractive
1468                             (message "Checking %s..." directory))
1469                         (setq file-count (1+ file-count))
1470                         (if (not (eq last-dir directory))
1471                             (setq last-dir directory
1472                                   dir-count (1+ dir-count)))
1473                         )))
1474            (setq files (cdr files))))
1475        (setq directories (cdr directories))))
1476     (message "Done (Total of %d file%s compiled%s)"
1477              file-count (if (= file-count 1) "" "s")
1478              (if (> dir-count 1) (format " in %d directories" dir-count) ""))))
1479
1480 ;;;###autoload
1481 (defun byte-recompile-file (filename &optional force)
1482   "Recompile a file of Lisp code named FILENAME if it needs recompilation.
1483 This is if the `.elc' file exists but is older than the `.el' file.
1484
1485 If the `.elc' file does not exist, normally the `.el' file is *not*
1486 compiled.  But a prefix argument (optional second arg) means ask user
1487 whether to compile it.  Prefix argument 0 don't ask and recompile anyway."
1488   (interactive "fByte recompile file: \nP")
1489   (let ((dest))
1490     (if (and (string-match emacs-lisp-file-regexp filename)
1491              (not (auto-save-file-name-p filename))
1492              (setq dest (byte-compile-dest-file filename))
1493              (if (file-exists-p dest)
1494                  (file-newer-than-file-p filename dest)
1495                (and force
1496                     (or (eq 0 force)
1497                         (y-or-n-p (concat "Compile " filename "? "))))))
1498         (byte-compile-file filename))))
1499
1500 ;;;###autoload
1501 (defun byte-compile-file (filename &optional load)
1502   "Compile a file of Lisp code named FILENAME into a file of byte code.
1503 The output file's name is made by appending `c' to the end of FILENAME.
1504 With prefix arg (noninteractively: 2nd arg), load the file after compiling."
1505 ;;  (interactive "fByte compile file: \nP")
1506   (interactive
1507    (let ((file buffer-file-name)
1508          (file-name nil)
1509          (file-dir nil))
1510      (and file
1511           (eq (cdr (assq 'major-mode (buffer-local-variables)))
1512               'emacs-lisp-mode)
1513           (setq file-name (file-name-nondirectory file)
1514                 file-dir (file-name-directory file)))
1515      (list (read-file-name (if current-prefix-arg
1516                                "Byte compile and load file: "
1517                              "Byte compile file: ")
1518                            file-dir nil nil file-name)
1519            current-prefix-arg)))
1520   ;; Expand now so we get the current buffer's defaults
1521   (setq filename (expand-file-name filename))
1522
1523   ;; If we're compiling a file that's in a buffer and is modified, offer
1524   ;; to save it first.
1525   (or noninteractive
1526       (let ((b (get-file-buffer (expand-file-name filename))))
1527         (if (and b (buffer-modified-p b)
1528                  (y-or-n-p (format "save buffer %s first? " (buffer-name b))))
1529             (save-excursion (set-buffer b) (save-buffer)))))
1530
1531   (if (or noninteractive byte-compile-verbose) ; XEmacs change
1532       (message "Compiling %s..." filename))
1533   (let (;;(byte-compile-current-file (file-name-nondirectory filename))
1534         (byte-compile-current-file filename)
1535         target-file input-buffer output-buffer
1536         byte-compile-dest-file)
1537     (setq target-file (byte-compile-dest-file filename))
1538     (setq byte-compile-dest-file target-file)
1539     (save-excursion
1540       (setq input-buffer (get-buffer-create " *Compiler Input*"))
1541       (set-buffer input-buffer)
1542       (erase-buffer)
1543       (insert-file-contents filename)
1544       ;; Run hooks including the uncompression hook.
1545       ;; If they change the file name, then change it for the output also.
1546       (let ((buffer-file-name filename)
1547             (default-major-mode 'emacs-lisp-mode)
1548             (enable-local-eval nil))
1549         (normal-mode)
1550         (setq filename buffer-file-name)))
1551       (setq byte-compiler-error-flag nil)
1552     ;; It is important that input-buffer not be current at this call,
1553     ;; so that the value of point set in input-buffer
1554     ;; within byte-compile-from-buffer lingers in that buffer.
1555     (setq output-buffer (byte-compile-from-buffer input-buffer filename))
1556     (if byte-compiler-error-flag
1557         nil
1558       (if byte-compile-verbose
1559           (message "Compiling %s...done" filename))
1560       (kill-buffer input-buffer)
1561       (save-excursion
1562         (set-buffer output-buffer)
1563         (goto-char (point-max))
1564         (insert "\n")                   ; aaah, unix.
1565         (setq target-file (byte-compile-dest-file filename))
1566         (unless byte-compile-overwrite-file
1567           (ignore-file-errors (delete-file target-file)))
1568         (if (file-writable-p target-file)
1569             (write-region 1 (point-max) target-file)
1570           ;; This is just to give a better error message than write-region
1571           (signal 'file-error
1572                   (list "Opening output file"
1573                         (if (file-exists-p target-file)
1574                             "cannot overwrite file"
1575                           "directory not writable or nonexistent")
1576                         target-file)))
1577         (or byte-compile-overwrite-file
1578             (condition-case ()
1579                 (set-file-modes target-file (file-modes filename))
1580               (error nil)))
1581         (kill-buffer (current-buffer)))
1582       (if (and byte-compile-generate-call-tree
1583                (or (eq t byte-compile-generate-call-tree)
1584                    (y-or-n-p (format "Report call tree for %s? " filename))))
1585           (save-excursion
1586             (display-call-tree filename)))
1587       (if load
1588           (load target-file))
1589       t)))
1590
1591 ;; RMS comments the next two out.
1592
1593 ;;;###autoload
1594 (defun byte-compile-and-load-file (&optional filename)
1595   "Compile a file of Lisp code named FILENAME into a file of byte code,
1596 and then load it.  The output file's name is made by appending \"c\" to
1597 the end of FILENAME."
1598   (interactive)
1599   (if filename ; I don't get it, (interactive-p) doesn't always work
1600         (byte-compile-file filename t)
1601     (let ((current-prefix-arg '(4)))
1602         (call-interactively 'byte-compile-file))))
1603
1604 ;;;###autoload
1605 (defun byte-compile-buffer (&optional buffer)
1606   "Byte-compile and evaluate contents of BUFFER (default: the current buffer)."
1607   (interactive "bByte compile buffer: ")
1608   (setq buffer (if buffer (get-buffer buffer) (current-buffer)))
1609   (message "Compiling %s..." buffer)
1610   (let* ((filename (or (buffer-file-name buffer)
1611                        (prin1-to-string buffer)))
1612          (byte-compile-current-file buffer))
1613     (byte-compile-from-buffer buffer filename t))
1614   (message "Compiling %s...done" buffer)
1615   t)
1616
1617 ;;; compiling a single function
1618 ;;;###autoload
1619 (defun compile-defun (&optional arg)
1620   "Compile and evaluate the current top-level form.
1621 Print the result in the minibuffer.
1622 With argument, insert value in current buffer after the form."
1623   (interactive "P")
1624   (save-excursion
1625     (end-of-defun)
1626     (beginning-of-defun)
1627     (let* ((byte-compile-current-file (buffer-file-name))
1628            (load-file-name (buffer-file-name))
1629            (byte-compile-last-warned-form 'nothing)
1630            (value (eval (displaying-byte-compile-warnings
1631                          (byte-compile-sexp (read (current-buffer))
1632                                             "toplevel forms")))))
1633       (cond (arg
1634              (message "Compiling from buffer... done.")
1635              (prin1 value (current-buffer))
1636              (insert "\n"))
1637             ((message "%s" (prin1-to-string value)))))))
1638
1639 (defvar byte-compile-inbuffer)
1640 (defvar byte-compile-outbuffer)
1641
1642 (defun byte-compile-from-buffer (byte-compile-inbuffer filename &optional eval)
1643   ;; buffer --> output-buffer, or buffer --> eval form, return nil
1644   (let (byte-compile-outbuffer
1645         ;; Prevent truncation of flonums and lists as we read and print them
1646         (float-output-format nil)
1647         (case-fold-search nil)
1648         (print-length nil)
1649         (print-level nil)
1650         ;; Simulate entry to byte-compile-top-level
1651         (byte-compile-constants nil)
1652         (byte-compile-variables nil)
1653         (byte-compile-tag-number 0)
1654         (byte-compile-depth 0)
1655         (byte-compile-maxdepth 0)
1656         (byte-compile-output nil)
1657         ;;        #### This is bound in b-c-close-variables.
1658         ;;        (byte-compile-warnings (if (eq byte-compile-warnings t)
1659         ;;                                   byte-compile-warning-types
1660         ;;                                 byte-compile-warnings))
1661         )
1662     (byte-compile-close-variables
1663      (save-excursion
1664        (setq byte-compile-outbuffer
1665              (set-buffer (get-buffer-create " *Compiler Output*")))
1666        (erase-buffer)
1667        ;;        (emacs-lisp-mode)
1668        (setq case-fold-search nil)
1669        (and filename
1670             (not eval)
1671             (byte-compile-insert-header filename
1672                                         byte-compile-inbuffer
1673                                         byte-compile-outbuffer))
1674
1675        ;; This is a kludge.  Some operating systems (OS/2, DOS) need to
1676        ;; write files containing binary information specially.
1677        ;; Under most circumstances, such files will be in binary
1678        ;; overwrite mode, so those OS's use that flag to guess how
1679        ;; they should write their data.  Advise them that .elc files
1680        ;; need to be written carefully.
1681        (setq overwrite-mode 'overwrite-mode-binary))
1682      (displaying-byte-compile-warnings
1683       (save-excursion
1684         (set-buffer byte-compile-inbuffer)
1685         (goto-char 1)
1686
1687         ;; Compile the forms from the input buffer.
1688         (while (progn
1689                  (while (progn (skip-chars-forward " \t\n\^L")
1690                                (looking-at ";"))
1691                    (forward-line 1))
1692                  (not (eobp)))
1693           (byte-compile-file-form (read byte-compile-inbuffer)))
1694
1695         ;; Compile pending forms at end of file.
1696         (byte-compile-flush-pending)
1697         (byte-compile-warn-about-unresolved-functions)
1698         ;; Should we always do this?  When calling multiple files, it
1699         ;; would be useful to delay this warning until all have
1700         ;; been compiled.
1701         (setq byte-compile-unresolved-functions nil)))
1702      (save-excursion
1703        (set-buffer byte-compile-outbuffer)
1704        (goto-char (point-min))))
1705     (if (not eval)
1706         byte-compile-outbuffer
1707       (let (form)
1708         (while (condition-case nil
1709                    (progn (setq form (read byte-compile-outbuffer))
1710                           t)
1711                  (end-of-file nil))
1712           (eval form)))
1713       (kill-buffer byte-compile-outbuffer)
1714       nil)))
1715
1716 (defun byte-compile-insert-header (filename byte-compile-inbuffer
1717                                             byte-compile-outbuffer)
1718   (set-buffer byte-compile-inbuffer)
1719   (let ((dynamic-docstrings byte-compile-dynamic-docstrings))
1720     (set-buffer byte-compile-outbuffer)
1721     (goto-char 1)
1722     ;;
1723     ;; The magic number of .elc files is ";ELC", or 0x3B454C43.  After that is
1724     ;; the file-format version number (19 or 20) as a byte, followed by some
1725     ;; nulls.  The primary motivation for doing this is to get some binary
1726     ;; characters up in the first line of the file so that `diff' will simply
1727     ;; say "Binary files differ" instead of actually doing a diff of two .elc
1728     ;; files.  An extra benefit is that you can add this to /etc/magic:
1729     ;;
1730     ;; 0        string          ;ELC            GNU Emacs Lisp compiled file,
1731     ;; >4       byte            x               version %d
1732     ;;
1733     (insert
1734      ";ELC"
1735      (if (byte-compile-version-cond byte-compile-emacs19-compatibility) 19 20)
1736      "\000\000\000\n"
1737      )
1738     (insert ";;; compiled by "
1739             (or (and (boundp 'user-mail-address) user-mail-address)
1740                 (concat (user-login-name) "@" (system-name)))
1741             " on "
1742             (current-time-string) "\n;;; from file " filename "\n")
1743     (insert ";;; emacs version " emacs-version ".\n")
1744     (insert ";;; bytecomp version " byte-compile-version "\n;;; "
1745      (cond
1746        ((eq byte-optimize 'source) "source-level optimization only")
1747        ((eq byte-optimize 'byte) "byte-level optimization only")
1748        (byte-optimize "optimization is on")
1749        (t "optimization is off"))
1750      (if (byte-compile-version-cond byte-compile-emacs19-compatibility)
1751          "; compiled with Emacs 19 compatibility.\n"
1752        ".\n"))
1753    (if (not (byte-compile-version-cond byte-compile-emacs19-compatibility))
1754        (insert ";;; this file uses opcodes which do not exist in Emacs 19.\n"
1755                ;; Have to check if emacs-version is bound so that this works
1756                ;; in files loaded early in loadup.el.
1757                "\n(if (and (boundp 'emacs-version)\n"
1758                "\t (or (and (boundp 'epoch::version) epoch::version)\n"
1759                "\t     (< emacs-major-version 20)))\n"
1760                "    (error \"`"
1761                ;; prin1-to-string is used to quote backslashes.
1762                (substring (prin1-to-string (file-name-nondirectory filename))
1763                           1 -1)
1764                "' was compiled for Emacs 20\"))\n\n"))
1765    (insert "(or (boundp 'current-load-list) (setq current-load-list nil))\n"
1766            "\n")
1767    (if (and (byte-compile-version-cond byte-compile-emacs19-compatibility)
1768             dynamic-docstrings)
1769        (insert ";;; this file uses opcodes which do not exist prior to\n"
1770                ";;; XEmacs 19.14/GNU Emacs 19.29 or later."
1771                ;; Have to check if emacs-version is bound so that this works
1772                ;; in files loaded early in loadup.el.
1773                "\n(if (and (boundp 'emacs-version)\n"
1774                "\t (or (and (boundp 'epoch::version) epoch::version)\n"
1775                "\t     (and (not (featurep 'xemacs))\n"
1776                "\t          (<= emacs-major-version 19)\n"
1777                "\t          (< emacs-minor-version 29))\n"
1778                "\t     (and (<= emacs-major-version 20)\n"
1779                "\t          (< emacs-minor-version 14))))\n"
1780                "    (error \"`"
1781                ;; prin1-to-string is used to quote backslashes.
1782                (substring (prin1-to-string (file-name-nondirectory filename))
1783                           1 -1)
1784                "' was compiled for XEmacs 19.14/Emacs 19.29 or later\"))\n\n"
1785                )
1786       ))
1787
1788   ;; back in the inbuffer; determine and set the coding system for the .elc
1789   ;; file if under Mule.  If there are any extended characters in the
1790   ;; input file, use `escape-quoted' to make sure that both binary and
1791   ;; extended characters are output properly and distinguished properly.
1792   ;; Otherwise, use `raw-text' for maximum portability with non-Mule
1793   ;; Emacsen.
1794   (when (featurep '(or mule file-coding))
1795     (defvar buffer-file-coding-system)
1796     (if (or (featurep '(not mule)) ;; Don't scan buffer if we are not muleized
1797             (save-excursion
1798               (set-buffer byte-compile-inbuffer)
1799               (goto-char (point-min))
1800               ;; mrb- There must be a better way than skip-chars-forward
1801               (skip-chars-forward (concat (char-to-string 0) "-"
1802                                           (char-to-string 255)))
1803               (eq (point) (point-max))))
1804         (setq buffer-file-coding-system 'raw-text-unix)
1805       (insert "(require 'mule)\n;;;###coding system: escape-quoted\n")
1806       (setq buffer-file-coding-system 'escape-quoted)
1807       ;; #### Lazy loading not yet implemented for MULE files
1808       ;; mrb - Fix this someday.
1809       (save-excursion
1810         (set-buffer byte-compile-inbuffer)
1811         (setq byte-compile-dynamic nil
1812               byte-compile-dynamic-docstrings nil))
1813       ;;(external-debugging-output (prin1-to-string (buffer-local-variables))))
1814       ))
1815   )
1816
1817
1818 (defun byte-compile-output-file-form (form)
1819   ;; writes the given form to the output buffer, being careful of docstrings
1820   ;; in defun, defmacro, defvar, defconst and autoload because make-docfile is
1821   ;; so amazingly stupid.
1822   ;; defalias calls are output directly by byte-compile-file-form-defmumble;
1823   ;; it does not pay to first build the defalias in defmumble and then parse
1824   ;; it here.
1825   (if (and (memq (car-safe form) '(defun defmacro defvar defconst autoload
1826                                    custom-declare-variable))
1827            (stringp (nth 3 form)))
1828       (byte-compile-output-docform nil nil '("\n(" 3 ")") form nil
1829                                    (memq (car form)
1830                                          '(autoload custom-declare-variable)))
1831     (let ((print-escape-newlines t)
1832           (print-length nil)
1833           (print-level nil)
1834           (print-readably t)    ; print #[] for bytecode, 'x for (quote x)
1835           (print-gensym (if (and byte-compile-print-gensym
1836                                  (not byte-compile-emacs19-compatibility))
1837                             t nil)))
1838       (princ "\n" byte-compile-outbuffer)
1839       (prin1 form byte-compile-outbuffer)
1840       nil)))
1841
1842 (defun byte-compile-output-docform (preface name info form specindex quoted)
1843   "Print a form with a doc string.  INFO is (prefix doc-index postfix).
1844 If PREFACE and NAME are non-nil, print them too,
1845 before INFO and the FORM but after the doc string itself.
1846 If SPECINDEX is non-nil, it is the index in FORM
1847 of the function bytecode string.  In that case,
1848 we output that argument and the following argument (the constants vector)
1849 together, for lazy loading.
1850 QUOTED says that we have to put a quote before the
1851 list that represents a doc string reference.
1852 `autoload' needs that."
1853   ;; We need to examine byte-compile-dynamic-docstrings
1854   ;; in the input buffer (now current), not in the output buffer.
1855   (let ((dynamic-docstrings byte-compile-dynamic-docstrings))
1856     (set-buffer
1857      (prog1 (current-buffer)
1858        (set-buffer byte-compile-outbuffer)
1859        (let (position)
1860
1861          ;; Insert the doc string, and make it a comment with #@LENGTH.
1862          (and (>= (nth 1 info) 0)
1863               dynamic-docstrings
1864               (progn
1865                 ;; Make the doc string start at beginning of line
1866                 ;; for make-docfile's sake.
1867                 (insert "\n")
1868                 (setq position
1869                       (byte-compile-output-as-comment
1870                        (nth (nth 1 info) form) nil))
1871                 ;; If the doc string starts with * (a user variable),
1872                 ;; negate POSITION.
1873                 (if (and (stringp (nth (nth 1 info) form))
1874                          (> (length (nth (nth 1 info) form)) 0)
1875                          (char= (aref (nth (nth 1 info) form) 0) ?*))
1876                     (setq position (- position)))))
1877
1878          (if preface
1879              (progn
1880                (insert preface)
1881                (prin1 name byte-compile-outbuffer)))
1882          (insert (car info))
1883          (let ((print-escape-newlines t)
1884                (print-readably t)       ; print #[] for bytecode, 'x for (quote x)
1885                ;; Use a cons cell to say that we want
1886                ;; print-gensym-alist not to be cleared between calls
1887                ;; to print functions.
1888                (print-gensym (if (and byte-compile-print-gensym
1889                                       (not byte-compile-emacs19-compatibility))
1890                                  '(t) nil))
1891                print-gensym-alist
1892                (index 0))
1893            (prin1 (car form) byte-compile-outbuffer)
1894            (while (setq form (cdr form))
1895              (setq index (1+ index))
1896              (insert " ")
1897              (cond ((and (numberp specindex) (= index specindex))
1898                     (let ((position
1899                            (byte-compile-output-as-comment
1900                             (cons (car form) (nth 1 form))
1901                             t)))
1902                       (princ (format "(#$ . %d) nil" position)
1903                              byte-compile-outbuffer)
1904                       (setq form (cdr form))
1905                       (setq index (1+ index))))
1906                    ((= index (nth 1 info))
1907                     (if position
1908                         (princ (format (if quoted "'(#$ . %d)"  "(#$ . %d)")
1909                                        position)
1910                                byte-compile-outbuffer)
1911                       (let ((print-escape-newlines nil))
1912                         (goto-char (prog1 (1+ (point))
1913                                      (prin1 (car form)
1914                                             byte-compile-outbuffer)))
1915                         (insert "\\\n")
1916                         (goto-char (point-max)))))
1917                    (t
1918                     (prin1 (car form) byte-compile-outbuffer)))))
1919          (insert (nth 2 info))))))
1920   nil)
1921
1922 (defvar for-effect) ; ## Kludge!  This should be an arg, not a special.
1923
1924 (defun byte-compile-keep-pending (form &optional handler)
1925   (if (memq byte-optimize '(t source))
1926       (setq form (byte-optimize-form form t)))
1927   (if handler
1928       (let ((for-effect t))
1929         ;; To avoid consing up monstrously large forms at load time, we split
1930         ;; the output regularly.
1931         (and (memq (car-safe form) '(fset defalias define-function))
1932              (nthcdr 300 byte-compile-output)
1933              (byte-compile-flush-pending))
1934         (funcall handler form)
1935         (when for-effect
1936           (byte-compile-discard)))
1937     (byte-compile-form form t))
1938   nil)
1939
1940 (defun byte-compile-flush-pending ()
1941   (if byte-compile-output
1942       (let ((form (byte-compile-out-toplevel t 'file)))
1943         (cond ((eq (car-safe form) 'progn)
1944                (mapcar 'byte-compile-output-file-form (cdr form)))
1945               (form
1946                (byte-compile-output-file-form form)))
1947         (setq byte-compile-constants nil
1948               byte-compile-variables nil
1949               byte-compile-depth 0
1950               byte-compile-maxdepth 0
1951               byte-compile-output nil))))
1952
1953 (defun byte-compile-file-form (form)
1954   (let ((byte-compile-current-form nil) ; close over this for warnings.
1955         handler)
1956     (cond
1957      ((not (consp form))
1958       (byte-compile-keep-pending form))
1959      ((and (symbolp (car form))
1960            (setq handler (get (car form) 'byte-hunk-handler)))
1961       (cond ((setq form (funcall handler form))
1962              (byte-compile-flush-pending)
1963              (byte-compile-output-file-form form))))
1964      ((eq form (setq form (macroexpand form byte-compile-macro-environment)))
1965       (byte-compile-keep-pending form))
1966      (t
1967       (byte-compile-file-form form)))))
1968
1969 ;; Functions and variables with doc strings must be output separately,
1970 ;; so make-docfile can recognize them.  Most other things can be output
1971 ;; as byte-code.
1972
1973 (put 'defsubst 'byte-hunk-handler 'byte-compile-file-form-defsubst)
1974 (defun byte-compile-file-form-defsubst (form)
1975   (cond ((assq (nth 1 form) byte-compile-unresolved-functions)
1976          (setq byte-compile-current-form (nth 1 form))
1977          (byte-compile-warn "defsubst %s was used before it was defined"
1978                             (nth 1 form))))
1979   (byte-compile-file-form
1980    (macroexpand form byte-compile-macro-environment))
1981   ;; Return nil so the form is not output twice.
1982   nil)
1983
1984 (put 'autoload 'byte-hunk-handler 'byte-compile-file-form-autoload)
1985 (defun byte-compile-file-form-autoload (form)
1986   ;;
1987   ;; If this is an autoload of a macro, and all arguments are constants (that
1988   ;; is, there is no hairy computation going on here) then evaluate the form
1989   ;; at compile-time.  This is so that we can make use of macros which we
1990   ;; have autoloaded from the file being compiled.  Normal function autoloads
1991   ;; are not automatically evaluated at compile time, because there's not
1992   ;; much point to it (so why bother cluttering up the compile-time namespace.)
1993   ;;
1994   ;; If this is an autoload of a function, then record its definition in the
1995   ;; byte-compile-autoload-environment to suppress any `not known to be
1996   ;; defined' warnings at the end of this file (this only matters for
1997   ;; functions which are autoloaded and compiled in the same file, if the
1998   ;; autoload already exists in the compilation environment, we wouldn't have
1999   ;; warned anyway.)
2000   ;;
2001   (let* ((name (if (byte-compile-constp (nth 1 form))
2002                    (eval (nth 1 form))))
2003          ;; In v19, the 5th arg to autoload can be t, nil, 'macro, or 'keymap.
2004          (macrop (and (byte-compile-constp (nth 5 form))
2005                       (memq (eval (nth 5 form)) '(t macro))))
2006 ;;       (functionp (and (byte-compile-constp (nth 5 form))
2007 ;;                       (eq 'nil (eval (nth 5 form)))))
2008          )
2009     (if (and macrop
2010              (let ((form form))
2011                ;; all forms are constant
2012                (while (if (setq form (cdr form))
2013                           (byte-compile-constp (car form))))
2014                (null form)))
2015         ;; eval the macro autoload into the compilation environment
2016         (eval form))
2017
2018     (if name
2019         (let ((old (assq name byte-compile-autoload-environment)))
2020           (cond (old
2021                  (if (memq 'redefine byte-compile-warnings)
2022                      (byte-compile-warn "multiple autoloads for %s" name))
2023                  (setcdr old form))
2024                 (t
2025                  ;; We only use the names in the autoload environment, but
2026                  ;; it might be useful to have the bodies some day.
2027                  (setq byte-compile-autoload-environment
2028                        (cons (cons name form)
2029                              byte-compile-autoload-environment)))))))
2030   ;;
2031   ;; Now output the form.
2032   (if (stringp (nth 3 form))
2033       form
2034     ;; No doc string, so we can compile this as a normal form.
2035     (byte-compile-keep-pending form 'byte-compile-normal-call)))
2036
2037 (put 'defvar   'byte-hunk-handler 'byte-compile-file-form-defvar-or-defconst)
2038 (put 'defconst 'byte-hunk-handler 'byte-compile-file-form-defvar-or-defconst)
2039 (put 'defregexp 'byte-hunk-handler 'byte-compile-file-form-defvar-or-defconst)
2040 (defun byte-compile-file-form-defvar-or-defconst (form)
2041   ;; (defvar|defconst VAR [VALUE [DOCSTRING]])
2042   (if (> (length form) 4)
2043       (byte-compile-warn
2044        "%s %s called with %d arguments, but accepts only %s"
2045        (car form) (nth 1 form) (length (cdr form)) 3))
2046   (if (and (> (length form) 3) (not (stringp (nth 3 form))))
2047       (byte-compile-warn "Third arg to %s %s is not a string: %s"
2048                          (car form) (nth 1 form) (nth 3 form)))
2049   (if (null (nth 3 form))
2050       ;; Since there is no doc string, we can compile this as a normal form,
2051       ;; and not do a file-boundary.
2052       (byte-compile-keep-pending form)
2053     (if (memq 'free-vars byte-compile-warnings)
2054         (setq byte-compile-bound-variables
2055               (cons (cons (nth 1 form) byte-compile-global-bit)
2056                     byte-compile-bound-variables)))
2057     (cond ((consp (nth 2 form))
2058            (setq form (copy-sequence form))
2059            (setcar (cdr (cdr form))
2060                    (byte-compile-top-level (nth 2 form) nil 'file))))
2061
2062     ;; The following turns out not to be necessary, since we emit a call to
2063     ;; defvar, which can hack Vfile_domain by itself!
2064     ;;
2065     ;; If a file domain has been set, emit (put 'VAR 'variable-domain ...)
2066     ;; after this defvar.
2067 ;    (if byte-compile-file-domain
2068 ;       (progn
2069 ;         ;; Actually, this will emit the (put ...) before the (defvar ...)
2070 ;         ;; but I don't think that can matter in this case.
2071 ;         (byte-compile-keep-pending
2072 ;          (list 'put (list 'quote (nth 1 form)) ''variable-domain
2073 ;               (list 'quote byte-compile-file-domain)))))
2074     form))
2075
2076 (put 'require 'byte-hunk-handler 'byte-compile-file-form-eval-boundary)
2077 (defun byte-compile-file-form-eval-boundary (form)
2078   (eval form)
2079   (byte-compile-keep-pending form 'byte-compile-normal-call))
2080
2081 (put 'progn 'byte-hunk-handler 'byte-compile-file-form-progn)
2082 (put 'prog1 'byte-hunk-handler 'byte-compile-file-form-progn)
2083 (put 'prog2 'byte-hunk-handler 'byte-compile-file-form-progn)
2084 (defun byte-compile-file-form-progn (form)
2085   (mapcar 'byte-compile-file-form (cdr form))
2086   ;; Return nil so the forms are not output twice.
2087   nil)
2088
2089 ;; This handler is not necessary, but it makes the output from dont-compile
2090 ;; and similar macros cleaner.
2091 (put 'eval 'byte-hunk-handler 'byte-compile-file-form-eval)
2092 (defun byte-compile-file-form-eval (form)
2093   (if (eq (car-safe (nth 1 form)) 'quote)
2094       (nth 1 (nth 1 form))
2095     (byte-compile-keep-pending form)))
2096
2097 (put 'defun 'byte-hunk-handler 'byte-compile-file-form-defun)
2098 (defun byte-compile-file-form-defun (form)
2099   (byte-compile-file-form-defmumble form nil))
2100
2101 (put 'defmacro 'byte-hunk-handler 'byte-compile-file-form-defmacro)
2102 (defun byte-compile-file-form-defmacro (form)
2103   (byte-compile-file-form-defmumble form t))
2104
2105 (defun byte-compile-compiled-obj-to-list (obj)
2106   ;; #### this is fairly disgusting.  Rewrite the code instead
2107   ;; so that it doesn't create compiled objects in the first place!
2108   ;; Much better than creating them and then "uncreating" them
2109   ;; like this.
2110   (read (concat "("
2111                 (substring (let ((print-readably t)
2112                                  (print-gensym
2113                                   (if (and byte-compile-print-gensym
2114                                            (not byte-compile-emacs19-compatibility))
2115                                       '(t) nil))
2116                                  (print-gensym-alist nil))
2117                              (prin1-to-string obj))
2118                            2 -1)
2119                 ")")))
2120
2121 (defun byte-compile-file-form-defmumble (form macrop)
2122   (let* ((name (car (cdr form)))
2123          (this-kind (if macrop 'byte-compile-macro-environment
2124                       'byte-compile-function-environment))
2125          (that-kind (if macrop 'byte-compile-function-environment
2126                       'byte-compile-macro-environment))
2127          (this-one (assq name (symbol-value this-kind)))
2128          (that-one (assq name (symbol-value that-kind)))
2129          (byte-compile-free-references nil)
2130          (byte-compile-free-assignments nil))
2131
2132     ;; When a function or macro is defined, add it to the call tree so that
2133     ;; we can tell when functions are not used.
2134     (if byte-compile-generate-call-tree
2135         (or (assq name byte-compile-call-tree)
2136             (setq byte-compile-call-tree
2137                   (cons (list name nil nil) byte-compile-call-tree))))
2138
2139     (setq byte-compile-current-form name) ; for warnings
2140     (when (memq 'redefine byte-compile-warnings)
2141       (byte-compile-arglist-warn form macrop))
2142     (defvar filename) ; #### filename used free
2143     (when byte-compile-verbose
2144       (message "Compiling %s... (%s)"
2145                (if filename (file-name-nondirectory filename) "")
2146                (nth 1 form)))
2147     (cond (that-one
2148            (when (and (memq 'redefine byte-compile-warnings)
2149                       ;; hack hack: don't warn when compiling the stubs in
2150                       ;; bytecomp-runtime...
2151                       (not (assq (nth 1 form)
2152                                  byte-compile-initial-macro-environment)))
2153              (byte-compile-warn
2154               "%s defined multiple times, as both function and macro"
2155               (nth 1 form)))
2156            (setcdr that-one nil))
2157           (this-one
2158            (when (and (memq 'redefine byte-compile-warnings)
2159                       ;; hack: don't warn when compiling the magic internal
2160                       ;; byte-compiler macros in bytecomp-runtime.el...
2161                       (not (assq (nth 1 form)
2162                                  byte-compile-initial-macro-environment)))
2163              (byte-compile-warn "%s %s defined multiple times in this file"
2164                                 (if macrop "macro" "function")
2165                                 (nth 1 form))))
2166           ((and (fboundp name)
2167                 (or (subrp (symbol-function name))
2168                     (eq (car-safe (symbol-function name))
2169                         (if macrop 'lambda 'macro))))
2170            (if (memq 'redefine byte-compile-warnings)
2171                (byte-compile-warn "%s %s being redefined as a %s"
2172                                   (if (subrp (symbol-function name))
2173                                       "subr"
2174                                     (if macrop "function" "macro"))
2175                                   (nth 1 form)
2176                                   (if macrop "macro" "function")))
2177            ;; shadow existing definition
2178            (set this-kind
2179                 (cons (cons name nil) (symbol-value this-kind)))))
2180     (let ((body (nthcdr 3 form)))
2181       (if (and (stringp (car body))
2182                (symbolp (car-safe (cdr-safe body)))
2183                (car-safe (cdr-safe body))
2184                (stringp (car-safe (cdr-safe (cdr-safe body)))))
2185           (byte-compile-warn "Probable `\"' without `\\' in doc string of %s"
2186                              (nth 1 form))))
2187     (let* ((new-one (byte-compile-lambda (cons 'lambda (nthcdr 2 form))))
2188            (code (byte-compile-byte-code-maker new-one)))
2189       (if this-one
2190           (setcdr this-one new-one)
2191         (set this-kind
2192              (cons (cons name new-one) (symbol-value this-kind))))
2193       (if (and (stringp (nth 3 form))
2194                (eq 'quote (car-safe code))
2195                (eq 'lambda (car-safe (nth 1 code))))
2196           (cons (car form)
2197                 (cons name (cdr (nth 1 code))))
2198         (byte-compile-flush-pending)
2199         (if (not (stringp (nth 3 form)))
2200             ;; No doc string.  Provide -1 as the "doc string index"
2201             ;; so that no element will be treated as a doc string.
2202             (byte-compile-output-docform
2203              "\n(defalias '"
2204              name
2205              (cond ((atom code)
2206                     (if macrop '(" '(macro . #[" -1 "])") '(" #[" -1 "]")))
2207                    ((eq (car code) 'quote)
2208                     (setq code new-one)
2209                     (if macrop '(" '(macro " -1 ")") '(" '(" -1 ")")))
2210                    ((if macrop '(" (cons 'macro (" -1 "))") '(" (" -1 ")"))))
2211              ;; FSF just calls `(append code nil)' here but that relies
2212              ;; on horrible C kludges in concat() that accept byte-
2213              ;; compiled objects and pretend they're vectors.
2214              (if (compiled-function-p code)
2215                  (byte-compile-compiled-obj-to-list code)
2216                (append code nil))
2217              (and (atom code) byte-compile-dynamic
2218                   1)
2219              nil)
2220           ;; Output the form by hand, that's much simpler than having
2221           ;; b-c-output-file-form analyze the defalias.
2222           (byte-compile-output-docform
2223            "\n(defalias '"
2224            name
2225            (cond ((atom code) ; compiled-function-p
2226                   (if macrop '(" '(macro . #[" 4 "])") '(" #[" 4 "]")))
2227                  ((eq (car code) 'quote)
2228                   (setq code new-one)
2229                   (if macrop '(" '(macro " 2 ")") '(" '(" 2 ")")))
2230                  ((if macrop '(" (cons 'macro (" 5 "))") '(" (" 5 ")"))))
2231            ;; The result of byte-compile-byte-code-maker is either a
2232            ;; compiled-function object, or a list of some kind.  If it's
2233            ;; not a cons, we must coerce it into a list of the elements
2234            ;; to be printed to the file.
2235            (if (consp code)
2236                code
2237              (nconc (list
2238                      (compiled-function-arglist code)
2239                      (compiled-function-instructions code)
2240                      (compiled-function-constants code)
2241                      (compiled-function-stack-depth code))
2242                     (let ((doc (documentation code t)))
2243                       (if doc (list doc)))
2244                     (if (commandp code)
2245                         (list (nth 1 (compiled-function-interactive code))))))
2246            (and (atom code) byte-compile-dynamic
2247                 1)
2248            nil))
2249         (princ ")" byte-compile-outbuffer)
2250         nil))))
2251
2252 ;; Print Lisp object EXP in the output file, inside a comment,
2253 ;; and return the file position it will have.
2254 ;; If QUOTED is non-nil, print with quoting; otherwise, print without quoting.
2255 (defun byte-compile-output-as-comment (exp quoted)
2256   (let ((position (point)))
2257     (set-buffer
2258      (prog1 (current-buffer)
2259        (set-buffer byte-compile-outbuffer)
2260
2261        ;; Insert EXP, and make it a comment with #@LENGTH.
2262        (insert " ")
2263        (if quoted
2264            (prin1 exp byte-compile-outbuffer)
2265          (princ exp byte-compile-outbuffer))
2266        (goto-char position)
2267        ;; Quote certain special characters as needed.
2268        ;; get_doc_string in doc.c does the unquoting.
2269        (while (search-forward "\^A" nil t)
2270          (replace-match "\^A\^A" t t))
2271        (goto-char position)
2272        (while (search-forward "\000" nil t)
2273          (replace-match "\^A0" t t))
2274        (goto-char position)
2275        (while (search-forward "\037" nil t)
2276          (replace-match "\^A_" t t))
2277        (goto-char (point-max))
2278        (insert "\037")
2279        (goto-char position)
2280        (insert "#@" (format "%d" (- (point-max) position)))
2281
2282        ;; Save the file position of the object.
2283        ;; Note we should add 1 to skip the space
2284        ;; that we inserted before the actual doc string,
2285        ;; and subtract 1 to convert from an 1-origin Emacs position
2286        ;; to a file position; they cancel.
2287        (setq position (point))
2288        (goto-char (point-max))))
2289     position))
2290
2291 \f
2292
2293 ;; The `domain' declaration.  This is legal only at top-level in a file, and
2294 ;; should generally be the first form in the file.  It is not legal inside
2295 ;; function bodies.
2296
2297 (put 'domain 'byte-hunk-handler 'byte-compile-file-form-domain)
2298 (defun byte-compile-file-form-domain (form)
2299   (if (not (null (cdr (cdr form))))
2300       (byte-compile-warn "domain used with too many arguments: %s" form))
2301   (let ((domain (nth 1 form)))
2302     (or (null domain)
2303         (stringp domain)
2304         (progn
2305           (byte-compile-warn
2306            "argument to `domain' declaration must be a literal string: %s"
2307            form)
2308           (setq domain nil)))
2309     (setq byte-compile-file-domain domain))
2310   (byte-compile-keep-pending form 'byte-compile-normal-call))
2311
2312 (defun byte-compile-domain (form)
2313   (byte-compile-warn "The `domain' declaration is legal only at top-level: %s"
2314                      (let ((print-escape-newlines t)
2315                            (print-level 4)
2316                            (print-length 4))
2317                        (prin1-to-string form)))
2318   (byte-compile-normal-call
2319    (list 'signal ''error
2320          (list 'quote (list "`domain' used inside a function" form)))))
2321
2322 ;; This is part of bytecomp.el in 19.35:
2323 (put 'custom-declare-variable 'byte-hunk-handler
2324      'byte-compile-file-form-custom-declare-variable)
2325 (defun byte-compile-file-form-custom-declare-variable (form)
2326   ;; XEmacs change; our implementation byte compiles and gives warnings
2327   ;; about the default value code, which GNU's doesn't.
2328   (let* ((quoted-default (car-safe (cdr-safe (cdr-safe form))))
2329          (to-examine (car-safe (cdr-safe quoted-default))))
2330     (if (memq 'free-vars byte-compile-warnings)
2331         (setq byte-compile-bound-variables
2332               (cons (cons (nth 1 (nth 1 form))
2333                           byte-compile-global-bit)
2334                     byte-compile-bound-variables)))
2335     ;; Byte compile anything that smells like a lambda. I initially
2336     ;; considered limiting it to the :initialize, :set and :get args, but
2337     ;; that's not amazingly forward-compatible, and anyone expecting other
2338     ;; things to be stored as data, not code, is unrealistic. 
2339      (loop
2340        for entry in-ref (nthcdr 4 form)
2341        do (cond ((and (eq 'function (car-safe entry))
2342                       (consp (car-safe (cdr-safe entry))))
2343                  (setf entry (copy-sequence entry))
2344                  (setcar (cdr entry) (byte-compile-lambda (car (cdr entry)))))
2345                 ((and (eq 'lambda (car-safe entry)))
2346                  (setf entry (byte-compile-lambda entry)))))
2347      ;; Byte compile the default value, as we do for defvar. 
2348      (when (consp (cdr-safe to-examine))
2349        (setq form (copy-sequence form))
2350        (setcdr (third form)
2351                (list (byte-compile-top-level to-examine nil 'file)))
2352        ;; And save a value to be examined in the custom UI, if that differs
2353        ;; from the init value.
2354        (unless (equal to-examine (car-safe (cdr (third form))))
2355          (setf (nthcdr 4 form) (nconc
2356                                 (list :default 
2357                                       (list 'quote to-examine))
2358                                 (nthcdr 4 form)))))
2359     form))
2360
2361 \f
2362 ;;;###autoload
2363 (defun byte-compile (form)
2364   "If FORM is a symbol, byte-compile its function definition.
2365 If FORM is a lambda or a macro, byte-compile it as a function."
2366   (displaying-byte-compile-warnings
2367    (byte-compile-close-variables
2368     (let* ((fun (if (symbolp form)
2369                     (and (fboundp form) (symbol-function form))
2370                   form))
2371            (macro (eq (car-safe fun) 'macro)))
2372       (if macro
2373           (setq fun (cdr fun)))
2374       (cond ((eq (car-safe fun) 'lambda)
2375              (setq fun (if macro
2376                            (cons 'macro (byte-compile-lambda fun))
2377                          (byte-compile-lambda fun)))
2378              (if (symbolp form)
2379                  (defalias form fun)
2380                fun)))))))
2381
2382 ;;;###autoload
2383 (defun byte-compile-sexp (sexp &optional msg)
2384   "Compile and return SEXP."
2385   (displaying-byte-compile-warnings
2386    (byte-compile-close-variables
2387     (prog1
2388         (byte-compile-top-level sexp)
2389       (byte-compile-warn-about-unresolved-functions msg)))))
2390
2391 ;; Given a function made by byte-compile-lambda, make a form which produces it.
2392 (defun byte-compile-byte-code-maker (fun)
2393   (cond
2394    ;; ## atom is faster than compiled-func-p.
2395    ((atom fun)                          ; compiled-function-p
2396     fun)
2397    ;; b-c-lambda didn't produce a compiled-function, so it must be a trivial
2398    ;; function.
2399    ((let (tmp)
2400       (if (and (setq tmp (assq 'byte-code (cdr-safe (cdr fun))))
2401                (null (cdr (memq tmp fun))))
2402           ;; Generate a make-byte-code call.
2403           (let* ((interactive (assq 'interactive (cdr (cdr fun)))))
2404             (nconc (list 'make-byte-code
2405                          (list 'quote (nth 1 fun)) ;arglist
2406                          (nth 1 tmp)    ;instructions
2407                          (nth 2 tmp)    ;constants
2408                          (nth 3 tmp))   ;stack-depth
2409                    (cond ((stringp (nth 2 fun))
2410                           (list (nth 2 fun))) ;docstring
2411                          (interactive
2412                           (list nil)))
2413                    (cond (interactive
2414                           (list (if (or (null (nth 1 interactive))
2415                                         (stringp (nth 1 interactive)))
2416                                     (nth 1 interactive)
2417                                   ;; Interactive spec is a list or a variable
2418                                   ;; (if it is correct).
2419                                   (list 'quote (nth 1 interactive))))))))
2420         ;; a non-compiled function (probably trivial)
2421         (list 'quote fun))))))
2422
2423 ;; Byte-compile a lambda-expression and return a valid function.
2424 ;; The value is usually a compiled function but may be the original
2425 ;; lambda-expression.
2426 (defun byte-compile-lambda (fun)
2427   (or (eq 'lambda (car-safe fun))
2428       (error "not a lambda -- %s" (prin1-to-string fun)))
2429   (let* ((arglist (nth 1 fun))
2430          (byte-compile-bound-variables
2431           (let ((new-bindings
2432                  (mapcar #'(lambda (x) (cons x byte-compile-arglist-bit))
2433                          (and (memq 'free-vars byte-compile-warnings)
2434                               (delq '&rest (delq '&optional
2435                                                  (copy-sequence arglist)))))))
2436             (nconc new-bindings
2437                    (cons 'new-scope byte-compile-bound-variables))))
2438          (body (cdr (cdr fun)))
2439          (doc (if (stringp (car body))
2440                   (prog1 (car body)
2441                     ;; Discard the doc string
2442                     ;; only if it is not the only element of the body.
2443                     (if (cdr body)
2444                         (setq body (cdr body))))))
2445          (int (assq 'interactive body)))
2446     (dolist (arg arglist)
2447       (cond ((not (symbolp arg))
2448              (byte-compile-warn "non-symbol in arglist: %S" arg))
2449             ((byte-compile-constant-symbol-p arg)
2450              (byte-compile-warn "constant symbol in arglist: %s" arg))
2451             ((and (char= ?\& (aref (symbol-name arg) 0))
2452                   (not (eq arg '&optional))
2453                   (not (eq arg '&rest)))
2454              (byte-compile-warn "unrecognized `&' keyword in arglist: %s"
2455                                 arg))))
2456     (cond (int
2457            ;; Skip (interactive) if it is in front (the most usual location).
2458            (if (eq int (car body))
2459                (setq body (cdr body)))
2460            (cond ((consp (cdr int))
2461                   (if (cdr (cdr int))
2462                       (byte-compile-warn "malformed interactive spec: %s"
2463                                          (prin1-to-string int)))
2464                   ;; If the interactive spec is a call to `list',
2465                   ;; don't compile it, because `call-interactively'
2466                   ;; looks at the args of `list'.
2467                   (let ((form (nth 1 int)))
2468                     (while (or (eq (car-safe form) 'let)
2469                                (eq (car-safe form) 'let*)
2470                                (eq (car-safe form) 'save-excursion))
2471                       (while (consp (cdr form))
2472                         (setq form (cdr form)))
2473                       (setq form (car form)))
2474                     (or (eq (car-safe form) 'list)
2475                         (setq int (list 'interactive
2476                                         (byte-compile-top-level (nth 1 int)))))))
2477                  ((cdr int)
2478                   (byte-compile-warn "malformed interactive spec: %s"
2479                                      (prin1-to-string int))))))
2480     (let ((compiled (byte-compile-top-level (cons 'progn body) nil 'lambda)))
2481       (if (memq 'unused-vars byte-compile-warnings)
2482           ;; done compiling in this scope, warn now.
2483           (byte-compile-warn-about-unused-variables))
2484       (if (eq 'byte-code (car-safe compiled))
2485           (apply 'make-byte-code
2486                  (append (list arglist)
2487                          ;; byte-string, constants-vector, stack depth
2488                          (cdr compiled)
2489                          ;; optionally, the doc string.
2490                          (if (or doc int)
2491                              (list doc))
2492                          ;; optionally, the interactive spec.
2493                          (if int
2494                              (list (nth 1 int)))))
2495         (setq compiled
2496               (nconc (if int (list int))
2497                      (cond ((eq (car-safe compiled) 'progn) (cdr compiled))
2498                            (compiled (list compiled)))))
2499         (nconc (list 'lambda arglist)
2500                (if (or doc (stringp (car compiled)))
2501                    (cons doc (cond (compiled)
2502                                    (body (list nil))))
2503                  compiled))))))
2504
2505 (defun byte-compile-constants-vector ()
2506   ;; Builds the constants-vector from the current variables and constants.
2507   ;;   This modifies the constants from (const . nil) to (const . offset).
2508   ;; To keep the byte-codes to look up the vector as short as possible:
2509   ;;   First 6 elements are vars, as there are one-byte varref codes for those.
2510   ;;   Next up to byte-constant-limit are constants, still with one-byte codes.
2511   ;;   Next variables again, to get 2-byte codes for variable lookup.
2512   ;;   The rest of the constants and variables need 3-byte byte-codes.
2513   (let* ((i -1)
2514          (rest (nreverse byte-compile-variables)) ; nreverse because the first
2515          (other (nreverse byte-compile-constants)) ; vars often are used most.
2516          ret tmp
2517          (limits '(5                    ; Use the 1-byte varref codes,
2518                    63  ; 1-constlim     ;  1-byte byte-constant codes,
2519                    255                  ;  2-byte varref codes,
2520                    65535))              ;  3-byte codes for the rest.
2521          limit)
2522     (while (or rest other)
2523       (setq limit (car limits))
2524       (while (and rest (not (eq i limit)))
2525         (if (setq tmp (assq (car (car rest)) ret))
2526             (setcdr (car rest) (cdr tmp))
2527           (setcdr (car rest) (setq i (1+ i)))
2528           (setq ret (cons (car rest) ret)))
2529         (setq rest (cdr rest)))
2530       (setq limits (cdr limits)
2531             rest (prog1 other
2532                    (setq other rest))))
2533     (apply 'vector (nreverse (mapcar 'car ret)))))
2534
2535 ;; Given an expression FORM, compile it and return an equivalent byte-code
2536 ;; expression (a call to the function byte-code).
2537 (defun byte-compile-top-level (form &optional for-effect output-type)
2538   ;; OUTPUT-TYPE advises about how form is expected to be used:
2539   ;;    'eval or nil    -> a single form,
2540   ;;    'progn or t     -> a list of forms,
2541   ;;    'lambda         -> body of a lambda,
2542   ;;    'file           -> used at file-level.
2543   (let ((byte-compile-constants nil)
2544         (byte-compile-variables nil)
2545         (byte-compile-tag-number 0)
2546         (byte-compile-depth 0)
2547         (byte-compile-maxdepth 0)
2548         (byte-compile-output nil))
2549     (if (memq byte-optimize '(t source))
2550         (setq form (byte-optimize-form form for-effect)))
2551     (while (and (eq (car-safe form) 'progn) (null (cdr (cdr form))))
2552       (setq form (nth 1 form)))
2553     (if (and (eq 'byte-code (car-safe form))
2554              (not (memq byte-optimize '(t byte)))
2555              (stringp (nth 1 form))
2556              (vectorp (nth 2 form))
2557              (natnump (nth 3 form)))
2558         form
2559       (byte-compile-form form for-effect)
2560       (byte-compile-out-toplevel for-effect output-type))))
2561
2562 (defun byte-compile-out-toplevel (&optional for-effect output-type)
2563   (if for-effect
2564       ;; The stack is empty. Push a value to be returned from (byte-code ..).
2565       (if (eq (car (car byte-compile-output)) 'byte-discard)
2566           (setq byte-compile-output (cdr byte-compile-output))
2567         (byte-compile-push-constant
2568          ;; Push any constant - preferably one which already is used, and
2569          ;; a number or symbol - ie not some big sequence.  The return value
2570          ;; isn't returned, but it would be a shame if some textually large
2571          ;; constant was not optimized away because we chose to return it.
2572          (and (not (assq nil byte-compile-constants)) ; Nil is often there.
2573               (let ((tmp (reverse byte-compile-constants)))
2574                 (while (and tmp (not (or (symbolp (car (car tmp)))
2575                                          (numberp (car (car tmp))))))
2576                   (setq tmp (cdr tmp)))
2577                 (car (car tmp)))))))
2578   (byte-compile-out 'byte-return 0)
2579   (setq byte-compile-output (nreverse byte-compile-output))
2580   (if (memq byte-optimize '(t byte))
2581       (setq byte-compile-output
2582             (byte-optimize-lapcode byte-compile-output for-effect)))
2583
2584   ;; Decompile trivial functions:
2585   ;; only constants and variables, or a single funcall except in lambdas.
2586   ;; Except for Lisp_Compiled objects, forms like (foo "hi")
2587   ;; are still quicker than (byte-code "..." [foo "hi"] 2).
2588   ;; Note that even (quote foo) must be parsed just as any subr by the
2589   ;; interpreter, so quote should be compiled into byte-code in some contexts.
2590   ;; What to leave uncompiled:
2591   ;;    lambda  -> never.  we used to leave it uncompiled if the body was
2592   ;;               a single atom, but that causes confusion if the docstring
2593   ;;               uses the (file . pos) syntax.  Besides, now that we have
2594   ;;               the Lisp_Compiled type, the compiled form is faster.
2595   ;;    eval    -> atom, quote or (function atom atom atom)
2596   ;;    progn   -> as <<same-as-eval>> or (progn <<same-as-eval>> atom)
2597   ;;    file    -> as progn, but takes both quotes and atoms, and longer forms.
2598   (let (rest
2599         (maycall (not (eq output-type 'lambda))) ; t if we may make a funcall.
2600         tmp body)
2601     (cond
2602      ;; #### This should be split out into byte-compile-nontrivial-function-p.
2603      ((or (eq output-type 'lambda)
2604           (nthcdr (if (eq output-type 'file) 50 8) byte-compile-output)
2605           (assq 'TAG byte-compile-output) ; Not necessary, but speeds up a bit.
2606           (not (setq tmp (assq 'byte-return byte-compile-output)))
2607           (progn
2608             (setq rest (nreverse
2609                         (cdr (memq tmp (reverse byte-compile-output)))))
2610             (while (cond
2611                     ((memq (car (car rest)) '(byte-varref byte-constant))
2612                      (setq tmp (car (cdr (car rest))))
2613                      (if (if (eq (car (car rest)) 'byte-constant)
2614                              (or (consp tmp)
2615                                  (and (symbolp tmp)
2616                                       (not (byte-compile-constant-symbol-p tmp)))))
2617                          (if maycall
2618                              (setq body (cons (list 'quote tmp) body)))
2619                        (setq body (cons tmp body))))
2620                     ((and maycall
2621                           ;; Allow a funcall if at most one atom follows it.
2622                           (null (nthcdr 3 rest))
2623                           (setq tmp
2624                                 ;; XEmacs change for rms funs
2625                                 (or (and
2626                                      (byte-compile-version-cond
2627                                       byte-compile-emacs19-compatibility)
2628                                      (get (car (car rest))
2629                                           'byte-opcode19-invert))
2630                                     (get (car (car rest))
2631                                          'byte-opcode-invert)))
2632                           (or (null (cdr rest))
2633                               (and (memq output-type '(file progn t))
2634                                    (cdr (cdr rest))
2635                                    (eq (car (nth 1 rest)) 'byte-discard)
2636                                    (progn (setq rest (cdr rest)) t))))
2637                      (setq maycall nil) ; Only allow one real function call.
2638                      (setq body (nreverse body))
2639                      (setq body (list
2640                                  (if (and (eq tmp 'funcall)
2641                                           (eq (car-safe (car body)) 'quote))
2642                                      (cons (nth 1 (car body)) (cdr body))
2643                                    (cons tmp body))))
2644                      (or (eq output-type 'file)
2645                          (not (delq nil (mapcar 'consp (cdr (car body))))))))
2646               (setq rest (cdr rest)))
2647             rest))
2648       (let ((byte-compile-vector (byte-compile-constants-vector)))
2649         (list 'byte-code (byte-compile-lapcode byte-compile-output)
2650               byte-compile-vector byte-compile-maxdepth)))
2651      ;; it's a trivial function
2652      ((cdr body) (cons 'progn (nreverse body)))
2653      ((car body)))))
2654
2655 ;; Given BODY, compile it and return a new body.
2656 (defun byte-compile-top-level-body (body &optional for-effect)
2657   (setq body (byte-compile-top-level (cons 'progn body) for-effect t))
2658   (cond ((eq (car-safe body) 'progn)
2659          (cdr body))
2660         (body
2661          (list body))))
2662 \f
2663 ;; This is the recursive entry point for compiling each subform of an
2664 ;; expression.
2665 ;; If for-effect is non-nil, byte-compile-form will output a byte-discard
2666 ;; before terminating (ie. no value will be left on the stack).
2667 ;; A byte-compile handler may, when for-effect is non-nil, choose output code
2668 ;; which does not leave a value on the stack, and then set for-effect to nil
2669 ;; (to prevent byte-compile-form from outputting the byte-discard).
2670 ;; If a handler wants to call another handler, it should do so via
2671 ;; byte-compile-form, or take extreme care to handle for-effect correctly.
2672 ;; (Use byte-compile-form-do-effect to reset the for-effect flag too.)
2673 ;;
2674 (defun byte-compile-form (form &optional for-effect)
2675   (setq form (macroexpand form byte-compile-macro-environment))
2676   (cond ((not (consp form))
2677          (cond ((or (not (symbolp form))
2678                     (byte-compile-constant-symbol-p form))
2679                 (byte-compile-constant form))
2680                ((and for-effect byte-compile-delete-errors)
2681                 (setq for-effect nil))
2682                (t (byte-compile-variable-ref 'byte-varref form))))
2683         ((symbolp (car form))
2684          (let* ((fn (car form))
2685                 (handler (get fn 'byte-compile)))
2686            (if (memq fn '(t nil))
2687                (byte-compile-warn "%s called as a function" fn))
2688            (if (and handler
2689                     (or (not (byte-compile-version-cond
2690                               byte-compile-emacs19-compatibility))
2691                         (not (get (get fn 'byte-opcode) 'emacs20-opcode))))
2692                (funcall handler form)
2693              (if (memq 'callargs byte-compile-warnings)
2694                  (byte-compile-callargs-warn form))
2695              (byte-compile-normal-call form))))
2696         ((and (or (compiled-function-p (car form))
2697                   (eq (car-safe (car form)) 'lambda))
2698               ;; if the form comes out the same way it went in, that's
2699               ;; because it was malformed, and we couldn't unfold it.
2700               (not (eq form (setq form (byte-compile-unfold-lambda form)))))
2701          (byte-compile-form form for-effect)
2702          (setq for-effect nil))
2703         ((byte-compile-normal-call form)))
2704   (when for-effect
2705     (byte-compile-discard)))
2706
2707 (defun byte-compile-normal-call (form)
2708   (if byte-compile-generate-call-tree
2709       (byte-compile-annotate-call-tree form))
2710   (byte-compile-push-constant (car form))
2711   (mapcar 'byte-compile-form (cdr form)) ; wasteful, but faster.
2712   (byte-compile-out 'byte-call (length (cdr form))))
2713
2714 ;; kludge added to XEmacs to work around the bogosities of a nonlexical lisp.
2715 (or (fboundp 'globally-boundp) (fset 'globally-boundp 'boundp))
2716
2717 (defun byte-compile-variable-ref (base-op var &optional varbind-flags)
2718   (if (or (not (symbolp var)) (byte-compile-constant-symbol-p var))
2719       (byte-compile-warn
2720        (case base-op
2721          (byte-varref "Variable reference to %s %s")
2722          (byte-varset "Attempt to set %s %s")
2723          (byte-varbind "Attempt to let-bind %s %s"))
2724        (if (symbolp var) "constant symbol" "non-symbol")
2725        var)
2726     (if (and (get var 'byte-obsolete-variable)
2727              (memq 'obsolete byte-compile-warnings))
2728         (let ((ob (get var 'byte-obsolete-variable)))
2729           (byte-compile-warn "%s is an obsolete variable; %s" var
2730                              (if (stringp ob)
2731                                  ob
2732                                (format "use %s instead." ob)))))
2733     (if (and (get var 'byte-compatible-variable)
2734              (memq 'pedantic byte-compile-warnings))
2735         (let ((ob (get var 'byte-compatible-variable)))
2736           (byte-compile-warn "%s is provided for compatibility; %s" var
2737                              (if (stringp ob)
2738                                  ob
2739                                (format "use %s instead." ob)))))
2740     (if (memq 'free-vars byte-compile-warnings)
2741         (if (eq base-op 'byte-varbind)
2742             (setq byte-compile-bound-variables
2743                   (cons (cons var (or varbind-flags 0))
2744                         byte-compile-bound-variables))
2745           (or (globally-boundp var)
2746               (let ((cell (assq var byte-compile-bound-variables)))
2747                 (if cell (setcdr cell
2748                                  (logior (cdr cell)
2749                                          (if (eq base-op 'byte-varset)
2750                                              byte-compile-assigned-bit
2751                                            byte-compile-referenced-bit)))))
2752               (and (boundp 'current-load-list)
2753                    (memq var current-load-list))
2754               (if (eq base-op 'byte-varset)
2755                   (or (memq var byte-compile-free-assignments)
2756                       (progn
2757                         (byte-compile-warn "assignment to free variable %s"
2758                                            var)
2759                         (setq byte-compile-free-assignments
2760                               (cons var byte-compile-free-assignments))))
2761                 (or (memq var byte-compile-free-references)
2762                     (progn
2763                       (byte-compile-warn "reference to free variable %s" var)
2764                       (setq byte-compile-free-references
2765                             (cons var byte-compile-free-references)))))))))
2766   (let ((tmp (assq var byte-compile-variables)))
2767     (or tmp
2768         (setq tmp (list var)
2769               byte-compile-variables (cons tmp byte-compile-variables)))
2770     (byte-compile-out base-op tmp)))
2771
2772 (defmacro byte-compile-get-constant (const)
2773   `(or (if (stringp ,const)
2774            (assoc ,const byte-compile-constants)
2775          (assq ,const byte-compile-constants))
2776        (car (setq byte-compile-constants
2777                   (cons (list ,const) byte-compile-constants)))))
2778
2779 ;; Use this when the value of a form is a constant.  This obeys for-effect.
2780 (defun byte-compile-constant (const)
2781   (if for-effect
2782       (setq for-effect nil)
2783     (byte-compile-out 'byte-constant (byte-compile-get-constant const))))
2784
2785 ;; Use this for a constant that is not the value of its containing form.
2786 ;; This ignores for-effect.
2787 (defun byte-compile-push-constant (const)
2788   (let ((for-effect nil))
2789     (inline (byte-compile-constant const))))
2790
2791 \f
2792 ;; Compile those primitive ordinary functions
2793 ;; which have special byte codes just for speed.
2794
2795 (defmacro byte-defop-compiler (function &optional compile-handler)
2796   ;; add a compiler-form for FUNCTION.
2797   ;; If FUNCTION is a symbol, then the variable "byte-SYMBOL" must name
2798   ;; the opcode to be used.  If is a list, the first element
2799   ;; is the function and the second element is the bytecode-symbol.
2800   ;; COMPILE-HANDLER is the function to use to compile this byte-op, or
2801   ;; may be the abbreviations 0, 1, 2, 3, 0-1, 1-2, 2-3, 0+1, 1+1, 2+1,
2802   ;; 0-1+1, 1-2+1, 2-3+1, 0+2, or 1+2.  If it is nil, then the handler is
2803   ;; "byte-compile-SYMBOL."
2804   (let (opcode)
2805     (if (symbolp function)
2806         (setq opcode (intern (concat "byte-" (symbol-name function))))
2807       (setq opcode (car (cdr function))
2808             function (car function)))
2809     (let ((fnform
2810            (list 'put (list 'quote function) ''byte-compile
2811                  (list 'quote
2812                        (or (cdr (assq compile-handler
2813                                       '((0 . byte-compile-no-args)
2814                                         (1 . byte-compile-one-arg)
2815                                         (2 . byte-compile-two-args)
2816                                         (3 . byte-compile-three-args)
2817                                         (0-1 . byte-compile-zero-or-one-arg)
2818                                         (1-2 . byte-compile-one-or-two-args)
2819                                         (2-3 . byte-compile-two-or-three-args)
2820                                         (0+1 . byte-compile-no-args-with-one-extra)
2821                                         (1+1 . byte-compile-one-arg-with-one-extra)
2822                                         (2+1 . byte-compile-two-args-with-one-extra)
2823                                         (0-1+1 . byte-compile-zero-or-one-arg-with-one-extra)
2824                                         (1-2+1 . byte-compile-one-or-two-args-with-one-extra)
2825                                         (2-3+1 . byte-compile-two-or-three-args-with-one-extra)
2826                                         (0+2 . byte-compile-no-args-with-two-extra)
2827                                         (1+2 . byte-compile-one-arg-with-two-extra)
2828
2829                                         )))
2830                            compile-handler
2831                            (intern (concat "byte-compile-"
2832                                            (symbol-name function))))))))
2833       (if opcode
2834           (list 'progn fnform
2835                 (list 'put (list 'quote function)
2836                       ''byte-opcode (list 'quote opcode))
2837                 (list 'put (list 'quote opcode)
2838                       ''byte-opcode-invert (list 'quote function)))
2839         fnform))))
2840
2841 (defmacro byte-defop-compiler20 (function &optional compile-handler)
2842   ;; Just like byte-defop-compiler, but defines an opcode that will only
2843   ;; be used when byte-compile-emacs19-compatibility is false.
2844   (if (and (byte-compile-single-version)
2845            byte-compile-emacs19-compatibility)
2846       ;; #### instead of doing nothing, this should do some remprops,
2847       ;; #### to protect against the case where a single-version compiler
2848       ;; #### is loaded into a world that has contained a multi-version one.
2849       nil
2850     (list 'progn
2851       (list 'put
2852         (list 'quote
2853           (or (car (cdr-safe function))
2854               (intern (concat "byte-"
2855                         (symbol-name (or (car-safe function) function))))))
2856         ''emacs20-opcode t)
2857       (list 'byte-defop-compiler function compile-handler))))
2858
2859 ;; XEmacs addition:
2860 (defmacro byte-defop-compiler-rmsfun (function &optional compile-handler)
2861   ;; for functions like `eq' that compile into different opcodes depending
2862   ;; on the Emacs version: byte-old-eq for v19, byte-eq for v20.
2863   (let ((opcode (intern (concat "byte-" (symbol-name function))))
2864         (opcode19 (intern (concat "byte-old-" (symbol-name function))))
2865         (fnform
2866          (list 'put (list 'quote function) ''byte-compile
2867                (list 'quote
2868                      (or (cdr (assq compile-handler
2869                                     '((2 . byte-compile-two-args-19->20)
2870                                       )))
2871                          compile-handler
2872                          (intern (concat "byte-compile-"
2873                                          (symbol-name function))))))))
2874     (list 'progn fnform
2875           (list 'put (list 'quote function)
2876                 ''byte-opcode (list 'quote opcode))
2877           (list 'put (list 'quote function)
2878                 ''byte-opcode19 (list 'quote opcode19))
2879           (list 'put (list 'quote opcode)
2880                 ''byte-opcode-invert (list 'quote function))
2881           (list 'put (list 'quote opcode19)
2882                 ''byte-opcode19-invert (list 'quote function)))))
2883
2884 (defmacro byte-defop-compiler-1 (function &optional compile-handler)
2885   (list 'byte-defop-compiler (list function nil) compile-handler))
2886
2887 \f
2888 (put 'byte-call 'byte-opcode-invert 'funcall)
2889 (put 'byte-list1 'byte-opcode-invert 'list)
2890 (put 'byte-list2 'byte-opcode-invert 'list)
2891 (put 'byte-list3 'byte-opcode-invert 'list)
2892 (put 'byte-list4 'byte-opcode-invert 'list)
2893 (put 'byte-listN 'byte-opcode-invert 'list)
2894 (put 'byte-concat2 'byte-opcode-invert 'concat)
2895 (put 'byte-concat3 'byte-opcode-invert 'concat)
2896 (put 'byte-concat4 'byte-opcode-invert 'concat)
2897 (put 'byte-concatN 'byte-opcode-invert 'concat)
2898 (put 'byte-insertN 'byte-opcode-invert 'insert)
2899
2900 ;; How old is this stuff? -slb
2901 ;(byte-defop-compiler (dot byte-point)          0+1)
2902 ;(byte-defop-compiler (dot-max byte-point-max)  0+1)
2903 ;(byte-defop-compiler (dot-min byte-point-min)  0+1)
2904 (byte-defop-compiler point              0+1)
2905 (byte-defop-compiler-rmsfun eq          2)
2906 (byte-defop-compiler point-max          0+1)
2907 (byte-defop-compiler point-min          0+1)
2908 (byte-defop-compiler following-char     0+1)
2909 (byte-defop-compiler preceding-char     0+1)
2910 (byte-defop-compiler current-column     0+1)
2911 ;; FSF has special function here; generalized here by the 1+2 stuff.
2912 (byte-defop-compiler (indent-to-column byte-indent-to) 1+2)
2913 (byte-defop-compiler indent-to          1+2)
2914 (byte-defop-compiler-rmsfun equal       2)
2915 (byte-defop-compiler eolp               0+1)
2916 (byte-defop-compiler eobp               0+1)
2917 (byte-defop-compiler bolp               0+1)
2918 (byte-defop-compiler bobp               0+1)
2919 (byte-defop-compiler current-buffer     0)
2920 ;;(byte-defop-compiler read-char        0) ;; obsolete
2921 (byte-defop-compiler-rmsfun memq        2)
2922 (byte-defop-compiler interactive-p      0)
2923 (byte-defop-compiler widen              0+1)
2924 (byte-defop-compiler end-of-line        0-1+1)
2925 (byte-defop-compiler forward-char       0-1+1)
2926 (byte-defop-compiler forward-line       0-1+1)
2927 (byte-defop-compiler symbolp            1)
2928 (byte-defop-compiler consp              1)
2929 (byte-defop-compiler stringp            1)
2930 (byte-defop-compiler listp              1)
2931 (byte-defop-compiler not                1)
2932 (byte-defop-compiler (null byte-not)    1)
2933 (byte-defop-compiler car                1)
2934 (byte-defop-compiler cdr                1)
2935 (byte-defop-compiler length             1)
2936 (byte-defop-compiler symbol-value       1)
2937 (byte-defop-compiler symbol-function    1)
2938 (byte-defop-compiler (1+ byte-add1)     1)
2939 (byte-defop-compiler (1- byte-sub1)     1)
2940 (byte-defop-compiler goto-char          1+1)
2941 (byte-defop-compiler char-after         0-1+1)
2942 (byte-defop-compiler set-buffer         1)
2943 ;;(byte-defop-compiler set-mark         1) ;; obsolete
2944 (byte-defop-compiler forward-word       0-1+1)
2945 (byte-defop-compiler char-syntax        1+1)
2946 (byte-defop-compiler nreverse           1)
2947 (byte-defop-compiler car-safe           1)
2948 (byte-defop-compiler cdr-safe           1)
2949 (byte-defop-compiler numberp            1)
2950 (byte-defop-compiler integerp           1)
2951 (byte-defop-compiler skip-chars-forward     1-2+1)
2952 (byte-defop-compiler skip-chars-backward    1-2+1)
2953 (byte-defop-compiler (eql byte-eq)      2)
2954 (byte-defop-compiler20 old-eq           2)
2955 (byte-defop-compiler20 old-memq         2)
2956 (byte-defop-compiler cons               2)
2957 (byte-defop-compiler aref               2)
2958 (byte-defop-compiler get                2+1)
2959 (byte-defop-compiler nth                2)
2960 (byte-defop-compiler substring          2-3)
2961 (byte-defop-compiler (move-marker byte-set-marker) 2-3)
2962 (byte-defop-compiler set-marker         2-3)
2963 (byte-defop-compiler match-beginning    1)
2964 (byte-defop-compiler match-end          1)
2965 (byte-defop-compiler upcase             1+1)
2966 (byte-defop-compiler downcase           1+1)
2967 (byte-defop-compiler string=            2)
2968 (byte-defop-compiler string<            2)
2969 (byte-defop-compiler (string-equal byte-string=) 2)
2970 (byte-defop-compiler (string-lessp byte-string<) 2)
2971 (byte-defop-compiler20 old-equal        2)
2972 (byte-defop-compiler nthcdr             2)
2973 (byte-defop-compiler elt                2)
2974 (byte-defop-compiler20 old-member       2)
2975 (byte-defop-compiler20 old-assq         2)
2976 (byte-defop-compiler (rplaca byte-setcar) 2)
2977 (byte-defop-compiler (rplacd byte-setcdr) 2)
2978 (byte-defop-compiler setcar             2)
2979 (byte-defop-compiler setcdr             2)
2980 (byte-defop-compiler delete-region      2+1)
2981 (byte-defop-compiler narrow-to-region   2+1)
2982 (byte-defop-compiler (% byte-rem)       2)
2983 (byte-defop-compiler aset               3)
2984
2985 (byte-defop-compiler-rmsfun member      2)
2986 (byte-defop-compiler-rmsfun assq        2)
2987
2988 ;;####(byte-defop-compiler move-to-column       1)
2989 (byte-defop-compiler-1 interactive byte-compile-noop)
2990 (byte-defop-compiler-1 domain byte-compile-domain)
2991
2992 ;; As of GNU Emacs 19.18 and Lucid Emacs 19.8, mod and % are different: `%'
2993 ;; means integral remainder and may have a negative result; `mod' is always
2994 ;; positive, and accepts floating point args.  All code which uses `mod' and
2995 ;; requires the new interpretation must be compiled with bytecomp version 2.18
2996 ;; or newer, or the emitted code will run the byte-code for `%' instead of an
2997 ;; actual call to `mod'.  So be careful of compiling new code with an old
2998 ;; compiler.  Note also that `%' is more efficient than `mod' because the
2999 ;; former is byte-coded and the latter is not.
3000 ;;(byte-defop-compiler (mod byte-rem) 2)
3001
3002 \f
3003 (defun byte-compile-subr-wrong-args (form n)
3004   (when (memq 'subr-callargs byte-compile-warnings)
3005     (byte-compile-warn "%s called with %d arg%s, but requires %s"
3006                        (car form) (length (cdr form))
3007                        (if (= 1 (length (cdr form))) "" "s") n))
3008   ;; get run-time wrong-number-of-args error.
3009   (byte-compile-normal-call form))
3010
3011 (defun byte-compile-no-args (form)
3012   (case (length (cdr form))
3013     (0 (byte-compile-out (get (car form) 'byte-opcode) 0))
3014     (t (byte-compile-subr-wrong-args form "none"))))
3015
3016 (defun byte-compile-one-arg (form)
3017   (case (length (cdr form))
3018     (1 (byte-compile-form (car (cdr form)))  ;; Push the argument
3019        (byte-compile-out (get (car form) 'byte-opcode) 0))
3020     (t (byte-compile-subr-wrong-args form 1))))
3021
3022 (defun byte-compile-two-args (form)
3023   (case (length (cdr form))
3024     (2 (byte-compile-form (nth 1 form))  ;; Push the arguments
3025        (byte-compile-form (nth 2 form))
3026        (byte-compile-out (get (car form) 'byte-opcode) 0))
3027     (t (byte-compile-subr-wrong-args form 2))))
3028
3029 (defun byte-compile-three-args (form)
3030   (case (length (cdr form))
3031     (3 (byte-compile-form (nth 1 form))  ;; Push the arguments
3032        (byte-compile-form (nth 2 form))
3033        (byte-compile-form (nth 3 form))
3034        (byte-compile-out (get (car form) 'byte-opcode) 0))
3035     (t (byte-compile-subr-wrong-args form 3))))
3036
3037 (defun byte-compile-zero-or-one-arg (form)
3038   (case (length (cdr form))
3039     (0 (byte-compile-one-arg (append form '(nil))))
3040     (1 (byte-compile-one-arg form))
3041     (t (byte-compile-subr-wrong-args form "0-1"))))
3042
3043 (defun byte-compile-one-or-two-args (form)
3044   (case (length (cdr form))
3045     (1 (byte-compile-two-args (append form '(nil))))
3046     (2 (byte-compile-two-args form))
3047     (t (byte-compile-subr-wrong-args form "1-2"))))
3048
3049 (defun byte-compile-two-or-three-args (form)
3050   (case (length (cdr form))
3051     (2 (byte-compile-three-args (append form '(nil))))
3052     (3 (byte-compile-three-args form))
3053     (t (byte-compile-subr-wrong-args form "2-3"))))
3054
3055 ;; from Ben Wing <ben@xemacs.org>: some inlined functions have extra
3056 ;; optional args added to them in XEmacs 19.12.  Changing the byte
3057 ;; interpreter to deal with these args would be wrong and cause
3058 ;; incompatibility, so we generate non-inlined calls for those cases.
3059 ;; Without the following functions, spurious warnings will be generated;
3060 ;; however, they would still compile correctly because
3061 ;; `byte-compile-subr-wrong-args' also converts the call to non-inlined.
3062
3063 (defun byte-compile-no-args-with-one-extra (form)
3064   (case (length (cdr form))
3065     (0 (byte-compile-no-args form))
3066     (1 (if (eq nil (nth 1 form))
3067            (byte-compile-no-args (butlast form))
3068          (byte-compile-normal-call form)))
3069     (t (byte-compile-subr-wrong-args form "0-1"))))
3070
3071 (defun byte-compile-one-arg-with-one-extra (form)
3072   (case (length (cdr form))
3073     (1 (byte-compile-one-arg form))
3074     (2 (if (eq nil (nth 2 form))
3075            (byte-compile-one-arg (butlast form))
3076          (byte-compile-normal-call form)))
3077     (t (byte-compile-subr-wrong-args form "1-2"))))
3078
3079 (defun byte-compile-two-args-with-one-extra (form)
3080   (case (length (cdr form))
3081     (2 (byte-compile-two-args form))
3082     (3 (if (eq nil (nth 3 form))
3083            (byte-compile-two-args (butlast form))
3084          (byte-compile-normal-call form)))
3085     (t (byte-compile-subr-wrong-args form "2-3"))))
3086
3087 (defun byte-compile-zero-or-one-arg-with-one-extra (form)
3088   (case (length (cdr form))
3089     (0 (byte-compile-one-arg (append form '(nil))))
3090     (1 (byte-compile-one-arg form))
3091     (2 (if (eq nil (nth 2 form))
3092            (byte-compile-one-arg (butlast form))
3093          (byte-compile-normal-call form)))
3094     (t (byte-compile-subr-wrong-args form "0-2"))))
3095
3096 (defun byte-compile-one-or-two-args-with-one-extra (form)
3097   (case (length (cdr form))
3098     (1 (byte-compile-two-args (append form '(nil))))
3099     (2 (byte-compile-two-args form))
3100     (3 (if (eq nil (nth 3 form))
3101            (byte-compile-two-args (butlast form))
3102          (byte-compile-normal-call form)))
3103     (t (byte-compile-subr-wrong-args form "1-3"))))
3104
3105 (defun byte-compile-two-or-three-args-with-one-extra (form)
3106   (case (length (cdr form))
3107     (2 (byte-compile-three-args (append form '(nil))))
3108     (3 (byte-compile-three-args form))
3109     (4 (if (eq nil (nth 4 form))
3110            (byte-compile-three-args (butlast form))
3111          (byte-compile-normal-call form)))
3112     (t (byte-compile-subr-wrong-args form "2-4"))))
3113
3114 (defun byte-compile-no-args-with-two-extra (form)
3115   (case (length (cdr form))
3116     (0     (byte-compile-no-args form))
3117     ((1 2) (byte-compile-normal-call form))
3118     (t     (byte-compile-subr-wrong-args form "0-2"))))
3119
3120 (defun byte-compile-one-arg-with-two-extra (form)
3121   (case (length (cdr form))
3122     (1     (byte-compile-one-arg form))
3123     ((2 3) (byte-compile-normal-call form))
3124     (t     (byte-compile-subr-wrong-args form "1-3"))))
3125
3126 ;; XEmacs: used for functions that have a different opcode in v19 than v20.
3127 ;; this includes `eq', `equal', and other old-ified functions.
3128 (defun byte-compile-two-args-19->20 (form)
3129   (if (not (= (length form) 3))
3130       (byte-compile-subr-wrong-args form 2)
3131     (byte-compile-form (car (cdr form)))  ;; Push the arguments
3132     (byte-compile-form (nth 2 form))
3133     (if (byte-compile-version-cond byte-compile-emacs19-compatibility)
3134         (byte-compile-out (get (car form) 'byte-opcode19) 0)
3135       (byte-compile-out (get (car form) 'byte-opcode) 0))))
3136
3137 (defun byte-compile-noop (form)
3138   (byte-compile-constant nil))
3139
3140 (defun byte-compile-discard ()
3141   (byte-compile-out 'byte-discard 0))
3142
3143 (defun byte-compile-max (form)
3144   (let ((args (cdr form)))
3145     (case (length args)
3146       (0 (byte-compile-subr-wrong-args form "1 or more"))
3147       (1 (byte-compile-form (car args))
3148          (when (not byte-compile-delete-errors)
3149            (byte-compile-out 'byte-dup 0)
3150            (byte-compile-out 'byte-max 0)))
3151       (t (byte-compile-form (car args))
3152          (dolist (elt (cdr args))
3153            (byte-compile-form elt)
3154            (byte-compile-out 'byte-max 0))))))
3155
3156 (defun byte-compile-min (form)
3157   (let ((args (cdr form)))
3158     (case (length args)
3159       (0 (byte-compile-subr-wrong-args form "1 or more"))
3160       (1 (byte-compile-form (car args))
3161          (when (not byte-compile-delete-errors)
3162            (byte-compile-out 'byte-dup 0)
3163            (byte-compile-out 'byte-min 0)))
3164       (t (byte-compile-form (car args))
3165          (dolist (elt (cdr args))
3166            (byte-compile-form elt)
3167            (byte-compile-out 'byte-min 0))))))
3168
3169 \f
3170 ;; more complicated compiler macros
3171
3172 (byte-defop-compiler list)
3173 (byte-defop-compiler concat)
3174 (byte-defop-compiler fset)
3175 (byte-defop-compiler insert)
3176 (byte-defop-compiler-1 function byte-compile-function-form)
3177 (byte-defop-compiler max)
3178 (byte-defop-compiler min)
3179 (byte-defop-compiler (+ byte-plus)      byte-compile-plus)
3180 (byte-defop-compiler-1 -                byte-compile-minus)
3181 (byte-defop-compiler (* byte-mult)      byte-compile-mult)
3182 (byte-defop-compiler (/ byte-quo)       byte-compile-quo)
3183 (byte-defop-compiler nconc)
3184 (byte-defop-compiler-1 beginning-of-line)
3185
3186 (byte-defop-compiler (=  byte-eqlsign)  byte-compile-arithcompare)
3187 (byte-defop-compiler (<  byte-lss)      byte-compile-arithcompare)
3188 (byte-defop-compiler (>  byte-gtr)      byte-compile-arithcompare)
3189 (byte-defop-compiler (<= byte-leq)      byte-compile-arithcompare)
3190 (byte-defop-compiler (>= byte-geq)      byte-compile-arithcompare)
3191
3192 (defun byte-compile-arithcompare (form)
3193   (case (length (cdr form))
3194     (0 (byte-compile-subr-wrong-args form "1 or more"))
3195     (1 (if byte-compile-delete-errors
3196            (byte-compile-constant t)
3197          (byte-compile-normal-call form)))
3198     (2 (byte-compile-two-args form))
3199     (t (byte-compile-normal-call form))))
3200
3201 (byte-defop-compiler /= byte-compile-/=)
3202
3203 (defun byte-compile-/= (form)
3204   (case (length (cdr form))
3205     (0 (byte-compile-subr-wrong-args form "1 or more"))
3206     (1 (byte-compile-constant t))
3207     ;; optimize (/= X Y) to (not (= X Y))
3208     (2 (byte-compile-form-do-effect `(not (= ,@(cdr form)))))
3209     (t (byte-compile-normal-call form))))
3210
3211 ;; buffer-substring now has its own function.  This used to be
3212 ;; 2+1, but now all args are optional.
3213 (byte-defop-compiler buffer-substring)
3214
3215 (defun byte-compile-buffer-substring (form)
3216   ;; buffer-substring used to take exactly two args, but now takes 0-3.
3217   ;; convert 0-2 to two args and use special bytecode operand.
3218   ;; convert 3 args to a normal call.
3219   (case (length (cdr form))
3220     (0 (byte-compile-two-args (append form '(nil nil))))
3221     (1 (byte-compile-two-args (append form '(nil))))
3222     (2 (byte-compile-two-args form))
3223     (3 (byte-compile-normal-call form))
3224     (t (byte-compile-subr-wrong-args form "0-3"))))
3225
3226 (defun byte-compile-list (form)
3227   (let* ((args (cdr form))
3228          (nargs (length args)))
3229     (cond
3230      ((= nargs 0)
3231       (byte-compile-constant nil))
3232      ((< nargs 5)
3233       (mapcar 'byte-compile-form args)
3234       (byte-compile-out
3235        (aref [byte-list1 byte-list2 byte-list3 byte-list4] (1- nargs))
3236        0))
3237      ((< nargs 256)
3238       (mapcar 'byte-compile-form args)
3239       (byte-compile-out 'byte-listN nargs))
3240      (t (byte-compile-normal-call form)))))
3241
3242 (defun byte-compile-concat (form)
3243   (let* ((args (cdr form))
3244          (nargs (length args)))
3245     ;; Concat of one arg is not a no-op if arg is not a string.
3246     (cond
3247      ((memq nargs '(2 3 4))
3248       (mapcar 'byte-compile-form args)
3249       (byte-compile-out
3250        (aref [byte-concat2 byte-concat3 byte-concat4] (- nargs 2))
3251        0))
3252      ((eq nargs 0)
3253       (byte-compile-form ""))
3254      ((< nargs 256)
3255       (mapcar 'byte-compile-form args)
3256       (byte-compile-out 'byte-concatN nargs))
3257      ((byte-compile-normal-call form)))))
3258
3259 (defun byte-compile-plus (form)
3260   (let ((args (cdr form)))
3261     (case (length args)
3262       (0 (byte-compile-constant 0))
3263       (1 (byte-compile-plus (append form '(0))))
3264       (t (byte-compile-form (car args))
3265          (dolist (elt (cdr args))
3266            (case elt
3267              (0  (when (not byte-compile-delete-errors)
3268                    (byte-compile-constant 0)
3269                    (byte-compile-out 'byte-plus 0)))
3270              (+1 (byte-compile-out 'byte-add1 0))
3271              (-1 (byte-compile-out 'byte-sub1 0))
3272              (t
3273               (byte-compile-form elt)
3274               (byte-compile-out 'byte-plus 0))))))))
3275
3276 (defun byte-compile-minus (form)
3277   (let ((args (cdr form)))
3278     (case (length args)
3279       (0 (byte-compile-subr-wrong-args form "1 or more"))
3280       (1 (byte-compile-form (car args))
3281          (byte-compile-out 'byte-negate 0))
3282       (t (byte-compile-form (car args))
3283          (dolist (elt (cdr args))
3284            (case elt
3285              (0  (when (not byte-compile-delete-errors)
3286                    (byte-compile-constant 0)
3287                    (byte-compile-out 'byte-diff 0)))
3288              (+1 (byte-compile-out 'byte-sub1 0))
3289              (-1 (byte-compile-out 'byte-add1 0))
3290              (t
3291               (byte-compile-form elt)
3292               (byte-compile-out 'byte-diff 0))))))))
3293
3294 (defun byte-compile-mult (form)
3295   (let ((args (cdr form)))
3296     (case (length args)
3297       (0 (byte-compile-constant 1))
3298       (1 (byte-compile-mult (append form '(1))))
3299       (t (byte-compile-form (car args))
3300          (dolist (elt (cdr args))
3301            (case elt
3302              (1  (when (not byte-compile-delete-errors)
3303                    (byte-compile-constant 1)
3304                    (byte-compile-out 'byte-mult 0)))
3305              (-1 (byte-compile-out 'byte-negate 0))
3306              (2  (byte-compile-out 'byte-dup 0)
3307                  (byte-compile-out 'byte-plus 0))
3308              (t
3309               (byte-compile-form elt)
3310               (byte-compile-out 'byte-mult 0))))))))
3311
3312 (defun byte-compile-quo (form)
3313   (let ((args (cdr form)))
3314     (case (length args)
3315       (0 (byte-compile-subr-wrong-args form "1 or more"))
3316       (1 (byte-compile-constant 1)
3317          (byte-compile-form (car args))
3318          (byte-compile-out 'byte-quo 0))
3319       (t (byte-compile-form (car args))
3320          (dolist (elt (cdr args))
3321            (case elt
3322              (+1 (when (not byte-compile-delete-errors)
3323                    (byte-compile-constant 1)
3324                    (byte-compile-out 'byte-quo 0)))
3325              (-1 (byte-compile-out 'byte-negate 0))
3326              (t
3327               (when (and (numberp elt) (= elt 0))
3328                 (byte-compile-warn "Attempt to divide by zero: %s" form))
3329               (byte-compile-form elt)
3330               (byte-compile-out 'byte-quo 0))))))))
3331
3332 (defun byte-compile-nconc (form)
3333   (let ((args (cdr form)))
3334     (case (length args)
3335       (0 (byte-compile-constant nil))
3336       ;; nconc of one arg is a noop, even if that arg isn't a list.
3337       (1 (byte-compile-form (car args)))
3338       (t (byte-compile-form (car args))
3339          (dolist (elt (cdr args))
3340            (byte-compile-form elt)
3341            (byte-compile-out 'byte-nconc 0))))))
3342
3343 (defun byte-compile-fset (form)
3344   ;; warn about forms like (fset 'foo '(lambda () ...))
3345   ;; (where the lambda expression is non-trivial...)
3346   ;; Except don't warn if the first argument is 'make-byte-code, because
3347   ;; I'm sick of getting mail asking me whether that warning is a problem.
3348   (let ((fn (nth 2 form))
3349         body)
3350     (when (and (eq (car-safe fn) 'quote)
3351                (eq (car-safe (setq fn (nth 1 fn))) 'lambda)
3352                (not (eq (car-safe (cdr-safe (nth 1 form))) 'make-byte-code)))
3353       (setq body (cdr (cdr fn)))
3354       (if (stringp (car body)) (setq body (cdr body)))
3355       (if (eq 'interactive (car-safe (car body))) (setq body (cdr body)))
3356       (if (and (consp (car body))
3357                (not (eq 'byte-code (car (car body)))))
3358           (byte-compile-warn
3359     "A quoted lambda form is the second argument of fset.  This is probably
3360      not what you want, as that lambda cannot be compiled.  Consider using
3361      the syntax (function (lambda (...) ...)) instead."))))
3362   (byte-compile-two-args form))
3363
3364 (defun byte-compile-funarg (form)
3365   ;; (mapcar '(lambda (x) ..) ..) ==> (mapcar (function (lambda (x) ..)) ..)
3366   ;; for cases where it's guaranteed that first arg will be used as a lambda.
3367   (byte-compile-normal-call
3368    (let ((fn (nth 1 form)))
3369      (if (and (eq (car-safe fn) 'quote)
3370               (eq (car-safe (nth 1 fn)) 'lambda))
3371          (cons (car form)
3372                (cons (cons 'function (cdr fn))
3373                      (cdr (cdr form))))
3374        form))))
3375
3376 ;; (function foo) must compile like 'foo, not like (symbol-function 'foo).
3377 ;; Otherwise it will be incompatible with the interpreter,
3378 ;; and (funcall (function foo)) will lose with autoloads.
3379
3380 (defun byte-compile-function-form (form)
3381   (byte-compile-constant
3382    (cond ((symbolp (nth 1 form))
3383           (nth 1 form))
3384          ((byte-compile-lambda (nth 1 form))))))
3385
3386 (defun byte-compile-insert (form)
3387   (cond ((null (cdr form))
3388          (byte-compile-constant nil))
3389         ((<= (length form) 256)
3390          (mapcar 'byte-compile-form (cdr form))
3391          (if (cdr (cdr form))
3392              (byte-compile-out 'byte-insertN (length (cdr form)))
3393            (byte-compile-out 'byte-insert 0)))
3394         ((memq t (mapcar 'consp (cdr (cdr form))))
3395          (byte-compile-normal-call form))
3396         ;; We can split it; there is no function call after inserting 1st arg.
3397         (t
3398          (while (setq form (cdr form))
3399            (byte-compile-form (car form))
3400            (byte-compile-out 'byte-insert 0)
3401            (when (cdr form)
3402              (byte-compile-discard))))))
3403
3404 ;; alas, the old (pre-19.12, and all existing versions of FSFmacs 19)
3405 ;; byte compiler will generate incorrect code for
3406 ;; (beginning-of-line nil buffer) because it buggily doesn't
3407 ;; check the number of arguments passed to beginning-of-line.
3408
3409 (defun byte-compile-beginning-of-line (form)
3410   (let ((len (length form)))
3411     (cond ((> len 3)
3412            (byte-compile-subr-wrong-args form "0-2"))
3413           ((or (= len 3) (not (byte-compile-constp (nth 1 form))))
3414            (byte-compile-normal-call form))
3415           (t
3416            (byte-compile-form
3417             (list 'forward-line
3418                   (if (integerp (setq form (or (eval (nth 1 form)) 1)))
3419                       (1- form)
3420                     (byte-compile-warn
3421                      "Non-numeric arg to beginning-of-line: %s" form)
3422                     (list '1- (list 'quote form))))
3423             t)
3424            (byte-compile-constant nil)))))
3425
3426 \f
3427 (byte-defop-compiler set)
3428 (byte-defop-compiler-1 setq)
3429 (byte-defop-compiler-1 set-default)
3430 (byte-defop-compiler-1 setq-default)
3431
3432 (byte-defop-compiler-1 quote)
3433 (byte-defop-compiler-1 quote-form)
3434
3435 (defun byte-compile-setq (form)
3436   (let ((args (cdr form)) var val)
3437     (if (null args)
3438         ;; (setq), with no arguments.
3439         (byte-compile-form nil for-effect)
3440       (while args
3441         (setq var (pop args))
3442         (if (null args)
3443             ;; Odd number of args?  Let `set' get the error.
3444             (byte-compile-form `(set ',var) for-effect)
3445           (setq val (pop args))
3446           (if (keywordp var)
3447               ;; (setq :foo ':foo) compatibility kludge
3448               (byte-compile-form `(set ',var ,val) (if args t for-effect))
3449             (byte-compile-form val)
3450             (unless (or args for-effect)
3451               (byte-compile-out 'byte-dup 0))
3452             (byte-compile-variable-ref 'byte-varset var))))))
3453   (setq for-effect nil))
3454
3455 (defun byte-compile-set (form)
3456   ;; Compile (set 'foo x) as (setq foo x) for trivially better code and so
3457   ;; that we get applicable warnings.  Compile everything else (including
3458   ;; malformed calls) like a normal 2-arg byte-coded function.
3459   (let ((symform (nth 1 form))
3460         (valform (nth 2 form))
3461         sym)
3462     (if (and (= (length form) 3)
3463              (= (safe-length symform) 2)
3464              (eq (car symform) 'quote)
3465              (symbolp (setq sym (car (cdr symform))))
3466              (not (byte-compile-constant-symbol-p sym)))
3467         (byte-compile-setq `(setq ,sym ,valform))
3468       (byte-compile-two-args form))))
3469
3470 (defun byte-compile-setq-default (form)
3471   (let ((args (cdr form)))
3472     (if (null args)
3473         ;; (setq-default), with no arguments.
3474         (byte-compile-form nil for-effect)
3475       ;; emit multiple calls to `set-default' if necessary
3476       (while args
3477         (byte-compile-form
3478          ;; Odd number of args?  Let `set-default' get the error.
3479          `(set-default ',(pop args) ,@(if args (list (pop args)) nil))
3480          (if args t for-effect)))))
3481   (setq for-effect nil))
3482
3483
3484 (defun byte-compile-set-default (form)
3485   (let* ((args (cdr form))
3486          (nargs (length args))
3487          (var (car args)))
3488     (when (and (= (safe-length var) 2)
3489                (eq (car var) 'quote))
3490       (let ((sym (nth 1 var)))
3491         (cond
3492          ((not (symbolp sym))
3493           (byte-compile-warn "Attempt to set-globally non-symbol %s" sym))
3494          ((byte-compile-constant-symbol-p sym)
3495           (byte-compile-warn "Attempt to set-globally constant symbol %s" sym))
3496          ((let ((cell (assq sym byte-compile-bound-variables)))
3497             (and cell
3498                  (setcdr cell (logior (cdr cell) byte-compile-assigned-bit))
3499                  t)))
3500          ;; notice calls to set-default/setq-default for variables which
3501          ;; have not been declared with defvar/defconst.
3502          ((globally-boundp sym))        ; OK
3503          ((not (memq 'free-vars byte-compile-warnings))) ; warnings suppressed?
3504          ((memq sym byte-compile-free-assignments)) ; already warned about sym
3505          (t
3506           (byte-compile-warn "assignment to free variable %s" sym)
3507           (push sym byte-compile-free-assignments)))))
3508     (if (= nargs 2)
3509         ;; now emit a normal call to set-default
3510         (byte-compile-normal-call form)
3511       (byte-compile-subr-wrong-args form 2))))
3512
3513
3514 (defun byte-compile-quote (form)
3515   (byte-compile-constant (car (cdr form))))
3516
3517 (defun byte-compile-quote-form (form)
3518   (byte-compile-constant (byte-compile-top-level (nth 1 form))))
3519
3520 \f
3521 ;;; control structures
3522
3523 (defun byte-compile-body (body &optional for-effect)
3524   (while (cdr body)
3525     (byte-compile-form (car body) t)
3526     (setq body (cdr body)))
3527   (byte-compile-form (car body) for-effect))
3528
3529 (proclaim-inline byte-compile-body-do-effect)
3530 (defun byte-compile-body-do-effect (body)
3531   (byte-compile-body body for-effect)
3532   (setq for-effect nil))
3533
3534 (proclaim-inline byte-compile-form-do-effect)
3535 (defun byte-compile-form-do-effect (form)
3536   (byte-compile-form form for-effect)
3537   (setq for-effect nil))
3538
3539 (byte-defop-compiler-1 inline byte-compile-progn)
3540 (byte-defop-compiler-1 progn)
3541 (byte-defop-compiler-1 prog1)
3542 (byte-defop-compiler-1 prog2)
3543 (byte-defop-compiler-1 if)
3544 (byte-defop-compiler-1 cond)
3545 (byte-defop-compiler-1 and)
3546 (byte-defop-compiler-1 or)
3547 (byte-defop-compiler-1 while)
3548 (byte-defop-compiler-1 funcall)
3549 (byte-defop-compiler-1 apply byte-compile-funarg)
3550 (byte-defop-compiler-1 mapcar byte-compile-funarg)
3551 (byte-defop-compiler-1 mapatoms byte-compile-funarg)
3552 (byte-defop-compiler-1 mapconcat byte-compile-funarg)
3553 (byte-defop-compiler-1 let)
3554 (byte-defop-compiler-1 let*)
3555 (byte-defop-compiler-1 cl:do)
3556 (byte-defop-compiler-1 cl:do*)
3557 (byte-defop-compiler-1 cl:dotimes)
3558 (byte-defop-compiler-1 cl:dolist)
3559 (byte-defop-compiler-1 cl:do-symbols)
3560 (byte-defop-compiler-1 cl:do-all-symbols)
3561 (byte-defop-compiler-1 cl:loop)
3562
3563 (defun byte-compile-progn (form)
3564   (byte-compile-body-do-effect (cdr form)))
3565
3566 (defun byte-compile-prog1 (form)
3567   (setq form (cdr form))
3568   (byte-compile-form-do-effect (pop form))
3569   (byte-compile-body form t))
3570
3571 (defun byte-compile-prog2 (form)
3572   (setq form (cdr form))
3573   (byte-compile-form (pop form) t)
3574   (byte-compile-form-do-effect (pop form))
3575   (byte-compile-body form t))
3576
3577 (defmacro byte-compile-goto-if (cond discard tag)
3578   `(byte-compile-goto
3579     (if ,cond
3580         (if ,discard 'byte-goto-if-not-nil 'byte-goto-if-not-nil-else-pop)
3581       (if ,discard 'byte-goto-if-nil 'byte-goto-if-nil-else-pop))
3582     ,tag))
3583
3584 (defun byte-compile-if (form)
3585   (byte-compile-form (car (cdr form)))
3586   (if (null (nthcdr 3 form))
3587       ;; No else-forms
3588       (let ((donetag (byte-compile-make-tag)))
3589         (byte-compile-goto-if nil for-effect donetag)
3590         (byte-compile-form (nth 2 form) for-effect)
3591         (byte-compile-out-tag donetag))
3592     (let ((donetag (byte-compile-make-tag)) (elsetag (byte-compile-make-tag)))
3593       (byte-compile-goto 'byte-goto-if-nil elsetag)
3594       (byte-compile-form (nth 2 form) for-effect)
3595       (byte-compile-goto 'byte-goto donetag)
3596       (byte-compile-out-tag elsetag)
3597       (byte-compile-body (cdr (cdr (cdr form))) for-effect)
3598       (byte-compile-out-tag donetag)))
3599   (setq for-effect nil))
3600
3601 (defun byte-compile-cond (clauses)
3602   (let ((donetag (byte-compile-make-tag))
3603         nexttag clause)
3604     (while (setq clauses (cdr clauses))
3605       (setq clause (car clauses))
3606       (cond ((or (eq (car clause) t)
3607                  (and (eq (car-safe (car clause)) 'quote)
3608                       (car-safe (cdr-safe (car clause)))))
3609              ;; Unconditional clause
3610              (setq clause (cons t clause)
3611                    clauses nil))
3612             ((cdr clauses)
3613              (byte-compile-form (car clause))
3614              (if (null (cdr clause))
3615                  ;; First clause is a singleton.
3616                  (byte-compile-goto-if t for-effect donetag)
3617                (setq nexttag (byte-compile-make-tag))
3618                (byte-compile-goto 'byte-goto-if-nil nexttag)
3619                (byte-compile-body (cdr clause) for-effect)
3620                (byte-compile-goto 'byte-goto donetag)
3621                (byte-compile-out-tag nexttag)))))
3622     ;; Last clause
3623     (and (cdr clause) (not (eq (car clause) t))
3624          (progn (byte-compile-form (car clause))
3625                 (byte-compile-goto-if nil for-effect donetag)
3626                 (setq clause (cdr clause))))
3627     (byte-compile-body-do-effect clause)
3628     (byte-compile-out-tag donetag)))
3629
3630 (defun byte-compile-and (form)
3631   (let ((failtag (byte-compile-make-tag))
3632         (args (cdr form)))
3633     (if (null args)
3634         (byte-compile-form-do-effect t)
3635       (while (cdr args)
3636         (byte-compile-form (car args))
3637         (byte-compile-goto-if nil for-effect failtag)
3638         (setq args (cdr args)))
3639       (byte-compile-form-do-effect (car args))
3640       (byte-compile-out-tag failtag))))
3641
3642 (defun byte-compile-or (form)
3643   (let ((wintag (byte-compile-make-tag))
3644         (args (cdr form)))
3645     (if (null args)
3646         (byte-compile-form-do-effect nil)
3647       (while (cdr args)
3648         (byte-compile-form (car args))
3649         (byte-compile-goto-if t for-effect wintag)
3650         (setq args (cdr args)))
3651       (byte-compile-form-do-effect (car args))
3652       (byte-compile-out-tag wintag))))
3653
3654 (defun byte-compile-while (form)
3655   (let ((endtag (byte-compile-make-tag))
3656         (looptag (byte-compile-make-tag)))
3657     (byte-compile-out-tag looptag)
3658     (byte-compile-form (car (cdr form)))
3659     (byte-compile-goto-if nil for-effect endtag)
3660     (byte-compile-body (cdr (cdr form)) t)
3661     (byte-compile-goto 'byte-goto looptag)
3662     (byte-compile-out-tag endtag)
3663     (setq for-effect nil)))
3664
3665 (defun byte-compile-funcall (form)
3666   (mapcar 'byte-compile-form (cdr form))
3667   (byte-compile-out 'byte-call (length (cdr (cdr form)))))
3668
3669
3670 (defun byte-compile-let (form)
3671   ;; First compute the binding values in the old scope.
3672   (let ((varlist (car (cdr form))))
3673     (while varlist
3674       (if (consp (car varlist))
3675           (byte-compile-form (car (cdr (car varlist))))
3676         (byte-compile-push-constant nil))
3677       (setq varlist (cdr varlist))))
3678   (let ((byte-compile-bound-variables
3679          (cons 'new-scope byte-compile-bound-variables))
3680         (varlist (reverse (car (cdr form))))
3681         (extra-flags
3682          ;; If this let is of the form (let (...) (byte-code ...))
3683          ;; then assume that it is the result of a transformation of
3684          ;; ((lambda (...) (byte-code ... )) ...) and thus compile
3685          ;; the variable bindings as if they were arglist bindings
3686          ;; (which matters for what warnings.)
3687          (if (eq 'byte-code (car-safe (nth 2 form)))
3688              byte-compile-arglist-bit
3689            nil)))
3690     (while varlist
3691       (byte-compile-variable-ref 'byte-varbind
3692                                  (if (consp (car varlist))
3693                                      (car (car varlist))
3694                                    (car varlist))
3695                                  extra-flags)
3696       (setq varlist (cdr varlist)))
3697     (byte-compile-body-do-effect (cdr (cdr form)))
3698     (if (memq 'unused-vars byte-compile-warnings)
3699         ;; done compiling in this scope, warn now.
3700         (byte-compile-warn-about-unused-variables))
3701     (byte-compile-out 'byte-unbind (length (car (cdr form))))))
3702
3703 (defun byte-compile-let* (form)
3704   (let ((byte-compile-bound-variables
3705          (cons 'new-scope byte-compile-bound-variables))
3706         (varlist (copy-sequence (car (cdr form)))))
3707     (while varlist
3708       (if (atom (car varlist))
3709           (byte-compile-push-constant nil)
3710         (byte-compile-form (car (cdr (car varlist))))
3711         (setcar varlist (car (car varlist))))
3712       (byte-compile-variable-ref 'byte-varbind (car varlist))
3713       (setq varlist (cdr varlist)))
3714     (byte-compile-body-do-effect (cdr (cdr form)))
3715     (if (memq 'unused-vars byte-compile-warnings)
3716         ;; done compiling in this scope, warn now.
3717         (byte-compile-warn-about-unused-variables))
3718     (byte-compile-out 'byte-unbind (length (car (cdr form))))))
3719
3720
3721 ;;(byte-defop-compiler-1 /= byte-compile-negated)
3722 (byte-defop-compiler-1 atom byte-compile-negated)
3723 (byte-defop-compiler-1 nlistp byte-compile-negated)
3724
3725 ;;(put '/= 'byte-compile-negated-op '=)
3726 (put 'atom 'byte-compile-negated-op 'consp)
3727 (put 'nlistp 'byte-compile-negated-op 'listp)
3728
3729 (defun byte-compile-negated (form)
3730   (byte-compile-form-do-effect (byte-compile-negation-optimizer form)))
3731
3732 ;; Even when optimization is off, atom is optimized to (not (consp ...)).
3733 (defun byte-compile-negation-optimizer (form)
3734   ;; an optimizer for forms where <form1> is less efficient than (not <form2>)
3735   (list 'not
3736     (cons (or (get (car form) 'byte-compile-negated-op)
3737               (error
3738                "Compiler error: `%s' has no `byte-compile-negated-op' property"
3739                (car form)))
3740           (cdr form))))
3741 \f
3742 ;;; other tricky macro-like special-forms
3743
3744 (byte-defop-compiler-1 catch)
3745 (byte-defop-compiler-1 unwind-protect)
3746 (byte-defop-compiler-1 condition-case)
3747 (byte-defop-compiler-1 save-excursion)
3748 (byte-defop-compiler-1 save-current-buffer)
3749 (byte-defop-compiler-1 save-restriction)
3750 (byte-defop-compiler-1 save-window-excursion)
3751 (byte-defop-compiler-1 with-output-to-temp-buffer)
3752 ;; no track-mouse.
3753
3754 (defun byte-compile-catch (form)
3755   (byte-compile-form (car (cdr form)))
3756   (byte-compile-push-constant
3757     (byte-compile-top-level (cons 'progn (cdr (cdr form))) for-effect))
3758   (byte-compile-out 'byte-catch 0))
3759
3760 (defun byte-compile-unwind-protect (form)
3761   (byte-compile-push-constant
3762    (byte-compile-top-level-body (cdr (cdr form)) t))
3763   (byte-compile-out 'byte-unwind-protect 0)
3764   (byte-compile-form-do-effect (car (cdr form)))
3765   (byte-compile-out 'byte-unbind 1))
3766
3767 ;;(defun byte-compile-track-mouse (form)
3768 ;;  (byte-compile-form
3769 ;;   (list
3770 ;;    'funcall
3771 ;;    (list 'quote
3772 ;;          (list 'lambda nil
3773 ;;                (cons 'track-mouse
3774 ;;                      (byte-compile-top-level-body (cdr form))))))))
3775
3776 (defun byte-compile-condition-case (form)
3777   (let* ((var (nth 1 form))
3778          (byte-compile-bound-variables
3779           (if var
3780               (cons (cons var 0)
3781                     (cons 'new-scope byte-compile-bound-variables))
3782             (cons 'new-scope byte-compile-bound-variables))))
3783     (or (symbolp var)
3784         (byte-compile-warn
3785          "%s is not a variable-name or nil (in condition-case)"
3786          (prin1-to-string var)))
3787     (byte-compile-push-constant var)
3788     (byte-compile-push-constant (byte-compile-top-level
3789                                  (nth 2 form) for-effect))
3790     (let ((clauses (cdr (cdr (cdr form))))
3791           compiled-clauses)
3792       (while clauses
3793         (let* ((clause (car clauses))
3794                (condition (car clause)))
3795           (cond ((not (or (symbolp condition)
3796                           (and (listp condition)
3797                                (let ((syms condition) (ok t))
3798                                  (while syms
3799                                    (if (not (symbolp (car syms)))
3800                                        (setq ok nil))
3801                                    (setq syms (cdr syms)))
3802                                  ok))))
3803                  (byte-compile-warn
3804                    "%s is not a symbol naming a condition or a list of such (in condition-case)"
3805                    (prin1-to-string condition)))
3806 ;;                ((not (or (eq condition 't)
3807 ;;                        (and (stringp (get condition 'error-message))
3808 ;;                             (consp (get condition 'error-conditions)))))
3809 ;;                 (byte-compile-warn
3810 ;;                   "%s is not a known condition name (in condition-case)"
3811 ;;                   condition))
3812                 )
3813           (setq compiled-clauses
3814                 (cons (cons condition
3815                             (byte-compile-top-level-body
3816                              (cdr clause) for-effect))
3817                       compiled-clauses)))
3818         (setq clauses (cdr clauses)))
3819       (byte-compile-push-constant (nreverse compiled-clauses)))
3820     (if (memq 'unused-vars byte-compile-warnings)
3821         ;; done compiling in this scope, warn now.
3822         (byte-compile-warn-about-unused-variables))
3823     (byte-compile-out 'byte-condition-case 0)))
3824
3825
3826 (defun byte-compile-save-excursion (form)
3827   (byte-compile-out 'byte-save-excursion 0)
3828   (byte-compile-body-do-effect (cdr form))
3829   (byte-compile-out 'byte-unbind 1))
3830
3831 (defun byte-compile-save-restriction (form)
3832   (byte-compile-out 'byte-save-restriction 0)
3833   (byte-compile-body-do-effect (cdr form))
3834   (byte-compile-out 'byte-unbind 1))
3835
3836 (defun byte-compile-save-current-buffer (form)
3837   (if (byte-compile-version-cond byte-compile-emacs19-compatibility)
3838       ;; `save-current-buffer' special form is not available in XEmacs 19.
3839       (byte-compile-form
3840        `(let ((_byte_compiler_save_buffer_emulation_closure_ (current-buffer)))
3841           (unwind-protect
3842               (progn ,@(cdr form))
3843             (and (buffer-live-p _byte_compiler_save_buffer_emulation_closure_)
3844                  (set-buffer _byte_compiler_save_buffer_emulation_closure_)))))
3845     (byte-compile-out 'byte-save-current-buffer 0)
3846     (byte-compile-body-do-effect (cdr form))
3847     (byte-compile-out 'byte-unbind 1)))
3848
3849 (defun byte-compile-save-window-excursion (form)
3850   (byte-compile-push-constant
3851    (byte-compile-top-level-body (cdr form) for-effect))
3852   (byte-compile-out 'byte-save-window-excursion 0))
3853
3854 (defun byte-compile-with-output-to-temp-buffer (form)
3855   (byte-compile-form (car (cdr form)))
3856   (byte-compile-out 'byte-temp-output-buffer-setup 0)
3857   (byte-compile-body (cdr (cdr form)))
3858   (byte-compile-out 'byte-temp-output-buffer-show 0))
3859
3860 ;; generic byte compiler code for emod-cl stuff
3861 (defun byte-compile-cl:macro (form)
3862   (byte-compile-push-constant form)
3863   (byte-compile-out 'byte-cl:macro 0))
3864 ;; now the macros in detail
3865 (defun byte-compile-cl:do (form)
3866   (byte-compile-cl:macro form))
3867 (defun byte-compile-cl:do* (form)
3868   (byte-compile-cl:macro form))
3869 (defun byte-compile-cl:dotimes (form)
3870   (byte-compile-cl:macro form))
3871 (defun byte-compile-cl:dolist (form)
3872   (byte-compile-cl:macro form))
3873 (defun byte-compile-cl:do-symbols (form)
3874   (byte-compile-cl:macro form))
3875 (defun byte-compile-cl:do-all-symbols (form)
3876   (byte-compile-cl:macro form))
3877 (defun byte-compile-cl:loop (form)
3878   (byte-compile-cl:macro form))
3879
3880 \f
3881 ;;; top-level forms elsewhere
3882
3883 (byte-defop-compiler-1 defun)
3884 (byte-defop-compiler-1 defmacro)
3885 (byte-defop-compiler-1 defvar)
3886 (byte-defop-compiler-1 defvar   byte-compile-defvar-or-defconst)
3887 (byte-defop-compiler-1 defconst byte-compile-defvar-or-defconst)
3888 (byte-defop-compiler-1 defregexp byte-compile-defvar-or-defconst)
3889 (byte-defop-compiler-1 autoload)
3890 ;; According to Mly this can go now that lambda is a macro
3891 ;(byte-defop-compiler-1 lambda byte-compile-lambda-form)
3892 (byte-defop-compiler-1 defalias)
3893 (byte-defop-compiler-1 define-function)
3894
3895 (defun byte-compile-defun (form)
3896   ;; This is not used for file-level defuns with doc strings.
3897   (byte-compile-two-args ; Use this to avoid byte-compile-fset's warning.
3898    (list 'fset (list 'quote (nth 1 form))
3899          (byte-compile-byte-code-maker
3900           (byte-compile-lambda (cons 'lambda (cdr (cdr form)))))))
3901   (byte-compile-discard)
3902   (byte-compile-constant (nth 1 form)))
3903
3904 (defun byte-compile-defmacro (form)
3905   ;; This is not used for file-level defmacros with doc strings.
3906   (byte-compile-body-do-effect
3907    (list (list 'fset (list 'quote (nth 1 form))
3908                (let ((code (byte-compile-byte-code-maker
3909                             (byte-compile-lambda
3910                              (cons 'lambda (cdr (cdr form)))))))
3911                  (if (eq (car-safe code) 'make-byte-code)
3912                      (list 'cons ''macro code)
3913                    (list 'quote (cons 'macro (eval code))))))
3914          (list 'quote (nth 1 form)))))
3915
3916 (defun byte-compile-defvar-or-defconst (form)
3917   ;; This is not used for file-level defvar/defconsts with doc strings:
3918   ;; byte-compile-file-form-defvar-or-defconst will be used in that case.
3919   ;; (defvar|defconst VAR [VALUE [DOCSTRING]])
3920   (let ((fun (nth 0 form))
3921         (var (nth 1 form))
3922         (value (nth 2 form))
3923         (string (nth 3 form)))
3924     (when (> (length form) 4)
3925       (byte-compile-warn
3926        "%s %s called with %d arguments, but accepts only %s"
3927        fun var (length (cdr form)) 3))
3928     (when (memq 'free-vars byte-compile-warnings)
3929       (push (cons var byte-compile-global-bit) byte-compile-bound-variables))
3930     (byte-compile-body-do-effect
3931      (list
3932       ;; Put the defined variable in this library's load-history entry
3933       ;; just as a real defvar would, but only in top-level forms with values.
3934       (when (and (> (length form) 2)
3935                  (null byte-compile-current-form))
3936         `(push ',var current-load-list))
3937       (when (> (length form) 3)
3938         (when (and string (not (stringp string)))
3939           (byte-compile-warn "Third arg to %s %s is not a string: %s"
3940                              fun var string))
3941         `(put ',var 'variable-documentation ,string))
3942       (if (cdr (cdr form))              ; `value' provided
3943           (cond ((eq fun 'defconst)
3944                  ;; `defconst' sets `var' unconditionally.
3945                  `(setq ,var ,value))
3946                 ((eq fun 'defregexp)
3947                  ;; `defregexp' sets `var' unconditionally, too
3948                  `(setq ,var (compile-regexp ,value)))
3949                 (t
3950                  ;; `defvar' sets `var' only when unbound.
3951                  `(if (not (default-boundp ',var)) (set-default ',var ,value)))))
3952       `',var))))
3953
3954 (defun byte-compile-autoload (form)
3955   (and (byte-compile-constp (nth 1 form))
3956        (byte-compile-constp (nth 5 form))
3957        (memq (eval (nth 5 form)) '(t macro))  ; macro-p
3958        (not (fboundp (eval (nth 1 form))))
3959        (byte-compile-warn
3960         "The compiler ignores `autoload' except at top level.  You should
3961      probably put the autoload of the macro `%s' at top-level."
3962         (eval (nth 1 form))))
3963   (byte-compile-normal-call form))
3964
3965 ;; Lambda's in valid places are handled as special cases by various code.
3966 ;; The ones that remain are errors.
3967 ;; According to Mly this can go now that lambda is a macro
3968 ;(defun byte-compile-lambda-form (form)
3969 ;  (byte-compile-warn
3970 ;   "`lambda' used in function position is invalid: probably you mean #'%s"
3971 ;   (let ((print-escape-newlines t)
3972 ;        (print-level 4)
3973 ;        (print-length 4))
3974 ;     (prin1-to-string form)))
3975 ;  (byte-compile-normal-call
3976 ;   (list 'signal ''error
3977 ;        (list 'quote (list "`lambda' used in function position" form)))))
3978
3979 ;; Compile normally, but deal with warnings for the function being defined.
3980 (defun byte-compile-defalias (form)
3981   (if (and (consp (cdr form)) (consp (nth 1 form))
3982            (eq (car (nth 1 form)) 'quote)
3983            (consp (cdr (nth 1 form)))
3984            (symbolp (nth 1 (nth 1 form)))
3985            (consp (nthcdr 2 form))
3986            (consp (nth 2 form))
3987            (eq (car (nth 2 form)) 'quote)
3988            (consp (cdr (nth 2 form)))
3989            (symbolp (nth 1 (nth 2 form))))
3990       (progn
3991         (byte-compile-defalias-warn (nth 1 (nth 1 form))
3992                                     (nth 1 (nth 2 form)))
3993         (setq byte-compile-function-environment
3994               (cons (cons (nth 1 (nth 1 form))
3995                           (nth 1 (nth 2 form)))
3996                     byte-compile-function-environment))))
3997   (byte-compile-normal-call form))
3998
3999 (defun byte-compile-define-function (form)
4000   (byte-compile-defalias form))
4001
4002 ;; Turn off warnings about prior calls to the function being defalias'd.
4003 ;; This could be smarter and compare those calls with
4004 ;; the function it is being aliased to.
4005 (defun byte-compile-defalias-warn (new alias)
4006   (let ((calls (assq new byte-compile-unresolved-functions)))
4007     (if calls
4008         (setq byte-compile-unresolved-functions
4009               (delq calls byte-compile-unresolved-functions)))))
4010 \f
4011 ;;; tags
4012
4013 ;; Note: Most operations will strip off the 'TAG, but it speeds up
4014 ;; optimization to have the 'TAG as a part of the tag.
4015 ;; Tags will be (TAG . (tag-number . stack-depth)).
4016 (defun byte-compile-make-tag ()
4017   (list 'TAG (setq byte-compile-tag-number (1+ byte-compile-tag-number))))
4018
4019
4020 (defun byte-compile-out-tag (tag)
4021   (push tag byte-compile-output)
4022   (if (cdr (cdr tag))
4023       (progn
4024         ;; ## remove this someday
4025         (and byte-compile-depth
4026           (not (= (cdr (cdr tag)) byte-compile-depth))
4027           (error "Compiler bug: depth conflict at tag %d" (car (cdr tag))))
4028         (setq byte-compile-depth (cdr (cdr tag))))
4029     (setcdr (cdr tag) byte-compile-depth)))
4030
4031 (defun byte-compile-goto (opcode tag)
4032   (push (cons opcode tag) byte-compile-output)
4033   (setcdr (cdr tag) (if (memq opcode byte-goto-always-pop-ops)
4034                         (1- byte-compile-depth)
4035                       byte-compile-depth))
4036   (setq byte-compile-depth (and (not (eq opcode 'byte-goto))
4037                                 (1- byte-compile-depth))))
4038
4039 (defun byte-compile-out (opcode offset)
4040   (push (cons opcode offset) byte-compile-output)
4041   (case opcode
4042     (byte-call
4043      (setq byte-compile-depth (- byte-compile-depth offset)))
4044     (byte-return
4045      ;; This is actually an unnecessary case, because there should be
4046      ;; no more opcodes behind byte-return.
4047      (setq byte-compile-depth nil))
4048     (t
4049      (setq byte-compile-depth (+ byte-compile-depth
4050                                  (or (aref byte-stack+-info
4051                                            (symbol-value opcode))
4052                                      (- (1- offset))))
4053            byte-compile-maxdepth (max byte-compile-depth
4054                                       byte-compile-maxdepth))))
4055   ;;(if (< byte-compile-depth 0) (error "Compiler error: stack underflow"))
4056   )
4057
4058 \f
4059 ;;; call tree stuff
4060
4061 (defun byte-compile-annotate-call-tree (form)
4062   (let (entry)
4063     ;; annotate the current call
4064     (if (setq entry (assq (car form) byte-compile-call-tree))
4065         (or (memq byte-compile-current-form (nth 1 entry)) ;callers
4066             (setcar (cdr entry)
4067                     (cons byte-compile-current-form (nth 1 entry))))
4068       (push (list (car form) (list byte-compile-current-form) nil)
4069             byte-compile-call-tree))
4070     ;; annotate the current function
4071     (if (setq entry (assq byte-compile-current-form byte-compile-call-tree))
4072         (or (memq (car form) (nth 2 entry)) ;called
4073             (setcar (cdr (cdr entry))
4074                     (cons (car form) (nth 2 entry))))
4075       (push (list byte-compile-current-form nil (list (car form)))
4076             byte-compile-call-tree))))
4077
4078 ;; Renamed from byte-compile-report-call-tree
4079 ;; to avoid interfering with completion of byte-compile-file.
4080 ;;;###autoload
4081 (defun display-call-tree (&optional filename)
4082   "Display a call graph of a specified file.
4083 This lists which functions have been called, what functions called
4084 them, and what functions they call.  The list includes all functions
4085 whose definitions have been compiled in this Emacs session, as well as
4086 all functions called by those functions.
4087
4088 The call graph does not include macros, inline functions, or
4089 primitives that the byte-code interpreter knows about directly \(eq,
4090 cons, etc.\).
4091
4092 The call tree also lists those functions which are not known to be called
4093 \(that is, to which no calls have been compiled\), and which cannot be
4094 invoked interactively."
4095   (interactive)
4096   (message "Generating call tree...")
4097   (with-output-to-temp-buffer "*Call-Tree*"
4098     (set-buffer "*Call-Tree*")
4099     (erase-buffer)
4100     (message "Generating call tree... (sorting on %s)"
4101              byte-compile-call-tree-sort)
4102     (insert "Call tree for "
4103             (cond ((null byte-compile-current-file) (or filename "???"))
4104                   ((stringp byte-compile-current-file)
4105                    byte-compile-current-file)
4106                   (t (buffer-name byte-compile-current-file)))
4107             " sorted on "
4108             (prin1-to-string byte-compile-call-tree-sort)
4109             ":\n\n")
4110     (if byte-compile-call-tree-sort
4111         (setq byte-compile-call-tree
4112               (sort byte-compile-call-tree
4113                     (cond
4114                      ((eq byte-compile-call-tree-sort 'callers)
4115                       #'(lambda (x y) (< (length (nth 1 x))
4116                                          (length (nth 1 y)))))
4117                      ((eq byte-compile-call-tree-sort 'calls)
4118                       #'(lambda (x y) (< (length (nth 2 x))
4119                                          (length (nth 2 y)))))
4120                      ((eq byte-compile-call-tree-sort 'calls+callers)
4121                       #'(lambda (x y) (< (+ (length (nth 1 x))
4122                                             (length (nth 2 x)))
4123                                          (+ (length (nth 1 y))
4124                                             (length (nth 2 y))))))
4125                      ((eq byte-compile-call-tree-sort 'name)
4126                       #'(lambda (x y) (string< (car x)
4127                                                (car y))))
4128                      (t (error
4129                       "`byte-compile-call-tree-sort': `%s' - unknown sort mode"
4130                                byte-compile-call-tree-sort))))))
4131     (message "Generating call tree...")
4132     (let ((rest byte-compile-call-tree)
4133           (b (current-buffer))
4134           f p
4135           callers calls)
4136       (while rest
4137         (prin1 (car (car rest)) b)
4138         (setq callers (nth 1 (car rest))
4139               calls (nth 2 (car rest)))
4140         (insert "\t"
4141           (cond ((not (fboundp (setq f (car (car rest)))))
4142                  (if (null f)
4143                      " <top level>";; shouldn't insert nil then, actually -sk
4144                    " <not defined>"))
4145                 ((subrp (setq f (symbol-function f)))
4146                  " <subr>")
4147                 ((symbolp f)
4148                  (format " ==> %s" f))
4149                 ((compiled-function-p f)
4150                  "<compiled function>")
4151                 ((not (consp f))
4152                  "<malformed function>")
4153                 ((eq 'macro (car f))
4154                  (if (or (compiled-function-p (cdr f))
4155                          (assq 'byte-code (cdr (cdr (cdr f)))))
4156                      " <compiled macro>"
4157                    " <macro>"))
4158                 ((assq 'byte-code (cdr (cdr f)))
4159                  "<compiled lambda>")
4160                 ((eq 'lambda (car f))
4161                  "<function>")
4162                 (t "???"))
4163           (format " (%d callers + %d calls = %d)"
4164                   ;; Does the optimizer eliminate common subexpressions?-sk
4165                   (length callers)
4166                   (length calls)
4167                   (+ (length callers) (length calls)))
4168           "\n")
4169         (if callers
4170             (progn
4171               (insert "  called by:\n")
4172               (setq p (point))
4173               (insert "    " (if (car callers)
4174                                  (mapconcat 'symbol-name callers ", ")
4175                                "<top level>"))
4176               (let ((fill-prefix "    "))
4177                 (fill-region-as-paragraph p (point)))))
4178         (if calls
4179             (progn
4180               (insert "  calls:\n")
4181               (setq p (point))
4182               (insert "    " (mapconcat 'symbol-name calls ", "))
4183               (let ((fill-prefix "    "))
4184                 (fill-region-as-paragraph p (point)))))
4185         (insert "\n")
4186         (setq rest (cdr rest)))
4187
4188       (message "Generating call tree...(finding uncalled functions...)")
4189       (setq rest byte-compile-call-tree)
4190       (let ((uncalled nil))
4191         (while rest
4192           (or (nth 1 (car rest))
4193               (null (setq f (car (car rest))))
4194               (byte-compile-fdefinition f t)
4195               (commandp (byte-compile-fdefinition f nil))
4196               (setq uncalled (cons f uncalled)))
4197           (setq rest (cdr rest)))
4198         (if uncalled
4199             (let ((fill-prefix "  "))
4200               (insert "Noninteractive functions not known to be called:\n  ")
4201               (setq p (point))
4202               (insert (mapconcat 'symbol-name (nreverse uncalled) ", "))
4203               (fill-region-as-paragraph p (point)))))
4204       )
4205     (message "Generating call tree...done.")
4206     ))
4207
4208 \f
4209 ;;; by crl@newton.purdue.edu
4210 ;;;  Only works noninteractively.
4211 ;;;###autoload
4212 (defun batch-byte-compile ()
4213   "Run `byte-compile-file' on the files remaining on the command line.
4214 Use this from the command line, with `-batch';
4215 it won't work in an interactive Emacs.
4216 Each file is processed even if an error occurred previously.
4217 For example, invoke \"xemacs -batch -f batch-byte-compile $emacs/ ~/*.el\"."
4218   ;; command-line-args-left is what is left of the command line (from
4219   ;; startup.el)
4220   (defvar command-line-args-left)       ;Avoid 'free variable' warning
4221   (if (not noninteractive)
4222       (error "`batch-byte-compile' is to be used only with -batch"))
4223   (let ((error nil))
4224     (while command-line-args-left
4225       (if (null (batch-byte-compile-one-file))
4226           (setq error t)))
4227     (message "Done")
4228     (kill-emacs (if error 1 0))))
4229
4230 ;;;###autoload
4231 (defun batch-byte-compile-one-file ()
4232   "Run `byte-compile-file' on a single file remaining on the command line.
4233 Use this from the command line, with `-batch';
4234 it won't work in an interactive Emacs."
4235   ;; command-line-args-left is what is left of the command line (from
4236   ;; startup.el)
4237   (defvar command-line-args-left)       ;Avoid 'free variable' warning
4238   (if (not noninteractive)
4239       (error "`batch-byte-compile-one-file' is to be used only with -batch"))
4240   (let (error
4241         (file-to-process (car command-line-args-left)))
4242     (setq command-line-args-left (cdr command-line-args-left))
4243     (if (file-directory-p (expand-file-name file-to-process))
4244         (let ((files (directory-files file-to-process))
4245               source dest)
4246           (while files
4247             (if (and (string-match emacs-lisp-file-regexp (car files))
4248                      (not (auto-save-file-name-p (car files)))
4249                      (setq source (expand-file-name
4250                                    (car files)
4251                                    file-to-process))
4252                      (setq dest (byte-compile-dest-file source))
4253                      (file-exists-p dest)
4254                      (file-newer-than-file-p source dest))
4255                 (if (null (batch-byte-compile-1 source))
4256                     (setq error t)))
4257             (setq files (cdr files)))
4258           (null error))
4259       (batch-byte-compile-1 file-to-process))))
4260
4261 (defun batch-byte-compile-one-file-here ()
4262   "Run `byte-compile-file' on a single file remaining on the command line.
4263 Use this from the command line, with `-batch';
4264 it won't work in an interactive Emacs."
4265   ;; command-line-args-left is what is left of the command line (from
4266   ;; startup.el)
4267   (defvar command-line-args-left)       ;Avoid 'free variable' warning
4268   (if (not noninteractive)
4269       (error "`batch-byte-compile-one-file-here' is to be used only with -batch"))
4270   ;; we hard-redefine it, since we ought to be called in batch mode only
4271   (fset 'byte-compile-dest-file
4272         #'(lambda (filename)
4273             "Convert an Emacs Lisp source file name to a compiled file name."
4274             (let ((outfile
4275                    (file-name-sans-extension
4276                     (if (string-match "lisp/" filename)
4277                         (substring filename (match-end 0))
4278                       filename))))
4279               (expand-file-name (concat outfile ".elc") default-directory))))
4280   (batch-byte-compile-one-file))
4281
4282 (defun batch-byte-compile-1 (file)
4283   (condition-case err
4284       (progn (byte-compile-file file) t)
4285     (error
4286      (princ ">>Error occurred processing ")
4287      (princ file)
4288      (princ ": ")
4289      (if (fboundp 'display-error) ; XEmacs 19.8+
4290          (display-error err nil)
4291        (princ (or (get (car err) 'error-message) (car err)))
4292        (mapcar #'(lambda (x) (princ " ") (prin1 x)) (cdr err)))
4293      (princ "\n")
4294      nil)))
4295
4296 ;;;###autoload
4297 (defun batch-byte-recompile-directory-norecurse ()
4298   "Same as `batch-byte-recompile-directory' but without recursion."
4299   (setq byte-recompile-directory-recursively nil)
4300   (batch-byte-recompile-directory))
4301
4302 ;;;###autoload
4303 (defun batch-byte-recompile-directory ()
4304   "Runs `byte-recompile-directory' on the dirs remaining on the command line.
4305 Must be used only with `-batch', and kills Emacs on completion.
4306 For example, invoke `xemacs -batch -f batch-byte-recompile-directory .'."
4307   ;; command-line-args-left is what is left of the command line (startup.el)
4308   (defvar command-line-args-left)       ;Avoid 'free variable' warning
4309   (if (not noninteractive)
4310       (error "batch-byte-recompile-directory is to be used only with -batch"))
4311   (or command-line-args-left
4312       (setq command-line-args-left '(".")))
4313   (let ((byte-recompile-directory-ignore-errors-p t))
4314     (while command-line-args-left
4315       (byte-recompile-directory (car command-line-args-left))
4316       (setq command-line-args-left (cdr command-line-args-left))))
4317   (kill-emacs 0))
4318
4319 (make-obsolete 'elisp-compile-defun 'compile-defun)
4320 (make-obsolete 'byte-compile-report-call-tree 'display-call-tree)
4321
4322 ;; other make-obsolete calls in obsolete.el.
4323
4324 (provide 'byte-compile)
4325 (provide 'bytecomp)
4326
4327 \f
4328 ;;; report metering (see the hacks in bytecode.c)
4329
4330 (if (boundp 'byte-code-meter)
4331     (defun byte-compile-report-ops ()
4332       (defvar byte-code-meter)
4333       (with-output-to-temp-buffer "*Meter*"
4334         (set-buffer "*Meter*")
4335         (let ((i 0) n op off)
4336           (while (< i 256)
4337             (setq n (aref (aref byte-code-meter 0) i)
4338                   off nil)
4339             (if t ;(not (zerop n))
4340                 (progn
4341                   (setq op i)
4342                   (setq off nil)
4343                   (cond ((< op byte-nth)
4344                          (setq off (logand op 7))
4345                          (setq op (logand op 248)))
4346                         ((>= op byte-constant)
4347                          (setq off (- op byte-constant)
4348                                op byte-constant)))
4349                   (setq op (aref byte-code-vector op))
4350                   (insert (format "%-4d" i))
4351                   (insert (symbol-name op))
4352                   (if off (insert " [" (int-to-string off) "]"))
4353                   (indent-to 40)
4354                   (insert (int-to-string n) "\n")))
4355             (setq i (1+ i)))))))
4356
4357 \f
4358 ;; To avoid "lisp nesting exceeds max-lisp-eval-depth" when bytecomp compiles
4359 ;; itself, compile some of its most used recursive functions (at load time).
4360 ;;
4361 (eval-when-compile
4362  (or (compiled-function-p (symbol-function 'byte-compile-form))
4363      (assq 'byte-code (symbol-function 'byte-compile-form))
4364      (let ((byte-optimize nil) ; do it fast
4365            (byte-compile-warnings nil))
4366        (mapcar #'(lambda (x)
4367                    (or noninteractive (message "compiling %s..." x))
4368                    (byte-compile x)
4369                    (or noninteractive (message "compiling %s...done" x)))
4370                '(byte-compile-normal-call
4371                  byte-compile-form
4372                  byte-compile-body
4373                  ;; Inserted some more than necessary, to speed it up.
4374                  byte-compile-top-level
4375                  byte-compile-out-toplevel
4376                  byte-compile-constant
4377                  byte-compile-variable-ref))))
4378  nil)
4379
4380 ;;; bytecomp.el ends here