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