Fix typos in docstrings and function names.
[sbcl.git] / src / code / target-pathname.lisp
1 ;;;; machine/filesystem-independent pathname functions
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13
14 #!-sb-fluid (declaim (freeze-type logical-pathname logical-host))
15 \f
16 ;;; To be initialized in unix/win32-pathname.lisp
17 (defvar *physical-host*)
18
19 (defun make-host-load-form (host)
20   (declare (ignore host))
21   '*physical-host*)
22
23 ;;; Return a value suitable, e.g., for preinitializing
24 ;;; *DEFAULT-PATHNAME-DEFAULTS* before *DEFAULT-PATHNAME-DEFAULTS* is
25 ;;; initialized (at which time we can't safely call e.g. #'PATHNAME).
26 (defun make-trivial-default-pathname ()
27   (%make-pathname *physical-host* nil nil nil nil :newest))
28 \f
29 ;;; pathname methods
30
31 (def!method print-object ((pathname pathname) stream)
32   (let ((namestring (handler-case (namestring pathname)
33                       (error nil))))
34     (if namestring
35         (format stream
36                 (if (or *print-readably* *print-escape*)
37                     "#P~S"
38                     "~A")
39                 (coerce namestring '(simple-array character (*))))
40         (print-unreadable-object (pathname stream :type t)
41           (format stream
42                   "~@<(with no namestring) ~_:HOST ~S ~_:DEVICE ~S ~_:DIRECTORY ~S ~
43                   ~_:NAME ~S ~_:TYPE ~S ~_:VERSION ~S~:>"
44                   (%pathname-host pathname)
45                   (%pathname-device pathname)
46                   (%pathname-directory pathname)
47                   (%pathname-name pathname)
48                   (%pathname-type pathname)
49                   (%pathname-version pathname))))))
50
51 (def!method make-load-form ((pathname pathname) &optional environment)
52   (make-load-form-saving-slots pathname :environment environment))
53 \f
54 ;;; A pathname is logical if the host component is a logical host.
55 ;;; This constructor is used to make an instance of the correct type
56 ;;; from parsed arguments.
57 (defun %make-maybe-logical-pathname (host device directory name type version)
58   ;; We canonicalize logical pathname components to uppercase. ANSI
59   ;; doesn't strictly require this, leaving it up to the implementor;
60   ;; but the arguments given in the X3J13 cleanup issue
61   ;; PATHNAME-LOGICAL:ADD seem compelling: we should canonicalize the
62   ;; case, and uppercase is the ordinary way to do that.
63   (flet ((upcase-maybe (x) (typecase x (string (logical-word-or-lose x)) (t x))))
64     (if (typep host 'logical-host)
65         (%make-logical-pathname host
66                                 :unspecific
67                                 (mapcar #'upcase-maybe directory)
68                                 (upcase-maybe name)
69                                 (upcase-maybe type)
70                                 version)
71         (progn
72           (aver (eq host *physical-host*))
73           (%make-pathname host device directory name type version)))))
74
75 ;;; Hash table searching maps a logical pathname's host to its
76 ;;; physical pathname translation.
77 (defvar *logical-hosts* (make-hash-table :test 'equal :synchronized t))
78 \f
79 ;;;; patterns
80
81 (def!method make-load-form ((pattern pattern) &optional environment)
82   (make-load-form-saving-slots pattern :environment environment))
83
84 (def!method print-object ((pattern pattern) stream)
85   (print-unreadable-object (pattern stream :type t)
86     (if *print-pretty*
87         (let ((*print-escape* t))
88           (pprint-fill stream (pattern-pieces pattern) nil))
89         (prin1 (pattern-pieces pattern) stream))))
90
91 (defun pattern= (pattern1 pattern2)
92   (declare (type pattern pattern1 pattern2))
93   (let ((pieces1 (pattern-pieces pattern1))
94         (pieces2 (pattern-pieces pattern2)))
95     (and (= (length pieces1) (length pieces2))
96          (every (lambda (piece1 piece2)
97                   (typecase piece1
98                     (simple-string
99                      (and (simple-string-p piece2)
100                           (string= piece1 piece2)))
101                     (cons
102                      (and (consp piece2)
103                           (eq (car piece1) (car piece2))
104                           (string= (cdr piece1) (cdr piece2))))
105                     (t
106                      (eq piece1 piece2))))
107                 pieces1
108                 pieces2))))
109
110 ;;; If the string matches the pattern returns the multiple values T
111 ;;; and a list of the matched strings.
112 (defun pattern-matches (pattern string)
113   (declare (type pattern pattern)
114            (type simple-string string))
115   (let ((len (length string)))
116     (labels ((maybe-prepend (subs cur-sub chars)
117                (if cur-sub
118                    (let* ((len (length chars))
119                           (new (make-string len))
120                           (index len))
121                      (dolist (char chars)
122                        (setf (schar new (decf index)) char))
123                      (cons new subs))
124                    subs))
125              (matches (pieces start subs cur-sub chars)
126                (if (null pieces)
127                    (if (= start len)
128                        (values t (maybe-prepend subs cur-sub chars))
129                        (values nil nil))
130                    (let ((piece (car pieces)))
131                      (etypecase piece
132                        (simple-string
133                         (let ((end (+ start (length piece))))
134                           (and (<= end len)
135                                (string= piece string
136                                         :start2 start :end2 end)
137                                (matches (cdr pieces) end
138                                         (maybe-prepend subs cur-sub chars)
139                                         nil nil))))
140                        (list
141                         (ecase (car piece)
142                           (:character-set
143                            (and (< start len)
144                                 (let ((char (schar string start)))
145                                   (if (find char (cdr piece) :test #'char=)
146                                       (matches (cdr pieces) (1+ start) subs t
147                                                (cons char chars))))))))
148                        ((member :single-char-wild)
149                         (and (< start len)
150                              (matches (cdr pieces) (1+ start) subs t
151                                       (cons (schar string start) chars))))
152                        ((member :multi-char-wild)
153                         (multiple-value-bind (won new-subs)
154                             (matches (cdr pieces) start subs t chars)
155                           (if won
156                               (values t new-subs)
157                               (and (< start len)
158                                    (matches pieces (1+ start) subs t
159                                             (cons (schar string start)
160                                                   chars)))))))))))
161       (multiple-value-bind (won subs)
162           (matches (pattern-pieces pattern) 0 nil nil nil)
163         (values won (reverse subs))))))
164
165 ;;; PATHNAME-MATCH-P for directory components
166 (defun directory-components-match (thing wild)
167   (or (eq thing wild)
168       (eq wild :wild)
169       ;; If THING has a null directory, assume that it matches
170       ;; (:ABSOLUTE :WILD-INFERIORS) or (:RELATIVE :WILD-INFERIORS).
171       (and (consp wild)
172            (null thing)
173            (member (first wild) '(:absolute :relative))
174            (eq (second wild) :wild-inferiors))
175       (and (consp wild)
176            (let ((wild1 (first wild)))
177              (if (eq wild1 :wild-inferiors)
178                  (let ((wild-subdirs (rest wild)))
179                    (or (null wild-subdirs)
180                        (loop
181                          (when (directory-components-match thing wild-subdirs)
182                            (return t))
183                          (pop thing)
184                          (unless thing (return nil)))))
185                  (and (consp thing)
186                       (components-match (first thing) wild1)
187                       (directory-components-match (rest thing)
188                                                   (rest wild))))))))
189
190 ;;; Return true if pathname component THING is matched by WILD. (not
191 ;;; commutative)
192 (defun components-match (thing wild)
193   (declare (type (or pattern symbol simple-string integer) thing wild))
194   (or (eq thing wild)
195       (eq wild :wild)
196       (typecase thing
197         (simple-string
198          ;; String is matched by itself, a matching pattern or :WILD.
199          (typecase wild
200            (pattern
201             (values (pattern-matches wild thing)))
202            (simple-string
203             (string= thing wild))))
204         (pattern
205          ;; A pattern is only matched by an identical pattern.
206          (and (pattern-p wild) (pattern= thing wild)))
207         (integer
208          ;; An integer (version number) is matched by :WILD or the
209          ;; same integer. This branch will actually always be NIL as
210          ;; long as the version is a fixnum.
211          (eql thing wild)))))
212
213 ;;; a predicate for comparing two pathname slot component sub-entries
214 (defun compare-component (this that)
215   (or (eql this that)
216       (typecase this
217         (simple-string
218          (and (simple-string-p that)
219               (string= this that)))
220         (pattern
221          (and (pattern-p that)
222               (pattern= this that)))
223         (cons
224          (and (consp that)
225               (compare-component (car this) (car that))
226               (compare-component (cdr this) (cdr that)))))))
227 \f
228 ;;;; pathname functions
229
230 (defun pathname= (pathname1 pathname2)
231   (declare (type pathname pathname1)
232            (type pathname pathname2))
233   (or (eq pathname1 pathname2)
234       (and (eq (%pathname-host pathname1)
235                (%pathname-host pathname2))
236            (compare-component (%pathname-device pathname1)
237                               (%pathname-device pathname2))
238            (compare-component (%pathname-directory pathname1)
239                               (%pathname-directory pathname2))
240            (compare-component (%pathname-name pathname1)
241                               (%pathname-name pathname2))
242            (compare-component (%pathname-type pathname1)
243                               (%pathname-type pathname2))
244            (or (eq (%pathname-host pathname1) *physical-host*)
245                (compare-component (%pathname-version pathname1)
246                                   (%pathname-version pathname2))))))
247
248 ;;; Convert PATHNAME-DESIGNATOR (a pathname, or string, or
249 ;;; stream), into a pathname in pathname.
250 ;;;
251 ;;; FIXME: was rewritten, should be tested (or rewritten again, this
252 ;;; time using ONCE-ONLY, *then* tested)
253 (eval-when (:compile-toplevel :execute)
254 (sb!xc:defmacro with-pathname ((pathname pathname-designator) &body body)
255   (let ((pd0 (gensym)))
256     `(let* ((,pd0 ,pathname-designator)
257             (,pathname (etypecase ,pd0
258                          (pathname ,pd0)
259                          (string (parse-namestring ,pd0))
260                          (file-stream (file-name ,pd0)))))
261        ,@body)))
262
263 (sb!xc:defmacro with-native-pathname ((pathname pathname-designator) &body body)
264   (let ((pd0 (gensym)))
265     `(let* ((,pd0 ,pathname-designator)
266             (,pathname (etypecase ,pd0
267                          (pathname ,pd0)
268                          (string (parse-native-namestring ,pd0))
269                          ;; FIXME
270                          #+nil
271                          (file-stream (file-name ,pd0)))))
272        ,@body)))
273
274 (sb!xc:defmacro with-host ((host host-designator) &body body)
275   ;; Generally, redundant specification of information in software,
276   ;; whether in code or in comments, is bad. However, the ANSI spec
277   ;; for this is messy enough that it's hard to hold in short-term
278   ;; memory, so I've recorded these redundant notes on the
279   ;; implications of the ANSI spec.
280   ;;
281   ;; According to the ANSI spec, HOST can be a valid pathname host, or
282   ;; a logical host, or NIL.
283   ;;
284   ;; A valid pathname host can be a valid physical pathname host or a
285   ;; valid logical pathname host.
286   ;;
287   ;; A valid physical pathname host is "any of a string, a list of
288   ;; strings, or the symbol :UNSPECIFIC, that is recognized by the
289   ;; implementation as the name of a host". In SBCL as of 0.6.9.8,
290   ;; that means :UNSPECIFIC: though someday we might want to
291   ;; generalize it to allow strings like "RTFM.MIT.EDU" or lists like
292   ;; '("RTFM" "MIT" "EDU"), that's not supported now.
293   ;;
294   ;; A valid logical pathname host is a string which has been defined as
295   ;; the name of a logical host, as with LOAD-LOGICAL-PATHNAME-TRANSLATIONS.
296   ;;
297   ;; A logical host is an object of implementation-dependent nature. In
298   ;; SBCL, it's a member of the HOST class (a subclass of STRUCTURE-OBJECT).
299   (let ((hd0 (gensym)))
300     `(let* ((,hd0 ,host-designator)
301             (,host (etypecase ,hd0
302                      ((string 0)
303                       ;; This is a special host. It's not valid as a
304                       ;; logical host, so it is a sensible thing to
305                       ;; designate the physical host object. So we do
306                       ;; that.
307                       *physical-host*)
308                      (string
309                       ;; In general ANSI-compliant Common Lisps, a
310                       ;; string might also be a physical pathname
311                       ;; host, but ANSI leaves this up to the
312                       ;; implementor, and in SBCL we don't do it, so
313                       ;; it must be a logical host.
314                       (find-logical-host ,hd0))
315                      ((or null (member :unspecific))
316                       ;; CLHS says that HOST=:UNSPECIFIC has
317                       ;; implementation-defined behavior. We
318                       ;; just turn it into NIL.
319                       nil)
320                      (list
321                       ;; ANSI also allows LISTs to designate hosts,
322                       ;; but leaves its interpretation
323                       ;; implementation-defined. Our interpretation
324                       ;; is that it's unsupported.:-|
325                       (error "A LIST representing a pathname host is not ~
326                               supported in this implementation:~%  ~S"
327                              ,hd0))
328                      (host ,hd0))))
329       ,@body)))
330 ) ; EVAL-WHEN
331
332 (defun find-host (host-designator &optional (errorp t))
333   (with-host (host host-designator)
334     (when (and errorp (not host))
335       (error "Couldn't find host: ~S" host-designator))
336     host))
337
338 (defun pathname (pathspec)
339   #!+sb-doc
340   "Convert PATHSPEC (a pathname designator) into a pathname."
341   (declare (type pathname-designator pathspec))
342   (with-pathname (pathname pathspec)
343     pathname))
344
345 (defun native-pathname (pathspec)
346   #!+sb-doc
347   "Convert PATHSPEC (a pathname designator) into a pathname, assuming
348 the operating system native pathname conventions."
349   (with-native-pathname (pathname pathspec)
350     pathname))
351
352 ;;; Change the case of thing if DIDDLE-P.
353 (defun maybe-diddle-case (thing diddle-p)
354   (if (and diddle-p (not (or (symbolp thing) (integerp thing))))
355       (labels ((check-for (pred in)
356                  (typecase in
357                    (pattern
358                     (dolist (piece (pattern-pieces in))
359                       (when (typecase piece
360                               (simple-string
361                                (check-for pred piece))
362                               (cons
363                                (case (car piece)
364                                  (:character-set
365                                   (check-for pred (cdr piece))))))
366                         (return t))))
367                    (list
368                     (dolist (x in)
369                       (when (check-for pred x)
370                         (return t))))
371                    (simple-string
372                     (dotimes (i (length in))
373                       (when (funcall pred (schar in i))
374                         (return t))))
375                    (t nil)))
376                (diddle-with (fun thing)
377                  (typecase thing
378                    (pattern
379                     (make-pattern
380                      (mapcar (lambda (piece)
381                                (typecase piece
382                                  (simple-string
383                                   (funcall fun piece))
384                                  (cons
385                                   (case (car piece)
386                                     (:character-set
387                                      (cons :character-set
388                                            (funcall fun (cdr piece))))
389                                     (t
390                                      piece)))
391                                  (t
392                                   piece)))
393                              (pattern-pieces thing))))
394                    (list
395                     (mapcar fun thing))
396                    (simple-string
397                     (funcall fun thing))
398                    (t
399                     thing))))
400         (let ((any-uppers (check-for #'upper-case-p thing))
401               (any-lowers (check-for #'lower-case-p thing)))
402           (cond ((and any-uppers any-lowers)
403                  ;; mixed case, stays the same
404                  thing)
405                 (any-uppers
406                  ;; all uppercase, becomes all lower case
407                  (diddle-with (lambda (x) (if (stringp x)
408                                               (string-downcase x)
409                                               x)) thing))
410                 (any-lowers
411                  ;; all lowercase, becomes all upper case
412                  (diddle-with (lambda (x) (if (stringp x)
413                                               (string-upcase x)
414                                               x)) thing))
415                 (t
416                  ;; no letters?  I guess just leave it.
417                  thing))))
418       thing))
419
420 (defun merge-directories (dir1 dir2 diddle-case)
421   (if (or (eq (car dir1) :absolute)
422           (null dir2))
423       dir1
424       (let ((results nil))
425         (flet ((add (dir)
426                  (if (and (eq dir :back)
427                           results
428                           (not (member (car results)
429                                        '(:back :wild-inferiors :relative :absolute))))
430                      (pop results)
431                      (push dir results))))
432           (dolist (dir (maybe-diddle-case dir2 diddle-case))
433             (add dir))
434           (dolist (dir (cdr dir1))
435             (add dir)))
436         (reverse results))))
437
438 (defun merge-pathnames (pathname
439                         &optional
440                         (defaults *default-pathname-defaults*)
441                         (default-version :newest))
442   #!+sb-doc
443   "Construct a filled in pathname by completing the unspecified components
444    from the defaults."
445   (declare (type pathname-designator pathname)
446            (type pathname-designator defaults)
447            (values pathname))
448   (with-pathname (defaults defaults)
449     (let ((pathname (let ((*default-pathname-defaults* defaults))
450                       (pathname pathname))))
451       (let* ((default-host (%pathname-host defaults))
452              (pathname-host (%pathname-host pathname))
453              (diddle-case
454               (and default-host pathname-host
455                    (not (eq (host-customary-case default-host)
456                             (host-customary-case pathname-host)))))
457              (directory (merge-directories (%pathname-directory pathname)
458                                            (%pathname-directory defaults)
459                                            diddle-case)))
460         (%make-maybe-logical-pathname
461          (or pathname-host default-host)
462          (and ;; The device of ~/ shouldn't be merged,
463               ;; because the expansion may have a different device
464               (not (and (>= (length directory) 2)
465                         (eql (car directory) :absolute)
466                         (eql (cadr directory) :home)))
467               (or (%pathname-device pathname)
468                   (maybe-diddle-case (%pathname-device defaults)
469                                      diddle-case)))
470          directory
471          (or (%pathname-name pathname)
472              (maybe-diddle-case (%pathname-name defaults)
473                                 diddle-case))
474          (or (%pathname-type pathname)
475              (maybe-diddle-case (%pathname-type defaults)
476                                 diddle-case))
477          (or (%pathname-version pathname)
478              (and (not (%pathname-name pathname)) (%pathname-version defaults))
479              default-version))))))
480
481 (defun import-directory (directory diddle-case)
482   (etypecase directory
483     (null nil)
484     ((member :wild) '(:absolute :wild-inferiors))
485     ((member :unspecific) '(:relative))
486     (list
487      (collect ((results))
488        (let ((root (pop directory)))
489          (if (member root '(:relative :absolute))
490              (results root)
491              (error "List of directory components must start with ~S or ~S."
492                     :absolute :relative)))
493        (when directory
494          (let ((next (pop directory)))
495            (if (or (eq :home next)
496                    (typep next '(cons (eql :home) (cons string null))))
497                (results next)
498                (push next directory)))
499          (dolist (piece directory)
500            (cond ((member piece '(:wild :wild-inferiors :up :back))
501                   (results piece))
502                  ((or (simple-string-p piece) (pattern-p piece))
503                   (results (maybe-diddle-case piece diddle-case)))
504                  ((stringp piece)
505                   (results (maybe-diddle-case (coerce piece 'simple-string)
506                                               diddle-case)))
507                  (t
508                   (error "~S is not allowed as a directory component." piece)))))
509        (results)))
510     (simple-string
511      `(:absolute ,(maybe-diddle-case directory diddle-case)))
512     (string
513      `(:absolute
514        ,(maybe-diddle-case (coerce directory 'simple-string) diddle-case)))))
515
516 (defun make-pathname (&key host
517                            (device nil devp)
518                            (directory nil dirp)
519                            (name nil namep)
520                            (type nil typep)
521                            (version nil versionp)
522                            defaults
523                            (case :local))
524   #!+sb-doc
525   "Makes a new pathname from the component arguments. Note that host is
526 a host-structure or string."
527   (declare (type (or string host pathname-component-tokens) host)
528            (type (or string pathname-component-tokens) device)
529            (type (or list string pattern pathname-component-tokens) directory)
530            (type (or string pattern pathname-component-tokens) name type)
531            (type (or integer pathname-component-tokens (member :newest))
532                  version)
533            (type (or pathname-designator null) defaults)
534            (type (member :common :local) case))
535   (let* ((defaults (when defaults
536                      (with-pathname (defaults defaults) defaults)))
537          (default-host (if defaults
538                            (%pathname-host defaults)
539                            (pathname-host *default-pathname-defaults*)))
540          ;; Raymond Toy writes: CLHS says make-pathname can take a
541          ;; string (as a logical-host) for the host part. We map that
542          ;; string into the corresponding logical host structure.
543          ;;
544          ;; Paul Werkowski writes:
545          ;; HyperSpec says for the arg to MAKE-PATHNAME;
546          ;; "host---a valid physical pathname host. ..."
547          ;; where it probably means -- a valid pathname host.
548          ;; "valid pathname host n. a valid physical pathname host or
549          ;; a valid logical pathname host."
550          ;; and defines
551          ;; "valid physical pathname host n. any of a string,
552          ;; a list of strings, or the symbol :unspecific,
553          ;; that is recognized by the implementation as the name of a host."
554          ;; "valid logical pathname host n. a string that has been defined
555          ;; as the name of a logical host. ..."
556          ;; HS is silent on what happens if the :HOST arg is NOT one of these.
557          ;; It seems an error message is appropriate.
558          (host (or (find-host host nil) default-host))
559          (diddle-args (and (eq (host-customary-case host) :lower)
560                            (eq case :common)))
561          (diddle-defaults
562           (not (eq (host-customary-case host)
563                    (host-customary-case default-host))))
564          (dev (if devp device (if defaults (%pathname-device defaults))))
565          (dir (import-directory directory diddle-args))
566          (ver (cond
567                (versionp version)
568                (defaults (%pathname-version defaults))
569                (t nil))))
570     (when (and defaults (not dirp))
571       (setf dir
572             (merge-directories dir
573                                (%pathname-directory defaults)
574                                diddle-defaults)))
575
576     (macrolet ((pick (var varp field)
577                  `(cond ((or (simple-string-p ,var)
578                              (pattern-p ,var))
579                          (maybe-diddle-case ,var diddle-args))
580                         ((stringp ,var)
581                          (maybe-diddle-case (coerce ,var 'simple-string)
582                                             diddle-args))
583                         (,varp
584                          (maybe-diddle-case ,var diddle-args))
585                         (defaults
586                          (maybe-diddle-case (,field defaults)
587                                             diddle-defaults))
588                         (t
589                          nil))))
590       (%make-maybe-logical-pathname host
591                                     dev ; forced to :UNSPECIFIC when logical
592                                     dir
593                                     (pick name namep %pathname-name)
594                                     (pick type typep %pathname-type)
595                                     ver))))
596
597 (defun pathname-host (pathname &key (case :local))
598   #!+sb-doc
599   "Return PATHNAME's host."
600   (declare (type pathname-designator pathname)
601            (type (member :local :common) case)
602            (values host)
603            (ignore case))
604   (with-pathname (pathname pathname)
605     (%pathname-host pathname)))
606
607 (defun pathname-device (pathname &key (case :local))
608   #!+sb-doc
609   "Return PATHNAME's device."
610   (declare (type pathname-designator pathname)
611            (type (member :local :common) case))
612   (with-pathname (pathname pathname)
613     (maybe-diddle-case (%pathname-device pathname)
614                        (and (eq case :common)
615                             (eq (host-customary-case
616                                  (%pathname-host pathname))
617                                 :lower)))))
618
619 (defun pathname-directory (pathname &key (case :local))
620   #!+sb-doc
621   "Return PATHNAME's directory."
622   (declare (type pathname-designator pathname)
623            (type (member :local :common) case))
624   (with-pathname (pathname pathname)
625     (maybe-diddle-case (%pathname-directory pathname)
626                        (and (eq case :common)
627                             (eq (host-customary-case
628                                  (%pathname-host pathname))
629                                 :lower)))))
630 (defun pathname-name (pathname &key (case :local))
631   #!+sb-doc
632   "Return PATHNAME's name."
633   (declare (type pathname-designator pathname)
634            (type (member :local :common) case))
635   (with-pathname (pathname pathname)
636     (maybe-diddle-case (%pathname-name pathname)
637                        (and (eq case :common)
638                             (eq (host-customary-case
639                                  (%pathname-host pathname))
640                                 :lower)))))
641
642 (defun pathname-type (pathname &key (case :local))
643   #!+sb-doc
644   "Return PATHNAME's type."
645   (declare (type pathname-designator pathname)
646            (type (member :local :common) case))
647   (with-pathname (pathname pathname)
648     (maybe-diddle-case (%pathname-type pathname)
649                        (and (eq case :common)
650                             (eq (host-customary-case
651                                  (%pathname-host pathname))
652                                 :lower)))))
653
654 (defun pathname-version (pathname)
655   #!+sb-doc
656   "Return PATHNAME's version."
657   (declare (type pathname-designator pathname))
658   (with-pathname (pathname pathname)
659     (%pathname-version pathname)))
660 \f
661 ;;;; namestrings
662
663 ;;; Handle the case for PARSE-NAMESTRING parsing a potentially
664 ;;; syntactically valid logical namestring with an explicit host.
665 ;;;
666 ;;; This then isn't fully general -- we are relying on the fact that
667 ;;; we will only pass to parse-namestring namestring with an explicit
668 ;;; logical host, so that we can pass the host return from
669 ;;; parse-logical-namestring through to %PARSE-NAMESTRING as a truth
670 ;;; value. Yeah, this is probably a KLUDGE - CSR, 2002-04-18
671 (defun parseable-logical-namestring-p (namestr start end)
672   (catch 'exit
673     (handler-bind
674         ((namestring-parse-error (lambda (c)
675                                    (declare (ignore c))
676                                    (throw 'exit nil))))
677       (let ((colon (position #\: namestr :start start :end end)))
678         (when colon
679           (let ((potential-host
680                  (logical-word-or-lose (subseq namestr start colon))))
681             ;; depending on the outcome of CSR comp.lang.lisp post
682             ;; "can PARSE-NAMESTRING create logical hosts", we may need
683             ;; to do things with potential-host (create it
684             ;; temporarily, parse the namestring and unintern the
685             ;; logical host potential-host on failure.
686             (declare (ignore potential-host))
687             (let ((result
688                    (handler-bind
689                        ((simple-type-error (lambda (c)
690                                              (declare (ignore c))
691                                              (throw 'exit nil))))
692                      (parse-logical-namestring namestr start end))))
693               ;; if we got this far, we should have an explicit host
694               ;; (first return value of parse-logical-namestring)
695               (aver result)
696               result)))))))
697
698 ;;; Handle the case where PARSE-NAMESTRING is actually parsing a
699 ;;; namestring. We pick off the :JUNK-ALLOWED case then find a host to
700 ;;; use for parsing, call the parser, then check whether the host matches.
701 (defun %parse-namestring (namestr host defaults start end junk-allowed)
702   (declare (type (or host null) host)
703            (type string namestr)
704            (type index start)
705            (type (or index null) end))
706   (cond
707     (junk-allowed
708      (handler-case
709          (%parse-namestring namestr host defaults start end nil)
710        (namestring-parse-error (condition)
711          (values nil (namestring-parse-error-offset condition)))))
712     (t
713      (let* ((end (%check-vector-sequence-bounds namestr start end)))
714        (multiple-value-bind (new-host device directory file type version)
715            ;; Comments below are quotes from the HyperSpec
716            ;; PARSE-NAMESTRING entry, reproduced here to demonstrate
717            ;; that we actually have to do things this way rather than
718            ;; some possibly more logical way. - CSR, 2002-04-18
719            (cond
720              ;; "If host is a logical host then thing is parsed as a
721              ;; logical pathname namestring on the host."
722              (host (funcall (host-parse host) namestr start end))
723              ;; "If host is nil and thing is a syntactically valid
724              ;; logical pathname namestring containing an explicit
725              ;; host, then it is parsed as a logical pathname
726              ;; namestring."
727              ((parseable-logical-namestring-p namestr start end)
728               (parse-logical-namestring namestr start end))
729              ;; "If host is nil, default-pathname is a logical
730              ;; pathname, and thing is a syntactically valid logical
731              ;; pathname namestring without an explicit host, then it
732              ;; is parsed as a logical pathname namestring on the
733              ;; host that is the host component of default-pathname."
734              ;;
735              ;; "Otherwise, the parsing of thing is
736              ;; implementation-defined."
737              ;;
738              ;; Both clauses are handled here, as the default
739              ;; *DEFAULT-PATHNAME-DEFAULTS* has a SB-IMPL::UNIX-HOST
740              ;; for a host.
741              ((pathname-host defaults)
742               (funcall (host-parse (pathname-host defaults))
743                        namestr
744                        start
745                        end))
746              ;; I don't think we should ever get here, as the default
747              ;; host will always have a non-null HOST, given that we
748              ;; can't create a new pathname without going through
749              ;; *DEFAULT-PATHNAME-DEFAULTS*, which has a non-null
750              ;; host...
751              (t (bug "Fallen through COND in %PARSE-NAMESTRING")))
752          (when (and host new-host (not (eq new-host host)))
753            (error 'simple-type-error
754                   :datum new-host
755                   ;; Note: ANSI requires that this be a TYPE-ERROR,
756                   ;; but there seems to be no completely correct
757                   ;; value to use for TYPE-ERROR-EXPECTED-TYPE.
758                   ;; Instead, we return a sort of "type error allowed
759                   ;; type", trying to say "it would be OK if you
760                   ;; passed NIL as the host value" but not mentioning
761                   ;; that a matching string would be OK too.
762                   :expected-type 'null
763                   :format-control
764                   "The host in the namestring, ~S,~@
765                    does not match the explicit HOST argument, ~S."
766                   :format-arguments (list new-host host)))
767          (let ((pn-host (or new-host host (pathname-host defaults))))
768            (values (%make-maybe-logical-pathname
769                     pn-host device directory file type version)
770                    end)))))))
771
772 ;;; If NAMESTR begins with a colon-terminated, defined, logical host,
773 ;;; then return that host, otherwise return NIL.
774 (defun extract-logical-host-prefix (namestr start end)
775   (declare (type simple-string namestr)
776            (type index start end)
777            (values (or logical-host null)))
778   (let ((colon-pos (position #\: namestr :start start :end end)))
779     (if colon-pos
780         (values (gethash (nstring-upcase (subseq namestr start colon-pos))
781                          *logical-hosts*))
782         nil)))
783
784 (defun parse-namestring (thing
785                          &optional
786                          host
787                          (defaults *default-pathname-defaults*)
788                          &key (start 0) end junk-allowed)
789   (declare (type pathname-designator thing defaults)
790            (type (or list host string (member :unspecific)) host)
791            (type index start)
792            (type (or index null) end)
793            (type (or t null) junk-allowed)
794            (values (or null pathname) (or null index)))
795   (with-host (found-host host)
796     (let (;; According to ANSI defaults may be any valid pathname designator
797           (defaults (etypecase defaults
798                       (pathname
799                        defaults)
800                       (string
801                        (aver (pathnamep *default-pathname-defaults*))
802                        (parse-namestring defaults))
803                       (stream
804                        (truename defaults)))))
805       (declare (type pathname defaults))
806       (etypecase thing
807         (simple-string
808          (%parse-namestring thing found-host defaults start end junk-allowed))
809         (string
810          (%parse-namestring (coerce thing 'simple-string)
811                             found-host defaults start end junk-allowed))
812         (pathname
813          (let ((defaulted-host (or found-host (%pathname-host defaults))))
814            (declare (type host defaulted-host))
815            (unless (eq defaulted-host (%pathname-host thing))
816              (error "The HOST argument doesn't match the pathname host:~%  ~
817                     ~S and ~S."
818                     defaulted-host (%pathname-host thing))))
819          (values thing start))
820         (stream
821          (let ((name (file-name thing)))
822            (unless name
823              (error "can't figure out the file associated with stream:~%  ~S"
824                     thing))
825            (values name nil)))))))
826
827 (defun %parse-native-namestring (namestr host defaults start end junk-allowed
828                                  as-directory)
829   (declare (type (or host null) host)
830            (type string namestr)
831            (type index start)
832            (type (or index null) end))
833   (cond
834     (junk-allowed
835      (handler-case
836          (%parse-native-namestring namestr host defaults start end nil as-directory)
837        (namestring-parse-error (condition)
838          (values nil (namestring-parse-error-offset condition)))))
839     (t
840      (let* ((end (%check-vector-sequence-bounds namestr start end)))
841        (multiple-value-bind (new-host device directory file type version)
842            (cond
843              (host
844               (funcall (host-parse-native host) namestr start end as-directory))
845              ((pathname-host defaults)
846               (funcall (host-parse-native (pathname-host defaults))
847                        namestr
848                        start
849                        end
850                        as-directory))
851              ;; I don't think we should ever get here, as the default
852              ;; host will always have a non-null HOST, given that we
853              ;; can't create a new pathname without going through
854              ;; *DEFAULT-PATHNAME-DEFAULTS*, which has a non-null
855              ;; host...
856              (t (bug "Fallen through COND in %PARSE-NAMESTRING")))
857          (when (and host new-host (not (eq new-host host)))
858            (error 'simple-type-error
859                   :datum new-host
860                   :expected-type `(or null (eql ,host))
861                   :format-control
862                   "The host in the namestring, ~S,~@
863                    does not match the explicit HOST argument, ~S."
864                   :format-arguments (list new-host host)))
865          (let ((pn-host (or new-host host (pathname-host defaults))))
866            (values (%make-pathname
867                     pn-host device directory file type version)
868                    end)))))))
869
870 (defun parse-native-namestring (thing
871                                 &optional
872                                 host
873                                 (defaults *default-pathname-defaults*)
874                                 &key (start 0) end junk-allowed
875                                 as-directory)
876   #!+sb-doc
877   "Convert THING into a pathname, using the native conventions
878 appropriate for the pathname host HOST, or if not specified the
879 host of DEFAULTS.  If THING is a string, the parse is bounded by
880 START and END, and error behaviour is controlled by JUNK-ALLOWED,
881 as with PARSE-NAMESTRING.  For file systems whose native
882 conventions allow directories to be indicated as files, if
883 AS-DIRECTORY is true, return a pathname denoting THING as a
884 directory."
885   (declare (type pathname-designator thing defaults)
886            (type (or list host string (member :unspecific)) host)
887            (type index start)
888            (type (or index null) end)
889            (type (or t null) junk-allowed)
890            (values (or null pathname) (or null index)))
891   (with-host (found-host host)
892     (let ((defaults (etypecase defaults
893                       (pathname
894                        defaults)
895                       (string
896                        (aver (pathnamep *default-pathname-defaults*))
897                        (parse-native-namestring defaults))
898                       (stream
899                        (truename defaults)))))
900       (declare (type pathname defaults))
901       (etypecase thing
902         (simple-string
903          (%parse-native-namestring
904           thing found-host defaults start end junk-allowed as-directory))
905         (string
906          (%parse-native-namestring (coerce thing 'simple-string)
907                                    found-host defaults start end junk-allowed
908                                    as-directory))
909         (pathname
910          (let ((defaulted-host (or found-host (%pathname-host defaults))))
911            (declare (type host defaulted-host))
912            (unless (eq defaulted-host (%pathname-host thing))
913              (error "The HOST argument doesn't match the pathname host:~%  ~
914                      ~S and ~S."
915                     defaulted-host (%pathname-host thing))))
916          (values thing start))
917         (stream
918          ;; FIXME
919          (let ((name (file-name thing)))
920            (unless name
921              (error "can't figure out the file associated with stream:~%  ~S"
922                     thing))
923            (values name nil)))))))
924
925 (defun namestring (pathname)
926   #!+sb-doc
927   "Construct the full (name)string form of the pathname."
928   (declare (type pathname-designator pathname))
929   (with-pathname (pathname pathname)
930     (when pathname
931       (let ((host (%pathname-host pathname)))
932         (unless host
933           (error "can't determine the namestring for pathnames with no ~
934                   host:~%  ~S" pathname))
935         (funcall (host-unparse host) pathname)))))
936
937 (defun native-namestring (pathname &key as-file)
938   #!+sb-doc
939   "Construct the full native (name)string form of PATHNAME.  For
940 file systems whose native conventions allow directories to be
941 indicated as files, if AS-FILE is true and the name, type, and
942 version components of PATHNAME are all NIL or :UNSPECIFIC,
943 construct a string that names the directory according to the file
944 system's syntax for files."
945   (declare (type pathname-designator pathname))
946   (with-native-pathname (pathname pathname)
947     (when pathname
948       (let ((host (%pathname-host pathname)))
949         (unless host
950           (error "can't determine the native namestring for pathnames with no ~
951                   host:~%  ~S" pathname))
952         (funcall (host-unparse-native host) pathname as-file)))))
953
954 (defun host-namestring (pathname)
955   #!+sb-doc
956   "Return a string representation of the name of the host in the pathname."
957   (declare (type pathname-designator pathname))
958   (with-pathname (pathname pathname)
959     (let ((host (%pathname-host pathname)))
960       (if host
961           (funcall (host-unparse-host host) pathname)
962           (error
963            "can't determine the namestring for pathnames with no host:~%  ~S"
964            pathname)))))
965
966 (defun directory-namestring (pathname)
967   #!+sb-doc
968   "Return a string representation of the directories used in the pathname."
969   (declare (type pathname-designator pathname))
970   (with-pathname (pathname pathname)
971     (let ((host (%pathname-host pathname)))
972       (if host
973           (funcall (host-unparse-directory host) pathname)
974           (error
975            "can't determine the namestring for pathnames with no host:~%  ~S"
976            pathname)))))
977
978 (defun file-namestring (pathname)
979   #!+sb-doc
980   "Return a string representation of the name used in the pathname."
981   (declare (type pathname-designator pathname))
982   (with-pathname (pathname pathname)
983     (let ((host (%pathname-host pathname)))
984       (if host
985           (funcall (host-unparse-file host) pathname)
986           (error
987            "can't determine the namestring for pathnames with no host:~%  ~S"
988            pathname)))))
989
990 (defun enough-namestring (pathname
991                           &optional
992                           (defaults *default-pathname-defaults*))
993   #!+sb-doc
994   "Return an abbreviated pathname sufficient to identify the pathname relative
995    to the defaults."
996   (declare (type pathname-designator pathname))
997   (with-pathname (pathname pathname)
998     (let ((host (%pathname-host pathname)))
999       (if host
1000           (with-pathname (defaults defaults)
1001             (funcall (host-unparse-enough host) pathname defaults))
1002           (error
1003            "can't determine the namestring for pathnames with no host:~%  ~S"
1004            pathname)))))
1005 \f
1006 ;;;; wild pathnames
1007
1008 (defun wild-pathname-p (pathname &optional field-key)
1009   #!+sb-doc
1010   "Predicate for determining whether pathname contains any wildcards."
1011   (declare (type pathname-designator pathname)
1012            (type (member nil :host :device :directory :name :type :version)
1013                  field-key))
1014   (with-pathname (pathname pathname)
1015     (flet ((frob (x)
1016              (or (pattern-p x) (member x '(:wild :wild-inferiors)))))
1017       (ecase field-key
1018         ((nil)
1019          (or (wild-pathname-p pathname :host)
1020              (wild-pathname-p pathname :device)
1021              (wild-pathname-p pathname :directory)
1022              (wild-pathname-p pathname :name)
1023              (wild-pathname-p pathname :type)
1024              (wild-pathname-p pathname :version)))
1025         (:host (frob (%pathname-host pathname)))
1026         (:device (frob (%pathname-host pathname)))
1027         (:directory (some #'frob (%pathname-directory pathname)))
1028         (:name (frob (%pathname-name pathname)))
1029         (:type (frob (%pathname-type pathname)))
1030         (:version (frob (%pathname-version pathname)))))))
1031
1032 (defun pathname-match-p (in-pathname in-wildname)
1033   #!+sb-doc
1034   "Pathname matches the wildname template?"
1035   (declare (type pathname-designator in-pathname))
1036   (with-pathname (pathname in-pathname)
1037     (with-pathname (wildname in-wildname)
1038       (macrolet ((frob (field &optional (op 'components-match))
1039                    `(or (null (,field wildname))
1040                         (,op (,field pathname) (,field wildname)))))
1041         (and (or (null (%pathname-host wildname))
1042                  (eq (%pathname-host wildname) (%pathname-host pathname)))
1043              (frob %pathname-device)
1044              (frob %pathname-directory directory-components-match)
1045              (frob %pathname-name)
1046              (frob %pathname-type)
1047              (or (eq (%pathname-host wildname) *physical-host*)
1048                  (frob %pathname-version)))))))
1049
1050 ;;; Place the substitutions into the pattern and return the string or pattern
1051 ;;; that results. If DIDDLE-CASE is true, we diddle the result case as well,
1052 ;;; in case we are translating between hosts with difference conventional case.
1053 ;;; The second value is the tail of subs with all of the values that we used up
1054 ;;; stripped off. Note that PATTERN-MATCHES matches all consecutive wildcards
1055 ;;; as a single string, so we ignore subsequent contiguous wildcards.
1056 (defun substitute-into (pattern subs diddle-case)
1057   (declare (type pattern pattern)
1058            (type list subs)
1059            (values (or simple-string pattern) list))
1060   (let ((in-wildcard nil)
1061         (pieces nil)
1062         (strings nil))
1063     (dolist (piece (pattern-pieces pattern))
1064       (cond ((simple-string-p piece)
1065              (push piece strings)
1066              (setf in-wildcard nil))
1067             (in-wildcard)
1068             (t
1069              (setf in-wildcard t)
1070              (unless subs
1071                (error "not enough wildcards in FROM pattern to match ~
1072                        TO pattern:~%  ~S"
1073                       pattern))
1074              (let ((sub (pop subs)))
1075                (typecase sub
1076                  (pattern
1077                   (when strings
1078                     (push (apply #'concatenate 'simple-string
1079                                  (nreverse strings))
1080                           pieces))
1081                   (dolist (piece (pattern-pieces sub))
1082                     (push piece pieces)))
1083                  (simple-string
1084                   (push sub strings))
1085                  (t
1086                   (error "can't substitute this into the middle of a word:~
1087                           ~%  ~S"
1088                          sub)))))))
1089
1090     (when strings
1091       (push (apply #'concatenate 'simple-string (nreverse strings))
1092             pieces))
1093     (values
1094      (maybe-diddle-case
1095       (if (and pieces (simple-string-p (car pieces)) (null (cdr pieces)))
1096           (car pieces)
1097           (make-pattern (nreverse pieces)))
1098       diddle-case)
1099      subs)))
1100
1101 ;;; Called when we can't see how source and from matched.
1102 (defun didnt-match-error (source from)
1103   (error "Pathname components from SOURCE and FROM args to TRANSLATE-PATHNAME~@
1104           did not match:~%  ~S ~S"
1105          source from))
1106
1107 ;;; Do TRANSLATE-COMPONENT for all components except host, directory
1108 ;;; and version.
1109 (defun translate-component (source from to diddle-case)
1110   (typecase to
1111     (pattern
1112      (typecase from
1113        (pattern
1114         (typecase source
1115           (pattern
1116            (if (pattern= from source)
1117                source
1118                (didnt-match-error source from)))
1119           (simple-string
1120            (multiple-value-bind (won subs) (pattern-matches from source)
1121              (if won
1122                  (values (substitute-into to subs diddle-case))
1123                  (didnt-match-error source from))))
1124           (t
1125            (maybe-diddle-case source diddle-case))))
1126        ((member :wild)
1127         (values (substitute-into to (list source) diddle-case)))
1128        (t
1129         (if (components-match source from)
1130             (maybe-diddle-case source diddle-case)
1131             (didnt-match-error source from)))))
1132     ((member nil :wild)
1133      (maybe-diddle-case source diddle-case))
1134     (t
1135      (if (components-match source from)
1136          to
1137          (didnt-match-error source from)))))
1138
1139 ;;; Return a list of all the things that we want to substitute into the TO
1140 ;;; pattern (the things matched by from on source.)  When From contains
1141 ;;; :WILD-INFERIORS, the result contains a sublist of the matched source
1142 ;;; subdirectories.
1143 (defun compute-directory-substitutions (orig-source orig-from)
1144   (let ((source orig-source)
1145         (from orig-from))
1146     (collect ((subs))
1147       (loop
1148         (unless source
1149           (unless (every (lambda (x) (eq x :wild-inferiors)) from)
1150             (didnt-match-error orig-source orig-from))
1151           (subs ())
1152           (return))
1153         (unless from (didnt-match-error orig-source orig-from))
1154         (let ((from-part (pop from))
1155               (source-part (pop source)))
1156           (typecase from-part
1157             (pattern
1158              (typecase source-part
1159                (pattern
1160                 (if (pattern= from-part source-part)
1161                     (subs source-part)
1162                     (didnt-match-error orig-source orig-from)))
1163                (simple-string
1164                 (multiple-value-bind (won new-subs)
1165                     (pattern-matches from-part source-part)
1166                   (if won
1167                       (dolist (sub new-subs)
1168                         (subs sub))
1169                       (didnt-match-error orig-source orig-from))))
1170                (t
1171                 (didnt-match-error orig-source orig-from))))
1172             ((member :wild)
1173              (subs source-part))
1174             ((member :wild-inferiors)
1175              (let ((remaining-source (cons source-part source)))
1176                (collect ((res))
1177                  (loop
1178                    (when (directory-components-match remaining-source from)
1179                      (return))
1180                    (unless remaining-source
1181                      (didnt-match-error orig-source orig-from))
1182                    (res (pop remaining-source)))
1183                  (subs (res))
1184                  (setq source remaining-source))))
1185             (simple-string
1186              (unless (and (simple-string-p source-part)
1187                           (string= from-part source-part))
1188                (didnt-match-error orig-source orig-from)))
1189             (t
1190              (didnt-match-error orig-source orig-from)))))
1191       (subs))))
1192
1193 ;;; This is called by TRANSLATE-PATHNAME on the directory components
1194 ;;; of its argument pathnames to produce the result directory
1195 ;;; component. If this leaves the directory NIL, we return the source
1196 ;;; directory. The :RELATIVE or :ABSOLUTE is taken from the source
1197 ;;; directory, except if TO is :ABSOLUTE, in which case the result
1198 ;;; will be :ABSOLUTE.
1199 (defun translate-directories (source from to diddle-case)
1200   (if (not (and source to from))
1201       (or (and to (null source) (remove :wild-inferiors to))
1202           (mapcar (lambda (x) (maybe-diddle-case x diddle-case)) source))
1203       (collect ((res))
1204                ;; If TO is :ABSOLUTE, the result should still be :ABSOLUTE.
1205                (res (if (eq (first to) :absolute)
1206                  :absolute
1207                  (first source)))
1208         (let ((subs-left (compute-directory-substitutions (rest source)
1209                                                           (rest from))))
1210           (dolist (to-part (rest to))
1211             (typecase to-part
1212               ((member :wild)
1213                (aver subs-left)
1214                (let ((match (pop subs-left)))
1215                  (when (listp match)
1216                    (error ":WILD-INFERIORS is not paired in from and to ~
1217                            patterns:~%  ~S ~S" from to))
1218                  (res (maybe-diddle-case match diddle-case))))
1219               ((member :wild-inferiors)
1220                (aver subs-left)
1221                (let ((match (pop subs-left)))
1222                  (unless (listp match)
1223                    (error ":WILD-INFERIORS not paired in from and to ~
1224                            patterns:~%  ~S ~S" from to))
1225                  (dolist (x match)
1226                    (res (maybe-diddle-case x diddle-case)))))
1227               (pattern
1228                (multiple-value-bind
1229                    (new new-subs-left)
1230                    (substitute-into to-part subs-left diddle-case)
1231                  (setf subs-left new-subs-left)
1232                  (res new)))
1233               (t (res to-part)))))
1234         (res))))
1235
1236 (defun translate-pathname (source from-wildname to-wildname &key)
1237   #!+sb-doc
1238   "Use the source pathname to translate the from-wildname's wild and
1239 unspecified elements into a completed to-pathname based on the to-wildname."
1240   (declare (type pathname-designator source from-wildname to-wildname))
1241   (with-pathname (source source)
1242     (with-pathname (from from-wildname)
1243       (with-pathname (to to-wildname)
1244           (let* ((source-host (%pathname-host source))
1245                  (from-host (%pathname-host from))
1246                  (to-host (%pathname-host to))
1247                  (diddle-case
1248                   (and source-host to-host
1249                        (not (eq (host-customary-case source-host)
1250                                 (host-customary-case to-host))))))
1251             (macrolet ((frob (field &optional (op 'translate-component))
1252                          `(let ((result (,op (,field source)
1253                                              (,field from)
1254                                              (,field to)
1255                                              diddle-case)))
1256                             (if (eq result :error)
1257                                 (error "~S doesn't match ~S." source from)
1258                                 result))))
1259               (%make-maybe-logical-pathname
1260                (or to-host source-host)
1261                (frob %pathname-device)
1262                (frob %pathname-directory translate-directories)
1263                (frob %pathname-name)
1264                (frob %pathname-type)
1265                (if (eq from-host *physical-host*)
1266                    (if (or (eq (%pathname-version to) :wild)
1267                            (eq (%pathname-version to) nil))
1268                        (%pathname-version source)
1269                        (%pathname-version to))
1270                    (frob %pathname-version)))))))))
1271 \f
1272 ;;;;  logical pathname support. ANSI 92-102 specification.
1273 ;;;;
1274 ;;;;  As logical-pathname translations are loaded they are
1275 ;;;;  canonicalized as patterns to enable rapid efficient translation
1276 ;;;;  into physical pathnames.
1277
1278 ;;;; utilities
1279
1280 (defun simplify-namestring (namestring &optional host)
1281   (funcall (host-simplify-namestring
1282             (or host
1283                 (pathname-host (sane-default-pathname-defaults))))
1284            namestring))
1285
1286 ;;; Canonicalize a logical pathname word by uppercasing it checking that it
1287 ;;; contains only legal characters.
1288 (defun logical-word-or-lose (word)
1289   (declare (string word))
1290   (when (string= word "")
1291     (error 'namestring-parse-error
1292            :complaint "Attempted to treat invalid logical hostname ~
1293                        as a logical host:~%  ~S"
1294            :args (list word)
1295            :namestring word :offset 0))
1296   (let ((word (string-upcase word)))
1297     (dotimes (i (length word))
1298       (let ((ch (schar word i)))
1299         (unless (and (typep ch 'standard-char)
1300                      (or (alpha-char-p ch) (digit-char-p ch) (char= ch #\-)))
1301           (error 'namestring-parse-error
1302                  :complaint "logical namestring character which ~
1303                              is not alphanumeric or hyphen:~%  ~S"
1304                  :args (list ch)
1305                  :namestring word :offset i))))
1306     (coerce word 'string))) ; why not simple-string?
1307
1308 ;;; Given a logical host or string, return a logical host. If ERROR-P
1309 ;;; is NIL, then return NIL when no such host exists.
1310 (defun find-logical-host (thing &optional (errorp t))
1311   (etypecase thing
1312     (string
1313      (let ((found (gethash (logical-word-or-lose thing)
1314                            *logical-hosts*)))
1315        (if (or found (not errorp))
1316            found
1317            ;; This is the error signalled from e.g.
1318            ;; LOGICAL-PATHNAME-TRANSLATIONS when host is not a defined
1319            ;; host, and ANSI specifies that that's a TYPE-ERROR.
1320            (error 'simple-type-error
1321                   :datum thing
1322                   ;; God only knows what ANSI expects us to use for
1323                   ;; the EXPECTED-TYPE here. Maybe this will be OK..
1324                   :expected-type
1325                   '(and string (satisfies logical-pathname-translations))
1326                   :format-control "logical host not yet defined: ~S"
1327                   :format-arguments (list thing)))))
1328     (logical-host thing)))
1329
1330 ;;; Given a logical host name or host, return a logical host, creating
1331 ;;; a new one if necessary.
1332 (defun intern-logical-host (thing)
1333   (declare (values logical-host))
1334   (with-locked-system-table (*logical-hosts*)
1335     (or (find-logical-host thing nil)
1336         (let* ((name (logical-word-or-lose thing))
1337                (new (make-logical-host :name name)))
1338           (setf (gethash name *logical-hosts*) new)
1339           new))))
1340 \f
1341 ;;;; logical pathname parsing
1342
1343 ;;; Deal with multi-char wildcards in a logical pathname token.
1344 (defun maybe-make-logical-pattern (namestring chunks)
1345   (let ((chunk (caar chunks)))
1346     (collect ((pattern))
1347       (let ((last-pos 0)
1348             (len (length chunk)))
1349         (declare (fixnum last-pos))
1350         (loop
1351           (when (= last-pos len) (return))
1352           (let ((pos (or (position #\* chunk :start last-pos) len)))
1353             (if (= pos last-pos)
1354                 (when (pattern)
1355                   (error 'namestring-parse-error
1356                          :complaint "double asterisk inside of logical ~
1357                                      word: ~S"
1358                          :args (list chunk)
1359                          :namestring namestring
1360                          :offset (+ (cdar chunks) pos)))
1361                 (pattern (subseq chunk last-pos pos)))
1362             (if (= pos len)
1363                 (return)
1364                 (pattern :multi-char-wild))
1365             (setq last-pos (1+ pos)))))
1366         (aver (pattern))
1367         (if (cdr (pattern))
1368             (make-pattern (pattern))
1369             (let ((x (car (pattern))))
1370               (if (eq x :multi-char-wild)
1371                   :wild
1372                   x))))))
1373
1374 ;;; Return a list of conses where the CDR is the start position and
1375 ;;; the CAR is a string (token) or character (punctuation.)
1376 (defun logical-chunkify (namestr start end)
1377   (collect ((chunks))
1378     (do ((i start (1+ i))
1379          (prev 0))
1380         ((= i end)
1381          (when (> end prev)
1382             (chunks (cons (nstring-upcase (subseq namestr prev end)) prev))))
1383       (let ((ch (schar namestr i)))
1384         (unless (or (alpha-char-p ch) (digit-char-p ch)
1385                     (member ch '(#\- #\*)))
1386           (when (> i prev)
1387             (chunks (cons (nstring-upcase (subseq namestr prev i)) prev)))
1388           (setq prev (1+ i))
1389           (unless (member ch '(#\; #\: #\.))
1390             (error 'namestring-parse-error
1391                    :complaint "illegal character for logical pathname:~%  ~S"
1392                    :args (list ch)
1393                    :namestring namestr
1394                    :offset i))
1395           (chunks (cons ch i)))))
1396     (chunks)))
1397
1398 ;;; Break up a logical-namestring, always a string, into its
1399 ;;; constituent parts.
1400 (defun parse-logical-namestring (namestr start end)
1401   (declare (type simple-string namestr)
1402            (type index start end))
1403   (collect ((directory))
1404     (let ((host nil)
1405           (name nil)
1406           (type nil)
1407           (version nil))
1408       (labels ((expecting (what chunks)
1409                  (unless (and chunks (simple-string-p (caar chunks)))
1410                    (error 'namestring-parse-error
1411                           :complaint "expecting ~A, got ~:[nothing~;~S~]."
1412                           :args (list what (caar chunks) (caar chunks))
1413                           :namestring namestr
1414                           :offset (if chunks (cdar chunks) end)))
1415                  (caar chunks))
1416                (parse-host (chunks)
1417                  (case (caadr chunks)
1418                    (#\:
1419                     (setq host
1420                           (find-logical-host (expecting "a host name" chunks)))
1421                     (parse-relative (cddr chunks)))
1422                    (t
1423                     (parse-relative chunks))))
1424                (parse-relative (chunks)
1425                  (case (caar chunks)
1426                    (#\;
1427                     (directory :relative)
1428                     (parse-directory (cdr chunks)))
1429                    (t
1430                     (directory :absolute) ; Assumption! Maybe revoked later.
1431                     (parse-directory chunks))))
1432                (parse-directory (chunks)
1433                  (case (caadr chunks)
1434                    (#\;
1435                     (directory
1436                      (let ((res (expecting "a directory name" chunks)))
1437                        (cond ((string= res "..") :up)
1438                              ((string= res "**") :wild-inferiors)
1439                              (t
1440                               (maybe-make-logical-pattern namestr chunks)))))
1441                     (parse-directory (cddr chunks)))
1442                    (t
1443                     (parse-name chunks))))
1444                (parse-name (chunks)
1445                  (when chunks
1446                    (expecting "a file name" chunks)
1447                    (setq name (maybe-make-logical-pattern namestr chunks))
1448                    (expecting-dot (cdr chunks))))
1449                (expecting-dot (chunks)
1450                  (when chunks
1451                    (unless (eql (caar chunks) #\.)
1452                      (error 'namestring-parse-error
1453                             :complaint "expecting a dot, got ~S."
1454                             :args (list (caar chunks))
1455                             :namestring namestr
1456                             :offset (cdar chunks)))
1457                    (if type
1458                        (parse-version (cdr chunks))
1459                        (parse-type (cdr chunks)))))
1460                (parse-type (chunks)
1461                  (expecting "a file type" chunks)
1462                  (setq type (maybe-make-logical-pattern namestr chunks))
1463                  (expecting-dot (cdr chunks)))
1464                (parse-version (chunks)
1465                  (let ((str (expecting "a positive integer, * or NEWEST"
1466                                        chunks)))
1467                    (cond
1468                     ((string= str "*") (setq version :wild))
1469                     ((string= str "NEWEST") (setq version :newest))
1470                     (t
1471                      (multiple-value-bind (res pos)
1472                          (parse-integer str :junk-allowed t)
1473                        (unless (and res (plusp res))
1474                          (error 'namestring-parse-error
1475                                 :complaint "expected a positive integer, ~
1476                                             got ~S"
1477                                 :args (list str)
1478                                 :namestring namestr
1479                                 :offset (+ pos (cdar chunks))))
1480                        (setq version res)))))
1481                  (when (cdr chunks)
1482                    (error 'namestring-parse-error
1483                           :complaint "extra stuff after end of file name"
1484                           :namestring namestr
1485                           :offset (cdadr chunks)))))
1486         (parse-host (logical-chunkify namestr start end)))
1487       (values host :unspecific (directory) name type version))))
1488
1489 ;;; We can't initialize this yet because not all host methods are
1490 ;;; loaded yet.
1491 (defvar *logical-pathname-defaults*)
1492
1493 (defun logical-namestring-p (x)
1494   (and (stringp x)
1495        (ignore-errors
1496          (typep (pathname x) 'logical-pathname))))
1497
1498 (deftype logical-namestring ()
1499   `(satisfies logical-namestring-p))
1500
1501 (defun logical-pathname (pathspec)
1502   #!+sb-doc
1503   "Converts the pathspec argument to a logical-pathname and returns it."
1504   (declare (type (or logical-pathname string stream) pathspec)
1505            (values logical-pathname))
1506   (if (typep pathspec 'logical-pathname)
1507       pathspec
1508       (flet ((oops (problem)
1509                (error 'simple-type-error
1510                       :datum pathspec
1511                       :expected-type 'logical-namestring
1512                       :format-control "~S is not a valid logical namestring:~%  ~A"
1513                       :format-arguments (list pathspec problem))))
1514         (let ((res (handler-case
1515                        (parse-namestring pathspec nil *logical-pathname-defaults*)
1516                      (error (e) (oops e)))))
1517           (when (eq (%pathname-host res)
1518                     (%pathname-host *logical-pathname-defaults*))
1519             (oops "no host specified"))
1520           res))))
1521 \f
1522 ;;;; logical pathname unparsing
1523
1524 (defun unparse-logical-directory (pathname)
1525   (declare (type pathname pathname))
1526   (collect ((pieces))
1527     (let ((directory (%pathname-directory pathname)))
1528       (when directory
1529         (ecase (pop directory)
1530           (:absolute) ; nothing special
1531           (:relative (pieces ";")))
1532         (dolist (dir directory)
1533           (cond ((or (stringp dir) (pattern-p dir))
1534                  (pieces (unparse-logical-piece dir))
1535                  (pieces ";"))
1536                 ((eq dir :wild)
1537                  (pieces "*;"))
1538                 ((eq dir :wild-inferiors)
1539                  (pieces "**;"))
1540                 (t
1541                  (error "invalid directory component: ~S" dir))))))
1542     (apply #'concatenate 'simple-string (pieces))))
1543
1544 (defun unparse-logical-piece (thing)
1545   (etypecase thing
1546     ((member :wild) "*")
1547     (simple-string thing)
1548     (pattern
1549      (collect ((strings))
1550        (dolist (piece (pattern-pieces thing))
1551          (etypecase piece
1552            (simple-string (strings piece))
1553            (keyword
1554             (cond ((eq piece :wild-inferiors)
1555                    (strings "**"))
1556                   ((eq piece :multi-char-wild)
1557                    (strings "*"))
1558                   (t (error "invalid keyword: ~S" piece))))))
1559        (apply #'concatenate 'simple-string (strings))))))
1560
1561 (defun unparse-logical-file (pathname)
1562   (declare (type pathname pathname))
1563     (collect ((strings))
1564     (let* ((name (%pathname-name pathname))
1565            (type (%pathname-type pathname))
1566            (version (%pathname-version pathname))
1567            (type-supplied (not (or (null type) (eq type :unspecific))))
1568            (version-supplied (not (or (null version)
1569                                       (eq version :unspecific)))))
1570       (when name
1571         (when (and (null type)
1572                    (typep name 'string)
1573                    (position #\. name :start 1))
1574           (error "too many dots in the name: ~S" pathname))
1575         (strings (unparse-logical-piece name)))
1576       (when type-supplied
1577         (unless name
1578           (error "cannot specify the type without a file: ~S" pathname))
1579         (when (typep type 'string)
1580           (when (position #\. type)
1581             (error "type component can't have a #\. inside: ~S" pathname)))
1582         (strings ".")
1583         (strings (unparse-logical-piece type)))
1584       (when version-supplied
1585         (unless type-supplied
1586           (error "cannot specify the version without a type: ~S" pathname))
1587         (etypecase version
1588           ((member :newest) (strings ".NEWEST"))
1589           ((member :wild) (strings ".*"))
1590           (fixnum (strings ".") (strings (format nil "~D" version))))))
1591     (apply #'concatenate 'simple-string (strings))))
1592
1593 ;;; Unparse a logical pathname string.
1594 (defun unparse-enough-namestring (pathname defaults)
1595   (let* ((path-directory (pathname-directory pathname))
1596          (def-directory (pathname-directory defaults))
1597          (enough-directory
1598            ;; Go down the directory lists to see what matches.  What's
1599            ;; left is what we want, more or less.
1600            (cond ((and (eq (first path-directory) (first def-directory))
1601                        (eq (first path-directory) :absolute))
1602                    ;; Both paths are :ABSOLUTE, so find where the
1603                    ;; common parts end and return what's left
1604                    (do* ((p (rest path-directory) (rest p))
1605                          (d (rest def-directory) (rest d)))
1606                         ((or (endp p) (endp d)
1607                              (not (equal (first p) (first d))))
1608                          `(:relative ,@p))))
1609                  (t
1610                    ;; At least one path is :RELATIVE, so just return the
1611                    ;; original path.  If the original path is :RELATIVE,
1612                    ;; then that's the right one.  If PATH-DIRECTORY is
1613                    ;; :ABSOLUTE, we want to return that except when
1614                    ;; DEF-DIRECTORY is :ABSOLUTE, as handled above. so return
1615                    ;; the original directory.
1616                    path-directory))))
1617     (unparse-logical-namestring
1618      (make-pathname :host (pathname-host pathname)
1619                     :directory enough-directory
1620                     :name (pathname-name pathname)
1621                     :type (pathname-type pathname)
1622                     :version (pathname-version pathname)))))
1623
1624 (defun unparse-logical-namestring (pathname)
1625   (declare (type logical-pathname pathname))
1626   (concatenate 'simple-string
1627                (logical-host-name (%pathname-host pathname)) ":"
1628                (unparse-logical-directory pathname)
1629                (unparse-logical-file pathname)))
1630 \f
1631 ;;;; logical pathname translations
1632
1633 ;;; Verify that the list of translations consists of lists and prepare
1634 ;;; canonical translations. (Parse pathnames and expand out wildcards
1635 ;;; into patterns.)
1636 (defun canonicalize-logical-pathname-translations (translation-list host)
1637   (declare (type list translation-list) (type host host)
1638            (values list))
1639   (mapcar (lambda (translation)
1640             (destructuring-bind (from to) translation
1641               (list (if (typep from 'logical-pathname)
1642                         from
1643                         (parse-namestring from host))
1644                     (pathname to))))
1645           translation-list))
1646
1647 (defun logical-pathname-translations (host)
1648   #!+sb-doc
1649   "Return the (logical) host object argument's list of translations."
1650   (declare (type (or string logical-host) host)
1651            (values list))
1652   (logical-host-translations (find-logical-host host)))
1653
1654 (defun (setf logical-pathname-translations) (translations host)
1655   #!+sb-doc
1656   "Set the translations list for the logical host argument."
1657   (declare (type (or string logical-host) host)
1658            (type list translations)
1659            (values list))
1660   (let ((host (intern-logical-host host)))
1661     (setf (logical-host-canon-transls host)
1662           (canonicalize-logical-pathname-translations translations host))
1663     (setf (logical-host-translations host) translations)))
1664
1665 (defun translate-logical-pathname (pathname &key)
1666   #!+sb-doc
1667   "Translate PATHNAME to a physical pathname, which is returned."
1668   (declare (type pathname-designator pathname)
1669            (values (or null pathname)))
1670   (typecase pathname
1671     (logical-pathname
1672      (dolist (x (logical-host-canon-transls (%pathname-host pathname))
1673                 (error 'simple-file-error
1674                        :pathname pathname
1675                        :format-control "no translation for ~S"
1676                        :format-arguments (list pathname)))
1677        (destructuring-bind (from to) x
1678          (when (pathname-match-p pathname from)
1679            (return (translate-logical-pathname
1680                     (translate-pathname pathname from to)))))))
1681     (pathname pathname)
1682     (t (translate-logical-pathname (pathname pathname)))))
1683
1684 (defvar *logical-pathname-defaults*
1685   (%make-logical-pathname
1686    (make-logical-host :name (logical-word-or-lose "BOGUS"))
1687    :unspecific nil nil nil nil))
1688
1689 (defun load-logical-pathname-translations (host)
1690   #!+sb-doc
1691   "Reads logical pathname translations from SYS:SITE;HOST.TRANSLATIONS.NEWEST,
1692 with HOST replaced by the supplied parameter. Returns T on success.
1693
1694 If HOST is already defined as logical pathname host, no file is loaded and NIL
1695 is returned.
1696
1697 The file should contain a single form, suitable for use with
1698 \(SETF LOGICAL-PATHNAME-TRANSLATIONS).
1699
1700 Note: behaviour of this function is highly implementation dependent, and
1701 historically it used to be a no-op in SBCL -- the current approach is somewhat
1702 experimental and subject to change."
1703   (declare (type string host)
1704            (values (member t nil)))
1705   (if (find-logical-host host nil)
1706       ;; This host is already defined, all is well and good.
1707       nil
1708       ;; ANSI: "The specific nature of the search is
1709       ;; implementation-defined."
1710       (prog1 t
1711         (setf (logical-pathname-translations host)
1712               (with-open-file (lpt (make-pathname :host "SYS"
1713                                                   :directory '(:absolute "SITE")
1714                                                   :name host
1715                                                   :type "TRANSLATIONS"
1716                                                   :version :newest))
1717                 (read lpt))))))
1718
1719 (defun !pathname-cold-init ()
1720   (let* ((sys *default-pathname-defaults*)
1721          (src
1722           (merge-pathnames
1723            (make-pathname :directory '(:relative "src" :wild-inferiors)
1724                           :name :wild :type :wild)
1725            sys))
1726          (contrib
1727           (merge-pathnames
1728            (make-pathname :directory '(:relative "contrib" :wild-inferiors)
1729                           :name :wild :type :wild)
1730            sys))
1731          (output
1732           (merge-pathnames
1733            (make-pathname :directory '(:relative "output" :wild-inferiors)
1734                           :name :wild :type :wild)
1735            sys)))
1736     (setf (logical-pathname-translations "SYS")
1737           `(("SYS:SRC;**;*.*.*" ,src)
1738             ("SYS:CONTRIB;**;*.*.*" ,contrib)
1739             ("SYS:OUTPUT;**;*.*.*" ,output)))))
1740
1741 (defun set-sbcl-source-location (pathname)
1742   "Initialize the SYS logical host based on PATHNAME, which should be
1743 the top-level directory of the SBCL sources. This will replace any
1744 existing translations for \"SYS:SRC;\", \"SYS:CONTRIB;\", and
1745 \"SYS:OUTPUT;\". Other \"SYS:\" translations are preserved."
1746   (let ((truename (truename pathname))
1747         (current-translations
1748          (remove-if (lambda (translation)
1749                       (or (pathname-match-p "SYS:SRC;" translation)
1750                           (pathname-match-p "SYS:CONTRIB;" translation)
1751                           (pathname-match-p "SYS:OUTPUT;" translation)))
1752                     (logical-pathname-translations "SYS")
1753                     :key #'first)))
1754     (flet ((physical-target (component)
1755              (merge-pathnames
1756               (make-pathname :directory (list :relative component
1757                                               :wild-inferiors)
1758                              :name :wild
1759                              :type :wild)
1760               truename)))
1761       (setf (logical-pathname-translations "SYS")
1762             `(("SYS:SRC;**;*.*.*" ,(physical-target "src"))
1763               ("SYS:CONTRIB;**;*.*.*" ,(physical-target "contrib"))
1764               ("SYS:OUTPUT;**;*.*.*" ,(physical-target "output"))
1765               ,@current-translations)))))