-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathxml-parse.lisp
More file actions
3974 lines (3608 loc) · 145 KB
/
xml-parse.lisp
File metadata and controls
3974 lines (3608 loc) · 145 KB
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
198
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
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
723
724
725
726
727
728
729
730
731
732
733
734
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
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
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
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
993
994
995
996
997
998
999
1000
;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: CXML; readtable: runes; -*-
;;; ---------------------------------------------------------------------------
;;; Title: XML parser
;;; Created: 1999-07-17
;;; Author: Gilbert Baumann <unk6@rz.uni-karlsruhe.de>
;;; Author: Henrik Motakef <hmot@henrik-motakef.de>
;;; Author: David Lichteblau <david@lichteblau.com>
;;; License: Lisp-LGPL (See file COPYING for details).
;;; ---------------------------------------------------------------------------
;;; (c) copyright 1999 by Gilbert Baumann
;;; (c) copyright 2003 by Henrik Motakef
;;; (c) copyright 2004 knowledgeTools Int. GmbH
;;; (c) copyright 2004 David Lichteblau
;;; (c) copyright 2005 David Lichteblau
;;; 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 t conversion on ; 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-decl (<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
;;
;; :nmtoken <interned-rod>
;; :#required
;; :#implied
;; :#fixed
;; :#pcdata
;; :s
;; :\[ :\] :\( :\) :|\ :\> :\" :\' :\, :\? :\* :\+
;; *data-behaviour* = :DOC
;;
;; :entity-ref <interned-rod>
;; :cdata <rod>
;;; TODO
;;
;; o provide for a faster DOM
;;
;; o morph zstream into a context object and thus also get rid of
;; special variables. Put the current DTD there too.
;; [partly done]
;; 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.
;; [for thread-safety reasons the array are allocated per context now,
;; reentrancy is still open]
;; 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).
;; [gemeint ist zstream-push--david]
;;
;; o better extensibility wrt character representation, one may want to
;; have
;; - UCS-4 in vectoren
;;
;; o xstreams auslagern, documententieren und dann auch in SGML und
;; CSS parser verwenden. (halt alles was zeichen liest).
;; [ausgelagert sind sie; dokumentiert "so la la"; die Reintegration
;; in Closure ist ein ganz anderes Thema]
;;
;; o recording of source locations for nodes.
;;
;; o based on the DTD and xml:space attribute implement HTML white
;; space rules.
;;
;; o on a parser option, do not expand external entities.
;;;; Validity constraints:
;;;; (00) Root Element Type like (03), c.f. MAKE-ROOT-MODEL
;;;; (01) Proper Declaration/PE Nesting P/MARKUP-DECL
;;;; (02) Standalone Document Declaration all over the place [*]
;;;; (03) Element Valid VALIDATE-*-ELEMENT, -CHARACTERS
;;;; (04) Attribute Value Type VALIDATE-ATTRIBUTE
;;;; (05) Unique Element Type Declaration DEFINE-ELEMENT
;;;; (06) Proper Group/PE Nesting P/CSPEC
;;;; (07) No Duplicate Types LEGAL-CONTENT-MODEL-P
;;;; (08) ID VALIDATE-ATTRIBUTE
;;;; (09) One ID per Element Type DEFINE-ATTRIBUTE
;;;; (10) ID Attribute Default DEFINE-ATTRIBUTE
;;;; (11) IDREF VALIDATE-ATTRIBUTE, P/DOCUMENT
;;;; (12) Entity Name VALIDATE-ATTRIBUTE
;;;; (13) Name Token VALIDATE-ATTRIBUTE
;;;; (14) Notation Attributes VALIDATE-ATTRIBUTE, P/ATT-TYPE
;;;; (15) One Notation Per Element Type DEFINE-ATTRIBUTE
;;;; (16) No Notation on Empty Element DEFINE-ELEMENT, -ATTRIBUTE
;;;; (17) Enumeration VALIDATE-ATTRIBUTE
;;;; (18) Required Attribute PROCESS-ATTRIBUTES
;;;; (19) Attribute Default Legal DEFINE-ATTRIBUTE
;;;; (20) Fixed Attribute Default VALIDATE-ATTRIBUTE
;;;; (21) Proper Conditional Section/PE Nesting P/CONDITIONAL-SECT, ...
;;;; (22) Entity Declared [**]
;;;; (23) Notation Declared P/ENTITY-DEF, P/DOCUMENT
;;;; (24) Unique Notation Name DEFINE-NOTATION
;;;;
;;;; [*] Perhaps we could revert the explicit checks of (02), if we did
;;;; _not_ read external subsets of standalone documents when parsing in
;;;; validating mode. Violations of VC (02) constraints would then appear as
;;;; wellformedness violations, right?
;;;;
;;;; [**] Although I haven't investigated this properly yet, I believe that
;;;; we check this VC together with the WFC even in non-validating mode.
(cl:in-package #:cxml)
#+allegro
(setf (excl:named-readtable :runes) *readtable*)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *fast* '(optimize (speed 3) (safety 0)))
;;(defparameter *fast* '(optimize (speed 2) (safety 3)))
)
;;; parser context
(defvar *ctx* nil)
(defstruct (context (:conc-name nil))
handler
(dtd nil)
model-stack
;; xml:base machen wir fuer klacks mal gleich als expliziten stack:
base-stack
(referenced-notations '())
(id-table (%make-rod-hash-table))
;; FIXME: Wofuer ist name-hashtable da? Will man das wissen?
(name-hashtable (make-rod-hashtable :size 2000))
(standalone-p nil)
(entity-resolver nil)
(disallow-internal-subset nil)
main-zstream)
(defmacro with-restored-base-stack ((context) &body body)
(let ((context-var (gensym "CONTEXT"))
(old-base-stack-var (gensym "OLD-BASE-STACK"))) ; TODO use alexandria later
`(let* ((,context-var ,context)
(,old-base-stack-var (base-stack ,context-var)))
(multiple-value-prog1
(progn ,@body)
(setf (base-stack ,context-var) ,old-base-stack-var)))))
(defvar *expand-pe-p* nil)
(defparameter *initial-namespace-bindings*
'((#"" . nil)
(#"xmlns" . #"http://www.w3.org/2000/xmlns/")
(#"xml" . #"http://www.w3.org/XML/1998/namespace")))
(defparameter *namespace-bindings* *initial-namespace-bindings*)
;;;; ---------------------------------------------------------------------------
;;;; xstreams
;;;;
(defstruct (stream-name
(:print-function print-stream-name))
entity-name
entity-kind
uri)
(defun print-stream-name (object stream depth)
(declare (ignore depth))
(format stream "[~A ~S ~A]"
(rod-string (stream-name-entity-name object))
(stream-name-entity-kind object)
(stream-name-uri object)))
(deftype read-element () 'rune)
(defun call-with-open-xstream (fn stream)
(unwind-protect
(funcall fn stream)
(close-xstream stream)))
(defmacro with-open-xstream ((var value) &body body)
`(call-with-open-xstream (lambda (,var) ,@body) ,value))
(defun call-with-open-xfile (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-xfile ((stream &rest open-args) &body body)
`(call-with-open-xfile (lambda (,stream) .,body) .,open-args))
;;;; -------------------------------------------------------------------
;;;; Rechnen mit Runen
;;;;
;; Let us first define fast fixnum arithmetric get rid of type
;; checks. (After all we know what we do here).
(defmacro fx-op (op &rest xs)
`(the fixnum (,op ,@(mapcar (lambda (x) `(the fixnum ,x)) xs))))
(defmacro fx-pred (op &rest xs)
`(,op ,@(mapcar (lambda (x) `(the fixnum ,x)) xs)))
(defmacro %+ (&rest xs) `(fx-op + ,@xs))
(defmacro %- (&rest xs) `(fx-op - ,@xs))
(defmacro %* (&rest xs) `(fx-op * ,@xs))
(defmacro %/ (&rest xs) `(fx-op floor ,@xs))
(defmacro %and (&rest xs) `(fx-op logand ,@xs))
(defmacro %ior (&rest xs) `(fx-op logior ,@xs))
(defmacro %xor (&rest xs) `(fx-op logxor ,@xs))
(defmacro %ash (&rest xs) `(fx-op ash ,@xs))
(defmacro %mod (&rest xs) `(fx-op mod ,@xs))
(defmacro %= (&rest xs) `(fx-pred = ,@xs))
(defmacro %<= (&rest xs) `(fx-pred <= ,@xs))
(defmacro %>= (&rest xs) `(fx-pred >= ,@xs))
(defmacro %< (&rest xs) `(fx-pred < ,@xs))
(defmacro %> (&rest xs) `(fx-pred > ,@xs))
;;; XXX Geschwindigkeit dieser Definitionen untersuchen!
(defmacro rune-op (op &rest xs)
`(code-rune (,op ,@(mapcar (lambda (x) `(rune-code ,x)) xs))))
(defmacro rune-pred (op &rest xs)
`(,op ,@(mapcar (lambda (x) `(rune-code ,x)) xs)))
(defmacro %rune+ (&rest xs) `(rune-op + ,@xs))
(defmacro %rune- (&rest xs) `(rune-op - ,@xs))
(defmacro %rune* (&rest xs) `(rune-op * ,@xs))
(defmacro %rune/ (&rest xs) `(rune-op floor ,@xs))
(defmacro %rune-and (&rest xs) `(rune-op logand ,@xs))
(defmacro %rune-ior (&rest xs) `(rune-op logior ,@xs))
(defmacro %rune-xor (&rest xs) `(rune-op logxor ,@xs))
(defmacro %rune-ash (a b) `(code-rune (ash (rune-code ,a) ,b)))
(defmacro %rune-mod (&rest xs) `(rune-op mod ,@xs))
(defmacro %rune= (&rest xs) `(rune-pred = ,@xs))
(defmacro %rune<= (&rest xs) `(rune-pred <= ,@xs))
(defmacro %rune>= (&rest xs) `(rune-pred >= ,@xs))
(defmacro %rune< (&rest xs) `(rune-pred < ,@xs))
(defmacro %rune> (&rest xs) `(rune-pred > ,@xs))
;;;; ---------------------------------------------------------------------------
;;;; 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 (nearest-greater-prime size))
(make-rod-hashtable/low
:size size
:table (make-array size :initial-element nil)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(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."))
(definline stir (a b)
(%and +fixnum-mask+
(%xor (%ior (%ash (%and a #.(ash +fixnum-mask+ -5)) 5)
(%ash a #.(- 5 +fixnum-bits+)))
b)))
(definline 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-code (%rune rod i)))))
res))
(definline 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= (%rune x i) (%rune y j))
(return nil)))))
(definline 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= (%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)))
#-rune-is-character
(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))))))))
#+rune-is-character
(defun rod-subseq* (source start &optional (end (length source)))
(subseq source start end))
(deftype ufixnum () `(unsigned-byte ,(integer-length most-positive-fixnum)))
#-rune-is-character
(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))
#+rune-is-character
(defun rod-subseq** (source start &optional (end (length source)))
(subseq source start end))
(defun (setf rod-hash-get) (new-value hashtable rod &optional (start 0) (end (length rod)))
(rod-hash-set new-value hashtable rod start end))
(defun intern-name (rod &optional (start 0) (end (length rod)))
(multiple-value-bind (value successp key) (rod-hash-get (name-hashtable *ctx*) rod start end)
(declare (ignore value))
(if successp
key
(nth-value 1 (rod-hash-set t (name-hashtable *ctx*) rod start end)))))
;;;; ---------------------------------------------------------------------------
;;;;
;;;; rod collector
;;;;
(defvar *scratch-pad*)
(defvar *scratch-pad-2*)
(defvar *scratch-pad-3*)
(defvar *scratch-pad-4*)
(declaim (type (simple-array rune (*))
*scratch-pad* *scratch-pad-2* *scratch-pad-3* *scratch-pad-4*))
(defmacro with-scratch-pads ((&optional) &body body)
`(let ((*scratch-pad* (make-array 1024 :element-type 'rune))
(*scratch-pad-2* (make-array 1024 :element-type 'rune))
(*scratch-pad-3* (make-array 1024 :element-type 'rune))
(*scratch-pad-4* (make-array 1024 :element-type 'rune)))
,@body))
(defmacro %put-unicode-char (code-var put)
`(progn
(cond #+rune-is-utf-16
((%> ,code-var #xFFFF)
(,put (the rune (code-rune (%+ #xD7C0 (%ash ,code-var -10)))))
(,put (the rune (code-rune (%ior #xDC00 (%and ,code-var #x03FF))))))
(t
(,put (code-rune ,code-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
;;;;
(define-condition xml-parse-error (simple-error) ()
(:documentation
"Superclass of all conditions signalled by the CXML parser."))
(define-condition well-formedness-violation (xml-parse-error) ()
(:documentation
"This condition is signalled for all well-formedness violations.
Note for validating mode: Sometimes violations of well-formedness are
first detected as validity errors by the parser and signalled as
instances of @class{validity-error} rather
than well-formedness-violation."))
(define-condition validity-error (xml-parse-error) ()
(:documentation
"Reports the violation of a validity constraint."))
;; We make some effort to signal end of file as a special condition, but we
;; don't actually try very hard. Not sure whether we should. Right now I
;; would prefer not to document this class.
(define-condition end-of-xstream (well-formedness-violation) ())
(defun describe-xstream (x s)
(format s " Line ~D, column ~D in ~A~%"
(xstream-line-number x)
(xstream-column-number x)
(let ((name (xstream-name x)))
(cond
((null name)
"<anonymous stream>")
((eq :main (stream-name-entity-kind name))
(stream-name-uri name))
(t
name)))))
(defun %error (class stream message)
(let* ((zmain (if *ctx* (main-zstream *ctx*) nil))
(zstream (if (zstream-p stream) stream zmain))
(xstream (if (xstream-p stream) stream nil))
(s (make-string-output-stream)))
(write-line message s)
(when xstream
(write-line "Location:" s)
(describe-xstream xstream s))
(when zstream
(let ((stack
(remove xstream (remove :stop (zstream-input-stack zstream)))))
(when stack
(write-line "Context:" s)
(dolist (x stack)
(describe-xstream x s)))))
(when (and zmain (not (eq zstream zmain)))
(let ((stack
(remove xstream (remove :stop (zstream-input-stack zmain)))))
(when stack
(write-line "Context in main document:" s)
(dolist (x stack)
(describe-xstream x s)))))
(error class
:format-control "~A"
:format-arguments (list (get-output-stream-string s)))))
(defun validity-error (fmt &rest args)
(%error 'validity-error
nil
(format nil "Document not valid: ~?" fmt args)))
(defun wf-error (stream fmt &rest args)
(%error 'well-formedness-violation
stream
(format nil "Document not well-formed: ~?" fmt args)))
(defun eox (stream &optional x &rest args)
(%error 'end-of-xstream
stream
(format nil "End of file~@[: ~?~]" x args)))
(defclass cxml-parser (sax:sax-parser) ((ctx :initarg :ctx)))
(defun parser-xstream (parser)
(car (zstream-input-stack (main-zstream (slot-value parser 'ctx)))))
(defun parser-stream-name (parser)
(let ((xstream (parser-xstream parser)))
(if xstream
(xstream-name xstream)
nil)))
(defmethod sax:line-number ((parser cxml-parser))
(let ((x (parser-xstream parser)))
(if x
(xstream-line-number x)
nil)))
(defmethod sax:column-number ((parser cxml-parser))
(let ((x (parser-xstream parser)))
(if x
(xstream-column-number x)
nil)))
(defmethod sax:system-id ((parser cxml-parser))
(let ((name (parser-stream-name parser)))
(if name
(stream-name-uri name)
nil)))
(defmethod sax:xml-base ((parser cxml-parser))
(let ((uri (car (base-stack (slot-value parser 'ctx)))))
(if (or (null uri) (stringp uri))
uri
(puri:render-uri uri nil))))
(defvar *validate* t)
(defvar *external-subset-p* nil)
(defstruct attdef
;; an attribute definition
(element nil :read-only t) ; name of element this attribute belongs to
(name nil :read-only t) ; name of attribute
(type nil :read-only t) ; type of attribute; either one of :CDATA, :ID, :IDREF, :IDREFS,
; :ENTITY, :ENTITIES, :NMTOKEN, :NMTOKENS, or
; (:NOTATION <name>*)
; (:ENUMERATION <name>*)
(default nil :read-only t) ; default value of attribute:
; :REQUIRED, :IMPLIED, (:FIXED content) or (:DEFAULT content)
(external-p *external-subset-p* :read-only t))
(defstruct elmdef
;; an element definition
(name nil :read-only t) ; name of the element
(content) ; content model [*]
(attributes) ; list of defined attributes
(compiled-cspec) ; cons of validation function for contentspec
(external-p *external-subset-p*))
(defstruct dtd
(elements (%make-rod-hash-table) :read-only t) ; elmdefs
(gentities (%make-rod-hash-table) :read-only t) ; general entities
(pentities (%make-rod-hash-table) :read-only t) ; parameter entities
(notations (%make-rod-hash-table) :read-only t))
(defun validate-start-element (ctx name)
(when *validate*
(let* ((pair (car (model-stack ctx)))
(newval (funcall (car pair) name)))
(unless newval
(validity-error "(03) Element Valid: ~A" (rod-string name)))
(setf (car pair) newval)
(let ((e (find-element name (dtd ctx))))
(unless e
(validity-error "(03) Element Valid: no definition for ~A"
(rod-string name)))
(maybe-compile-cspec e)
(push (copy-cons (elmdef-compiled-cspec e)) (model-stack ctx))))))
(defun copy-cons (x)
(cons (car x) (cdr x)))
(defun validate-end-element (ctx name)
(when *validate*
(let ((pair (car (model-stack ctx))))
(unless (eq (funcall (car pair) nil) t)
(validity-error "(03) Element Valid: ~A" (rod-string name)))
(pop (model-stack ctx)))))
(defun validate-characters (ctx rod)
(when *validate*
(let ((pair (car (model-stack ctx))))
(unless (funcall (cdr pair) rod)
(validity-error "(03) Element Valid: unexpected PCDATA")))))
(defun standalone-check-necessary-p (def)
(and *validate*
(standalone-p *ctx*)
(etypecase def
(elmdef (elmdef-external-p def))
(attdef (attdef-external-p def)))))
;; attribute validation, defaulting, and normalization -- except for for
;; uniqueness checks, which are done after namespaces have been declared
(defun process-attributes (ctx name attlist)
(let ((e (find-element name (dtd ctx))))
(cond
(e
(dolist (ad (elmdef-attributes e)) ;handle default values
(unless (get-attribute (attdef-name ad) attlist)
(case (attdef-default ad)
(:IMPLIED)
(:REQUIRED
(when *validate*
(validity-error "(18) Required Attribute: ~S not specified"
(rod-string (attdef-name ad)))))
(t
(when (standalone-check-necessary-p ad)
(validity-error "(02) Standalone Document Declaration: missing attribute value"))
(push (sax:make-attribute :qname (attdef-name ad)
:value (cadr (attdef-default ad))
:specified-p nil)
attlist)))))
(dolist (a attlist) ;normalize non-CDATA values
(let* ((qname (sax:attribute-qname a))
(adef (find-attribute e qname)))
(when adef
(when (and *validate*
sax:*namespace-processing*
(eq (attdef-type adef) :ID)
(find #/: (sax:attribute-value a)))
(validity-error "colon in ID attribute"))
(unless (eq (attdef-type adef) :CDATA)
(let ((canon (canon-not-cdata-attval (sax:attribute-value a))))
(when (and (standalone-check-necessary-p adef)
(not (rod= (sax:attribute-value a) canon)))
(validity-error "(02) Standalone Document Declaration: attribute value not normalized"))
(setf (sax:attribute-value a) canon))))))
(when *validate* ;maybe validate attribute values
(dolist (a attlist)
(validate-attribute ctx e a))))
((and *validate* attlist)
(validity-error "(04) Attribute Value Type: no definition for element ~A"
(rod-string name)))))
attlist)
(defun get-attribute (name attributes)
(member name attributes :key #'sax:attribute-qname :test #'rod=))
(defun validate-attribute (ctx e a)
(when (sax:attribute-specified-p a) ;defaults checked by DEFINE-ATTRIBUTE
(let* ((qname (sax:attribute-qname a))
(adef
(or (find-attribute e qname)
(validity-error "(04) Attribute Value Type: not declared: ~A"
(rod-string qname)))))
(validate-attribute* ctx adef (sax:attribute-value a)))))
(defun validate-attribute* (ctx adef value)
(let ((type (attdef-type adef))
(default (attdef-default adef)))
(when (and (listp default)
(eq (car default) :FIXED)
(not (rod= value (cadr default))))
(validity-error "(20) Fixed Attribute Default: expected ~S but got ~S"
(rod-string (cadr default))
(rod-string value)))
(ecase (if (listp type) (car type) type)
(:ID
(unless (valid-name-p value)
(validity-error "(08) ID: not a name: ~S" (rod-string value)))
(when (eq (gethash value (id-table ctx)) t)
(validity-error "(08) ID: ~S not unique" (rod-string value)))
(setf (gethash value (id-table ctx)) t))
(:IDREF
(validate-idref ctx value))
(:IDREFS
(let ((names (split-names value)))
(unless names
(validity-error "(11) IDREF: malformed names"))
(mapc (curry #'validate-idref ctx) names)))
(:NMTOKEN
(validate-nmtoken value))
(:NMTOKENS
(let ((tokens (split-names value)))
(unless tokens
(validity-error "(13) Name Token: malformed NMTOKENS"))
(mapc #'validate-nmtoken tokens)))
(:ENUMERATION
(unless (member value (cdr type) :test #'rod=)
(validity-error "(17) Enumeration: value not declared: ~S"
(rod-string value))))
(:NOTATION
(unless (member value (cdr type) :test #'rod=)
(validity-error "(14) Notation Attributes: ~S" (rod-string value))))
(:ENTITY
(validate-entity value))
(:ENTITIES
(let ((names (split-names value)))
(unless names
(validity-error "(13) Name Token: malformed NMTOKENS"))
(mapc #'validate-entity names)))
(:CDATA))))
(defun validate-idref (ctx value)
(unless (valid-name-p value)
(validity-error "(11) IDREF: not a name: ~S" (rod-string value)))
(unless (gethash value (id-table ctx))
(setf (gethash value (id-table ctx)) nil)))
(defun validate-nmtoken (value)
(unless (valid-nmtoken-p value)
(validity-error "(13) Name Token: not a NMTOKEN: ~S"
(rod-string value))))
(defstruct (entdef (:constructor)))
(defstruct (internal-entdef
(:include entdef)
(:constructor make-internal-entdef (value))
(:conc-name #:entdef-))
(value (error "missing argument") :type rod)
(expansion nil)
(external-subset-p *external-subset-p*))
(defstruct (external-entdef
(:include entdef)
(:constructor make-external-entdef (extid ndata))
(:conc-name #:entdef-))
(extid (error "missing argument") :type extid)
(ndata nil :type (or rod null)))
(defun validate-entity (value)
(unless (valid-name-p value)
(validity-error "(12) Entity Name: not a name: ~S" (rod-string value)))
(let ((def (let ((*validate*
;; Similarly the entity refs are internal and
;; don't need normalization ... the unparsed
;; entities (and entities) aren't "references"
;; -- sun/valid/sa03.xml
nil))
(get-entity-definition value :general (dtd *ctx*)))))
(unless (and (typep def 'external-entdef) (entdef-ndata def))
;; unparsed entity
(validity-error "(12) Entity Name: ~S" (rod-string value)))))
(defun split-names (rod)
(flet ((whitespacep (x)
(or (rune= x #/U+0009)
(rune= x #/U+000A)
(rune= x #/U+000D)
(rune= x #/U+0020))))
(if (let ((n (length rod)))
(and (not (zerop n))
(or (whitespacep (rune rod 0))
(whitespacep (rune rod (1- n))))))
nil
(split-sequence-if #'whitespacep rod :remove-empty-subseqs t))))
(defun zstream-base-sysid (zstream)
(let ((base-sysid
(dolist (k (zstream-input-stack zstream))
(let ((base-sysid (stream-name-uri (xstream-name k))))
(when base-sysid (return base-sysid))))))
base-sysid))
(defun absolute-uri (sysid source-stream)
(let ((base-sysid (zstream-base-sysid source-stream)))
;; XXX is the IF correct?
(if base-sysid
(puri:merge-uris sysid base-sysid)
sysid)))
(defstruct (extid (:constructor make-extid (public system)))
(public nil :type (or rod null))
(system (error "missing argument") :type (or puri:uri null)))
(setf (documentation 'extid 'type)
"Represents an External ID, consisting of a Public ID and a System ID.
@see-constructor{make-extiid}
@see-slot{exitid-system}
@see-slot{exitid-public}")
(setf (documentation #'make-extid 'function)
"@arg[publicid]{string or nil}
@arg[systemid]{@class{puri:uri} or nil}
@return{an instance of @class{extid}}
Create an object representing the External ID composed
of the specified Public ID and System ID.")
(setf (documentation #'extid-public 'function)
"@arg[extid]{A @class{extid}}
@return[publicid]{string or nil}
Returns the Public ID part of this External ID.")
(setf (documentation #'extid-system 'function)
"@arg[extid]{A @class{extid}}
@return[sytemid]{puri:uri or nil}
Returns the System ID part of this External ID.")
(defun absolute-extid (source-stream extid)
(let ((sysid (extid-system extid))
(result (copy-extid extid)))
(setf (extid-system result) (absolute-uri sysid source-stream))
result))
(defun define-entity (source-stream name kind def)
(setf name (intern-name name))
(when (and sax:*namespace-processing* (find #/: name))
(wf-error source-stream "colon in entity name"))
(let ((table