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