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