replace transform: don't fall on NIL.
[sbcl.git] / doc / manual / beyond-ansi.texinfo
blob5cf2b8461ab83f5e33d18acf79bca240d63189bc
1 @node  Beyond the ANSI Standard
2 @comment  node-name,  next,  previous,  up
3 @chapter Beyond the ANSI Standard
5 SBCL is derived from CMUCL, which implements many extensions to the
6 ANSI standard. SBCL doesn't support as many extensions as CMUCL, but
7 it still has quite a few.  @xref{Contributed Modules}.
9 @menu
10 * Reader Extensions::
11 * Package-Local Nicknames::
12 * Package Variance::
13 * Garbage Collection::
14 * Generic Function Dispatch::
15 * Slot Access::
16 * Metaobject Protocol::
17 * Extensible Sequences::
18 * Support For Unix::
19 * Unicode Support::
20 * Customization Hooks for Users::
21 * Tools To Help Developers::
22 * Resolution of Name Conflicts::
23 * Hash Table Extensions::
24 * Random Number Generation::
25 * Timeouts and Deadlines::
26 * Miscellaneous Extensions::
27 * Stale Extensions::
28 * Efficiency Hacks::
29 @end menu
31 @node Reader Extensions
32 @comment  node-name,  next,  previous,  up
33 @section Reader Extensions
34 @cindex Reader Extensions
36 @subsection Extended Package Prefix Syntax
37 @cindex Extended Package Prefix Syntax
38 @cindex Package Prefix Syntax, extended
40 @vindex @cl{@earmuffs{package}}
41 @cindex Interning Symbols
42 @cindex Symbols, interning
43 @findex @cl{intern}
44 SBCL supports extended package prefix syntax, which allows specifying
45 an alternate package instead of @code{*package*} for the reader to use
46 as the default package for interning symbols:
48 @lisp
49 @var{package-name}::@var{form-with-interning-into-package}
50 @end lisp
52 Example:
54 @lisp
55   'foo::(bar quux zot) == '(foo::bar foo::quux foo::zot)
56 @end lisp
58 @cindex Package Locks
59 @vindex @cl{@earmuffs{package}}
60 @code{*package*} is not rebound during the course of reading a form
61 with extended package prefix syntax; if @code{foo::bar} would cause a
62 read-time package lock violation, so does @code{foo::(bar)}.
64 @subsection Symbol Name Normalization
65 @cindex Symbol Name Normalization
66 @cindex Normalization, Symbol Name
67 @cindex Unicode
68 @cindex NFKC
70 SBCL also extends the reader to normalize all symbols to Normalization
71 Form KC in builds with Unicode enabled. Whether symbols are normalized
72 is controlled by
74 @include fun-sb-ext-readtable-normalization.texinfo
76 Symbols created by
77 @findex @cl{intern}
78 @code{intern} and similar functions are not affected by this setting. If
79 @code{sb-ext:readtable-normalization} is @code{t}, symbols that are not
80 normalized are escaped during printing.
82 @subsection Decimal Syntax for Rationals
83 @cindex Decimal Syntax for Rationals
84 @cindex Rational, decimal syntax for
85 @tindex @cl{float}
87 SBCL supports a decimal syntax for rationals, modelled after the
88 standard syntax for floating-point numbers.  If a number with
89 floating-point syntax has an exponent marker of @code{r} or @code{R}
90 (rather than one of the standard exponent markers), it is read as the
91 rational with the exact value of the decimal number expressed as a
92 float.
94 @vindex @cl{@earmuffs{read-default-float-format}}
95 @tindex @cl{rational}
96 @findex @cl{read}
97 @findex @cl{read-from-string}
98 In addition, setting or binding the value of
99 @code{*read-default-float-format*} to @code{rational} around a call to
100 @code{read} or @code{read-from-string} has the effect that
101 floating-point numbers without exponent markers are read as rational
102 numbers, as if there had been an explicit @code{r} or @code{R} marker.
104 @vindex @cl{@earmuffs{read-default-float-format}}
105 @tindex @cl{rational}
106 Floating point numbers of all types are printed with an exponent
107 marker while the value of @code{*read-default-float-format*} is
108 @code{rational}; however, rational numbers are printed in their
109 standard syntax, irrespective of the value of
110 @code{*read-default-float-format*}.
112 @node  Package-Local Nicknames
113 @comment  node-name,  next,  previous,  up
114 @section Package-Local Nicknames
115 @cindex Package-Local Nicknames
116 @cindex Nicknames, Package-local
118 SBCL allows giving packages local nicknames: they allow short and
119 easy-to-use names to be used without fear of name conflict associated
120 with normal nicknames.
122 A local nickname is valid only when inside the package for which it
123 has been specified. Different packages can use same local nickname for
124 different global names, or different local nickname for same global
125 name.
127 @vindex @cl{@earmuffs{features}}
128 Symbol @code{:package-local-nicknames} in @code{*features*} denotes
129 the support for this feature.
131 @findex @cl{defpackage}
132 @defmac @cl{defpackage} name [[option]]* @result{} package
134 Options are extended to include
136 @itemize
137 @item
138 @code{:local-nicknames (@var{local-nickname} @var{actual-package-name})*}
140 The package has the specified local nicknames for the corresponding
141 actual packages.
142 @end itemize
144 Example:
146 @findex @cl{find-symbol}
147 @findex @cl{find-package}
148 @vindex @cl{@earmuffs{package}}
149 @lisp
150 (defpackage :bar (:intern "X"))
151 (defpackage :foo (:intern "X"))
152 (defpackage :quux (:use :cl) (:local-nicknames (:bar :foo) (:foo :bar)))
153 (find-symbol "X" :foo) ; => FOO::X
154 (find-symbol "X" :bar) ; => BAR::X
155 (let ((*package* (find-package :quux)))
156   (find-symbol "X" :foo))               ; => BAR::X
157 (let ((*package* (find-package :quux)))
158   (find-symbol "X" :bar))               ; => FOO::X
159 @end lisp
160 @end defmac
162 @include fun-sb-ext-package-local-nicknames.texinfo
163 @include fun-sb-ext-package-locally-nicknamed-by-list.texinfo
164 @include fun-sb-ext-add-package-local-nickname.texinfo
165 @include fun-sb-ext-remove-package-local-nickname.texinfo
167 @node  Package Variance
168 @comment  node-name,  next,  previous,  up
169 @section Package Variance
171 Common Lisp standard specifies that ``If the new definition is at
172 variance with the current state of that package, the consequences are
173 undefined;'' SBCL by default signals a full warning and retains as
174 much of the package state as possible.
176 This can be adjusted using @code{sb-ext:*on-package-variance*}:
178 @include var-sb-ext-star-on-package-variance-star.texinfo
180 @node  Garbage Collection
181 @comment  node-name,  next,  previous,  up
182 @section Garbage Collection
183 @cindex Garbage collection
185 SBCL provides additional garbage collection functionality not
186 specified by ANSI.
188 @include var-sb-ext-star-after-gc-hooks-star.texinfo
189 @include fun-sb-ext-gc.texinfo
191 @subsection Finalization
192 @cindex Finalization
194 Finalization allows code to be executed after an object has been
195 garbage collected. This is useful for example for releasing foreign
196 memory associated with a Lisp object.
198 @include fun-sb-ext-finalize.texinfo
199 @include fun-sb-ext-cancel-finalization.texinfo
201 @subsection Weak Pointers
202 @cindex Weak pointers
204 Weak pointers allow references to objects to be maintained without
205 keeping them from being garbage collected: useful for building caches
206 among other things.
208 Hash tables can also have weak keys and values: @pxref{Hash Table
209 Extensions}.
211 @include fun-sb-ext-make-weak-pointer.texinfo
212 @include fun-sb-ext-weak-pointer-value.texinfo
214 @subsection Introspection and Tuning
216 @include var-sb-ext-star-gc-run-time-star.texinfo
217 @include fun-sb-ext-bytes-consed-between-gcs.texinfo
218 @include fun-sb-ext-dynamic-space-size.texinfo
219 @include fun-sb-ext-get-bytes-consed.texinfo
220 @include fun-sb-ext-gc-logfile.texinfo
221 @include fun-sb-ext-generation-average-age.texinfo
222 @include fun-sb-ext-generation-bytes-allocated.texinfo
223 @include fun-sb-ext-generation-bytes-consed-between-gcs.texinfo
224 @include fun-sb-ext-generation-minimum-age-before-gc.texinfo
225 @include fun-sb-ext-generation-number-of-gcs-before-promotion.texinfo
226 @include fun-sb-ext-generation-number-of-gcs.texinfo
228 @subsection Tracing Live Objects Back to Roots
230 @quotation note
231 This feature is intended to help expert users diagnose rare low-level
232 issues and should not be needed during normal usage.  On top of that,
233 the interface and implementation are experimental and may change at any
234 time without further notice.
235 @end quotation
237 It is sometimes important to understand why a given object is retained
238 in the Lisp image instead of being garbage collected.  To help with this
239 problem, SBCL provides a mechanism that searches through the different
240 memory spaces, builds a path of references from a root to the object in
241 question and finally reports this paths:
243 @include fun-sb-ext-search-roots.texinfo
245 An example of using this could look like this:
247 @lisp
248 * (defvar *my-string* (list 1 2 "my string"))
249 *MY-STRING*
251 * (sb-ext:search-roots (sb-ext:make-weak-pointer (third *my-string*)))
252  -> ((SIMPLE-VECTOR 3)) #x10004E9EAF[2] -> (SYMBOL) #x5044100F[1] -> (CONS) #x100181FAE7[1] -> (CONS) #x100181FAF7[1] -> (CONS) #x100181FB07[0] -> #x100181F9AF
253 @end lisp
255 The single line of output on @code{cl:*standard-output*} shows the path
256 from a root to @t{"my string"}: the path starts with SBCL's internal
257 package system data structures followed by the symbol
258 (@t{cl-user:*my-string*}) followed the three cons cells of the list.
260 The @code{:print :verbose} argument produces similar behavior but
261 describe the path elements in more detail:
263 @lisp
264 * (sb-ext:search-roots (sb-ext:make-weak-pointer (third *my-string*)) :print :verbose)
265 Path to "my string":
266  6       10004E9EAF [   2] a (simple-vector 3)
267  0         5044100F [   1] COMMON-LISP-USER::*MY-STRING*
268  0       100181FAE7 [   1] a cons
269  0       100181FAF7 [   1] a cons
270  0       100181FB07 [   0] a cons
271 @end lisp
273 The @code{:print nil} argument is a bit different:
275 @lisp
276 * (sb-ext:search-roots (sb-ext:make-weak-pointer (third *my-string*)) :print nil)
277 (("my string" :STATIC (#(*MY-STRING* 0 0) . 2) (*MY-STRING* . 1)
278   ((1 2 "my string") . 1) ((2 "my string") . 1) (("my string") . 0)))
279 @end lisp
281 There is no output on @code{cl:*standard-output*} and the return value
282 is a single path for the target object @t{"my string"}. As before, the
283 path shows the symbol and the three cons cells.
285 @node Generic Function Dispatch
286 @comment  node-name,  next,  previous,  up
287 @section Generic Function Dispatch
289 @findex @sbpcl{no-primary-method}
290 @findex @cl{no-applicable-method}
291 If a generic function with standard or short method combination is
292 called, and the set of applicable methods does not include any primary
293 methods, then the generic function @code{no-primary-method} will be
294 invoked, with the arguments to @code{no-primary-method} being the
295 invoked generic function and its arguments, similar to the standard
296 function @code{no-applicable-method}.  As with
297 @code{no-applicable-method}, the default method on
298 @code{no-primary-method} signals an error; programmers may define
299 methods on it.
301 @node Slot Access
302 @comment  node-name,  next,  previous,  up
303 @section Slot Access
305 @findex @cl{slot-value}
306 @findex @setf{@cl{slot-value}}
307 @findex @cl{slot-boundp}
308 @findex @cl{slot-makunbound}
309 The slot access functions @code{slot-value}, @code{(setf slot-value)},
310 @code{slot-boundp} and @code{slot-makunbound} are defined to function
311 as expected on conditions (of metaclass @code{condition-class}) and,
312 with some limitations, on structures (of metaclass
313 @code{structure-class}).
315 For structures:
317 @itemize
318 @item
319 @findex @cl{defstruct}
320 The name of a slot for the purposes of the slot access functions is
321 the symbol used as the slot-name in the slot-description in the
322 @code{defstruct} form;
324 @item
325 @findex @cl{slot-unbound}
326 @findex @cl{slot-value}
327 @findex @cl{slot-boundp}
328 @cindex Unbound slots
329 @code{slot-value} and @code{slot-boundp} function as expected,
330 including (for @code{slot-value}) calling and respecting the return
331 value of @code{slot-unbound} if the slot is unbound;
333 @item
334 @findex @setf{@cl{slot-value}}
335 @code{(setf slot-value)} functions as expected, including performing
336 type checks to verify that the new value is of an appropriate type for
337 the slot;
339 @item
340 @findex @cl{slot-makunbound}
341 @cindex Unbound slots
342 @code{slot-makunbound} makes the slot be unbound only when the slot
343 corresponds to an @code{&aux} argument with no default in a
344 by-order-of-arguments (BOA) constructor.  In all other cases calling
345 @code{slot-makunbound} on a structure signals an error.
347 @item
348 @findex @cl{slot-missing}
349 If any of the slot access functions is called with a structure
350 instance which does not have a slot of the given name,
351 @code{slot-missing} is called and the return value of the effective
352 method, if any, is respected.
354 @end itemize
356 @node Metaobject Protocol
357 @comment  node-name,  next,  previous,  up
358 @section Metaobject Protocol
360 @subsection AMOP Compatibility of Metaobject Protocol
362 SBCL supports a metaobject protocol which is intended to be compatible
363 with AMOP; present exceptions to this (as distinct from current bugs)
364 are:
366 @itemize
368 @item
369 @findex @sbmop{compute-effective-method}
370 @code{compute-effective-method} only returns one value, not two.
372 There is no record of what the second return value was meant to
373 indicate, and apparently no clients for it.
375 @item
376 @tindex @cl{generic-function}
377 @tindex @cl{standard-generic-function}
378 @tindex @sbmop{funcallable-standard-object}
379 @tindex @cl{standard-object}
380 @tindex @cl{function}
381 The direct superclasses of @code{funcallable-standard-object} are
382 @code{(function standard-object)}, not @code{(standard-object function)}.
384 This is to ensure that the @code{standard-object} class is the last of
385 the standardized classes before @code{t} appearing in the class
386 precedence list of @code{generic-function} and
387 @code{standard-generic-function}, as required by section 1.4.4.5 of the
388 ANSI specification.
390 @item
391 @findex @cl{ensure-generic-function}
392 @findex @sbmop{generic-function-declarations}
393 the arguments @code{:declare} and @code{:declarations} to
394 @code{ensure-generic-function} are both accepted, with the leftmost
395 argument defining the declarations to be stored and returned by
396 @code{generic-function-declarations}.
398 Where AMOP specifies @code{:declarations} as the keyword argument to
399 @code{ensure-generic-function}, the Common Lisp standard specifies
400 @code{:declare}.  Portable code should use @code{:declare}.
402 @item
403 @findex @sbmop{validate-superclass}
404 @findex @sbmop{finalize-inheritance}
405 @tindex @cl{standard-class}
406 @tindex @sbmop{funcallable-standard-class}
407 @tindex @cl{function}
408 @findex @sbmop{class-prototype}
409 although SBCL obeys the requirement in AMOP that
410 @code{validate-superclass} should treat @code{standard-class} and
411 @code{funcallable-standard-class} as compatible metaclasses, we
412 impose an additional requirement at class finalization time: a class
413 of metaclass @code{funcallable-standard-class} must have
414 @code{function} in its superclasses, and a class of metaclass
415 @code{standard-class} must not.
417 @findex @cl{typep}
418 @findex @cl{class-of}
419 @findex @cl{subtypep}
420 After a class has been finalized, it is associated with a class
421 prototype which is accessible by a standard mop function
422 @code{class-prototype}.  The user can then ask whether this object is a
423 @code{function} or not in several different ways: whether it is a
424 function according to @code{typep}; whether its @code{class-of} is
425 @code{subtypep} @code{function}, or whether @code{function} appears in
426 the superclasses of the class.  The additional consistency requirement
427 comes from the desire to make all of these answers the same.
429 The following class definitions are bad, and will lead to errors
430 either immediately or if an instance is created:
431 @lisp
432 (defclass bad-object (funcallable-standard-object)
433   ()
434   (:metaclass standard-class))
435 @end lisp
436 @lisp
437 (defclass bad-funcallable-object (standard-object)
438   ()
439   (:metaclass funcallable-standard-class))
440 @end lisp
441 The following definition is acceptable:
442 @lisp
443 (defclass mixin ()
444   ((slot :initarg slot)))
445 (defclass funcallable-object (funcallable-standard-object mixin)
446   ()
447   (:metaclass funcallable-standard-class))
448 @end lisp
449 and leads to a class whose instances are funcallable and have one slot.
451 @tindex @sbmop{funcallable-standard-object}
452 Note that this requirement also applies to the class
453 @code{funcallable-standard-object}, which has metaclass
454 @code{funcallable-standard-class} rather than
455 @code{standard-class} as AMOP specifies.
457 @item
458 the requirement that ``No portable class @math{C_p} may inherit, by
459 virtue of being a direct or indirect subclass of a specified class, any
460 slot for which the name is a symbol accessible in the
461 @code{common-lisp-user} package or exported by any package defined in
462 the ANSI Common Lisp standard.'' is interpreted to mean that the
463 standardized classes themselves should not have slots named by external
464 symbols of public packages.
466 The rationale behind the restriction is likely to be similar to the ANSI
467 Common Lisp restriction on defining functions, variables and types named
468 by symbols in the Common Lisp package: preventing two independent pieces
469 of software from colliding with each other.
471 @item
472 @findex @sbmop{slot-value-using-class}
473 @findex @setf{@sbmop{slot-value-using-class}}
474 @findex @sbmop{slot-boundp-using-class}
475 specializations of the @code{new-value} argument to @code{(setf
476 slot-value-using-class)} are not allowed: all user-defined methods must
477 have a specializer of the class @code{t}.
479 This prohibition is motivated by a separation of layers: the
480 @code{slot-value-using-class} family of functions is intended for use in
481 implementing different and new slot allocation strategies, rather than
482 in performing application-level dispatching.  Additionally, with this
483 requirement, there is a one-to-one mapping between metaclass, class and
484 slot-definition-class tuples and effective methods of @code{(setf
485 slot-value-using-class)}, which permits optimization of @code{(setf
486 slot-value-using-class)}'s discriminating function in the same manner as
487 for @code{slot-value-using-class} and @code{slot-boundp-using-class}.
489 Note that application code may specialize on the @code{new-value}
490 argument of slot accessors.
492 @item
493 @findex @cl{defclass}
494 @findex @sbmop{ensure-class}
495 @findex @sbmop{ensure-class-using-class}
496 @findex @cl{find-class}
497 @findex @cl{class-name}
498 the class named by the @code{name} argument to @code{ensure-class}, if
499 any, is only redefined if it is the proper name of that class;
500 otherwise, a new class is created.
502 This is consistent with the description of @code{ensure-class} in AMOP
503 as the functional version of @code{defclass}, which has this behaviour;
504 however, it is not consistent with the weaker requirement in AMOP, which
505 states that any class found by @code{find-class}, no matter what its
506 @code{class-name}, is redefined.
508 @item
509 @findex @sbmop{slot-definition-name}
510 @tindex @cl{structure-class}
511 @findex @cl{defstruct}
512 an error is not signaled in the case of the @code{:name} initialization
513 argument for @code{slot-definition} objects being a constant, when the
514 slot definition is of type @code{structure-slot-definition} (i.e. it is
515 associated with a class of type @code{structure-class}).
517 This allows code which uses constant names for structure slots to
518 continue working as specified in ANSI, while enforcing the constraint
519 for all other types of slot.
521 @item
522 @tindex @cl{t}
523 @tindex @cl{built-in-class}
524 @findex @sbmop{validate-superclass}
525 @findex @cl{defclass}
526 the class named @code{t} is not an instance of the @code{built-in-class}
527 metaclass.
529 AMOP specifies, in the ``Inheritance Structure of Metaobject Classes''
530 section, that the class named @code{t} should be an instance of
531 @code{built-in-class}.  However, it also specifies that
532 @code{validate-superclass} should return true (indicating that a direct
533 superclass relationship is permissible) if the second argument is the
534 class named @code{t}.  Also, ANSI specifies that classes with metaclass
535 @code{built-in-class} may not be subclassed using @code{defclass}, and
536 also that the class named @code{t} is the universal superclass,
537 inconsistent with it being a @code{built-in-class}.
539 @item
540 @findex @cl{change-class}
541 @findex @cl{defclass}
542 @findex @sbmop{ensure-class}
543 @findex @sbmop{ensure-class-using-class}
544 @findex @sbmop{slot-value-using-class}
545 @findex @setf{@sbmop{slot-value-using-class}}
546 @findex @sbmop{slot-boundp-using-class}
547 @findex @sbmop{slot-definition-allocation}
548 uses of @code{change-class} and redefinitions of classes with
549 @code{defclass} (or the functional interfaces @code{ensure-class} or
550 @code{ensure-class-using-class}) must ensure that for each slot with
551 allocation @code{:instance} or @code{:class}, the set of applicable
552 methods on the @code{slot-value-using-class} family of generic
553 functions is the same before and after the change.
555 This is required for correct operation of the protocol to update
556 instances for the new or redefined class, and can be seen as part of
557 the contract of the @code{:instance} or @code{:class} allocations.
559 @item
560 @findex @cl{no-applicable-method}
561 @findex @sbpcl{no-primary-method}
562 @findex @sbmop{compute-discriminating-function}
563 @findex @cl{compute-applicable-methods}
564 @findex @sbmop{compute-effective-method}
565 Metaobject protocol users may wish to override
566 @code{compute-discriminating-function} for their own generic function
567 classes.  Overriding implementations of
568 @code{compute-discriminating-function} must, in order to participate
569 in the @code{no-applicable-method} and @code{no-primary-method}
570 protocols, perform appropriate checks on the return value of
571 @code{compute-applicable-methods} before processing the effective
572 method; the standard effective method contains error-invoking forms,
573 but those forms have no access to the generic function invocation's
574 arguments.
576 @end itemize
578 @subsection Metaobject Protocol Extensions
580 In addition, SBCL supports extensions to the Metaobject protocol from
581 AMOP; at present, they are:
583 @itemize
585 @item
586 @findex @cl{defmethod}
587 @findex @cl{find-class}
588 @findex @sbmop{intern-eql-specializer}
589 @findex @sbpcl{make-method-specializers-form}
590 @findex @sbmop{make-method-lambda}
591 compile-time support for generating specializer metaobjects from
592 specializer names in @code{defmethod} forms is provided by the
593 @code{make-method-specializers-form} function, which returns a form
594 which, when evaluated in the lexical environment of the
595 @code{defmethod}, returns a list of specializer metaobjects.  This
596 operator suffers from similar restrictions to those affecting
597 @code{make-method-lambda}, namely that the generic function must be
598 defined when the @code{defmethod} form is expanded, so that the
599 correct method of @code{make-method-specializers-form} is invoked.
600 The system-provided method on @code{make-method-specializers-form}
601 generates a call to @code{find-class} for each symbol specializer
602 name, and a call to @code{intern-eql-specializer} for each @code{(eql
603 @var{x})} specializer name.
605 @item
606 @findex @cl{find-method}
607 @findex @sbpcl{parse-specializer-using-class}
608 @findex @sbpcl{unparse-specializer-using-class}
609 run-time support for converting between specializer names and
610 specializer metaobjects, mostly for the purposes of
611 @code{find-method}, is provided by
612 @code{parse-specializer-using-class} and
613 @code{unparse-specializer-using-class}, which dispatch on their first
614 argument, the generic function associated with a method with the given
615 specializer.  The system-provided methods on those methods convert
616 between classes and proper names and between lists of the form
617 @code{(eql @var{x})} and interned eql specializer objects.
619 @item
620 @vindex @sbpcl{@earstuds{slot-unbound}}
621 @findex @sbmop{standard-instance-access}
622 @findex @sbmop{funcallable-standard-instance-access}
623 @cindex Unbound slots
624 distinguishing unbound instance allocated slots from bound ones when
625 using @code{standard-instance-access} and
626 @code{funcallable-standard-instance-access} is possible by comparison
627 to the symbol-macro @code{+slot-unbound+}.
629 @end itemize
631 @node Extensible Sequences
632 @comment  node-name,  next,  previous,  up
633 @section Extensible Sequences
635 @menu
636 * Iterator Protocol::
637 * Simple Iterator Protocol::
638 @end menu
640 @tindex @cl{sequence}
641 @tindex @cl{vector}
642 @findex @cl{find}
643 @findex @cl{subseq}
644 ANSI Common Lisp has a class @code{sequence} with subclasses @code{list} and
645 @code{vector} on which the ``sequence functions'' like @code{find},
646 @code{subseq}, etc. operate. As an extension to the ANSI specification,
647 SBCL allows additional subclasses of @code{sequence} to be defined
648 @footnote{A motivation, rationale and additional examples for the design
649 of this extension can be found in the paper @cite{Rhodes, Christophe
650 (2007): User-extensible sequences in Common Lisp} available for download
652 @url{http://www.doc.gold.ac.uk/~mas01cr/papers/ilc2007/sequences-20070301.pdf}.}.
654 @findex @cl{coerce}
655 @findex @cl{subseq}
656 @findex @cl{make-instance}
657 @tindex @cl{list}
658 Users of this extension just make instances of @code{sequence} subclasses
659 and transparently operate on them using sequence functions:
660 @lisp
661 (coerce (subseq (make-instance 'my-sequence) 5 10) 'list)
662 @end lisp
663 From this perspective, no distinction between builtin and user-defined
664 @code{sequence} subclasses should be necessary.
666 Providers of the extension, that is of user-defined @code{sequence}
667 subclasses, have to adhere to a ``sequence protocol'' which consists of
668 a set of generic functions in the @code{sequence} package.
670 @tindex @cl{sequence}
671 @tindex @cl{standard-object}
672 A minimal @code{sequence} subclass has to specify @code{standard-object} and
673 @code{sequence} as its superclasses and has to be the specializer of the
674 @code{sequence} parameter of methods on at least the following generic
675 functions:
677 @include fun-sb-sequence-length.texinfo
678 @include fun-sb-sequence-elt.texinfo
679 @include fun-sb-sequence-setf-elt.texinfo
680 @include fun-sb-sequence-adjust-sequence.texinfo
681 @include fun-sb-sequence-make-sequence-like.texinfo
683 @tindex @cl{sequence}
684 @findex @sequence{make-sequence-like}
685 @findex @cl{subseq}
686 @findex @cl{copy-seq}
687 @findex @sequence{adjust-sequence}
688 @code{make-sequence-like} is needed for functions returning
689 freshly-allocated sequences such as @code{subseq} or
690 @code{copy-seq}. @code{adjust-sequence} is needed for functions which
691 destructively modify their arguments such as @code{delete}. In fact, all
692 other sequence functions can be implemented in terms of the above
693 functions and actually are, if no additional methods are
694 defined. However, relying on these generic implementations, in
695 particular not implementing the iterator protocol can incur a high
696 performance penalty @xref{Iterator Protocol}.
698 When the sequence protocol is only partially implemented for a given
699 @code{sequence} subclass, an attempt to apply one of the missing
700 operations to instances of that class signals the following condition:
702 @include condition-sb-sequence-protocol-unimplemented.texinfo
704 In addition to the mandatory functions above, methods on the sequence
705 functions listed below can be defined.
707 There are two noteworthy irregularities:
708 @itemize
709 @item
710 The function @code{sb-sequence:emptyp} does not have a counterpart in
711 the @code{cl} package. It is intended to be used instead of
712 @code{length} when working with lazy or infinite sequences.
714 @item
715 The functions @code{map}, @code{concatenate} and @code{merge} receive a
716 type designator specifying the type of the constructed sequence as their
717 first argument. However, the corresponding generic functions
718 @code{sb-sequence:map}, @code{sb-sequence:concatenate} and
719 @code{sb-sequence:merge} receive a prototype instance of the requested
720 @code{sequence} subclass instead.
721 @end itemize
723 @include fun-sb-sequence-emptyp.texinfo
725 @itemize
726 @item
727 @code{sb-sequence:count}, @code{sb-sequence:count-if}, @code{sb-sequence:count-if-not}
729 @item
730 @code{sb-sequence:find}, @code{sb-sequence:find-if}, @code{sb-sequence:find-if-not}
732 @item
733 @code{sb-sequence:position}, @code{sb-sequence:position-if}, @code{sb-sequence:position-if-not}
735 @item
736 @code{sb-sequence:subseq}
738 @item
739 @code{sb-sequence:copy-seq}
741 @item
742 @code{sb-sequence:fill}
744 @item
745 @include fun-sb-sequence-map.texinfo
747 @item
748 @code{sb-sequence:nsubstitute}, @code{sb-sequence:nsubstitute-if},
749 @code{sb-sequence:nsubstitute-if-not}, @code{sb-sequence:substitute},
750 @code{sb-sequence:substitute-if}, @code{sb-sequence:substitute-if-not}
752 @item
753 @code{sb-sequence:replace}
755 @item
756 @code{sb-sequence:nreverse}, @code{sb-sequence:reverse}
758 @item
759 @include fun-sb-sequence-concatenate.texinfo
761 @item
762 @code{sb-sequence:reduce}
764 @item
765 @code{sb-sequence:mismatch}
767 @item
768 @code{sb-sequence:search}
770 @item
771 @code{sb-sequence:delete}, @code{sb-sequence:delete-if}, @code{sb-sequence:delete-if-not},
772 @code{sb-sequence:remove}, @code{sb-sequence:remove-if}, @code{sb-sequence:remove-if-not},
774 @item
775 @code{sb-sequence:delete-duplicates}, @code{sb-sequence:remove-duplicates}
777 @item
778 @code{sb-sequence:sort}, @code{sb-sequence:stable-sort}
780 @item
781 @include fun-sb-sequence-merge.texinfo
782 @end itemize
784 @findex @cl{dolist}
785 In the spirit of @code{dolist}, generic sequences can be traversed using
786 the macro
788 @include macro-sb-sequence-dosequence.texinfo
790 @node Iterator Protocol
791 @comment  node-name,  next,  previous,  up
792 @subsection Iterator Protocol
794 The iterator protocol allows subsequently accessing some or all elements
795 of a sequence in forward or reverse direction. Users first call
796 @code{make-sequence-iterator} to create an iteration state and
797 receive functions to query and mutate it. These functions allow, among
798 other things, moving to, retrieving or modifying elements of the
799 sequence. An iteration state consists of a state object, a limit object,
800 a from-end indicator and the following six functions to query or mutate
801 this state:
802 @findex @sequence{make-sequence-iterator}
803 @deffn {Function} @code{step function} sequence iterator from-end
804 Moves the iterator one position forward or backward in the associated
805 sequence depending on the iteration direction.
806 @end deffn
807 @deffn {Function} @code{endp function} sequence iterator limit from-end
808 Returns non-@code{nil} when the iterator has reached the end of the
809 associated sequence with respect to the iteration direction.
810 @end deffn
811 @deffn {Function} @code{element function} sequence iterator
812 Returns the sequence element associated to the current position of the
813 iteration.
814 @end deffn
815 @deffn {Function} @code{setf element function} new-value sequence iterator
816 Destructively modifies the associates sequence by replacing the sequence
817 element associated to the current iteration position with a new value.
818 @end deffn
819 @deffn {Function} @code{index function} sequence iterator
820 Returns the position of the iteration in the associated sequence.
821 @end deffn
822 @deffn {Function} @code{copy function} sequence iterator
823 Returns a copy of the iteration state which can be mutated independently
824 of the copied iteration state.
825 @end deffn
827 An iterator is created by calling:
829 @include fun-sb-sequence-make-sequence-iterator.texinfo
831 @findex @sequence{make-sequence-iterator}
832 @findex @sequence{make-simple-sequence-iterator}
833 @tindex @cl{sequence}
834 Note that @code{make-sequence-iterator} calls
835 @code{make-simple-sequence-iterator} when there is no specialized
836 method for a particular @code{sequence} subclass. @xref{Simple Iterator
837 Protocol}.
839 The following convenience macros simplify traversing sequences using
840 iterators:
842 @include macro-sb-sequence-with-sequence-iterator.texinfo
843 @include macro-sb-sequence-with-sequence-iterator-functions.texinfo
845 @node Simple Iterator Protocol
846 @comment  node-name,  next,  previous,  up
847 @subsection Simple Iterator Protocol
849 For cases in which the full flexibility and performance of the general
850 sequence iterator protocol is not required, there is a simplified
851 sequence iterator protocol consisting of a few generic functions which
852 can be specialized for iterator classes:
854 @include fun-sb-sequence-iterator-step.texinfo
855 @include fun-sb-sequence-iterator-endp.texinfo
856 @include fun-sb-sequence-iterator-element.texinfo
857 @include fun-sb-sequence-setf-iterator-element.texinfo
858 @include fun-sb-sequence-iterator-index.texinfo
859 @include fun-sb-sequence-iterator-copy.texinfo
861 Iterator objects implementing the above simple iteration protocol are
862 created by calling the following generic function:
864 @include fun-sb-sequence-make-simple-sequence-iterator.texinfo
866 @node  Support For Unix
867 @comment  node-name,  next,  previous,  up
868 @section Support For Unix
870 @menu
871 * Command-line arguments::
872 * Querying the process environment::
873 * Running external programs::
874 @end menu
876 @node Command-line arguments
877 @subsection Command-line arguments
878 @vindex @sbext{@earmuffs{posix-argv}}
880 The UNIX command line can be read from the variable
881 @code{sb-ext:*posix-argv*}.
883 @node Querying the process environment
884 @subsection Querying the process environment
886 The UNIX environment can be queried with the
887 @code{sb-ext:posix-getenv} function.
889 @include fun-sb-ext-posix-getenv.texinfo
891 @node Running external programs
892 @subsection Running external programs
894 External programs can be run with @code{sb-ext:run-program}.
895 @footnote{In SBCL versions prior to 1.0.13, @code{sb-ext:run-program}
896 searched for executables in a manner somewhat incompatible with other
897 languages.  As of this version, SBCL uses the system library routine
898 @code{execvp(3)}, and no longer contains the function,
899 @code{find-executable-in-search-path}, which implemented the old
900 search.  Users who need this function may find it
901 in @file{run-program.lisp} versions 1.67 and earlier in SBCL's CVS
902 repository here
903 @url{http://sbcl.cvs.sourceforge.net/sbcl/sbcl/src/code/run-program.lisp?view=log}. However,
904 we caution such users that this search routine finds executables that
905 system library routines do not.}
907 @include fun-sb-ext-run-program.texinfo
909 When @code{sb-ext:run-program} is called with @code{wait} equal to
910 NIL, an instance of class @var{sb-ext:process} is returned.  The
911 following functions are available for use with processes:
913 @include fun-sb-ext-process-p.texinfo
915 @include fun-sb-ext-process-input.texinfo
917 @include fun-sb-ext-process-output.texinfo
919 @include fun-sb-ext-process-error.texinfo
921 @include fun-sb-ext-process-alive-p.texinfo
923 @include fun-sb-ext-process-status.texinfo
925 @include fun-sb-ext-process-wait.texinfo
927 @include fun-sb-ext-process-exit-code.texinfo
929 @include fun-sb-ext-process-core-dumped.texinfo
931 @include fun-sb-ext-process-close.texinfo
933 @include fun-sb-ext-process-kill.texinfo
935 @node  Unicode Support
936 @comment  node-name,  next,  previous,  up
937 @section Unicode Support
938 @cindex Unicode
940 SBCL provides support for working with Unicode text and querying the
941 standard Unicode database for information about individual codepoints.
942 Unicode-related functions are located in the @code{sb-unicode} package.
944 @cindex Character Names
945 @cindex Name, of character
946 @findex @cl{name-char}
947 @findex @cl{char-name}
948 SBCL also extends ANSI character literal syntax to support Unicode
949 codepoints. You can either specify a character by its Unicode name, with
950 spaces replaced by underscores, if a unique name exists @footnote{Please
951 note that the codepoint U+1F5CF (PAGE) introduced in Unicode 7.0 is
952 named @code{UNICODE_PAGE}, since the name ``Page'' is required to be
953 assigned to form-feed (U+0C) by the ANSI standard.} or
954 by giving its hexadecimal codepoint preceded by a ``U'', an optional
955 ``+'', and an arbitrary number of leading zeros. You may also input the
956 character directly into your source code if it can be encoded in your
957 file. If a character had an assigned name in Unicode 1.0 that was
958 distinct from its current name, you may also use that name (with spaces
959 replaced by underscores) to specify the character, unless the name is
960 already associated with a codepoint in the latest Unicode standard (such
961 as ``BELL'').
963 For example, you can specify the codepoint U+00E1 (``Latin
964 Small Letter A With Acute'') as
965 @itemize @bullet
966 @item
967 @code{#\LATIN_SMALL_LETTER_A_WITH_ACUTE}
968 @item
969 @code{#\LATIN_SMALL_LETTER_A_ACUTE}
970 @item
971 @code{#\á} assuming a Unicode source file
972 @item
973 @code{#\U00E1}
974 @item
975 @code{#\UE1}
976 @item
977 @code{#\U+00E1}
978 @end itemize
980 @subsection Unicode property access
982 The following functions can be used to find information about a Unicode
983 codepoint.
985 @include fun-sb-unicode-general-category.texinfo
987 @include fun-sb-unicode-bidi-class.texinfo
989 @include fun-sb-unicode-combining-class.texinfo
991 @include fun-sb-unicode-decimal-value.texinfo
993 @include fun-sb-unicode-digit-value.texinfo
995 @include fun-sb-unicode-numeric-value.texinfo
997 @include fun-sb-unicode-mirrored-p.texinfo
999 @include fun-sb-unicode-bidi-mirroring-glyph.texinfo
1001 @include fun-sb-unicode-age.texinfo
1003 @include fun-sb-unicode-hangul-syllable-type.texinfo
1005 @include fun-sb-unicode-east-asian-width.texinfo
1007 @include fun-sb-unicode-script.texinfo
1009 @include fun-sb-unicode-char-block.texinfo
1011 @include fun-sb-unicode-unicode-1-name.texinfo
1013 @include fun-sb-unicode-proplist-p.texinfo
1015 @include fun-sb-unicode-uppercase-p.texinfo
1017 @include fun-sb-unicode-lowercase-p.texinfo
1019 @include fun-sb-unicode-cased-p.texinfo
1021 @include fun-sb-unicode-case-ignorable-p.texinfo
1023 @include fun-sb-unicode-alphabetic-p.texinfo
1025 @include fun-sb-unicode-ideographic-p.texinfo
1027 @include fun-sb-unicode-math-p.texinfo
1029 @include fun-sb-unicode-whitespace-p.texinfo
1031 @include fun-sb-unicode-soft-dotted-p.texinfo
1033 @include fun-sb-unicode-hex-digit-p.texinfo
1035 @include fun-sb-unicode-default-ignorable-p.texinfo
1037 @include fun-sb-unicode-grapheme-break-class.texinfo
1039 @include fun-sb-unicode-word-break-class.texinfo
1041 @include fun-sb-unicode-sentence-break-class.texinfo
1043 @include fun-sb-unicode-line-break-class.texinfo
1045 @subsection String operations
1046 @cindex Normalization, String
1048 SBCL can normalize strings using:
1050 @include fun-sb-unicode-normalize-string.texinfo
1052 @include fun-sb-unicode-normalized-p.texinfo
1054 SBCL implements the full range of Unicode case operations with the
1055 functions
1057 @include fun-sb-unicode-uppercase.texinfo
1059 @include fun-sb-unicode-lowercase.texinfo
1061 @include fun-sb-unicode-titlecase.texinfo
1063 @include fun-sb-unicode-casefold.texinfo
1065 @findex @cl{string-upcase}
1066 @findex @cl{char-downcase}
1067 @findex @cl{both-case-p}
1068 It also extends standard Common Lisp case functions such as
1069 @code{string-upcase} and @code{string-downcase} to support a subset of
1070 Unicode's casing behavior.  Specifically, a character is
1071 @code{both-case-p} if its case mapping in Unicode is one-to-one and
1072 invertable.
1074 The @code{sb-unicode} package also provides functions for
1075 collating/sorting strings according to the Unicode Collation Algorithm.
1077 @include fun-sb-unicode-unicode-lt.texinfo
1079 @include fun-sb-unicode-unicode=.texinfo
1081 @include fun-sb-unicode-unicode-equal.texinfo
1083 @include fun-sb-unicode-unicode-lt=.texinfo
1085 @include fun-sb-unicode-unicode-gt.texinfo
1087 @include fun-sb-unicode-unicode-gt=.texinfo
1089 The following functions are provided for detecting visually confusable strings:
1091 @include fun-sb-unicode-confusable-p.texinfo
1093 @subsection Breaking strings
1095 The @code{sb-unicode} package includes several functions for breaking a
1096 Unicode string into useful parts.
1098 @include fun-sb-unicode-graphemes.texinfo
1100 @include fun-sb-unicode-words.texinfo
1102 @include fun-sb-unicode-sentences.texinfo
1104 @include fun-sb-unicode-lines.texinfo
1106 @node  Customization Hooks for Users
1107 @comment  node-name,  next,  previous,  up
1108 @section Customization Hooks for Users
1110 The toplevel repl prompt may be customized, and the function
1111 that reads user input may be replaced completely.
1112 @c <!-- FIXME but I don't currently remember how -->
1114 The behaviour of @code{require} when called with only one argument is
1115 implementation-defined.  In SBCL, @code{require} behaves in the
1116 following way:
1118 @include fun-common-lisp-require.texinfo
1119 @include var-sb-ext-star-module-provider-functions-star.texinfo
1121 Although SBCL does not provide a resident editor, the @code{ed}
1122 function can be customized to hook into user-provided editing
1123 mechanisms as follows:
1125 @include fun-common-lisp-ed.texinfo
1126 @include var-sb-ext-star-ed-functions-star.texinfo
1128 Conditions of type @code{warning} and @code{style-warning} are
1129 sometimes signaled at runtime, especially during execution of Common
1130 Lisp defining forms such as @code{defun}, @code{defmethod}, etc.  To
1131 muffle these warnings at runtime, SBCL provides a variable
1132 @code{sb-ext:*muffled-warnings*}:
1134 @include var-sb-ext-star-muffled-warnings-star.texinfo
1136 @node Tools To Help Developers
1137 @comment  node-name,  next,  previous,  up
1138 @section Tools To Help Developers
1139 @findex @cl{trace}
1140 @findex @cl{inspect}
1142 SBCL provides a profiler and other extensions to the ANSI @code{trace}
1143 facility.  For more information, see @ref{Macro common-lisp trace}.
1145 The debugger supports a number of options. Its documentation is
1146 accessed by typing @kbd{help} at the debugger prompt. @xref{Debugger}.
1148 Documentation for @code{inspect} is accessed by typing @kbd{help} at
1149 the @code{inspect} prompt.
1151 @node Resolution of Name Conflicts
1152 @section Resolution of Name Conflicts
1153 @tindex @sbext{name-conflict}
1154 @findex @sbext{name-conflict-symbols}
1156 The ANSI standard (section 11.1.1.2.5) requires that name conflicts in
1157 packages be resolvable in favour of any of the conflicting symbols.  In
1158 the interactive debugger, this is achieved by prompting for the symbol
1159 in whose favour the conflict should be resolved; for programmatic use,
1160 the @code{sb-ext:resolve-conflict} restart should be invoked with one
1161 argument, which should be a member of the list returned by the condition
1162 accessor @code{sb-ext:name-conflict-symbols}.
1164 @node    Hash Table Extensions
1165 @comment  node-name,  next,  previous,  up
1166 @section Hash Table Extensions
1167 @cindex Hash tables
1169 Hash table extensions supported by SBCL are all controlled by keyword
1170 arguments to @code{make-hash-table}.
1172 @include fun-common-lisp-make-hash-table.texinfo
1174 @include macro-sb-ext-define-hash-table-test.texinfo
1176 @include macro-sb-ext-with-locked-hash-table.texinfo
1178 @include fun-sb-ext-hash-table-synchronized-p.texinfo
1180 @include fun-sb-ext-hash-table-weakness.texinfo
1182 @node    Random Number Generation
1183 @comment  node-name,  next,  previous,  up
1184 @section Random Number Generation
1185 @cindex Random Number Generation
1187 @vindex @cl{@earmuffs{random-state}}
1188 @findex @cl{make-random-state}
1189 The initial value of @code{*random-state*} is the same each time SBCL
1190 is started. This makes it possible for user code to obtain repeatable
1191 pseudo random numbers using only standard-provided functionality. See
1192 @code{seed-random-state} below for an SBCL extension that allows to
1193 seed the random number generator from given data for an additional
1194 possibility to achieve this. Non-repeatable random numbers can always
1195 be obtained using @code{(make-random-state t)}.
1197 @findex @cl{random}
1198 The sequence of numbers produced by repeated calls to @code{random}
1199 starting with the same random state and using the same sequence of
1200 @code{limit} arguments is guaranteed to be reproducible only in the
1201 same version of SBCL on the same platform, using the same code under
1202 the same evaluator mode and compiler optimization qualities. Just two
1203 examples of differences that may occur otherwise: calls to
1204 @code{random} can be compiled differently depending on how much is
1205 known about the @code{limit} argument at compile time, yielding
1206 different results even if called with the same argument at run time,
1207 and the results can differ depending on the machine's word size, for
1208 example for limits that are fixnums under 64-bit word size but bignums
1209 under 32-bit word size.
1211 @include fun-sb-ext-seed-random-state.texinfo
1213 @tindex @cl{float}
1214 Some notes on random floats: The standard doesn't prescribe a specific
1215 method of generating random floats. The following paragraph describes
1216 SBCL's current implementation and should be taken as purely
1217 informational, that is, user code should not depend on any of its
1218 specific properties.  The method used has been chosen because it is
1219 common, conceptually simple and fast.
1221 @findex @cl{expt}
1222 @findex @cl{random}
1223 To generate random floats, SBCL evaluates code that has an equivalent
1224 effect as
1225 @lisp
1226 (* limit
1227    (float (/ (random (expt 2 23)) (expt 2 23)) 1.0f0))
1228 @end lisp
1229 (for single-floats) and correspondingly (with @code{52} and
1230 @code{1.0d0} instead of @code{23} and @code{1.0f0}) for double-floats.
1231 Note especially that this means that zero is a possible return value
1232 occurring with probability @code{(expt 2 -23)} respectively
1233 @code{(expt 2 -52)}. Also note that there exist twice as many
1234 equidistant floats between 0 and 1 as are generated. For example, the
1235 largest number that @code{(random 1.0f0)} ever returns is
1236 @code{(float (/ (1- (expt 2 23)) (expt 2 23)) 1.0f0)} while
1237 @code{(float (/ (1- (expt 2 24)) (expt 2 24)) 1.0f0)} is the
1238 largest single-float less than 1. This is a side effect of the fact
1239 that the implementation uses the fastest possible conversion from bits
1240 to floats.
1242 SBCL currently uses the Mersenne Twister as its random number
1243 generator, specifically the 32-bit version under both 32- and 64-bit
1244 word size. The seeding algorithm has been improved several times by
1245 the authors of the Mersenne Twister; SBCL uses the third version
1246 (from 2002) which is still the most recent as of June 2012. The
1247 implementation has been tested to provide output identical to the
1248 recommended C implementation.
1250 While the Mersenne Twister generates random numbers of much better
1251 statistical quality than other widely used generators, it uses only
1252 linear operations modulo 2 and thus fails some statistical
1253 tests@footnote{See chapter 7 "Testing widely used RNGs" in
1254 @cite{TestU01: A C Library for Empirical Testing of Random Number
1255 Generators} by Pierre L'Ecuyer and Richard Simard, ACM Transactions on
1256 Mathematical Software, Vol. 33, article 22, 2007.}.
1257 For example, the distribution of ranks of (sufficiently large) random
1258 binary matrices is much distorted compared to the theoretically
1259 expected one when the matrices are generated by the Mersenne Twister.
1260 Thus, applications that are sensitive to this aspect should use a
1261 different type of generator.
1263 @node   Timeouts and Deadlines
1264 @comment  node-name,  next,  previous,  up
1265 @section Timeouts and Deadlines
1267 SBCL supports three different ways of restricting the execution time
1268 available to individual operations or parts of computations:
1270 @table @strong
1272 @item Timeout Parameters
1273 Some operations such as thread synchronization primitives accept a
1274 @code{:timeout} parameter. @xref{Timeout Parameters}.
1276 @item Synchronous Timeouts (Deadlines)
1277 @findex @cl{sleep}
1278 Certain operations that may suspend execution for extended periods of
1279 time such as @code{cl:sleep}, thread synchronization primitives, IO and
1280 waiting for external processes respect deadlines established for a part
1281 of a computation. @xref{Synchronous Timeouts (Deadlines)}.
1283 @item Asynchronous Timeouts
1284 Asynchronous timeouts can interrupt most computations at (almost) any
1285 point. Thus, this kind of timeouts is the most versatile but it is also
1286 somewhat unsafe. @xref{Asynchronous Timeouts}.
1288 @end table
1290 @menu
1291 * Timeout Parameters::
1292 * Synchronous Timeouts (Deadlines)::
1293 * Asynchronous Timeouts::
1294 * Operations Supporting Timeouts and Deadlines::
1295 @end menu
1297 @node Timeout Parameters
1298 @subsection Timeout Parameters
1299 @cindex Timeout
1301 @tindex @sbthread{join-thread-error}
1302 Certain operations accept @code{:timeout} keyword arguments. These
1303 only affect the specific operation and must be specified at each call
1304 site by passing a @code{:timeout} keyword argument and a corresponding
1305 timeout value to the respective operation. Expiration of the timeout
1306 before the operation completes results in either a normal return with
1307 a return value indicating the timeout or in the signaling of a
1308 specialized condition such as @code{sb-thread:join-thread-error}.
1310 Example:
1312 @lisp
1313 (defun join-thread-within-5-seconds (thread)
1314   (multiple-value-bind (value result)
1315       (sb-thread:join-thread thread :default nil :timeout 5)
1316     (when (eq result :timeout)
1317       (error "Could not join ~A within 5 seconds" thread))
1318     value))
1319 @end lisp
1321 @findex @sbthread{join-thread}
1322 The above code attempts to join the specified thread for up to five
1323 seconds, returning its value in case of success. If the thread is
1324 still running after the five seconds have elapsed,
1325 @code{sb-thread:join-thread} indicates the timeout in its second
1326 return value. If a @code{:default} value was not provided,
1327 @code{sb-thread:join-thread} would signal a
1328 @code{sb-thread:join-thread-error} instead.
1330 To wait for an arbitrary condition, optionally with a timeout, the
1331 @code{sb-ext:wait-for} macro can be used:
1333 @include macro-sb-ext-wait-for.texinfo
1335 @c @code{sb-sys:make-fd-stream} also takes a @code{:timeout} argument
1336 @c resulting in @code{sb-sys:io-timeout}, but that seems to niche to
1337 @c document here.
1339 @node Synchronous Timeouts (Deadlines)
1340 @subsection Synchronous Timeouts (Deadlines)
1341 @cindex Timeout
1342 @cindex Synchronous Timeout
1343 @cindex Deadline
1345 Deadlines, in contrast to timeout parameters, are established for a
1346 dynamic scope using the @code{sb-sys:with-deadline} macro and indirectly
1347 affect operations within that scope. In case of nested uses, the
1348 effective deadline is the one that expires first unless an inner use
1349 explicitly overrides outer deadlines.
1351 @include macro-sb-sys-with-deadline.texinfo
1353 Expiration of deadlines set up this way only has an effect when it
1354 happens before or during the execution of a deadline-aware operation
1355 (@pxref{Operations Supporting Timeouts and Deadlines}). In this case, a
1356 @code{sb-sys:deadline-timeout} is signaled. A handler for this condition
1357 type may use the @code{sb-sys:defer-deadline} or
1358 @code{sb-sys:cancel-deadline} restarts to defer or cancel the deadline
1359 respectively and resume execution of the interrupted operation.
1361 @include condition-sb-sys-deadline-timeout.texinfo
1363 When a thread is executing the debugger, signaling of
1364 @code{sb-sys:deadline-timeout} conditions for that thread is deferred
1365 until it exits the debugger.
1367 Example:
1369 @lisp
1370 (defun read-input ()
1371   (list (read-line) (read-line)))
1373 (defun do-it ()
1374   (sb-sys:with-deadline (:seconds 5))
1375     (read-input)
1376     (sleep 2)
1377     (sb-ext:run-program "my-program"))
1378 @end lisp
1380 @findex @cl{read-line}
1381 @findex @cl{sleep}
1382 @findex @sbext{run-program}
1383 The above code establishes a deadline of five seconds within which the
1384 body of the @code{do-it} function should execute. All calls of
1385 deadline-aware functions in the dynamic scope, in this case two
1386 @code{read-line} calls, a @code{sleep} call and a
1387 @code{sb-ext:run-program} call, are affected by the deadline. If, for
1388 example, the first @code{read-line} call completes in one second and the
1389 second @code{read-line} call completes in three seconds, a
1390 @code{sb-sys:deadline-timeout} condition will be signaled after the
1391 @code{sleep} call has been executing for one second.
1393 @node Asynchronous Timeouts
1394 @subsection Asynchronous Timeouts
1395 @cindex Timeout
1396 @cindex Asynchronous Timeout
1398 Asynchronous timeouts are established for a dynamic scope using the
1399 @code{sb-sys:with-timeout} macro:
1401 @include macro-sb-ext-with-timeout.texinfo
1403 Expiration of the timeout will cause the operation being executed at
1404 that moment to be interrupted by an asynchronously signaled
1405 @code{sb-ext:timeout} condition, (almost) irregardless of the operation
1406 and its context.
1408 @include condition-sb-ext-timeout.texinfo
1410 @node Operations Supporting Timeouts and Deadlines
1411 @comment  node-name,
1412 @subsection Operations Supporting Timeouts and Deadlines
1414 @multitable @columnfractions .5 .25 .25
1415 @headitem Operation                                            @tab Timeout Parameter @tab Affected by Deadlines
1416 @item     @code{cl:sleep}                                      @tab -                 @tab since SBCL 1.4.3
1417 @item     @code{cl:read-line}, etc.                            @tab no                @tab yes
1418 @item     @ref{Macro sb-ext wait-for,,@code{wait-for}}@:  @tab yes               @tab yes
1419 @item     @ref{Function sb-ext process-wait,,@code{process-wait}}@:                   @tab no                @tab yes
1420 @item     @ref{Function sb-thread grab-mutex,,@code{grab-mutex}}@:                  @tab yes               @tab yes
1421 @item     @ref{Function sb-thread condition-wait,,@code{condition-wait}}@:              @tab yes               @tab yes
1422 @item     @ref{Function sb-thread wait-on-semaphore,,@code{wait-on-semaphore}}@:           @tab yes               @tab yes
1423 @item     @ref{Function sb-thread join-thread,,@code{join-thread}}@:                 @tab yes               @tab yes
1424 @item     @ref{Function sb-concurrency receive-message,,@code{receive-message}}@:        @tab yes               @tab yes?
1425 @item     @ref{Function sb-concurrency wait-on-gate,,@code{wait-on-gate}}@:           @tab yes               @tab yes?
1426 @item     @ref{Macro sb-concurrency frlock-write,,@code{frlock-write}}@:              @tab yes               @tab yes?
1427 @item     @ref{Function sb-concurrency grab-frlock-write-lock,,@code{grab-frlock-write-lock}}@: @tab yes               @tab yes?
1428 @end multitable
1430 @node    Miscellaneous Extensions
1431 @comment  node-name,  next,  previous,  up
1432 @section Miscellaneous Extensions
1434 @include fun-sb-ext-array-storage-vector.texinfo
1435 @include fun-sb-ext-delete-directory.texinfo
1436 @include fun-sb-ext-get-time-of-day.texinfo
1437 @include fun-sb-ext-assert-version-gt=.texinfo
1439 @node Stale Extensions
1440 @comment  node-name,  next,  previous,  up
1441 @section Stale Extensions
1443 SBCL has inherited from CMUCL various hooks to allow the user to
1444 tweak and monitor the garbage collection process. These are somewhat
1445 stale code, and their interface might need to be cleaned up. If you
1446 have urgent need of them, look at the code in @file{src/code/gc.lisp}
1447 and bring it up on the developers' mailing list.
1449 @findex @sbext{float-denormalized-p}
1450 SBCL has various hooks inherited from CMUCL, like
1451 @code{sb-ext:float-denormalized-p}, to allow a program to take
1452 advantage of IEEE floating point arithmetic properties which aren't
1453 conveniently or efficiently expressible using the ANSI standard. These
1454 look good, and their interface looks good, but IEEE support is
1455 slightly broken due to a stupid decision to remove some support for
1456 infinities (because it wasn't in the ANSI spec and it didn't occur to
1457 me that it was in the IEEE spec). If you need this stuff, take a look
1458 at the code and bring it up on the developers' mailing
1459 list.
1462 @node  Efficiency Hacks
1463 @comment  node-name,  next,  previous,  up
1464 @section Efficiency Hacks
1466 @findex @sbext{purify}
1467 The @code{sb-ext:purify} function causes SBCL first to collect all
1468 garbage, then to mark all uncollected objects as permanent, never again
1469 attempting to collect them as garbage. This can cause a large increase
1470 in efficiency when using a primitive garbage collector, or a more
1471 moderate increase in efficiency when using a more sophisticated garbage
1472 collector which is well suited to the program's memory usage pattern. It
1473 also allows permanent code to be frozen at fixed addresses, a
1474 precondition for using copy-on-write to share code between multiple Lisp
1475 processes.  This is less important with modern generational garbage
1476 collectors, but not all SBCL platforms use such a garbage collector.
1478 @comment @include fun-sb-ext-purify.texinfo
1480 The @code{sb-ext:truly-the} special form declares the type of the
1481 result of the operations, producing its argument; the declaration is
1482 not checked. In short: don't use it.
1484 @include special-operator-sb-ext-truly-the.texinfo
1486 @cindex @code{freeze-type} declaration
1487 @cindex Declaration, @code{freeze-type}
1488 The @code{sb-ext:freeze-type} declaration declares that a
1489 type will never change, which can make type testing
1490 (@code{typep}, etc.) more efficient for structure types.