suffix PACKAGE-LOCALLY-NICKNAMED-BY with -LIST
[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 ;;;; Thread safety
32 ;;;;
33 ;;;; ...this could still use work, but the basic idea is:
34 ;;;;
35 ;;;; *PACKAGE-GRAPH-LOCK* is held via WITH-PACKAGE-GRAPH while working on
36 ;;;; package graph, including package -> package links, and interning and
37 ;;;; uninterning symbols.
38 ;;;;
39 ;;;; Hash-table lock on *PACKAGE-NAMES* is held via WITH-PACKAGE-NAMES while
40 ;;;; frobbing name -> package associations.
41 ;;;;
42 ;;;; There should be no deadlocks due to ordering issues between these two, as
43 ;;;; the latter is only held over operations guaranteed to terminate in finite
44 ;;;; time.
45 ;;;;
46 ;;;; Errors may be signalled while holding on to the *PACKAGE-GRAPH-LOCK*,
47 ;;;; which can still lead to pretty damned inconvenient situations -- but
48 ;;;; since FIND-PACKAGE, FIND-SYMBOL from other threads isn't blocked by this,
49 ;;;; the situation isn't *quite* hopeless.
50 ;;;;
51 ;;;; A better long-term solution seems to be in splitting the granularity of
52 ;;;; the *PACKAGE-GRAPH-LOCK* down: for interning a per-package lock should be
53 ;;;; sufficient, though interaction between parallel intern and use-package
54 ;;;; needs to be considered with some care.
55
56 (defvar *package-graph-lock*)
57 (!cold-init-forms
58  (setf *package-graph-lock* (sb!thread:make-mutex :name "Package Graph Lock")))
59
60 (defun call-with-package-graph (function)
61   (declare (function function))
62   ;; FIXME: Since name conflicts can be signalled while holding the
63   ;; mutex, user code can be run leading to lock ordering problems.
64   (sb!thread:with-recursive-lock (*package-graph-lock*)
65     (funcall function)))
66
67 ;;; a map from package names to packages
68 (defvar *package-names*)
69 (declaim (type hash-table *package-names*))
70 (!cold-init-forms
71  (setf *package-names* (make-hash-table :test 'equal :synchronized t)))
72
73 (defmacro with-package-names ((names &key) &body body)
74   `(let ((,names *package-names*))
75      (with-locked-system-table (,names)
76        ,@body)))
77 \f
78 ;;;; PACKAGE-HASHTABLE stuff
79
80 (def!method print-object ((table package-hashtable) stream)
81   (declare (type stream stream))
82   (print-unreadable-object (table stream :type t)
83     (format stream
84             ":SIZE ~S :FREE ~S :DELETED ~S"
85             (package-hashtable-size table)
86             (package-hashtable-free table)
87             (package-hashtable-deleted table))))
88
89 ;;; the maximum load factor we allow in a package hashtable
90 (defconstant +package-rehash-threshold+ 0.75)
91
92 ;;; the load factor desired for a package hashtable when writing a
93 ;;; core image
94 (defconstant +package-hashtable-image-load-factor+ 0.5)
95
96 ;;; Make a package hashtable having a prime number of entries at least
97 ;;; as great as (/ SIZE +PACKAGE-REHASH-THRESHOLD+). If RES is supplied,
98 ;;; then it is destructively modified to produce the result. This is
99 ;;; useful when changing the size, since there are many pointers to
100 ;;; the hashtable.
101 ;;; Actually, the smallest table built here has three entries. This
102 ;;; is necessary because the double hashing step size is calculated
103 ;;; using a division by the table size minus two.
104 (defun make-or-remake-package-hashtable (size
105                                          &optional
106                                          res)
107   (flet ((actual-package-hashtable-size (size)
108            (loop for n of-type fixnum
109               from (logior (ceiling size +package-rehash-threshold+) 1)
110               by 2
111               when (positive-primep n) return n)))
112     (let* ((n (actual-package-hashtable-size size))
113            (size (truncate (* n +package-rehash-threshold+)))
114            (table (make-array n))
115            (hash (make-array n
116                              :element-type '(unsigned-byte 8)
117                              :initial-element 0)))
118       (if res
119           (setf (package-hashtable-table res) table
120                 (package-hashtable-hash res) hash
121                 (package-hashtable-size res) size
122                 (package-hashtable-free res) size
123                 (package-hashtable-deleted res) 0)
124           (setf res (%make-package-hashtable table hash size)))
125       res)))
126
127 ;;; Destructively resize TABLE to have room for at least SIZE entries
128 ;;; and rehash its existing entries.
129 (defun resize-package-hashtable (table size)
130   (let* ((vec (package-hashtable-table table))
131          (hash (package-hashtable-hash table))
132          (len (length vec)))
133     (make-or-remake-package-hashtable size table)
134     (dotimes (i len)
135       (when (> (aref hash i) 1)
136         (add-symbol table (svref vec i))))))
137 \f
138 ;;;; package locking operations, built conditionally on :sb-package-locks
139
140 #!+sb-package-locks
141 (progn
142 (defun package-locked-p (package)
143   #!+sb-doc
144   "Returns T when PACKAGE is locked, NIL otherwise. Signals an error
145 if PACKAGE doesn't designate a valid package."
146   (package-lock (find-undeleted-package-or-lose package)))
147
148 (defun lock-package (package)
149   #!+sb-doc
150   "Locks PACKAGE and returns T. Has no effect if PACKAGE was already
151 locked. Signals an error if PACKAGE is not a valid package designator"
152   (setf (package-lock (find-undeleted-package-or-lose package)) t))
153
154 (defun unlock-package (package)
155   #!+sb-doc
156   "Unlocks PACKAGE and returns T. Has no effect if PACKAGE was already
157 unlocked. Signals an error if PACKAGE is not a valid package designator."
158   (setf (package-lock (find-undeleted-package-or-lose package)) nil)
159   t)
160
161 (defun package-implemented-by-list (package)
162   #!+sb-doc
163   "Returns a list containing the implementation packages of
164 PACKAGE. Signals an error if PACKAGE is not a valid package designator."
165   (package-%implementation-packages (find-undeleted-package-or-lose package)))
166
167 (defun package-implements-list (package)
168   #!+sb-doc
169   "Returns the packages that PACKAGE is an implementation package
170 of. Signals an error if PACKAGE is not a valid package designator."
171   (let ((package (find-undeleted-package-or-lose package)))
172     (loop for x in (list-all-packages)
173           when (member package (package-%implementation-packages x))
174           collect x)))
175
176 (defun add-implementation-package (packages-to-add
177                                    &optional (package *package*))
178   #!+sb-doc
179   "Adds PACKAGES-TO-ADD as implementation packages of PACKAGE. Signals
180 an error if PACKAGE or any of the PACKAGES-TO-ADD is not a valid
181 package designator."
182   (let ((package (find-undeleted-package-or-lose package))
183         (packages-to-add (package-listify packages-to-add)))
184     (setf (package-%implementation-packages package)
185           (union (package-%implementation-packages package)
186                  (mapcar #'find-undeleted-package-or-lose packages-to-add)))))
187
188 (defun remove-implementation-package (packages-to-remove
189                                       &optional (package *package*))
190   #!+sb-doc
191   "Removes PACKAGES-TO-REMOVE from the implementation packages of
192 PACKAGE. Signals an error if PACKAGE or any of the PACKAGES-TO-REMOVE
193 is not a valid package designator."
194   (let ((package (find-undeleted-package-or-lose package))
195         (packages-to-remove (package-listify packages-to-remove)))
196     (setf (package-%implementation-packages package)
197           (nset-difference
198            (package-%implementation-packages package)
199            (mapcar #'find-undeleted-package-or-lose packages-to-remove)))))
200
201 (defmacro with-unlocked-packages ((&rest packages) &body forms)
202   #!+sb-doc
203   "Unlocks PACKAGES for the dynamic scope of the body. Signals an
204 error if any of PACKAGES is not a valid package designator."
205   (with-unique-names (unlocked-packages)
206     `(let (,unlocked-packages)
207       (unwind-protect
208            (progn
209              (dolist (p ',packages)
210                (when (package-locked-p p)
211                  (push p ,unlocked-packages)
212                  (unlock-package p)))
213              ,@forms)
214         (dolist (p ,unlocked-packages)
215           (when (find-package p)
216             (lock-package p)))))))
217
218 (defun package-lock-violation (package &key (symbol nil symbol-p)
219                                format-control format-arguments)
220   (let* ((restart :continue)
221          (cl-violation-p (eq package *cl-package*))
222          (error-arguments
223           (append (list (if symbol-p
224                             'symbol-package-locked-error
225                             'package-locked-error)
226                         :package package
227                         :format-control format-control
228                         :format-arguments format-arguments)
229                   (when symbol-p (list :symbol symbol))
230                   (list :references
231                         (append '((:sbcl :node "Package Locks"))
232                                 (when cl-violation-p
233                                   '((:ansi-cl :section (11 1 2 1 2)))))))))
234     (restart-case
235         (apply #'cerror "Ignore the package lock." error-arguments)
236       (:ignore-all ()
237         :report "Ignore all package locks in the context of this operation."
238         (setf restart :ignore-all))
239       (:unlock-package ()
240         :report "Unlock the package."
241         (setf restart :unlock-package)))
242     (ecase restart
243       (:continue
244        (pushnew package *ignored-package-locks*))
245       (:ignore-all
246        (setf *ignored-package-locks* t))
247       (:unlock-package
248        (unlock-package package)))))
249
250 (defun package-lock-violation-p (package &optional (symbol nil symbolp))
251   ;; KLUDGE: (package-lock package) needs to be before
252   ;; comparison to *package*, since during cold init this gets
253   ;; called before *package* is bound -- but no package should
254   ;; be locked at that point.
255   (and package
256        (package-lock package)
257        ;; In package or implementation package
258        (not (or (eq package *package*)
259                 (member *package* (package-%implementation-packages package))))
260        ;; Runtime disabling
261        (not (eq t *ignored-package-locks*))
262        (or (eq :invalid *ignored-package-locks*)
263            (not (member package *ignored-package-locks*)))
264        ;; declarations for symbols
265        (not (and symbolp (member symbol (disabled-package-locks))))))
266
267 (defun disabled-package-locks ()
268   (if (boundp 'sb!c::*lexenv*)
269       (sb!c::lexenv-disabled-package-locks sb!c::*lexenv*)
270       sb!c::*disabled-package-locks*))
271
272 ) ; progn
273
274 ;;;; more package-locking these are NOPs unless :sb-package-locks is
275 ;;;; in target features. Cross-compiler NOPs for these are in cross-misc.
276
277 ;;; The right way to establish a package lock context is
278 ;;; WITH-SINGLE-PACKAGE-LOCKED-ERROR, defined in early-package.lisp
279 ;;;
280 ;;; Must be used inside the dynamic contour established by
281 ;;; WITH-SINGLE-PACKAGE-LOCKED-ERROR
282 (defun assert-package-unlocked (package &optional format-control
283                                 &rest format-arguments)
284   #!-sb-package-locks
285   (declare (ignore format-control format-arguments))
286   #!+sb-package-locks
287   (when (package-lock-violation-p package)
288     (package-lock-violation package
289                             :format-control format-control
290                             :format-arguments format-arguments))
291   package)
292
293 ;;; Must be used inside the dynamic contour established by
294 ;;; WITH-SINGLE-PACKAGE-LOCKED-ERROR.
295 ;;;
296 ;;; FIXME: Maybe we should establish such contours for he toplevel
297 ;;; and others, so that %set-fdefinition and others could just use
298 ;;; this.
299 (defun assert-symbol-home-package-unlocked (name format)
300   #!-sb-package-locks
301   (declare (ignore format))
302   #!+sb-package-locks
303   (let* ((symbol (etypecase name
304                    (symbol name)
305                    (list (if (and (consp (cdr name))
306                                   (eq 'setf (first name)))
307                              (second name)
308                              ;; Skip lists of length 1, single conses and
309                              ;; (class-predicate foo), etc.
310                              ;; FIXME: MOP and package-lock
311                              ;; interaction needs to be thought about.
312                              (return-from
313                               assert-symbol-home-package-unlocked
314                                name)))))
315          (package (symbol-package symbol)))
316     (when (package-lock-violation-p package symbol)
317       (package-lock-violation package
318                               :symbol symbol
319                               :format-control format
320                               :format-arguments (list name))))
321   name)
322
323 \f
324 ;;;; miscellaneous PACKAGE operations
325
326 (def!method print-object ((package package) stream)
327   (let ((name (package-%name package)))
328     (if name
329         (print-unreadable-object (package stream :type t)
330           (prin1 name stream))
331         (print-unreadable-object (package stream :type t :identity t)
332           (write-string "(deleted)" stream)))))
333
334 ;;; ANSI says (in the definition of DELETE-PACKAGE) that these, and
335 ;;; most other operations, are unspecified for deleted packages. We
336 ;;; just do the easy thing and signal errors in that case.
337 (macrolet ((def (ext real)
338              `(defun ,ext (package-designator)
339                 (,real (find-undeleted-package-or-lose package-designator)))))
340   (def package-nicknames package-%nicknames)
341   (def package-use-list package-%use-list)
342   (def package-used-by-list package-%used-by-list)
343   (def package-shadowing-symbols package-%shadowing-symbols))
344
345 (defun package-local-nicknames (package-designator)
346   "Returns an alist of \(local-nickname . actual-package) describing the
347 nicknames local to the designated package.
348
349 When in the designated package, calls to FIND-PACKAGE with the any of the
350 local-nicknames will return the corresponding actual-package instead. This
351 also affects all implied calls to FIND-PACKAGE, including those performed by
352 the reader.
353
354 When printing a package prefix for a symbol with a package local nickname, the
355 local nickname is used instead of the real name in order to preserve
356 print-read consistency.
357
358 See also: ADD-PACKAGE-LOCAL-NICKNAME, PACKAGE-LOCALLY-NICKNAMED-BY-LIST,
359 REMOVE-PACKAGE-LOCAL-NICKNAME, and the DEFPACKAGE option :LOCAL-NICKNAMES.
360
361 Experimental: interface subject to change."
362   (copy-tree
363    (package-%local-nicknames
364     (find-undeleted-package-or-lose package-designator))))
365
366 (defun package-locally-nicknamed-by-list (package-designator)
367   "Returns a list of packages which have a local nickname for the designated
368 package.
369
370 See also: ADD-PACKAGE-LOCAL-NICKNAME, PACKAGE-LOCAL-NICKNAMES,
371 REMOVE-PACKAGE-LOCAL-NICKNAME, and the DEFPACKAGE option :LOCAL-NICKNAMES.
372
373 Experimental: interface subject to change."
374   (copy-list
375    (package-%locally-nicknamed-by
376     (find-undeleted-package-or-lose package-designator))))
377
378 (defun add-package-local-nickname (local-nickname actual-package
379                                    &optional (package-designator (sane-package)))
380   "Adds LOCAL-NICKNAME for ACTUAL-PACKAGE in the designated package, defaulting
381 to current package. LOCAL-NICKNAME must be a string designator, and
382 ACTUAL-PACKAGE must be a package designator.
383
384 Returns the designated package.
385
386 Signals a continuable error if LOCAL-NICKNAME is already a package local
387 nickname for a different package, or if LOCAL-NICKNAME is one of \"CL\",
388 \"COMMON-LISP\", or, \"KEYWORD\".
389
390 When in the designated package, calls to FIND-PACKAGE with the LOCAL-NICKNAME
391 will return the package the designated ACTUAL-PACKAGE instead. This also
392 affects all implied calls to FIND-PACKAGE, including those performed by the
393 reader.
394
395 When printing a package prefix for a symbol with a package local nickname,
396 local nickname is used instead of the real name in order to preserve
397 print-read consistency.
398
399 See also: PACKAGE-LOCAL-NICKNAMES, PACKAGE-LOCALLY-NICKNAMED-BY-LIST,
400 REMOVE-PACKAGE-LOCAL-NICKNAME, and the DEFPACKAGE option :LOCAL-NICKNAMES.
401
402 Experimental: interface subject to change."
403   (let* ((nick (string local-nickname))
404          (actual (find-package-using-package actual-package nil))
405          (package (find-undeleted-package-or-lose package-designator))
406          (existing (package-%local-nicknames package))
407          (cell (assoc nick existing :test #'string=)))
408     (unless (package-name actual)
409       (error "Cannot add ~A as local nickname for a deleted package: ~S"
410              nick actual))
411     (with-single-package-locked-error
412         (:package package "adding ~A as a local nickname for ~A"
413                   nick actual))
414     (when (member nick '("CL" "COMMON-LISP" "KEYWORD") :test #'string=)
415       (cerror "Continue, use it as local nickname anyways."
416               "Attempt to use ~A as a package local nickname." nick))
417     (when (and cell (neq actual (cdr cell)))
418       (restart-case
419           (error "~@<Cannot add ~A as local nickname for ~A in ~S: already nickname for ~A.~:@>"
420                  nick actual package (cdr cell))
421         (keep-old ()
422           :report (lambda (s)
423                     (format s "Keep ~A as local nicname for ~A."
424                             nick (cdr cell))))
425         (change-nick ()
426           :report (lambda (s)
427                     (format s "Use ~A as local nickname for ~A instead."
428                             nick actual))
429           (let ((old (cdr cell)))
430             (with-package-graph ()
431               (setf (package-%locally-nicknamed-by old)
432                     (delete package (package-%locally-nicknamed-by old)))
433               (push package (package-%locally-nicknamed-by actual))
434               (setf (cdr cell) actual)))))
435       (return-from add-package-local-nickname package))
436     (unless cell
437       (with-package-graph ()
438         (push (cons nick actual) (package-%local-nicknames package))
439         (push package (package-%locally-nicknamed-by actual))))
440     package))
441
442 (defun remove-package-local-nickname (old-nickname
443                                       &optional (package-designator (sane-package)))
444   "If the designated package had OLD-NICKNAME as a local nickname for
445 another package, it is removed. Returns true if the nickname existed and was
446 removed, and NIL otherwise.
447
448 See also: ADD-PACKAGE-LOCAL-NICKNAME, PACKAGE-LOCAL-NICKNAMES,
449 PACKAGE-LOCALLY-NICKNAMED-BY-LIST, and the DEFPACKAGE option :LOCAL-NICKNAMES.
450
451 Experimental: interface subject to change."
452   (let* ((nick (string old-nickname))
453          (package (find-undeleted-package-or-lose package-designator))
454          (existing (package-%local-nicknames package))
455          (cell (assoc nick existing :test #'string=)))
456     (when cell
457       (with-single-package-locked-error
458           (:package package "removing local nickname ~A for ~A"
459                     nick (cdr cell)))
460       (with-package-graph ()
461         (let ((old (cdr cell)))
462           (setf (package-%local-nicknames package) (delete cell existing))
463           (setf (package-%locally-nicknamed-by old)
464                 (delete package (package-%locally-nicknamed-by old)))))
465       t)))
466
467 (defun %package-hashtable-symbol-count (table)
468   (let ((size (the fixnum
469                 (- (package-hashtable-size table)
470                    (package-hashtable-deleted table)))))
471     (the fixnum
472       (- size (package-hashtable-free table)))))
473
474 (defun package-internal-symbol-count (package)
475   (%package-hashtable-symbol-count (package-internal-symbols package)))
476
477 (defun package-external-symbol-count (package)
478   (%package-hashtable-symbol-count (package-external-symbols package)))
479 \f
480 (defvar *package* (error "*PACKAGE* should be initialized in cold load!")
481   #!+sb-doc "the current package")
482 ;;; FIXME: should be declared of type PACKAGE, with no NIL init form,
483 ;;; after I get around to cleaning up DOCUMENTATION
484
485 ;;; This magical variable is T during initialization so that
486 ;;; USE-PACKAGE's of packages that don't yet exist quietly win. Such
487 ;;; packages are thrown onto the list *DEFERRED-USE-PACKAGES* so that
488 ;;; this can be fixed up later.
489 ;;;
490 ;;; FIXME: This could be cleaned up the same way I do it in my package
491 ;;; hacking when setting up the cross-compiler. Then we wouldn't have
492 ;;; this extraneous global variable and annoying runtime tests on
493 ;;; package operations. (*DEFERRED-USE-PACKAGES* would also go away.)
494 (defvar *in-package-init*)
495
496 ;;; pending USE-PACKAGE arguments saved up while *IN-PACKAGE-INIT* is true
497 (defvar *!deferred-use-packages*)
498 (!cold-init-forms
499   (setf *!deferred-use-packages* nil))
500
501 (define-condition bootstrap-package-not-found (condition)
502   ((name :initarg :name :reader bootstrap-package-name)))
503 (defun debootstrap-package (&optional condition)
504   (invoke-restart
505    (find-restart-or-control-error 'debootstrap-package condition)))
506
507 (defun find-package (package-designator)
508   "If PACKAGE-DESIGNATOR is a package, it is returned. Otherwise PACKAGE-DESIGNATOR
509 must be a string designator, in which case the package it names is located and returned.
510
511 As an SBCL extension, the current package may effect the way a package name is
512 resolved: if the current package has local nicknames specified, package names
513 matching those are resolved to the packages associated with them instead.
514
515 Example:
516
517   (defpackage :a)
518   (defpackage :example (:use :cl) (:local-nicknames (:x :a)))
519   (let ((*package* (find-package :example)))
520     (find-package :x)) => #<PACKAGE A>
521
522 See also: ADD-PACKAGE-LOCAL-NICKNAME, PACKAGE-LOCAL-NICKNAMES,
523 REMOVE-PACKAGE-LOCAL-NICKNAME, and the DEFPACKAGE option :LOCAL-NICKNAMES."
524   (find-package-using-package package-designator
525                               (when (boundp '*package*)
526                                 *package*)))
527
528 ;;; This is undocumented and unexported for now, but the idea is that by
529 ;;; making this a generic function then packages with custom package classes
530 ;;; could hook into this to provide their own resolution.
531 (defun find-package-using-package (package-designator base)
532   (flet ((find-package-from-string (string)
533            (declare (type string string))
534            (let* ((nicknames (when base
535                                (package-%local-nicknames base)))
536                   (nicknamed (when nicknames
537                                (cdr (assoc string nicknames :test #'string=))))
538                   (packageoid (or nicknamed (gethash string *package-names*))))
539              (when (and (null packageoid)
540                         (not *in-package-init*) ; KLUDGE
541                         (let ((mismatch (mismatch "SB!" string)))
542                           (and mismatch (= mismatch 3))))
543                (restart-case
544                    (signal 'bootstrap-package-not-found :name string)
545                  (debootstrap-package ()
546                    (return-from find-package-using-package
547                      (if (string= string "SB!XC")
548                          (find-package "COMMON-LISP")
549                          (find-package
550                           (substitute #\- #\! string :count 1)))))))
551              packageoid)))
552     (typecase package-designator
553       (package package-designator)
554       (symbol (find-package-from-string (symbol-name package-designator)))
555       (string (find-package-from-string package-designator))
556       (character (find-package-from-string (string package-designator)))
557       (t (error 'type-error
558                 :datum package-designator
559                 :expected-type '(or character package string symbol))))))
560
561 ;;; Return a list of packages given a package designator or list of
562 ;;; package designators, or die trying.
563 (defun package-listify (thing)
564   (let ((res ()))
565     (dolist (thing (if (listp thing) thing (list thing)) res)
566       (push (find-undeleted-package-or-lose thing) res))))
567
568 ;;; Make a package name into a simple-string.
569 (defun package-namify (n)
570   (stringify-package-designator n))
571
572 ;;; ANSI specifies (in the definition of DELETE-PACKAGE) that PACKAGE-NAME
573 ;;; returns NIL (not an error) for a deleted package, so this is a special
574 ;;; case where we want to use bare %FIND-PACKAGE-OR-LOSE instead of
575 ;;; FIND-UNDELETED-PACKAGE-OR-LOSE.
576 (defun package-name (package-designator)
577   (package-%name (%find-package-or-lose package-designator)))
578 \f
579 ;;;; operations on package hashtables
580
581 ;;; Compute a number from the sxhash of the pname and the length which
582 ;;; must be between 2 and 255.
583 (defmacro entry-hash (length sxhash)
584   `(the fixnum
585         (+ (the fixnum
586                 (rem (the fixnum
587                           (logxor ,length
588                                   ,sxhash
589                                   (the fixnum (ash ,sxhash -8))
590                                   (the fixnum (ash ,sxhash -16))
591                                   (the fixnum (ash ,sxhash -19))))
592                      254))
593            2)))
594 ;;; FIXME: should be wrapped in EVAL-WHEN (COMPILE EXECUTE)
595
596 ;;; Add a symbol to a package hashtable. The symbol is assumed
597 ;;; not to be present.
598 (defun add-symbol (table symbol)
599   (when (zerop (package-hashtable-free table))
600     ;; The hashtable is full. Resize it to be able to hold twice the
601     ;; amount of symbols than it currently contains. The actual new size
602     ;; can be smaller than twice the current size if the table contained
603     ;; deleted entries.
604     (resize-package-hashtable table
605                               (* (- (package-hashtable-size table)
606                                     (package-hashtable-deleted table))
607                                  2)))
608   (let* ((vec (package-hashtable-table table))
609          (hash (package-hashtable-hash table))
610          (len (length vec))
611          (sxhash (%sxhash-simple-string (symbol-name symbol)))
612          (h2 (1+ (rem sxhash (- len 2)))))
613     (declare (fixnum sxhash h2))
614     (do ((i (rem sxhash len) (rem (+ i h2) len)))
615         ((< (the fixnum (aref hash i)) 2)
616          (if (zerop (the fixnum (aref hash i)))
617              (decf (package-hashtable-free table))
618              (decf (package-hashtable-deleted table)))
619          (setf (svref vec i) symbol)
620          (setf (aref hash i)
621                (entry-hash (length (symbol-name symbol))
622                            sxhash)))
623       (declare (fixnum i)))))
624
625 ;;; Resize the package hashtables of all packages so that their load
626 ;;; factor is +PACKAGE-HASHTABLE-IMAGE-LOAD-FACTOR+. Called from
627 ;;; SAVE-LISP-AND-DIE to optimize space usage in the image.
628 (defun tune-hashtable-sizes-of-all-packages ()
629   (flet ((tune-table-size (table)
630            (resize-package-hashtable
631             table
632             (round (* (/ +package-rehash-threshold+
633                          +package-hashtable-image-load-factor+)
634                       (- (package-hashtable-size table)
635                          (package-hashtable-free table)
636                          (package-hashtable-deleted table)))))))
637     (dolist (package (list-all-packages))
638       (tune-table-size (package-internal-symbols package))
639       (tune-table-size (package-external-symbols package)))))
640
641 ;;; Find where the symbol named STRING is stored in TABLE. INDEX-VAR
642 ;;; is bound to the index, or NIL if it is not present. SYMBOL-VAR
643 ;;; is bound to the symbol. LENGTH and HASH are the length and sxhash
644 ;;; of STRING. ENTRY-HASH is the entry-hash of the string and length.
645 (defmacro with-symbol ((index-var symbol-var table string length sxhash
646                                   entry-hash)
647                        &body forms)
648   (let ((vec (gensym)) (hash (gensym)) (len (gensym)) (h2 (gensym))
649         (name (gensym)) (name-len (gensym)) (ehash (gensym)))
650     `(let* ((,vec (package-hashtable-table ,table))
651             (,hash (package-hashtable-hash ,table))
652             (,len (length ,vec))
653             (,h2 (1+ (the index (rem (the hash ,sxhash)
654                                       (the index (- ,len 2)))))))
655        (declare (type index ,len ,h2))
656        (prog ((,index-var (rem (the hash ,sxhash) ,len))
657               ,symbol-var ,ehash)
658          (declare (type (or index null) ,index-var))
659          LOOP
660          (setq ,ehash (aref ,hash ,index-var))
661          (cond ((eql ,ehash ,entry-hash)
662                 (setq ,symbol-var (svref ,vec ,index-var))
663                 (let* ((,name (symbol-name ,symbol-var))
664                        (,name-len (length ,name)))
665                   (declare (type index ,name-len))
666                   (when (and (= ,name-len ,length)
667                              (string= ,string ,name
668                                       :end1 ,length
669                                       :end2 ,name-len))
670                     (go DOIT))))
671                ((zerop ,ehash)
672                 (setq ,index-var nil)
673                 (go DOIT)))
674          (setq ,index-var (+ ,index-var ,h2))
675          (when (>= ,index-var ,len)
676            (setq ,index-var (- ,index-var ,len)))
677          (go LOOP)
678          DOIT
679          (return (progn ,@forms))))))
680
681 ;;; Delete the entry for STRING in TABLE. The entry must exist.
682 (defun nuke-symbol (table string)
683   (declare (simple-string string))
684   (let* ((length (length string))
685          (hash (%sxhash-simple-string string))
686          (ehash (entry-hash length hash)))
687     (declare (type index length)
688              (type hash hash))
689     (with-symbol (index symbol table string length hash ehash)
690       (setf (aref (package-hashtable-hash table) index) 1)
691       (setf (aref (package-hashtable-table table) index) nil)
692       (incf (package-hashtable-deleted table))))
693   ;; If the table is less than one quarter full, halve its size and
694   ;; rehash the entries.
695   (let* ((size (package-hashtable-size table))
696          (deleted (package-hashtable-deleted table))
697          (used (- size
698                   (package-hashtable-free table)
699                   deleted)))
700     (declare (type fixnum size deleted used))
701     (when (< used (truncate size 4))
702       (resize-package-hashtable table (* used 2)))))
703 \f
704 ;;; Enter any new NICKNAMES for PACKAGE into *PACKAGE-NAMES*. If there is a
705 ;;; conflict then give the user a chance to do something about it. Caller is
706 ;;; responsible for having acquired the mutex via WITH-PACKAGES.
707 (defun %enter-new-nicknames (package nicknames)
708   (declare (type list nicknames))
709   (dolist (n nicknames)
710     (let* ((n (package-namify n))
711            (found (with-package-names (names)
712                     (or (gethash n names)
713                         (progn
714                           (setf (gethash n names) package)
715                           (push n (package-%nicknames package))
716                           package)))))
717       (cond ((eq found package))
718             ((string= (the string (package-%name found)) n)
719              (cerror "Ignore this nickname."
720                      'simple-package-error
721                      :package package
722                      :format-control "~S is a package name, so it cannot be a nickname for ~S."
723                      :format-arguments (list n (package-%name package))))
724             (t
725              (cerror "Leave this nickname alone."
726                      'simple-package-error
727                      :package package
728                      :format-control "~S is already a nickname for ~S."
729                      :format-arguments (list n (package-%name found))))))))
730
731 (defun make-package (name &key
732                           (use '#.*default-package-use-list*)
733                           nicknames
734                           (internal-symbols 10)
735                           (external-symbols 10))
736   #!+sb-doc
737   #.(format nil
738      "Make a new package having the specified NAME, NICKNAMES, and USE
739 list. :INTERNAL-SYMBOLS and :EXTERNAL-SYMBOLS are estimates for the number of
740 internal and external symbols which will ultimately be present in the package.
741 The default value of USE is implementation-dependent, and in this
742 implementation it is ~S." *default-package-use-list*)
743   (prog (clobber)
744    :restart
745      (when (find-package name)
746        ;; ANSI specifies that this error is correctable.
747        (cerror "Clobber existing package."
748                "A package named ~S already exists" name)
749        (setf clobber t))
750      (with-package-graph ()
751        ;; Check for race, signal the error outside the lock.
752        (when (and (not clobber) (find-package name))
753          (go :restart))
754        (let* ((name (package-namify name))
755               (package (internal-make-package
756                         :%name name
757                         :internal-symbols (make-or-remake-package-hashtable
758                                            internal-symbols)
759                         :external-symbols (make-or-remake-package-hashtable
760                                            external-symbols))))
761
762          ;; Do a USE-PACKAGE for each thing in the USE list so that checking for
763          ;; conflicting exports among used packages is done.
764          (if *in-package-init*
765              (push (list use package) *!deferred-use-packages*)
766              (use-package use package))
767
768          ;; FIXME: ENTER-NEW-NICKNAMES can fail (ERROR) if nicknames are illegal,
769          ;; which would leave us with possibly-bad side effects from the earlier
770          ;; USE-PACKAGE (e.g. this package on the used-by lists of other packages,
771          ;; but not in *PACKAGE-NAMES*, and possibly import side effects too?).
772          ;; Perhaps this can be solved by just moving ENTER-NEW-NICKNAMES before
773          ;; USE-PACKAGE, but I need to check what kinds of errors can be caused by
774          ;; USE-PACKAGE, too.
775          (%enter-new-nicknames package nicknames)
776          (return (setf (gethash name *package-names*) package))))
777      (bug "never")))
778
779 ;;; Change the name if we can, blast any old nicknames and then
780 ;;; add in any new ones.
781 ;;;
782 ;;; FIXME: ANSI claims that NAME is a package designator (not just a
783 ;;; string designator -- weird). Thus, NAME could
784 ;;; be a package instead of a string. Presumably then we should not change
785 ;;; the package name if NAME is the same package that's referred to by PACKAGE.
786 ;;; If it's a *different* package, we should probably signal an error.
787 ;;; (perhaps (ERROR 'ANSI-WEIRDNESS ..):-)
788 (defun rename-package (package-designator name &optional (nicknames ()))
789   #!+sb-doc
790   "Changes the name and nicknames for a package."
791   (let ((package nil))
792   (tagbody :restart
793        (setq package (find-undeleted-package-or-lose package-designator))
794        (let* ((name (package-namify name))
795             (found (find-package name))
796             (nicks (mapcar #'string nicknames)))
797        (unless (or (not found) (eq found package))
798          (error 'simple-package-error
799                 :package name
800                 :format-control "A package named ~S already exists."
801                 :format-arguments (list name)))
802        (with-single-package-locked-error ()
803          (unless (and (string= name (package-name package))
804                       (null (set-difference nicks (package-nicknames package)
805                                             :test #'string=)))
806            (assert-package-unlocked package "rename as ~A~@[ with nickname~P ~
807                                            ~{~A~^, ~}~]"
808                                     name (length nicks) nicks))
809          (with-package-names (names)
810            ;; Check for race conditions now that we have the lock.
811            (unless (eq package (find-package package-designator))
812              (go :restart))
813            ;; Do the renaming.
814            (remhash (package-%name package) names)
815            (dolist (n (package-%nicknames package))
816              (remhash n names))
817            (setf (package-%name package) name
818                  (gethash name names) package
819                  (package-%nicknames package) ()))
820            (%enter-new-nicknames package nicknames))))
821     package))
822
823 (defun delete-package (package-designator)
824   #!+sb-doc
825   "Delete the package designated by PACKAGE-DESIGNATOR from the package
826   system data structures."
827   (tagbody :restart
828      (let ((package (find-package package-designator)))
829        (cond ((not package)
830               ;; This continuable error is required by ANSI.
831               (cerror
832                "Return ~S."
833                (make-condition
834                 'simple-package-error
835                 :package package-designator
836                 :format-control "There is no package named ~S."
837                 :format-arguments (list package-designator))
838                (return-from delete-package nil)))
839              ((not (package-name package)) ; already deleted
840               (return-from delete-package nil))
841              (t
842               (with-single-package-locked-error
843                   (:package package "deleting package ~A" package)
844                 (let ((use-list (package-used-by-list package)))
845                   (when use-list
846                     ;; This continuable error is specified by ANSI.
847                     (cerror
848                      "Remove dependency in other packages."
849                      (make-condition
850                       'simple-package-error
851                       :package package
852                       :format-control
853                       "~@<Package ~S is used by package~P:~2I~_~S~@:>"
854                       :format-arguments (list (package-name package)
855                                               (length use-list)
856                                               (mapcar #'package-name use-list))))
857                     (dolist (p use-list)
858                       (unuse-package package p))))
859                 (dolist (p (package-implements-list package))
860                   (remove-implementation-package package p))
861                 (with-package-graph ()
862                   ;; Check for races, restart if necessary.
863                   (let ((package2 (find-package package-designator)))
864                     (when (or (neq package package2) (package-used-by-list package2))
865                       (go :restart)))
866                   (dolist (used (package-use-list package))
867                     (unuse-package used package))
868                   (dolist (namer (package-%locally-nicknamed-by package))
869                     (setf (package-%local-nicknames namer)
870                           (delete package (package-%local-nicknames namer) :key #'cdr)))
871                   (setf (package-%locally-nicknamed-by package) nil)
872                   (dolist (cell (package-%local-nicknames package))
873                     (let ((actual (cdr cell)))
874                       (setf (package-%locally-nicknamed-by actual)
875                             (delete package (package-%locally-nicknamed-by actual)))))
876                   (setf (package-%local-nicknames package) nil)
877                   (do-symbols (sym package)
878                     (unintern sym package))
879                   (with-package-names (names)
880                     (remhash (package-name package) names)
881                     (dolist (nick (package-nicknames package))
882                       (remhash nick names))
883                     (setf (package-%name package) nil
884                           ;; Setting PACKAGE-%NAME to NIL is required in order to
885                           ;; make PACKAGE-NAME return NIL for a deleted package as
886                           ;; ANSI requires. Setting the other slots to NIL
887                           ;; and blowing away the PACKAGE-HASHTABLES is just done
888                           ;; for tidiness and to help the GC.
889                           (package-%nicknames package) nil))
890                   (setf (package-%use-list package) nil
891                         (package-tables package) nil
892                         (package-%shadowing-symbols package) nil
893                         (package-internal-symbols package)
894                         (make-or-remake-package-hashtable 0)
895                         (package-external-symbols package)
896                         (make-or-remake-package-hashtable 0)))
897                 (return-from delete-package t)))))))
898
899 (defun list-all-packages ()
900   #!+sb-doc
901   "Return a list of all existing packages."
902   (let ((res ()))
903     (with-package-names (names)
904       (maphash (lambda (k v)
905                  (declare (ignore k))
906                  (pushnew v res))
907                names))
908     res))
909 \f
910 (defun intern (name &optional (package (sane-package)))
911   #!+sb-doc
912   "Return a symbol in PACKAGE having the specified NAME, creating it
913   if necessary."
914   ;; We just simple-stringify the name and call INTERN*, where the real
915   ;; logic is.
916   (let ((name (if (simple-string-p name)
917                   name
918                   (coerce name 'simple-string)))
919         (package (find-undeleted-package-or-lose package)))
920     (declare (simple-string name))
921       (intern* name
922                (length name)
923                package)))
924
925 (defun find-symbol (name &optional (package (sane-package)))
926   #!+sb-doc
927   "Return the symbol named STRING in PACKAGE. If such a symbol is found
928   then the second value is :INTERNAL, :EXTERNAL or :INHERITED to indicate
929   how the symbol is accessible. If no symbol is found then both values
930   are NIL."
931   ;; We just simple-stringify the name and call FIND-SYMBOL*, where the
932   ;; real logic is.
933   (let ((name (if (simple-string-p name) name (coerce name 'simple-string))))
934     (declare (simple-string name))
935     (find-symbol* name
936                   (length name)
937                   (find-undeleted-package-or-lose package))))
938
939 ;;; If the symbol named by the first LENGTH characters of NAME doesn't exist,
940 ;;; then create it, special-casing the keyword package.
941 (defun intern* (name length package &key no-copy)
942   (declare (simple-string name))
943   (multiple-value-bind (symbol where) (find-symbol* name length package)
944     (cond (where
945            (values symbol where))
946           (t
947            ;; Let's try again with a lock: the common case has the
948            ;; symbol already interned, handled by the first leg of the
949            ;; COND, but in case another thread is interning in
950            ;; parallel we need to check after grabbing the lock.
951            (with-package-graph ()
952              (setf (values symbol where) (find-symbol* name length package))
953              (if where
954                  (values symbol where)
955                  (let ((symbol-name (cond (no-copy
956                                            (aver (= (length name) length))
957                                            name)
958                                           (t
959                                            ;; This so that SUBSEQ is inlined,
960                                            ;; because we need it fixed for cold init.
961                                            (string-dispatch
962                                                ((simple-array base-char (*))
963                                                 (simple-array character (*)))
964                                                name
965                                              (declare (optimize speed))
966                                              (subseq name 0 length))))))
967                    (with-single-package-locked-error
968                        (:package package "interning ~A" symbol-name)
969                      (let ((symbol (make-symbol symbol-name)))
970                        (%set-symbol-package symbol package)
971                        (cond
972                          ((eq package *keyword-package*)
973                           (%set-symbol-value symbol symbol)
974                           (add-symbol (package-external-symbols package) symbol))
975                          (t
976                           (add-symbol (package-internal-symbols package) symbol)))
977                        (values symbol nil))))))))))
978
979 ;;; Check internal and external symbols, then scan down the list
980 ;;; of hashtables for inherited symbols.
981 (defun find-symbol* (string length package)
982   (declare (simple-string string)
983            (type index length))
984   (let* ((hash (%sxhash-simple-substring string length))
985          (ehash (entry-hash length hash)))
986     (declare (type hash hash ehash))
987     (with-symbol (found symbol (package-internal-symbols package)
988                         string length hash ehash)
989       (when found
990         (return-from find-symbol* (values symbol :internal))))
991     (with-symbol (found symbol (package-external-symbols package)
992                         string length hash ehash)
993       (when found
994         (return-from find-symbol* (values symbol :external))))
995     (let ((head (package-tables package)))
996       (do ((prev head table)
997            (table (cdr head) (cdr table)))
998           ((null table) (values nil nil))
999         (with-symbol (found symbol (car table) string length hash ehash)
1000           (when found
1001             ;; At this point we used to move the table to the
1002             ;; beginning of the list, probably on the theory that we'd
1003             ;; soon be looking up further items there. Unfortunately
1004             ;; that was very much non-thread safe. Since the failure
1005             ;; mode was nasty (corruption of the package in a way
1006             ;; which would make symbol lookups loop infinitely) and it
1007             ;; would be triggered just by doing reads to a resource
1008             ;; that users can't do their own locking on, that code has
1009             ;; been removed. If we ever add locking to packages,
1010             ;; resurrecting that code might make sense, even though it
1011             ;; didn't seem to have much of an performance effect in
1012             ;; normal use.
1013             ;;
1014             ;; -- JES, 2006-09-13
1015             (return-from find-symbol* (values symbol :inherited))))))))
1016
1017 ;;; Similar to FIND-SYMBOL, but only looks for an external symbol.
1018 ;;; This is used for fast name-conflict checking in this file and symbol
1019 ;;; printing in the printer.
1020 (defun find-external-symbol (string package)
1021   (declare (simple-string string))
1022   (let* ((length (length string))
1023          (hash (%sxhash-simple-string string))
1024          (ehash (entry-hash length hash)))
1025     (declare (type index length)
1026              (type hash hash))
1027     (with-symbol (found symbol (package-external-symbols package)
1028                         string length hash ehash)
1029       (values symbol found))))
1030 \f
1031 (defun print-symbol-with-prefix (stream symbol colon at)
1032   #!+sb-doc
1033   "For use with ~/: Write SYMBOL to STREAM as if it is not accessible from
1034   the current package."
1035   (declare (ignore colon at))
1036   ;; Only keywords should be accessible from the keyword package, and
1037   ;; keywords are always printed with colons, so this guarantees that the
1038   ;; symbol will not be printed without a prefix.
1039   (let ((*package* *keyword-package*))
1040     (write symbol :stream stream :escape t)))
1041
1042 (define-condition name-conflict (reference-condition package-error)
1043   ((function :initarg :function :reader name-conflict-function)
1044    (datum :initarg :datum :reader name-conflict-datum)
1045    (symbols :initarg :symbols :reader name-conflict-symbols))
1046   (:default-initargs :references (list '(:ansi-cl :section (11 1 1 2 5))))
1047   (:report
1048    (lambda (c s)
1049      (format s "~@<~S ~S causes name-conflicts in ~S between the ~
1050                 following symbols:~2I~@:_~
1051                 ~{~/sb-impl::print-symbol-with-prefix/~^, ~}~:@>"
1052              (name-conflict-function c)
1053              (name-conflict-datum c)
1054              (package-error-package c)
1055              (name-conflict-symbols c)))))
1056
1057 (defun name-conflict (package function datum &rest symbols)
1058   (flet ((importp (c)
1059            (declare (ignore c))
1060            (eq 'import function))
1061          (use-or-export-p (c)
1062            (declare (ignore c))
1063            (or (eq 'use-package function)
1064                (eq 'export function)))
1065          (old-symbol ()
1066            (car (remove datum symbols))))
1067     (let ((pname (package-name package)))
1068       (restart-case
1069           (error 'name-conflict :package package :symbols symbols
1070                                 :function function :datum datum)
1071         ;; USE-PACKAGE and EXPORT
1072         (keep-old ()
1073           :report (lambda (s)
1074                     (ecase function
1075                       (export
1076                        (format s "Keep ~S accessible in ~A (shadowing ~S)."
1077                                (old-symbol) pname datum))
1078                       (use-package
1079                        (format s "Keep symbols already accessible ~A (shadowing others)."
1080                                pname))))
1081           :test use-or-export-p
1082           (dolist (s (remove-duplicates symbols :test #'string=))
1083             (shadow (symbol-name s) package)))
1084         (take-new ()
1085           :report (lambda (s)
1086                     (ecase function
1087                       (export
1088                        (format s "Make ~S accessible in ~A (uninterning ~S)."
1089                                datum pname (old-symbol)))
1090                       (use-package
1091                        (format s "Make newly exposed symbols accessible in ~A, ~
1092                                   uninterning old ones."
1093                                pname))))
1094           :test use-or-export-p
1095           (dolist (s symbols)
1096             (when (eq s (find-symbol (symbol-name s) package))
1097               (unintern s package))))
1098         ;; IMPORT
1099         (shadowing-import-it ()
1100           :report (lambda (s)
1101                     (format s "Shadowing-import ~S, uninterning ~S."
1102                             datum (old-symbol)))
1103           :test importp
1104           (shadowing-import datum package))
1105         (dont-import-it ()
1106           :report (lambda (s)
1107                     (format s "Don't import ~S, keeping ~S."
1108                             datum
1109                             (car (remove datum symbols))))
1110           :test importp)
1111         ;; General case. This is exposed via SB-EXT.
1112         (resolve-conflict (chosen-symbol)
1113           :report "Resolve conflict."
1114           :interactive
1115           (lambda ()
1116             (let* ((len (length symbols))
1117                    (nlen (length (write-to-string len :base 10)))
1118                    (*print-pretty* t))
1119               (format *query-io* "~&~@<Select a symbol to be made accessible in ~
1120                               package ~A:~2I~@:_~{~{~V,' D. ~
1121                               ~/sb-impl::print-symbol-with-prefix/~}~@:_~}~
1122                               ~@:>"
1123                       (package-name package)
1124                       (loop for s in symbols
1125                             for i upfrom 1
1126                             collect (list nlen i s)))
1127               (loop
1128                 (format *query-io* "~&Enter an integer (between 1 and ~D): " len)
1129                 (finish-output *query-io*)
1130                 (let ((i (parse-integer (read-line *query-io*) :junk-allowed t)))
1131                   (when (and i (<= 1 i len))
1132                     (return (list (nth (1- i) symbols))))))))
1133           (multiple-value-bind (package-symbol status)
1134               (find-symbol (symbol-name chosen-symbol) package)
1135             (let* ((accessiblep status)     ; never NIL here
1136                    (presentp (and accessiblep
1137                                   (not (eq :inherited status)))))
1138               (ecase function
1139                 ((unintern)
1140                  (if presentp
1141                      (if (eq package-symbol chosen-symbol)
1142                          (shadow (list package-symbol) package)
1143                          (shadowing-import (list chosen-symbol) package))
1144                      (shadowing-import (list chosen-symbol) package)))
1145                 ((use-package export)
1146                  (if presentp
1147                      (if (eq package-symbol chosen-symbol)
1148                          (shadow (list package-symbol) package) ; CLHS 11.1.1.2.5
1149                          (if (eq (symbol-package package-symbol) package)
1150                              (unintern package-symbol package) ; CLHS 11.1.1.2.5
1151                              (shadowing-import (list chosen-symbol) package)))
1152                      (shadowing-import (list chosen-symbol) package)))
1153                 ((import)
1154                  (if presentp
1155                      (if (eq package-symbol chosen-symbol)
1156                          nil                ; re-importing the same symbol
1157                          (shadowing-import (list chosen-symbol) package))
1158                      (shadowing-import (list chosen-symbol) package)))))))))))
1159
1160 ;;; If we are uninterning a shadowing symbol, then a name conflict can
1161 ;;; result, otherwise just nuke the symbol.
1162 (defun unintern (symbol &optional (package (sane-package)))
1163   #!+sb-doc
1164   "Makes SYMBOL no longer present in PACKAGE. If SYMBOL was present then T is
1165 returned, otherwise NIL. If PACKAGE is SYMBOL's home package, then it is made
1166 uninterned."
1167   (with-package-graph ()
1168     (let* ((package (find-undeleted-package-or-lose package))
1169            (name (symbol-name symbol))
1170            (shadowing-symbols (package-%shadowing-symbols package)))
1171       (declare (list shadowing-symbols))
1172
1173       (with-single-package-locked-error ()
1174         (when (find-symbol name package)
1175           (assert-package-unlocked package "uninterning ~A" name))
1176
1177         ;; If a name conflict is revealed, give us a chance to
1178         ;; shadowing-import one of the accessible symbols.
1179         (when (member symbol shadowing-symbols)
1180           (let ((cset ()))
1181             (dolist (p (package-%use-list package))
1182               (multiple-value-bind (s w) (find-external-symbol name p)
1183                 (when w (pushnew s cset))))
1184             (when (cdr cset)
1185               (apply #'name-conflict package 'unintern symbol cset)
1186               (return-from unintern t)))
1187           (setf (package-%shadowing-symbols package)
1188                 (remove symbol shadowing-symbols)))
1189
1190         (multiple-value-bind (s w) (find-symbol name package)
1191           (cond ((not (eq symbol s)) nil)
1192                 ((or (eq w :internal) (eq w :external))
1193                  (nuke-symbol (if (eq w :internal)
1194                                   (package-internal-symbols package)
1195                                   (package-external-symbols package))
1196                               name)
1197                  (if (eq (symbol-package symbol) package)
1198                      (%set-symbol-package symbol nil))
1199                  t)
1200                 (t nil)))))))
1201 \f
1202 ;;; Take a symbol-or-list-of-symbols and return a list, checking types.
1203 (defun symbol-listify (thing)
1204   (cond ((listp thing)
1205          (dolist (s thing)
1206            (unless (symbolp s) (error "~S is not a symbol." s)))
1207          thing)
1208         ((symbolp thing) (list thing))
1209         (t
1210          (error "~S is neither a symbol nor a list of symbols." thing))))
1211
1212 (defun string-listify (thing)
1213   (mapcar #'string (if (listp thing)
1214                        thing
1215                        (list thing))))
1216
1217 ;;; This is like UNINTERN, except if SYMBOL is inherited, it chases
1218 ;;; down the package it is inherited from and uninterns it there. Used
1219 ;;; for name-conflict resolution. Shadowing symbols are not uninterned
1220 ;;; since they do not cause conflicts.
1221 (defun moby-unintern (symbol package)
1222   (unless (member symbol (package-%shadowing-symbols package))
1223     (or (unintern symbol package)
1224         (let ((name (symbol-name symbol)))
1225           (multiple-value-bind (s w) (find-symbol name package)
1226             (declare (ignore s))
1227             (when (eq w :inherited)
1228               (dolist (q (package-%use-list package))
1229                 (multiple-value-bind (u x) (find-external-symbol name q)
1230                   (declare (ignore u))
1231                   (when x
1232                     (unintern symbol q)
1233                     (return t))))))))))
1234 \f
1235 (defun export (symbols &optional (package (sane-package)))
1236   #!+sb-doc
1237   "Exports SYMBOLS from PACKAGE, checking that no name conflicts result."
1238   (with-package-graph ()
1239     (let ((package (find-undeleted-package-or-lose package))
1240           (symbols (symbol-listify symbols))
1241           (syms ()))
1242       ;; Punt any symbols that are already external.
1243       (dolist (sym symbols)
1244         (multiple-value-bind (s w)
1245             (find-external-symbol (symbol-name sym) package)
1246           (declare (ignore s))
1247           (unless (or w (member sym syms))
1248             (push sym syms))))
1249       (with-single-package-locked-error ()
1250         (when syms
1251           (assert-package-unlocked package "exporting symbol~P ~{~A~^, ~}"
1252                                    (length syms) syms))
1253         ;; Find symbols and packages with conflicts.
1254         (let ((used-by (package-%used-by-list package)))
1255           (dolist (sym syms)
1256             (let ((name (symbol-name sym)))
1257               (dolist (p used-by)
1258                 (multiple-value-bind (s w) (find-symbol name p)
1259                   (when (and w
1260                              (not (eq s sym))
1261                              (not (member s (package-%shadowing-symbols p))))
1262                     ;; Beware: the name conflict is in package P, not in
1263                     ;; PACKAGE.
1264                     (name-conflict p 'export sym sym s)))))))
1265         ;; Check that all symbols are accessible. If not, ask to import them.
1266         (let ((missing ())
1267               (imports ()))
1268           (dolist (sym syms)
1269             (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
1270               (cond ((not (and w (eq s sym)))
1271                      (push sym missing))
1272                     ((eq w :inherited)
1273                      (push sym imports)))))
1274           (when missing
1275             (cerror
1276              "~S these symbols into the ~A package."
1277              (make-condition
1278               'simple-package-error
1279               :package package
1280               :format-control
1281               "~@<These symbols are not accessible in the ~A package:~2I~_~S~@:>"
1282               :format-arguments (list (package-%name package) missing))
1283              'import (package-%name package))
1284             (import missing package))
1285           (import imports package))
1286
1287         ;; And now, three pages later, we export the suckers.
1288         (let ((internal (package-internal-symbols package))
1289               (external (package-external-symbols package)))
1290           (dolist (sym syms)
1291             (nuke-symbol internal (symbol-name sym))
1292             (add-symbol external sym))))
1293       t)))
1294 \f
1295 ;;; Check that all symbols are accessible, then move from external to internal.
1296 (defun unexport (symbols &optional (package (sane-package)))
1297   #!+sb-doc
1298   "Makes SYMBOLS no longer exported from PACKAGE."
1299   (with-package-graph ()
1300     (let ((package (find-undeleted-package-or-lose package))
1301           (symbols (symbol-listify symbols))
1302           (syms ()))
1303       (dolist (sym symbols)
1304         (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
1305           (cond ((or (not w) (not (eq s sym)))
1306                  (error 'simple-package-error
1307                         :package package
1308                         :format-control "~S is not accessible in the ~A package."
1309                         :format-arguments (list sym (package-%name package))))
1310                 ((eq w :external) (pushnew sym syms)))))
1311       (with-single-package-locked-error ()
1312         (when syms
1313           (assert-package-unlocked package "unexporting symbol~P ~{~A~^, ~}"
1314                                    (length syms) syms))
1315         (let ((internal (package-internal-symbols package))
1316               (external (package-external-symbols package)))
1317           (dolist (sym syms)
1318             (add-symbol internal sym)
1319             (nuke-symbol external (symbol-name sym)))))
1320       t)))
1321 \f
1322 ;;; Check for name conflict caused by the import and let the user
1323 ;;; shadowing-import if there is.
1324 (defun import (symbols &optional (package (sane-package)))
1325   #!+sb-doc
1326   "Make SYMBOLS accessible as internal symbols in PACKAGE. If a symbol is
1327 already accessible then it has no effect. If a name conflict would result from
1328 the importation, then a correctable error is signalled."
1329   (with-package-graph ()
1330     (let* ((package (find-undeleted-package-or-lose package))
1331            (symbols (symbol-listify symbols))
1332            (homeless (remove-if #'symbol-package symbols))
1333            (syms ()))
1334       (with-single-package-locked-error ()
1335         (dolist (sym symbols)
1336           (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
1337             (cond ((not w)
1338                    (let ((found (member sym syms :test #'string=)))
1339                      (if found
1340                          (when (not (eq (car found) sym))
1341                            (setf syms (remove (car found) syms))
1342                            (name-conflict package 'import sym sym (car found)))
1343                          (push sym syms))))
1344                   ((not (eq s sym))
1345                    (name-conflict package 'import sym sym s))
1346                   ((eq w :inherited) (push sym syms)))))
1347         (when (or homeless syms)
1348           (let ((union (delete-duplicates (append homeless syms))))
1349             (assert-package-unlocked package "importing symbol~P ~{~A~^, ~}"
1350                                      (length union) union)))
1351         ;; Add the new symbols to the internal hashtable.
1352         (let ((internal (package-internal-symbols package)))
1353           (dolist (sym syms)
1354             (add-symbol internal sym)))
1355         ;; If any of the symbols are uninterned, make them be owned by PACKAGE.
1356         (dolist (sym homeless)
1357           (%set-symbol-package sym package))
1358         t))))
1359 \f
1360 ;;; If a conflicting symbol is present, unintern it, otherwise just
1361 ;;; stick the symbol in.
1362 (defun shadowing-import (symbols &optional (package (sane-package)))
1363   #!+sb-doc
1364   "Import SYMBOLS into package, disregarding any name conflict. If
1365   a symbol of the same name is present, then it is uninterned."
1366   (with-package-graph ()
1367     (let* ((package (find-undeleted-package-or-lose package))
1368            (internal (package-internal-symbols package))
1369            (symbols (symbol-listify symbols))
1370            (lock-asserted-p nil))
1371       (with-single-package-locked-error ()
1372         (dolist (sym symbols)
1373           (multiple-value-bind (s w) (find-symbol (symbol-name sym) package)
1374             (unless (or lock-asserted-p
1375                         (and (eq s sym)
1376                              (member s (package-shadowing-symbols package))))
1377               (assert-package-unlocked package "shadowing-importing symbol~P ~
1378                                            ~{~A~^, ~}" (length symbols) symbols)
1379               (setf lock-asserted-p t))
1380             (unless (and w (not (eq w :inherited)) (eq s sym))
1381               (when (or (eq w :internal) (eq w :external))
1382                 ;; If it was shadowed, we don't want UNINTERN to flame out...
1383                 (setf (package-%shadowing-symbols package)
1384                       (remove s (the list (package-%shadowing-symbols package))))
1385                 (unintern s package))
1386               (add-symbol internal sym))
1387             (pushnew sym (package-%shadowing-symbols package)))))))
1388   t)
1389
1390 (defun shadow (symbols &optional (package (sane-package)))
1391   #!+sb-doc
1392   "Make an internal symbol in PACKAGE with the same name as each of the
1393 specified SYMBOLS. If a symbol with the given name is already present in
1394 PACKAGE, then the existing symbol is placed in the shadowing symbols list if
1395 it is not already present."
1396   (with-package-graph ()
1397     (let* ((package (find-undeleted-package-or-lose package))
1398            (internal (package-internal-symbols package))
1399            (symbols (string-listify symbols))
1400            (lock-asserted-p nil))
1401       (flet ((present-p (w)
1402                (and w (not (eq w :inherited)))))
1403         (with-single-package-locked-error ()
1404           (dolist (name symbols)
1405             (multiple-value-bind (s w) (find-symbol name package)
1406               (unless (or lock-asserted-p
1407                           (and (present-p w)
1408                                (member s (package-shadowing-symbols package))))
1409                 (assert-package-unlocked package "shadowing symbol~P ~{~A~^, ~}"
1410                                          (length symbols) symbols)
1411                 (setf lock-asserted-p t))
1412               (unless (present-p w)
1413                 (setq s (make-symbol name))
1414                 (%set-symbol-package s package)
1415                 (add-symbol internal s))
1416               (pushnew s (package-%shadowing-symbols package))))))))
1417   t)
1418 \f
1419 ;;; Do stuff to use a package, with all kinds of fun name-conflict checking.
1420 (defun use-package (packages-to-use &optional (package (sane-package)))
1421   #!+sb-doc
1422   "Add all the PACKAGES-TO-USE to the use list for PACKAGE so that the
1423 external symbols of the used packages are accessible as internal symbols in
1424 PACKAGE."
1425   (with-package-graph ()
1426     (let ((packages (package-listify packages-to-use))
1427           (package (find-undeleted-package-or-lose package)))
1428
1429       ;; Loop over each package, USE'ing one at a time...
1430       (with-single-package-locked-error ()
1431         (dolist (pkg packages)
1432           (unless (member pkg (package-%use-list package))
1433             (assert-package-unlocked package "using package~P ~{~A~^, ~}"
1434                                      (length packages) packages)
1435             (let ((shadowing-symbols (package-%shadowing-symbols package))
1436                   (use-list (package-%use-list package)))
1437
1438               ;; If the number of symbols already accessible is less
1439               ;; than the number to be inherited then it is faster to
1440               ;; run the test the other way. This is particularly
1441               ;; valuable in the case of a new package USEing
1442               ;; COMMON-LISP.
1443               (cond
1444                 ((< (+ (package-internal-symbol-count package)
1445                        (package-external-symbol-count package)
1446                        (let ((res 0))
1447                          (dolist (p use-list res)
1448                            (incf res (package-external-symbol-count p)))))
1449                     (package-external-symbol-count pkg))
1450                  (do-symbols (sym package)
1451                    (multiple-value-bind (s w)
1452                        (find-external-symbol (symbol-name sym) pkg)
1453                      (when (and w
1454                                 (not (eq s sym))
1455                                 (not (member sym shadowing-symbols)))
1456                        (name-conflict package 'use-package pkg sym s))))
1457                  (dolist (p use-list)
1458                    (do-external-symbols (sym p)
1459                      (multiple-value-bind (s w)
1460                          (find-external-symbol (symbol-name sym) pkg)
1461                        (when (and w
1462                                   (not (eq s sym))
1463                                   (not (member
1464                                         (find-symbol (symbol-name sym) package)
1465                                         shadowing-symbols)))
1466                          (name-conflict package 'use-package pkg sym s))))))
1467                 (t
1468                  (do-external-symbols (sym pkg)
1469                    (multiple-value-bind (s w)
1470                        (find-symbol (symbol-name sym) package)
1471                      (when (and w
1472                                 (not (eq s sym))
1473                                 (not (member s shadowing-symbols)))
1474                        (name-conflict package 'use-package pkg sym s)))))))
1475
1476             (push pkg (package-%use-list package))
1477             (push (package-external-symbols pkg) (cdr (package-tables package)))
1478             (push package (package-%used-by-list pkg)))))))
1479   t)
1480
1481 (defun unuse-package (packages-to-unuse &optional (package (sane-package)))
1482   #!+sb-doc
1483   "Remove PACKAGES-TO-UNUSE from the USE list for PACKAGE."
1484   (with-package-graph ()
1485     (let ((package (find-undeleted-package-or-lose package))
1486           (packages (package-listify packages-to-unuse)))
1487       (with-single-package-locked-error ()
1488         (dolist (p packages)
1489           (when (member p (package-use-list package))
1490             (assert-package-unlocked package "unusing package~P ~{~A~^, ~}"
1491                                      (length packages) packages))
1492           (setf (package-%use-list package)
1493                 (remove p (the list (package-%use-list package))))
1494           (setf (package-tables package)
1495                 (delete (package-external-symbols p)
1496                         (the list (package-tables package))))
1497           (setf (package-%used-by-list p)
1498                 (remove package (the list (package-%used-by-list p))))))
1499       t)))
1500
1501 (defun find-all-symbols (string-or-symbol)
1502   #!+sb-doc
1503   "Return a list of all symbols in the system having the specified name."
1504   (let ((string (string string-or-symbol))
1505         (res ()))
1506     (with-package-names (names)
1507       (maphash (lambda (k v)
1508                  (declare (ignore k))
1509                  (multiple-value-bind (s w) (find-symbol string v)
1510                    (when w (pushnew s res))))
1511                names))
1512     res))
1513 \f
1514 ;;;; APROPOS and APROPOS-LIST
1515
1516 (defun briefly-describe-symbol (symbol)
1517   (fresh-line)
1518   (prin1 symbol)
1519   (when (boundp symbol)
1520     (write-string " (bound)"))
1521   (when (fboundp symbol)
1522     (write-string " (fbound)")))
1523
1524 (defun apropos-list (string-designator
1525                      &optional
1526                      package-designator
1527                      external-only)
1528   #!+sb-doc
1529   "Like APROPOS, except that it returns a list of the symbols found instead
1530   of describing them."
1531   (if package-designator
1532       (let ((package (find-undeleted-package-or-lose package-designator))
1533             (string (stringify-string-designator string-designator))
1534             (result nil))
1535         (do-symbols (symbol package)
1536           (when (and (eq (symbol-package symbol) package)
1537                      (or (not external-only)
1538                          (eq (nth-value 1 (find-symbol (symbol-name symbol)
1539                                                        package))
1540                              :external))
1541                      (search string (symbol-name symbol) :test #'char-equal))
1542             (push symbol result)))
1543         (sort result #'string-lessp))
1544       (mapcan (lambda (package)
1545                 (apropos-list string-designator package external-only))
1546               (sort (list-all-packages) #'string-lessp :key #'package-name))))
1547
1548 (defun apropos (string-designator &optional package external-only)
1549   #!+sb-doc
1550   "Briefly describe all symbols which contain the specified STRING.
1551   If PACKAGE is supplied then only describe symbols present in
1552   that package. If EXTERNAL-ONLY then only describe
1553   external symbols in the specified package."
1554   ;; Implementing this in terms of APROPOS-LIST keeps things simple at the cost
1555   ;; of some unnecessary consing; and the unnecessary consing shouldn't be an
1556   ;; issue, since this function is is only useful interactively anyway, and
1557   ;; we can cons and GC a lot faster than the typical user can read..
1558   (dolist (symbol (apropos-list string-designator package external-only))
1559     (briefly-describe-symbol symbol))
1560   (values))
1561 \f
1562 ;;;; final initialization
1563
1564 ;;;; The cold loader (GENESIS) makes the data structure in
1565 ;;;; *!INITIAL-SYMBOLS*. We grovel over it, making the specified
1566 ;;;; packages and interning the symbols. For a description of the
1567 ;;;; format of *!INITIAL-SYMBOLS*, see the GENESIS source.
1568
1569 (defvar *!initial-symbols*)
1570
1571 (!cold-init-forms
1572
1573   (setq *in-package-init* t)
1574
1575   (/show0 "about to loop over *!INITIAL-SYMBOLS* to make packages")
1576   (dolist (spec *!initial-symbols*)
1577     (let* ((pkg (apply #'make-package (first spec)))
1578            (internal (package-internal-symbols pkg))
1579            (external (package-external-symbols pkg)))
1580       (/show0 "back from MAKE-PACKAGE, PACKAGE-NAME=..")
1581       (/primitive-print (package-name pkg))
1582
1583       ;; Put internal symbols in the internal hashtable and set package.
1584       (dolist (symbol (second spec))
1585         (add-symbol internal symbol)
1586         (%set-symbol-package symbol pkg))
1587
1588       ;; External symbols same, only go in external table.
1589       (dolist (symbol (third spec))
1590         (add-symbol external symbol)
1591         (%set-symbol-package symbol pkg))
1592
1593       ;; Don't set package for imported symbols.
1594       (dolist (symbol (fourth spec))
1595         (add-symbol internal symbol))
1596       (dolist (symbol (fifth spec))
1597         (add-symbol external symbol))
1598
1599       ;; Put shadowing symbols in the shadowing symbols list.
1600       (setf (package-%shadowing-symbols pkg) (sixth spec))
1601       ;; Set the package documentation
1602       (setf (package-doc-string pkg) (seventh spec))))
1603
1604   ;; FIXME: These assignments are also done at toplevel in
1605   ;; boot-extensions.lisp. They should probably only be done once.
1606   (/show0 "setting up *CL-PACKAGE* and *KEYWORD-PACKAGE*")
1607   (setq *cl-package* (find-package "COMMON-LISP"))
1608   (setq *keyword-package* (find-package "KEYWORD"))
1609
1610   (/show0 "about to MAKUNBOUND *!INITIAL-SYMBOLS*")
1611   (%makunbound '*!initial-symbols*)       ; (so that it gets GCed)
1612
1613   ;; Make some other packages that should be around in the cold load.
1614   ;; The COMMON-LISP-USER package is required by the ANSI standard,
1615   ;; but not completely specified by it, so in the cross-compilation
1616   ;; host Lisp it could contain various symbols, USE-PACKAGEs, or
1617   ;; nicknames that we don't want in our target SBCL. For that reason,
1618   ;; we handle it specially, not dumping the host Lisp version at
1619   ;; genesis time..
1620   (aver (not (find-package "COMMON-LISP-USER")))
1621   ;; ..but instead making our own from scratch here.
1622   (/show0 "about to MAKE-PACKAGE COMMON-LISP-USER")
1623   (make-package "COMMON-LISP-USER"
1624                 :nicknames '("CL-USER")
1625                 :use '("COMMON-LISP"
1626                        ;; ANSI encourages us to put extension packages
1627                        ;; in the USE list of COMMON-LISP-USER.
1628                        "SB!ALIEN" "SB!ALIEN" "SB!DEBUG"
1629                        "SB!EXT" "SB!GRAY" "SB!PROFILE"))
1630
1631   ;; Now do the *!DEFERRED-USE-PACKAGES*.
1632   (/show0 "about to do *!DEFERRED-USE-PACKAGES*")
1633   (dolist (args *!deferred-use-packages*)
1634     (apply #'use-package args))
1635
1636   ;; The Age Of Magic is over, we can behave ANSIly henceforth.
1637   (/show0 "about to SETQ *IN-PACKAGE-INIT*")
1638   (setq *in-package-init* nil)
1639
1640   ;; For the kernel core image wizards, set the package to *CL-PACKAGE*.
1641   ;;
1642   ;; FIXME: We should just set this to (FIND-PACKAGE
1643   ;; "COMMON-LISP-USER") once and for all here, instead of setting it
1644   ;; once here and resetting it later.
1645   (setq *package* *cl-package*))
1646 \f
1647 (!cold-init-forms
1648   (/show0 "done with !PACKAGE-COLD-INIT"))
1649
1650 (!defun-from-collected-cold-init-forms !package-cold-init)