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