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