]> dreyeck.freedombox.rocks Git - topic-maps.git/blob - src/xtm/reader.lisp
Support arbitrary absolute XTM resourceData datatypes (Slice 22D)
[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 leaf-href (node)
66 (attributes node '("href") '("href"))
67 (when (elements node) (reject :unexpected-child "A locator element must be empty." node))
68 (resolve-iri (attr node "href") *document-iri* node))
69 (defun reference-iri (node)
70 (let* ((iri (leaf-href node)) (fragment (iri-parts-fragment (split-iri iri))))
71 (unless (and fragment (ncname-p fragment))
72 (reject :invalid-topic-ref "topicRef requires an XPointer shorthand fragment." node))
73 iri))
74
75 (defun validate-source (root)
76 "Check the supported XTM schema before model construction; keep event order.
77 Unsupported legal extension points are explicit; no claim to validate excluded
78 constructs' complete subgrammars is made. XML errors have already been checked."
79 (let ((ids (make-hash-table :test #'equal))) ; XML ID uniqueness only, no Topics.
80 (labels ((validate (node context)
81 (check-namespace node)
82 (let ((name (node-name node)))
83 (unless (member name context :test #'string=)
84 (reject :unexpected-element (format nil "Unexpected ~A element." name) node))
85 (cond
86 ((string= name "topicMap")
87 (attributes node '("version" "reifier") '("version"))
88 (unless (equal (attr node "version") "2.0")
89 (reject :invalid-version "This reader accepts XTM version 2.0 only." node))
90 (when (attr node "reifier")
91 (resolve-iri (attr node "reifier") *document-iri* node))
92 (let ((phase 0))
93 (dolist (child (elements node))
94 (let* ((name (node-name child))
95 (next (cond ((string= name "itemIdentity") 0)
96 ((string= name "mergeMap") 1) (t 2))))
97 (when (< next phase) (reject :element-order "topicMap child order is invalid." child))
98 (setf phase next)
99 (validate child '("itemIdentity" "mergeMap" "topic" "association"))))))
100 ((string= name "topic")
101 (attributes node '("id") '("id"))
102 (let ((id (collapse-space (attr node "id"))))
103 (unless (ncname-p id) (reject :invalid-id "topic/@id must be an XML Schema ID." node))
104 (when (gethash id ids) (reject :duplicate-id "Duplicate XML ID in this document." node))
105 (setf (gethash id ids) t))
106 (let ((phase 0) (instance-seen nil))
107 (dolist (child (elements node))
108 (let* ((name (node-name child))
109 (next (cond ((member name '("itemIdentity" "subjectLocator" "subjectIdentifier")
110 :test #'string=) 0)
111 ((string= name "instanceOf") 1) (t 2))))
112 (when (< next phase) (reject :element-order "topic child order is invalid." child))
113 (when (= next 1)
114 (when instance-seen (reject :duplicate-instance-of "Only one instanceOf element is allowed." child))
115 (setf instance-seen t))
116 (setf phase next)
117 (validate child '("itemIdentity" "subjectLocator" "subjectIdentifier" "instanceOf" "name" "occurrence"))))))
118 ((string= name "instanceOf")
119 (attributes node nil nil)
120 (unless (elements node) (reject :empty-instance-of "instanceOf needs at least one topicRef." node))
121 (dolist (child (elements node)) (validate child '("topicRef"))))
122 ((string= name "name")
123 (attributes node '("reifier") nil)
124 (when (attr node "reifier")
125 (resolve-iri (attr node "reifier") *document-iri* node))
126 (let ((phase 0) (type-seen nil) (scope-seen nil) (value-seen nil))
127 (dolist (child (elements node))
128 (check-namespace child)
129 (let* ((kind (node-name child))
130 (next (position kind '("itemIdentity" "type" "scope" "value" "variant") :test #'string=)))
131 (unless next (reject :unexpected-element (format nil "Unexpected ~A element." kind) child))
132 (when (or (< next phase) (and (string= kind "variant") (not value-seen)))
133 (reject :element-order "name child order is invalid." child))
134 (setf phase next)
135 (cond
136 ((member kind '("itemIdentity" "variant") :test #'string=) nil)
137 ((string= kind "type")
138 (when type-seen (reject :duplicate-name-type "Only one name type is allowed." child))
139 (setf type-seen t))
140 ((string= kind "scope")
141 (when scope-seen (reject :duplicate-name-scope "Only one name scope is allowed." child))
142 (setf scope-seen t))
143 ((string= kind "value")
144 (when value-seen (reject :duplicate-name-value "Only one name value is allowed." child))
145 (setf value-seen t))
146 ;; Valid extension points remain explicitly unsupported.
147 ;; Their complete subgrammars are outside this subset.
148 (t (unsupported child)))
149 (validate child '("itemIdentity" "type" "scope" "value" "variant"))))
150 (unless value-seen (reject :missing-name-value "name requires a value element." node))))
151 ((string= name "variant")
152 (attributes node '("reifier") nil)
153 (when (attr node "reifier") (resolve-iri (attr node "reifier") *document-iri* node))
154 (let ((phase 0) (scope-seen nil) (resource-seen nil))
155 (dolist (child (elements node))
156 (check-namespace child)
157 (let* ((kind (node-name child))
158 (next (cond ((string= kind "itemIdentity") 0)
159 ((string= kind "scope") 1)
160 ((member kind '("resourceData" "resourceRef") :test #'string=) 2))))
161 (unless next (reject :unexpected-element (format nil "Unexpected ~A element." kind) child))
162 (when (< next phase) (reject :element-order "variant child order is invalid." child))
163 (setf phase next)
164 (cond
165 ((string= kind "itemIdentity") nil)
166 ((string= kind "scope")
167 (when scope-seen (reject :duplicate-variant-scope "Only one variant scope is allowed." child))
168 (setf scope-seen t))
169 (t
170 (unless scope-seen (reject :missing-variant-scope "variant requires scope before its resource." child))
171 (when resource-seen (reject :variant-resource-cardinality "variant requires exactly one resource." child))
172 (setf resource-seen t)))
173 (validate child '("itemIdentity" "scope" "resourceData" "resourceRef"))))
174 (unless scope-seen (reject :missing-variant-scope "variant requires a scope element." node))
175 (unless resource-seen (reject :missing-variant-resource "variant requires a resource element." node))))
176 ((string= name "resourceRef") (leaf-href node))
177 ((string= name "resourceData")
178 (attributes node '("datatype") nil)
179 (let ((datatype (attr node "datatype")))
180 ;; DATATYPE is already an absolute IRI, not content to
181 ;; resolve against the document or percent-normalize.
182 (when datatype
183 (unless (iri-parts-scheme (split-iri datatype))
184 (reject :invalid-resource-data-datatype "resourceData datatype must be an absolute IRI." node))
185 (validate-decoded-reference (unescape-reference datatype node) node)
186 (when (equal datatype "http://www.w3.org/2001/XMLSchema#anyType")
187 (reject :resource-data-datatype "xsd:anyType XML canonicalization is outside this subset." node 'xtm-unsupported)))
188 (dolist (child (node-children node))
189 (unless (stringp child)
190 (reject :unexpected-child "Textual resourceData cannot contain child elements." child)))))
191 ((string= name "type")
192 (attributes node nil nil)
193 (let ((refs (elements node)))
194 (unless (= 1 (length refs)) (reject :type-cardinality "type requires exactly one topicRef." node))
195 (validate (first refs) '("topicRef"))))
196 ((string= name "scope")
197 (attributes node nil nil)
198 (unless (elements node) (reject :empty-scope "scope requires at least one topicRef." node))
199 (dolist (child (elements node)) (validate child '("topicRef"))))
200 ((string= name "value")
201 (attributes node nil nil)
202 ;; VALUE accepts all character data, including empty text and
203 ;; whitespace. ELEMENTS would apply the wrong text policy.
204 (dolist (child (node-children node))
205 (unless (stringp child) (reject :unexpected-child "value accepts character data only." child))))
206 ((string= name "topicRef") (reference-iri node))
207 ((member name '("itemIdentity" "subjectIdentifier" "subjectLocator") :test #'string=)
208 (leaf-href node))
209 (t (unsupported node))))))
210 (validate root '("topicMap"))))
211 root)
212
213 (defun find-reference-topic (map iri)
214 ;; XTM 4.20 searches the actual model, not a speculative pre-scan registry.
215 ;; Unlike INTERN-TOPIC, a hit MUST NOT add another identifier category.
216 (let ((topic (find-if (lambda (topic)
217 (or (member iri (topic-maps.tmdm:topic-subject-identifiers topic) :test #'string=)
218 (member iri (topic-maps.tmdm:topic-item-identifiers topic) :test #'string=)))
219 (topic-maps.tmdm:topic-map-topics map))))
220 (if topic (topic-maps.tmdm:canonical-topic topic)
221 (topic-maps.tmdm:intern-topic map :item-identifier iri))))
222 (defun read-item-reifier (node item map)
223 ;; XTM 4.3.2 looks up Item Identifiers only, unlike topicRef (4.20).
224 ;; INTERN-TOPIC adds the II on a miss; any SI/II identity merging then
225 ;; follows the existing TMDM rules, independently of this lookup.
226 (when (attr node "reifier")
227 (let* ((iri (resolve-iri (attr node "reifier") *document-iri* node))
228 (topic (or (find iri (topic-maps.tmdm:topic-map-topics map)
229 :test (lambda (iri topic)
230 (member iri (topic-maps.tmdm:topic-item-identifiers topic) :test #'string=)))
231 (topic-maps.tmdm:intern-topic map :item-identifier iri))))
232 (return-from read-item-reifier (topic-maps.tmdm:set-item-reifier item topic))))
233 item)
234 (defun read-map-reifier (node map)
235 (read-item-reifier node map map))
236 (defun core-topic (map local)
237 (topic-maps.tmdm:intern-topic map :subject-identifier
238 (concatenate 'string "http://psi.topicmaps.org/iso13250/model/" local)))
239 (defun read-instance-of (node owner map)
240 (dolist (ref (elements node))
241 (let ((type (find-reference-topic map (reference-iri ref))))
242 (topic-maps.tmdm:make-association map (core-topic map "type-instance")
243 (list (list (core-topic map "type") type)
244 (list (core-topic map "instance") (topic-maps.tmdm:canonical-topic owner)))))))
245 (defun read-resource-value (resource)
246 "Return value and datatype for a validated resource node (XTM 4.16/4.17).
247 This operation neither looks up Topics nor fetches resources. ANYTYPE is rejected
248 by source validation before model construction. Preserve other datatype IRIs."
249 (if (string= (node-name resource) "resourceRef")
250 (values (leaf-href resource) (topic-maps.tmdm:iri-datatype))
251 (let ((datatype (or (attr resource "datatype") (topic-maps.tmdm:string-datatype)))
252 (text (with-output-to-string (out)
253 (dolist (part (node-children resource)) (write-string part out)))))
254 (values (if (equal datatype (topic-maps.tmdm:iri-datatype))
255 (resolve-iri text *document-iri* resource)
256 text)
257 datatype))))
258 (defun read-variant (node name map)
259 (let* ((children (elements node))
260 (scope-node (find "scope" children :key #'node-name :test #'string=))
261 (resource (find-if (lambda (child) (member (node-name child) '("resourceData" "resourceRef") :test #'string=)) children))
262 (explicit (mapcar (lambda (ref) (find-reference-topic map (reference-iri ref))) (elements scope-node))))
263 (multiple-value-bind (value datatype) (read-resource-value resource)
264 ;; ADD-VARIANT owns canonicalization and the proper-superset constraint.
265 (let ((variant (topic-maps.tmdm:add-variant name value :datatype datatype
266 :scope (append (topic-maps.tmdm:topic-name-scope name) explicit))))
267 (dolist (child children)
268 (when (string= (node-name child) "itemIdentity")
269 (setf variant (topic-maps.tmdm:add-item-identifier variant (leaf-href child)))))
270 ;; Reification may normalize again; retain the native canonical handle.
271 (topic-maps.tmdm:canonical-variant (read-item-reifier node variant map))))))
272 (defun read-name (node owner map)
273 (let* ((children (elements node))
274 (type-node (find "type" children :key #'node-name :test #'string=))
275 (scope-node (find "scope" children :key #'node-name :test #'string=))
276 (type (when type-node (find-reference-topic map (reference-iri (first (elements type-node))))))
277 (scope (when scope-node (mapcar (lambda (ref) (find-reference-topic map (reference-iri ref)))
278 (elements scope-node))))
279 (value-node (find "value" children :key #'node-name :test #'string=))
280 (value (with-output-to-string (out)
281 (dolist (part (node-children value-node)) (write-string part out)))))
282 ;; SAX has already resolved XML character/entity references. Preserve the
283 ;; resulting Unicode sequence without trimming or decoding it again.
284 ;; ADD-NAME owns canonical set semantics and normalization after merging.
285 (let ((name (if type-node
286 (topic-maps.tmdm:add-name owner value :type type :scope scope)
287 (topic-maps.tmdm:add-default-name owner value :scope scope))))
288 ;; Item identifiers belong to the canonical Name, never its owner/type.
289 ;; Use the shared model API for set semantics and global conflicts.
290 (dolist (child children)
291 (when (string= (node-name child) "itemIdentity")
292 (setf name (topic-maps.tmdm:add-item-identifier name (leaf-href child)))))
293 ;; ADD-NAME may have returned an existing canonical Name. Reifier
294 ;; resolution/merging can normalize it again: retain the native result
295 ;; before processing Variants and return the current Name handle.
296 (setf name (read-item-reifier node name map))
297 (dolist (child children)
298 (when (string= (node-name child) "variant") (read-variant child name map)))
299 (topic-maps.tmdm:canonical-topic-name name))))
300 (defun read-topic (node map)
301 (let ((topic (topic-maps.tmdm:intern-topic map :item-identifier
302 (concatenate 'string *document-iri* "#" (collapse-space (attr node "id"))))))
303 (dolist (child (elements node))
304 (let ((name (node-name child)))
305 (cond
306 ((string= name "instanceOf") (read-instance-of child topic map))
307 ((string= name "name") (read-name child topic map))
308 (t (setf topic (topic-maps.tmdm:add-topic-identifier topic
309 (cond ((string= name "itemIdentity") :item-identifier)
310 ((string= name "subjectIdentifier") :subject-identifier)
311 (t :subject-locator))
312 (leaf-href child)))))))
313 (topic-maps.tmdm:canonical-topic topic)))
314 (defun deserialize-octets (bytes &key document-iri source-key)
315 "Deserialize raw XML octets into a new TMDM Topic Map (XTM 2.0 identity/Name subset).
316 DOCUMENT-IRI is required, absolute and fragment-free. SOURCE-KEY is a diagnostic
317 label only. XML positions are approximate SAX line/column values, not spans.
318 XML-policy errors, XTM rejection/unsupported and original TMDM conflicts remain
319 distinct. No resources are fetched. No externally supplied Map is mutated."
320 (check-type bytes (vector (unsigned-byte 8)))
321 (let ((*document-iri* document-iri) (*source-key* source-key)
322 (handler (make-instance 'source-handler)))
323 (require-document-iri document-iri)
324 (let* ((root
325 (handler-case (topic-maps.xml:parse-octets bytes handler)
326 (cxml:well-formedness-violation (c)
327 (error 'xtm-xml-error :code :xml-not-well-formed :cause c
328 :detail (princ-to-string c) :document-iri document-iri :source-key source-key
329 :line (sax:line-number handler) :column (sax:column-number handler)))
330 (topic-maps.xml:doctype-forbidden (c)
331 (error 'xtm-xml-error :code :doctype-forbidden :cause c
332 :detail "DOCTYPE forbidden by the mandatory XML byte boundary."
333 :document-iri document-iri :source-key source-key
334 :line (sax:line-number handler) :column (sax:column-number handler)))))
335 (map (topic-maps.tmdm:make-topic-map)))
336 (validate-source root)
337 ;; The attribute is processed before itemIdentity and later Topic nodes.
338 (read-map-reifier root map)
339 (dolist (child (elements root))
340 (if (string= (node-name child) "itemIdentity")
341 (topic-maps.tmdm:add-item-identifier map (leaf-href child))
342 (read-topic child map)))
343 map)))