17d32e99bb1961f64fc6b002d1adfc1e5fc1f328
[sbcl.git] / doc / manual / beyond-ansi.texinfo
1 @node  Beyond the ANSI Standard
2 @comment  node-name,  next,  previous,  up
3 @chapter Beyond the ANSI Standard
4
5 SBCL is mostly an implementation of the ANSI standard for
6 Common Lisp. However, there's some important behavior which extends
7 or clarifies the standard, and various behavior which outright
8 violates the standard.
9
10
11 @menu
12 * Non-Conformance With The ANSI Standard::  
13 * Idiosyncrasies::              
14 * Extensions::                  
15 @end menu
16
17 @node Non-Conformance With The ANSI Standard
18 @comment  node-name,  next,  previous,  up
19 @section Non-Conformance With The ANSI Standard
20
21 Essentially every type of non-conformance is considered a bug.  (The
22 exceptions involve internal inconsistencies in the standard.)  In SBCL
23 0.7.6, the master record of known bugs is in the @file{BUGS} file in
24 the distribution.  Some highlight information about bugs may also be
25 found in the manual page. The recommended way to report bugs is
26 through the sbcl-help or sbcl-devel mailing lists.  For mailing list
27 addresses, @xref{More SBCL Information}.
28
29
30 @node Idiosyncrasies
31 @comment  node-name,  next,  previous,  up
32 @section Idiosyncrasies
33
34 The information in this section describes some of the ways that SBCL
35 deals with choices that the ANSI standard leaves to the
36 implementation.
37
38 Declarations are generally treated as assertions. This general
39 principle, and its implications, and the bugs which still keep the
40 compiler from quite satisfying this principle, are discussed in
41 @ref{Compiler}.
42
43 SBCL is essentially a compiler-only implementation of Common
44 Lisp. That is, for all but a few special cases, @code{eval} creates a
45 lambda expression, calls @code{compile} on the lambda expression to
46 create a compiled function, and then calls @code{funcall} on the
47 resulting function object. This is explicitly allowed by the ANSI
48 standard, but leads to some oddities, e.g. collapsing @code{functionp}
49 and @code{compiled-function-p} into the same predicate.
50
51 @findex defconstant
52 SBCL is quite strict about ANSI's definition of
53 @code{defconstant}. ANSI says that doing @code{defconstant} of the
54 same symbol more than once is undefined unless the new value is
55 @code{eql} to the old value. Conforming to this specification is a
56 nuisance when the ``constant'' value is only constant under some
57 weaker test like @code{string=} or @code{equal}. It's especially
58 annoying because, in SBCL, @code{defconstant} takes effect not only at
59 load time but also at compile time, so that just compiling and loading
60 reasonable code like
61 @lisp
62 (defconstant +foobyte+ '(1 4))
63 @end lisp
64 runs into this undefined behavior. Many implementations of Common Lisp
65 try to help the programmer around this annoyance by silently accepting
66 the undefined code and trying to do what the programmer probably
67 meant. SBCL instead treats the undefined behavior as an error. Often
68 such code can be rewritten in portable ANSI Common Lisp which has the
69 desired behavior.  E.g., the code above can be given an exactly
70 defined meaning by replacing @code{defconstant} either with
71 @code{defparameter} or with a customized macro which does the right
72 thing, possibly along the lines of the @code{defconstant-eqx} macro
73 used internally in the implementation of SBCL itself.  In
74 circumstances where this is not appropriate, the programmer can handle
75 the condition type @code{sb-ext:defconstant-uneql}, and choose either
76 the @command{continue} or @command{abort} restart as appropriate.
77
78 SBCL gives style warnings about various kinds of perfectly legal code,
79 e.g.
80
81 @itemize
82   
83 @item
84 @code{defmethod} without a preceding @code{defgeneric};
85   
86 @item
87 multiple @code{defun}s of the same symbol in different units;
88   
89 @item
90 special variables not named in the conventional @code{*foo*} style,
91 and lexical variables unconventionally named in the @code{*foo*} style
92
93 @end itemize
94
95 This causes friction with people who point out that other ways of
96 organizing code (especially avoiding the use of @code{defgeneric}) are
97 just as aesthetically stylish.  However, these warnings should be read
98 not as ``warning, bad aesthetics detected, you have no style'' but
99 ``warning, this style keeps the compiler from understanding the code
100 as well as you might like.'' That is, unless the compiler warns about
101 such conditions, there's no way for the compiler to warn about some
102 programming errors which would otherwise be easy to overlook. (Related
103 bug: The warning about multiple @code{defun}s is pointlessly annoying
104 when you compile and then load a function containing @code{defun}
105 wrapped in @code{eval-when}, and ideally should be suppressed in that
106 case, but still isn't as of SBCL 0.7.6.)
107
108
109 @node  Extensions
110 @comment  node-name,  next,  previous,  up
111 @section Extensions
112
113 SBCL is derived from CMUCL, which implements many extensions to the
114 ANSI standard. SBCL doesn't support as many extensions as CMUCL, but
115 it still has quite a few.  @xref{Contributed Modules}.
116
117
118 @menu
119 * Things Which Might Be In The Next ANSI Standard::  
120 * Threading::                   
121 * Support For Unix::            
122 * Customization Hooks for Users::  
123 * Tools To Help Developers::    
124 * Interface To Low-Level SBCL Implementation::  
125 * Stale Extensions::            
126 * Efficiency Hacks::            
127 @end menu
128
129 @node  Things Which Might Be In The Next ANSI Standard
130 @comment  node-name,  next,  previous,  up
131 @subsection Things Which Might Be In The Next ANSI Standard
132
133 SBCL provides extensive support for calling external C code,
134 @ref{Foreign Function Interface}.
135
136 SBCL provides additional garbage collection functionality not
137 specified by ANSI. Weak pointers allow references to objects to be
138 maintained without keeping them from being GCed (garbage
139 collected). And ``finalization'' hooks are available to cause code to
140 be executed when an object has been GCed.
141 @c <!-- FIXME: Actually documenting these would be good.:-| -->
142
143 SBCL supports @dfn{Gray streams}, user-overloadable CLOS classes whose
144 instances can be used as Lisp streams (e.g. passed as the first
145 argument to @code{format}).  Additionally, the bundled contrib module
146 @dfn{sb-simple-streams} implements a subset of the Franz Allegro
147 simple-streams proposal.
148
149 SBCL supports a MetaObject Protocol which is intended to be compatible
150 with AMOP; present exceptions to this (as distinct from current bugs)
151 are:
152
153 @itemize
154   
155 @item
156 the abstract @code{metaobject} class is not present in the class
157 hierarchy;
158   
159 @item
160 the @code{standard-object} and @code{funcallable-standard-object}
161 classes are disjoint;
162   
163 @item
164 @code{compute-effective-method} only returns one value, not two;
165   
166 @item
167 the system-supplied @code{:around} method for @code{compute-slots}
168 specialized on @code{funcallable-standard-class} does not respect the
169 requested order from a user-supplied primary method.
170
171 @end itemize
172
173
174 @node  Threading
175 @comment  node-name,  next,  previous,  up
176 @subsection Threading (a.k.a Multiprocessing)
177
178 SBCL supports a fairly low-level threading interface that maps onto
179 the host operating system's concept of threads or lightweight
180 processes.  This means that threads may take advantage of hardware
181 multiprocessing on machines that have more than one CPU, but it does 
182 not allow Lisp control of the scheduler.  This is found in the
183 SB-THREAD package.
184
185 This requires x86 and Linux kernel 2.6 or systems with NPTL backports.
186
187 @subsubsection Special variables
188
189 The interaction of special variables with multiple threads is mostly
190 as one would expect, but users of other Lisps are warned that the
191 behaviour of locally bound specials differs in places from what they
192 may expect.
193
194 @itemize
195 @item 
196 global special values are visible across all threads;
197 @item
198 bindings (e.g. using LET) are local to the thread;
199 @item
200 initial values in a new thread are taken from the thread that created it. 
201 @end itemize
202
203 @subsubsection Mutex support
204
205 Mutexes are used for controlling access to a shared resource. One
206 thread is allowed to hold the mutex, others which attempt to take it
207 will be made to wait until it's free. Threads are woken in the order
208 that they go to sleep.
209
210 There isn't a timeout on mutex acquisition, but the usual WITH-TIMEOUT
211 macro (which throws a TIMEOUT condition after n seconds) can be used
212 if you want a bounded wait.
213
214 @lisp
215 (defpackage :demo (:use "CL" "SB-THREAD" "SB-EXT"))
216
217 (in-package :demo)
218
219 (defvar *a-mutex* (make-mutex :name "my lock"))
220
221 (defun thread-fn ()
222   (let ((id (current-thread-id)))
223     (format t "Thread ~A running ~%" id)
224     (with-mutex (*a-mutex*)
225       (format t "Thread ~A got the lock~%" id)
226       (sleep (random 5)))
227     (format t "Thread ~A dropped lock, dying now~%" id)))
228
229 (make-thread #'thread-fn)
230 (make-thread #'thread-fn)
231
232 @end lisp
233
234 @subsubsection Waitqueue/condition variables
235
236 These are based on the POSIX condition variable design, hence the
237 annoyingly CL-conflicting name. For use when you want to check a
238 condition and sleep until it's true. For example: you have a shared
239 queue, a writer process checking ``queue is empty'' and one or more
240 readers that need to know when ``queue is not empty''. It sounds
241 simple, but is astonishingly easy to deadlock if another process runs
242 when you weren't expecting it to.
243
244 There are three components:
245
246 @itemize
247 @item the condition itself (not represented in code)
248 @item the condition variable (a.k.a waitqueue) which proxies for it
249 @item a lock to hold while testing the condition 
250 @end itemize
251
252 Important stuff to be aware of:
253
254 @itemize
255 @item when calling condition-wait, you must hold the mutex. condition-wait will drop the mutex while it waits, and obtain it again before returning for whatever reason;
256
257 @item likewise, you must be holding the mutex around calls to condition-notify;
258
259 @item a process may return from condition-wait in several circumstances: it is not guaranteed that the underlying condition has become true. You must check that the resource is ready for whatever you want to do to it. 
260
261 @end itemize
262
263 @lisp
264 (defvar *buffer-queue* (make-waitqueue))
265 (defvar *buffer-lock* (make-mutex :name "buffer lock"))
266
267 (defvar *buffer* (list nil))
268
269 (defun reader ()
270   (with-mutex (*buffer-lock*)
271     (loop
272      (condition-wait *buffer-queue* *buffer-lock*)
273      (loop
274       (unless *buffer* (return))
275       (let ((head (car *buffer*)))
276         (setf *buffer* (cdr *buffer*))
277         (format t "reader ~A woke, read ~A~%" 
278                 (current-thread-id) head))))))
279
280 (defun writer ()
281   (loop
282    (sleep (random 5))
283    (with-mutex (*buffer-lock*)
284      (let ((el (intern
285                 (string (code-char 
286                          (+ (char-code #\A) (random 26)))))))
287        (setf *buffer* (cons el *buffer*)))
288      (condition-notify *buffer-queue*))))
289
290 (make-thread #'writer)
291 (make-thread #'reader)
292 (make-thread #'reader)       
293
294 @end lisp
295
296 @subsubsection Sessions/Debugging
297
298 If the user has multiple views onto the same Lisp image (for example,
299 using multiple terminals, or a windowing system, or network access)
300 they are typically set up as multiple @dfn{sessions} such that each
301 view has its own collection of foreground/background/stopped threads.
302 A thread which wishes to create a new session can use
303 @code{sb-thread:with-new-session} to remove itself from the current
304 session (which it shares with its parent and siblings) and create a
305 fresh one.  
306 # See also @code{sb-thread:make-listener-thread}.
307
308 Within a single session, threads arbitrate between themselves for the
309 user's attention.  A thread may be in one of three notional states:
310 foreground, background, or stopped.  When a background process
311 attempts to print a repl prompt or to enter the debugger, it will stop
312 and print a message saying that it has stopped.  The user at his
313 leisure may switch to that thread to find out what it needs.  If a
314 background thread enters the debugger, selecting any restart will put
315 it back into the background before it resumes.  Arbitration for the
316 input stream is managed by calls to @code{sb-thread:get-foreground}
317 (which may block) and @code{sb-thread:release-foreground}.
318
319 @code{sb-ext:quit} terminates all threads in the current session, but
320 leaves other sessions running.
321
322
323 @subsubsection Implementation (Linux x86)
324
325 On Linux x86, threading is implemented using @code{clone()} and does
326 not involve pthreads.  This is not because there is anything wrong
327 with pthreads @emph{per se}, but there is plenty wrong (from our
328 perspective) with LinuxThreads.  SBCL threads are mapped 1:1 onto
329 Linux tasks which share a VM but nothing else - each has its own
330 process id and can be seen in e.g. @command{ps} output.
331
332 Per-thread local bindings for special variables is achieved using the
333 %fs segment register to point to a per-thread storage area.  This may
334 cause interesting results if you link to foreign code that expects
335 threading or creates new threads, and the thread library in question
336 uses %fs in an incompatible way.
337
338 Queues require the @code{sys_futex()} system call to be available:
339 this is the reason for the NPTL requirement.  We test at runtime that
340 this system call exists.
341
342 Garbage collection is done with the existing Conservative Generational
343 GC.  Allocation is done in small (typically 8k) regions: each thread
344 has its own region so this involves no stopping. However, when a
345 region fills, a lock must be obtained while another is allocated, and
346 when a collection is required, all processes are stopped.  This is
347 achieved by sending them signals, which may make for interesting
348 behaviour if they are interrupted in system calls.  The streams
349 interface is believed to handle the required system call restarting
350 correctly, but this may be a consideration when making other blocking
351 calls e.g. from foreign library code.
352
353 Large amounts of the SBCL library have not been inspected for
354 thread-safety.  Some of the obviously unsafe areas have large locks
355 around them, so compilation and fasl loading, for example, cannot be
356 parallelized.  Work is ongoing in this area.
357
358 A new thread by default is created in the same POSIX process group and
359 session as the thread it was created by.  This has an impact on
360 keyboard interrupt handling: pressing your terminal's intr key
361 (typically @kbd{Control-C}) will interrupt all processes in the
362 foreground process group, including Lisp threads that SBCL considers
363 to be notionally `background'.  This is undesirable, so background
364 threads are set to ignore the SIGINT signal.
365
366 @code{sb-thread:make-listener-thread} in addition to creating a new
367 Lisp session makes a new POSIX session, so that pressing
368 @kbd{Control-C} in one window will not interrupt another listener -
369 this has been found to be embarrassing.
370
371
372 @node  Support For Unix
373 @comment  node-name,  next,  previous,  up
374 @subsection Support For Unix
375
376 The UNIX command line can be read from the variable
377 @code{sb-ext:*posix-argv*}. The UNIX environment can be queried with
378 the @code{sb-ext:posix-getenv} function.
379
380 @include fun-sb-ext-posix-getenv.texinfo
381
382 The SBCL system can be terminated with @code{sb-ext:quit}, (but see
383 notes in @ref{Threading} about the interaction between this feature and
384 sessions) optionally returning a specified numeric value to the
385 calling Unix process. The normal Unix idiom of terminating on end of
386 file on input is also supported.
387
388 @include fun-sb-ext-quit.texinfo
389
390 @node  Customization Hooks for Users
391 @comment  node-name,  next,  previous,  up
392 @subsection Customization Hooks for Users
393
394 The toplevel repl prompt may be customized, and the function
395 that reads user input may be replaced completely.
396 @c <!-- FIXME but I don't currently remember how -->
397
398 The behaviour of @code{require} when called with only one argument is
399 implementation-defined.  In SBCL, @code{require} behaves in the
400 following way:
401
402 @include fun-common-lisp-require.texinfo
403 @include var-sb-ext-star-module-provider-functions-star.texinfo
404
405 Although SBCL does not provide a resident editor, the @code{ed}
406 function can be customized to hook into user-provided editing
407 mechanisms as follows:
408
409 @include fun-common-lisp-ed.texinfo
410 @include var-sb-ext-star-ed-functions-star.texinfo
411
412 @node  Tools To Help Developers
413 @comment  node-name,  next,  previous,  up
414 @subsection Tools To Help Developers
415
416 SBCL provides a profiler and other extensions to the ANSI @code{trace}
417 facility.  For more information, see @ref{macro-common-lisp-trace}.
418
419 The debugger supports a number of options. Its documentation is
420 accessed by typing @kbd{help} at the debugger prompt. @xref{Debugger}.
421
422 Documentation for @code{inspect} is accessed by typing @kbd{help} at
423 the @code{inspect} prompt.
424
425 @node  Interface To Low-Level SBCL Implementation
426 @comment  node-name,  next,  previous,  up
427 @subsection Interface To Low-Level SBCL Implementation
428
429 SBCL has the ability to save its state as a file for later
430 execution. This functionality is important for its bootstrapping
431 process, and is also provided as an extension to the user.  Note that
432 foreign libraries loaded via @code{load-shared-object} don't survive
433 this process; a core should not be saved in this case.
434
435 @emph{FIXME: what should be done for foreign libraries?}
436
437 @emph{FIXME: document load-shared-object somewhere - it's in
438 ffi.texinfo?}
439
440 @include fun-sb-ext-save-lisp-and-die.texinfo
441
442
443 @node Stale Extensions
444 @comment  node-name,  next,  previous,  up
445 @subsection Stale Extensions
446
447 SBCL has inherited from CMUCL various hooks to allow the user to
448 tweak and monitor the garbage collection process. These are somewhat
449 stale code, and their interface might need to be cleaned up. If you
450 have urgent need of them, look at the code in @file{src/code/gc.lisp}
451 and bring it up on the developers' mailing list.
452
453 SBCL has various hooks inherited from CMUCL, like
454 @code{sb-ext:float-denormalized-p}, to allow a program to take
455 advantage of IEEE floating point arithmetic properties which aren't
456 conveniently or efficiently expressible using the ANSI standard. These
457 look good, and their interface looks good, but IEEE support is
458 slightly broken due to a stupid decision to remove some support for
459 infinities (because it wasn't in the ANSI spec and it didn't occur to
460 me that it was in the IEEE spec). If you need this stuff, take a look
461 at the code and bring it up on the developers' mailing
462 list.
463
464
465 @node  Efficiency Hacks
466 @comment  node-name,  next,  previous,  up
467 @subsection Efficiency Hacks
468
469 The @code{sb-ext:purify} function causes SBCL first to collect all
470 garbage, then to mark all uncollected objects as permanent, never
471 again attempting to collect them as garbage. This can cause a large
472 increase in efficiency when using a primitive garbage collector, or a
473 more moderate increase in efficiency when using a more sophisticated
474 garbage collector which is well suited to the program's memory usage
475 pattern. It also allows permanent code to be frozen at fixed
476 addresses, a precondition for using copy-on-write to share code
477 between multiple Lisp processes. it is less important with modern
478 generational garbage collectors.
479
480 @include fun-sb-ext-purify.texinfo
481
482 The @code{sb-ext:truly-the} special form declares the type of the
483 result of the operations, producing its argument; the declaration is
484 not checked. In short: don't use it.
485
486 @include special-operator-sb-ext-truly-the.texinfo
487
488 The @code{sb-ext:freeze-type} declaration declares that a
489 type will never change, which can make type testing
490 (@code{typep}, etc.) more efficient for structure types.
491
492 The @code{sb-ext:constant-function} declaration specifies
493 that a function will always return the same value for the same
494 arguments, which may allow the compiler to optimize calls
495 to it. This is appropriate for functions like @code{sqrt}, but
496 is @emph{not} appropriate for functions like @code{aref},
497 which can change their return values when the underlying data are
498 changed.
499 @c <!-- FIXME: This declaration does not seem to be supported in the 
500 @c      current compiler. -->