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