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