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