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