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