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