Byte Compilation
****************

GNU Emacs Lisp has a compiler that translates functions written in Lisp into a special representation called byte-code that can be executed more efficiently.  The compiler replaces Lisp function definitions with byte-code.  When a byte-code function is called, its definition is evaluated by the byte-code interpreter.

Because the byte-compiled code is evaluated by the byte-code interpreter, instead of being executed directly by the machine's hardware (as true compiled code is), byte-code is completely transportable from machine to machine without recompilation.  It is not, however, as fast as true compiled code.

In general, any version of Emacs can run byte-compiled code produced by recent earlier versions of Emacs, but the reverse is not true.  In particular, if you compile a program with Emacs 18, you can run the compiled code in Emacs 19, but not vice versa.

See Compilation Errors, for how to investigate errors occurring in byte compilation.

The Compilation Functions
=========================

You can byte-compile an individual function or macro definition with the byte-compile function.  You can compile a whole file with byte-compile-file, or several files with byte-recompile-directory or batch-byte-compile.

When you run the byte compiler, you may get warnings in a buffer called *Compile-Log*.  These report usage in your program that suggest a problem, but are not necessarily erroneous.

Be careful when byte-compiling code that uses macros.  Macro calls are expanded when they are compiled, so the macros must already be defined for proper compilation.  For more details, see Compiling Macros.

While byte-compiling a file, any require calls at top-level are executed.  One way to ensure that necessary macro definitions are available during compilation is to require the file that defines them. See Features.

A byte-compiled function is not as efficient as a primitive function written in C, but runs much faster than the version written in Lisp. For a rough comparison, consider the example below:

     (defun silly-loop (n)
       "Return time before and after N iterations of a loop."
       (let ((t1 (current-time-string)))
         (while (> (setq n (1- n))
                   0))
         (list t1 (current-time-string))))
     => silly-loop

     (silly-loop 100000)
     => ("Thu Jan 12 20:18:38 1989"
         "Thu Jan 12 20:19:29 1989")  ; 51 seconds

     (byte-compile 'silly-loop)
     => [Compiled code not shown]

     (silly-loop 100000)
     => ("Thu Jan 12 20:21:04 1989"
         "Thu Jan 12 20:21:17 1989")  ; 13 seconds

In this example, the interpreted code required 51 seconds to run, whereas the byte-compiled code required 13 seconds.  These results are representative, but actual results will vary greatly.

 -- Function: byte-compile symbol
     This function byte-compiles the function definition of SYMBOL, replacing the previous definition with the compiled one.  The function definition of SYMBOL must be the actual code for the function; i.e., the compiler does not follow indirection to another symbol. byte-compile does not compile macros.  byte-compile returns the new, compiled definition of SYMBOL.

          (defun factorial (integer)
            "Compute factorial of INTEGER."
            (if (= 1 integer) 1
              (* integer (factorial (1- integer)))))
               => factorial

          (byte-compile 'factorial)
               =>
          #[(integer)
            "^H\301U\203^H^@\301\207\302^H\303^HS!\"\207"
            [integer 1 * factorial]
            4 "Compute factorial of INTEGER."]

     The result is a compiled function object.  The string it contains is the actual byte-code; each character in it is an instruction.  The vector contains all the constants, variable names and function names used by the function, except for certain primitives that are coded as special instructions.

 -- Command: compile-defun
     This command reads the defun containing point, compiles it, and evaluates the result.  If you use this on a defun that is actually a function definition, the effect is to install a compiled version of that function.

 -- Command: byte-compile-file filename
     This function compiles a file of Lisp code named FILENAME into a file of byte-code.  The output file's name is made by appending c to the end of FILENAME.

     Compilation works by reading the input file one form at a time.  If it is a definition of a function or macro, the compiled function or macro definition is written out.  Other forms are batched together, then each batch is compiled, and written so that its compiled code will be executed when the file is read.  All comments are discarded when the input file is read.

     This command returns t.  When called interactively, it prompts for the file name.

          % ls -l push*
          -rw-r--r--  1 lewis     791 Oct  5 20:31 push.el

          (byte-compile-file "~/emacs/push.el")
               => t

          % ls -l push*
          -rw-r--r--  1 lewis     791 Oct  5 20:31 push.el
          -rw-rw-rw-  1 lewis     638 Oct  8 20:25 push.elc

 -- Command: byte-recompile-directory directory flag
     This function recompiles every .el file in DIRECTORY that needs recompilation.  A file needs recompilation if a .elc file exists but is older than the .el file.

     If a .el file exists, but there is no corresponding .elc file, then FLAG is examined.  If it is nil, the file is ignored.  If it is non-nil, the user is asked whether the file should be compiled.

     The returned value of this command is unpredictable.

 -- Function: batch-byte-compile
     This function runs byte-compile-file on the files remaining on the command line.  This function must be used only in a batch execution of Emacs, as it kills Emacs on completion.  An error in one file does not prevent processing of subsequent files.  (The file which gets the error will not, of course, produce any compiled code.)

          % emacs -batch -f batch-byte-compile *.el

 -- Function: byte-code code-string data-vector max-stack
     This function actually interprets byte-code.  A byte-compiled function is actually defined with a body that calls byte-code.  Don't call this function yourself.  Only the byte compiler knows how to generate valid calls to this function.

     In newer Emacs versions (19 and up), byte-code is usually executed as part of a compiled function object, and only rarely as part of a call to byte-code.

Evaluation During Compilation
=============================

These features permit you to write code to be evaluated during compilation of a program.

 -- Special Form: eval-and-compile body
     This form marks BODY to be evaluated both when you compile the containing code and when you run it (whether compiled or not).

     You can get a similar result by putting BODY in a separate file and referring to that file with require.  Using require is preferable if there is a substantial amount of code to be executed in this way.

 -- Special Form: eval-when-compile body
     This form marks BODY to be evaluated at compile time only. The result of evaluation by the compiler becomes a constant which appears in the compiled program.  When the program is interpreted, not compiled at all, BODY is evaluated normally.

     At top-level, this is analogous to the Common Lisp idiom (eval-when (compile eval) ...).  Elsewhere, the Common Lisp #. reader macro (but not when interpreting) is closer to what eval-when-compile does.

Byte-Code Objects
=================

Byte-compiled functions have a special data type: they are byte-code function objects.

Internally, a byte-code function object is much like a vector; however, the evaluator handles this data type specially when it appears as a function to be called.  The printed representation for a byte-code function object is like that for a vector, with an additional # before the opening [.

In Emacs version 18, there was no byte-code function object data type; compiled functions used the function byte-code to run the byte code.

A byte-code function object must have at least four elements; there is no maximum number, but only the first six elements are actually used. They are:

arglist
     The list of argument symbols.

byte-code
     The string containing the byte-code instructions.

constants
     The vector of constants referenced by the byte code.

stacksize
     The maximum stack size this function needs.

docstring
     The documentation string (if any); otherwise, nil.  For functions preloaded before Emacs is dumped, this is usually an integer which is an index into the DOC file; use documentation to convert this into a string (see Accessing Documentation).

interactive
     The interactive spec (if any).  This can be a string or a Lisp expression.  It is nil for a function that isn't interactive.

Here's an example of a byte-code function object, in printed representation.  It is the definition of the command backward-sexp.

     #[(&optional arg)
       "^H\204^F^@\301^P\302^H[!\207"
       [arg 1 forward-sexp]
       2
       254435
       "p"]

The primitive way to create a byte-code object is with make-byte-code:

 -- Function: make-byte-code &rest elements
     This function constructs and returns a byte-code function object with ELEMENTS as its elements.

You should not try to come up with the elements for a byte-code function yourself, because if they are inconsistent, Emacs may crash when you call the function.  Always leave it to the byte-compiler to create these objects; it, we hope, always makes the elements consistent.

You can access the elements of a byte-code object using aref; you can also use vconcat to create a vector with the same elements.

Disassembled Byte-Code
======================

People do not write byte-code; that job is left to the byte compiler. But we provide a disassembler to satisfy a cat-like curiosity.  The disassembler converts the byte-compiled code into humanly readable form.

The byte-code interpreter is implemented as a simple stack machine. Values get stored by being pushed onto the stack, and are popped off and manipulated, the results being pushed back onto the stack.  When a function returns, the top of the stack is popped and returned as the value of the function.

In addition to the stack, values used during byte-code execution can be stored in ordinary Lisp variables.  Variable values can be pushed onto the stack, and variables can be set by popping the stack.

 -- Command: disassemble object &optional stream
     This function prints the disassembled code for OBJECT.  If STREAM is supplied, then output goes there.  Otherwise, the disassembled code is printed to the stream standard-output.  The argument OBJECT can be a function name or a lambda expression.

     As a special exception, if this function is used interactively, it outputs to a buffer named *Disassemble*.

Here are two examples of using the disassemble function.  We have added explanatory comments to help you relate the byte-code to the Lisp source; these do not appear in the output of disassemble. These examples show unoptimized byte-code.  Nowadays byte-code is usually optimized, but we did not want to rewrite these examples, since they still serve their purpose.

     (defun factorial (integer)
       "Compute factorial of an integer."
       (if (= 1 integer) 1
         (* integer (factorial (1- integer)))))
          => factorial

     (factorial 4)
          => 24

     (disassemble 'factorial)
          -| byte-code for factorial:
      doc: Compute factorial of an integer.
      args: (integer)

     0   constant 1              ; Push 1 onto stack.

     1   varref   integer        ; Get value of integer
                                 ;   from the environment
                                 ;   and push the value
                                 ;   onto the stack.

     2   eqlsign                 ; Pop top two values off stack,
                                 ;   compare them,
                                 ;   and push result onto stack.

     3   goto-if-nil 10          ; Pop and test top of stack;
                                 ;   if nil, go to 10,
                                 ;   else continue.

     6   constant 1              ; Push 1 onto top of stack.

     7   goto     17             ; Go to 17 (in this case, 1 will be
                                 ;   returned by the function).

     10  constant *              ; Push symbol * onto stack.

     11  varref   integer        ; Push value of integer onto stack.

     12  constant factorial      ; Push factorial onto stack.

     13  varref   integer        ; Push value of integer onto stack.

     14  sub1                    ; Pop integer, decrement value,
                                 ;   push new value onto stack.

                                 ; Stack now contains:
                                 ;   - decremented value of integer
                                 ;   - factorial
                                 ;   - value of integer
                                 ;   - *

     15  call     1              ; Call function factorial using
                                 ;   the first (i.e., the top) element
                                 ;   of the stack as the argument;
                                 ;   push returned value onto stack.

                                 ; Stack now contains:
                                 ;   - result of result of recursive
                                 ;        call to factorial
                                 ;   - value of integer
                                 ;   - *

     16  call     2              ; Using the first two
                                 ;   (i.e., the top two)
                                 ;   elements of the stack
                                 ;   as arguments,
                                 ;   call the function *,
                                 ;   pushing the result onto the stack.

     17  return                  ; Return the top element
                                 ;   of the stack.
          => nil

The silly-loop function is somewhat more complex:

     (defun silly-loop (n)
       "Return time before and after N iterations of a loop."
       (let ((t1 (current-time-string)))
         (while (> (setq n (1- n))
                   0))
         (list t1 (current-time-string))))
          => silly-loop

     (disassemble 'silly-loop)
          -| byte-code for silly-loop:
      doc: Return time before and after N iterations of a loop.
      args: (n)

     0   constant current-time-string  ; Push
                                       ;   current-time-string
                                       ;   onto top of stack.

     1   call     0              ; Call current-time-string
                                 ;    with no argument,
                                 ;    pushing result onto stack.

     2   varbind  t1             ; Pop stack and bind t1
                                 ;   to popped value.

     3   varref   n              ; Get value of n from
                                 ;   the environment and push
                                 ;   the value onto the stack.

     4   sub1                    ; Subtract 1 from top of stack.

     5   dup                     ; Duplicate the top of the stack;
                                 ;   i.e. copy the top of
                                 ;   the stack and push the
                                 ;   copy onto the stack.

     6   varset   n              ; Pop the top of the stack,
                                 ;   and bind n to the value.

                                 ; In effect, the sequence dup varset
                                 ;   copies the top of the stack
                                 ;   into the value of n
                                 ;   without popping it.

     7   constant 0              ; Push 0 onto stack.

     8   gtr                     ; Pop top two values off stack,
                                 ;   test if N is greater than 0
                                 ;   and push result onto stack.

     9   goto-if-nil-else-pop 17 ; Goto 17 if n > 0
                                 ;   else pop top of stack
                                 ;   and continue
                                 ;   (this exits the while loop).

     12  constant nil            ; Push nil onto stack
                                 ;   (this is the body of the loop).

     13  discard                 ; Discard result of the body
                                 ;   of the loop (a while loop
                                 ;   is always evaluated for
                                 ;   its side effects).

     14  goto     3              ; Jump back to beginning
                                 ;   of while loop.

     17  discard                 ; Discard result of while loop
                                 ;   by popping top of stack.

     18  varref   t1             ; Push value of t1 onto stack.

     19  constant current-time-string  ; Push
                                       ;   current-time-string
                                       ;   onto top of stack.

     20  call     0              ; Call current-time-string again.

     21  list2                   ; Pop top two elements off stack,
                                 ;   create a list of them,
                                 ;   and push list onto stack.

     22  unbind   1              ; Unbind t1 in local environment.

     23  return                  ; Return value of the top of stack.

          => nil