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