extensible CAS and CAS extensions
[sbcl.git] / src / code / primordial-extensions.lisp
1 ;;;; various user-level definitions which need to be done particularly
2 ;;;; early
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!IMPL")
14 \f
15 ;;;; target constants which need to appear as early as possible
16
17 ;;; an internal tag for marking empty slots, which needs to be defined
18 ;;; as early as possible because it appears in macroexpansions for
19 ;;; iteration over hash tables
20 ;;;
21 ;;; CMU CL 18b used :EMPTY for this purpose, which was somewhat nasty
22 ;;; since it's easily accessible to the user, so that e.g.
23 ;;;     (DEFVAR *HT* (MAKE-HASH-TABLE))
24 ;;;     (SETF (GETHASH :EMPTY *HT*) :EMPTY)
25 ;;;     (MAPHASH (LAMBDA (K V) (FORMAT T "~&~S ~S~%" K V)))
26 ;;; gives no output -- oops!
27 ;;;
28 ;;; FIXME: It'd probably be good to use the unbound marker for this.
29 ;;; However, there might be some gotchas involving assumptions by
30 ;;; e.g. AREF that they're not going to return the unbound marker,
31 ;;; and there's also the noted-below problem that the C-level code
32 ;;; contains implicit assumptions about this marker.
33 ;;;
34 ;;; KLUDGE: Note that as of version 0.pre7 there's a dependence in the
35 ;;; gencgc.c code on this value being a symbol. (This is only one of
36 ;;; several nasty dependencies between that code and this, alas.)
37 ;;; -- WHN 2001-08-17
38 (eval-when (:compile-toplevel :load-toplevel :execute)
39   (def!constant +empty-ht-slot+ '%empty-ht-slot%))
40 ;;; We shouldn't need this mess now that EVAL-WHEN works.
41
42 ;;; KLUDGE: Using a private symbol still leaves us vulnerable to users
43 ;;; getting nonconforming behavior by messing around with
44 ;;; DO-ALL-SYMBOLS. That seems like a fairly obscure problem, so for
45 ;;; now we just don't worry about it. If for some reason it becomes
46 ;;; worrisome and the magic value needs replacement:
47 ;;;   * The replacement value needs to be LOADable with EQL preserved,
48 ;;;     so that the macroexpansion for WITH-HASH-TABLE-ITERATOR will
49 ;;;     work when compiled into a file and loaded back into SBCL.
50 ;;;     (Thus, just uninterning %EMPTY-HT-SLOT% doesn't work.)
51 ;;;   * The replacement value needs to be acceptable to the
52 ;;;     low-level gencgc.lisp hash table scavenging code.
53 ;;;   * The change will break binary compatibility, since comparisons
54 ;;;     against the value used at the time of compilation are wired
55 ;;;     into FASL files.
56 ;;; -- WHN 20000622
57 \f
58 ;;;; DO-related stuff which needs to be visible on the cross-compilation host
59
60 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
61   (defun frob-do-body (varlist endlist decls-and-code bind step name block)
62     (let* ((r-inits nil) ; accumulator for reversed list
63            (r-steps nil) ; accumulator for reversed list
64            (label-1 (gensym))
65            (label-2 (gensym)))
66       ;; Check for illegal old-style DO.
67       (when (or (not (listp varlist)) (atom endlist))
68         (error "ill-formed ~S -- possibly illegal old style DO?" name))
69       ;; Parse VARLIST to get R-INITS and R-STEPS.
70       (dolist (v varlist)
71         (flet (;; (We avoid using CL:PUSH here so that CL:PUSH can be
72                ;; defined in terms of CL:SETF, and CL:SETF can be
73                ;; defined in terms of CL:DO, and CL:DO can be defined
74                ;; in terms of the current function.)
75                (push-on-r-inits (x)
76                  (setq r-inits (cons x r-inits)))
77                ;; common error-handling
78                (illegal-varlist ()
79                  (error "~S is an illegal form for a ~S varlist." v name)))
80           (cond ((symbolp v) (push-on-r-inits v))
81                 ((listp v)
82                  (unless (symbolp (first v))
83                    (error "~S step variable is not a symbol: ~S"
84                           name
85                           (first v)))
86                  (let ((lv (length v)))
87                    ;; (We avoid using CL:CASE here so that CL:CASE can
88                    ;; be defined in terms of CL:SETF, and CL:SETF can
89                    ;; be defined in terms of CL:DO, and CL:DO can be
90                    ;; defined in terms of the current function.)
91                    (cond ((= lv 1)
92                           (push-on-r-inits (first v)))
93                          ((= lv 2)
94                           (push-on-r-inits v))
95                          ((= lv 3)
96                           (push-on-r-inits (list (first v) (second v)))
97                           (setq r-steps (list* (third v) (first v) r-steps)))
98                          (t (illegal-varlist)))))
99                 (t (illegal-varlist)))))
100       ;; Construct the new form.
101       (multiple-value-bind (code decls)
102           (parse-body decls-and-code :doc-string-allowed nil)
103         `(block ,block
104            (,bind ,(nreverse r-inits)
105                   ,@decls
106                   (tagbody
107                      (go ,label-2)
108                      ,label-1
109                      (tagbody ,@code)
110                      (,step ,@(nreverse r-steps))
111                      ,label-2
112                      (unless ,(first endlist) (go ,label-1))
113                      (return-from ,block (progn ,@(rest endlist))))))))))
114
115 ;;; This is like DO, except it has no implicit NIL block. Each VAR is
116 ;;; initialized in parallel to the value of the specified INIT form.
117 ;;; On subsequent iterations, the VARS are assigned the value of the
118 ;;; STEP form (if any) in parallel. The TEST is evaluated before each
119 ;;; evaluation of the body FORMS. When the TEST is true, the
120 ;;; EXIT-FORMS are evaluated as a PROGN, with the result being the
121 ;;; value of the DO.
122 (defmacro do-anonymous (varlist endlist &rest body)
123   (frob-do-body varlist endlist body 'let 'psetq 'do-anonymous (gensym)))
124 \f
125 ;;;; GENSYM tricks
126
127 ;;; GENSYM variant for easier debugging and better backtraces: append
128 ;;; the closest enclosing non-nil block name to the provided stem.
129 (defun block-gensym (&optional (name "G") (env (when (boundp 'sb!c::*lexenv*)
130                                              (symbol-value 'sb!c::*lexenv*))))
131   (let ((block-name (when env
132                       (car (find-if #'car (sb!c::lexenv-blocks env))))))
133     (if block-name
134         (sb!xc:gensym (format nil "~A[~A]" name block-name))
135         (sb!xc:gensym name))))
136
137 ;;; Compile a version of BODY for all TYPES, and dispatch to the
138 ;;; correct one based on the value of VAR. This was originally used
139 ;;; only for strings, hence the name. Renaming it to something more
140 ;;; generic might not be a bad idea.
141 (defmacro string-dispatch ((&rest types) var &body body)
142   (let ((fun (sb!xc:gensym "STRING-DISPATCH-FUN")))
143     `(flet ((,fun (,var)
144               ,@body))
145        (declare (inline ,fun))
146        (etypecase ,var
147          ,@(loop for type in types
148                  ;; TRULY-THE allows transforms to take advantage of the type
149                  ;; information without need for constraint propagation.
150                  collect `(,type (,fun (truly-the ,type ,var))))))))
151
152 ;;; Automate an idiom often found in macros:
153 ;;;   (LET ((FOO (GENSYM "FOO"))
154 ;;;         (MAX-INDEX (GENSYM "MAX-INDEX-")))
155 ;;;     ...)
156 ;;;
157 ;;; "Good notation eliminates thought." -- Eric Siggia
158 ;;;
159 ;;; Incidentally, this is essentially the same operator which
160 ;;; _On Lisp_ calls WITH-GENSYMS.
161 (defmacro with-unique-names (symbols &body body)
162   `(let ,(mapcar (lambda (symbol)
163                    (let* ((symbol-name (symbol-name symbol))
164                           (stem (if (every #'alpha-char-p symbol-name)
165                                     symbol-name
166                                     (concatenate 'string symbol-name "-"))))
167                      `(,symbol (block-gensym ,stem))))
168                  symbols)
169      ,@body))
170
171 ;;; Return a list of N gensyms. (This is a common suboperation in
172 ;;; macros and other code-manipulating code.)
173 (declaim (ftype (function (index &optional t) (values list &optional))
174                 make-gensym-list))
175 (defun make-gensym-list (n &optional name)
176   (case name
177     ((t)
178      (loop repeat n collect (gensym)))
179     ((nil)
180      (loop repeat n collect (block-gensym)))
181     (otherwise
182      (loop repeat n collect (gensym name)))))
183 \f
184 ;;;; miscellany
185
186 ;;; Lots of code wants to get to the KEYWORD package or the
187 ;;; COMMON-LISP package without a lot of fuss, so we cache them in
188 ;;; variables. TO DO: How much does this actually buy us? It sounds
189 ;;; sensible, but I don't know for sure that it saves space or time..
190 ;;; -- WHN 19990521
191 ;;;
192 ;;; (The initialization forms here only matter on the cross-compilation
193 ;;; host; In the target SBCL, these variables are set in cold init.)
194 (declaim (type package *cl-package* *keyword-package*))
195 (defvar *cl-package*      (find-package "COMMON-LISP"))
196 (defvar *keyword-package* (find-package "KEYWORD"))
197
198 ;;; Concatenate together the names of some strings and symbols,
199 ;;; producing a symbol in the current package.
200 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
201   (defun symbolicate (&rest things)
202     (let* ((length (reduce #'+ things
203                            :key (lambda (x) (length (string x)))))
204            (name (make-array length :element-type 'character)))
205       (let ((index 0))
206         (dolist (thing things (values (intern name)))
207           (let* ((x (string thing))
208                  (len (length x)))
209             (replace name x :start1 index)
210             (incf index len)))))))
211
212 (defun gensymify (x)
213   (if (symbolp x)
214       (sb!xc:gensym (symbol-name x))
215       (sb!xc:gensym)))
216
217 ;;; like SYMBOLICATE, but producing keywords
218 (defun keywordicate (&rest things)
219   (let ((*package* *keyword-package*))
220     (apply #'symbolicate things)))
221
222 ;;; Access *PACKAGE* in a way which lets us recover when someone has
223 ;;; done something silly like (SETF *PACKAGE* :CL-USER). (Such an
224 ;;; assignment is undefined behavior, so it's sort of reasonable for
225 ;;; it to cause the system to go totally insane afterwards, but it's a
226 ;;; fairly easy mistake to make, so let's try to recover gracefully
227 ;;; instead.)
228 (defun sane-package ()
229   (let ((maybe-package *package*))
230     (cond ((and (packagep maybe-package)
231                 ;; For good measure, we also catch the problem of
232                 ;; *PACKAGE* being bound to a deleted package.
233                 ;; Technically, this is not undefined behavior in itself,
234                 ;; but it will immediately lead to undefined to behavior,
235                 ;; since almost any operation on a deleted package is
236                 ;; undefined.
237                 (package-name maybe-package))
238            maybe-package)
239           (t
240            ;; We're in the undefined behavior zone. First, munge the
241            ;; system back into a defined state.
242            (let ((really-package (find-package :cl-user)))
243              (setf *package* really-package)
244              ;; Then complain.
245              (error 'simple-type-error
246                     :datum maybe-package
247                     :expected-type '(and package (satisfies package-name))
248                     :format-control
249                     "~@<~S can't be a ~A: ~2I~_~S has been reset to ~S.~:>"
250                     :format-arguments (list '*package*
251                                             (if (packagep maybe-package)
252                                                 "deleted package"
253                                                 (type-of maybe-package))
254                                             '*package* really-package)))))))
255
256 ;;; Access *DEFAULT-PATHNAME-DEFAULTS*, issuing a warning if its value
257 ;;; is silly. (Unlike the vaguely-analogous SANE-PACKAGE, we don't
258 ;;; actually need to reset the variable when it's silly, since even
259 ;;; crazy values of *DEFAULT-PATHNAME-DEFAULTS* don't leave the system
260 ;;; in a state where it's hard to recover interactively.)
261 (defun sane-default-pathname-defaults ()
262   (let* ((dfd *default-pathname-defaults*)
263          (dfd-dir (pathname-directory dfd)))
264     ;; It's generally not good to use a relative pathname for
265     ;; *DEFAULT-PATHNAME-DEFAULTS*, since relative pathnames
266     ;; are defined by merging into a default pathname (which is,
267     ;; by default, *DEFAULT-PATHNAME-DEFAULTS*).
268     (when (and (consp dfd-dir)
269                (eql (first dfd-dir) :relative))
270       (warn
271        "~@<~S is a relative pathname. (But we'll try using it anyway.)~@:>"
272        '*default-pathname-defaults*))
273     dfd))
274
275 ;;; Give names to elements of a numeric sequence.
276 (defmacro defenum ((&key (start 0) (step 1))
277                    &rest identifiers)
278   (let ((results nil)
279         (index 0)
280         (start (eval start))
281         (step (eval step)))
282     (dolist (id identifiers)
283       (when id
284         (multiple-value-bind (sym docs)
285             (if (consp id)
286                 (values (car id) (cdr id))
287                 (values id nil))
288           (push `(def!constant ,sym
289                    ,(+ start (* step index))
290                    ,@docs)
291                 results)))
292       (incf index))
293     `(progn
294        ,@(nreverse results))))
295
296 ;;; generalization of DEFCONSTANT to values which are the same not
297 ;;; under EQL but under e.g. EQUAL or EQUALP
298 ;;;
299 ;;; DEFCONSTANT-EQX is to be used instead of DEFCONSTANT for values
300 ;;; which are appropriately compared using the function given by the
301 ;;; EQX argument instead of EQL.
302 ;;;
303 ;;; Note: Be careful when using this macro, since it's easy to
304 ;;; unintentionally pessimize your code. A good time to use this macro
305 ;;; is when the values defined will be fed into optimization
306 ;;; transforms and never actually appear in the generated code; this
307 ;;; is especially common when defining BYTE expressions. Unintentional
308 ;;; pessimization can result when the values defined by this macro are
309 ;;; actually used in generated code: because of the way that the
310 ;;; dump/load system works, you'll typically get one copy of consed
311 ;;; structure for each object file which contains code referring to
312 ;;; the value, plus perhaps one more copy bound to the SYMBOL-VALUE of
313 ;;; the constant. If you don't want that to happen, you should
314 ;;; probably use DEFPARAMETER instead; or if you truly desperately
315 ;;; need to avoid runtime indirection through a symbol, you might be
316 ;;; able to do something with LOAD-TIME-VALUE or MAKE-LOAD-FORM.
317 (defmacro defconstant-eqx (symbol expr eqx &optional doc)
318   `(def!constant ,symbol
319      (%defconstant-eqx-value ',symbol ,expr ,eqx)
320      ,@(when doc (list doc))))
321 (defun %defconstant-eqx-value (symbol expr eqx)
322   (declare (type function eqx))
323   (flet ((bummer (explanation)
324            (error "~@<bad DEFCONSTANT-EQX ~S ~2I~_~S: ~2I~_~A ~S~:>"
325                   symbol
326                   expr
327                   explanation
328                   (symbol-value symbol))))
329     (cond ((not (boundp symbol))
330            expr)
331           ((not (constantp symbol))
332            (bummer "already bound as a non-constant"))
333           ((not (funcall eqx (symbol-value symbol) expr))
334            (bummer "already bound as a different constant value"))
335           (t
336            (symbol-value symbol)))))
337 \f
338 ;;; a helper function for various macros which expect clauses of a
339 ;;; given length, etc.
340 ;;;
341 ;;; Return true if X is a proper list whose length is between MIN and
342 ;;; MAX (inclusive).
343 (defun proper-list-of-length-p (x min &optional (max min))
344   ;; FIXME: This implementation will hang on circular list
345   ;; structure. Since this is an error-checking utility, i.e. its
346   ;; job is to deal with screwed-up input, it'd be good style to fix
347   ;; it so that it can deal with circular list structure.
348   (cond ((minusp max) nil)
349         ((null x) (zerop min))
350         ((consp x)
351          (and (plusp max)
352               (proper-list-of-length-p (cdr x)
353                                        (if (plusp (1- min))
354                                            (1- min)
355                                            0)
356                                        (1- max))))
357         (t nil)))
358
359 ;;; Helpers for defining error-signalling NOP's for "not supported
360 ;;; here" operations.
361 (defmacro define-unsupported-fun (name &optional
362                                   (doc "Unsupported on this platform.")
363                                   (control
364                                    "~S is unsupported on this platform ~
365                                     (OS, CPU, whatever)."
366                                    controlp)
367                                   arguments)
368   `(defun ,name (&rest args)
369     ,doc
370     (declare (ignore args))
371     (error 'unsupported-operator
372      :format-control ,control
373      :format-arguments (if ,controlp ',arguments (list ',name)))))