ENTITY
[cxml-rng.git] / parse.lisp
blobf629ed1cd39b701c76fb0d4a6e8df6ec8d7cfbf0
1 ;;; Copyright (c) 2007 David Lichteblau. All rights reserved.
3 ;;; Redistribution and use in source and binary forms, with or without
4 ;;; modification, are permitted provided that the following conditions
5 ;;; are met:
6 ;;;
7 ;;; * Redistributions of source code must retain the above copyright
8 ;;; notice, this list of conditions and the following disclaimer.
9 ;;;
10 ;;; * Redistributions in binary form must reproduce the above
11 ;;; copyright notice, this list of conditions and the following
12 ;;; disclaimer in the documentation and/or other materials
13 ;;; provided with the distribution.
14 ;;;
15 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
16 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
19 ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
21 ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 (in-package :cxml-rng)
29 #+sbcl
30 (declaim (optimize (debug 2)))
33 ;;;; Errors
35 (define-condition rng-error (simple-error)
36 ((line-number :initarg :line-number :accessor rng-error-line-number)
37 (column-number :initarg :column-number :accessor rng-error-column-number)
38 (system-id :initarg :system-id :accessor rng-error-system-id))
39 (:documentation
40 "The class of all validation errors.
41 @see-slot{rng-error-line-number}
42 @see-slot{rng-error-column-number}
43 @see-slot{rng-error-system-id}"))
45 (setf (documentation 'rng-error-line-number 'function)
46 "@arg[instance]{an instance of @class{rng-error}}
47 @return{an integer, or nil}
48 Return the line number reported by the parser when the Relax NG error
49 was detected, or NIL if not available.")
51 (setf (documentation 'rng-error-column-number 'function)
52 "@arg[instance]{an instance of @class{rng-error}}
53 @return{an integer, or nil}
54 Return the column number reported by the parser when the Relax NG error
55 was detected, or NIL if not available.")
57 (setf (documentation 'rng-error-system-id 'function)
58 "@arg[instance]{an instance of @class{rng-error}}
59 @return{a puri:uri, or nil}
60 Return the System ID of the document being parsed when the Relax NG
61 error was detected, or NIL if not available.")
63 (defun rng-error (source fmt &rest args)
64 "@unexport{}"
65 (let ((s (make-string-output-stream)))
66 (apply #'format s fmt args)
67 (multiple-value-bind (line-number column-number system-id)
68 (etypecase source
69 (null)
70 (klacks:source
71 (values (klacks:current-line-number source)
72 (klacks:current-column-number source)
73 (klacks:current-system-id source)))
74 (sax:sax-parser-mixin
75 (values (sax:line-number source)
76 (sax:column-number source)
77 (sax:system-id source))))
78 (when (or line-number column-number system-id)
79 (format s "~& [ Error at line ~D, column ~D in ~S ]"
80 line-number
81 column-number
82 system-id))
83 (error 'rng-error
84 :format-control "~A"
85 :format-arguments (list (get-output-stream-string s))
86 :line-number line-number
87 :column-number column-number
88 :system-id system-id))))
91 ;;;; Parser
93 (defvar *datatype-library*)
94 (defvar *namespace-uri*)
95 (defvar *ns*)
96 (defvar *entity-resolver*)
97 (defvar *external-href-stack*)
98 (defvar *include-uri-stack*)
99 (defvar *include-body-p* nil)
100 (defvar *grammar*)
102 (defvar *debug* nil)
104 (defstruct (schema
105 (:constructor make-schema (start definitions)))
106 "An instance of this class represents a Relax NG grammar that has
107 been parsed and simplified.
108 @see-slot{schema-start}
109 @see-constructor{parse-schema}
110 @see{make-validator}
111 @see{serialize-schema} "
112 (start (missing) :type pattern)
113 (definitions (missing) :type list)
114 (interned-start nil :type (or null pattern))
115 (registratur nil :type (or null hash-table)))
117 (setf (documentation 'schema-start 'function)
118 "@arg[instance]{an instance of @class{schema}}
119 @return{the start pattern, an instance of @class{pattern}}
120 Reader function for the grammar's start pattern, from which all
121 of the grammar's patters are reachable.")
123 (defmethod print-object ((object schema) stream)
124 (print-unreadable-object (object stream :type t :identity t)))
126 (defun invoke-with-klacks-handler (fn source)
127 (if *debug*
128 (funcall fn)
129 (handler-case
130 (funcall fn)
131 (cxml:xml-parse-error (c)
132 (rng-error source "Cannot parse schema: ~A" c)))))
134 (defvar *validate-grammar* t)
135 (defparameter *relax-ng-grammar* nil)
137 (defun make-validating-source (input)
138 (let ((upstream (cxml:make-source input)))
139 (if *validate-grammar*
140 (klacks:make-tapping-source upstream
141 (make-validator *relax-ng-grammar*))
142 upstream)))
144 (defun parse-schema (input &key entity-resolver)
145 "@arg[input]{a string, pathname, stream, or xstream}
146 @arg[entity-resolver]{a function of two arguments, or NIL}
147 @return{a parsed @class{schema}}
148 @short{This function parses a Relax NG schema file in XML syntax}
149 and returns a parsed representation of that schema.
151 @code{input} can be any stream designator as understood by
152 @code{cxml:make-source}.
154 Note that namestrings are not valid arguments,
155 because they would be interpreted as XML source code. Use pathnames
156 instead.
158 @code{entity-resolver} can be passed as a function of two arguments.
159 It is invoked for every entity referenced by the
160 document with the entity's Public ID (a rod) and System ID (an
161 URI object) as arguments. The function may either return
162 nil, CXML will then try to resolve the entity as usual.
163 Alternatively it may return a Common Lisp stream specialized on
164 @code{(unsigned-byte 8)} which will be used instead.
166 @see{parse-compact}
167 @see{make-validator}"
168 (when *validate-grammar*
169 (unless *relax-ng-grammar*
170 (setf *relax-ng-grammar*
171 (let* ((*validate-grammar* nil)
172 (d (slot-value (asdf:find-system :cxml-rng)
173 'asdf::relative-pathname)))
174 (parse-schema (merge-pathnames "rng.rng" d))
175 #+(or)
176 (parse-compact (merge-pathnames "rng.rnc" d))))))
177 (klacks:with-open-source (source (make-validating-source input))
178 (invoke-with-klacks-handler
179 (lambda ()
180 (klacks:find-event source :start-element)
181 (let* ((*datatype-library* "")
182 (*namespace-uri* "")
183 (*entity-resolver* entity-resolver)
184 (*external-href-stack* '())
185 (*include-uri-stack* '())
186 (*grammar* (make-grammar nil))
187 (start (p/pattern source)))
188 (unless start
189 (rng-error nil "empty grammar"))
190 (setf (grammar-start *grammar*)
191 (make-definition :name :start :child start))
192 (check-pattern-definitions source *grammar*)
193 (check-recursion start 0)
194 (multiple-value-bind (new-start defns)
195 (finalize-definitions start)
196 (setf start (fold-not-allowed new-start))
197 (dolist (defn defns)
198 (setf (defn-child defn) (fold-not-allowed (defn-child defn))))
199 (setf start (fold-empty start))
200 (dolist (defn defns)
201 (setf (defn-child defn) (fold-empty (defn-child defn)))))
202 (multiple-value-bind (new-start defns)
203 (finalize-definitions start)
204 (check-start-restrictions new-start)
205 (dolist (defn defns)
206 (check-restrictions (defn-child defn)))
207 (make-schema new-start defns))))
208 source)))
211 ;;;; pattern structures
213 (defstruct pattern
214 "@short{The superclass of all patterns.}
215 Instances of this class represent elements of the simplified syntax
216 for Relax NG.
218 Patterns are documented for introspective purposes and are not meant to
219 be modified by user code.
221 The start pattern of a schema is available through @fun{schema-start}.
223 @see{schema}"
224 (nullable :uninitialized))
226 (defmethod print-object :around ((object pattern) stream)
227 (if *debug*
228 (let ((*print-circle* t))
229 (call-next-method))
230 (print-unreadable-object (object stream :type t :identity t))))
232 (defstruct (%parent (:include pattern) (:conc-name "PATTERN-"))
233 child)
235 (defstruct (%named-pattern (:include %parent) (:conc-name "PATTERN-"))
236 name)
238 (setf (documentation 'pattern-name 'function)
239 "@arg[instance]{an instance of @class{pattern}}
240 @return{a @class{name-class}}
241 @short{Returns the @code{pattern}'s name class.}
243 This slot describes the name allowed for the current element or
244 attribute.
246 @see{element}
247 @see{attribute}")
249 (setf (documentation 'pattern-child 'function)
250 "@arg[instance]{an instance of @class{pattern}}
251 @return{an instance of @class{pattern}}
252 @short{Returns the pattern's sub-pattern.}
254 (Elements in the full Relax NG syntax allow more than one child
255 pattern, but simplification normalizes the representation so that
256 any such element has exactly one child.)
258 @see{element}
259 @see{attribute}
260 @see{one-or-more}
261 @see{list-pattern}
262 @see{choice}")
264 (defstruct (element (:include %named-pattern))
265 "@short{This pattern specifies that an element of a certain name class
266 is required.}
268 Its child pattern describes the attributes and child nodes
269 of this element.
270 @see-slot{pattern-name}
271 @see-slot{pattern-child}")
273 (defstruct (attribute (:include %named-pattern))
274 "@short{This pattern specifies that an attribute of a certain name class
275 is required.}
277 Its child pattern describes the type of the attribute's
278 contents.
279 @see-slot{pattern-name}
280 @see-slot{pattern-child}")
282 (defstruct (%combination (:include pattern) (:conc-name "PATTERN-"))
283 a b)
285 (setf (documentation 'pattern-a 'function)
286 "@arg[instance]{an instance of @class{pattern}}
287 @return{an instance of @class{pattern}}
288 @short{Returns the first of two sub-patterns the pattern instance has.}
290 (Elements in the full Relax NG syntax allow more than two child
291 patterns, but simplification normalizes the representation so that
292 any such element has exactly two children.)
294 @see{pattern-b}
295 @see{group}
296 @see{interleave}
297 @see{choice}")
299 (setf (documentation 'pattern-b 'function)
300 "@arg[instance]{an instance of @class{pattern}}
301 @return{an instance of @class{pattern}}
302 @short{Returns the second of two sub-patterns the pattern instance has.}
304 (Elements in the full Relax NG syntax allow more than two child
305 patterns, but simplification normalizes the representation so that
306 any such element has exactly two children.)
308 @see{pattern-a}
309 @see{group}
310 @see{interleave}
311 @see{choice}")
313 (defstruct (group
314 (:include %combination)
315 (:constructor make-group (a b)))
316 "@short{This pattern specifies that two subpatterns are
317 required at the current position in a specific order.}
319 @see-slot{pattern-a}
320 @see-slot{pattern-b}")
321 (defstruct (interleave
322 (:include %combination)
323 (:constructor make-interleave (a b)))
324 "@short{This pattern specifies that two possible subpatterns are
325 allowed to occur in any order at the current position.}
327 @see-slot{pattern-a}
328 @see-slot{pattern-b}")
329 (defstruct (choice
330 (:include %combination)
331 (:constructor make-choice (a b)))
332 "@short{This pattern specifies that one of two possible subpatterns are
333 allowed at the current position, given as its children.}
335 @see-slot{pattern-a}
336 @see-slot{pattern-b}")
337 (defstruct (after
338 (:include %combination)
339 (:constructor make-after (a b))))
341 (defstruct (one-or-more
342 (:include %parent)
343 (:constructor make-one-or-more (child)))
344 "@short{This pattern specifies that its subpattern is
345 allowed to occur at the current position one or more times.}
347 @see-slot{pattern-child}")
348 (defstruct (list-pattern
349 (:include %parent)
350 (:constructor make-list-pattern (child)))
351 "@short{This pattern specifies that a subpatterns is allowed multiple
352 times a the current position, with whitespace as a separator.}
354 @see-slot{pattern-child}")
356 (defstruct (ref
357 (:include pattern)
358 (:conc-name "PATTERN-")
359 (:constructor make-ref (target)))
360 "@short{This pattern references another part of the pattern graph.}
362 @code{ref} is the only pattern to introduce shared structure and
363 circularity into the pattern graph, by referring to elements defined
364 elsewhere.
366 (@code{ref} pattern in the full Relax NG syntax can be used to refer
367 to any pattern definition in the grammar. Simplification normalizes
368 the schema so that ref patterns only refer to definitions which have
369 an @code{element} as their child.)
371 @see-slot{pattern-element}"
372 crdepth
373 target)
375 (defun pattern-element (ref)
376 "@arg[ref]{an instance of @class{ref}}
377 @return{an instance of @class{element}}
378 @short{Returns the ref pattern's target.}
380 @code{ref} is the only pattern to introduce shared structure and
381 circularity into the pattern graph, by referring to elements defined
382 elsewhere.
384 (@code{ref} pattern in the full Relax NG syntax can be used to refer
385 to any pattern definition in the grammar. Simplification normalizes
386 the schema so that ref patterns only refer to definitions which have
387 an @code{element} as their child.)"
388 (defn-child (pattern-target ref)))
390 (defstruct (%leaf (:include pattern)))
392 (defstruct (empty (:include %leaf))
393 "@short{This pattern specifies that nothing more is expected at the current
394 position.}")
396 (defstruct (text (:include %leaf))
397 "@short{This pattern specifies that text is expected here.}")
399 (defstruct (%typed-pattern (:include %leaf) (:conc-name "PATTERN-"))
400 type)
402 (setf (documentation 'pattern-type 'function)
403 "@arg[instance]{an instance of @class{pattern}}
404 @return{a @class{cxml-types:data-type}}
405 @short{Returns the data type expected at this position.}
407 This type has already been parsed into an object. Its name and
408 the URI of its library can be queried from that object.
410 @see{data}
411 @see{value}
412 @see{cxml-types:type-name}
413 @see{cxml-types:type-library}")
415 (defstruct (value (:include %typed-pattern) (:conc-name "PATTERN-"))
416 "@short{This pattern specifies that a specific value is expected as text
417 here.}
419 The value expected is @code{pattern-value}, parsed from
420 @code{pattern-string} using @code{pattern-type}.
422 @see-slot{pattern-type}
423 @see-slot{pattern-value}
424 @see-slot{pattern-string}"
426 string
427 value)
429 (setf (documentation 'pattern-string 'function)
430 "@arg[instance]{an instance of @class{value}}
431 @return{a string}
432 @short{Returns the string expected at this position.}
434 This string is the lexical representation expected, not parsed into
435 a value object yet. The parsed object is available as
436 @fun{pattern-value}.
438 @see{pattern-type}")
440 (setf (documentation 'pattern-value 'function)
441 "@arg[instance]{an instance of @class{value}}
442 @return{an object as returned by @fun{cxml-types:parse}}
443 @short{Returns the value expected at this position.}
445 This object is the result of parsing @fun{pattern-string} using
446 @fun{pattern-type}.")
448 (defstruct (data (:include %typed-pattern) (:conc-name "PATTERN-"))
449 "@short{This pattern specifies that text of a specific data type is
450 expected.}
452 The data type instance stored in the @code{pattern-type} slot takes into
453 account additional paramaters, which can be retrieved using
454 @code{pattern-params} in their original form.
456 @see-slot{pattern-type}
457 @see-slot{pattern-params}
458 @see-slot{pattern-except}"
459 params
460 except)
462 (setf (documentation 'pattern-except 'function)
463 "@arg[instance]{an instance of @class{data}}
464 @return{a @class{pattern}, or @code{nil}}
465 @short{Returns the @code{data} instance's @code{except} pattern.}
467 In addition to a data type, @code{data} can specify that certain
468 values are @em{not} permitted. They are described using a pattern.
470 If this slot is @code{nil}, no exception is defined.")
472 (setf (documentation 'pattern-params 'function)
473 "@arg[instance]{an instance of @class{data}}
474 @return{a list of parameters}
475 @short{fixme}
477 fixme: params aren't actually exported yet.")
479 (defstruct (not-allowed (:include %leaf))
480 "@short{This pattern specifies that the part of the schema reached at
481 this point is not valid.}")
484 ;;;; non-pattern
486 (defstruct (grammar (:constructor make-grammar (parent)))
487 (start nil)
488 parent
489 (definitions (make-hash-table :test 'equal)))
491 (defstruct param
492 name
493 string)
495 ;; Clark calls this structure "RefPattern"
496 (defstruct (definition (:conc-name "DEFN-"))
497 name
498 combine-method
499 head-p
500 redefinition
501 child)
504 ;;; name-class
506 (defun missing ()
507 (error "missing arg"))
509 (defstruct name-class
510 "@short{The abstract superclass of all name-related classes.}
512 Name classes represent sets of permissible names for an element or
513 attribute.
515 Names are pairs of namespace URI and local-name.
517 @see{attribute}
518 @see{element}")
520 (defstruct (any-name (:include name-class)
521 (:constructor make-any-name (except)))
522 "@short{This name class allows any name.}
524 Exceptions are given as @code{any-name-except}.
526 @see-slot{any-name-except}"
527 (except (missing) :type (or null name-class)))
529 (setf (documentation 'any-name-except 'function)
530 "@arg[instance]{an instance of @class{any-name}}
531 @return{a @class{name-class} or @code{nil}}
533 Return the name class @em{not} allowed by this @code{any-name},
534 or @code{nil} if there is no such exception.")
536 (defstruct (name (:include name-class)
537 (:constructor make-name (uri lname)))
538 "@short{This name class allows only a specific name.}
540 A specific namespace URI and local name are expected.
542 @see-slot{name-uri}
543 @see-slot{name-lname}"
544 (uri (missing) :type string)
545 (lname (missing) :type string))
547 (setf (documentation 'name-uri 'function)
548 "@arg[instance]{an instance of @class{name}}
549 @return{a string}
550 Return the expected namespace URI.")
552 (setf (documentation 'name-lname 'function)
553 "@arg[instance]{an instance of @class{name}}
554 @return{a string}
555 Return the expected local name.")
557 (defstruct (ns-name (:include name-class)
558 (:constructor make-ns-name (uri except)))
559 "@short{This name class allows all names in a specific namespace}, with
560 possible exceptions.
562 A specific namespace URI is expected.
564 Exceptions are given as @code{ns-name-except}.
566 @see-slot{ns-name-uri}
567 @see-slot{ns-name-except}"
568 (uri (missing) :type string)
569 (except (missing) :type (or null name-class)))
571 (setf (documentation 'ns-name-uri 'function)
572 "@arg[instance]{an instance of @class{ns-name}}
573 @return{a string}
574 Return the expected namespace URI.")
576 (setf (documentation 'ns-name-except 'function)
577 "@arg[instance]{an instance of @class{ns-name}}
578 @return{a @class{name-class} or @code{nil}}
580 Return the name class @em{not} allowed by this @code{ns-name},
581 or @code{nil} if there is no such exception.")
583 (defstruct (name-class-choice (:include name-class)
584 (:constructor make-name-class-choice (a b)))
585 "@short{This name class represents the union of two other name classes.}
587 @see-slot{name-class-choice-a}
588 @see-slot{name-class-choice-b}"
589 (a (missing) :type name-class)
590 (b (missing) :type name-class))
592 (setf (documentation 'name-class-choice-a 'function)
593 "@arg[instance]{an instance of @class{name-class-choice}}
594 @return{a @class{name-class}}
595 Returns the 'first' of two name classes that are allowed.
596 @see{name-class-choice-b}")
598 (setf (documentation 'name-class-choice-b 'function)
599 "@arg[instance]{an instance of @class{name-class-choice}}
600 @return{a @class{name-class}}
601 Returns the 'second' of two name classes that are allowed.
602 @see{name-class-choice-a}")
604 (defun simplify-nc-choice (values)
605 (zip #'make-name-class-choice values))
608 ;;;; parser
610 (defvar *rng-namespace* "http://relaxng.org/ns/structure/1.0")
612 (defun skip-foreign* (source)
613 (loop
614 (case (klacks:peek-next source)
615 (:start-element (skip-foreign source))
616 (:end-element (return)))))
618 (defun skip-to-native (source)
619 (loop
620 (case (klacks:peek source)
621 (:start-element
622 (when (equal (klacks:current-uri source) *rng-namespace*)
623 (return))
624 (klacks:serialize-element source nil))
625 (:end-element (return)))
626 (klacks:consume source)))
628 (defun consume-and-skip-to-native (source)
629 (klacks:consume source)
630 (skip-to-native source))
632 (defun skip-foreign (source)
633 (when (equal (klacks:current-uri source) *rng-namespace*)
634 (rng-error source
635 "invalid schema: ~A not allowed here"
636 (klacks:current-lname source)))
637 (klacks:serialize-element source nil))
639 (defun attribute (lname attrs)
640 "@unexport{}"
641 (let ((a (sax:find-attribute-ns "" lname attrs)))
642 (if a
643 (sax:attribute-value a)
644 nil)))
646 (defparameter *whitespace*
647 (format nil "~C~C~C~C"
648 (code-char 9)
649 (code-char 32)
650 (code-char 13)
651 (code-char 10)))
653 (defun ntc (lname source-or-attrs)
654 ;; used for (n)ame, (t)ype, and (c)ombine, this also strings whitespace
655 (let* ((attrs
656 (if (listp source-or-attrs)
657 source-or-attrs
658 (klacks:list-attributes source-or-attrs)))
659 (a (sax:find-attribute-ns "" lname attrs)))
660 (if a
661 (string-trim *whitespace* (sax:attribute-value a))
662 nil)))
664 (defmacro with-library-and-ns (attrs &body body)
665 `(invoke-with-library-and-ns (lambda () ,@body) ,attrs))
667 (defun invoke-with-library-and-ns (fn attrs)
668 (let* ((dl (attribute "datatypeLibrary" attrs))
669 (ns (attribute "ns" attrs))
670 (*datatype-library* (if dl (escape-uri dl) *datatype-library*))
671 (*namespace-uri* (or ns *namespace-uri*))
672 (*ns* ns))
673 ;; FIXME: Ganz boese gehackt -- gerade so, dass wir die Relax NG
674 ;; Test-Suite bestehen.
675 (when (and dl
676 (not (zerop (length *datatype-library*)))
677 ;; scheme pruefen, und es muss was folgen
678 (or (not (cl-ppcre:all-matches
679 "^[a-zA-Z][a-zA-Z0-9+.-]*:.+"
680 *datatype-library*))
681 ;; keine kaputten %te, keine #
682 (cl-ppcre:all-matches
683 "(%$|%.$|%[^0-9A-Fa-f][^0-9A-Fa-f]|#)"
684 *datatype-library*)))
685 (rng-error nil "malformed datatypeLibrary: ~A" *datatype-library*))
686 (funcall fn)))
688 (defun p/pattern (source)
689 (let* ((lname (klacks:current-lname source))
690 (attrs (klacks:list-attributes source)))
691 (with-library-and-ns attrs
692 (case (find-symbol lname :keyword)
693 (:|element| (p/element source (ntc "name" attrs)))
694 (:|attribute| (p/attribute source (ntc "name" attrs)))
695 (:|group| (p/combination #'groupify source))
696 (:|interleave| (p/combination #'interleave-ify source))
697 (:|choice| (p/combination #'choice-ify source))
698 (:|optional| (p/optional source))
699 (:|zeroOrMore| (p/zero-or-more source))
700 (:|oneOrMore| (p/one-or-more source))
701 (:|list| (p/list source))
702 (:|mixed| (p/mixed source))
703 (:|ref| (p/ref source))
704 (:|parentRef| (p/parent-ref source))
705 (:|empty| (p/empty source))
706 (:|text| (p/text source))
707 (:|value| (p/value source))
708 (:|data| (p/data source))
709 (:|notAllowed| (p/not-allowed source))
710 (:|externalRef| (p/external-ref source))
711 (:|grammar| (p/grammar source))
712 (t (skip-foreign source))))))
714 (defun p/pattern+ (source)
715 (let ((children nil))
716 (loop
717 (case (klacks:peek source)
718 (:start-element
719 (let ((p (p/pattern source))) (when p (push p children))))
720 (:end-element
721 (return))
723 (klacks:consume source))))
724 (unless children
725 (rng-error source "empty element"))
726 (nreverse children)))
728 (defun p/pattern? (source)
729 (let ((result nil))
730 (loop
731 (skip-to-native source)
732 (case (klacks:peek source)
733 (:start-element
734 (when result
735 (rng-error source "at most one pattern expected here"))
736 (setf result (p/pattern source)))
737 (:end-element
738 (return))
740 (klacks:consume source))))
741 result))
743 (defun p/element (source name)
744 (klacks:expecting-element (source "element")
745 (let ((elt (make-element)))
746 (consume-and-skip-to-native source)
747 (if name
748 (setf (pattern-name elt) (destructure-name source name))
749 (setf (pattern-name elt) (p/name-class source)))
750 (skip-to-native source)
751 (setf (pattern-child elt) (groupify (p/pattern+ source)))
752 (make-ref (make-definition :name (gensym "ANONYMOUS") :child elt)))))
754 (defvar *attribute-namespace-p* nil)
756 (defun p/attribute (source name)
757 (klacks:expecting-element (source "attribute")
758 (let ((result (make-attribute)))
759 (consume-and-skip-to-native source)
760 (if name
761 (setf (pattern-name result)
762 (let ((*namespace-uri* (or *ns* ""))
763 (*attribute-namespace-p* t))
764 (destructure-name source name)))
765 (setf (pattern-name result)
766 (let ((*attribute-namespace-p* t))
767 (p/name-class source))))
768 (skip-to-native source)
769 (setf (pattern-child result)
770 (or (p/pattern? source) (make-text)))
771 result)))
773 (defun p/combination (zipper source)
774 (klacks:expecting-element (source)
775 (consume-and-skip-to-native source)
776 (funcall zipper (p/pattern+ source))))
778 (defun p/one-or-more (source)
779 (klacks:expecting-element (source "oneOrMore")
780 (consume-and-skip-to-native source)
781 (let ((children (p/pattern+ source)))
782 (make-one-or-more (groupify children)))))
784 (defun p/zero-or-more (source)
785 (klacks:expecting-element (source "zeroOrMore")
786 (consume-and-skip-to-native source)
787 (let ((children (p/pattern+ source)))
788 (make-choice (make-one-or-more (groupify children))
789 (make-empty)))))
791 (defun p/optional (source)
792 (klacks:expecting-element (source "optional")
793 (consume-and-skip-to-native source)
794 (let ((children (p/pattern+ source)))
795 (make-choice (groupify children) (make-empty)))))
797 (defun p/list (source)
798 (klacks:expecting-element (source "list")
799 (consume-and-skip-to-native source)
800 (let ((children (p/pattern+ source)))
801 (make-list-pattern (groupify children)))))
803 (defun p/mixed (source)
804 (klacks:expecting-element (source "mixed")
805 (consume-and-skip-to-native source)
806 (let ((children (p/pattern+ source)))
807 (make-interleave (groupify children) (make-text)))))
809 (defun p/ref (source)
810 (klacks:expecting-element (source "ref")
811 (prog1
812 (let* ((name (ntc "name" source))
813 (pdefinition
814 (or (find-definition name)
815 (setf (find-definition name)
816 (make-definition :name name :child nil)))))
817 (make-ref pdefinition))
818 (skip-foreign* source))))
820 (defun p/parent-ref (source)
821 (klacks:expecting-element (source "parentRef")
822 (prog1
823 (let* ((name (ntc "name" source))
824 (grammar (grammar-parent *grammar*))
825 (pdefinition
826 (or (find-definition name grammar)
827 (setf (find-definition name grammar)
828 (make-definition :name name :child nil)))))
829 (make-ref pdefinition))
830 (skip-foreign* source))))
832 (defun p/empty (source)
833 (klacks:expecting-element (source "empty")
834 (skip-foreign* source)
835 (make-empty)))
837 (defun p/text (source)
838 (klacks:expecting-element (source "text")
839 (skip-foreign* source)
840 (make-text)))
842 (defun consume-and-parse-characters (source)
843 ;; fixme
844 (let ((tmp ""))
845 (loop
846 (multiple-value-bind (key data) (klacks:peek-next source)
847 (case key
848 (:characters
849 (setf tmp (concatenate 'string tmp data)))
850 (:end-element (return)))))
851 tmp))
853 (defun p/value (source)
854 (klacks:expecting-element (source "value")
855 (let* ((type (ntc "type" source))
856 (string (consume-and-parse-characters source))
857 (ns *namespace-uri*)
858 (dl *datatype-library*))
859 (unless type
860 (setf type "token")
861 (setf dl ""))
862 (let ((data-type
863 (cxml-types:find-type (and dl (find-symbol dl :keyword)) type))
864 (vc (cxml-types:make-klacks-validation-context source)))
865 (unless data-type
866 (rng-error source "type not found: ~A/~A" type dl))
867 (make-value :string string
868 :value (cxml-types:parse data-type string vc)
869 :type data-type
870 :ns ns)))))
872 (defun p/data (source)
873 (klacks:expecting-element (source "data")
874 (let* ((type (ntc "type" source))
875 (params '())
876 (except nil))
877 (loop
878 (multiple-value-bind (key uri lname)
879 (klacks:peek-next source)
881 (case key
882 (:start-element
883 (case (find-symbol lname :keyword)
884 (:|param| (push (p/param source) params))
885 (:|except|
886 (setf except (p/except-pattern source))
887 (skip-to-native source)
888 (return))
889 (t (skip-foreign source))))
890 (:end-element
891 (return)))))
892 (setf params (nreverse params))
893 (let* ((dl *datatype-library*)
894 (data-type (apply #'cxml-types:find-type
895 (and dl (find-symbol dl :keyword))
896 type
897 (loop
898 for p in params
899 collect (find-symbol (param-name p)
900 :keyword)
901 collect (param-string p)))))
902 (unless data-type
903 (rng-error source "type not found: ~A/~A" type dl))
904 (make-data
905 :type data-type
906 :params params
907 :except except)))))
909 (defun p/param (source)
910 (klacks:expecting-element (source "param")
911 (let ((name (ntc "name" source))
912 (string (consume-and-parse-characters source)))
913 (make-param :name name :string string))))
915 (defun p/except-pattern (source)
916 (klacks:expecting-element (source "except")
917 (with-library-and-ns (klacks:list-attributes source)
918 (klacks:consume source)
919 (choice-ify (p/pattern+ source)))))
921 (defun p/not-allowed (source)
922 (klacks:expecting-element (source "notAllowed")
923 (consume-and-skip-to-native source)
924 (make-not-allowed)))
926 (defun safe-parse-uri (source str &optional base)
927 (when (zerop (length str))
928 (rng-error source "missing URI"))
929 (let* ((compactp (rnc-uri-p str))
930 (str (if compactp (follow-rnc-uri str) str))
931 (uri
932 (handler-case
933 (if base
934 (puri:merge-uris str base)
935 (puri:parse-uri str))
936 (puri:uri-parse-error ()
937 (rng-error source "invalid URI: ~A" str)))))
938 (when (and (eq (puri:uri-scheme uri) :file)
939 (puri:uri-fragment uri))
940 (rng-error source "Forbidden fragment in URI: ~A" str))
941 (values uri compactp)))
943 (defun named-string-xstream (str uri)
944 (let ((xstream (cxml::string->xstream str)))
945 (setf (cxml::xstream-name xstream)
946 (cxml::make-stream-name
947 :entity-name "main document"
948 :entity-kind :main
949 :uri uri))
950 xstream))
952 (defun xstream-open-schema (uri compactp)
953 (if compactp
954 (named-string-xstream
955 (uncompact-file
956 ;; fixme: Hier waere es schon, mit *entity-resolver* arbeiten
957 ;; zu koennen, aber der liefert binaere Streams.
958 (open (cxml::uri-to-pathname uri)
959 :element-type 'character
960 :direction :input))
961 uri)
962 (cxml::xstream-open-extid* *entity-resolver* nil uri)))
964 (defun p/external-ref (source)
965 (klacks:expecting-element (source "externalRef")
966 (let* ((href
967 (escape-uri (attribute "href" (klacks:list-attributes source))))
968 (base (klacks:current-xml-base source)))
969 (multiple-value-bind (uri compactp)
970 (safe-parse-uri source href base)
971 (when (find uri *include-uri-stack* :test #'puri:uri=)
972 (rng-error source "looping include"))
973 (prog1
974 (let* ((*include-uri-stack* (cons uri *include-uri-stack*))
975 (xstream (xstream-open-schema uri compactp)))
976 (klacks:with-open-source
977 (source (make-validating-source xstream))
978 (invoke-with-klacks-handler
979 (lambda ()
980 (klacks:find-event source :start-element)
981 (let ((*datatype-library* ""))
982 (p/pattern source)))
983 source)))
984 (skip-foreign* source))))))
986 (defun p/grammar (source &optional grammar)
987 (klacks:expecting-element (source "grammar")
988 (consume-and-skip-to-native source)
989 (let ((*grammar* (or grammar (make-grammar *grammar*)))
990 (includep grammar))
991 (process-grammar-content* source)
992 (unless (or includep (grammar-start *grammar*))
993 (rng-error source "no <start> in grammar"))
994 (unless includep
995 (check-pattern-definitions source *grammar*)
996 (defn-child (grammar-start *grammar*))))))
998 (defvar *include-start*)
999 (defvar *include-definitions*)
1001 (defun process-grammar-content* (source &key disallow-include)
1002 (loop
1003 (multiple-value-bind (key uri lname) (klacks:peek source)
1005 (ecase key
1006 (:characters
1007 (klacks:consume source))
1008 (:start-element
1009 (with-library-and-ns (klacks:list-attributes source)
1010 (case (find-symbol lname :keyword)
1011 (:|start|
1012 (process-start source))
1013 (:|define| (process-define source))
1014 (:|div| (process-div source))
1015 (:|include|
1016 (when disallow-include
1017 (rng-error source "nested include not permitted"))
1018 (process-include source))
1020 (skip-foreign source)))))
1021 (:end-element
1022 (return))))))
1024 (defun process-start (source)
1025 (klacks:expecting-element (source "start")
1026 (let* ((combine0 (ntc "combine" source))
1027 (combine
1028 (when combine0
1029 (find-symbol (string-upcase combine0) :keyword)))
1030 (child
1031 (progn
1032 (consume-and-skip-to-native source)
1033 (p/pattern source)))
1034 (pdefinition (grammar-start *grammar*)))
1035 (skip-foreign* source)
1036 ;; fixme: shared code with process-define
1037 (unless pdefinition
1038 (setf pdefinition (make-definition :name :start :child nil))
1039 (setf (grammar-start *grammar*) pdefinition))
1040 (when *include-body-p*
1041 (setf *include-start* pdefinition))
1042 (cond
1043 ((defn-child pdefinition)
1044 (ecase (defn-redefinition pdefinition)
1045 (:not-being-redefined
1046 (when (and combine
1047 (defn-combine-method pdefinition)
1048 (not (eq combine
1049 (defn-combine-method pdefinition))))
1050 (rng-error source "conflicting combine values for <start>"))
1051 (unless combine
1052 (when (defn-head-p pdefinition)
1053 (rng-error source "multiple definitions for <start>"))
1054 (setf (defn-head-p pdefinition) t))
1055 (unless (defn-combine-method pdefinition)
1056 (setf (defn-combine-method pdefinition) combine))
1057 (setf (defn-child pdefinition)
1058 (case (defn-combine-method pdefinition)
1059 (:choice
1060 (make-choice (defn-child pdefinition) child))
1061 (:interleave
1062 (make-interleave (defn-child pdefinition) child)))))
1063 (:being-redefined-and-no-original
1064 (setf (defn-redefinition pdefinition)
1065 :being-redefined-and-original))
1066 (:being-redefined-and-original)))
1068 (setf (defn-child pdefinition) child)
1069 (setf (defn-combine-method pdefinition) combine)
1070 (setf (defn-head-p pdefinition) (null combine))
1071 (setf (defn-redefinition pdefinition) :not-being-redefined))))))
1073 (defun zip (constructor children)
1074 (cond
1075 ((null children)
1076 (rng-error nil "empty choice?"))
1077 ((null (cdr children))
1078 (car children))
1080 (destructuring-bind (a b &rest rest)
1081 children
1082 (zip constructor (cons (funcall constructor a b) rest))))))
1084 (defun choice-ify (children) (zip #'make-choice children))
1085 (defun groupify (children) (zip #'make-group children))
1086 (defun interleave-ify (children) (zip #'make-interleave children))
1088 (defun find-definition (name &optional (grammar *grammar*))
1089 (gethash name (grammar-definitions grammar)))
1091 (defun (setf find-definition) (newval name &optional (grammar *grammar*))
1092 (setf (gethash name (grammar-definitions grammar)) newval))
1094 (defun process-define (source)
1095 (klacks:expecting-element (source "define")
1096 (let* ((name (ntc "name" source))
1097 (combine0 (ntc "combine" source))
1098 (combine (when combine0
1099 (find-symbol (string-upcase combine0) :keyword)))
1100 (child (groupify
1101 (progn
1102 (consume-and-skip-to-native source)
1103 (p/pattern+ source))))
1104 (pdefinition (find-definition name)))
1105 (unless pdefinition
1106 (setf pdefinition (make-definition :name name :child nil))
1107 (setf (find-definition name) pdefinition))
1108 (when *include-body-p*
1109 (push pdefinition *include-definitions*))
1110 (cond
1111 ((defn-child pdefinition)
1112 (case (defn-redefinition pdefinition)
1113 (:not-being-redefined
1114 (when (and combine
1115 (defn-combine-method pdefinition)
1116 (not (eq combine
1117 (defn-combine-method pdefinition))))
1118 (rng-error source "conflicting combine values for ~A" name))
1119 (unless combine
1120 (when (defn-head-p pdefinition)
1121 (rng-error source "multiple definitions for ~A" name))
1122 (setf (defn-head-p pdefinition) t))
1123 (unless (defn-combine-method pdefinition)
1124 (setf (defn-combine-method pdefinition) combine))
1125 (setf (defn-child pdefinition)
1126 (case (defn-combine-method pdefinition)
1127 (:choice
1128 (make-choice (defn-child pdefinition) child))
1129 (:interleave
1130 (make-interleave (defn-child pdefinition) child)))))
1131 (:being-redefined-and-no-original
1132 (setf (defn-redefinition pdefinition)
1133 :being-redefined-and-original))
1134 (:being-redefined-and-original)))
1136 (setf (defn-child pdefinition) child)
1137 (setf (defn-combine-method pdefinition) combine)
1138 (setf (defn-head-p pdefinition) (null combine))
1139 (setf (defn-redefinition pdefinition) :not-being-redefined))))))
1141 (defun process-div (source)
1142 (klacks:expecting-element (source "div")
1143 (consume-and-skip-to-native source)
1144 (process-grammar-content* source)))
1146 (defun reset-definition-for-include (defn)
1147 (setf (defn-combine-method defn) nil)
1148 (setf (defn-redefinition defn) :being-redefined-and-no-original)
1149 (setf (defn-head-p defn) nil))
1151 (defun restore-definition (defn original)
1152 (setf (defn-combine-method defn) (defn-combine-method original))
1153 (setf (defn-redefinition defn) (defn-redefinition original))
1154 (setf (defn-head-p defn) (defn-head-p original)))
1156 (defun process-include (source)
1157 (klacks:expecting-element (source "include")
1158 (let* ((href
1159 (escape-uri (attribute "href" (klacks:list-attributes source))))
1160 (base (klacks:current-xml-base source))
1161 (*include-start* nil)
1162 (*include-definitions* '()))
1163 (multiple-value-bind (uri compactp)
1164 (safe-parse-uri source href base)
1165 (consume-and-skip-to-native source)
1166 (let ((*include-body-p* t))
1167 (process-grammar-content* source :disallow-include t))
1168 (let ((tmp-start
1169 (when *include-start*
1170 (prog1
1171 (copy-structure *include-start*)
1172 (reset-definition-for-include *include-start*))))
1173 (tmp-defns
1174 (loop
1175 for defn in *include-definitions*
1176 collect
1177 (prog1
1178 (copy-structure defn)
1179 (reset-definition-for-include defn)))))
1180 (when (find uri *include-uri-stack* :test #'puri:uri=)
1181 (rng-error source "looping include"))
1182 (let* ((*include-uri-stack* (cons uri *include-uri-stack*))
1183 (xstream (xstream-open-schema uri compactp)))
1184 (klacks:with-open-source (source (make-validating-source xstream))
1185 (invoke-with-klacks-handler
1186 (lambda ()
1187 (klacks:find-event source :start-element)
1188 (let ((*datatype-library* ""))
1189 (p/grammar source *grammar*)))
1190 source))
1191 (when tmp-start
1192 (when (eq (defn-redefinition *include-start*)
1193 :being-redefined-and-no-original)
1194 (rng-error source "start not found in redefinition of grammar"))
1195 (restore-definition *include-start* tmp-start))
1196 (dolist (copy tmp-defns)
1197 (let ((defn (gethash (defn-name copy)
1198 (grammar-definitions *grammar*))))
1199 (when (eq (defn-redefinition defn)
1200 :being-redefined-and-no-original)
1201 (rng-error source "redefinition not found in grammar"))
1202 (restore-definition defn copy)))
1203 nil))))))
1205 (defun check-pattern-definitions (source grammar)
1206 (when (and (grammar-start grammar)
1207 (eq (defn-redefinition (grammar-start grammar))
1208 :being-redefined-and-no-original))
1209 (rng-error source "start not found in redefinition of grammar"))
1210 (loop for defn being each hash-value in (grammar-definitions grammar) do
1211 (when (eq (defn-redefinition defn) :being-redefined-and-no-original)
1212 (rng-error source "redefinition not found in grammar"))
1213 (unless (defn-child defn)
1214 (rng-error source "unresolved reference to ~A" (defn-name defn)))))
1216 (defvar *any-name-allowed-p* t)
1217 (defvar *ns-name-allowed-p* t)
1219 (defun destructure-name (source qname)
1220 (multiple-value-bind (uri lname)
1221 (klacks:decode-qname qname source)
1222 (setf uri (or uri *namespace-uri*))
1223 (when (and *attribute-namespace-p*
1224 (or (and (equal lname "xmlns") (equal uri ""))
1225 (equal uri "http://www.w3.org/2000/xmlns")))
1226 (rng-error source "namespace attribute not permitted"))
1227 (make-name uri lname)))
1229 (defun p/name-class (source)
1230 (klacks:expecting-element (source)
1231 (with-library-and-ns (klacks:list-attributes source)
1232 (case (find-symbol (klacks:current-lname source) :keyword)
1233 (:|name|
1234 (let ((qname (string-trim *whitespace*
1235 (consume-and-parse-characters source))))
1236 (destructure-name source qname)))
1237 (:|anyName|
1238 (unless *any-name-allowed-p*
1239 (rng-error source "anyname not permitted in except"))
1240 (klacks:consume source)
1241 (prog1
1242 (let ((*any-name-allowed-p* nil))
1243 (make-any-name (p/except-name-class? source)))
1244 (skip-to-native source)))
1245 (:|nsName|
1246 (unless *ns-name-allowed-p*
1247 (rng-error source "nsname not permitted in except"))
1248 (let ((uri *namespace-uri*)
1249 (*any-name-allowed-p* nil)
1250 (*ns-name-allowed-p* nil))
1251 (when (and *attribute-namespace-p*
1252 (equal uri "http://www.w3.org/2000/xmlns"))
1253 (rng-error source "namespace attribute not permitted"))
1254 (klacks:consume source)
1255 (prog1
1256 (make-ns-name uri (p/except-name-class? source))
1257 (skip-to-native source))))
1258 (:|choice|
1259 (klacks:consume source)
1260 (simplify-nc-choice (p/name-class* source)))
1262 (rng-error source "invalid child in except"))))))
1264 (defun p/name-class* (source)
1265 (let ((results nil))
1266 (loop
1267 (skip-to-native source)
1268 (case (klacks:peek source)
1269 (:characters
1270 (klacks:consume source))
1271 (:start-element
1272 (push (p/name-class source) results))
1273 (:end-element
1274 (return))))
1275 (nreverse results)))
1277 (defun p/except-name-class? (source)
1278 (skip-to-native source)
1279 (multiple-value-bind (key uri lname)
1280 (klacks:peek source)
1282 (if (and (eq key :start-element)
1283 (string= (find-symbol lname :keyword) "except"))
1284 (p/except-name-class source)
1285 nil)))
1287 (defun p/except-name-class (source)
1288 (klacks:expecting-element (source "except")
1289 (with-library-and-ns (klacks:list-attributes source)
1290 (klacks:consume source)
1291 (let ((x (p/name-class* source)))
1292 (if (cdr x)
1293 (simplify-nc-choice x)
1294 (car x))))))
1296 (defun escape-uri (string)
1297 (with-output-to-string (out)
1298 (loop for c across (cxml::rod-to-utf8-string string) do
1299 (let ((code (char-code c)))
1300 ;; http://www.w3.org/TR/xlink/#link-locators
1301 (if (or (>= code 127) (<= code 32) (find c "<>\"{}|\\^`"))
1302 (format out "%~2,'0X" code)
1303 (write-char c out))))))
1306 ;;;; unparsing
1308 (defvar *definitions-to-names*)
1309 (defvar *seen-names*)
1311 (defun serialization-name (defn)
1312 (or (gethash defn *definitions-to-names*)
1313 (setf (gethash defn *definitions-to-names*)
1314 (let ((name (if (gethash (defn-name defn) *seen-names*)
1315 (format nil "~A-~D"
1316 (defn-name defn)
1317 (hash-table-count *seen-names*))
1318 (defn-name defn))))
1319 (setf (gethash name *seen-names*) defn)
1320 name))))
1322 (defun serialize-schema (schema sink)
1323 "@arg[schema]{a Relax NG @class{schema}}
1324 @arg[sink]{a SAX handler}
1325 @return{the result of @code{sax:end-document}}
1326 @short{This function serializes a parsed Relax NG back into XML syntax.}
1328 Note that the schema represented in memory has gone through simplification
1329 as is textually different from the original XML document.
1331 @see{parse-schema}"
1332 (cxml:with-xml-output sink
1333 (let ((*definitions-to-names* (make-hash-table))
1334 (*seen-names* (make-hash-table :test 'equal)))
1335 (cxml:with-element "grammar"
1336 (cxml:with-element "start"
1337 (serialize-pattern (schema-start schema)))
1338 (loop for defn being each hash-key in *definitions-to-names* do
1339 (serialize-definition defn))))))
1341 (defun serialize-pattern (pattern)
1342 (etypecase pattern
1343 (element
1344 (cxml:with-element "element"
1345 (serialize-name (pattern-name pattern))
1346 (serialize-pattern (pattern-child pattern))))
1347 (attribute
1348 (cxml:with-element "attribute"
1349 (serialize-name (pattern-name pattern))
1350 (serialize-pattern (pattern-child pattern))))
1351 (%combination
1352 (cxml:with-element
1353 (etypecase pattern
1354 (group "group")
1355 (interleave "interleave")
1356 (choice "choice"))
1357 (serialize-pattern (pattern-a pattern))
1358 (serialize-pattern (pattern-b pattern))))
1359 (one-or-more
1360 (cxml:with-element "oneOrMore"
1361 (serialize-pattern (pattern-child pattern))))
1362 (list-pattern
1363 (cxml:with-element "list"
1364 (serialize-pattern (pattern-child pattern))))
1365 (ref
1366 (cxml:with-element "ref"
1367 (cxml:attribute "name" (serialization-name (pattern-target pattern)))))
1368 (empty
1369 (cxml:with-element "empty"))
1370 (not-allowed
1371 (cxml:with-element "notAllowed"))
1372 (text
1373 (cxml:with-element "text"))
1374 (value
1375 (cxml:with-element "value"
1376 (let ((type (pattern-type pattern)))
1377 (cxml:attribute "datatype-library"
1378 (symbol-name (cxml-types:type-library type)))
1379 (cxml:attribute "type" (cxml-types:type-name type)))
1380 (cxml:attribute "ns" (pattern-ns pattern))
1381 (cxml:text (pattern-string pattern))))
1382 (data
1383 (cxml:with-element "value"
1384 (let ((type (pattern-type pattern)))
1385 (cxml:attribute "datatype-library"
1386 (symbol-name (cxml-types:type-library type)))
1387 (cxml:attribute "type" (cxml-types:type-name type)))
1388 (dolist (param (pattern-params pattern))
1389 (cxml:with-element "param"
1390 (cxml:attribute "name" (param-name param))
1391 (cxml:text (param-string param))))
1392 (when (pattern-except pattern)
1393 (cxml:with-element "except"
1394 (serialize-pattern (pattern-except pattern))))))))
1396 (defun serialize-definition (defn)
1397 (cxml:with-element "define"
1398 (cxml:attribute "name" (serialization-name defn))
1399 (serialize-pattern (defn-child defn))))
1401 (defun serialize-name (name)
1402 (etypecase name
1403 (name
1404 (cxml:with-element "name"
1405 (cxml:attribute "ns" (name-uri name))
1406 (cxml:text (name-lname name))))
1407 (any-name
1408 (cxml:with-element "anyName"
1409 (when (any-name-except name)
1410 (serialize-except-name (any-name-except name)))))
1411 (ns-name
1412 (cxml:with-element "anyName"
1413 (cxml:attribute "ns" (ns-name-uri name))
1414 (when (ns-name-except name)
1415 (serialize-except-name (ns-name-except name)))))
1416 (name-class-choice
1417 (cxml:with-element "choice"
1418 (serialize-name (name-class-choice-a name))
1419 (serialize-name (name-class-choice-b name))))))
1421 (defun serialize-except-name (spec)
1422 (cxml:with-element "except"
1423 (serialize-name spec)))
1426 ;;;; simplification
1428 ;;; 4.1 Annotations
1429 ;;; Foreign attributes and elements are removed implicitly while parsing.
1431 ;;; 4.2 Whitespace
1432 ;;; All character data is discarded while parsing (which can only be
1433 ;;; whitespace after validation).
1435 ;;; Whitespace in name, type, and combine attributes is stripped while
1436 ;;; parsing. Ditto for <name/>.
1438 ;;; 4.3. datatypeLibrary attribute
1439 ;;; Escaping is done by p/pattern.
1440 ;;; Attribute value defaulting is done using *datatype-library*; only
1441 ;;; p/data and p/value record the computed value.
1443 ;;; 4.4. type attribute of value element
1444 ;;; Done by p/value.
1446 ;;; 4.5. href attribute
1447 ;;; Escaping is done by process-include and p/external-ref.
1449 ;;; FIXME: Mime-type handling should be the job of the entity resolver,
1450 ;;; but that requires xstream hacking.
1452 ;;; 4.6. externalRef element
1453 ;;; Done by p/external-ref.
1455 ;;; 4.7. include element
1456 ;;; Done by process-include.
1458 ;;; 4.8. name attribute of element and attribute elements
1459 ;;; `name' is stored as a slot, not a child. Done by p/element and
1460 ;;; p/attribute.
1462 ;;; 4.9. ns attribute
1463 ;;; done by p/name-class, p/value, p/element, p/attribute
1465 ;;; 4.10. QNames
1466 ;;; done by p/name-class
1468 ;;; 4.11. div element
1469 ;;; Legen wir gar nicht erst an.
1471 ;;; 4.12. 4.13 4.14 4.15
1472 ;;; beim anlegen
1474 ;;; 4.16
1475 ;;; p/name-class
1476 ;;; -- ausser der sache mit den datentypen
1478 ;;; 4.17, 4.18, 4.19
1479 ;;; Ueber die Grammar-und Definition Objekte, wie von James Clark
1480 ;;; beschrieben.
1482 ;;; Dabei werden keine Umbenennungen vorgenommen, weil Referenzierung
1483 ;;; durch Aufbei der Graphenstruktur zwischen ref und Definition
1484 ;;; erfolgt und Namen dann bereits aufgeloest sind. Wir benennen
1485 ;;; dafuer beim Serialisieren um.
1487 (defmethod check-recursion ((pattern element) depth)
1488 (check-recursion (pattern-child pattern) (1+ depth)))
1490 (defmethod check-recursion ((pattern ref) depth)
1491 (when (eql (pattern-crdepth pattern) depth)
1492 (rng-error nil "infinite recursion in ~A"
1493 (defn-name (pattern-target pattern))))
1494 (when (null (pattern-crdepth pattern))
1495 (setf (pattern-crdepth pattern) depth)
1496 (check-recursion (defn-child (pattern-target pattern)) depth)
1497 (setf (pattern-crdepth pattern) t)))
1499 (defmethod check-recursion ((pattern %parent) depth)
1500 (check-recursion (pattern-child pattern) depth))
1502 (defmethod check-recursion ((pattern %combination) depth)
1503 (check-recursion (pattern-a pattern) depth)
1504 (check-recursion (pattern-b pattern) depth))
1506 (defmethod check-recursion ((pattern %leaf) depth)
1507 (declare (ignore depth)))
1509 (defmethod check-recursion ((pattern data) depth)
1510 (when (pattern-except pattern)
1511 (check-recursion (pattern-except pattern) depth)))
1514 ;;;; 4.20
1516 ;;; %PARENT
1518 (defmethod fold-not-allowed ((pattern element))
1519 (setf (pattern-child pattern) (fold-not-allowed (pattern-child pattern)))
1520 pattern)
1522 (defmethod fold-not-allowed ((pattern %parent))
1523 (setf (pattern-child pattern) (fold-not-allowed (pattern-child pattern)))
1524 (if (typep (pattern-child pattern) 'not-allowed)
1525 (pattern-child pattern)
1526 pattern))
1528 ;;; %COMBINATION
1530 (defmethod fold-not-allowed ((pattern %combination))
1531 (setf (pattern-a pattern) (fold-not-allowed (pattern-a pattern)))
1532 (setf (pattern-b pattern) (fold-not-allowed (pattern-b pattern)))
1533 pattern)
1535 (defmethod fold-not-allowed ((pattern group))
1536 (call-next-method)
1537 (cond
1538 ;; remove if any child is not allowed
1539 ((typep (pattern-a pattern) 'not-allowed) (pattern-a pattern))
1540 ((typep (pattern-b pattern) 'not-allowed) (pattern-b pattern))
1541 (t pattern)))
1543 (defmethod fold-not-allowed ((pattern interleave))
1544 (call-next-method)
1545 (cond
1546 ;; remove if any child is not allowed
1547 ((typep (pattern-a pattern) 'not-allowed) (pattern-a pattern))
1548 ((typep (pattern-b pattern) 'not-allowed) (pattern-b pattern))
1549 (t pattern)))
1551 (defmethod fold-not-allowed ((pattern choice))
1552 (call-next-method)
1553 (cond
1554 ;; if any child is not allowed, choose the other
1555 ((typep (pattern-a pattern) 'not-allowed) (pattern-b pattern))
1556 ((typep (pattern-b pattern) 'not-allowed) (pattern-a pattern))
1557 (t pattern)))
1559 ;;; LEAF
1561 (defmethod fold-not-allowed ((pattern %leaf))
1562 pattern)
1564 (defmethod fold-not-allowed ((pattern data))
1565 (when (pattern-except pattern)
1566 (setf (pattern-except pattern) (fold-not-allowed (pattern-except pattern)))
1567 (when (typep (pattern-except pattern) 'not-allowed)
1568 (setf (pattern-except pattern) nil)))
1569 pattern)
1571 ;;; REF
1573 (defmethod fold-not-allowed ((pattern ref))
1574 pattern)
1577 ;;;; 4.21
1579 ;;; %PARENT
1581 (defmethod fold-empty ((pattern one-or-more))
1582 (call-next-method)
1583 (if (typep (pattern-child pattern) 'empty)
1584 (pattern-child pattern)
1585 pattern))
1587 (defmethod fold-empty ((pattern %parent))
1588 (setf (pattern-child pattern) (fold-empty (pattern-child pattern)))
1589 pattern)
1591 ;;; %COMBINATION
1593 (defmethod fold-empty ((pattern %combination))
1594 (setf (pattern-a pattern) (fold-empty (pattern-a pattern)))
1595 (setf (pattern-b pattern) (fold-empty (pattern-b pattern)))
1596 pattern)
1598 (defmethod fold-empty ((pattern group))
1599 (call-next-method)
1600 (cond
1601 ;; if any child is empty, choose the other
1602 ((typep (pattern-a pattern) 'empty) (pattern-b pattern))
1603 ((typep (pattern-b pattern) 'empty) (pattern-a pattern))
1604 (t pattern)))
1606 (defmethod fold-empty ((pattern interleave))
1607 (call-next-method)
1608 (cond
1609 ;; if any child is empty, choose the other
1610 ((typep (pattern-a pattern) 'empty) (pattern-b pattern))
1611 ((typep (pattern-b pattern) 'empty) (pattern-a pattern))
1612 (t pattern)))
1614 (defmethod fold-empty ((pattern choice))
1615 (call-next-method)
1616 (if (typep (pattern-b pattern) 'empty)
1617 (cond
1618 ((typep (pattern-a pattern) 'empty)
1619 (pattern-a pattern))
1621 (rotatef (pattern-a pattern) (pattern-b pattern))
1622 pattern))
1623 pattern))
1625 ;;; LEAF
1627 (defmethod fold-empty ((pattern %leaf))
1628 pattern)
1630 (defmethod fold-empty ((pattern data))
1631 (when (pattern-except pattern)
1632 (setf (pattern-except pattern) (fold-empty (pattern-except pattern))))
1633 pattern)
1635 ;;; REF
1637 (defmethod fold-empty ((pattern ref))
1638 pattern)
1641 ;;;; name class overlap
1643 ;;; fixme: memorize this stuff?
1645 (defparameter !uri (string (code-char 1)))
1646 (defparameter !lname "")
1648 (defun classes-overlap-p (nc1 nc2)
1649 (flet ((both-contain (x)
1650 (and (contains nc1 (car x) (cdr x))
1651 (contains nc2 (car x) (cdr x)))))
1652 (or (some #'both-contain (representatives nc1))
1653 (some #'both-contain (representatives nc2)))))
1655 (defmethod representatives ((nc any-name))
1656 (cons (cons !uri !lname)
1657 (if (any-name-except nc)
1658 (representatives (any-name-except nc))
1659 nil)))
1661 (defmethod representatives ((nc ns-name))
1662 (cons (cons (ns-name-uri nc) !lname)
1663 (if (ns-name-except nc)
1664 (representatives (ns-name-except nc))
1665 nil)))
1667 (defmethod representatives ((nc name))
1668 (list (cons (name-uri nc) (name-lname nc))))
1670 (defmethod representatives ((nc name-class-choice))
1671 (nconc (representatives (name-class-choice-a nc))
1672 (representatives (name-class-choice-b nc))))
1675 ;;;; 7.1
1677 (defun finalize-definitions (pattern)
1678 (let ((defns (make-hash-table)))
1679 (labels ((recurse (p)
1680 (cond
1681 ((typep p 'ref)
1682 (let ((target (pattern-target p)))
1683 (unless (gethash target defns)
1684 (setf (gethash target defns) t)
1685 (setf (defn-child target) (recurse (defn-child target))))
1686 (if (typep (defn-child target) 'element)
1688 (copy-pattern-tree (defn-child target)))))
1690 (etypecase p
1691 (data
1692 (when (pattern-except p)
1693 (setf (pattern-except p) (recurse (pattern-except p)))))
1694 (%parent
1695 (setf (pattern-child p) (recurse (pattern-child p))))
1696 (%combination
1697 (setf (pattern-a p) (recurse (pattern-a p)))
1698 (setf (pattern-b p) (recurse (pattern-b p))))
1699 (%leaf))
1700 p))))
1701 (values
1702 (recurse pattern)
1703 (loop
1704 for defn being each hash-key in defns
1705 collect defn)))))
1707 (defun copy-pattern-tree (pattern)
1708 (labels ((recurse (p)
1709 (let ((q (copy-structure p)))
1710 (etypecase p
1711 (data
1712 (when (pattern-except p)
1713 (setf (pattern-except q) (recurse (pattern-except p)))))
1714 (%parent
1715 (setf (pattern-child q) (recurse (pattern-child p))))
1716 (%combination
1717 (setf (pattern-a q) (recurse (pattern-a p)))
1718 (setf (pattern-b q) (recurse (pattern-b p))))
1719 ((or %leaf ref)))
1720 q)))
1721 (recurse pattern)))
1723 (defparameter *in-attribute-p* nil)
1724 (defparameter *in-one-or-more-p* nil)
1725 (defparameter *in-one-or-more//group-or-interleave-p* nil)
1726 (defparameter *in-list-p* nil)
1727 (defparameter *in-data-except-p* nil)
1728 (defparameter *in-start-p* nil)
1730 (defun check-start-restrictions (pattern)
1731 (let ((*in-start-p* t))
1732 (check-restrictions pattern)))
1734 (defun content-type-max (a b)
1735 (if (and a b)
1736 (cond
1737 ((eq a :empty) b)
1738 ((eq b :empty) a)
1739 ((eq a :complex) b)
1740 (:simple))
1741 nil))
1743 (defun groupable-max (a b)
1744 (if (or (eq a :empty)
1745 (eq b :empty)
1746 (and (eq a :complex)
1747 (eq b :complex)))
1748 (content-type-max a b)
1749 nil))
1751 (defun assert-name-class-finite (nc)
1752 (etypecase nc
1753 ((or any-name ns-name)
1754 (rng-error nil "infinite attribute name class outside of one-or-more"))
1755 (name)
1756 (name-class-choice
1757 (assert-name-class-finite (name-class-choice-a nc))
1758 (assert-name-class-finite (name-class-choice-b nc)))))
1760 (defmethod check-restrictions ((pattern attribute))
1761 (when *in-attribute-p*
1762 (rng-error nil "nested attribute not allowed"))
1763 (when *in-one-or-more//group-or-interleave-p*
1764 (rng-error nil "attribute not allowed in oneOrMore//group, oneOrMore//interleave"))
1765 (when *in-list-p*
1766 (rng-error nil "attribute in list not allowed"))
1767 (when *in-data-except-p*
1768 (rng-error nil "attribute in data/except not allowed"))
1769 (when *in-start-p*
1770 (rng-error nil "attribute in start not allowed"))
1771 (let ((*in-attribute-p* t))
1772 (unless *in-one-or-more-p*
1773 (assert-name-class-finite (pattern-name pattern)))
1774 (values (if (check-restrictions (pattern-child pattern))
1775 :empty
1776 nil)
1777 (list (pattern-name pattern))
1778 nil)))
1780 (defmethod check-restrictions ((pattern ref))
1781 (when *in-attribute-p*
1782 (rng-error nil "ref in attribute not allowed"))
1783 (when *in-list-p*
1784 (rng-error nil "ref in list not allowed"))
1785 (when *in-data-except-p*
1786 (rng-error nil "ref in data/except not allowed"))
1787 (values :complex
1789 (list (pattern-name (defn-child (pattern-target pattern))))
1790 nil))
1792 (defmethod check-restrictions ((pattern one-or-more))
1793 (when *in-data-except-p*
1794 (rng-error nil "oneOrMore in data/except not allowed"))
1795 (when *in-start-p*
1796 (rng-error nil "one-or-more in start not allowed"))
1797 (let* ((*in-one-or-more-p* t))
1798 (multiple-value-bind (x a e textp)
1799 (check-restrictions (pattern-child pattern))
1800 (values (groupable-max x x) a e textp))))
1802 (defmethod check-restrictions ((pattern group))
1803 (when *in-data-except-p*
1804 (rng-error nil "group in data/except not allowed"))
1805 (when *in-start-p*
1806 (rng-error nil "group in start not allowed"))
1807 (let ((*in-one-or-more//group-or-interleave-p*
1808 *in-one-or-more-p*))
1809 (multiple-value-bind (x a e tp) (check-restrictions (pattern-a pattern))
1810 (multiple-value-bind (y b f tq) (check-restrictions (pattern-b pattern))
1811 (dolist (nc1 a)
1812 (dolist (nc2 b)
1813 (when (classes-overlap-p nc1 nc2)
1814 (rng-error nil "attribute name overlap in group: ~A ~A"
1815 nc1 nc2))))
1816 (values (groupable-max x y)
1817 (append a b)
1818 (append e f)
1819 (or tp tq))))))
1821 (defmethod check-restrictions ((pattern interleave))
1822 (when *in-list-p*
1823 (rng-error nil "interleave in list not allowed"))
1824 (when *in-data-except-p*
1825 (rng-error nil "interleave in data/except not allowed"))
1826 (when *in-start-p*
1827 (rng-error nil "interleave in start not allowed"))
1828 (let ((*in-one-or-more//group-or-interleave-p*
1829 *in-one-or-more-p*))
1830 (multiple-value-bind (x a e tp) (check-restrictions (pattern-a pattern))
1831 (multiple-value-bind (y b f tq) (check-restrictions (pattern-b pattern))
1832 (dolist (nc1 a)
1833 (dolist (nc2 b)
1834 (when (classes-overlap-p nc1 nc2)
1835 (rng-error nil "attribute name overlap in interleave: ~A ~A"
1836 nc1 nc2))))
1837 (dolist (nc1 e)
1838 (dolist (nc2 f)
1839 (when (classes-overlap-p nc1 nc2)
1840 (rng-error nil "element name overlap in interleave: ~A ~A"
1841 nc1 nc2))))
1842 (when (and tp tq)
1843 (rng-error nil "multiple text permitted by interleave"))
1844 (values (groupable-max x y)
1845 (append a b)
1846 (append e f)
1847 (or tp tq))))))
1849 (defmethod check-restrictions ((pattern choice))
1850 (multiple-value-bind (x a e tp) (check-restrictions (pattern-a pattern))
1851 (multiple-value-bind (y b f tq) (check-restrictions (pattern-b pattern))
1852 (values (content-type-max x y)
1853 (append a b)
1854 (append e f)
1855 (or tp tq)))))
1857 (defmethod check-restrictions ((pattern list-pattern))
1858 (when *in-list-p*
1859 (rng-error nil "nested list not allowed"))
1860 (when *in-data-except-p*
1861 (rng-error nil "list in data/except not allowed"))
1862 (let ((*in-list-p* t))
1863 (check-restrictions (pattern-child pattern)))
1864 (when *in-start-p*
1865 (rng-error nil "list in start not allowed"))
1866 :simple)
1868 (defmethod check-restrictions ((pattern text))
1869 (when *in-list-p*
1870 (rng-error nil "text in list not allowed"))
1871 (when *in-data-except-p*
1872 (rng-error nil "text in data/except not allowed"))
1873 (when *in-start-p*
1874 (rng-error nil "text in start not allowed"))
1875 (values :complex nil nil t))
1877 (defmethod check-restrictions ((pattern data))
1878 (when *in-start-p*
1879 (rng-error nil "data in start not allowed"))
1880 (when (pattern-except pattern)
1881 (let ((*in-data-except-p* t))
1882 (check-restrictions (pattern-except pattern))))
1883 :simple)
1885 (defmethod check-restrictions ((pattern value))
1886 (when *in-start-p*
1887 (rng-error nil "value in start not allowed"))
1888 :simple)
1890 (defmethod check-restrictions ((pattern empty))
1891 (when *in-data-except-p*
1892 (rng-error nil "empty in data/except not allowed"))
1893 (when *in-start-p*
1894 (rng-error nil "empty in start not allowed"))
1895 :empty)
1897 (defmethod check-restrictions ((pattern element))
1898 (unless (check-restrictions (pattern-child pattern))
1899 (rng-error nil "restrictions on string sequences violated")))
1901 (defmethod check-restrictions ((pattern not-allowed))
1902 nil)