Sync up with r21-4-14-chise-0_21-17.
[chise/xemacs-chise.git] / info / cl.info-5
1 This is ../info/cl.info, produced by makeinfo version 4.0 from cl.texi.
2
3 INFO-DIR-SECTION XEmacs Editor
4 START-INFO-DIR-ENTRY
5 * Common Lisp: (cl).            GNU Emacs Common Lisp emulation package.
6 END-INFO-DIR-ENTRY
7
8    This file documents the GNU Emacs Common Lisp emulation package.
9
10    Copyright (C) 1993 Free Software Foundation, Inc.
11
12    Permission is granted to make and distribute verbatim copies of this
13 manual provided the copyright notice and this permission notice are
14 preserved on all copies.
15
16    Permission is granted to copy and distribute modified versions of
17 this manual under the conditions for verbatim copying, provided also
18 that the section entitled "GNU General Public License" is included
19 exactly as in the original, and provided that the entire resulting
20 derived work is distributed under the terms of a permission notice
21 identical to this one.
22
23    Permission is granted to copy and distribute translations of this
24 manual into another language, under the above conditions for modified
25 versions, except that the section entitled "GNU General Public License"
26 may be included in a translation approved by the author instead of in
27 the original English.
28
29 \1f
30 File: cl.info,  Node: Structures,  Next: Assertions,  Prev: Hash Tables,  Up: Top
31
32 Structures
33 **********
34
35 The Common Lisp "structure" mechanism provides a general way to define
36 data types similar to C's `struct' types.  A structure is a Lisp object
37 containing some number of "slots", each of which can hold any Lisp data
38 object.  Functions are provided for accessing and setting the slots,
39 creating or copying structure objects, and recognizing objects of a
40 particular structure type.
41
42    In true Common Lisp, each structure type is a new type distinct from
43 all existing Lisp types.  Since the underlying Emacs Lisp system
44 provides no way to create new distinct types, this package implements
45 structures as vectors (or lists upon request) with a special "tag"
46 symbol to identify them.
47
48  - Special Form: defstruct name slots...
49      The `defstruct' form defines a new structure type called NAME,
50      with the specified SLOTS.  (The SLOTS may begin with a string
51      which documents the structure type.)  In the simplest case, NAME
52      and each of the SLOTS are symbols.  For example,
53
54           (defstruct person name age sex)
55
56      defines a struct type called `person' which contains three slots.
57      Given a `person' object P, you can access those slots by calling
58      `(person-name P)', `(person-age P)', and `(person-sex P)'.  You
59      can also change these slots by using `setf' on any of these place
60      forms:
61
62           (incf (person-age birthday-boy))
63
64      You can create a new `person' by calling `make-person', which
65      takes keyword arguments `:name', `:age', and `:sex' to specify the
66      initial values of these slots in the new object.  (Omitting any of
67      these arguments leaves the corresponding slot "undefined,"
68      according to the Common Lisp standard; in Emacs Lisp, such
69      uninitialized slots are filled with `nil'.)
70
71      Given a `person', `(copy-person P)' makes a new object of the same
72      type whose slots are `eq' to those of P.
73
74      Given any Lisp object X, `(person-p X)' returns true if X looks
75      like a `person', false otherwise.  (Again, in Common Lisp this
76      predicate would be exact; in Emacs Lisp the best it can do is
77      verify that X is a vector of the correct length which starts with
78      the correct tag symbol.)
79
80      Accessors like `person-name' normally check their arguments
81      (effectively using `person-p') and signal an error if the argument
82      is the wrong type.  This check is affected by `(optimize (safety
83      ...))' declarations.  Safety level 1, the default, uses a somewhat
84      optimized check that will detect all incorrect arguments, but may
85      use an uninformative error message (e.g., "expected a vector"
86      instead of "expected a `person'").  Safety level 0 omits all
87      checks except as provided by the underlying `aref' call; safety
88      levels 2 and 3 do rigorous checking that will always print a
89      descriptive error message for incorrect inputs.  *Note
90      Declarations::.
91
92           (setq dave (make-person :name "Dave" :sex 'male))
93                => [cl-struct-person "Dave" nil male]
94           (setq other (copy-person dave))
95                => [cl-struct-person "Dave" nil male]
96           (eq dave other)
97                => nil
98           (eq (person-name dave) (person-name other))
99                => t
100           (person-p dave)
101                => t
102           (person-p [1 2 3 4])
103                => nil
104           (person-p "Bogus")
105                => nil
106           (person-p '[cl-struct-person counterfeit person object])
107                => t
108
109      In general, NAME is either a name symbol or a list of a name
110      symbol followed by any number of "struct options"; each SLOT is
111      either a slot symbol or a list of the form `(SLOT-NAME
112      DEFAULT-VALUE SLOT-OPTIONS...)'.  The DEFAULT-VALUE is a Lisp form
113      which is evaluated any time an instance of the structure type is
114      created without specifying that slot's value.
115
116      Common Lisp defines several slot options, but the only one
117      implemented in this package is `:read-only'.  A non-`nil' value
118      for this option means the slot should not be `setf'-able; the
119      slot's value is determined when the object is created and does not
120      change afterward.
121
122           (defstruct person
123             (name nil :read-only t)
124             age
125             (sex 'unknown))
126
127      Any slot options other than `:read-only' are ignored.
128
129      For obscure historical reasons, structure options take a different
130      form than slot options.  A structure option is either a keyword
131      symbol, or a list beginning with a keyword symbol possibly followed
132      by arguments.  (By contrast, slot options are key-value pairs not
133      enclosed in lists.)
134
135           (defstruct (person (:constructor create-person)
136                              (:type list)
137                              :named)
138             name age sex)
139
140      The following structure options are recognized.
141
142     `:conc-name'
143           The argument is a symbol whose print name is used as the
144           prefix for the names of slot accessor functions.  The default
145           is the name of the struct type followed by a hyphen.  The
146           option `(:conc-name p-)' would change this prefix to `p-'.
147           Specifying `nil' as an argument means no prefix, so that the
148           slot names themselves are used to name the accessor functions.
149
150     `:constructor'
151           In the simple case, this option takes one argument which is an
152           alternate name to use for the constructor function.  The
153           default is `make-NAME', e.g., `make-person'.  The above
154           example changes this to `create-person'.  Specifying `nil' as
155           an argument means that no standard constructor should be
156           generated at all.
157
158           In the full form of this option, the constructor name is
159           followed by an arbitrary argument list.  *Note Program
160           Structure::, for a description of the format of Common Lisp
161           argument lists.  All options, such as `&rest' and `&key', are
162           supported.  The argument names should match the slot names;
163           each slot is initialized from the corresponding argument.
164           Slots whose names do not appear in the argument list are
165           initialized based on the DEFAULT-VALUE in their slot
166           descriptor.  Also, `&optional' and `&key' arguments which
167           don't specify defaults take their defaults from the slot
168           descriptor.  It is legal to include arguments which don't
169           correspond to slot names; these are useful if they are
170           referred to in the defaults for optional, keyword, or `&aux'
171           arguments which _do_ correspond to slots.
172
173           You can specify any number of full-format `:constructor'
174           options on a structure.  The default constructor is still
175           generated as well unless you disable it with a simple-format
176           `:constructor' option.
177
178                (defstruct
179                 (person
180                  (:constructor nil)   ; no default constructor
181                  (:constructor new-person (name sex &optional (age 0)))
182                  (:constructor new-hound (&key (name "Rover")
183                                                (dog-years 0)
184                                           &aux (age (* 7 dog-years))
185                                                (sex 'canine))))
186                 name age sex)
187
188           The first constructor here takes its arguments positionally
189           rather than by keyword.  (In official Common Lisp
190           terminology, constructors that work By Order of Arguments
191           instead of by keyword are called "BOA constructors."  No, I'm
192           not making this up.)  For example, `(new-person "Jane"
193           'female)' generates a person whose slots are `"Jane"', 0, and
194           `female', respectively.
195
196           The second constructor takes two keyword arguments, `:name',
197           which initializes the `name' slot and defaults to `"Rover"',
198           and `:dog-years', which does not itself correspond to a slot
199           but which is used to initialize the `age' slot.  The `sex'
200           slot is forced to the symbol `canine' with no syntax for
201           overriding it.
202
203     `:copier'
204           The argument is an alternate name for the copier function for
205           this type.  The default is `copy-NAME'.  `nil' means not to
206           generate a copier function.  (In this implementation, all
207           copier functions are simply synonyms for `copy-sequence'.)
208
209     `:predicate'
210           The argument is an alternate name for the predicate which
211           recognizes objects of this type.  The default is `NAME-p'.
212           `nil' means not to generate a predicate function.  (If the
213           `:type' option is used without the `:named' option, no
214           predicate is ever generated.)
215
216           In true Common Lisp, `typep' is always able to recognize a
217           structure object even if `:predicate' was used.  In this
218           package, `typep' simply looks for a function called
219           `TYPENAME-p', so it will work for structure types only if
220           they used the default predicate name.
221
222     `:include'
223           This option implements a very limited form of C++-style
224           inheritance.  The argument is the name of another structure
225           type previously created with `defstruct'.  The effect is to
226           cause the new structure type to inherit all of the included
227           structure's slots (plus, of course, any new slots described
228           by this struct's slot descriptors).  The new structure is
229           considered a "specialization" of the included one.  In fact,
230           the predicate and slot accessors for the included type will
231           also accept objects of the new type.
232
233           If there are extra arguments to the `:include' option after
234           the included-structure name, these options are treated as
235           replacement slot descriptors for slots in the included
236           structure, possibly with modified default values.  Borrowing
237           an example from Steele:
238
239                (defstruct person name (age 0) sex)
240                     => person
241                (defstruct (astronaut (:include person (age 45)))
242                  helmet-size
243                  (favorite-beverage 'tang))
244                     => astronaut
245                
246                (setq joe (make-person :name "Joe"))
247                     => [cl-struct-person "Joe" 0 nil]
248                (setq buzz (make-astronaut :name "Buzz"))
249                     => [cl-struct-astronaut "Buzz" 45 nil nil tang]
250                
251                (list (person-p joe) (person-p buzz))
252                     => (t t)
253                (list (astronaut-p joe) (astronaut-p buzz))
254                     => (nil t)
255                
256                (person-name buzz)
257                     => "Buzz"
258                (astronaut-name joe)
259                     => error: "astronaut-name accessing a non-astronaut"
260
261           Thus, if `astronaut' is a specialization of `person', then
262           every `astronaut' is also a `person' (but not the other way
263           around).  Every `astronaut' includes all the slots of a
264           `person', plus extra slots that are specific to astronauts.
265           Operations that work on people (like `person-name') work on
266           astronauts just like other people.
267
268     `:print-function'
269           In full Common Lisp, this option allows you to specify a
270           function which is called to print an instance of the
271           structure type.  The Emacs Lisp system offers no hooks into
272           the Lisp printer which would allow for such a feature, so
273           this package simply ignores `:print-function'.
274
275     `:type'
276           The argument should be one of the symbols `vector' or `list'.
277           This tells which underlying Lisp data type should be used to
278           implement the new structure type.  Vectors are used by
279           default, but `(:type list)' will cause structure objects to
280           be stored as lists instead.
281
282           The vector representation for structure objects has the
283           advantage that all structure slots can be accessed quickly,
284           although creating vectors is a bit slower in Emacs Lisp.
285           Lists are easier to create, but take a relatively long time
286           accessing the later slots.
287
288     `:named'
289           This option, which takes no arguments, causes a
290           characteristic "tag" symbol to be stored at the front of the
291           structure object.  Using `:type' without also using `:named'
292           will result in a structure type stored as plain vectors or
293           lists with no identifying features.
294
295           The default, if you don't specify `:type' explicitly, is to
296           use named vectors.  Therefore, `:named' is only useful in
297           conjunction with `:type'.
298
299                (defstruct (person1) name age sex)
300                (defstruct (person2 (:type list) :named) name age sex)
301                (defstruct (person3 (:type list)) name age sex)
302                
303                (setq p1 (make-person1))
304                     => [cl-struct-person1 nil nil nil]
305                (setq p2 (make-person2))
306                     => (person2 nil nil nil)
307                (setq p3 (make-person3))
308                     => (nil nil nil)
309                
310                (person1-p p1)
311                     => t
312                (person2-p p2)
313                     => t
314                (person3-p p3)
315                     => error: function person3-p undefined
316
317           Since unnamed structures don't have tags, `defstruct' is not
318           able to make a useful predicate for recognizing them.  Also,
319           accessors like `person3-name' will be generated but they will
320           not be able to do any type checking.  The `person3-name'
321           function, for example, will simply be a synonym for `car' in
322           this case.  By contrast, `person2-name' is able to verify
323           that its argument is indeed a `person2' object before
324           proceeding.
325
326     `:initial-offset'
327           The argument must be a nonnegative integer.  It specifies a
328           number of slots to be left "empty" at the front of the
329           structure.  If the structure is named, the tag appears at the
330           specified position in the list or vector; otherwise, the first
331           slot appears at that position.  Earlier positions are filled
332           with `nil' by the constructors and ignored otherwise.  If the
333           type `:include's another type, then `:initial-offset'
334           specifies a number of slots to be skipped between the last
335           slot of the included type and the first new slot.
336
337    Except as noted, the `defstruct' facility of this package is
338 entirely compatible with that of Common Lisp.
339
340 \1f
341 File: cl.info,  Node: Assertions,  Next: Efficiency Concerns,  Prev: Structures,  Up: Top
342
343 Assertions and Errors
344 *********************
345
346 This section describes two macros that test "assertions", i.e.,
347 conditions which must be true if the program is operating correctly.
348 Assertions never add to the behavior of a Lisp program; they simply
349 make "sanity checks" to make sure everything is as it should be.
350
351    If the optimization property `speed' has been set to 3, and `safety'
352 is less than 3, then the byte-compiler will optimize away the following
353 assertions.  Because assertions might be optimized away, it is a bad
354 idea for them to include side-effects.
355
356  - Special Form: assert test-form [show-args string args...]
357      This form verifies that TEST-FORM is true (i.e., evaluates to a
358      non-`nil' value).  If so, it returns `nil'.  If the test is not
359      satisfied, `assert' signals an error.
360
361      A default error message will be supplied which includes TEST-FORM.
362      You can specify a different error message by including a STRING
363      argument plus optional extra arguments.  Those arguments are simply
364      passed to `error' to signal the error.
365
366      If the optional second argument SHOW-ARGS is `t' instead of `nil',
367      then the error message (with or without STRING) will also include
368      all non-constant arguments of the top-level FORM.  For example:
369
370           (assert (> x 10) t "x is too small: %d")
371
372      This usage of SHOW-ARGS is a change to Common Lisp.  In true
373      Common Lisp, the second argument gives a list of PLACES which can
374      be `setf''d by the user before continuing from the error.
375
376  - Special Form: check-type place type &optional string
377      This form verifies that PLACE evaluates to a value of type TYPE.
378      If so, it returns `nil'.  If not, `check-type' signals a
379      continuable `wrong-type-argument' error.  The default error
380      message lists the erroneous value along with TYPE and PLACE
381      themselves.  If STRING is specified, it is included in the error
382      message in place of TYPE.  For example:
383
384           (check-type x (integer 1 *) "a positive integer")
385
386      *Note Type Predicates::, for a description of the type specifiers
387      that may be used for TYPE.
388
389      Note that as in Common Lisp, the first argument to `check-type'
390      should be a PLACE suitable for use by `setf', because `check-type'
391      signals a continuable error that allows the user to modify PLACE,
392      most simply by returning a value from the debugger.
393
394    The following error-related macro is also defined:
395
396  - Special Form: ignore-errors forms...
397      This executes FORMS exactly like a `progn', except that errors are
398      ignored during the FORMS.  More precisely, if an error is
399      signalled then `ignore-errors' immediately aborts execution of the
400      FORMS and returns `nil'.  If the FORMS complete successfully,
401      `ignore-errors' returns the result of the last FORM.
402
403 \1f
404 File: cl.info,  Node: Efficiency Concerns,  Next: Common Lisp Compatibility,  Prev: Assertions,  Up: Top
405
406 Efficiency Concerns
407 *******************
408
409 Macros
410 ======
411
412 Many of the advanced features of this package, such as `defun*',
413 `loop', and `setf', are implemented as Lisp macros.  In byte-compiled
414 code, these complex notations will be expanded into equivalent Lisp
415 code which is simple and efficient.  For example, the forms
416
417      (incf i n)
418      (push x (car p))
419
420 are expanded at compile-time to the Lisp forms
421
422      (setq i (+ i n))
423      (setcar p (cons x (car p)))
424
425 which are the most efficient ways of doing these respective operations
426 in Lisp.  Thus, there is no performance penalty for using the more
427 readable `incf' and `push' forms in your compiled code.
428
429    _Interpreted_ code, on the other hand, must expand these macros
430 every time they are executed.  For this reason it is strongly
431 recommended that code making heavy use of macros be compiled.  (The
432 features labelled "Special Form" instead of "Function" in this manual
433 are macros.)  A loop using `incf' a hundred times will execute
434 considerably faster if compiled, and will also garbage-collect less
435 because the macro expansion will not have to be generated, used, and
436 thrown away a hundred times.
437
438    You can find out how a macro expands by using the `cl-prettyexpand'
439 function.
440
441  - Function: cl-prettyexpand form &optional full
442      This function takes a single Lisp form as an argument and inserts
443      a nicely formatted copy of it in the current buffer (which must be
444      in Lisp mode so that indentation works properly).  It also expands
445      all Lisp macros which appear in the form.  The easiest way to use
446      this function is to go to the `*scratch*' buffer and type, say,
447
448           (cl-prettyexpand '(loop for x below 10 collect x))
449
450      and type `C-x C-e' immediately after the closing parenthesis; the
451      expansion
452
453           (block nil
454             (let* ((x 0)
455                    (G1004 nil))
456               (while (< x 10)
457                 (setq G1004 (cons x G1004))
458                 (setq x (+ x 1)))
459               (nreverse G1004)))
460
461      will be inserted into the buffer.  (The `block' macro is expanded
462      differently in the interpreter and compiler, so `cl-prettyexpand'
463      just leaves it alone.  The temporary variable `G1004' was created
464      by `gensym'.)
465
466      If the optional argument FULL is true, then _all_ macros are
467      expanded, including `block', `eval-when', and compiler macros.
468      Expansion is done as if FORM were a top-level form in a file being
469      compiled.  For example,
470
471           (cl-prettyexpand '(pushnew 'x list))
472                -| (setq list (adjoin 'x list))
473           (cl-prettyexpand '(pushnew 'x list) t)
474                -| (setq list (if (memq 'x list) list (cons 'x list)))
475           (cl-prettyexpand '(caddr (member* 'a list)) t)
476                -| (car (cdr (cdr (memq 'a list))))
477
478      Note that `adjoin', `caddr', and `member*' all have built-in
479      compiler macros to optimize them in common cases.
480
481
482 Error Checking
483 ==============
484
485 Common Lisp compliance has in general not been sacrificed for the sake
486 of efficiency.  A few exceptions have been made for cases where
487 substantial gains were possible at the expense of marginal
488 incompatibility.  One example is the use of `memq' (which is treated
489 very efficiently by the byte-compiler) to scan for keyword arguments;
490 this can become confused in rare cases when keyword symbols are used as
491 both keywords and data values at once.  This is extremely unlikely to
492 occur in practical code, and the use of `memq' allows functions with
493 keyword arguments to be nearly as fast as functions that use
494 `&optional' arguments.
495
496    The Common Lisp standard (as embodied in Steele's book) uses the
497 phrase "it is an error if" to indicate a situation which is not
498 supposed to arise in complying programs; implementations are strongly
499 encouraged but not required to signal an error in these situations.
500 This package sometimes omits such error checking in the interest of
501 compactness and efficiency.  For example, `do' variable specifiers are
502 supposed to be lists of one, two, or three forms; extra forms are
503 ignored by this package rather than signalling a syntax error.  The
504 `endp' function is simply a synonym for `null' in this package.
505 Functions taking keyword arguments will accept an odd number of
506 arguments, treating the trailing keyword as if it were followed by the
507 value `nil'.
508
509    Argument lists (as processed by `defun*' and friends) _are_ checked
510 rigorously except for the minor point just mentioned; in particular,
511 keyword arguments are checked for validity, and `&allow-other-keys' and
512 `:allow-other-keys' are fully implemented.  Keyword validity checking
513 is slightly time consuming (though not too bad in byte-compiled code);
514 you can use `&allow-other-keys' to omit this check.  Functions defined
515 in this package such as `find' and `member*' do check their keyword
516 arguments for validity.
517
518
519 Optimizing Compiler
520 ===================
521
522 The byte-compiler that comes with Emacs 18 normally fails to expand
523 macros that appear in top-level positions in the file (i.e., outside of
524 `defun's or other enclosing forms).  This would have disastrous
525 consequences to programs that used such top-level macros as `defun*',
526 `eval-when', and `defstruct'.  To work around this problem, the "CL"
527 package patches the Emacs 18 compiler to expand top-level macros.  This
528 patch will apply to your own macros, too, if they are used in a
529 top-level context.  The patch will not harm versions of the Emacs 18
530 compiler which have already had a similar patch applied, nor will it
531 affect the optimizing Emacs 19 byte-compiler written by Jamie Zawinski
532 and Hallvard Furuseth.  The patch is applied to the byte compiler's
533 code in Emacs' memory, _not_ to the `bytecomp.elc' file stored on disk.
534
535    The Emacs 19 compiler (for Emacs 18) is available from various Emacs
536 Lisp archive sites such as `archive.cis.ohio-state.edu'.  Its use is
537 highly recommended; many of the Common Lisp macros emit code which can
538 be improved by optimization.  In particular, `block's (whether explicit
539 or implicit in constructs like `defun*' and `loop') carry a fair
540 run-time penalty; the optimizing compiler removes `block's which are
541 not actually referenced by `return' or `return-from' inside the block.
542
543 \1f
544 File: cl.info,  Node: Common Lisp Compatibility,  Next: Old CL Compatibility,  Prev: Efficiency Concerns,  Up: Top
545
546 Common Lisp Compatibility
547 *************************
548
549 Following is a list of all known incompatibilities between this package
550 and Common Lisp as documented in Steele (2nd edition).
551
552    Certain function names, such as `member', `assoc', and `floor', were
553 already taken by (incompatible) Emacs Lisp functions; this package
554 appends `*' to the names of its Common Lisp versions of these functions.
555
556    The word `defun*' is required instead of `defun' in order to use
557 extended Common Lisp argument lists in a function.  Likewise,
558 `defmacro*' and `function*' are versions of those forms which
559 understand full-featured argument lists.  The `&whole' keyword does not
560 work in `defmacro' argument lists (except inside recursive argument
561 lists).
562
563    In order to allow an efficient implementation, keyword arguments use
564 a slightly cheesy parser which may be confused if a keyword symbol is
565 passed as the _value_ of another keyword argument.  (Specifically,
566 `(memq :KEYWORD REST-OF-ARGUMENTS)' is used to scan for `:KEYWORD'
567 among the supplied keyword arguments.)
568
569    The `eql' and `equal' predicates do not distinguish between IEEE
570 floating-point plus and minus zero.  The `equalp' predicate has several
571 differences with Common Lisp; *note Predicates::.
572
573    The `setf' mechanism is entirely compatible, except that
574 setf-methods return a list of five values rather than five values
575 directly.  Also, the new "`setf' function" concept (typified by `(defun
576 (setf foo) ...)') is not implemented.
577
578    The `do-all-symbols' form is the same as `do-symbols' with no
579 OBARRAY argument.  In Common Lisp, this form would iterate over all
580 symbols in all packages.  Since Emacs obarrays are not a first-class
581 package mechanism, there is no way for `do-all-symbols' to locate any
582 but the default obarray.
583
584    The `loop' macro is complete except that `loop-finish' and type
585 specifiers are unimplemented.
586
587    The multiple-value return facility treats lists as multiple values,
588 since Emacs Lisp cannot support multiple return values directly.  The
589 macros will be compatible with Common Lisp if `values' or `values-list'
590 is always used to return to a `multiple-value-bind' or other
591 multiple-value receiver; if `values' is used without
592 `multiple-value-...' or vice-versa the effect will be different from
593 Common Lisp.
594
595    Many Common Lisp declarations are ignored, and others match the
596 Common Lisp standard in concept but not in detail.  For example, local
597 `special' declarations, which are purely advisory in Emacs Lisp, do not
598 rigorously obey the scoping rules set down in Steele's book.
599
600    The variable `*gensym-counter*' starts out with a pseudo-random
601 value rather than with zero.  This is to cope with the fact that
602 generated symbols become interned when they are written to and loaded
603 back from a file.
604
605    The `defstruct' facility is compatible, except that structures are
606 of type `:type vector :named' by default rather than some special,
607 distinct type.  Also, the `:type' slot option is ignored.
608
609    The second argument of `check-type' is treated differently.
610
611 \1f
612 File: cl.info,  Node: Old CL Compatibility,  Next: Porting Common Lisp,  Prev: Common Lisp Compatibility,  Up: Top
613
614 Old CL Compatibility
615 ********************
616
617 Following is a list of all known incompatibilities between this package
618 and the older Quiroz `cl.el' package.
619
620    This package's emulation of multiple return values in functions is
621 incompatible with that of the older package.  That package attempted to
622 come as close as possible to true Common Lisp multiple return values;
623 unfortunately, it could not be 100% reliable and so was prone to
624 occasional surprises if used freely.  This package uses a simpler
625 method, namely replacing multiple values with lists of values, which is
626 more predictable though more noticeably different from Common Lisp.
627
628    The `defkeyword' form and `keywordp' function are not implemented in
629 this package.
630
631    The `member', `floor', `ceiling', `truncate', `round', `mod', and
632 `rem' functions are suffixed by `*' in this package to avoid collision
633 with existing functions in Emacs 18 or Emacs 19.  The older package
634 simply redefined these functions, overwriting the built-in meanings and
635 causing serious portability problems with Emacs 19.  (Some more recent
636 versions of the Quiroz package changed the names to `cl-member', etc.;
637 this package defines the latter names as aliases for `member*', etc.)
638
639    Certain functions in the old package which were buggy or inconsistent
640 with the Common Lisp standard are incompatible with the conforming
641 versions in this package.  For example, `eql' and `member' were
642 synonyms for `eq' and `memq' in that package, `setf' failed to preserve
643 correct order of evaluation of its arguments, etc.
644
645    Finally, unlike the older package, this package is careful to prefix
646 all of its internal names with `cl-'.  Except for a few functions which
647 are explicitly defined as additional features (such as `floatp-safe'
648 and `letf'), this package does not export any non-`cl-' symbols which
649 are not also part of Common Lisp.
650
651
652 The `cl-compat' package
653 =======================
654
655 The "CL" package includes emulations of some features of the old
656 `cl.el', in the form of a compatibility package `cl-compat'.  To use
657 it, put `(require 'cl-compat)' in your program.
658
659    The old package defined a number of internal routines without `cl-'
660 prefixes or other annotations.  Call to these routines may have crept
661 into existing Lisp code.  `cl-compat' provides emulations of the
662 following internal routines: `pair-with-newsyms', `zip-lists',
663 `unzip-lists', `reassemble-arglists', `duplicate-symbols-p',
664 `safe-idiv'.
665
666    Some `setf' forms translated into calls to internal functions that
667 user code might call directly.  The functions `setnth', `setnthcdr',
668 and `setelt' fall in this category; they are defined by `cl-compat',
669 but the best fix is to change to use `setf' properly.
670
671    The `cl-compat' file defines the keyword functions `keywordp',
672 `keyword-of', and `defkeyword', which are not defined by the new "CL"
673 package because the use of keywords as data is discouraged.
674
675    The `build-klist' mechanism for parsing keyword arguments is
676 emulated by `cl-compat'; the `with-keyword-args' macro is not, however,
677 and in any case it's best to change to use the more natural keyword
678 argument processing offered by `defun*'.
679
680    Multiple return values are treated differently by the two Common
681 Lisp packages.  The old package's method was more compatible with true
682 Common Lisp, though it used heuristics that caused it to report
683 spurious multiple return values in certain cases.  The `cl-compat'
684 package defines a set of multiple-value macros that are compatible with
685 the old CL package; again, they are heuristic in nature, but they are
686 guaranteed to work in any case where the old package's macros worked.
687 To avoid name collision with the "official" multiple-value facilities,
688 the ones in `cl-compat' have capitalized names:  `Values',
689 `Values-list', `Multiple-value-bind', etc.
690
691    The functions `cl-floor', `cl-ceiling', `cl-truncate', and
692 `cl-round' are defined by `cl-compat' to use the old-style
693 multiple-value mechanism, just as they did in the old package.  The
694 newer `floor*' and friends return their two results in a list rather
695 than as multiple values.  Note that older versions of the old package
696 used the unadorned names `floor', `ceiling', etc.; `cl-compat' cannot
697 use these names because they conflict with Emacs 19 built-ins.
698
699 \1f
700 File: cl.info,  Node: Porting Common Lisp,  Next: Function Index,  Prev: Old CL Compatibility,  Up: Top
701
702 Porting Common Lisp
703 *******************
704
705 This package is meant to be used as an extension to Emacs Lisp, not as
706 an Emacs implementation of true Common Lisp.  Some of the remaining
707 differences between Emacs Lisp and Common Lisp make it difficult to
708 port large Common Lisp applications to Emacs.  For one, some of the
709 features in this package are not fully compliant with ANSI or Steele;
710 *note Common Lisp Compatibility::.  But there are also quite a few
711 features that this package does not provide at all.  Here are some
712 major omissions that you will want watch out for when bringing Common
713 Lisp code into Emacs.
714
715    * Case-insensitivity.  Symbols in Common Lisp are case-insensitive
716      by default.  Some programs refer to a function or variable as
717      `foo' in one place and `Foo' or `FOO' in another.  Emacs Lisp will
718      treat these as three distinct symbols.
719
720      Some Common Lisp code is written in all upper-case.  While Emacs
721      is happy to let the program's own functions and variables use this
722      convention, calls to Lisp builtins like `if' and `defun' will have
723      to be changed to lower-case.
724
725    * Lexical scoping.  In Common Lisp, function arguments and `let'
726      bindings apply only to references physically within their bodies
727      (or within macro expansions in their bodies).  Emacs Lisp, by
728      contrast, uses "dynamic scoping" wherein a binding to a variable
729      is visible even inside functions called from the body.
730
731      Variables in Common Lisp can be made dynamically scoped by
732      declaring them `special' or using `defvar'.  In Emacs Lisp it is
733      as if all variables were declared `special'.
734
735      Often you can use code that was written for lexical scoping even
736      in a dynamically scoped Lisp, but not always.  Here is an example
737      of a Common Lisp code fragment that would fail in Emacs Lisp:
738
739           (defun map-odd-elements (func list)
740             (loop for x in list
741                   for flag = t then (not flag)
742                   collect (if flag x (funcall func x))))
743           
744           (defun add-odd-elements (list x)
745             (map-odd-elements (function (lambda (a) (+ a x))) list))
746
747      In Common Lisp, the two functions' usages of `x' are completely
748      independent.  In Emacs Lisp, the binding to `x' made by
749      `add-odd-elements' will have been hidden by the binding in
750      `map-odd-elements' by the time the `(+ a x)' function is called.
751
752      (This package avoids such problems in its own mapping functions by
753      using names like `cl-x' instead of `x' internally; as long as you
754      don't use the `cl-' prefix for your own variables no collision can
755      occur.)
756
757      *Note Lexical Bindings::, for a description of the `lexical-let'
758      form which establishes a Common Lisp-style lexical binding, and
759      some examples of how it differs from Emacs' regular `let'.
760
761    * Common Lisp allows the shorthand `#'x' to stand for `(function
762      x)', just as `'x' stands for `(quote x)'.  In Common Lisp, one
763      traditionally uses `#'' notation when referring to the name of a
764      function.  In Emacs Lisp, it works just as well to use a regular
765      quote:
766
767           (loop for x in y by #'cddr collect (mapcar #'plusp x)) ; Common Lisp
768           (loop for x in y by 'cddr collect (mapcar 'plusp x))   ; Emacs Lisp
769
770      When `#'' introduces a `lambda' form, it is best to write out
771      `(function ...)' longhand in Emacs Lisp.  You can use a regular
772      quote, but then the byte-compiler won't know that the `lambda'
773      expression is code that can be compiled.
774
775           (mapcar #'(lambda (x) (* x 2)) list)            ; Common Lisp
776           (mapcar (function (lambda (x) (* x 2))) list)   ; Emacs Lisp
777
778      XEmacs supports `#'' notation starting with version 19.8.
779
780    * Reader macros.  Common Lisp includes a second type of macro that
781      works at the level of individual characters.  For example, Common
782      Lisp implements the quote notation by a reader macro called `'',
783      whereas Emacs Lisp's parser just treats quote as a special case.
784      Some Lisp packages use reader macros to create special syntaxes
785      for themselves, which the Emacs parser is incapable of reading.
786
787    * Other syntactic features.  Common Lisp provides a number of
788      notations beginning with `#' that the Emacs Lisp parser won't
789      understand.  For example, `#| ... |#' is an alternate comment
790      notation, and `#+lucid (foo)' tells the parser to ignore the
791      `(foo)' except in Lucid Common Lisp.
792
793      The number prefixes `#b', `#o', and `#x', however, are supported
794      by the Emacs Lisp parser to represent numbers in binary, octal,
795      and hexadecimal notation (or radix), just like in Common Lisp.
796
797    * Packages.  In Common Lisp, symbols are divided into "packages".
798      Symbols that are Lisp built-ins are typically stored in one
799      package; symbols that are vendor extensions are put in another,
800      and each application program would have a package for its own
801      symbols.  Certain symbols are "exported" by a package and others
802      are internal; certain packages "use" or import the exported symbols
803      of other packages.  To access symbols that would not normally be
804      visible due to this importing and exporting, Common Lisp provides
805      a syntax like `package:symbol' or `package::symbol'.
806
807      Emacs Lisp has a single namespace for all interned symbols, and
808      then uses a naming convention of putting a prefix like `cl-' in
809      front of the name.  Some Emacs packages adopt the Common Lisp-like
810      convention of using `cl:' or `cl::' as the prefix.  However, the
811      Emacs parser does not understand colons and just treats them as
812      part of the symbol name.  Thus, while `mapcar' and `lisp:mapcar'
813      may refer to the same symbol in Common Lisp, they are totally
814      distinct in Emacs Lisp.  Common Lisp programs which refer to a
815      symbol by the full name sometimes and the short name other times
816      will not port cleanly to Emacs.
817
818      Emacs Lisp does have a concept of "obarrays," which are
819      package-like collections of symbols, but this feature is not
820      strong enough to be used as a true package mechanism.
821
822    * Keywords.  The notation `:test-not' in Common Lisp really is a
823      shorthand for `keyword:test-not'; keywords are just symbols in a
824      built-in `keyword' package with the special property that all its
825      symbols are automatically self-evaluating.  Common Lisp programs
826      often use keywords liberally to avoid having to use quotes.
827
828      In Emacs Lisp a keyword is just a symbol whose name begins with a
829      colon; since the Emacs parser does not treat them specially, they
830      have to be explicitly made self-evaluating by a statement like
831      `(setq :test-not ':test-not)'.  This package arranges to execute
832      such a statement whenever `defun*' or some other form sees a
833      keyword being used as an argument.  Common Lisp code that assumes
834      that a symbol `:mumble' will be self-evaluating even though it was
835      never introduced by a `defun*' will have to be fixed.
836
837    * The `format' function is quite different between Common Lisp and
838      Emacs Lisp.  It takes an additional "destination" argument before
839      the format string.  A destination of `nil' means to format to a
840      string as in Emacs Lisp; a destination of `t' means to write to
841      the terminal (similar to `message' in Emacs).  Also, format
842      control strings are utterly different; `~' is used instead of `%'
843      to introduce format codes, and the set of available codes is much
844      richer.  There are no notations like `\n' for string literals;
845      instead, `format' is used with the "newline" format code, `~%'.
846      More advanced formatting codes provide such features as paragraph
847      filling, case conversion, and even loops and conditionals.
848
849      While it would have been possible to implement most of Common Lisp
850      `format' in this package (under the name `format*', of course), it
851      was not deemed worthwhile.  It would have required a huge amount
852      of code to implement even a decent subset of `format*', yet the
853      functionality it would provide over Emacs Lisp's `format' would
854      rarely be useful.
855
856    * Vector constants use square brackets in Emacs Lisp, but `#(a b c)'
857      notation in Common Lisp.  To further complicate matters, Emacs 19
858      introduces its own `#(' notation for something entirely
859      different--strings with properties.
860
861    * Characters are distinct from integers in Common Lisp.  The
862      notation for character constants is also different:  `#\A' instead
863      of `?A'.  Also, `string=' and `string-equal' are synonyms in Emacs
864      Lisp whereas the latter is case-insensitive in Common Lisp.
865
866    * Data types.  Some Common Lisp data types do not exist in Emacs
867      Lisp.  Rational numbers and complex numbers are not present, nor
868      are large integers (all integers are "fixnums").  All arrays are
869      one-dimensional.  There are no readtables or pathnames; streams
870      are a set of existing data types rather than a new data type of
871      their own.  Hash tables, random-states, structures, and packages
872      (obarrays) are built from Lisp vectors or lists rather than being
873      distinct types.
874
875    * The Common Lisp Object System (CLOS) is not implemented, nor is
876      the Common Lisp Condition System.
877
878    * Common Lisp features that are completely redundant with Emacs Lisp
879      features of a different name generally have not been implemented.
880      For example, Common Lisp writes `defconstant' where Emacs Lisp
881      uses `defconst'.  Similarly, `make-list' takes its arguments in
882      different ways in the two Lisps but does exactly the same thing,
883      so this package has not bothered to implement a Common Lisp-style
884      `make-list'.
885
886    * A few more notable Common Lisp features not included in this
887      package:  `compiler-let', `tagbody', `prog', `ldb/dpb',
888      `parse-integer', `cerror'.
889
890    * Recursion.  While recursion works in Emacs Lisp just like it does
891      in Common Lisp, various details of the Emacs Lisp system and
892      compiler make recursion much less efficient than it is in most
893      Lisps.  Some schools of thought prefer to use recursion in Lisp
894      over other techniques; they would sum a list of numbers using
895      something like
896
897           (defun sum-list (list)
898             (if list
899                 (+ (car list) (sum-list (cdr list)))
900               0))
901
902      where a more iteratively-minded programmer might write one of
903      these forms:
904
905           (let ((total 0)) (dolist (x my-list) (incf total x)) total)
906           (loop for x in my-list sum x)
907
908      While this would be mainly a stylistic choice in most Common Lisps,
909      in Emacs Lisp you should be aware that the iterative forms are
910      much faster than recursion.  Also, Lisp programmers will want to
911      note that the current Emacs Lisp compiler does not optimize tail
912      recursion.
913