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