XEmacs 21.2.36 "Notos"
[chise/xemacs-chise.git.1] / lisp / bytecomp.el
1 ;;; bytecomp.el --- compilation of Lisp code into byte code.
2
3 ;;; Copyright (C) 1985-1987, 1991-1994 Free Software Foundation, Inc.
4 ;;; Copyright (C) 1996 Ben Wing.
5
6 ;; 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 `raw-text' for maximum portability with non-Mule
1757   ;; Emacsen.
1758   (when (featurep '(or mule file-coding))
1759     (defvar buffer-file-coding-system)
1760     (if (or (featurep '(not mule)) ;; Don't scan buffer if we are not muleized
1761             (save-excursion
1762               (set-buffer byte-compile-inbuffer)
1763               (goto-char (point-min))
1764               ;; mrb- There must be a better way than skip-chars-forward
1765               (skip-chars-forward (concat (char-to-string 0) "-"
1766                                           (char-to-string 255)))
1767               (eq (point) (point-max))))
1768         (setq buffer-file-coding-system 'raw-text-unix)
1769       (insert "(require 'mule)\n;;;###coding system: escape-quoted\n")
1770       (setq buffer-file-coding-system 'escape-quoted)
1771       ;; #### Lazy loading not yet implemented for MULE files
1772       ;; mrb - Fix this someday.
1773       (save-excursion
1774         (set-buffer byte-compile-inbuffer)
1775         (setq byte-compile-dynamic nil
1776               byte-compile-dynamic-docstrings nil))
1777       ;;(external-debugging-output (prin1-to-string (buffer-local-variables))))
1778       ))
1779   )
1780
1781
1782 (defun byte-compile-output-file-form (form)
1783   ;; writes the given form to the output buffer, being careful of docstrings
1784   ;; in defun, defmacro, defvar, defconst and autoload because make-docfile is
1785   ;; so amazingly stupid.
1786   ;; defalias calls are output directly by byte-compile-file-form-defmumble;
1787   ;; it does not pay to first build the defalias in defmumble and then parse
1788   ;; it here.
1789   (if (and (memq (car-safe form) '(defun defmacro defvar defconst autoload))
1790            (stringp (nth 3 form)))
1791       (byte-compile-output-docform nil nil '("\n(" 3 ")") form nil
1792                                    (eq (car form) 'autoload))
1793     (let ((print-escape-newlines t)
1794           (print-length nil)
1795           (print-level nil)
1796           (print-readably t)    ; print #[] for bytecode, 'x for (quote x)
1797           (print-gensym (if (and byte-compile-print-gensym
1798                                  (not byte-compile-emacs19-compatibility))
1799                             t nil)))
1800       (princ "\n" byte-compile-outbuffer)
1801       (prin1 form byte-compile-outbuffer)
1802       nil)))
1803
1804 (defun byte-compile-output-docform (preface name info form specindex quoted)
1805   "Print a form with a doc string.  INFO is (prefix doc-index postfix).
1806 If PREFACE and NAME are non-nil, print them too,
1807 before INFO and the FORM but after the doc string itself.
1808 If SPECINDEX is non-nil, it is the index in FORM
1809 of the function bytecode string.  In that case,
1810 we output that argument and the following argument (the constants vector)
1811 together, for lazy loading.
1812 QUOTED says that we have to put a quote before the
1813 list that represents a doc string reference.
1814 `autoload' needs that."
1815   ;; We need to examine byte-compile-dynamic-docstrings
1816   ;; in the input buffer (now current), not in the output buffer.
1817   (let ((dynamic-docstrings byte-compile-dynamic-docstrings))
1818     (set-buffer
1819      (prog1 (current-buffer)
1820        (set-buffer byte-compile-outbuffer)
1821        (let (position)
1822
1823          ;; Insert the doc string, and make it a comment with #@LENGTH.
1824          (and (>= (nth 1 info) 0)
1825               dynamic-docstrings
1826               (progn
1827                 ;; Make the doc string start at beginning of line
1828                 ;; for make-docfile's sake.
1829                 (insert "\n")
1830                 (setq position
1831                       (byte-compile-output-as-comment
1832                        (nth (nth 1 info) form) nil))
1833                 ;; If the doc string starts with * (a user variable),
1834                 ;; negate POSITION.
1835                 (if (and (stringp (nth (nth 1 info) form))
1836                          (> (length (nth (nth 1 info) form)) 0)
1837                          (char= (aref (nth (nth 1 info) form) 0) ?*))
1838                     (setq position (- position)))))
1839
1840          (if preface
1841              (progn
1842                (insert preface)
1843                (prin1 name byte-compile-outbuffer)))
1844          (insert (car info))
1845          (let ((print-escape-newlines t)
1846                (print-readably t)       ; print #[] for bytecode, 'x for (quote x)
1847                ;; Use a cons cell to say that we want
1848                ;; print-gensym-alist not to be cleared between calls
1849                ;; to print functions.
1850                (print-gensym (if (and byte-compile-print-gensym
1851                                       (not byte-compile-emacs19-compatibility))
1852                                  '(t) nil))
1853                print-gensym-alist
1854                (index 0))
1855            (prin1 (car form) byte-compile-outbuffer)
1856            (while (setq form (cdr form))
1857              (setq index (1+ index))
1858              (insert " ")
1859              (cond ((and (numberp specindex) (= index specindex))
1860                     (let ((position
1861                            (byte-compile-output-as-comment
1862                             (cons (car form) (nth 1 form))
1863                             t)))
1864                       (princ (format "(#$ . %d) nil" position)
1865                              byte-compile-outbuffer)
1866                       (setq form (cdr form))
1867                       (setq index (1+ index))))
1868                    ((= index (nth 1 info))
1869                     (if position
1870                         (princ (format (if quoted "'(#$ . %d)"  "(#$ . %d)")
1871                                        position)
1872                                byte-compile-outbuffer)
1873                       (let ((print-escape-newlines nil))
1874                         (goto-char (prog1 (1+ (point))
1875                                      (prin1 (car form)
1876                                             byte-compile-outbuffer)))
1877                         (insert "\\\n")
1878                         (goto-char (point-max)))))
1879                    (t
1880                     (prin1 (car form) byte-compile-outbuffer)))))
1881          (insert (nth 2 info))))))
1882   nil)
1883
1884 (defvar for-effect) ; ## Kludge!  This should be an arg, not a special.
1885
1886 (defun byte-compile-keep-pending (form &optional handler)
1887   (if (memq byte-optimize '(t source))
1888       (setq form (byte-optimize-form form t)))
1889   (if handler
1890       (let ((for-effect t))
1891         ;; To avoid consing up monstrously large forms at load time, we split
1892         ;; the output regularly.
1893         (and (memq (car-safe form) '(fset defalias define-function))
1894              (nthcdr 300 byte-compile-output)
1895              (byte-compile-flush-pending))
1896         (funcall handler form)
1897         (when for-effect
1898           (byte-compile-discard)))
1899     (byte-compile-form form t))
1900   nil)
1901
1902 (defun byte-compile-flush-pending ()
1903   (if byte-compile-output
1904       (let ((form (byte-compile-out-toplevel t 'file)))
1905         (cond ((eq (car-safe form) 'progn)
1906                (mapcar 'byte-compile-output-file-form (cdr form)))
1907               (form
1908                (byte-compile-output-file-form form)))
1909         (setq byte-compile-constants nil
1910               byte-compile-variables nil
1911               byte-compile-depth 0
1912               byte-compile-maxdepth 0
1913               byte-compile-output nil))))
1914
1915 (defun byte-compile-file-form (form)
1916   (let ((byte-compile-current-form nil) ; close over this for warnings.
1917         handler)
1918     (cond
1919      ((not (consp form))
1920       (byte-compile-keep-pending form))
1921      ((and (symbolp (car form))
1922            (setq handler (get (car form) 'byte-hunk-handler)))
1923       (cond ((setq form (funcall handler form))
1924              (byte-compile-flush-pending)
1925              (byte-compile-output-file-form form))))
1926      ((eq form (setq form (macroexpand form byte-compile-macro-environment)))
1927       (byte-compile-keep-pending form))
1928      (t
1929       (byte-compile-file-form form)))))
1930
1931 ;; Functions and variables with doc strings must be output separately,
1932 ;; so make-docfile can recognize them.  Most other things can be output
1933 ;; as byte-code.
1934
1935 (put 'defsubst 'byte-hunk-handler 'byte-compile-file-form-defsubst)
1936 (defun byte-compile-file-form-defsubst (form)
1937   (cond ((assq (nth 1 form) byte-compile-unresolved-functions)
1938          (setq byte-compile-current-form (nth 1 form))
1939          (byte-compile-warn "defsubst %s was used before it was defined"
1940                             (nth 1 form))))
1941   (byte-compile-file-form
1942    (macroexpand form byte-compile-macro-environment))
1943   ;; Return nil so the form is not output twice.
1944   nil)
1945
1946 (put 'autoload 'byte-hunk-handler 'byte-compile-file-form-autoload)
1947 (defun byte-compile-file-form-autoload (form)
1948   ;;
1949   ;; If this is an autoload of a macro, and all arguments are constants (that
1950   ;; is, there is no hairy computation going on here) then evaluate the form
1951   ;; at compile-time.  This is so that we can make use of macros which we
1952   ;; have autoloaded from the file being compiled.  Normal function autoloads
1953   ;; are not automatically evaluated at compile time, because there's not
1954   ;; much point to it (so why bother cluttering up the compile-time namespace.)
1955   ;;
1956   ;; If this is an autoload of a function, then record its definition in the
1957   ;; byte-compile-autoload-environment to suppress any `not known to be
1958   ;; defined' warnings at the end of this file (this only matters for
1959   ;; functions which are autoloaded and compiled in the same file, if the
1960   ;; autoload already exists in the compilation environment, we wouldn't have
1961   ;; warned anyway.)
1962   ;;
1963   (let* ((name (if (byte-compile-constp (nth 1 form))
1964                    (eval (nth 1 form))))
1965          ;; In v19, the 5th arg to autoload can be t, nil, 'macro, or 'keymap.
1966          (macrop (and (byte-compile-constp (nth 5 form))
1967                       (memq (eval (nth 5 form)) '(t macro))))
1968 ;;       (functionp (and (byte-compile-constp (nth 5 form))
1969 ;;                       (eq 'nil (eval (nth 5 form)))))
1970          )
1971     (if (and macrop
1972              (let ((form form))
1973                ;; all forms are constant
1974                (while (if (setq form (cdr form))
1975                           (byte-compile-constp (car form))))
1976                (null form)))
1977         ;; eval the macro autoload into the compilation environment
1978         (eval form))
1979
1980     (if name
1981         (let ((old (assq name byte-compile-autoload-environment)))
1982           (cond (old
1983                  (if (memq 'redefine byte-compile-warnings)
1984                      (byte-compile-warn "multiple autoloads for %s" name))
1985                  (setcdr old form))
1986                 (t
1987                  ;; We only use the names in the autoload environment, but
1988                  ;; it might be useful to have the bodies some day.
1989                  (setq byte-compile-autoload-environment
1990                        (cons (cons name form)
1991                              byte-compile-autoload-environment)))))))
1992   ;;
1993   ;; Now output the form.
1994   (if (stringp (nth 3 form))
1995       form
1996     ;; No doc string, so we can compile this as a normal form.
1997     (byte-compile-keep-pending form 'byte-compile-normal-call)))
1998
1999 (put 'defvar   'byte-hunk-handler 'byte-compile-file-form-defvar-or-defconst)
2000 (put 'defconst 'byte-hunk-handler 'byte-compile-file-form-defvar-or-defconst)
2001 (defun byte-compile-file-form-defvar-or-defconst (form)
2002   ;; (defvar|defconst VAR [VALUE [DOCSTRING]])
2003   (if (> (length form) 4)
2004       (byte-compile-warn
2005        "%s %s called with %d arguments, but accepts only %s"
2006        (car form) (nth 1 form) (length (cdr form)) 3))
2007   (if (and (> (length form) 3) (not (stringp (nth 3 form))))
2008       (byte-compile-warn "Third arg to %s %s is not a string: %s"
2009                          (car form) (nth 1 form) (nth 3 form)))
2010   (if (null (nth 3 form))
2011       ;; Since there is no doc string, we can compile this as a normal form,
2012       ;; and not do a file-boundary.
2013       (byte-compile-keep-pending form)
2014     (if (memq 'free-vars byte-compile-warnings)
2015         (setq byte-compile-bound-variables
2016               (cons (cons (nth 1 form) byte-compile-global-bit)
2017                     byte-compile-bound-variables)))
2018     (cond ((consp (nth 2 form))
2019            (setq form (copy-sequence form))
2020            (setcar (cdr (cdr form))
2021                    (byte-compile-top-level (nth 2 form) nil 'file))))
2022
2023     ;; The following turns out not to be necessary, since we emit a call to
2024     ;; defvar, which can hack Vfile_domain by itself!
2025     ;;
2026     ;; If a file domain has been set, emit (put 'VAR 'variable-domain ...)
2027     ;; after this defvar.
2028 ;    (if byte-compile-file-domain
2029 ;       (progn
2030 ;         ;; Actually, this will emit the (put ...) before the (defvar ...)
2031 ;         ;; but I don't think that can matter in this case.
2032 ;         (byte-compile-keep-pending
2033 ;          (list 'put (list 'quote (nth 1 form)) ''variable-domain
2034 ;               (list 'quote byte-compile-file-domain)))))
2035     form))
2036
2037 (put 'require 'byte-hunk-handler 'byte-compile-file-form-eval-boundary)
2038 (defun byte-compile-file-form-eval-boundary (form)
2039   (eval form)
2040   (byte-compile-keep-pending form 'byte-compile-normal-call))
2041
2042 (put 'progn 'byte-hunk-handler 'byte-compile-file-form-progn)
2043 (put 'prog1 'byte-hunk-handler 'byte-compile-file-form-progn)
2044 (put 'prog2 'byte-hunk-handler 'byte-compile-file-form-progn)
2045 (defun byte-compile-file-form-progn (form)
2046   (mapcar 'byte-compile-file-form (cdr form))
2047   ;; Return nil so the forms are not output twice.
2048   nil)
2049
2050 ;; This handler is not necessary, but it makes the output from dont-compile
2051 ;; and similar macros cleaner.
2052 (put 'eval 'byte-hunk-handler 'byte-compile-file-form-eval)
2053 (defun byte-compile-file-form-eval (form)
2054   (if (eq (car-safe (nth 1 form)) 'quote)
2055       (nth 1 (nth 1 form))
2056     (byte-compile-keep-pending form)))
2057
2058 (put 'defun 'byte-hunk-handler 'byte-compile-file-form-defun)
2059 (defun byte-compile-file-form-defun (form)
2060   (byte-compile-file-form-defmumble form nil))
2061
2062 (put 'defmacro 'byte-hunk-handler 'byte-compile-file-form-defmacro)
2063 (defun byte-compile-file-form-defmacro (form)
2064   (byte-compile-file-form-defmumble form t))
2065
2066 (defun byte-compile-compiled-obj-to-list (obj)
2067   ;; #### this is fairly disgusting.  Rewrite the code instead
2068   ;; so that it doesn't create compiled objects in the first place!
2069   ;; Much better than creating them and then "uncreating" them
2070   ;; like this.
2071   (read (concat "("
2072                 (substring (let ((print-readably t)
2073                                  (print-gensym
2074                                   (if (and byte-compile-print-gensym
2075                                            (not byte-compile-emacs19-compatibility))
2076                                       '(t) nil))
2077                                  (print-gensym-alist nil))
2078                              (prin1-to-string obj))
2079                            2 -1)
2080                 ")")))
2081
2082 (defun byte-compile-file-form-defmumble (form macrop)
2083   (let* ((name (car (cdr form)))
2084          (this-kind (if macrop 'byte-compile-macro-environment
2085                       'byte-compile-function-environment))
2086          (that-kind (if macrop 'byte-compile-function-environment
2087                       'byte-compile-macro-environment))
2088          (this-one (assq name (symbol-value this-kind)))
2089          (that-one (assq name (symbol-value that-kind)))
2090          (byte-compile-free-references nil)
2091          (byte-compile-free-assignments nil))
2092
2093     ;; When a function or macro is defined, add it to the call tree so that
2094     ;; we can tell when functions are not used.
2095     (if byte-compile-generate-call-tree
2096         (or (assq name byte-compile-call-tree)
2097             (setq byte-compile-call-tree
2098                   (cons (list name nil nil) byte-compile-call-tree))))
2099
2100     (setq byte-compile-current-form name) ; for warnings
2101     (when (memq 'redefine byte-compile-warnings)
2102       (byte-compile-arglist-warn form macrop))
2103     (defvar filename) ; #### filename used free
2104     (when byte-compile-verbose
2105       (message "Compiling %s... (%s)"
2106                (if filename (file-name-nondirectory filename) "")
2107                (nth 1 form)))
2108     (cond (that-one
2109            (when (and (memq 'redefine byte-compile-warnings)
2110                       ;; hack hack: don't warn when compiling the stubs in
2111                       ;; bytecomp-runtime...
2112                       (not (assq (nth 1 form)
2113                                  byte-compile-initial-macro-environment)))
2114              (byte-compile-warn
2115               "%s defined multiple times, as both function and macro"
2116               (nth 1 form)))
2117            (setcdr that-one nil))
2118           (this-one
2119            (when (and (memq 'redefine byte-compile-warnings)
2120                       ;; hack: don't warn when compiling the magic internal
2121                       ;; byte-compiler macros in bytecomp-runtime.el...
2122                       (not (assq (nth 1 form)
2123                                  byte-compile-initial-macro-environment)))
2124              (byte-compile-warn "%s %s defined multiple times in this file"
2125                                 (if macrop "macro" "function")
2126                                 (nth 1 form))))
2127           ((and (fboundp name)
2128                 (or (subrp (symbol-function name))
2129                     (eq (car-safe (symbol-function name))
2130                         (if macrop 'lambda 'macro))))
2131            (if (memq 'redefine byte-compile-warnings)
2132                (byte-compile-warn "%s %s being redefined as a %s"
2133                                   (if (subrp (symbol-function name))
2134                                       "subr"
2135                                     (if macrop "function" "macro"))
2136                                   (nth 1 form)
2137                                   (if macrop "macro" "function")))
2138            ;; shadow existing definition
2139            (set this-kind
2140                 (cons (cons name nil) (symbol-value this-kind)))))
2141     (let ((body (nthcdr 3 form)))
2142       (if (and (stringp (car body))
2143                (symbolp (car-safe (cdr-safe body)))
2144                (car-safe (cdr-safe body))
2145                (stringp (car-safe (cdr-safe (cdr-safe body)))))
2146           (byte-compile-warn "Probable `\"' without `\\' in doc string of %s"
2147                              (nth 1 form))))
2148     (let* ((new-one (byte-compile-lambda (cons 'lambda (nthcdr 2 form))))
2149            (code (byte-compile-byte-code-maker new-one)))
2150       (if this-one
2151           (setcdr this-one new-one)
2152         (set this-kind
2153              (cons (cons name new-one) (symbol-value this-kind))))
2154       (if (and (stringp (nth 3 form))
2155                (eq 'quote (car-safe code))
2156                (eq 'lambda (car-safe (nth 1 code))))
2157           (cons (car form)
2158                 (cons name (cdr (nth 1 code))))
2159         (byte-compile-flush-pending)
2160         (if (not (stringp (nth 3 form)))
2161             ;; No doc string.  Provide -1 as the "doc string index"
2162             ;; so that no element will be treated as a doc string.
2163             (byte-compile-output-docform
2164              "\n(defalias '"
2165              name
2166              (cond ((atom code)
2167                     (if macrop '(" '(macro . #[" -1 "])") '(" #[" -1 "]")))
2168                    ((eq (car code) 'quote)
2169                     (setq code new-one)
2170                     (if macrop '(" '(macro " -1 ")") '(" '(" -1 ")")))
2171                    ((if macrop '(" (cons 'macro (" -1 "))") '(" (" -1 ")"))))
2172              ;; FSF just calls `(append code nil)' here but that relies
2173              ;; on horrible C kludges in concat() that accept byte-
2174              ;; compiled objects and pretend they're vectors.
2175              (if (compiled-function-p code)
2176                  (byte-compile-compiled-obj-to-list code)
2177                (append code nil))
2178              (and (atom code) byte-compile-dynamic
2179                   1)
2180              nil)
2181           ;; Output the form by hand, that's much simpler than having
2182           ;; b-c-output-file-form analyze the defalias.
2183           (byte-compile-output-docform
2184            "\n(defalias '"
2185            name
2186            (cond ((atom code) ; compiled-function-p
2187                   (if macrop '(" '(macro . #[" 4 "])") '(" #[" 4 "]")))
2188                  ((eq (car code) 'quote)
2189                   (setq code new-one)
2190                   (if macrop '(" '(macro " 2 ")") '(" '(" 2 ")")))
2191                  ((if macrop '(" (cons 'macro (" 5 "))") '(" (" 5 ")"))))
2192            ;; The result of byte-compile-byte-code-maker is either a
2193            ;; compiled-function object, or a list of some kind.  If it's
2194            ;; not a cons, we must coerce it into a list of the elements
2195            ;; to be printed to the file.
2196            (if (consp code)
2197                code
2198              (nconc (list
2199                      (compiled-function-arglist code)
2200                      (compiled-function-instructions code)
2201                      (compiled-function-constants code)
2202                      (compiled-function-stack-depth code))
2203                     (let ((doc (documentation code t)))
2204                       (if doc (list doc)))
2205                     (if (commandp code)
2206                         (list (nth 1 (compiled-function-interactive code))))))
2207            (and (atom code) byte-compile-dynamic
2208                 1)
2209            nil))
2210         (princ ")" byte-compile-outbuffer)
2211         nil))))
2212
2213 ;; Print Lisp object EXP in the output file, inside a comment,
2214 ;; and return the file position it will have.
2215 ;; If QUOTED is non-nil, print with quoting; otherwise, print without quoting.
2216 (defun byte-compile-output-as-comment (exp quoted)
2217   (let ((position (point)))
2218     (set-buffer
2219      (prog1 (current-buffer)
2220        (set-buffer byte-compile-outbuffer)
2221
2222        ;; Insert EXP, and make it a comment with #@LENGTH.
2223        (insert " ")
2224        (if quoted
2225            (prin1 exp byte-compile-outbuffer)
2226          (princ exp byte-compile-outbuffer))
2227        (goto-char position)
2228        ;; Quote certain special characters as needed.
2229        ;; get_doc_string in doc.c does the unquoting.
2230        (while (search-forward "\^A" nil t)
2231          (replace-match "\^A\^A" t t))
2232        (goto-char position)
2233        (while (search-forward "\000" nil t)
2234          (replace-match "\^A0" t t))
2235        (goto-char position)
2236        (while (search-forward "\037" nil t)
2237          (replace-match "\^A_" t t))
2238        (goto-char (point-max))
2239        (insert "\037")
2240        (goto-char position)
2241        (insert "#@" (format "%d" (- (point-max) position)))
2242
2243        ;; Save the file position of the object.
2244        ;; Note we should add 1 to skip the space
2245        ;; that we inserted before the actual doc string,
2246        ;; and subtract 1 to convert from an 1-origin Emacs position
2247        ;; to a file position; they cancel.
2248        (setq position (point))
2249        (goto-char (point-max))))
2250     position))
2251
2252 \f
2253
2254 ;; The `domain' declaration.  This is legal only at top-level in a file, and
2255 ;; should generally be the first form in the file.  It is not legal inside
2256 ;; function bodies.
2257
2258 (put 'domain 'byte-hunk-handler 'byte-compile-file-form-domain)
2259 (defun byte-compile-file-form-domain (form)
2260   (if (not (null (cdr (cdr form))))
2261       (byte-compile-warn "domain used with too many arguments: %s" form))
2262   (let ((domain (nth 1 form)))
2263     (or (null domain)
2264         (stringp domain)
2265         (progn
2266           (byte-compile-warn
2267            "argument to `domain' declaration must be a literal string: %s"
2268            form)
2269           (setq domain nil)))
2270     (setq byte-compile-file-domain domain))
2271   (byte-compile-keep-pending form 'byte-compile-normal-call))
2272
2273 (defun byte-compile-domain (form)
2274   (byte-compile-warn "The `domain' declaration is legal only at top-level: %s"
2275                      (let ((print-escape-newlines t)
2276                            (print-level 4)
2277                            (print-length 4))
2278                        (prin1-to-string form)))
2279   (byte-compile-normal-call
2280    (list 'signal ''error
2281          (list 'quote (list "`domain' used inside a function" form)))))
2282
2283 ;; This is part of bytecomp.el in 19.35:
2284 (put 'custom-declare-variable 'byte-hunk-handler
2285      'byte-compile-file-form-custom-declare-variable)
2286 (defun byte-compile-file-form-custom-declare-variable (form)
2287   (if (memq 'free-vars byte-compile-warnings)
2288       (setq byte-compile-bound-variables
2289             (cons (cons (nth 1 (nth 1 form))
2290                         byte-compile-global-bit)
2291                   byte-compile-bound-variables)))
2292   form)
2293
2294 \f
2295 ;;;###autoload
2296 (defun byte-compile (form)
2297   "If FORM is a symbol, byte-compile its function definition.
2298 If FORM is a lambda or a macro, byte-compile it as a function."
2299   (displaying-byte-compile-warnings
2300    (byte-compile-close-variables
2301     (let* ((fun (if (symbolp form)
2302                     (and (fboundp form) (symbol-function form))
2303                   form))
2304            (macro (eq (car-safe fun) 'macro)))
2305       (if macro
2306           (setq fun (cdr fun)))
2307       (cond ((eq (car-safe fun) 'lambda)
2308              (setq fun (if macro
2309                            (cons 'macro (byte-compile-lambda fun))
2310                          (byte-compile-lambda fun)))
2311              (if (symbolp form)
2312                  (defalias form fun)
2313                fun)))))))
2314
2315 ;;;###autoload
2316 (defun byte-compile-sexp (sexp &optional msg)
2317   "Compile and return SEXP."
2318   (displaying-byte-compile-warnings
2319    (byte-compile-close-variables
2320     (prog1
2321         (byte-compile-top-level sexp)
2322       (byte-compile-warn-about-unresolved-functions msg)))))
2323
2324 ;; Given a function made by byte-compile-lambda, make a form which produces it.
2325 (defun byte-compile-byte-code-maker (fun)
2326   (cond
2327    ;; ## atom is faster than compiled-func-p.
2328    ((atom fun)                          ; compiled-function-p
2329     fun)
2330    ;; b-c-lambda didn't produce a compiled-function, so it must be a trivial
2331    ;; function.
2332    ((let (tmp)
2333       (if (and (setq tmp (assq 'byte-code (cdr-safe (cdr fun))))
2334                (null (cdr (memq tmp fun))))
2335           ;; Generate a make-byte-code call.
2336           (let* ((interactive (assq 'interactive (cdr (cdr fun)))))
2337             (nconc (list 'make-byte-code
2338                          (list 'quote (nth 1 fun)) ;arglist
2339                          (nth 1 tmp)    ;instructions
2340                          (nth 2 tmp)    ;constants
2341                          (nth 3 tmp))   ;stack-depth
2342                    (cond ((stringp (nth 2 fun))
2343                           (list (nth 2 fun))) ;docstring
2344                          (interactive
2345                           (list nil)))
2346                    (cond (interactive
2347                           (list (if (or (null (nth 1 interactive))
2348                                         (stringp (nth 1 interactive)))
2349                                     (nth 1 interactive)
2350                                   ;; Interactive spec is a list or a variable
2351                                   ;; (if it is correct).
2352                                   (list 'quote (nth 1 interactive))))))))
2353         ;; a non-compiled function (probably trivial)
2354         (list 'quote fun))))))
2355
2356 ;; Byte-compile a lambda-expression and return a valid function.
2357 ;; The value is usually a compiled function but may be the original
2358 ;; lambda-expression.
2359 (defun byte-compile-lambda (fun)
2360   (or (eq 'lambda (car-safe fun))
2361       (error "not a lambda -- %s" (prin1-to-string fun)))
2362   (let* ((arglist (nth 1 fun))
2363          (byte-compile-bound-variables
2364           (let ((new-bindings
2365                  (mapcar #'(lambda (x) (cons x byte-compile-arglist-bit))
2366                          (and (memq 'free-vars byte-compile-warnings)
2367                               (delq '&rest (delq '&optional
2368                                                  (copy-sequence arglist)))))))
2369             (nconc new-bindings
2370                    (cons 'new-scope byte-compile-bound-variables))))
2371          (body (cdr (cdr fun)))
2372          (doc (if (stringp (car body))
2373                   (prog1 (car body)
2374                     (setq body (cdr body)))))
2375          (int (assq 'interactive body)))
2376     (dolist (arg arglist)
2377       (cond ((not (symbolp arg))
2378              (byte-compile-warn "non-symbol in arglist: %S" arg))
2379             ((byte-compile-constant-symbol-p arg)
2380              (byte-compile-warn "constant symbol in arglist: %s" arg))
2381             ((and (char= ?\& (aref (symbol-name arg) 0))
2382                   (not (eq arg '&optional))
2383                   (not (eq arg '&rest)))
2384              (byte-compile-warn "unrecognized `&' keyword in arglist: %s"
2385                                 arg))))
2386     (cond (int
2387            ;; Skip (interactive) if it is in front (the most usual location).
2388            (if (eq int (car body))
2389                (setq body (cdr body)))
2390            (cond ((consp (cdr int))
2391                   (if (cdr (cdr int))
2392                       (byte-compile-warn "malformed interactive spec: %s"
2393                                          (prin1-to-string int)))
2394                   ;; If the interactive spec is a call to `list',
2395                   ;; don't compile it, because `call-interactively'
2396                   ;; looks at the args of `list'.
2397                   (let ((form (nth 1 int)))
2398                     (while (or (eq (car-safe form) 'let)
2399                                (eq (car-safe form) 'let*)
2400                                (eq (car-safe form) 'save-excursion))
2401                       (while (consp (cdr form))
2402                         (setq form (cdr form)))
2403                       (setq form (car form)))
2404                     (or (eq (car-safe form) 'list)
2405                         (setq int (list 'interactive
2406                                         (byte-compile-top-level (nth 1 int)))))))
2407                  ((cdr int)
2408                   (byte-compile-warn "malformed interactive spec: %s"
2409                                      (prin1-to-string int))))))
2410     (let ((compiled (byte-compile-top-level (cons 'progn body) nil 'lambda)))
2411       (if (memq 'unused-vars byte-compile-warnings)
2412           ;; done compiling in this scope, warn now.
2413           (byte-compile-warn-about-unused-variables))
2414       (if (eq 'byte-code (car-safe compiled))
2415           (apply 'make-byte-code
2416                  (append (list arglist)
2417                          ;; byte-string, constants-vector, stack depth
2418                          (cdr compiled)
2419                          ;; optionally, the doc string.
2420                          (if (or doc int)
2421                              (list doc))
2422                          ;; optionally, the interactive spec.
2423                          (if int
2424                              (list (nth 1 int)))))
2425         (setq compiled
2426               (nconc (if int (list int))
2427                      (cond ((eq (car-safe compiled) 'progn) (cdr compiled))
2428                            (compiled (list compiled)))))
2429         (nconc (list 'lambda arglist)
2430                (if (or doc (stringp (car compiled)))
2431                    (cons doc (cond (compiled)
2432                                    (body (list nil))))
2433                  compiled))))))
2434
2435 (defun byte-compile-constants-vector ()
2436   ;; Builds the constants-vector from the current variables and constants.
2437   ;;   This modifies the constants from (const . nil) to (const . offset).
2438   ;; To keep the byte-codes to look up the vector as short as possible:
2439   ;;   First 6 elements are vars, as there are one-byte varref codes for those.
2440   ;;   Next up to byte-constant-limit are constants, still with one-byte codes.
2441   ;;   Next variables again, to get 2-byte codes for variable lookup.
2442   ;;   The rest of the constants and variables need 3-byte byte-codes.
2443   (let* ((i -1)
2444          (rest (nreverse byte-compile-variables)) ; nreverse because the first
2445          (other (nreverse byte-compile-constants)) ; vars often are used most.
2446          ret tmp
2447          (limits '(5                    ; Use the 1-byte varref codes,
2448                    63  ; 1-constlim     ;  1-byte byte-constant codes,
2449                    255                  ;  2-byte varref codes,
2450                    65535))              ;  3-byte codes for the rest.
2451          limit)
2452     (while (or rest other)
2453       (setq limit (car limits))
2454       (while (and rest (not (eq i limit)))
2455         (if (setq tmp (assq (car (car rest)) ret))
2456             (setcdr (car rest) (cdr tmp))
2457           (setcdr (car rest) (setq i (1+ i)))
2458           (setq ret (cons (car rest) ret)))
2459         (setq rest (cdr rest)))
2460       (setq limits (cdr limits)
2461             rest (prog1 other
2462                    (setq other rest))))
2463     (apply 'vector (nreverse (mapcar 'car ret)))))
2464
2465 ;; Given an expression FORM, compile it and return an equivalent byte-code
2466 ;; expression (a call to the function byte-code).
2467 (defun byte-compile-top-level (form &optional for-effect output-type)
2468   ;; OUTPUT-TYPE advises about how form is expected to be used:
2469   ;;    'eval or nil    -> a single form,
2470   ;;    'progn or t     -> a list of forms,
2471   ;;    'lambda         -> body of a lambda,
2472   ;;    'file           -> used at file-level.
2473   (let ((byte-compile-constants nil)
2474         (byte-compile-variables nil)
2475         (byte-compile-tag-number 0)
2476         (byte-compile-depth 0)
2477         (byte-compile-maxdepth 0)
2478         (byte-compile-output nil))
2479     (if (memq byte-optimize '(t source))
2480         (setq form (byte-optimize-form form for-effect)))
2481     (while (and (eq (car-safe form) 'progn) (null (cdr (cdr form))))
2482       (setq form (nth 1 form)))
2483     (if (and (eq 'byte-code (car-safe form))
2484              (not (memq byte-optimize '(t byte)))
2485              (stringp (nth 1 form))
2486              (vectorp (nth 2 form))
2487              (natnump (nth 3 form)))
2488         form
2489       (byte-compile-form form for-effect)
2490       (byte-compile-out-toplevel for-effect output-type))))
2491
2492 (defun byte-compile-out-toplevel (&optional for-effect output-type)
2493   (if for-effect
2494       ;; The stack is empty. Push a value to be returned from (byte-code ..).
2495       (if (eq (car (car byte-compile-output)) 'byte-discard)
2496           (setq byte-compile-output (cdr byte-compile-output))
2497         (byte-compile-push-constant
2498          ;; Push any constant - preferably one which already is used, and
2499          ;; a number or symbol - ie not some big sequence.  The return value
2500          ;; isn't returned, but it would be a shame if some textually large
2501          ;; constant was not optimized away because we chose to return it.
2502          (and (not (assq nil byte-compile-constants)) ; Nil is often there.
2503               (let ((tmp (reverse byte-compile-constants)))
2504                 (while (and tmp (not (or (symbolp (car (car tmp)))
2505                                          (numberp (car (car tmp))))))
2506                   (setq tmp (cdr tmp)))
2507                 (car (car tmp)))))))
2508   (byte-compile-out 'byte-return 0)
2509   (setq byte-compile-output (nreverse byte-compile-output))
2510   (if (memq byte-optimize '(t byte))
2511       (setq byte-compile-output
2512             (byte-optimize-lapcode byte-compile-output for-effect)))
2513
2514   ;; Decompile trivial functions:
2515   ;; only constants and variables, or a single funcall except in lambdas.
2516   ;; Except for Lisp_Compiled objects, forms like (foo "hi")
2517   ;; are still quicker than (byte-code "..." [foo "hi"] 2).
2518   ;; Note that even (quote foo) must be parsed just as any subr by the
2519   ;; interpreter, so quote should be compiled into byte-code in some contexts.
2520   ;; What to leave uncompiled:
2521   ;;    lambda  -> never.  we used to leave it uncompiled if the body was
2522   ;;               a single atom, but that causes confusion if the docstring
2523   ;;               uses the (file . pos) syntax.  Besides, now that we have
2524   ;;               the Lisp_Compiled type, the compiled form is faster.
2525   ;;    eval    -> atom, quote or (function atom atom atom)
2526   ;;    progn   -> as <<same-as-eval>> or (progn <<same-as-eval>> atom)
2527   ;;    file    -> as progn, but takes both quotes and atoms, and longer forms.
2528   (let (rest
2529         (maycall (not (eq output-type 'lambda))) ; t if we may make a funcall.
2530         tmp body)
2531     (cond
2532      ;; #### This should be split out into byte-compile-nontrivial-function-p.
2533      ((or (eq output-type 'lambda)
2534           (nthcdr (if (eq output-type 'file) 50 8) byte-compile-output)
2535           (assq 'TAG byte-compile-output) ; Not necessary, but speeds up a bit.
2536           (not (setq tmp (assq 'byte-return byte-compile-output)))
2537           (progn
2538             (setq rest (nreverse
2539                         (cdr (memq tmp (reverse byte-compile-output)))))
2540             (while (cond
2541                     ((memq (car (car rest)) '(byte-varref byte-constant))
2542                      (setq tmp (car (cdr (car rest))))
2543                      (if (if (eq (car (car rest)) 'byte-constant)
2544                              (or (consp tmp)
2545                                  (and (symbolp tmp)
2546                                       (not (byte-compile-constant-symbol-p tmp)))))
2547                          (if maycall
2548                              (setq body (cons (list 'quote tmp) body)))
2549                        (setq body (cons tmp body))))
2550                     ((and maycall
2551                           ;; Allow a funcall if at most one atom follows it.
2552                           (null (nthcdr 3 rest))
2553                           (setq tmp
2554                                 ;; XEmacs change for rms funs
2555                                 (or (and
2556                                      (byte-compile-version-cond
2557                                       byte-compile-emacs19-compatibility)
2558                                      (get (car (car rest))
2559                                           'byte-opcode19-invert))
2560                                     (get (car (car rest))
2561                                          'byte-opcode-invert)))
2562                           (or (null (cdr rest))
2563                               (and (memq output-type '(file progn t))
2564                                    (cdr (cdr rest))
2565                                    (eq (car (nth 1 rest)) 'byte-discard)
2566                                    (progn (setq rest (cdr rest)) t))))
2567                      (setq maycall nil) ; Only allow one real function call.
2568                      (setq body (nreverse body))
2569                      (setq body (list
2570                                  (if (and (eq tmp 'funcall)
2571                                           (eq (car-safe (car body)) 'quote))
2572                                      (cons (nth 1 (car body)) (cdr body))
2573                                    (cons tmp body))))
2574                      (or (eq output-type 'file)
2575                          (not (delq nil (mapcar 'consp (cdr (car body))))))))
2576               (setq rest (cdr rest)))
2577             rest))
2578       (let ((byte-compile-vector (byte-compile-constants-vector)))
2579         (list 'byte-code (byte-compile-lapcode byte-compile-output)
2580               byte-compile-vector byte-compile-maxdepth)))
2581      ;; it's a trivial function
2582      ((cdr body) (cons 'progn (nreverse body)))
2583      ((car body)))))
2584
2585 ;; Given BODY, compile it and return a new body.
2586 (defun byte-compile-top-level-body (body &optional for-effect)
2587   (setq body (byte-compile-top-level (cons 'progn body) for-effect t))
2588   (cond ((eq (car-safe body) 'progn)
2589          (cdr body))
2590         (body
2591          (list body))))
2592 \f
2593 ;; This is the recursive entry point for compiling each subform of an
2594 ;; expression.
2595 ;; If for-effect is non-nil, byte-compile-form will output a byte-discard
2596 ;; before terminating (ie. no value will be left on the stack).
2597 ;; A byte-compile handler may, when for-effect is non-nil, choose output code
2598 ;; which does not leave a value on the stack, and then set for-effect to nil
2599 ;; (to prevent byte-compile-form from outputting the byte-discard).
2600 ;; If a handler wants to call another handler, it should do so via
2601 ;; byte-compile-form, or take extreme care to handle for-effect correctly.
2602 ;; (Use byte-compile-form-do-effect to reset the for-effect flag too.)
2603 ;;
2604 (defun byte-compile-form (form &optional for-effect)
2605   (setq form (macroexpand form byte-compile-macro-environment))
2606   (cond ((not (consp form))
2607          (cond ((or (not (symbolp form))
2608                     (byte-compile-constant-symbol-p form))
2609                 (byte-compile-constant form))
2610                ((and for-effect byte-compile-delete-errors)
2611                 (setq for-effect nil))
2612                (t (byte-compile-variable-ref 'byte-varref form))))
2613         ((symbolp (car form))
2614          (let* ((fn (car form))
2615                 (handler (get fn 'byte-compile)))
2616            (if (memq fn '(t nil))
2617                (byte-compile-warn "%s called as a function" fn))
2618            (if (and handler
2619                     (or (not (byte-compile-version-cond
2620                               byte-compile-emacs19-compatibility))
2621                         (not (get (get fn 'byte-opcode) 'emacs20-opcode))))
2622                (funcall handler form)
2623              (if (memq 'callargs byte-compile-warnings)
2624                  (byte-compile-callargs-warn form))
2625              (byte-compile-normal-call form))))
2626         ((and (or (compiled-function-p (car form))
2627                   (eq (car-safe (car form)) 'lambda))
2628               ;; if the form comes out the same way it went in, that's
2629               ;; because it was malformed, and we couldn't unfold it.
2630               (not (eq form (setq form (byte-compile-unfold-lambda form)))))
2631          (byte-compile-form form for-effect)
2632          (setq for-effect nil))
2633         ((byte-compile-normal-call form)))
2634   (when for-effect
2635     (byte-compile-discard)))
2636
2637 (defun byte-compile-normal-call (form)
2638   (if byte-compile-generate-call-tree
2639       (byte-compile-annotate-call-tree form))
2640   (byte-compile-push-constant (car form))
2641   (mapcar 'byte-compile-form (cdr form)) ; wasteful, but faster.
2642   (byte-compile-out 'byte-call (length (cdr form))))
2643
2644 ;; kludge added to XEmacs to work around the bogosities of a nonlexical lisp.
2645 (or (fboundp 'globally-boundp) (fset 'globally-boundp 'boundp))
2646
2647 (defun byte-compile-variable-ref (base-op var &optional varbind-flags)
2648   (if (or (not (symbolp var)) (byte-compile-constant-symbol-p var))
2649       (byte-compile-warn
2650        (case base-op
2651          (byte-varref "Variable reference to %s %s")
2652          (byte-varset "Attempt to set %s %s")
2653          (byte-varbind "Attempt to let-bind %s %s"))
2654        (if (symbolp var) "constant symbol" "non-symbol")
2655        var)
2656     (if (and (get var 'byte-obsolete-variable)
2657              (memq 'obsolete byte-compile-warnings))
2658         (let ((ob (get var 'byte-obsolete-variable)))
2659           (byte-compile-warn "%s is an obsolete variable; %s" var
2660                              (if (stringp ob)
2661                                  ob
2662                                (format "use %s instead." ob)))))
2663     (if (and (get var 'byte-compatible-variable)
2664              (memq 'pedantic byte-compile-warnings))
2665         (let ((ob (get var 'byte-compatible-variable)))
2666           (byte-compile-warn "%s is provided for compatibility; %s" var
2667                              (if (stringp ob)
2668                                  ob
2669                                (format "use %s instead." ob)))))
2670     (if (memq 'free-vars byte-compile-warnings)
2671         (if (eq base-op 'byte-varbind)
2672             (setq byte-compile-bound-variables
2673                   (cons (cons var (or varbind-flags 0))
2674                         byte-compile-bound-variables))
2675           (or (globally-boundp var)
2676               (let ((cell (assq var byte-compile-bound-variables)))
2677                 (if cell (setcdr cell
2678                                  (logior (cdr cell)
2679                                          (if (eq base-op 'byte-varset)
2680                                              byte-compile-assigned-bit
2681                                            byte-compile-referenced-bit)))))
2682               (if (eq base-op 'byte-varset)
2683                   (or (memq var byte-compile-free-assignments)
2684                       (progn
2685                         (byte-compile-warn "assignment to free variable %s"
2686                                            var)
2687                         (setq byte-compile-free-assignments
2688                               (cons var byte-compile-free-assignments))))
2689                 (or (memq var byte-compile-free-references)
2690                     (progn
2691                       (byte-compile-warn "reference to free variable %s" var)
2692                       (setq byte-compile-free-references
2693                             (cons var byte-compile-free-references)))))))))
2694   (let ((tmp (assq var byte-compile-variables)))
2695     (or tmp
2696         (setq tmp (list var)
2697               byte-compile-variables (cons tmp byte-compile-variables)))
2698     (byte-compile-out base-op tmp)))
2699
2700 (defmacro byte-compile-get-constant (const)
2701   `(or (if (stringp ,const)
2702            (assoc ,const byte-compile-constants)
2703          (assq ,const byte-compile-constants))
2704        (car (setq byte-compile-constants
2705                   (cons (list ,const) byte-compile-constants)))))
2706
2707 ;; Use this when the value of a form is a constant.  This obeys for-effect.
2708 (defun byte-compile-constant (const)
2709   (if for-effect
2710       (setq for-effect nil)
2711     (byte-compile-out 'byte-constant (byte-compile-get-constant const))))
2712
2713 ;; Use this for a constant that is not the value of its containing form.
2714 ;; This ignores for-effect.
2715 (defun byte-compile-push-constant (const)
2716   (let ((for-effect nil))
2717     (inline (byte-compile-constant const))))
2718
2719 \f
2720 ;; Compile those primitive ordinary functions
2721 ;; which have special byte codes just for speed.
2722
2723 (defmacro byte-defop-compiler (function &optional compile-handler)
2724   ;; add a compiler-form for FUNCTION.
2725   ;; If function is a symbol, then the variable "byte-SYMBOL" must name
2726   ;; the opcode to be used.  If function is a list, the first element
2727   ;; is the function and the second element is the bytecode-symbol.
2728   ;; COMPILE-HANDLER is the function to use to compile this byte-op, or
2729   ;; may be the abbreviations 0, 1, 2, 3, 0-1, 1-2, 2-3, 0+1, 1+1, 2+1,
2730   ;; 0-1+1, 1-2+1, 2-3+1, 0+2, or 1+2.  If it is nil, then the handler is
2731   ;; "byte-compile-SYMBOL."
2732   (let (opcode)
2733     (if (symbolp function)
2734         (setq opcode (intern (concat "byte-" (symbol-name function))))
2735       (setq opcode (car (cdr function))
2736             function (car function)))
2737     (let ((fnform
2738            (list 'put (list 'quote function) ''byte-compile
2739                  (list 'quote
2740                        (or (cdr (assq compile-handler
2741                                       '((0 . byte-compile-no-args)
2742                                         (1 . byte-compile-one-arg)
2743                                         (2 . byte-compile-two-args)
2744                                         (3 . byte-compile-three-args)
2745                                         (0-1 . byte-compile-zero-or-one-arg)
2746                                         (1-2 . byte-compile-one-or-two-args)
2747                                         (2-3 . byte-compile-two-or-three-args)
2748                                         (0+1 . byte-compile-no-args-with-one-extra)
2749                                         (1+1 . byte-compile-one-arg-with-one-extra)
2750                                         (2+1 . byte-compile-two-args-with-one-extra)
2751                                         (0-1+1 . byte-compile-zero-or-one-arg-with-one-extra)
2752                                         (1-2+1 . byte-compile-one-or-two-args-with-one-extra)
2753                                         (2-3+1 . byte-compile-two-or-three-args-with-one-extra)
2754                                         (0+2 . byte-compile-no-args-with-two-extra)
2755                                         (1+2 . byte-compile-one-arg-with-two-extra)
2756
2757                                         )))
2758                            compile-handler
2759                            (intern (concat "byte-compile-"
2760                                            (symbol-name function))))))))
2761       (if opcode
2762           (list 'progn fnform
2763                 (list 'put (list 'quote function)
2764                       ''byte-opcode (list 'quote opcode))
2765                 (list 'put (list 'quote opcode)
2766                       ''byte-opcode-invert (list 'quote function)))
2767         fnform))))
2768
2769 (defmacro byte-defop-compiler20 (function &optional compile-handler)
2770   ;; Just like byte-defop-compiler, but defines an opcode that will only
2771   ;; be used when byte-compile-emacs19-compatibility is false.
2772   (if (and (byte-compile-single-version)
2773            byte-compile-emacs19-compatibility)
2774       ;; #### instead of doing nothing, this should do some remprops,
2775       ;; #### to protect against the case where a single-version compiler
2776       ;; #### is loaded into a world that has contained a multi-version one.
2777       nil
2778     (list 'progn
2779       (list 'put
2780         (list 'quote
2781           (or (car (cdr-safe function))
2782               (intern (concat "byte-"
2783                         (symbol-name (or (car-safe function) function))))))
2784         ''emacs20-opcode t)
2785       (list 'byte-defop-compiler function compile-handler))))
2786
2787 ;; XEmacs addition:
2788 (defmacro byte-defop-compiler-rmsfun (function &optional compile-handler)
2789   ;; for functions like `eq' that compile into different opcodes depending
2790   ;; on the Emacs version: byte-old-eq for v19, byte-eq for v20.
2791   (let ((opcode (intern (concat "byte-" (symbol-name function))))
2792         (opcode19 (intern (concat "byte-old-" (symbol-name function))))
2793         (fnform
2794          (list 'put (list 'quote function) ''byte-compile
2795                (list 'quote
2796                      (or (cdr (assq compile-handler
2797                                     '((2 . byte-compile-two-args-19->20)
2798                                       )))
2799                          compile-handler
2800                          (intern (concat "byte-compile-"
2801                                          (symbol-name function))))))))
2802     (list 'progn fnform
2803           (list 'put (list 'quote function)
2804                 ''byte-opcode (list 'quote opcode))
2805           (list 'put (list 'quote function)
2806                 ''byte-opcode19 (list 'quote opcode19))
2807           (list 'put (list 'quote opcode)
2808                 ''byte-opcode-invert (list 'quote function))
2809           (list 'put (list 'quote opcode19)
2810                 ''byte-opcode19-invert (list 'quote function)))))
2811
2812 (defmacro byte-defop-compiler-1 (function &optional compile-handler)
2813   (list 'byte-defop-compiler (list function nil) compile-handler))
2814
2815 \f
2816 (put 'byte-call 'byte-opcode-invert 'funcall)
2817 (put 'byte-list1 'byte-opcode-invert 'list)
2818 (put 'byte-list2 'byte-opcode-invert 'list)
2819 (put 'byte-list3 'byte-opcode-invert 'list)
2820 (put 'byte-list4 'byte-opcode-invert 'list)
2821 (put 'byte-listN 'byte-opcode-invert 'list)
2822 (put 'byte-concat2 'byte-opcode-invert 'concat)
2823 (put 'byte-concat3 'byte-opcode-invert 'concat)
2824 (put 'byte-concat4 'byte-opcode-invert 'concat)
2825 (put 'byte-concatN 'byte-opcode-invert 'concat)
2826 (put 'byte-insertN 'byte-opcode-invert 'insert)
2827
2828 ;; How old is this stuff? -slb
2829 ;(byte-defop-compiler (dot byte-point)          0+1)
2830 ;(byte-defop-compiler (dot-max byte-point-max)  0+1)
2831 ;(byte-defop-compiler (dot-min byte-point-min)  0+1)
2832 (byte-defop-compiler point              0+1)
2833 (byte-defop-compiler-rmsfun eq          2)
2834 (byte-defop-compiler point-max          0+1)
2835 (byte-defop-compiler point-min          0+1)
2836 (byte-defop-compiler following-char     0+1)
2837 (byte-defop-compiler preceding-char     0+1)
2838 (byte-defop-compiler current-column     0+1)
2839 ;; FSF has special function here; generalized here by the 1+2 stuff.
2840 (byte-defop-compiler (indent-to-column byte-indent-to) 1+2)
2841 (byte-defop-compiler indent-to          1+2)
2842 (byte-defop-compiler-rmsfun equal       2)
2843 (byte-defop-compiler eolp               0+1)
2844 (byte-defop-compiler eobp               0+1)
2845 (byte-defop-compiler bolp               0+1)
2846 (byte-defop-compiler bobp               0+1)
2847 (byte-defop-compiler current-buffer     0)
2848 ;;(byte-defop-compiler read-char        0) ;; obsolete
2849 (byte-defop-compiler-rmsfun memq        2)
2850 (byte-defop-compiler interactive-p      0)
2851 (byte-defop-compiler widen              0+1)
2852 (byte-defop-compiler end-of-line        0-1+1)
2853 (byte-defop-compiler forward-char       0-1+1)
2854 (byte-defop-compiler forward-line       0-1+1)
2855 (byte-defop-compiler symbolp            1)
2856 (byte-defop-compiler consp              1)
2857 (byte-defop-compiler stringp            1)
2858 (byte-defop-compiler listp              1)
2859 (byte-defop-compiler not                1)
2860 (byte-defop-compiler (null byte-not)    1)
2861 (byte-defop-compiler car                1)
2862 (byte-defop-compiler cdr                1)
2863 (byte-defop-compiler length             1)
2864 (byte-defop-compiler symbol-value       1)
2865 (byte-defop-compiler symbol-function    1)
2866 (byte-defop-compiler (1+ byte-add1)     1)
2867 (byte-defop-compiler (1- byte-sub1)     1)
2868 (byte-defop-compiler goto-char          1+1)
2869 (byte-defop-compiler char-after         0-1+1)
2870 (byte-defop-compiler set-buffer         1)
2871 ;;(byte-defop-compiler set-mark         1) ;; obsolete
2872 (byte-defop-compiler forward-word       1+1)
2873 (byte-defop-compiler char-syntax        1+1)
2874 (byte-defop-compiler nreverse           1)
2875 (byte-defop-compiler car-safe           1)
2876 (byte-defop-compiler cdr-safe           1)
2877 (byte-defop-compiler numberp            1)
2878 (byte-defop-compiler integerp           1)
2879 (byte-defop-compiler skip-chars-forward     1-2+1)
2880 (byte-defop-compiler skip-chars-backward    1-2+1)
2881 (byte-defop-compiler (eql byte-eq)      2)
2882 (byte-defop-compiler20 old-eq           2)
2883 (byte-defop-compiler20 old-memq         2)
2884 (byte-defop-compiler cons               2)
2885 (byte-defop-compiler aref               2)
2886 (byte-defop-compiler get                2+1)
2887 (byte-defop-compiler nth                2)
2888 (byte-defop-compiler substring          2-3)
2889 (byte-defop-compiler (move-marker byte-set-marker) 2-3)
2890 (byte-defop-compiler set-marker         2-3)
2891 (byte-defop-compiler match-beginning    1)
2892 (byte-defop-compiler match-end          1)
2893 (byte-defop-compiler upcase             1+1)
2894 (byte-defop-compiler downcase           1+1)
2895 (byte-defop-compiler string=            2)
2896 (byte-defop-compiler string<            2)
2897 (byte-defop-compiler (string-equal byte-string=) 2)
2898 (byte-defop-compiler (string-lessp byte-string<) 2)
2899 (byte-defop-compiler20 old-equal        2)
2900 (byte-defop-compiler nthcdr             2)
2901 (byte-defop-compiler elt                2)
2902 (byte-defop-compiler20 old-member       2)
2903 (byte-defop-compiler20 old-assq         2)
2904 (byte-defop-compiler (rplaca byte-setcar) 2)
2905 (byte-defop-compiler (rplacd byte-setcdr) 2)
2906 (byte-defop-compiler setcar             2)
2907 (byte-defop-compiler setcdr             2)
2908 (byte-defop-compiler delete-region      2+1)
2909 (byte-defop-compiler narrow-to-region   2+1)
2910 (byte-defop-compiler (% byte-rem)       2)
2911 (byte-defop-compiler aset               3)
2912
2913 (byte-defop-compiler-rmsfun member      2)
2914 (byte-defop-compiler-rmsfun assq        2)
2915
2916 (byte-defop-compiler max                byte-compile-associative)
2917 (byte-defop-compiler min                byte-compile-associative)
2918 (byte-defop-compiler (+ byte-plus)      byte-compile-associative)
2919 (byte-defop-compiler (* byte-mult)      byte-compile-associative)
2920
2921 ;;####(byte-defop-compiler move-to-column       1)
2922 (byte-defop-compiler-1 interactive byte-compile-noop)
2923 (byte-defop-compiler-1 domain byte-compile-domain)
2924
2925 ;; As of GNU Emacs 19.18 and Lucid Emacs 19.8, mod and % are different: `%'
2926 ;; means integral remainder and may have a negative result; `mod' is always
2927 ;; positive, and accepts floating point args.  All code which uses `mod' and
2928 ;; requires the new interpretation must be compiled with bytecomp version 2.18
2929 ;; or newer, or the emitted code will run the byte-code for `%' instead of an
2930 ;; actual call to `mod'.  So be careful of compiling new code with an old
2931 ;; compiler.  Note also that `%' is more efficient than `mod' because the
2932 ;; former is byte-coded and the latter is not.
2933 ;;(byte-defop-compiler (mod byte-rem) 2)
2934
2935 \f
2936 (defun byte-compile-subr-wrong-args (form n)
2937   (when (memq 'subr-callargs byte-compile-warnings)
2938     (byte-compile-warn "%s called with %d arg%s, but requires %s"
2939                        (car form) (length (cdr form))
2940                        (if (= 1 (length (cdr form))) "" "s") n))
2941   ;; get run-time wrong-number-of-args error.
2942   (byte-compile-normal-call form))
2943
2944 (defun byte-compile-no-args (form)
2945   (case (length (cdr form))
2946     (0 (byte-compile-out (get (car form) 'byte-opcode) 0))
2947     (t (byte-compile-subr-wrong-args form "none"))))
2948
2949 (defun byte-compile-one-arg (form)
2950   (case (length (cdr form))
2951     (1 (byte-compile-form (car (cdr form)))  ;; Push the argument
2952        (byte-compile-out (get (car form) 'byte-opcode) 0))
2953     (t (byte-compile-subr-wrong-args form 1))))
2954
2955 (defun byte-compile-two-args (form)
2956   (case (length (cdr form))
2957     (2 (byte-compile-form (nth 1 form))  ;; Push the arguments
2958        (byte-compile-form (nth 2 form))
2959        (byte-compile-out (get (car form) 'byte-opcode) 0))
2960     (t (byte-compile-subr-wrong-args form 2))))
2961
2962 (defun byte-compile-three-args (form)
2963   (case (length (cdr form))
2964     (3 (byte-compile-form (nth 1 form))  ;; Push the arguments
2965        (byte-compile-form (nth 2 form))
2966        (byte-compile-form (nth 3 form))
2967        (byte-compile-out (get (car form) 'byte-opcode) 0))
2968     (t (byte-compile-subr-wrong-args form 3))))
2969
2970 (defun byte-compile-zero-or-one-arg (form)
2971   (case (length (cdr form))
2972     (0 (byte-compile-one-arg (append form '(nil))))
2973     (1 (byte-compile-one-arg form))
2974     (t (byte-compile-subr-wrong-args form "0-1"))))
2975
2976 (defun byte-compile-one-or-two-args (form)
2977   (case (length (cdr form))
2978     (1 (byte-compile-two-args (append form '(nil))))
2979     (2 (byte-compile-two-args form))
2980     (t (byte-compile-subr-wrong-args form "1-2"))))
2981
2982 (defun byte-compile-two-or-three-args (form)
2983   (case (length (cdr form))
2984     (2 (byte-compile-three-args (append form '(nil))))
2985     (3 (byte-compile-three-args form))
2986     (t (byte-compile-subr-wrong-args form "2-3"))))
2987
2988 ;; from Ben Wing <ben@xemacs.org>: some inlined functions have extra
2989 ;; optional args added to them in XEmacs 19.12.  Changing the byte
2990 ;; interpreter to deal with these args would be wrong and cause
2991 ;; incompatibility, so we generate non-inlined calls for those cases.
2992 ;; Without the following functions, spurious warnings will be generated;
2993 ;; however, they would still compile correctly because
2994 ;; `byte-compile-subr-wrong-args' also converts the call to non-inlined.
2995
2996 (defun byte-compile-no-args-with-one-extra (form)
2997   (case (length (cdr form))
2998     (0 (byte-compile-no-args form))
2999     (1 (byte-compile-normal-call form))
3000     (t (byte-compile-subr-wrong-args form "0-1"))))
3001
3002 (defun byte-compile-one-arg-with-one-extra (form)
3003   (case (length (cdr form))
3004     (1 (byte-compile-one-arg form))
3005     (2 (byte-compile-normal-call form))
3006     (t (byte-compile-subr-wrong-args form "1-2"))))
3007
3008 (defun byte-compile-two-args-with-one-extra (form)
3009   (case (length (cdr form))
3010     (2 (byte-compile-two-args form))
3011     (3 (byte-compile-normal-call form))
3012     (t (byte-compile-subr-wrong-args form "2-3"))))
3013
3014 (defun byte-compile-zero-or-one-arg-with-one-extra (form)
3015   (case (length (cdr form))
3016     (0 (byte-compile-one-arg (append form '(nil))))
3017     (1 (byte-compile-one-arg form))
3018     (2 (byte-compile-normal-call form))
3019     (t (byte-compile-subr-wrong-args form "0-2"))))
3020
3021 (defun byte-compile-one-or-two-args-with-one-extra (form)
3022   (case (length (cdr form))
3023     (1 (byte-compile-two-args (append form '(nil))))
3024     (2 (byte-compile-two-args form))
3025     (3 (byte-compile-normal-call form))
3026     (t (byte-compile-subr-wrong-args form "1-3"))))
3027
3028 (defun byte-compile-two-or-three-args-with-one-extra (form)
3029   (case (length (cdr form))
3030     (2 (byte-compile-three-args (append form '(nil))))
3031     (3 (byte-compile-three-args form))
3032     (4 (byte-compile-normal-call form))
3033     (t (byte-compile-subr-wrong-args form "2-4"))))
3034
3035 (defun byte-compile-no-args-with-two-extra (form)
3036   (case (length (cdr form))
3037     (0     (byte-compile-no-args form))
3038     ((1 2) (byte-compile-normal-call form))
3039     (t     (byte-compile-subr-wrong-args form "0-2"))))
3040
3041 (defun byte-compile-one-arg-with-two-extra (form)
3042   (case (length (cdr form))
3043     (1     (byte-compile-one-arg form))
3044     ((2 3) (byte-compile-normal-call form))
3045     (t     (byte-compile-subr-wrong-args form "1-3"))))
3046
3047 ;; XEmacs: used for functions that have a different opcode in v19 than v20.
3048 ;; this includes `eq', `equal', and other old-ified functions.
3049 (defun byte-compile-two-args-19->20 (form)
3050   (if (not (= (length form) 3))
3051       (byte-compile-subr-wrong-args form 2)
3052     (byte-compile-form (car (cdr form)))  ;; Push the arguments
3053     (byte-compile-form (nth 2 form))
3054     (if (byte-compile-version-cond byte-compile-emacs19-compatibility)
3055         (byte-compile-out (get (car form) 'byte-opcode19) 0)
3056       (byte-compile-out (get (car form) 'byte-opcode) 0))))
3057
3058 (defun byte-compile-noop (form)
3059   (byte-compile-constant nil))
3060
3061 (defun byte-compile-discard ()
3062   (byte-compile-out 'byte-discard 0))
3063
3064 ;; Compile a function that accepts one or more args and is right-associative.
3065 ;; We do it by left-associativity so that the operations
3066 ;; are done in the same order as in interpreted code.
3067 ;(defun byte-compile-associative (form)
3068 ;  (if (cdr form)
3069 ;      (let ((opcode (get (car form) 'byte-opcode))
3070 ;           (args (copy-sequence (cdr form))))
3071 ;       (byte-compile-form (car args))
3072 ;       (setq args (cdr args))
3073 ;       (while args
3074 ;         (byte-compile-form (car args))
3075 ;         (byte-compile-out opcode 0)
3076 ;         (setq args (cdr args))))
3077 ;    (byte-compile-constant (eval form))))
3078
3079 ;; Compile a function that accepts one or more args and is right-associative.
3080 ;; We do it by left-associativity so that the operations
3081 ;; are done in the same order as in interpreted code.
3082 (defun byte-compile-associative (form)
3083   (let ((args (cdr form))
3084         (opcode (get (car form) 'byte-opcode)))
3085     (case (length args)
3086       (0 (byte-compile-constant (eval form)))
3087       (t (byte-compile-form (car args))
3088          (dolist (arg (cdr args))
3089            (byte-compile-form arg)
3090            (byte-compile-out opcode 0))))))
3091
3092 \f
3093 ;; more complicated compiler macros
3094
3095 (byte-defop-compiler list)
3096 (byte-defop-compiler concat)
3097 (byte-defop-compiler fset)
3098 (byte-defop-compiler insert)
3099 (byte-defop-compiler-1 function byte-compile-function-form)
3100 (byte-defop-compiler-1 - byte-compile-minus)
3101 (byte-defop-compiler (/ byte-quo) byte-compile-quo)
3102 (byte-defop-compiler nconc)
3103 (byte-defop-compiler-1 beginning-of-line)
3104
3105 (byte-defop-compiler (=  byte-eqlsign)  byte-compile-arithcompare)
3106 (byte-defop-compiler (<  byte-lss)      byte-compile-arithcompare)
3107 (byte-defop-compiler (>  byte-gtr)      byte-compile-arithcompare)
3108 (byte-defop-compiler (<= byte-leq)      byte-compile-arithcompare)
3109 (byte-defop-compiler (>= byte-geq)      byte-compile-arithcompare)
3110
3111 (defun byte-compile-arithcompare (form)
3112   (case (length (cdr form))
3113     (0 (byte-compile-subr-wrong-args form "1 or more"))
3114     (1 (byte-compile-constant t))
3115     (2 (byte-compile-two-args form))
3116     (t (byte-compile-normal-call form))))
3117
3118 (byte-defop-compiler /= byte-compile-/=)
3119
3120 (defun byte-compile-/= (form)
3121   (case (length (cdr form))
3122     (0 (byte-compile-subr-wrong-args form "1 or more"))
3123     (1 (byte-compile-constant t))
3124     ;; optimize (/= X Y) to (not (= X Y))
3125     (2 (byte-compile-form-do-effect `(not (= ,@(cdr form)))))
3126     (t (byte-compile-normal-call form))))
3127
3128 ;; buffer-substring now has its own function.  This used to be
3129 ;; 2+1, but now all args are optional.
3130 (byte-defop-compiler buffer-substring)
3131
3132 (defun byte-compile-buffer-substring (form)
3133   ;; buffer-substring used to take exactly two args, but now takes 0-3.
3134   ;; convert 0-2 to two args and use special bytecode operand.
3135   ;; convert 3 args to a normal call.
3136   (case (length (cdr form))
3137     (0 (byte-compile-two-args (append form '(nil nil))))
3138     (1 (byte-compile-two-args (append form '(nil))))
3139     (2 (byte-compile-two-args form))
3140     (3 (byte-compile-normal-call form))
3141     (t (byte-compile-subr-wrong-args form "0-3"))))
3142
3143 (defun byte-compile-list (form)
3144   (let* ((args (cdr form))
3145          (nargs (length args)))
3146     (cond
3147      ((= nargs 0)
3148       (byte-compile-constant nil))
3149      ((< nargs 5)
3150       (mapcar 'byte-compile-form args)
3151       (byte-compile-out
3152        (aref [byte-list1 byte-list2 byte-list3 byte-list4] (1- nargs))
3153        0))
3154      ((< nargs 256)
3155       (mapcar 'byte-compile-form args)
3156       (byte-compile-out 'byte-listN nargs))
3157      (t (byte-compile-normal-call form)))))
3158
3159 (defun byte-compile-concat (form)
3160   (let* ((args (cdr form))
3161          (nargs (length args)))
3162     ;; Concat of one arg is not a no-op if arg is not a string.
3163     (cond
3164      ((memq nargs '(2 3 4))
3165       (mapcar 'byte-compile-form args)
3166       (byte-compile-out
3167        (aref [byte-concat2 byte-concat3 byte-concat4] (- nargs 2))
3168        0))
3169      ((eq nargs 0)
3170       (byte-compile-form ""))
3171      ((< nargs 256)
3172       (mapcar 'byte-compile-form args)
3173       (byte-compile-out 'byte-concatN nargs))
3174      ((byte-compile-normal-call form)))))
3175
3176 (defun byte-compile-minus (form)
3177   (let ((args (cdr form)))
3178     (case (length args)
3179       (0 (byte-compile-subr-wrong-args form "1 or more"))
3180       (1 (byte-compile-form (car args))
3181          (byte-compile-out 'byte-negate 0))
3182       (t (byte-compile-form (car args))
3183          (dolist (elt (cdr args))
3184            (byte-compile-form elt)
3185            (byte-compile-out 'byte-diff 0))))))
3186
3187 (defun byte-compile-quo (form)
3188   (let ((args (cdr form)))
3189     (case (length args)
3190       (0 (byte-compile-subr-wrong-args form "1 or more"))
3191       (1 (byte-compile-constant 1)
3192          (byte-compile-form (car args))
3193          (byte-compile-out 'byte-quo 0))
3194       (t (byte-compile-form (car args))
3195          (dolist (elt (cdr args))
3196            (byte-compile-form elt)
3197            (byte-compile-out 'byte-quo 0))))))
3198
3199 (defun byte-compile-nconc (form)
3200   (let ((args (cdr form)))
3201     (case (length args)
3202       (0 (byte-compile-constant nil))
3203       ;; nconc of one arg is a noop, even if that arg isn't a list.
3204       (1 (byte-compile-form (car args)))
3205       (t (byte-compile-form (car args))
3206          (dolist (elt (cdr args))
3207            (byte-compile-form elt)
3208            (byte-compile-out 'byte-nconc 0))))))
3209
3210 (defun byte-compile-fset (form)
3211   ;; warn about forms like (fset 'foo '(lambda () ...))
3212   ;; (where the lambda expression is non-trivial...)
3213   ;; Except don't warn if the first argument is 'make-byte-code, because
3214   ;; I'm sick of getting mail asking me whether that warning is a problem.
3215   (let ((fn (nth 2 form))
3216         body)
3217     (when (and (eq (car-safe fn) 'quote)
3218                (eq (car-safe (setq fn (nth 1 fn))) 'lambda)
3219                (not (eq (car-safe (cdr-safe (nth 1 form))) 'make-byte-code)))
3220       (setq body (cdr (cdr fn)))
3221       (if (stringp (car body)) (setq body (cdr body)))
3222       (if (eq 'interactive (car-safe (car body))) (setq body (cdr body)))
3223       (if (and (consp (car body))
3224                (not (eq 'byte-code (car (car body)))))
3225           (byte-compile-warn
3226     "A quoted lambda form is the second argument of fset.  This is probably
3227      not what you want, as that lambda cannot be compiled.  Consider using
3228      the syntax (function (lambda (...) ...)) instead."))))
3229   (byte-compile-two-args form))
3230
3231 (defun byte-compile-funarg (form)
3232   ;; (mapcar '(lambda (x) ..) ..) ==> (mapcar (function (lambda (x) ..)) ..)
3233   ;; for cases where it's guaranteed that first arg will be used as a lambda.
3234   (byte-compile-normal-call
3235    (let ((fn (nth 1 form)))
3236      (if (and (eq (car-safe fn) 'quote)
3237               (eq (car-safe (nth 1 fn)) 'lambda))
3238          (cons (car form)
3239                (cons (cons 'function (cdr fn))
3240                      (cdr (cdr form))))
3241        form))))
3242
3243 ;; (function foo) must compile like 'foo, not like (symbol-function 'foo).
3244 ;; Otherwise it will be incompatible with the interpreter,
3245 ;; and (funcall (function foo)) will lose with autoloads.
3246
3247 (defun byte-compile-function-form (form)
3248   (byte-compile-constant
3249    (cond ((symbolp (nth 1 form))
3250           (nth 1 form))
3251          ((byte-compile-lambda (nth 1 form))))))
3252
3253 (defun byte-compile-insert (form)
3254   (cond ((null (cdr form))
3255          (byte-compile-constant nil))
3256         ((<= (length form) 256)
3257          (mapcar 'byte-compile-form (cdr form))
3258          (if (cdr (cdr form))
3259              (byte-compile-out 'byte-insertN (length (cdr form)))
3260            (byte-compile-out 'byte-insert 0)))
3261         ((memq t (mapcar 'consp (cdr (cdr form))))
3262          (byte-compile-normal-call form))
3263         ;; We can split it; there is no function call after inserting 1st arg.
3264         (t
3265          (while (setq form (cdr form))
3266            (byte-compile-form (car form))
3267            (byte-compile-out 'byte-insert 0)
3268            (when (cdr form)
3269              (byte-compile-discard))))))
3270
3271 ;; alas, the old (pre-19.12, and all existing versions of FSFmacs 19)
3272 ;; byte compiler will generate incorrect code for
3273 ;; (beginning-of-line nil buffer) because it buggily doesn't
3274 ;; check the number of arguments passed to beginning-of-line.
3275
3276 (defun byte-compile-beginning-of-line (form)
3277   (let ((len (length form)))
3278     (cond ((> len 3)
3279            (byte-compile-subr-wrong-args form "0-2"))
3280           ((or (= len 3) (not (byte-compile-constp (nth 1 form))))
3281            (byte-compile-normal-call form))
3282           (t
3283            (byte-compile-form
3284             (list 'forward-line
3285                   (if (integerp (setq form (or (eval (nth 1 form)) 1)))
3286                       (1- form)
3287                     (byte-compile-warn
3288                      "Non-numeric arg to beginning-of-line: %s" form)
3289                     (list '1- (list 'quote form))))
3290             t)
3291            (byte-compile-constant nil)))))
3292
3293 \f
3294 (byte-defop-compiler set)
3295 (byte-defop-compiler-1 setq)
3296 (byte-defop-compiler-1 set-default)
3297 (byte-defop-compiler-1 setq-default)
3298
3299 (byte-defop-compiler-1 quote)
3300 (byte-defop-compiler-1 quote-form)
3301
3302 (defun byte-compile-setq (form)
3303   (let ((args (cdr form)) var val)
3304     (if (null args)
3305         ;; (setq), with no arguments.
3306         (byte-compile-form nil for-effect)
3307       (while args
3308         (setq var (pop args))
3309         (if (null args)
3310             ;; Odd number of args?  Let `set' get the error.
3311             (byte-compile-form `(set ',var) for-effect)
3312           (setq val (pop args))
3313           (if (keywordp var)
3314               ;; (setq :foo ':foo) compatibility kludge
3315               (byte-compile-form `(set ',var ,val) (if args t for-effect))
3316             (byte-compile-form val)
3317             (unless (or args for-effect)
3318               (byte-compile-out 'byte-dup 0))
3319             (byte-compile-variable-ref 'byte-varset var))))))
3320   (setq for-effect nil))
3321
3322 (defun byte-compile-set (form)
3323   ;; Compile (set 'foo x) as (setq foo x) for trivially better code and so
3324   ;; that we get applicable warnings.  Compile everything else (including
3325   ;; malformed calls) like a normal 2-arg byte-coded function.
3326   (let ((symform (nth 1 form))
3327         (valform (nth 2 form))
3328         sym)
3329     (if (and (= (length form) 3)
3330              (= (safe-length symform) 2)
3331              (eq (car symform) 'quote)
3332              (symbolp (setq sym (car (cdr symform))))
3333              (not (byte-compile-constant-symbol-p sym)))
3334         (byte-compile-setq `(setq ,sym ,valform))
3335       (byte-compile-two-args form))))
3336
3337 (defun byte-compile-setq-default (form)
3338   (let ((args (cdr form)))
3339     (if (null args)
3340         ;; (setq-default), with no arguments.
3341         (byte-compile-form nil for-effect)
3342       ;; emit multiple calls to `set-default' if necessary
3343       (while args
3344         (byte-compile-form
3345          ;; Odd number of args?  Let `set-default' get the error.
3346          `(set-default ',(pop args) ,@(if args (list (pop args)) nil))
3347          (if args t for-effect)))))
3348   (setq for-effect nil))
3349
3350
3351 (defun byte-compile-set-default (form)
3352   (let* ((args (cdr form))
3353          (nargs (length args))
3354          (var (car args)))
3355     (when (and (= (safe-length var) 2)
3356                (eq (car var) 'quote))
3357       (let ((sym (nth 1 var)))
3358         (cond
3359          ((not (symbolp sym))
3360           (byte-compile-warn "Attempt to set-globally non-symbol %s" sym))
3361          ((byte-compile-constant-symbol-p sym)
3362           (byte-compile-warn "Attempt to set-globally constant symbol %s" sym))
3363          ((let ((cell (assq sym byte-compile-bound-variables)))
3364             (and cell
3365                  (setcdr cell (logior (cdr cell) byte-compile-assigned-bit))
3366                  t)))
3367          ;; notice calls to set-default/setq-default for variables which
3368          ;; have not been declared with defvar/defconst.
3369          ((globally-boundp sym))        ; OK
3370          ((not (memq 'free-vars byte-compile-warnings))) ; warnings suppressed?
3371          ((memq sym byte-compile-free-assignments)) ; already warned about sym
3372          (t
3373           (byte-compile-warn "assignment to free variable %s" sym)
3374           (push sym byte-compile-free-assignments)))))
3375     (if (= nargs 2)
3376         ;; now emit a normal call to set-default
3377         (byte-compile-normal-call form)
3378       (byte-compile-subr-wrong-args form 2))))
3379
3380
3381 (defun byte-compile-quote (form)
3382   (byte-compile-constant (car (cdr form))))
3383
3384 (defun byte-compile-quote-form (form)
3385   (byte-compile-constant (byte-compile-top-level (nth 1 form))))
3386
3387 \f
3388 ;;; control structures
3389
3390 (defun byte-compile-body (body &optional for-effect)
3391   (while (cdr body)
3392     (byte-compile-form (car body) t)
3393     (setq body (cdr body)))
3394   (byte-compile-form (car body) for-effect))
3395
3396 (proclaim-inline byte-compile-body-do-effect)
3397 (defun byte-compile-body-do-effect (body)
3398   (byte-compile-body body for-effect)
3399   (setq for-effect nil))
3400
3401 (proclaim-inline byte-compile-form-do-effect)
3402 (defun byte-compile-form-do-effect (form)
3403   (byte-compile-form form for-effect)
3404   (setq for-effect nil))
3405
3406 (byte-defop-compiler-1 inline byte-compile-progn)
3407 (byte-defop-compiler-1 progn)
3408 (byte-defop-compiler-1 prog1)
3409 (byte-defop-compiler-1 prog2)
3410 (byte-defop-compiler-1 if)
3411 (byte-defop-compiler-1 cond)
3412 (byte-defop-compiler-1 and)
3413 (byte-defop-compiler-1 or)
3414 (byte-defop-compiler-1 while)
3415 (byte-defop-compiler-1 funcall)
3416 (byte-defop-compiler-1 apply byte-compile-funarg)
3417 (byte-defop-compiler-1 mapcar byte-compile-funarg)
3418 (byte-defop-compiler-1 mapatoms byte-compile-funarg)
3419 (byte-defop-compiler-1 mapconcat byte-compile-funarg)
3420 (byte-defop-compiler-1 let)
3421 (byte-defop-compiler-1 let*)
3422
3423 (defun byte-compile-progn (form)
3424   (byte-compile-body-do-effect (cdr form)))
3425
3426 (defun byte-compile-prog1 (form)
3427   (setq form (cdr form))
3428   (byte-compile-form-do-effect (pop form))
3429   (byte-compile-body form t))
3430
3431 (defun byte-compile-prog2 (form)
3432   (setq form (cdr form))
3433   (byte-compile-form (pop form) t)
3434   (byte-compile-form-do-effect (pop form))
3435   (byte-compile-body form t))
3436
3437 (defmacro byte-compile-goto-if (cond discard tag)
3438   `(byte-compile-goto
3439     (if ,cond
3440         (if ,discard 'byte-goto-if-not-nil 'byte-goto-if-not-nil-else-pop)
3441       (if ,discard 'byte-goto-if-nil 'byte-goto-if-nil-else-pop))
3442     ,tag))
3443
3444 (defun byte-compile-if (form)
3445   (byte-compile-form (car (cdr form)))
3446   (if (null (nthcdr 3 form))
3447       ;; No else-forms
3448       (let ((donetag (byte-compile-make-tag)))
3449         (byte-compile-goto-if nil for-effect donetag)
3450         (byte-compile-form (nth 2 form) for-effect)
3451         (byte-compile-out-tag donetag))
3452     (let ((donetag (byte-compile-make-tag)) (elsetag (byte-compile-make-tag)))
3453       (byte-compile-goto 'byte-goto-if-nil elsetag)
3454       (byte-compile-form (nth 2 form) for-effect)
3455       (byte-compile-goto 'byte-goto donetag)
3456       (byte-compile-out-tag elsetag)
3457       (byte-compile-body (cdr (cdr (cdr form))) for-effect)
3458       (byte-compile-out-tag donetag)))
3459   (setq for-effect nil))
3460
3461 (defun byte-compile-cond (clauses)
3462   (let ((donetag (byte-compile-make-tag))
3463         nexttag clause)
3464     (while (setq clauses (cdr clauses))
3465       (setq clause (car clauses))
3466       (cond ((or (eq (car clause) t)
3467                  (and (eq (car-safe (car clause)) 'quote)
3468                       (car-safe (cdr-safe (car clause)))))
3469              ;; Unconditional clause
3470              (setq clause (cons t clause)
3471                    clauses nil))
3472             ((cdr clauses)
3473              (byte-compile-form (car clause))
3474              (if (null (cdr clause))
3475                  ;; First clause is a singleton.
3476                  (byte-compile-goto-if t for-effect donetag)
3477                (setq nexttag (byte-compile-make-tag))
3478                (byte-compile-goto 'byte-goto-if-nil nexttag)
3479                (byte-compile-body (cdr clause) for-effect)
3480                (byte-compile-goto 'byte-goto donetag)
3481                (byte-compile-out-tag nexttag)))))
3482     ;; Last clause
3483     (and (cdr clause) (not (eq (car clause) t))
3484          (progn (byte-compile-form (car clause))
3485                 (byte-compile-goto-if nil for-effect donetag)
3486                 (setq clause (cdr clause))))
3487     (byte-compile-body-do-effect clause)
3488     (byte-compile-out-tag donetag)))
3489
3490 (defun byte-compile-and (form)
3491   (let ((failtag (byte-compile-make-tag))
3492         (args (cdr form)))
3493     (if (null args)
3494         (byte-compile-form-do-effect t)
3495       (while (cdr args)
3496         (byte-compile-form (car args))
3497         (byte-compile-goto-if nil for-effect failtag)
3498         (setq args (cdr args)))
3499       (byte-compile-form-do-effect (car args))
3500       (byte-compile-out-tag failtag))))
3501
3502 (defun byte-compile-or (form)
3503   (let ((wintag (byte-compile-make-tag))
3504         (args (cdr form)))
3505     (if (null args)
3506         (byte-compile-form-do-effect nil)
3507       (while (cdr args)
3508         (byte-compile-form (car args))
3509         (byte-compile-goto-if t for-effect wintag)
3510         (setq args (cdr args)))
3511       (byte-compile-form-do-effect (car args))
3512       (byte-compile-out-tag wintag))))
3513
3514 (defun byte-compile-while (form)
3515   (let ((endtag (byte-compile-make-tag))
3516         (looptag (byte-compile-make-tag)))
3517     (byte-compile-out-tag looptag)
3518     (byte-compile-form (car (cdr form)))
3519     (byte-compile-goto-if nil for-effect endtag)
3520     (byte-compile-body (cdr (cdr form)) t)
3521     (byte-compile-goto 'byte-goto looptag)
3522     (byte-compile-out-tag endtag)
3523     (setq for-effect nil)))
3524
3525 (defun byte-compile-funcall (form)
3526   (mapcar 'byte-compile-form (cdr form))
3527   (byte-compile-out 'byte-call (length (cdr (cdr form)))))
3528
3529
3530 (defun byte-compile-let (form)
3531   ;; First compute the binding values in the old scope.
3532   (let ((varlist (car (cdr form))))
3533     (while varlist
3534       (if (consp (car varlist))
3535           (byte-compile-form (car (cdr (car varlist))))
3536         (byte-compile-push-constant nil))
3537       (setq varlist (cdr varlist))))
3538   (let ((byte-compile-bound-variables
3539          (cons 'new-scope byte-compile-bound-variables))
3540         (varlist (reverse (car (cdr form))))
3541         (extra-flags
3542          ;; If this let is of the form (let (...) (byte-code ...))
3543          ;; then assume that it is the result of a transformation of
3544          ;; ((lambda (...) (byte-code ... )) ...) and thus compile
3545          ;; the variable bindings as if they were arglist bindings
3546          ;; (which matters for what warnings.)
3547          (if (eq 'byte-code (car-safe (nth 2 form)))
3548              byte-compile-arglist-bit
3549            nil)))
3550     (while varlist
3551       (byte-compile-variable-ref 'byte-varbind
3552                                  (if (consp (car varlist))
3553                                      (car (car varlist))
3554                                    (car varlist))
3555                                  extra-flags)
3556       (setq varlist (cdr varlist)))
3557     (byte-compile-body-do-effect (cdr (cdr form)))
3558     (if (memq 'unused-vars byte-compile-warnings)
3559         ;; done compiling in this scope, warn now.
3560         (byte-compile-warn-about-unused-variables))
3561     (byte-compile-out 'byte-unbind (length (car (cdr form))))))
3562
3563 (defun byte-compile-let* (form)
3564   (let ((byte-compile-bound-variables
3565          (cons 'new-scope byte-compile-bound-variables))
3566         (varlist (copy-sequence (car (cdr form)))))
3567     (while varlist
3568       (if (atom (car varlist))
3569           (byte-compile-push-constant nil)
3570         (byte-compile-form (car (cdr (car varlist))))
3571         (setcar varlist (car (car varlist))))
3572       (byte-compile-variable-ref 'byte-varbind (car varlist))
3573       (setq varlist (cdr varlist)))
3574     (byte-compile-body-do-effect (cdr (cdr form)))
3575     (if (memq 'unused-vars byte-compile-warnings)
3576         ;; done compiling in this scope, warn now.
3577         (byte-compile-warn-about-unused-variables))
3578     (byte-compile-out 'byte-unbind (length (car (cdr form))))))
3579
3580
3581 ;;(byte-defop-compiler-1 /= byte-compile-negated)
3582 (byte-defop-compiler-1 atom byte-compile-negated)
3583 (byte-defop-compiler-1 nlistp byte-compile-negated)
3584
3585 ;;(put '/= 'byte-compile-negated-op '=)
3586 (put 'atom 'byte-compile-negated-op 'consp)
3587 (put 'nlistp 'byte-compile-negated-op 'listp)
3588
3589 (defun byte-compile-negated (form)
3590   (byte-compile-form-do-effect (byte-compile-negation-optimizer form)))
3591
3592 ;; Even when optimization is off, atom is optimized to (not (consp ...)).
3593 (defun byte-compile-negation-optimizer (form)
3594   ;; an optimizer for forms where <form1> is less efficient than (not <form2>)
3595   (list 'not
3596     (cons (or (get (car form) 'byte-compile-negated-op)
3597               (error
3598                "Compiler error: `%s' has no `byte-compile-negated-op' property"
3599                (car form)))
3600           (cdr form))))
3601 \f
3602 ;;; other tricky macro-like special-forms
3603
3604 (byte-defop-compiler-1 catch)
3605 (byte-defop-compiler-1 unwind-protect)
3606 (byte-defop-compiler-1 condition-case)
3607 (byte-defop-compiler-1 save-excursion)
3608 (byte-defop-compiler-1 save-current-buffer)
3609 (byte-defop-compiler-1 save-restriction)
3610 (byte-defop-compiler-1 save-window-excursion)
3611 (byte-defop-compiler-1 with-output-to-temp-buffer)
3612 ;; no track-mouse.
3613
3614 (defun byte-compile-catch (form)
3615   (byte-compile-form (car (cdr form)))
3616   (byte-compile-push-constant
3617     (byte-compile-top-level (cons 'progn (cdr (cdr form))) for-effect))
3618   (byte-compile-out 'byte-catch 0))
3619
3620 (defun byte-compile-unwind-protect (form)
3621   (byte-compile-push-constant
3622    (byte-compile-top-level-body (cdr (cdr form)) t))
3623   (byte-compile-out 'byte-unwind-protect 0)
3624   (byte-compile-form-do-effect (car (cdr form)))
3625   (byte-compile-out 'byte-unbind 1))
3626
3627 ;;(defun byte-compile-track-mouse (form)
3628 ;;  (byte-compile-form
3629 ;;   (list
3630 ;;    'funcall
3631 ;;    (list 'quote
3632 ;;          (list 'lambda nil
3633 ;;                (cons 'track-mouse
3634 ;;                      (byte-compile-top-level-body (cdr form))))))))
3635
3636 (defun byte-compile-condition-case (form)
3637   (let* ((var (nth 1 form))
3638          (byte-compile-bound-variables
3639           (if var
3640               (cons (cons var 0)
3641                     (cons 'new-scope byte-compile-bound-variables))
3642             (cons 'new-scope byte-compile-bound-variables))))
3643     (or (symbolp var)
3644         (byte-compile-warn
3645          "%s is not a variable-name or nil (in condition-case)"
3646          (prin1-to-string var)))
3647     (byte-compile-push-constant var)
3648     (byte-compile-push-constant (byte-compile-top-level
3649                                  (nth 2 form) for-effect))
3650     (let ((clauses (cdr (cdr (cdr form))))
3651           compiled-clauses)
3652       (while clauses
3653         (let* ((clause (car clauses))
3654                (condition (car clause)))
3655           (cond ((not (or (symbolp condition)
3656                           (and (listp condition)
3657                                (let ((syms condition) (ok t))
3658                                  (while syms
3659                                    (if (not (symbolp (car syms)))
3660                                        (setq ok nil))
3661                                    (setq syms (cdr syms)))
3662                                  ok))))
3663                  (byte-compile-warn
3664                    "%s is not a symbol naming a condition or a list of such (in condition-case)"
3665                    (prin1-to-string condition)))
3666 ;;                ((not (or (eq condition 't)
3667 ;;                        (and (stringp (get condition 'error-message))
3668 ;;                             (consp (get condition 'error-conditions)))))
3669 ;;                 (byte-compile-warn
3670 ;;                   "%s is not a known condition name (in condition-case)"
3671 ;;                   condition))
3672                 )
3673           (setq compiled-clauses
3674                 (cons (cons condition
3675                             (byte-compile-top-level-body
3676                              (cdr clause) for-effect))
3677                       compiled-clauses)))
3678         (setq clauses (cdr clauses)))
3679       (byte-compile-push-constant (nreverse compiled-clauses)))
3680     (if (memq 'unused-vars byte-compile-warnings)
3681         ;; done compiling in this scope, warn now.
3682         (byte-compile-warn-about-unused-variables))
3683     (byte-compile-out 'byte-condition-case 0)))
3684
3685
3686 (defun byte-compile-save-excursion (form)
3687   (byte-compile-out 'byte-save-excursion 0)
3688   (byte-compile-body-do-effect (cdr form))
3689   (byte-compile-out 'byte-unbind 1))
3690
3691 (defun byte-compile-save-restriction (form)
3692   (byte-compile-out 'byte-save-restriction 0)
3693   (byte-compile-body-do-effect (cdr form))
3694   (byte-compile-out 'byte-unbind 1))
3695
3696 (defun byte-compile-save-current-buffer (form)
3697   (if (byte-compile-version-cond byte-compile-emacs19-compatibility)
3698       ;; `save-current-buffer' special form is not available in XEmacs 19.
3699       (byte-compile-form
3700        `(let ((_byte_compiler_save_buffer_emulation_closure_ (current-buffer)))
3701           (unwind-protect
3702               (progn ,@(cdr form))
3703             (and (buffer-live-p _byte_compiler_save_buffer_emulation_closure_)
3704                  (set-buffer _byte_compiler_save_buffer_emulation_closure_)))))
3705     (byte-compile-out 'byte-save-current-buffer 0)
3706     (byte-compile-body-do-effect (cdr form))
3707     (byte-compile-out 'byte-unbind 1)))
3708
3709 (defun byte-compile-save-window-excursion (form)
3710   (byte-compile-push-constant
3711    (byte-compile-top-level-body (cdr form) for-effect))
3712   (byte-compile-out 'byte-save-window-excursion 0))
3713
3714 (defun byte-compile-with-output-to-temp-buffer (form)
3715   (byte-compile-form (car (cdr form)))
3716   (byte-compile-out 'byte-temp-output-buffer-setup 0)
3717   (byte-compile-body (cdr (cdr form)))
3718   (byte-compile-out 'byte-temp-output-buffer-show 0))
3719
3720 \f
3721 ;;; top-level forms elsewhere
3722
3723 (byte-defop-compiler-1 defun)
3724 (byte-defop-compiler-1 defmacro)
3725 (byte-defop-compiler-1 defvar)
3726 (byte-defop-compiler-1 defvar   byte-compile-defvar-or-defconst)
3727 (byte-defop-compiler-1 defconst byte-compile-defvar-or-defconst)
3728 (byte-defop-compiler-1 autoload)
3729 ;; According to Mly this can go now that lambda is a macro
3730 ;(byte-defop-compiler-1 lambda byte-compile-lambda-form)
3731 (byte-defop-compiler-1 defalias)
3732 (byte-defop-compiler-1 define-function)
3733
3734 (defun byte-compile-defun (form)
3735   ;; This is not used for file-level defuns with doc strings.
3736   (byte-compile-two-args ; Use this to avoid byte-compile-fset's warning.
3737    (list 'fset (list 'quote (nth 1 form))
3738          (byte-compile-byte-code-maker
3739           (byte-compile-lambda (cons 'lambda (cdr (cdr form)))))))
3740   (byte-compile-discard)
3741   (byte-compile-constant (nth 1 form)))
3742
3743 (defun byte-compile-defmacro (form)
3744   ;; This is not used for file-level defmacros with doc strings.
3745   (byte-compile-body-do-effect
3746    (list (list 'fset (list 'quote (nth 1 form))
3747                (let ((code (byte-compile-byte-code-maker
3748                             (byte-compile-lambda
3749                              (cons 'lambda (cdr (cdr form)))))))
3750                  (if (eq (car-safe code) 'make-byte-code)
3751                      (list 'cons ''macro code)
3752                    (list 'quote (cons 'macro (eval code))))))
3753          (list 'quote (nth 1 form)))))
3754
3755 (defun byte-compile-defvar-or-defconst (form)
3756   ;; This is not used for file-level defvar/defconsts with doc strings:
3757   ;; byte-compile-file-form-defvar-or-defconst will be used in that case.
3758   ;; (defvar|defconst VAR [VALUE [DOCSTRING]])
3759   (let ((fun (nth 0 form))
3760         (var (nth 1 form))
3761         (value (nth 2 form))
3762         (string (nth 3 form)))
3763     (when (> (length form) 4)
3764       (byte-compile-warn
3765        "%s %s called with %d arguments, but accepts only %s"
3766        fun var (length (cdr form)) 3))
3767     (when (memq 'free-vars byte-compile-warnings)
3768       (push (cons var byte-compile-global-bit) byte-compile-bound-variables))
3769     (byte-compile-body-do-effect
3770      (list
3771       ;; Put the defined variable in this library's load-history entry
3772       ;; just as a real defvar would, but only in top-level forms.
3773       (when (null byte-compile-current-form)
3774         `(push ',var current-load-list))
3775       (when (> (length form) 3)
3776         (when (and string (not (stringp string)))
3777           (byte-compile-warn "Third arg to %s %s is not a string: %s"
3778                              fun var string))
3779         `(put ',var 'variable-documentation ,string))
3780       (if (cdr (cdr form))              ; `value' provided
3781           (if (eq fun 'defconst)
3782               ;; `defconst' sets `var' unconditionally.
3783               `(setq ,var ,value)
3784             ;; `defvar' sets `var' only when unbound.
3785             `(if (not (boundp ',var)) (setq ,var ,value))))
3786       `',var))))
3787
3788 (defun byte-compile-autoload (form)
3789   (and (byte-compile-constp (nth 1 form))
3790        (byte-compile-constp (nth 5 form))
3791        (memq (eval (nth 5 form)) '(t macro))  ; macro-p
3792        (not (fboundp (eval (nth 1 form))))
3793        (byte-compile-warn
3794         "The compiler ignores `autoload' except at top level.  You should
3795      probably put the autoload of the macro `%s' at top-level."
3796         (eval (nth 1 form))))
3797   (byte-compile-normal-call form))
3798
3799 ;; Lambda's in valid places are handled as special cases by various code.
3800 ;; The ones that remain are errors.
3801 ;; According to Mly this can go now that lambda is a macro
3802 ;(defun byte-compile-lambda-form (form)
3803 ;  (byte-compile-warn
3804 ;   "`lambda' used in function position is invalid: probably you mean #'%s"
3805 ;   (let ((print-escape-newlines t)
3806 ;        (print-level 4)
3807 ;        (print-length 4))
3808 ;     (prin1-to-string form)))
3809 ;  (byte-compile-normal-call
3810 ;   (list 'signal ''error
3811 ;        (list 'quote (list "`lambda' used in function position" form)))))
3812
3813 ;; Compile normally, but deal with warnings for the function being defined.
3814 (defun byte-compile-defalias (form)
3815   (if (and (consp (cdr form)) (consp (nth 1 form))
3816            (eq (car (nth 1 form)) 'quote)
3817            (consp (cdr (nth 1 form)))
3818            (symbolp (nth 1 (nth 1 form)))
3819            (consp (nthcdr 2 form))
3820            (consp (nth 2 form))
3821            (eq (car (nth 2 form)) 'quote)
3822            (consp (cdr (nth 2 form)))
3823            (symbolp (nth 1 (nth 2 form))))
3824       (progn
3825         (byte-compile-defalias-warn (nth 1 (nth 1 form))
3826                                     (nth 1 (nth 2 form)))
3827         (setq byte-compile-function-environment
3828               (cons (cons (nth 1 (nth 1 form))
3829                           (nth 1 (nth 2 form)))
3830                     byte-compile-function-environment))))
3831   (byte-compile-normal-call form))
3832
3833 (defun byte-compile-define-function (form)
3834   (byte-compile-defalias form))
3835
3836 ;; Turn off warnings about prior calls to the function being defalias'd.
3837 ;; This could be smarter and compare those calls with
3838 ;; the function it is being aliased to.
3839 (defun byte-compile-defalias-warn (new alias)
3840   (let ((calls (assq new byte-compile-unresolved-functions)))
3841     (if calls
3842         (setq byte-compile-unresolved-functions
3843               (delq calls byte-compile-unresolved-functions)))))
3844 \f
3845 ;;; tags
3846
3847 ;; Note: Most operations will strip off the 'TAG, but it speeds up
3848 ;; optimization to have the 'TAG as a part of the tag.
3849 ;; Tags will be (TAG . (tag-number . stack-depth)).
3850 (defun byte-compile-make-tag ()
3851   (list 'TAG (setq byte-compile-tag-number (1+ byte-compile-tag-number))))
3852
3853
3854 (defun byte-compile-out-tag (tag)
3855   (push tag byte-compile-output)
3856   (if (cdr (cdr tag))
3857       (progn
3858         ;; ## remove this someday
3859         (and byte-compile-depth
3860           (not (= (cdr (cdr tag)) byte-compile-depth))
3861           (error "Compiler bug: depth conflict at tag %d" (car (cdr tag))))
3862         (setq byte-compile-depth (cdr (cdr tag))))
3863     (setcdr (cdr tag) byte-compile-depth)))
3864
3865 (defun byte-compile-goto (opcode tag)
3866   (push (cons opcode tag) byte-compile-output)
3867   (setcdr (cdr tag) (if (memq opcode byte-goto-always-pop-ops)
3868                         (1- byte-compile-depth)
3869                       byte-compile-depth))
3870   (setq byte-compile-depth (and (not (eq opcode 'byte-goto))
3871                                 (1- byte-compile-depth))))
3872
3873 (defun byte-compile-out (opcode offset)
3874   (push (cons opcode offset) byte-compile-output)
3875   (case opcode
3876     (byte-call
3877      (setq byte-compile-depth (- byte-compile-depth offset)))
3878     (byte-return
3879      ;; This is actually an unnecessary case, because there should be
3880      ;; no more opcodes behind byte-return.
3881      (setq byte-compile-depth nil))
3882     (t
3883      (setq byte-compile-depth (+ byte-compile-depth
3884                                  (or (aref byte-stack+-info
3885                                            (symbol-value opcode))
3886                                      (- (1- offset))))
3887            byte-compile-maxdepth (max byte-compile-depth
3888                                       byte-compile-maxdepth))))
3889   ;;(if (< byte-compile-depth 0) (error "Compiler error: stack underflow"))
3890   )
3891
3892 \f
3893 ;;; call tree stuff
3894
3895 (defun byte-compile-annotate-call-tree (form)
3896   (let (entry)
3897     ;; annotate the current call
3898     (if (setq entry (assq (car form) byte-compile-call-tree))
3899         (or (memq byte-compile-current-form (nth 1 entry)) ;callers
3900             (setcar (cdr entry)
3901                     (cons byte-compile-current-form (nth 1 entry))))
3902       (push (list (car form) (list byte-compile-current-form) nil)
3903             byte-compile-call-tree))
3904     ;; annotate the current function
3905     (if (setq entry (assq byte-compile-current-form byte-compile-call-tree))
3906         (or (memq (car form) (nth 2 entry)) ;called
3907             (setcar (cdr (cdr entry))
3908                     (cons (car form) (nth 2 entry))))
3909       (push (list byte-compile-current-form nil (list (car form)))
3910             byte-compile-call-tree))))
3911
3912 ;; Renamed from byte-compile-report-call-tree
3913 ;; to avoid interfering with completion of byte-compile-file.
3914 ;;;###autoload
3915 (defun display-call-tree (&optional filename)
3916   "Display a call graph of a specified file.
3917 This lists which functions have been called, what functions called
3918 them, and what functions they call.  The list includes all functions
3919 whose definitions have been compiled in this Emacs session, as well as
3920 all functions called by those functions.
3921
3922 The call graph does not include macros, inline functions, or
3923 primitives that the byte-code interpreter knows about directly \(eq,
3924 cons, etc.\).
3925
3926 The call tree also lists those functions which are not known to be called
3927 \(that is, to which no calls have been compiled\), and which cannot be
3928 invoked interactively."
3929   (interactive)
3930   (message "Generating call tree...")
3931   (with-output-to-temp-buffer "*Call-Tree*"
3932     (set-buffer "*Call-Tree*")
3933     (erase-buffer)
3934     (message "Generating call tree... (sorting on %s)"
3935              byte-compile-call-tree-sort)
3936     (insert "Call tree for "
3937             (cond ((null byte-compile-current-file) (or filename "???"))
3938                   ((stringp byte-compile-current-file)
3939                    byte-compile-current-file)
3940                   (t (buffer-name byte-compile-current-file)))
3941             " sorted on "
3942             (prin1-to-string byte-compile-call-tree-sort)
3943             ":\n\n")
3944     (if byte-compile-call-tree-sort
3945         (setq byte-compile-call-tree
3946               (sort byte-compile-call-tree
3947                     (cond
3948                      ((eq byte-compile-call-tree-sort 'callers)
3949                       #'(lambda (x y) (< (length (nth 1 x))
3950                                          (length (nth 1 y)))))
3951                      ((eq byte-compile-call-tree-sort 'calls)
3952                       #'(lambda (x y) (< (length (nth 2 x))
3953                                          (length (nth 2 y)))))
3954                      ((eq byte-compile-call-tree-sort 'calls+callers)
3955                       #'(lambda (x y) (< (+ (length (nth 1 x))
3956                                             (length (nth 2 x)))
3957                                          (+ (length (nth 1 y))
3958                                             (length (nth 2 y))))))
3959                      ((eq byte-compile-call-tree-sort 'name)
3960                       #'(lambda (x y) (string< (car x)
3961                                                (car y))))
3962                      (t (error
3963                       "`byte-compile-call-tree-sort': `%s' - unknown sort mode"
3964                                byte-compile-call-tree-sort))))))
3965     (message "Generating call tree...")
3966     (let ((rest byte-compile-call-tree)
3967           (b (current-buffer))
3968           f p
3969           callers calls)
3970       (while rest
3971         (prin1 (car (car rest)) b)
3972         (setq callers (nth 1 (car rest))
3973               calls (nth 2 (car rest)))
3974         (insert "\t"
3975           (cond ((not (fboundp (setq f (car (car rest)))))
3976                  (if (null f)
3977                      " <top level>";; shouldn't insert nil then, actually -sk
3978                    " <not defined>"))
3979                 ((subrp (setq f (symbol-function f)))
3980                  " <subr>")
3981                 ((symbolp f)
3982                  (format " ==> %s" f))
3983                 ((compiled-function-p f)
3984                  "<compiled function>")
3985                 ((not (consp f))
3986                  "<malformed function>")
3987                 ((eq 'macro (car f))
3988                  (if (or (compiled-function-p (cdr f))
3989                          (assq 'byte-code (cdr (cdr (cdr f)))))
3990                      " <compiled macro>"
3991                    " <macro>"))
3992                 ((assq 'byte-code (cdr (cdr f)))
3993                  "<compiled lambda>")
3994                 ((eq 'lambda (car f))
3995                  "<function>")
3996                 (t "???"))
3997           (format " (%d callers + %d calls = %d)"
3998                   ;; Does the optimizer eliminate common subexpressions?-sk
3999                   (length callers)
4000                   (length calls)
4001                   (+ (length callers) (length calls)))
4002           "\n")
4003         (if callers
4004             (progn
4005               (insert "  called by:\n")
4006               (setq p (point))
4007               (insert "    " (if (car callers)
4008                                  (mapconcat 'symbol-name callers ", ")
4009                                "<top level>"))
4010               (let ((fill-prefix "    "))
4011                 (fill-region-as-paragraph p (point)))))
4012         (if calls
4013             (progn
4014               (insert "  calls:\n")
4015               (setq p (point))
4016               (insert "    " (mapconcat 'symbol-name calls ", "))
4017               (let ((fill-prefix "    "))
4018                 (fill-region-as-paragraph p (point)))))
4019         (insert "\n")
4020         (setq rest (cdr rest)))
4021
4022       (message "Generating call tree...(finding uncalled functions...)")
4023       (setq rest byte-compile-call-tree)
4024       (let ((uncalled nil))
4025         (while rest
4026           (or (nth 1 (car rest))
4027               (null (setq f (car (car rest))))
4028               (byte-compile-fdefinition f t)
4029               (commandp (byte-compile-fdefinition f nil))
4030               (setq uncalled (cons f uncalled)))
4031           (setq rest (cdr rest)))
4032         (if uncalled
4033             (let ((fill-prefix "  "))
4034               (insert "Noninteractive functions not known to be called:\n  ")
4035               (setq p (point))
4036               (insert (mapconcat 'symbol-name (nreverse uncalled) ", "))
4037               (fill-region-as-paragraph p (point)))))
4038       )
4039     (message "Generating call tree...done.")
4040     ))
4041
4042 \f
4043 ;;; by crl@newton.purdue.edu
4044 ;;;  Only works noninteractively.
4045 ;;;###autoload
4046 (defun batch-byte-compile ()
4047   "Run `byte-compile-file' on the files remaining on the command line.
4048 Use this from the command line, with `-batch';
4049 it won't work in an interactive Emacs.
4050 Each file is processed even if an error occurred previously.
4051 For example, invoke \"xemacs -batch -f batch-byte-compile $emacs/ ~/*.el\""
4052   ;; command-line-args-left is what is left of the command line (from
4053   ;; startup.el)
4054   (defvar command-line-args-left)       ;Avoid 'free variable' warning
4055   (if (not noninteractive)
4056       (error "`batch-byte-compile' is to be used only with -batch"))
4057   (let ((error nil))
4058     (while command-line-args-left
4059       (if (null (batch-byte-compile-one-file))
4060           (setq error t)))
4061     (message "Done")
4062     (kill-emacs (if error 1 0))))
4063
4064 ;;;###autoload
4065 (defun batch-byte-compile-one-file ()
4066   "Run `byte-compile-file' on a single file remaining on the command line.
4067 Use this from the command line, with `-batch';
4068 it won't work in an interactive Emacs."
4069   ;; command-line-args-left is what is left of the command line (from
4070   ;; startup.el)
4071   (defvar command-line-args-left)       ;Avoid 'free variable' warning
4072   (if (not noninteractive)
4073       (error "`batch-byte-compile-one-file' is to be used only with -batch"))
4074   (let (error
4075         (file-to-process (car command-line-args-left)))
4076     (setq command-line-args-left (cdr command-line-args-left))
4077     (if (file-directory-p (expand-file-name file-to-process))
4078         (let ((files (directory-files file-to-process))
4079               source dest)
4080           (while files
4081             (if (and (string-match emacs-lisp-file-regexp (car files))
4082                      (not (auto-save-file-name-p (car files)))
4083                      (setq source (expand-file-name
4084                                    (car files)
4085                                    file-to-process))
4086                      (setq dest (byte-compile-dest-file source))
4087                      (file-exists-p dest)
4088                      (file-newer-than-file-p source dest))
4089                 (if (null (batch-byte-compile-1 source))
4090                     (setq error t)))
4091             (setq files (cdr files)))
4092           (null error))
4093       (batch-byte-compile-1 file-to-process))))
4094
4095 (defun batch-byte-compile-1 (file)
4096   (condition-case err
4097       (progn (byte-compile-file file) t)
4098     (error
4099      (princ ">>Error occurred processing ")
4100      (princ file)
4101      (princ ": ")
4102      (if (fboundp 'display-error) ; XEmacs 19.8+
4103          (display-error err nil)
4104        (princ (or (get (car err) 'error-message) (car err)))
4105        (mapcar #'(lambda (x) (princ " ") (prin1 x)) (cdr err)))
4106      (princ "\n")
4107      nil)))
4108
4109 ;;;###autoload
4110 (defun batch-byte-recompile-directory-norecurse ()
4111   "Same as `batch-byte-recompile-directory' but without recursion."
4112   (setq byte-recompile-directory-recursively nil)
4113   (batch-byte-recompile-directory))
4114
4115 ;;;###autoload
4116 (defun batch-byte-recompile-directory ()
4117   "Runs `byte-recompile-directory' on the dirs remaining on the command line.
4118 Must be used only with `-batch', and kills Emacs on completion.
4119 For example, invoke `xemacs -batch -f batch-byte-recompile-directory .'."
4120   ;; command-line-args-left is what is left of the command line (startup.el)
4121   (defvar command-line-args-left)       ;Avoid 'free variable' warning
4122   (if (not noninteractive)
4123       (error "batch-byte-recompile-directory is to be used only with -batch"))
4124   (or command-line-args-left
4125       (setq command-line-args-left '(".")))
4126   (let ((byte-recompile-directory-ignore-errors-p t))
4127     (while command-line-args-left
4128       (byte-recompile-directory (car command-line-args-left))
4129       (setq command-line-args-left (cdr command-line-args-left))))
4130   (kill-emacs 0))
4131
4132 (make-obsolete 'elisp-compile-defun 'compile-defun)
4133 (make-obsolete 'byte-compile-report-call-tree 'display-call-tree)
4134
4135 ;; other make-obsolete calls in obsolete.el.
4136
4137 (provide 'byte-compile)
4138 (provide 'bytecomp)
4139
4140 \f
4141 ;;; report metering (see the hacks in bytecode.c)
4142
4143 (if (boundp 'byte-code-meter)
4144     (defun byte-compile-report-ops ()
4145       (defvar byte-code-meter)
4146       (with-output-to-temp-buffer "*Meter*"
4147         (set-buffer "*Meter*")
4148         (let ((i 0) n op off)
4149           (while (< i 256)
4150             (setq n (aref (aref byte-code-meter 0) i)
4151                   off nil)
4152             (if t ;(not (zerop n))
4153                 (progn
4154                   (setq op i)
4155                   (setq off nil)
4156                   (cond ((< op byte-nth)
4157                          (setq off (logand op 7))
4158                          (setq op (logand op 248)))
4159                         ((>= op byte-constant)
4160                          (setq off (- op byte-constant)
4161                                op byte-constant)))
4162                   (setq op (aref byte-code-vector op))
4163                   (insert (format "%-4d" i))
4164                   (insert (symbol-name op))
4165                   (if off (insert " [" (int-to-string off) "]"))
4166                   (indent-to 40)
4167                   (insert (int-to-string n) "\n")))
4168             (setq i (1+ i)))))))
4169
4170 \f
4171 ;; To avoid "lisp nesting exceeds max-lisp-eval-depth" when bytecomp compiles
4172 ;; itself, compile some of its most used recursive functions (at load time).
4173 ;;
4174 (eval-when-compile
4175  (or (compiled-function-p (symbol-function 'byte-compile-form))
4176      (assq 'byte-code (symbol-function 'byte-compile-form))
4177      (let ((byte-optimize nil) ; do it fast
4178            (byte-compile-warnings nil))
4179        (mapcar #'(lambda (x)
4180                    (or noninteractive (message "compiling %s..." x))
4181                    (byte-compile x)
4182                    (or noninteractive (message "compiling %s...done" x)))
4183                '(byte-compile-normal-call
4184                  byte-compile-form
4185                  byte-compile-body
4186                  ;; Inserted some more than necessary, to speed it up.
4187                  byte-compile-top-level
4188                  byte-compile-out-toplevel
4189                  byte-compile-constant
4190                  byte-compile-variable-ref))))
4191  nil)
4192
4193 ;;; bytecomp.el ends here