c9ff756b6be27f9a53015e9984a49cb3a4c380c8
[sbcl.git] / src / code / target-package.lisp
1 ;;;; PACKAGEs and stuff like that
2 ;;;;
3 ;;;; Note: The code in this file signals many correctable errors. This
4 ;;;; is not just an arbitrary aesthetic decision on the part of the
5 ;;;; implementor -- many of these are specified by ANSI 11.1.1.2.5,
6 ;;;; "Prevention of Name Conflicts in Packages":
7 ;;;;   Within one package, any particular name can refer to at most one
8 ;;;;   symbol. A name conflict is said to occur when there would be more
9 ;;;;   than one candidate symbol. Any time a name conflict is about to
10 ;;;;   occur, a correctable error is signaled.
11 ;;;;
12 ;;;; FIXME: The code contains a lot of type declarations. Are they
13 ;;;; all really necessary?
14
15 ;;;; This software is part of the SBCL system. See the README file for
16 ;;;; more information.
17 ;;;;
18 ;;;; This software is derived from the CMU CL system, which was
19 ;;;; written at Carnegie Mellon University and released into the
20 ;;;; public domain. The software is in the public domain and is
21 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
22 ;;;; files for more information.
23
24 (in-package "SB!IMPL")
25
26 (!begin-collecting-cold-init-forms)
27
28 (!cold-init-forms
29   (/show0 "entering !PACKAGE-COLD-INIT"))
30 \f
31 ;;;; PACKAGE-HASHTABLE stuff
32
33 (def!method print-object ((table package-hashtable) stream)
34   (declare (type stream stream))
35   (print-unreadable-object (table stream :type t)
36     (format stream
37             ":SIZE ~S :FREE ~S :DELETED ~S"
38             (package-hashtable-size table)
39             (package-hashtable-free table)
40             (package-hashtable-deleted table))))
41
42 ;;; the maximum density we allow in a package hashtable
43 (defconstant package-rehash-threshold 0.75)
44
45 ;;; Make a package hashtable having a prime number of entries at least
46 ;;; as great as (/ SIZE PACKAGE-REHASH-THRESHOLD). If RES is supplied,
47 ;;; then it is destructively modified to produce the result. This is
48 ;;; useful when changing the size, since there are many pointers to
49 ;;; the hashtable.
50 (defun make-or-remake-package-hashtable (size
51                                          &optional
52                                          res)
53   (flet ((actual-package-hashtable-size (size)
54            (loop for n of-type fixnum
55               from (logior (truncate size package-rehash-threshold) 1)
56               by 2
57               when (positive-primep n) return n)))
58     (let* ((n (actual-package-hashtable-size size))
59            (size (truncate (* n package-rehash-threshold)))
60            (table (make-array n))
61            (hash (make-array n
62                              :element-type '(unsigned-byte 8)
63                              :initial-element 0)))
64       (if res
65           (setf (package-hashtable-table res) table
66                 (package-hashtable-hash res) hash
67                 (package-hashtable-size res) size
68                 (package-hashtable-free res) size
69                 (package-hashtable-deleted res) 0)
70           (setf res (%make-package-hashtable table hash size)))
71       res)))
72 \f
73 ;;;; package locking operations, built conditionally on :sb-package-locks
74
75 #!+sb-package-locks
76 (progn
77 (defun package-locked-p (package)
78   #!+sb-doc
79   "Returns T when PACKAGE is locked, NIL otherwise. Signals an error
80 if PACKAGE doesn't designate a valid package."
81   (package-lock (find-undeleted-package-or-lose package)))
82
83 (defun lock-package (package)
84   #!+sb-doc
85   "Locks PACKAGE and returns T. Has no effect if PACKAGE was already
86 locked. Signals an error if PACKAGE is not a valid package designator"
87   (setf (package-lock (find-undeleted-package-or-lose package)) t))
88
89 (defun unlock-package (package)
90   #!+sb-doc
91   "Unlocks PACKAGE and returns T. Has no effect if PACKAGE was already
92 unlocked. Signals an error if PACKAGE is not a valid package designator."
93   (setf (package-lock (find-undeleted-package-or-lose package)) nil)
94   t)
95
96 (defun package-implemented-by-list (package)
97   #!+sb-doc
98   "Returns a list containing the implementation packages of
99 PACKAGE. Signals an error if PACKAGE is not a valid package designator."
100   (package-%implementation-packages (find-undeleted-package-or-lose package)))
101
102 (defun package-implements-list (package)
103   #!+sb-doc
104   "Returns the packages that PACKAGE is an implementation package
105 of. Signals an error if PACKAGE is not a valid package designator."
106   (let ((package (find-undeleted-package-or-lose package)))
107     (loop for x in (list-all-packages)
108           when (member package (package-%implementation-packages x))
109           collect x)))
110
111 (defun add-implementation-package (packages-to-add
112                                    &optional (package *package*))
113   #!+sb-doc
114   "Adds PACKAGES-TO-ADD as implementation packages of PACKAGE. Signals
115 an error if PACKAGE or any of the PACKAGES-TO-ADD is not a valid
116 package designator."
117   (let ((package (find-undeleted-package-or-lose package))
118         (packages-to-add (package-listify packages-to-add)))
119     (setf (package-%implementation-packages package)
120           (union (package-%implementation-packages package)
121                  (mapcar #'find-undeleted-package-or-lose packages-to-add)))))
122
123 (defun remove-implementation-package (packages-to-remove
124                                       &optional (package *package*))
125   #!+sb-doc
126   "Removes PACKAGES-TO-REMOVE from the implementation packages of
127 PACKAGE. Signals an error if PACKAGE or any of the PACKAGES-TO-REMOVE
128 is not a valid package designator."
129   (let ((package (find-undeleted-package-or-lose package))
130         (packages-to-remove (package-listify packages-to-remove)))
131     (setf (package-%implementation-packages package)
132           (nset-difference
133            (package-%implementation-packages package)
134            (mapcar #'find-undeleted-package-or-lose packages-to-remove)))))
135
136 (defmacro with-unlocked-packages ((&rest packages) &body forms)
137   #!+sb-doc
138   "Unlocks PACKAGES for the dynamic scope of the body. Signals an
139 error if any of PACKAGES is not a valid package designator."
140   (with-unique-names (unlocked-packages)
141     `(let (,unlocked-packages)
142       (unwind-protect
143            (progn
144              (dolist (p ',packages)
145                (when (package-locked-p p)
146                  (push p ,unlocked-packages)
147                  (unlock-package p)))
148              ,@forms)
149         (dolist (p ,unlocked-packages)
150           (when (find-package p)
151             (lock-package p)))))))
152
153 (defun package-lock-violation (package &key (symbol nil symbol-p)
154                                format-control format-arguments)
155   (let* ((restart :continue)
156          (cl-violation-p (eq package *cl-package*))
157          (error-arguments
158           (append (list (if symbol-p
159                             'symbol-package-locked-error
160                             'package-locked-error)
161                         :package package
162                         :format-control format-control
163                         :format-arguments format-arguments)
164                   (when symbol-p (list :symbol symbol))
165                   (list :references
166                         (append '((:sbcl :node "Package Locks"))
167                                 (when cl-violation-p
168                                   '((:ansi-cl :section (11 1 2 1 2)))))))))
169     (restart-case
170         (apply #'cerror "Ignore the package lock." error-arguments)
171       (:ignore-all ()
172         :report "Ignore all package locks in the context of this operation."
173         (setf restart :ignore-all))
174       (:unlock-package ()
175         :report "Unlock the package."
176         (setf restart :unlock-package)))
177     (ecase restart
178       (:continue
179        (pushnew package *ignored-package-locks*))
180       (:ignore-all
181        (setf *ignored-package-locks* t))
182       (:unlock-package
183        (unlock-package package)))))
184
185 (defun package-lock-violation-p (package &optional (symbol nil symbolp))
186   ;; KLUDGE: (package-lock package) needs to be before
187   ;; comparison to *package*, since during cold init this gets
188   ;; called before *package* is bound -- but no package should
189   ;; be locked at that point.
190   (and package
191        (package-lock package)
192        ;; In package or implementation package
193        (not (or (eq package *package*)
194                 (member *package* (package-%implementation-packages package))))
195        ;; Runtime disabling
196        (not (eq t *ignored-package-locks*))
197        (or (eq :invalid *ignored-package-locks*)
198            (not (member package *ignored-package-locks*)))
199        ;; declarations for symbols
200        (not (and symbolp (member symbol (disabled-package-locks))))))
201
202 (defun disabled-package-locks ()
203   (if (boundp 'sb!c::*lexenv*)
204       (sb!c::lexenv-disabled-package-locks sb!c::*lexenv*)
205       sb!c::*disabled-package-locks*))
206
207 ) ; progn
208
209 ;;;; more package-locking these are NOPs unless :sb-package-locks is
210 ;;;; in target features. Cross-compiler NOPs for these are in cross-misc.
211
212 ;;; The right way to establish a package lock context is
213 ;;; WITH-SINGLE-PACKAGE-LOCKED-ERROR, defined in early-package.lisp
214 ;;;
215 ;;; Must be used inside the dynamic contour established by
216 ;;; WITH-SINGLE-PACKAGE-LOCKED-ERROR
217 (defun assert-package-unlocked (package &optional format-control
218                                 &rest format-arguments)
219   #!-sb-package-locks
220   (declare (ignore format-control format-arguments))
221   #!+sb-package-locks
222   (when (package-lock-violation-p package)
223     (package-lock-violation package
224                             :format-control format-control
225                             :format-arguments format-arguments))
226   package)
227
228 ;;; Must be used inside the dynamic contour established by
229 ;;; WITH-SINGLE-PACKAGE-LOCKED-ERROR.
230 ;;;
231 ;;; FIXME: Maybe we should establish such contours for he toplevel
232 ;;; and others, so that %set-fdefinition and others could just use
233 ;;; this.
234 (defun assert-symbol-home-package-unlocked (name format)
235   #!-sb-package-locks
236   (declare (ignore format))
237   #!+sb-package-locks
238   (let* ((symbol (etypecase name
239                    (symbol name)
240                    (list (if (and (consp (cdr name))
241                                   (eq 'setf (first name)))
242                              (second name)
243                              ;; Skip lists of length 1, single conses and
244                              ;; (class-predicate foo), etc.
245                              ;; FIXME: MOP and package-lock
246                              ;; interaction needs to be thought about.
247                              (return-from
248                               assert-symbol-home-package-unlocked
249                                name)))))
250          (package (symbol-package symbol)))
251     (when (package-lock-violation-p package symbol)
252       (package-lock-violation package
253                               :symbol symbol
254                               :format-control format
255                               :format-arguments (list name))))
256   name)
257
258 \f
259 ;;;; miscellaneous PACKAGE operations
260
261 (def!method print-object ((package package) stream)
262   (let ((name (package-%name package)))
263     (if name
264         (print-unreadable-object (package stream :type t)
265           (prin1 name stream))
266         (print-unreadable-object (package stream :type t :identity t)
267           (write-string "(deleted)" stream)))))
268
269 ;;; ANSI says (in the definition of DELETE-PACKAGE) that these, and
270 ;;; most other operations, are unspecified for deleted packages. We
271 ;;; just do the easy thing and signal errors in that case.
272 (macrolet ((def (ext real)
273              `(defun ,ext (x) (,real (find-undeleted-package-or-lose x)))))
274   (def package-nicknames package-%nicknames)
275   (def package-use-list package-%use-list)
276   (def package-used-by-list package-%used-by-list)
277   (def package-shadowing-symbols package-%shadowing-symbols))
278
279 (defun %package-hashtable-symbol-count (table)
280   (let ((size (the fixnum
281                 (- (package-hashtable-size table)
282                    (package-hashtable-deleted table)))))
283     (the fixnum
284       (- size (package-hashtable-free table)))))
285
286 (defun package-internal-symbol-count (package)
287   (%package-hashtable-symbol-count (package-internal-symbols package)))
288
289 (defun package-external-symbol-count (package)
290   (%package-hashtable-symbol-count (package-external-symbols package)))
291 \f
292 (defvar *package* (error "*PACKAGE* should be initialized in cold load!")
293   #!+sb-doc "the current package")
294 ;;; FIXME: should be declared of type PACKAGE, with no NIL init form,
295 ;;; after I get around to cleaning up DOCUMENTATION
296
297 ;;; a map from package names to packages
298 (defvar *package-names*)
299 (declaim (type hash-table *package-names*))
300 (!cold-init-forms
301   (setf *package-names* (make-hash-table :test 'equal)))
302
303 ;;; This magical variable is T during initialization so that
304 ;;; USE-PACKAGE's of packages that don't yet exist quietly win. Such
305 ;;; packages are thrown onto the list *DEFERRED-USE-PACKAGES* so that
306 ;;; this can be fixed up later.
307 ;;;
308 ;;; FIXME: This could be cleaned up the same way I do it in my package
309 ;;; hacking when setting up the cross-compiler. Then we wouldn't have
310 ;;; this extraneous global variable and annoying runtime tests on
311 ;;; package operations. (*DEFERRED-USE-PACKAGES* would also go away.)
312 (defvar *in-package-init*)
313
314 ;;; pending USE-PACKAGE arguments saved up while *IN-PACKAGE-INIT* is true
315 (defvar *!deferred-use-packages*)
316 (!cold-init-forms
317   (setf *!deferred-use-packages* nil))
318
319 (define-condition bootstrap-package-not-found (condition)
320   ((name :initarg :name :reader bootstrap-package-name)))
321 (defun debootstrap-package (&optional condition)
322   (invoke-restart
323    (find-restart-or-control-error 'debootstrap-package condition)))
324
325 (defun find-package (package-designator)
326   (flet ((find-package-from-string (string)
327            (declare (type string string))
328            (let ((packageoid (gethash string *package-names*)))
329              (when (and (null packageoid)
330                         (not *in-package-init*) ; KLUDGE
331                         (let ((mismatch (mismatch "SB!" string)))
332                           (and mismatch (= mismatch 3))))
333                (restart-case
334                    (signal 'bootstrap-package-not-found :name string)
335                  (debootstrap-package ()
336                    (return-from find-package
337                      (if (string= string "SB!XC")
338                          (find-package "COMMON-LISP")
339                          (find-package
340                           (substitute #\- #\! string :count 1)))))))
341              packageoid)))
342     (typecase package-designator
343       (package package-designator)
344       (symbol (find-package-from-string (symbol-name package-designator)))
345       (string (find-package-from-string package-designator))
346       (character (find-package-from-string (string package-designator)))
347       (t (error 'type-error
348                 :datum package-designator
349                 :expected-type '(or character package string symbol))))))
350
351 ;;; Return a list of packages given a package designator or list of
352 ;;; package designators, or die trying.
353 (defun package-listify (thing)
354   (let ((res ()))
355     (dolist (thing (if (listp thing) thing (list thing)) res)
356       (push (find-undeleted-package-or-lose thing) res))))
357
358 ;;; Make a package name into a simple-string.
359 (defun package-namify (n)
360   (stringify-name n "package"))
361
362 ;;; ANSI specifies (in the definition of DELETE-PACKAGE) that PACKAGE-NAME
363 ;;; returns NIL (not an error) for a deleted package, so this is a special
364 ;;; case where we want to use bare %FIND-PACKAGE-OR-LOSE instead of
365 ;;; FIND-UNDELETED-PACKAGE-OR-LOSE.
366 (defun package-name (package-designator)
367   (package-%name (%find-package-or-lose package-designator)))
368 \f
369 ;;;; operations on package hashtables
370
371 ;;; Compute a number from the sxhash of the pname and the length which
372 ;;; must be between 2 and 255.
373 (defmacro entry-hash (length sxhash)
374   `(the fixnum
375         (+ (the fixnum
376                 (rem (the fixnum
377                           (logxor ,length
378                                   ,sxhash
379                                   (the fixnum (ash ,sxhash -8))
380                                   (the fixnum (ash ,sxhash -16))
381                                   (the fixnum (ash ,sxhash -19))))
382                      254))
383            2)))
384 ;;; FIXME: should be wrapped in EVAL-WHEN (COMPILE EXECUTE)
385
386 ;;; Add a symbol to a package hashtable. The symbol is assumed
387 ;;; not to be present.
388 (defun add-symbol (table symbol)
389   (let* ((vec (package-hashtable-table table))
390          (hash (package-hashtable-hash table))
391          (len (length vec))
392          (sxhash (%sxhash-simple-string (symbol-name symbol)))
393          (h2 (the fixnum (1+ (the fixnum (rem sxhash
394                                               (the fixnum (- len 2))))))))
395     (declare (fixnum len sxhash h2))
396     (cond ((zerop (the fixnum (package-hashtable-free table)))
397            (make-or-remake-package-hashtable (* (package-hashtable-size table)
398                                                 2)
399                                              table)
400            (add-symbol table symbol)
401            (dotimes (i len)
402              (declare (fixnum i))
403              (when (> (the fixnum (aref hash i)) 1)
404                (add-symbol table (svref vec i)))))
405           (t
406            (do ((i (rem sxhash len) (rem (+ i h2) len)))
407                ((< (the fixnum (aref hash i)) 2)
408                 (if (zerop (the fixnum (aref hash i)))
409                     (decf (package-hashtable-free table))
410                     (decf (package-hashtable-deleted table)))
411                 (setf (svref vec i) symbol)
412                 (setf (aref hash i)
413                       (entry-hash (length (symbol-name symbol))
414                                   sxhash)))
415              (declare (fixnum i)))))))
416
417 ;;; Find where the symbol named STRING is stored in TABLE. INDEX-VAR
418 ;;; is bound to the index, or NIL if it is not present. SYMBOL-VAR
419 ;;; is bound to the symbol. LENGTH and HASH are the length and sxhash
420 ;;; of STRING. ENTRY-HASH is the entry-hash of the string and length.
421 (defmacro with-symbol ((index-var symbol-var table string length sxhash
422                                   entry-hash)
423                        &body forms)
424   (let ((vec (gensym)) (hash (gensym)) (len (gensym)) (h2 (gensym))
425         (name (gensym)) (name-len (gensym)) (ehash (gensym)))
426     `(let* ((,vec (package-hashtable-table ,table))
427             (,hash (package-hashtable-hash ,table))
428             (,len (length ,vec))
429             (,h2 (1+ (the index (rem (the index ,sxhash)
430                                       (the index (- ,len 2)))))))
431        (declare (type index ,len ,h2))
432        (prog ((,index-var (rem (the index ,sxhash) ,len))
433               ,symbol-var ,ehash)
434          (declare (type (or index null) ,index-var))
435          LOOP
436          (setq ,ehash (aref ,hash ,index-var))
437          (cond ((eql ,ehash ,entry-hash)
438                 (setq ,symbol-var (svref ,vec ,index-var))
439                 (let* ((,name (symbol-name ,symbol-var))
440                        (,name-len (length ,name)))
441                   (declare (type index ,name-len))
442                   (when (and (= ,name-len ,length)
443                              (string= ,string ,name
444                                       :end1 ,length
445                                       :end2 ,name-len))
446                     (go DOIT))))
447                ((zerop ,ehash)
448                 (setq ,index-var nil)
449                 (go DOIT)))
450          (setq ,index-var (+ ,index-var ,h2))
451          (when (>= ,index-var ,len)
452            (setq ,index-var (- ,index-var ,len)))
453          (go LOOP)
454          DOIT
455          (return (progn ,@forms))))))
456
457 ;;; Delete the entry for STRING in TABLE. The entry must exist.
458 (defun nuke-symbol (table string)
459   (declare (simple-string string))
460   (let* ((length (length string))
461          (hash (%sxhash-simple-string string))
462          (ehash (entry-hash length hash)))
463     (declare (type index length hash))
464     (with-symbol (index symbol table string length hash ehash)
465       (setf (aref (package-hashtable-hash table) index) 1)
466       (setf (aref (package-hashtable-table table) index) nil)
467       (incf (package-hashtable-deleted table)))))
468 \f
469 ;;; Enter any new NICKNAMES for PACKAGE into *PACKAGE-NAMES*.
470 ;;; If there is a conflict then give the user a chance to do
471 ;;; something about it.
472 (defun enter-new-nicknames (package nicknames)
473   (declare (type list nicknames))
474   (dolist (n nicknames)
475     (let* ((n (package-namify n))
476            (found (gethash n *package-names*)))
477       (cond ((not found)
478              (setf (gethash n *package-names*) package)
479              (push n (package-%nicknames package)))
480             ((eq found package))
481             ((string= (the string (package-%name found)) n)
482              (cerror "Ignore this nickname."
483                      'simple-package-error
484                      :package package
485                      :format-control "~S is a package name, so it cannot be a nickname for ~S."
486                      :format-arguments (list n (package-%name package))))
487             (t
488              (cerror "Leave this nickname alone."
489                      'simple-package-error
490                      :package package
491                      :format-control "~S is already a nickname for ~S."
492                      :format-arguments (list n (package-%name found))))))))
493
494 (defun make-package (name &key
495                           (use '#.*default-package-use-list*)
496                           nicknames
497                           (internal-symbols 10)
498                           (external-symbols 10))
499   #!+sb-doc
500   #.(format nil
501      "Make a new package having the specified NAME, NICKNAMES, and
502   USE list. :INTERNAL-SYMBOLS and :EXTERNAL-SYMBOLS are
503   estimates for the number of internal and external symbols which
504   will ultimately be present in the package. The default value of
505   USE is implementation-dependent, and in this implementation
506   it is ~S."
507      *default-package-use-list*)
508
509   ;; Check for package name conflicts in name and nicknames, then
510   ;; make the package.
511   (when (find-package name)
512     ;; ANSI specifies that this error is correctable.
513     (cerror "Leave existing package alone."
514             "A package named ~S already exists" name))
515   (let* ((name (package-namify name))
516          (package (internal-make-package
517                    :%name name
518                    :internal-symbols (make-or-remake-package-hashtable
519                                       internal-symbols)
520                    :external-symbols (make-or-remake-package-hashtable
521                                       external-symbols))))
522
523     ;; Do a USE-PACKAGE for each thing in the USE list so that checking for
524     ;; conflicting exports among used packages is done.
525     (if *in-package-init*
526         (push (list use package) *!deferred-use-packages*)
527         (use-package use package))
528
529     ;; FIXME: ENTER-NEW-NICKNAMES can fail (ERROR) if nicknames are illegal,
530     ;; which would leave us with possibly-bad side effects from the earlier
531     ;; USE-PACKAGE (e.g. this package on the used-by lists of other packages,
532     ;; but not in *PACKAGE-NAMES*, and possibly import side effects too?).
533     ;; Perhaps this can be solved by just moving ENTER-NEW-NICKNAMES before
534     ;; USE-PACKAGE, but I need to check what kinds of errors can be caused by
535     ;; USE-PACKAGE, too.
536     (enter-new-nicknames package nicknames)
537     (setf (gethash name *package-names*) package)))
538
539 ;;; Change the name if we can, blast any old nicknames and then
540 ;;; add in any new ones.
541 ;;;
542 ;;; FIXME: ANSI claims that NAME is a package designator (not just a
543 ;;; string designator -- weird). Thus, NAME could
544 ;;; be a package instead of a string. Presumably then we should not change
545 ;;; the package name if NAME is the same package that's referred to by PACKAGE.
546 ;;; If it's a *different* package, we should probably signal an error.
547 ;;; (perhaps (ERROR 'ANSI-WEIRDNESS ..):-)
548 (defun rename-package (package name &optional (nicknames ()))
549   #!+sb-doc
550   "Changes the name and nicknames for a package."
551   (let* ((package (find-undeleted-package-or-lose package))
552          (name (package-namify name))
553          (found (find-package name))
554          (nicks (mapcar #'string nicknames)))
555     (unless (or (not found) (eq found package))
556       (error 'simple-package-error
557              :package name
558              :format-control "A package named ~S already exists."
559              :format-arguments (list name)))
560     (with-single-package-locked-error ()
561         (unless (and (string= name (package-name package))
562                      (null (set-difference nicks (package-nicknames package)
563                                        :test #'string=)))
564           (assert-package-unlocked package "rename as ~A~@[ with nickname~P ~
565                                            ~{~A~^, ~}~]"
566                                    name (length nicks) nicks))
567       ;; do the renaming
568       (remhash (package-%name package) *package-names*)
569       (dolist (n (package-%nicknames package))
570         (remhash n *package-names*))
571       (setf (package-%name package) name
572             (gethash name *package-names*) package
573             (package-%nicknames package) ())
574       (enter-new-nicknames package nicknames))
575     package))
576
577 (defun delete-package (package-designator)
578   #!+sb-doc
579   "Delete the package designated by PACKAGE-DESIGNATOR from the package
580   system data structures."
581   (let ((package (if (packagep package-designator)
582                      package-designator
583                      (find-package package-designator))))
584     (cond ((not package)
585            ;; This continuable error is required by ANSI.
586            (cerror
587             "Return ~S."
588             (make-condition
589              'simple-package-error
590              :package package-designator
591              :format-control "There is no package named ~S."
592              :format-arguments (list package-designator))
593             nil))
594           ((not (package-name package)) ; already deleted
595            nil)
596           (t
597            (with-single-package-locked-error
598                (:package package "deleting package ~A" package)
599              (let ((use-list (package-used-by-list package)))
600                (when use-list
601                  ;; This continuable error is specified by ANSI.
602                  (cerror
603                   "Remove dependency in other packages."
604                   (make-condition
605                    'simple-package-error
606                    :package package
607                    :format-control
608                    "~@<Package ~S is used by package~P:~2I~_~S~@:>"
609                    :format-arguments (list (package-name package)
610                                            (length use-list)
611                                            (mapcar #'package-name use-list))))
612                  (dolist (p use-list)
613                    (unuse-package package p))))
614              (dolist (used (package-use-list package))
615                (unuse-package used package))
616              (do-symbols (sym package)
617                (unintern sym package))
618              (remhash (package-name package) *package-names*)
619              (dolist (nick (package-nicknames package))
620                (remhash nick *package-names*))
621              (setf (package-%name package) nil
622                    ;; Setting PACKAGE-%NAME to NIL is required in order to
623                    ;; make PACKAGE-NAME return NIL for a deleted package as
624                    ;; ANSI requires. Setting the other slots to NIL
625                    ;; and blowing away the PACKAGE-HASHTABLES is just done
626                    ;; for tidiness and to help the GC.
627                    (package-%nicknames package) nil
628                    (package-%use-list package) nil
629                    (package-tables package) nil
630                    (package-%shadowing-symbols package) nil
631                    (package-internal-symbols package)
632                    (make-or-remake-package-hashtable 0)
633                    (package-external-symbols package)
634                    (make-or-remake-package-hashtable 0))
635              t)))))
636
637 (defun list-all-packages ()
638   #!+sb-doc
639   "Return a list of all existing packages."
640   (let ((res ()))
641     (maphash (lambda (k v)
642                (declare (ignore k))
643                (pushnew v res))
644              *package-names*)
645     res))
646 \f
647 (defun intern (name &optional (package (sane-package)))
648   #!+sb-doc
649   "Return a symbol in PACKAGE having the specified NAME, creating it
650   if necessary."
651   ;; We just simple-stringify the name and call INTERN*, where the real
652   ;; logic is.
653   (let ((name (if (simple-string-p name)
654                   name
655                   (coerce name 'simple-string)))
656         (package (find-undeleted-package-or-lose package)))
657     (declare (simple-string name))
658       (intern* name
659                (length name)
660                package)))
661
662 (defun find-symbol (name &optional (package (sane-package)))
663   #!+sb-doc
664   "Return the symbol named STRING in PACKAGE. If such a symbol is found
665   then the second value is :INTERNAL, :EXTERNAL or :INHERITED to indicate
666   how the symbol is accessible. If no symbol is found then both values
667   are NIL."
668   ;; We just simple-stringify the name and call FIND-SYMBOL*, where the
669   ;; real logic is.
670   (let ((name (if (simple-string-p name) name (coerce name 'simple-string))))
671     (declare (simple-string name))
672     (find-symbol* name
673                   (length name)
674                   (find-undeleted-package-or-lose package))))
675
676 ;;; If the symbol named by the first LENGTH characters of NAME doesn't exist,
677 ;;; then create it, special-casing the keyword package.
678 (defun intern* (name length package)
679   (declare (simple-string name))
680   (multiple-value-bind (symbol where) (find-symbol* name length package)
681     (cond (where
682            (values symbol where))
683           (t
684            (let ((symbol-name (subseq name 0 length)))
685              (with-single-package-locked-error
686                  (:package package "interning ~A" symbol-name)
687                (let ((symbol (make-symbol symbol-name)))
688                  (%set-symbol-package symbol package)
689                  (cond ((eq package *keyword-package*)
690                         (add-symbol (package-external-symbols package) symbol)
691                         (%set-symbol-value symbol symbol))
692                        (t
693                         (add-symbol (package-internal-symbols package) symbol)))
694                  (values symbol nil))))))))
695
696 ;;; Check internal and external symbols, then scan down the list
697 ;;; of hashtables for inherited symbols. When an inherited symbol
698 ;;; is found pull that table to the beginning of the list.
699 (defun find-symbol* (string length package)
700   (declare (simple-string string)
701            (type index length))
702   (let* ((hash (%sxhash-simple-substring string length))
703          (ehash (entry-hash length hash)))
704     (declare (type index hash ehash))
705     (with-symbol (found symbol (package-internal-symbols package)
706                         string length hash ehash)
707       (when found
708         (return-from find-symbol* (values symbol :internal))))
709     (with-symbol (found symbol (package-external-symbols package)
710                         string length hash ehash)
711       (when found
712         (return-from find-symbol* (values symbol :external))))
713     (let ((head (package-tables package)))
714       (do ((prev head table)
715            (table (cdr head) (cdr table)))
716           ((null table) (values nil nil))
717         (with-symbol (found symbol (car table) string length hash ehash)
718           (when found
719             (unless (eq prev head)
720               (shiftf (cdr prev) (cdr table) (cdr head) table))
721             (return-from find-symbol* (values symbol :inherited))))))))
722
723 ;;; Similar to FIND-SYMBOL, but only looks for an external symbol.
724 ;;; This is used for fast name-conflict checking in this file and symbol
725 ;;; printing in the printer.
726 (defun find-external-symbol (string package)
727   (declare (simple-string string))
728   (let* ((length (length string))
729          (hash (%sxhash-simple-string string))
730          (ehash (entry-hash length hash)))
731     (declare (type index length hash))
732     (with-symbol (found symbol (package-external-symbols package)
733                         string length hash ehash)
734       (values symbol found))))
735 \f
736 (define-condition name-conflict (reference-condition package-error)
737   ((function :initarg :function :reader name-conflict-function)
738    (datum :initarg :datum :reader name-conflict-datum)
739    (symbols :initarg :symbols :reader name-conflict-symbols))
740   (:default-initargs :references (list '(:ansi-cl :section (11 1 1 2 5))))
741   (:report
742    (lambda (c s)
743      (format s "~@<~S ~S causes name-conflicts in ~S between the ~
744                 following symbols:~2I~@:_~{~S~^, ~}~:@>"
745              (name-conflict-function c)
746              (name-conflict-datum c)
747              (package-error-package c)
748              (name-conflict-symbols c)))))
749
750 (defun name-conflict (package function datum &rest symbols)
751   (restart-case
752       (error 'name-conflict :package package :symbols symbols
753              :function function :datum datum)
754     (resolve-conflict (s)
755       :report "Resolve conflict."
756       :interactive
757       (lambda ()
758         (let* ((len (length symbols))
759                (nlen (length (write-to-string len :base 10)))
760                (*print-pretty* t))
761           (format *query-io* "~&~@<Select a symbol to be made accessible in ~
762                               package ~A:~2I~@:_~{~{~V,' D. ~S~}~@:_~}~@:>"
763                 (package-name package)
764                 (loop for s in symbols
765                       for i upfrom 1
766                       collect (list nlen i s)))
767           (loop
768            (format *query-io* "~&Enter an integer (between 1 and ~D): " len)
769            (finish-output *query-io*)
770            (let ((i (parse-integer (read-line *query-io*) :junk-allowed t)))
771              (when (and i (<= 1 i len))
772                (return (list (nth (1- i) symbols))))))))
773       (multiple-value-bind (symbol status)
774           (find-symbol (symbol-name s) package)
775         (declare (ignore status)) ; FIXME: is that true?
776         (case function
777           ((export)
778            (if (eq symbol s)
779                (shadow symbol package)
780                (unintern symbol package)))
781           ((unintern)
782            (shadowing-import s package))
783           ((import)
784            (if (eq symbol s)
785                nil ; do nothing
786                (shadowing-import s package)))
787           ((use-package)
788            (if (eq symbol s)
789                (shadow s package)
790                (shadowing-import s package))))))))
791
792 #+nil ; this solution gives a variable number of restarts instead, but
793       ; no good way of programmatically choosing between them.
794 (defun name-conflict (package function datum &rest symbols)
795   (let ((condition (make-condition 'name-conflict
796                                    :package package :symbols symbols
797                                    :function function :datum datum)))
798     ;; this is a gross violation of modularity, but I can't see any
799     ;; other way to have a variable number of restarts.
800     (let ((*restart-clusters*
801            (cons
802             (mapcan
803              (lambda (s)
804                (multiple-value-bind (accessible-symbol status)
805                    (find-symbol (symbol-name s) package)
806                  (cond
807                    ;; difficult case
808                    ((eq s accessible-symbol)
809                     (ecase status
810                       ((:inherited)
811                        (list (make-restart
812                               :name (make-symbol "SHADOWING-IMPORT")
813                               :function (lambda ()
814                                           (shadowing-import s package)
815                                           (return-from name-conflict))
816                               :report-function
817                               (lambda (stream)
818                                 (format stream "Shadowing-import ~S into ~A."
819                                         s (package-%name package))))))
820                       ((:internal :external)
821                        (aver (= (length symbols) 2))
822                        ;; ARGH! FIXME: this unintern restart can
823                        ;; _still_ leave the system in an
824                        ;; unsatisfactory state: if the symbol is a
825                        ;; external symbol of a package which is
826                        ;; already used by this package, and has also
827                        ;; been imported, then uninterning it from this
828                        ;; package will still leave it visible!
829                        ;;
830                        ;; (DEFPACKAGE "FOO" (:EXPORT "SYM"))
831                        ;; (DEFPACKAGE "BAR" (:EXPORT "SYM"))
832                        ;; (DEFPACKAGE "BAZ" (:USE "FOO"))
833                        ;; (IMPORT 'FOO:SYM "BAZ")
834                        ;; (USE-PACKAGE "BAR" "BAZ")
835                        ;;
836                        ;; Now (UNINTERN 'FOO:SYM "BAZ") doesn't
837                        ;; resolve the conflict. :-(
838                        ;;
839                        ;; -- CSR, 2004-10-20
840                        (list (make-restart
841                               :name (make-symbol "UNINTERN")
842                               :function (lambda ()
843                                           (unintern s package)
844                                           (import
845                                            (find s symbols :test-not #'eq)
846                                            package)
847                                           (return-from name-conflict))
848                               :report-function
849                               (lambda (stream)
850                                 (format stream
851                                         "Unintern ~S from ~A and import ~S."
852                                         s
853                                         (package-%name package)
854                                         (find s symbols :test-not #'eq))))))))
855                    (t (list (make-restart
856                              :name (make-symbol "SHADOWING-IMPORT")
857                              :function (lambda ()
858                                          (shadowing-import s package)
859                                          (return-from name-conflict))
860                              :report-function
861                              (lambda (stream)
862                                (format stream "Shadowing-import ~S into ~A."
863                                        s (package-%name package)))))))))
864              symbols)
865             *restart-clusters*)))
866       (with-condition-restarts condition (car *restart-clusters*)
867         (with-simple-restart (abort "Leave action undone.")
868           (error condition))))))
869
870 ;;; If we are uninterning a shadowing symbol, then a name conflict can
871 ;;; result, otherwise just nuke the symbol.
872 (defun unintern (symbol &optional (package (sane-package)))
873   #!+sb-doc
874   "Makes SYMBOL no longer present in PACKAGE. If SYMBOL was present
875   then T is returned, otherwise NIL. If PACKAGE is SYMBOL's home
876   package, then it is made uninterned."
877   (let* ((package (find-undeleted-package-or-lose package))
878          (name (symbol-name symbol))
879          (shadowing-symbols (package-%shadowing-symbols package)))
880     (declare (list shadowing-symbols))
881
882     (with-single-package-locked-error ()
883       (when (find-symbol name package)
884         (assert-package-unlocked package "uninterning ~A" name))
885
886       ;; If a name conflict is revealed, give us a chance to
887       ;; shadowing-import one of the accessible symbols.
888       (when (member symbol shadowing-symbols)
889         (let ((cset ()))
890           (dolist (p (package-%use-list package))
891             (multiple-value-bind (s w) (find-external-symbol name p)
892               (when w (pushnew s cset))))
893           (when (cdr cset)
894             (apply #'name-conflict package 'unintern symbol cset)
895             (return-from unintern t)))
896         (setf (package-%shadowing-symbols package)
897               (remove symbol shadowing-symbols)))
898
899       (multiple-value-bind (s w) (find-symbol name package)
900         (declare (ignore s))
901         (cond ((or (eq w :internal) (eq w :external))
902                (nuke-symbol (if (eq w :internal)
903                                 (package-internal-symbols package)
904                                 (package-external-symbols package))
905                             name)
906                (if (eq (symbol-package symbol) package)
907                    (%set-symbol-package symbol nil))
908                t)
909               (t nil))))))
910 \f
911 ;;; Take a symbol-or-list-of-symbols and return a list, checking types.
912 (defun symbol-listify (thing)
913   (cond ((listp thing)
914          (dolist (s thing)
915            (unless (symbolp s) (error "~S is not a symbol." s)))
916          thing)
917         ((symbolp thing) (list thing))
918         (t
919          (error "~S is neither a symbol nor a list of symbols." thing))))
920
921 (defun string-listify (thing)
922   (mapcar #'string (if (listp thing)
923                        thing
924                        (list thing))))
925
926 ;;; This is like UNINTERN, except if SYMBOL is inherited, it chases
927 ;;; down the package it is inherited from and uninterns it there. Used
928 ;;; for name-conflict resolution. Shadowing symbols are not uninterned
929 ;;; since they do not cause conflicts.
930 (defun moby-unintern (symbol package)
931   (unless (member symbol (package-%shadowing-symbols package))
932     (or (unintern symbol package)
933         (let ((name (symbol-name symbol)))
934           (multiple-value-bind (s w) (find-symbol name package)
935             (declare (ignore s))
936             (when (eq w :inherited)
937               (dolist (q (package-%use-list package))
938                 (multiple-value-bind (u x) (find-external-symbol name q)
939                   (declare (ignore u))
940                   (when x
941                     (unintern symbol q)
942                     (return t))))))))))
943 \f
944 (defun export (symbols &optional (package (sane-package)))
945   #!+sb-doc
946   "Exports SYMBOLS from PACKAGE, checking that no name conflicts result."
947   (let ((package (find-undeleted-package-or-lose package))
948         (syms ()))
949     ;; Punt any symbols that are already external.
950     (dolist (sym (symbol-listify symbols))
951       (multiple-value-bind (s w)
952           (find-external-symbol (symbol-name sym) package)
953         (declare (ignore s))
954         (unless (or w (member sym syms))
955           (push sym syms))))
956     (with-single-package-locked-error ()
957       (when syms
958         (assert-package-unlocked package "exporting symbol~P ~{~A~^, ~}"
959                                  (length syms) syms))
960       ;; Find symbols and packages with conflicts.
961       (let ((used-by (package-%used-by-list package))
962             (cset ()))
963         (dolist (sym syms)
964           (let ((name (symbol-name sym)))
965             (dolist (p used-by)
966               (multiple-value-bind (s w) (find-symbol name p)
967                 (when (and w
968                            (not (eq s sym))
969                            (not (member s (package-%shadowing-symbols p))))
970                   ;; Beware: the name conflict is in package P, not in
971                   ;; PACKAGE.
972                   (name-conflict p 'export sym sym s)
973                   (pushnew sym cset))))))
974         (when cset
975           (setq syms (set-difference syms cset))))
976       ;; Check that all symbols are accessible. If not, ask to import them.
977       (let ((missing ())
978             (imports ()))
979         (dolist (sym syms)
980           (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
981             (cond ((not (and w (eq s sym)))
982                    (push sym missing))
983                   ((eq w :inherited)
984                    (push sym imports)))))
985         (when missing
986           (cerror
987            "~S these symbols into the ~A package."
988            (make-condition
989             'simple-package-error
990             :package package
991             :format-control
992             "~@<These symbols are not accessible in the ~A package:~2I~_~S~@:>"
993             :format-arguments (list (package-%name package) missing))
994            'import (package-%name package))
995           (import missing package))
996         (import imports package))
997
998       ;; And now, three pages later, we export the suckers.
999       (let ((internal (package-internal-symbols package))
1000             (external (package-external-symbols package)))
1001         (dolist (sym syms)
1002           (nuke-symbol internal (symbol-name sym))
1003           (add-symbol external sym))))
1004       t))
1005 \f
1006 ;;; Check that all symbols are accessible, then move from external to internal.
1007 (defun unexport (symbols &optional (package (sane-package)))
1008   #!+sb-doc
1009   "Makes SYMBOLS no longer exported from PACKAGE."
1010   (let ((package (find-undeleted-package-or-lose package))
1011         (syms ()))
1012     (dolist (sym (symbol-listify symbols))
1013       (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
1014         (cond ((or (not w) (not (eq s sym)))
1015                (error 'simple-package-error
1016                       :package package
1017                       :format-control "~S is not accessible in the ~A package."
1018                       :format-arguments (list sym (package-%name package))))
1019               ((eq w :external) (pushnew sym syms)))))
1020     (with-single-package-locked-error ()
1021       (when syms
1022         (assert-package-unlocked package "unexporting symbol~P ~{~A~^, ~}"
1023                                  (length syms) syms))
1024       (let ((internal (package-internal-symbols package))
1025             (external (package-external-symbols package)))
1026         (dolist (sym syms)
1027           (add-symbol internal sym)
1028           (nuke-symbol external (symbol-name sym)))))
1029     t))
1030 \f
1031 ;;; Check for name conflict caused by the import and let the user
1032 ;;; shadowing-import if there is.
1033 (defun import (symbols &optional (package (sane-package)))
1034   #!+sb-doc
1035   "Make SYMBOLS accessible as internal symbols in PACKAGE. If a symbol
1036   is already accessible then it has no effect. If a name conflict
1037   would result from the importation, then a correctable error is signalled."
1038   (let* ((package (find-undeleted-package-or-lose package))
1039          (symbols (symbol-listify symbols))
1040          (homeless (remove-if #'symbol-package symbols))
1041          (syms ()))
1042     (with-single-package-locked-error ()
1043       (dolist (sym symbols)
1044         (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
1045           (cond ((not w)
1046                  (let ((found (member sym syms :test #'string=)))
1047                    (if found
1048                        (when (not (eq (car found) sym))
1049                          (name-conflict package 'import sym sym (car found)))
1050                        (push sym syms))))
1051                 ((not (eq s sym))
1052                  (name-conflict package 'import sym sym s))
1053                 ((eq w :inherited) (push sym syms)))))
1054       (when (or homeless syms)
1055         (let ((union (delete-duplicates (append homeless syms))))
1056           (assert-package-unlocked package "importing symbol~P ~{~A~^, ~}"
1057                                    (length union) union)))
1058       ;; Add the new symbols to the internal hashtable.
1059       (let ((internal (package-internal-symbols package)))
1060         (dolist (sym syms)
1061           (add-symbol internal sym)))
1062       ;; If any of the symbols are uninterned, make them be owned by PACKAGE.
1063       (dolist (sym homeless)
1064         (%set-symbol-package sym package))
1065       t)))
1066 \f
1067 ;;; If a conflicting symbol is present, unintern it, otherwise just
1068 ;;; stick the symbol in.
1069 (defun shadowing-import (symbols &optional (package (sane-package)))
1070   #!+sb-doc
1071   "Import SYMBOLS into package, disregarding any name conflict. If
1072   a symbol of the same name is present, then it is uninterned."
1073   (let* ((package (find-undeleted-package-or-lose package))
1074          (internal (package-internal-symbols package))
1075          (symbols (symbol-listify symbols))
1076          (lock-asserted-p nil))
1077     (with-single-package-locked-error ()
1078       (dolist (sym symbols)
1079         (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
1080           (unless (or lock-asserted-p
1081                       (and (eq s sym)
1082                            (member s (package-shadowing-symbols package))))
1083             (assert-package-unlocked package "shadowing-importing symbol~P ~
1084                                            ~{~A~^, ~}" (length symbols) symbols)
1085             (setf lock-asserted-p t))
1086           (unless (and w (not (eq w :inherited)) (eq s sym))
1087             (when (or (eq w :internal) (eq w :external))
1088               ;; If it was shadowed, we don't want UNINTERN to flame out...
1089               (setf (package-%shadowing-symbols package)
1090                     (remove s (the list (package-%shadowing-symbols package))))
1091               (unintern s package))
1092             (add-symbol internal sym))
1093           (pushnew sym (package-%shadowing-symbols package))))))
1094   t)
1095
1096 (defun shadow (symbols &optional (package (sane-package)))
1097   #!+sb-doc
1098   "Make an internal symbol in PACKAGE with the same name as each of
1099   the specified SYMBOLS. If a symbol with the given name is already
1100   present in PACKAGE, then the existing symbol is placed in the
1101   shadowing symbols list if it is not already present."
1102   (let* ((package (find-undeleted-package-or-lose package))
1103          (internal (package-internal-symbols package))
1104          (symbols (string-listify symbols))
1105          (lock-asserted-p nil))
1106     (flet ((present-p (w)
1107              (and w (not (eq w :inherited)))))
1108       (with-single-package-locked-error ()
1109         (dolist (name symbols)
1110           (multiple-value-bind (s w) (find-symbol name package)
1111             (unless (or lock-asserted-p
1112                         (and (present-p w)
1113                              (member s (package-shadowing-symbols package))))
1114               (assert-package-unlocked package "shadowing symbol~P ~{~A~^, ~}"
1115                                        (length symbols) symbols)
1116               (setf lock-asserted-p t))
1117             (unless (present-p w)
1118               (setq s (make-symbol name))
1119               (%set-symbol-package s package)
1120               (add-symbol internal s))
1121             (pushnew s (package-%shadowing-symbols package)))))))
1122   t)
1123 \f
1124 ;;; Do stuff to use a package, with all kinds of fun name-conflict checking.
1125 (defun use-package (packages-to-use &optional (package (sane-package)))
1126   #!+sb-doc
1127   "Add all the PACKAGES-TO-USE to the use list for PACKAGE so that
1128   the external symbols of the used packages are accessible as internal
1129   symbols in PACKAGE."
1130   (let ((packages (package-listify packages-to-use))
1131         (package (find-undeleted-package-or-lose package)))
1132
1133     ;; Loop over each package, USE'ing one at a time...
1134     (with-single-package-locked-error ()
1135       (dolist (pkg packages)
1136         (unless (member pkg (package-%use-list package))
1137           (assert-package-unlocked package "using package~P ~{~A~^, ~}"
1138                                    (length packages) packages)
1139           (let ((shadowing-symbols (package-%shadowing-symbols package))
1140                 (use-list (package-%use-list package)))
1141
1142             ;; If the number of symbols already accessible is less
1143             ;; than the number to be inherited then it is faster to
1144             ;; run the test the other way. This is particularly
1145             ;; valuable in the case of a new package USEing
1146             ;; COMMON-LISP.
1147             (cond
1148               ((< (+ (package-internal-symbol-count package)
1149                      (package-external-symbol-count package)
1150                      (let ((res 0))
1151                        (dolist (p use-list res)
1152                          (incf res (package-external-symbol-count p)))))
1153                   (package-external-symbol-count pkg))
1154                (do-symbols (sym package)
1155                  (multiple-value-bind (s w)
1156                      (find-external-symbol (symbol-name sym) pkg)
1157                    (when (and w
1158                               (not (eq s sym))
1159                               (not (member sym shadowing-symbols)))
1160                      (name-conflict package 'use-package pkg sym s))))
1161                (dolist (p use-list)
1162                  (do-external-symbols (sym p)
1163                    (multiple-value-bind (s w)
1164                        (find-external-symbol (symbol-name sym) pkg)
1165                      (when (and w
1166                                 (not (eq s sym))
1167                                 (not (member
1168                                       (find-symbol (symbol-name sym) package)
1169                                       shadowing-symbols)))
1170                        (name-conflict package 'use-package pkg sym s))))))
1171               (t
1172                (do-external-symbols (sym pkg)
1173                  (multiple-value-bind (s w)
1174                      (find-symbol (symbol-name sym) package)
1175                    (when (and w
1176                               (not (eq s sym))
1177                               (not (member s shadowing-symbols)))
1178                      (name-conflict package 'use-package pkg sym s)))))))
1179
1180           (push pkg (package-%use-list package))
1181           (push (package-external-symbols pkg) (cdr (package-tables package)))
1182           (push package (package-%used-by-list pkg))))))
1183   t)
1184
1185 (defun unuse-package (packages-to-unuse &optional (package (sane-package)))
1186   #!+sb-doc
1187   "Remove PACKAGES-TO-UNUSE from the USE list for PACKAGE."
1188   (let ((package (find-undeleted-package-or-lose package))
1189         (packages (package-listify packages-to-unuse)))
1190     (with-single-package-locked-error ()
1191       (dolist (p packages)
1192         (when (member p (package-use-list package))
1193           (assert-package-unlocked package "unusing package~P ~{~A~^, ~}"
1194                                    (length packages) packages))
1195         (setf (package-%use-list package)
1196               (remove p (the list (package-%use-list package))))
1197         (setf (package-tables package)
1198               (delete (package-external-symbols p)
1199                       (the list (package-tables package))))
1200         (setf (package-%used-by-list p)
1201               (remove package (the list (package-%used-by-list p))))))
1202     t))
1203
1204 (defun find-all-symbols (string-or-symbol)
1205   #!+sb-doc
1206   "Return a list of all symbols in the system having the specified name."
1207   (let ((string (string string-or-symbol))
1208         (res ()))
1209     (maphash (lambda (k v)
1210                (declare (ignore k))
1211                (multiple-value-bind (s w) (find-symbol string v)
1212                  (when w (pushnew s res))))
1213              *package-names*)
1214     res))
1215 \f
1216 ;;;; APROPOS and APROPOS-LIST
1217
1218 (defun briefly-describe-symbol (symbol)
1219   (fresh-line)
1220   (prin1 symbol)
1221   (when (boundp symbol)
1222     (write-string " (bound)"))
1223   (when (fboundp symbol)
1224     (write-string " (fbound)")))
1225
1226 (defun apropos-list (string-designator
1227                      &optional
1228                      package-designator
1229                      external-only)
1230   #!+sb-doc
1231   "Like APROPOS, except that it returns a list of the symbols found instead
1232   of describing them."
1233   (if package-designator
1234       (let ((package (find-undeleted-package-or-lose package-designator))
1235             (string (stringify-name string-designator "APROPOS search"))
1236             (result nil))
1237         (do-symbols (symbol package)
1238           (when (and (eq (symbol-package symbol) package)
1239                      (or (not external-only)
1240                          (eq (nth-value 1 (find-symbol (symbol-name symbol)
1241                                                        package))
1242                              :external))
1243                      (search string (symbol-name symbol) :test #'char-equal))
1244             (push symbol result)))
1245         result)
1246       (mapcan (lambda (package)
1247                 (apropos-list string-designator package external-only))
1248               (list-all-packages))))
1249
1250 (defun apropos (string-designator &optional package external-only)
1251   #!+sb-doc
1252   "Briefly describe all symbols which contain the specified STRING.
1253   If PACKAGE is supplied then only describe symbols present in
1254   that package. If EXTERNAL-ONLY then only describe
1255   external symbols in the specified package."
1256   ;; Implementing this in terms of APROPOS-LIST keeps things simple at the cost
1257   ;; of some unnecessary consing; and the unnecessary consing shouldn't be an
1258   ;; issue, since this function is is only useful interactively anyway, and
1259   ;; we can cons and GC a lot faster than the typical user can read..
1260   (dolist (symbol (apropos-list string-designator package external-only))
1261     (briefly-describe-symbol symbol))
1262   (values))
1263 \f
1264 ;;;; final initialization
1265
1266 ;;;; The cold loader (GENESIS) makes the data structure in
1267 ;;;; *!INITIAL-SYMBOLS*. We grovel over it, making the specified
1268 ;;;; packages and interning the symbols. For a description of the
1269 ;;;; format of *!INITIAL-SYMBOLS*, see the GENESIS source.
1270
1271 (defvar *!initial-symbols*)
1272
1273 (!cold-init-forms
1274
1275   (setq *in-package-init* t)
1276
1277   (/show0 "about to loop over *!INITIAL-SYMBOLS* to make packages")
1278   (dolist (spec *!initial-symbols*)
1279     (let* ((pkg (apply #'make-package (first spec)))
1280            (internal (package-internal-symbols pkg))
1281            (external (package-external-symbols pkg)))
1282       (/show0 "back from MAKE-PACKAGE, PACKAGE-NAME=..")
1283       (/primitive-print (package-name pkg))
1284
1285       ;; Put internal symbols in the internal hashtable and set package.
1286       (dolist (symbol (second spec))
1287         (add-symbol internal symbol)
1288         (%set-symbol-package symbol pkg))
1289
1290       ;; External symbols same, only go in external table.
1291       (dolist (symbol (third spec))
1292         (add-symbol external symbol)
1293         (%set-symbol-package symbol pkg))
1294
1295       ;; Don't set package for imported symbols.
1296       (dolist (symbol (fourth spec))
1297         (add-symbol internal symbol))
1298       (dolist (symbol (fifth spec))
1299         (add-symbol external symbol))
1300
1301       ;; Put shadowing symbols in the shadowing symbols list.
1302       (setf (package-%shadowing-symbols pkg) (sixth spec))
1303       ;; Set the package documentation
1304       (setf (package-doc-string pkg) (seventh spec))))
1305
1306   ;; FIXME: These assignments are also done at toplevel in
1307   ;; boot-extensions.lisp. They should probably only be done once.
1308   (/show0 "setting up *CL-PACKAGE* and *KEYWORD-PACKAGE*")
1309   (setq *cl-package* (find-package "COMMON-LISP"))
1310   (setq *keyword-package* (find-package "KEYWORD"))
1311
1312   (/show0 "about to MAKUNBOUND *!INITIAL-SYMBOLS*")
1313   (makunbound '*!initial-symbols*)       ; (so that it gets GCed)
1314
1315   ;; Make some other packages that should be around in the cold load.
1316   ;; The COMMON-LISP-USER package is required by the ANSI standard,
1317   ;; but not completely specified by it, so in the cross-compilation
1318   ;; host Lisp it could contain various symbols, USE-PACKAGEs, or
1319   ;; nicknames that we don't want in our target SBCL. For that reason,
1320   ;; we handle it specially, not dumping the host Lisp version at
1321   ;; genesis time..
1322   (aver (not (find-package "COMMON-LISP-USER")))
1323   ;; ..but instead making our own from scratch here.
1324   (/show0 "about to MAKE-PACKAGE COMMON-LISP-USER")
1325   (make-package "COMMON-LISP-USER"
1326                 :nicknames '("CL-USER")
1327                 :use '("COMMON-LISP"
1328                        ;; ANSI encourages us to put extension packages
1329                        ;; in the USE list of COMMON-LISP-USER.
1330                        "SB!ALIEN" "SB!ALIEN" "SB!DEBUG"
1331                        "SB!EXT" "SB!GRAY" "SB!PROFILE"))
1332
1333   ;; Now do the *!DEFERRED-USE-PACKAGES*.
1334   (/show0 "about to do *!DEFERRED-USE-PACKAGES*")
1335   (dolist (args *!deferred-use-packages*)
1336     (apply #'use-package args))
1337
1338   ;; The Age Of Magic is over, we can behave ANSIly henceforth.
1339   (/show0 "about to SETQ *IN-PACKAGE-INIT*")
1340   (setq *in-package-init* nil)
1341
1342   ;; For the kernel core image wizards, set the package to *CL-PACKAGE*.
1343   ;;
1344   ;; FIXME: We should just set this to (FIND-PACKAGE
1345   ;; "COMMON-LISP-USER") once and for all here, instead of setting it
1346   ;; once here and resetting it later.
1347   (setq *package* *cl-package*))
1348 \f
1349 (!cold-init-forms
1350   (/show0 "done with !PACKAGE-COLD-INIT"))
1351
1352 (!defun-from-collected-cold-init-forms !package-cold-init)