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