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