Merge branch 'master' of github.com:archimag/puri-unicode
[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 (defmethod initialize-instance :after ((uri puri:uri) &key &allow-other-keys)
248   (let ((parsed-path (puri:uri-parsed-path uri)))
249     (when parsed-path
250       (setf (puri:uri-parsed-path uri)
251             parsed-path))))
252
253 (defclass urn (uri)
254   ((nid :initarg :nid :initform nil :accessor urn-nid)
255    (nss :initarg :nss :initform nil :accessor urn-nss)))
256
257 (eval-when (:compile-toplevel :execute)
258   (defmacro clear-caching-on-slot-change (name)
259     `(defmethod (setf ,name) :around (new-value (self uri))
260        (declare (ignore new-value))
261        (prog1 (call-next-method)
262          (setf (uri-string self) nil)
263          ,@(when (eq name 'uri-path) `((setf (.uri-parsed-path self) nil)))
264          (setf (uri-hashcode self) nil))))
265   )
266
267 (clear-caching-on-slot-change uri-scheme)
268 (clear-caching-on-slot-change uri-host)
269 (clear-caching-on-slot-change uri-port)
270 (clear-caching-on-slot-change uri-path)
271 (clear-caching-on-slot-change uri-query)
272 (clear-caching-on-slot-change uri-fragment)
273
274
275 (defmethod make-load-form ((self uri) &optional env)
276   (declare (ignore env))
277   `(make-instance ',(class-name (class-of self))
278      :scheme ,(uri-scheme self)
279      :host ,(uri-host self)
280      :port ,(uri-port self)
281      :path ',(uri-path self)
282      :query ,(uri-query self)
283      :fragment ,(uri-fragment self)
284      :plist ',(uri-plist self)
285      :string ,(uri-string self)
286      :parsed-path ',(.uri-parsed-path self)))
287
288 (defmethod uri-p ((thing uri)) t)
289 (defmethod uri-p ((thing t)) nil)
290
291 (defun copy-uri (uri
292                  &key place
293                       (scheme (when uri (uri-scheme uri)))
294                       (host (when uri (uri-host uri)))
295                       (port (when uri (uri-port uri)))
296                       (path (when uri (uri-path uri)))
297                       (parsed-path
298                        (when uri (copy-list (.uri-parsed-path uri))))
299                       (query (when uri (uri-query uri)))
300                       (fragment (when uri (uri-fragment uri)))
301                       (plist (when uri (copy-list (uri-plist uri))))
302                       (class (when uri (class-of uri)))
303                  &aux (escaped (when uri (uri-escaped uri))))
304   (if* place
305      then (setf (uri-scheme place) scheme)
306           (setf (uri-host place) host)
307           (setf (uri-port place) port)
308           (setf (uri-path place) path)
309           (setf (.uri-parsed-path place) parsed-path)
310           (setf (uri-query place) query)
311           (setf (uri-fragment place) fragment)
312           (setf (uri-plist place) plist)
313           (setf (uri-escaped place) escaped)
314           (setf (uri-string place) nil)
315           (setf (uri-hashcode place) nil)
316           place
317    elseif (eq 'uri class)
318      then ;; allow the compiler to optimize the call to make-instance:
319           (make-instance 'uri
320             :scheme scheme :host host :port port :path path
321             :parsed-path parsed-path
322             :query query :fragment fragment :plist plist
323             :escaped escaped :string nil :hashcode nil)
324      else (make-instance class
325             :scheme scheme :host host :port port :path path
326             :parsed-path parsed-path
327             :query query :fragment fragment :plist plist
328             :escaped escaped :string nil :hashcode nil)))
329
330 (defmethod uri-parsed-path ((uri uri))
331   (when (uri-path uri)
332     (when (null (.uri-parsed-path uri))
333       (setf (.uri-parsed-path uri)
334         (parse-path (uri-path uri) (uri-escaped uri))))
335     (.uri-parsed-path uri)))
336
337 (defmethod (setf uri-parsed-path) (path-list (uri uri))
338   (assert (and (consp path-list)
339                (or (member (car path-list) '(:absolute :relative)
340                            :test #'eq))))
341   (setf (uri-path uri) (render-parsed-path path-list t))
342   (setf (.uri-parsed-path uri) path-list)
343   path-list)
344
345 (defun uri-authority (uri)
346   (when (uri-host uri)
347     (let ((*print-pretty* nil))
348       (format nil "~a~@[:~a~]" (uri-host uri) (uri-port uri)))))
349
350 (defun uri-nid (uri)
351   (if* (equalp "urn" (uri-scheme uri))
352      then (uri-host uri)
353      else (error "URI is not a URN: ~s." uri)))
354
355 (defun uri-nss (uri)
356   (if* (equalp "urn" (uri-scheme uri))
357      then (uri-path uri)
358      else (error "URI is not a URN: ~s." uri)))
359
360 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
361 ;; Parsing
362
363 (defparameter *excluded-characters*
364     (append
365      ;; exclude control characters
366      (loop for i from 0 to #x1f
367            collect (code-char i))
368      '(;; `delims' (except #\%, because it's handled specially):
369       #\< #\> #\" #\space #\#
370       #\Rubout ;; (code-char #x7f)
371       ;; `unwise':
372       #\{ #\} #\| #\\ #\^ #\[ #\] #\`))
373   "Excluded charcters from RFC2369 (http://www.ietf.org/rfc/rfc2396.txt 2.4.3)")
374
375 (defun reserved-char-vector (chars &key except)
376   (do* ((a (make-array 128 :element-type 'bit :initial-element 0))
377         (chars chars (cdr chars))
378         (c (car chars) (car chars)))
379       ((null chars) a)
380     (if* (and except (member c except :test #'char=))
381        thenret
382        else (setf (sbit a (char-int c)) 1))))
383
384 (defparameter *reserved-characters*
385     (reserved-char-vector
386      (append *excluded-characters*
387              '(#\; #\/ #\? #\: #\@ #\& #\= #\+ #\$ #\, #\%))))
388 (defparameter *reserved-authority-characters*
389     (reserved-char-vector
390      (append *excluded-characters* '(#\; #\/ #\? #\: #\@))))
391 (defparameter *reserved-path-characters*
392     (reserved-char-vector
393      (append *excluded-characters*
394              '(#\; #\%
395 ;;;;The rfc says this should be here, but it doesn't make sense.
396                ;; #\=
397                #\/ #\?))))
398
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
660               (if* (and (equalp "file" scheme)
661                         (null host))
662                  then ;; file:///...
663                       (push "/" path-components)
664                       (setq state 6)
665                  else (failure)))
666              (:string (setq host tokval)
667                       (setq state 11))
668              (:end (failure))))
669           (11 ;; seen [<scheme>:]//<host>
670            (ecase (read-token t)
671              (:colon (setq state 5))
672              (:question (setq state 7))
673              (:hash (setq state 8))
674              (:slash (push "/" path-components)
675                      (setq state 6))
676              (:string (impossible))
677              (:end (setq state 9))))
678           (5 ;; seen [<scheme>:]//<host>:
679            (ecase (read-token t)
680              (:colon (failure))
681              (:question (failure))
682              (:hash (failure))
683              (:slash (push "/" path-components)
684                      (setq state 6))
685              (:string (setq port tokval)
686                       (setq state 12))
687              (:end (failure))))
688           (12 ;; seen [<scheme>:]//<host>:[<port>]
689            (ecase (read-token t)
690              (:colon (failure))
691              (:question (setq state 7))
692              (:hash (setq state 8))
693              (:slash (push "/" path-components)
694                      (setq state 6))
695              (:string (impossible))
696              (:end (setq state 9))))
697           (6 ;; seen /
698            (ecase (read-token :path)
699              (:question (setq state 7))
700              (:hash (setq state 8))
701              (:string (push tokval path-components)
702                       (setq state 13))
703              (:end (setq state 9))))
704           (13 ;; seen path
705            (ecase (read-token :path)
706              (:question (setq state 7))
707              (:hash (setq state 8))
708              (:string (impossible))
709              (:end (setq state 9))))
710           (7 ;; seen ?
711            (setq illegal-chars
712              (if* *strict-parse*
713                 then *strict-illegal-query-characters*
714                 else *illegal-query-characters*))
715            (ecase (prog1 (read-token :query)
716                     (setq illegal-chars *illegal-characters*))
717              (:hash (setq state 8))
718              (:string (setq query tokval)
719                       (setq state 14))
720              (:end (setq state 9))))
721           (14 ;; query
722            (ecase (read-token :query)
723              (:hash (setq state 8))
724              (:string (impossible))
725              (:end (setq state 9))))
726           (8 ;; seen #
727            (ecase (read-token :rest)
728              (:string (setq fragment tokval)
729                       (setq state 9))
730              (:end (setq state 9))))
731           (9 ;; done
732            (return
733              (values
734               scheme host port
735               (apply #'concatenate 'string (nreverse path-components))
736               query fragment)))
737           ;; URN parsing:
738           (15 ;; seen urn:, read nid now
739            (case (read-token :colon *valid-nid-characters*)
740              (:string (setq nid tokval)
741                       (setq state 16))
742              (t (failure "missing namespace identifier"))))
743           (16 ;; seen urn:<nid>
744            (case (read-token t)
745              (:colon (setq state 17))
746              (t (failure "missing namespace specific string"))))
747           (17 ;; seen urn:<nid>:, rest is nss
748            (return (values scheme
749                            nid
750                            nil
751                            (progn
752                              (setq illegal-chars *reserved-nss-characters*)
753                              (read-token :rest)
754                              tokval))))
755           (t (.parse-error
756               "internal error in parse engine, wrong state: ~s." state)))))))
757
758 (defun escape-p (string)
759   (declare (optimize (speed 3)))
760   (do* ((i 0 (1+ i))
761         (max (the fixnum (length string))))
762       ((= i max) nil)
763     (declare (fixnum i max))
764     (when (char= #\% (char string i))
765       (return t))))
766
767 (defun parse-path (path-string escape)
768   (do* ((xpath-list (delimited-string-to-list path-string #\/))
769         (path-list
770          (progn
771            (if* (string= "" (car xpath-list))
772               then (setf (car xpath-list) :absolute)
773               else (push :relative xpath-list))
774            xpath-list))
775         (pl (cdr path-list) (cdr pl))
776         segments)
777       ((null pl) path-list)
778
779     (if* (cdr (setq segments
780                 (if* (string= "" (car pl))
781                    then '("")
782                    else (delimited-string-to-list (car pl) #\;))))
783        then ;; there is a param
784             (setf (car pl)
785               (mapcar #'(lambda (s)
786                           (decode-escaped-encoding s escape
787                                                    ;; decode all %xx:
788                                                    nil))
789                       segments))
790        else ;; no param
791             (setf (car pl)
792               (decode-escaped-encoding (car segments) escape
793                                        ;; decode all %xx:
794                                        nil)))))
795
796 (defun decode-escaped-encoding (string escape
797                                 &optional (reserved-chars
798                                            *reserved-characters*))
799   ;;Return a string with the real characters.
800   (when (null escape) (return-from decode-escaped-encoding string))
801
802   (let ((curpos 0)
803         (maxpos (length string))
804         (strs nil))
805     (flet ((next-ansii-substring ()
806              (let ((pos (or (position #\% string :start curpos)
807                             maxpos)))
808                (when (and (= curpos 0)
809                           (= pos maxpos))
810                  (return-from decode-escaped-encoding string))
811                (when (< curpos pos)
812                  (push (subseq string
813                                curpos
814                                pos)
815                        strs)
816                  (setf curpos pos))))
817            (next-encoded-substring ()
818              (let ((pos (or (loop for i from curpos below maxpos by 3
819                                unless (char= (aref string i)
820                                              #\%)
821                                return i)
822                             maxpos)))
823                (when (< curpos pos)
824                  (let ((octets (handler-case (make-array (/ (- pos curpos)
825                                                             3)
826                                                          :element-type '(unsigned-byte 8)
827                                                          :fill-pointer 0)
828                                  (error () 
829                                    (.parse-error "Unsyntactic escaped encoding in ~s." string)))))
830                    (loop for i from curpos below pos by 3
831                       do (vector-push (handler-case
832                                           (parse-integer string
833                                                          :start (1+ i)
834                                                          :end (+ i 3)
835                                                          :radix 16)
836                                         (error ()
837                                           (.parse-error "Non-hexidecimal digits after %: ~c~c." 
838                                                         (aref string  (1+ i))
839                                                         (aref string (+ 2 i)))))
840                                       octets))
841                    
842                    (let* ((decoded-string (babel:octets-to-string octets
843                                                                   :encoding :utf-8))
844                           (rpos (if reserved-chars
845                                     (position-if #'(lambda (ch)
846                                                      (not (or (> (char-code ch) 127)
847                                                               (= (sbit reserved-chars (char-code ch)) 0))))
848                                                  decoded-string))))
849                      (push (if rpos
850                                (with-output-to-string (out)
851                                  (loop for ch across decoded-string
852                                     with i = curpos
853                                     do (let ((code (char-code ch)))
854                                          (cond
855                                            ((or (null reserved-chars)
856                                                 (> code 127)
857                                                 (= (sbit reserved-chars code) 0))
858                                             (write-char ch out)
859                                             (incf i
860                                                   (* (cond
861                                                        ((< code #x80) 1)
862                                                        ((< code #x800) 2)
863                                                        ((< code #x10000) 3)
864                                                        ((< code #x200000) 4)
865                                                        ((< code #x4000000) 5)
866                                                        (t 6))
867                                                      3)))
868                                            (t (write-string (subseq string i (+ i 3)) out)
869                                               (incf i 3))))))
870                                decoded-string)
871                            strs))))
872                    (setf curpos pos))))
873       (loop
874          while (< curpos maxpos)
875          do (next-ansii-substring)
876          while (< curpos maxpos)
877          do (next-encoded-substring)))
878     (if (cdr strs)
879         (apply #'concatenate
880                    'string
881                    (nreverse strs))
882         (or (car strs)
883             ""))))
884
885                          
886 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
887 ;;;; Printing
888
889 (defun render-uri (uri stream
890                    &aux (escape (uri-escaped uri))
891                         (*print-pretty* nil))
892   (when (null (uri-string uri))
893     (setf (uri-string uri)
894       (let ((scheme (uri-scheme uri))
895             (host (uri-host uri))
896             (port (uri-port uri))
897             (path (uri-path uri))
898             (query (uri-query uri))
899             (fragment (uri-fragment uri)))
900         (concatenate 'string
901           (when scheme
902             (encode-escaped-encoding
903              (string-downcase ;; for upper case lisps
904               (symbol-name scheme))
905              *reserved-characters* escape))
906           (when scheme ":")
907           (when (or host (eq :file scheme)) "//")
908           (when host
909             (encode-escaped-encoding
910              host *reserved-authority-characters* escape))
911           (when port ":")
912           (when port
913             #-allegro (format nil "~D" port)
914             #+allegro (with-output-to-string (s)
915                         (excl::maybe-print-fast s port))
916             )
917           (encode-escaped-encoding (or path "/")
918                                    nil
919                                    ;;*reserved-path-characters*
920                                    escape)
921           (when query "?")
922           (when query (encode-escaped-encoding query nil escape))
923           (when fragment "#")
924           (when fragment (encode-escaped-encoding fragment nil escape))))))
925   (if* stream
926      then (format stream "~a" (uri-string uri))
927      else (uri-string uri)))
928
929 (defun render-parsed-path (path-list escape)
930   (do* ((res '())
931         (first (car path-list))
932         (pl (cdr path-list) (cdr pl))
933         (pe (car pl) (car pl)))
934       ((null pl)
935        (when res (apply #'concatenate 'string (nreverse res))))
936     (when (or (null first)
937               (prog1 (eq :absolute first)
938                 (setq first nil)))
939       (push "/" res))
940     (if* (atom pe)
941        then (push
942              (encode-escaped-encoding pe *reserved-path-characters* escape)
943              res)
944        else ;; contains params
945             (push (encode-escaped-encoding
946                    (car pe) *reserved-path-characters* escape)
947                   res)
948             (dolist (item (cdr pe))
949               (push ";" res)
950               (push (encode-escaped-encoding
951                      item *reserved-path-characters* escape)
952                     res)))))
953
954 (defun render-urn (urn stream
955                    &aux (*print-pretty* nil))
956   (when (null (uri-string urn))
957     (setf (uri-string urn)
958       (let ((nid (urn-nid urn))
959             (nss (urn-nss urn)))
960         (concatenate 'string "urn:" nid ":" nss))))
961   (if* stream
962      then (format stream "~a" (uri-string urn))
963      else (uri-string urn)))
964
965 (defun encode-escaped-encoding (string reserved-chars escape)
966   (when (null escape) (return-from encode-escaped-encoding string))
967   (with-output-to-string (out)
968     (loop for ch across string
969        do (let ((code (char-code ch)))  
970             (if (and (< code 128)
971                      (or (null reserved-chars)
972                          (= 0 (sbit reserved-chars code))))
973                 (write-char ch out)
974                 (loop for octet across (babel:string-to-octets (string ch) :encoding :utf-8)
975                    do (format out "%~(~2,'0x~)" octet)))))))
976
977 (defmethod print-object ((uri uri) stream)
978   (if* *print-escape*
979      then (print-unreadable-object (uri stream :type t) (render-uri uri stream))
980      else (render-uri uri stream)))
981
982 (defmethod print-object ((urn urn) stream)
983   (if* *print-escape*
984      then (print-unreadable-object (urn stream :type t) (render-urn urn stream))
985      else (render-urn urn stream)))
986
987 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
988 ;; merging and unmerging
989
990 (defmethod merge-uris ((uri string) (base string) &optional place)
991   (merge-uris (parse-uri uri) (parse-uri base) place))
992
993 (defmethod merge-uris ((uri uri) (base string) &optional place)
994   (merge-uris uri (parse-uri base) place))
995
996 (defmethod merge-uris ((uri string) (base uri) &optional place)
997   (merge-uris (parse-uri uri) base place))
998
999
1000 (defmethod merge-uris ((uri uri) (base uri) &optional place)
1001   ;; See ../doc/rfc2396.txt for info on the algorithm we use to merge
1002   ;; URIs.
1003   ;;
1004   (tagbody
1005 ;;;; step 2
1006     (when (and (null (uri-parsed-path uri))
1007                (null (uri-scheme uri))
1008                (null (uri-host uri))
1009                (null (uri-port uri))
1010                (null (uri-query uri)))
1011       (return-from merge-uris
1012         (let ((new (copy-uri base :place place)))
1013           (when (uri-query uri)
1014             (setf (uri-query new) (uri-query uri)))
1015           (when (uri-fragment uri)
1016             (setf (uri-fragment new) (uri-fragment uri)))
1017           new)))
1018
1019     (setq uri (copy-uri uri :place place))
1020
1021 ;;;; step 3
1022     (when (uri-scheme uri)
1023       (return-from merge-uris uri))
1024     (setf (uri-scheme uri) (uri-scheme base))
1025
1026 ;;;; step 4
1027     (when (uri-host uri) (go :done))
1028     (setf (uri-host uri) (uri-host base))
1029     (setf (uri-port uri) (uri-port base))
1030
1031 ;;;; step 5
1032     (let ((p (uri-parsed-path uri)))
1033
1034       ;; bug13133:
1035       ;; The following form causes our implementation to be at odds with
1036       ;; RFC 2396, however this is apparently what was intended by the
1037       ;; authors of the RFC.  Specifically, (merge-uris "?y" "/foo")
1038       ;; should return #<uri /foo?y> instead of #<uri ?y>, according to
1039       ;; this:
1040 ;;; http://www.apache.org/~fielding/uri/rev-2002/issues.html#003-relative-query
1041       (when (null p)
1042         (setf (uri-path uri) (uri-path base))
1043         (go :done))
1044
1045       (when (and p (eq :absolute (car p)))
1046         (when (equal '(:absolute "") p)
1047           ;; Canonicalize the way parsing does:
1048           (setf (uri-path uri) nil))
1049         (go :done)))
1050
1051 ;;;; step 6
1052     (let* ((base-path
1053             (or (uri-parsed-path base)
1054                 ;; needed because we canonicalize away a path of just `/':
1055                 '(:absolute "")))
1056            (path (uri-parsed-path uri))
1057            new-path-list)
1058       (when (not (eq :absolute (car base-path)))
1059         (error "Cannot merge ~a and ~a, since latter is not absolute."
1060                uri base))
1061
1062       ;; steps 6a and 6b:
1063       (setq new-path-list
1064         (append (butlast base-path)
1065                 (if* path then (cdr path) else '(""))))
1066
1067       ;; steps 6c and 6d:
1068       (let ((last (last new-path-list)))
1069         (if* (atom (car last))
1070            then (when (string= "." (car last))
1071                   (setf (car last) ""))
1072            else (when (string= "." (caar last))
1073                   (setf (caar last) ""))))
1074       (setq new-path-list
1075         (delete "." new-path-list :test #'(lambda (a b)
1076                                             (if* (atom b)
1077                                                then (string= a b)
1078                                                else nil))))
1079
1080       ;; steps 6e and 6f:
1081       (let ((npl (cdr new-path-list))
1082             index tmp fix-tail)
1083         (setq fix-tail
1084           (string= ".." (let ((l (car (last npl))))
1085                           (if* (atom l)
1086                              then l
1087                              else (car l)))))
1088         (loop
1089           (setq index
1090             (position ".." npl
1091                       :test #'(lambda (a b)
1092                                 (string= a
1093                                          (if* (atom b)
1094                                             then b
1095                                             else (car b))))))
1096           (when (null index) (return))
1097           (when (= 0 index)
1098             ;; The RFC says, in 6g, "that the implementation may handle
1099             ;; this error by retaining these components in the resolved
1100             ;; path, by removing them from the resolved path, or by
1101             ;; avoiding traversal of the reference."  The examples in C.2
1102             ;; imply that we should do the first thing (retain them), so
1103             ;; that's what we'll do.
1104             (return))
1105           (if* (= 1 index)
1106              then (setq npl (cddr npl))
1107              else (setq tmp npl)
1108                   (dotimes (x (- index 2)) (setq tmp (cdr tmp)))
1109                   (setf (cdr tmp) (cdddr tmp))))
1110         (setf (cdr new-path-list) npl)
1111         (when fix-tail (setq new-path-list (nconc new-path-list '("")))))
1112
1113       ;; step 6g:
1114       ;; don't complain if new-path-list starts with `..'.  See comment
1115       ;; above about this step.
1116
1117       ;; step 6h:
1118       (when (or (equal '(:absolute "") new-path-list)
1119                 (equal '(:absolute) new-path-list))
1120         (setq new-path-list nil))
1121       (setf (uri-path uri)
1122         (render-parsed-path new-path-list
1123                             ;; don't know, so have to assume:
1124                             t)))
1125
1126 ;;;; step 7
1127    :done
1128     (return-from merge-uris uri)))
1129
1130 (defmethod enough-uri ((uri string) (base string) &optional place)
1131   (enough-uri (parse-uri uri) (parse-uri base) place))
1132
1133 (defmethod enough-uri ((uri uri) (base string) &optional place)
1134   (enough-uri uri (parse-uri base) place))
1135
1136 (defmethod enough-uri ((uri string) (base uri) &optional place)
1137   (enough-uri (parse-uri uri) base place))
1138
1139 (defmethod enough-uri ((uri uri) (base uri) &optional place)
1140   (let ((new-scheme nil)
1141         (new-host nil)
1142         (new-port nil)
1143         (new-parsed-path nil))
1144
1145     (when (or (and (uri-scheme uri)
1146                    (not (equalp (uri-scheme uri) (uri-scheme base))))
1147               (and (uri-host uri)
1148                    (not (equalp (uri-host uri) (uri-host base))))
1149               (not (equalp (uri-port uri) (uri-port base))))
1150       (return-from enough-uri uri))
1151
1152     (when (null (uri-host uri))
1153       (setq new-host (uri-host base)))
1154     (when (null (uri-port uri))
1155       (setq new-port (uri-port base)))
1156
1157     (when (null (uri-scheme uri))
1158       (setq new-scheme (uri-scheme base)))
1159
1160     ;; Now, for the hard one, path.
1161     ;; We essentially do here what enough-namestring does.
1162     (do* ((base-path (uri-parsed-path base))
1163           (path (uri-parsed-path uri))
1164           (bp base-path (cdr bp))
1165           (p path (cdr p)))
1166         ((or (null bp) (null p))
1167          ;; If p is nil, that means we have something like
1168          ;; (enough-uri "/foo/bar" "/foo/bar/baz.htm"), so
1169          ;; new-parsed-path will be nil.
1170          (when (null bp)
1171            (setq new-parsed-path (copy-list p))
1172            (when (not (symbolp (car new-parsed-path)))
1173              (push :relative new-parsed-path))))
1174       (if* (equal (car bp) (car p))
1175          thenret ;; skip it
1176          else (setq new-parsed-path (copy-list p))
1177               (when (not (symbolp (car new-parsed-path)))
1178                 (push :relative new-parsed-path))
1179               (return)))
1180
1181     (let ((new-path
1182            (when new-parsed-path
1183              (render-parsed-path new-parsed-path
1184                                  ;; don't know, so have to assume:
1185                                  t)))
1186           (new-query (uri-query uri))
1187           (new-fragment (uri-fragment uri))
1188           (new-plist (copy-list (uri-plist uri))))
1189       (if* (and (null new-scheme)
1190                 (null new-host)
1191                 (null new-port)
1192                 (null new-path)
1193                 (null new-parsed-path)
1194                 (null new-query)
1195                 (null new-fragment))
1196          then ;; can't have a completely empty uri!
1197               (copy-uri nil
1198                         :class (class-of uri)
1199                         :place place
1200                         :path "/"
1201                         :plist new-plist)
1202          else (copy-uri nil
1203                         :class (class-of uri)
1204                         :place place
1205                         :scheme new-scheme
1206                         :host new-host
1207                         :port new-port
1208                         :path new-path
1209                         :parsed-path new-parsed-path
1210                         :query new-query
1211                         :fragment new-fragment
1212                         :plist new-plist)))))
1213
1214 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1215 ;; support for interning URIs
1216
1217 (defun make-uri-space (&rest keys &key (size 777) &allow-other-keys)
1218   #+allegro
1219   (apply #'make-hash-table :size size
1220          :hash-function 'uri-hash
1221          :test 'uri= :values nil keys)
1222   #-allegro
1223   (apply #'make-hash-table :size size keys))
1224
1225 (defun gethash-uri (uri table)
1226   #+allegro (gethash uri table)
1227   #-allegro
1228   (let* ((hash (uri-hash uri))
1229          (existing (gethash hash table)))
1230     (dolist (u existing)
1231       (when (uri= u uri)
1232         (return-from gethash-uri (values u t))))
1233     (values nil nil)))
1234
1235 (defun puthash-uri (uri table)
1236   #+allegro (excl:puthash-key uri table)
1237   #-allegro
1238   (let ((existing (gethash (uri-hash uri) table)))
1239     (dolist (u existing)
1240       (when (uri= u uri)
1241         (return-from puthash-uri u)))
1242     (setf (gethash (uri-hash uri) table)
1243       (cons uri existing))
1244     uri))
1245
1246
1247 (defun uri-hash (uri)
1248   (if* (uri-hashcode uri)
1249      thenret
1250      else (setf (uri-hashcode uri)
1251                 (sxhash
1252                  #+allegro
1253                  (render-uri uri nil)
1254                  #-allegro
1255                  (string-downcase
1256                   (render-uri uri nil))))))
1257
1258 (defvar *uris* (make-uri-space))
1259
1260 (defun uri-space () *uris*)
1261
1262 (defun (setf uri-space) (new-val)
1263   (setq *uris* new-val))
1264
1265 ;; bootstrapping (uri= changed from function to method):
1266 (when (fboundp 'uri=) (fmakunbound 'uri=))
1267
1268 (defgeneric uri= (uri1 uri2))
1269 (defmethod uri= ((uri1 uri) (uri2 uri))
1270   (when (not (eq (uri-scheme uri1) (uri-scheme uri2)))
1271     (return-from uri= nil))
1272   ;; RFC2396 says: a URL with an explicit ":port", where the port is
1273   ;; the default for the scheme, is the equivalent to one where the
1274   ;; port is elided.  Hmmmm.  This means that this function has to be
1275   ;; scheme dependent.  Grrrr.
1276   (let ((default-port (case (uri-scheme uri1)
1277                         (:http 80)
1278                         (:https 443)
1279                         (:ftp 21)
1280                         (:telnet 23))))
1281     (and (equalp (uri-host uri1) (uri-host uri2))
1282          (eql (or (uri-port uri1) default-port)
1283               (or (uri-port uri2) default-port))
1284          (string= (uri-path uri1) (uri-path uri2))
1285          (string= (uri-query uri1) (uri-query uri2))
1286          (string= (uri-fragment uri1) (uri-fragment uri2)))))
1287
1288 (defmethod uri= ((urn1 urn) (urn2 urn))
1289   (when (not (eq (uri-scheme urn1) (uri-scheme urn2)))
1290     (return-from uri= nil))
1291   (and (equalp (urn-nid urn1) (urn-nid urn2))
1292        (urn-nss-equal (urn-nss urn1) (urn-nss urn2))))
1293
1294 (defun urn-nss-equal (nss1 nss2 &aux len)
1295   ;; Return t iff the nss values are the same.
1296   ;; %2c and %2C are equivalent.
1297   (when (or (null nss1) (null nss2)
1298             (not (= (setq len (length nss1))
1299                     (length nss2))))
1300     (return-from urn-nss-equal nil))
1301   (do* ((i 0 (1+ i))
1302         (state :char)
1303         c1 c2)
1304       ((= i len) t)
1305     (setq c1 (char nss1 i))
1306     (setq c2 (char nss2 i))
1307     (ecase state
1308       (:char
1309        (if* (and (char= #\% c1) (char= #\% c2))
1310           then (setq state :percent+1)
1311         elseif (char/= c1 c2)
1312           then (return nil)))
1313       (:percent+1
1314        (when (char-not-equal c1 c2) (return nil))
1315        (setq state :percent+2))
1316       (:percent+2
1317        (when (char-not-equal c1 c2) (return nil))
1318        (setq state :char)))))
1319
1320 (defmethod intern-uri ((xuri uri) &optional (uri-space *uris*))
1321   (let ((uri (gethash-uri xuri uri-space)))
1322     (if* uri
1323        thenret
1324        else (puthash-uri xuri uri-space))))
1325
1326 (defmethod intern-uri ((uri string) &optional (uri-space *uris*))
1327   (intern-uri (parse-uri uri) uri-space))
1328
1329 (defun unintern-uri (uri &optional (uri-space *uris*))
1330   (if* (eq t uri)
1331      then (clrhash uri-space)
1332    elseif (uri-p uri)
1333      then (remhash uri uri-space)
1334      else (error "bad uri: ~s." uri)))
1335
1336 (defmacro do-all-uris ((var &optional uri-space result-form)
1337                        &rest forms
1338                        &environment env)
1339   "do-all-uris (var [[uri-space] result-form])
1340                     {declaration}* {tag | statement}*
1341 Executes the forms once for each uri with var bound to the current uri"
1342   (let ((f (gensym))
1343         (g-ignore (gensym))
1344         (g-uri-space (gensym))
1345         (body (third (parse-body forms env))))
1346     `(let ((,g-uri-space (or ,uri-space *uris*)))
1347        (prog nil
1348          (flet ((,f (,var &optional ,g-ignore)
1349                   (declare (ignore-if-unused ,var ,g-ignore))
1350                   (tagbody ,@body)))
1351            (maphash #',f ,g-uri-space))
1352          (return ,result-form)))))
1353
1354 (defun sharp-u (stream chr arg)
1355   (declare (ignore chr arg))
1356   (let ((arg (read stream nil nil t)))
1357     (if *read-suppress*
1358         nil
1359       (if* (stringp arg)
1360          then (parse-uri arg)
1361          else
1362
1363          (internal-reader-error
1364           stream
1365           "#u takes a string or list argument: ~s" arg)))))
1366
1367
1368 (set-dispatch-macro-character #\# #\u #'puri::sharp-u)
1369
1370 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1371
1372 (provide :uri)
1373
1374 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1375 ;; timings
1376 ;; (don't run under emacs with M-x fi:common-lisp)
1377
1378 #+allegro
1379 (eval-when (:compile-toplevel :load-toplevel :execute)
1380   (import 'excl::gc))
1381
1382 #-allegro
1383 (defun gc (&rest options)
1384   (declare (ignore options))
1385   #+sbcl (sb-ext::gc)
1386   #+cmu (ext::gc)
1387   )
1388
1389 (defun time-uri-module ()
1390   (declare (optimize (speed 3) (safety 0) (debug 0)))
1391   (let ((uri "http://www.franz.com/a/b;x;y;z/c/foo?bar=baz&xxx#foo")
1392         (uri2 "http://www.franz.com/a/b;x;y;z/c/%2ffoo?bar=baz&xxx#foo"))
1393     (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1394     (format t "~&;;; starting timing testing 1...~%")
1395     (time (dotimes (i 100000) (parse-uri uri)))
1396
1397     (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1398     (format t "~&;;; starting timing testing 2...~%")
1399     (let ((uri (parse-uri uri)))
1400       (time (dotimes (i 100000)
1401               ;; forces no caching of the printed representation:
1402               (setf (uri-string uri) nil)
1403               (format nil "~a" uri))))
1404
1405     (gc t) (gc :tenure) (gc :tenure) (gc :tenure)
1406     (format t "~&;;; starting timing testing 3...~%")
1407     (time
1408      (progn
1409        (dotimes (i 100000) (parse-uri uri2))
1410        (let ((uri (parse-uri uri)))
1411          (dotimes (i 100000)
1412            ;; forces no caching of the printed representation:
1413            (setf (uri-string uri) nil)
1414            (format nil "~a" uri)))))))
1415
1416 ;;******** reference output (ultra, modified 5.0.1):
1417 ;;; starting timing testing 1...
1418 ; cpu time (non-gc) 13,710 msec user, 0 msec system
1419 ; cpu time (gc)     600 msec user, 10 msec system
1420 ; cpu time (total)  14,310 msec user, 10 msec system
1421 ; real time  14,465 msec
1422 ; space allocation:
1423 ;  1,804,261 cons cells, 7 symbols, 41,628,832 other bytes, 0 static bytes
1424 ;;; starting timing testing 2...
1425 ; cpu time (non-gc) 27,500 msec user, 0 msec system
1426 ; cpu time (gc)     280 msec user, 20 msec system
1427 ; cpu time (total)  27,780 msec user, 20 msec system
1428 ; real time  27,897 msec
1429 ; space allocation:
1430 ;  1,900,463 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1431 ;;; starting timing testing 3...
1432 ; cpu time (non-gc) 52,290 msec user, 10 msec system
1433 ; cpu time (gc)     1,290 msec user, 30 msec system
1434 ; cpu time (total)  53,580 msec user, 40 msec system
1435 ; real time  54,062 msec
1436 ; space allocation:
1437 ;  7,800,205 cons cells, 0 symbols, 81,697,496 other bytes, 0 static bytes
1438
1439 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1440 ;;; after improving decode-escaped-encoding/encode-escaped-encoding:
1441
1442 ;;; starting timing testing 1...
1443 ; cpu time (non-gc) 14,520 msec user, 0 msec system
1444 ; cpu time (gc)     400 msec user, 0 msec system
1445 ; cpu time (total)  14,920 msec user, 0 msec system
1446 ; real time  15,082 msec
1447 ; space allocation:
1448 ;  1,800,270 cons cells, 0 symbols, 41,600,160 other bytes, 0 static bytes
1449 ;;; starting timing testing 2...
1450 ; cpu time (non-gc) 27,490 msec user, 10 msec system
1451 ; cpu time (gc)     300 msec user, 0 msec system
1452 ; cpu time (total)  27,790 msec user, 10 msec system
1453 ; real time  28,025 msec
1454 ; space allocation:
1455 ;  1,900,436 cons cells, 0 symbols, 17,693,712 other bytes, 0 static bytes
1456 ;;; starting timing testing 3...
1457 ; cpu time (non-gc) 47,900 msec user, 20 msec system
1458 ; cpu time (gc)     920 msec user, 10 msec system
1459 ; cpu time (total)  48,820 msec user, 30 msec system
1460 ; real time  49,188 msec
1461 ; space allocation:
1462 ;  3,700,215 cons cells, 0 symbols, 81,707,144 other bytes, 0 static bytes