]> dreyeck.freedombox.rocks Git - topic-maps.git/blob - src/cxtm/canonicalizer.lisp
test: prove CTM/XTM anyType equivalence (slice 22T)
[topic-maps.git] / src / cxtm / canonicalizer.lisp
1 (in-package #:topic-maps.cxtm)
2
3 (defvar *base-locator*)
4 (defvar *locator-cache*)
5
6 (defun path-start (iri)
7 (let* ((colon (position #\: iri)) (start (if colon (1+ colon) 0)))
8 (if (and (<= (+ start 2) (length iri))
9 (string= "//" iri :start2 start :end2 (+ start 2)))
10 (or (position #\/ iri :start (+ start 2)) (length iri)) start)))
11 (defun normalized-locator (locator)
12 "CXTM 3.18, literal prefix removal, NOT RFC relative-IRI resolution."
13 (or (gethash locator *locator-cache*)
14 (setf (gethash locator *locator-cache*)
15 (nfc
16 (let ((prefix (string-right-trim "/" (subseq *base-locator* 0
17 (position-if (lambda (c) (find c "?#")) *base-locator*)))))
18 (loop
19 (when (and (<= (length prefix) (length locator))
20 (string= prefix locator :end2 (length prefix)))
21 (return (string-left-trim "/" (subseq locator (length prefix)))))
22 (let ((start (path-start prefix)))
23 (when (>= start (length prefix)) (return locator))
24 (setf prefix (string-right-trim "/"
25 (subseq prefix 0 (or (position #\/ prefix :start start :from-end t) start)))))))))))
26
27 (defun string-order (a b)
28 ;; Character CODE order, independent of a Lisp implementation's collation.
29 (loop for x across a for y across b
30 when (< (char-code x) (char-code y)) do (return-from string-order -1)
31 when (> (char-code x) (char-code y)) do (return-from string-order 1))
32 (signum (- (length a) (length b))))
33 (defun sorted (items comparison)
34 (stable-sort (copy-list items) (lambda (a b) (minusp (funcall comparison a b)))))
35 (defun set-order (a b comparison)
36 (let ((size (signum (- (length a) (length b)))))
37 (if (not (zerop size)) size
38 (loop for x in (sorted a comparison) for y in (sorted b comparison)
39 for c = (funcall comparison x y) when (not (zerop c)) return c
40 finally (return 0)))))
41 (defun locator-order (a b) (string-order (normalized-locator a) (normalized-locator b)))
42 (defun topic-order (a b)
43 (loop for getter in '(topic-subject-identifiers topic-subject-locators topic-item-identifiers)
44 for c = (set-order (funcall getter a) (funcall getter b) #'locator-order)
45 when (not (zerop c)) return c finally (return 0)))
46 (defun name-order (a b)
47 (let ((c (string-order (nfc (topic-name-value a)) (nfc (topic-name-value b)))))
48 (if (not (zerop c)) c
49 (let ((type (topic-order (topic-name-type a) (topic-name-type b))))
50 (if (not (zerop type)) type
51 (let ((scope (set-order (topic-name-scope a) (topic-name-scope b) #'topic-order)))
52 (if (not (zerop scope)) scope (topic-order (topic-name-parent a) (topic-name-parent b)))))))))
53 (defun literal-value-order (value-a datatype-a value-b datatype-b)
54 ;; TMDM 4.3/5.5/5.6: anyURI values are locators; other supported values are strings.
55 ;; CXTM 4.2 orders strings before locators, independent of their spelling.
56 (let ((iri-a (string= datatype-a (iri-datatype)))
57 (iri-b (string= datatype-b (iri-datatype))))
58 (cond ((and iri-a iri-b) (locator-order value-a value-b))
59 (iri-a 1) (iri-b -1)
60 (t (string-order (nfc value-a) (nfc value-b))))))
61 (defun occurrence-value-order (a b)
62 (literal-value-order (occurrence-value a) (occurrence-datatype a)
63 (occurrence-value b) (occurrence-datatype b)))
64 (defun variant-order (a b)
65 (loop for comparison in
66 (list (literal-value-order (variant-value a) (variant-datatype a) (variant-value b) (variant-datatype b))
67 (locator-order (variant-datatype a) (variant-datatype b))
68 (set-order (variant-scope a) (variant-scope b) #'topic-order)
69 (name-order (variant-parent a) (variant-parent b)))
70 when (not (zerop comparison)) return comparison finally (return 0)))
71
72 (defun canonical-literal-value (value datatype)
73 "CXTM 3.16: shared Occurrence/Variant representation; never rewrite model data."
74 (cond ((string= datatype (iri-datatype)) (normalized-locator value))
75 ((string= datatype (integer-datatype)) (canonical-integer-lexical-form value))
76 ((string= datatype (decimal-datatype)) (canonical-decimal-lexical-form value))
77 ((string= datatype (date-datatype)) (canonical-date-lexical-form value))
78 ((string= datatype (datetime-datatype)) (canonical-datetime-lexical-form value))
79 (t value)))
80 (defun occurrence-order (a b)
81 (loop for comparison in
82 (list (occurrence-value-order a b)
83 (locator-order (occurrence-datatype a) (occurrence-datatype b))
84 (topic-order (occurrence-type a) (occurrence-type b))
85 (set-order (occurrence-scope a) (occurrence-scope b) #'topic-order)
86 (topic-order (occurrence-parent a) (occurrence-parent b)))
87 when (not (zerop comparison)) return comparison finally (return 0)))
88
89 (defun role-signature-order (a b)
90 ;; In a single parent's roles set, [parent] is equal. During association
91 ;; comparison equal player/type pairs also have equal parent-comparison
92 ;; context. Comparing this prefix avoids recursive parent/roles traversal.
93 (let ((c (topic-order (association-role-player a) (association-role-player b))))
94 (if (not (zerop c)) c (topic-order (association-role-type a) (association-role-type b)))))
95 (defun association-order (a b)
96 (let ((c (topic-order (association-type a) (association-type b))))
97 (if (not (zerop c)) c
98 (let ((roles (set-order (association-roles a) (association-roles b) #'role-signature-order)))
99 ;; Parent Map is equal for all associations compared by this serializer.
100 (if (not (zerop roles)) roles
101 (set-order (association-scope a) (association-scope b) #'topic-order))))))
102 (defun role-order (a b)
103 (let ((c (role-signature-order a b)))
104 (if (not (zerop c)) c
105 (association-order (association-role-parent a) (association-role-parent b)))))
106
107 (defun require-exact-item (item type)
108 ;; A future/subclass model carrying extra properties is explicitly unsupported.
109 (unless (eq (type-of item) type)
110 (fail :unsupported-information-item (format nil "Expected exact ~S, received ~S." type (type-of item)) t)))
111 (defun require-set (items)
112 (unless (and (topic-maps.tmdm::proper-list-p items) (= (length items) (length (remove-duplicates items :test #'eq))))
113 (fail :invalid-set "An information-item collection must be a proper set.")))
114 (defun validate-literal-value (value datatype)
115 "Validate the shared Variant/Occurrence literal representation without mutation."
116 (unless (and (stringp value) (stringp datatype)) (fail :invalid-literal "Value and datatype must be strings."))
117 (unless (topic-maps.tmdm::absolute-locator-p datatype)
118 (fail :invalid-occurrence-datatype "Datatype must be an absolute locator."))
119 (when (and (string= datatype (integer-datatype))
120 (not (integer-lexical-p value)))
121 (fail :invalid-integer-value "Literal value is not an xsd:integer lexical form."))
122 (when (and (string= datatype (decimal-datatype))
123 (not (decimal-lexical-p value)))
124 (fail :invalid-decimal-value "Literal value is not an xsd:decimal lexical form."))
125 (when (string= datatype (date-datatype))
126 (unless (date-lexical-p value)
127 (fail :invalid-date-value "Literal value is not a valid XSD 1.0 date."))
128 (unless (canonical-date-lexical-form value)
129 (fail :date-timezone-canonicalization "XSD date recoverable-timezone canonicalization is outside this slice." t)))
130 (when (string= datatype (datetime-datatype))
131 (unless (datetime-lexical-p value)
132 (fail :invalid-datetime-value "Literal value is not a valid XSD 1.0 dateTime."))
133 (multiple-value-bind (value reason) (canonical-datetime-lexical-form value)
134 (unless value (fail (if (eq reason :unsupported-bce-timezone-rollover)
135 :datetime-bce-timezone-rollover :datetime-leap-second-context)
136 "DateTime BCE rollover/leap-second context is outside this canonical subset." t))))
137 (when (and (string= datatype (iri-datatype))
138 (not (topic-maps.tmdm::absolute-locator-p value)))
139 (fail :invalid-occurrence-value "IRI-valued literals must store an absolute locator."))
140 t)
141 (defun validate-map (map)
142 "Validate current model schema and referential integrity; never normalize/mutate."
143 (require-exact-item map 'topic-map)
144 (let ((topics (topic-map-topics map)) (associations (topic-map-associations map)))
145 (require-set topics) (require-set associations)
146 (labels ((reference (topic)
147 (require-exact-item topic 'topic)
148 (unless (and (eq topic (canonical-topic topic)) (member topic topics :test #'eq))
149 (fail :invalid-topic-reference "Reference must designate a current Topic in this map."))))
150 (dolist (topic topics)
151 (reference topic)
152 (unless (eq (topic-parent topic) map) (fail :invalid-parent "Topic parent mismatch."))
153 (unless (or (topic-item-identifiers topic) (topic-subject-identifiers topic) (topic-subject-locators topic))
154 (fail :unidentified-topic "CXTM 4.6 requires an identity-bearing Topic." t))
155 (dolist (getter '(topic-item-identifiers topic-subject-identifiers topic-subject-locators))
156 (let ((ids (funcall getter topic)))
157 (unless (and (every (lambda (s) (and (stringp s) (plusp (length s)))) ids)
158 (= (length ids) (length (remove-duplicates ids :test #'string=))))
159 (fail :invalid-locators "Locator properties must be sets of nonempty strings."))))
160 (require-set (topic-names topic))
161 (dolist (name (topic-names topic))
162 (require-exact-item name 'topic-name)
163 (unless (and (eq name (canonical-topic-name name)) (eq (topic-name-parent name) topic))
164 (fail :invalid-parent "Name must be current and owned by its containing Topic."))
165 (reference (topic-name-type name))
166 (require-set (topic-name-scope name)) (mapc #'reference (topic-name-scope name))
167 (require-set (topic-name-variants name))
168 (dolist (item (topic-name-variants name))
169 (require-exact-item item 'variant)
170 (unless (and (eq item (canonical-variant item)) (eq (variant-parent item) name))
171 (fail :invalid-parent "Variant must be current and owned by its containing Name."))
172 (require-set (variant-scope item)) (mapc #'reference (variant-scope item))
173 (unless (topic-maps.tmdm::variant-scope-valid-p (variant-scope item) (topic-name-scope name))
174 (fail :invalid-variant-scope "Variant scope must properly contain its Parent Name scope."))
175 (validate-literal-value (variant-value item) (variant-datatype item))))
176 (require-set (topic-occurrences topic))
177 (dolist (item (topic-occurrences topic))
178 (require-exact-item item 'occurrence)
179 (unless (and (eq item (canonical-occurrence item)) (eq (occurrence-parent item) topic))
180 (fail :invalid-parent "Occurrence must be current and owned by its containing Topic."))
181 (reference (occurrence-type item))
182 (require-set (occurrence-scope item)) (mapc #'reference (occurrence-scope item))
183 (validate-literal-value (occurrence-value item) (occurrence-datatype item))
184 (let ((ids (occurrence-item-identifiers item)))
185 (unless (and (every #'topic-maps.tmdm::absolute-locator-p ids)
186 (= (length ids) (length (remove-duplicates ids :test #'string=))))
187 (fail :invalid-locators "Occurrence identifiers must be an absolute locator set.")))))
188 (dolist (a associations)
189 (require-exact-item a 'association)
190 (unless (and (eq a (canonical-association a)) (eq (association-parent a) map))
191 (fail :invalid-parent "Association must be current and owned by this map."))
192 (reference (association-type a))
193 (require-set (association-scope a)) (mapc #'reference (association-scope a))
194 (require-set (association-roles a))
195 (unless (association-roles a) (fail :empty-association "Association requires Roles."))
196 (dolist (r (association-roles a))
197 (require-exact-item r 'association-role)
198 (unless (and (eq r (canonical-association-role r)) (eq (association-role-parent r) a))
199 (fail :invalid-parent "Role must be current and owned by its Association."))
200 (reference (association-role-type r)) (reference (association-role-player r))))))
201 (handler-case (topic-maps.tmdm::validate-map-core-subjects map)
202 (topic-maps.tmdm:core-subject-error (c)
203 (fail (topic-maps.tmdm:core-subject-error-code c) (princ-to-string c))))
204 (handler-case (topic-maps.tmdm::validate-map-item-identifiers map)
205 (topic-maps.tmdm:item-identifier-error (c)
206 (fail (topic-maps.tmdm:item-identifier-error-code c) (princ-to-string c))))
207 (handler-case (topic-maps.tmdm::validate-map-reification map)
208 (topic-maps.tmdm:reification-error (c)
209 (fail (topic-maps.tmdm:reification-error-code c) (princ-to-string c)))))
210
211 (defun xml-text (text out)
212 (loop for c across (nfc text) for n = (char-code c) do
213 (unless (or (member n '(9 10 13)) (<= 32 n #xd7ff) (<= #xe000 n #xfffd) (<= #x10000 n #x10ffff))
214 (fail :xml-character (format nil "U+~4,'0X cannot be represented in XML 1.0." n)))
215 (case c
216 (#\& (write-string "&amp;" out)) (#\< (write-string "&lt;" out))
217 (#\> (write-string "&gt;" out)) (#\Return (write-string "&#xD;" out))
218 (otherwise (write-char c out)))))
219 (defun emit-locators (tag locators out)
220 (when locators
221 (format out "<~A>~%" tag)
222 (dolist (locator (sorted locators #'locator-order))
223 (write-string "<locator>" out) (xml-text (normalized-locator locator) out)
224 (format out "</locator>~%"))
225 (format out "</~A>~%" tag)))
226
227 (defun emit-scope (themes topic-numbers out)
228 ;; CXTM 3.12/4.4/4.6. Empty Scope has no XML representation.
229 (when themes
230 (format out "<scope>~%")
231 (dolist (theme (sorted themes #'topic-order))
232 (format out "<scopingTopic topicref=\"~D\"></scopingTopic>~%" (gethash theme topic-numbers)))
233 (format out "</scope>~%")))
234
235 (defun canonicalize (map &key base-locator)
236 "Return CXTM as a string. BASE-LOCATOR is an explicit absolute IRI (CXTM 3.1).
237 Supports Scope, Variants, Item Identifiers and same-map Reification.
238 Does not mutate MAP or retained handles."
239 (unless (and (stringp base-locator) (position #\: base-locator)
240 (let ((scheme (subseq base-locator 0 (position #\: base-locator))))
241 (and (plusp (length scheme))
242 (or (char<= #\a (char scheme 0) #\z) (char<= #\A (char scheme 0) #\Z))
243 (every (lambda (c) (or (char<= #\a c #\z) (char<= #\A c #\Z)
244 (char<= #\0 c #\9) (find c "+-."))) scheme))))
245 (fail :invalid-base-locator "Supply an absolute base locator."))
246 (validate-map map)
247 (let* ((*base-locator* base-locator) (*locator-cache* (make-hash-table :test #'equal))
248 (topics (sorted (topic-map-topics map) #'topic-order))
249 (associations (sorted (topic-map-associations map) #'association-order))
250 (topic-numbers (make-hash-table :test #'eq))
251 (association-numbers (make-hash-table :test #'eq))
252 (role-numbers (make-hash-table :test #'eq)))
253 ;; NFC/base normalization can expose distinct, comparator-equal Topics.
254 ;; No address/construction-order tie breaker or implicit merge is permitted.
255 (loop for (a b) on topics while b do
256 (when (zerop (topic-order a b))
257 (fail :ambiguous-topic-order "Distinct Topics have identical normalized identity keys; resolve model identity first." t)))
258 (loop for topic in topics for number from 1 do (setf (gethash topic topic-numbers) number))
259 (loop for a in associations for number from 1 do
260 (setf (gethash a association-numbers) number)
261 (loop for r in (sorted (association-roles a) #'role-order) for index from 1 do
262 (setf (gethash r role-numbers) index)))
263 (with-output-to-string (out)
264 (labels ((start (tag item number)
265 ;; CXTM 3.11, canonical XML attribute order: number, reifier.
266 (format out "<~A" tag)
267 (when number (format out " number=\"~D\"" number))
268 (when (item-reifier item)
269 (format out " reifier=\"~D\"" (gethash (item-reifier item) topic-numbers)))
270 (format out ">~%"))
271 (type-ref (topic)
272 (format out "<type topicref=\"~D\"></type>~%" (gethash topic topic-numbers)))
273 (role-ref (r)
274 (format out "<rolePlayed ref=\"association.~D.role.~D\"></rolePlayed>~%"
275 (gethash (association-role-parent r) association-numbers)
276 (gethash r role-numbers))))
277 (start "topicMap" map nil)
278 (emit-locators "itemIdentifiers" (item-identifiers map) out)
279 (loop for topic in topics for number from 1 do
280 (format out "<topic number=\"~D\">~%" number)
281 (emit-locators "subjectIdentifiers" (topic-subject-identifiers topic) out)
282 (emit-locators "subjectLocators" (topic-subject-locators topic) out)
283 (emit-locators "itemIdentifiers" (topic-item-identifiers topic) out)
284 (loop for name in (sorted (topic-names topic) #'name-order) for index from 1 do
285 (start "name" name index) (write-string "<value>" out)
286 (xml-text (topic-name-value name) out) (format out "</value>~%")
287 (type-ref (topic-name-type name))
288 (emit-scope (topic-name-scope name) topic-numbers out)
289 (loop for item in (sorted (topic-name-variants name) #'variant-order) for number from 1 do
290 (start "variant" item number) (write-string "<value>" out)
291 (xml-text (canonical-literal-value (variant-value item) (variant-datatype item)) out)
292 (format out "</value>~%<datatype>") (xml-text (variant-datatype item) out)
293 (format out "</datatype>~%") (emit-scope (variant-scope item) topic-numbers out)
294 (emit-locators "itemIdentifiers" (item-identifiers item) out)
295 (format out "</variant>~%"))
296 (emit-locators "itemIdentifiers" (item-identifiers name) out)
297 (format out "</name>~%"))
298 (loop for item in (sorted (topic-occurrences topic) #'occurrence-order) for index from 1 do
299 (start "occurrence" item index) (write-string "<value>" out)
300 (xml-text (canonical-literal-value (occurrence-value item) (occurrence-datatype item)) out)
301 (format out "</value>~%<datatype>")
302 ;; CXTM 3.14: datatype locator is NOT base-normalized.
303 (xml-text (occurrence-datatype item) out) (format out "</datatype>~%")
304 (type-ref (occurrence-type item))
305 (emit-scope (occurrence-scope item) topic-numbers out)
306 (emit-locators "itemIdentifiers" (occurrence-item-identifiers item) out)
307 (format out "</occurrence>~%"))
308 (dolist (r (sorted (topic-roles-played topic) #'role-order)) (role-ref r))
309 (format out "</topic>~%"))
310 (loop for a in associations for number from 1 do
311 (start "association" a number)
312 (type-ref (association-type a))
313 (loop for r in (sorted (association-roles a) #'role-order) for index from 1 do
314 (start "role" r index)
315 (format out "<player topicref=\"~D\"></player>~%" (gethash (association-role-player r) topic-numbers))
316 (type-ref (association-role-type r))
317 (emit-locators "itemIdentifiers" (item-identifiers r) out)
318 (format out "</role>~%"))
319 (emit-scope (association-scope a) topic-numbers out)
320 (emit-locators "itemIdentifiers" (item-identifiers a) out)
321 (format out "</association>~%"))
322 ;; CXTM 3.1 step 2 appends LF after EVERY element, including the root.
323 (format out "</topicMap>~%")))))
324
325 (defun canonicalize-octets (map &key base-locator)
326 "Return canonical UTF-8 octets, with no BOM and the CXTM-mandated final LF."
327 (let ((out (make-array 0 :element-type '(unsigned-byte 8) :adjustable t :fill-pointer 0)))
328 (loop for c across (canonicalize map :base-locator base-locator) for n = (char-code c) do
329 (flet ((octet (b) (vector-push-extend b out)))
330 (cond ((< n #x80) (octet n))
331 ((< n #x800) (octet (logior #xc0 (ash n -6))) (octet (logior #x80 (logand n 63))))
332 ((< n #x10000) (octet (logior #xe0 (ash n -12)))
333 (octet (logior #x80 (logand (ash n -6) 63))) (octet (logior #x80 (logand n 63))))
334 (t (octet (logior #xf0 (ash n -18))) (octet (logior #x80 (logand (ash n -12) 63)))
335 (octet (logior #x80 (logand (ash n -6) 63))) (octet (logior #x80 (logand n 63))))))) out))
336 (defun write-cxtm (map pathname &key base-locator)
337 "Write canonical UTF-8 bytes to PATHNAME; MAP is not modified."
338 (let ((bytes (canonicalize-octets map :base-locator base-locator)))
339 (with-open-file (out pathname :direction :output :element-type '(unsigned-byte 8)
340 :if-exists :supersede :if-does-not-exist :create)
341 (write-sequence bytes out))) pathname)