Merge branch 'master' of git://git.b9.com/puri
[puri-unicode.git] / src.lisp
1 ;; -*- mode: common-lisp; package: puri -*-
2 ;; Support for URIs
3 ;; For general URI information see RFC2396.
4 ;;
5 ;; copyright (c) 1999-2002 Franz Inc, Berkeley, CA  - All rights reserved.
6 ;; copyright (c) 2002-2005 Franz Inc, Oakland, CA - All rights reserved.
7 ;; copyright (c) 2003-2010 Kevin Rosenberg
8 ;;
9 ;; This code is free software; you can redistribute it and/or
10 ;; modify it under the terms of the version 2.1 of
11 ;; the GNU Lesser General Public License as published by
12 ;; the Free Software Foundation, as clarified by the
13 ;; preamble found here:
14 ;;     http://opensource.franz.com/preamble.html
15 ;;
16 ;; Versions ported from Franz's opensource release
17 ;; uri.cl,v 2.3.6.4.2.1 2001/08/09 17:42:39 layer
18 ;; uri.cl,v 2.9.84.1 2005/08/11 18:38:52 layer
19
20 ;; This code is distributed in the hope that it will be useful,
21 ;; but without any warranty; without even the implied warranty of
22 ;; merchantability or fitness for a particular purpose.  See the GNU
23 ;; Lesser General Public License for more details.
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     (append
359      ;; exclude control characters
360      (loop for i from 0 to #x1f
361            collect (code-char i))
362      '(;; `delims' (except #\%, because it's handled specially):
363       #\< #\> #\" #\space #\#
364       #\Rubout ;; (code-char #x7f)
365       ;; `unwise':
366       #\{ #\} #\| #\\ #\^ #\[ #\] #\`))
367   "Excluded charcters from RFC2369 (http://www.ietf.org/rfc/rfc2396.txt 2.4.3)")
368
369 (defun reserved-char-vector (chars &key except)
370   (do* ((a (make-array 128 :element-type 'bit :initial-element 0))
371         (chars chars (cdr chars))
372         (c (car chars) (car chars)))
373       ((null chars) a)
374     (if* (and except (member c except :test #'char=))
375        thenret
376        else (setf (sbit a (char-int c)) 1))))
377
378 (defparameter *reserved-characters*
379     (reserved-char-vector
380      (append *excluded-characters*
381              '(#\; #\/ #\? #\: #\@ #\& #\= #\+ #\$ #\, #\%))))
382 (defparameter *reserved-authority-characters*
383     (reserved-char-vector
384      (append *excluded-characters* '(#\; #\/ #\? #\: #\@))))
385 (defparameter *reserved-path-characters*
386     (reserved-char-vector
387      (append *excluded-characters*
388              '(#\;
389 ;;;;The rfc says this should be here, but it doesn't make sense.
390                ;; #\=
391                #\/ #\?))))
392
393 (defparameter *reserved-fragment-characters*
394     (reserved-char-vector (remove #\# *excluded-characters*)))
395
396 (eval-when (:compile-toplevel :execute)
397 (defun gen-char-range-list (start end)
398   (do* ((res '())
399         (endcode (1+ (char-int end)))
400         (chcode (char-int start)
401                 (1+ chcode))
402         (hyphen nil))
403       ((= chcode endcode)
404        ;; - has to be first, otherwise it signifies a range!
405        (if* hyphen
406           then (setq res (nreverse res))
407                (push #\- res)
408                res
409           else (nreverse res)))
410     (if* (= #.(char-int #\-) chcode)
411        then (setq hyphen t)
412        else (push (code-char chcode) res))))
413 )
414
415 (defparameter *valid-nid-characters*
416     (reserved-char-vector
417      '#.(nconc (gen-char-range-list #\a #\z)
418                (gen-char-range-list #\A #\Z)
419                (gen-char-range-list #\0 #\9)
420                '(#\- #\. #\+))))
421 (defparameter *reserved-nss-characters*
422     (reserved-char-vector
423      (append *excluded-characters* '(#\& #\~ #\/ #\?))))
424
425 (defparameter *illegal-characters*
426     (reserved-char-vector (remove #\# *excluded-characters*)))
427 (defparameter *strict-illegal-query-characters*
428     (reserved-char-vector (append '(#\?) (remove #\# *excluded-characters*))))
429 (defparameter *illegal-query-characters*
430     (reserved-char-vector
431      *excluded-characters* :except '(#\^ #\| #\#)))
432
433
434 (defun parse-uri (thing &key (class 'uri) &aux escape)
435   (when (uri-p thing) (return-from parse-uri thing))
436
437   (setq escape (escape-p thing))
438   (multiple-value-bind (scheme host port path query fragment)
439       (parse-uri-string thing)
440     (when scheme
441       (setq scheme
442         (intern (funcall
443                  (case *current-case-mode*
444                    ((:case-insensitive-upper :case-sensitive-upper)
445                     #'string-upcase)
446                    ((:case-insensitive-lower :case-sensitive-lower)
447                     #'string-downcase))
448                  (decode-escaped-encoding scheme escape))
449                 (find-package :keyword))))
450
451     (when (and scheme (eq :urn scheme))
452       (return-from parse-uri
453         (make-instance 'urn :scheme scheme :nid host :nss path)))
454
455     (when host (setq host (decode-escaped-encoding host escape)))
456     (when port
457       (setq port (read-from-string port))
458       (when (not (numberp port)) (error "port is not a number: ~s." port))
459       (when (not (plusp port))
460         (error "port is not a positive integer: ~d." port))
461       (when (eql port (case scheme
462                       (:http 80)
463                       (:https 443)
464                       (:ftp 21)
465                       (:telnet 23)))
466         (setq port nil)))
467     (when (or (string= "" path)
468               (and ;; we canonicalize away a reference to just /:
469                scheme
470                (member scheme '(:http :https :ftp) :test #'eq)
471                (string= "/" path)))
472       (setq path nil))
473     (when path
474       (setq path
475         (decode-escaped-encoding path escape *reserved-path-characters*)))
476     (when query (setq query (decode-escaped-encoding query escape)))
477     (when fragment
478       (setq fragment
479         (decode-escaped-encoding fragment escape
480                                  *reserved-fragment-characters*)))
481     (if* (eq 'uri class)
482        then ;; allow the compiler to optimize the make-instance call:
483             (make-instance 'uri
484               :scheme scheme
485               :host host
486               :port port
487               :path path
488               :query query
489               :fragment fragment
490               :escaped escape)
491        else ;; do it the slow way:
492             (make-instance class
493               :scheme scheme
494               :host host
495               :port port
496               :path path
497               :query query
498               :fragment fragment
499               :escaped escape))))
500
501 (defmethod uri ((thing uri))
502   thing)
503
504 (defmethod uri ((thing string))
505   (parse-uri thing))
506
507 (defmethod uri ((thing t))
508   (error "Cannot coerce ~s to a uri." thing))
509
510 (defvar *strict-parse* t)
511
512 (defun parse-uri-string (string &aux (illegal-chars *illegal-characters*))
513   (declare (optimize (speed 3)))
514   ;; Speed is important, so use a specialized state machine instead of
515   ;; regular expressions for parsing the URI string. The regexp we are
516   ;; simulating:
517   ;;  ^(([^:/?#]+):)?
518   ;;   (//([^/?#]*))?
519   ;;   ([^?#]*)
520   ;;   (\?([^#]*))?
521   ;;   (#(.*))?
522   (let* ((state 0)
523          (start 0)
524          (end (length string))
525          (tokval nil)
526          (scheme nil)
527          (host nil)
528          (port nil)
529          (path-components '())
530          (query nil)
531          (fragment nil)
532          ;; namespace identifier, for urn parsing only:
533          (nid nil))
534     (declare (fixnum state start end))
535     (flet ((read-token (kind &optional legal-chars)
536              (setq tokval nil)
537              (if* (>= start end)
538                 then :end
539                 else (let ((sindex start)
540                            (res nil)
541                            c)
542                        (declare (fixnum sindex))
543                        (setq res
544                          (loop
545                            (when (>= start end) (return nil))
546                            (setq c (char string start))
547                            (let ((ci (char-int c)))
548                              (if* legal-chars
549                                 then (if* (and (eq :colon kind) (eq c #\:))
550                                         then (return :colon)
551                                       elseif (= 0 (sbit legal-chars ci))
552                                         then (.parse-error
553                                               "~
554 URI ~s contains illegal character ~s at position ~d."
555                                               string c start))
556                               elseif (and (< ci 128)
557                                           *strict-parse*
558                                           (= 1 (sbit illegal-chars ci)))
559                                 then (.parse-error "~
560 URI ~s contains illegal character ~s at position ~d."
561                                                          string c start)))
562                            (case kind
563                              (:path (case c
564                                       (#\? (return :question))
565                                       (#\# (return :hash))))
566                              (:query (case c (#\# (return :hash))))
567                              (:rest)
568                              (t (case c
569                                   (#\: (return :colon))
570                                   (#\? (return :question))
571                                   (#\# (return :hash))
572                                   (#\/ (return :slash)))))
573                            (incf start)))
574                        (if* (> start sindex)
575                           then ;; we found some chars
576                                ;; before we stopped the parse
577                                (setq tokval (subseq string sindex start))
578                                :string
579                           else ;; immediately stopped at a special char
580                                (incf start)
581                                res))))
582            (failure (&optional why)
583              (.parse-error "illegal URI: ~s [~d]~@[: ~a~]"
584                                  string state why))
585            (impossible ()
586              (.parse-error "impossible state: ~d [~s]" state string)))
587       (loop
588         (case state
589           (0 ;; starting to parse
590            (ecase (read-token t)
591              (:colon (failure))
592              (:question (setq state 7))
593              (:hash (setq state 8))
594              (:slash (setq state 3))
595              (:string (setq state 1))
596              (:end (setq state 9))))
597           (1 ;; seen <token><special char>
598            (let ((token tokval))
599              (ecase (read-token t)
600                (:colon (setq scheme token)
601                        (if* (equalp "urn" scheme)
602                           then (setq state 15)
603                           else (setq state 2)))
604                (:question (push token path-components)
605                           (setq state 7))
606                (:hash (push token path-components)
607                       (setq state 8))
608                (:slash (push token path-components)
609                        (push "/" path-components)
610                        (setq state 6))
611                (:string (failure))
612                (:end (push token path-components)
613                      (setq state 9)))))
614           (2 ;; seen <scheme>:
615            (ecase (read-token t)
616              (:colon (failure))
617              (:question (setq state 7))
618              (:hash (setq state 8))
619              (:slash (setq state 3))
620              (:string (setq state 10))
621              (:end (setq state 9))))
622           (10 ;; seen <scheme>:<token>
623            (let ((token tokval))
624              (ecase (read-token t)
625                (:colon (failure))
626                (:question (push token path-components)
627                           (setq state 7))
628                (:hash (push token path-components)
629                       (setq state 8))
630                (:slash (push token path-components)
631                        (setq state 6))
632                (:string (failure))
633                (:end (push token path-components)
634                      (setq state 9)))))
635           (3 ;; seen / or <scheme>:/
636            (ecase (read-token t)
637              (:colon (failure))
638              (:question (push "/" path-components)
639                         (setq state 7))
640              (:hash (push "/" path-components)
641                     (setq state 8))
642              (:slash (setq state 4))
643              (:string (push "/" path-components)
644                       (push tokval path-components)
645                       (setq state 6))
646              (:end (push "/" path-components)
647                    (setq state 9))))
648           (4 ;; seen [<scheme>:]//
649            (ecase (read-token t)
650              (:colon (failure))
651              (:question (failure))
652              (:hash (failure))
653              (:slash
654               (if* (and (equalp "file" scheme)
655                         (null host))
656                  then ;; file:///...
657                       (push "/" path-components)
658                       (setq state 6)
659                  else (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
796   (let ((curpos 0)
797         (maxpos (length string))
798         (strs nil))
799     (flet ((next-ansii-substring ()
800              (let ((pos (or (position #\% string :start curpos)
801                             maxpos)))
802                (when (and (= curpos 0)
803                           (= pos maxpos))
804                  (return-from decode-escaped-encoding string))
805                (when (< curpos pos)
806                  (push (subseq string
807                                curpos
808                                pos)
809                        strs)
810                  (setf curpos pos))))
811            (next-encoded-substring ()
812              (let ((pos (or (loop for i from curpos below maxpos by 3
813                                unless (char= (aref string i)
814                                              #\%)
815                                return i)
816                             maxpos)))
817                (when (< curpos pos)
818                  (let ((octets (handler-case (make-array (/ (- pos curpos)
819                                                             3)
820                                                          :element-type '(unsigned-byte 8)
821                                                          :fill-pointer 0)
822                                  (error () 
823                                    (.parse-error "Unsyntactic escaped encoding in ~s." string)))))
824                    (loop for i from curpos below pos by 3
825                       do (vector-push (handler-case
826                                           (parse-integer string
827                                                          :start (1+ i)
828                                                          :end (+ i 3)
829                                                          :radix 16)
830                                         (error ()
831                                           (.parse-error "Non-hexidecimal digits after %: ~c~c." 
832                                                         (aref string  (1+ i))
833                                                         (aref string (+ 2 i)))))
834                                       octets))
835                    
836                    (let* ((decoded-string (babel:octets-to-string octets
837                                                                   :encoding :utf-8))
838                           (rpos (if reserved-chars
839                                     (position-if #'(lambda (ch)
840                                                      (not (or (> (char-code ch) 127)
841                                                               (= (sbit reserved-chars (char-code ch)) 0))))
842                                                  decoded-string))))
843                      (push (if rpos
844                                (with-output-to-string (out)
845                                  (loop for ch across decoded-string
846                                     with i = curpos
847                                     do (let ((code (char-code ch)))
848                                          (cond
849                                            ((or (null reserved-chars)
850                                                 (> code 127)
851                                                 (= (sbit reserved-chars code) 0))
852                                             (write-char ch out)
853                                             (incf i
854                                                   (* (cond
855                                                        ((< code #x80) 1)
856                                                        ((< code #x800) 2)
857                                                        ((< code #x10000) 3)
858                                                        ((< code #x200000) 4)
859                                                        ((< code #x4000000) 5)
860                                                        (t 6))
861                                                      3)))
862                                            (t (write-string (subseq string i (+ i 3)) out)
863                                               (incf i 3))))))
864                                decoded-string)
865                            strs))))
866                    (setf curpos pos))))
867       (loop
868          while (< curpos maxpos)
869          do (next-ansii-substring)
870          while (< curpos maxpos)
871          do (next-encoded-substring)))
872     (if (cdr strs)
873         (apply #'concatenate
874                    'string
875                    (nreverse strs))
876         (or (car strs)
877             ""))))
878
879                          
880 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
881 ;;;; Printing
882
883 (defun render-uri (uri stream
884                    &aux (escape (uri-escaped uri))
885                         (*print-pretty* nil))
886   (when (null (uri-string uri))
887     (setf (uri-string uri)
888       (let ((scheme (uri-scheme uri))
889             (host (uri-host uri))
890             (port (uri-port uri))
891             (path (uri-path uri))
892             (query (uri-query uri))
893             (fragment (uri-fragment uri)))
894         (concatenate 'string
895           (when scheme
896             (encode-escaped-encoding
897              (string-downcase ;; for upper case lisps
898               (symbol-name scheme))
899              *reserved-characters* escape))
900           (when scheme ":")
901           (when (or host (eq :file scheme)) "//")
902           (when host
903             (encode-escaped-encoding
904              host *reserved-authority-characters* escape))
905           (when port ":")
906           (when port
907             #-allegro (format nil "~D" port)
908             #+allegro (with-output-to-string (s)
909                         (excl::maybe-print-fast s port))
910             )
911           (encode-escaped-encoding (or path "/")
912                                    nil
913                                    ;;*reserved-path-characters*
914                                    escape)
915           (when query "?")
916           (when query (encode-escaped-encoding query nil escape))
917           (when fragment "#")
918           (when fragment (encode-escaped-encoding fragment nil escape))))))
919   (if* stream
920      then (format stream "~a" (uri-string uri))
921      else (uri-string uri)))
922
923 (defun render-parsed-path (path-list escape)
924   (do* ((res '())
925         (first (car path-list))
926         (pl (cdr path-list) (cdr pl))
927         (pe (car pl) (car pl)))
928       ((null pl)
929        (when res (apply #'concatenate 'string (nreverse res))))
930     (when (or (null first)
931               (prog1 (eq :absolute first)
932                 (setq first nil)))
933       (push "/" res))
934     (if* (atom pe)
935        then (push
936              (encode-escaped-encoding pe *reserved-path-characters* escape)
937              res)
938        else ;; contains params
939             (push (encode-escaped-encoding
940                    (car pe) *reserved-path-characters* escape)
941                   res)
942             (dolist (item (cdr pe))
943               (push ";" res)
944               (push (encode-escaped-encoding
945                      item *reserved-path-characters* escape)
946                     res)))))
947
948 (defun render-urn (urn stream
949                    &aux (*print-pretty* nil))
950   (when (null (uri-string urn))
951     (setf (uri-string urn)
952       (let ((nid (urn-nid urn))
953             (nss (urn-nss urn)))
954         (concatenate 'string "urn:" nid ":" nss))))
955   (if* stream
956      then (format stream "~a" (uri-string urn))
957      else (uri-string urn)))
958
959 (defun encode-escaped-encoding (string reserved-chars escape)
960   (when (null escape) (return-from encode-escaped-encoding string))
961   (with-output-to-string (out)
962     (loop for ch across string
963        do (let ((code (char-code ch)))  
964             (if (and (< code 128)
965                      (or (null reserved-chars)
966                          (= 0 (sbit reserved-chars code))))
967                 (write-char ch out)
968                 (loop for octet across (babel:string-to-octets (string ch) :encoding :utf-8)
969                    do (format out "%~(~2,'0x~)" octet)))))))
970
971 (defmethod print-object ((uri uri) stream)
972   (if* *print-escape*
973      then (print-unreadable-object (uri stream :type t) (render-uri uri stream))
974      else (render-uri uri stream)))
975
976 (defmethod print-object ((urn urn) stream)
977   (if* *print-escape*
978      then (print-unreadable-object (urn stream :type t) (render-urn urn stream))
979      else (render-urn urn stream)))
980
981 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
982 ;; merging and unmerging
983
984 (defmethod merge-uris ((uri string) (base string) &optional place)
985   (merge-uris (parse-uri uri) (parse-uri base) place))
986
987 (defmethod merge-uris ((uri uri) (base string) &optional place)
988   (merge-uris uri (parse-uri base) place))
989
990 (defmethod merge-uris ((uri string) (base uri) &optional place)
991   (merge-uris (parse-uri uri) base place))
992
993
994 (defmethod merge-uris ((uri uri) (base uri) &optional place)
995   ;; See ../doc/rfc2396.txt for info on the algorithm we use to merge
996   ;; URIs.
997   ;;
998   (tagbody
999 ;;;; step 2
1000     (when (and (null (uri-parsed-path uri))
1001                (null (uri-scheme uri))
1002                (null (uri-host uri))
1003                (null (uri-port uri))
1004                (null (uri-query uri)))
1005       (return-from merge-uris
1006         (let ((new (copy-uri base :place place)))
1007           (when (uri-query uri)
1008             (setf (uri-query new) (uri-query uri)))
1009           (when (uri-fragment uri)
1010             (setf (uri-fragment new) (uri-fragment uri)))
1011           new)))
1012
1013     (setq uri (copy-uri uri :place place))
1014
1015 ;;;; step 3
1016     (when (uri-scheme uri)
1017       (return-from merge-uris uri))
1018     (setf (uri-scheme uri) (uri-scheme base))
1019
1020 ;;;; step 4
1021     (when (uri-host uri) (go :done))
1022     (setf (uri-host uri) (uri-host base))
1023     (setf (uri-port uri) (uri-port base))
1024
1025 ;;;; step 5
1026     (let ((p (uri-parsed-path uri)))
1027
1028       ;; bug13133:
1029       ;; The following form causes our implementation to be at odds with
1030       ;; RFC 2396, however this is apparently what was intended by the
1031       ;; authors of the RFC.  Specifically, (merge-uris "?y" "/foo")
1032       ;; should return #<uri /foo?y> instead of #<uri ?y>, according to
1033       ;; this:
1034 ;;; http://www.apache.org/~fielding/uri/rev-2002/issues.html#003-relative-query
1035       (when (null p)
1036         (setf (uri-path uri) (uri-path base))
1037         (go :done))
1038
1039       (when (and p (eq :absolute (car p)))
1040         (when (equal '(:absolute "") p)
1041           ;; Canonicalize the way parsing does:
1042           (setf (uri-path uri) nil))
1043         (go :done)))
1044
1045 ;;;; step 6
1046     (let* ((base-path
1047             (or (uri-parsed-path base)
1048                 ;; needed because we canonicalize away a path of just `/':
1049                 '(:absolute "")))
1050            (path (uri-parsed-path uri))
1051            new-path-list)
1052       (when (not (eq :absolute (car base-path)))
1053         (error "Cannot merge ~a and ~a, since latter is not absolute."
1054                uri base))
1055
1056       ;; steps 6a and 6b:
1057       (setq new-path-list
1058         (append (butlast base-path)
1059                 (if* path then (cdr path) else '(""))))
1060
1061       ;; steps 6c and 6d:
1062       (let ((last (last new-path-list)))
1063         (if* (atom (car last))
1064            then (when (string= "." (car last))
1065                   (setf (car last) ""))
1066            else (when (string= "." (caar last))
1067                   (setf (caar last) ""))))
1068       (setq new-path-list
1069         (delete "." new-path-list :test #'(lambda (a b)
1070                                             (if* (atom b)
1071                                                then (string= a b)
1072                                                else nil))))
1073
1074       ;; steps 6e and 6f:
1075       (let ((npl (cdr new-path-list))
1076             index tmp fix-tail)
1077         (setq fix-tail
1078           (string= ".." (let ((l (car (last npl))))
1079                           (if* (atom l)
1080                              then l
1081                              else (car l)))))
1082         (loop
1083           (setq index
1084             (position ".." npl
1085                       :test #'(lambda (a b)
1086                                 (string= a
1087                                          (if* (atom b)
1088                                             then b
1089                                             else (car b))))))
1090           (when (null index) (return))
1091           (when (= 0 index)
1092             ;; The RFC says, in 6g, "that the implementation may handle
1093             ;; this error by retaining these components in the resolved
1094             ;; path, by removing them from the resolved path, or by
1095             ;; avoiding traversal of the reference."  The examples in C.2
1096             ;; imply that we should do the first thing (retain them), so
1097             ;; that's what we'll do.
1098             (return))
1099           (if* (= 1 index)
1100              then (setq npl (cddr npl))
1101              else (setq tmp npl)
1102                   (dotimes (x (- index 2)) (setq tmp (cdr tmp)))
1103                   (setf (cdr tmp) (cdddr tmp))))
1104         (setf (cdr new-path-list) npl)
1105         (when fix-tail (setq new-path-list (nconc new-path-list '("")))))
1106
1107       ;; step 6g:
1108       ;; don't complain if new-path-list starts with `..'.  See comment
1109       ;; above about this step.
1110
1111       ;; step 6h:
1112       (when (or (equal '(:absolute "") new-path-list)
1113                 (equal '(:absolute) new-path-list))
1114         (setq new-path-list nil))
1115       (setf (uri-path uri)
1116         (render-parsed-path new-path-list
1117                             ;; don't know, so have to assume:
1118                             t)))
1119
1120 ;;;; step 7
1121    :done
1122     (return-from merge-uris uri)))
1123
1124 (defmethod enough-uri ((uri string) (base string) &optional place)
1125   (enough-uri (parse-uri uri) (parse-uri base) place))
1126
1127 (defmethod enough-uri ((uri uri) (base string) &optional place)
1128   (enough-uri uri (parse-uri base) place))
1129
1130 (defmethod enough-uri ((uri string) (base uri) &optional place)
1131   (enough-uri (parse-uri uri) base place))
1132
1133 (defmethod enough-uri ((uri uri) (base uri) &optional place)
1134   (let ((new-scheme nil)
1135         (new-host nil)
1136         (new-port nil)
1137         (new-parsed-path nil))
1138
1139     (when (or (and (uri-scheme uri)
1140                    (not (equalp (uri-scheme uri) (uri-scheme base))))
1141               (and (uri-host uri)
1142                    (not (equalp (uri-host uri) (uri-host base))))
1143               (not (equalp (uri-port uri) (uri-port base))))
1144       (return-from enough-uri uri))
1145
1146     (when (null (uri-host uri))
1147       (setq new-host (uri-host base)))
1148     (when (null (uri-port uri))
1149       (setq new-port (uri-port base)))
1150
1151     (when (null (uri-scheme uri))
1152       (setq new-scheme (uri-scheme base)))
1153
1154     ;; Now, for the hard one, path.
1155     ;; We essentially do here what enough-namestring does.
1156     (do* ((base-path (uri-parsed-path base))
1157           (path (uri-parsed-path uri))
1158           (bp base-path (cdr bp))
1159           (p path (cdr p)))
1160         ((or (null bp) (null p))
1161          ;; If p is nil, that means we have something like
1162          ;; (enough-uri "/foo/bar" "/foo/bar/baz.htm"), so
1163          ;; new-parsed-path will be nil.
1164          (when (null bp)
1165            (setq new-parsed-path (copy-list p))
1166            (when (not (symbolp (car new-parsed-path)))
1167              (push :relative new-parsed-path))))
1168       (if* (equal (car bp) (car p))
1169          thenret ;; skip it
1170          else (setq new-parsed-path (copy-list p))
1171               (when (not (symbolp (car new-parsed-path)))
1172                 (push :relative new-parsed-path))
1173               (return)))
1174
1175     (let ((new-path
1176            (when new-parsed-path
1177              (render-parsed-path new-parsed-path
1178                                  ;; don't know, so have to assume:
1179                                  t)))
1180           (new-query (uri-query uri))
1181           (new-fragment (uri-fragment uri))
1182           (new-plist (copy-list (uri-plist uri))))
1183       (if* (and (null new-scheme)
1184                 (null new-host)
1185                 (null new-port)
1186                 (null new-path)
1187                 (null new-parsed-path)
1188                 (null new-query)
1189                 (null new-fragment))
1190          then ;; can't have a completely empty uri!
1191               (copy-uri nil
1192                         :class (class-of uri)
1193                         :place place
1194                         :path "/"
1195                         :plist new-plist)
1196          else (copy-uri nil
1197                         :class (class-of uri)
1198                         :place place
1199                         :scheme new-scheme
1200                         :host new-host
1201                         :port new-port
1202                         :path new-path
1203                         :parsed-path new-parsed-path
1204                         :query new-query
1205                         :fragment new-fragment
1206                         :plist new-plist)))))
1207
1208 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1209 ;; support for interning URIs
1210
1211 (defun make-uri-space (&rest keys &key (size 777) &allow-other-keys)
1212   #+allegro
1213   (apply #'make-hash-table :size size
1214          :hash-function 'uri-hash
1215          :test 'uri= :values nil keys)
1216   #-allegro
1217   (apply #'make-hash-table :size size keys))
1218
1219 (defun gethash-uri (uri table)
1220   #+allegro (gethash uri table)
1221   #-allegro
1222   (let* ((hash (uri-hash uri))
1223          (existing (gethash hash table)))
1224     (dolist (u existing)
1225       (when (uri= u uri)
1226         (return-from gethash-uri (values u t))))
1227     (values nil nil)))
1228
1229 (defun puthash-uri (uri table)
1230   #+allegro (excl:puthash-key uri table)
1231   #-allegro
1232   (let ((existing (gethash (uri-hash uri) table)))
1233     (dolist (u existing)
1234       (when (uri= u uri)
1235         (return-from puthash-uri u)))
1236     (setf (gethash (uri-hash uri) table)
1237       (cons uri existing))
1238     uri))
1239
1240
1241 (defun uri-hash (uri)
1242   (if* (uri-hashcode uri)
1243      thenret
1244      else (setf (uri-hashcode uri)
1245                 (sxhash
1246                  #+allegro
1247                  (render-uri uri nil)
1248                  #-allegro
1249                  (string-downcase
1250                   (render-uri uri nil))))))
1251
1252 (defvar *uris* (make-uri-space))
1253
1254 (defun uri-space () *uris*)
1255
1256 (defun (setf uri-space) (new-val)
1257   (setq *uris* new-val))
1258
1259 ;; bootstrapping (uri= changed from function to method):
1260 (when (fboundp 'uri=) (fmakunbound 'uri=))
1261
1262 (defgeneric uri= (uri1 uri2))
1263 (defmethod uri= ((uri1 uri) (uri2 uri))
1264   (when (not (eq (uri-scheme uri1) (uri-scheme uri2)))
1265     (return-from uri= nil))
1266   ;; RFC2396 says: a URL with an explicit ":port", where the port is
1267   ;; the default for the scheme, is the equivalent to one where the
1268   ;; port is elided.  Hmmmm.  This means that this function has to be
1269   ;; scheme dependent.  Grrrr.
1270   (let ((default-port (case (uri-scheme uri1)
1271                         (:http 80)
1272                         (:https 443)
1273                         (:ftp 21)
1274                         (:telnet 23))))
1275     (and (equalp (uri-host uri1) (uri-host uri2))
1276          (eql (or (uri-port uri1) default-port)
1277               (or (uri-port uri2) default-port))
1278          (string= (uri-path uri1) (uri-path uri2))
1279          (string= (uri-query uri1) (uri-query uri2))
1280          (string= (uri-fragment uri1) (uri-fragment uri2)))))
1281
1282 (defmethod uri= ((urn1 urn) (urn2 urn))
1283   (when (not (eq (uri-scheme urn1) (uri-scheme urn2)))
1284     (return-from uri= nil))
1285   (and (equalp (urn-nid urn1) (urn-nid urn2))
1286        (urn-nss-equal (urn-nss urn1) (urn-nss urn2))))
1287
1288 (defun urn-nss-equal (nss1 nss2 &aux len)
1289   ;; Return t iff the nss values are the same.
1290   ;; %2c and %2C are equivalent.
1291   (when (or (null nss1) (null nss2)
1292             (not (= (setq len (length nss1))
1293                     (length nss2))))
1294     (return-from urn-nss-equal nil))
1295   (do* ((i 0 (1+ i))
1296         (state :char)
1297         c1 c2)
1298       ((= i len) t)
1299     (setq c1 (char nss1 i))
1300     (setq c2 (char nss2 i))
1301     (ecase state
1302       (:char
1303        (if* (and (char= #\% c1) (char= #\% c2))
1304           then (setq state :percent+1)
1305         elseif (char/= c1 c2)
1306           then (return nil)))
1307       (:percent+1
1308        (when (char-not-equal c1 c2) (return nil))
1309        (setq state :percent+2))
1310       (:percent+2
1311        (when (char-not-equal c1 c2) (return nil))
1312        (setq state :char)))))
1313
1314 (defmethod intern-uri ((xuri uri) &optional (uri-space *uris*))
1315   (let ((uri (gethash-uri xuri uri-space)))
1316     (if* uri
1317        thenret
1318        else (puthash-uri xuri uri-space))))
1319
1320 (defmethod intern-uri ((uri string) &optional (uri-space *uris*))
1321   (intern-uri (parse-uri uri) uri-space))
1322
1323 (defun unintern-uri (uri &optional (uri-space *uris*))
1324   (if* (eq t uri)
1325      then (clrhash uri-space)
1326    elseif (uri-p uri)
1327      then (remhash uri uri-space)
1328      else (error "bad uri: ~s." uri)))
1329
1330 (defmacro do-all-uris ((var &optional uri-space result-form)
1331                        &rest forms
1332                        &environment env)
1333   "do-all-uris (var [[uri-space] result-form])
1334                     {declaration}* {tag | statement}*
1335 Executes the forms once for each uri with var bound to the current uri"
1336   (let ((f (gensym))
1337         (g-ignore (gensym))
1338         (g-uri-space (gensym))
1339         (body (third (parse-body forms env))))
1340     `(let ((,g-uri-space (or ,uri-space *uris*)))
1341        (prog nil
1342          (flet ((,f (,var &optional ,g-ignore)
1343                   (declare (ignore-if-unused ,var ,g-ignore))
1344                   (tagbody ,@body)))
1345            (maphash #',f ,g-uri-space))
1346          (return ,result-form)))))
1347
1348 (defun sharp-u (stream chr arg)
1349   (declare (ignore chr arg))
1350   (let ((arg (read stream nil nil t)))
1351     (if *read-suppress*
1352         nil
1353       (if* (stringp arg)
1354          then (parse-uri arg)
1355          else
1356
1357          (internal-reader-error
1358           stream
1359           "#u takes a string or list argument: ~s" arg)))))
1360
1361
1362 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)
1363
1364 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1365
1366 (provide :uri)
1367
1368 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1369 ;; timings
1370 ;; (don't run under emacs with M-x fi:common-lisp)
1371
1372 #+allegro
1373 (eval-when (:compile-toplevel :load-toplevel :execute)
1374   (import 'excl::gc))
1375
1376 #-allegro
1377 (defun gc (&rest options)
1378   (declare (ignore options))
1379   #+sbcl (sb-ext::gc)
1380   #+cmu (ext::gc)
1381   )
1382
1383 (defun time-uri-module ()
1384   (declare (optimize (speed 3) (safety 0) (debug 0)))
1385   (let ((uri "http://www.franz.com/a/b;x;y;z/c/foo?bar=baz&xxx#foo")
1386         (uri2 "http://www.franz.com/a/b;x;y;z/c/%2ffoo?bar=baz&xxx#foo"))
1387     (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1388     (format t "~&;;; starting timing testing 1...~%")
1389     (time (dotimes (i 100000) (parse-uri uri)))
1390
1391     (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1392     (format t "~&;;; starting timing testing 2...~%")
1393     (let ((uri (parse-uri uri)))
1394       (time (dotimes (i 100000)
1395               ;; forces no caching of the printed representation:
1396               (setf (uri-string uri) nil)
1397               (format nil "~a" uri))))
1398
1399     (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1400     (format t "~&;;; starting timing testing 3...~%")
1401     (time
1402      (progn
1403        (dotimes (i 100000) (parse-uri uri2))
1404        (let ((uri (parse-uri uri)))
1405          (dotimes (i 100000)
1406            ;; forces no caching of the printed representation:
1407            (setf (uri-string uri) nil)
1408            (format nil "~a" uri)))))))
1409
1410 ;;******** reference output (ultra, modified 5.0.1):
1411 ;;; starting timing testing 1...
1412 ; cpu time (non-gc) 13,710 msec user, 0 msec system
1413 ; cpu time (gc)     600 msec user, 10 msec system
1414 ; cpu time (total)  14,310 msec user, 10 msec system
1415 ; real time  14,465 msec
1416 ; space allocation:
1417 ;  1,804,261 cons cells, 7 symbols, 41,628,832 other bytes, 0 static bytes
1418 ;;; starting timing testing 2...
1419 ; cpu time (non-gc) 27,500 msec user, 0 msec system
1420 ; cpu time (gc)     280 msec user, 20 msec system
1421 ; cpu time (total)  27,780 msec user, 20 msec system
1422 ; real time  27,897 msec
1423 ; space allocation:
1424 ;  1,900,463 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1425 ;;; starting timing testing 3...
1426 ; cpu time (non-gc) 52,290 msec user, 10 msec system
1427 ; cpu time (gc)     1,290 msec user, 30 msec system
1428 ; cpu time (total)  53,580 msec user, 40 msec system
1429 ; real time  54,062 msec
1430 ; space allocation:
1431 ;  7,800,205 cons cells, 0 symbols, 81,697,496 other bytes, 0 static bytes
1432
1433 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1434 ;;; after improving decode-escaped-encoding/encode-escaped-encoding:
1435
1436 ;;; starting timing testing 1...
1437 ; cpu time (non-gc) 14,520 msec user, 0 msec system
1438 ; cpu time (gc)     400 msec user, 0 msec system
1439 ; cpu time (total)  14,920 msec user, 0 msec system
1440 ; real time  15,082 msec
1441 ; space allocation:
1442 ;  1,800,270 cons cells, 0 symbols, 41,600,160 other bytes, 0 static bytes
1443 ;;; starting timing testing 2...
1444 ; cpu time (non-gc) 27,490 msec user, 10 msec system
1445 ; cpu time (gc)     300 msec user, 0 msec system
1446 ; cpu time (total)  27,790 msec user, 10 msec system
1447 ; real time  28,025 msec
1448 ; space allocation:
1449 ;  1,900,436 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1450 ;;; starting timing testing 3...
1451 ; cpu time (non-gc) 47,900 msec user, 20 msec system
1452 ; cpu time (gc)     920 msec user, 10 msec system
1453 ; cpu time (total)  48,820 msec user, 30 msec system
1454 ; real time  49,188 msec
1455 ; space allocation:
1456 ;  3,700,215 cons cells, 0 symbols, 81,707,144 other bytes, 0 static bytes