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