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