0.6.8.9:
[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 ;;;; This software is part of the SBCL system. See the README file for
13 ;;;; more information.
14 ;;;;
15 ;;;; This software is derived from the CMU CL system, which was
16 ;;;; written at Carnegie Mellon University and released into the
17 ;;;; public domain. The software is in the public domain and is
18 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
19 ;;;; files for more information.
20
21 (in-package "SB!IMPL")
22
23 (!begin-collecting-cold-init-forms)
24
25 (!cold-init-forms
26   (/show0 "entering !PACKAGE-COLD-INIT"))
27
28 (defvar *default-package-use-list*)
29 (!cold-init-forms
30   (setf *default-package-use-list* '("COMMON-LISP")))
31 #!+sb-doc
32 (setf (fdocumentation '*default-package-use-list* 'variable)
33   "the list of packages to use by default when no :USE argument is supplied
34   to MAKE-PACKAGE or other package creation forms")
35 \f
36 ;;;; PACKAGE-HASHTABLE stuff
37
38 (def!method print-object ((table package-hashtable) stream)
39   (declare (type stream stream))
40   (print-unreadable-object (table stream :type t)
41     (format stream
42             ":SIZE ~S :FREE ~S :DELETED ~S"
43             (package-hashtable-size table)
44             (package-hashtable-free table)
45             (package-hashtable-deleted table))))
46
47 ;;; the maximum density we allow in a package hashtable
48 (defconstant package-rehash-threshold 0.75)
49
50 ;;; Make a package hashtable having a prime number of entries at least
51 ;;; as great as (/ SIZE PACKAGE-REHASH-THRESHOLD). If RES is supplied,
52 ;;; then it is destructively modified to produce the result. This is
53 ;;; useful when changing the size, since there are many pointers to
54 ;;; the hashtable.
55 (defun make-or-remake-package-hashtable (size
56                                          &optional
57                                          (res (%make-package-hashtable)))
58   (do ((n (logior (truncate size package-rehash-threshold) 1)
59           (+ n 2)))
60       ((positive-primep n)
61        (setf (package-hashtable-table res)
62              (make-array n))
63        (setf (package-hashtable-hash res)
64              (make-array n
65                          :element-type '(unsigned-byte 8)
66                          :initial-element 0))
67        (let ((size (truncate (* n package-rehash-threshold))))
68          (setf (package-hashtable-size res) size)
69          (setf (package-hashtable-free res) size))
70        (setf (package-hashtable-deleted res) 0)
71        res)
72     (declare (type fixnum n))))
73 \f
74 ;;;; miscellaneous PACKAGE operations
75
76 (def!method print-object ((package package) stream)
77   (let ((name (package-%name package)))
78     (if name
79         (print-unreadable-object (package stream :type t)
80           (prin1 name stream))
81         (print-unreadable-object (package stream :type t :identity t)
82           (write-string "(deleted)" stream)))))
83
84 ;;; ANSI says (in the definition of DELETE-PACKAGE) that these, and
85 ;;; most other operations, are unspecified for deleted packages. We
86 ;;; just do the easy thing and signal errors in that case.
87 (macrolet ((def-frob (ext real)
88              `(defun ,ext (x) (,real (find-undeleted-package-or-lose x)))))
89   (def-frob package-nicknames package-%nicknames)
90   (def-frob package-use-list package-%use-list)
91   (def-frob package-used-by-list package-%used-by-list)
92   (def-frob package-shadowing-symbols package-%shadowing-symbols))
93
94 (flet ((stuff (table)
95          (let ((size (the fixnum
96                           (- (the fixnum (package-hashtable-size table))
97                              (the fixnum
98                                   (package-hashtable-deleted table))))))
99            (declare (fixnum size))
100            (values (the fixnum
101                         (- size
102                            (the fixnum
103                                 (package-hashtable-free table))))
104                    size))))
105   (defun package-internal-symbol-count (package)
106     (stuff (package-internal-symbols package)))
107   (defun package-external-symbol-count (package)
108     (stuff (package-external-symbols package))))
109 \f
110 (defvar *package* () ; actually initialized in cold load
111   #!+sb-doc "the current package")
112 ;;; FIXME: should be declared of type PACKAGE, with no NIL init form,
113 ;;; after I get around to cleaning up DOCUMENTATION
114 ;;;
115 ;;; FIXME: Setting *PACKAGE* to a non-PACKAGE value (even a plausible
116 ;;; one, like :CL-USER) makes the system fairly unusable, without
117 ;;; generating useful diagnostics. Is it possible to handle this
118 ;;; situation more gracefully by replacing references to *PACKAGE*
119 ;;; with references to (DEFAULT-PACKAGE) and implementing
120 ;;; DEFAULT-PACKAGE so that it checks for the PACKAGEness of *PACKAGE*
121 ;;; and helps the user to fix any problem (perhaps going through
122 ;;; CERROR)?
123 ;;;   Error: An attempt was made to use the *PACKAGE* variable when it was
124 ;;;       bound to the illegal (non-PACKAGE) value ~S. This is
125 ;;;       forbidden by the ANSI specification and could have made
126 ;;;       the system very confused. The *PACKAGE* variable has been
127 ;;;       temporarily reset to #<PACKAGE "COMMON-LISP-USER">. How
128 ;;;       would you like to proceed?
129 ;;;         NAMED Set *PACKAGE* to ~S (which is the package which is
130 ;;;               named by the old illegal ~S value of *PACKAGE*, and
131 ;;;               is thus very likely the intended value) and continue
132 ;;;               without signalling an error.
133 ;;;         ERROR Leave *PACKAGE* set to #<PACKAGE "COMMON-LISP-USER">
134 ;;;               and signal PACKAGE-ERROR to the code which tried to
135 ;;;               use the old illegal value of *PACKAGE*.
136 ;;;         CONTINUE Leave *PACKAGE* set to #<PACKAGE "COMMON-LISP-USER">
137 ;;;               and continue without signalling an error.
138
139 ;;; a map from package names to packages
140 (defvar *package-names*)
141 (declaim (type hash-table *package-names*))
142 (!cold-init-forms
143   (setf *package-names* (make-hash-table :test 'equal)))
144
145 ;;; This magical variable is T during initialization so that
146 ;;; USE-PACKAGE's of packages that don't yet exist quietly win. Such
147 ;;; packages are thrown onto the list *DEFERRED-USE-PACKAGES* so that
148 ;;; this can be fixed up later.
149 ;;;
150 ;;; FIXME: This could be cleaned up the same way I do it in my package
151 ;;; hacking when setting up the cross-compiler. Then we wouldn't have
152 ;;; this extraneous global variable and annoying runtime tests on
153 ;;; package operations. (*DEFERRED-USE-PACKAGES* would also go away.)
154 (defvar *in-package-init*)
155
156 ;;; pending USE-PACKAGE arguments saved up while *IN-PACKAGE-INIT* is true
157 (defvar *!deferred-use-packages*)
158 (!cold-init-forms
159   (setf *!deferred-use-packages* nil))
160
161 ;;; FIXME: I rewrote this. Test it and the stuff that calls it.
162 (defun find-package (package-designator)
163   (flet ((find-package-from-string (string)
164            (declare (type string string))
165            (values (gethash string *package-names*))))
166     (declare (inline find-package-from-string))
167     (typecase package-designator
168       (package package-designator)
169       (symbol (find-package-from-string (symbol-name package-designator)))
170       (string (find-package-from-string package-designator))
171       (character (find-package-from-string (string package-designator)))
172       (t (error 'type-error
173                 :datum package-designator
174                 :expected-type '(or character package string symbol))))))
175
176 ;;; Return a list of packages given a package designator or list of
177 ;;; package designators, or die trying.
178 (defun package-listify (thing)
179   (let ((res ()))
180     (dolist (thing (if (listp thing) thing (list thing)) res)
181       (push (find-undeleted-package-or-lose thing) res))))
182
183 ;;; Make a package name into a simple-string.
184 (defun package-namify (n)
185   (stringify-name n "package"))
186
187 ;;; ANSI specifies (in the definition of DELETE-PACKAGE) that PACKAGE-NAME
188 ;;; returns NIL (not an error) for a deleted package, so this is a special
189 ;;; case where we want to use bare %FIND-PACKAGE-OR-LOSE instead of
190 ;;; FIND-UNDELETED-PACKAGE-OR-LOSE.
191 (defun package-name (package-designator)
192   (package-%name (%find-package-or-lose package-designator)))
193 \f
194 ;;;; operations on package hashtables
195
196 ;;; Compute a number from the sxhash of the pname and the length which
197 ;;; must be between 2 and 255.
198 (defmacro entry-hash (length sxhash)
199   `(the fixnum
200         (+ (the fixnum
201                 (rem (the fixnum
202                           (logxor ,length
203                                   ,sxhash
204                                   (the fixnum (ash ,sxhash -8))
205                                   (the fixnum (ash ,sxhash -16))
206                                   (the fixnum (ash ,sxhash -19))))
207                      254))
208            2)))
209 ;;; FIXME: should be wrapped in EVAL-WHEN (COMPILE EXECUTE)
210
211 ;;; Add a symbol to a package hashtable. The symbol is assumed
212 ;;; not to be present.
213 (defun add-symbol (table symbol)
214   (let* ((vec (package-hashtable-table table))
215          (hash (package-hashtable-hash table))
216          (len (length vec))
217          (sxhash (%sxhash-simple-string (symbol-name symbol)))
218          (h2 (the fixnum (1+ (the fixnum (rem sxhash
219                                               (the fixnum (- len 2))))))))
220     (declare (simple-vector vec)
221              (type (simple-array (unsigned-byte 8)) hash)
222              (fixnum len sxhash h2))
223     (cond ((zerop (the fixnum (package-hashtable-free table)))
224            (make-or-remake-package-hashtable (* (package-hashtable-size table)
225                                                 2)
226                                              table)
227            (add-symbol table symbol)
228            (dotimes (i len)
229              (declare (fixnum i))
230              (when (> (the fixnum (aref hash i)) 1)
231                (add-symbol table (svref vec i)))))
232           (t
233            (do ((i (rem sxhash len) (rem (+ i h2) len)))
234                ((< (the fixnum (aref hash i)) 2)
235                 (if (zerop (the fixnum (aref hash i)))
236                     (decf (the fixnum (package-hashtable-free table)))
237                     (decf (the fixnum (package-hashtable-deleted table))))
238                 (setf (svref vec i) symbol)
239                 (setf (aref hash i)
240                       (entry-hash (length (the simple-string
241                                                (symbol-name symbol)))
242                                   sxhash)))
243              (declare (fixnum i)))))))
244
245 ;;; Find where the symbol named String is stored in Table. Index-Var
246 ;;; is bound to the index, or NIL if it is not present. Symbol-Var
247 ;;; is bound to the symbol. Length and Hash are the length and sxhash
248 ;;; of String. Entry-Hash is the entry-hash of the string and length.
249 (defmacro with-symbol ((index-var symbol-var table string length sxhash
250                                   entry-hash)
251                        &body forms)
252   (let ((vec (gensym)) (hash (gensym)) (len (gensym)) (h2 (gensym))
253         (name (gensym)) (name-len (gensym)) (ehash (gensym)))
254     `(let* ((,vec (package-hashtable-table ,table))
255             (,hash (package-hashtable-hash ,table))
256             (,len (length ,vec))
257             (,h2 (1+ (the index (rem (the index ,sxhash)
258                                       (the index (- ,len 2)))))))
259        (declare (type (simple-array (unsigned-byte 8) (*)) ,hash)
260                 (simple-vector ,vec)
261                 (type index ,len ,h2))
262        (prog ((,index-var (rem (the index ,sxhash) ,len))
263               ,symbol-var ,ehash)
264          (declare (type (or index null) ,index-var))
265          LOOP
266          (setq ,ehash (aref ,hash ,index-var))
267          (cond ((eql ,ehash ,entry-hash)
268                 (setq ,symbol-var (svref ,vec ,index-var))
269                 (let* ((,name (symbol-name ,symbol-var))
270                        (,name-len (length ,name)))
271                   (declare (simple-string ,name)
272                            (type index ,name-len))
273                   (when (and (= ,name-len ,length)
274                              (string= ,string ,name
275                                       :end1 ,length
276                                       :end2 ,name-len))
277                     (go DOIT))))
278                ((zerop ,ehash)
279                 (setq ,index-var nil)
280                 (go DOIT)))
281          (setq ,index-var (+ ,index-var ,h2))
282          (when (>= ,index-var ,len)
283            (setq ,index-var (- ,index-var ,len)))
284          (go LOOP)
285          DOIT
286          (return (progn ,@forms))))))
287
288 ;;; Delete the entry for String in Table. The entry must exist.
289 (defun nuke-symbol (table string)
290   (declare (simple-string string))
291   (let* ((length (length string))
292          (hash (%sxhash-simple-string string))
293          (ehash (entry-hash length hash)))
294     (declare (type index length hash))
295     (with-symbol (index symbol table string length hash ehash)
296       (setf (aref (package-hashtable-hash table) index) 1)
297       (setf (aref (package-hashtable-table table) index) nil)
298       (incf (package-hashtable-deleted table)))))
299 \f
300 ;;; Enter any new Nicknames for Package into *package-names*.
301 ;;; If there is a conflict then give the user a chance to do
302 ;;; something about it.
303 (defun enter-new-nicknames (package nicknames)
304   (check-type nicknames list)
305   (dolist (n nicknames)
306     (let* ((n (package-namify n))
307            (found (gethash n *package-names*)))
308       (cond ((not found)
309              (setf (gethash n *package-names*) package)
310              (push n (package-%nicknames package)))
311             ((eq found package))
312             ((string= (the string (package-%name found)) n)
313              ;; FIXME: This and the next error needn't have restarts.
314              (with-simple-restart (continue "Ignore this nickname.")
315                (error 'simple-package-error
316                       :package package
317                       :format-control "~S is a package name, so it cannot be a nickname for ~S."
318                       :format-arguments (list n (package-%name package)))))
319             (t
320              (with-simple-restart (continue "Redefine this nickname.")
321                (error 'simple-package-error
322                       :package package
323                       :format-control "~S is already a nickname for ~S."
324                       :format-arguments (list n (package-%name found))))
325              (setf (gethash n *package-names*) package)
326              (push n (package-%nicknames package)))))))
327
328 (defun make-package (name &key
329                           (use *default-package-use-list*)
330                           nicknames
331                           (internal-symbols 10)
332                           (external-symbols 10))
333   #!+sb-doc
334   "Makes a new package having the specified Name and Nicknames. The
335   package will inherit all external symbols from each package in
336   the use list. :Internal-Symbols and :External-Symbols are
337   estimates for the number of internal and external symbols which
338   will ultimately be present in the package."
339
340   ;; Check for package name conflicts in name and nicknames, then
341   ;; make the package.
342   (when (find-package name)
343     ;; ANSI specifies that this error is correctable.
344     (cerror "Leave existing package alone."
345             "A package named ~S already exists" name))
346   (let* ((name (package-namify name))
347          (package (internal-make-package
348                    :%name name
349                    :internal-symbols (make-or-remake-package-hashtable
350                                       internal-symbols)
351                    :external-symbols (make-or-remake-package-hashtable
352                                       external-symbols))))
353
354     ;; Do a USE-PACKAGE for each thing in the USE list so that checking for
355     ;; conflicting exports among used packages is done.
356     (if *in-package-init*
357         (push (list use package) *!deferred-use-packages*)
358         (use-package use package))
359
360     ;; FIXME: ENTER-NEW-NICKNAMES can fail (ERROR) if nicknames are illegal,
361     ;; which would leave us with possibly-bad side effects from the earlier
362     ;; USE-PACKAGE (e.g. this package on the used-by lists of other packages,
363     ;; but not in *PACKAGE-NAMES*, and possibly import side effects too?).
364     ;; Perhaps this can be solved by just moving ENTER-NEW-NICKNAMES before
365     ;; USE-PACKAGE, but I need to check what kinds of errors can be caused by
366     ;; USE-PACKAGE, too.
367     (enter-new-nicknames package nicknames)
368     (setf (gethash name *package-names*) package)))
369
370 ;;; Change the name if we can, blast any old nicknames and then
371 ;;; add in any new ones.
372 ;;;
373 ;;; FIXME: ANSI claims that NAME is a package designator (not just a
374 ;;; string designator -- weird). Thus, NAME could
375 ;;; be a package instead of a string. Presumably then we should not change
376 ;;; the package name if NAME is the same package that's referred to by PACKAGE.
377 ;;; If it's a *different* package, we should probably signal an error.
378 ;;; (perhaps (ERROR 'ANSI-WEIRDNESS ..):-)
379 (defun rename-package (package name &optional (nicknames ()))
380   #!+sb-doc
381   "Changes the name and nicknames for a package."
382   (let* ((package (find-undeleted-package-or-lose package))
383          (name (string name))
384          (found (find-package name)))
385     (unless (or (not found) (eq found package))
386       (error "A package named ~S already exists." name))
387     (remhash (package-%name package) *package-names*)
388     (dolist (n (package-%nicknames package))
389       (remhash n *package-names*))
390      (setf (package-%name package) name)
391     (setf (gethash name *package-names*) package)
392     (setf (package-%nicknames package) ())
393     (enter-new-nicknames package nicknames)
394     package))
395
396 (defun delete-package (package-or-name)
397   #!+sb-doc
398   "Delete the package-or-name from the package system data structures."
399   (let ((package (if (packagep package-or-name)
400                      package-or-name
401                      (find-package package-or-name))))
402     (cond ((not package)
403            ;; This continuable error is required by ANSI.
404            (with-simple-restart (continue "Return NIL")
405              (error 'simple-package-error
406                     :package package-or-name
407                     :format-control "There is no package named ~S."
408                     :format-arguments (list package-or-name))))
409           ((not (package-name package)) ; already deleted
410            nil)
411           (t
412            (let ((use-list (package-used-by-list package)))
413              (when use-list
414                ;; This continuable error is specified by ANSI.
415                (with-simple-restart
416                    (continue "Remove dependency in other packages.")
417                  (error 'simple-package-error
418                         :package package
419                         :format-control
420                         "Package ~S is used by package(s):~%  ~S"
421                         :format-arguments
422                         (list (package-name package)
423                               (mapcar #'package-name use-list))))
424                (dolist (p use-list)
425                  (unuse-package package p))))
426            (dolist (used (package-use-list package))
427              (unuse-package used package))
428            (do-symbols (sym package)
429              (unintern sym package))
430            (remhash (package-name package) *package-names*)
431            (dolist (nick (package-nicknames package))
432              (remhash nick *package-names*))
433            (setf (package-%name package) nil
434                  ;; Setting PACKAGE-%NAME to NIL is required in order to
435                  ;; make PACKAGE-NAME return NIL for a deleted package as
436                  ;; ANSI requires. Setting the other slots to NIL
437                  ;; and blowing away the PACKAGE-HASHTABLES is just done
438                  ;; for tidiness and to help the GC.
439                  (package-%nicknames package) nil
440                  (package-%use-list package) nil
441                  (package-tables package) nil
442                  (package-%shadowing-symbols package) nil
443                  (package-internal-symbols package)
444                  (make-or-remake-package-hashtable 0)
445                  (package-external-symbols package)
446                  (make-or-remake-package-hashtable 0))
447            t))))
448
449 (defun list-all-packages ()
450   #!+sb-doc
451   "Returns a list of all existing packages."
452   (let ((res ()))
453     (maphash #'(lambda (k v)
454                  (declare (ignore k))
455                  (pushnew v res))
456              *package-names*)
457     res))
458 \f
459 (defun intern (name &optional (package *package*))
460   #!+sb-doc
461   "Returns a symbol having the specified name, creating it if necessary."
462   ;; We just simple-stringify the name and call INTERN*, where the real
463   ;; logic is.
464   (let ((name (if (simple-string-p name)
465                 name
466                 (coerce name 'simple-string))))
467     (declare (simple-string name))
468     (intern* name
469              (length name)
470              (find-undeleted-package-or-lose package))))
471
472 (defun find-symbol (name &optional (package *package*))
473   #!+sb-doc
474   "Returns the symbol named String in Package. If such a symbol is found
475   then the second value is :internal, :external or :inherited to indicate
476   how the symbol is accessible. If no symbol is found then both values
477   are NIL."
478   ;; We just simple-stringify the name and call FIND-SYMBOL*, where the
479   ;; real logic is.
480   (let ((name (if (simple-string-p name) name (coerce name 'simple-string))))
481     (declare (simple-string name))
482     (find-symbol* name
483                   (length name)
484                   (find-undeleted-package-or-lose package))))
485
486 ;;; If the symbol named by the first LENGTH characters of NAME doesn't exist,
487 ;;; then create it, special-casing the keyword package.
488 (defun intern* (name length package)
489   (declare (simple-string name))
490   (multiple-value-bind (symbol where) (find-symbol* name length package)
491     (if where
492         (values symbol where)
493         (let ((symbol (make-symbol (subseq name 0 length))))
494           (%set-symbol-package symbol package)
495           (cond ((eq package *keyword-package*)
496                  (add-symbol (package-external-symbols package) symbol)
497                  (%set-symbol-value symbol symbol))
498                 (t
499                  (add-symbol (package-internal-symbols package) symbol)))
500           (values symbol nil)))))
501
502 ;;; Check internal and external symbols, then scan down the list
503 ;;; of hashtables for inherited symbols. When an inherited symbol
504 ;;; is found pull that table to the beginning of the list.
505 (defun find-symbol* (string length package)
506   (declare (simple-string string)
507            (type index length))
508   (let* ((hash (%sxhash-simple-substring string length))
509          (ehash (entry-hash length hash)))
510     (declare (type index hash ehash))
511     (with-symbol (found symbol (package-internal-symbols package)
512                         string length hash ehash)
513       (when found
514         (return-from find-symbol* (values symbol :internal))))
515     (with-symbol (found symbol (package-external-symbols package)
516                         string length hash ehash)
517       (when found
518         (return-from find-symbol* (values symbol :external))))
519     (let ((head (package-tables package)))
520       (do ((prev head table)
521            (table (cdr head) (cdr table)))
522           ((null table) (values nil nil))
523         (with-symbol (found symbol (car table) string length hash ehash)
524           (when found
525             (unless (eq prev head)
526               (shiftf (cdr prev) (cdr table) (cdr head) table))
527             (return-from find-symbol* (values symbol :inherited))))))))
528
529 ;;; Similar to Find-Symbol, but only looks for an external symbol.
530 ;;; This is used for fast name-conflict checking in this file and symbol
531 ;;; printing in the printer.
532 (defun find-external-symbol (string package)
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 hash))
538     (with-symbol (found symbol (package-external-symbols package)
539                         string length hash ehash)
540       (values symbol found))))
541 \f
542 ;;; If we are uninterning a shadowing symbol, then a name conflict can
543 ;;; result, otherwise just nuke the symbol.
544 (defun unintern (symbol &optional (package *package*))
545   #!+sb-doc
546   "Makes Symbol no longer present in Package. If Symbol was present
547   then T is returned, otherwise NIL. If Package is Symbol's home
548   package, then it is made uninterned."
549   (let* ((package (find-undeleted-package-or-lose package))
550          (name (symbol-name symbol))
551          (shadowing-symbols (package-%shadowing-symbols package)))
552     (declare (list shadowing-symbols) (simple-string name))
553
554     ;; If a name conflict is revealed, give use a chance to shadowing-import
555     ;; one of the accessible symbols.
556     (when (member symbol shadowing-symbols)
557       (let ((cset ()))
558         (dolist (p (package-%use-list package))
559           (multiple-value-bind (s w) (find-external-symbol name p)
560             (when w (pushnew s cset))))
561         (when (cdr cset)
562           (loop
563            (cerror
564             "Prompt for a symbol to SHADOWING-IMPORT."
565             "Uninterning symbol ~S causes name conflict among these symbols:~%~S"
566             symbol cset)
567            (write-string "Symbol to shadowing-import: " *query-io*)
568            (let ((sym (read *query-io*)))
569              (cond
570               ((not (symbolp sym))
571                (format *query-io* "~S is not a symbol."))
572               ((not (member sym cset))
573                (format *query-io* "~S is not one of the conflicting symbols."))
574               (t
575                (shadowing-import sym package)
576                (return-from unintern t)))))))
577       (setf (package-%shadowing-symbols package)
578             (remove symbol shadowing-symbols)))
579
580     (multiple-value-bind (s w) (find-symbol name package)
581       (declare (ignore s))
582       (cond ((or (eq w :internal) (eq w :external))
583              (nuke-symbol (if (eq w :internal)
584                               (package-internal-symbols package)
585                               (package-external-symbols package))
586                           name)
587              (if (eq (symbol-package symbol) package)
588                  (%set-symbol-package symbol nil))
589              t)
590             (t nil)))))
591 \f
592 ;;; Take a symbol-or-list-of-symbols and return a list, checking types.
593 (defun symbol-listify (thing)
594   (cond ((listp thing)
595          (dolist (s thing)
596            (unless (symbolp s) (error "~S is not a symbol." s)))
597          thing)
598         ((symbolp thing) (list thing))
599         (t
600          (error "~S is neither a symbol nor a list of symbols." thing))))
601
602 ;;; Like UNINTERN, but if symbol is inherited chases down the package
603 ;;; it is inherited from and uninterns it there. Used for
604 ;;; name-conflict resolution. Shadowing symbols are not uninterned
605 ;;; since they do not cause conflicts.
606 (defun moby-unintern (symbol package)
607   (unless (member symbol (package-%shadowing-symbols package))
608     (or (unintern symbol package)
609         (let ((name (symbol-name symbol)))
610           (multiple-value-bind (s w) (find-symbol name package)
611             (declare (ignore s))
612             (when (eq w :inherited)
613               (dolist (q (package-%use-list package))
614                 (multiple-value-bind (u x) (find-external-symbol name q)
615                   (declare (ignore u))
616                   (when x
617                     (unintern symbol q)
618                     (return t))))))))))
619 \f
620 (defun export (symbols &optional (package *package*))
621   #!+sb-doc
622   "Exports Symbols from Package, checking that no name conflicts result."
623   (let ((package (find-undeleted-package-or-lose package))
624         (syms ()))
625     ;; Punt any symbols that are already external.
626     (dolist (sym (symbol-listify symbols))
627       (multiple-value-bind (s w)
628           (find-external-symbol (symbol-name sym) package)
629         (declare (ignore s))
630         (unless (or w (member sym syms))
631           (push sym syms))))
632     ;; Find symbols and packages with conflicts.
633     (let ((used-by (package-%used-by-list package))
634           (cpackages ())
635           (cset ()))
636       (dolist (sym syms)
637         (let ((name (symbol-name sym)))
638           (dolist (p used-by)
639             (multiple-value-bind (s w) (find-symbol name p)
640               (when (and w (not (eq s sym))
641                          (not (member s (package-%shadowing-symbols p))))
642                 (pushnew sym cset)
643                 (pushnew p cpackages))))))
644       (when cset
645         (restart-case
646             (error
647              'simple-package-error
648              :package package
649              :format-control
650              "Exporting these symbols from the ~A package:~%~S~%~
651               results in name conflicts with these packages:~%~{~A ~}"
652              :format-arguments
653              (list (package-%name package) cset
654                    (mapcar #'package-%name cpackages)))
655           (unintern-conflicting-symbols ()
656            :report "Unintern conflicting symbols."
657            (dolist (p cpackages)
658              (dolist (sym cset)
659                (moby-unintern sym p))))
660           (skip-exporting-these-symbols ()
661            :report "Skip exporting conflicting symbols."
662            (setq syms (nset-difference syms cset))))))
663
664     ;; Check that all symbols are accessible. If not, ask to import them.
665     (let ((missing ())
666           (imports ()))
667       (dolist (sym syms)
668         (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
669           (cond ((not (and w (eq s sym)))
670                  (push sym missing))
671                 ((eq w :inherited)
672                  (push sym imports)))))
673       (when missing
674         (with-simple-restart
675             (continue "Import these symbols into the ~A package."
676               (package-%name package))
677           (error 'simple-package-error
678                  :package package
679                  :format-control
680                  "These symbols are not accessible in the ~A package:~%~S"
681                  :format-arguments
682                  (list (package-%name package) missing)))
683         (import missing package))
684       (import imports package))
685
686     ;; And now, three pages later, we export the suckers.
687     (let ((internal (package-internal-symbols package))
688           (external (package-external-symbols package)))
689       (dolist (sym syms)
690         (nuke-symbol internal (symbol-name sym))
691         (add-symbol external sym)))
692     t))
693 \f
694 ;;; Check that all symbols are accessible, then move from external to internal.
695 (defun unexport (symbols &optional (package *package*))
696   #!+sb-doc
697   "Makes Symbols no longer exported from Package."
698   (let ((package (find-undeleted-package-or-lose package))
699         (syms ()))
700     (dolist (sym (symbol-listify symbols))
701       (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
702         (cond ((or (not w) (not (eq s sym)))
703                (error 'simple-package-error
704                       :package package
705                       :format-control "~S is not accessible in the ~A package."
706                       :format-arguments (list sym (package-%name package))))
707               ((eq w :external) (pushnew sym syms)))))
708
709     (let ((internal (package-internal-symbols package))
710           (external (package-external-symbols package)))
711       (dolist (sym syms)
712         (add-symbol internal sym)
713         (nuke-symbol external (symbol-name sym))))
714     t))
715 \f
716 ;;; Check for name conflict caused by the import and let the user
717 ;;; shadowing-import if there is.
718 (defun import (symbols &optional (package *package*))
719   #!+sb-doc
720   "Make Symbols accessible as internal symbols in Package. If a symbol
721   is already accessible then it has no effect. If a name conflict
722   would result from the importation, then a correctable error is signalled."
723   (let ((package (find-undeleted-package-or-lose package))
724         (symbols (symbol-listify symbols))
725         (syms ())
726         (cset ()))
727     (dolist (sym symbols)
728       (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
729         (cond ((not w)
730                (let ((found (member sym syms :test #'string=)))
731                  (if found
732                      (when (not (eq (car found) sym))
733                        (push sym cset))
734                      (push sym syms))))
735               ((not (eq s sym)) (push sym cset))
736               ((eq w :inherited) (push sym syms)))))
737     (when cset
738       ;; ANSI specifies that this error is correctable.
739       (with-simple-restart
740           (continue "Import these symbols with Shadowing-Import.")
741         (error 'simple-package-error
742                :package package
743                :format-control
744                "Importing these symbols into the ~A package ~
745                 causes a name conflict:~%~S"
746                :format-arguments (list (package-%name package) cset))))
747     ;; Add the new symbols to the internal hashtable.
748     (let ((internal (package-internal-symbols package)))
749       (dolist (sym syms)
750         (add-symbol internal sym)))
751     ;; If any of the symbols are uninterned, make them be owned by Package.
752     (dolist (sym symbols)
753       (unless (symbol-package sym) (%set-symbol-package sym package)))
754     (shadowing-import cset package)))
755 \f
756 ;;; If a conflicting symbol is present, unintern it, otherwise just
757 ;;; stick the symbol in.
758 (defun shadowing-import (symbols &optional (package *package*))
759   #!+sb-doc
760   "Import Symbols into package, disregarding any name conflict. If
761   a symbol of the same name is present, then it is uninterned.
762   The symbols are added to the Package-Shadowing-Symbols."
763   (let* ((package (find-undeleted-package-or-lose package))
764          (internal (package-internal-symbols package)))
765     (dolist (sym (symbol-listify symbols))
766       (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
767         (unless (and w (not (eq w :inherited)) (eq s sym))
768           (when (or (eq w :internal) (eq w :external))
769             ;; If it was shadowed, we don't want UNINTERN to flame out...
770             (setf (package-%shadowing-symbols package)
771                   (remove s (the list (package-%shadowing-symbols package))))
772             (unintern s package))
773           (add-symbol internal sym))
774         (pushnew sym (package-%shadowing-symbols package)))))
775   t)
776
777 (defun shadow (symbols &optional (package *package*))
778   #!+sb-doc
779   "Make an internal symbol in Package with the same name as each of the
780   specified symbols, adding the new symbols to the Package-Shadowing-Symbols.
781   If a symbol with the given name is already present in Package, then
782   the existing symbol is placed in the shadowing symbols list if it is
783   not already present."
784   (let* ((package (find-undeleted-package-or-lose package))
785          (internal (package-internal-symbols package)))
786     (dolist (name (mapcar #'string
787                           (if (listp symbols) symbols (list symbols))))
788       (multiple-value-bind (s w) (find-symbol name package)
789         (when (or (not w) (eq w :inherited))
790           (setq s (make-symbol name))
791           (%set-symbol-package s package)
792           (add-symbol internal s))
793         (pushnew s (package-%shadowing-symbols package)))))
794   t)
795 \f
796 ;;; Do stuff to use a package, with all kinds of fun name-conflict checking.
797 (defun use-package (packages-to-use &optional (package *package*))
798   #!+sb-doc
799   "Add all the Packages-To-Use to the use list for Package so that
800   the external symbols of the used packages are accessible as internal
801   symbols in Package."
802   (let ((packages (package-listify packages-to-use))
803         (package (find-undeleted-package-or-lose package)))
804
805     ;; Loop over each package, USE'ing one at a time...
806     (dolist (pkg packages)
807       (unless (member pkg (package-%use-list package))
808         (let ((cset ())
809               (shadowing-symbols (package-%shadowing-symbols package))
810               (use-list (package-%use-list package)))
811
812           ;;   If the number of symbols already accessible is less than the
813           ;; number to be inherited then it is faster to run the test the
814           ;; other way. This is particularly valuable in the case of
815           ;; a new package USEing Lisp.
816           (cond
817            ((< (+ (package-internal-symbol-count package)
818                   (package-external-symbol-count package)
819                   (let ((res 0))
820                     (dolist (p use-list res)
821                       (incf res (package-external-symbol-count p)))))
822                (package-external-symbol-count pkg))
823             (do-symbols (sym package)
824               (multiple-value-bind (s w)
825                   (find-external-symbol (symbol-name sym) pkg)
826                 (when (and w (not (eq s sym))
827                            (not (member sym shadowing-symbols)))
828                   (push sym cset))))
829             (dolist (p use-list)
830               (do-external-symbols (sym p)
831                 (multiple-value-bind (s w)
832                     (find-external-symbol (symbol-name sym) pkg)
833                   (when (and w (not (eq s sym))
834                              (not (member (find-symbol (symbol-name sym)
835                                                        package)
836                                           shadowing-symbols)))
837                     (push sym cset))))))
838            (t
839             (do-external-symbols (sym pkg)
840               (multiple-value-bind (s w)
841                   (find-symbol (symbol-name sym) package)
842                 (when (and w (not (eq s sym))
843                            (not (member s shadowing-symbols)))
844                   (push s cset))))))
845
846           (when cset
847             (cerror
848              "Unintern the conflicting symbols in the ~2*~A package."
849              "Use'ing package ~A results in name conflicts for these symbols:~%~S"
850              (package-%name pkg) cset (package-%name package))
851             (dolist (s cset) (moby-unintern s package))))
852
853         (push pkg (package-%use-list package))
854         (push (package-external-symbols pkg) (cdr (package-tables package)))
855         (push package (package-%used-by-list pkg)))))
856   t)
857
858 (defun unuse-package (packages-to-unuse &optional (package *package*))
859   #!+sb-doc
860   "Remove Packages-To-Unuse from the use list for Package."
861   (let ((package (find-undeleted-package-or-lose package)))
862     (dolist (p (package-listify packages-to-unuse))
863       (setf (package-%use-list package)
864             (remove p (the list (package-%use-list package))))
865       (setf (package-tables package)
866             (delete (package-external-symbols p)
867                     (the list (package-tables package))))
868       (setf (package-%used-by-list p)
869             (remove package (the list (package-%used-by-list p)))))
870     t))
871
872 (defun find-all-symbols (string-or-symbol)
873   #!+sb-doc
874   "Return a list of all symbols in the system having the specified name."
875   (let ((string (string string-or-symbol))
876         (res ()))
877     (maphash #'(lambda (k v)
878                  (declare (ignore k))
879                  (multiple-value-bind (s w) (find-symbol string v)
880                    (when w (pushnew s res))))
881              *package-names*)
882     res))
883 \f
884 ;;;; APROPOS and APROPOS-LIST
885
886 ;;; KLUDGE: All the APROPOS stuff should probably be byte-compiled, since it's
887 ;;; only likely to be used interactively. -- WHN 19990827
888
889 (defun briefly-describe-symbol (symbol)
890   (fresh-line)
891   (prin1 symbol)
892   (when (boundp symbol)
893     (write-string " (bound)"))
894   (when (fboundp symbol)
895     (write-string " (fbound)")))
896
897 (defun apropos-list (string-designator &optional package external-only)
898   #!+sb-doc
899   "Like APROPOS, except that it returns a list of the symbols found instead
900   of describing them."
901   (if package
902     (let ((string (stringify-name string-designator "APROPOS search"))
903           (result nil))
904       (do-symbols (symbol package)
905         (when (and (eq (symbol-package symbol) package)
906                    (or (not external-only)
907                        (eq (find-symbol (symbol-name symbol) package)
908                            :external))
909                    (search string (symbol-name symbol) :test #'char-equal))
910           (push symbol result)))
911       result)
912     (mapcan (lambda (package)
913               (apropos-list string-designator package external-only))
914             (list-all-packages))))
915
916 (defun apropos (string-designator &optional package external-only)
917   #!+sb-doc
918   "Briefly describe all symbols which contain the specified STRING.
919   If PACKAGE is supplied then only describe symbols present in
920   that package. If EXTERNAL-ONLY then only describe
921   external symbols in the specified package."
922   ;; Implementing this in terms of APROPOS-LIST keeps things simple at the cost
923   ;; of some unnecessary consing; and the unnecessary consing shouldn't be an
924   ;; issue, since this function is is only useful interactively anyway, and
925   ;; we can cons and GC a lot faster than the typical user can read..
926   (dolist (symbol (apropos-list string-designator package external-only))
927     (briefly-describe-symbol symbol))
928   (values))
929 \f
930 ;;;; final initialization
931
932 ;;;; The cold loader (GENESIS) makes the data structure in
933 ;;;; *!INITIAL-SYMBOLS*. We grovel over it, making the specified
934 ;;;; packages and interning the symbols. For a description of the
935 ;;;; format of *!INITIAL-SYMBOLS*, see the GENESIS source.
936
937 (defvar *!initial-symbols*)
938
939 (!cold-init-forms
940
941   (setq *in-package-init* t)
942
943   (/show0 "about to loop over *!INITIAL-SYMBOLS* to make packages")
944   (dolist (spec *!initial-symbols*)
945     (let* ((pkg (apply #'make-package (first spec)))
946            (internal (package-internal-symbols pkg))
947            (external (package-external-symbols pkg)))
948       (/show0 "back from MAKE-PACKAGE")
949       #!+sb-show (sb!sys:%primitive print (package-name pkg))
950
951       ;; Put internal symbols in the internal hashtable and set package.
952       (dolist (symbol (second spec))
953         (add-symbol internal symbol)
954         (%set-symbol-package symbol pkg))
955
956       ;; External symbols same, only go in external table.
957       (dolist (symbol (third spec))
958         (add-symbol external symbol)
959         (%set-symbol-package symbol pkg))
960
961       ;; Don't set package for imported symbols.
962       (dolist (symbol (fourth spec))
963         (add-symbol internal symbol))
964       (dolist (symbol (fifth spec))
965         (add-symbol external symbol))
966
967       ;; Put shadowing symbols in the shadowing symbols list.
968       (setf (package-%shadowing-symbols pkg) (sixth spec))))
969
970   ;; FIXME: These assignments are also done at toplevel in
971   ;; boot-extensions.lisp. They should probably only be done once.
972   (/show0 "setting up *CL-PACKAGE* and *KEYWORD-PACKAGE*")
973   (setq *cl-package* (find-package "COMMON-LISP"))
974   (setq *keyword-package* (find-package "KEYWORD"))
975
976   (/show0 "about to MAKUNBOUND *!INITIAL-SYMBOLS*")
977   (makunbound '*!initial-symbols*)       ; (so that it gets GCed)
978
979   ;; Make some other packages that should be around in the cold load.
980   ;; The COMMON-LISP-USER package is required by the ANSI standard,
981   ;; but not completely specified by it, so in the cross-compilation
982   ;; host Lisp it could contain various symbols, USE-PACKAGEs, or
983   ;; nicknames that we don't want in our target SBCL. For that reason,
984   ;; we handle it specially, not dumping the host Lisp version at
985   ;; genesis time..
986   (assert (not (find-package "COMMON-LISP-USER")))
987   ;; ..but instead making our own from scratch here.
988   (/show0 "about to MAKE-PACKAGE COMMON-LISP-USER")
989   (make-package "COMMON-LISP-USER"
990                 :nicknames '("CL-USER")
991                 :use '("COMMON-LISP"
992                        ;; ANSI encourages us to put extension packages
993                        ;; in the USE list of COMMON-LISP-USER.
994                        "SB!ALIEN" "SB!C-CALL" "SB!DEBUG"
995                        "SB!EXT" "SB!GRAY" "SB!PROFILE"))
996
997   ;; Now do the *!DEFERRED-USE-PACKAGES*.
998   (/show0 "about to do *!DEFERRED-USE-PACKAGES*")
999   (dolist (args *!deferred-use-packages*)
1000     (apply #'use-package args))
1001
1002   ;; The Age Of Magic is over, we can behave ANSIly henceforth.
1003   (/show0 "about to SETQ *IN-PACKAGE-INIT*")
1004   (setq *in-package-init* nil)
1005
1006   ;; For the kernel core image wizards, set the package to *CL-PACKAGE*.
1007   ;;
1008   ;; FIXME: We should just set this to (FIND-PACKAGE
1009   ;; "COMMON-LISP-USER") once and for all here, instead of setting it
1010   ;; once here and resetting it later.
1011   (setq *package* *cl-package*))
1012 \f
1013 (!cold-init-forms
1014   (/show0 "done with !PACKAGE-COLD-INIT"))
1015
1016 (!defun-from-collected-cold-init-forms !package-cold-init)