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