Merge remote-tracking branch 'origin/master' into for-steve
[sxemacs] / info / lispref / compile.texi
1 @c -*-texinfo-*-
2 @c This is part of the SXEmacs Lisp Reference Manual.
3 @c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
4 @c Copyright (C) 2005 Sebastian Freundt <hroptatyr@sxemacs.org>
5 @c See the file lispref.texi for copying conditions.
6 @setfilename ../../info/compile.info
7
8 @node Byte Compilation, Debugging, Loading, Top
9 @chapter Byte Compilation
10 @cindex byte-code
11 @cindex compilation
12
13   SXEmacs Lisp has a @dfn{compiler} that translates functions written
14 in elisp into a special representation called @dfn{byte-code} that can be
15 executed more efficiently.  The compiler replaces Lisp function
16 definitions with byte-code.  When a byte-coded function is called, its
17 definition is evaluated by the @dfn{byte-code interpreter}.
18
19   Because the byte-compiled code is evaluated by the byte-code
20 interpreter, instead of being executed directly by the machine's
21 hardware (as true compiled code is), byte-code is completely
22 transportable from machine to machine without recompilation.  It is not,
23 however, as fast as true compiled code.
24
25 In general, any version of ((S)X)Emacs can run byte-compiled code produced
26 by recent earlier versions of ((S)X)Emacs, but the reverse is not true.  In
27 particular, if you compile a program with SXEmacs 22, the compiled code
28 may not run in earlier versions of XEmacs.
29 Also byte-compiled code is not interchangable with different flavours of
30 Emacs, that is byte compiled code from SXEmacs may not run in FSF Emacs
31 and vice versa.
32
33 The first time a compiled-function object is executed, the byte-code
34 instructions are validated and the byte-code is further optimized.  An
35 @code{invalid-byte-code} error is signaled if the byte-code is invalid,
36 for example if it contains invalid opcodes.  This usually means a bug in
37 the byte compiler.
38
39 @iftex
40 @xref{Docs and Compilation}.
41 @end iftex
42
43   @xref{Compilation Errors}, for how to investigate errors occurring in
44 byte compilation.
45
46 @menu
47 * Speed of Byte-Code::          An example of speedup from byte compilation.
48 * Compilation Functions::       Byte compilation functions.
49 * Compilation Options::         Controlling the byte compiler's behavior.
50 * Docs and Compilation::        Dynamic loading of documentation strings.
51 * Dynamic Loading::             Dynamic loading of individual functions.
52 * Eval During Compile::         Code to be evaluated when you compile.
53 * Compiled-Function Objects::   The data type used for byte-compiled functions.
54 * Disassembly::                 Disassembling byte-code; how to read byte-code.
55 * Different Behaviour::         When compiled code gives different results.
56 @end menu
57
58
59 @node Speed of Byte-Code
60 @section Performance of Byte-Compiled Code
61
62   A byte-compiled function is not as efficient as a primitive function
63 written in C, but runs much faster than the version written in Lisp.
64 Here is an example:
65
66 @example
67 @group
68 (defun silly-loop (n)
69   "Return time before and after N iterations of a loop."
70   (let ((t1 (current-time-string)))
71     (while (> (setq n (- n 1))
72               0))
73     (list t1 (current-time-string))))
74 @result{} silly-loop
75 @end group
76
77 @group
78 (silly-loop 40000000)
79 @result{} ("Mon May  2 14:02:28 2005"
80     "Mon May  2 14:02:43 2005")  ; @r{15 seconds}
81 @end group
82
83 @group
84 (byte-compile 'silly-loop)
85 @result{} #<compiled-function
86 (n)
87 "...(23)"
88 [current-time-string t1 n 0]
89 2
90 "Return time before and after N iterations of a loop.">
91 @end group
92
93 @group
94 (silly-loop 40000000)
95 @result{} ("Mon May  2 14:03:24 2005"
96     "Mon May  2 14:03:29 2005")  ; @r{5 seconds}
97 @end group
98 @end example
99
100   In this example, the interpreted code required 15 seconds to run,
101 whereas the byte-compiled code required 5 seconds.  These results are
102 representative, but actual results will vary greatly.
103
104 Now of course, machines get faster, so efficiency differences is not
105 always this drastic.
106
107 Just compare to the old example:
108 @example
109 @group
110 (silly-loop 5000000)
111 @result{} ("Mon Sep 14 15:51:49 1998"
112     "Mon Sep 14 15:52:07 1998")  ; @r{18 seconds}
113 @end group
114
115 and evaluation 7 years later:
116 @group
117 (silly-loop 5000000)
118 @result{} ("Fri May  6 12:49:16 2005"
119     "Fri May  6 12:49:17 2005")  ; @r{1 second}
120 @end group
121 @end example
122
123   In this particular case, the byte-code version of @code{silly-loop}
124 would not be faster (within the resolution of whole seconds).
125
126
127 @node Compilation Functions
128 @comment  node-name,  next,  previous,  up
129 @section The Compilation Functions
130 @cindex compilation functions
131
132   You can byte-compile an individual function or macro definition with
133 the @code{byte-compile} function.  You can compile a whole file with
134 @code{byte-compile-file}, or several files with
135 @code{byte-recompile-directory} or @code{batch-byte-compile}.
136
137   When you run the byte compiler, you may get warnings in a buffer
138 called @samp{*Compile-Log*}.  These report things in your program that
139 suggest a problem but are not necessarily erroneous.
140
141 @cindex macro compilation
142   Be careful when byte-compiling code that uses macros.  Macro calls are
143 expanded when they are compiled, so the macros must already be defined
144 for proper compilation.  For more details, see @ref{Compiling Macros}.
145
146   Normally, compiling a file does not evaluate the file's contents or
147 load the file.  But it does execute any @code{require} calls at top
148 level in the file.  One way to ensure that necessary macro definitions
149 are available during compilation is to @code{require} the file that defines
150 them (@pxref{Named Features}).  To avoid loading the macro definition files
151 when someone @emph{runs} the compiled program, write
152 @code{eval-when-compile} around the @code{require} calls (@pxref{Eval
153 During Compile}).
154
155 @defun byte-compile symbol
156 This function byte-compiles the function definition of @var{symbol},
157 replacing the previous definition with the compiled one.  The function
158 definition of @var{symbol} must be the actual code for the function;
159 i.e., the compiler does not follow indirection to another symbol.
160 @code{byte-compile} returns the new, compiled definition of
161 @var{symbol}.
162
163   If @var{symbol}'s definition is a compiled-function object,
164 @code{byte-compile} does nothing and returns @code{nil}.  Lisp records
165 only one function definition for any symbol, and if that is already
166 compiled, non-compiled code is not available anywhere.  So there is no
167 way to ``compile the same definition again.''
168
169 @example
170 @group
171 (defun factorial (integer)
172   "Compute factorial of INTEGER."
173   (if (= 1 integer) 1
174     (* integer (factorial (1- integer)))))
175 @result{} factorial
176 @end group
177
178 @group
179 (byte-compile 'factorial)
180 @result{} #<compiled-function
181 (integer)
182 "...(21)"
183 [integer 1 factorial]
184 3
185 "Compute factorial of INTEGER.">
186 @end group
187 @end example
188
189 @noindent
190 The result is a compiled-function object.  The string it contains is
191 the actual byte-code; each character in it is an instruction or an
192 operand of an instruction.  The vector contains all the constants,
193 variable names and function names used by the function, except for
194 certain primitives that are coded as special instructions.
195 @end defun
196
197 @deffn Command compile-defun &optional arg
198 This command reads the defun containing point, compiles it, and
199 evaluates the result.  If you use this on a defun that is actually a
200 function definition, the effect is to install a compiled version of that
201 function.
202
203 @c SXEmacs feature
204 If @var{arg} is non-@code{nil}, the result is inserted in the current
205 buffer after the form; otherwise, it is printed in the minibuffer.
206 @end deffn
207
208 @deffn Command byte-compile-file filename &optional load
209 This function compiles a file of Lisp code named @var{filename} into
210 a file of byte-code.  The output file's name is made by appending
211 @samp{c} to the end of @var{filename}.
212
213 @c SXEmacs feature
214   If @code{load} is non-@code{nil}, the file is loaded after having been
215 compiled.
216
217 Compilation works by reading the input file one form at a time.  If it
218 is a definition of a function or macro, the compiled function or macro
219 definition is written out.  Other forms are batched together, then each
220 batch is compiled, and written so that its compiled code will be
221 executed when the file is read.  All comments are discarded when the
222 input file is read.
223
224 This command returns @code{t}.  When called interactively, it prompts
225 for the file name.
226
227 @example
228 @group
229 % ls -l push*
230 -rw-r--r--  1 lewis     791 Oct  5 20:31 push.el
231 @end group
232
233 @group
234 (byte-compile-file "~/emacs/push.el")
235      @result{} t
236 @end group
237
238 @group
239 % ls -l push*
240 -rw-r--r--  1 lewis     791 Oct  5 20:31 push.el
241 -rw-r--r--  1 lewis     638 Oct  8 20:25 push.elc
242 @end group
243 @end example
244 @end deffn
245
246 @c flag is not optional in FSF Emacs
247 @deffn Command byte-recompile-directory directory &optional flag norecursion force
248 @cindex library compilation
249 This function recompiles every @samp{.el} file in @var{directory} that
250 needs recompilation.  A file needs recompilation if a @samp{.elc} file
251 exists but is older than the @samp{.el} file.
252 Files in subdirectories of @var{directory} are processed depending on
253 the variable @code{byte-recompile-directory-recursively} (which is
254 @code{t} by default).
255
256 The optional second argument @var{flag} indicates what to do when a
257 @samp{.el} file has no corresponding @samp{.elc} file.
258 If it is @code{nil}, these files are ignored.
259 If it is non-@code{nil} or an integer greater than 0, the user is asked
260 whether to compile each such file.
261 If it is 0 or less, the file in question is compiled quietly, i.e. the
262 user is not asked.
263 Note: @var{flag} is not optional in FSF Emacs.
264
265 If the third optional argument @var{norecursion} is non-@code{nil},
266 files in subdirectories are not processed. This may be unnecessary
267 depending on the value of @code{byte-recompile-directory-recursively}.
268
269 If the fourth optional argument @var{force} is non-@code{nil},
270 recompile every @samp{.el} file that already has a @samp{.elc} file.
271
272 The return value of this command is unpredictable.
273 @end deffn
274
275 @defun batch-byte-compile
276 This function runs @code{byte-compile-file} on files specified on the
277 command line.  This function must be used only in a batch execution of
278 Emacs, as it kills Emacs on completion.  An error in one file does not
279 prevent processing of subsequent files.  (The file that gets the error
280 will not, of course, produce any compiled code.)
281
282 @example
283 % sxemacs -batch -f batch-byte-compile *.el
284 @end example
285 @end defun
286
287 @c SXEmacs feature
288 @defun batch-byte-recompile-directory
289   This function is similar to @code{batch-byte-compile} but runs the
290 command @code{byte-recompile-directory} on the files remaining on the
291 command line.
292 @end defun
293
294 @c SXEmacs feature
295 @defvar byte-recompile-directory-ignore-errors-p
296   When non-@code{nil}, @code{byte-recompile-directory} will continue
297 compiling even when an error occurs in a file.  Default: @code{nil}, but
298 bound to @code{t} by @code{batch-byte-recompile-directory}.
299 @end defvar
300
301 @c SXEmacs feature
302 @defvar byte-recompile-directory-recursively
303    When non-@code{nil}, @code{byte-recompile-directory} will recurse on
304 subdirectories.  Default: @code{t}.
305 @end defvar
306
307 @defun byte-code instructions constants stack-depth
308 @cindex byte-code interpreter
309 This function actually interprets byte-code.
310 Don't call this function yourself.  Only the byte compiler knows how to
311 generate valid calls to this function.
312
313 In all SXEmacs versions, and recent Emacs versions (19 and up), byte
314 code is usually executed as part of a compiled-function object, and only
315 rarely due to an explicit call to @code{byte-code}.  A byte-compiled
316 function was once actually defined with a body that calls
317 @code{byte-code}, but in recent versions of Emacs @code{byte-code} is
318 only used to run isolated fragments of lisp code without an associated
319 argument list.
320 @end defun
321
322
323 @node Compilation Options
324 @section Options for the Byte Compiler
325 @cindex compilation options
326
327 Warning: this node is a quick draft based on docstrings.  There may be
328 inaccuracies, as the docstrings occasionally disagree with each other.
329 This has not been checked yet.
330
331 The byte compiler and optimizer are controlled by the following
332 variables.  The @code{byte-compiler-options} macro described below
333 provides a convenient way to set most of them on a file-by-file basis.
334
335 @defvar emacs-lisp-file-regexp
336 Regexp which matches Emacs Lisp source files.
337 You may want to redefine @code{byte-compile-dest-file} if you change
338 this.  Default: @code{"\\.el$"}.
339 @end defvar
340
341 @defun byte-compile-dest-file filename
342 Convert an Emacs Lisp source file name to a compiled file name.  This
343 function may be redefined by the user, if necessary, for compatibility
344 with @code{emacs-lisp-file-regexp}.
345 @end defun
346
347 @c ;; This can be the 'byte-compile property of any symbol.
348 @c (autoload 'byte-compile-inline-expand "byte-optimize")
349
350 @defvar byte-compile-verbose
351 When non-@code{nil}, print messages describing progress of
352 byte-compiler.  Default: @code{t} if interactive on a not-too-slow
353 terminal (see @code{search-slow-speed}), otherwise @code{nil}.
354 @end defvar
355
356 @defvar byte-optimize
357 Level of optimization in the byte compiler.
358
359 @table @code
360 @item nil
361 Do no optimization.
362
363 @item t
364 Do all optimizations.
365
366 @item source
367 Do optimizations manipulating the source code only.
368
369 @item byte
370 Do optimizations manipulating the byte code (actually, LAP code) only.
371 @end table
372 Default: @code{t}.
373 @end defvar
374
375 @defvar byte-compile-delete-errors
376 When non-@code{nil}, the optimizer may delete forms that may signal an
377 error if that is the only change in the function's behavior.
378 This includes variable references and calls to functions such as
379 @code{car}.
380 Default: @code{t}.
381 @end defvar
382
383 @defvar byte-optimize-log nil
384 When non-@code{nil}, the byte-compiler logs optimizations into
385 @file{*Compile-Log*}.
386
387 @table @code
388 @item nil
389 Log no optimization.
390
391 @item t
392 Log all optimizations.
393
394 @item source
395 Log optimizations manipulating the source code only.
396
397 @item byte
398 Log optimizations manipulating the byte code (actually, LAP code) only.
399 @end table
400 Default: @code{nil}.
401 @end defvar
402
403 @defvar byte-compile-error-on-warn
404 When non-@code{nil}, the byte-compiler reports warnings with @code{error}.
405 Default:  @code{nil}.
406 @end defvar
407
408 @defvar byte-compile-default-warnings
409 The warnings used when @code{byte-compile-warnings} is @code{t}.  Called
410 @code{byte-compile-warning-types} in GNU Emacs.
411 Default: @code{(redefine callargs subr-callargs free-vars unresolved
412 unused-vars obsolete)}.
413 @end defvar
414
415 @defvar byte-compile-warnings
416 List of warnings that the compiler should issue (@code{t} for the
417 default set).  Elements of the list may be:
418
419 @table @code
420 @item free-vars
421 References to variables not in the current lexical scope.
422
423 @item unused-vars
424 References to non-global variables bound but not referenced.
425
426 @item unresolved
427 Calls to unknown functions.
428
429 @item callargs
430 Lambda calls with args that don't match the definition.
431
432 @item subr-callargs
433 Calls to subrs with args that don't match the definition.
434
435 @item redefine
436 Function cell redefined from a macro to a lambda or vice
437 versa, or redefined to take a different number of arguments.
438
439 @item obsolete
440 Use of an obsolete function or variable.
441
442 @item pedantic
443 Warn of use of compatible symbols.
444 @end table
445
446 The default set is specified by @code{byte-compile-default-warnings} and
447 normally encompasses all possible warnings.
448
449 See also the macro @code{byte-compiler-options}.  Default: @code{t}.
450 @end defvar
451
452 The compiler can generate a call graph, which gives information about
453 which functions call which functions.
454
455 @defvar byte-compile-generate-call-tree
456 When non-@code{nil}, the compiler generates a call graph.  This records
457 functions that were called and from where.  If the value is @code{t},
458 compilation displays the call graph when it finishes.  If the value is
459 neither @code{t} nor @code{nil}, compilation asks you whether to display
460 the graph.
461
462 The call tree only lists functions called, not macros used. Those
463 functions which the byte-code interpreter knows about directly
464 (@code{eq}, @code{cons}, etc.) are not reported.
465
466 The call tree also lists those functions which are not known to be called
467 (that is, to which no calls have been compiled).  Functions which can be
468 invoked interactively are excluded from this list.  Default: @code{nil}.
469 @end defvar
470
471 @defvar byte-compile-call-tree nil
472 Alist of functions and their call tree, used internally.
473 Each element takes the form
474
475   (@var{function} @var{callers} @var{calls})
476
477 where @var{callers} is a list of functions that call @var{function}, and
478 @var{calls} is a list of functions for which calls were generated while
479 compiling @var{function}.
480 @end defvar
481
482 @defvar byte-compile-call-tree-sort
483 When non-@code{nil}, sort the call tree.  The values @code{name},
484 @code{callers}, @code{calls}, and @code{calls+callers} specify different
485 fields to sort on.")  Default: @code{name}.
486 @end defvar
487
488 @code{byte-compile-overwrite-file} controls treatment of existing
489 compiled files.
490
491 @defvar byte-compile-overwrite-file
492 When non-@code{nil}, do not preserve backups of @file{.elc}s.
493 Precisely, if @code{nil}, old @file{.elc} files are deleted before the
494 new one is saved, and @file{.elc} files will have the same modes as the
495 corresponding @file{.el} file.  Otherwise, existing @file{.elc} files
496 will simply be overwritten, and the existing modes will not be changed.
497 If this variable is @code{nil}, then an @file{.elc} file which is a
498 symbolic link will be turned into a normal file, instead of the file
499 which the link points to being overwritten.  Default: @code{t}.
500 @end defvar
501
502 Variables controlling recompiling directories are described elsewhere
503 @xref{Compilation Functions}.  They are
504 @code{byte-recompile-directory-ignore-errors-p} and
505 @code{byte-recompile-directory-recursively}.
506
507 The dynamic loading features are described elsewhere.  These are
508 controlled by the variables @code{byte-compile-dynamic} (@pxref{Dynamic
509 Loading}) and @code{byte-compile-dynamic-docstrings} (@pxref{Docs and
510 Compilation}).
511
512 The byte compiler is a relatively recent development, and has evolved
513 significantly over the period covering Emacs versions 19 and 20.  The
514 following variables control use of newer functionality by the byte
515 compiler.  These are rarely needed since the release of SXEmacs 22.
516
517 Another set of compatibility issues arises between Mule and non-Mule
518 SXEmacsen; there are no known compatibility issues specific to the byte
519 compiler.  There are also compatibility issues between SXEmacs and GNU
520 Emacs's versions of the byte compiler.  While almost all of the byte
521 codes are the same, and code compiled by one version often runs
522 perfectly well on the other, this is very dangerous, and can result in
523 crashes or data loss.  Always recompile your Lisp when moving between
524 SXEmacs, XEmacs and GNU Emacs.
525
526 @ignore
527 @comment var void here -hroptatyr
528 @defvar byte-compile-single-version nil
529 When non-@code{nil}, the choice of emacs version (v19 or v20) byte-codes
530 will be hard-coded into bytecomp when it compiles itself.  If the
531 compiler itself is compiled with optimization, this causes a speedup.
532 Default: @code{nil}.
533 @end defvar
534 @end ignore
535
536 @defvar byte-compile-emacs19-compatibility
537 When non-@code{nil} generate output that can run in Emacs 19.
538 Default: @code{nil}
539 @end defvar
540
541 @defvar byte-compile-print-gensym
542 When non-@code{nil}, the compiler may generate code that creates unique
543 symbols at run-time.  This is achieved by printing uninterned symbols
544 using the @code{#:@var{}} notation, so that they will be read uninterned
545 when run.
546
547 Default: When @code{byte-compile-emacs19-compatibility} is non-nil, this
548 variable is ignored and considered to be @code{nil}.  Otherwise
549 @code{t}.
550 @end defvar
551
552 @defvar byte-compile-new-bytecodes
553 This is completely ignored.  For backwards compatibility.
554 @end defvar
555
556 @defun byte-compiler-options &rest args
557 Set some compilation-parameters for this file.
558 This will affect only the file in which it appears; this does nothing when
559 evaluated, or when loaded from a @file{.el} file.
560
561 Each argument to this macro must be a list of a key and a value.
562 (#### Need to check whether the newer variables are settable here.)
563
564 @example
565   Keys:           Values:               Corresponding variable:
566
567   verbose         t, nil                byte-compile-verbose
568   optimize        t, nil, source, byte  byte-optimize
569   warnings        list of warnings      byte-compile-warnings
570   file-format     emacs19, emacs20      byte-compile-emacs19-compatibility
571 @end example
572
573 The value specified with the @code{warnings}option must be a list,
574 containing some subset of the following flags:
575
576 @example
577   free-vars     references to variables not in the current lexical scope.
578   unused-vars   references to non-global variables bound but not referenced.
579   unresolved    calls to unknown functions.
580   callargs      lambda calls with args that don't match the definition.
581   redefine      function cell redefined from a macro to a lambda or vice
582                 versa, or redefined to take a different number of arguments.
583 @end example
584
585 If the first element if the list is @code{+} or `@code{} then the
586 specified elements are added to or removed from the current set of
587 warnings, instead of the entire set of warnings being overwritten.
588 (#### Need to check whether the newer warnings are settable here.)
589
590 For example, something like this might appear at the top of a source file:
591
592 @example
593     (byte-compiler-options
594       (optimize t)
595       (warnings (- callargs))           ; Don't warn about arglist mismatch
596       (warnings (+ unused-vars))        ; Do warn about unused bindings
597       (file-format emacs19))
598 @end example
599 @end defun
600
601
602 @node Docs and Compilation
603 @section Documentation Strings and Compilation
604 @cindex dynamic loading of documentation
605
606   Functions and variables loaded from a byte-compiled file access their
607 documentation strings dynamically from the file whenever needed.  This
608 saves space within Emacs, and makes loading faster because the
609 documentation strings themselves need not be processed while loading the
610 file.  Actual access to the documentation strings becomes slower as a
611 result, but normally not enough to bother users.
612
613   Dynamic access to documentation strings does have drawbacks:
614
615 @itemize @bullet
616 @item
617 If you delete or move the compiled file after loading it, SXEmacs can no
618 longer access the documentation strings for the functions and variables
619 in the file.
620
621 @item
622 If you alter the compiled file (such as by compiling a new version),
623 then further access to documentation strings in this file will give
624 nonsense results.
625 This will often show as documentation strings moved by a certain offset.
626 @end itemize
627
628   If your site installs SXEmacs following the usual procedures, these
629 problems will never normally occur.  Installing a new version uses a new
630 directory with a different name; as long as the old version remains
631 installed, its files will remain unmodified in the places where they are
632 expected to be.
633
634   However, if you have built SXEmacs yourself and use it from the
635 directory where you built it, you will experience this problem
636 occasionally if you edit and recompile Lisp files.  When it happens, you
637 can cure the problem by reloading the file after recompiling it.
638
639   Versions of Emacs up to and including XEmacs 19.14 and FSF Emacs 19.28
640 do not support the dynamic docstrings feature, and so will not be able
641 to load bytecode created by more recent Emacs versions.  You can turn
642 off the dynamic docstring feature by setting
643 @code{byte-compile-dynamic-docstrings} to @code{nil}.
644
645 Once this is done, you can compile files that will load into older Emacs
646 versions. You can do this globally, or for one source file by specifying
647 a file-local binding for the variable.  Here's one way to do that:
648
649 @example
650 -*-byte-compile-dynamic-docstrings: nil;-*-
651 @end example
652
653 @defvar byte-compile-dynamic-docstrings
654 If this is non-@code{nil}, the byte compiler generates compiled files
655 that are set up for dynamic loading of documentation strings.
656 Default: t.
657 @end defvar
658
659 @cindex @samp{#@@@var{count}}
660 @cindex @samp{#$}
661   The dynamic documentation string feature writes compiled files that
662 use a special Lisp reader construct, @samp{#@@@var{count}}.  This
663 construct skips the next @var{count} characters.  It also uses the
664 @samp{#$} construct, which stands for ``the name of this file, as a
665 string.''  It is best not to use these constructs in Lisp source files.
666
667
668 @node Dynamic Loading
669 @section Dynamic Loading of Individual Functions
670
671 @cindex dynamic loading of functions
672 @cindex lazy loading
673   When you compile a file, you can optionally enable the @dfn{dynamic
674 function loading} feature (also known as @dfn{lazy loading}).  With
675 dynamic function loading, loading the file doesn't fully read the
676 function definitions in the file.  Instead, each function definition
677 contains a place-holder which refers to the file.  The first time each
678 function is called, it reads the full definition from the file, to
679 replace the place-holder.
680
681   The advantage of dynamic function loading is that loading the file
682 becomes much faster.  This is a good thing for a file which contains
683 many separate commands, provided that using one of them does not imply
684 you will soon (or ever) use the rest.  A specialized mode which provides
685 many keyboard commands often has that usage pattern: a user may invoke
686 the mode, but use only a few of the commands it provides.
687
688   The dynamic loading feature has certain disadvantages:
689
690 @itemize @bullet
691 @item
692 If you delete or move the compiled file after loading it, SXEmacs can no
693 longer load the remaining function definitions not already loaded.
694
695 @item
696 If you alter the compiled file (such as by compiling a new version),
697 then trying to load any function not already loaded will get nonsense
698 results.
699 @end itemize
700
701   If you compile a new version of the file, the best thing to do is
702 immediately load the new compiled file.  That will prevent any future
703 problems.
704
705   The byte compiler uses the dynamic function loading feature if the
706 variable @code{byte-compile-dynamic} is non-@code{nil} at compilation
707 time.  Do not set this variable globally, since dynamic loading is
708 desirable only for certain files.  Instead, enable the feature for
709 specific source files with file-local variable bindings, like this:
710
711 @example
712 -*-byte-compile-dynamic: t;-*-
713 @end example
714
715 @defvar byte-compile-dynamic
716 If this is non-@code{nil}, the byte compiler generates compiled files
717 that are set up for dynamic function loading.
718 Default: nil.
719 @end defvar
720
721 @defun fetch-bytecode function
722 This immediately finishes loading the definition of @var{function} from
723 its byte-compiled file, if it is not fully loaded already.  The argument
724 @var{function} may be a compiled-function object or a function name.
725 @end defun
726
727
728 @node Eval During Compile
729 @section Evaluation During Compilation
730
731   These features permit you to write code to be evaluated during
732 compilation of a program.
733
734 @defspec eval-and-compile body
735 This form marks @var{body} to be evaluated both when you compile the
736 containing code and when you run it (whether compiled or not).
737
738 You can get a similar result by putting @var{body} in a separate file
739 and referring to that file with @code{require}.  Using @code{require} is
740 preferable if there is a substantial amount of code to be executed in
741 this way.
742 @end defspec
743
744 @defspec eval-when-compile body
745 This form marks @var{body} to be evaluated at compile time and not when
746 the compiled program is loaded.  The result of evaluation by the
747 compiler becomes a constant which appears in the compiled program.  When
748 the program is interpreted, not compiled at all, @var{body} is evaluated
749 normally.
750
751 At top level, this is analogous to the Common Lisp idiom
752 @code{(eval-when (compile eval) @dots{})}.  Elsewhere, the Common Lisp
753 @samp{#.} reader macro (but not when interpreting) is closer to what
754 @code{eval-when-compile} does.
755 @end defspec
756
757
758 @node Compiled-Function Objects
759 @section Compiled-Function Objects
760 @cindex compiled function
761 @cindex byte-code function
762
763   Byte-compiled functions have a special data type: they are
764 @dfn{compiled-function objects}. The evaluator handles this data type
765 specially when it appears as a function to be called.
766
767   The printed representation for a compiled-function object normally
768 begins with @samp{#<compiled-function} and ends with @samp{>}.  However,
769 if the variable @code{print-readably} is non-@code{nil}, the object is
770 printed beginning with @samp{#[} and ending with @samp{]}.  This
771 representation can be read directly by the Lisp reader, and is used in
772 byte-compiled files (those ending in @samp{.elc}).
773
774   In Emacs version 18, there was no compiled-function object data type;
775 compiled functions used the function @code{byte-code} to run the byte
776 code.
777
778   A compiled-function object has a number of different attributes.
779 They are:
780
781 @table @var
782 @item arglist
783 The list of argument symbols.
784
785 @item instructions
786 The string containing the byte-code instructions.
787
788 @item constants
789 The vector of Lisp objects referenced by the byte code.  These include
790 symbols used as function names and variable names.
791
792 @item stack-depth
793 The maximum stack size this function needs.
794
795 @item doc-string
796 The documentation string (if any); otherwise, @code{nil}.  The value may
797 be a number or a list, in case the documentation string is stored in a
798 file.  Use the function @code{documentation} to get the real
799 documentation string (@pxref{Accessing Documentation}).
800
801 @item interactive
802 The interactive spec (if any).  This can be a string or a Lisp
803 expression.  It is @code{nil} for a function that isn't interactive.
804
805 @item domain
806 The domain (if any).  This is only meaningful if I18N3 (message-translation)
807 support was compiled into SXEmacs.  This is a string defining which
808 domain to find the translation for the documentation string and
809 interactive prompt.  @xref{Domain Specification}.
810 @end table
811
812 Here's an example of a compiled-function object, in printed
813 representation.  It is the definition of the command
814 @code{backward-sexp}.
815
816 @example
817 (symbol-function 'backward-sexp)
818 @result{} #<compiled-function
819 (&optional arg)
820 "...(15)" [arg 1 forward-sexp] 2 854740 "_p">
821 @end example
822
823   The primitive way to create a compiled-function object is with
824 @code{make-byte-code}:
825
826 @defun make-byte-code arglist instructions constants stack-depth &optional doc-string interactive
827 This function constructs and returns a compiled-function object
828 with the specified attributes.
829
830 @emph{Please note:} Unlike all other elisp functions, calling this with
831 five arguments is @emph{not} the same as calling it with six arguments,
832 the last of which is @code{nil}.  If the @var{interactive} arg is
833 specified as @code{nil}, then that means that this function was defined
834 with @code{(interactive)}.  If the arg is not specified, then that means
835 the function is not interactive.  This is terrible behavior which is
836 retained for compatibility with old @samp{.elc} files which expected
837 these semantics.
838 @end defun
839
840   You should not try to come up with the elements for a compiled-function
841 object yourself, because if they are inconsistent, SXEmacs may crash
842 when you call the function.  Always leave it to the byte compiler to
843 create these objects; it makes the elements consistent (we hope).
844
845   The following primitives are provided for accessing the elements of
846 a compiled-function object.
847
848 @defun compiled-function-arglist function
849 This function returns the argument list of compiled-function object
850 @var{function}.
851 @end defun
852
853 @defun compiled-function-instructions function
854 This function returns a string describing the byte-code instructions
855 of compiled-function object @var{function}.
856 @end defun
857
858 @defun compiled-function-constants function
859 This function returns the vector of Lisp objects referenced by
860 compiled-function object @var{function}.
861 @end defun
862
863 @defun compiled-function-stack-depth function
864 This function returns the maximum stack size needed by compiled-function
865 object @var{function}.
866 @end defun
867
868 @defun compiled-function-doc-string function
869 This function returns the doc string of compiled-function object
870 @var{function}, if available.
871 @end defun
872
873 @defun compiled-function-interactive function
874 This function returns the interactive spec of compiled-function object
875 @var{function}, if any.  The return value is @code{nil} or a two-element
876 list, the first element of which is the symbol @code{interactive} and
877 the second element is the interactive spec (a string or Lisp form).
878 @end defun
879
880 @defun compiled-function-domain function
881 This function returns the domain of compiled-function object
882 @var{function}, if any.  The result will be a string or @code{nil}.
883 @xref{Domain Specification}.
884 @end defun
885
886 @node Disassembly
887 @section Disassembled Byte-Code
888 @cindex disassembled byte-code
889
890   People do not write byte-code; that job is left to the byte compiler.
891 But we provide a disassembler to satisfy a cat-like curiosity.  The
892 disassembler converts the byte-compiled code into humanly readable
893 form.
894
895   The byte-code interpreter is implemented as a simple stack machine.
896 It pushes values onto a stack of its own, then pops them off to use them
897 in calculations whose results are themselves pushed back on the stack.
898 When a byte-code function returns, it pops a value off the stack and
899 returns it as the value of the function.
900
901   In addition to the stack, byte-code functions can use, bind, and set
902 ordinary Lisp variables, by transferring values between variables and
903 the stack.
904
905 @deffn Command disassemble object &optional stream
906 This function prints the disassembled code for @var{object}.  If
907 @var{stream} is supplied, then output goes there.  Otherwise, the
908 disassembled code is printed to the stream @code{standard-output}.  The
909 argument @var{object} can be a function name or a lambda expression.
910
911 As a special exception, if this function is used interactively,
912 it outputs to a buffer named @samp{*Disassemble*}.
913 @end deffn
914
915   Here are two examples of using the @code{disassemble} function.  We
916 have added explanatory comments to help you relate the byte-code to the
917 Lisp source; these do not appear in the output of @code{disassemble}.
918
919 @example
920 @group
921 (defun factorial (integer)
922   "Compute factorial of an integer."
923   (if (= 1 integer) 1
924     (* integer (factorial (1- integer)))))
925      @result{} factorial
926 @end group
927
928 @group
929 (factorial 4)
930      @result{} 24
931 @end group
932
933 @group
934 (disassemble 'factorial)
935      @print{} byte-code for factorial:
936  doc: Compute factorial of an integer.
937  args: (integer)
938 @end group
939
940 @group
941 0   varref   integer        ; @r{Get value of @code{integer}}
942                             ;   @r{from the environment}
943                             ;   @r{and push the value}
944                             ;   @r{onto the stack.}
945
946 1   constant 1              ; @r{Push 1 onto stack.}
947 @end group
948
949 @group
950 2   eqlsign                 ; @r{Pop top two values off stack,}
951                             ;   @r{compare them,}
952                             ;   @r{and push result onto stack.}
953 @end group
954
955 @group
956 3   goto-if-nil 1           ; @r{Pop and test top of stack;}
957                             ;   @r{if @code{nil},}
958                             ;   @r{go to label 1 (which is also byte 7),}
959                             ;   @r{else continue.}
960 @end group
961
962 @group
963 5   constant 1              ; @r{Push 1 onto top of stack.}
964
965 6   return                  ; @r{Return the top element}
966                             ;   @r{of the stack.}
967 @end group
968
969 7:1 varref   integer        ; @r{Push value of @code{integer} onto stack.}
970
971 @group
972 8   constant factorial      ; @r{Push @code{factorial} onto stack.}
973
974 9   varref   integer        ; @r{Push value of @code{integer} onto stack.}
975
976 10  sub1                    ; @r{Pop @code{integer}, decrement value,}
977                             ;   @r{push new value onto stack.}
978 @end group
979
980 @group
981                             ; @r{Stack now contains:}
982                             ;   @minus{} @r{decremented value of @code{integer}}
983                             ;   @minus{} @r{@code{factorial}}
984                             ;   @minus{} @r{value of @code{integer}}
985 @end group
986
987 @group
988 15  call     1              ; @r{Call function @code{factorial} using}
989                             ;   @r{the first (i.e., the top) element}
990                             ;   @r{of the stack as the argument;}
991                             ;   @r{push returned value onto stack.}
992 @end group
993
994 @group
995                             ; @r{Stack now contains:}
996                             ;   @minus{} @r{result of recursive}
997                             ;        @r{call to @code{factorial}}
998                             ;   @minus{} @r{value of @code{integer}}
999 @end group
1000
1001 @group
1002 12  mult                    ; @r{Pop top two values off the stack,}
1003                             ;   @r{multiply them,}
1004                             ;   @r{pushing the result onto the stack.}
1005 @end group
1006
1007 @group
1008 13  return                  ; @r{Return the top element}
1009                             ;   @r{of the stack.}
1010      @result{} nil
1011 @end group
1012 @end example
1013
1014 The @code{silly-loop} function is somewhat more complex:
1015
1016 @example
1017 @group
1018 (defun silly-loop (n)
1019   "Return time before and after N iterations of a loop."
1020   (let ((t1 (current-time-string)))
1021     (while (> (setq n (1- n))
1022               0))
1023     (list t1 (current-time-string))))
1024      @result{} silly-loop
1025 @end group
1026
1027 @group
1028 (disassemble 'silly-loop)
1029      @print{} byte-code for silly-loop:
1030  doc: Return time before and after N iterations of a loop.
1031  args: (n)
1032
1033 0   constant current-time-string  ; @r{Push}
1034                                   ;   @r{@code{current-time-string}}
1035                                   ;   @r{onto top of stack.}
1036 @end group
1037
1038 @group
1039 1   call     0              ; @r{Call @code{current-time-string}}
1040                             ;   @r{ with no argument,}
1041                             ;   @r{ pushing result onto stack.}
1042 @end group
1043
1044 @group
1045 2   varbind  t1             ; @r{Pop stack and bind @code{t1}}
1046                             ;   @r{to popped value.}
1047 @end group
1048
1049 @group
1050 3:1 varref   n              ; @r{Get value of @code{n} from}
1051                             ;   @r{the environment and push}
1052                             ;   @r{the value onto the stack.}
1053 @end group
1054
1055 @group
1056 4   sub1                    ; @r{Subtract 1 from top of stack.}
1057 @end group
1058
1059 @group
1060 5   dup                     ; @r{Duplicate the top of the stack;}
1061                             ;   @r{i.e., copy the top of}
1062                             ;   @r{the stack and push the}
1063                             ;   @r{copy onto the stack.}
1064
1065 6   varset   n              ; @r{Pop the top of the stack,}
1066                             ;   @r{and set @code{n} to the value.}
1067
1068                             ; @r{In effect, the sequence @code{dup varset}}
1069                             ;   @r{copies the top of the stack}
1070                             ;   @r{into the value of @code{n}}
1071                             ;   @r{without popping it.}
1072 @end group
1073
1074 @group
1075 7   constant 0              ; @r{Push 0 onto stack.}
1076
1077 8   gtr                     ; @r{Pop top two values off stack,}
1078                             ;   @r{test if @var{n} is greater than 0}
1079                             ;   @r{and push result onto stack.}
1080 @end group
1081
1082 @group
1083 9   goto-if-not-nil 1       ; @r{Goto label 1 (byte 3) if @code{n} <= 0}
1084                             ;   @r{(this exits the while loop).}
1085                             ;   @r{else pop top of stack}
1086                             ;   @r{and continue}
1087 @end group
1088
1089 @group
1090 11  varref   t1             ; @r{Push value of @code{t1} onto stack.}
1091 @end group
1092
1093 @group
1094 12  constant current-time-string  ; @r{Push}
1095                                   ;   @r{@code{current-time-string}}
1096                                   ;   @r{onto top of stack.}
1097 @end group
1098
1099 @group
1100 13  call     0              ; @r{Call @code{current-time-string} again.}
1101
1102 14  unbind   1              ; @r{Unbind @code{t1} in local environment.}
1103 @end group
1104
1105 @group
1106 15  list2                   ; @r{Pop top two elements off stack,}
1107                             ;   @r{create a list of them,}
1108                             ;   @r{and push list onto stack.}
1109 @end group
1110
1111 @group
1112 16  return                  ; @r{Return the top element of the stack.}
1113
1114      @result{} nil
1115 @end group
1116 @end example
1117
1118
1119 @node Different Behaviour
1120 @section Different Behaviour
1121
1122 The intent is that compiled byte-code and the corresponding code
1123 executed by the Lisp interpreter produce identical results.  However,
1124 there are some circumstances where the results will differ.
1125
1126 @itemize @bullet
1127 @item
1128 Arithmetic operations may be rearranged for efficiency or compile-time
1129 evaluation.  When floating point numbers are involved, this may produce
1130 different values or an overflow.
1131 @item
1132 Some arithmetic operations may be optimized away.  For example, the
1133 expression @code{(+ x)} may be optimized to simply @code{x}.  If the
1134 value of @code{x} is a marker, then the value will be a marker instead
1135 of an integer.  If the value of @samp{x} is a cons cell, then the
1136 interpreter will issue an error, while the bytecode will not.
1137
1138 If you're trying to use @samp{(+ @var{object} 0)} to convert
1139 @var{object} to integer, consider using an explicit conversion function,
1140 which is clearer and guaranteed to work.
1141 Instead of @samp{(+ @var{marker} 0)}, use @samp{(marker-position @var{marker})}.
1142 Instead of @samp{(+ @var{char} 0)}, use @samp{(char-int @var{char})}.
1143 @end itemize
1144
1145 For maximal equivalence between interpreted and compiled code, the
1146 variables @code{byte-compile-delete-errors} and
1147 @code{byte-compile-optimize} can be set to @code{nil}, but this is not
1148 recommended.