0% found this document useful (0 votes)
44 views54 pages

Programming Language - Common Lisp 3. Evaluation and Compilation

This document discusses evaluation and compilation in Common Lisp. It describes environments, including the global environment, dynamic environments, and lexical environments. Bindings are established in environments and partitioned into namespaces. Evaluation involves recursively traversing a form and performing each computation step. Compilation produces code that can be invoked instead of interpreting forms.

Uploaded by

Benjamin Culkin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PS, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views54 pages

Programming Language - Common Lisp 3. Evaluation and Compilation

This document discusses evaluation and compilation in Common Lisp. It describes environments, including the global environment, dynamic environments, and lexical environments. Bindings are established in environments and partitioned into namespaces. Evaluation involves recursively traversing a form and performing each computation step. Compilation produces code that can be invoked instead of interpreting forms.

Uploaded by

Benjamin Culkin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PS, PDF, TXT or read online on Scribd
You are on page 1/ 54

Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.

Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

Programming Language|Common Lisp

3. Evaluation and Compilation

Evaluation and Compilation i ii Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.1 Evaluation 3.1.1.2 Dynamic Environments


Execution of code can be accomplished by a variety of means ranging from direct interpretation of A dynamic environment for evaluation is that part of an environment that contains bindings
a form representing a program to invocation of compiled code produced by a compiler . whose duration is bounded by points of establishment and disestablishment within the execution
of the form that established the binding . A dynamic environment contains, among other things,
Evaluation is the process by which a program is executed in Common Lisp. The mechanism of the following:
evaluation is manifested both implicitly through the e ect of the Lisp read-eval-print loop , and
explicitly through the presence of the functions eval, compile, compile- le, and load. Any of  bindings for dynamic variables .
these facilities might share the same execution strategy, or each might use a di erent one.
 information about active catch tags .
The behavior of a conforming program processed by eval and by compile- le might di er; see  information about exit points established by unwind-protect.
Section 3.2.2.3 (Semantic Constraints).
 information about active handlers and restarts .
Evaluation can be understood in terms of a model in which an interpreter recursively traverses
a form performing each step of the computation as it goes. This model, which describes the The dynamic environment that is active at any given point in the execution of a program is
semantics of Common Lisp programs , is described in Section 3.1.2 (The Evaluation Model). referred to by de nite reference as \the current dynamic environment ," or sometimes as just \the
dynamic environment ."
3.1.1 Introduction to Environments Within a given namespace , a name is said to be bound in a dynamic environment if there is
A binding is an association between a name and that which the name denotes. Bindings are a binding associated with its name in the dynamic environment or, if not, there is a binding
established in a lexical environment or a dynamic environment by particular special operators . associated with its name in the global environment .
An environment is a set of bindings and other information used during evaluation (e.g., to
associate meanings with names).
3.1.1.3 Lexical Environments
A lexical environment for evaluation at some position in a program is that part of the environ-
Bindings in an environment are partitioned into namespaces . A single name can simultaneously ment that contains information having lexical scope within the forms containing that position. A
have more than one associated binding per environment , but can have only one associated binding lexical environment contains, among other things, the following:
per namespace .
 bindings of lexical variables and symbol macros .
3.1.1.1 The Global Environment  bindings of functions and macros . (Implicit in this is information about those compiler
The global environment is that part of an environment that contains bindings with both macros that are locally disabled.)
inde nite scope and inde nite extent . The global environment contains, among other things, the  bindings of block tags .
following:  bindings of go tags .
 bindings of dynamic variables and constant variables .  information about declarations .
 bindings of functions , macros , and special operators . The lexical environment that is active at any given position in a program being semantically
 bindings of compiler macros . processed is referred to by de nite reference as \the current lexical environment ," or sometimes as
just \the lexical environment ."
 bindings of type and class names
 information about proclamations . Within a given namespace , a name is said to be bound in a lexical environment if there is a bind-
ing associated with its name in the lexical environment or, if not, there is a binding associated
with its name in the global environment .

Evaluation and Compilation 3{1 3{2 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.1.1.3.1 The Null Lexical Environment If a form is a symbol that is not a symbol macro , then it is the name of a variable , and the
value of that variable is returned. There are three kinds of variables: lexical variables , dynamic
The null lexical environment is equivalent to the global environment . variables , and constant variables . A variable can store one object . The main operations on a
Although in general the representation of an environment object is implementation-dependent , nil variable are to read 1 and to write 1 its value .
can be used in any situation where an environment object is called for in order to denote the null An error of type unbound-variable should be signaled if an unbound variable is referenced.
lexical environment .
Non-constant variables can be assigned by using setq or bound 3 by using let. Figure 3{1 lists
3.1.1.4 Environment Objects some de ned names that are applicable to assigning, binding, and de ning variables .
Some operators make use of an object , called an environment object, that represents the set boundp let progv
of lexical bindings needed to perform semantic analysis on a form in a given lexical environment . defconstant let* psetq
The set of bindings in an environment object may be a subset of the bindings that would be defparameter makunbound set
needed to actually perform an evaluation ; for example, values associated with variable names and defvar multiple-value-bind setq
function names in the corresponding lexical environment might not be available in an environ- lambda multiple-value-setq symbol-value
ment object .
The type and nature of an environment object is implementation-dependent . The values of Figure 3{1. Some De ned Names Applicable to Variables
environment parameters to macro functions are examples of environment objects . The following is a description of each kind of variable.
The object nil when used as an environment object denotes the null lexical environment ; see 3.1.2.1.1.1 Lexical Variables
Section 3.1.1.3.1 (The Null Lexical Environment).
A lexical variable is a variable that can be referenced only within the lexical scope of the form
3.1.2 The Evaluation Model that establishes that variable ; lexical variables have lexical scope . Each time a form creates a
lexical binding of a variable , a fresh binding is established .
A Common Lisp system evaluates forms with respect to lexical, dynamic, and global environ-
ments . The following sections describe the components of the Common Lisp evaluation model. Within the scope of a binding for a lexical variable name , uses of that name as a variable are
considered to be references to that binding except where the variable is shadowed 2 by a form that
establishes a fresh binding for that variable name , or by a form that locally declares the name
3.1.2.1 Form Evaluation special.
Forms fall into three categories: symbols , conses , and self-evaluating objects . The following A lexical variable always has a value . There is no operator that introduces a binding for a lexical
sections explain these categories. variable without giving it an initial value , nor is there any operator that can make a lexical
variable be unbound .
3.1.2.1.1 Symbols as Forms
Bindings of lexical variables are found in the lexical environment .
If a form is a symbol , then it is either a symbol macro or a variable .
3.1.2.1.1.2 Dynamic Variables
The symbol names a symbol macro if there is a binding of the symbol as a symbol macro in the
current lexical environment (see de ne-symbol-macro and symbol-macrolet). If the symbol is A variable is a dynamic variable if one of the following conditions hold:
a symbol macro , its expansion function is obtained. The expansion function is a function of two
arguments, and is invoked by calling the macroexpand hook with the expansion function as its  It is locally declared or globally proclaimed special.
rst argument, the symbol as its second argument, and an environment object (corresponding
to the current lexical environment ) as its third argument. The macroexpand hook , in turn, calls  It occurs textually within a form that creates a dynamic binding for a variable of the same
the expansion function with the form as its rst argument and the environment as its second name , and the binding is not shadowed 2 by a form that creates a lexical binding of the same
argument. The value of the expansion function, which is passed through by the macroexpand variable name .
hook , is a form . This resulting form is processed in place of the original symbol .

Evaluation and Compilation 3{3 3{4 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

A dynamic variable can be referenced at any time in any program ; there is no textual limitation 3.1.2.1.2 Conses as Forms
on references to dynamic variables . At any given time, all dynamic variables with a given name
refer to exactly one binding , either in the dynamic environment or in the global environment . A cons that is used as a form is called a compound form .
The value part of the binding for a dynamic variable might be empty; in this case, the dynamic If the car of that compound form is a symbol , that symbol is the name of an operator , and the
variable is said to have no value , or to be unbound . A dynamic variable can be made unbound by form is either a special form , a macro form , or a function form , depending on the function
using makunbound. binding of the operator in the current lexical environment . If the operator is neither a special
operator nor a macro name , it is assumed to be a function name (even if there is no de nition for
The e ect of binding a dynamic variable is to create a new binding to which all references to that such a function ).
dynamic variable in any program refer for the duration of the evaluation of the form that creates
the dynamic binding . If the car of the compound form is not a symbol , then that car must be a lambda expression , in
which case the compound form is a lambda form .
A dynamic variable can be referenced outside the dynamic extent of a form that binds it. Such
a variable is sometimes called a \global variable" but is still in all respects just a dynamic vari- How a compound form is processed depends on whether it is classi ed as a special form , a macro
able whose binding happens to exist in the global environment rather than in some dynamic form , a function form , or a lambda form .
environment . 3.1.2.1.2.1 Special Forms
A dynamic variable is unbound unless and until explicitly assigned a value, except for those A special form is a form with special syntax, special evaluation rules, or both, possibly manip-
variables whose initial value is de ned in this speci cation or by an implementation . ulating the evaluation environment, control ow, or both. A special operator has access to the
3.1.2.1.1.3 Constant Variables current lexical environment and the current dynamic environment . Each special operator de nes
the manner in which its subexpressions are treated|which are forms , which are special syntax,
Certain variables, called constant variables , are reserved as \named constants." The consequences etc.
are unde ned if an attempt is made to assign a value to, or create a binding for a constant
variable , except that a `compatible' rede nition of a constant variable using defconstant is Some special operators create new lexical or dynamic environments for use during the evaluation
permitted; see the macro defconstant. of subforms of the special form . For example, block creates a new lexical environment that is
the same as the one in force at the point of evaluation of the block form with the addition of a
Keywords , symbols de ned by Common Lisp or the implementation as constant (such as nil, t, binding of the block name to an exit point from the block.
and pi), and symbols declared as constant using defconstant are constant variables .
The set of special operator names is xed in Common Lisp; no way is provided for the user to
3.1.2.1.1.4 Symbols Naming Both Lexical and Dynamic Variables de ne a special operator . Figure 3{2 lists all of the Common Lisp symbols that have de nitions as
special operators .
The same symbol can name both a lexical variable and a dynamic variable , but never in the same
lexical environment . block let* return-from
In the following example, the symbol x is used, at di erent times, as the name of a lexical variable catch load-time-value setq
and as the name of a dynamic variable . eval-when locally symbol-macrolet
et macrolet tagbody
(let ((x 1)) ;Binds a special variable X function multiple-value-call the
(declare (special x)) go multiple-value-prog1 throw
(let ((x 2)) ;Binds a lexical variable X if progn unwind-protect
(+ x ;Reads a lexical variable X labels progv
(locally (declare (special x)) let quote
x)))) ;Reads a special variable X
! 3 Figure 3{2. Common Lisp Special Operators

Evaluation and Compilation 3{5 3{6 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.1.2.1.2.2 Macro Forms The functional value of the operator is retrieved from the lexical environment , and that function
is invoked with the indicated arguments.
If the operator names a macro , its associated macro function is applied to the entire form and
the result of that application is used in place of the original form . Although the order of evaluation of the argument subforms themselves is strictly left-to-right, it
is not speci ed whether the de nition of the operator in a function form is looked up before the
Speci cally, a symbol names a macro in a given lexical environment if macro-function is true evaluation of the argument subforms , after the evaluation of the argument subforms , or between
of the symbol and that environment . The function returned by macro-function is a function of the evaluation of any two argument subforms if there is more than one such argument subform .
two arguments, called the expansion function. The expansion function is invoked by calling the For example, the following might return 23 or 24.
macroexpand hook with the expansion function as its rst argument, the entire macro form as its
second argument, and an environment object (corresponding to the current lexical environment ) (defun foo (x) (+ x 3))
as its third argument. The macroexpand hook , in turn, calls the expansion function with the form (defun bar () (setf (symbol-function 'foo) #'(lambda (x) (+ x 4))))
as its rst argument and the environment as its second argument. The value of the expansion (foo (progn (bar) 20))
function, which is passed through by the macroexpand hook , is a form . The returned form is
evaluated in place of the original form . A binding for a function name can be established in one of several ways. A binding for a
function name in the global environment can be established by defun, setf of fde nition,
The consequences are unde ned if a macro function destructively modi es any part of its form setf of symbol-function, ensure-generic-function, defmethod (implicitly, due to
argument. ensure-generic-function), or defgeneric. A binding for a function name in the lexical envi-
ronment can be established by et or labels.
A macro name is not a function designator , and cannot be used as the function argument to
functions such as apply, funcall, or map. Figure 3{4 lists some de ned names that are applicable to functions .
An implementation is free to implement a Common Lisp special operator as a macro . An imple- apply fde nition mapcan
mentation is free to implement any macro operator as a special operator , but only if an equivalent call-arguments-limit et mapcar
de nition of the macro is also provided. complement fmakunbound mapcon
Figure 3{3 lists some de ned names that are applicable to macros . constantly funcall mapl
defgeneric function maplist
*macroexpand-hook* macro-function macroexpand-1 defmethod functionp multiple-value-call
defmacro macroexpand macrolet defun labels reduce
fboundp map symbol-function
Figure 3{3. De ned names applicable to macros Figure 3{4. Some function-related de ned names

3.1.2.1.2.3 Function Forms 3.1.2.1.2.4 Lambda Forms


If the operator is a symbol naming a function , the form represents a function form , and the cdr A lambda form is similar to a function form , except that the function name is replaced by a
of the list contains the forms which when evaluated will supply the arguments passed to the lambda expression .
function .
When a function name is not de ned, an error of type unde ned-function should be signaled at A lambda form is equivalent to using funcall of a lexical closure of the lambda expression on
run time; see Section 3.2.2.3 (Semantic Constraints). the given arguments . (In practice, some compilers are more likely to produce inline code for a
lambda form than for an arbitrary named function that has been declared inline; however, such a
A function form is evaluated as follows: di erence is not semantic.)
The subforms in the cdr of the original form are evaluated in left-to-right order in the current For further information, see Section 3.1.3 (Lambda Expressions).
lexical and dynamic environments . The primary value of each such evaluation becomes an
argument to the named function ; any additional values returned by the subforms are discarded.

Evaluation and Compilation 3{7 3{8 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.1.2.1.3 Self-Evaluating Objects The function special form coerces a lambda expression into a closure in which the lexical environ-
ment in e ect when the special form is evaluated is captured along with the lambda expression .
A form that is neither a symbol nor a cons is de ned to be a self-evaluating object . Evaluating
such an object yields the same object as a result. The function two-funs returns a list of two functions , each of which refers to the binding of the
variable x created on entry to the function two-funs when it was called. This variable has the
Certain speci c symbols and conses might also happen to be \self-evaluating" but only as a value 6 initially, but setq can alter this binding . The lexical closure created for the rst lambda
special case of a more general set of rules for the evaluation of symbols and conses ; such objects expression does not \snapshot" the value 6 for x when the closure is created; rather it captures
are not considered to be self-evaluating objects . the binding of x. The second function can be used to alter the value in the same (captured)
The consequences are unde ned if literal objects (including self-evaluating objects ) are destruc- binding (to 43, in the example), and this altered variable binding then a ects the value returned
tively modi ed. by the rst function .
3.1.2.1.3.1 Examples of Self-Evaluating Objects In situations where a closure of a lambda expression over the same set of bindings may be pro-
duced more than once, the various resulting closures may or may not be identical , at the discre-
Numbers , pathnames , and arrays are examples of self-evaluating objects . tion of the implementation . That is, two functions that are behaviorally indistinguishable might
or might not be identical . Two functions that are behaviorally distinguishable are distinct . For
3 ! 3 example:
#c(2/3 5/8) ! #C(2/3 5/8)
#p"S:[BILL]OTHELLO.TXT" ! #P"S:[BILL]OTHELLO.TXT" (let ((x 5) (funs '()))
#(a b c) ! #(A B C) (dotimes (j 10)
"fred smith" ! "fred smith" (push #'(lambda (z)
(if (null z) (setq x 0) (+ x z)))

3.1.3 Lambda Expressions funs)


funs))

In a lambda expression , the body is evaluated in a lexical environment that is formed by adding The result of the above form is a list of ten closures . Each requires only the binding of x. It is
the binding of each parameter in the lambda list with the corresponding value from the arguments the same binding in each case, but the ten closure objects might or might not be identical . On
to the current lexical environment . the other hand, the result of the form
For further discussion of how bindings are established based on the lambda list , see Section 3.4 (let ((funs '()))
(Lambda Lists). (dotimes (j 10)

The body of a lambda expression is an implicit progn ; the values it returns are returned by the (let ((x 5))

lambda expression . (push (function (lambda (z)


(if (null z) (setq x 0) (+ x z))))

3.1.4 Closures and Lexical Binding funs)


funs)))

A lexical closure is a function that can refer to and alter the values of lexical bindings established is also a list of ten closures . However, in this case no two of the closure objects can be identical
by binding forms that textually include the function de nition. because each closure is closed over a distinct binding of x, and these bindings can be behaviorally
distinguished because of the use of setq .
Consider this code, where x is not declared special:
The result of the form
(defun two-funs (x)
(list (function (lambda () x)) (let ((funs '()))
(function (lambda (y) (setq x y))))) (dotimes (j 10)
(setq funs (two-funs 6)) (let ((x 5))
(funcall (car funs)) ! 6 (push (function (lambda (z) (+ x z)))
(funcall (cadr funs) 43) ! 43 funs)))
(funcall (car funs)) ! 43 funs)

Evaluation and Compilation 3{9 3{10 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

is a list of ten closure objects that might or might not be identical . A di erent binding of x (contorted-example nil nil 2)
is involved for each closure , but the bindings cannot be distinguished because their values are (block here1 ...)
the same and immutable (there being no occurrence of setq on x). A compiler could internally (contorted-example nil #'(lambda () (return-from here1 4)) 1)
transform the form to (block here2 ...)
(contorted-example #'(lambda () (return-from here1 4))
(let ((funs '())) #'(lambda () (return-from here2 4))
(dotimes (j 10) 0)
(push (function (lambda (z) (+ 5 z))) (funcall f)
funs)) where f ! #'(lambda () (return-from here1 4))
funs) (return-from here1 4)
where the closures may be identical . At the time the funcall is executed there are two block exit points outstanding, each apparently
It is possible that a closure does not close over any variable bindings. In the code fragment named here. The return-from form executed as a result of the funcall operation refers to
the outer outstanding exit point (here1 ), not the inner one (here2 ). It refers to that exit point
(mapcar (function (lambda (x) (+ x 2))) y) textually visible at the point of execution of function (here abbreviated by the #' syntax) that
resulted in creation of the function object actually invoked by funcall.
the function (lambda (x) (+ x 2)) contains no references to any outside object. In this case, the
same closure might be returned for all evaluations of the function form . If, in this example, one were to change the (funcall f) to (funcall g), then the value of the
call (contorted-example nil nil 2) would be 9. The value would change because funcall
3.1.5 Shadowing would cause the execution of (return-from here2 4), thereby causing a return from the inner
exit point (here2 ). When that occurs, the value 4 is returned from the middle invocation of
If two forms that establish lexical bindings with the same name N are textually nested, then contorted-example, 5 is added to that to get 9, and that value is returned from the outer block
references to N within the inner form refer to the binding established by the inner form ; the and the outermost call to contorted-example. The point is that the choice of exit point returned
inner binding for N shadows the outer binding for N . Outside the inner form but inside the from has nothing to do with its being innermost or outermost; rather, it depends on the lexical
outer one, references to N refer to the binding established by the outer form . For example: environment that is packaged up with a lambda expression when function is executed.
(defun test (x z)
(let ((z (* x 2)))
3.1.6 Extent
(print z)) Contorted-example works only because the function named by f is invoked during the extent of
z) the exit point . Once the ow of execution has left the block, the exit point is disestablished . For
The binding of the variable z by let shadows the parameter binding for the function test. The example:
reference to the variable z in the print form refers to the let binding. The reference to z at the (defun invalid-example ()
end of the function test refers to the parameter named z. (let ((y (block here #'(lambda (z) (return-from here z)))))

Constructs that are lexically scoped act as if new names were generated for each object on each (if (numberp y) y (funcall y 5))))

execution. Therefore, dynamic shadowing cannot occur. For example: One might expect the call (invalid-example) to produce 5 by the following incorrect reasoning:
let binds y to the value of block; this value is a function resulting from the lambda expression .
(defun contorted-example (f g x)
(if (= x 0)
Because y is not a number, it is invoked on the value 5. The return-from should then return this
(funcall f)
value from the exit point named here, thereby exiting from the block again and giving y the value
5 which, being a number, is then returned as the value of the call to invalid-example.
(block here
(+ 5 (contorted-example g The argument fails only because exit points have dynamic extent . The argument is correct up
#'(lambda () (return-from here 4)) to the execution of return-from. The execution of return-from should signal an error of type
(- x 1)))))) control-error, however, not because it cannot refer to the exit point , but because it does correctly
Consider the call (contorted-example nil nil 2). This produces 4. During the course of execu- refer to an exit point and that exit point has been disestablished .
tion, there are three calls to contorted-example, interleaved with two blocks:

Evaluation and Compilation 3{11 3{12 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

A reference by name to a dynamic exit point binding such as a catch tag refers to the most
recently established binding of that name that has not been disestablished . For example:
3.2 Compilation
(defun fun1 (x)
(catch 'trap (+ 3 (fun2 x))))
(defun fun2 (y)
3.2.1 Compiler Terminology
(catch 'trap (* 5 (fun3 y)))) The following terminology is used in this section.
(defun fun3 (z)
The compiler is a utility that translates code into an implementation-dependent form that might
(throw 'trap z))
be represented or executed eciently. The term compiler refers to both of the functions compile
Consider the call (fun1 7). The result is 10. At the time the throw is executed, there are two and compile- le.
outstanding catchers with the name trap: one established within procedure fun1, and the other The term compiled code refers to objects representing compiled programs, such as objects
within procedure fun2. The latter is the more recent, and so the value 7 is returned from catch in constructed by compile or by load when loading a compiled le .
fun2. Viewed from within fun3, the catch in fun2 shadows the one in fun1. Had fun2 been de ned
as The term implicit compilation refers to compilation performed during evaluation .
(defun fun2 (y) The term literal object refers to a quoted object or a self-evaluating object or an object that is a
(catch 'snare (* 5 (fun3 y)))) substructure of such an object . A constant variable is not itself a literal object .
then the two exit points would have di erent names , and therefore the one in fun1 would not be The term coalesce is de ned as follows. Suppose A and B are two literal constants in the source
shadowed. The result would then have been 7. code , and that A' and B' are the corresponding objects in the compiled code . If A' and B' are eql
but A and B are not eql, then it is said that A and B have been coalesced by the compiler.
3.1.7 Return Values The term minimal compilation refers to actions the compiler must take at compile time . These
Ordinarily the result of calling a function is a single object . Sometimes, however, it is convenient actions are speci ed in Section 3.2.2 (Compilation Semantics).
for a function to compute several objects and return them. The verb process refers to performing minimal compilation , determining the time of evaluation
In order to receive other than exactly one value from a form , one of several special forms or for a form , and possibly evaluating that form (if required).
macros must be used to request those values. If a form produces multiple values which were not The term further compilation refers to implementation-dependent compilation beyond min-
requested in this way, then the rst value is given to the caller and all others are discarded; if the imal compilation . That is, processing does not imply complete compilation. Block compilation
form produces zero values, then the caller receives nil as a value. and generation of machine-speci c instructions are examples of further compilation. Further
Figure 3{5 lists some operators for receiving multiple values 2 . These operators can be used to compilation is permitted to take place at run time .
specify one or more forms to evaluate and where to put the values returned by those forms . Four di erent environments relevant to compilation are distinguished: the startup environment ,
multiple-value-bind multiple-value-prog1 return-from the compilation environment , the evaluation environment , and the run-time environment .
multiple-value-call multiple-value-setq throw The startup environment is the environment of the Lisp image from which the compiler was
multiple-value-list return invoked.
Figure 3{5. Some operators applicable to receiving multiple values The compilation environment is maintained by the compiler and is used to hold de nitions
and declarations to be used internally by the compiler. Only those parts of a de nition needed for
The function values can produce multiple values 2 . (values) returns zero values; (values form) correct compilation are saved. The compilation environment is used as the environment argument
returns the primary value returned by form; (values form1 form2 ) returns two values, the to macro expanders called by the compiler. It is unspeci ed whether a de nition available in the
primary value of form1 and the primary value of form2 ; and so on. compilation environment can be used in an evaluation initiated in the startup environment or
evaluation environment .
See multiple-values-limit and values-list. The evaluation environment is a run-time environment in which macro expanders and code
speci ed by eval-when to be evaluated are evaluated. All evaluations initiated by the compiler

Evaluation and Compilation 3{13 3{14 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

take place in the evaluation environment . form as its second argument, and the current compilation environment (or with the current
lexical environment , if the form is being processed by something other than compile- le) as its
The run-time environment is the environment in which the program being compiled will be third argument. The macroexpand hook , in turn, calls the expansion function with the form as its
executed. rst argument and the environment as its second argument. The return value from the expansion
The compilation environment inherits from the evaluation environment , and the compilation function, which is passed through by the macroexpand hook , might either be the same form , or
environment and evaluation environment might be identical . The evaluation environment inherits else a form that can, at the discretion of the code doing the expansion, be used in place of the
from the startup environment , and the startup environment and evaluation environment might be original form .
identical .
*macroexpand-hook* compiler-macro-function de ne-compiler-macro
The term compile time refers to the duration of time that the compiler is processing source
code . At compile time , only the compilation environment and the evaluation environment are Figure 3{6. De ned names applicable to compiler macros
available.
The term compile-time de nition refers to a de nition in the compilation environment . For
example, when compiling a le, the de nition of a function might be retained in the compilation 3.2.2.1.1 Purpose of Compiler Macros
environment if it is declared inline. This de nition might not be available in the evaluation
environment . The purpose of the compiler macro facility is to permit selective source code transformations as
optimization advice to the compiler . When a compound form is being processed (as by the com-
The term run time refers to the duration of time that the loader is loading compiled code or piler), if the operator names a compiler macro then the compiler macro function may be invoked
compiled code is being executed. At run time, only the run-time environment is available. on the form, and the resulting expansion recursively processed in preference to performing the
usual processing on the original form according to its normal interpretation as a function form or
The term run-time de nition refers to a de nition in the run-time environment . macro form .
The term run-time compiler refers to the function compile or implicit compilation , for which A compiler macro function , like a macro function , is a function of two arguments : the entire call
the compilation and run-time environments are maintained in the same Lisp image . Note that form and the environment . Unlike an ordinary macro function , a compiler macro function can
when the run-time compiler is used, the run-time environment and startup environment are the decline to provide an expansion merely by returning a value that is the same as the original form .
same. The consequences are unde ned if a compiler macro function destructively modi es any part of
its form argument.
3.2.2 Compilation Semantics The form passed to the compiler macro function can either be a list whose car is the function
Conceptually, compilation is a process that traverses code, performs certain kinds of syntactic and name, or a list whose car is funcall and whose cadr is a list (function name ); note that this af-
semantic analyses using information (such as proclamations and macro de nitions) present in the fects destructuring of the form argument by the compiler macro function . de ne-compiler-macro
compilation environment , and produces equivalent, possibly more ecient code. arranges for destructuring of arguments to be performed correctly for both possible formats.
When compile- le chooses to expand a top level form that is a compiler macro form , the ex-
3.2.2.1 Compiler Macros pansion is also treated as a top level form for the purposes of eval-when processing; see Section
3.2.3.1 (Processing of Top Level Forms).
A compiler macro can be de ned for a name that also names a function or macro . That is, it is
possible for a function name to name both a function and a compiler macro . 3.2.2.1.2 Naming of Compiler Macros
A function name names a compiler macro if compiler-macro-function is true of the function Compiler macros may be de ned for function names that name macros as well as functions .
name in the lexical environment in which it appears. Creating a lexical binding for the function
name not only creates a new local function or macro de nition, but also shadows 2 the compiler Compiler macro de nitions are strictly global. There is no provision for de ning local compiler
macro . macros in the way that macrolet de nes local macros . Lexical bindings of a function name
shadow any compiler macro de nition associated with the name as well as its global function or
The function returned by compiler-macro-function is a function of two arguments, called the macro de nition.
expansion function. To expand a compiler macro , the expansion function is invoked by calling the
macroexpand hook with the expansion function as its rst argument, the entire compiler macro

Evaluation and Compilation 3{15 3{16 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

Note that the presence of a compiler macro de nition does not a ect the values returned by func- 3.2.2.2 Minimal Compilation
tions that access function de nitions (e.g., fboundp) or macro de nitions (e.g., macroexpand).
Compiler macros are global, and the function compiler-macro-function is sucient to resolve Minimal compilation is de ned as follows:
their interaction with other lexical and global de nitions.
 All compiler macro calls appearing in the source code being compiled are expanded, if at
3.2.2.1.3 When Compiler Macros Are Used all, at compile time; they will not be expanded at run time.
The presence of a compiler macro de nition for a function or macro indicates that it is desirable  All macro and symbol macro calls appearing in the source code being compiled are
for the compiler to use the expansion of the compiler macro instead of the original function form expanded at compile time in such a way that they will not be expanded again at run
or macro form . However, no language processor (compiler, evaluator, or other code walker) is ever time. macrolet and symbol-macrolet are e ectively replaced by forms corresponding to
required to actually invoke compiler macro functions , or to make use of the resulting expansion if their bodies in which calls to macros are replaced by their expansions.
it does invoke a compiler macro function .
When the compiler encounters a form during processing that represents a call to a compiler  The rst argument in a load-time-value form in source code processed by compile
macro name (that is not declared notinline), the compiler might expand the compiler macro , and is evaluated at compile time ; in source code processed by compile- le, the compiler
might use the expansion in place of the original form . arranges for it to be evaluated at load time . In either case, the result of the evaluation is
remembered and used later as the value of the load-time-value form at execution time .
When eval encounters a form during processing that represents a call to a compiler macro name
(that is not declared notinline), eval might expand the compiler macro , and might use the
expansion in place of the original form .
3.2.2.3 Semantic Constraints
All conforming programs must obey the following constraints, which are designed to minimize the
There are two situations in which a compiler macro de nition must not be applied by any lan- observable di erences between compiled and interpreted programs:
guage processor:
 De nitions of any referenced macros must be present in the compilation environment .
 The global function name binding associated with the compiler macro is shadowed by a Any form that is a list beginning with a symbol that does not name a special operator or
lexical binding of the function name. a macro de ned in the compilation environment is treated by the compiler as a function
call.
 The function name has been declared or proclaimed notinline and the call form appears
within the scope of the declaration.  Special proclamations for dynamic variables must be made in the compilation envi-
It is unspeci ed whether compiler macros are expanded or used in any other situations. ronment . Any binding for which there is no special declaration or proclamation in the
compilation environment is treated by the compiler as a lexical binding .
3.2.2.1.3.1 Notes about the Implementation of Compiler Macros
 The de nition of a function that is de ned and declared inline in the compilation envi-
Although it is technically permissible, as described above, for eval to treat compiler macros in the ronment must be the same at run time.
same situations as compiler might, this is not necessarily a good idea in interpreted implementa-
tions .  Within a function named F , the compiler may (but is not required to) assume that
Compiler macros exist for the purpose of trading compile-time speed for run-time speed. Pro- an apparent recursive call to a function named F refers to the same de nition of F ,
grammers who write compiler macros tend to assume that the compiler macros can take more unless that function has been declared notinline. The consequences of rede ning such a
time than normal functions and macros in order to produce code which is especially optimal for recursively de ned function F while it is executing are unde ned.
use at run time. Since eval in an interpreted implementation might perform semantic analysis of  A call within a le to a named function that is de ned in the same le refers to that func-
the same form multiple times, it might be inecient in general for the implementation to choose tion, unless that function has been declared notinline. The consequences are unspeci ed
to call compiler macros on every such evaluation . if functions are rede ned individually at run time or multiply de ned in the same le.
Nevertheless, the decision about what to do in these situations is left to each implementation .
 The argument syntax and number of return values for all functions whose ftype is
declared at compile time must remain the same at run time.

Evaluation and Compilation 3{17 3{18 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

 Constant variables de ned in the compilation environment must have a similar value at The eval-when special form can be used to control whether a top level form is evaluated at com-
run time. A reference to a constant variable in source code is equivalent to a reference to pile time, load time, or both. It is possible to specify any of three situations with eval-when, de-
a literal object that is the value of the constant variable . noted by the symbols :compile-toplevel, :load-toplevel, and :execute. For top level eval-when
forms, :compile-toplevel speci es that the compiler must evaluate the body at compile time, and
 Type de nitions made with deftype or defstruct in the compilation environment must :load-toplevel speci es that the compiler must arrange to evaluate the body at load time. For
retain the same de nition at run time. Classes de ned by defclass in the compilation non-top level eval-when forms, :execute speci es that the body must be executed in the run-time
environment must be de ned at run time to have the same superclasses and same meta- environment .
class .
The behavior of this form can be more precisely understood in terms of a model of how
This implies that subtype /supertype relationships of type speci ers must not change compile- le processes forms in a le to be compiled. There are two processing modes, called
between compile time and run time . \not-compile-time" and \compile-time-too".
 Type declarations present in the compilation environment must accurately describe Successive forms are read from the le by compile- le and processed in not-compile-time mode;
the corresponding values at run time; otherwise, the consequences are unde ned. It is in this mode, compile- le arranges for forms to be evaluated only at load time and not at com-
permissible for an unknown type to appear in a declaration at compile time, though a pile time. When compile- le is in compile-time-too mode, forms are evaluated both at compile
warning might be signaled in such a case. time and load time.
 Except in the situations explicitly listed above, a function de ned in the evaluation 3.2.3.1 Processing of Top Level Forms
environment is permitted to have a di erent de nition or a di erent signature at run Processing of top level forms in the le compiler is de ned as follows:
time, and the run-time de nition prevails.
Conforming programs should not be written using any additional assumptions about consistency 1. If the form is a compiler macro form (not disabled by a notinline declaration ), the
between the run-time environment and the startup, evaluation, and compilation environments . implementation might or might not choose to compute the compiler macro expansion of
the form and, having performed the expansion, might or might not choose to process the
Except where noted, when a compile-time and a run-time de nition are di erent, one of the result as a top level form in the same processing mode (compile-time-too or not-compile-
following occurs at run time: time). If it declines to obtain or use the expansion, it must process the original form .
 an error of type error is signaled
 the compile-time de nition prevails 2. If the form is a macro form , its macro expansion is computed and processed as a top level
form in the same processing mode (compile-time-too or not-compile-time).
 the run-time de nition prevails
If the compiler processes a function form whose operator is not de ned at compile time, no error 3. If the form is a progn form, each of its body forms is sequentially processed as a top level
is signaled at compile time. form in the same processing mode.
4. If the form is a locally, macrolet, or symbol-macrolet, compile- le establishes the ap-
3.2.3 File Compilation propriate bindings and processes the body forms as top level forms with those bindings in
The function compile- le performs compilation of forms in a le following the rules speci ed in e ect in the same processing mode. (Note that this implies that the lexical environment
Section 3.2.2 (Compilation Semantics), and produces an output le that can be loaded by using in which top level forms are processed is not necessarily the null lexical environment .)
load. 5. If the form is an eval-when form, it is handled according to Figure 3{7.
Normally, the top level forms appearing in a le compiled with compile- le are evaluated only
when the resulting compiled le is loaded, and not when the le is compiled. However, it is typi-
cally the case that some forms in the le need to be evaluated at compile time so the remainder of
the le can be read and compiled correctly.

Evaluation and Compilation 3{19 3{20 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

forms , an eval-when specifying the :execute situation is treated as an implicit progn including
CT LT E Mode Action New Mode the forms in the body of the eval-when form ; otherwise, the forms in the body are ignored.
Yes Yes | | Process compile-time-too
No Yes Yes CTT Process compile-time-too 3.2.3.1.1 Processing of De ning Macros
No Yes Yes NCT Process not-compile-time De ning macros (such as defmacro or defvar) appearing within a le being processed by
No Yes No | Process not-compile-time compile- le normally have compile-time side e ects which a ect how subsequent forms
Yes No | | Evaluate | in the same le are compiled. A convenient model for explaining how these side e ects
No No Yes CTT Evaluate | happen is that the de ning macro expands into one or more eval-when forms , and that
No No Yes NCT Discard | the calls which cause the compile-time side e ects to happen appear in the body of an
No No No | Discard | (eval-when (:compile-toplevel) ...) form .

Figure 3{7. EVAL-WHEN processing The compile-time side e ects may cause information about the de nition to be stored di erently
than if the de ning macro had been processed in the `normal' way (either interpretively or by
loading the compiled le).
Column CT indicates whether :compile-toplevel is speci ed. Column LT indicates
whether :load-toplevel is speci ed. Column E indicates whether :execute is speci ed. In particular, the information stored by the de ning macros at compile time might or might not
Column Mode indicates the processing mode; a dash (|) indicates that the processing be available to the interpreter (either during or after compilation), or during subsequent calls
mode is not relevant. to the compiler . For example, the following code is nonportable because it assumes that the
compiler stores the macro de nition of foo where it is available to the interpreter:
The Action column speci es one of three actions:
(defmacro foo (x) `(car ,x))
Process: process the body as top level forms in the speci ed mode. (eval-when (:execute :compile-toplevel :load-toplevel)
(print (foo '(a b c))))
Evaluate: evaluate the body in the dynamic execution context of the compiler, using A portable way to do the same thing would be to include the macro de nition inside the
the evaluation environment as the global environment and the lexical environment in eval-when form , as in:
which the eval-when appears.
(eval-when (:execute :compile-toplevel :load-toplevel)
Discard: ignore the form . (defmacro foo (x) `(car ,x))
(print (foo '(a b c))))
The New Mode column indicates the new processing mode. A dash (|) indicates the
compiler remains in its current mode. Figure 3{8 lists macros that make de nitions available both in the compilation and run-time
environments . It is not speci ed whether de nitions made available in the compilation environ-
6. Otherwise, the form is a top level form that is not one of the special cases. In compile- ment are available in the evaluation environment , nor is it speci ed whether they are available in
time-too mode, the compiler rst evaluates the form in the evaluation environment and subsequent compilation units or subsequent invocations of the compiler. As with eval-when, these
then minimally compiles it. In not-compile-time mode, the form is simply minimally compile-time side e ects happen only when the de ning macros appear at top level.
compiled. All subforms are treated as non-top-level forms .
declaim de ne-modify-macro defsetf
Note that top level forms are processed in the order in which they textually appear in defclass de ne-setf-expander defstruct
the le and that each top level form read by the compiler is processed before the next is defconstant defmacro deftype
read. However, the order of processing (including macro expansion) of subforms that are de ne-compiler-macro defpackage defvar
not top level forms and the order of further compilation is unspeci ed as long as Common de ne-condition defparameter
Lisp semantics are preserved.
eval-when forms cause compile-time evaluation only at top level. Both :compile-toplevel and Figure 3{8. De ning Macros That A ect the Compile-Time Environment
:load-toplevel situation speci cations are ignored for non-top-level forms . For non-top-level

Evaluation and Compilation 3{21 3{22 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.2.3.1.2 Constraints on Macros and Compiler Macros can be shown to be similar to the original object which existed at the time the le compiler was
operating.
Except where explicitly stated otherwise, no macro de ned in the Common Lisp standard pro-
duces an expansion that could cause any of the subforms of the macro form to be treated as top 3.2.4.2 Similarity of Literal Objects
level forms . If an implementation also provides a special operator de nition of a Common Lisp
macro , the special operator de nition must be semantically equivalent in this respect.
Compiler macro expansions must also have the same top level evaluation semantics as the form 3.2.4.2.1 Similarity of Aggregate Objects
which they replace. This is of concern both to conforming implementations and to conforming
programs . Of the types over which similarity is de ned, some are treated as aggregate objects. For these
types, similarity is de ned recursively. We say that an object of these types has certain \basic
3.2.4 Literal Objects in Compiled Files qualities" and to satisfy the similarity relationship, the values of the corresponding qualities of
the two objects must also be similar.
The functions eval and compile are required to ensure that literal objects referenced within the 3.2.4.2.2 De nition of Similarity
resulting interpreted or compiled code objects are the same as the corresponding objects in the
source code . compile- le, on the other hand, must produce a compiled le that, when loaded with Two objects S (in source code ) and C (in compiled code ) are de ned to be similar if and only if
load, constructs the objects de ned by the source code and produces references to them. they are both of one of the types listed here (or de ned by the implementation ) and they both
In the case of compile- le, objects constructed by load of the compiled le cannot be spoken of satisfy all additional requirements of similarity indicated for that type .
as being the same as the objects constructed at compile time, because the compiled le may be
loaded into a di erent Lisp image than the one in which it was compiled. This section de nes the number
concept of similarity which relates objects in the evaluation environment to the corresponding Two numbers S and C are similar if they are of the same type and represent the same
objects in the run-time environment . mathematical value.
The constraints on literal objects described in this section apply only to compile- le; eval and
compile do not copy or coalesce constants. character
Two simple characters S and C are similar if they have similar code attributes .
3.2.4.1 Externalizable Objects Implementations providing additional, implementation-de ned attributes must de ne
The fact that the le compiler represents literal objects externally in a compiled le and must whether and how non-simple characters can be regarded as similar .
later reconstruct suitable equivalents of those objects when that le is loaded imposes a need for
constraints on the nature of the objects that can be used as literal objects in code to be processed symbol
by the le compiler .
Two apparently uninterned symbols S and C are similar if their names are similar .
An object that can be used as a literal object in code to be processed by the le compiler is called
an externalizable object. Two interned symbols S and C are similar if their names are similar , and if either S
is accessible in the current package at compile time and C is accessible in the current
We de ne that two objects are similar if they satisfy a two-place conceptual equivalence predi- package at load time, or C is accessible in the package that is similar to the home
cate (de ned below), which is independent of the Lisp image so that the two objects in di erent package of S .
Lisp images can be understood to be equivalent under this predicate. Further, by inspecting the
de nition of this conceptual predicate, the programmer can anticipate what aspects of an object (Note that similarity of symbols is dependent on neither the current readtable nor how
are reliably preserved by le compilation . the function read would parse the characters in the name of the symbol .)
The le compiler must cooperate with the loader in order to assure that in each case where an package
externalizable object is processed as a literal object , the loader will construct a similar object .
Two packages S and C are similar if their names are similar .
The set of objects that are externalizable objects are those for which the new conceptual term
\similar " is de ned, such that when a compiled le is loaded , an object can be constructed which

Evaluation and Compilation 3{23 3{24 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

Note that although a package object is an externalizable object , the programmer is pathname
responsible for ensuring that the corresponding package is already in existence when code
referencing it as a literal object is loaded . The loader nds the corresponding package Two pathnames S and C are similar if all corresponding pathname components are
object as if by calling nd-package with that name as an argument . An error is signaled similar .
by the loader if no package exists at load time.
function
random-state Functions are not externalizable objects .
Two random states S and C are similar if S would always produce the same sequence of
pseudo-random numbers as a copy 5 of C when given as the random-state argument to the structure-object and standard-object
function random, assuming equivalent limit arguments in each case. A general-purpose concept of similarity does not exist for structures and standard objects .
(Note that since C has been processed by the le compiler , it cannot be used directly as However, a conforming program is permitted to de ne a make-load-form method for
an argument to random because random would perform a side e ect.) any class K de ned by that program that is a subclass of either structure-object or
standard-object. The e ect of such a method is to de ne that an object S of type K in
cons source code is similar to an object C of type K in compiled code if C was constructed
from code produced by calling make-load-form on S .
Two conses , S and C , are similar if the car 2 of S is similar to the car 2 of C , and the
cdr 2 of S is similar to the cdr 2 of C . 3.2.4.3 Extensions to Similarity Rules
array Some objects , such as streams , readtables, and methods are not externalizable objects under
Two one-dimensional arrays , S and C , are similar if the length of S is similar to the the de nition of similarity given above. That is, such objects may not portably appear as literal
length of C , the actual array element type of S is similar to the actual array element type objects in code to be processed by the le compiler .
of C , and each active element of S is similar to the corresponding element of C . An implementation is permitted to extend the rules of similarity, so that other kinds of objects
Two arrays of rank other than one, S and C , are similar if the rank of S is similar to are externalizable objects for that implementation .
the rank of C , each dimension 1 of S is similar to the corresponding dimension 1 of C , the If for some kind of object , similarity is neither de ned by this speci cation nor by the implemen-
actual array element type of S is similar to the actual array element type of C , and each tation , then the le compiler must signal an error upon encountering such an object as a literal
element of S is similar to the corresponding element of C . constant .
In addition, if S is a simple array , then C must also be a simple array . If S is a displaced
array , has a ll pointer , or is actually adjustable , C is permitted to lack any or all of
these qualities.
3.2.4.4 Additional Constraints on Externalizable Objects
If two literal objects appearing in the source code for a single le processed with the le compiler
hash-table are the identical , the corresponding objects in the compiled code must also be the identical . With
the exception of symbols and packages , any two literal objects in code being processed by the le
Two hash tables S and C are similar if they meet the following three requirements: compiler may be coalesced if and only if they are similar ; if they are either both symbols or both
packages , they may only be coalesced if and only if they are identical .
1. They both have the same test (e.g., they are both eql hash tables ). Objects containing circular references can be externalizable objects . The le compiler is required
2. There is a unique one-to-one correspondence between the keys of the two hash tables , to preserve eqlness of substructures within a le . Preserving eqlness means that subobjects that
such that the corresponding keys are similar . are the same in the source code must be the same in the corresponding compiled code .
In addition, the following are constraints on the handling of literal objects by the le compiler :
3. For all keys, the values associated with two corresponding keys are similar .
If there is more than one possible one-to-one correspondence between the keys of S and
C , the consequences are unspeci ed. A conforming program cannot use a table such as S
as an externalizable constant .

Evaluation and Compilation 3{25 3{26 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

array: If an array in the source code is a simple array , then the corresponding array in the 3. For all symbols represented in the compiled le that were external symbols in their
compiled code will also be a simple array . If an array in the source code is displaced, has home package at compile time, there must be a symbol with the same name that is
a ll pointer , or is actually adjustable , the corresponding array in the compiled code might an external symbol in the package with the same name at load time.
lack any or all of these qualities. If an array in the source code has a ll pointer, then the
corresponding array in the compiled code might be only the size implied by the ll pointer. If any of these conditions do not hold, the package in which the loader looks for the a ected
symbols is unspeci ed. Implementations are permitted to signal an error or to de ne this
packages: The loader is required to nd the corresponding package object as if by calling behavior.
nd-package with the package name as an argument. An error of type package-error is
signaled if no package of that name exists at load time. 3.2.5 Exceptional Situations in the Compiler
random-state: A constant random state object cannot be used as the state argument to the compile and compile- le are permitted to signal errors and warnings, including errors due to
function random because random modi es this data structure. compile-time processing of (eval-when (:compile-toplevel) ...) forms, macro expansion, and
conditions signaled by the compiler itself.
structure, standard-object: Objects of type structure-object and standard-object may Conditions of type error might be signaled by the compiler in situations where the compilation
appear in compiled constants if there is an appropriate make-load-form method de ned for cannot proceed without intervention.
that type .
In addition to situations for which the standard speci es that conditions of type warning must
The le compiler calls make-load-form on any object that is referenced as a literal object if or might be signaled, warnings might be signaled in situations where the compiler can determine
the object is a generalized instance of standard-object, structure-object, condition, or any that the consequences are unde ned or that a run-time error will be signaled. Examples of this
of a (possibly empty) implementation-dependent set of other classes . The le compiler only situation are as follows: violating type declarations, altering or assigning the value of a constant
calls make-load-form once for any given object within a single le . de ned with defconstant, calling built-in Lisp functions with a wrong number of arguments or
malformed keyword argument lists, and using unrecognized declaration speci ers.
symbol: In order to guarantee that compiled les can be loaded correctly, users must ensure The compiler is permitted to issue warnings about matters of programming style as conditions
that the packages referenced in those les are de ned consistently at compile time and load
time. Conforming programs must satisfy the following requirements: of type style-warning. Examples of this situation are as follows: rede ning a function using
a di erent argument list, calling a function with a wrong number of arguments, not declaring
1. The current package when a top level form in the le is processed by compile- le ignore of a local variable that is not referenced, and referencing a variable declared ignore.
must be the same as the current package when the code corresponding to that top Both compile and compile- le are permitted (but not required) to establish a handler for
level form in the compiled le is executed by load. In particular: conditions of type error. For example, they might signal a warning, and restart compilation from
some implementation-dependent point in order to let the compilation proceed without manual
a. Any top level form in a le that alters the current package must change it to intervention.
a package of the same name both at compile time and at load time.
Both compile and compile- le return three values, the second two indicating whether the source
b. If the rst non-atomic top level form in the le is not an in-package form , code being compiled contained errors and whether style warnings were issued.
then the current package at the time load is called must be a package with
the same name as the package that was the current package at the time Some warnings might be deferred until the end of compilation. See with-compilation-unit.
compile- le was called.
2. For all symbols appearing lexically within a top level form that were accessible in
the package that was the current package during processing of that top level form
at compile time, but whose home package was another package , at load time there
must be a symbol with the same name that is accessible in both the load-time current
package and in the package with the same name as the compile-time home package .

Evaluation and Compilation 3{27 3{28 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.3 Declarations An implementation is free to support other (implementation-de ned ) declaration identi ers as
well. A warning might be issued if a declaration identi er is not among those de ned above,
Declarations provide a way of specifying information for use by program processors, such as the is not de ned by the implementation , is not a type name , and has not been declared in a
evaluator or the compiler. declaration proclamation .
Local declarations can be embedded in executable code using declare. Global declarations,
or proclamations , are established by proclaim or declaim. 3.3.3.1 Shorthand notation for Type Declarations
The the special form provides a shorthand notation for making a local declaration about the type A type speci er can be used as a declaration identi er . (type-speci er fvar g*) is taken as short-
of the value of a given form . hand for (type type-speci er fvar g*).
The consequences are unde ned if a program violates a declaration or a proclamation .
3.3.4 Declaration Scope
3.3.1 Minimal Declaration Processing Requirements Declarations can be divided into two kinds: those that apply to the bindings of variables or
functions ; and those that do not apply to bindings .
In general, an implementation is free to ignore declaration speci ers except for the declaration,
notinline, safety, and special declaration speci ers . A declaration that appears at the head of a binding form and applies to a variable or function
binding made by that form is called a bound declaration; such a declaration a ects both the
A declaration declaration must suppress warnings about unrecognized declarations of the kind binding and any references within the scope of the declaration .
that it declares. If an implementation does not produce warnings about unrecognized declara-
tions, it may safely ignore this declaration . Declarations that are not bound declarations are called free declarations .
A notinline declaration must be recognized by any implementation that supports inline functions A free declaration in a form F 1 that applies to a binding for a name N established by some form
or compiler macros in order to disable those facilities. An implementation that does not use inline F 2 of which F 1 is a subform a ects only references to N within F 1; it does not to apply to other
functions or compiler macros may safely ignore this declaration . references to N outside of F 1, nor does it a ect the manner in which the binding of N by F 2 is
established .
A safety declaration that increases the current safety level must always be recognized. An imple-
mentation that always processes code as if safety were high may safely ignore this declaration . Declarations that do not apply to bindings can only appear as free declarations .
A special declaration must be processed by all implementations . The scope of a bound declaration is the same as the lexical scope of the binding to which it
applies; for special variables , this means the scope that the binding would have had had it been a
3.3.2 Declaration Speci ers lexical binding .
A declaration speci er is an expression that can appear at top level of a declare expression or Unless explicitly stated otherwise, the scope of a free declaration includes only the body subforms
a declaim form, or as the argument to proclaim. It is a list whose car is a declaration identi er , of the form at whose head it appears, and no other subforms . The scope of free declarations
and whose cdr is data interpreted according to rules speci c to the declaration identi er . speci cally does not include initialization forms for bindings established by the form containing
the declarations .
3.3.3 Declaration Identi ers Some iteration forms include step, end-test, or result subforms that are also included in the scope
of declarations that appear in the iteration form . Speci cally, the iteration forms and subforms
Figure 3{9 shows a list of all declaration identi ers de ned by this standard. involved are:
declaration ignore special  do, do*: step-forms , end-test-form, and result-forms .
dynamic-extent inline type  dolist, dotimes: result-form
ftype notinline
ignorable optimize  do-all-symbols, do-external-symbols, do-symbols: result-form
Figure 3{9. Common Lisp Declaration Identi ers

Evaluation and Compilation 3{29 3{30 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.3.4.1 Examples of Declaration Scope (let ((x 2)) ;[3]


(dotimes (i x x) ;[4]
Here is an example illustrating the scope of bound declarations . (declare (special x))))) ;[5]
(let ((x 1)) ;[1] 1st occurrence of x
! 1
(declare (special x)) ;[2] 2nd occurrence of x In this example, the rst reference to x on the fourth line is to the lexical binding of x established
(let ((x 2)) ;[3] 3rd occurrence of x on the third line. However, the second occurrence of x on the fourth line lies within the scope of
(let ((old-x x) ;[4] 4th occurrence of x the free declaration on the fth line (because this is the result-form of the dotimes) and therefore
(x 3)) ;[5] 5th occurrence of x refers to the dynamic binding of x.
(declare (special x)) ;[6] 6th occurrence of x
(list old-x x)))) ;[7] 7th occurrence of x
! (2 3)
The rst occurrence of x establishes a dynamic binding of x because of the special declaration for
x in the second line. The third occurrence of x establishes a lexical binding of x (because there is
no special declaration in the corresponding let form ). The fourth occurrence of x x is a reference
to the lexical binding of x established in the third line. The fth occurrence of x establishes a
dynamic binding of x for the body of the let form that begins on that line because of the special
declaration for x in the sixth line. The reference to x in the fourth line is not a ected by the
special declaration in the sixth line because that reference is not within the \would-be lexical
scope " of the variable x in the fth line. The reference to x in the seventh line is a reference to
the dynamic binding of x established in the fth line.
Here is another example, to illustrate the scope of a free declaration . In the following:
(lambda (&optional (x (foo 1))) ;[1]
(declare (notinline foo)) ;[2]
(foo x)) ;[3]

the call to foo in the rst line might be compiled inline even though the call to foo in the third
line must not be. This is because the notinline declaration for foo in the second line applies only
to the body on the third line. In order to suppress inlining for both calls , one might write:
(locally (declare (notinline foo)) ;[1]
(lambda (&optional (x (foo 1))) ;[2]
(foo x))) ;[3]

or, alternatively:
(lambda (&optional ;[1]
(x (locally (declare (notinline foo)) ;[2]
(foo 1)))) ;[3]
(declare (notinline foo)) ;[4]
(foo x)) ;[5]

Finally, here is an example that shows the scope of declarations in an iteration form .
(let ((x 1)) ;[1]
(declare (special x)) ;[2]

Evaluation and Compilation 3{31 3{32 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.4 Lambda Lists de ne-method-combination handler-case restart-case


A lambda list is a list that speci es a set of parameters (sometimes called lambda variables ) and defun labels
a protocol for receiving values for those parameters . et lambda
There are several kinds of lambda lists . Figure 3{12. Standardized Operators that use Ordinary Lambda Lists
Context Kind of Lambda List An ordinary lambda list can contain the lambda list keywords shown in Figure 3{13.
defun form ordinary lambda list
defmacro form macro lambda list &allow-other-keys &key &rest
lambda expression ordinary lambda list &aux &optional
et local function de nition ordinary lambda list
labels local function de nition ordinary lambda list
handler-case clause speci cation ordinary lambda list Figure 3{13. Lambda List Keywords used by Ordinary Lambda Lists
restart-case clause speci cation ordinary lambda list
macrolet local macro de nition macro lambda list Each element of a lambda list is either a parameter speci er or a lambda list keyword . Implemen-
de ne-method-combination ordinary lambda list tations are free to provide additional lambda list keywords . For a list of all lambda list keywords
de ne-method-combination :arguments option de ne-method-combination arguments lambda list used by the implementation, see lambda-list-keywords.
defstruct :constructor option boa lambda list The syntax for ordinary lambda lists is as follows:
defgeneric form generic function lambda list
defgeneric method clause specialized lambda list
defmethod form specialized lambda list lambda-list::=(fvar g*
defsetf form defsetf lambda list [&optional fvar j (var [init-form [supplied-p-parameter ]])g*]
de ne-setf-expander form macro lambda list var ]
deftype form deftype lambda list [&rest

destructuring-bind form destructuring lambda list [&key fvar j (fvar j (keyword-name var )g [init-form [supplied-p-parameter ]])g*
de ne-compiler-macro form macro lambda list [&allow-other-keys]]
de ne-modify-macro form de ne-modify-macro lambda list
[&aux fvar j (var [init-form])g*])
Figure 3{10. What Kind of Lambda Lists to Use
Figure 3{11 lists some de ned names that are applicable to lambda lists . A var or supplied-p-parameter must be a symbol that is not the name of a constant variable .
An init-form can be any form . Whenever any init-form is evaluated for any parameter speci er,
lambda-list-keywords lambda-parameters-limit that form may refer to any parameter variable to the left of the speci er in which the init-form
appears, including any supplied-p-parameter variables, and may rely on the fact that no other
Figure 3{11. De ned names applicable to lambda lists parameter variable has yet been bound (including its own parameter variable).
A keyword-name can be any symbol , but by convention is normally a keyword 1 ; all standardized
functions follow that convention.
3.4.1 Ordinary Lambda Lists An ordinary lambda list has ve parts, any or all of which may be empty. For information about
An ordinary lambda list is used to describe how a set of arguments is received by an ordinary the treatment of argument mismatches, see Section 3.5 (Error Checking in Function Calls).
function . The de ned names in Figure 3{12 are those which use ordinary lambda lists :

Evaluation and Compilation 3{33 3{34 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.4.1.1 Speci ers for the required parameters value. The rst object of each pair must be a symbol ; see Section 3.5.1.5 (Invalid Keyword
Arguments). The keyword parameter speci ers may optionally be followed by the lambda list
These are all the parameter speci ers up to the rst lambda list keyword ; if there are no lambda keyword &allow-other-keys.
list keywords , then all the speci ers are for required parameters. Each required parameter is
speci ed by a parameter variable var . var is bound as a lexical variable unless it is declared In each keyword parameter speci er must be a name var for the parameter variable. If the
special. var appears alone or in a (var init-form) combination, the keyword name used when matching
arguments to parameters is a symbol in the KEYWORD package whose name is the same (under
If there are n required parameters (n may be zero), there must be at least n passed arguments, string=) as var 's. If the notation ((keyword-name var ) init-form) is used, then the keyword name
and the required parameters are bound to the rst n passed arguments; see Section 3.5 (Error used to match arguments to parameters is keyword-name , which may be a symbol in any package .
Checking in Function Calls). The other parameters are then processed using any remaining (Of course, if it is not a symbol in the KEYWORD package , it does not necessarily self-evaluate, so
arguments. care must be taken when calling the function to make sure that normal evaluation still yields the
keyword name.) Thus
3.4.1.2 Speci ers for optional parameters (defun foo (&key radix (type 'integer)) ...)
If &optional is present, the optional parameter speci ers are those following &optional up to the means exactly the same as
next lambda list keyword or the end of the list. If optional parameters are speci ed, then each one
is processed as follows. If any unprocessed arguments remain, then the parameter variable var is (defun foo (&key ((:radix radix)) ((:type type) 'integer)) ...)
bound to the next remaining argument, just as for a required parameter. If no arguments remain,
however, then init-form is evaluated, and the parameter variable is bound to the resulting value The keyword parameter speci ers are, like all parameter speci ers, e ectively processed from left
(or to nil if no init-form appears in the parameter speci er). If another variable name supplied-p- to right. For each keyword parameter speci er, if there is an argument pair whose name matches
parameter appears in the speci er, it is bound to true if an argument had been available, and to that speci er's name (that is, the names are eq), then the parameter variable for that speci er is
false if no argument remained (and therefore init-form had to be evaluated). Supplied-p-parameter bound to the second item (the value) of that argument pair. If more than one such argument pair
is bound not to an argument but to a value indicating whether or not an argument had been matches, the leftmost argument pair is used. If no such argument pair exists, then the init-form
supplied for the corresponding var . for that speci er is evaluated and the parameter variable is bound to that value (or to nil if no
init-form was speci ed). supplied-p-parameter is treated as for &optional parameters: it is bound
3.4.1.3 A speci er for a rest parameter to true if there was a matching argument pair, and to false otherwise.
&rest , if present, must be followed by a single rest parameter speci er, which in turn must be fol- Unless keyword argument checking is suppressed, an argument pair must a name matched by a
lowed by another lambda list keyword or the end of the lambda list . After all optional parameter parameter speci er; see Section 3.5.1.4 (Unrecognized Keyword Arguments).
speci ers have been processed, then there may or may not be a rest parameter . If there is a rest If keyword argument checking is suppressed, then it is permitted for an argument pair to match
parameter , it is bound to a list of all as-yet-unprocessed arguments. If no unprocessed arguments no parameter speci er, and the argument pair is ignored, but such an argument pair is accessible
remain, the rest parameter is bound to the empty list . If there is no rest parameter and there are through the rest parameter if one was supplied. The purpose of these mechanisms is to allow
no keyword parameters , then an error should be signaled if any unprocessed arguments remain; sharing of argument lists among several lambda expressions and to allow either the caller or the
see Section 3.5 (Error Checking in Function Calls). The value of a rest parameter is permitted, called lambda expression to specify that such sharing may be taking place.
but not required, to share structure with the last argument to apply.
Note that if &key is present, a keyword argument of :allow-other-keys is always permitted|
3.4.1.4 Speci ers for keyword parameters regardless of whether the associated value is true or false . However, if the value is false , other
non-matching keywords are not tolerated (unless &allow-other-keys was used).
If &key is present, all speci ers up to the next lambda list keyword or the end of the list are Furthermore, if the receiving argument list speci es a regular argument which would be agged
keyword parameter speci ers. When keyword parameters are processed, the same arguments are by :allow-other-keys, then :allow-other-keys has both its special-cased meaning (identifying
processed that would be made into a list for a rest parameter . It is permitted to specify both whether additional keywords are permitted) and its normal meaning (data ow into the function
&rest and &key . In this case the remaining arguments are used for both purposes; that is, all in question).
remaining arguments are made into a list for the rest parameter , and are also processed for the
&key parameters. If &key is speci ed, there must remain an even number of arguments; see
Section 3.5.1.6 (Odd Number of Keyword Arguments). These arguments are considered as pairs,
the rst argument in each pair being interpreted as a name and the second as the corresponding

Evaluation and Compilation 3{35 3{36 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.4.1.4.1 Suppressing Keyword Argument Checking 3.4.1.6 Examples of Ordinary Lambda Lists
If &allow-other-keys was speci ed in the lambda list of a function , keyword 2 argument checking Here are some examples involving optional parameters and rest parameters :
is suppressed in calls to that function . ((lambda (a b) (+ a (* b 3))) 4 5) ! 19
If the :allow-other-keys argument is true in a call to a function , keyword 2 argument checking is ((lambda (a &optional (b 2)) (+ a (* b 3))) 4 5) ! 19
suppressed in that call. ((lambda (a &optional (b 2)) (+ a (* b 3))) 4) ! 10
((lambda (&optional (a 2 b) (c 3 d) &rest x) (list a b c d x)))
The :allow-other-keys argument is permissible in all situations involving keyword 2 arguments , ! (2 NIL 3 NIL NIL)
even when its associated value is false . ((lambda (&optional (a 2 b) (c 3 d) &rest x) (list a b c d x)) 6)

3.4.1.4.1.1 Examples of Suppressing Keyword Argument Checking ! (6 T 3


((lambda
NIL NIL)
(&optional (a 2 b) (c 3 d) &rest x) (list a b c d x)) 6 3)
! (6 T 3 T NIL)
;;; The caller can supply :ALLOW-OTHER-KEYS T to suppress checking. ((lambda (&optional (a 2 b) (c 3 d) &rest x) (list a b c d x)) 6 3 8)
((lambda (&key x) x) :x 1 :y 2 :allow-other-keys t) ! 1 ! (6 T 3 T (8))
;;; The callee can use &ALLOW-OTHER-KEYS to suppress checking. ((lambda (&optional (a 2 b) (c 3 d) &rest x) (list a b c d x))
((lambda (&key x &allow-other-keys) x) :x 1 :y 2) ! 1 6 3 8 9 10 11)
;;; :ALLOW-OTHER-KEYS NIL is always permitted. ! (6 t 3 t (8 9 10 11))
((lambda (&key) t) :allow-other-keys nil) ! T
;;; As with other keyword arguments, only the left-most pair
Here are some examples involving keyword parameters :
;;; named :ALLOW-OTHER-KEYS has any effect. ((lambda (a b &key c d) (list a b c d)) 1 2) ! (1 2 NIL NIL)
((lambda (&key x) x) ((lambda (a b &key c d) (list a b c d)) 1 2 :c 6) ! (1 2 6 NIL)
:x 1 :y 2 :allow-other-keys t :allow-other-keys nil) ((lambda (a b &key c d) (list a b c d)) 1 2 :d 8) ! (1 2 NIL 8)
! 1 ((lambda (a b &key c d) (list a b c d)) 1 2 :c 6 :d 8) ! (1 2 6 8)
;;; Only the left-most pair named :ALLOW-OTHER-KEYS has any effect, ((lambda (a b &key c d) (list a b c d)) 1 2 :d 8 :c 6) ! (1 2 6 8)
;;; so in safe code this signals a PROGRAM-ERROR (and might enter the ((lambda (a b &key c d) (list a b c d)) :a 1 :d 8 :c 6) ! (:a 1 6 8)
;;; debugger). In unsafe code, the consequences are undefined. ((lambda (a b &key c d) (list a b c d)) :a :b :c :d) ! (:a :b :d NIL)
((lambda (&key x) x) ;This call is not valid ((lambda (a b &key ((:sea c)) d) (list a b c d)) 1 2 :sea 6) ! (1 2 6 NIL)
:x 1 :y 2 :allow-other-keys nil :allow-other-keys t) ((lambda (a b &key ((c c)) d) (list a b c d)) 1 2 'c 6) ! (1 2 6 NIL)

3.4.1.5 Speci ers for &aux variables Here are some examples involving optional parameters , rest parameters , and keyword parameters
together:
These are not really parameters. If the lambda list keyword &aux is present, all speci ers after it
are auxiliary variable speci ers. After all parameter speci ers have been processed, the auxiliary ((lambda (a &optional (b 3) &rest x &key c (d a))

variable speci ers (those following &aux) are processed from left to right. For each one, init-form (list a b c d x)) 1)
! (1 3 NIL 1 ())
is evaluated and var is bound to that value (or to nil if no init-form was speci ed). &aux variable
processing is analogous to let* processing. ((lambda (a &optional (b 3)
(list a b c d x)) 1 2)
&rest x &key c (d a))

(lambda (x y &aux (a (car x)) (b 2) c) (list x y a b c)) ! (1 2 NIL 1 ())


 (lambda (x y) (let* ((a (car x)) (b 2) c) (list x y a b c))) ((lambda (a &optional (b 3) &rest x &key c (d a))
(list a b c d x)) :c 7)
! (:c 7 NIL :c ())
((lambda (a &optional (b 3) &rest x &key c (d a))
(list a b c d x)) 1 6 :c 7)
! (1 6 7 1 (:c 7))
((lambda (a &optional (b 3) &rest x &key c (d a))

Evaluation and Compilation 3{37 3{38 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

(list a b c d x)) 1 6 :d 8) A generic function lambda list can contain the lambda list keywords shown in Figure 3{14.
! (1 6 NIL 8 (:d 8))
((lambda (a &optional (b 3) &rest x &key c (d a)) &allow-other-keys &optional
(list a b c d x)) 1 6 :d 8 :c 9 :d 10) &key &rest
! (1 6 9 8 (:d 8 :c 9 :d 10))

As an example of the use of &allow-other-keys and :allow-other-keys, consider a function that Figure 3{14. Lambda List Keywords used by Generic Function Lambda Lists
takes two named arguments of its own and also accepts additional named arguments to be passed A generic function lambda list di ers from an ordinary lambda list in the following ways:
to make-array :
(defun array-of-strings (str dims &rest named-pairs Required arguments
&key (start 0) end &allow-other-keys)
(apply #'make-array dims Zero or more required parameters must be speci ed.
:initial-element (subseq str start end)
:allow-other-keys t Optional and keyword arguments
named-pairs))
Optional parameters and keyword parameters may not have default initial value forms nor
This function takes a string and dimensioning information and returns an array of the speci ed use supplied-p parameters.
dimensions, each of whose elements is the speci ed string . However, :start and :end named argu-
ments may be used to specify that a substring of the given string should be used. In addition, the Use of &aux
presence of &allow-other-keys in the lambda list indicates that the caller may supply additional
named arguments; the rest parameter provides access to them. These additional named argu- The use of &aux is not allowed.
ments are passed to make-array . The function make-array normally does not allow the named
arguments :start and :end to be used, and an error should be signaled if such named arguments
are supplied to make-array . However, the presence in the call to make-array of the named ar-
gument :allow-other-keys with a true value causes any extraneous named arguments, including
3.4.3 Specialized Lambda Lists
:start and :end, to be acceptable and ignored. A specialized lambda list is used to specialize a method for a particular signature and to
describe how arguments matching that signature are received by the method . The de ned names
3.4.2 Generic Function Lambda Lists in Figure 3{15 use specialized lambda lists in some way; see the dictionary entry for each for
information about how.
A generic function lambda list is used to describe the overall shape of the argument list to be
accepted by a generic function . Individual method signatures might contribute additional keyword defmethod defgeneric
parameters to the lambda list of the e ective method .
Figure 3{15. Standardized Operators that use Specialized Lambda Lists
A generic function lambda list is used by defgeneric.
A generic function lambda list has the following syntax: A specialized lambda list can contain the lambda list keywords shown in Figure 3{16.
lambda-list::=(fvar g* &allow-other-keys &key &rest
&aux &optional
[&optional fvar j (var )g*]
[&rest var ] Figure 3{16. Lambda List Keywords used by Specialized Lambda Lists
[&key fvar j (fvar j (keyword-name var )g)g*
[&allow-other-keys]])

Evaluation and Compilation 3{39 3{40 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

A specialized lambda list is syntactically the same as an ordinary lambda list except that each pattern::=(#wholevar #reqvars #optvars #restvar #keyvars #auxvars ) j
required parameter may optionally be associated with a class or object for which that parameter (#wholevar #reqvars #optvars . var )
is specialized .
A macro lambda list can contain the lambda list keywords shown in Figure 3{18.
lambda-list::=(fvar j (var [specializer ])g*
[&optional fvar j (var [init-form [supplied-p-parameter ]])g*]
&allow-other-keys &environment &rest
&aux &key &whole
[&rest var ] &body &optional
[&key fvar j (fvar j (keyword-name var )g [init-form [supplied-p-parameter ]])g* [&allow-other-keys]]
[&aux fvar j (var [init-form ])g*]) Figure 3{18. Lambda List Keywords used by Macro Lambda Lists
Optional parameters (introduced by &optional) and keyword parameters (introduced by &key )
can be supplied in a macro lambda list , just as in an ordinary lambda list . Both may contain
3.4.4 Macro Lambda Lists default initialization forms and supplied-p parameters .
A macro lambda list is used in describing macros de ned by the operators in Figure 3{17. &body is identical in function to &rest, but it can be used to inform certain output-formatting
and editing functions that the remainder of the form is treated as a body, and should be indented
de ne-compiler-macro defmacro macrolet accordingly. Only one of &body or &rest can be used at any particular level; see Section 3.4.4.1
de ne-setf-expander (Destructuring by Lambda Lists). &body can appear at any level of a macro lambda list ; for
details, see Section 3.4.4.1 (Destructuring by Lambda Lists).
Figure 3{17. Operators that use Macro Lambda Lists &whole is followed by a single variable that is bound to the entire macro-call form; this is the
value that the macro function receives as its rst argument. If &whole and a following variable
With the additional restriction that an environment parameter may appear only once (at any of appear, they must appear rst in lambda-list , before any other parameter or lambda list keyword .
the positions indicated), a macro lambda list has the following syntax: &whole can appear at any level of a macro lambda list . At inner levels, the &whole variable is
bound to the corresponding part of the argument, as with &rest, but unlike &rest , other argu-
reqvars::=fvar j #patterng* ments are also allowed. The use of &whole does not a ect the pattern of arguments speci ed.
optvars::=[&optional fvar j (fvar j #patterng [init-form [supplied-p-parameter ]])g*]
&environment is followed by a single variable that is bound to an environment representing the
restvar::=[f&rest j &bodyg fvar j #patterng] lexical environment in which the macro call is to be interpreted. This environment should be
used with macro-function, get-setf-expansion, compiler-macro-function, and macroexpand
keyvars::=[&key fvar j (fvar j (keyword-name fvarj #patterng)g [init-form [supplied-p-parameter ]])g* (for example) in computing the expansion of the macro, to ensure that any lexical bindings or
[&allow-other-keys]] de nitions established in the compilation environment are taken into account. &environment can
only appear at the top level of a macro lambda list , and can only appear once, but can appear
auxvars::=[&aux fvar j (var [init-form])g*] anywhere in that list; the &environment parameter is bound along with &whole before any other
variables in the lambda list , regardless of where &environment appears in the lambda list . The
envvar::=[&environment var ] object that is bound to the environment parameter has dynamic extent .
wholevar::=[&whole var ] Destructuring allows a macro lambda list to express the structure of a macro call syntax. If no
lambda list keywords appear, then the macro lambda list is a tree containing parameter names at
lambda-list::=(#wholevar #envvar #reqvars #envvar #optvars #envvar the leaves. The pattern and the macro form must have compatible tree structure ; that is, their
#restvar #envvar #keyvars #envvar #auxvars #envvar ) j
tree structure must be equivalent, or it must di er only in that some leaves of the pattern match
non-atomic objects of the macro form . For information about error detection in this situation , see
(#wholevar #envvar #reqvars #envvar #optvars #envvar . var ) Section 3.5.1.7 (Destructuring Mismatch).

Evaluation and Compilation 3{41 3{42 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

A destructuring lambda list (whether at top level or embedded) can be dotted, ending in a 3.4.4.1.2 Lambda-list-directed Destructuring by Lambda Lists
parameter name. This situation is treated exactly as if the parameter name that ends the list had
appeared preceded by &rest. An extension of data-directed destructuring of trees is lambda-list-directed destructuring. This
derives from the analogy between the three-element destructuring pattern
It is permissible for a macro form (or a subexpression of a macro form ) to be a dotted list only
when (... &rest var) or (... . var) is used to match it. It is the responsibility of the macro (first second third)
to recognize and deal with such situations. and the three-argument lambda list
3.4.4.1 Destructuring by Lambda Lists (first second third)

Anywhere in a macro lambda list where a parameter name can appear, and where ordinary Lambda-list-directed destructuring is identical to data-directed destructuring if no lambda list
lambda list syntax (as described in Section 3.4.1 (Ordinary Lambda Lists)) does not otherwise keywords appear in the pattern. Any list in the pattern (whether a sub-list or the whole pattern
allow a list , a destructuring lambda list can appear in place of the parameter name. When this is itself) that contains a lambda list keyword is interpreted specially. Elements of the list to the left
done, then the argument that would match the parameter is treated as a (possibly dotted) list , of the rst lambda list keyword are treated as destructuring patterns, as usual, but the remaining
to be used as an argument list for satisfying the parameters in the embedded lambda list . This is elements of the list are treated like a function's lambda list except that where a variable would
known as destructuring. normally be required, an arbitrary destructuring pattern is allowed. Note that in case of ambi-
guity, lambda list syntax is preferred over destructuring syntax. Thus, after &optional a list of
Destructuring is the process of decomposing a compound object into its component parts, us- elements is a list of a destructuring pattern and a default value form.
ing an abbreviated, declarative syntax, rather than writing it out by hand using the primitive The detailed behavior of each lambda list keyword in a lambda-list-directed destructuring pattern
component-accessing functions. Each component part is bound to a variable. is as follows:
A destructuring operation requires an object to be decomposed, a pattern that speci es what
components are to be extracted, and the names of the variables whose values are to be the &optional
components. Each following element is a variable or a list of a destructuring pattern, a default value
3.4.4.1.1 Data-directed Destructuring by Lambda Lists form, and a supplied-p variable. The default value and the supplied-p variable can be
omitted. If the list being destructured ends early, so that it does not have an element
In data-directed destructuring, the pattern is a sample object of the type to be decomposed. to match against this destructuring (sub)-pattern, the default form is evaluated and
Wherever a component is to be extracted, a symbol appears in the pattern; this symbol is the destructured instead. The supplied-p variable receives the value nil if the default form is
name of the variable whose value will be that component. used, t otherwise.
3.4.4.1.1.1 Examples of Data-directed Destructuring by Lambda Lists &rest , &body
An example pattern is The next element is a destructuring pattern that matches the rest of the list. &body
is identical to &rest but declares that what is being matched is a list of forms that
(a b c)
constitutes the body of form . This next element must be the last unless a lambda list
which destructures a list of three elements. The variable a is assigned to the rst element, b to the keyword follows it.
second, etc. A more complex example is
&aux
((first . rest) . more)
The remaining elements are not destructuring patterns at all, but are auxiliary variable
The important features of data-directed destructuring are its syntactic simplicity and the ability bindings.
to extend it to lambda-list-directed destructuring.
&whole
The next element is a destructuring pattern that matches the entire form in a macro, or
the entire subexpression at inner levels.

Evaluation and Compilation 3{43 3{44 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

&key 3.4.6 Boa Lambda Lists


Each following element is one of A boa lambda list is a lambda list that is syntactically like an ordinary lambda list , but that is
processed in \by order of argument" style.
a variable , A boa lambda list is used only in a defstruct form , when explicitly specifying the lambda list of a
or a list of a variable, an optional initialization form, and an optional supplied-p constructor function (sometimes called a \boa constructor").
variable. The &optional, &rest, &aux, &key , and &allow-other-keys lambda list keywords are recognized
in a boa lambda list . The way these lambda list keywords di er from their use in an ordinary
or a list of a list of a keyword and a destructuring pattern, an optional initialization lambda list follows.
form, and an optional supplied-p variable.
Consider this example, which describes how destruct processes its :constructor option.
The rest of the list being destructured is taken to be alternating keywords and values and
is taken apart appropriately. (:constructor create-foo
(a &optional b (c 'sea) &rest d &aux e (f 'eff)))
&allow-other-keys This de nes create-foo to be a constructor of one or more arguments. The rst argument is
Stands by itself. used to initialize the a slot. The second argument is used to initialize the b slot. If there isn't
any second argument, then the default value given in the body of the defstruct (if given) is used
3.4.5 Destructuring Lambda Lists instead. The third argument is used to initialize the c slot. If there isn't any third argument, then
the symbol sea is used instead. Any arguments following the third argument are collected into a
A destructuring lambda list is used by destructuring-bind. list and used to initialize the d slot. If there are three or fewer arguments, then nil is placed in
the d slot. The e slot is not initialized; its initial value is implementation-de ned . Finally, the f
Destructuring lambda lists are closely related to macro lambda lists ; see Section 3.4.4 (Macro slot is initialized to contain the symbol eff. &key and &allow-other-keys arguments default in a
Lambda Lists). A destructuring lambda list can contain all of the lambda list keywords listed for manner similar to that of &optional arguments: if no default is supplied in the lambda list then
macro lambda lists except for &environment, and supports destructuring in the same way. Inner the default value given in the body of the defstruct (if given) is used instead. For example:
lambda lists nested within a macro lambda list have the syntax of destructuring lambda lists . (defstruct (foo (:constructor CREATE-FOO (a &optional b (c 'sea)
A destructuring lambda list has the following syntax: &key (d 2)
&aux e (f 'eff))))
reqvars::=fvar j #lambda-list g* (a 1) (b 2) (c 3) (d 4) (e 5) (f 6))

optvars::=[&optional fvar j (fvar j #lambda-list g [init-form [supplied-p-parameter ]])g*] (create-foo 10) ! #S(FOO A 10 B 2 C SEA D 2 E implemention-dependent F EFF)
(create-foo 10 'bee 'see :d 'dee)
restvar::=[f&rest j &bodyg fvar j #lambda-list g] ! #S(FOO A 10 B BEE C SEE D DEE E implemention-dependent F EFF)

keyvars::=[&key fvar j (fvar j (keyword-name fvar j #lambda-list g)g [init-form [supplied-p-parameter ]])g* If keyword arguments of the form ((key var) [default [svar ]]) are speci ed, the slot name is
matched with var (not key).
[&allow-other-keys]]
The actions taken in the b and e cases were carefully chosen to allow the user to specify all possi-
auxvars::=[&aux fvar j (var [init-form])g*] ble behaviors. The &aux variables can be used to completely override the default initializations
given in the body.
envvar::=[&environment var ]
If no default value is supplied for an aux variable variable, the consequences are unde ned if an
wholevar::=[&whole var ] attempt is later made to read the corresponding slot 's value before a value is explicitly assigned.
If such a slot has a :type option speci ed, this suppressed initialization does not imply a type
lambda-list::=(#wholevar #reqvars #optvars #restvar #keyvars #auxvars ) j mismatch situation; the declared type is only required to apply when the slot is nally assigned.
(#wholevar #reqvars #optvars . var )

Evaluation and Compilation 3{45 3{46 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

With this de nition, the following can be written: 3.4.8 Deftype Lambda Lists
(create-foo 1 2) A deftype lambda list is used by deftype.
instead of A deftype lambda list has the same syntax as a macro lambda list , and can therefore contain the
(make-foo :a 1 :b 2)
lambda list keywords as a macro lambda list .
and create-foo provides defaulting di erent from that of make-foo. A deftype lambda list di ers from a macro lambda list only in that if no init-form is supplied
for an optional parameter or keyword parameter in the lambda-list , the default value for that
Additional arguments that do not correspond to slot names but are merely present to supply parameter is the symbol * (rather than nil).
values used in subsequent initialization computations are allowed. For example, in the de nition
(defstruct (frob (:constructor create-frob
3.4.9 De ne-modify-macro Lambda Lists
(a &key (b 3 have-b) (c-token 'c) A de ne-modify-macro lambda list is used by de ne-modify-macro.
(c (list c-token (if have-b 7 2))))))
a b c) A de ne-modify-macro lambda list can contain the lambda list keywords shown in Figure 3{20.
the c-token argument is used merely to supply a value used in the initialization of the c slot. The &optional &rest
supplied-p parameters associated with optional parameters and keyword parameters might also be
used this way. Figure 3{20. Lambda List Keywords used by De ne-modify-macro Lambda Lists
3.4.7 Defsetf Lambda Lists De ne-modify-macro lambda lists are similar to ordinary lambda lists , but do not support key-
A defsetf lambda list is used by defsetf . word arguments. de ne-modify-macro has no need match keyword arguments, and a rest param-
eter is sucient. Aux variables are also not supported, since de ne-modify-macro has no body
A defsetf lambda list has the following syntax: forms which could refer to such bindings . See the macro de ne-modify-macro.
lambda-list::=(fvar g* 3.4.10 De ne-method-combination Arguments Lambda Lists
[&optional fvar j (var [init-form [supplied-p-parameter ]])g*] A de ne-method-combination arguments lambda list is used by the :arguments option to
[&rest var ] de ne-method-combination.
[&key fvar j (fvar j (keyword-name var )g [init-form [supplied-p-parameter ]])g*
A de ne-method-combination arguments lambda list can contain the lambda list keywords shown
[&allow-other-keys]] in Figure 3{21.
[&environment var ] &allow-other-keys &key &rest
A defsetf lambda list can contain the lambda list keywords shown in Figure 3{19. &aux &optional &whole
&allow-other-keys &key &rest Figure 3{21. Lambda List Keywords used by De ne-method-combination arguments Lambda Lists
&environment &optional
De ne-method-combination arguments lambda lists are similar to ordinary lambda lists , but also
Figure 3{19. Lambda List Keywords used by Defsetf Lambda Lists permit the use of &whole.
A defsetf lambda list di ers from an ordinary lambda list only in that it does not permit the use
of &aux, and that it permits use of &environment, which introduces an environment parameter .

Evaluation and Compilation 3{47 3{48 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.4.11 Syntactic Interaction of Documentation Strings and 3.5 Error Checking in Function Calls
Declarations
In a number of situations, a documentation string can appear amidst a series of declare expres-
sions prior to a series of forms . 3.5.1 Argument Mismatch Detection
In that case, if a string S appears where a documentation string is permissible and is not followed
by either a declare expression or a form then S is taken to be a form ; otherwise, S is taken as
a documentation string . The consequences are unspeci ed if more than one such documentation
3.5.1.1 Safe and Unsafe Calls
string is present. A call is a safe call if each of the following is either safe code or system code (other than system
code that results from macro expansion of programmer code ):
 the call .
 the de nition of the function being called .
 the point of functional evaluation
The following special cases require some elaboration:
 If the function being called is a generic function , it is considered safe if all of the follow-
ing are safe code or system code :
{ its de nition (if it was de ned explicitly).
{ the method de nitions for all applicable methods .
{ the de nition of its method combination .
 For the form (coerce x 'function), where x is a lambda expression , the value of the
optimize quality safety in the global environment at the time the coerce is executed
applies to the resulting function .
 For a call to the function ensure-generic-function, the value of the optimize quality
safety in the environment object passed as the :environment argument applies to the
resulting generic function .
 For a call to compile with a lambda expression as the argument , the value of the optimize
quality safety in the global environment at the time compile is called applies to the
resulting compiled function .
 For a call to compile with only one argument, if the original de nition of the function
was safe , then the resulting compiled function must also be safe .
 A call to a method by call-next-method must be considered safe if each of the following
is safe code or system code :
{ the de nition of the generic function (if it was de ned explicitly).

Evaluation and Compilation 3{49 3{50 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

{ the method de nitions for all applicable methods . 3.5.1.5 Invalid Keyword Arguments
{ the de nition of the method combination . It is not permitted to supply a keyword argument to a function using a name that is not a
{ the point of entry into the body of the method de ning form , where the binding symbol .
of call-next-method is established.
If this situation occurs in a safe call , an error of type program-error must be signaled unless
{ the point of functional evaluation of the name call-next-method. keyword argument checking is suppressed as described in Section 3.4.1.4.1 (Suppressing Keyword
Argument Checking); and in an unsafe call the situation has unde ned consequences.
An unsafe call is a call that is not a safe call .
The informal intent is that the programmer can rely on a call to be safe , even when system code
3.5.1.6 Odd Number of Keyword Arguments
is involved, if all reasonable steps have been taken to ensure that the call is safe . For example, if An odd number of arguments must not be supplied for the keyword parameters .
a programmer calls mapcar from safe code and supplies a function that was compiled as safe , the If this situation occurs in a safe call , an error of type program-error must be signaled unless
implementation is required to ensure that mapcar makes a safe call as well.
keyword argument checking is suppressed as described in Section 3.4.1.4.1 (Suppressing Keyword
3.5.1.1.1 Error Detection Time in Safe Calls Argument Checking); and in an unsafe call the situation has unde ned consequences.
If an error is signaled in a safe call , the exact point of the signal is implementation-dependent .
In particular, it might be signaled at compile time or at run time, and if signaled at run time, it
3.5.1.7 Destructuring Mismatch
might be prior to, during, or after executing the call . However, it is always prior to the execution When matching a destructuring lambda list against a form , the pattern and the form must have
of the body of the function being called . compatible tree structure , as described in Section 3.4.4 (Macro Lambda Lists).
3.5.1.2 Too Few Arguments Otherwise, in a safe call , an error of type program-error must be signaled; and in an unsafe call
the situation has unde ned consequences.
It is not permitted to supply too few arguments to a function . Too few arguments means fewer
arguments than the number of required parameters for the function . 3.5.1.8 Errors When Calling a Next Method
If this situation occurs in a safe call , an error of type program-error must be signaled; and in an If call-next-method is called with arguments , the ordered set of applicable methods for the
unsafe call the situation has unde ned consequences. changed set of arguments for call-next-method must be the same as the ordered set of applicable
methods for the original arguments to the generic function , or else an error should be signaled.
3.5.1.3 Too Many Arguments The comparison between the set of methods applicable to the new arguments and the set appli-
It is not permitted to supply too many arguments to a function . Too many arguments means cable to the original arguments is insensitive to order di erences among methods with the same
more arguments than the number of required parameters plus the number of optional parame- specializers.
ters ; however, if the function uses &rest or &key, it is not possible for it to receive too many If call-next-method is called with arguments that specify a di erent ordered set of applicable
arguments. methods and there is no next method available, the test for di erent methods and the associated
If this situation occurs in a safe call , an error of type program-error must be signaled; and in an error signaling (when present) takes precedence over calling no-next-method.
unsafe call the situation has unde ned consequences.
3.5.1.4 Unrecognized Keyword Arguments
It is not permitted to supply a keyword argument to a function using a name that is not recog-
nized by that function unless keyword argument checking is suppressed as described in Section
3.4.1.4.1 (Suppressing Keyword Argument Checking).
If this situation occurs in a safe call , an error of type program-error must be signaled; and in an
unsafe call the situation has unde ned consequences.

Evaluation and Compilation 3{51 3{52 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

3.6 Traversal Rules and Side E ects 3.7 Destructive Operations


The consequences are unde ned when code executed during an object-traversing operation de-
structively modi es the object in a way that might a ect the ongoing traversal operation. In
particular, the following rules apply. 3.7.1 Modi cation of Literal Objects
List traversal The consequences are unde ned if literal objects are destructively modi ed. For this purpose, the
following operations are considered destructive :
For list traversal operations, the cdr chain of the list is not allowed to be destructively
modi ed. random-state
Array traversal Using it as an argument to the function random.
For array traversal operations, the array is not allowed to be adjusted and its ll pointer , cons
if any, is not allowed to be changed. Changing the car 1 or cdr 1 of the cons , or performing a destructive operation on an object
which is either the car 2 or the cdr 2 of the cons .
Hash-table traversal
array
For hash table traversal operations, new elements may not be added or deleted except
that the element corresponding to the current hash key may be changed or removed. Storing a new value into some element of the array , or performing a destructive operation
on an object that is already such an element .
Package traversal Changing the ll pointer , dimensions , or displacement of the array (regardless of whether
For package traversal operations (e.g., do-symbols), new symbols may not be interned in the array is actually adjustable ).
or uninterned from the package being traversed or any package that it uses except that
the current symbol may be uninterned from the package being traversed. Performing a destructive operation on another array that is displaced to the array or
that otherwise shares its contents with the array .
hash-table
Performing a destructive operation on any key .
Storing a new value 4 for any key , or performing a destructive operation on any object
that is such a value .
Adding or removing entries from the hash table .
structure-object
Storing a new value into any slot, or performing a destructive operation on an object that
is the value of some slot.
standard-object
Storing a new value into any slot, or performing a destructive operation on an object that
is the value of some slot.
Changing the class of the object (e.g., using the function change-class).

Evaluation and Compilation 3{53 3{54 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

readtable lambda Symbol


Altering the readtable case .
Altering the syntax type of any character in this readtable. Syntax:
lambda lambda-list [ fdeclarationg* j documentation ] fformg*
Altering the reader macro function associated with any character in the readtable , or
altering the reader macro functions associated with characters de ned as dispatching Arguments:
macro characters in the readtable . lambda-list |an ordinary lambda list .
stream declaration|a declare expression ; not evaluated.
Performing I/O operations on the stream , or closing the stream . documentation|a string ; not evaluated.
All other standardized types form|a form .
[This category includes, for example, character, condition, function, Description:
method-combination, method, number, package, pathname, restart , and symbol.] A lambda expression is a list that can be used in place of a function name in certain contexts to
denote a function by directly describing its behavior rather than indirectly by referring to the
There are no standardized destructive operations de ned on objects of these types . name of an established function .
Documentation is attached to the denoted function (if any is actually created) as a documentation
string .
3.7.2 Transfer of Control during a Destructive Operation See Also:
Should a transfer of control out of a destructive operation occur (e.g., due to an error) the state function, documentation, Section 3.1.3 (Lambda Expressions), Section 3.1.2.1.2.4 (Lambda
of the object being modi ed is implementation-dependent . Forms), Section 3.4.11 (Syntactic Interaction of Documentation Strings and Declarations)
3.7.2.1 Examples of Transfer of Control during a Destructive Operation Notes:
The lambda form
The following examples illustrate some of the many ways in which the implementation-dependent
nature of the modi cation can manifest itself. ((lambda lambda-list . body ) . arguments )
(let ((a (list 2 1 4 3 7 6 'five))) is semantically equivalent to the function form
(ignore-errors (sort a #'<))
a) (funcall #'(lambda lambda-list . body ) . arguments )
! (1 2 3 4 6 7 FIVE)
or
! (2 1 4 3 7 6 FIVE)
or
! (2)

(prog foo ((a (list 1 2 3 4 5 6 7 8 9 10)))


lambda Macro
(sort a #'(lambda (x y) (if (zerop (random 5)) (return-from foo a) (> x y)))))
! (1 2 3 4 5 6 7 8 9 10)
or
! (3 4 5 6 2 7 8 9 10 1)
Syntax:
or
! (1 2 4 3)
lambda lambda-list [ fdeclarationg* j documentation ] fformg* ! function
Arguments and Values:
lambda-list |an ordinary lambda list .

Evaluation and Compilation 3{55 3{56 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

compile
declaration|a declare expression ; not evaluated. warnings-p |a generalized boolean .
documentation|a string ; not evaluated. failure-p |a generalized boolean .
form|a form . Description:
function|a function . Compiles an interpreted function .
Description: compile produces a compiled function from de nition. If the de nition is a lambda expression , it
is coerced to a function . If the de nition is already a compiled function , compile either produces
Provides a shorthand notation for a function special form involving a lambda expression such that function itself (i.e., is an identity operation) or an equivalent function.
that:
If the name is nil, the resulting compiled function is returned directly as the primary value .
(lambda lambda-list [ fdeclaration g* j documentation ] fform g*) If a non-nil name is given, then the resulting compiled function replaces the existing function
 (function (lambda lambda-list [ fdeclarationg* j documentation ] fformg*)) de nition of name and the name is returned as the primary value ; if name is a symbol that names
 #'(lambda lambda-list [ fdeclarationg* j documentation ] fformg*) a macro , its macro function is updated and the name is returned as the primary value .
Examples: Literal objects appearing in code processed by the compile function are neither copied nor
coalesced . The code resulting from the execution of compile references objects that are eql to the
(funcall (lambda (x) (+ x 3)) 4) ! 7 corresponding objects in the source code.
See Also: compile is permitted, but not required, to establish a handler for conditions of type error. For
lambda (symbol) example, the handler might issue a warning and restart compilation from some implementation-
dependent point in order to let the compilation proceed without manual intervention.
Notes: The secondary value , warnings-p , is false if no conditions of type error or warning were detected
This macro could be implemented by:
by the compiler, and true otherwise.
(defmacro lambda (&whole form &rest bvl-decls-and-body)
(declare (ignore bvl-decls-and-body)) The tertiary value , failure-p , is false if no conditions of type error or warning (other than
`#',form) style-warning) were detected by the compiler, and true otherwise.
Examples:
compile Function
(defun foo () "bar") ! FOO
(compiled-function-p #'foo) !
(compile 'foo) ! FOO
implementation-dependent
(compiled-function-p #'foo) ! true
Syntax: (setf (symbol-function 'foo)
compile name &optional de nition ! function, warnings-p, failure-p (compile nil '(lambda () "replaced"))) ! #<Compiled-Function>
(foo) ! "replaced"
Arguments and Values: A ected By:
name |a function name , or nil.
*error-output*, *macroexpand-hook*.
de nition|a lambda expression or a function . The default is the function de nition of name if
it names a function , or the macro function of name if it names a macro . The consequences are The presence of macro de nitions and proclamations.
unde ned if no de nition is supplied when the name is nil. Exceptional Situations:
function|the function-name , or a compiled function . The consequences are unde ned if the lexical environment surrounding the function to be com-
piled contains any bindings other than those for macros , symbol macros , or declarations .

Evaluation and Compilation 3{57 3{58 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

For information about errors detected during the compilation process, see Section 3.2.5 (Excep- results from this normal argument evaluation becomes the value of the form parameter , and is
tional Situations in the Compiler). then evaluated as part of the eval form . For example:
See Also: (eval (list 'cdr (car '((quote (a . b)) c)))) ! b
compile- le The argument form (list 'cdr (car '((quote (a . b)) c))) is evaluated in the usual
way to produce the argument (cdr (quote (a . b))); eval then evaluates its argument ,
eval Function
(cdr (quote (a . b))), to produce b. Since a single evaluation already occurs for any argu-
ment form in any function form , eval is sometimes said to perform \an extra level of evaluation."

Syntax:
eval form ! fresult g*
eval-when Special Operator
Arguments and Values: Syntax:
form|a form . eval-when (fsituationg*) fformg* ! fresult g*
results |the values yielded by the evaluation of form. Arguments and Values:
Description: situation|One of the symbols :compile-toplevel, :load-toplevel, :execute, compile, load, or
eval.
Evaluates form in the current dynamic environment and the null lexical environment .
eval is a user interface to the evaluator. The use of eval, compile, and load is deprecated.
The evaluator expands macro calls as if through the use of macroexpand-1. forms |an implicit progn .
Constants appearing in code processed by eval are not copied nor coalesced. The code resulting results |the values of the forms if they are executed, or nil if they are not.
from the execution of eval references objects that are eql to the corresponding objects in the Description:
source code. The body of an eval-when form is processed as an implicit progn , but only in the situations listed.
Examples: The use of the situations :compile-toplevel (or compile) and :load-toplevel (or load) controls
(setq form '(1+ a) a 999) ! 999 whether and when evaluation occurs when eval-when appears as a top level form in code pro-
(eval form) ! 1000 cessed by compile- le. See Section 3.2.3 (File Compilation).
(eval 'form) ! (1+ A)
The use of the situation :execute (or eval) controls whether evaluation occurs for other eval-when
(let ((a '(this would break if eval used local value))) (eval form))
! 1000
forms ; that is, those that are not top level forms , or those in code processed by eval or compile.
If the :execute situation is speci ed in such a form , then the body forms are processed as an
See Also: implicit progn ; otherwise, the eval-when form returns nil.
macroexpand-1, Section 3.1.2 (The Evaluation Model) eval-when normally appears as a top level form , but it is meaningful for it to appear as a non-
top-level form . However, the compile-time side e ects described in Section 3.2 (Compilation) only
Notes: take place when eval-when appears as a top level form .
To obtain the current dynamic value of a symbol , use of symbol-value is equivalent (and usually
preferable) to use of eval. Examples:
Note that an eval form involves two levels of evaluation for its argument . First, form is evaluated One example of the use of eval-when is that for the compiler to be able to read a le properly
by the normal argument evaluation mechanism as would occur with any call . The object that when it uses user-de ned reader macros , it is necessary to write

Evaluation and Compilation 3{59 3{60 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

eval-when eval-when
(eval-when (:compile-toplevel :load-toplevel :execute) ;;; printed at compile time. If this form occurs in a non-top-level
(set-macro-character #\$ #'(lambda (stream char) ;;; position, nothing is printed at compile time. Regardless of context,
(declare (ignore char)) ;;; nothing is ever printed at load time or execution time.
(list 'dollar (read stream))))) ! T (eval-when (:execute :load-toplevel)
(eval-when (:compile-toplevel)
This causes the call to set-macro-character to be executed in the compiler's execution environ- (print 'foo6)))
ment, thereby modifying its reader syntax table.
;;; The EVAL-WHEN in this case is not at toplevel, so only the :EXECUTE
See Also:
;;; keyword is considered. At compile time, this has no effect. compile- le, Section 3.2 (Compilation)
;;;
;;;
At load time (if the LET is at toplevel), or at execution time
(if the LET is embedded in some other form which does not execute
Notes:
;;; until later) this sets (SYMBOL-FUNCTION 'FOO1) to a function which The following e ects are logical consequences of the de nition of eval-when:
;;; returns 1.
(let ((x 1))  Execution of a single eval-when expression executes the body code at most once.
(eval-when (:execute :load-toplevel :compile-toplevel)
(setf (symbol-function 'foo1) #'(lambda () x))))  Macros intended for use in top level forms should be written so that side-e ects are
done by the forms in the macro expansion. The macro-expander itself should not do the
;;; If this expression occurs at the toplevel of a file to be compiled, side-e ects.
;;; it has BOTH a compile time AND a load-time effect of setting
;;; (SYMBOL-FUNCTION 'FOO2) to a function which returns 2.
For example:
(eval-when (:execute :load-toplevel :compile-toplevel)
(let ((x 2))
Wrong:
(eval-when (:execute :load-toplevel :compile-toplevel) (defmacro foo ()
(setf (symbol-function 'foo2) #'(lambda () x))))) (really-foo)
`(really-foo))
;;; If this expression occurs at the toplevel of a file to be compiled,
;;; it has BOTH a compile time AND a load-time effect of setting the Right:
;;; function cell of FOO3 to a function which returns 3.
(defmacro foo ()
(eval-when (:execute :load-toplevel :compile-toplevel)
`(eval-when (:compile-toplevel :execute :load-toplevel) (really-foo)))
(setf (symbol-function 'foo3) #'(lambda () 3)))
Adherence to this convention means that such macros behave intuitively when appearing
;;; #4: This always does nothing. It simply returns NIL. as non-top-level forms .
(eval-when (:compile-toplevel)
(eval-when (:compile-toplevel)  Placing a variable binding around an eval-when reliably captures the binding because the
(print 'foo4))) compile-time-too mode cannot occur (i.e., introducing a variable binding means that the
eval-when is not a top level form ). For example,
;;; If this form occurs at toplevel of a file to be compiled, FOO5 is
;;; printed at compile time. If this form occurs in a non-top-level (let ((x 3))
;;; position, nothing is printed at compile time. Regardless of context, (eval-when (:execute :load-toplevel :compile-toplevel) (print x)))
;;; nothing is ever printed at load time or execution time.
(eval-when (:compile-toplevel)
prints 3 at execution (i.e., load) time, and does not print anything at compile time.
(eval-when (:execute)
This is important so that expansions of defun and defmacro can be done in terms of
(print 'foo5)))
eval-when and can correctly capture the lexical environment .
(defun bar (x) (defun foo () (+ x 3)))
;;; If this form occurs at toplevel of a file to be compiled, FOO6 is

Evaluation and Compilation 3{61 3{62 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

load-time-value
might expand into If a load-time-value expression appears within a function compiled with compile, the form is
evaluated at compile time in a null lexical environment . The result of this compile-time evalua-
(defun bar (x) tion is treated as a literal object in the compiled code.
(progn (eval-when (:compile-toplevel)
(compiler::notice-function-definition 'foo '(x))) If a load-time-value expression is processed by eval, form is evaluated in a null lexical environ-
(eval-when (:execute :load-toplevel) ment , and one value is returned. Implementations that implicitly compile (or partially compile)
(setf (symbol-function 'foo) #'(lambda () (+ x 3)))))) expressions processed by eval might evaluate form only once, at the time this compilation is
which would be treated by the above rules the same as performed.
If the same list (load-time-value form) is evaluated or compiled more than once, it is
(defun bar (x)
implementation-dependent whether form is evaluated only once or is evaluated more than once.
(setf (symbol-function 'foo) #'(lambda () (+ x 3))))
This can happen both when an expression being evaluated or compiled shares substructure, and
when the de nition of bar is not a top level form . when the same form is processed by eval or compile multiple times. Since a load-time-value
expression can be referenced in more than one place and can be evaluated multiple times by
eval, it is implementation-dependent whether each execution returns a fresh object or returns the
same object as some other execution. Users must use caution when destructively modifying the
load-time-value Special Operator
resulting object .
If two lists (load-time-value form) that are the same under equal but are not identical are
evaluated or compiled, their values always come from distinct evaluations of form. Their values
Syntax: may not be coalesced unless read-only-p is t.
load-time-value form &optional read-only-p ! object Examples:
Arguments and Values: ;;; The function INCR1 always returns the same value, even in different images.
form|a form ; evaluated as described below. ;;; The function INCR2 always returns the same value in a given image,
read-only-p |a boolean ; not evaluated. ;;; but the value it returns might vary from image to image.
(defun incr1 (x) (+ x #.(random 17)))
object |the primary value resulting from evaluating form. (defun incr2 (x) (+ x (load-time-value (random 17))))

Description: ;;; The function FOO1-REF references the nth element of the first of
load-time-value provides a mechanism for delaying evaluation of form until the expression is in ;;; the *FOO-ARRAYS* that is available at load time. It is permissible for
the run-time environment; see Section 3.2 (Compilation). ;;; that array to be modified (e.g., by SET-FOO1-REF); FOO1-REF will see the
;;; updated values.
Read-only-p designates whether the result can be considered a constant object . If t, the result is a (defvar *foo-arrays* (list (make-array 7) (make-array 8)))
read-only quantity that can, if appropriate to the implementation , be copied into read-only space (defun foo1-ref (n) (aref (load-time-value (first *my-arrays*) nil) n))
and/or coalesced with similar constant objects from other programs . If nil (the default), the result (defun set-foo1-ref (n val)
must be neither copied nor coalesced; it must be considered to be potentially modi able data. (setf (aref (load-time-value (first *my-arrays*) nil) n) val))

If a load-time-value expression is processed by compile- le, the compiler performs its normal ;;; The function BAR1-REF references the nth element of the first of
semantic processing (such as macro expansion and translation into machine code) on form, but ;;; the *BAR-ARRAYS* that is available at load time. The programmer has
arranges for the execution of form to occur at load time in a null lexical environment , with the ;;; promised that the array will be treated as read-only, so the system
result of this evaluation then being treated as a literal object at run time. It is guaranteed that ;;; can copy or coalesce the array.
the evaluation of form will take place only once when the le is loaded , but the order of evaluation (defvar *bar-arrays* (list (make-array 7) (make-array 8)))
with respect to the evaluation of top level forms in the le is implementation-dependent . (defun bar1-ref (n) (aref (load-time-value (first *my-arrays*) t) n))

Evaluation and Compilation 3{63 3{64 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

;;; This use of LOAD-TIME-VALUE permits the indicated vector to be coalesced Examples:
;;; even though NIL was specified, because the object was already read-only
;;; when it was written as a literal vector rather than created by a constructor. (setq a 1) ! 1
;;; User programs must treat the vector v as read-only. (quote (setq a 3)) ! (SETQ A 3)
(defun baz-ref (n) a ! 1
(let ((v (load-time-value #(A B C) nil))) 'a ! A
(values (svref v n) v))) ''a ! (QUOTE A)
'''a ! (QUOTE (QUOTE A))
;;; This use of LOAD-TIME-VALUE permits the indicated vector to be coalesced (setq a 43) ! 43
;;; even though NIL was specified in the outer situation because T was specified (list a (cons a 3)) ! (43 (43 . 3))
;;; in the inner situation. User programs must treat the vector v as read-only. (list (quote a) (quote (cons a 3))) ! (A (CONS A 3))
(defun baz-ref (n) 1 ! 1
(let ((v (load-time-value (load-time-value (vector 1 2 3) t) nil))) '1 ! 1
(values (svref v n) v))) "foo" ! "foo"
'"foo" ! "foo"
See Also: (car '(a b)) ! A
compile- le, compile, eval, Section 3.2.2.2 (Minimal Compilation), Section 3.2 (Compilation) '(car '(a b)) ! (CAR (QUOTE (A B)))
#(car '(a b)) ! #(CAR (QUOTE (A B)))
Notes: '#(car '(a b)) ! #(CAR (QUOTE (A B)))
load-time-value must appear outside of quoted structure in a \for evaluation " position. In See Also:
situations which would appear to call for use of load-time-value within a quoted structure, the
backquote reader macro is probably called for; see Section 2.4.6 (Backquote). Section 3.1 (Evaluation), Section 2.4.3 (Single-Quote), Section 3.2.1 (Compiler Terminology)
Specifying nil for read-only-p is not a way to force an object to become modi able if it has already Notes:
been made read-only. It is only a way to say that, for an object that is modi able, this operation The textual notation 'object is equivalent to (quote object ); see Section 3.2.1 (Compiler Termi-
is not intended to make that object read-only. nology).
Some objects , called self-evaluating objects , do not require quotation by quote. However, symbols
quote Special Operator and lists are used to represent parts of programs, and so would not be useable as constant data
in a program without quote. Since quote suppresses the evaluation of these objects , they become
data rather than program.
Syntax:
quote object
Arguments and Values:
! object
compiler-macro-function Accessor
object |an object ; not evaluated.
Syntax:
Description: compiler-macro-function name &optional environment ! function
The quote special operator just returns object . (setf (compiler-macro-function name &optional environment) new-function)
The consequences are unde ned if literal objects (including quoted objects ) are destructively
modi ed.
Arguments and Values:
name |a function name .

Evaluation and Compilation 3{65 3{66 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

de ne-compiler-macro
environment |an environment object .  The &whole argument is bound to the form argument that is passed to the compiler
macro function . The remaining lambda-list parameters are speci ed as if this form
function, new-function|a compiler macro function , or nil. contained the function name in the car and the actual arguments in the cdr , but if the
Description: car of the actual form is the symbol funcall, then the destructuring of the arguments is
actually performed using its cddr instead.
Accesses the compiler macro function named name , if any, in the environment .
A value of nil denotes the absence of a compiler macro function named name .  Documentation is attached as a documentation string to name (as kind compiler-macro)
and to the compiler macro function .
Exceptional Situations:
The consequences are unde ned if environment is non-nil in a use of setf of  Unlike an ordinary macro , a compiler macro can decline to provide an expansion merely
compiler-macro-function. by returning a form that is the same as the original (which can be obtained by using
&whole).
See Also: Examples:
de ne-compiler-macro, Section 3.2.2.1 (Compiler Macros)
(defun square (x) (expt x 2)) ! SQUARE

de ne-compiler-macro Macro
(define-compiler-macro square (&whole form arg)
(if (atom arg)
`(expt ,arg 2)
(case (car arg)
Syntax: (square (if (= (length arg) 2)
de ne-compiler-macro name lambda-list [ fdeclarationg* j documentation ] fformg* `(expt ,(nth 1 arg) 4)
! name form))
(expt (if (= (length arg) 3)
Arguments and Values: (if (numberp (nth 2 arg))
name |a function name . `(expt ,(nth 1 arg) ,(* 2 (nth 2 arg)))
`(expt ,(nth 1 arg) (* 2 ,(nth 2 arg))))
lambda-list |a macro lambda list . form))
(otherwise `(expt ,arg 2))))) ! SQUARE
declaration|a declare expression ; not evaluated. (square (square 3)) ! 81
documentation|a string ; not evaluated. (macroexpand '(square x)) ! (SQUARE X), false
(funcall (compiler-macro-function 'square) '(square x) nil)
form|a form . ! (EXPT X 2)
(funcall (compiler-macro-function 'square) '(square (square x)) nil)
Description: ! (EXPT X 4)
This is the normal mechanism for de ning a compiler macro function . Its manner of de nition is (funcall (compiler-macro-function 'square) '(funcall #'square x) nil)
the same as for defmacro; the only di erences are: ! (EXPT X 2)

 The name can be a function name naming any function or macro . (defun distance-positional (x1 y1 x2 y2)
(sqrt (+ (expt (- x2 x1) 2) (expt (- y2 y1) 2))))
 The expander function is installed as a compiler macro function for the name , rather than ! DISTANCE-POSITIONAL
as a macro function . (defun distance (&key (x1 0) (y1 0) (x2 x1) (y2 y1))
(distance-positional x1 y1 x2 y2))
! DISTANCE
(define-compiler-macro distance (&whole form
&rest key-value-pairs

Evaluation and Compilation 3{67 3{68 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

de ne-compiler-macro
&key (x1 0 x1-p) '((distance :x1 (setq x 7) :x2 (decf x) :y1 (decf x) :y2 (decf x))
(y1 0 y1-p) (distance :x1 (setq x 7) :y1 (decf x) :x2 (decf x) :y2 (decf x))
(x2 x1 x2-p) (distance :x1 (setq x 7) :y1 (incf x))
(y2 y1 y2-p) (distance :x1 (setq x 7) :y1 (incf x) :x1 (incf x))
&allow-other-keys (distance :x1 a1 :y1 b1 :x2 a2 :y2 b2)
&environment env) (distance :x1 a1 :x2 a2 :y1 b1 :y2 b2)
(flet ((key (n) (nth (* n 2) key-value-pairs)) (distance :x1 a1 :y1 b1 :z1 c1 :x2 a2 :y2 b2 :z2 c2)))
(arg (n) (nth (1+ (* n 2)) key-value-pairs)) (print (funcall (compiler-macro-function 'distance) form nil)))
(simplep (x) . (LET ((#:G6558 (SETQ X 7))
(let ((expanded-x (macroexpand x env))) . (#:G6559 (DECF X))
(or (constantp expanded-x env) . (#:G6560 (DECF X))
(symbolp expanded-x))))) . (#:G6561 (DECF X)))
(let ((n (/ (length key-value-pairs) 2))) . (DISTANCE :X1 #:G6558 :X2 #:G6559 :Y1 #:G6560 :Y2 #:G6561))
(multiple-value-bind (x1s y1s x2s y2s others) . (DISTANCE-POSITIONAL (SETQ X 7) (DECF X) (DECF X) (DECF X))
(loop for (key) on key-value-pairs by #'cddr . (LET ((#:G6567 (SETQ X 7))
count (eq key ':x1) into x1s . (#:G6568 (INCF X)))
count (eq key ':y1) into y1s . (DISTANCE :X1 #:G6567 :Y1 #:G6568))
count (eq key ':x2) into x2s . (DISTANCE :X1 (SETQ X 7) :Y1 (INCF X) :X1 (INCF X))
count (eq key ':y1) into y2s . (DISTANCE-POSITIONAL A1 B1 A2 B2)
count (not (member key '(:x1 :x2 :y1 :y2))) . (DISTANCE-POSITIONAL A1 B1 A2 B2)
into others . (DISTANCE :X1 A1 :Y1 B1 :Z1 C1 :X2 A2 :Y2 B2 :Z2 C2)
finally (return (values x1s y1s x2s y2s others))) ! NIL
(cond ((and (= n 4)
(eq (key 0) :x1) See Also:
(eq (key 1) :y1) compiler-macro-function, defmacro, documentation, Section 3.4.11 (Syntactic Interaction of
(eq (key 2) :x2) Documentation Strings and Declarations)
(eq (key 3) :y2))
`(distance-positional ,x1 ,y1 ,x2 ,y2)) Notes:
((and (if x1-p (and (= x1s 1) (simplep x1)) t) The consequences of writing a compiler macro de nition for a function in the COMMON-LISP package
(if y1-p (and (= y1s 1) (simplep y1)) t) are unde ned; it is quite possible that in some implementations such an attempt would override
(if x2-p (and (= x2s 1) (simplep x2)) t) an equivalent or equally important de nition. In general, it is recommended that a programmer
(if y2-p (and (= y2s 1) (simplep y2)) t) only write compiler macro de nitions for functions he or she personally maintains{writing a
(zerop others)) compiler macro de nition for a function maintained elsewhere is normally considered a violation
`(distance-positional ,x1 ,y1 ,x2 ,y2)) of traditional rules of modularity and data abstraction.
((and (< x1s 2) (< y1s 2) (< x2s 2) (< y2s 2)

defmacro
(zerop others))
(let ((temps (loop repeat n collect (gensym))))
`(let ,(loop for i below n
Macro
collect (list (nth i temps) (arg i)))
(distance
,@(loop for i below n
Syntax:
append (list (key i) (nth i temps))))))) defmacro name lambda-list [ fdeclarationg* j documentation ] fformg*
(t form)))))) ! name
! DISTANCE
(dolist (form
Arguments and Values:
name |a symbol .

Evaluation and Compilation 3{69 3{70 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

defmacro defmacro
lambda-list |a macro lambda list . (mac2 6 3 8) ! (6 T 3 T (8))
(defmacro mac3 (&whole r a &optional (b 3) &rest x &key c (d a))
declaration|a declare expression ; not evaluated. `'(,r ,a ,b ,c ,d ,x)) ! MAC3
(mac3 1 6 :d 8 :c 9 :d 10) ! ((MAC3 1 6 :D 8 :C 9 :D 10) 1 6 9 8 (:D 8 :C 9 :D 10))
documentation|a string ; not evaluated.
form|a form . The stipulation that an embedded destructuring lambda list is permitted only where ordinary
lambda list syntax would permit a parameter name but not a list is made to prevent ambiguity.
Description: For example, the following is not valid:
De nes name as a macro by associating a macro function with that name in the global environ- (defmacro loser (x &optional (a b &rest c) &rest z)
ment. The macro function is de ned in the same lexical environment in which the defmacro form ...)
appears.
because ordinary lambda list syntax does permit a list following &optional; the list (a b &rest c)
The parameter variables in lambda-list are bound to destructured portions of the macro call. would be interpreted as describing an optional parameter named a whose default value is that of
The expansion function accepts two arguments, a form and an environment . The expansion the form b, with a supplied-p parameter named &rest (not valid), and an extraneous symbol c in
function returns a form . The body of the expansion function is speci ed by forms . Forms are the list (also not valid). An almost correct way to express this is
executed in order. The value of the last form executed is returned as the expansion of the macro . (defmacro loser (x &optional ((a b &rest c)) &rest z)
The body forms of the expansion function (but not the lambda-list ) are implicitly enclosed in a ...)
block whose name is name .
The extra set of parentheses removes the ambiguity. However, the de nition is now incorrect
The lambda-list conforms to the requirements described in Section 3.4.4 (Macro Lambda Lists). because a macro call such as (loser (car pool)) would not provide any argument form for the
lambda list (a b &rest c), and so the default value against which to match the lambda list would
Documentation is attached as a documentation string to name (as kind function) and to the be nil because no explicit default value was speci ed. The consequences of this are unspeci ed
macro function . since the empty list, nil, does not have forms to satisfy the parameters a and b. The fully correct
defmacro can be used to rede ne a macro or to replace a function de nition with a macro de nition would be either
de nition. (defmacro loser (x &optional ((a b &rest c) '(nil nil)) &rest z)

Recursive expansion of the form returned must terminate, including the expansion of other ...)

macros which are subforms of other forms returned. or


The consequences are unde ned if the result of fully macroexpanding a form contains any circular (defmacro loser (x &optional ((&optional a b &rest c)) &rest z)
list structure except in literal objects . ...)

If a defmacro form appears as a top level form , the compiler must store the macro de nition These di er slightly: the rst requires that if the macro call speci es a explicitly then it must also
at compile time, so that occurrences of the macro later on in the le can be expanded correctly. specify b explicitly, whereas the second does not have this requirement. For example,
Users must ensure that the body of the macro can be evaluated at compile time if it is referenced
within the le being compiled . (loser (car pool) ((+ x 1)))

Examples: would be a valid call for the second de nition but not for the rst.
(defmacro dm1a (&whole x) `',x)
(defmacro mac1 (a b) "Mac1 multiplies and adds" (macroexpand '(dm1a)) ! (QUOTE (DM1A))
`(+ ,a (* ,b 3))) ! MAC1 (macroexpand '(dm1a a)) is an error.
(mac1 4 5) ! 19
(documentation 'mac1 'function) ! "Mac1 multiplies and adds" (defmacro dm1b (&whole x a &optional b) `'(,x ,a ,b))
(defmacro mac2 (&optional (a 2 b) (c 3 d) &rest x) `'(,a ,b ,c ,d ,x)) ! MAC2 (macroexpand '(dm1b)) is an error.
(mac2 6) ! (6 T 3 NIL NIL) (macroexpand '(dm1b q)) ! (QUOTE ((DM1B Q) Q NIL))

Evaluation and Compilation 3{71 3{72 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

macro-function
(macroexpand '(dm1b q r)) ! (QUOTE ((DM1B Q R) Q R)) function|a macro function or nil.
(macroexpand '(dm1b q r s)) is an error.
new-function|a macro function .
Description:
(defmacro dm2a (&whole form a b) `'(form ,form a ,a b ,b))
(macroexpand '(dm2a x y)) ! (QUOTE (FORM (DM2A X Y) A X B Y))
(dm2a x y) ! (FORM (DM2A X Y) A X B Y) Determines whether symbol has a function de nition as a macro in the speci ed environment .
(defmacro dm2b (&whole form a (&whole b (c . d) &optional (e 5)) If so, the macro expansion function, a function of two arguments, is returned. If symbol has
&body f &environment env) no function de nition in the lexical environment environment , or its de nition is not a macro ,
``(,',form ,,a ,',b ,',(macroexpand c env) ,',d ,',e ,',f)) macro-function returns nil.
;Note that because backquote is involved, implementations may differ
It is possible for both macro-function and special-operator-p to return true of symbol . The
;slightly in the nature (though not the functionality) of the expansion.
macro de nition must be available for use by programs that understand only the standard
(macroexpand '(dm2b x1 (((incf x2) x3 x4)) x5 x6))
! (LIST* '(DM2B X1 (((INCF X2) X3 X4))
Common Lisp special forms .
X1
X5 X6)
Examples:
'((((INCF X2) X3 X4)) (SETQ X2 (+ X2 1)) (X3 X4) 5 (X5 X6))), (defmacro macfun (x) '(macro-function 'macfun)) ! MACFUN
T (not (macro-function 'macfun)) ! false
(let ((x1 5))
(macrolet ((segundo (x) `(cadr ,x)))
(dm2b x1 (((segundo x2) x3 x4)) x5 x6))) (macrolet ((foo (&environment env)
! ((DM2B X1 (((SEGUNDO X2) X3 X4)) X5 X6) (if (macro-function 'bar env)
5 (((SEGUNDO X2) X3 X4)) (CADR X2) (X3 X4) 5 (X5 X6)) ''yes
''no)))

See Also:
(list (foo)
(macrolet ((bar () :beep))
de ne-compiler-macro, destructuring-bind, documentation, macroexpand, (foo))))
*macroexpand-hook*, macrolet, macro-function, Section 3.1 (Evaluation), Section 3.2 (Compi-
lation), Section 3.4.11 (Syntactic Interaction of Documentation Strings and Declarations) ! (NO YES)

macro-function Accessor A ected By:


(setf macro-function) , defmacro, and macrolet.
Syntax: Exceptional Situations:
macro-function symbol &optional environment ! function The consequences are unde ned if environment is non-nil in a use of setf of macro-function.
(setf (macro-function symbol &optional environment) new-function) See Also:
defmacro, Section 3.1 (Evaluation)
Notes:
Arguments and Values: setf can be used with macro-function to install a macro as a symbol's global function de nition:
symbol |a symbol . (setf (macro-function symbol) fn)

environment |an environment object . The value installed must be a function that accepts two arguments, the entire macro call and

Evaluation and Compilation 3{73 3{74 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

macroexpand, macroexpand-1
an environment , and computes the expansion for that call. Performing this operation causes (defmacro beta (x y) `(gamma ,x ,y)) ! BETA
symbol to have only that macro de nition as its global function de nition; any previous de nition, (defmacro delta (x y) `(gamma ,x ,y)) ! EPSILON
whether as a macro or as a function , is lost. (defmacro expand (form &environment env)
(multiple-value-bind (expansion expanded-p)

macroexpand, macroexpand-1
(macroexpand form env)
Function `(values ',expansion ',expanded-p))) ! EXPAND
(defmacro expand-1 (form &environment env)
(multiple-value-bind (expansion expanded-p)
Syntax: (macroexpand-1 form env)
`(values ',expansion ',expanded-p))) ! EXPAND-1
macroexpand form &optional env ! expansion, expanded-p
macroexpand-1 form &optional env ! expansion, expanded-p
Arguments and Values: ;; Simple examples involving just the global environment
(macroexpand-1 '(alpha a b)) ! (BETA A B), true
form|a form . (expand-1 (alpha a b)) ! (BETA A B), true
env |an environment object . The default is nil. (macroexpand '(alpha a b)) ! (GAMMA A B), true
(expand (alpha a b)) ! (GAMMA A B), true
expansion|a form . (macroexpand-1 'not-a-macro) ! NOT-A-MACRO, false
(expand-1 not-a-macro) ! NOT-A-MACRO, false
expanded-p |a generalized boolean . (macroexpand '(not-a-macro a b)) ! (NOT-A-MACRO A B), false
(expand (not-a-macro a b)) ! (NOT-A-MACRO A B), false
Description:
macroexpand and macroexpand-1 expand macros .
If form is a macro form , then macroexpand-1 expands the macro form call once. ;; Examples involving lexical environments
(macrolet ((alpha (x y) `(delta ,x ,y)))
macroexpand repeatedly expands form until it is no longer a macro form . In e ect, (macroexpand-1 '(alpha a b))) ! (BETA A B), true
macroexpand calls macroexpand-1 repeatedly until the secondary value it returns is nil. (macrolet ((alpha (x y) `(delta ,x ,y)))
(expand-1 (alpha a b))) ! (DELTA A B), true
If form is a macro form , then the expansion is a macro expansion and expanded-p is true . Other- (macrolet ((alpha (x y) `(delta ,x ,y)))
wise, the expansion is the given form and expanded-p is false . (macroexpand '(alpha a b))) ! (GAMMA A B), true
Macro expansion is carried out as follows. Once macroexpand-1 has determined that the form (macrolet ((alpha (x y) `(delta ,x ,y)))
true
is a macro form , it obtains an appropriate expansion function for the macro or symbol macro . (expand (alpha a b))) ! (GAMMA A B),
The value of *macroexpand-hook* is coerced to a function and then called as a function of three (macrolet ((beta (x y) `(epsilon ,x ,y)))
true
arguments: the expansion function , the form, and the env . The value returned from this call is (expand (alpha a b))) ! (EPSILON A B),
taken to be the expansion of the form. (let ((x (list 1 2 3)))
(symbol-macrolet ((a (first x)))
In addition to macro de nitions in the global environment, any local macro de nitions established (expand a))) ! (FIRST X), true
within env by macrolet or symbol-macrolet are considered. If only form is supplied as an argu- (let ((x (list 1 2 3)))
ment, then the environment is e ectively null, and only global macro de nitions as established by (symbol-macrolet ((a (first x)))
defmacro are considered. Macro de nitions are shadowed by local function de nitions. (macroexpand 'a))) ! A, false
Examples:
(symbol-macrolet ((b (alpha x y)))
(expand-1 b)) ! (ALPHA X Y), true
(symbol-macrolet ((b (alpha x y)))
(defmacro alpha (x y) `(beta ,x ,y)) ! ALPHA (expand b)) ! (GAMMA X Y), true
(symbol-macrolet ((b (alpha x y))

Evaluation and Compilation 3{75 3{76 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

de ne-symbol-macro
(a b)) Description:
(expand-1 a)) ! B, true Provides a mechanism for globally a ecting the macro expansion of the indicated symbol .
(symbol-macrolet ((b (alpha x y))
(a b)) Globally establishes an expansion function for the symbol macro named by symbol . The only
(expand a)) ! (GAMMA X Y), true guaranteed property of an expansion function for a symbol macro is that when it is applied to the
form and the environment it returns the correct expansion. (In particular, it is implementation-
dependent whether the expansion is conceptually stored in the expansion function, the environ-
ment , or both.)
;; Examples of shadowing behavior
(flet ((beta (x y) (+ x y))) Each global reference to symbol (i.e., not shadowed 2 by a binding for a variable or symbol macro
(expand (alpha a b))) ! (BETA A B), true named by the same symbol ) is expanded by the normal macro expansion process; see Section
(macrolet ((alpha (x y) `(delta ,x ,y))) 3.1.2.1.1 (Symbols as Forms). The expansion of a symbol macro is subject to further macro
(flet ((alpha (x y) (+ x y))) expansion in the same lexical environment as the symbol macro reference, exactly analogous to
(expand (alpha a b)))) ! (ALPHA A B), false normal macros .
(let ((x (list 1 2 3)))
(symbol-macrolet ((a (first x))) The consequences are unspeci ed if a special declaration is made for symbol while in the scope of
(let ((a x)) this de nition (i.e., when it is not shadowed 2 by a binding for a variable or symbol macro named
(expand a)))) ! A, false by the same symbol ).
A ected By: Any use of setq to set the value of the symbol while in the scope of this de nition is treated as if
it were a setf . psetq of symbol is treated as if it were a psetf , and multiple-value-setq is treated
defmacro, setf of macro-function, macrolet, symbol-macrolet as if it were a setf of values.
See Also: A binding for a symbol macro can be shadowed 2 by let or symbol-macrolet.
*macroexpand-hook*, defmacro, setf of macro-function, macrolet, symbol-macrolet, Section
3.1 (Evaluation) Examples:
Notes: (defvar *things* (list 'alpha 'beta 'gamma)) ! *THINGS*
Neither macroexpand nor macroexpand-1 makes any explicit attempt to expand macro forms
that are either subforms of the form or subforms of the expansion. Such expansion might occur (define-symbol-macro thing1 (first *things*)) ! THING1
implicitly, however, due to the semantics or implementation of the macro function . (define-symbol-macro thing2 (second *things*)) ! THING2
(define-symbol-macro thing3 (third *things*)) ! THING3

de ne-symbol-macro Macro thing1 ! ALPHA


(setq thing1 'ONE) ! ONE
*things* ! (ONE BETA GAMMA)

Syntax: (multiple-value-setq (thing2 thing3) (values 'two 'three))


thing3 ! THREE
! TWO

de ne-symbol-macro symbol expansion *things* ! (ONE TWO THREE)


! symbol
Arguments and Values: (list thing2 (let ((thing2 2)) thing2)) ! (TWO 2)

symbol |a symbol . Exceptional Situations:


expansion|a form . If symbol is already de ned as a global variable , an error of type program-error is signaled.
See Also:
symbol-macrolet, macroexpand

Evaluation and Compilation 3{77 3{78 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

Examples:
symbol-macrolet Special Operator ;;; The following is equivalent to
;;; (list 'foo (let ((x 'bar)) x)),
;;; not

Syntax: ;;; (list 'foo (let (('foo 'bar)) 'foo))


(symbol-macrolet ((x 'foo))
symbol-macrolet (f(symbol expansion)g*) fdeclarationg* fformg* (list x (let ((x 'bar)) x)))
! fresult g* ! (foo bar)
Arguments and Values:
not
! (foo foo)

symbol |a symbol . (symbol-macrolet ((x '(foo x)))


expansion|a form . (list x))
! ((FOO X))
declaration|a declare expression ; not evaluated.
Exceptional Situations:
forms |an implicit progn . If an attempt is made to bind a symbol that is de ned as a global variable , an error of type
results |the values returned by the forms . program-error is signaled.
Description: If declaration contains a special declaration that names one of the symbols being bound by
symbol-macrolet, an error of type program-error is signaled.
symbol-macrolet provides a mechanism for a ecting the macro expansion environment for
symbols . See Also:
symbol-macrolet lexically establishes expansion functions for each of the symbol macros named with-slots, macroexpand
by symbols . The only guaranteed property of an expansion function for a symbol macro is that
when it is applied to the form and the environment it returns the correct expansion. (In particu- Notes:
lar, it is implementation-dependent whether the expansion is conceptually stored in the expansion The special form symbol-macrolet is the basic mechanism that is used to implement with-slots.
function, the environment , or both.) If a symbol-macrolet form is a top level form , the forms are also processed as top level forms .
Each reference to symbol as a variable within the lexical scope of symbol-macrolet is expanded See Section 3.2.3 (File Compilation).
by the normal macro expansion process; see Section 3.1.2.1.1 (Symbols as Forms). The expansion
macroexpand-hook
of a symbol macro is subject to further macro expansion in the same lexical environment as the
symbol macro invocation, exactly analogous to normal macros . Variable
Exactly the same declarations are allowed as for let with one exception: symbol-macrolet signals
an error if a special declaration names one of the symbols being de ned by symbol-macrolet. Value Type:
When the forms of the symbol-macrolet form are expanded, any use of setq to set the value of a designator for a function of three arguments : a macro function , a macro form , and an environ-
one of the speci ed variables is treated as if it were a setf . psetq of a symbol de ned as a symbol ment object .
macro is treated as if it were a psetf , and multiple-value-setq is treated as if it were a setf of Initial Value:
values.
a designator for a function that is equivalent to the function funcall, but that might have addi-
The use of symbol-macrolet can be shadowed by let. In other words, symbol-macrolet only tional implementation-dependent side-e ects.
substitutes for occurrences of symbol that would be in the scope of a lexical binding of symbol
surrounding the forms .

Evaluation and Compilation 3{79 3{80 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

proclaim
Description: Description:
Used as the expansion interface hook by macroexpand-1 to control the macro expansion process. Establishes the declaration speci ed by declaration-speci er in the global environment .
When a macro form is to be expanded, this function is called with three arguments: the macro
function , the macro form , and the environment in which the macro form is to be expanded. The Such a declaration , sometimes called a global declaration or a proclamation , is always in force
environment object has dynamic extent ; the consequences are unde ned if the environment object unless locally shadowed .
is referred to outside the dynamic extent of the macro expansion function. Names of variables and functions within declaration-speci er refer to dynamic variables and global
Examples: function de nitions, respectively.
(defun hook (expander form env)
Figure 3{22 shows a list of declaration identi ers that can be used with proclaim.
(format t "Now expanding: ~S~%" form)
(funcall expander form env)) ! HOOK
declaration inline optimize type
(defmacro machook (x y) `(/ (+ ,x ,y) 2)) ! MACHOOK
ftype notinline special
(macroexpand '(machook 1 2)) ! (/ (+ 1 2) 2), true
(let ((*macroexpand-hook* #'hook)) (macroexpand '(machook 1 2))) Figure 3{22. Global Declaration Speci ers
. Now expanding (MACHOOK 1 2)
! (/ (+ 1 2) 2), true An implementation is free to support other (implementation-de ned ) declaration identi ers as
well.
See Also:
macroexpand, macroexpand-1, funcall, Section 3.1 (Evaluation) Examples:
Notes: (defun declare-variable-types-globally (type vars)

The net e ect of the chosen initial value is to just invoke the macro function , giving it the macro (proclaim `(type ,type ,@vars))

form and environment as its two arguments. type)

Users or user programs can assign this variable to customize or trace the macro expansion ;; Once this form is executed, the dynamic variable *TOLERANCE*
mechanism. Note, however, that this variable is a global resource, potentially shared by multiple ;; must always contain a float.
programs ; as such, if any two programs depend for their correctness on the setting of this variable , (declare-variable-types-globally 'float '(*tolerance*))
those programs may not be able to run in the same Lisp image . For this reason, it is frequently ! FLOAT
best to con ne its uses to debugging situations.
See Also:
Users who put their own function into *macroexpand-hook* should consider saving the previous declaim, declare, Section 3.2 (Compilation)
value of the hook, and calling that value from their own.
Notes:
Although the execution of a proclaim form has e ects that might a ect compilation, the compiler
proclaim Function does not make any attempt to recognize and specially process proclaim forms . A proclamation
such as the following, even if a top level form , does not have any e ect until it is executed:
Syntax: (proclaim '(special *x*))

proclaim declaration-speci er ! implementation-dependent If compile time side e ects are desired, eval-when may be useful. For example:
Arguments and Values: (eval-when (:execute :compile-toplevel :load-toplevel)

declaration-speci er |a declaration speci er . (proclaim '(special *x*)))

In most such cases, however, it is preferrable to use declaim for this purpose.

Evaluation and Compilation 3{81 3{82 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

declare
Since proclaim forms are ordinary function forms , macro forms can expand into them.
defgeneric do-external-symbols prog
de ne-compiler-macro do-symbols prog*
declaim Macro de ne-method-combination
de ne-setf-expander
dolist
dotimes
restart-case
symbol-macrolet
defmacro et with-accessors
Syntax: defmethod handler-case with-hash-table-iterator
defsetf labels with-input-from-string
declaim fdeclaration-speci er g* ! implementation-dependent deftype let with-open- le
Arguments and Values: defun let* with-open-stream
destructuring-bind locally with-output-to-string
declaration-speci er |a declaration speci er ; not evaluated. do macrolet with-package-iterator
Description: do* multiple-value-bind with-slots
do-all-symbols pprint-logical-block
Establishes the declarations speci ed by the declaration-speci ers .
If a use of this macro appears as a top level form in a le being processed by the le compiler , Figure 3{23. Standardized Forms In Which Declarations Can Occur
the proclamations are also made at compile-time. As with other de ning macros, it is unspeci ed
whether or not the compile-time side-e ects of a declaim persist after the le has been compiled . A declare expression can only occur where speci ed by the syntax of these forms . The conse-
quences of attempting to evaluate a declare expression are unde ned. In situations where such
Examples: expressions can appear, explicit checks are made for their presence and they are never actually
evaluated; it is for this reason that they are called \declare expressions " rather than \declare
See Also: forms ."
declare, proclaim Macro forms cannot expand into declarations; declare expressions must appear as actual subex-
pressions of the form to which they refer.
declare Symbol Figure 3{24 shows a list of declaration identi ers that can be used with declare.
dynamic-extent ignore optimize
Syntax: ftype
ignorable
inline
notinline
special
type
declare fdeclaration-speci er g*
Arguments: Figure 3{24. Local Declaration Speci ers
declaration-speci er |a declaration speci er ; not evaluated.
An implementation is free to support other (implementation-de ned ) declaration identi ers as
Description: well.
A declare expression , sometimes called a declaration , can occur only at the beginning of the
bodies of certain forms ; that is, it may be preceded only by other declare expressions , or by a Examples:
documentation string if the context permits.
(defun nonsense (k x z)
A declare expression can occur in a lambda expression or in any of the forms listed in Figure (foo z x) ;First call to foo
3{23. (let ((j (foo k x)) ;Second call to foo
(x (* k k)))
(declare (inline foo) (special x z))
(foo x j z))) ;Third call to foo

Evaluation and Compilation 3{83 3{84 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

In this example, the inline declaration applies only to the third call to foo, but not to the rst An ignorable declaration speci es that for-value references to the indicated bindings might or
or second ones. The special declaration of x causes let to make a dynamic binding for x, and might not occur within the scope of the declaration . Within the scope of such a declaration , it is
causes the reference to x in the body of let to be a dynamic reference. The reference to x in the not desirable for a compiler to issue a warning about the presence or absence of either a for-value
second call to foo is a local reference to the second parameter of nonsense. The reference to x in reference to any var or fn, or a special declaration for any var .
the rst call to foo is a local reference, not a special one. The special declaration of z causes the
reference to z in the third call to foo to be a dynamic reference; it does not refer to the parameter When not within the scope of a ignore or ignorable declaration , it is desirable for a compiler
to nonsense named z, because that parameter binding has not been declared to be special. (The to issue a warning about any var for which there is neither a for-value reference nor a special
special declaration of z does not appear in the body of defun, but in an inner form , and therefore declaration , or about any fn for which there is no for-value reference .
does not a ect the binding of the parameter .) Any warning about a \used" or \unused" binding must be of type style-warning, and may not
Exceptional Situations: a ect program semantics.
The consequences of trying to use a declare expression as a form to be evaluated are unde ned. The stream variables established by with-open- le, with-open-stream, with-input-from-string,
and with-output-to-string, and all iteration variables are, by de nition, always \used". Using
See Also: (declare (ignore v )), for such a variable v has unspeci ed consequences.
proclaim, Section 4.2.3 (Type Speci ers), declaration, dynamic-extent, ftype, ignorable,
ignore, inline, notinline, optimize, type See Also:
declare
ignore, ignorable Declaration
dynamic-extent Declaration
Syntax:
(ignore fvar | (function fn)g*) Syntax:
(ignorable fvar | (function fn)g*) (dynamic-extent [ fvar g* | (function fn)* ] )
Arguments: Arguments:
var |a variable name .
var |a variable name .
fn|a function name .
fn|a function name .
Valid Context: Valid Context:
declaration
declaration
Binding Types A ected: Binding Types A ected:
variable , function
variable , function
Description: Description:
The ignore and ignorable declarations refer to for-value references to variable bindings for the In some containing form , F , this declaration asserts for each vari (which need not be bound by
F ), and for each value vij that vari takes on, and for each object xijk that is an otherwise inacces-
vars and to function bindings for the fns . sible part of vij at any time when vij becomes the value of vari , that just after the execution of
An ignore declaration speci es that for-value references to the indicated bindings will not occur F terminates, xijk is either inaccessible (if F established a binding for vari ) or still an otherwise
within the scope of the declaration . Within the scope of such a declaration , it is desirable for a inaccessible part of the current value of vari (if F did not establish a binding for vari). The same
compiler to issue a warning about the presence of either a for-value reference to any var or fn, or relation holds for each fni , except that the bindings are in the function namespace .
a special declaration for any var .

Evaluation and Compilation 3{85 3{86 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

dynamic-extent dynamic-extent
The compiler is permitted to use this information in any way that is appropriate to the imple- (declare (dynamic-extent x))
mentation and that does not con ict with the semantics of Common Lisp. ...)

dynamic-extent declarations can be free declarations or bound declarations . Note that although the initial value of x is not explicit, the f function is responsible for assem-
bling the list x from the passed arguments, so the f function can be optimized by the compiler to
The vars and fns named in a dynamic-extent declaration must not refer to symbol macro or construct a stack-allocated list instead of a heap-allocated list in implementations that support
macro bindings. such.
Examples: In the following example,
Since stack allocation of the initial value entails knowing at the object 's creation time that the
object can be stack-allocated , it is not generally useful to make a dynamic-extent declaration (let ((x (list 'a1 'b1 'c1))
for variables which have no lexically apparent initial value. For example, it is probably useful to (y (cons 'a2 (cons 'b2 (cons 'c2 nil)))))
write: (declare (dynamic-extent x y))
...)
(defun f ()
(let ((x (list 1 2 3))) The otherwise inaccessible parts of x are three conses , and the otherwise inaccessible parts of y
(declare (dynamic-extent x)) are three other conses . None of the symbols a1, b1, c1, a2, b2, c2, or nil is an otherwise inacces-
...)) sible part of x or y because each is interned and hence accessible by the package (or packages ) in
which it is interned . However, if a freshly allocated uninterned symbol had been used, it would
This would permit those compilers that wish to do so to stack allocate the list held by the local have been an otherwise inaccessible part of the list which contained it.
variable x. It is permissible, but in practice probably not as useful, to write:
;; In this example, the implementation is permitted to stack allocate
(defun g (x) (declare (dynamic-extent x)) ...) ;; the list that is bound to X.
(defun f () (g (list 1 2 3))) (let ((x (list 1 2 3)))
(declare (dynamic-extent x))
Most compilers would probably not stack allocate the argument to g in f because it would be (print x)
a modularity violation for the compiler to assume facts about g from within f. Only an im- :done)
plementation that was willing to be responsible for recompiling f if the de nition of g changed . (1 2 3)
incompatibly could legitimately stack allocate the list argument to g in f. ! :DONE
Here is another example: ;; In this example, the list to be bound to L can be stack-allocated .
(declaim (inline g)) (defun zap (x y z)
(defun g (x) (declare (dynamic-extent x)) ...) (do ((l (list x y z) (cdr l)))
(defun f () (g (list 1 2 3))) ((null l))
(declare (dynamic-extent l))
(defun f () (prin1 (car l)))) ! ZAP
(flet ((g (x) (declare (dynamic-extent x)) ...)) (zap 1 2 3)
(g (list 1 2 3)))) . 123
! NIL
In the previous example, some compilers might determine that optimization was possible and ;; Some implementations might open-code LIST-ALL-PACKAGES in a way
others might not. ;; that permits using stack allocation
of the list to be bound to L.
(do ((l (list-all-packages) (cdr l)))
A variant of this is the so-called \stack allocated rest list" that can be achieved (in implementa-
tions supporting the optimization) by: ((null l))
(declare (dynamic-extent l))
(defun f (&rest x) (let ((name (package-name (car l))))
(when (string-search "COMMON-LISP" name) (print name))))

Evaluation and Compilation 3{87 3{88 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

type
. "COMMON-LISP"
. "COMMON-LISP-USER"
type Declaration
! NIL
Syntax:
;; Some implementations might have the ability to stack allocate (type typespec fvar g*)
;; rest lists. A declaration such as the following should be a cue
;; to such implementations that stack-allocation of the rest list (typespec fvar g*)
;; would be desirable.
(defun add (&rest x) Arguments:
(declare (dynamic-extent x)) typespec |a type speci er .
(apply #'+ x)) ! ADD
(add 1 2 3) ! 6 var |a variable name .
(defun zap (n m)
Valid Context:
;; Computes (RANDOM (+ M 1)) at relative speed of roughly O(N). declaration or proclamation
;; It may be slow, but with a good compiler at least it
;; doesn't waste much heap storage. :-}
Binding Types A ected:
(let ((a (make-array n))) variable
(declare (dynamic-extent a))
(dotimes (i n)
Description:
(declare (dynamic-extent i)) A ects only variable bindings and speci es that the vars take on values only of the speci ed
(setf (aref a i) (random (+ i 1)))) typespec . In particular, values assigned to the variables by setq, as well as the initial values of the
(aref a m))) ! ZAP vars must be of the speci ed typespec . type declarations never apply to function bindings (see
(< (zap 5 3) 3) ! true ftype).
The following are in error, since the value of x is used outside of its extent : A type declaration of a symbol de ned by symbol-macrolet is equivalent to wrapping a the
expression around the expansion of that symbol , although the symbol 's macro expansion is not
(length (list (let ((x (list 1 2 3))) ; Invalid actually a ected.
(declare (dynamic-extent x))
x))) The meaning of a type declaration is equivalent to changing each reference to a variable (var )
within the scope of the declaration to (the typespec var ), changing each expression assigned to
(progn (let ((x (list 1 2 3))) ; Invalid the variable (new-value ) within the scope of the declaration to (the typespec new-value ), and
(declare (dynamic-extent x)) executing (the typespec var ) at the moment the scope of the declaration is entered.
x)
nil)
A type declaration is valid in all declarations. The interpretation of a type declaration is as
follows:
See Also: 1. During the execution of any reference to the declared variable within the scope of the
declaration, the consequences are unde ned if the value of the declared variable is not of
declare the declared type .
Notes: 2. During the execution of any setq of the declared variable within the scope of the declara-
The most common optimization is to stack allocate the initial value of the objects named by the
vars . tion, the consequences are unde ned if the newly assigned value of the declared variable is
not of the declared type .
It is permissible for an implementation to simply ignore this declaration.
3. At the moment the scope of the declaration is entered, the consequences are unde ned if

Evaluation and Compilation 3{89 3{90 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

type type
the value of the declared variable is not of the declared type . (setf (aref an-array 3) (* 2 (aref an-array 3)))
(let ((foo 0))
A type declaration a ects only variable references within its scope. (declare (type (signed-byte 5) foo))
If nested type declarations refer to the same variable, then the value of the variable must be a (setf foo (aref an-array 0))))
member of the intersection of the declared types . (frob *one-array*)
If there is a local type declaration for a dynamic variable, and there is also a global type procla- (frob *another-array*)
mation for that same variable, then the value of the variable within the scope of the local declara- The above de nition of frob is equivalent to:
tion must be a member of the intersection of the two declared types .
type declarations can be free declarations or bound declarations . (defun frob (an-array)
(setf (the (signed-byte 5) (aref an-array 1)) 31)
A symbol cannot be both the name of a type and the name of a declaration. De ning a symbol (setf (the (signed-byte 5) (aref an-array 2)) 127)
as the name of a class , structure , condition , or type , when the symbol has been declared as a (setf (the (signed-byte 5) (aref an-array 3))
declaration name, or vice versa, signals an error. (* 2 (the (signed-byte 5) (aref an-array 3))))
(let ((foo 0))
Within the lexical scope of an array type declaration, all references to array elements are as- (declare (type (signed-byte 5) foo))
sumed to satisfy the expressed array element type (as opposed to the upgraded array element (setf foo (the (signed-byte 5) (aref an-array 0)))))
type ). A compiler can treat the code within the scope of the array type declaration as if each
access of an array element were surrounded by an appropriate the form. Given an implementation in which xnums are 29 bits but xnum arrays are upgraded to signed
32-bit arrays , the following could be compiled with all xnum arithmetic:
Examples: (defun bump-counters (counters)
(defun f (x y) (declare (type (array fixnum *) bump-counters))
(declare (type fixnum x y)) (dotimes (i (length counters))
(let ((z (+ x y))) (incf (aref counters i))))
(declare (type fixnum z))
z)) ! F
(f 1 2) ! 3 See Also:
;; The previous definition of F is equivalent to declare, declaim, proclaim
(defun f (x y)
;; This declaration is a shorthand form of the TYPE declaration Notes:
(declare (fixnum x y)) (typespec fvar g*) is an abbreviation for (type typespec fvar g*).
;; To declare the type of a return value, it's not necessary to
;; create a named variable. A THE special form can be used instead.
A type declaration for the arguments to a function does not necessarily imply anything about the
(the fixnum (+ x y))) ! F
type of the result. The following function is not permitted to be compiled using implementation-
(f 1 2) ! 3
dependent xnum -only arithmetic:
(defun f (x y) (declare (fixnum x y)) (+ x y))

(defvar *one-array* (make-array 10 :element-type '(signed-byte 5))) To see why, consider (f most-positive-fixnum 1). Common Lisp de nes that F must return a
(defvar *another-array* (make-array 10 :element-type '(signed-byte 8))) bignum here, rather than signal an error or produce a mathematically incorrect result. If you have
special knowledge such \ xnum over ow" cases will not come up, you can declare the result value
(defun frob (an-array) to be in the xnum range, enabling some compilers to use more ecient arithmetic:
(declare (type (array (signed-byte 5) 1) an-array))
(setf (aref an-array 1) 31) (defun f (x y)
(setf (aref an-array 2) 127) (declare (fixnum x y))
(the fixnum (+ x y)))

Evaluation and Compilation 3{91 3{92 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

inline, notinline
Note, however, that in the three-argument case, because of the possibility of an implicit interme- While no conforming implementation is required to perform inline expansion of user-de ned
diate value growing too large, the following will not cause implementation-dependent xnum -only functions, those implementations that do attempt to recognize the following paradigm:
arithmetic to be used:
To de ne a function f that is not inline by default but for which (declare (inline f)) will make
(defun f (x y) f be locally inlined, the proper de nition sequence is:
(declare (fixnum x y z))
(the fixnum (+ x y z))) (declaim (inline f))
(defun f ...)
To see why, consider (f most-positive-fixnum 1 -1). Although the arguments and the result (declaim (notinline f))
are all xnums , an intermediate value is not a xnum . If it is important that implementation-
dependent xnum -only arithmetic be selected in implementations that provide it, consider writing The inline proclamation preceding the defun form ensures that the compiler has the opportunity
something like this instead: save the information necessary for inline expansion, and the notinline proclamation following the
defun form prevents f from being expanded inline everywhere.
(defun f (x y)
(declare (fixnum x y z)) notinline speci es that it is undesirable to compile the functions named by function-names in-
(the fixnum (+ (the fixnum (+ x y)) z))) line. A compiler is not free to ignore this declaration; calls to the speci ed functions must be
implemented as out-of-line subroutine calls.
If one of the functions mentioned has a lexically apparent local de nition (as made by et
inline, notinline Declaration
or labels), then the declaration applies to that local de nition and not to the global function
de nition.
In the presence of a compiler macro de nition for function-name , a notinline declaration prevents
Syntax: that compiler macro from being used. An inline declaration may be used to encourage use of
compiler macro de nitions. inline and notinline declarations otherwise have no e ect when the
(inline ffunction-name g*)
lexically visible de nition of function-name is a macro de nition.
ffunction-name g*)
(notinline
inline and notinline declarations can be free declarations or bound declarations . inline and
Arguments: notinline declarations of functions that appear before the body of a et or labels form that
de nes that function are bound declarations . Such declarations in other contexts are free declara-
function-name |a function name . tions .
Valid Context: Examples:
declaration or proclamation
Binding Types A ected: ;; The globally defined function DISPATCH should be open-coded,
;; if the implementation supports inlining, unless a NOTINLINE
function ;; declaration overrides this effect.

Description: (declaim (inline dispatch))


(defun dispatch (x) (funcall (get (car x) 'dispatch) x))
inline speci es that it is desirable for the compiler to produce inline calls to the functions named ;; Here is an example where inlining would be encouraged.
by function-names ; that is, the code for a speci ed function-name should be integrated into the (defun top-level-1 () (dispatch (read-command)))
calling routine, appearing \in line" in place of a procedure call. A compiler is free to ignore this ;; Here is an example where inlining would be prohibited.
declaration. inline declarations never apply to variable bindings . (defun top-level-2 ()
(declare (notinline dispatch))
If one of the functions mentioned has a lexically apparent local de nition (as made by et (dispatch (read-command)))
or labels), then the declaration applies to that local de nition and not to the global function ;; Here is an example where inlining would be prohibited.
de nition. (declaim (notinline dispatch))
(defun top-level-3 () (dispatch (read-command)))

Evaluation and Compilation 3{93 3{94 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

;; Here is an example where inlining would be encouraged. See Also:


(defun top-level-4 () declare, declaim, proclaim
(declare (inline dispatch))

declaration
(dispatch (read-command)))

See Also: Declaration


declare, declaim, proclaim
Syntax:
ftype Declaration
Arguments:
(declaration fname g*)

name |a symbol .
Syntax:
(ftype type ffunction-name g*) Valid Context:
proclamation only
Arguments:
function-name |a function name . Description:
type |a type speci er . Advises the compiler that each name is a valid but potentially non-standard declaration name.
The purpose of this is to tell one compiler not to issue warnings for declarations meant for
Valid Context: another compiler or other program processor.
declaration or proclamation Examples:
Binding Types A ected: (declaim (declaration author target-language target-machine))
function (declaim (target-language ada))

Description: (declaim (target-machine IBM-650))


(defun strangep (x)
Speci es that the functions named by function-names are of the functional type type . For exam- (declare (author "Harry Tweeker"))
ple: (member x '(strange weird odd peculiar)))

(declare (ftype (function (integer list) t) ith) See Also:


(ftype (function (number) float) sine cosine))
declaim, proclaim
If one of the functions mentioned has a lexically apparent local de nition (as made by et
or labels), then the declaration applies to that local de nition and not to the global function
de nition. ftype declarations never apply to variable bindings (see type).
The lexically apparent bindings of function-names must not be macro de nitions. (This is because
ftype declares the functional de nition of each function name to be of a particular subtype of
function, and macros do not denote functions .)
ftype declarations can be free declarations or bound declarations . ftype declarations of func-
tions that appear before the body of a et or labels form that de nes that function are bound
declarations . Such declarations in other contexts are free declarations .

Evaluation and Compilation 3{95 3{96 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

optimize
optimize Declaration ((null z))
;; This inner loop really needs to burn.
(declare (optimize speed))
Syntax: (declare (fixnum i))
(optimize fquality quality value )g*)
| ( ))

Arguments: See Also:


quality |an optimize quality . declare, declaim, proclaim, Section 3.3.4 (Declaration Scope)
value |one of the integers 0, 1, 2, or 3. Notes:
An optimize declaration never applies to either a variable or a function binding . An optimize
Valid Context: declaration can only be a free declaration . For more information, see Section 3.3.4 (Declaration
declaration or proclamation Scope).
Description:
Advises the compiler that each quality should be given attention according to the speci ed
corresponding value . Each quality must be a symbol naming an optimize quality ; the names and special Declaration
meanings of the standard optimize qualities are shown in Figure 3{25.
Name Meaning Syntax:
(special fvar g*)
compilation-speed speed of the compilation process
debug
safety
ease of debugging
run-time error checking
Arguments:
space both code size and run-time space var |a symbol .
speed speed of the object code Valid Context:
declaration or proclamation
Figure 3{25. Optimize qualities
Binding Types A ected:
There may be other, implementation-de ned optimize qualities . variable
A value 0 means that the corresponding quality is totally unimportant, and 3 that the quality is
extremely important; 1 and 2 are intermediate values, with 1 the neutral value. (quality 3) can be
Description:
abbreviated to quality . Speci es that all of the vars named are dynamic. This speci er a ects variable bindings and
a ects references. All variable bindings a ected are made to be dynamic bindings , and a ected
Note that code which has the optimization (safety 3), or just safety, is called safe code . variable references refer to the current dynamic binding . For example:
The consequences are unspeci ed if a quality appears more than once with di erent values . (defun hack (thing *mod*)
(declare (special *mod*))
;The binding of the parameter
; *mod* is visible to hack1,
Examples: (hack1 (car thing)))
(defun hack1 (arg)
; but not that of thing.

(defun often-used-subroutine (x y) (declare (special *mod*)) ;Declare references to *mod*


(declare (optimize (safety 2))) ;within hack1 to be special.
(error-check x y) (if (atom arg) *mod*
(hairy-setup x) (cons (hack1 (car arg)) (hack1 (cdr arg)))))
(do ((i 0 (+ i 1))
(z x (cdr z)))

Evaluation and Compilation 3{97 3{98 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

special
A special declaration does not a ect inner bindings of a var ; the inner bindings implicitly shadow (x y)) ;[3] 3rd occurrence of x
a special declaration and must be explicitly re-declared to be special. special declarations never (declare (special x))
apply to function bindings . (list old-x x)))
(bar 'first 'second) ! (FIRST SECOND)
special declarations can be either bound declarations , a ecting both a binding and references, or
free declarations , a ecting only references, depending on whether the declaration is attached to a (defun few (x &optional (y *foo*))
variable binding. (declare (special *foo*))
...)
When used in a proclamation , a special declaration speci er applies to all bindings as well as to
all references of the mentioned variables. For example, after The reference to *foo* in the rst line of this example is not special even though there is a
special declaration in the second line.
(declaim (special x))
(declaim (special prosp)) ! implementation-dependent
then in a function de nition such as (setq prosp 1 reg 1) ! 1
(let ((prosp 2) (reg 2)) ;the binding of prosp is special
(defun example (x) ...)
(set 'prosp 3) (set 'reg 3) ;due to the preceding proclamation,
the parameter x is bound as a dynamic variable rather than as a lexical variable. (list prosp reg)) ;whereas the variable reg is lexical
! (3 2)
Examples: (list prosp reg) ! (1 3)

(defun declare-eg (y) ;this y is special (declaim (special x)) ;x is always special.
(declare (special y)) (defun example (x y)
(let ((y t)) ;this y is lexical (declare (special y))
(list y (let ((y 3) (x (* x 2)))
(locally (declare (special y)) y)))) ;this y refers to the (print (+ y (locally (declare (special y)) y)))
;special binding of y (let ((y 4)) (declare (special y)) (foo x)))) ! EXAMPLE
! DECLARE-EG
(declare-eg nil) ! (T NIL) In the contorted code above, the outermost and innermost bindings of y are dynamic, but the
middle binding is lexical. The two arguments to + are di erent, one being the value, which is 3, of
(setf (symbol-value 'x) 6) the lexical variable y, and the other being the value of the dynamic variable named y (a binding
(defun foo (x) ;a lexical binding of x of which happens, coincidentally, to lexically surround it at an outer level). All the bindings of x
(print x) and references to x are dynamic, however, because of the proclamation that x is always special.
(let ((x (1+ x))) ;a special binding of x
(declare (special x)) ;and a lexical reference See Also:
(bar)) defparameter, defvar
(1+ x))
(defun bar ()
(print (locally (declare (special x))
x))) locally Special Operator
(foo 10)
. 10
. 11 Syntax:
! 11 locally fdeclarationg* fformg* ! fresult g*
(setf (symbol-value 'x) 6)
(defun bar (x y) ;[1] 1st occurrence of x Arguments and Values:
(let ((old-x x) ;[2] 2nd occurrence of x -- same as 1st occurrence
Declaration|a declare expression ; not evaluated.

Evaluation and Compilation 3{99 3{100 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

locally
forms |an implicit progn . Notes:
results |the values of the forms . The special declaration may be used with locally to a ect references to, rather than bindings of,
variables .
Description: If a locally form is a top level form , the body forms are also processed as top level forms . See
Sequentially evaluates a body of forms in a lexical environment where the given declarations have Section 3.2.3 (File Compilation).
e ect.
Examples: the Special Operator
(defun sample-function (y) ;this y is regarded as special

Syntax:
(declare (special y))
(let ((y t)) ;this y is regarded as lexical
(list y the value-type form ! fresult g*

Arguments and Values:


(locally (declare (special y))
;; this next y is regarded as special
y)))) value-type |a type speci er ; not evaluated.
! SAMPLE-FUNCTION
(sample-function nil) ! (T NIL) form|a form ; evaluated.
(setq x '(1 2 3) y '(4 . 5)) ! (4 . 5)
results |the values resulting from the evaluation of form. These values must conform to the type
;;; The following declarations are not notably useful in specific.
supplied by value-type ; see below.
;;; They just offer a sample of valid declaration syntax using LOCALLY.
(locally (declare (inline floor) (notinline car cdr))
Description:
(declare (optimize space))
the speci es that the values 1a returned by form are of the types speci ed by value-type . The
(floor (car x) (cdr y))) ! 0, 1
consequences are unde ned if any result is not of the declared type.
It is permissible for form to yield a di erent number of values than are speci ed by value-type ,
;;; This example shows a definition of a function that has a particular set
provided that the values for which types are declared are indeed of those types . Missing values are
;;; of OPTIMIZE settings made locally to that definition.
treated as nil for the purposes of checking their types .
(locally (declare (optimize (safety 3) (space 3) (speed 0))) Regardless of number of values declared by value-type , the number of values returned by the the
(defun frob (w x y &optional (z (foo x y))) special form is the same as the number of values returned by form.
(mumble x y z w)))
! FROB Examples:
;;; This is like the previous example, except that the optimize settings (the symbol (car (list (gensym)))) ! #:G9876
;;; remain in effect for subsequent definitions in the same compilation unit. (the fixnum (+ 5 7)) ! 12
(declaim (optimize (safety 3) (space 3) (speed 0))) (the (values) (truncate 3.2 2)) ! 1, 1.2
(defun frob (w x y &optional (z (foo x y))) (the integer (truncate 3.2 2)) ! 1, 1.2
(mumble x y z w)) (the (values integer) (truncate 3.2 2)) ! 1, 1.2
! FROB (the (values integer float) (truncate 3.2 2)) ! 1, 1.2
(the (values integer float symbol) (truncate 3.2 2)) ! 1, 1.2

See Also:
(the (values integer float symbol t null list)
(truncate 3.2 2)) ! 1, 1.2
declare (let ((i 100))
(declare (fixnum i))

Evaluation and Compilation 3{101 3{102 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

(the fixnum (1+ i))) ! 101 Exceptional Situations:


(let* ((x (list 'a 'b 'c)) Should signal type-error if its argument is not a symbol .
(y 5))
(setf (the fixnum (car x)) y) Notes:
x) ! (5 B C) Historically, this function was called special-form-p. The name was nally declared a misnomer
and changed, since it returned true for special operators , not special forms .
Exceptional Situations:
The consequences are unde ned if the values yielded by the form are not of the type speci ed by
value-type . constantp Function
See Also: Syntax:
values constantp form &optional environment ! generalized-boolean
Notes: Arguments and Values:
The values type speci er can be used to indicate the types of multiple values : form|a form .
(the (values integer integer) (floor x y))
(the (values string t) environment |an environment object . The default is nil.
(gethash the-key the-string-table))
generalized-boolean|a generalized boolean .
setf can be used with the type declarations. In this case the declaration is transferred to the form Description:
that speci es the new value. The resulting setf form is then analyzed.
Returns true if form can be determined by the implementation to be a constant form in the
indicated environment ; otherwise, it returns false indicating either that the form is not a constant
special-operator-p Function form or that it cannot be determined whether or not form is a constant form .
The following kinds of forms are considered constant forms :
Syntax:  Self-evaluating objects (such as numbers , characters , and the various kinds of arrays ) are
special-operator-p symbol ! generalized-boolean always considered constant forms and must be recognized as such by constantp.
Arguments and Values:  Constant variables , such as keywords , symbols de ned by Common Lisp as constant (such
symbol |a symbol . as nil, t, and pi), and symbols declared as constant by the user in the indicated environ-
ment using defconstant are always considered constant forms and must be recognized as
generalized-boolean|a generalized boolean . such by constantp.
Description:  quote forms are always considered constant forms and must be recognized as such by
Returns true if symbol is a special operator ; otherwise, returns false . constantp.
Examples:  An implementation is permitted, but not required, to detect additional constant forms . If
(special-operator-p 'if) ! true it does, it is also permitted, but not required, to make use of information in the environ-
(special-operator-p 'car) ! false ment . Examples of constant forms for which constantp might or might not return true
(special-operator-p 'one) ! false are: (sqrt pi), (+ 3 2), (length '(a b c)), and (let ((x 7)) (zerop x)).

Evaluation and Compilation 3{103 3{104 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

constantp
If an implementation chooses to make use of the environment information, such actions as expand-
ing macros or performing function inlining are permitted to be used, but not required; however,
expanding compiler macros is not permitted.
Examples:
(constantp 1) ! true
(constantp 'temp) ! false
(constantp ''temp)) ! true
(defconstant this-is-a-constant 'never-changing) ! THIS-IS-A-CONSTANT
(constantp 'this-is-a-constant) ! true
(constantp "temp") ! true
(setq a 6) ! 6
(constantp a) ! true
(constantp '(sin pi)) ! implementation-dependent
(constantp '(car '(x))) ! implementation-dependent
(constantp '(eql x x)) ! implementation-dependent
(constantp '(typep x 'nil)) ! implementation-dependent
(constantp '(typep x 't)) ! implementation-dependent
(constantp '(values this-is-a-constant)) ! implementation-dependent
(constantp '(values 'x 'y)) ! implementation-dependent
(constantp '(let ((a '(a b c))) (+ (length a) 6))) ! implementation-dependent
A ected By:
The state of the global environment (e.g., which symbols have been declared to be the names of
constant variables ).
See Also:
defconstant

Evaluation and Compilation 3{105 3{106 Programming Language|Common Lisp

You might also like