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