r5339: *** empty log message ***
[puri.git] / src.lisp
1 ;; -*- mode: common-lisp; package: puri -*-
2 ;; Support for URIs in Allegro.
3 ;; For general URI information see RFC2396.
4 ;;
5 ;; copyright (c) 1999-2001 Franz Inc, Berkeley, CA - All rights reserved.
6 ;; copyright (c) 2003 Kevin Rosenberg (porting changes)
7 ;;
8 ;; The software, data and information contained herein are proprietary
9 ;; to, and comprise valuable trade secrets of, Franz, Inc.  They are
10 ;; given in confidence by Franz, Inc. pursuant to a written license
11 ;; agreement, and may be stored and used only in accordance with the terms
12 ;; of such license.
13 ;;
14 ;; Restricted Rights Legend
15 ;; ------------------------
16 ;; Use, duplication, and disclosure of the software, data and information
17 ;; contained herein by any agency, department or entity of the U.S.
18 ;; Government are subject to restrictions of Restricted Rights for
19 ;; Commercial Software developed at private expense as specified in
20 ;; DOD FAR Supplement 52.227-7013 (c) (1) (ii), as applicable.
21 ;;
22 ;; Original version from ACL 6.1:
23 ;; uri.cl,v 2.3.6.4.2.1 2001/08/09 17:42:39 layer
24 ;;
25 ;; $Id: src.lisp,v 1.7 2003/07/19 20:32:48 kevin Exp $
26
27 (defpackage #:puri
28   (:use #:cl)
29   (:export
30    #:uri                                ; the type and a function
31    #:uri-p
32    #:copy-uri
33
34    #:uri-scheme                         ; and slots
35    #:uri-host #:uri-port
36    #:uri-path
37    #:uri-query
38    #:uri-fragment
39    #:uri-plist
40    #:uri-authority                      ; pseudo-slot accessor
41
42    #:urn                                ; class
43    #:urn-nid                            ; pseudo-slot accessor
44    #:urn-nss                            ; pseudo-slot accessor
45    
46    #:*strict-parse*
47    #:parse-uri
48    #:merge-uris
49    #:enough-uri
50    #:uri-parsed-path
51    #:render-uri
52
53    #:make-uri-space                     ; interning...
54    #:uri-space
55    #:uri=
56    #:intern-uri
57    #:unintern-uri
58    #:do-all-uris))
59
60 (in-package #:puri)
61
62 (eval-when (:compile-toplevel)
63   (declaim (optimize (speed 3))))
64
65
66 #-(or allegro lispworks)
67 (define-condition parse-error (error)  ())
68
69 #-allegro
70 (defun parse-body (forms &optional env)
71   "Parses a body, returns (VALUES docstring declarations forms)"
72   (declare (ignore env))
73   ;; fixme -- need to add parsing of multiple declarations
74   (let (docstring declarations)
75     (when (stringp (car forms))
76       (setq docstring (car forms))
77       (setq forms (cdr forms)))
78     (when (and (listp (car forms))
79                (symbolp (caar forms))
80                (string-equal (symbol-name '#:declare)
81                              (symbol-name (caar forms))))
82       (setq declarations (car forms))
83       (setq forms (cdr forms)))
84     (values docstring declarations forms)))
85
86   
87 (defun shrink-vector (str size)
88   #+allegro
89   (excl::.primcall 'sys::shrink-svector str size)
90   #+sbcl
91   (sb-kernel:shrink-vector str size)
92   #+cmu
93   (lisp::shrink-vector str size)
94   #+lispworks
95   (system::shrink-vector$vector str size)
96   #+(or allegro cmu sbcl lispworks)
97   str
98   #-(or allegro cmu sbcl lispworks)
99   (subseq str 0 size))
100
101
102 #-allegro
103 (defun .parse-error (fmt &rest args)
104   (error (make-condition 'parse-error :format-control fmt
105                          :format-arguments args)))
106
107 #-allegro
108 (defun internal-reader-error (stream fmt &rest args)
109   (apply #'format stream fmt args))
110
111 #-allegro (defvar *current-case-mode* :case-insensitive-upper)
112 #+allegro (eval-when (:compile-toplevel :load-toplevel :execute)
113             (import '(excl:*current-case-mode*
114                       excl:delimited-string-to-list
115                       excl::.parse-error
116                       excl::parse-body
117                       excl::internal-reader-error
118                       excl:if*)))
119
120 #-allegro
121 (defun position-char (char string start max)
122   (declare (optimize (speed 3) (safety 0) (space 0))
123            (fixnum start max) (simple-string string))
124   (do* ((i start (1+ i)))
125        ((= i max) nil)
126     (declare (fixnum i))
127     (when (char= char (schar string i)) (return i))))
128
129 #-allegro 
130 (defun delimited-string-to-list (string &optional (separator #\space) 
131                                  skip-terminal)
132   (declare (optimize (speed 3) (safety 0) (space 0)
133                      (compilation-speed 0))
134            (type string string)
135            (type character separator))
136   (do* ((len (length string))
137         (output '())
138         (pos 0)
139         (end (position-char separator string pos len)
140              (position-char separator string pos len)))
141        ((null end)
142         (if (< pos len)
143             (push (subseq string pos) output)
144             (when (or (not skip-terminal) (zerop len))
145               (push "" output)))
146         (nreverse output))
147     (declare (type fixnum pos len)
148              (type (or null fixnum) end))
149     (push (subseq string pos end) output)
150     (setq pos (1+ end))))
151
152 #-allegro
153 (eval-when (:compile-toplevel :load-toplevel :execute)
154   (defvar if*-keyword-list '("then" "thenret" "else" "elseif"))
155
156   (defmacro if* (&rest args)
157     (do ((xx (reverse args) (cdr xx))
158          (state :init)
159          (elseseen nil)
160          (totalcol nil)
161         (lookat nil nil)
162          (col nil))
163         ((null xx)
164          (cond ((eq state :compl)
165                 `(cond ,@totalcol))
166                (t (error "if*: illegal form ~s" args))))
167       (cond ((and (symbolp (car xx))
168                   (member (symbol-name (car xx))
169                           if*-keyword-list
170                           :test #'string-equal))
171              (setq lookat (symbol-name (car xx)))))
172
173        (cond ((eq state :init)
174               (cond (lookat (cond ((string-equal lookat "thenret")
175                                    (setq col nil
176                                          state :then))
177                                   (t (error
178                                       "if*: bad keyword ~a" lookat))))
179                     (t (setq state :col
180                              col nil)
181                        (push (car xx) col))))
182              ((eq state :col)
183               (cond (lookat
184                      (cond ((string-equal lookat "else")
185                             (cond (elseseen
186                                    (error
187                                     "if*: multiples elses")))
188                             (setq elseseen t)
189                             (setq state :init)
190                             (push `(t ,@col) totalcol))
191                            ((string-equal lookat "then")
192                             (setq state :then))
193                            (t (error "if*: bad keyword ~s"
194                                               lookat))))
195                     (t (push (car xx) col))))
196              ((eq state :then)
197               (cond (lookat
198                      (error
199                       "if*: keyword ~s at the wrong place " (car xx)))
200                     (t (setq state :compl)
201                        (push `(,(car xx) ,@col) totalcol))))
202              ((eq state :compl)
203               (cond ((not (string-equal lookat "elseif"))
204                      (error "if*: missing elseif clause ")))
205               (setq state :init))))))
206
207
208 (defclass uri ()
209   (
210 ;;;; external:
211    (scheme :initarg :scheme :initform nil :accessor uri-scheme)
212    (host :initarg :host :initform nil :accessor uri-host)
213    (port :initarg :port :initform nil :accessor uri-port)
214    (path :initarg :path :initform nil :accessor uri-path)
215    (query :initarg :query :initform nil :accessor uri-query)
216    (fragment :initarg :fragment :initform nil :accessor uri-fragment)
217    (plist :initarg :plist :initform nil :accessor uri-plist)
218
219 ;;;; internal:
220    (escaped
221     ;; used to prevent unnessary work, looking for chars to escape and
222     ;; unescape.
223     :initarg :escaped :initform nil :accessor uri-escaped)
224    (string
225     ;; the cached printable representation of the URI.  It *might* be
226     ;; different than the original string, though, because the user might
227     ;; have escaped non-reserved chars--they won't be escaped when the URI
228     ;; is printed.
229     :initarg :string :initform nil :accessor uri-string)
230    (parsed-path
231     ;; the cached parsed representation of the URI path.
232     :initarg :parsed-path
233     :initform nil
234     :accessor .uri-parsed-path)
235    (hashcode
236     ;; cached sxhash, so we don't have to compute it more than once.
237     :initarg :hashcode :initform nil :accessor uri-hashcode)))
238
239 (defclass urn (uri)
240   ((nid :initarg :nid :initform nil :accessor urn-nid)
241    (nss :initarg :nss :initform nil :accessor urn-nss)))
242
243 (eval-when (:compile-toplevel :execute)
244   (defmacro clear-caching-on-slot-change (name)
245     `(defmethod (setf ,name) :around (new-value (self uri))
246        (declare (ignore new-value))
247        (prog1 (call-next-method)
248          (setf (uri-string self) nil)
249          ,@(when (eq name 'uri-path) `((setf (.uri-parsed-path self) nil)))
250          (setf (uri-hashcode self) nil))))
251   )
252
253 (clear-caching-on-slot-change uri-scheme)
254 (clear-caching-on-slot-change uri-host)
255 (clear-caching-on-slot-change uri-port)
256 (clear-caching-on-slot-change uri-path)
257 (clear-caching-on-slot-change uri-query)
258 (clear-caching-on-slot-change uri-fragment)
259
260
261 (defmethod make-load-form ((self uri) &optional env)
262   (declare (ignore env))
263   `(make-instance ',(class-name (class-of self))
264      :scheme ,(uri-scheme self)
265      :host ,(uri-host self)
266      :port ,(uri-port self)
267      :path ',(uri-path self)
268      :query ,(uri-query self)
269      :fragment ,(uri-fragment self)
270      :plist ',(uri-plist self)
271      :string ,(uri-string self)
272      :parsed-path ',(.uri-parsed-path self)))
273
274 (defmethod uri-p ((thing uri)) t)
275 (defmethod uri-p ((thing t)) nil)
276
277 (defun copy-uri (uri
278                  &key place
279                       (scheme (when uri (uri-scheme uri)))
280                       (host (when uri (uri-host uri)))
281                       (port (when uri (uri-port uri)))
282                       (path (when uri (uri-path uri)))
283                       (parsed-path
284                        (when uri (copy-list (.uri-parsed-path uri))))
285                       (query (when uri (uri-query uri)))
286                       (fragment (when uri (uri-fragment uri)))
287                       (plist (when uri (copy-list (uri-plist uri))))
288                       (class (when uri (class-of uri)))
289                  &aux (escaped (when uri (uri-escaped uri))))
290   (if* place
291      then (setf (uri-scheme place) scheme)
292           (setf (uri-host place) host)
293           (setf (uri-port place) port)
294           (setf (uri-path place) path)
295           (setf (.uri-parsed-path place) parsed-path)
296           (setf (uri-query place) query)
297           (setf (uri-fragment place) fragment)
298           (setf (uri-plist place) plist)
299           (setf (uri-escaped place) escaped)
300           (setf (uri-string place) nil)
301           (setf (uri-hashcode place) nil)
302           place
303    elseif (eq 'uri class)
304      then ;; allow the compiler to optimize the call to make-instance:
305           (make-instance 'uri
306             :scheme scheme :host host :port port :path path
307             :parsed-path parsed-path
308             :query query :fragment fragment :plist plist
309             :escaped escaped :string nil :hashcode nil)
310      else (make-instance class
311             :scheme scheme :host host :port port :path path
312             :parsed-path parsed-path
313             :query query :fragment fragment :plist plist
314             :escaped escaped :string nil :hashcode nil)))
315
316 (defmethod uri-parsed-path ((uri uri))
317   (when (uri-path uri)
318     (when (null (.uri-parsed-path uri))
319       (setf (.uri-parsed-path uri)
320         (parse-path (uri-path uri) (uri-escaped uri))))
321     (.uri-parsed-path uri)))
322
323 (defmethod (setf uri-parsed-path) (path-list (uri uri))
324   (assert (and (consp path-list)
325                (or (member (car path-list) '(:absolute :relative)
326                            :test #'eq))))
327   (setf (uri-path uri) (render-parsed-path path-list t))
328   (setf (.uri-parsed-path uri) path-list)
329   path-list)
330
331 (defun uri-authority (uri)
332   (when (uri-host uri)
333     (let ((*print-pretty* nil))
334       (format nil "~a~@[:~a~]" (uri-host uri) (uri-port uri)))))
335
336 (defun uri-nid (uri)
337   (if* (equalp "urn" (uri-scheme uri))
338      then (uri-host uri)
339      else (error "URI is not a URN: ~s." uri)))
340
341 (defun uri-nss (uri)
342   (if* (equalp "urn" (uri-scheme uri))
343      then (uri-path uri)
344      else (error "URI is not a URN: ~s." uri)))
345
346 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
347 ;; Parsing
348
349 (defparameter *excluded-characters*
350     '(;; `delims' (except #\%, because it's handled specially):
351       #\< #\> #\" #\space #\#
352       ;; `unwise':
353       #\{ #\} #\| #\\ #\^ #\[ #\] #\`))
354
355 (defun reserved-char-vector (chars &key except)
356   (do* ((a (make-array 127 :element-type 'bit :initial-element 0))
357         (chars chars (cdr chars))
358         (c (car chars) (car chars)))
359       ((null chars) a)
360     (if* (and except (member c except :test #'char=))
361        thenret
362        else (setf (sbit a (char-int c)) 1))))
363
364 (defparameter *reserved-characters*
365     (reserved-char-vector
366      (append *excluded-characters*
367              '(#\; #\/ #\? #\: #\@ #\& #\= #\+ #\$ #\, #\%))))
368 (defparameter *reserved-authority-characters*
369     (reserved-char-vector
370      (append *excluded-characters* '(#\; #\/ #\? #\: #\@))))
371 (defparameter *reserved-path-characters*
372     (reserved-char-vector
373      (append *excluded-characters*
374              '(#\;
375 ;;;;The rfc says this should be here, but it doesn't make sense.
376                ;; #\=
377                #\/ #\?))))
378 (defparameter *reserved-path-characters2*
379     ;; These are the same characters that are in
380     ;; *reserved-path-characters*, minus #\/.  Why?  Because the parsed
381     ;; representation of the path can contain the %2f converted into a /.
382     ;; That's the whole point of having the parsed representation, so that
383     ;; lisp programs can deal with the path element data in the most
384     ;; convenient form.
385     (reserved-char-vector
386      (append *excluded-characters*
387              '(#\;
388 ;;;;The rfc says this should be here, but it doesn't make sense.
389                ;; #\=
390                #\?))))
391 (defparameter *reserved-fragment-characters*
392     (reserved-char-vector (remove #\# *excluded-characters*)))
393
394 (eval-when (:compile-toplevel :execute)
395 (defun gen-char-range-list (start end)
396   (do* ((res '())
397         (endcode (1+ (char-int end)))
398         (chcode (char-int start)
399                 (1+ chcode))
400         (hyphen nil))
401       ((= chcode endcode)
402        ;; - has to be first, otherwise it signifies a range!
403        (if* hyphen
404           then (setq res (nreverse res))
405                (push #\- res)
406                res
407           else (nreverse res)))
408     (if* (= #.(char-int #\-) chcode)
409        then (setq hyphen t)
410        else (push (code-char chcode) res))))
411 )
412
413 (defparameter *valid-nid-characters*
414     (reserved-char-vector
415      '#.(nconc (gen-char-range-list #\a #\z)
416                (gen-char-range-list #\A #\Z)
417                (gen-char-range-list #\0 #\9)
418                '(#\- #\. #\+))))
419 (defparameter *reserved-nss-characters*
420     (reserved-char-vector
421      (append *excluded-characters* '(#\& #\~ #\/ #\?))))
422
423 (defparameter *illegal-characters*
424     (reserved-char-vector (remove #\# *excluded-characters*)))
425 (defparameter *strict-illegal-query-characters*
426     (reserved-char-vector (append '(#\?) (remove #\# *excluded-characters*))))
427 (defparameter *illegal-query-characters*
428     (reserved-char-vector
429      *excluded-characters* :except '(#\^ #\| #\#)))
430
431
432 (defun parse-uri (thing &key (class 'uri) &aux escape)
433   (when (uri-p thing) (return-from parse-uri thing))
434   
435   (setq escape (escape-p thing))
436   (multiple-value-bind (scheme host port path query fragment)
437       (parse-uri-string thing)
438     (when scheme
439       (setq scheme
440         (intern (funcall
441                  (case *current-case-mode*
442                    ((:case-insensitive-upper :case-sensitive-upper)
443                     #'string-upcase)
444                    ((:case-insensitive-lower :case-sensitive-lower)
445                     #'string-downcase))
446                  (decode-escaped-encoding scheme escape))
447                 (find-package :keyword))))
448     
449     (when (and scheme (eq :urn scheme))
450       (return-from parse-uri
451         (make-instance 'urn :scheme scheme :nid host :nss path)))
452     
453     (when host (setq host (decode-escaped-encoding host escape)))
454     (when port
455       (setq port (read-from-string port))
456       (when (not (numberp port)) (error "port is not a number: ~s." port))
457       (when (not (plusp port))
458         (error "port is not a positive integer: ~d." port))
459       (when (eql port (case scheme
460                       (:http 80)
461                       (:https 443)
462                       (:ftp 21)
463                       (:telnet 23)))
464         (setq port nil)))
465     (when (or (string= "" path)
466               (and ;; we canonicalize away a reference to just /:
467                scheme
468                (member scheme '(:http :https :ftp) :test #'eq)
469                (string= "/" path)))
470       (setq path nil))
471     (when path
472       (setq path
473         (decode-escaped-encoding path escape *reserved-path-characters*)))
474     (when query (setq query (decode-escaped-encoding query escape)))
475     (when fragment
476       (setq fragment
477         (decode-escaped-encoding fragment escape
478                                  *reserved-fragment-characters*)))
479     (if* (eq 'uri class)
480        then ;; allow the compiler to optimize the make-instance call:
481             (make-instance 'uri
482               :scheme scheme
483               :host host
484               :port port
485               :path path
486               :query query
487               :fragment fragment
488               :escaped escape)
489        else ;; do it the slow way:
490             (make-instance class
491               :scheme scheme
492               :host host
493               :port port
494               :path path
495               :query query
496               :fragment fragment
497               :escaped escape))))
498
499 (defmethod uri ((thing uri))
500   thing)
501
502 (defmethod uri ((thing string))
503   (parse-uri thing))
504
505 (defmethod uri ((thing t))
506   (error "Cannot coerce ~s to a uri." thing))
507
508 (defvar *strict-parse* t)
509
510 (defun parse-uri-string (string &aux (illegal-chars *illegal-characters*))
511   (declare (optimize (speed 3)))
512   ;; Speed is important, so use a specialized state machine instead of
513   ;; regular expressions for parsing the URI string. The regexp we are
514   ;; simulating:
515   ;;  ^(([^:/?#]+):)?
516   ;;   (//([^/?#]*))?
517   ;;   ([^?#]*)
518   ;;   (\?([^#]*))?
519   ;;   (#(.*))?
520   (let* ((state 0)
521          (start 0)
522          (end (length string))
523          (tokval nil)
524          (scheme nil)
525          (host nil)
526          (port nil)
527          (path-components '())
528          (query nil)
529          (fragment nil)
530          ;; namespace identifier, for urn parsing only:
531          (nid nil))
532     (declare (fixnum state start end))
533     (flet ((read-token (kind &optional legal-chars)
534              (setq tokval nil)
535              (if* (>= start end)
536                 then :end
537                 else (let ((sindex start)
538                            (res nil)
539                            c)
540                        (declare (fixnum sindex))
541                        (setq res
542                          (loop
543                            (when (>= start end) (return nil))
544                            (setq c (schar string start))
545                            (let ((ci (char-int c)))
546                              (if* legal-chars
547                                 then (if* (and (eq :colon kind) (eq c #\:))
548                                         then (return :colon)
549                                       elseif (= 0 (sbit legal-chars ci))
550                                         then (.parse-error
551                                               "~
552 URI ~s contains illegal character ~s at position ~d."
553                                               string c start))
554                               elseif (and (< ci 128)
555                                           *strict-parse*
556                                           (= 1 (sbit illegal-chars ci)))
557                                 then (.parse-error "~
558 URI ~s contains illegal character ~s at position ~d."
559                                                          string c start)))
560                            (case kind
561                              (:path (case c
562                                       (#\? (return :question))
563                                       (#\# (return :hash))))
564                              (:query (case c (#\# (return :hash))))
565                              (:rest)
566                              (t (case c
567                                   (#\: (return :colon))
568                                   (#\? (return :question))
569                                   (#\# (return :hash))
570                                   (#\/ (return :slash)))))
571                            (incf start)))
572                        (if* (> start sindex)
573                           then ;; we found some chars
574                                ;; before we stopped the parse
575                                (setq tokval (subseq string sindex start))
576                                :string
577                           else ;; immediately stopped at a special char
578                                (incf start)
579                                res))))
580            (failure (&optional why)
581              (.parse-error "illegal URI: ~s [~d]~@[: ~a~]"
582                                  string state why))
583            (impossible ()
584              (.parse-error "impossible state: ~d [~s]" state string)))
585       (loop
586         (case state
587           (0 ;; starting to parse
588            (ecase (read-token t)
589              (:colon (failure))
590              (:question (setq state 7))
591              (:hash (setq state 8))
592              (:slash (setq state 3))
593              (:string (setq state 1))
594              (:end (setq state 9))))
595           (1 ;; seen <token><special char>
596            (let ((token tokval))
597              (ecase (read-token t)
598                (:colon (setq scheme token)
599                        (if* (equalp "urn" scheme)
600                           then (setq state 15)
601                           else (setq state 2)))
602                (:question (push token path-components)
603                           (setq state 7))
604                (:hash (push token path-components)
605                       (setq state 8))
606                (:slash (push token path-components)
607                        (push "/" path-components)
608                        (setq state 6))
609                (:string (failure))
610                (:end (push token path-components)
611                      (setq state 9)))))
612           (2 ;; seen <scheme>:
613            (ecase (read-token t)
614              (:colon (failure))
615              (:question (setq state 7))
616              (:hash (setq state 8))
617              (:slash (setq state 3))
618              (:string (setq state 10))
619              (:end (setq state 9))))
620           (10 ;; seen <scheme>:<token>
621            (let ((token tokval))
622              (ecase (read-token t)
623                (:colon (failure))
624                (:question (push token path-components)
625                           (setq state 7))
626                (:hash (push token path-components)
627                       (setq state 8))
628                (:slash (push token path-components)
629                        (setq state 6))
630                (:string (failure))
631                (:end (push token path-components)
632                      (setq state 9)))))
633           (3 ;; seen / or <scheme>:/
634            (ecase (read-token t)
635              (:colon (failure))
636              (:question (push "/" path-components)
637                         (setq state 7))
638              (:hash (push "/" path-components)
639                     (setq state 8))
640              (:slash (setq state 4))
641              (:string (push "/" path-components)
642                       (push tokval path-components)
643                       (setq state 6))
644              (:end (push "/" path-components)
645                    (setq state 9))))
646           (4 ;; seen [<scheme>:]//
647            (ecase (read-token t)
648              (:colon (failure))
649              (:question (failure))
650              (:hash (failure))
651              (:slash (failure))
652              (:string (setq host tokval)
653                       (setq state 11))
654              (:end (failure))))
655           (11 ;; seen [<scheme>:]//<host>
656            (ecase (read-token t)
657              (:colon (setq state 5))
658              (:question (setq state 7))
659              (:hash (setq state 8))
660              (:slash (push "/" path-components)
661                      (setq state 6))
662              (:string (impossible))
663              (:end (setq state 9))))
664           (5 ;; seen [<scheme>:]//<host>:
665            (ecase (read-token t)
666              (:colon (failure))
667              (:question (failure))
668              (:hash (failure))
669              (:slash (push "/" path-components)
670                      (setq state 6))
671              (:string (setq port tokval)
672                       (setq state 12))
673              (:end (failure))))
674           (12 ;; seen [<scheme>:]//<host>:[<port>]
675            (ecase (read-token t)
676              (:colon (failure))
677              (:question (setq state 7))
678              (:hash (setq state 8))
679              (:slash (push "/" path-components)
680                      (setq state 6))
681              (:string (impossible))
682              (:end (setq state 9))))
683           (6 ;; seen /
684            (ecase (read-token :path)
685              (:question (setq state 7))
686              (:hash (setq state 8))
687              (:string (push tokval path-components)
688                       (setq state 13))
689              (:end (setq state 9))))
690           (13 ;; seen path
691            (ecase (read-token :path)
692              (:question (setq state 7))
693              (:hash (setq state 8))
694              (:string (impossible))
695              (:end (setq state 9))))
696           (7 ;; seen ?
697            (setq illegal-chars
698              (if* *strict-parse*
699                 then *strict-illegal-query-characters*
700                 else *illegal-query-characters*))
701            (ecase (prog1 (read-token :query)
702                     (setq illegal-chars *illegal-characters*))
703              (:hash (setq state 8))
704              (:string (setq query tokval)
705                       (setq state 14))
706              (:end (setq state 9))))
707           (14 ;; query
708            (ecase (read-token :query)
709              (:hash (setq state 8))
710              (:string (impossible))
711              (:end (setq state 9))))
712           (8 ;; seen #
713            (ecase (read-token :rest)
714              (:string (setq fragment tokval)
715                       (setq state 9))
716              (:end (setq state 9))))
717           (9 ;; done
718            (return
719              (values
720               scheme host port
721               (apply #'concatenate 'simple-string (nreverse path-components))
722               query fragment)))
723           ;; URN parsing:
724           (15 ;; seen urn:, read nid now
725            (case (read-token :colon *valid-nid-characters*)
726              (:string (setq nid tokval)
727                       (setq state 16))
728              (t (failure "missing namespace identifier"))))
729           (16 ;; seen urn:<nid>
730            (case (read-token t)
731              (:colon (setq state 17))
732              (t (failure "missing namespace specific string"))))
733           (17 ;; seen urn:<nid>:, rest is nss
734            (return (values scheme
735                            nid
736                            nil
737                            (progn
738                              (setq illegal-chars *reserved-nss-characters*)
739                              (read-token :rest)
740                              tokval))))
741           (t (.parse-error
742               "internal error in parse engine, wrong state: ~s." state)))))))
743
744 (defun escape-p (string)
745   (declare (optimize (speed 3)))
746   (do* ((i 0 (1+ i))
747         (max (the fixnum (length string))))
748       ((= i max) nil)
749     (declare (fixnum i max))
750     (when (char= #\% (schar string i))
751       (return t))))
752
753 (defun parse-path (path-string escape)
754   (do* ((xpath-list (delimited-string-to-list path-string #\/))
755         (path-list
756          (progn
757            (if* (string= "" (car xpath-list))
758               then (setf (car xpath-list) :absolute)
759               else (push :relative xpath-list))
760            xpath-list))
761         (pl (cdr path-list) (cdr pl))
762         segments)
763       ((null pl) path-list)
764     (if* (cdr (setq segments (delimited-string-to-list (car pl) #\;)))
765        then ;; there is a param
766 ;;;         (setf (car pl) segments)
767             (setf (car pl)
768               (mapcar #'(lambda (s)
769                           (decode-escaped-encoding
770                            s escape *reserved-path-characters2*))
771                segments))
772        else ;; no param
773 ;;;         (setf (car pl) (car segments))
774             (setf (car pl)
775               (decode-escaped-encoding
776                (car segments) escape *reserved-path-characters2*)))))
777
778 (defun decode-escaped-encoding (string escape
779                                 &optional (reserved-chars
780                                            *reserved-characters*))
781   ;; Return a string with the real characters.
782   (when (null escape) (return-from decode-escaped-encoding string))
783   (do* ((i 0 (1+ i))
784         (max (length string))
785         (new-string (copy-seq string))
786         (new-i 0 (1+ new-i))
787         ch ch2 chc chc2)
788       ((= i max)
789        (shrink-vector new-string new-i))
790     (if* (char= #\% (setq ch (schar string i)))
791        then (when (> (+ i 3) max)
792               (.parse-error
793                "Unsyntactic escaped encoding in ~s." string))
794             (setq ch (schar string (incf i)))
795             (setq ch2 (schar string (incf i)))
796             (when (not (and (setq chc (digit-char-p ch 16))
797                             (setq chc2 (digit-char-p ch2 16))))
798               (.parse-error
799                "Non-hexidecimal digits after %: %c%c." ch ch2))
800             (let ((ci (+ (* 16 chc) chc2)))
801               (if* (or (null reserved-chars)
802                        (= 0 (sbit reserved-chars ci)))
803                  then ;; ok as is
804                       (setf (schar new-string new-i)
805                         (code-char ci))
806                  else (setf (schar new-string new-i) #\%)
807                       (setf (schar new-string (incf new-i)) ch)
808                       (setf (schar new-string (incf new-i)) ch2)))
809        else (setf (schar new-string new-i) ch))))
810
811 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
812 ;;;; Printing
813
814 (defun render-uri (uri stream
815                    &aux (escape (uri-escaped uri))
816                         (*print-pretty* nil))
817   (when (null (uri-string uri))
818     (setf (uri-string uri)
819       (let ((scheme (uri-scheme uri))
820             (host (uri-host uri))
821             (port (uri-port uri))
822             (path (uri-path uri))
823             (query (uri-query uri))
824             (fragment (uri-fragment uri)))
825         (concatenate 'simple-string
826           (when scheme
827             (encode-escaped-encoding
828              (string-downcase ;; for upper case lisps
829               (symbol-name scheme))
830              *reserved-characters* escape))
831           (when scheme ":")
832           (when host "//")
833           (when host
834             (encode-escaped-encoding
835              host *reserved-authority-characters* escape))
836           (when port ":")
837           (when port
838             #-allegro (format nil "~D" port)
839             #+allegro (with-output-to-string (s)
840                         (excl::maybe-print-fast s port))
841             )
842           (when path
843             (encode-escaped-encoding path
844                                      nil
845                                      ;;*reserved-path-characters*
846                                      escape))
847           (when query "?")
848           (when query (encode-escaped-encoding query nil escape))
849           (when fragment "#")
850           (when fragment (encode-escaped-encoding fragment nil escape))))))
851   (if* stream
852      then (format stream "~a" (uri-string uri))
853      else (uri-string uri)))
854
855 (defun render-parsed-path (path-list escape)
856   (do* ((res '())
857         (first (car path-list))
858         (pl (cdr path-list) (cdr pl))
859         (pe (car pl) (car pl)))
860       ((null pl)
861        (when res (apply #'concatenate 'simple-string (nreverse res))))
862     (when (or (null first)
863               (prog1 (eq :absolute first)
864                 (setq first nil)))
865       (push "/" res))
866     (if* (atom pe)
867        then (push
868              (encode-escaped-encoding pe *reserved-path-characters* escape)
869              res)
870        else ;; contains params
871             (push (encode-escaped-encoding
872                    (car pe) *reserved-path-characters* escape)
873                   res)
874             (dolist (item (cdr pe))
875               (push ";" res)
876               (push (encode-escaped-encoding
877                      item *reserved-path-characters* escape)
878                     res)))))
879
880 (defun render-urn (urn stream
881                    &aux (*print-pretty* nil))
882   (when (null (uri-string urn))
883     (setf (uri-string urn)
884       (let ((nid (urn-nid urn))
885             (nss (urn-nss urn)))
886         (concatenate 'simple-string "urn:" nid ":" nss))))
887   (if* stream
888      then (format stream "~a" (uri-string urn))
889      else (uri-string urn)))
890
891 (defparameter *escaped-encoding*
892     (vector #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\a #\b #\c #\d #\e #\f))
893
894 (defun encode-escaped-encoding (string reserved-chars escape)
895   (when (null escape) (return-from encode-escaped-encoding string))
896   ;; Make a string as big as it possibly needs to be (3 times the original
897   ;; size), and truncate it at the end.
898   (do* ((max (length string))
899         (new-max (* 3 max)) ;; worst case new size
900         (new-string (make-string new-max))
901         (i 0 (1+ i))
902         (new-i -1)
903         c ci)
904       ((= i max)
905        (shrink-vector new-string (incf new-i)))
906     (setq ci (char-int (setq c (schar string i))))
907     (if* (or (null reserved-chars)
908              (> ci 127)
909              (= 0 (sbit reserved-chars ci)))
910        then ;; ok as is
911             (incf new-i)
912             (setf (schar new-string new-i) c)
913        else ;; need to escape it
914             (multiple-value-bind (q r) (truncate ci 16)
915               (setf (schar new-string (incf new-i)) #\%)
916               (setf (schar new-string (incf new-i)) (elt *escaped-encoding* q))
917               (setf (schar new-string (incf new-i))
918                 (elt *escaped-encoding* r))))))
919
920 (defmethod print-object ((uri uri) stream)
921   (if* *print-escape*
922      then (format stream "#<~a ~a>" 'uri (render-uri uri nil))
923      else (render-uri uri stream)))
924
925 (defmethod print-object ((urn urn) stream)
926   (if* *print-escape*
927      then (format stream "#<~a ~a>" 'uri (render-urn urn nil))
928      else (render-urn urn stream)))
929
930 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
931 ;; merging and unmerging
932
933 (defmethod merge-uris ((uri string) (base string) &optional place)
934   (merge-uris (parse-uri uri) (parse-uri base) place))
935
936 (defmethod merge-uris ((uri uri) (base string) &optional place)
937   (merge-uris uri (parse-uri base) place))
938
939 (defmethod merge-uris ((uri string) (base uri) &optional place)
940   (merge-uris (parse-uri uri) base place))
941
942 (defmethod merge-uris ((uri uri) (base uri) &optional place)
943   ;; The following is from
944   ;; http://info.internet.isi.edu/in-notes/rfc/files/rfc2396.txt
945   ;; and is algorithm we use to merge URIs.
946   ;;
947   ;; For more information, see section 5.2 of the RFC.
948   ;;
949   (tagbody
950 ;;;; step 2
951     (when (and (null (uri-parsed-path uri))
952                (null (uri-scheme uri))
953                (null (uri-host uri))
954                (null (uri-port uri))
955                (null (uri-query uri)))
956       (return-from merge-uris
957         (let ((new (copy-uri base :place place)))
958           (when (uri-query uri)
959             (setf (uri-query new) (uri-query uri)))
960           (when (uri-fragment uri)
961             (setf (uri-fragment new) (uri-fragment uri)))
962           new)))
963
964     (setq uri (copy-uri uri :place place))
965
966 ;;;; step 3
967     (when (uri-scheme uri)
968       (return-from merge-uris uri))
969     (setf (uri-scheme uri) (uri-scheme base))
970   
971 ;;;; step 4
972     (when (uri-host uri) (go :done))
973     (setf (uri-host uri) (uri-host base))
974     (setf (uri-port uri) (uri-port base))
975     
976 ;;;; step 5
977     (let ((p (uri-parsed-path uri)))
978       (when (and p (eq :absolute (car p)))
979         (when (equal '(:absolute "") p)
980           ;; Canonicalize the way parsing does:
981           (setf (uri-path uri) nil))
982         (go :done)))
983     
984 ;;;; step 6
985     (let* ((base-path
986             (or (uri-parsed-path base)
987                 ;; needed because we canonicalize away a path of just `/':
988                 '(:absolute "")))
989            (path (uri-parsed-path uri))
990            new-path-list)
991       (when (not (eq :absolute (car base-path)))
992         (error "Cannot merge ~a and ~a, since latter is not absolute."
993                uri base))
994
995       ;; steps 6a and 6b:
996       (setq new-path-list
997         (append (butlast base-path)
998                 (if* path then (cdr path) else '(""))))
999
1000       ;; steps 6c and 6d:
1001       (let ((last (last new-path-list)))
1002         (if* (atom (car last))
1003            then (when (string= "." (car last))
1004                   (setf (car last) ""))
1005            else (when (string= "." (caar last))
1006                   (setf (caar last) ""))))
1007       (setq new-path-list
1008         (delete "." new-path-list :test #'(lambda (a b)
1009                                             (if* (atom b)
1010                                                then (string= a b)
1011                                                else nil))))
1012
1013       ;; steps 6e and 6f:
1014       (let ((npl (cdr new-path-list))
1015             index tmp fix-tail)
1016         (setq fix-tail
1017           (string= ".." (let ((l (car (last npl))))
1018                           (if* (atom l)
1019                              then l
1020                              else (car l)))))
1021         (loop
1022           (setq index
1023             (position ".." npl
1024                       :test #'(lambda (a b)
1025                                 (string= a
1026                                          (if* (atom b)
1027                                             then b
1028                                             else (car b))))))
1029           (when (null index) (return))
1030           (when (= 0 index)
1031             ;; The RFC says, in 6g, "that the implementation may handle
1032             ;; this error by retaining these components in the resolved
1033             ;; path, by removing them from the resolved path, or by
1034             ;; avoiding traversal of the reference."  The examples in C.2
1035             ;; imply that we should do the first thing (retain them), so
1036             ;; that's what we'll do.
1037             (return))
1038           (if* (= 1 index)
1039              then (setq npl (cddr npl))
1040              else (setq tmp npl)
1041                   (dotimes (x (- index 2)) (setq tmp (cdr tmp)))
1042                   (setf (cdr tmp) (cdddr tmp))))
1043         (setf (cdr new-path-list) npl)
1044         (when fix-tail (setq new-path-list (nconc new-path-list '("")))))
1045
1046       ;; step 6g:
1047       ;; don't complain if new-path-list starts with `..'.  See comment
1048       ;; above about this step.
1049
1050       ;; step 6h:
1051       (when (or (equal '(:absolute "") new-path-list)
1052                 (equal '(:absolute) new-path-list))
1053         (setq new-path-list nil))
1054       (setf (uri-path uri)
1055         (render-parsed-path new-path-list
1056                             ;; don't know, so have to assume:
1057                             t)))
1058
1059 ;;;; step 7
1060    :done
1061     (return-from merge-uris uri)))
1062
1063 (defmethod enough-uri ((uri string) (base string) &optional place)
1064   (enough-uri (parse-uri uri) (parse-uri base) place))
1065
1066 (defmethod enough-uri ((uri uri) (base string) &optional place)
1067   (enough-uri uri (parse-uri base) place))
1068
1069 (defmethod enough-uri ((uri string) (base uri) &optional place)
1070   (enough-uri (parse-uri uri) base place))
1071
1072 (defmethod enough-uri ((uri uri) (base uri) &optional place)
1073   (let ((new-scheme nil)
1074         (new-host nil)
1075         (new-port nil)
1076         (new-parsed-path nil))
1077
1078     (when (or (and (uri-scheme uri)
1079                    (not (equalp (uri-scheme uri) (uri-scheme base))))
1080               (and (uri-host uri)
1081                    (not (equalp (uri-host uri) (uri-host base))))
1082               (not (equalp (uri-port uri) (uri-port base))))
1083       (return-from enough-uri uri))
1084
1085     (when (null (uri-host uri))
1086       (setq new-host (uri-host base)))
1087     (when (null (uri-port uri))
1088       (setq new-port (uri-port base)))
1089     
1090     (when (null (uri-scheme uri))
1091       (setq new-scheme (uri-scheme base)))
1092
1093     ;; Now, for the hard one, path.
1094     ;; We essentially do here what enough-namestring does.
1095     (do* ((base-path (uri-parsed-path base))
1096           (path (uri-parsed-path uri))
1097           (bp base-path (cdr bp))
1098           (p path (cdr p)))
1099         ((or (null bp) (null p))
1100          ;; If p is nil, that means we have something like
1101          ;; (enough-uri "/foo/bar" "/foo/bar/baz.htm"), so
1102          ;; new-parsed-path will be nil.
1103          (when (null bp)
1104            (setq new-parsed-path (copy-list p))
1105            (when (not (symbolp (car new-parsed-path)))
1106              (push :relative new-parsed-path))))
1107       (if* (equal (car bp) (car p))
1108          thenret ;; skip it
1109          else (setq new-parsed-path (copy-list p))
1110               (when (not (symbolp (car new-parsed-path)))
1111                 (push :relative new-parsed-path))
1112               (return)))
1113
1114     (let ((new-path 
1115            (when new-parsed-path
1116              (render-parsed-path new-parsed-path
1117                                  ;; don't know, so have to assume:
1118                                  t)))
1119           (new-query (uri-query uri))
1120           (new-fragment (uri-fragment uri))
1121           (new-plist (copy-list (uri-plist uri))))
1122       (if* (and (null new-scheme)
1123                 (null new-host)
1124                 (null new-port)
1125                 (null new-path)
1126                 (null new-parsed-path)
1127                 (null new-query)
1128                 (null new-fragment))
1129          then ;; can't have a completely empty uri!
1130               (copy-uri nil
1131                         :class (class-of uri)
1132                         :place place
1133                         :path "/"
1134                         :plist new-plist)
1135          else (copy-uri nil
1136                         :class (class-of uri)
1137                         :place place
1138                         :scheme new-scheme
1139                         :host new-host
1140                         :port new-port
1141                         :path new-path
1142                         :parsed-path new-parsed-path
1143                         :query new-query
1144                         :fragment new-fragment
1145                         :plist new-plist)))))
1146
1147 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1148 ;; support for interning URIs
1149
1150 (defun make-uri-space (&rest keys &key (size 777) &allow-other-keys)
1151   #+allegro
1152   (apply #'make-hash-table :size size
1153          :hash-function 'uri-hash
1154          :test 'uri= :values nil keys)
1155   #-allegro
1156   (apply #'make-hash-table :size size keys))
1157
1158 (defun gethash-uri (uri table)
1159   #+allegro (gethash uri table)
1160   #-allegro 
1161   (let* ((hash (uri-hash uri))
1162          (existing (gethash hash table)))
1163     (dolist (u existing)
1164       (when (uri= u uri)
1165         (return-from gethash-uri (values u t))))
1166     (values nil nil)))
1167
1168 (defun puthash-uri (uri table)
1169   #+allegro (excl:puthash-key uri table)
1170   #-allegro 
1171   (let ((existing (gethash (uri-hash uri) table)))
1172     (dolist (u existing)
1173       (when (uri= u uri)
1174         (return-from puthash-uri u)))
1175     (setf (gethash (uri-hash uri) table)
1176       (cons uri existing))
1177     uri))
1178
1179
1180 (defun uri-hash (uri)
1181   (if* (uri-hashcode uri)
1182      thenret
1183      else (setf (uri-hashcode uri)
1184                 (sxhash
1185                  #+allegro
1186                  (render-uri uri nil)
1187                  #-allegro
1188                  (string-downcase 
1189                   (render-uri uri nil))))))
1190
1191 (defvar *uris* (make-uri-space))
1192
1193 (defun uri-space () *uris*)
1194
1195 (defun (setf uri-space) (new-val)
1196   (setq *uris* new-val))
1197
1198 ;; bootstrapping (uri= changed from function to method):
1199 (when (fboundp 'uri=) (fmakunbound 'uri=))
1200
1201 (defgeneric uri= (uri1 uri2))
1202 (defmethod uri= ((uri1 uri) (uri2 uri))
1203   (when (not (eq (uri-scheme uri1) (uri-scheme uri2)))
1204     (return-from uri= nil))
1205   ;; RFC2396 says: a URL with an explicit ":port", where the port is
1206   ;; the default for the scheme, is the equivalent to one where the
1207   ;; port is elided.  Hmmmm.  This means that this function has to be
1208   ;; scheme dependent.  Grrrr.
1209   (let ((default-port (case (uri-scheme uri1)
1210                         (:http 80)
1211                         (:https 443)
1212                         (:ftp 21)
1213                         (:telnet 23))))
1214     (and (equalp (uri-host uri1) (uri-host uri2))
1215          (eql (or (uri-port uri1) default-port)
1216               (or (uri-port uri2) default-port))
1217          (string= (uri-path uri1) (uri-path uri2))
1218          (string= (uri-query uri1) (uri-query uri2))
1219          (string= (uri-fragment uri1) (uri-fragment uri2)))))
1220
1221 (defmethod uri= ((urn1 urn) (urn2 urn))
1222   (when (not (eq (uri-scheme urn1) (uri-scheme urn2)))
1223     (return-from uri= nil))
1224   (and (equalp (urn-nid urn1) (urn-nid urn2))
1225        (urn-nss-equal (urn-nss urn1) (urn-nss urn2))))
1226
1227 (defun urn-nss-equal (nss1 nss2 &aux len)
1228   ;; Return t iff the nss values are the same.
1229   ;; %2c and %2C are equivalent.
1230   (when (or (null nss1) (null nss2)
1231             (not (= (setq len (length nss1))
1232                     (length nss2))))
1233     (return-from urn-nss-equal nil))
1234   (do* ((i 0 (1+ i))
1235         (state :char)
1236         c1 c2)
1237       ((= i len) t)
1238     (setq c1 (schar nss1 i))
1239     (setq c2 (schar nss2 i))
1240     (ecase state
1241       (:char
1242        (if* (and (char= #\% c1) (char= #\% c2))
1243           then (setq state :percent+1)
1244         elseif (char/= c1 c2)
1245           then (return nil)))
1246       (:percent+1
1247        (when (char-not-equal c1 c2) (return nil))
1248        (setq state :percent+2))
1249       (:percent+2
1250        (when (char-not-equal c1 c2) (return nil))
1251        (setq state :char)))))
1252
1253 (defmethod intern-uri ((xuri uri) &optional (uri-space *uris*))
1254   (let ((uri (gethash-uri xuri uri-space)))
1255     (if* uri
1256        thenret
1257        else (puthash-uri xuri uri-space))))
1258
1259 (defmethod intern-uri ((uri string) &optional (uri-space *uris*))
1260   (intern-uri (parse-uri uri) uri-space))
1261
1262 (defun unintern-uri (uri &optional (uri-space *uris*))
1263   (if* (eq t uri)
1264      then (clrhash uri-space)
1265    elseif (uri-p uri)
1266      then (remhash uri uri-space)
1267      else (error "bad uri: ~s." uri)))
1268
1269 (defmacro do-all-uris ((var &optional uri-space result-form)
1270                        &rest forms
1271                        &environment env)
1272   "do-all-uris (var [[uri-space] result-form])
1273                     {declaration}* {tag | statement}*
1274 Executes the forms once for each uri with var bound to the current uri"
1275   (let ((f (gensym))
1276         (g-ignore (gensym))
1277         (g-uri-space (gensym))
1278         (body (third (parse-body forms env))))
1279     `(let ((,g-uri-space (or ,uri-space *uris*)))
1280        (prog nil
1281          (flet ((,f (,var &optional ,g-ignore)
1282                   (declare (ignore-if-unused ,var ,g-ignore))
1283                   (tagbody ,@body)))
1284            (maphash #',f ,g-uri-space))
1285          (return ,result-form)))))
1286
1287 (defun sharp-u (stream chr arg)
1288   (declare (ignore chr arg))
1289   (let ((arg (read stream nil nil t)))
1290     (if *read-suppress*
1291         nil
1292       (if* (stringp arg)
1293          then (parse-uri arg)
1294          else
1295
1296          (internal-reader-error
1297           stream
1298           "#u takes a string or list argument: ~s" arg)))))
1299
1300
1301 #+allegro
1302 excl::
1303 #+allegro
1304 (locally (declare (special std-lisp-readtable))
1305   (let ((*readtable* std-lisp-readtable))
1306     (set-dispatch-macro-character #\# #\u #'puri::sharp-u)))
1307 #-allegro
1308 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)
1309
1310 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1311
1312 (provide :uri)
1313
1314 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1315 ;; timings
1316 ;; (don't run under emacs with M-x fi:common-lisp)
1317
1318 #+allegro
1319 (eval-when (:compile-toplevel :load-toplevel :execute)
1320   (import 'excl::gc))
1321
1322 #-allegro
1323 (defun gc (&rest options)
1324   (declare (ignore options))
1325   #+sbcl (sb-ext::gc)
1326   #+cmu (ext::gc)
1327   )
1328
1329 (defun time-uri-module ()
1330   (declare (optimize (speed 3) (safety 0) (debug 0)))
1331   (let ((uri "http://www.franz.com/a/b;x;y;z/c/foo?bar=baz&xxx#foo")
1332         (uri2 "http://www.franz.com/a/b;x;y;z/c/%2ffoo?bar=baz&xxx#foo"))
1333     (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1334     (format t "~&;;; starting timing testing 1...~%")
1335     (time (dotimes (i 100000) (parse-uri uri)))
1336     
1337     (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1338     (format t "~&;;; starting timing testing 2...~%")
1339     (let ((uri (parse-uri uri)))
1340       (time (dotimes (i 100000)
1341               ;; forces no caching of the printed representation:
1342               (setf (uri-string uri) nil)
1343               (format nil "~a" uri))))
1344     
1345     (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1346     (format t "~&;;; starting timing testing 3...~%")
1347     (time
1348      (progn
1349        (dotimes (i 100000) (parse-uri uri2))
1350        (let ((uri (parse-uri uri)))
1351          (dotimes (i 100000)
1352            ;; forces no caching of the printed representation:
1353            (setf (uri-string uri) nil)
1354            (format nil "~a" uri)))))))
1355
1356 ;;******** reference output (ultra, modified 5.0.1):
1357 ;;; starting timing testing 1...
1358 ; cpu time (non-gc) 13,710 msec user, 0 msec system
1359 ; cpu time (gc)     600 msec user, 10 msec system
1360 ; cpu time (total)  14,310 msec user, 10 msec system
1361 ; real time  14,465 msec
1362 ; space allocation:
1363 ;  1,804,261 cons cells, 7 symbols, 41,628,832 other bytes, 0 static bytes
1364 ;;; starting timing testing 2...
1365 ; cpu time (non-gc) 27,500 msec user, 0 msec system
1366 ; cpu time (gc)     280 msec user, 20 msec system
1367 ; cpu time (total)  27,780 msec user, 20 msec system
1368 ; real time  27,897 msec
1369 ; space allocation:
1370 ;  1,900,463 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1371 ;;; starting timing testing 3...
1372 ; cpu time (non-gc) 52,290 msec user, 10 msec system
1373 ; cpu time (gc)     1,290 msec user, 30 msec system
1374 ; cpu time (total)  53,580 msec user, 40 msec system
1375 ; real time  54,062 msec
1376 ; space allocation:
1377 ;  7,800,205 cons cells, 0 symbols, 81,697,496 other bytes, 0 static bytes
1378
1379 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1380 ;;; after improving decode-escaped-encoding/encode-escaped-encoding:
1381
1382 ;;; starting timing testing 1...
1383 ; cpu time (non-gc) 14,520 msec user, 0 msec system
1384 ; cpu time (gc)     400 msec user, 0 msec system
1385 ; cpu time (total)  14,920 msec user, 0 msec system
1386 ; real time  15,082 msec
1387 ; space allocation:
1388 ;  1,800,270 cons cells, 0 symbols, 41,600,160 other bytes, 0 static bytes
1389 ;;; starting timing testing 2...
1390 ; cpu time (non-gc) 27,490 msec user, 10 msec system
1391 ; cpu time (gc)     300 msec user, 0 msec system
1392 ; cpu time (total)  27,790 msec user, 10 msec system
1393 ; real time  28,025 msec
1394 ; space allocation:
1395 ;  1,900,436 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1396 ;;; starting timing testing 3...
1397 ; cpu time (non-gc) 47,900 msec user, 20 msec system
1398 ; cpu time (gc)     920 msec user, 10 msec system
1399 ; cpu time (total)  48,820 msec user, 30 msec system
1400 ; real time  49,188 msec
1401 ; space allocation:
1402 ;  3,700,215 cons cells, 0 symbols, 81,707,144 other bytes, 0 static bytes