]> dreyeck.freedombox.rocks Git - topic-maps.git/blob - src/xtm/reader.lisp
Document XTM normative coverage and remaining qualification gaps
[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 "mergeMap") (mergemap-iri node))
101 ((string= name "topic")
102 (attributes node '("id") '("id"))
103 (let ((id (collapse-space (attr node "id"))))
104 (unless (ncname-p id) (reject :invalid-id "topic/@id must be an XML Schema ID." node))
105 (when (gethash id ids) (reject :duplicate-id "Duplicate XML ID in this document." node))
106 (setf (gethash id ids) t))
107 (let ((phase 0) (instance-seen nil))
108 (dolist (child (elements node))
109 (let* ((name (node-name child))
110 (next (cond ((member name '("itemIdentity" "subjectLocator" "subjectIdentifier")
111 :test #'string=) 0)
112 ((string= name "instanceOf") 1) (t 2))))
113 (when (< next phase) (reject :element-order "topic child order is invalid." child))
114 (when (= next 1)
115 (when instance-seen (reject :duplicate-instance-of "Only one instanceOf element is allowed." child))
116 (setf instance-seen t))
117 (setf phase next)
118 (validate child '("itemIdentity" "subjectLocator" "subjectIdentifier" "instanceOf" "name" "occurrence"))))))
119 ((string= name "instanceOf")
120 (attributes node nil nil)
121 (unless (elements node) (reject :empty-instance-of "instanceOf needs at least one topicRef." node))
122 (dolist (child (elements node)) (validate child '("topicRef"))))
123 ((string= name "name")
124 (attributes node '("reifier") nil)
125 (when (attr node "reifier")
126 (resolve-iri (attr node "reifier") *document-iri* 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 (when (attr node "reifier") (resolve-iri (attr node "reifier") *document-iri* 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") nil)
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 '("itemIdentity" "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 "occurrence")
178 (attributes node '("reifier") nil)
179 (when (attr node "reifier")
180 (resolve-iri (attr node "reifier") *document-iri* node))
181 (let ((phase 0) (type-seen nil) (scope-seen nil) (resource-seen nil))
182 (dolist (child (elements node))
183 (check-namespace child)
184 (let* ((kind (node-name child))
185 (next (cond ((string= kind "itemIdentity") 0)
186 ((string= kind "type") 1)
187 ((string= kind "scope") 2)
188 ((member kind '("resourceData" "resourceRef") :test #'string=) 3))))
189 (unless next (reject :unexpected-element (format nil "Unexpected ~A element." kind) child))
190 (when (< next phase) (reject :element-order "occurrence child order is invalid." child))
191 (setf phase next)
192 (cond
193 ((string= kind "itemIdentity") nil)
194 ((string= kind "type")
195 (when type-seen (reject :duplicate-occurrence-type "Only one occurrence type is allowed." child))
196 (setf type-seen t))
197 ((string= kind "scope")
198 (unless type-seen (reject :missing-occurrence-type "occurrence requires type before scope." child))
199 (when scope-seen (reject :duplicate-occurrence-scope "Only one occurrence scope is allowed." child))
200 (setf scope-seen t))
201 (t
202 (unless type-seen (reject :missing-occurrence-type "occurrence requires type before its resource." child))
203 (when resource-seen (reject :occurrence-resource-cardinality "occurrence requires exactly one resource." child))
204 (setf resource-seen t)))
205 (validate child '("itemIdentity" "type" "scope" "resourceData" "resourceRef"))))
206 (unless type-seen (reject :missing-occurrence-type "occurrence requires a type element." node))
207 (unless resource-seen (reject :missing-occurrence-resource "occurrence requires a resource element." node))))
208 ((member name '("association" "role") :test #'string=)
209 (attributes node '("reifier") nil)
210 (when (attr node "reifier")
211 (resolve-iri (attr node "reifier") *document-iri* node))
212 (let ((association-p (string= name "association"))
213 (phase 0) (type-seen nil) (scope-seen nil) (participants 0))
214 (dolist (child (elements node))
215 (check-namespace child)
216 (let* ((kind (node-name child))
217 (next (cond ((string= kind "itemIdentity") 0)
218 ((string= kind "type") 1)
219 ((and association-p (string= kind "scope")) 2)
220 ((string= kind (if association-p "role" "topicRef")) 3))))
221 (unless next (reject :unexpected-element (format nil "Unexpected ~A element." kind) child))
222 (when (< next phase) (reject :element-order (format nil "~A child order is invalid." name) child))
223 (setf phase next)
224 (cond
225 ((string= kind "itemIdentity") nil)
226 ((string= kind "type")
227 (when type-seen (reject :duplicate-type (format nil "Only one ~A type is allowed." name) child))
228 (setf type-seen t))
229 (t
230 (unless type-seen
231 (reject :missing-type (format nil "~A requires type before ~A." name kind) child))
232 (if (string= kind "scope")
233 (progn
234 (when scope-seen (reject :duplicate-scope "Only one association scope is allowed." child))
235 (setf scope-seen t))
236 (progn
237 (incf participants)
238 (when (and (not association-p) (> participants 1))
239 (reject :role-player-cardinality "role requires exactly one topicRef player." child))))))
240 (validate child (if association-p '("itemIdentity" "type" "scope" "role") '("itemIdentity" "type" "topicRef")))))
241 (unless type-seen (reject :missing-type (format nil "~A requires a type element." name) node))
242 (when (zerop participants)
243 (reject (if association-p :missing-roles :missing-role-player)
244 (if association-p "association requires at least one role." "role requires a topicRef player.") node))))
245 ((string= name "resourceRef") (leaf-href node))
246 ((string= name "resourceData")
247 (attributes node '("datatype") nil)
248 (let ((datatype (attr node "datatype")))
249 ;; DATATYPE is already an absolute IRI, not content to
250 ;; resolve against the document or percent-normalize.
251 (when datatype
252 (unless (iri-parts-scheme (split-iri datatype))
253 (reject :invalid-resource-data-datatype "resourceData datatype must be an absolute IRI." node))
254 (validate-decoded-reference (unescape-reference datatype node) node)
255 (when (equal datatype "http://www.w3.org/2001/XMLSchema#anyType")
256 (reject :resource-data-datatype "xsd:anyType XML canonicalization is outside this subset." node 'xtm-unsupported)))
257 (dolist (child (node-children node))
258 (unless (stringp child)
259 (reject :unexpected-child "Textual resourceData cannot contain child elements." child)))))
260 ((string= name "type")
261 (attributes node nil nil)
262 (let ((refs (elements node)))
263 (unless (= 1 (length refs)) (reject :type-cardinality "type requires exactly one topicRef." node))
264 (validate (first refs) '("topicRef"))))
265 ((string= name "scope")
266 (attributes node nil nil)
267 (unless (elements node) (reject :empty-scope "scope requires at least one topicRef." node))
268 (dolist (child (elements node)) (validate child '("topicRef"))))
269 ((string= name "value")
270 (attributes node nil nil)
271 ;; VALUE accepts all character data, including empty text and
272 ;; whitespace. ELEMENTS would apply the wrong text policy.
273 (dolist (child (node-children node))
274 (unless (stringp child) (reject :unexpected-child "value accepts character data only." child))))
275 ((string= name "topicRef") (reference-iri node))
276 ((member name '("itemIdentity" "subjectIdentifier" "subjectLocator") :test #'string=)
277 (leaf-href node))
278 (t (unsupported node))))))
279 (validate root '("topicMap"))))
280 root)
281
282 (defun find-reference-topic (map iri)
283 ;; XTM 4.20 searches the actual model, not a speculative pre-scan registry.
284 ;; Unlike INTERN-TOPIC, a hit MUST NOT add another identifier category.
285 (let ((topic (find-if (lambda (topic)
286 (or (member iri (topic-maps.tmdm:topic-subject-identifiers topic) :test #'string=)
287 (member iri (topic-maps.tmdm:topic-item-identifiers topic) :test #'string=)))
288 (topic-maps.tmdm:topic-map-topics map))))
289 (if topic (topic-maps.tmdm:canonical-topic topic)
290 (topic-maps.tmdm:intern-topic map :item-identifier iri))))
291 (defun read-item-reifier (node item map)
292 ;; XTM 4.3.2 looks up Item Identifiers only, unlike topicRef (4.20).
293 ;; INTERN-TOPIC adds the II on a miss; any SI/II identity merging then
294 ;; follows the existing TMDM rules, independently of this lookup.
295 (when (attr node "reifier")
296 (let* ((iri (resolve-iri (attr node "reifier") *document-iri* node))
297 (topic (or (find iri (topic-maps.tmdm:topic-map-topics map)
298 :test (lambda (iri topic)
299 (member iri (topic-maps.tmdm:topic-item-identifiers topic) :test #'string=)))
300 (topic-maps.tmdm:intern-topic map :item-identifier iri))))
301 (return-from read-item-reifier (topic-maps.tmdm:set-item-reifier item topic))))
302 item)
303 (defun read-map-reifier (node map)
304 (read-item-reifier node map map))
305 (defun core-topic (map local)
306 (topic-maps.tmdm:intern-topic map :subject-identifier
307 (concatenate 'string "http://psi.topicmaps.org/iso13250/model/" local)))
308 (defun read-instance-of (node owner map)
309 (dolist (ref (elements node))
310 (let ((type (find-reference-topic map (reference-iri ref))))
311 (topic-maps.tmdm:make-association map (core-topic map "type-instance")
312 (list (list (core-topic map "type") type)
313 (list (core-topic map "instance") (topic-maps.tmdm:canonical-topic owner)))))))
314 (defun read-item-identities (node item)
315 ;; XTM 4.6: assign locators to the actual canonical item, never intern Topics.
316 ;; ADD-ITEM-IDENTIFIER owns set semantics and cross-item conflict checks.
317 (dolist (child (elements node) item)
318 (when (string= (node-name child) "itemIdentity")
319 (setf item (topic-maps.tmdm:add-item-identifier item (leaf-href child))))))
320 (defun read-association (node map)
321 ;; Resolve references in source order, then construct the complete native
322 ;; Association. The constructor may already merge Associations AND Roles.
323 (let ((type nil) (scope nil) (roles nil) (role-nodes nil))
324 (labels ((reference (ref) (find-reference-topic map (reference-iri ref)))
325 (type-reference (node) (reference (first (elements node)))))
326 (dolist (child (elements node))
327 (cond ((string= (node-name child) "type") (setf type (type-reference child)))
328 ((string= (node-name child) "scope") (setf scope (mapcar #'reference (elements child))))
329 ((string= (node-name child) "role")
330 (let ((children (elements child)))
331 (push (list (type-reference (find "type" children :key #'node-name :test #'string=))
332 (reference (find "topicRef" children :key #'node-name :test #'string=))) roles)
333 (push child role-nodes)))))
334 (let ((association (read-item-identities node
335 (topic-maps.tmdm:make-association map type (reverse roles) :scope scope))))
336 ;; Match source metadata to the native Role by its complete signature
337 ;; within THIS canonical Parent. Role order/II are not equality keys.
338 (loop for pair in (reverse roles) for source in (reverse role-nodes) do
339 ;; A preceding Role Reifier may have merged Topics and this Parent.
340 (setf association (topic-maps.tmdm:canonical-association association))
341 (let ((role (find-if (lambda (role)
342 (and (eq (topic-maps.tmdm:association-role-type role)
343 (topic-maps.tmdm:canonical-topic (first pair)))
344 (eq (topic-maps.tmdm:association-role-player role)
345 (topic-maps.tmdm:canonical-topic (second pair)))))
346 (topic-maps.tmdm:association-roles association))))
347 (setf role (read-item-identities source role))
348 (read-item-reifier source (topic-maps.tmdm:canonical-association-role role) map)))
349 ;; Role metadata is now on the native canonical Parent. Reifier merging
350 ;; may normalize it again; return the resulting Association handle.
351 (topic-maps.tmdm:canonical-association
352 (read-item-reifier node association map))))))
353 (defun read-resource-value (resource)
354 "Return value and datatype for a validated resource node (XTM 4.16/4.17).
355 This operation neither looks up Topics nor fetches resources. ANYTYPE is rejected
356 by source validation before model construction. Preserve other datatype IRIs."
357 (if (string= (node-name resource) "resourceRef")
358 (values (leaf-href resource) (topic-maps.tmdm:iri-datatype))
359 (let ((datatype (or (attr resource "datatype") (topic-maps.tmdm:string-datatype)))
360 (text (with-output-to-string (out)
361 (dolist (part (node-children resource)) (write-string part out)))))
362 (values (if (equal datatype (topic-maps.tmdm:iri-datatype))
363 (resolve-iri text *document-iri* resource)
364 text)
365 datatype))))
366 (defun read-variant (node name map)
367 (let* ((children (elements node))
368 (scope-node (find "scope" children :key #'node-name :test #'string=))
369 (resource (find-if (lambda (child) (member (node-name child) '("resourceData" "resourceRef") :test #'string=)) children))
370 (explicit (mapcar (lambda (ref) (find-reference-topic map (reference-iri ref))) (elements scope-node))))
371 (multiple-value-bind (value datatype) (read-resource-value resource)
372 ;; ADD-VARIANT owns canonicalization and the proper-superset constraint.
373 (let ((variant (topic-maps.tmdm:add-variant name value :datatype datatype
374 :scope (append (topic-maps.tmdm:topic-name-scope name) explicit))))
375 (setf variant (read-item-identities node variant))
376 ;; Reification may normalize again; retain the native canonical handle.
377 (topic-maps.tmdm:canonical-variant (read-item-reifier node variant map))))))
378 (defun read-name (node owner map)
379 (let* ((children (elements node))
380 (type-node (find "type" children :key #'node-name :test #'string=))
381 (scope-node (find "scope" children :key #'node-name :test #'string=))
382 (type (when type-node (find-reference-topic map (reference-iri (first (elements type-node))))))
383 (scope (when scope-node (mapcar (lambda (ref) (find-reference-topic map (reference-iri ref)))
384 (elements scope-node))))
385 (value-node (find "value" children :key #'node-name :test #'string=))
386 (value (with-output-to-string (out)
387 (dolist (part (node-children value-node)) (write-string part out)))))
388 ;; SAX has already resolved XML character/entity references. Preserve the
389 ;; resulting Unicode sequence without trimming or decoding it again.
390 ;; ADD-NAME owns canonical set semantics and normalization after merging.
391 (let ((name (if type-node
392 (topic-maps.tmdm:add-name owner value :type type :scope scope)
393 (topic-maps.tmdm:add-default-name owner value :scope scope))))
394 ;; Item identifiers belong to the canonical Name, never its owner/type.
395 ;; Use the shared model API for set semantics and global conflicts.
396 (setf name (read-item-identities node name))
397 ;; ADD-NAME may have returned an existing canonical Name. Reifier
398 ;; resolution/merging can normalize it again: retain the native result
399 ;; before processing Variants and return the current Name handle.
400 (setf name (read-item-reifier node name map))
401 (dolist (child children)
402 (when (string= (node-name child) "variant") (read-variant child name map)))
403 (topic-maps.tmdm:canonical-topic-name name))))
404 (defun read-occurrence (node owner map)
405 ;; XTM 4.13-4.17/4.20: reuse native Topics and the qualified resource path.
406 ;; ADD-OCCURRENCE owns live Parent/Type/Scope handles and TMDM 5.6/6.5 merging.
407 (let* ((children (elements node))
408 (type-node (find "type" children :key #'node-name :test #'string=))
409 (type (find-reference-topic map (reference-iri (first (elements type-node)))))
410 (scope-node (find "scope" children :key #'node-name :test #'string=))
411 (scope (when scope-node (mapcar (lambda (ref) (find-reference-topic map (reference-iri ref)))
412 (elements scope-node))))
413 (resource (find-if (lambda (child) (member (node-name child) '("resourceData" "resourceRef") :test #'string=)) children)))
414 (multiple-value-bind (value datatype) (read-resource-value resource)
415 (topic-maps.tmdm:canonical-occurrence
416 ;; Resolve Reifier by II only after native Occurrence normalization and
417 ;; II assignment. Reifier merging can normalize again: return its handle.
418 (read-item-reifier node
419 (read-item-identities node
420 (topic-maps.tmdm:add-occurrence owner type value :datatype datatype :scope scope)) map)))))
421 (defun read-topic (node map)
422 (let ((topic (topic-maps.tmdm:intern-topic map :item-identifier
423 (concatenate 'string *document-iri* "#" (collapse-space (attr node "id"))))))
424 (dolist (child (elements node))
425 (let ((name (node-name child)))
426 (cond
427 ((string= name "instanceOf") (read-instance-of child topic map))
428 ((string= name "name") (read-name child topic map))
429 ((string= name "occurrence") (read-occurrence child topic map))
430 (t (setf topic (topic-maps.tmdm:add-topic-identifier topic
431 (cond ((string= name "itemIdentity") :item-identifier)
432 ((string= name "subjectIdentifier") :subject-identifier)
433 (t :subject-locator))
434 (leaf-href child)))))))
435 (topic-maps.tmdm:canonical-topic topic)))
436 (defun mergemap-iri (node)
437 (let ((iri (leaf-href node)))
438 (when (iri-parts-fragment (split-iri iri))
439 (reject :mergemap-fragment "mergeMap href must not have a fragment identifier." node))
440 iri))
441 (defun resource-failure (code detail node &optional cause)
442 (error 'xtm-resource-error :code code :detail detail :cause cause
443 :document-iri *document-iri* :source-key *source-key*
444 :line (node-line node) :column (node-column node)))
445 (defun resource-octets-p (value)
446 ;; Same resolver value convention as CTM, without a dependency on its Reader.
447 (and (vectorp value) (not (stringp value))
448 (every (lambda (n) (and (integerp n) (<= 0 n 255))) value)))
449 (defun read-mergemap (node map resolver max-depth active-iris)
450 (let ((resource (mergemap-iri node)))
451 (unless resolver
452 (reject :resource-resolver-required "mergeMap requires an explicit resource resolver; no resource was loaded." node 'xtm-unsupported))
453 ;; These are finite resource-policy guards, not normative cycle semantics.
454 ;; Each independent public call starts a new active path; siblings may repeat.
455 (when (member resource active-iris :test #'string=)
456 (reject :cyclic-mergemap "Active recursive XTM resource dependency; cycle processing is not implemented." node 'xtm-unsupported))
457 (when (>= (length active-iris) (1+ max-depth))
458 (reject :resource-depth-limit "Configured nested XTM resource limit reached; this is implementation policy." node 'xtm-unsupported))
459 (multiple-value-bind (bytes source-key)
460 (handler-case
461 (funcall resolver resource :purpose :mergemap :from-document-iri *document-iri*
462 :notation "http://psi.topicmaps.org/iso13250/xtm")
463 (error (c) (resource-failure :resource-resolver-failure (princ-to-string c) node c)))
464 (unless bytes
465 (resource-failure :resource-unavailable "Resolver declined or did not supply the requested XTM resource." node))
466 (unless (and (resource-octets-p bytes) (or (null source-key) (stringp source-key)))
467 (resource-failure :invalid-resource-result "Resolver must return an octet vector and a string source key or NIL." node))
468 (let ((source (deserialize-document
469 (if (typep bytes '(vector (unsigned-byte 8))) bytes
470 (map '(vector (unsigned-byte 8)) #'identity bytes))
471 resource (or source-key resource) resolver max-depth active-iris)))
472 ;; Import only Topics/Associations. The existing operation preflights
473 ;; conflicts, preserves SOURCE, and excludes its Map identifiers/reifier.
474 (handler-case (topic-maps.tmdm:import-map-content map source)
475 (error (c) (resource-failure :mergemap-import-failure (princ-to-string c) node c)))))))
476 (defun deserialize-octets (bytes &key document-iri source-key resource-resolver (max-resource-depth 32))
477 "Deserialize raw XTM 2.0 octets into a fresh TMDM Map.
478 DOCUMENT-IRI is required, absolute and fragment-free. SOURCE-KEY is diagnostic.
479 RESOURCE-RESOLVER is optional: (resolver absolute-iri :purpose :mergemap
480 :from-document-iri parent-iri :notation XTM-notation-IRI)
481 returns raw octets and an optional diagnostic source key. No implicit I/O.
482 Children use their resolved IRI as Document IRI and the same explicit resolver.
483 MAX-RESOURCE-DEPTH bounds nested imports (default 32); active cycles are
484 Unsupported implementation policy, not a normative XTM invalidity decision.
485 Child XML/XTM/model errors retain their original contexts; resolver/import
486 failures use XTM-RESOURCE-ERROR with the original ERROR-CAUSE. No supplied Map
487 is mutated. Each public call has its own resource recursion context."
488 (check-type max-resource-depth (integer 0 *))
489 (deserialize-document bytes document-iri source-key resource-resolver max-resource-depth nil))
490 (defun deserialize-document (bytes document-iri source-key resource-resolver max-resource-depth active-iris)
491 (check-type bytes (vector (unsigned-byte 8)))
492 (let ((*document-iri* document-iri) (*source-key* source-key)
493 (handler (make-instance 'source-handler)))
494 (require-document-iri document-iri)
495 (let* ((root
496 (handler-case (topic-maps.xml:parse-octets bytes handler)
497 (cxml:well-formedness-violation (c)
498 (error 'xtm-xml-error :code :xml-not-well-formed :cause c
499 :detail (princ-to-string c) :document-iri document-iri :source-key source-key
500 :line (sax:line-number handler) :column (sax:column-number handler)))
501 (topic-maps.xml:doctype-forbidden (c)
502 (error 'xtm-xml-error :code :doctype-forbidden :cause c
503 :detail "DOCTYPE forbidden by the mandatory XML byte boundary."
504 :document-iri document-iri :source-key source-key
505 :line (sax:line-number handler) :column (sax:column-number handler)))))
506 (map (topic-maps.tmdm:make-topic-map)))
507 (validate-source root)
508 ;; The attribute is processed before itemIdentity and later Topic nodes.
509 (read-map-reifier root map)
510 (dolist (child (elements root))
511 (cond ((string= (node-name child) "itemIdentity")
512 (topic-maps.tmdm:add-item-identifier map (leaf-href child)))
513 ((string= (node-name child) "mergeMap")
514 (read-mergemap child map resource-resolver max-resource-depth
515 (cons document-iri active-iris)))
516 ((string= (node-name child) "association") (read-association child map))
517 (t (read-topic child map))))
518 map)))