blue.css
[cxml-rng.git] / parse.lisp
blob1a628f023d30c1a131511c8f53b7fd953f52ad4d
1 ;;; -*- show-trailing-whitespace: t; indent-tabs: nil -*-
3 ;;; Copyright (c) 2007 David Lichteblau. All rights reserved.
5 ;;; Redistribution and use in source and binary forms, with or without
6 ;;; modification, are permitted provided that the following conditions
7 ;;; are met:
8 ;;;
9 ;;; * Redistributions of source code must retain the above copyright
10 ;;; notice, this list of conditions and the following disclaimer.
11 ;;;
12 ;;; * Redistributions in binary form must reproduce the above
13 ;;; copyright notice, this list of conditions and the following
14 ;;; disclaimer in the documentation and/or other materials
15 ;;; provided with the distribution.
16 ;;;
17 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
18 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
21 ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
23 ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25 ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 (in-package :cxml-rng)
31 #+sbcl
32 (declaim (optimize (debug 2)))
35 ;;;; Errors
37 (define-condition rng-error (simple-error)
38 ((line-number :initarg :line-number :accessor rng-error-line-number)
39 (column-number :initarg :column-number :accessor rng-error-column-number)
40 (system-id :initarg :system-id :accessor rng-error-system-id))
41 (:documentation
42 "The class of all validation errors.
43 @see-slot{rng-error-line-number}
44 @see-slot{rng-error-column-number}
45 @see-slot{rng-error-system-id}"))
47 (setf (documentation 'rng-error-line-number 'function)
48 "@arg[instance]{an instance of @class{rng-error}}
49 @return{an integer, or nil}
50 Return the line number reported by the parser when the Relax NG error
51 was detected, or NIL if not available.")
53 (setf (documentation 'rng-error-column-number 'function)
54 "@arg[instance]{an instance of @class{rng-error}}
55 @return{an integer, or nil}
56 Return the column number reported by the parser when the Relax NG error
57 was detected, or NIL if not available.")
59 (setf (documentation 'rng-error-system-id 'function)
60 "@arg[instance]{an instance of @class{rng-error}}
61 @return{a puri:uri, or nil}
62 Return the System ID of the document being parsed when the Relax NG
63 error was detected, or NIL if not available.")
65 (defun rng-error (source fmt &rest args)
66 "@unexport{}"
67 (let ((s (make-string-output-stream)))
68 (apply #'format s fmt args)
69 (multiple-value-bind (line-number column-number system-id)
70 (etypecase source
71 (null)
72 (klacks:source
73 (values (klacks:current-line-number source)
74 (klacks:current-column-number source)
75 (klacks:current-system-id source)))
76 (sax:sax-parser-mixin
77 (values (sax:line-number source)
78 (sax:column-number source)
79 (sax:system-id source))))
80 (when (or line-number column-number system-id)
81 (format s "~& [ Error at line ~D, column ~D in ~S ]"
82 line-number
83 column-number
84 system-id))
85 (error 'rng-error
86 :format-control "~A"
87 :format-arguments (list (get-output-stream-string s))
88 :line-number line-number
89 :column-number column-number
90 :system-id system-id))))
93 ;;;; Parser
95 (defvar *datatype-library*)
96 (defvar *namespace-uri*)
97 (defvar *ns*)
98 (defvar *entity-resolver*)
99 (defvar *external-href-stack*)
100 (defvar *include-uri-stack*)
101 (defvar *include-body-p* nil)
102 (defvar *grammar*)
104 (defvar *debug* nil)
106 (defstruct (schema
107 (:constructor make-schema (start definitions)))
108 "An instance of this class represents a Relax NG grammar that has
109 been parsed and simplified.
110 @see-slot{schema-start}
111 @see-constructor{parse-schema}
112 @see{make-validator}
113 @see{serialize-schema} "
114 (start (missing) :type pattern)
115 (definitions (missing) :type list)
116 (interned-start nil :type (or null pattern))
117 (registratur nil :type (or null hash-table)))
119 (setf (documentation 'schema-start 'function)
120 "@arg[instance]{an instance of @class{schema}}
121 @return{the start pattern, an instance of @class{pattern}}
122 Reader function for the grammar's start pattern, from which all
123 of the grammar's patters are reachable.")
125 (defmethod print-object ((object schema) stream)
126 (print-unreadable-object (object stream :type t :identity t)))
128 (defun invoke-with-klacks-handler (fn source)
129 (if *debug*
130 (funcall fn)
131 (handler-case
132 (funcall fn)
133 (cxml:xml-parse-error (c)
134 (rng-error source "Cannot parse schema: ~A" c)))))
136 (defvar *validate-grammar* t)
137 (defparameter *relax-ng-grammar* nil)
139 (defun make-validating-source (input)
140 (let ((upstream (cxml:make-source input)))
141 (if *validate-grammar*
142 (klacks:make-tapping-source upstream
143 (make-validator *relax-ng-grammar*))
144 upstream)))
146 (defun parse-schema (input &key entity-resolver)
147 "@arg[input]{a string, pathname, stream, or xstream}
148 @arg[entity-resolver]{a function of two arguments, or NIL}
149 @return{a parsed @class{schema}}
150 @short{This function parses a Relax NG schema file in XML syntax}
151 and returns a parsed representation of that schema.
153 @code{input} can be any stream designator as understood by
154 @code{cxml:make-source}.
156 Note that namestrings are not valid arguments,
157 because they would be interpreted as XML source code. Use pathnames
158 instead.
160 @code{entity-resolver} can be passed as a function of two arguments.
161 It is invoked for every entity referenced by the
162 document with the entity's Public ID (a rod) and System ID (an
163 URI object) as arguments. The function may either return
164 nil, CXML will then try to resolve the entity as usual.
165 Alternatively it may return a Common Lisp stream specialized on
166 @code{(unsigned-byte 8)} which will be used instead.
168 @see{parse-compact}
169 @see{make-validator}"
170 (when *validate-grammar*
171 (unless *relax-ng-grammar*
172 (setf *relax-ng-grammar*
173 (let* ((*validate-grammar* nil)
174 (d (slot-value (asdf:find-system :cxml-rng)
175 'asdf::relative-pathname)))
176 (parse-schema (merge-pathnames "rng.rng" d))
177 #+(or)
178 (parse-compact (merge-pathnames "rng.rnc" d))))))
179 (klacks:with-open-source (source (make-validating-source input))
180 (invoke-with-klacks-handler
181 (lambda ()
182 (klacks:find-event source :start-element)
183 (let* ((*datatype-library* "")
184 (*namespace-uri* "")
185 (*entity-resolver* entity-resolver)
186 (*external-href-stack* '())
187 (*include-uri-stack* '())
188 (*grammar* (make-grammar nil))
189 (start (p/pattern source)))
190 (unless start
191 (rng-error nil "empty grammar"))
192 (setf (grammar-start *grammar*)
193 (make-definition :name :start :child start))
194 (check-pattern-definitions source *grammar*)
195 (check-recursion start 0)
196 (multiple-value-bind (new-start defns)
197 (finalize-definitions start)
198 (setf start (fold-not-allowed new-start))
199 (dolist (defn defns)
200 (setf (defn-child defn) (fold-not-allowed (defn-child defn))))
201 (setf start (fold-empty start))
202 (dolist (defn defns)
203 (setf (defn-child defn) (fold-empty (defn-child defn)))))
204 (multiple-value-bind (new-start defns)
205 (finalize-definitions start)
206 (check-start-restrictions new-start)
207 (dolist (defn defns)
208 (check-restrictions (defn-child defn)))
209 (make-schema new-start defns))))
210 source)))
213 ;;;; pattern structures
215 (defstruct pattern
216 "@short{The superclass of all patterns.}
217 Instances of this class represent elements in the \"simplified syntax\"
218 of Relax NG.
220 Patterns are documented for introspective purposes and are not meant to
221 be modified by user code.
223 The start pattern of a schema is available through @fun{schema-start}.
225 @see{schema}"
226 (nullable :uninitialized))
228 (defmethod print-object :around ((object pattern) stream)
229 (if *debug*
230 (let ((*print-circle* t))
231 (call-next-method))
232 (print-unreadable-object (object stream :type t :identity t))))
234 (defstruct (%parent (:include pattern) (:conc-name "PATTERN-"))
235 child)
237 (defstruct (%named-pattern (:include %parent) (:conc-name "PATTERN-"))
238 name)
240 (setf (documentation 'pattern-name 'function)
241 "@arg[instance]{an instance of @class{pattern}}
242 @return{a @class{name-class}}
243 @short{Returns the @code{pattern}'s name class.}
245 This slot describes the name allowed for the current element or
246 attribute.
248 @see{element}
249 @see{attribute}")
251 (setf (documentation 'pattern-child 'function)
252 "@arg[instance]{an instance of @class{pattern}}
253 @return{an instance of @class{pattern}}
254 @short{Returns the pattern's sub-pattern.}
256 (Elements in the full Relax NG syntax allow more than one child
257 pattern, but simplification normalizes the representation so that
258 any such element has exactly one child.)
260 @see{element}
261 @see{attribute}
262 @see{one-or-more}
263 @see{list-pattern}
264 @see{choice}")
266 (defstruct (element (:include %named-pattern))
267 "@short{This pattern specifies that an element of a certain name class
268 is required.}
270 Its child pattern describes the attributes and child nodes
271 of this element.
272 @see-slot{pattern-name}
273 @see-slot{pattern-child}")
275 (defstruct (attribute (:include %named-pattern))
276 "@short{This pattern specifies that an attribute of a certain name class
277 is required.}
279 Its child pattern describes the type of the attribute's
280 contents.
281 @see-slot{pattern-name}
282 @see-slot{pattern-child}")
284 (defstruct (%combination (:include pattern) (:conc-name "PATTERN-"))
285 a b)
287 (setf (documentation 'pattern-a 'function)
288 "@arg[instance]{an instance of @class{pattern}}
289 @return{an instance of @class{pattern}}
290 @short{Returns the first of two sub-patterns the pattern instance has.}
292 (Elements in the full Relax NG syntax allow more than two child
293 patterns, but simplification normalizes the representation so that
294 any such element has exactly two children.)
296 @see{pattern-b}
297 @see{group}
298 @see{interleave}
299 @see{choice}")
301 (setf (documentation 'pattern-b 'function)
302 "@arg[instance]{an instance of @class{pattern}}
303 @return{an instance of @class{pattern}}
304 @short{Returns the second of two sub-patterns the pattern instance has.}
306 (Elements in the full Relax NG syntax allow more than two child
307 patterns, but simplification normalizes the representation so that
308 any such element has exactly two children.)
310 @see{pattern-a}
311 @see{group}
312 @see{interleave}
313 @see{choice}")
315 (defstruct (group
316 (:include %combination)
317 (:constructor make-group (a b)))
318 "@short{This pattern specifies that two subpatterns are
319 required at the current position in a specific order.}
321 @see-slot{pattern-a}
322 @see-slot{pattern-b}")
323 (defstruct (interleave
324 (:include %combination)
325 (:constructor make-interleave (a b)))
326 "@short{This pattern specifies that two possible subpatterns are
327 allowed to occur in any order at the current position.}
329 @see-slot{pattern-a}
330 @see-slot{pattern-b}")
331 (defstruct (choice
332 (:include %combination)
333 (:constructor make-choice (a b)))
334 "@short{This pattern specifies that one of two possible subpatterns are
335 allowed at the current position, given as its children.}
337 @see-slot{pattern-a}
338 @see-slot{pattern-b}")
339 (defstruct (after
340 (:include %combination)
341 (:constructor make-after (a b))))
343 (defstruct (one-or-more
344 (:include %parent)
345 (:constructor make-one-or-more (child)))
346 "@short{This pattern specifies that its subpattern is
347 allowed to occur at the current position one or more times.}
349 @see-slot{pattern-child}")
350 (defstruct (list-pattern
351 (:include %parent)
352 (:constructor make-list-pattern (child)))
353 "@short{This pattern specifies that a subpatterns is allowed multiple
354 times a the current position, with whitespace as a separator.}
356 @see-slot{pattern-child}")
358 (defstruct (ref
359 (:include pattern)
360 (:conc-name "PATTERN-")
361 (:constructor make-ref (target)))
362 "@short{This pattern references another part of the pattern graph.}
364 @code{ref} is the only pattern to introduce shared structure and
365 circularity into the pattern graph, by referring to elements defined
366 elsewhere.
368 (@code{ref} pattern in the full Relax NG syntax can be used to refer
369 to any pattern definition in the grammar. Simplification normalizes
370 the schema so that ref patterns only refer to definitions which have
371 an @code{element} as their child.)
373 @see-slot{pattern-element}"
374 crdepth
375 target)
377 (defun pattern-element (ref)
378 "@arg[ref]{an instance of @class{ref}}
379 @return{an instance of @class{element}}
380 @short{Returns the ref pattern's target.}
382 @code{ref} is the only pattern to introduce shared structure and
383 circularity into the pattern graph, by referring to elements defined
384 elsewhere.
386 (@code{ref} pattern in the full Relax NG syntax can be used to refer
387 to any pattern definition in the grammar. Simplification normalizes
388 the schema so that ref patterns only refer to definitions which have
389 an @code{element} as their child.)"
390 (defn-child (pattern-target ref)))
392 (defstruct (%leaf (:include pattern)))
394 (defstruct (empty (:include %leaf))
395 "@short{This pattern specifies that nothing more is expected at the current
396 position.}")
398 (defstruct (text (:include %leaf))
399 "@short{This pattern specifies that text is expected here.}")
401 (defstruct (%typed-pattern (:include %leaf) (:conc-name "PATTERN-"))
402 type)
404 (setf (documentation 'pattern-type 'function)
405 "@arg[instance]{an instance of @class{pattern}}
406 @return{a @class{cxml-types:data-type}}
407 @short{Returns the data type expected at this position.}
409 This type has already been parsed into an object. Its name and
410 the URI of its library can be queried from that object.
412 @see{data}
413 @see{value}
414 @see{cxml-types:type-name}
415 @see{cxml-types:type-library}")
417 (defstruct (value (:include %typed-pattern) (:conc-name "PATTERN-"))
418 "@short{This pattern specifies that a specific value is expected as text
419 here.}
421 The value expected is @code{pattern-value}, parsed from
422 @code{pattern-string} using @code{pattern-type}.
424 @see-slot{pattern-type}
425 @see-slot{pattern-value}
426 @see-slot{pattern-string}"
428 string
429 value)
431 (setf (documentation 'pattern-string 'function)
432 "@arg[instance]{an instance of @class{value}}
433 @return{a string}
434 @short{Returns the string expected at this position.}
436 This string is the lexical representation expected, not parsed into
437 a value object yet. The parsed object is available as
438 @fun{pattern-value}.
440 @see{pattern-type}")
442 (setf (documentation 'pattern-value 'function)
443 "@arg[instance]{an instance of @class{value}}
444 @return{an object as returned by @fun{cxml-types:parse}}
445 @short{Returns the value expected at this position.}
447 This object is the result of parsing @fun{pattern-string} using
448 @fun{pattern-type}.")
450 (defstruct (data (:include %typed-pattern) (:conc-name "PATTERN-"))
451 "@short{This pattern specifies that text of a specific data type is
452 expected.}
454 The data type instance stored in the @code{pattern-type} slot takes into
455 account additional paramaters, which can be retrieved using
456 @code{pattern-params} in their original form.
458 @see-slot{pattern-type}
459 @see-slot{pattern-params}
460 @see-slot{pattern-except}"
461 params
462 except)
464 (setf (documentation 'pattern-except 'function)
465 "@arg[instance]{an instance of @class{data}}
466 @return{a @class{pattern}, or @code{nil}}
467 @short{Returns the @code{data} instance's @code{except} pattern.}
469 In addition to a data type, @code{data} can specify that certain
470 values are @em{not} permitted. They are described using a pattern.
472 If this slot is @code{nil}, no exception is defined.")
474 (setf (documentation 'pattern-params 'function)
475 "@arg[instance]{an instance of @class{data}}
476 @return{a list of @fun{cxml-types:param}}
477 @short{The data type parameters for this data pattern.}
479 (With the XSD type library, these are known as restricting facets.)")
481 (defstruct (not-allowed (:include %leaf))
482 "@short{This pattern specifies that the part of the schema reached at
483 this point is not valid.}")
486 ;;;; non-pattern
488 (defstruct (grammar (:constructor make-grammar (parent)))
489 (start nil)
490 parent
491 (definitions (make-hash-table :test 'equal)))
493 ;; Clark calls this structure "RefPattern"
494 (defstruct (definition (:conc-name "DEFN-"))
495 name
496 combine-method
497 head-p
498 redefinition
499 child)
502 ;;; name-class
504 (defun missing ()
505 (error "missing arg"))
507 (defstruct name-class
508 "@short{The abstract superclass of all name-related classes.}
510 Name classes represent sets of permissible names for an element or
511 attribute.
513 Names are pairs of namespace URI and local-name.
515 @see{attribute}
516 @see{element}")
518 (defstruct (any-name (:include name-class)
519 (:constructor make-any-name (except)))
520 "@short{This name class allows any name.}
522 Exceptions are given as @code{any-name-except}.
524 @see-slot{any-name-except}"
525 (except (missing) :type (or null name-class)))
527 (setf (documentation 'any-name-except 'function)
528 "@arg[instance]{an instance of @class{any-name}}
529 @return{a @class{name-class} or @code{nil}}
531 Return the name class @em{not} allowed by this @code{any-name},
532 or @code{nil} if there is no such exception.")
534 (defstruct (name (:include name-class)
535 (:constructor make-name (uri lname)))
536 "@short{This name class allows only a specific name.}
538 A specific namespace URI and local name are expected.
540 @see-slot{name-uri}
541 @see-slot{name-lname}"
542 (uri (missing) :type string)
543 (lname (missing) :type string))
545 (setf (documentation 'name-uri 'function)
546 "@arg[instance]{an instance of @class{name}}
547 @return{a string}
548 Return the expected namespace URI.")
550 (setf (documentation 'name-lname 'function)
551 "@arg[instance]{an instance of @class{name}}
552 @return{a string}
553 Return the expected local name.")
555 (defstruct (ns-name (:include name-class)
556 (:constructor make-ns-name (uri except)))
557 "@short{This name class allows all names in a specific namespace}, with
558 possible exceptions.
560 A specific namespace URI is expected.
562 Exceptions are given as @code{ns-name-except}.
564 @see-slot{ns-name-uri}
565 @see-slot{ns-name-except}"
566 (uri (missing) :type string)
567 (except (missing) :type (or null name-class)))
569 (setf (documentation 'ns-name-uri 'function)
570 "@arg[instance]{an instance of @class{ns-name}}
571 @return{a string}
572 Return the expected namespace URI.")
574 (setf (documentation 'ns-name-except 'function)
575 "@arg[instance]{an instance of @class{ns-name}}
576 @return{a @class{name-class} or @code{nil}}
578 Return the name class @em{not} allowed by this @code{ns-name},
579 or @code{nil} if there is no such exception.")
581 (defstruct (name-class-choice (:include name-class)
582 (:constructor make-name-class-choice (a b)))
583 "@short{This name class represents the union of two other name classes.}
585 @see-slot{name-class-choice-a}
586 @see-slot{name-class-choice-b}"
587 (a (missing) :type name-class)
588 (b (missing) :type name-class))
590 (setf (documentation 'name-class-choice-a 'function)
591 "@arg[instance]{an instance of @class{name-class-choice}}
592 @return{a @class{name-class}}
593 Returns the 'first' of two name classes that are allowed.
594 @see{name-class-choice-b}")
596 (setf (documentation 'name-class-choice-b 'function)
597 "@arg[instance]{an instance of @class{name-class-choice}}
598 @return{a @class{name-class}}
599 Returns the 'second' of two name classes that are allowed.
600 @see{name-class-choice-a}")
602 (defun simplify-nc-choice (values)
603 (zip #'make-name-class-choice values))
606 ;;;; parser
608 (defvar *rng-namespace* "http://relaxng.org/ns/structure/1.0")
610 (defun skip-foreign* (source)
611 (loop
612 (case (klacks:peek-next source)
613 (:start-element (skip-foreign source))
614 (:end-element (return)))))
616 (defun skip-to-native (source)
617 (loop
618 (case (klacks:peek source)
619 (:start-element
620 (when (equal (klacks:current-uri source) *rng-namespace*)
621 (return))
622 (klacks:serialize-element source nil))
623 (:end-element (return)))
624 (klacks:consume source)))
626 (defun consume-and-skip-to-native (source)
627 (klacks:consume source)
628 (skip-to-native source))
630 (defun skip-foreign (source)
631 (when (equal (klacks:current-uri source) *rng-namespace*)
632 (rng-error source
633 "invalid schema: ~A not allowed here"
634 (klacks:current-lname source)))
635 (klacks:serialize-element source nil))
637 (defun attribute (lname attrs)
638 "@unexport{}"
639 (let ((a (sax:find-attribute-ns "" lname attrs)))
640 (if a
641 (sax:attribute-value a)
642 nil)))
644 (defparameter *whitespace*
645 (format nil "~C~C~C~C"
646 (code-char 9)
647 (code-char 32)
648 (code-char 13)
649 (code-char 10)))
651 (defun ntc (lname source-or-attrs)
652 ;; used for (n)ame, (t)ype, and (c)ombine, this also strings whitespace
653 (let* ((attrs
654 (if (listp source-or-attrs)
655 source-or-attrs
656 (klacks:list-attributes source-or-attrs)))
657 (a (sax:find-attribute-ns "" lname attrs)))
658 (if a
659 (string-trim *whitespace* (sax:attribute-value a))
660 nil)))
662 (defmacro with-library-and-ns (attrs &body body)
663 `(invoke-with-library-and-ns (lambda () ,@body) ,attrs))
665 (defun invoke-with-library-and-ns (fn attrs)
666 (let* ((dl (attribute "datatypeLibrary" attrs))
667 (ns (attribute "ns" attrs))
668 (*datatype-library* (if dl (escape-uri dl) *datatype-library*))
669 (*namespace-uri* (or ns *namespace-uri*))
670 (*ns* ns))
671 ;; FIXME: Ganz boese gehackt -- gerade so, dass wir die Relax NG
672 ;; Test-Suite bestehen.
673 (when (and dl
674 (not (zerop (length *datatype-library*)))
675 ;; scheme pruefen, und es muss was folgen
676 (or (not (cl-ppcre:all-matches
677 "^[a-zA-Z][a-zA-Z0-9+.-]*:.+"
678 *datatype-library*))
679 ;; keine kaputten %te, keine #
680 (cl-ppcre:all-matches
681 "(%$|%.$|%[^0-9A-Fa-f][^0-9A-Fa-f]|#)"
682 *datatype-library*)))
683 (rng-error nil "malformed datatypeLibrary: ~A" *datatype-library*))
684 (funcall fn)))
686 (defun p/pattern (source)
687 (let* ((lname (klacks:current-lname source))
688 (attrs (klacks:list-attributes source)))
689 (with-library-and-ns attrs
690 (case (find-symbol lname :keyword)
691 (:|element| (p/element source (ntc "name" attrs)))
692 (:|attribute| (p/attribute source (ntc "name" attrs)))
693 (:|group| (p/combination #'groupify source))
694 (:|interleave| (p/combination #'interleave-ify source))
695 (:|choice| (p/combination #'choice-ify source))
696 (:|optional| (p/optional source))
697 (:|zeroOrMore| (p/zero-or-more source))
698 (:|oneOrMore| (p/one-or-more source))
699 (:|list| (p/list source))
700 (:|mixed| (p/mixed source))
701 (:|ref| (p/ref source))
702 (:|parentRef| (p/parent-ref source))
703 (:|empty| (p/empty source))
704 (:|text| (p/text source))
705 (:|value| (p/value source))
706 (:|data| (p/data source))
707 (:|notAllowed| (p/not-allowed source))
708 (:|externalRef| (p/external-ref source))
709 (:|grammar| (p/grammar source))
710 (t (skip-foreign source))))))
712 (defun p/pattern+ (source)
713 (let ((children nil))
714 (loop
715 (case (klacks:peek source)
716 (:start-element
717 (let ((p (p/pattern source))) (when p (push p children))))
718 (:end-element
719 (return))
721 (klacks:consume source))))
722 (unless children
723 (rng-error source "empty element"))
724 (nreverse children)))
726 (defun p/pattern? (source)
727 (let ((result nil))
728 (loop
729 (skip-to-native source)
730 (case (klacks:peek source)
731 (:start-element
732 (when result
733 (rng-error source "at most one pattern expected here"))
734 (setf result (p/pattern source)))
735 (:end-element
736 (return))
738 (klacks:consume source))))
739 result))
741 (defun p/element (source name)
742 (klacks:expecting-element (source "element")
743 (let ((elt (make-element)))
744 (consume-and-skip-to-native source)
745 (if name
746 (setf (pattern-name elt) (destructure-name source name))
747 (setf (pattern-name elt) (p/name-class source)))
748 (skip-to-native source)
749 (setf (pattern-child elt) (groupify (p/pattern+ source)))
750 (make-ref (make-definition :name (gensym "ANONYMOUS") :child elt)))))
752 (defvar *attribute-namespace-p* nil)
754 (defun p/attribute (source name)
755 (klacks:expecting-element (source "attribute")
756 (let ((result (make-attribute)))
757 (consume-and-skip-to-native source)
758 (if name
759 (setf (pattern-name result)
760 (let ((*namespace-uri* (or *ns* ""))
761 (*attribute-namespace-p* t))
762 (destructure-name source name)))
763 (setf (pattern-name result)
764 (let ((*attribute-namespace-p* t))
765 (p/name-class source))))
766 (skip-to-native source)
767 (setf (pattern-child result)
768 (or (p/pattern? source) (make-text)))
769 result)))
771 (defun p/combination (zipper source)
772 (klacks:expecting-element (source)
773 (consume-and-skip-to-native source)
774 (funcall zipper (p/pattern+ source))))
776 (defun p/one-or-more (source)
777 (klacks:expecting-element (source "oneOrMore")
778 (consume-and-skip-to-native source)
779 (let ((children (p/pattern+ source)))
780 (make-one-or-more (groupify children)))))
782 (defun p/zero-or-more (source)
783 (klacks:expecting-element (source "zeroOrMore")
784 (consume-and-skip-to-native source)
785 (let ((children (p/pattern+ source)))
786 (make-choice (make-one-or-more (groupify children))
787 (make-empty)))))
789 (defun p/optional (source)
790 (klacks:expecting-element (source "optional")
791 (consume-and-skip-to-native source)
792 (let ((children (p/pattern+ source)))
793 (make-choice (groupify children) (make-empty)))))
795 (defun p/list (source)
796 (klacks:expecting-element (source "list")
797 (consume-and-skip-to-native source)
798 (let ((children (p/pattern+ source)))
799 (make-list-pattern (groupify children)))))
801 (defun p/mixed (source)
802 (klacks:expecting-element (source "mixed")
803 (consume-and-skip-to-native source)
804 (let ((children (p/pattern+ source)))
805 (make-interleave (groupify children) (make-text)))))
807 (defun p/ref (source)
808 (klacks:expecting-element (source "ref")
809 (prog1
810 (let* ((name (ntc "name" source))
811 (pdefinition
812 (or (find-definition name)
813 (setf (find-definition name)
814 (make-definition :name name :child nil)))))
815 (make-ref pdefinition))
816 (skip-foreign* source))))
818 (defun p/parent-ref (source)
819 (klacks:expecting-element (source "parentRef")
820 (prog1
821 (let* ((name (ntc "name" source))
822 (grammar (grammar-parent *grammar*))
823 (pdefinition
824 (or (find-definition name grammar)
825 (setf (find-definition name grammar)
826 (make-definition :name name :child nil)))))
827 (make-ref pdefinition))
828 (skip-foreign* source))))
830 (defun p/empty (source)
831 (klacks:expecting-element (source "empty")
832 (skip-foreign* source)
833 (make-empty)))
835 (defun p/text (source)
836 (klacks:expecting-element (source "text")
837 (skip-foreign* source)
838 (make-text)))
840 (defun consume-and-parse-characters (source)
841 ;; fixme
842 (let ((tmp ""))
843 (loop
844 (multiple-value-bind (key data) (klacks:peek-next source)
845 (case key
846 (:characters
847 (setf tmp (concatenate 'string tmp data)))
848 (:end-element (return)))))
849 tmp))
851 (defun p/value (source)
852 (klacks:expecting-element (source "value")
853 (let* ((type (ntc "type" source))
854 (string (consume-and-parse-characters source))
855 (ns *namespace-uri*)
856 (dl *datatype-library*))
857 (unless type
858 (setf type "token")
859 (setf dl ""))
860 (let ((data-type
861 (cxml-types:find-type (and dl (find-symbol dl :keyword))
862 type
863 nil))
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 (cxml-types:find-type
895 (and dl (find-symbol dl :keyword))
896 type
897 params)))
898 (unless data-type
899 (rng-error source "type not found: ~A/~A" type dl))
900 (when (eq data-type :error)
901 (rng-error source "params not valid for type: ~A/~A/~A"
902 type dl params))
903 (make-data
904 :type data-type
905 :params params
906 :except except)))))
908 (defun p/param (source)
909 (klacks:expecting-element (source "param")
910 (let ((name (ntc "name" source))
911 (string (consume-and-parse-characters source)))
912 (cxml-types:make-param name string))))
914 (defun p/except-pattern (source)
915 (klacks:expecting-element (source "except")
916 (with-library-and-ns (klacks:list-attributes source)
917 (klacks:consume source)
918 (choice-ify (p/pattern+ source)))))
920 (defun p/not-allowed (source)
921 (klacks:expecting-element (source "notAllowed")
922 (consume-and-skip-to-native source)
923 (make-not-allowed)))
925 (defun safe-parse-uri (source str &optional base)
926 (when (zerop (length str))
927 (rng-error source "missing URI"))
928 (let* ((compactp (rnc-uri-p str))
929 (str (if compactp (follow-rnc-uri str) str))
930 (uri
931 (handler-case
932 (if base
933 (puri:merge-uris str base)
934 (puri:parse-uri str))
935 (puri:uri-parse-error ()
936 (rng-error source "invalid URI: ~A" str)))))
937 (when (and (eq (puri:uri-scheme uri) :file)
938 (puri:uri-fragment uri))
939 (rng-error source "Forbidden fragment in URI: ~A" str))
940 (values uri compactp)))
942 (defun named-string-xstream (str uri)
943 (let ((xstream (cxml::string->xstream str)))
944 (setf (cxml::xstream-name xstream)
945 (cxml::make-stream-name
946 :entity-name "main document"
947 :entity-kind :main
948 :uri uri))
949 xstream))
951 (defun xstream-open-schema (uri compactp)
952 (if compactp
953 (named-string-xstream
954 (uncompact-file
955 ;; fixme: Hier waere es schon, mit *entity-resolver* arbeiten
956 ;; zu koennen, aber der liefert binaere Streams.
957 (open (cxml::uri-to-pathname uri)
958 :element-type 'character
959 :direction :input))
960 uri)
961 (cxml::xstream-open-extid* *entity-resolver* nil uri)))
963 (defun p/external-ref (source)
964 (klacks:expecting-element (source "externalRef")
965 (let* ((href
966 (escape-uri (attribute "href" (klacks:list-attributes source))))
967 (base (klacks:current-xml-base source)))
968 (multiple-value-bind (uri compactp)
969 (safe-parse-uri source href base)
970 (when (find uri *include-uri-stack* :test #'puri:uri=)
971 (rng-error source "looping include"))
972 (prog1
973 (let* ((*include-uri-stack* (cons uri *include-uri-stack*))
974 (xstream (xstream-open-schema uri compactp)))
975 (klacks:with-open-source
976 (source (make-validating-source xstream))
977 (invoke-with-klacks-handler
978 (lambda ()
979 (klacks:find-event source :start-element)
980 (let ((*datatype-library* ""))
981 (p/pattern source)))
982 source)))
983 (skip-foreign* source))))))
985 (defun p/grammar (source &optional grammar)
986 (klacks:expecting-element (source "grammar")
987 (consume-and-skip-to-native source)
988 (let ((*grammar* (or grammar (make-grammar *grammar*)))
989 (includep grammar))
990 (process-grammar-content* source)
991 (unless (or includep (grammar-start *grammar*))
992 (rng-error source "no <start> in grammar"))
993 (unless includep
994 (check-pattern-definitions source *grammar*)
995 (defn-child (grammar-start *grammar*))))))
997 (defvar *include-start*)
998 (defvar *include-definitions*)
1000 (defun process-grammar-content* (source &key disallow-include)
1001 (loop
1002 (multiple-value-bind (key uri lname) (klacks:peek source)
1004 (ecase key
1005 (:characters
1006 (klacks:consume source))
1007 (:start-element
1008 (with-library-and-ns (klacks:list-attributes source)
1009 (case (find-symbol lname :keyword)
1010 (:|start|
1011 (process-start source))
1012 (:|define| (process-define source))
1013 (:|div| (process-div source))
1014 (:|include|
1015 (when disallow-include
1016 (rng-error source "nested include not permitted"))
1017 (process-include source))
1019 (skip-foreign source)))))
1020 (:end-element
1021 (return))))))
1023 (defun process-start (source)
1024 (klacks:expecting-element (source "start")
1025 (let* ((combine0 (ntc "combine" source))
1026 (combine
1027 (when combine0
1028 (find-symbol (string-upcase combine0) :keyword)))
1029 (child
1030 (progn
1031 (consume-and-skip-to-native source)
1032 (p/pattern source)))
1033 (pdefinition (grammar-start *grammar*)))
1034 (skip-foreign* source)
1035 ;; fixme: shared code with process-define
1036 (unless pdefinition
1037 (setf pdefinition (make-definition :name :start :child nil))
1038 (setf (grammar-start *grammar*) pdefinition))
1039 (when *include-body-p*
1040 (setf *include-start* pdefinition))
1041 (cond
1042 ((defn-child pdefinition)
1043 (ecase (defn-redefinition pdefinition)
1044 (:not-being-redefined
1045 (when (and combine
1046 (defn-combine-method pdefinition)
1047 (not (eq combine
1048 (defn-combine-method pdefinition))))
1049 (rng-error source "conflicting combine values for <start>"))
1050 (unless combine
1051 (when (defn-head-p pdefinition)
1052 (rng-error source "multiple definitions for <start>"))
1053 (setf (defn-head-p pdefinition) t))
1054 (unless (defn-combine-method pdefinition)
1055 (setf (defn-combine-method pdefinition) combine))
1056 (setf (defn-child pdefinition)
1057 (case (defn-combine-method pdefinition)
1058 (:choice
1059 (make-choice (defn-child pdefinition) child))
1060 (:interleave
1061 (make-interleave (defn-child pdefinition) child)))))
1062 (:being-redefined-and-no-original
1063 (setf (defn-redefinition pdefinition)
1064 :being-redefined-and-original))
1065 (:being-redefined-and-original)))
1067 (setf (defn-child pdefinition) child)
1068 (setf (defn-combine-method pdefinition) combine)
1069 (setf (defn-head-p pdefinition) (null combine))
1070 (setf (defn-redefinition pdefinition) :not-being-redefined))))))
1072 (defun zip (constructor children)
1073 (cond
1074 ((null children)
1075 (rng-error nil "empty choice?"))
1076 ((null (cdr children))
1077 (car children))
1079 (destructuring-bind (a b &rest rest)
1080 children
1081 (zip constructor (cons (funcall constructor a b) rest))))))
1083 (defun choice-ify (children) (zip #'make-choice children))
1084 (defun groupify (children) (zip #'make-group children))
1085 (defun interleave-ify (children) (zip #'make-interleave children))
1087 (defun find-definition (name &optional (grammar *grammar*))
1088 (gethash name (grammar-definitions grammar)))
1090 (defun (setf find-definition) (newval name &optional (grammar *grammar*))
1091 (setf (gethash name (grammar-definitions grammar)) newval))
1093 (defun process-define (source)
1094 (klacks:expecting-element (source "define")
1095 (let* ((name (ntc "name" source))
1096 (combine0 (ntc "combine" source))
1097 (combine (when combine0
1098 (find-symbol (string-upcase combine0) :keyword)))
1099 (child (groupify
1100 (progn
1101 (consume-and-skip-to-native source)
1102 (p/pattern+ source))))
1103 (pdefinition (find-definition name)))
1104 (unless pdefinition
1105 (setf pdefinition (make-definition :name name :child nil))
1106 (setf (find-definition name) pdefinition))
1107 (when *include-body-p*
1108 (push pdefinition *include-definitions*))
1109 (cond
1110 ((defn-child pdefinition)
1111 (case (defn-redefinition pdefinition)
1112 (:not-being-redefined
1113 (when (and combine
1114 (defn-combine-method pdefinition)
1115 (not (eq combine
1116 (defn-combine-method pdefinition))))
1117 (rng-error source "conflicting combine values for ~A" name))
1118 (unless combine
1119 (when (defn-head-p pdefinition)
1120 (rng-error source "multiple definitions for ~A" name))
1121 (setf (defn-head-p pdefinition) t))
1122 (unless (defn-combine-method pdefinition)
1123 (setf (defn-combine-method pdefinition) combine))
1124 (setf (defn-child pdefinition)
1125 (case (defn-combine-method pdefinition)
1126 (:choice
1127 (make-choice (defn-child pdefinition) child))
1128 (:interleave
1129 (make-interleave (defn-child pdefinition) child)))))
1130 (:being-redefined-and-no-original
1131 (setf (defn-redefinition pdefinition)
1132 :being-redefined-and-original))
1133 (:being-redefined-and-original)))
1135 (setf (defn-child pdefinition) child)
1136 (setf (defn-combine-method pdefinition) combine)
1137 (setf (defn-head-p pdefinition) (null combine))
1138 (setf (defn-redefinition pdefinition) :not-being-redefined))))))
1140 (defun process-div (source)
1141 (klacks:expecting-element (source "div")
1142 (consume-and-skip-to-native source)
1143 (process-grammar-content* source)))
1145 (defun reset-definition-for-include (defn)
1146 (setf (defn-combine-method defn) nil)
1147 (setf (defn-redefinition defn) :being-redefined-and-no-original)
1148 (setf (defn-head-p defn) nil))
1150 (defun restore-definition (defn original)
1151 (setf (defn-combine-method defn) (defn-combine-method original))
1152 (setf (defn-redefinition defn) (defn-redefinition original))
1153 (setf (defn-head-p defn) (defn-head-p original)))
1155 (defun process-include (source)
1156 (klacks:expecting-element (source "include")
1157 (let* ((href
1158 (escape-uri (attribute "href" (klacks:list-attributes source))))
1159 (base (klacks:current-xml-base source))
1160 (*include-start* nil)
1161 (*include-definitions* '()))
1162 (multiple-value-bind (uri compactp)
1163 (safe-parse-uri source href base)
1164 (consume-and-skip-to-native source)
1165 (let ((*include-body-p* t))
1166 (process-grammar-content* source :disallow-include t))
1167 (let ((tmp-start
1168 (when *include-start*
1169 (prog1
1170 (copy-structure *include-start*)
1171 (reset-definition-for-include *include-start*))))
1172 (tmp-defns
1173 (loop
1174 for defn in *include-definitions*
1175 collect
1176 (prog1
1177 (copy-structure defn)
1178 (reset-definition-for-include defn)))))
1179 (when (find uri *include-uri-stack* :test #'puri:uri=)
1180 (rng-error source "looping include"))
1181 (let* ((*include-uri-stack* (cons uri *include-uri-stack*))
1182 (xstream (xstream-open-schema uri compactp)))
1183 (klacks:with-open-source (source (make-validating-source xstream))
1184 (invoke-with-klacks-handler
1185 (lambda ()
1186 (klacks:find-event source :start-element)
1187 (let ((*datatype-library* ""))
1188 (p/grammar source *grammar*)))
1189 source))
1190 (when tmp-start
1191 (when (eq (defn-redefinition *include-start*)
1192 :being-redefined-and-no-original)
1193 (rng-error source "start not found in redefinition of grammar"))
1194 (restore-definition *include-start* tmp-start))
1195 (dolist (copy tmp-defns)
1196 (let ((defn (gethash (defn-name copy)
1197 (grammar-definitions *grammar*))))
1198 (when (eq (defn-redefinition defn)
1199 :being-redefined-and-no-original)
1200 (rng-error source "redefinition not found in grammar"))
1201 (restore-definition defn copy)))
1202 nil))))))
1204 (defun check-pattern-definitions (source grammar)
1205 (when (and (grammar-start grammar)
1206 (eq (defn-redefinition (grammar-start grammar))
1207 :being-redefined-and-no-original))
1208 (rng-error source "start not found in redefinition of grammar"))
1209 (loop for defn being each hash-value in (grammar-definitions grammar) do
1210 (when (eq (defn-redefinition defn) :being-redefined-and-no-original)
1211 (rng-error source "redefinition not found in grammar"))
1212 (unless (defn-child defn)
1213 (rng-error source "unresolved reference to ~A" (defn-name defn)))))
1215 (defvar *any-name-allowed-p* t)
1216 (defvar *ns-name-allowed-p* t)
1218 (defun destructure-name (source qname)
1219 (multiple-value-bind (uri lname)
1220 (klacks:decode-qname qname source)
1221 (setf uri (or uri *namespace-uri*))
1222 (when (and *attribute-namespace-p*
1223 (or (and (equal lname "xmlns") (equal uri ""))
1224 (equal uri "http://www.w3.org/2000/xmlns")))
1225 (rng-error source "namespace attribute not permitted"))
1226 (make-name uri lname)))
1228 (defun p/name-class (source)
1229 (klacks:expecting-element (source)
1230 (with-library-and-ns (klacks:list-attributes source)
1231 (case (find-symbol (klacks:current-lname source) :keyword)
1232 (:|name|
1233 (let ((qname (string-trim *whitespace*
1234 (consume-and-parse-characters source))))
1235 (destructure-name source qname)))
1236 (:|anyName|
1237 (unless *any-name-allowed-p*
1238 (rng-error source "anyname not permitted in except"))
1239 (klacks:consume source)
1240 (prog1
1241 (let ((*any-name-allowed-p* nil))
1242 (make-any-name (p/except-name-class? source)))
1243 (skip-to-native source)))
1244 (:|nsName|
1245 (unless *ns-name-allowed-p*
1246 (rng-error source "nsname not permitted in except"))
1247 (let ((uri *namespace-uri*)
1248 (*any-name-allowed-p* nil)
1249 (*ns-name-allowed-p* nil))
1250 (when (and *attribute-namespace-p*
1251 (equal uri "http://www.w3.org/2000/xmlns"))
1252 (rng-error source "namespace attribute not permitted"))
1253 (klacks:consume source)
1254 (prog1
1255 (make-ns-name uri (p/except-name-class? source))
1256 (skip-to-native source))))
1257 (:|choice|
1258 (klacks:consume source)
1259 (simplify-nc-choice (p/name-class* source)))
1261 (rng-error source "invalid child in except"))))))
1263 (defun p/name-class* (source)
1264 (let ((results nil))
1265 (loop
1266 (skip-to-native source)
1267 (case (klacks:peek source)
1268 (:characters
1269 (klacks:consume source))
1270 (:start-element
1271 (push (p/name-class source) results))
1272 (:end-element
1273 (return))))
1274 (nreverse results)))
1276 (defun p/except-name-class? (source)
1277 (skip-to-native source)
1278 (multiple-value-bind (key uri lname)
1279 (klacks:peek source)
1281 (if (and (eq key :start-element)
1282 (string= (find-symbol lname :keyword) "except"))
1283 (p/except-name-class source)
1284 nil)))
1286 (defun p/except-name-class (source)
1287 (klacks:expecting-element (source "except")
1288 (with-library-and-ns (klacks:list-attributes source)
1289 (klacks:consume source)
1290 (let ((x (p/name-class* source)))
1291 (if (cdr x)
1292 (simplify-nc-choice x)
1293 (car x))))))
1295 (defun escape-uri (string)
1296 (with-output-to-string (out)
1297 (loop for c across (cxml::rod-to-utf8-string string) do
1298 (let ((code (char-code c)))
1299 ;; http://www.w3.org/TR/xlink/#link-locators
1300 (if (or (>= code 127) (<= code 32) (find c "<>\"{}|\\^`"))
1301 (format out "%~2,'0X" code)
1302 (write-char c out))))))
1305 ;;;; unparsing
1307 (defvar *definitions-to-names*)
1308 (defvar *seen-names*)
1310 (defun serialization-name (defn)
1311 (or (gethash defn *definitions-to-names*)
1312 (setf (gethash defn *definitions-to-names*)
1313 (let ((name (if (gethash (defn-name defn) *seen-names*)
1314 (format nil "~A-~D"
1315 (defn-name defn)
1316 (hash-table-count *seen-names*))
1317 (defn-name defn))))
1318 (setf (gethash name *seen-names*) defn)
1319 name))))
1321 (defun serialize-schema (schema sink)
1322 "@arg[schema]{a Relax NG @class{schema}}
1323 @arg[sink]{a SAX handler}
1324 @return{the result of @code{sax:end-document}}
1325 @short{This function serializes a parsed Relax NG back into XML syntax.}
1327 Note that the schema represented in memory has gone through simplification
1328 as is textually different from the original XML document.
1330 @see{parse-schema}"
1331 (cxml:with-xml-output sink
1332 (let ((*definitions-to-names* (make-hash-table))
1333 (*seen-names* (make-hash-table :test 'equal)))
1334 (cxml:with-element "grammar"
1335 (cxml:with-element "start"
1336 (serialize-pattern (schema-start schema)))
1337 (loop for defn being each hash-key in *definitions-to-names* do
1338 (serialize-definition defn))))))
1340 (defun serialize-pattern (pattern)
1341 (etypecase pattern
1342 (element
1343 (cxml:with-element "element"
1344 (serialize-name (pattern-name pattern))
1345 (serialize-pattern (pattern-child pattern))))
1346 (attribute
1347 (cxml:with-element "attribute"
1348 (serialize-name (pattern-name pattern))
1349 (serialize-pattern (pattern-child pattern))))
1350 (%combination
1351 (cxml:with-element
1352 (etypecase pattern
1353 (group "group")
1354 (interleave "interleave")
1355 (choice "choice"))
1356 (serialize-pattern (pattern-a pattern))
1357 (serialize-pattern (pattern-b pattern))))
1358 (one-or-more
1359 (cxml:with-element "oneOrMore"
1360 (serialize-pattern (pattern-child pattern))))
1361 (list-pattern
1362 (cxml:with-element "list"
1363 (serialize-pattern (pattern-child pattern))))
1364 (ref
1365 (cxml:with-element "ref"
1366 (cxml:attribute "name" (serialization-name (pattern-target pattern)))))
1367 (empty
1368 (cxml:with-element "empty"))
1369 (not-allowed
1370 (cxml:with-element "notAllowed"))
1371 (text
1372 (cxml:with-element "text"))
1373 (value
1374 (cxml:with-element "value"
1375 (let ((type (pattern-type pattern)))
1376 (cxml:attribute "datatype-library"
1377 (symbol-name (cxml-types:type-library type)))
1378 (cxml:attribute "type" (cxml-types:type-name type)))
1379 (cxml:attribute "ns" (pattern-ns pattern))
1380 (cxml:text (pattern-string pattern))))
1381 (data
1382 (cxml:with-element "value"
1383 (let ((type (pattern-type pattern)))
1384 (cxml:attribute "datatype-library"
1385 (symbol-name (cxml-types:type-library type)))
1386 (cxml:attribute "type" (cxml-types:type-name type)))
1387 (dolist (param (pattern-params pattern))
1388 (cxml:with-element "param"
1389 (cxml:attribute "name" (cxml-types:param-name param))
1390 (cxml:text (cxml-types:param-value param))))
1391 (when (pattern-except pattern)
1392 (cxml:with-element "except"
1393 (serialize-pattern (pattern-except pattern))))))))
1395 (defun serialize-definition (defn)
1396 (cxml:with-element "define"
1397 (cxml:attribute "name" (serialization-name defn))
1398 (serialize-pattern (defn-child defn))))
1400 (defun serialize-name (name)
1401 (etypecase name
1402 (name
1403 (cxml:with-element "name"
1404 (cxml:attribute "ns" (name-uri name))
1405 (cxml:text (name-lname name))))
1406 (any-name
1407 (cxml:with-element "anyName"
1408 (when (any-name-except name)
1409 (serialize-except-name (any-name-except name)))))
1410 (ns-name
1411 (cxml:with-element "anyName"
1412 (cxml:attribute "ns" (ns-name-uri name))
1413 (when (ns-name-except name)
1414 (serialize-except-name (ns-name-except name)))))
1415 (name-class-choice
1416 (cxml:with-element "choice"
1417 (serialize-name (name-class-choice-a name))
1418 (serialize-name (name-class-choice-b name))))))
1420 (defun serialize-except-name (spec)
1421 (cxml:with-element "except"
1422 (serialize-name spec)))
1425 ;;;; simplification
1427 ;;; 4.1 Annotations
1428 ;;; Foreign attributes and elements are removed implicitly while parsing.
1430 ;;; 4.2 Whitespace
1431 ;;; All character data is discarded while parsing (which can only be
1432 ;;; whitespace after validation).
1434 ;;; Whitespace in name, type, and combine attributes is stripped while
1435 ;;; parsing. Ditto for <name/>.
1437 ;;; 4.3. datatypeLibrary attribute
1438 ;;; Escaping is done by p/pattern.
1439 ;;; Attribute value defaulting is done using *datatype-library*; only
1440 ;;; p/data and p/value record the computed value.
1442 ;;; 4.4. type attribute of value element
1443 ;;; Done by p/value.
1445 ;;; 4.5. href attribute
1446 ;;; Escaping is done by process-include and p/external-ref.
1448 ;;; FIXME: Mime-type handling should be the job of the entity resolver,
1449 ;;; but that requires xstream hacking.
1451 ;;; 4.6. externalRef element
1452 ;;; Done by p/external-ref.
1454 ;;; 4.7. include element
1455 ;;; Done by process-include.
1457 ;;; 4.8. name attribute of element and attribute elements
1458 ;;; `name' is stored as a slot, not a child. Done by p/element and
1459 ;;; p/attribute.
1461 ;;; 4.9. ns attribute
1462 ;;; done by p/name-class, p/value, p/element, p/attribute
1464 ;;; 4.10. QNames
1465 ;;; done by p/name-class
1467 ;;; 4.11. div element
1468 ;;; Legen wir gar nicht erst an.
1470 ;;; 4.12. 4.13 4.14 4.15
1471 ;;; beim anlegen
1473 ;;; 4.16
1474 ;;; p/name-class
1475 ;;; -- ausser der sache mit den datentypen
1477 ;;; 4.17, 4.18, 4.19
1478 ;;; Ueber die Grammar-und Definition Objekte, wie von James Clark
1479 ;;; beschrieben.
1481 ;;; Dabei werden keine Umbenennungen vorgenommen, weil Referenzierung
1482 ;;; durch Aufbei der Graphenstruktur zwischen ref und Definition
1483 ;;; erfolgt und Namen dann bereits aufgeloest sind. Wir benennen
1484 ;;; dafuer beim Serialisieren um.
1486 (defmethod check-recursion ((pattern element) depth)
1487 (check-recursion (pattern-child pattern) (1+ depth)))
1489 (defmethod check-recursion ((pattern ref) depth)
1490 (when (eql (pattern-crdepth pattern) depth)
1491 (rng-error nil "infinite recursion in ~A"
1492 (defn-name (pattern-target pattern))))
1493 (when (null (pattern-crdepth pattern))
1494 (setf (pattern-crdepth pattern) depth)
1495 (check-recursion (defn-child (pattern-target pattern)) depth)
1496 (setf (pattern-crdepth pattern) t)))
1498 (defmethod check-recursion ((pattern %parent) depth)
1499 (check-recursion (pattern-child pattern) depth))
1501 (defmethod check-recursion ((pattern %combination) depth)
1502 (check-recursion (pattern-a pattern) depth)
1503 (check-recursion (pattern-b pattern) depth))
1505 (defmethod check-recursion ((pattern %leaf) depth)
1506 (declare (ignore depth)))
1508 (defmethod check-recursion ((pattern data) depth)
1509 (when (pattern-except pattern)
1510 (check-recursion (pattern-except pattern) depth)))
1513 ;;;; 4.20
1515 ;;; %PARENT
1517 (defmethod fold-not-allowed ((pattern element))
1518 (setf (pattern-child pattern) (fold-not-allowed (pattern-child pattern)))
1519 pattern)
1521 (defmethod fold-not-allowed ((pattern %parent))
1522 (setf (pattern-child pattern) (fold-not-allowed (pattern-child pattern)))
1523 (if (typep (pattern-child pattern) 'not-allowed)
1524 (pattern-child pattern)
1525 pattern))
1527 ;;; %COMBINATION
1529 (defmethod fold-not-allowed ((pattern %combination))
1530 (setf (pattern-a pattern) (fold-not-allowed (pattern-a pattern)))
1531 (setf (pattern-b pattern) (fold-not-allowed (pattern-b pattern)))
1532 pattern)
1534 (defmethod fold-not-allowed ((pattern group))
1535 (call-next-method)
1536 (cond
1537 ;; remove if any child is not allowed
1538 ((typep (pattern-a pattern) 'not-allowed) (pattern-a pattern))
1539 ((typep (pattern-b pattern) 'not-allowed) (pattern-b pattern))
1540 (t pattern)))
1542 (defmethod fold-not-allowed ((pattern interleave))
1543 (call-next-method)
1544 (cond
1545 ;; remove if any child is not allowed
1546 ((typep (pattern-a pattern) 'not-allowed) (pattern-a pattern))
1547 ((typep (pattern-b pattern) 'not-allowed) (pattern-b pattern))
1548 (t pattern)))
1550 (defmethod fold-not-allowed ((pattern choice))
1551 (call-next-method)
1552 (cond
1553 ;; if any child is not allowed, choose the other
1554 ((typep (pattern-a pattern) 'not-allowed) (pattern-b pattern))
1555 ((typep (pattern-b pattern) 'not-allowed) (pattern-a pattern))
1556 (t pattern)))
1558 ;;; LEAF
1560 (defmethod fold-not-allowed ((pattern %leaf))
1561 pattern)
1563 (defmethod fold-not-allowed ((pattern data))
1564 (when (pattern-except pattern)
1565 (setf (pattern-except pattern) (fold-not-allowed (pattern-except pattern)))
1566 (when (typep (pattern-except pattern) 'not-allowed)
1567 (setf (pattern-except pattern) nil)))
1568 pattern)
1570 ;;; REF
1572 (defmethod fold-not-allowed ((pattern ref))
1573 pattern)
1576 ;;;; 4.21
1578 ;;; %PARENT
1580 (defmethod fold-empty ((pattern one-or-more))
1581 (call-next-method)
1582 (if (typep (pattern-child pattern) 'empty)
1583 (pattern-child pattern)
1584 pattern))
1586 (defmethod fold-empty ((pattern %parent))
1587 (setf (pattern-child pattern) (fold-empty (pattern-child pattern)))
1588 pattern)
1590 ;;; %COMBINATION
1592 (defmethod fold-empty ((pattern %combination))
1593 (setf (pattern-a pattern) (fold-empty (pattern-a pattern)))
1594 (setf (pattern-b pattern) (fold-empty (pattern-b pattern)))
1595 pattern)
1597 (defmethod fold-empty ((pattern group))
1598 (call-next-method)
1599 (cond
1600 ;; if any child is empty, choose the other
1601 ((typep (pattern-a pattern) 'empty) (pattern-b pattern))
1602 ((typep (pattern-b pattern) 'empty) (pattern-a pattern))
1603 (t pattern)))
1605 (defmethod fold-empty ((pattern interleave))
1606 (call-next-method)
1607 (cond
1608 ;; if any child is empty, choose the other
1609 ((typep (pattern-a pattern) 'empty) (pattern-b pattern))
1610 ((typep (pattern-b pattern) 'empty) (pattern-a pattern))
1611 (t pattern)))
1613 (defmethod fold-empty ((pattern choice))
1614 (call-next-method)
1615 (if (typep (pattern-b pattern) 'empty)
1616 (cond
1617 ((typep (pattern-a pattern) 'empty)
1618 (pattern-a pattern))
1620 (rotatef (pattern-a pattern) (pattern-b pattern))
1621 pattern))
1622 pattern))
1624 ;;; LEAF
1626 (defmethod fold-empty ((pattern %leaf))
1627 pattern)
1629 (defmethod fold-empty ((pattern data))
1630 (when (pattern-except pattern)
1631 (setf (pattern-except pattern) (fold-empty (pattern-except pattern))))
1632 pattern)
1634 ;;; REF
1636 (defmethod fold-empty ((pattern ref))
1637 pattern)
1640 ;;;; name class overlap
1642 ;;; fixme: memorize this stuff?
1644 (defparameter !uri (string (code-char 1)))
1645 (defparameter !lname "")
1647 (defun classes-overlap-p (nc1 nc2)
1648 (flet ((both-contain (x)
1649 (and (contains nc1 (car x) (cdr x))
1650 (contains nc2 (car x) (cdr x)))))
1651 (or (some #'both-contain (representatives nc1))
1652 (some #'both-contain (representatives nc2)))))
1654 (defmethod representatives ((nc any-name))
1655 (cons (cons !uri !lname)
1656 (if (any-name-except nc)
1657 (representatives (any-name-except nc))
1658 nil)))
1660 (defmethod representatives ((nc ns-name))
1661 (cons (cons (ns-name-uri nc) !lname)
1662 (if (ns-name-except nc)
1663 (representatives (ns-name-except nc))
1664 nil)))
1666 (defmethod representatives ((nc name))
1667 (list (cons (name-uri nc) (name-lname nc))))
1669 (defmethod representatives ((nc name-class-choice))
1670 (nconc (representatives (name-class-choice-a nc))
1671 (representatives (name-class-choice-b nc))))
1674 ;;;; 7.1
1676 (defun finalize-definitions (pattern)
1677 (let ((defns (make-hash-table)))
1678 (labels ((recurse (p)
1679 (cond
1680 ((typep p 'ref)
1681 (let ((target (pattern-target p)))
1682 (unless (gethash target defns)
1683 (setf (gethash target defns) t)
1684 (setf (defn-child target) (recurse (defn-child target))))
1685 (if (typep (defn-child target) 'element)
1687 (copy-pattern-tree (defn-child target)))))
1689 (etypecase p
1690 (data
1691 (when (pattern-except p)
1692 (setf (pattern-except p) (recurse (pattern-except p)))))
1693 (%parent
1694 (setf (pattern-child p) (recurse (pattern-child p))))
1695 (%combination
1696 (setf (pattern-a p) (recurse (pattern-a p)))
1697 (setf (pattern-b p) (recurse (pattern-b p))))
1698 (%leaf))
1699 p))))
1700 (values
1701 (recurse pattern)
1702 (loop
1703 for defn being each hash-key in defns
1704 collect defn)))))
1706 (defun copy-pattern-tree (pattern)
1707 (labels ((recurse (p)
1708 (let ((q (copy-structure p)))
1709 (etypecase p
1710 (data
1711 (when (pattern-except p)
1712 (setf (pattern-except q) (recurse (pattern-except p)))))
1713 (%parent
1714 (setf (pattern-child q) (recurse (pattern-child p))))
1715 (%combination
1716 (setf (pattern-a q) (recurse (pattern-a p)))
1717 (setf (pattern-b q) (recurse (pattern-b p))))
1718 ((or %leaf ref)))
1719 q)))
1720 (recurse pattern)))
1722 (defparameter *in-attribute-p* nil)
1723 (defparameter *in-one-or-more-p* nil)
1724 (defparameter *in-one-or-more//group-or-interleave-p* nil)
1725 (defparameter *in-list-p* nil)
1726 (defparameter *in-data-except-p* nil)
1727 (defparameter *in-start-p* nil)
1729 (defun check-start-restrictions (pattern)
1730 (let ((*in-start-p* t))
1731 (check-restrictions pattern)))
1733 (defun content-type-max (a b)
1734 (if (and a b)
1735 (cond
1736 ((eq a :empty) b)
1737 ((eq b :empty) a)
1738 ((eq a :complex) b)
1739 (:simple))
1740 nil))
1742 (defun groupable-max (a b)
1743 (if (or (eq a :empty)
1744 (eq b :empty)
1745 (and (eq a :complex)
1746 (eq b :complex)))
1747 (content-type-max a b)
1748 nil))
1750 (defun assert-name-class-finite (nc)
1751 (etypecase nc
1752 ((or any-name ns-name)
1753 (rng-error nil "infinite attribute name class outside of one-or-more"))
1754 (name)
1755 (name-class-choice
1756 (assert-name-class-finite (name-class-choice-a nc))
1757 (assert-name-class-finite (name-class-choice-b nc)))))
1759 (defmethod check-restrictions ((pattern attribute))
1760 (when *in-attribute-p*
1761 (rng-error nil "nested attribute not allowed"))
1762 (when *in-one-or-more//group-or-interleave-p*
1763 (rng-error nil "attribute not allowed in oneOrMore//group, oneOrMore//interleave"))
1764 (when *in-list-p*
1765 (rng-error nil "attribute in list not allowed"))
1766 (when *in-data-except-p*
1767 (rng-error nil "attribute in data/except not allowed"))
1768 (when *in-start-p*
1769 (rng-error nil "attribute in start not allowed"))
1770 (let ((*in-attribute-p* t))
1771 (unless *in-one-or-more-p*
1772 (assert-name-class-finite (pattern-name pattern)))
1773 (values (if (check-restrictions (pattern-child pattern))
1774 :empty
1775 nil)
1776 (list (pattern-name pattern))
1777 nil)))
1779 (defmethod check-restrictions ((pattern ref))
1780 (when *in-attribute-p*
1781 (rng-error nil "ref in attribute not allowed"))
1782 (when *in-list-p*
1783 (rng-error nil "ref in list not allowed"))
1784 (when *in-data-except-p*
1785 (rng-error nil "ref in data/except not allowed"))
1786 (values :complex
1788 (list (pattern-name (defn-child (pattern-target pattern))))
1789 nil))
1791 (defmethod check-restrictions ((pattern one-or-more))
1792 (when *in-data-except-p*
1793 (rng-error nil "oneOrMore in data/except not allowed"))
1794 (when *in-start-p*
1795 (rng-error nil "one-or-more in start not allowed"))
1796 (let* ((*in-one-or-more-p* t))
1797 (multiple-value-bind (x a e textp)
1798 (check-restrictions (pattern-child pattern))
1799 (values (groupable-max x x) a e textp))))
1801 (defmethod check-restrictions ((pattern group))
1802 (when *in-data-except-p*
1803 (rng-error nil "group in data/except not allowed"))
1804 (when *in-start-p*
1805 (rng-error nil "group in start not allowed"))
1806 (let ((*in-one-or-more//group-or-interleave-p*
1807 *in-one-or-more-p*))
1808 (multiple-value-bind (x a e tp) (check-restrictions (pattern-a pattern))
1809 (multiple-value-bind (y b f tq) (check-restrictions (pattern-b pattern))
1810 (dolist (nc1 a)
1811 (dolist (nc2 b)
1812 (when (classes-overlap-p nc1 nc2)
1813 (rng-error nil "attribute name overlap in group: ~A ~A"
1814 nc1 nc2))))
1815 (values (groupable-max x y)
1816 (append a b)
1817 (append e f)
1818 (or tp tq))))))
1820 (defmethod check-restrictions ((pattern interleave))
1821 (when *in-list-p*
1822 (rng-error nil "interleave in list not allowed"))
1823 (when *in-data-except-p*
1824 (rng-error nil "interleave in data/except not allowed"))
1825 (when *in-start-p*
1826 (rng-error nil "interleave in start not allowed"))
1827 (let ((*in-one-or-more//group-or-interleave-p*
1828 *in-one-or-more-p*))
1829 (multiple-value-bind (x a e tp) (check-restrictions (pattern-a pattern))
1830 (multiple-value-bind (y b f tq) (check-restrictions (pattern-b pattern))
1831 (dolist (nc1 a)
1832 (dolist (nc2 b)
1833 (when (classes-overlap-p nc1 nc2)
1834 (rng-error nil "attribute name overlap in interleave: ~A ~A"
1835 nc1 nc2))))
1836 (dolist (nc1 e)
1837 (dolist (nc2 f)
1838 (when (classes-overlap-p nc1 nc2)
1839 (rng-error nil "element name overlap in interleave: ~A ~A"
1840 nc1 nc2))))
1841 (when (and tp tq)
1842 (rng-error nil "multiple text permitted by interleave"))
1843 (values (groupable-max x y)
1844 (append a b)
1845 (append e f)
1846 (or tp tq))))))
1848 (defmethod check-restrictions ((pattern choice))
1849 (multiple-value-bind (x a e tp) (check-restrictions (pattern-a pattern))
1850 (multiple-value-bind (y b f tq) (check-restrictions (pattern-b pattern))
1851 (values (content-type-max x y)
1852 (append a b)
1853 (append e f)
1854 (or tp tq)))))
1856 (defmethod check-restrictions ((pattern list-pattern))
1857 (when *in-list-p*
1858 (rng-error nil "nested list not allowed"))
1859 (when *in-data-except-p*
1860 (rng-error nil "list in data/except not allowed"))
1861 (let ((*in-list-p* t))
1862 (check-restrictions (pattern-child pattern)))
1863 (when *in-start-p*
1864 (rng-error nil "list in start not allowed"))
1865 :simple)
1867 (defmethod check-restrictions ((pattern text))
1868 (when *in-list-p*
1869 (rng-error nil "text in list not allowed"))
1870 (when *in-data-except-p*
1871 (rng-error nil "text in data/except not allowed"))
1872 (when *in-start-p*
1873 (rng-error nil "text in start not allowed"))
1874 (values :complex nil nil t))
1876 (defmethod check-restrictions ((pattern data))
1877 (when *in-start-p*
1878 (rng-error nil "data in start not allowed"))
1879 (when (pattern-except pattern)
1880 (let ((*in-data-except-p* t))
1881 (check-restrictions (pattern-except pattern))))
1882 :simple)
1884 (defmethod check-restrictions ((pattern value))
1885 (when *in-start-p*
1886 (rng-error nil "value in start not allowed"))
1887 :simple)
1889 (defmethod check-restrictions ((pattern empty))
1890 (when *in-data-except-p*
1891 (rng-error nil "empty in data/except not allowed"))
1892 (when *in-start-p*
1893 (rng-error nil "empty in start not allowed"))
1894 :empty)
1896 (defmethod check-restrictions ((pattern element))
1897 (unless (check-restrictions (pattern-child pattern))
1898 (rng-error nil "restrictions on string sequences violated")))
1900 (defmethod check-restrictions ((pattern not-allowed))
1901 nil)