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