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