]> dreyeck.freedombox.rocks Git - topic-maps.git/blob - src/cxtm/canonicalizer.lisp
Implement CXTM canonicalization for supported TMDM items
[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 (topic-order (topic-name-parent a) (topic-name-parent b)))))))
51 (defun role-signature-order (a b)
52 ;; In a single parent's roles set, [parent] is equal. During association
53 ;; comparison equal player/type pairs also have equal parent-comparison
54 ;; context. Comparing this prefix avoids recursive parent/roles traversal.
55 (let ((c (topic-order (association-role-player a) (association-role-player b))))
56 (if (not (zerop c)) c (topic-order (association-role-type a) (association-role-type b)))))
57 (defun association-order (a b)
58 (let ((c (topic-order (association-type a) (association-type b))))
59 (if (not (zerop c)) c
60 (set-order (association-roles a) (association-roles b) #'role-signature-order))))
61 (defun role-order (a b)
62 (let ((c (role-signature-order a b)))
63 (if (not (zerop c)) c
64 (association-order (association-role-parent a) (association-role-parent b)))))
65
66 (defun require-exact-item (item type)
67 ;; A future/subclass model carrying extra properties is explicitly unsupported.
68 (unless (eq (type-of item) type)
69 (fail :unsupported-information-item (format nil "Expected exact ~S, received ~S." type (type-of item)) t)))
70 (defun require-set (items)
71 (unless (and (listp items) (= (length items) (length (remove-duplicates items :test #'eq))))
72 (fail :invalid-set "An information-item collection must be a proper set.")))
73 (defun validate-map (map)
74 "Validate current model schema and referential integrity; never normalize/mutate."
75 (require-exact-item map 'topic-map)
76 (let ((topics (topic-map-topics map)) (associations (topic-map-associations map)))
77 (require-set topics) (require-set associations)
78 (labels ((reference (topic)
79 (require-exact-item topic 'topic)
80 (unless (and (eq topic (canonical-topic topic)) (member topic topics :test #'eq))
81 (fail :invalid-topic-reference "Reference must designate a current Topic in this map."))))
82 (dolist (topic topics)
83 (reference topic)
84 (unless (eq (topic-parent topic) map) (fail :invalid-parent "Topic parent mismatch."))
85 (unless (or (topic-item-identifiers topic) (topic-subject-identifiers topic) (topic-subject-locators topic))
86 (fail :unidentified-topic "CXTM 4.6 requires an identity-bearing Topic." t))
87 (dolist (getter '(topic-item-identifiers topic-subject-identifiers topic-subject-locators))
88 (let ((ids (funcall getter topic)))
89 (unless (and (every (lambda (s) (and (stringp s) (plusp (length s)))) ids)
90 (= (length ids) (length (remove-duplicates ids :test #'string=))))
91 (fail :invalid-locators "Locator properties must be sets of nonempty strings."))))
92 (require-set (topic-names topic))
93 (dolist (name (topic-names topic))
94 (require-exact-item name 'topic-name)
95 (unless (and (eq name (canonical-topic-name name)) (eq (topic-name-parent name) topic))
96 (fail :invalid-parent "Name must be current and owned by its containing Topic."))
97 (reference (topic-name-type name))))
98 (dolist (a associations)
99 (require-exact-item a 'association)
100 (unless (and (eq a (canonical-association a)) (eq (association-parent a) map))
101 (fail :invalid-parent "Association must be current and owned by this map."))
102 (reference (association-type a)) (require-set (association-roles a))
103 (unless (association-roles a) (fail :empty-association "Association requires Roles."))
104 (dolist (r (association-roles a))
105 (require-exact-item r 'association-role)
106 (unless (and (eq r (canonical-association-role r)) (eq (association-role-parent r) a))
107 (fail :invalid-parent "Role must be current and owned by its Association."))
108 (reference (association-role-type r)) (reference (association-role-player r)))))))
109
110 (defun xml-text (text out)
111 (loop for c across (nfc text) for n = (char-code c) do
112 (unless (or (member n '(9 10 13)) (<= 32 n #xd7ff) (<= #xe000 n #xfffd) (<= #x10000 n #x10ffff))
113 (fail :xml-character (format nil "U+~4,'0X cannot be represented in XML 1.0." n)))
114 (case c
115 (#\& (write-string "&amp;" out)) (#\< (write-string "&lt;" out))
116 (#\> (write-string "&gt;" out)) (#\Return (write-string "&#xD;" out))
117 (otherwise (write-char c out)))))
118 (defun emit-locators (tag locators out)
119 (when locators
120 (format out "<~A>~%" tag)
121 (dolist (locator (sorted locators #'locator-order))
122 (write-string "<locator>" out) (xml-text (normalized-locator locator) out)
123 (format out "</locator>~%"))
124 (format out "</~A>~%" tag)))
125
126 (defun canonicalize (map &key base-locator)
127 "Return CXTM as a string. BASE-LOCATOR is an explicit absolute IRI (CXTM 3.1).
128 Only the existing TMDM schema is supported: empty Scope, null Reifier, no
129 Occurrences/Variants or non-Topic identifiers. Does not mutate MAP or handles."
130 (unless (and (stringp base-locator) (position #\: base-locator)
131 (let ((scheme (subseq base-locator 0 (position #\: base-locator))))
132 (and (plusp (length scheme))
133 (or (char<= #\a (char scheme 0) #\z) (char<= #\A (char scheme 0) #\Z))
134 (every (lambda (c) (or (char<= #\a c #\z) (char<= #\A c #\Z)
135 (char<= #\0 c #\9) (find c "+-."))) scheme))))
136 (fail :invalid-base-locator "Supply an absolute base locator."))
137 (validate-map map)
138 (let* ((*base-locator* base-locator) (*locator-cache* (make-hash-table :test #'equal))
139 (topics (sorted (topic-map-topics map) #'topic-order))
140 (associations (sorted (topic-map-associations map) #'association-order))
141 (topic-numbers (make-hash-table :test #'eq))
142 (association-numbers (make-hash-table :test #'eq))
143 (role-numbers (make-hash-table :test #'eq)))
144 ;; NFC/base normalization can expose distinct, comparator-equal Topics.
145 ;; No address/construction-order tie breaker or implicit merge is permitted.
146 (loop for (a b) on topics while b do
147 (when (zerop (topic-order a b))
148 (fail :ambiguous-topic-order "Distinct Topics have identical normalized identity keys; resolve model identity first." t)))
149 (loop for topic in topics for number from 1 do (setf (gethash topic topic-numbers) number))
150 (loop for a in associations for number from 1 do
151 (setf (gethash a association-numbers) number)
152 (loop for r in (sorted (association-roles a) #'role-order) for index from 1 do
153 (setf (gethash r role-numbers) index)))
154 (with-output-to-string (out)
155 (labels ((type-ref (topic)
156 (format out "<type topicref=\"~D\"></type>~%" (gethash topic topic-numbers)))
157 (role-ref (r)
158 (format out "<rolePlayed ref=\"association.~D.role.~D\"></rolePlayed>~%"
159 (gethash (association-role-parent r) association-numbers)
160 (gethash r role-numbers))))
161 (format out "<topicMap>~%")
162 (loop for topic in topics for number from 1 do
163 (format out "<topic number=\"~D\">~%" number)
164 (emit-locators "subjectIdentifiers" (topic-subject-identifiers topic) out)
165 (emit-locators "subjectLocators" (topic-subject-locators topic) out)
166 (emit-locators "itemIdentifiers" (topic-item-identifiers topic) out)
167 (loop for name in (sorted (topic-names topic) #'name-order) for index from 1 do
168 (format out "<name number=\"~D\">~%<value>" index)
169 (xml-text (topic-name-value name) out) (format out "</value>~%")
170 (type-ref (topic-name-type name)) (format out "</name>~%"))
171 (dolist (r (sorted (topic-roles-played topic) #'role-order)) (role-ref r))
172 (format out "</topic>~%"))
173 (loop for a in associations for number from 1 do
174 (format out "<association number=\"~D\">~%" number)
175 (type-ref (association-type a))
176 (loop for r in (sorted (association-roles a) #'role-order) for index from 1 do
177 (format out "<role number=\"~D\">~%<player topicref=\"~D\"></player>~%"
178 index (gethash (association-role-player r) topic-numbers))
179 (type-ref (association-role-type r)) (format out "</role>~%"))
180 (format out "</association>~%"))
181 ;; CXTM 3.1 step 2 appends LF after EVERY element, including the root.
182 (format out "</topicMap>~%")))))
183
184 (defun canonicalize-octets (map &key base-locator)
185 "Return canonical UTF-8 octets, with no BOM and the CXTM-mandated final LF."
186 (let ((out (make-array 0 :element-type '(unsigned-byte 8) :adjustable t :fill-pointer 0)))
187 (loop for c across (canonicalize map :base-locator base-locator) for n = (char-code c) do
188 (flet ((octet (b) (vector-push-extend b out)))
189 (cond ((< n #x80) (octet n))
190 ((< n #x800) (octet (logior #xc0 (ash n -6))) (octet (logior #x80 (logand n 63))))
191 ((< n #x10000) (octet (logior #xe0 (ash n -12)))
192 (octet (logior #x80 (logand (ash n -6) 63))) (octet (logior #x80 (logand n 63))))
193 (t (octet (logior #xf0 (ash n -18))) (octet (logior #x80 (logand (ash n -12) 63)))
194 (octet (logior #x80 (logand (ash n -6) 63))) (octet (logior #x80 (logand n 63))))))) out))
195 (defun write-cxtm (map pathname &key base-locator)
196 "Write canonical UTF-8 bytes to PATHNAME; MAP is not modified."
197 (let ((bytes (canonicalize-octets map :base-locator base-locator)))
198 (with-open-file (out pathname :direction :output :element-type '(unsigned-byte 8)
199 :if-exists :supersede :if-does-not-exist :create)
200 (write-sequence bytes out))) pathname)