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