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