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