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