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