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