]> dreyeck.freedombox.rocks Git - topic-maps.git/blob - src/xtm/reader.lisp
test(xtm): register variant item-identity merge original
[topic-maps.git] / src / xtm / reader.lisp
1 (in-package #:topic-maps.xtm)
2
3 (defparameter +namespace+ "http://www.topicmaps.org/xtm/")
4 ;; This is a source tree of XML events, not a second Topic Maps object model.
5 ;; Positions are SAX approximations at the end of a start tag, never byte spans.
6 (defstruct node uri name attributes children line column)
7 (defclass source-handler (sax:default-handler)
8 ((stack :initform nil :accessor handler-stack)
9 (root :initform nil :accessor handler-root)))
10 (defmethod sax:start-element ((h source-handler) uri local qname attributes)
11 (declare (ignore qname))
12 (let ((node (make-node :uri uri :name local :line (sax:line-number h)
13 :column (sax:column-number h)
14 :attributes (mapcar (lambda (a)
15 (list (sax:attribute-namespace-uri a)
16 (sax:attribute-local-name a)
17 (sax:attribute-value a))) attributes))))
18 (if (handler-stack h) (push node (node-children (first (handler-stack h))))
19 (setf (handler-root h) node))
20 (push node (handler-stack h))))
21 (defmethod sax:characters ((h source-handler) data)
22 (when (handler-stack h) (push (copy-seq data) (node-children (first (handler-stack h))))))
23 (defmethod sax:end-element ((h source-handler) uri local qname)
24 (declare (ignore uri local qname))
25 (let ((node (pop (handler-stack h)))) (setf (node-children node) (nreverse (node-children node)))))
26 (defmethod sax:end-document ((h source-handler)) (handler-root h))
27
28 (defun xml-space-p (c) (find c '(#\Space #\Tab #\Newline #\Return)))
29 (defun collapse-space (text)
30 ;; xsd:ID has whiteSpace=collapse, even with a non-validating XML processor.
31 (with-output-to-string (out)
32 (let ((written nil) (pending nil))
33 (loop for c across text do
34 (if (xml-space-p c) (when written (setf pending t))
35 (progn (when pending (write-char #\Space out))
36 (write-char c out) (setf written t pending nil)))))))
37 (defun ncname-p (text)
38 ;; Use the pinned XML processor's XML 1.0 name character tables; exclude ':'
39 ;; for XML Schema ID/NCName and XPointer shorthand pointers (XTM 4.5/4.20).
40 (and (plusp (length text)) (not (find #\: text))
41 (cxml::valid-name-p (runes:string-rod text))))
42 (defun attributes (node allowed required)
43 (dolist (attr (node-attributes node))
44 (unless (and (or (null (first attr)) (equal (first attr) ""))
45 (member (second attr) allowed :test #'string=))
46 (reject :unexpected-attribute (format nil "Attribute ~S on ~A." (second attr) (node-name node)) node)))
47 (dolist (name required)
48 (unless (find name (node-attributes node) :key #'second :test #'string=)
49 (reject (if (string= name "id") :missing-id :missing-attribute)
50 (format nil "Required ~A attribute is absent." name) node))))
51 (defun attr (node name)
52 (third (find name (node-attributes node) :key #'second :test #'string=)))
53 (defun elements (node)
54 (loop for child in (node-children node)
55 if (stringp child) do
56 (unless (every #'xml-space-p child)
57 (reject :unexpected-text "Only XML whitespace is allowed here." node))
58 else collect child))
59 (defun check-namespace (node)
60 (unless (equal (node-uri node) +namespace+)
61 (reject :invalid-namespace "Expected the XTM 2.0 namespace." node)))
62 (defun unsupported (node)
63 (reject :unsupported-construct (format nil "XTM ~A is not implemented in this subset." (node-name node))
64 node 'xtm-unsupported))
65 (defun check-reifier (node)
66 (when (attr node "reifier")
67 (reject :reification "XTM Reification is outside this subset." node 'xtm-unsupported)))
68 (defun leaf-href (node)
69 (attributes node '("href") '("href"))
70 (when (elements node) (reject :unexpected-child "A locator element must be empty." node))
71 (resolve-iri (attr node "href") *document-iri* node))
72 (defun reference-iri (node)
73 (let* ((iri (leaf-href node)) (fragment (iri-parts-fragment (split-iri iri))))
74 (unless (and fragment (ncname-p fragment))
75 (reject :invalid-topic-ref "topicRef requires an XPointer shorthand fragment." node))
76 iri))
77
78 (defun validate-source (root)
79 "Check the supported XTM schema before model construction; keep event order.
80 Unsupported legal extension points are explicit; no claim to validate excluded
81 constructs' complete subgrammars is made. XML errors have already been checked."
82 (let ((ids (make-hash-table :test #'equal))) ; XML ID uniqueness only, no Topics.
83 (labels ((validate (node context)
84 (check-namespace node)
85 (let ((name (node-name node)))
86 (unless (member name context :test #'string=)
87 (reject :unexpected-element (format nil "Unexpected ~A element." name) node))
88 (cond
89 ((string= name "topicMap")
90 (attributes node '("version" "reifier") '("version"))
91 (unless (equal (attr node "version") "2.0")
92 (reject :invalid-version "This reader accepts XTM version 2.0 only." node))
93 (check-reifier node)
94 (let ((phase 0))
95 (dolist (child (elements node))
96 (let* ((name (node-name child))
97 (next (cond ((string= name "itemIdentity") 0)
98 ((string= name "mergeMap") 1) (t 2))))
99 (when (< next phase) (reject :element-order "topicMap child order is invalid." child))
100 (setf phase next)
101 (validate child '("itemIdentity" "mergeMap" "topic" "association"))))))
102 ((string= name "topic")
103 (attributes node '("id") '("id"))
104 (let ((id (collapse-space (attr node "id"))))
105 (unless (ncname-p id) (reject :invalid-id "topic/@id must be an XML Schema ID." node))
106 (when (gethash id ids) (reject :duplicate-id "Duplicate XML ID in this document." node))
107 (setf (gethash id ids) t))
108 (let ((phase 0) (instance-seen nil))
109 (dolist (child (elements node))
110 (let* ((name (node-name child))
111 (next (cond ((member name '("itemIdentity" "subjectLocator" "subjectIdentifier")
112 :test #'string=) 0)
113 ((string= name "instanceOf") 1) (t 2))))
114 (when (< next phase) (reject :element-order "topic child order is invalid." child))
115 (when (= next 1)
116 (when instance-seen (reject :duplicate-instance-of "Only one instanceOf element is allowed." child))
117 (setf instance-seen t))
118 (setf phase next)
119 (validate child '("itemIdentity" "subjectLocator" "subjectIdentifier" "instanceOf" "name" "occurrence"))))))
120 ((string= name "instanceOf")
121 (attributes node nil nil)
122 (unless (elements node) (reject :empty-instance-of "instanceOf needs at least one topicRef." node))
123 (dolist (child (elements node)) (validate child '("topicRef"))))
124 ((string= name "name")
125 (attributes node '("reifier") nil)
126 (check-reifier node)
127 (let ((phase 0) (type-seen nil) (scope-seen nil) (value-seen nil))
128 (dolist (child (elements node))
129 (check-namespace child)
130 (let* ((kind (node-name child))
131 (next (position kind '("itemIdentity" "type" "scope" "value" "variant") :test #'string=)))
132 (unless next (reject :unexpected-element (format nil "Unexpected ~A element." kind) child))
133 (when (or (< next phase) (and (string= kind "variant") (not value-seen)))
134 (reject :element-order "name child order is invalid." child))
135 (setf phase next)
136 (cond
137 ((member kind '("itemIdentity" "variant") :test #'string=) nil)
138 ((string= kind "type")
139 (when type-seen (reject :duplicate-name-type "Only one name type is allowed." child))
140 (setf type-seen t))
141 ((string= kind "scope")
142 (when scope-seen (reject :duplicate-name-scope "Only one name scope is allowed." child))
143 (setf scope-seen t))
144 ((string= kind "value")
145 (when value-seen (reject :duplicate-name-value "Only one name value is allowed." child))
146 (setf value-seen t))
147 ;; Valid extension points remain explicitly unsupported.
148 ;; Their complete subgrammars are outside this subset.
149 (t (unsupported child)))
150 (validate child '("itemIdentity" "type" "scope" "value" "variant"))))
151 (unless value-seen (reject :missing-name-value "name requires a value element." node))))
152 ((string= name "variant")
153 (attributes node '("reifier") nil)
154 (check-reifier node)
155 (let ((phase 0) (scope-seen nil) (resource-seen nil))
156 (dolist (child (elements node))
157 (check-namespace child)
158 (let* ((kind (node-name child))
159 (next (cond ((string= kind "itemIdentity") 0)
160 ((string= kind "scope") 1)
161 ((member kind '("resourceData" "resourceRef") :test #'string=) 2))))
162 (unless next (reject :unexpected-element (format nil "Unexpected ~A element." kind) child))
163 (when (< next phase) (reject :element-order "variant child order is invalid." child))
164 (setf phase next)
165 (cond
166 ((string= kind "itemIdentity") (leaf-href child) (unsupported child))
167 ((string= kind "scope")
168 (when scope-seen (reject :duplicate-variant-scope "Only one variant scope is allowed." child))
169 (setf scope-seen t))
170 (t
171 (unless scope-seen (reject :missing-variant-scope "variant requires scope before its resource." child))
172 (when resource-seen (reject :variant-resource-cardinality "variant requires exactly one resource." child))
173 (setf resource-seen t)))
174 (validate child '("scope" "resourceData" "resourceRef"))))
175 (unless scope-seen (reject :missing-variant-scope "variant requires a scope element." node))
176 (unless resource-seen (reject :missing-variant-resource "variant requires a resource element." node))))
177 ((string= name "resourceRef") (leaf-href node) (unsupported node))
178 ((string= name "resourceData")
179 (attributes node '("datatype") nil)
180 (when (and (attr node "datatype")
181 (not (equal (attr node "datatype") (topic-maps.tmdm:string-datatype))))
182 (reject :resource-data-datatype "Only textual xsd:string resourceData is implemented." node 'xtm-unsupported))
183 (dolist (child (node-children node))
184 (unless (stringp child)
185 (if (equal (node-uri child) +namespace+)
186 (reject :unexpected-child "resourceData cannot contain XTM markup." child)
187 (reject :resource-data-markup "Embedded XML resourceData is outside this subset." child 'xtm-unsupported)))))
188 ((string= name "type")
189 (attributes node nil nil)
190 (let ((refs (elements node)))
191 (unless (= 1 (length refs)) (reject :type-cardinality "type requires exactly one topicRef." node))
192 (validate (first refs) '("topicRef"))))
193 ((string= name "scope")
194 (attributes node nil nil)
195 (unless (elements node) (reject :empty-scope "scope requires at least one topicRef." node))
196 (dolist (child (elements node)) (validate child '("topicRef"))))
197 ((string= name "value")
198 (attributes node nil nil)
199 ;; VALUE accepts all character data, including empty text and
200 ;; whitespace. ELEMENTS would apply the wrong text policy.
201 (dolist (child (node-children node))
202 (unless (stringp child) (reject :unexpected-child "value accepts character data only." child))))
203 ((string= name "topicRef") (reference-iri node))
204 ((member name '("itemIdentity" "subjectIdentifier" "subjectLocator") :test #'string=)
205 (leaf-href node))
206 (t (unsupported node))))))
207 (validate root '("topicMap"))))
208 root)
209
210 (defun find-reference-topic (map iri)
211 ;; XTM 4.20 searches the actual model, not a speculative pre-scan registry.
212 ;; Unlike INTERN-TOPIC, a hit MUST NOT add another identifier category.
213 (let ((topic (find-if (lambda (topic)
214 (or (member iri (topic-maps.tmdm:topic-subject-identifiers topic) :test #'string=)
215 (member iri (topic-maps.tmdm:topic-item-identifiers topic) :test #'string=)))
216 (topic-maps.tmdm:topic-map-topics map))))
217 (if topic (topic-maps.tmdm:canonical-topic topic)
218 (topic-maps.tmdm:intern-topic map :item-identifier iri))))
219 (defun core-topic (map local)
220 (topic-maps.tmdm:intern-topic map :subject-identifier
221 (concatenate 'string "http://psi.topicmaps.org/iso13250/model/" local)))
222 (defun read-instance-of (node owner map)
223 (dolist (ref (elements node))
224 (let ((type (find-reference-topic map (reference-iri ref))))
225 (topic-maps.tmdm:make-association map (core-topic map "type-instance")
226 (list (list (core-topic map "type") type)
227 (list (core-topic map "instance") (topic-maps.tmdm:canonical-topic owner)))))))
228 (defun read-variant (node name map)
229 (let* ((children (elements node))
230 (scope-node (find "scope" children :key #'node-name :test #'string=))
231 (data-node (find "resourceData" children :key #'node-name :test #'string=))
232 (explicit (mapcar (lambda (ref) (find-reference-topic map (reference-iri ref))) (elements scope-node)))
233 (value (with-output-to-string (out)
234 (dolist (part (node-children data-node)) (write-string part out)))))
235 ;; ADD-VARIANT canonicalizes the union and enforces the proper superset.
236 ;; A nonempty explicit scope may still add no theme to the Name scope.
237 (topic-maps.tmdm:add-variant name value
238 :scope (append (topic-maps.tmdm:topic-name-scope name) explicit))))
239 (defun read-name (node owner map)
240 (let* ((children (elements node))
241 (type-node (find "type" children :key #'node-name :test #'string=))
242 (scope-node (find "scope" children :key #'node-name :test #'string=))
243 (type (when type-node (find-reference-topic map (reference-iri (first (elements type-node))))))
244 (scope (when scope-node (mapcar (lambda (ref) (find-reference-topic map (reference-iri ref)))
245 (elements scope-node))))
246 (value-node (find "value" children :key #'node-name :test #'string=))
247 (value (with-output-to-string (out)
248 (dolist (part (node-children value-node)) (write-string part out)))))
249 ;; SAX has already resolved XML character/entity references. Preserve the
250 ;; resulting Unicode sequence without trimming or decoding it again.
251 ;; ADD-NAME owns canonical set semantics and normalization after merging.
252 (let ((name (if type-node
253 (topic-maps.tmdm:add-name owner value :type type :scope scope)
254 (topic-maps.tmdm:add-default-name owner value :scope scope))))
255 ;; Item identifiers belong to the canonical Name, never its owner/type.
256 ;; Use the shared model API for set semantics and global conflicts.
257 (dolist (child children name)
258 (cond ((string= (node-name child) "itemIdentity")
259 (setf name (topic-maps.tmdm:add-item-identifier name (leaf-href child))))
260 ((string= (node-name child) "variant") (read-variant child name map)))))))
261 (defun read-topic (node map)
262 (let ((topic (topic-maps.tmdm:intern-topic map :item-identifier
263 (concatenate 'string *document-iri* "#" (collapse-space (attr node "id"))))))
264 (dolist (child (elements node))
265 (let ((name (node-name child)))
266 (cond
267 ((string= name "instanceOf") (read-instance-of child topic map))
268 ((string= name "name") (read-name child topic map))
269 (t (setf topic (topic-maps.tmdm:add-topic-identifier topic
270 (cond ((string= name "itemIdentity") :item-identifier)
271 ((string= name "subjectIdentifier") :subject-identifier)
272 (t :subject-locator))
273 (leaf-href child)))))))
274 (topic-maps.tmdm:canonical-topic topic)))
275 (defun deserialize-octets (bytes &key document-iri source-key)
276 "Deserialize raw XML octets into a new TMDM Topic Map (XTM 2.0 identity/Name subset).
277 DOCUMENT-IRI is required, absolute and fragment-free. SOURCE-KEY is a diagnostic
278 label only. XML positions are approximate SAX line/column values, not spans.
279 XML-policy errors, XTM rejection/unsupported and original TMDM conflicts remain
280 distinct. No resources are fetched. No externally supplied Map is mutated."
281 (check-type bytes (vector (unsigned-byte 8)))
282 (let ((*document-iri* document-iri) (*source-key* source-key)
283 (handler (make-instance 'source-handler)))
284 (require-document-iri document-iri)
285 (let* ((root
286 (handler-case (topic-maps.xml:parse-octets bytes handler)
287 (cxml:well-formedness-violation (c)
288 (error 'xtm-xml-error :code :xml-not-well-formed :cause c
289 :detail (princ-to-string c) :document-iri document-iri :source-key source-key
290 :line (sax:line-number handler) :column (sax:column-number handler)))
291 (topic-maps.xml:doctype-forbidden (c)
292 (error 'xtm-xml-error :code :doctype-forbidden :cause c
293 :detail "DOCTYPE forbidden by the mandatory XML byte boundary."
294 :document-iri document-iri :source-key source-key
295 :line (sax:line-number handler) :column (sax:column-number handler)))))
296 (map (topic-maps.tmdm:make-topic-map)))
297 (validate-source root)
298 (dolist (child (elements root))
299 (if (string= (node-name child) "itemIdentity")
300 (topic-maps.tmdm:add-item-identifier map (leaf-href child))
301 (read-topic child map)))
302 map)))