xml-parse.lisp 101 KB
Newer Older
david's avatar
david committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: XML; readtable: glisp; Encoding: utf-8; -*-
;;; ---------------------------------------------------------------------------
;;;     Title: A prototype XML parser
;;;   Created: 1999-07-17
;;;    Author: Gilbert Baumann <unk6@rz.uni-karlsruhe.de>
;;;   License: LGPL (See file COPYING for details).
;;; ---------------------------------------------------------------------------
;;;  © copyright 1999 by Gilbert Baumann

;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Library General Public
;;; License as published by the Free Software Foundation; either
;;; version 2 of the License, or (at your option) any later version.
;;;
;;; This library is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; Library General Public License for more details.
;;;
;;; You should have received a copy of the GNU Library General Public
;;; License along with this library; if not, write to the 
;;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, 
;;; Boston, MA  02111-1307  USA.

;;; Streams

;;; xstreams

;; For reading runes, I defined my own streams, called xstreams,
;; because we want to be fast. A function call or even a method call
;; per character is not acceptable, instead of that we define a
;; buffered stream with and advertised buffer layout, so that we
;; could use the trick stdio uses: READ-RUNE and PEEK-RUNE are macros,
;; directly accessing the buffer and only calling some underflow
;; handler in case of stream underflows. This will yield to quite a
;; performance boost vs calling READ-BYTE per character.

;; Also we need to do encoding and character set conversion on input,
;; this better done at large chunks of data rather than on a character
;; by character basis. This way we need a dispatch on the active
;; encoding only once in a while, instead of for each character. This
;; allows us to use a CLOS interface to do the underflow handling.

;;; zstreams

;; Now, for reading tokens, we define another kind of streams, called
;; zstreams. These zstreams also maintain an input stack to implement
;; inclusion of external entities. This input stack contains xstreams
;; or the special marker :STOP. Such a :STOP marker indicates, that
;; input should not continue there, but well stop; that is simulate an
;; EOF. The user is then responsible to pop this marker off the input
;; stack.
;;
;; This input stack is also used to detect circular entity inclusion.

;; The zstream tokenizer recognizes the following types of tokens and
;; is controlled by the *DATA-BEHAVIOUR* flag. (Which should become a
;; slot of zstreams instead).

;; Common
;;    :xml-pi (<target> . <content>)    ;processing-instruction starting with "<?xml"
;;    :pi (<target> . <content>)        ;processing-instruction
;;    :stag (<name> . <atts>)           ;start tag
;;    :etag (<name> . <atts>)           ;end tag
;;    :ztag (<name> . <atts>)           ;empty tag
;;    :<!element
;;    :<!entity
;;    :<!attlist
;;    :<!notation
;;    :<!doctype
;;    :<![
;;    :comment <content>

;; *data-behaviour* = :DTD
;;
;;    :name <interned-rod>
;;    :#required
;;    :#implied
;;    :#fixed
;;    :#pcdata
;;    :s
;;    :\[ :\] :\( :\) :|\ :\> :\" :\' :\, :\? :\* :\+ 

;; *data-behaviour* = :DOC
;;
;;    :entity-ref <interned-rod>
;;    :cdata <rod>




;;; NOTES
;;
;; Stream buffers as well as RODs are supposed to be encoded in
;; UTF-16. 

;; where does the time go?
;; DATA-RUNE-P
;; CANON-NOT-CDATA-ATTVAL
;; READ-ATTVAL (MUFFLE)
;; CLOSy DOM
;; UTF-8 decoder (13%)
;; READ-ATTVAL (10%)
;; 

;;; TODO
;;
;; o Improve error messages:
;;    - line and column number counters
;;    - better texts
;;    - better handling of errors (no crash'n burn behaviour)
;;
;; o provide for a faster DOM
;;
;; o parse document should get passed a document instance, so that a user
;;   could pass his own DOM implementation
;;
;; o morph zstream into a context object and thus also get rid of
;;   special variables. Put the current DTD there too.

;; o the *scratch-pad* hack should become something much more
;;   reentrant, we could either define a system-wide resource
;;   or allocate some scratch-pads per context.

;; o only parse the DTD on an option

;; o make the invalid tests pass.
;;
;; o CR handling in utf-16 deocders
;;
;; o UCS-4 reader
;;
;; o max depth together with circle detection
;;   (or proof, that our circle detection is enough).
;;
;; o element definitions (with att definitions in the elements)
;;
;; o store entities in the DTD
;;
;; o better extensibility wrt character representation, one may want to
;;   have
;;    - UTF-8  in standard CL strings
;;    - UCS-2  in RODs
;;    - UTF-16 in RODs
;;    - UCS-4  in vectoren
;;
;; o xstreams auslagern, documententieren und dann auch in SGML und
;;   CSS parser verwenden. (halt alles was zeichen liest).
;;
;; o merge node representation with SGML module
;; 
;; o namespaces (this will get ugly).
;; 
;; o validation
;;
;; o line/column number recording
;;
;; o better error messages
;;
;; o recording of source locations for nodes.
;;
;; o make the *scratch-pad* hack safe
;;
;; o based on the DTD and xml:space attribute implement HTML white
;;   space rules.
;;
;; o on a parser option, do not expand external entities.
;;
;; o on a parser option, do not parse the DTD.
;;
;; o caching DTDs?
;;
;;   That is, if we parse a lot of documents all having the same DTD,
;;   we do not need to re-read it every time.
;;   But watch the file write date, since not doing so would be
;;   a good way to confuse a hell lot of users.
;;   But: What to do with declarations in the <!DOCTYPE header?
;;
;;
;; o does the user need the distinction between "&#20;" and " " ?
;;   That is literal and 'quoted' white space.
;;
;; o on an option merge CDATA section;
;;
;; o data in parse tree? extra nodes like in SGML?!
;;
;; o what to store in the node-gi field? Some name object or the
;;   string used?
;;

;; Test that fail:
;;
;; not-wf/sa/128        is false a alarm
;;

(in-package :xml)

david's avatar
david committed
198
#+allegro
david's avatar
david committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
(setf (excl:named-readtable :glisp) *readtable*)

(eval-when (eval compile load)
  (defparameter *fast* '(optimize (speed 3) (safety 0)))
  ;;(defparameter *fast* '(optimize (speed 2) (safety 3)))
  )

(defvar *expand-pe-p*)

;;;; ---------------------------------------------------------------------------
;;;; xstreams
;;;;


(defstruct (stream-name (:type list))
  entity-name
  entity-kind
  file-name)

(defun print-xstream (self sink depth)
  (declare (ignore depth))
  (format sink "#<~S ~S>" (type-of self) (mu (xstream-name self))))

(deftype read-element () 'rune)

;; (unsigned-byte 16)) ;;t)

(defmethod figure-encoding ((stream null))
  (values :utf-8 nil))

(defmethod figure-encoding ((stream stream))
  (let ((c0 (read-byte stream nil :eof)))
    (cond ((eq c0 :eof)
           (values :utf-8 nil))
          (t
           (let ((c1 (read-byte stream nil :eof)))
             (cond ((eq c1 :eof)
                    (values :utf-8 (list c0)))
                   (t
                    (cond ((and (= c0 #xFE) (= c1 #xFF)) (values :utf-16-big-endian nil))
                          ((and (= c0 #xFF) (= c1 #xFE)) (values :utf-16-little-endian nil))
                          (t
                           (values :utf-8 (list c0 c1)))))))))))

(defun call-with-open-xstream (continuation &rest open-args)
  (let ((input (apply #'open (car open-args) :element-type '(unsigned-byte 8) (cdr open-args))))
    (unwind-protect
        (progn
          (funcall continuation (make-xstream input)))
      (close input))))

(defmacro with-open-xstream ((stream &rest open-args) &body body)
  `(call-with-open-xstream (lambda (,stream) .,body) .,open-args))

;;; Decoders

;; The decoders share a common signature:
;;
;; DECODE input input-start input-end
;;        output output-start output-end
;;        eof-p
;; -> first-not-written ; first-not-read
;;
;; These decode functions should decode as much characters off `input'
;; into the `output' as possible and return the indexes to the first
;; not read and first not written element of `input' and `output'
;; respectively.  If there are not enough bytes in `input' to decode a
;; full character, decoding shold be abandomed; the caller has to
;; ensure that the remaining bytes of `input' are passed to the
;; decoder again with more bytes appended. 
;;
;; `eof-p' now in turn indicates, if the given input sequence, is all
;; the producer does have and might be used to produce error messages
;; in case of incomplete codes or decided what to do.
;;
;; Decoders are expected to handle the various CR/NL conventions and
;; canonicalize each end of line into a single NL rune (#xA) in good
;; old Lisp tradition.
;;

;; TODO: change this to an encoding class, which then might carry
;; additional state. Stateless encodings could been represented by
;; keywords. e.g.
;;
;;  defmethod DECODE-SEQUENCE ((encoding (eql :utf-8)) ...)
;;

;;;; ---------------------------------------------------------------------------
;;;; rod hashtable
;;;;

;;; make-rod-hashtable
;;; rod-hash-get hashtable rod &optional start end -> value ; successp
;;; (setf (rod-hash-get hashtable rod &optional start end) new-value
;;; 

(defstruct (rod-hashtable (:constructor make-rod-hashtable/low))
  size          ;size of table
  table         ;
  )

(defun make-rod-hashtable (&key (size 200))
  (setf size (glisp::nearest-greater-prime size))
  (make-rod-hashtable/low
   :size size
   :table (make-array size :initial-element nil)))

(eval-when (compile eval load)
  (defconstant +fixnum-bits+
      (1- (integer-length most-positive-fixnum))
    "Pessimistic approximation of the number of bits of fixnums.")

  (defconstant +fixnum-mask+
      (1- (expt 2 +fixnum-bits+))
    "Pessimistic approximation of the largest bit-mask, still being a fixnum."))

(defsubst stir (a b)
  (%and +fixnum-mask+
        (%xor (%ior (%ash (%and a #.(ash +fixnum-mask+ -5)) 5)
                    (%ash a #.(- 5 +fixnum-bits+)))
              b)))

(defsubst rod-hash (rod start end)
  "Compute a hash code out of a rod."
  (let ((res (%- end start)))
    (do ((i start (%+ i 1)))
        ((%= i end))
      (declare (type fixnum i))
      (setf res (stir res (%rune rod i))))
    res))

(defsubst rod=* (x y &key (start1 0) (end1 (length x))
                          (start2 0) (end2 (length y)))
  (and (%= (%- end1 start1) (%- end2 start2))
       (do ((i start1 (%+ i 1))
            (j start2 (%+ j 1)))
           ((%= i end1)
            t)
         (unless (= (%rune x i) (%rune y j))
           (return nil)))))

(defsubst rod=** (x y start1 end1 start2 end2)
  (and (%= (%- end1 start1) (%- end2 start2))
       (do ((i start1 (%+ i 1))
            (j start2 (%+ j 1)))
           ((%= i end1)
            t)
         (unless (= (%rune x i) (%rune y j))
           (return nil)))))

(defun rod-hash-get (hashtable rod &optional (start 0) (end (length rod)))
  (declare (type (simple-array rune (*)) rod))
  (let ((j (%mod (rod-hash rod start end)
                 (rod-hashtable-size hashtable))))
    (dolist (q (svref (rod-hashtable-table hashtable) j)
               (values nil nil nil))
      (declare (type cons q))
      (when (rod=** (car q) rod 0 (length (the (simple-array rune (*)) (car q))) start end)
        (return (values (cdr q) t (car q)))))))

(defun rod-hash-set (new-value hashtable rod &optional (start 0) (end (length rod)))
  (let ((j (%mod (rod-hash rod start end)
                 (rod-hashtable-size hashtable)))
        (key nil))
    (dolist (q (svref (rod-hashtable-table hashtable) j)
              (progn
                (setf key (rod-subseq* rod start end))
                (push (cons key new-value)
                      (aref (rod-hashtable-table hashtable) j))))
      (when (rod=* (car q) rod :start2 start :end2 end)
        (setf key (car q))
        (setf (cdr q) new-value)
        (return)))
    (values new-value key)))

(defun rod-subseq* (source start &optional (end (length source)))
  (unless (and (typep start 'fixnum) (>= start 0))
    (error "~S is not a non-negative fixnum." start))
  (unless (and (typep end 'fixnum) (>= end start))
    (error "END argument, ~S, is not a fixnum no less than START, ~S." end start))
  (when (> start (length source))
    (error "START argument, ~S, should be no greater than length of rod." start))
  (when (> end (length source))
    (error "END argument, ~S, should be no greater than length of rod." end))
  (locally
      (declare (type fixnum start end))
    (let ((res (make-rod (- end start))))
      (declare (type rod res))
      (do ((i (- (- end start) 1) (the fixnum (- i 1))))
          ((< i 0) res)
        (declare (type fixnum i))
        (setf (%rune res i) (aref source (the fixnum (+ i start))))))))

(deftype ufixnum () `(unsigned-byte ,(integer-length most-positive-fixnum)))

(defun rod-subseq** (source start &optional (end (length source)))
  (declare (type (simple-array rune (*)) source)
           (type ufixnum start)
           (type ufixnum end)
           (optimize (speed 3) (safety 0)))
  (let ((res (make-array (%- end start) :element-type 'rune)))
    (declare (type (simple-array rune (*)) res))
    (let ((i (%- end start)))
      (declare (type ufixnum i))
      (loop
        (setf i (- i 1))
        (when (= i 0)
          (return))
        (setf (%rune res i) (%rune source (the ufixnum (+ i start))))))
    res))

(defun (setf rod-hash-get) (new-value hashtable rod &optional (start 0) (end (length rod)))
  (rod-hash-set new-value hashtable rod start end))

(defparameter *name-hashtable* (make-rod-hashtable :size 2000))

(defun intern-name (rod &optional (start 0) (end (length rod)))
  (multiple-value-bind (value successp key) (rod-hash-get *name-hashtable* rod start end)
    (declare (ignore value))
    (if successp
        key
      (nth-value 1 (rod-hash-set t *name-hashtable* rod start end)))))

;;;; ---------------------------------------------------------------------------
;;;;
;;;;  rod collector
;;;;

(defparameter *scratch-pad*
    (make-array 1024 :element-type 'rune))

(defparameter *scratch-pad-2*
    (make-array 1024 :element-type 'rune))

(defparameter *scratch-pad-3*
    (make-array 1024 :element-type 'rune))

(defparameter *scratch-pad-4*
    (make-array 1024 :element-type 'rune))

(declaim (type (simple-array rune (*))
               *scratch-pad* *scratch-pad-2* *scratch-pad-3* *scratch-pad-4*))

(defmacro %put-rune (rune-var put)
  `(progn
     (cond ((%> ,rune-var #xFFFF)
          (,put (the (unsigned-byte 16) (%+ #xD7C0 (ash ,rune-var -10))))
          (,put (the (unsigned-byte 16) (%ior #xDC00 (%and ,rune-var #x3FF)))))
         (t
          (,put ,rune-var)))))

(defun adjust-array-by-copying (old-array new-size)
  "Adjust an array by copying and thus ensures, that result is a SIMPLE-ARRAY."
  (let ((res (make-array new-size :element-type (array-element-type old-array))))
    (replace res old-array
             :start1 0 :end1 (length old-array)
             :start2 0 :end2 (length old-array))
    res))

(defmacro with-rune-collector-aux (scratch collect body mode)
  (let ((rod (gensym))
        (n (gensym))
        (i (gensym))
        (b (gensym)))
    `(let ((,n (length ,scratch))
           (,i 0)
           (,b ,scratch))
       (declare (type fixnum ,n ,i))
       (macrolet 
           ((,collect (x) 
              `((lambda (x)
                  (locally
                      (declare #.*fast*)
                    (when (%>= ,',i ,',n)
                      (setf ,',n (* 2 ,',n))
                      (setf ,',b
                            (setf ,',scratch
                                  (adjust-array-by-copying ,',scratch ,',n))))
                    (setf (aref (the (simple-array rune (*)) ,',b) ,',i) x)
                    (incf ,',i)))
                ,x)))
         ,@body
         ,(ecase mode
            (:intern
             `(intern-name ,b 0 ,i))
            (:copy
             `(let ((,rod (make-rod ,i)))
                (while (not (%= ,i 0))
                       (setf ,i (%- ,i 1))
                       (setf (%rune ,rod ,i) 
                         (aref (the (simple-array rune (*)) ,b) ,i)))
                ,rod))
            (:raw
             `(values ,b 0 ,i))
            )))))

'(defmacro with-rune-collector-aux (scratch collect body mode)
  (let ((rod (gensym))
        (n (gensym))
        (i (gensym))
        (b (gensym)))
    `(let ((,n (length ,scratch))
           (,i 0))
       (declare (type fixnum ,n ,i))
       (macrolet 
           ((,collect (x) 
              `((lambda (x)
                  (locally
                      (declare #.*fast*)
                    (when (%>= ,',i ,',n)
                      (setf ,',n (* 2 ,',n))
                      (setf ,',scratch
                            (setf ,',scratch
                                  (adjust-array-by-copying ,',scratch ,',n))))
                    (setf (aref (the (simple-array rune (*)) ,',scratch) ,',i) x)
                    (incf ,',i)))
                ,x)))
         ,@body
         ,(ecase mode
            (:intern
             `(intern-name ,scratch 0 ,i))
            (:copy
             `(let ((,rod (make-rod ,i)))
                (while (%> ,i 0)
                       (setf ,i (%- ,i 1))
                       (setf (%rune ,rod ,i) 
                         (aref (the (simple-array rune (*)) ,scratch) ,i)))
                ,rod))
            (:raw
             `(values ,scratch 0 ,i))
            )))))

(defmacro with-rune-collector ((collect) &body body)
  `(with-rune-collector-aux *scratch-pad* ,collect ,body :copy))

(defmacro with-rune-collector-2 ((collect) &body body)
  `(with-rune-collector-aux *scratch-pad-2* ,collect ,body :copy))

(defmacro with-rune-collector-3 ((collect) &body body)
  `(with-rune-collector-aux *scratch-pad-3* ,collect ,body :copy))

(defmacro with-rune-collector-4 ((collect) &body body)
  `(with-rune-collector-aux *scratch-pad-4* ,collect ,body :copy))

(defmacro with-rune-collector/intern ((collect) &body body)
  `(with-rune-collector-aux *scratch-pad* ,collect ,body :intern))

(defmacro with-rune-collector/raw ((collect) &body body)
  `(with-rune-collector-aux *scratch-pad* ,collect ,body :raw))

#|
(defmacro while-reading-runes ((reader stream-in) &rest body)
  ;; Thou shalt not leave body via a non local exit
  (let ((stream (make-symbol "STREAM"))
        (rptr (make-symbol "RPTR"))
        (fptr (make-symbol "FPTR"))
        (buf  (make-symbol "BUF")) )
    `(let* ((,stream ,stream-in)
            (,rptr (xstream-read-ptr ,stream))
            (,fptr (xstream-fill-ptr ,stream))
            (,buf  (xstream-buffer ,stream)))
       (declare (type fixnum ,rptr ,fptr)
                (type xstream ,stream))
       (macrolet ((,reader (res-var)
                    `(cond ((%= ,',rptr ,',fptr)
                            (setf (xstream-read-ptr ,',stream) ,',rptr)
                            (setf ,res-var (xstream-underflow ,',stream))
                            (setf ,',rptr (xstream-read-ptr ,',stream))
                            (setf ,',fptr (xstream-fill-ptr ,',stream))
                            (setf ,',buf  (xstream-buffer ,',stream)))
                           (t
                            (setf ,res-var
                              (aref (the (simple-array read-element (*)) ,',buf)
                                    (the fixnum ,',rptr)))
                            (setf ,',rptr (%+ ,',rptr 1))))))
         (prog1
             (let () .,body)
           (setf (xstream-read-ptr ,stream) ,rptr) )))))
|#

;;;;  ---------------------------------------------------------------------------
;;;;  DTD
;;;;

(defparameter *entities* nil)
(defvar *dtd*)

(defun absolute-uri (sysid source-stream)
  (setq sysid (rod-string sysid))
  (let ((base-sysid
         (dolist (k (zstream-input-stack source-stream))
           (let ((base-sysid (stream-name-file-name (xstream-name k))))
             (when base-sysid (return base-sysid))))))
    (assert (not (null base-sysid)))
    (merge-sysid sysid base-sysid)))

(defun absolute-extid (source-stream extid)
  (case (car extid)
david's avatar
david committed
597
    (:SYSTEM
david's avatar
david committed
598 599
     (list (car extid)
           (absolute-uri (cadr extid) source-stream)))
david's avatar
david committed
600
    (:PUBLIC
david's avatar
david committed
601 602 603 604 605
     (list (car extid)
           (cadr extid)
           (absolute-uri (caddr extid) source-stream)))))

(defun define-entity (source-stream name kind def)
david's avatar
david committed
606
  (when (eq (car def) :EXTERNAL)
david's avatar
david committed
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
    (setf def
      (list (car def) (absolute-extid source-stream (cadr def)))))
  (setf name (intern-name name))
  (setf *entities*
    (append *entities*
            (list (cons (list kind name)
                        def)))))

#||
(defun define-element (zinput dtd element-name content-model)
  ;; zinput is for source code location recoding
  (let ((elmdef (make-elmdef :name element-name
                             :content content-model
                             )))
    ()))
||#

(defun entity->xstream (entity-name kind &optional zstream)
  ;; `zstream' is for error messages
david's avatar
david committed
626
  (let ((looked (assoc (list kind entity-name) *entities* :test #'equalp)))
david's avatar
david committed
627 628 629 630 631 632
    (unless looked
      (if zstream 
          (perror zstream "Entity '~A' is not defined." (rod-string entity-name))
        (error "Entity '~A' is not defined." (rod-string entity-name))))
    (let (r)
      (ecase (cadr looked)
david's avatar
david committed
633
        (:INTERNAL 
david's avatar
david committed
634 635 636 637 638
         (setf r (make-rod-xstream (caddr looked)))
         (setf (xstream-name r)
           (make-stream-name :entity-name entity-name
                             :entity-kind kind
                             :file-name nil)))
david's avatar
david committed
639
        (:EXTERNAL
david's avatar
david committed
640 641 642 643 644 645
         (setf r (open-extid (caddr looked)))
         (setf (stream-name-entity-name (xstream-name r)) entity-name
               (stream-name-entity-kind (xstream-name r)) kind)))
      r)))

(defun entity-source-kind (name type)
david's avatar
david committed
646
  (let ((looked (assoc (list type name) *entities* :test #'equalp)))
david's avatar
david committed
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    (unless looked
      (error "Entity '~A' is not defined." (rod-string name)))
    (cadr looked)))

(defun open-extid (extid)
  (let ((nam (ecase (car extid)
               (:SYSTEM (cadr extid))
               (:PUBLIC (caddr extid)))))
    (make-xstream (open-sysid nam)
                  :name (make-stream-name :file-name nam)
                  :initial-speed 1)))

(defun call-with-entity-expansion-as-stream (zstream cont name kind)
  ;; `zstream' is for error messages -- we need something better!
  (let ((in (entity->xstream name kind zstream)))
    (unwind-protect
        (funcall cont in)
      (close-xstream in))))

(defun define-default-entities ()
david's avatar
david committed
667 668 669 670 671
  (define-entity nil '#.(string-rod "lt")   :general `(:INTERNAL #.(string-rod "&#60;")))
  (define-entity nil '#.(string-rod "gt")   :general `(:INTERNAL #.(string-rod ">")))
  (define-entity nil '#.(string-rod "amp")  :general `(:INTERNAL #.(string-rod "&#38;")))
  (define-entity nil '#.(string-rod "apos") :general `(:INTERNAL #.(string-rod "'")))
  (define-entity nil '#.(string-rod "quot") :general `(:INTERNAL #.(string-rod "\"")))
david's avatar
david committed
672 673
  ;;
  #||
david's avatar
david committed
674 675 676 677 678 679 680
  (define-entity nil '#.(string-rod "ouml") :general `(:INTERNAL #.(string-rod "ö")))
  (define-entity nil '#.(string-rod "uuml") :general `(:INTERNAL #.(string-rod "ü")))
  (define-entity nil '#.(string-rod "auml") :general `(:INTERNAL #.(string-rod "ä")))
  (define-entity nil '#.(string-rod "Ouml") :general `(:INTERNAL #.(string-rod "Ö")))
  (define-entity nil '#.(string-rod "Auml") :general `(:INTERNAL #.(string-rod "Ä")))
  (define-entity nil '#.(string-rod "Uuml") :general `(:INTERNAL #.(string-rod "Ü")))
  (define-entity nil '#.(string-rod "szlig") :general `(:INTERNAL #.(string-rod "ß")))
david's avatar
david committed
681 682 683 684
  ||#
  ;;
  #||
  (define-entity nil '#.(string-rod "nbsp") 
david's avatar
david committed
685
    :general `(:INTERNAL ,(let ((r (make-rod 1)))
david's avatar
david committed
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
                            (setf (aref r 0) #o240)
                            r)))
  ||#
  )

(defstruct attdef
  ;; an attribute definition
  element       ;name of element this attribute belongs to
  name          ;name of attribute
  type          ;type of attribute; either one of :CDATA, :ID, :IDREF, :IDREFS,
                ; :ENTITY, :ENTITIES, :NMTOKEN, :NMTOKENS, or
                ; (:NOTATION <name>*)
                ; (:ENUMERATION <name>*)
  default)      ;default value of attribute:
                ; :REQUIRED, :IMPLIED, (:FIXED content) or (:DEFAULT content)

(defstruct elmdef
  ;; an element definition
  name          ;name of the element
  content       ;content model
  attributes    ;list of defined attribtes
  defined-p)    ;is this element defined? [*]

;; [*] in XML it is possible to define attributes, before the element
;; itself is defined and since we hang attribute definitions into the
;; relevant element definitions, this flag indicates, whether an
;; element was actually defined.

(defstruct dtd
  elements      ;hashtable or whatnot of all elements
  attdefs       ;
  gentities     ;general entities
  pentities     ;parameter entities
  )

;;;;

david's avatar
david committed
723 724
(defvar *redefinition-warning* t)

david's avatar
david committed
725 726 727 728 729 730
(defun define-attribute (dtd element name type default)
  (let ((adef (make-attdef :element element
                           :name name
                           :type type
                           :default default)))
    (cond ((find-attribute dtd element name)
david's avatar
david committed
731 732 733 734
           (when *redefinition-warning*
             (warn "Attribute \"~A\" of \"~A\" not redefined."
                   (rod-string name)
                   (rod-string element))))
david's avatar
david committed
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
          (t
           (push adef (dtd-attdefs dtd))))))

(defun find-attribute (dtd element name)
  (dolist (k (dtd-attdefs dtd))
    (cond ((and (eq element (attdef-element k))
                (eq name (attdef-name k)))
           (return k)))))

(defun map-all-attdefs-for-element (dtd element continuation)
  (declare (dynamic-extent continuation));this does not help under ACL
  (dolist (k (dtd-attdefs dtd))
    (cond ((eq element (attdef-element k))
           (funcall continuation k)))))

;;;; ---------------------------------------------------------------------------
;;;;  z streams and lexer
;;;;

(defstruct zstream
  token-category
  token-semantic
  input-stack)

(defun read-token (input)
  (cond ((zstream-token-category input)
         (multiple-value-prog1
             (values (zstream-token-category input)
                     (zstream-token-semantic input))
           (setf (zstream-token-category input) nil
                 (zstream-token-semantic input) nil)))
        (t
         (read-token-2 input))))

(defun peek-token (input)
  (cond ((zstream-token-category input)
         (values 
          (zstream-token-category input)
          (zstream-token-semantic input)))
        (t
         (multiple-value-bind (c s) (read-token input)
           (setf (zstream-token-category input) c
                 (zstream-token-semantic input) s))
         (values (zstream-token-category input)
                 (zstream-token-semantic input)))))

(defun read-token-2 (input)
  (cond ((null (zstream-input-stack input))
         (values :eof nil))
        (t
         (let ((c (peek-rune (car (zstream-input-stack input)))))
           (cond ((eq c :eof)
                  (cond ((eq (cadr (zstream-input-stack input)) :stop)
                         (values :eof nil))
                        (t
                         (close-xstream (pop (zstream-input-stack input)))
                         (if (null (zstream-input-stack input))
                             (values :eof nil)
                           (values :S nil) ;fake #x20 after PE expansion
                           ))))
                 (t
                  (read-token-3 input)))))))

(defvar *data-behaviour*
    )           ;either :DTD or :DOC

(defun read-token-3 (zinput)
  (let ((input (car (zstream-input-stack zinput))))
    ;; PI Comment
    (let ((c (read-rune input)))
      (cond
       ;; first the common tokens
       ((rune= #/< c)
        (read-token-after-|<| zinput input))
       ;; now dispatch
       (t
        (ecase *data-behaviour*
          (:DTD
           (cond ((rune= #/\[ c) :\[)
                 ((rune= #/\] c) :\])
                 ((rune= #/\( c) :\()
                 ((rune= #/\) c) :\))
                 ((rune= #/\| c) :\|)
                 ((rune= #/\> c) :\>)
                 ((rune= #/\" c) :\")
                 ((rune= #/\' c) :\')
                 ((rune= #/\, c) :\,)
                 ((rune= #/\? c) :\?)
                 ((rune= #/\* c) :\*)
                 ((rune= #/\+ c) :\+)
                 ((name-rune-p c)
                  (unread-rune c input)
                  (values :name (read-name-token input)))
                 ((rune= #/# c)
                  (let ((q (read-name-token input)))
                    (cond ((equalp q '#.(string-rod "REQUIRED")) :|#REQUIRED|)
                          ((equalp q '#.(string-rod "IMPLIED")) :|#IMPLIED|)
                          ((equalp q '#.(string-rod "FIXED"))   :|#FIXED|)
                          ((equalp q '#.(string-rod "PCDATA"))  :|#PCDATA|)
                          (t
                           (error "Unknown token: ~S." q)))))
                 ((or (rune= c #/U+0020)
                      (rune= c #/U+0009)
                      (rune= c #/U+000D)
                      (rune= c #/U+000A))
david's avatar
david committed
840
                  (values :S nil))
david's avatar
david committed
841 842 843 844 845 846 847 848 849 850 851 852
                 ((rune= #/% c)
                  (cond ((name-start-rune-p (peek-rune input))
                         ;; an entity reference
                         (read-pe-reference zinput))
                        (t
                         (values :%))))
                 (t
                  (error "Unexpected character ~S." c))))
          (:DOC
           (cond 
            ((rune= c #/&)
             (multiple-value-bind (kind data) (read-entity-ref input)
david's avatar
david committed
853 854 855 856
               (cond ((eq kind :NAMED)
                      (values :ENTITY-REF data) )
                     ((eq kind :NUMERIC)
                      (values :CDATA
david's avatar
david committed
857 858 859 860
                              (with-rune-collector (collect)
                                (%put-rune data collect)))))))
            (t
             (unread-rune c input)
david's avatar
david committed
861
             (values :CDATA (read-cdata input))) ))))))))
david's avatar
david committed
862 863 864 865 866 867 868 869 870 871 872 873

(defun read-pe-reference (zinput)
  (let* ((input (car (zstream-input-stack zinput)))
         (nam (read-name-token input)))
    (assert (rune= #/\; (read-rune input)))
    (cond (*expand-pe-p*
           ;; no external entities here!
           (let ((i2 (entity->xstream nam :parameter)))
             (zstream-push i2 zinput))
           (values :S nil) ;space before inserted PE expansion.
           )
          (t
david's avatar
david committed
874
           (values :PE-REFERENCE nam)) )))
david's avatar
david committed
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891

(defun read-token-after-|<| (zinput input)
  (let ((d (read-rune input)))
    (cond ((eq d :eof)
           (error "EOF after '<'"))
          ((rune= #/! d)
           (read-token-after-|<!| input))
          ((rune= #/? d)
           (multiple-value-bind (target content) (read-pi input)
             (cond ((rod= target '#.(string-rod "xml"))
                    (values :xml-pi (cons target content)))
                   ((rod-equal target '#.(string-rod "XML"))
                    (error "You lost -- no XML processing instructions."))
		   ((and sax:*namespace-processing* (position #/: target))
		    (error "Processing instruction target ~S is not a valid NcName."
			   (mu target)))
                   (t
david's avatar
david committed
892
                    (values :PI (cons target content))))))
david's avatar
david committed
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
          ((rune= #// d)
           (let ((c (peek-rune input)))
             (cond ((name-start-rune-p c)
                    (read-tag-2 zinput input :etag))
                   (t
                    (error "Expecting name start rune after \"</\".")))))
          ((name-start-rune-p d)
           (unread-rune d input)
           (read-tag-2 zinput input :stag))
          (t
           (error "Expected '!' or '?' after '<' in DTD.")))))

(defun read-token-after-|<!| (input)
  (let ((d (read-rune input)))
    (cond ((eq d :eof)
           (error "EOF after \"<!\"."))
          ((name-start-rune-p d)
           (unread-rune d input)
           (let ((name (read-name-token input)))
             (cond ((rod= name '#.(string-rod "ELEMENT")) :|<!ELEMENT|)
                   ((rod= name '#.(string-rod "ENTITY")) :|<!ENTITY|)
                   ((rod= name '#.(string-rod "ATTLIST")) :|<!ATTLIST|)
                   ((rod= name '#.(string-rod "NOTATION")) :|<!NOTATION|)
                   ((rod= name '#.(string-rod "DOCTYPE")) :|<!DOCTYPE|)
                   (t
                    (error "`<!~A' unknown." (rod-string name))))))
          ((rune= #/\[ d)
           (values :|<![| nil))
          ((rune= #/- d)
           (setf d (read-rune input))
           (cond ((rune= #/- d)
                  (values
                   :COMMENT
                   (read-comment-content input)))
                 (t
                  (error "Bad character ~S after \"<!-\"" d))))
          (t
           (error "Bad character ~S after \"<!\"" d)))))

(defun read-attribute-list (zinput input imagine-space-p)
  (cond ((or imagine-space-p
             (let ((c (peek-rune input)))
               (and (not (eq c :eof))
                    (space-rune-p c))))
david's avatar
david committed
937
         (read-s? input)
david's avatar
david committed
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
         (cond ((eq (peek-rune input) :eof)
                nil)
               ((name-start-rune-p (peek-rune input))
                (cons (read-attribute zinput input)
                      (read-attribute-list zinput input nil)))
               (t
                nil)))
        (t
         nil)))

(defun read-entity-ref (input)
  "Read an entity reference off the xstream `input'. Returns two values:
   either :NAMED <interned-rod> in case of a named entity
   or     :NUMERIC <integer> in case of numeric entities.
   The initial #\\& is considered to be consumed already."
  (let ((c (peek-rune input)))
    (cond ((eq c :eof)
           (error "EOF after '&'"))
          ((rune= c #/#)
david's avatar
david committed
957
           (values :NUMERIC (read-numeric-entity input)))
david's avatar
david committed
958 959 960 961 962 963 964
          (t
           (unless (name-start-rune-p (peek-rune input))
             (error "Expecting name after &."))
           (let ((name (read-name-token input)))
             (setf c (read-rune input))
             (unless (rune= c #/\;)
               (perror input "Expected \";\"."))
david's avatar
david committed
965
             (values :NAMED name))))))
david's avatar
david committed
966

david's avatar
david committed
967
(defsubst read-s? (input)
david's avatar
david committed
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
  (while (member (peek-rune input) '(#/U+0020 #/U+0009 #/U+000A #/U+000D)
                 :test #'eq)
    (consume-rune input)))

(defun read-tag-2 (zinput input kind)
  (let ((name (read-name-token input))
        (atts nil))
    (setf atts (read-attribute-list zinput input nil))
    ;;(setf atts (nreverse atts))
    ;; care for atts
    ;;
    ;;zzz
    (let ((fn (lambda (adef &aux x)
                 (setf x (assoc (attdef-name adef) atts))
       
                 (when (and (consp (attdef-default adef))
                            (eq (car (attdef-default adef)) :default)
                            (not x))
                   (setf atts (cons (setf x (cons (attdef-name adef) (cadr (attdef-default adef))))
                                    atts)))
                 (when (and (consp (attdef-default adef))
                            (eq (car (attdef-default adef)) :fixed)
                            (not x))
                   (setf atts (cons (setf x (cons (attdef-name adef) (cadr (attdef-default adef))))
                                    atts)))
david's avatar
david committed
993
                 (unless (eq (attdef-type adef) :CDATA)
david's avatar
david committed
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
                   (when x
                     (setf (cdr x) (canon-not-cdata-attval (cdr x)))))
       
                 ;; xxx more tests
                 )))
       (declare (dynamic-extent fn))
       (map-all-attdefs-for-element 
        *dtd* name fn))

    ;; check for double attributes
    (do ((q atts (cdr q)))
        ((null q))
      (cond ((find (caar q) (cdr q) :key #'car)
             (error "Attribute ~S has two definitions in element ~S."
                    (rod-string (caar q))
                    (rod-string name)))))

    (cond ((eq (peek-rune input) #/>)
           (consume-rune input)
           (values kind (cons name atts)))
          ((eq (peek-rune input) #//)
           (consume-rune input)
           (assert (rune= #/> (read-rune input)))
           (values :ztag (cons name atts)))
          (t
           (error "syntax error in read-tag-2.")) )))

(defun read-attribute (zinput input)
  (unless (name-start-rune-p (peek-rune input))
    (error "Expected name."))
  ;; arg thanks to the post mortem nature of name space declarations,
  ;; we could only process the attribute values post mortem.
  (let ((name (read-name-token input)))
    (while (let ((c (peek-rune input)))
             (and (not (eq c :eof))
                  (or (= c #/U+0020)
                      (= c #/U+0009)
                      (= c #/U+000A)
                      (= c #/U+000D))))
      (consume-rune input))
    (unless (eq (read-rune input) #/=)
      (perror zinput "Expected \"=\"."))
    (while (let ((c (peek-rune input)))
             (and (not (eq c :eof))
                  (or (= c #/U+0020)
                      (= c #/U+0009)
                      (= c #/U+000A)
                      (= c #/U+000D))))
      (consume-rune input))
    (cons name (read-att-value-2 input))
david's avatar
david committed
1044
    ;;(cons name (read-att-value zinput input :ATT t))
david's avatar
david committed
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    ))

(defun canon-not-cdata-attval (value)
  ;; | If the declared value is not CDATA, then the XML processor must
  ;; | further process the normalized attribute value by discarding any
  ;; | leading and trailing space (#x20) characters, and by replacing
  ;; | sequences of space (#x20) characters by a single space (#x20)
  ;; | character.
  (with-rune-collector (collect)
    (let ((gimme-20 nil)
          (anything-seen-p nil))
      (map nil (lambda (c)
                 (cond ((= c #x20)
                        (setf gimme-20 t))
                       (t
                        (when (and anything-seen-p gimme-20)
                          (collect #x20))
                        (setf gimme-20 nil)
                        (setf anything-seen-p t)
                        (collect c))))
           value))))

#||
(defun canon-not-cdata-attval (value)
  ;; | If the declared value is not CDATA, then the XML processor must
  ;; | further process the normalized attribute value by discarding any
  ;; | leading and trailing space (#x20) characters, and by replacing
  ;; | sequences of space (#x20) characters by a single space (#x20)
  ;; | character.
  value)
||#

(defsubst data-rune-p (c)
  ;; any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
  (or (= c #x9) (= c #xA) (= c #xD)
      (<= #x20 c #xD7FF)
      (<= #xE000 c #xFFFD)
      ;;
      (<= #xD800 c #xDBFF)
      (<= #xDC00 c #xDFFF)
      ;;
      ))

#||
(defsubst data-rune-p (c)
  t)
||#

(defun read-att-value (zinput input mode &optional canon-space-p (delim nil))
  (with-rune-collector-2 (collect)
    (labels ((muffle (input delim)
               (let (c)
                 (loop
                   (setf c (read-rune input))
                   (cond ((eql delim c)
                          (return))
                         ((eq c :eof)
                          (error "EOF"))
                         ((rune= c #/&)
                          (setf c (peek-rune input))
                          (cond ((rune= c #/#)
                                 (let ((c (read-numeric-entity input)))
                                   (%put-rune c collect)))
                                (t
                                 (unless (name-start-rune-p (peek-rune input))
                                   (error "Expecting name after &."))
                                 (let ((name (read-name-token input)))
                                   (setf c (read-rune input))
                                   (assert (rune= c #/\;))
                                   (ecase mode
david's avatar
david committed
1115
                                     (:ATT
david's avatar
david committed
1116 1117 1118 1119 1120
                                      (recurse-on-entity 
                                       zinput name :general
                                       (lambda (zinput)
                                         (muffle (car (zstream-input-stack zinput))
                                                 :eof))))
david's avatar
david committed
1121
                                     (:ENT
david's avatar
david committed
1122 1123 1124 1125 1126 1127 1128 1129
                                      ;; bypass, but never the less we
                                      ;; need to check for legal
                                      ;; syntax.
                                      ;; Must it be defined?
                                      ;; allerdings: unparsed sind verboten
                                      (collect #/&)
                                      (map nil (lambda (x) (collect x)) name)
                                      (collect #/\; )))))))
david's avatar
david committed
1130
                         ((and (eq mode :ENT) (rune= c #/%))
david's avatar
david committed
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
                          (unless (name-start-rune-p (peek-rune input))
                            (error "Expecting name after %."))
                          (let ((name (read-name-token input)))
                            (setf c (read-rune input))
                            (assert (rune= c #/\;))
                            (cond (*expand-pe-p*
                                   (recurse-on-entity 
                                    zinput name :parameter
                                    (lambda (zinput)
                                      (muffle (car (zstream-input-stack zinput))
                                              :eof))))
                                  (t
                                   (error "No PE here.")))))
david's avatar
david committed
1144
                         ((and (eq mode :ATT) (rune= c #/<))
david's avatar
david committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
                          ;; xxx fix error message
                          (cerror "Eat them in spite of this."
                                  "For no apparent reason #\/< is forbidden in attribute values. ~
                           You lost -- next time choose SEXPR syntax.")
                          (collect c))
                         ((and canon-space-p (space-rune-p c))
                          (collect #/space))
                         ((not (data-rune-p c))
                          (error "illegal char: ~S." c))
                         (t
                          (collect c)))))))
      (declare (dynamic-extent #'muffle))
      (muffle input (or delim
                        (let ((delim (read-rune input)))
                          (assert (member delim '(#/\" #/\')))
                          delim))))))

(defun read-numeric-entity (input)
  ;; xxx eof handling
  ;; The #/& is already read
  (let ((res
         (let ((c (read-rune input)))
           (assert (rune= c #/#))
           (setq c (read-rune input))
           (cond ((rune= c #/x)
                  ;; hexadecimal
                  (setq c (read-rune input))
                  (assert (digit-rune-p c 16))
                  (prog1
                      (parse-integer
                       (with-output-to-string (sink)
                         (write-char (code-char c) sink)
                         (while (digit-rune-p (setq c (read-rune input)) 16)
                                (write-char (code-char c) sink)))
                       :radix 16)
                    (assert (rune= c #/\;)))
                  )
                 ((<= #/0 c #/9)
                  ;; decimal
                  (prog1
                      (parse-integer
                       (with-output-to-string (sink)
                         (write-char (code-char c) sink)
                         (while (<= #/0 (setq c (read-rune input)) #/9)
                                (write-char (code-char c) sink)))
                       :radix 10)
                    (assert (rune= c #/\;))) )
                 (t
                  (error "Bad char in numeric character entity.") )))))
    (unless (data-char-p res)
      (error "expansion of numeric character reference (#x~X) is no data char."
             res))
    res))

(defun read-pi (input)
  ;; "<?" is already read
  (let (name)
    (let ((c (peek-rune input)))
      (unless (name-start-rune-p c)
        (error "Expecting name after '<?'"))
      (setf name (read-name-token input)))
    (values name
            (read-pi-content input))))

(defun read-pi-content (input &aux d)
  (read-s? input)
  (with-rune-collector (collect)
    (block nil
      (tagbody
       state-1
        (setf d (read-rune input))
        (unless (data-rune-p d)
          (error "Illegal char: ~S." d))
        (when (rune= d #/?) (go state-2))
        (collect d)
        (go state-1)
       state-2 ;; #/? seen
        (setf d (read-rune input))
        (unless (data-rune-p d)
          (error "Illegal char: ~S." d))
        (when (rune= d #/>) (return))
        (when (rune= d #/?) 
          (collect #/?) 
          (go state-2))
        (collect #/?)
        (collect d)
        (go state-1)))))

(defun read-comment-content (input &aux d)
  (let ((warnedp nil))
    (with-rune-collector (collect)
      (block nil
        (tagbody
         state-1
          (setf d (read-rune input))
          (unless (data-rune-p d)
            (error "Illegal char: ~S." d))
          (when (rune= d #/-) (go state-2))
          (collect d)
          (go state-1)
         state-2 ;; #/- seen
          (setf d (read-rune input))
          (unless (data-rune-p d)
            (error "Illegal char: ~S." d))
          (when (rune= d #/-) (go state-3))
          (collect #/-)
          (collect d)
          (go state-1)
         state-3 ;; #/- #/- seen
          (setf d (read-rune input))
          (unless (data-rune-p d)
            (error "Illegal char: ~S." d))
          (when (rune= d #/>) (return))
          (unless warnedp
            (warn "WFC: no '--' in comments please.")
            (setf warnedp t))
          (when (rune= d #/-)
            (collect #/-)
            (go state-3))
          (collect #/-)
          (collect #/-)
          (collect d)
          (go state-1))))))

(defun read-cdata-sect (input &aux d)
  ;; <![CDATA[ is already read
  ;; read anything up to ]]>
  (with-rune-collector (collect)
    (block nil
      (tagbody
       state-1
        (setf d (read-rune input))
        (unless (data-rune-p d)
          (error "Illegal char: ~S." d))
        (when (rune= d #/\]) (go state-2))
        (collect d)
        (go state-1)
       state-2 ;; #/] seen
        (setf d (read-rune input))
        (unless (data-rune-p d)
          (error "Illegal char: ~S." d))
        (when (rune= d #/\]) (go state-3))
        (collect #/\])
        (collect d)
        (go state-1)
       state-3 ;; #/\] #/\] seen
        (setf d (read-rune input))
        (unless (data-rune-p d)
          (error "Illegal char: ~S." d))
        (when (rune= d #/>)
          (return))
        (when (rune= d #/\])
          (collect #/\])
          (go state-3))
        (collect #/\])
        (collect #/\])
        (collect d)
        (go state-1)))))

#+(or) ;; FIXME: There is another definition below that looks more reasonable.
(defun read-cdata (input initial-char &aux d)
  (cond ((not (data-rune-p initial-char))
         (error "Illegal char: ~S." initial-char)))
  (with-rune-collector (collect)
    (block nil
      (tagbody
        (cond ((rune= initial-char #/\])
               (go state-2))
              (t
               (collect initial-char)))
       state-1
        (setf d (peek-rune input))
        (when (or (eq d :eof) (rune= d #/<) (rune= d #/&))
          (return))
        (read-rune input)
        (unless (data-rune-p d)
          (error "Illegal char: ~S." d))
        (when (rune= d #/\]) (go state-2))
        (collect d)
        (go state-1)
        
       state-2 ;; #/\] seen
        (setf d (peek-rune input))
        (when (or (eq d :eof) (rune= d #/<) (rune= d #/&))
          (collect #/\])
          (return))
        (read-rune input)
        (unless (data-rune-p d)
          (error "Illegal char: ~S." d))
        (when (rune= d #/\]) (go state-3))
        (collect #/\])
        (collect d)
        (go state-1)
        
       state-3 ;; #/\] #/\] seen
        (setf d (peek-rune input))
        (when (or (eq d :eof) (rune= d #/<) (rune= d #/&))
          (collect #/\])
          (collect #/\])
          (return))
        (read-rune input)
        (unless (data-rune-p d)
          (error "Illegal char: ~S." d))
        (when (rune= d #/>) 
          (error "For no apparent reason ']]>' in not allowed in a CharData token -- you lost."))
        (when (rune= d #/\])
          (collect #/\])
          (go state-3))
        (collect #/\])
        (collect #/\])
        (collect d)
        (go state-1)))))


;; some character categories

#||
(defun name-start-rune-p (rune)
  (or (<= #x0041 rune #x005A)
      (<= #x0061 rune #x007A)
      ;; lots more
      (>= rune #x0080)
      (rune= rune #/_)
      (rune= rune #/:)))

(defun name-rune-p (rune)
  (or (name-start-rune-p rune)
      (rune= rune #/.)
      (rune= rune #/-)
      (rune<= #/0 rune #/9)))
||#

(defun space-rune-p (rune)
  (declare (type rune rune))
  (or (rune= rune #/U+0020)
      (rune= rune #/U+0009)
      (rune= rune #/U+000A)
      (rune= rune #/U+000D)))

(defun data-char-p (c)
  ;; any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
  (or (= c #x9) (= c #xA) (= c #xD)
      (<= #x20 c #xD7FF)
      (<= #xE000 c #xFFFD)
      (<= #x10000 c #x10FFFF)))

(defun pubid-char-p (c)
  (or (= c #x20) (= c #xD) (= c #xA)
      (<= #/a c #/z)
      (<= #/A c #/Z)
      (<= #/0 c #/9)
      (member c '(#/- #/' #/\( #/\) #/+ #/, #/. #//
                  #/: #/= #/? #/\; #/! #/* #/#
                  #/@ #/$ #/_ #/%))))


(defun expect (input category)
  (multiple-value-bind (cat sem) (read-token input)
    (unless (eq cat category)
      (error "Expected ~S saw ~S [~S]" category cat sem))
    (values cat sem)))

(defun consume-token (input)
  (read-token input))

;;;; ---------------------------------------------------------------------------
;;;;  Parser
;;;;

(defun p/S (input)
  ;; S ::= (#x20 | #x9 | #xD | #xA)+
  (expect input :S)
  (while (eq (peek-token input) :S)
    (consume-token input)))

(defun p/S? (input)
  ;; S ::= (#x20 | #x9 | #xD | #xA)+
  (while (eq (peek-token input) :S)
    (consume-token input)))

(defun p/name (input)
  (nth-value 1 (expect input :name)))

(defun p/attlist-decl (input)
  ;; [52] AttlistDecl ::= '<!ATTLIST' S Name (S AttDef)* S? '>'
  (let (elm-name)
    (expect input :|<!ATTLIST|)
    (p/S input)
    (setf elm-name (p/name input))
    (loop
      (let ((tok (read-token input)))
        (case tok
          (:S
           (p/S? input)
           (cond ((eq (peek-token input) :>)
                  (consume-token input)
                  (return))
                 (t
                  (multiple-value-bind (name type default) (p/attdef input)
                    (define-attribute *dtd* elm-name name type default)) )))
          (:>
           (return))
          (otherwise
           (error "Expected either another AttDef or end of \"<!ATTLIST\". -- saw ~S."
                  tok)) )) )))

(defun p/attdef (input)
  ;; [53] AttDef ::= Name S AttType S DefaultDecl
  (let (name type default)
    (setf name (p/name input))
    (p/S input)
    (setf type (p/att-type input))
    (p/S input)
    (setf default (p/default-decl input))
    (values name type default)))

(defun p/list (input item-parser delimiter)
  ;; Parse something like S? <item> (S? <delimiter> <item>)* S?
  ;;
  (declare (type function item-parser))
  (let (res)
    (p/S? input)
    (setf res (list (funcall item-parser input)))
    (loop
      (p/S? input)
      (cond ((eq (peek-token input) delimiter)
             (consume-token input)
             (p/S? input)
             (push (funcall item-parser input) res))
            (t
             (return))))
    (p/S? input)
    (reverse res)))

(defun p/att-type (input)
  ;; [54] AttType ::= StringType | TokenizedType | EnumeratedType
  ;; [55] StringType ::= 'CDATA'
  ;; [56] TokenizedType ::= 'ID'                          /*VC: ID */
  ;;                                                        /*VC: One ID per Element Type */
  ;;                                                        /*VC: ID Attribute Default */
  ;;                          | 'IDREF'                     /*VC: IDREF */
  ;;                          | 'IDREFS'                    /*VC: IDREF */
  ;;                          | 'ENTITY'                    /*VC: Entity Name */
  ;;                          | 'ENTITIES'                  /*VC: Entity Name */
  ;;                          | 'NMTOKEN'                   /*VC: Name Token */
  ;;                          | 'NMTOKENS'                  /*VC: Name Token */
  ;; [57] EnumeratedType ::= NotationType | Enumeration
  ;; [58]   NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
  ;; /* VC: Notation Attributes */
  ;; [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')' /* VC: Enumeration */
  (multiple-value-bind (cat sem) (read-token input)
    (cond ((eq cat :name)
david's avatar
david committed
1497 1498 1499 1500 1501 1502 1503 1504
           (cond ((equalp sem '#.(string-rod "CDATA"))    :CDATA)
                 ((equalp sem '#.(string-rod "ID"))       :ID)
                 ((equalp sem '#.(string-rod "IDREF"))    :IDREFS)
                 ((equalp sem '#.(string-rod "IDREFS"))   :IDREFS)
                 ((equalp sem '#.(string-rod "ENTITY"))   :ENTITY)
                 ((equalp sem '#.(string-rod "ENTITIES")) :ENTITIES)
                 ((equalp sem '#.(string-rod "NMTOKEN"))  :NMTOKEN)
                 ((equalp sem '#.(string-rod "NMTOKENS")) :NMTOKENS)
david's avatar
david committed
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
                 ((equalp sem '#.(string-rod "NOTATION"))
                  ;; xxx nmtoken vs name
                  (let (names)
                    (p/S input)
                    (expect input :\()
                    (setf names (p/list input #'p/name :\| ))
                    (expect input :\))
                    (cons :notation names)))
                 (t
                  (error "In p/att-type: ~S ~S." cat sem))))
          ((eq cat :\()
           ;; xxx nmtoken vs name
           (let (names)
             ;;(expect input :\()
             (setf names (p/list input #'p/name :\| ))
             (expect input :\))
             (cons :enumeration names)))
          (t
           (error "In p/att-type: ~S ~S." cat sem)) )))

(defun p/default-decl (input)
  ;; [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED'
  ;;                       | (('#FIXED' S)? AttValue) /* VC: Required Attribute */
  ;;                       
  ;; /* VC: Attribute Default Legal */
  ;; /* WFC: No < in Attribute Values */
  ;; /* VC: Fixed Attribute Default */
  (multiple-value-bind (cat sem) (peek-token input)
    (cond ((eq cat :|#REQUIRED|) 
           (consume-token input) :required)
          ((eq cat :|#IMPLIED|)  
           (consume-token input) :implied)
          ((eq cat :|#FIXED|)
           (consume-token input)
           (p/S input)
           (list :fixed (p/att-value input)))
          ((or (eq cat :\') (eq cat :\"))
           (list :default (p/att-value input)))
          (t
           (error "p/default-decl: ~S ~S." cat sem)) )))
;;;;

;;  [70] EntityDecl ::= GEDecl | PEDecl
;;  [71]     GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
;;  [72]     PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
;;  [73]  EntityDef ::= EntityValue | (ExternalID NDataDecl?)
;;  [74]      PEDef ::= EntityValue | ExternalID
;;  [75] ExternalID ::= 'SYSTEM' S SystemLiteral
;;                      | 'PUBLIC' S PubidLiteral S SystemLiteral
;;  [76]  NDataDecl ::= S 'NDATA' S Name                /* VC: Notation Declared */

(defun p/entity-decl (input)
  (let (name def kind)
    (expect input :|<!ENTITY|)
    (p/S input)
    (cond ((eq (peek-token input) :%)
           (setf kind :parameter)
           (consume-token input)
           (p/S input))
          (t
           (setf kind :general)))
    (setf name (p/name input))
    (p/S input)
    (setf def (p/entity-def input kind))
    (define-entity input name kind def)
    (p/S? input)
    (expect input :\>)))

(defun p/entity-def (input kind)
  (multiple-value-bind (cat sem) (peek-token input)
    (cond ((member cat '(:\" :\'))
david's avatar
david committed
1576
           (list :INTERNAL (p/entity-value input)))
david's avatar
david committed
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
          ((and (eq cat :name)
                (or (equalp sem '#.(string-rod "SYSTEM"))
                    (equalp sem '#.(string-rod "PUBLIC"))))
           (let (extid ndata)
             (setf extid (p/external-id input nil))
             (when (eq kind :general)   ;NDATA allowed at all?
               (cond ((eq (peek-token input) :S)
                      (p/S? input)
                      (when (and (eq (peek-token input) :name)
                                 (equalp (nth-value 1 (peek-token input))
                                         '#.(string-rod "NDATA")))
                        (consume-token input)
                        (p/S input)
                        (setf ndata (p/name input))))))
david's avatar
david committed
1591
             (list :EXTERNAL extid ndata)))
david's avatar
david committed
1592 1593 1594 1595 1596 1597 1598
          (t
           (error "p/entity-def: ~S / ~S." cat sem)) )))

(defun p/entity-value (input)
  (let ((delim (if (eq (read-token input) :\") #/\" #/\')))
    (read-att-value input
                    (car (zstream-input-stack input))
david's avatar
david committed
1599
                    :ENT
david's avatar
david committed
1600 1601 1602 1603 1604 1605 1606
                    nil
                    delim)))

(defun p/att-value (input)
  (let ((delim (if (eq (read-token input) :\") #/\" #/\')))
    (read-att-value input
                    (car (zstream-input-stack input))
david's avatar
david committed
1607
                    :ATT
david's avatar
david committed
1608 1609 1610 1611 1612 1613 1614 1615
                    t
                    delim)))

(defun p/external-id (input &optional (public-only-ok-p nil))
  ;; xxx public-only-ok-p
  (multiple-value-bind (cat sem) (read-token input)
    (cond ((and (eq cat :name) (equalp sem '#.(string-rod "SYSTEM")))
           (p/S input)
david's avatar
david committed
1616
           (list :SYSTEM (p/system-literal input))
david's avatar
david committed
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
           )
          ((and (eq cat :name) (equalp sem '#.(string-rod "PUBLIC")))
           (let (pub sys)
             (p/S input)
             (setf pub (p/pubid-literal input))
             (when (eq (peek-token input) :S)
               (p/S input)
               (when (member (peek-token input) '(:\" :\'))
                 (setf sys (p/system-literal input))))
             (unless (every #'pubid-char-p pub)
               (error "Illegal pubid: ~S." (rod-string pub)))
             (when (and (not public-only-ok-p)
                        (null sys))
               (error "System identifier needed for this PUBLIC external identifier."))
david's avatar
david committed
1631
             (list :PUBLIC pub sys)))
david's avatar
david committed
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
          (t
           (error "Expected external-id: ~S / ~S." cat sem)))))


;;  [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
;;  [12]  PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
;;  [13]     PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9]
;;                         | [-'()+,./:=?;!*#@$_%]

(defun p/system-literal (input)
  (multiple-value-bind (cat) (read-token input)
    (cond ((member cat '(:\" :\'))
           (let ((delim (if (eq cat :\") #/\" #/\')))
             (with-rune-collector (collect)
               (loop
                 (let ((c (read-rune (car (zstream-input-stack input)))))
                   (cond ((eq c :eof)
                          (error "EOF in system literal."))
                         ((rune= c delim)
                          (return))
                         (t
                          (collect c))))))))
          (t
           (error "Expect either \" or \'.")))))

(defun p/pubid-literal (input)
  ;; xxx check for valid chars
  (p/system-literal input))


;;;;

(defun p/element-decl (input)
  (let (name content)
    (expect input :|<!ELEMENT|)
    (p/S input)
    (setf name (p/name input))
    (p/S input)
    (setf content (p/cspec input))
    (unless (legal-content-model-p content)
      '(error "Illegal content model: ~S." (mu content))
      (warn "Illegal content model: ~S." (mu content)))
    (p/S? input)
    (expect input :\>)
    (list :element name content)))

(defun legal-content-model-p (cspec)
  (or (eq cspec :PCDATA)
      (eq cspec :ANY)
      (eq cspec :EMPTY)
      (and (consp cspec)
           (eq (car cspec) '*)
           (consp (cadr cspec))
           (eq (car (cadr cspec)) 'or)
david's avatar
david committed
1686
           (eq (cadr (cadr cspec)) :PCDATA)
david's avatar
david committed
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
           (every #'vectorp (cddr (cadr cspec))))
      (labels ((walk (x)
                 (cond ((member x '(:PCDATA :ANY :EMPTY))
                        nil)
                       ((atom x) t)
                       ((and (walk (car x))
                             (walk (cdr x)))))))
        (walk cspec))))
                 
;; wir fahren besser, wenn wir machen:

;; cspec ::= 'EMPTY' | 'ANY' | '#PCDATA' 
;;         | Name
;;         | cs
;;    cs ::= '(' S? cspec ( S? '|' S? cs)* S? ')' ('?' | '*' | '+')?
;; und eine post mortem analyse

(defun p/cspec (input &optional (level 0) (only-names-p nil))
  (let ((term
         (let ((names nil) op-cat op res)
           (multiple-value-bind (cat sem) (peek-token input)
             (cond ((eq cat :name) 
                    (consume-token input) 
                    (cond ((rod= sem '#.(string-rod "EMPTY"))
                           :empty)
                          ((rod= sem '#.(string-rod "ANY"))
david's avatar
david committed
1713
                           :ANY)
david's avatar
david committed
1714 1715 1716 1717 1718 1719
                          (t
                           sem)))
                   ((and (eq cat :\#PCDATA) (not only-names-p))
                    (unless (= level 1)
                      (error "#PCDATA only on top level in content modell."))
                    (consume-token input)
david's avatar
david committed
1720
                    :PCDATA)
david's avatar
david committed
1721 1722 1723 1724 1725
                   ((and (eq cat :\() (not only-names-p))
                    (consume-token input)
                    (p/S? input)
                    (setq names (list (p/cspec input (+ level 1))))
                    (p/S? input)
david's avatar
david committed
1726
                    (let ((on? (eq (car names) :PCDATA)))
david's avatar
david committed
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
                      (cond ((member (peek-token input) '(:\| :\,))
                             (setf op-cat (peek-token input))
                             (setf op (if (eq op-cat :\,) 'and 'or))
                             (while (eq (peek-token input) op-cat)
                                    (consume-token input)
                                    (p/S? input)
                                    (push (p/cspec input (+ level 1) on?) names)
                                    (p/S? input))
                             (setf res (cons op (reverse names))))
                            (t
                             (setf res (car names)))))
                    (p/S? input)
                    (expect input :\))
                    res)
                   (t
                    (error "p/cspec - ~s / ~s" cat sem)))))))
    (cond ((eq (peek-token input) :?) (consume-token input) (list '? term))
          ((eq (peek-token input) :+) (consume-token input) (list '+ term))
          ((eq (peek-token input) :*) (consume-token input) (list '* term))
          (t
           term))))
   
;; [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'
    

;; [52] AttlistDecl ::= '<!ATTLIST' S Name AttDefs S? '>'
;; [52] AttlistDecl ::= '<!ATTLIST' S Name S? '>'
;; [53] AttDefs ::= S Name S AttType S DefaultDecl AttDefs
;; [53] AttDefs ::= 

(defun p/notation-decl (input)
  (let (name id)
    (expect input :|<!NOTATION|)
    (p/S input)
    (setf name (p/name input))
    (p/S input)
    (setf id (p/external-id input t))
    (p/S? input)
    (expect input :\>)
    (list :notation-decl name id)))

;;;

(defun p/conditional-sect (input)
  (expect input :<!\[ )
  (p/S? input)
  (multiple-value-bind (cat sem) (read-token input)
    (cond ((and (eq cat :name)
                (rod= sem '#.(string-rod "INCLUDE")))
           (p/include-sect input))
          ((and (eq cat :name)
                (rod= sem '#.(string-rod "IGNORE")))
           (p/ignore-sect input))
          (t
           (error "Expected INCLUDE or IGNORE after \"<![\".")))))

(defun p/include-sect (input)
  ;; <![INCLUDE is already read.
  (p/S? input)
  (expect input :\[)
  (p/ext-subset-decl input)
  (expect input :\])
  (expect input :\])
  (expect input :\>) )

(defun p/ignore-sect (input)
  ;; <![IGNORE is already read.
  (p/S? input)
  (expect input :\[)
  (let ((input (car (zstream-input-stack input))))
    (let ((level 0))
      (do ((c1 (read-rune input) (read-rune input))
           (c2 0 c1)
           (c3 0 c2))
          ((= level -1))
        (declare (type fixnum level))
        (cond ((eq c1 :eof)
               (error "EOF in <![IGNORE ... >")))
        (cond ((and (rune= c3 #/<) (rune= c2 #/!) (rune= c1 #/\[))
               (incf level)))
        (cond ((and (rune= c3 #/\]) (rune= c2 #/\]) (rune= c1 #/>))
               (decf level))) ))))

(defun p/ext-subset-decl (input)
  ;; ( markupdecl | conditionalSect | S )*
  (loop
    (case (let ((*expand-pe-p* nil)) (peek-token input))
      (:|<![| (let ((*expand-pe-p* t)) (p/conditional-sect input)))
      (:S     (consume-token input))
      (:eof   (return))
      ((:|<!ELEMENT| :|<!ATTLIST| :|<!ENTITY| :|<!NOTATION| :PI :COMMENT)
       (let ((*expand-pe-p* t))
         (p/markup-decl input)))
david's avatar
david committed
1820
      ((:PE-REFERENCE)
david's avatar
david committed
1821 1822 1823 1824
       (let ((name (nth-value 1 (read-token input))))
         (recurse-on-entity input name :parameter
                            (lambda (input)
                              (ecase (entity-source-kind name :parameter)
david's avatar
david committed
1825
                                (:EXTERNAL
david's avatar
david committed
1826
                                 (p/ext-subset input))
david's avatar
david committed
1827
                                (:INTERNAL
david's avatar
david committed
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
                                 (p/ext-subset-decl input)))
                              (unless (eq :eof (peek-token input))
                                (error "Trailing garbage."))))))
      (otherwise (return)))) )

(defun p/markup-decl (input)
  ;; markupdecl ::= elementdecl | AttlistDecl       /* VC: Proper Declaration/PE Nesting */
  ;;              | EntityDecl | NotationDecl 
  ;;              | PI | Comment               /* WFC: PEs in Internal Subset */
  (case (peek-token input)
    (:|<!ELEMENT|  (p/element-decl input))
    (:|<!ATTLIST|  (p/attlist-decl input))
    (:|<!ENTITY|   (p/entity-decl input))
    (:|<!NOTATION| (p/notation-decl input))
    (:PI           (consume-token input))
    (:COMMENT      (consume-token input))
    (otherwise
     (error "p/markup-decl ~S" (peek-token input)))))

(defun setup-encoding (input xml-header)
  (when (xml-header-encoding xml-header)
    (let ((enc (find-encoding (xml-header-encoding xml-header))))
      (cond (enc
             (setf (xstream-encoding (car (zstream-input-stack input)))
               enc))
            (t
             (warn "There is no such encoding: ~S." (xml-header-encoding xml-header)))))))

(defun set-full-speed (input)
  (let ((xstream (car (zstream-input-stack input))))
    (when xstream
      (setf (xstream-speed xstream)
        (length (xstream-os-buffer xstream))))
    '(warn "Reverting ~S to full speed." input)
    ))

(defun p/ext-subset (input)
  (cond ((eq (peek-token input) :xml-pi)
         (let ((hd (parse-xml-pi (cdr (nth-value 1 (peek-token input))) nil)))
           (setup-encoding input hd))
         (consume-token input)))
  (set-full-speed input)
  (p/ext-subset-decl input)
  (unless (eq (peek-token input) :eof)
    (error "Trailing garbage - ~S." (peek-token input))))

(defun p/doctype-decl (input)
  (let ((*expand-pe-p* nil))
    (let (name extid)
      (expect input :|<!DOCTYPE|)
      (p/S input)
      (setq name (p/name input))
      (when (eq (peek-token input) :S)
        (p/S input)
        (unless (or (eq (peek-token input) :\[ )
                    (eq (peek-token input) :\> ))
          (setf extid (p/external-id input t))))
      (p/S? input)
      (when (eq (peek-token input) :\[ )
        (consume-token input)
        (while (progn (p/S? input)
                      (not (eq (peek-token input) :\] )))
david's avatar
david committed
1890
          (if (eq (peek-token input) :PE-REFERENCE)
david's avatar
david committed
1891 1892 1893 1894
              (let ((name (nth-value 1 (read-token input))))
                (recurse-on-entity input name :parameter
                                   (lambda (input)
                                     (ecase (entity-source-kind name :parameter)
david's avatar
david committed
1895
                                       (:EXTERNAL
david's avatar
david committed
1896
                                        (p/ext-subset input))
david's avatar
david committed
1897
                                       (:INTERNAL
david's avatar
david committed
1898 1899 1900 1901 1902 1903 1904
                                        (p/ext-subset-decl input)))
                                     (unless (eq :eof (peek-token input))
                                       (error "Trailing garbage.")))))
            (p/markup-decl input)))
        (consume-token input)
        (p/S? input))
      (expect input :>)
david's avatar
david committed
1905 1906 1907
      (ecase (car extid)
        (:PUBLIC (sax:start-dtd *handler* name (cadr extid) (caddr extid)))
        (:SYSTEM (sax:start-dtd *handler* name nil (cadr extid))))
david's avatar
david committed
1908 1909 1910 1911 1912
      (when extid
        (let* ((xi2 (open-extid (absolute-extid input extid)))
               (zi2 (make-zstream :input-stack (list xi2))))
          (let ()
            (p/ext-subset zi2))))
david's avatar
david committed
1913
      (sax:end-dtd *handler*)
david's avatar
david committed
1914
      (list :DOCTYPE name extid))))
david's avatar
david committed
1915 1916 1917

(defun p/misc*-2 (input)
  ;; Misc*
david's avatar
david committed
1918
  (while (member (peek-token input) '(:COMMENT :PI :S))
david's avatar
david committed
1919 1920 1921 1922 1923 1924 1925 1926 1927
    (case (peek-token input)
      (:COMMENT
        (sax:comment *handler* (nth-value 1 (peek-token input))))
      (:PI
        (sax:processing-instruction 
         *handler*
         (car (nth-value 1 (peek-token input)))
         (cdr (nth-value 1 (peek-token input))))))
    (consume-token input)))
david's avatar
david committed
1928 1929 1930 1931 1932 1933
  

(defvar *handler*)

(defun p/document (input handler)
  (let ((*handler* handler)
david's avatar
david committed
1934 1935 1936
	(*namespace-bindings* *default-namespace-bindings*)
        (*entities* nil)
        (*dtd* (make-dtd)))
david's avatar
david committed
1937
    (declare (special *namespace-bindings*)) ;forward declaration for DEFVAR
david's avatar
david committed
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
    (define-default-entities)
    (sax:start-document *handler*)
    ;; document ::= XMLDecl? Misc* (doctypedecl Misc*)? element Misc*
    ;; Misc ::= Comment | PI |  S
    ;; xmldecl::='<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
    ;; sddecl::= S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"'))
    ;;
    ;; we will use the attribute-value parser for the xml decl.
    (let ((*data-behaviour* :DTD))
      ;; optional XMLDecl?
      (cond ((eq (peek-token input) :xml-pi)