1.0.43.75: pathnames: both Unix and Win32 use UNPARSE-PHYSICAL-DIRECTORY
[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-physical-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-physical-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 :synchronized t))
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 (eval-when (:compile-toplevel :execute)
290 (sb!xc: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 (sb!xc: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 (sb!xc: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 ) ; EVAL-WHEN
367
368 (defun find-host (host-designator &optional (errorp t))
369   (with-host (host host-designator)
370     (when (and errorp (not host))
371       (error "Couldn't find host: ~S" host-designator))
372     host))
373
374 (defun pathname (pathspec)
375   #!+sb-doc
376   "Convert PATHSPEC (a pathname designator) into a pathname."
377   (declare (type pathname-designator pathspec))
378   (with-pathname (pathname pathspec)
379     pathname))
380
381 (defun native-pathname (pathspec)
382   #!+sb-doc
383   "Convert PATHSPEC (a pathname designator) into a pathname, assuming
384 the operating system native pathname conventions."
385   (with-native-pathname (pathname pathspec)
386     pathname))
387
388 ;;; Change the case of thing if DIDDLE-P.
389 (defun maybe-diddle-case (thing diddle-p)
390   (if (and diddle-p (not (or (symbolp thing) (integerp thing))))
391       (labels ((check-for (pred in)
392                  (typecase in
393                    (pattern
394                     (dolist (piece (pattern-pieces in))
395                       (when (typecase piece
396                               (simple-string
397                                (check-for pred piece))
398                               (cons
399                                (case (car piece)
400                                  (:character-set
401                                   (check-for pred (cdr piece))))))
402                         (return t))))
403                    (list
404                     (dolist (x in)
405                       (when (check-for pred x)
406                         (return t))))
407                    (simple-string
408                     (dotimes (i (length in))
409                       (when (funcall pred (schar in i))
410                         (return t))))
411                    (t nil)))
412                (diddle-with (fun thing)
413                  (typecase thing
414                    (pattern
415                     (make-pattern
416                      (mapcar (lambda (piece)
417                                (typecase piece
418                                  (simple-string
419                                   (funcall fun piece))
420                                  (cons
421                                   (case (car piece)
422                                     (:character-set
423                                      (cons :character-set
424                                            (funcall fun (cdr piece))))
425                                     (t
426                                      piece)))
427                                  (t
428                                   piece)))
429                              (pattern-pieces thing))))
430                    (list
431                     (mapcar fun thing))
432                    (simple-string
433                     (funcall fun thing))
434                    (t
435                     thing))))
436         (let ((any-uppers (check-for #'upper-case-p thing))
437               (any-lowers (check-for #'lower-case-p thing)))
438           (cond ((and any-uppers any-lowers)
439                  ;; mixed case, stays the same
440                  thing)
441                 (any-uppers
442                  ;; all uppercase, becomes all lower case
443                  (diddle-with (lambda (x) (if (stringp x)
444                                               (string-downcase x)
445                                               x)) thing))
446                 (any-lowers
447                  ;; all lowercase, becomes all upper case
448                  (diddle-with (lambda (x) (if (stringp x)
449                                               (string-upcase x)
450                                               x)) thing))
451                 (t
452                  ;; no letters?  I guess just leave it.
453                  thing))))
454       thing))
455
456 (defun merge-directories (dir1 dir2 diddle-case)
457   (if (or (eq (car dir1) :absolute)
458           (null dir2))
459       dir1
460       (let ((results nil))
461         (flet ((add (dir)
462                  (if (and (eq dir :back)
463                           results
464                           (not (member (car results)
465                                        '(:back :wild-inferiors :relative :absolute))))
466                      (pop results)
467                      (push dir results))))
468           (dolist (dir (maybe-diddle-case dir2 diddle-case))
469             (add dir))
470           (dolist (dir (cdr dir1))
471             (add dir)))
472         (reverse results))))
473
474 (defun merge-pathnames (pathname
475                         &optional
476                         (defaults *default-pathname-defaults*)
477                         (default-version :newest))
478   #!+sb-doc
479   "Construct a filled in pathname by completing the unspecified components
480    from the defaults."
481   (declare (type pathname-designator pathname)
482            (type pathname-designator defaults)
483            (values pathname))
484   (with-pathname (defaults defaults)
485     (let ((pathname (let ((*default-pathname-defaults* defaults))
486                       (pathname pathname))))
487       (let* ((default-host (%pathname-host defaults))
488              (pathname-host (%pathname-host pathname))
489              (diddle-case
490               (and default-host pathname-host
491                    (not (eq (host-customary-case default-host)
492                             (host-customary-case pathname-host))))))
493         (%make-maybe-logical-pathname
494          (or pathname-host default-host)
495          (or (%pathname-device pathname)
496              (maybe-diddle-case (%pathname-device defaults)
497                                 diddle-case))
498          (merge-directories (%pathname-directory pathname)
499                             (%pathname-directory defaults)
500                             diddle-case)
501          (or (%pathname-name pathname)
502              (maybe-diddle-case (%pathname-name defaults)
503                                 diddle-case))
504          (or (%pathname-type pathname)
505              (maybe-diddle-case (%pathname-type defaults)
506                                 diddle-case))
507          (or (%pathname-version pathname)
508              (and (not (%pathname-name pathname)) (%pathname-version defaults))
509              default-version))))))
510
511 (defun import-directory (directory diddle-case)
512   (etypecase directory
513     (null nil)
514     ((member :wild) '(:absolute :wild-inferiors))
515     ((member :unspecific) '(:relative))
516     (list
517      (collect ((results))
518        (results (pop directory))
519        (dolist (piece directory)
520          (cond ((member piece '(:wild :wild-inferiors :up :back))
521                 (results piece))
522                ((or (simple-string-p piece) (pattern-p piece))
523                 (results (maybe-diddle-case piece diddle-case)))
524                ((stringp piece)
525                 (results (maybe-diddle-case (coerce piece 'simple-string)
526                                             diddle-case)))
527                (t
528                 (error "~S is not allowed as a directory component." piece))))
529        (results)))
530     (simple-string
531      `(:absolute ,(maybe-diddle-case directory diddle-case)))
532     (string
533      `(:absolute
534        ,(maybe-diddle-case (coerce directory 'simple-string) diddle-case)))))
535
536 (defun make-pathname (&key host
537                            (device nil devp)
538                            (directory nil dirp)
539                            (name nil namep)
540                            (type nil typep)
541                            (version nil versionp)
542                            defaults
543                            (case :local))
544   #!+sb-doc
545   "Makes a new pathname from the component arguments. Note that host is
546 a host-structure or string."
547   (declare (type (or string host pathname-component-tokens) host)
548            (type (or string pathname-component-tokens) device)
549            (type (or list string pattern pathname-component-tokens) directory)
550            (type (or string pattern pathname-component-tokens) name type)
551            (type (or integer pathname-component-tokens (member :newest))
552                  version)
553            (type (or pathname-designator null) defaults)
554            (type (member :common :local) case))
555   (let* ((defaults (when defaults
556                      (with-pathname (defaults defaults) defaults)))
557          (default-host (if defaults
558                            (%pathname-host defaults)
559                            (pathname-host *default-pathname-defaults*)))
560          ;; Raymond Toy writes: CLHS says make-pathname can take a
561          ;; string (as a logical-host) for the host part. We map that
562          ;; string into the corresponding logical host structure.
563          ;;
564          ;; Paul Werkowski writes:
565          ;; HyperSpec says for the arg to MAKE-PATHNAME;
566          ;; "host---a valid physical pathname host. ..."
567          ;; where it probably means -- a valid pathname host.
568          ;; "valid pathname host n. a valid physical pathname host or
569          ;; a valid logical pathname host."
570          ;; and defines
571          ;; "valid physical pathname host n. any of a string,
572          ;; a list of strings, or the symbol :unspecific,
573          ;; that is recognized by the implementation as the name of a host."
574          ;; "valid logical pathname host n. a string that has been defined
575          ;; as the name of a logical host. ..."
576          ;; HS is silent on what happens if the :HOST arg is NOT one of these.
577          ;; It seems an error message is appropriate.
578          (host (or (find-host host nil) default-host))
579          (diddle-args (and (eq (host-customary-case host) :lower)
580                            (eq case :common)))
581          (diddle-defaults
582           (not (eq (host-customary-case host)
583                    (host-customary-case default-host))))
584          (dev (if devp device (if defaults (%pathname-device defaults))))
585          (dir (import-directory directory diddle-args))
586          (ver (cond
587                (versionp version)
588                (defaults (%pathname-version defaults))
589                (t nil))))
590     (when (and defaults (not dirp))
591       (setf dir
592             (merge-directories dir
593                                (%pathname-directory defaults)
594                                diddle-defaults)))
595
596     (macrolet ((pick (var varp field)
597                  `(cond ((or (simple-string-p ,var)
598                              (pattern-p ,var))
599                          (maybe-diddle-case ,var diddle-args))
600                         ((stringp ,var)
601                          (maybe-diddle-case (coerce ,var 'simple-string)
602                                             diddle-args))
603                         (,varp
604                          (maybe-diddle-case ,var diddle-args))
605                         (defaults
606                          (maybe-diddle-case (,field defaults)
607                                             diddle-defaults))
608                         (t
609                          nil))))
610       (%make-maybe-logical-pathname host
611                                     dev ; forced to :UNSPECIFIC when logical
612                                     dir
613                                     (pick name namep %pathname-name)
614                                     (pick type typep %pathname-type)
615                                     ver))))
616
617 (defun pathname-host (pathname &key (case :local))
618   #!+sb-doc
619   "Return PATHNAME's host."
620   (declare (type pathname-designator pathname)
621            (type (member :local :common) case)
622            (values host)
623            (ignore case))
624   (with-pathname (pathname pathname)
625     (%pathname-host pathname)))
626
627 (defun pathname-device (pathname &key (case :local))
628   #!+sb-doc
629   "Return PATHNAME's device."
630   (declare (type pathname-designator pathname)
631            (type (member :local :common) case))
632   (with-pathname (pathname pathname)
633     (maybe-diddle-case (%pathname-device pathname)
634                        (and (eq case :common)
635                             (eq (host-customary-case
636                                  (%pathname-host pathname))
637                                 :lower)))))
638
639 (defun pathname-directory (pathname &key (case :local))
640   #!+sb-doc
641   "Return PATHNAME's directory."
642   (declare (type pathname-designator pathname)
643            (type (member :local :common) case))
644   (with-pathname (pathname pathname)
645     (maybe-diddle-case (%pathname-directory pathname)
646                        (and (eq case :common)
647                             (eq (host-customary-case
648                                  (%pathname-host pathname))
649                                 :lower)))))
650 (defun pathname-name (pathname &key (case :local))
651   #!+sb-doc
652   "Return PATHNAME's name."
653   (declare (type pathname-designator pathname)
654            (type (member :local :common) case))
655   (with-pathname (pathname pathname)
656     (maybe-diddle-case (%pathname-name pathname)
657                        (and (eq case :common)
658                             (eq (host-customary-case
659                                  (%pathname-host pathname))
660                                 :lower)))))
661
662 (defun pathname-type (pathname &key (case :local))
663   #!+sb-doc
664   "Return PATHNAME's type."
665   (declare (type pathname-designator pathname)
666            (type (member :local :common) case))
667   (with-pathname (pathname pathname)
668     (maybe-diddle-case (%pathname-type pathname)
669                        (and (eq case :common)
670                             (eq (host-customary-case
671                                  (%pathname-host pathname))
672                                 :lower)))))
673
674 (defun pathname-version (pathname)
675   #!+sb-doc
676   "Return PATHNAME's version."
677   (declare (type pathname-designator pathname))
678   (with-pathname (pathname pathname)
679     (%pathname-version pathname)))
680 \f
681 ;;;; namestrings
682
683 ;;; Handle the case for PARSE-NAMESTRING parsing a potentially
684 ;;; syntactically valid logical namestring with an explicit host.
685 ;;;
686 ;;; This then isn't fully general -- we are relying on the fact that
687 ;;; we will only pass to parse-namestring namestring with an explicit
688 ;;; logical host, so that we can pass the host return from
689 ;;; parse-logical-namestring through to %PARSE-NAMESTRING as a truth
690 ;;; value. Yeah, this is probably a KLUDGE - CSR, 2002-04-18
691 (defun parseable-logical-namestring-p (namestr start end)
692   (catch 'exit
693     (handler-bind
694         ((namestring-parse-error (lambda (c)
695                                    (declare (ignore c))
696                                    (throw 'exit nil))))
697       (let ((colon (position #\: namestr :start start :end end)))
698         (when colon
699           (let ((potential-host
700                  (logical-word-or-lose (subseq namestr start colon))))
701             ;; depending on the outcome of CSR comp.lang.lisp post
702             ;; "can PARSE-NAMESTRING create logical hosts", we may need
703             ;; to do things with potential-host (create it
704             ;; temporarily, parse the namestring and unintern the
705             ;; logical host potential-host on failure.
706             (declare (ignore potential-host))
707             (let ((result
708                    (handler-bind
709                        ((simple-type-error (lambda (c)
710                                              (declare (ignore c))
711                                              (throw 'exit nil))))
712                      (parse-logical-namestring namestr start end))))
713               ;; if we got this far, we should have an explicit host
714               ;; (first return value of parse-logical-namestring)
715               (aver result)
716               result)))))))
717
718 ;;; Handle the case where PARSE-NAMESTRING is actually parsing a
719 ;;; namestring. We pick off the :JUNK-ALLOWED case then find a host to
720 ;;; use for parsing, call the parser, then check whether the host matches.
721 (defun %parse-namestring (namestr host defaults start end junk-allowed)
722   (declare (type (or host null) host)
723            (type string namestr)
724            (type index start)
725            (type (or index null) end))
726   (cond
727     (junk-allowed
728      (handler-case
729          (%parse-namestring namestr host defaults start end nil)
730        (namestring-parse-error (condition)
731          (values nil (namestring-parse-error-offset condition)))))
732     (t
733      (let* ((end (%check-vector-sequence-bounds namestr start end)))
734        (multiple-value-bind (new-host device directory file type version)
735            ;; Comments below are quotes from the HyperSpec
736            ;; PARSE-NAMESTRING entry, reproduced here to demonstrate
737            ;; that we actually have to do things this way rather than
738            ;; some possibly more logical way. - CSR, 2002-04-18
739            (cond
740              ;; "If host is a logical host then thing is parsed as a
741              ;; logical pathname namestring on the host."
742              (host (funcall (host-parse host) namestr start end))
743              ;; "If host is nil and thing is a syntactically valid
744              ;; logical pathname namestring containing an explicit
745              ;; host, then it is parsed as a logical pathname
746              ;; namestring."
747              ((parseable-logical-namestring-p namestr start end)
748               (parse-logical-namestring namestr start end))
749              ;; "If host is nil, default-pathname is a logical
750              ;; pathname, and thing is a syntactically valid logical
751              ;; pathname namestring without an explicit host, then it
752              ;; is parsed as a logical pathname namestring on the
753              ;; host that is the host component of default-pathname."
754              ;;
755              ;; "Otherwise, the parsing of thing is
756              ;; implementation-defined."
757              ;;
758              ;; Both clauses are handled here, as the default
759              ;; *DEFAULT-PATHNAME-DEFAULTS* has a SB-IMPL::UNIX-HOST
760              ;; for a host.
761              ((pathname-host defaults)
762               (funcall (host-parse (pathname-host defaults))
763                        namestr
764                        start
765                        end))
766              ;; I don't think we should ever get here, as the default
767              ;; host will always have a non-null HOST, given that we
768              ;; can't create a new pathname without going through
769              ;; *DEFAULT-PATHNAME-DEFAULTS*, which has a non-null
770              ;; host...
771              (t (bug "Fallen through COND in %PARSE-NAMESTRING")))
772          (when (and host new-host (not (eq new-host host)))
773            (error 'simple-type-error
774                   :datum new-host
775                   ;; Note: ANSI requires that this be a TYPE-ERROR,
776                   ;; but there seems to be no completely correct
777                   ;; value to use for TYPE-ERROR-EXPECTED-TYPE.
778                   ;; Instead, we return a sort of "type error allowed
779                   ;; type", trying to say "it would be OK if you
780                   ;; passed NIL as the host value" but not mentioning
781                   ;; that a matching string would be OK too.
782                   :expected-type 'null
783                   :format-control
784                   "The host in the namestring, ~S,~@
785                    does not match the explicit HOST argument, ~S."
786                   :format-arguments (list new-host host)))
787          (let ((pn-host (or new-host host (pathname-host defaults))))
788            (values (%make-maybe-logical-pathname
789                     pn-host device directory file type version)
790                    end)))))))
791
792 ;;; If NAMESTR begins with a colon-terminated, defined, logical host,
793 ;;; then return that host, otherwise return NIL.
794 (defun extract-logical-host-prefix (namestr start end)
795   (declare (type simple-string namestr)
796            (type index start end)
797            (values (or logical-host null)))
798   (let ((colon-pos (position #\: namestr :start start :end end)))
799     (if colon-pos
800         (values (gethash (nstring-upcase (subseq namestr start colon-pos))
801                          *logical-hosts*))
802         nil)))
803
804 (defun parse-namestring (thing
805                          &optional
806                          host
807                          (defaults *default-pathname-defaults*)
808                          &key (start 0) end junk-allowed)
809   (declare (type pathname-designator thing defaults)
810            (type (or list host string (member :unspecific)) host)
811            (type index start)
812            (type (or index null) end)
813            (type (or t null) junk-allowed)
814            (values (or null pathname) (or null index)))
815   (with-host (found-host host)
816     (let (;; According to ANSI defaults may be any valid pathname designator
817           (defaults (etypecase defaults
818                       (pathname
819                        defaults)
820                       (string
821                        (aver (pathnamep *default-pathname-defaults*))
822                        (parse-namestring defaults))
823                       (stream
824                        (truename defaults)))))
825       (declare (type pathname defaults))
826       (etypecase thing
827         (simple-string
828          (%parse-namestring thing found-host defaults start end junk-allowed))
829         (string
830          (%parse-namestring (coerce thing 'simple-string)
831                             found-host defaults start end junk-allowed))
832         (pathname
833          (let ((defaulted-host (or found-host (%pathname-host defaults))))
834            (declare (type host defaulted-host))
835            (unless (eq defaulted-host (%pathname-host thing))
836              (error "The HOST argument doesn't match the pathname host:~%  ~
837                     ~S and ~S."
838                     defaulted-host (%pathname-host thing))))
839          (values thing start))
840         (stream
841          (let ((name (file-name thing)))
842            (unless name
843              (error "can't figure out the file associated with stream:~%  ~S"
844                     thing))
845            (values name nil)))))))
846
847 (defun %parse-native-namestring (namestr host defaults start end junk-allowed
848                                  as-directory)
849   (declare (type (or host null) host)
850            (type string namestr)
851            (type index start)
852            (type (or index null) end))
853   (cond
854     (junk-allowed
855      (handler-case
856          (%parse-namestring namestr host defaults start end nil)
857        (namestring-parse-error (condition)
858          (values nil (namestring-parse-error-offset condition)))))
859     (t
860      (let* ((end (%check-vector-sequence-bounds namestr start end)))
861        (multiple-value-bind (new-host device directory file type version)
862            (cond
863              (host
864               (funcall (host-parse-native host) namestr start end as-directory))
865              ((pathname-host defaults)
866               (funcall (host-parse-native (pathname-host defaults))
867                        namestr
868                        start
869                        end
870                        as-directory))
871              ;; I don't think we should ever get here, as the default
872              ;; host will always have a non-null HOST, given that we
873              ;; can't create a new pathname without going through
874              ;; *DEFAULT-PATHNAME-DEFAULTS*, which has a non-null
875              ;; host...
876              (t (bug "Fallen through COND in %PARSE-NAMESTRING")))
877          (when (and host new-host (not (eq new-host host)))
878            (error 'simple-type-error
879                   :datum new-host
880                   :expected-type `(or null (eql ,host))
881                   :format-control
882                   "The host in the namestring, ~S,~@
883                    does not match the explicit HOST argument, ~S."
884                   :format-arguments (list new-host host)))
885          (let ((pn-host (or new-host host (pathname-host defaults))))
886            (values (%make-pathname
887                     pn-host device directory file type version)
888                    end)))))))
889
890 (defun parse-native-namestring (thing
891                                 &optional
892                                 host
893                                 (defaults *default-pathname-defaults*)
894                                 &key (start 0) end junk-allowed
895                                 as-directory)
896   #!+sb-doc
897   "Convert THING into a pathname, using the native conventions
898 appropriate for the pathname host HOST, or if not specified the
899 host of DEFAULTS.  If THING is a string, the parse is bounded by
900 START and END, and error behaviour is controlled by JUNK-ALLOWED,
901 as with PARSE-NAMESTRING.  For file systems whose native
902 conventions allow directories to be indicated as files, if
903 AS-DIRECTORY is true, return a pathname denoting THING as a
904 directory."
905   (declare (type pathname-designator thing defaults)
906            (type (or list host string (member :unspecific)) host)
907            (type index start)
908            (type (or index null) end)
909            (type (or t null) junk-allowed)
910            (values (or null pathname) (or null index)))
911   (with-host (found-host host)
912     (let ((defaults (etypecase defaults
913                       (pathname
914                        defaults)
915                       (string
916                        (aver (pathnamep *default-pathname-defaults*))
917                        (parse-native-namestring defaults))
918                       (stream
919                        (truename defaults)))))
920       (declare (type pathname defaults))
921       (etypecase thing
922         (simple-string
923          (%parse-native-namestring
924           thing found-host defaults start end junk-allowed as-directory))
925         (string
926          (%parse-native-namestring (coerce thing 'simple-string)
927                                    found-host defaults start end junk-allowed
928                                    as-directory))
929         (pathname
930          (let ((defaulted-host (or found-host (%pathname-host defaults))))
931            (declare (type host defaulted-host))
932            (unless (eq defaulted-host (%pathname-host thing))
933              (error "The HOST argument doesn't match the pathname host:~%  ~
934                      ~S and ~S."
935                     defaulted-host (%pathname-host thing))))
936          (values thing start))
937         (stream
938          ;; FIXME
939          (let ((name (file-name thing)))
940            (unless name
941              (error "can't figure out the file associated with stream:~%  ~S"
942                     thing))
943            (values name nil)))))))
944
945 (defun namestring (pathname)
946   #!+sb-doc
947   "Construct the full (name)string form of the pathname."
948   (declare (type pathname-designator pathname))
949   (with-pathname (pathname pathname)
950     (when pathname
951       (let ((host (%pathname-host pathname)))
952         (unless host
953           (error "can't determine the namestring for pathnames with no ~
954                   host:~%  ~S" pathname))
955         (funcall (host-unparse host) pathname)))))
956
957 (defun native-namestring (pathname &key as-file)
958   #!+sb-doc
959   "Construct the full native (name)string form of PATHNAME.  For
960 file systems whose native conventions allow directories to be
961 indicated as files, if AS-FILE is true and the name, type, and
962 version components of PATHNAME are all NIL or :UNSPECIFIC,
963 construct a string that names the directory according to the file
964 system's syntax for files."
965   (declare (type pathname-designator pathname))
966   (with-native-pathname (pathname pathname)
967     (when pathname
968       (let ((host (%pathname-host pathname)))
969         (unless host
970           (error "can't determine the native namestring for pathnames with no ~
971                   host:~%  ~S" pathname))
972         (funcall (host-unparse-native host) pathname as-file)))))
973
974 (defun host-namestring (pathname)
975   #!+sb-doc
976   "Return a string representation of the name of the host in the pathname."
977   (declare (type pathname-designator pathname))
978   (with-pathname (pathname pathname)
979     (let ((host (%pathname-host pathname)))
980       (if host
981           (funcall (host-unparse-host host) pathname)
982           (error
983            "can't determine the namestring for pathnames with no host:~%  ~S"
984            pathname)))))
985
986 (defun directory-namestring (pathname)
987   #!+sb-doc
988   "Return a string representation of the directories used in the pathname."
989   (declare (type pathname-designator pathname))
990   (with-pathname (pathname pathname)
991     (let ((host (%pathname-host pathname)))
992       (if host
993           (funcall (host-unparse-directory host) pathname)
994           (error
995            "can't determine the namestring for pathnames with no host:~%  ~S"
996            pathname)))))
997
998 (defun file-namestring (pathname)
999   #!+sb-doc
1000   "Return a string representation of the name used in the pathname."
1001   (declare (type pathname-designator pathname))
1002   (with-pathname (pathname pathname)
1003     (let ((host (%pathname-host pathname)))
1004       (if host
1005           (funcall (host-unparse-file host) pathname)
1006           (error
1007            "can't determine the namestring for pathnames with no host:~%  ~S"
1008            pathname)))))
1009
1010 (defun enough-namestring (pathname
1011                           &optional
1012                           (defaults *default-pathname-defaults*))
1013   #!+sb-doc
1014   "Return an abbreviated pathname sufficent to identify the pathname relative
1015    to the defaults."
1016   (declare (type pathname-designator pathname))
1017   (with-pathname (pathname pathname)
1018     (let ((host (%pathname-host pathname)))
1019       (if host
1020           (with-pathname (defaults defaults)
1021             (funcall (host-unparse-enough host) pathname defaults))
1022           (error
1023            "can't determine the namestring for pathnames with no host:~%  ~S"
1024            pathname)))))
1025 \f
1026 ;;;; wild pathnames
1027
1028 (defun wild-pathname-p (pathname &optional field-key)
1029   #!+sb-doc
1030   "Predicate for determining whether pathname contains any wildcards."
1031   (declare (type pathname-designator pathname)
1032            (type (member nil :host :device :directory :name :type :version)
1033                  field-key))
1034   (with-pathname (pathname pathname)
1035     (flet ((frob (x)
1036              (or (pattern-p x) (member x '(:wild :wild-inferiors)))))
1037       (ecase field-key
1038         ((nil)
1039          (or (wild-pathname-p pathname :host)
1040              (wild-pathname-p pathname :device)
1041              (wild-pathname-p pathname :directory)
1042              (wild-pathname-p pathname :name)
1043              (wild-pathname-p pathname :type)
1044              (wild-pathname-p pathname :version)))
1045         (:host (frob (%pathname-host pathname)))
1046         (:device (frob (%pathname-host pathname)))
1047         (:directory (some #'frob (%pathname-directory pathname)))
1048         (:name (frob (%pathname-name pathname)))
1049         (:type (frob (%pathname-type pathname)))
1050         (:version (frob (%pathname-version pathname)))))))
1051
1052 (defun pathname-match-p (in-pathname in-wildname)
1053   #!+sb-doc
1054   "Pathname matches the wildname template?"
1055   (declare (type pathname-designator in-pathname))
1056   (with-pathname (pathname in-pathname)
1057     (with-pathname (wildname in-wildname)
1058       (macrolet ((frob (field &optional (op 'components-match))
1059                    `(or (null (,field wildname))
1060                         (,op (,field pathname) (,field wildname)))))
1061         (and (or (null (%pathname-host wildname))
1062                  (eq (%pathname-host wildname) (%pathname-host pathname)))
1063              (frob %pathname-device)
1064              (frob %pathname-directory directory-components-match)
1065              (frob %pathname-name)
1066              (frob %pathname-type)
1067              (or (eq (%pathname-host wildname) *physical-host*)
1068                  (frob %pathname-version)))))))
1069
1070 ;;; Place the substitutions into the pattern and return the string or pattern
1071 ;;; that results. If DIDDLE-CASE is true, we diddle the result case as well,
1072 ;;; in case we are translating between hosts with difference conventional case.
1073 ;;; The second value is the tail of subs with all of the values that we used up
1074 ;;; stripped off. Note that PATTERN-MATCHES matches all consecutive wildcards
1075 ;;; as a single string, so we ignore subsequent contiguous wildcards.
1076 (defun substitute-into (pattern subs diddle-case)
1077   (declare (type pattern pattern)
1078            (type list subs)
1079            (values (or simple-string pattern) list))
1080   (let ((in-wildcard nil)
1081         (pieces nil)
1082         (strings nil))
1083     (dolist (piece (pattern-pieces pattern))
1084       (cond ((simple-string-p piece)
1085              (push piece strings)
1086              (setf in-wildcard nil))
1087             (in-wildcard)
1088             (t
1089              (setf in-wildcard t)
1090              (unless subs
1091                (error "not enough wildcards in FROM pattern to match ~
1092                        TO pattern:~%  ~S"
1093                       pattern))
1094              (let ((sub (pop subs)))
1095                (typecase sub
1096                  (pattern
1097                   (when strings
1098                     (push (apply #'concatenate 'simple-string
1099                                  (nreverse strings))
1100                           pieces))
1101                   (dolist (piece (pattern-pieces sub))
1102                     (push piece pieces)))
1103                  (simple-string
1104                   (push sub strings))
1105                  (t
1106                   (error "can't substitute this into the middle of a word:~
1107                           ~%  ~S"
1108                          sub)))))))
1109
1110     (when strings
1111       (push (apply #'concatenate 'simple-string (nreverse strings))
1112             pieces))
1113     (values
1114      (maybe-diddle-case
1115       (if (and pieces (simple-string-p (car pieces)) (null (cdr pieces)))
1116           (car pieces)
1117           (make-pattern (nreverse pieces)))
1118       diddle-case)
1119      subs)))
1120
1121 ;;; Called when we can't see how source and from matched.
1122 (defun didnt-match-error (source from)
1123   (error "Pathname components from SOURCE and FROM args to TRANSLATE-PATHNAME~@
1124           did not match:~%  ~S ~S"
1125          source from))
1126
1127 ;;; Do TRANSLATE-COMPONENT for all components except host, directory
1128 ;;; and version.
1129 (defun translate-component (source from to diddle-case)
1130   (typecase to
1131     (pattern
1132      (typecase from
1133        (pattern
1134         (typecase source
1135           (pattern
1136            (if (pattern= from source)
1137                source
1138                (didnt-match-error source from)))
1139           (simple-string
1140            (multiple-value-bind (won subs) (pattern-matches from source)
1141              (if won
1142                  (values (substitute-into to subs diddle-case))
1143                  (didnt-match-error source from))))
1144           (t
1145            (maybe-diddle-case source diddle-case))))
1146        ((member :wild)
1147         (values (substitute-into to (list source) diddle-case)))
1148        (t
1149         (if (components-match source from)
1150             (maybe-diddle-case source diddle-case)
1151             (didnt-match-error source from)))))
1152     ((member nil :wild)
1153      (maybe-diddle-case source diddle-case))
1154     (t
1155      (if (components-match source from)
1156          to
1157          (didnt-match-error source from)))))
1158
1159 ;;; Return a list of all the things that we want to substitute into the TO
1160 ;;; pattern (the things matched by from on source.)  When From contains
1161 ;;; :WILD-INFERIORS, the result contains a sublist of the matched source
1162 ;;; subdirectories.
1163 (defun compute-directory-substitutions (orig-source orig-from)
1164   (let ((source orig-source)
1165         (from orig-from))
1166     (collect ((subs))
1167       (loop
1168         (unless source
1169           (unless (every (lambda (x) (eq x :wild-inferiors)) from)
1170             (didnt-match-error orig-source orig-from))
1171           (subs ())
1172           (return))
1173         (unless from (didnt-match-error orig-source orig-from))
1174         (let ((from-part (pop from))
1175               (source-part (pop source)))
1176           (typecase from-part
1177             (pattern
1178              (typecase source-part
1179                (pattern
1180                 (if (pattern= from-part source-part)
1181                     (subs source-part)
1182                     (didnt-match-error orig-source orig-from)))
1183                (simple-string
1184                 (multiple-value-bind (won new-subs)
1185                     (pattern-matches from-part source-part)
1186                   (if won
1187                       (dolist (sub new-subs)
1188                         (subs sub))
1189                       (didnt-match-error orig-source orig-from))))
1190                (t
1191                 (didnt-match-error orig-source orig-from))))
1192             ((member :wild)
1193              (subs source-part))
1194             ((member :wild-inferiors)
1195              (let ((remaining-source (cons source-part source)))
1196                (collect ((res))
1197                  (loop
1198                    (when (directory-components-match remaining-source from)
1199                      (return))
1200                    (unless remaining-source
1201                      (didnt-match-error orig-source orig-from))
1202                    (res (pop remaining-source)))
1203                  (subs (res))
1204                  (setq source remaining-source))))
1205             (simple-string
1206              (unless (and (simple-string-p source-part)
1207                           (string= from-part source-part))
1208                (didnt-match-error orig-source orig-from)))
1209             (t
1210              (didnt-match-error orig-source orig-from)))))
1211       (subs))))
1212
1213 ;;; This is called by TRANSLATE-PATHNAME on the directory components
1214 ;;; of its argument pathnames to produce the result directory
1215 ;;; component. If this leaves the directory NIL, we return the source
1216 ;;; directory. The :RELATIVE or :ABSOLUTE is taken from the source
1217 ;;; directory, except if TO is :ABSOLUTE, in which case the result
1218 ;;; will be :ABSOLUTE.
1219 (defun translate-directories (source from to diddle-case)
1220   (if (not (and source to from))
1221       (or (and to (null source) (remove :wild-inferiors to))
1222           (mapcar (lambda (x) (maybe-diddle-case x diddle-case)) source))
1223       (collect ((res))
1224                ;; If TO is :ABSOLUTE, the result should still be :ABSOLUTE.
1225                (res (if (eq (first to) :absolute)
1226                  :absolute
1227                  (first source)))
1228         (let ((subs-left (compute-directory-substitutions (rest source)
1229                                                           (rest from))))
1230           (dolist (to-part (rest to))
1231             (typecase to-part
1232               ((member :wild)
1233                (aver subs-left)
1234                (let ((match (pop subs-left)))
1235                  (when (listp match)
1236                    (error ":WILD-INFERIORS is not paired in from and to ~
1237                            patterns:~%  ~S ~S" from to))
1238                  (res (maybe-diddle-case match diddle-case))))
1239               ((member :wild-inferiors)
1240                (aver subs-left)
1241                (let ((match (pop subs-left)))
1242                  (unless (listp match)
1243                    (error ":WILD-INFERIORS not paired in from and to ~
1244                            patterns:~%  ~S ~S" from to))
1245                  (dolist (x match)
1246                    (res (maybe-diddle-case x diddle-case)))))
1247               (pattern
1248                (multiple-value-bind
1249                    (new new-subs-left)
1250                    (substitute-into to-part subs-left diddle-case)
1251                  (setf subs-left new-subs-left)
1252                  (res new)))
1253               (t (res to-part)))))
1254         (res))))
1255
1256 (defun translate-pathname (source from-wildname to-wildname &key)
1257   #!+sb-doc
1258   "Use the source pathname to translate the from-wildname's wild and
1259 unspecified elements into a completed to-pathname based on the to-wildname."
1260   (declare (type pathname-designator source from-wildname to-wildname))
1261   (with-pathname (source source)
1262     (with-pathname (from from-wildname)
1263       (with-pathname (to to-wildname)
1264           (let* ((source-host (%pathname-host source))
1265                  (from-host (%pathname-host from))
1266                  (to-host (%pathname-host to))
1267                  (diddle-case
1268                   (and source-host to-host
1269                        (not (eq (host-customary-case source-host)
1270                                 (host-customary-case to-host))))))
1271             (macrolet ((frob (field &optional (op 'translate-component))
1272                          `(let ((result (,op (,field source)
1273                                              (,field from)
1274                                              (,field to)
1275                                              diddle-case)))
1276                             (if (eq result :error)
1277                                 (error "~S doesn't match ~S." source from)
1278                                 result))))
1279               (%make-maybe-logical-pathname
1280                (or to-host source-host)
1281                (frob %pathname-device)
1282                (frob %pathname-directory translate-directories)
1283                (frob %pathname-name)
1284                (frob %pathname-type)
1285                (if (eq from-host *unix-host*)
1286                    (if (or (eq (%pathname-version to) :wild)
1287                            (eq (%pathname-version to) nil))
1288                        (%pathname-version source)
1289                        (%pathname-version to))
1290                    (frob %pathname-version)))))))))
1291 \f
1292 ;;;;  logical pathname support. ANSI 92-102 specification.
1293 ;;;;
1294 ;;;;  As logical-pathname translations are loaded they are
1295 ;;;;  canonicalized as patterns to enable rapid efficient translation
1296 ;;;;  into physical pathnames.
1297
1298 ;;;; utilities
1299
1300 (defun simplify-namestring (namestring &optional host)
1301   (funcall (host-simplify-namestring
1302             (or host
1303                 (pathname-host (sane-default-pathname-defaults))))
1304            namestring))
1305
1306 ;;; Canonicalize a logical pathname word by uppercasing it checking that it
1307 ;;; contains only legal characters.
1308 (defun logical-word-or-lose (word)
1309   (declare (string word))
1310   (when (string= word "")
1311     (error 'namestring-parse-error
1312            :complaint "Attempted to treat invalid logical hostname ~
1313                        as a logical host:~%  ~S"
1314            :args (list word)
1315            :namestring word :offset 0))
1316   (let ((word (string-upcase word)))
1317     (dotimes (i (length word))
1318       (let ((ch (schar word i)))
1319         (unless (and (typep ch 'standard-char)
1320                      (or (alpha-char-p ch) (digit-char-p ch) (char= ch #\-)))
1321           (error 'namestring-parse-error
1322                  :complaint "logical namestring character which ~
1323                              is not alphanumeric or hyphen:~%  ~S"
1324                  :args (list ch)
1325                  :namestring word :offset i))))
1326     (coerce word 'string))) ; why not simple-string?
1327
1328 ;;; Given a logical host or string, return a logical host. If ERROR-P
1329 ;;; is NIL, then return NIL when no such host exists.
1330 (defun find-logical-host (thing &optional (errorp t))
1331   (etypecase thing
1332     (string
1333      (let ((found (gethash (logical-word-or-lose thing)
1334                            *logical-hosts*)))
1335        (if (or found (not errorp))
1336            found
1337            ;; This is the error signalled from e.g.
1338            ;; LOGICAL-PATHNAME-TRANSLATIONS when host is not a defined
1339            ;; host, and ANSI specifies that that's a TYPE-ERROR.
1340            (error 'simple-type-error
1341                   :datum thing
1342                   ;; God only knows what ANSI expects us to use for
1343                   ;; the EXPECTED-TYPE here. Maybe this will be OK..
1344                   :expected-type
1345                   '(and string (satisfies logical-pathname-translations))
1346                   :format-control "logical host not yet defined: ~S"
1347                   :format-arguments (list thing)))))
1348     (logical-host thing)))
1349
1350 ;;; Given a logical host name or host, return a logical host, creating
1351 ;;; a new one if necessary.
1352 (defun intern-logical-host (thing)
1353   (declare (values logical-host))
1354   (with-locked-hash-table (*logical-hosts*)
1355     (or (find-logical-host thing nil)
1356         (let* ((name (logical-word-or-lose thing))
1357                (new (make-logical-host :name name)))
1358           (setf (gethash name *logical-hosts*) new)
1359           new))))
1360 \f
1361 ;;;; logical pathname parsing
1362
1363 ;;; Deal with multi-char wildcards in a logical pathname token.
1364 (defun maybe-make-logical-pattern (namestring chunks)
1365   (let ((chunk (caar chunks)))
1366     (collect ((pattern))
1367       (let ((last-pos 0)
1368             (len (length chunk)))
1369         (declare (fixnum last-pos))
1370         (loop
1371           (when (= last-pos len) (return))
1372           (let ((pos (or (position #\* chunk :start last-pos) len)))
1373             (if (= pos last-pos)
1374                 (when (pattern)
1375                   (error 'namestring-parse-error
1376                          :complaint "double asterisk inside of logical ~
1377                                      word: ~S"
1378                          :args (list chunk)
1379                          :namestring namestring
1380                          :offset (+ (cdar chunks) pos)))
1381                 (pattern (subseq chunk last-pos pos)))
1382             (if (= pos len)
1383                 (return)
1384                 (pattern :multi-char-wild))
1385             (setq last-pos (1+ pos)))))
1386         (aver (pattern))
1387         (if (cdr (pattern))
1388             (make-pattern (pattern))
1389             (let ((x (car (pattern))))
1390               (if (eq x :multi-char-wild)
1391                   :wild
1392                   x))))))
1393
1394 ;;; Return a list of conses where the CDR is the start position and
1395 ;;; the CAR is a string (token) or character (punctuation.)
1396 (defun logical-chunkify (namestr start end)
1397   (collect ((chunks))
1398     (do ((i start (1+ i))
1399          (prev 0))
1400         ((= i end)
1401          (when (> end prev)
1402             (chunks (cons (nstring-upcase (subseq namestr prev end)) prev))))
1403       (let ((ch (schar namestr i)))
1404         (unless (or (alpha-char-p ch) (digit-char-p ch)
1405                     (member ch '(#\- #\*)))
1406           (when (> i prev)
1407             (chunks (cons (nstring-upcase (subseq namestr prev i)) prev)))
1408           (setq prev (1+ i))
1409           (unless (member ch '(#\; #\: #\.))
1410             (error 'namestring-parse-error
1411                    :complaint "illegal character for logical pathname:~%  ~S"
1412                    :args (list ch)
1413                    :namestring namestr
1414                    :offset i))
1415           (chunks (cons ch i)))))
1416     (chunks)))
1417
1418 ;;; Break up a logical-namestring, always a string, into its
1419 ;;; constituent parts.
1420 (defun parse-logical-namestring (namestr start end)
1421   (declare (type simple-string namestr)
1422            (type index start end))
1423   (collect ((directory))
1424     (let ((host nil)
1425           (name nil)
1426           (type nil)
1427           (version nil))
1428       (labels ((expecting (what chunks)
1429                  (unless (and chunks (simple-string-p (caar chunks)))
1430                    (error 'namestring-parse-error
1431                           :complaint "expecting ~A, got ~:[nothing~;~S~]."
1432                           :args (list what (caar chunks) (caar chunks))
1433                           :namestring namestr
1434                           :offset (if chunks (cdar chunks) end)))
1435                  (caar chunks))
1436                (parse-host (chunks)
1437                  (case (caadr chunks)
1438                    (#\:
1439                     (setq host
1440                           (find-logical-host (expecting "a host name" chunks)))
1441                     (parse-relative (cddr chunks)))
1442                    (t
1443                     (parse-relative chunks))))
1444                (parse-relative (chunks)
1445                  (case (caar chunks)
1446                    (#\;
1447                     (directory :relative)
1448                     (parse-directory (cdr chunks)))
1449                    (t
1450                     (directory :absolute) ; Assumption! Maybe revoked later.
1451                     (parse-directory chunks))))
1452                (parse-directory (chunks)
1453                  (case (caadr chunks)
1454                    (#\;
1455                     (directory
1456                      (let ((res (expecting "a directory name" chunks)))
1457                        (cond ((string= res "..") :up)
1458                              ((string= res "**") :wild-inferiors)
1459                              (t
1460                               (maybe-make-logical-pattern namestr chunks)))))
1461                     (parse-directory (cddr chunks)))
1462                    (t
1463                     (parse-name chunks))))
1464                (parse-name (chunks)
1465                  (when chunks
1466                    (expecting "a file name" chunks)
1467                    (setq name (maybe-make-logical-pattern namestr chunks))
1468                    (expecting-dot (cdr chunks))))
1469                (expecting-dot (chunks)
1470                  (when chunks
1471                    (unless (eql (caar chunks) #\.)
1472                      (error 'namestring-parse-error
1473                             :complaint "expecting a dot, got ~S."
1474                             :args (list (caar chunks))
1475                             :namestring namestr
1476                             :offset (cdar chunks)))
1477                    (if type
1478                        (parse-version (cdr chunks))
1479                        (parse-type (cdr chunks)))))
1480                (parse-type (chunks)
1481                  (expecting "a file type" chunks)
1482                  (setq type (maybe-make-logical-pattern namestr chunks))
1483                  (expecting-dot (cdr chunks)))
1484                (parse-version (chunks)
1485                  (let ((str (expecting "a positive integer, * or NEWEST"
1486                                        chunks)))
1487                    (cond
1488                     ((string= str "*") (setq version :wild))
1489                     ((string= str "NEWEST") (setq version :newest))
1490                     (t
1491                      (multiple-value-bind (res pos)
1492                          (parse-integer str :junk-allowed t)
1493                        (unless (and res (plusp res))
1494                          (error 'namestring-parse-error
1495                                 :complaint "expected a positive integer, ~
1496                                             got ~S"
1497                                 :args (list str)
1498                                 :namestring namestr
1499                                 :offset (+ pos (cdar chunks))))
1500                        (setq version res)))))
1501                  (when (cdr chunks)
1502                    (error 'namestring-parse-error
1503                           :complaint "extra stuff after end of file name"
1504                           :namestring namestr
1505                           :offset (cdadr chunks)))))
1506         (parse-host (logical-chunkify namestr start end)))
1507       (values host :unspecific (directory) name type version))))
1508
1509 ;;; We can't initialize this yet because not all host methods are
1510 ;;; loaded yet.
1511 (defvar *logical-pathname-defaults*)
1512
1513 (defun logical-namestring-p (x)
1514   (and (stringp x)
1515        (ignore-errors
1516          (typep (pathname x) 'logical-pathname))))
1517
1518 (deftype logical-namestring ()
1519   `(satisfies logical-namestring-p))
1520
1521 (defun logical-pathname (pathspec)
1522   #!+sb-doc
1523   "Converts the pathspec argument to a logical-pathname and returns it."
1524   (declare (type (or logical-pathname string stream) pathspec)
1525            (values logical-pathname))
1526   (if (typep pathspec 'logical-pathname)
1527       pathspec
1528       (flet ((oops (problem)
1529                (error 'simple-type-error
1530                       :datum pathspec
1531                       :expected-type 'logical-namestring
1532                       :format-control "~S is not a valid logical namestring:~%  ~A"
1533                       :format-arguments (list pathspec problem))))
1534         (let ((res (handler-case
1535                        (parse-namestring pathspec nil *logical-pathname-defaults*)
1536                      (error (e) (oops e)))))
1537           (when (eq (%pathname-host res)
1538                     (%pathname-host *logical-pathname-defaults*))
1539             (oops "no host specified"))
1540           res))))
1541 \f
1542 ;;;; logical pathname unparsing
1543
1544 (defun unparse-logical-directory (pathname)
1545   (declare (type pathname pathname))
1546   (collect ((pieces))
1547     (let ((directory (%pathname-directory pathname)))
1548       (when directory
1549         (ecase (pop directory)
1550           (:absolute) ; nothing special
1551           (:relative (pieces ";")))
1552         (dolist (dir directory)
1553           (cond ((or (stringp dir) (pattern-p dir))
1554                  (pieces (unparse-logical-piece dir))
1555                  (pieces ";"))
1556                 ((eq dir :wild)
1557                  (pieces "*;"))
1558                 ((eq dir :wild-inferiors)
1559                  (pieces "**;"))
1560                 (t
1561                  (error "invalid directory component: ~S" dir))))))
1562     (apply #'concatenate 'simple-string (pieces))))
1563
1564 (defun unparse-logical-piece (thing)
1565   (etypecase thing
1566     ((member :wild) "*")
1567     (simple-string thing)
1568     (pattern
1569      (collect ((strings))
1570        (dolist (piece (pattern-pieces thing))
1571          (etypecase piece
1572            (simple-string (strings piece))
1573            (keyword
1574             (cond ((eq piece :wild-inferiors)
1575                    (strings "**"))
1576                   ((eq piece :multi-char-wild)
1577                    (strings "*"))
1578                   (t (error "invalid keyword: ~S" piece))))))
1579        (apply #'concatenate 'simple-string (strings))))))
1580
1581 (defun unparse-logical-file (pathname)
1582   (declare (type pathname pathname))
1583     (collect ((strings))
1584     (let* ((name (%pathname-name pathname))
1585            (type (%pathname-type pathname))
1586            (version (%pathname-version pathname))
1587            (type-supplied (not (or (null type) (eq type :unspecific))))
1588            (version-supplied (not (or (null version)
1589                                       (eq version :unspecific)))))
1590       (when name
1591         (when (and (null type)
1592                    (typep name 'string)
1593                    (position #\. name :start 1))
1594           (error "too many dots in the name: ~S" pathname))
1595         (strings (unparse-logical-piece name)))
1596       (when type-supplied
1597         (unless name
1598           (error "cannot specify the type without a file: ~S" pathname))
1599         (when (typep type 'string)
1600           (when (position #\. type)
1601             (error "type component can't have a #\. inside: ~S" pathname)))
1602         (strings ".")
1603         (strings (unparse-logical-piece type)))
1604       (when version-supplied
1605         (unless type-supplied
1606           (error "cannot specify the version without a type: ~S" pathname))
1607         (etypecase version
1608           ((member :newest) (strings ".NEWEST"))
1609           ((member :wild) (strings ".*"))
1610           (fixnum (strings ".") (strings (format nil "~D" version))))))
1611     (apply #'concatenate 'simple-string (strings))))
1612
1613 ;;; Unparse a logical pathname string.
1614 (defun unparse-enough-namestring (pathname defaults)
1615   (let* ((path-directory (pathname-directory pathname))
1616          (def-directory (pathname-directory defaults))
1617          (enough-directory
1618            ;; Go down the directory lists to see what matches.  What's
1619            ;; left is what we want, more or less.
1620            (cond ((and (eq (first path-directory) (first def-directory))
1621                        (eq (first path-directory) :absolute))
1622                    ;; Both paths are :ABSOLUTE, so find where the
1623                    ;; common parts end and return what's left
1624                    (do* ((p (rest path-directory) (rest p))
1625                          (d (rest def-directory) (rest d)))
1626                         ((or (endp p) (endp d)
1627                              (not (equal (first p) (first d))))
1628                          `(:relative ,@p))))
1629                  (t
1630                    ;; At least one path is :RELATIVE, so just return the
1631                    ;; original path.  If the original path is :RELATIVE,
1632                    ;; then that's the right one.  If PATH-DIRECTORY is
1633                    ;; :ABSOLUTE, we want to return that except when
1634                    ;; DEF-DIRECTORY is :ABSOLUTE, as handled above. so return
1635                    ;; the original directory.
1636                    path-directory))))
1637     (unparse-logical-namestring
1638      (make-pathname :host (pathname-host pathname)
1639                     :directory enough-directory
1640                     :name (pathname-name pathname)
1641                     :type (pathname-type pathname)
1642                     :version (pathname-version pathname)))))
1643
1644 (defun unparse-logical-namestring (pathname)
1645   (declare (type logical-pathname pathname))
1646   (concatenate 'simple-string
1647                (logical-host-name (%pathname-host pathname)) ":"
1648                (unparse-logical-directory pathname)
1649                (unparse-logical-file pathname)))
1650 \f
1651 ;;;; logical pathname translations
1652
1653 ;;; Verify that the list of translations consists of lists and prepare
1654 ;;; canonical translations. (Parse pathnames and expand out wildcards
1655 ;;; into patterns.)
1656 (defun canonicalize-logical-pathname-translations (translation-list host)
1657   (declare (type list translation-list) (type host host)
1658            (values list))
1659   (mapcar (lambda (translation)
1660             (destructuring-bind (from to) translation
1661               (list (if (typep from 'logical-pathname)
1662                         from
1663                         (parse-namestring from host))
1664                     (pathname to))))
1665           translation-list))
1666
1667 (defun logical-pathname-translations (host)
1668   #!+sb-doc
1669   "Return the (logical) host object argument's list of translations."
1670   (declare (type (or string logical-host) host)
1671            (values list))
1672   (logical-host-translations (find-logical-host host)))
1673
1674 (defun (setf logical-pathname-translations) (translations host)
1675   #!+sb-doc
1676   "Set the translations list for the logical host argument."
1677   (declare (type (or string logical-host) host)
1678            (type list translations)
1679            (values list))
1680   (let ((host (intern-logical-host host)))
1681     (setf (logical-host-canon-transls host)
1682           (canonicalize-logical-pathname-translations translations host))
1683     (setf (logical-host-translations host) translations)))
1684
1685 (defun translate-logical-pathname (pathname &key)
1686   #!+sb-doc
1687   "Translate PATHNAME to a physical pathname, which is returned."
1688   (declare (type pathname-designator pathname)
1689            (values (or null pathname)))
1690   (typecase pathname
1691     (logical-pathname
1692      (dolist (x (logical-host-canon-transls (%pathname-host pathname))
1693                 (error 'simple-file-error
1694                        :pathname pathname
1695                        :format-control "no translation for ~S"
1696                        :format-arguments (list pathname)))
1697        (destructuring-bind (from to) x
1698          (when (pathname-match-p pathname from)
1699            (return (translate-logical-pathname
1700                     (translate-pathname pathname from to)))))))
1701     (pathname pathname)
1702     (t (translate-logical-pathname (pathname pathname)))))
1703
1704 (defvar *logical-pathname-defaults*
1705   (%make-logical-pathname
1706    (make-logical-host :name (logical-word-or-lose "BOGUS"))
1707    :unspecific nil nil nil nil))
1708
1709 (defun load-logical-pathname-translations (host)
1710   #!+sb-doc
1711   "Reads logical pathname translations from SYS:SITE;HOST.TRANSLATIONS.NEWEST,
1712 with HOST replaced by the supplied parameter. Returns T on success.
1713
1714 If HOST is already defined as logical pathname host, no file is loaded and NIL
1715 is returned.
1716
1717 The file should contain a single form, suitable for use with
1718 \(SETF LOGICAL-PATHNAME-TRANSLATIONS).
1719
1720 Note: behaviour of this function is higly implementation dependent, and
1721 historically it used to be a no-op in SBcL -- the current approach is somewhat
1722 experimental and subject to change."
1723   (declare (type string host)
1724            (values (member t nil)))
1725   (if (find-logical-host host nil)
1726       ;; This host is already defined, all is well and good.
1727       nil
1728       ;; ANSI: "The specific nature of the search is
1729       ;; implementation-defined."
1730       (prog1 t
1731         (setf (logical-pathname-translations host)
1732               (with-open-file (lpt (make-pathname :host "SYS"
1733                                                   :directory '(:absolute "SITE")
1734                                                   :name host
1735                                                   :type "TRANSLATIONS"
1736                                                   :version :newest))
1737                 (read lpt))))))
1738
1739 (defun !pathname-cold-init ()
1740   (let* ((sys *default-pathname-defaults*)
1741          (src
1742           (merge-pathnames
1743            (make-pathname :directory '(:relative "src" :wild-inferiors)
1744                           :name :wild :type :wild)
1745            sys))
1746          (contrib
1747           (merge-pathnames
1748            (make-pathname :directory '(:relative "contrib" :wild-inferiors)
1749                           :name :wild :type :wild)
1750            sys))
1751          (output
1752           (merge-pathnames
1753            (make-pathname :directory '(:relative "output" :wild-inferiors)
1754                           :name :wild :type :wild)
1755            sys)))
1756     (setf (logical-pathname-translations "SYS")
1757           `(("SYS:SRC;**;*.*.*" ,src)
1758             ("SYS:CONTRIB;**;*.*.*" ,contrib)
1759             ("SYS:OUTPUT;**;*.*.*" ,output)))))