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