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