0.7.0:
[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 "A package named ~S already exists." name))
359     (remhash (package-%name package) *package-names*)
360     (dolist (n (package-%nicknames package))
361       (remhash n *package-names*))
362      (setf (package-%name package) name)
363     (setf (gethash name *package-names*) package)
364     (setf (package-%nicknames package) ())
365     (enter-new-nicknames package nicknames)
366     package))
367
368 (defun delete-package (package-or-name)
369   #!+sb-doc
370   "Delete the package-or-name from the package system data structures."
371   (let ((package (if (packagep package-or-name)
372                      package-or-name
373                      (find-package package-or-name))))
374     (cond ((not package)
375            ;; This continuable error is required by ANSI.
376            (with-simple-restart (continue "Return NIL")
377              (error 'simple-package-error
378                     :package package-or-name
379                     :format-control "There is no package named ~S."
380                     :format-arguments (list package-or-name))))
381           ((not (package-name package)) ; already deleted
382            nil)
383           (t
384            (let ((use-list (package-used-by-list package)))
385              (when use-list
386                ;; This continuable error is specified by ANSI.
387                (with-simple-restart
388                    (continue "Remove dependency in other packages.")
389                  (error 'simple-package-error
390                         :package package
391                         :format-control
392                         "Package ~S is used by package(s):~%  ~S"
393                         :format-arguments
394                         (list (package-name package)
395                               (mapcar #'package-name use-list))))
396                (dolist (p use-list)
397                  (unuse-package package p))))
398            (dolist (used (package-use-list package))
399              (unuse-package used package))
400            (do-symbols (sym package)
401              (unintern sym package))
402            (remhash (package-name package) *package-names*)
403            (dolist (nick (package-nicknames package))
404              (remhash nick *package-names*))
405            (setf (package-%name package) nil
406                  ;; Setting PACKAGE-%NAME to NIL is required in order to
407                  ;; make PACKAGE-NAME return NIL for a deleted package as
408                  ;; ANSI requires. Setting the other slots to NIL
409                  ;; and blowing away the PACKAGE-HASHTABLES is just done
410                  ;; for tidiness and to help the GC.
411                  (package-%nicknames package) nil
412                  (package-%use-list package) nil
413                  (package-tables package) nil
414                  (package-%shadowing-symbols package) nil
415                  (package-internal-symbols package)
416                  (make-or-remake-package-hashtable 0)
417                  (package-external-symbols package)
418                  (make-or-remake-package-hashtable 0))
419            t))))
420
421 (defun list-all-packages ()
422   #!+sb-doc
423   "Return a list of all existing packages."
424   (let ((res ()))
425     (maphash (lambda (k v)
426                (declare (ignore k))
427                (pushnew v res))
428              *package-names*)
429     res))
430 \f
431 (defun intern (name &optional (package (sane-package)))
432   #!+sb-doc
433   "Return a symbol having the specified name, creating it if necessary."
434   ;; We just simple-stringify the name and call INTERN*, where the real
435   ;; logic is.
436   (let ((name (if (simple-string-p name)
437                 name
438                 (coerce name 'simple-string))))
439     (declare (simple-string name))
440     (intern* name
441              (length name)
442              (find-undeleted-package-or-lose package))))
443
444 (defun find-symbol (name &optional (package (sane-package)))
445   #!+sb-doc
446   "Return the symbol named String in Package. If such a symbol is found
447   then the second value is :internal, :external or :inherited to indicate
448   how the symbol is accessible. If no symbol is found then both values
449   are NIL."
450   ;; We just simple-stringify the name and call FIND-SYMBOL*, where the
451   ;; real logic is.
452   (let ((name (if (simple-string-p name) name (coerce name 'simple-string))))
453     (declare (simple-string name))
454     (find-symbol* name
455                   (length name)
456                   (find-undeleted-package-or-lose package))))
457
458 ;;; If the symbol named by the first LENGTH characters of NAME doesn't exist,
459 ;;; then create it, special-casing the keyword package.
460 (defun intern* (name length package)
461   (declare (simple-string name))
462   (multiple-value-bind (symbol where) (find-symbol* name length package)
463     (if where
464         (values symbol where)
465         (let ((symbol (make-symbol (subseq name 0 length))))
466           (%set-symbol-package symbol package)
467           (cond ((eq package *keyword-package*)
468                  (add-symbol (package-external-symbols package) symbol)
469                  (%set-symbol-value symbol symbol))
470                 (t
471                  (add-symbol (package-internal-symbols package) symbol)))
472           (values symbol nil)))))
473
474 ;;; Check internal and external symbols, then scan down the list
475 ;;; of hashtables for inherited symbols. When an inherited symbol
476 ;;; is found pull that table to the beginning of the list.
477 (defun find-symbol* (string length package)
478   (declare (simple-string string)
479            (type index length))
480   (let* ((hash (%sxhash-simple-substring string length))
481          (ehash (entry-hash length hash)))
482     (declare (type index hash ehash))
483     (with-symbol (found symbol (package-internal-symbols package)
484                         string length hash ehash)
485       (when found
486         (return-from find-symbol* (values symbol :internal))))
487     (with-symbol (found symbol (package-external-symbols package)
488                         string length hash ehash)
489       (when found
490         (return-from find-symbol* (values symbol :external))))
491     (let ((head (package-tables package)))
492       (do ((prev head table)
493            (table (cdr head) (cdr table)))
494           ((null table) (values nil nil))
495         (with-symbol (found symbol (car table) string length hash ehash)
496           (when found
497             (unless (eq prev head)
498               (shiftf (cdr prev) (cdr table) (cdr head) table))
499             (return-from find-symbol* (values symbol :inherited))))))))
500
501 ;;; Similar to Find-Symbol, but only looks for an external symbol.
502 ;;; This is used for fast name-conflict checking in this file and symbol
503 ;;; printing in the printer.
504 (defun find-external-symbol (string package)
505   (declare (simple-string string))
506   (let* ((length (length string))
507          (hash (%sxhash-simple-string string))
508          (ehash (entry-hash length hash)))
509     (declare (type index length hash))
510     (with-symbol (found symbol (package-external-symbols package)
511                         string length hash ehash)
512       (values symbol found))))
513 \f
514 ;;; If we are uninterning a shadowing symbol, then a name conflict can
515 ;;; result, otherwise just nuke the symbol.
516 (defun unintern (symbol &optional (package (sane-package)))
517   #!+sb-doc
518   "Makes Symbol no longer present in Package. If Symbol was present
519   then T is returned, otherwise NIL. If Package is Symbol's home
520   package, then it is made uninterned."
521   (let* ((package (find-undeleted-package-or-lose package))
522          (name (symbol-name symbol))
523          (shadowing-symbols (package-%shadowing-symbols package)))
524     (declare (list shadowing-symbols) (simple-string name))
525
526     ;; If a name conflict is revealed, give use a chance to shadowing-import
527     ;; one of the accessible symbols.
528     (when (member symbol shadowing-symbols)
529       (let ((cset ()))
530         (dolist (p (package-%use-list package))
531           (multiple-value-bind (s w) (find-external-symbol name p)
532             (when w (pushnew s cset))))
533         (when (cdr cset)
534           (loop
535            (cerror
536             "Prompt for a symbol to SHADOWING-IMPORT."
537             "Uninterning symbol ~S causes name conflict among these symbols:~%~S"
538             symbol cset)
539            (write-string "Symbol to shadowing-import: " *query-io*)
540            (let ((sym (read *query-io*)))
541              (cond
542               ((not (symbolp sym))
543                (format *query-io* "~S is not a symbol."))
544               ((not (member sym cset))
545                (format *query-io* "~S is not one of the conflicting symbols."))
546               (t
547                (shadowing-import sym package)
548                (return-from unintern t)))))))
549       (setf (package-%shadowing-symbols package)
550             (remove symbol shadowing-symbols)))
551
552     (multiple-value-bind (s w) (find-symbol name package)
553       (declare (ignore s))
554       (cond ((or (eq w :internal) (eq w :external))
555              (nuke-symbol (if (eq w :internal)
556                               (package-internal-symbols package)
557                               (package-external-symbols package))
558                           name)
559              (if (eq (symbol-package symbol) package)
560                  (%set-symbol-package symbol nil))
561              t)
562             (t nil)))))
563 \f
564 ;;; Take a symbol-or-list-of-symbols and return a list, checking types.
565 (defun symbol-listify (thing)
566   (cond ((listp thing)
567          (dolist (s thing)
568            (unless (symbolp s) (error "~S is not a symbol." s)))
569          thing)
570         ((symbolp thing) (list thing))
571         (t
572          (error "~S is neither a symbol nor a list of symbols." thing))))
573
574 ;;; Like UNINTERN, but if symbol is inherited chases down the package
575 ;;; it is inherited from and uninterns it there. Used for
576 ;;; name-conflict resolution. Shadowing symbols are not uninterned
577 ;;; since they do not cause conflicts.
578 (defun moby-unintern (symbol package)
579   (unless (member symbol (package-%shadowing-symbols package))
580     (or (unintern symbol package)
581         (let ((name (symbol-name symbol)))
582           (multiple-value-bind (s w) (find-symbol name package)
583             (declare (ignore s))
584             (when (eq w :inherited)
585               (dolist (q (package-%use-list package))
586                 (multiple-value-bind (u x) (find-external-symbol name q)
587                   (declare (ignore u))
588                   (when x
589                     (unintern symbol q)
590                     (return t))))))))))
591 \f
592 (defun export (symbols &optional (package (sane-package)))
593   #!+sb-doc
594   "Exports Symbols from Package, checking that no name conflicts result."
595   (let ((package (find-undeleted-package-or-lose package))
596         (syms ()))
597     ;; Punt any symbols that are already external.
598     (dolist (sym (symbol-listify symbols))
599       (multiple-value-bind (s w)
600           (find-external-symbol (symbol-name sym) package)
601         (declare (ignore s))
602         (unless (or w (member sym syms))
603           (push sym syms))))
604     ;; Find symbols and packages with conflicts.
605     (let ((used-by (package-%used-by-list package))
606           (cpackages ())
607           (cset ()))
608       (dolist (sym syms)
609         (let ((name (symbol-name sym)))
610           (dolist (p used-by)
611             (multiple-value-bind (s w) (find-symbol name p)
612               (when (and w (not (eq s sym))
613                          (not (member s (package-%shadowing-symbols p))))
614                 (pushnew sym cset)
615                 (pushnew p cpackages))))))
616       (when cset
617         (restart-case
618             (error
619              'simple-package-error
620              :package package
621              :format-control
622              "Exporting these symbols from the ~A package:~%~S~%~
623               results in name conflicts with these packages:~%~{~A ~}"
624              :format-arguments
625              (list (package-%name package) cset
626                    (mapcar #'package-%name cpackages)))
627           (unintern-conflicting-symbols ()
628            :report "Unintern conflicting symbols."
629            (dolist (p cpackages)
630              (dolist (sym cset)
631                (moby-unintern sym p))))
632           (skip-exporting-these-symbols ()
633            :report "Skip exporting conflicting symbols."
634            (setq syms (nset-difference syms cset))))))
635
636     ;; Check that all symbols are accessible. If not, ask to import them.
637     (let ((missing ())
638           (imports ()))
639       (dolist (sym syms)
640         (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
641           (cond ((not (and w (eq s sym)))
642                  (push sym missing))
643                 ((eq w :inherited)
644                  (push sym imports)))))
645       (when missing
646         (with-simple-restart
647             (continue "Import these symbols into the ~A package."
648               (package-%name package))
649           (error 'simple-package-error
650                  :package package
651                  :format-control
652                  "These symbols are not accessible in the ~A package:~%~S"
653                  :format-arguments
654                  (list (package-%name package) missing)))
655         (import missing package))
656       (import imports package))
657
658     ;; And now, three pages later, we export the suckers.
659     (let ((internal (package-internal-symbols package))
660           (external (package-external-symbols package)))
661       (dolist (sym syms)
662         (nuke-symbol internal (symbol-name sym))
663         (add-symbol external sym)))
664     t))
665 \f
666 ;;; Check that all symbols are accessible, then move from external to internal.
667 (defun unexport (symbols &optional (package (sane-package)))
668   #!+sb-doc
669   "Makes Symbols no longer exported from Package."
670   (let ((package (find-undeleted-package-or-lose package))
671         (syms ()))
672     (dolist (sym (symbol-listify symbols))
673       (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
674         (cond ((or (not w) (not (eq s sym)))
675                (error 'simple-package-error
676                       :package package
677                       :format-control "~S is not accessible in the ~A package."
678                       :format-arguments (list sym (package-%name package))))
679               ((eq w :external) (pushnew sym syms)))))
680
681     (let ((internal (package-internal-symbols package))
682           (external (package-external-symbols package)))
683       (dolist (sym syms)
684         (add-symbol internal sym)
685         (nuke-symbol external (symbol-name sym))))
686     t))
687 \f
688 ;;; Check for name conflict caused by the import and let the user
689 ;;; shadowing-import if there is.
690 (defun import (symbols &optional (package (sane-package)))
691   #!+sb-doc
692   "Make Symbols accessible as internal symbols in Package. If a symbol
693   is already accessible then it has no effect. If a name conflict
694   would result from the importation, then a correctable error is signalled."
695   (let ((package (find-undeleted-package-or-lose package))
696         (symbols (symbol-listify symbols))
697         (syms ())
698         (cset ()))
699     (dolist (sym symbols)
700       (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
701         (cond ((not w)
702                (let ((found (member sym syms :test #'string=)))
703                  (if found
704                      (when (not (eq (car found) sym))
705                        (push sym cset))
706                      (push sym syms))))
707               ((not (eq s sym)) (push sym cset))
708               ((eq w :inherited) (push sym syms)))))
709     (when cset
710       ;; ANSI specifies that this error is correctable.
711       (with-simple-restart
712           (continue "Import these symbols with Shadowing-Import.")
713         (error 'simple-package-error
714                :package package
715                :format-control
716                "Importing these symbols into the ~A package ~
717                 causes a name conflict:~%~S"
718                :format-arguments (list (package-%name package) cset))))
719     ;; Add the new symbols to the internal hashtable.
720     (let ((internal (package-internal-symbols package)))
721       (dolist (sym syms)
722         (add-symbol internal sym)))
723     ;; If any of the symbols are uninterned, make them be owned by Package.
724     (dolist (sym symbols)
725       (unless (symbol-package sym) (%set-symbol-package sym package)))
726     (shadowing-import cset package)))
727 \f
728 ;;; If a conflicting symbol is present, unintern it, otherwise just
729 ;;; stick the symbol in.
730 (defun shadowing-import (symbols &optional (package (sane-package)))
731   #!+sb-doc
732   "Import Symbols into package, disregarding any name conflict. If
733   a symbol of the same name is present, then it is uninterned.
734   The symbols are added to the Package-Shadowing-Symbols."
735   (let* ((package (find-undeleted-package-or-lose package))
736          (internal (package-internal-symbols package)))
737     (dolist (sym (symbol-listify symbols))
738       (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
739         (unless (and w (not (eq w :inherited)) (eq s sym))
740           (when (or (eq w :internal) (eq w :external))
741             ;; If it was shadowed, we don't want UNINTERN to flame out...
742             (setf (package-%shadowing-symbols package)
743                   (remove s (the list (package-%shadowing-symbols package))))
744             (unintern s package))
745           (add-symbol internal sym))
746         (pushnew sym (package-%shadowing-symbols package)))))
747   t)
748
749 (defun shadow (symbols &optional (package (sane-package)))
750   #!+sb-doc
751   "Make an internal symbol in Package with the same name as each of the
752   specified symbols, adding the new symbols to the Package-Shadowing-Symbols.
753   If a symbol with the given name is already present in Package, then
754   the existing symbol is placed in the shadowing symbols list if it is
755   not already present."
756   (let* ((package (find-undeleted-package-or-lose package))
757          (internal (package-internal-symbols package)))
758     (dolist (name (mapcar #'string
759                           (if (listp symbols) symbols (list symbols))))
760       (multiple-value-bind (s w) (find-symbol name package)
761         (when (or (not w) (eq w :inherited))
762           (setq s (make-symbol name))
763           (%set-symbol-package s package)
764           (add-symbol internal s))
765         (pushnew s (package-%shadowing-symbols package)))))
766   t)
767 \f
768 ;;; Do stuff to use a package, with all kinds of fun name-conflict checking.
769 (defun use-package (packages-to-use &optional (package (sane-package)))
770   #!+sb-doc
771   "Add all the Packages-To-Use to the use list for Package so that
772   the external symbols of the used packages are accessible as internal
773   symbols in Package."
774   (let ((packages (package-listify packages-to-use))
775         (package (find-undeleted-package-or-lose package)))
776
777     ;; Loop over each package, USE'ing one at a time...
778     (dolist (pkg packages)
779       (unless (member pkg (package-%use-list package))
780         (let ((cset ())
781               (shadowing-symbols (package-%shadowing-symbols package))
782               (use-list (package-%use-list package)))
783
784           ;;   If the number of symbols already accessible is less than the
785           ;; number to be inherited then it is faster to run the test the
786           ;; other way. This is particularly valuable in the case of
787           ;; a new package USEing Lisp.
788           (cond
789            ((< (+ (package-internal-symbol-count package)
790                   (package-external-symbol-count package)
791                   (let ((res 0))
792                     (dolist (p use-list res)
793                       (incf res (package-external-symbol-count p)))))
794                (package-external-symbol-count pkg))
795             (do-symbols (sym package)
796               (multiple-value-bind (s w)
797                   (find-external-symbol (symbol-name sym) pkg)
798                 (when (and w (not (eq s sym))
799                            (not (member sym shadowing-symbols)))
800                   (push sym cset))))
801             (dolist (p use-list)
802               (do-external-symbols (sym p)
803                 (multiple-value-bind (s w)
804                     (find-external-symbol (symbol-name sym) pkg)
805                   (when (and w (not (eq s sym))
806                              (not (member (find-symbol (symbol-name sym)
807                                                        package)
808                                           shadowing-symbols)))
809                     (push sym cset))))))
810            (t
811             (do-external-symbols (sym pkg)
812               (multiple-value-bind (s w)
813                   (find-symbol (symbol-name sym) package)
814                 (when (and w (not (eq s sym))
815                            (not (member s shadowing-symbols)))
816                   (push s cset))))))
817
818           (when cset
819             (cerror
820              "Unintern the conflicting symbols in the ~2*~A package."
821              "Use'ing package ~A results in name conflicts for these symbols:~%~S"
822              (package-%name pkg) cset (package-%name package))
823             (dolist (s cset) (moby-unintern s package))))
824
825         (push pkg (package-%use-list package))
826         (push (package-external-symbols pkg) (cdr (package-tables package)))
827         (push package (package-%used-by-list pkg)))))
828   t)
829
830 (defun unuse-package (packages-to-unuse &optional (package (sane-package)))
831   #!+sb-doc
832   "Remove PACKAGES-TO-UNUSE from the USE list for PACKAGE."
833   (let ((package (find-undeleted-package-or-lose package)))
834     (dolist (p (package-listify packages-to-unuse))
835       (setf (package-%use-list package)
836             (remove p (the list (package-%use-list package))))
837       (setf (package-tables package)
838             (delete (package-external-symbols p)
839                     (the list (package-tables package))))
840       (setf (package-%used-by-list p)
841             (remove package (the list (package-%used-by-list p)))))
842     t))
843
844 (defun find-all-symbols (string-or-symbol)
845   #!+sb-doc
846   "Return a list of all symbols in the system having the specified name."
847   (let ((string (string string-or-symbol))
848         (res ()))
849     (maphash (lambda (k v)
850                (declare (ignore k))
851                (multiple-value-bind (s w) (find-symbol string v)
852                  (when w (pushnew s res))))
853              *package-names*)
854     res))
855 \f
856 ;;;; APROPOS and APROPOS-LIST
857
858 (defun briefly-describe-symbol (symbol)
859   (fresh-line)
860   (prin1 symbol)
861   (when (boundp symbol)
862     (write-string " (bound)"))
863   (when (fboundp symbol)
864     (write-string " (fbound)")))
865
866 (defun apropos-list (string-designator
867                      &optional
868                      package-designator
869                      external-only)
870   #!+sb-doc
871   "Like APROPOS, except that it returns a list of the symbols found instead
872   of describing them."
873   (if package-designator
874       (let ((package (find-undeleted-package-or-lose package-designator))
875             (string (stringify-name string-designator "APROPOS search"))
876             (result nil))
877         (do-symbols (symbol package)
878           (when (and (eq (symbol-package symbol) package)
879                      (or (not external-only)
880                          (eq (find-symbol (symbol-name symbol) package)
881                              :external))
882                      (search string (symbol-name symbol) :test #'char-equal))
883             (push symbol result)))
884         result)
885       (mapcan (lambda (package)
886                 (apropos-list string-designator package external-only))
887               (list-all-packages))))
888
889 (defun apropos (string-designator &optional package external-only)
890   #!+sb-doc
891   "Briefly describe all symbols which contain the specified STRING.
892   If PACKAGE is supplied then only describe symbols present in
893   that package. If EXTERNAL-ONLY then only describe
894   external symbols in the specified package."
895   ;; Implementing this in terms of APROPOS-LIST keeps things simple at the cost
896   ;; of some unnecessary consing; and the unnecessary consing shouldn't be an
897   ;; issue, since this function is is only useful interactively anyway, and
898   ;; we can cons and GC a lot faster than the typical user can read..
899   (dolist (symbol (apropos-list string-designator package external-only))
900     (briefly-describe-symbol symbol))
901   (values))
902 \f
903 ;;;; final initialization
904
905 ;;;; The cold loader (GENESIS) makes the data structure in
906 ;;;; *!INITIAL-SYMBOLS*. We grovel over it, making the specified
907 ;;;; packages and interning the symbols. For a description of the
908 ;;;; format of *!INITIAL-SYMBOLS*, see the GENESIS source.
909
910 (defvar *!initial-symbols*)
911
912 (!cold-init-forms
913
914   (setq *in-package-init* t)
915
916   (/show0 "about to loop over *!INITIAL-SYMBOLS* to make packages")
917   (dolist (spec *!initial-symbols*)
918     (let* ((pkg (apply #'make-package (first spec)))
919            (internal (package-internal-symbols pkg))
920            (external (package-external-symbols pkg)))
921       (/show0 "back from MAKE-PACKAGE, PACKAGE-NAME=..")
922       (/primitive-print (package-name pkg))
923
924       ;; Put internal symbols in the internal hashtable and set package.
925       (dolist (symbol (second spec))
926         (add-symbol internal symbol)
927         (%set-symbol-package symbol pkg))
928
929       ;; External symbols same, only go in external table.
930       (dolist (symbol (third spec))
931         (add-symbol external symbol)
932         (%set-symbol-package symbol pkg))
933
934       ;; Don't set package for imported symbols.
935       (dolist (symbol (fourth spec))
936         (add-symbol internal symbol))
937       (dolist (symbol (fifth spec))
938         (add-symbol external symbol))
939
940       ;; Put shadowing symbols in the shadowing symbols list.
941       (setf (package-%shadowing-symbols pkg) (sixth spec))))
942
943   ;; FIXME: These assignments are also done at toplevel in
944   ;; boot-extensions.lisp. They should probably only be done once.
945   (/show0 "setting up *CL-PACKAGE* and *KEYWORD-PACKAGE*")
946   (setq *cl-package* (find-package "COMMON-LISP"))
947   (setq *keyword-package* (find-package "KEYWORD"))
948
949   (/show0 "about to MAKUNBOUND *!INITIAL-SYMBOLS*")
950   (makunbound '*!initial-symbols*)       ; (so that it gets GCed)
951
952   ;; Make some other packages that should be around in the cold load.
953   ;; The COMMON-LISP-USER package is required by the ANSI standard,
954   ;; but not completely specified by it, so in the cross-compilation
955   ;; host Lisp it could contain various symbols, USE-PACKAGEs, or
956   ;; nicknames that we don't want in our target SBCL. For that reason,
957   ;; we handle it specially, not dumping the host Lisp version at
958   ;; genesis time..
959   (aver (not (find-package "COMMON-LISP-USER")))
960   ;; ..but instead making our own from scratch here.
961   (/show0 "about to MAKE-PACKAGE COMMON-LISP-USER")
962   (make-package "COMMON-LISP-USER"
963                 :nicknames '("CL-USER")
964                 :use '("COMMON-LISP"
965                        ;; ANSI encourages us to put extension packages
966                        ;; in the USE list of COMMON-LISP-USER.
967                        "SB!ALIEN" "SB!ALIEN" "SB!DEBUG"
968                        "SB!EXT" "SB!GRAY" "SB!PROFILE"))
969
970   ;; Now do the *!DEFERRED-USE-PACKAGES*.
971   (/show0 "about to do *!DEFERRED-USE-PACKAGES*")
972   (dolist (args *!deferred-use-packages*)
973     (apply #'use-package args))
974
975   ;; The Age Of Magic is over, we can behave ANSIly henceforth.
976   (/show0 "about to SETQ *IN-PACKAGE-INIT*")
977   (setq *in-package-init* nil)
978
979   ;; For the kernel core image wizards, set the package to *CL-PACKAGE*.
980   ;;
981   ;; FIXME: We should just set this to (FIND-PACKAGE
982   ;; "COMMON-LISP-USER") once and for all here, instead of setting it
983   ;; once here and resetting it later.
984   (setq *package* *cl-package*))
985 \f
986 (!cold-init-forms
987   (/show0 "done with !PACKAGE-COLD-INIT"))
988
989 (!defun-from-collected-cold-init-forms !package-cold-init)