1 (in-package #:topic-maps.ctm)
3 (defstruct (parser (:constructor make-parser (lexer document-iri wildcard-iri wildcard-counter)))
4 lexer document-iri wildcard-iri wildcard-counter lookahead
5 (wildcards (make-hash-table :test #'equal)) (prefixes (make-hash-table :test #'equal)))
7 (or (parser-lookahead parser)
8 (setf (parser-lookahead parser) (next-token (parser-lexer parser)))))
9 (defun consume (parser)
10 (prog1 (look parser) (setf (parser-lookahead parser) nil)))
11 (defun punctuation-p (parser character)
12 (and (eq :punctuation (token-kind (look parser)))
13 (eql character (token-value (look parser)))))
15 (defun require-wildcard-environment (iri counter)
16 (handler-case (require-document-iri iri)
17 (ctm-rejection () (problem 'ctm-rejection :invalid-wildcard-iri 0 "Wildcard IRI must be an absolute, fragment-free IRI.")))
18 (unless (and (integerp counter) (>= counter 0))
19 (problem 'ctm-rejection :invalid-wildcard-counter 0 "Wildcard counter must be a non-negative integer.")))
21 (defun wildcard-locator (parser &optional name)
22 "CTM 3.3.8: cache locators, not Lisp object handles; identity uses INTERN-TOPIC."
23 (or (and name (gethash name (parser-wildcards parser)))
24 (let ((iri (format nil "~A#$__~D~@[.~A~]" (parser-wildcard-iri parser)
25 (incf (parser-wildcard-counter parser)) name)))
26 (when name (setf (gethash name (parser-wildcards parser)) iri)) iri)))
28 (defun topic-reference-start-p (token)
29 (or (member (token-kind token) '(:identifier :iri :qname :wildcard))
30 (and (eq :punctuation (token-kind token)) (find (token-value token) "=^["))))
32 (defun resolve-qname (parser token)
33 "CTM 3.3.4: concatenate the resolved binding and local part exactly once."
34 (let* ((text (token-value token)) (colon (position #\: text))
35 (prefix (subseq text 0 colon)) (bound (gethash prefix (parser-prefixes parser))))
37 (problem 'undefined-prefix :undefined-prefix (token-position token)
38 (format nil "Prefix ~S has no binding." prefix)))
39 ;; Do not re-resolve or percent-decode an already resolved binding.
40 (validate-iri-characters (concatenate 'string bound (subseq text (1+ colon)))
41 (token-position token))))
43 (defun read-prefix-directive (parser)
44 "CTM 3.16.1: document-ordered, per-deserialization bindings; reference is an IRI."
45 (consume parser) ; %prefix
46 (let ((name (consume parser)) (reference (consume parser)))
47 (unless (eq :identifier (token-kind name))
48 (problem 'ctm-rejection :expected-prefix-name (token-position name) "Expected a prefix identifier."))
49 (unless (eq :iri (token-kind reference))
50 (problem 'ctm-rejection :expected-prefix-iri (token-position reference)
51 "A prefix binding requires an IRI, not a QName or Topic identifier."))
52 (let* ((iri (resolve-iri (token-value reference) (parser-document-iri parser) (token-position reference)))
53 (old (gethash (token-value name) (parser-prefixes parser))))
54 (when (and old (not (string= old iri)))
55 (problem 'prefix-collision :prefix-collision (token-position name)
56 (format nil "Prefix ~S is already bound to ~S, not ~S." (token-value name) old iri)))
57 (setf (gethash (token-value name) (parser-prefixes parser)) iri))))
59 (defun identity-value (parser &optional explicit-kind)
60 (let ((token (consume parser)))
61 (case (token-kind token)
64 (problem 'ctm-rejection :expected-iri (token-position token) "Explicit = or ^ needs an IRI reference."))
65 (when (member (token-value token) '("def" "isa" "ako" "end") :test #'string=)
66 (problem 'ctm-unsupported :unsupported-keyword (token-position token) "This keyword is outside the implemented subset."))
67 (values :item-identifier
68 (concatenate 'string (parser-document-iri parser) "#" (token-value token))))
70 (values (or explicit-kind :subject-identifier)
71 (resolve-iri (token-value token) (parser-document-iri parser) (token-position token))))
72 (:qname (values (or explicit-kind :subject-identifier) (resolve-qname parser token)))
75 (problem 'ctm-rejection :expected-iri (token-position token) "Explicit = or ^ needs an IRI reference."))
76 (values :item-identifier (wildcard-locator parser (token-value token))))
78 (case (token-value token)
79 (#\= (if explicit-kind
80 (problem 'ctm-rejection :expected-iri (token-position token) "Unexpected identity marker.")
81 (identity-value parser :subject-locator)))
82 (#\^ (if explicit-kind
83 (problem 'ctm-rejection :expected-iri (token-position token) "Unexpected identity marker.")
84 (identity-value parser :item-identifier)))
85 (otherwise (problem 'ctm-rejection :expected-topic-identity (token-position token) "Expected topic identity."))))
86 (otherwise (problem 'ctm-rejection :expected-topic-identity (token-position token) "Expected topic identity.")))))
88 (defun identity-reference (parser map)
89 (multiple-value-bind (kind iri) (identity-value parser)
90 (topic-maps.tmdm:intern-topic map kind iri)))
92 (defun topic-reference (parser map)
93 "CTM 3.3.7: one recursive reference path for Types, Players and Scope themes."
94 (if (punctuation-p parser #\[)
97 (let ((topic (topic-maps.tmdm:intern-topic map :item-identifier (wildcard-locator parser))))
98 (read-topic-tail parser map topic #\] :required t)))
99 (identity-reference parser map)))
101 (defun read-scope (parser map)
102 "CTM 3.3.9: optional @ followed by a nonempty comma-separated Topic set.
103 Use the shared Topic reference resolver, including Embedded Topics and Wildcards.
104 The owning information item is not constructed until this function finishes."
105 (when (punctuation-p parser #\@)
109 ;; A reifier marker where a Theme is required is malformed Scope,
110 ;; even though reification after a complete Scope remains unsupported.
111 (unless (parser-lookahead parser)
112 (skip-layout (parser-lexer parser))
113 (when (eql #\~ (peek-character (parser-lexer parser)))
114 (problem 'ctm-rejection :expected-scope-theme (lexer-cursor (parser-lexer parser))
115 "Expected a Theme, not a reifier marker.")))
116 (let ((token (look parser)))
117 (unless (topic-reference-start-p token)
118 (problem 'ctm-rejection :expected-scope-theme (token-position token)
119 "Expected a Topic reference after '@' or the scope comma."))
120 (push (topic-reference parser map) themes))
121 (if (punctuation-p parser #\,) (consume parser) (return (nreverse themes)))))))
123 (defun literal-iri-reference (parser)
124 "An IRI locator, not a Topic identity. Used for values/datatype syntax."
125 (let ((token (consume parser)))
126 (case (token-kind token)
127 (:iri (resolve-iri (token-value token) (parser-document-iri parser) (token-position token)))
128 (:qname (resolve-qname parser token))
129 (otherwise (problem 'ctm-rejection :expected-datatype-iri (token-position token)
130 "A datatype qualifier requires an IRI reference, not a Topic identifier.")))))
132 (defun read-literal (parser &optional (context :occurrence))
133 "Shared CTM 3.4.1 literal reader for Occurrences and Variants."
134 (let ((token (look parser)))
135 (case (token-kind token)
138 ;; Numeric-literal value policy: represent the unquoted integer value
139 ;; canonically; qualified quoted strings retain their lexical value.
140 (values (topic-maps.tmdm:canonical-integer-lexical-form (token-value token))
141 (topic-maps.tmdm:integer-datatype)))
144 ;; Same value-representation policy as bare integers; token spelling is
145 ;; retained by the lexer, qualified strings remain lexical model data.
146 (values (topic-maps.tmdm:canonical-decimal-lexical-form (token-value token))
147 (topic-maps.tmdm:decimal-datatype)))
150 (values (topic-maps.tmdm:canonical-date-lexical-form (token-value token)) (topic-maps.tmdm:date-datatype)))
153 (multiple-value-bind (value reason) (topic-maps.tmdm:canonical-datetime-lexical-form (token-value token))
154 (unless value (problem 'ctm-unsupported
155 (if (eq reason :unsupported-bce-timezone-rollover)
156 :datetime-bce-timezone-rollover :datetime-leap-second-context)
157 (token-position token) "DateTime normalization is outside the supported BCE/leap-second calendar context."))
158 (values value (topic-maps.tmdm:datetime-datatype))))
160 (problem 'ctm-unsupported (if (eq context :variant) :variant-literal-datatype :occurrence-literal-datatype) (token-position token)
161 "The separate CTM '*' literal is outside this slice."))
164 (if (punctuation-p parser #\^)
165 (let ((caret (consume parser)))
166 (unless (and (punctuation-p parser #\^)
167 (= (token-position (look parser)) (1+ (token-position caret))))
168 (problem 'ctm-rejection :invalid-datatype-marker (token-position caret) "Expected contiguous '^^'."))
170 (let ((datatype (literal-iri-reference parser)))
171 (when (and (string= datatype (topic-maps.tmdm:integer-datatype))
172 (not (topic-maps.tmdm:integer-lexical-p (token-value token))))
173 (problem 'ctm-rejection :invalid-integer-value (token-position token)
174 "Quoted value is not an xsd:integer lexical form."))
175 (when (and (string= datatype (topic-maps.tmdm:decimal-datatype))
176 (not (topic-maps.tmdm:decimal-lexical-p (token-value token))))
177 (problem 'ctm-rejection :invalid-decimal-value (token-position token)
178 "Quoted value is not an xsd:decimal lexical form."))
179 (when (and (string= datatype (topic-maps.tmdm:date-datatype))
180 (not (topic-maps.tmdm:date-lexical-p (token-value token))))
181 (problem 'ctm-rejection :invalid-date-value (token-position token)
182 "Quoted value is not a valid XSD 1.0 date lexical form."))
183 (when (and (string= datatype (topic-maps.tmdm:datetime-datatype))
184 (not (topic-maps.tmdm:datetime-lexical-p (token-value token))))
185 (problem 'ctm-rejection :invalid-datetime-value (token-position token)
186 "Quoted value is not a valid XSD 1.0 dateTime."))
187 ;; TMDM 4.4 requires absolute anyURI content; quoted content is
188 ;; lexical data, never an IRI reference to resolve against the document.
189 (when (and (string= datatype (topic-maps.tmdm:iri-datatype))
190 (not (topic-maps.tmdm::absolute-locator-p (token-value token))))
191 (problem 'ctm-rejection :relative-uri-value (token-position token)
192 "A quoted anyURI value must already be absolute (TMDM 4.4)."))
193 (values (token-value token) datatype)))
194 (values (token-value token) (topic-maps.tmdm:string-datatype))))
195 ((:iri :qname) (values (literal-iri-reference parser) (topic-maps.tmdm:iri-datatype)))
196 (otherwise (problem 'ctm-rejection (if (eq context :variant) :expected-variant-value :expected-occurrence-value)
197 (token-position token) "Expected a supported CTM literal value.")))))
199 (defun read-identity-tail (parser map topic)
200 (let* ((start (look parser)) (embedded (punctuation-p parser #\[))
201 (type (when embedded (topic-reference parser map))))
202 ;; Identity tail statements add directly to their owner, without constructing
203 ;; an intermediate Topic. Identity-form Type references use the same resolver.
204 (multiple-value-bind (kind iri) (unless embedded (identity-value parser))
205 (if (punctuation-p parser #\:)
208 (multiple-value-bind (value datatype) (read-literal parser)
209 (let* ((type (or type (topic-maps.tmdm:intern-topic map kind iri)))
210 (scope (read-scope parser map)))
211 (topic-maps.tmdm:add-occurrence topic type value :datatype datatype :scope scope)
212 (topic-maps.tmdm:canonical-topic topic))))
213 (if (or embedded (member (token-kind start) '(:identifier :wildcard)))
214 (if (and (eq :identifier (token-kind start)) (punctuation-p parser #\())
215 (problem 'ctm-unsupported :topic-tail (token-position start) "Template invocations are outside this subset.")
216 (problem 'ctm-rejection :expected-occurrence-type-separator (token-position (look parser))
217 "Expected ':' after the Occurrence Type."))
218 (topic-maps.tmdm:add-topic-identifier topic kind iri))))))
220 (defun read-variant (parser map name)
221 "CTM 3.12: required explicit Scope, then union with the current Parent Scope."
223 (multiple-value-bind (value datatype) (read-literal parser :variant)
224 (unless (punctuation-p parser #\@)
225 (problem 'ctm-rejection :expected-variant-scope (token-position (look parser))
226 "A Variant requires an explicit '@' Scope."))
227 (let* ((scope-position (token-position (look parser))) (themes (read-scope parser map))
228 (scope (append (topic-maps.tmdm:topic-name-scope name) themes)))
229 (unless (punctuation-p parser #\))
230 (problem 'ctm-rejection :missing-variant-close (token-position (look parser))
231 "Expected ')' after the Variant Scope."))
233 (handler-case (topic-maps.tmdm:add-variant name value :datatype datatype :scope scope)
234 (topic-maps.tmdm:variant-error (c)
235 (problem 'ctm-rejection (topic-maps.tmdm:variant-error-code c) scope-position (princ-to-string c)))))))
237 (defun read-name (parser map topic)
238 "CTM 3.11: optional Topic reference plus ':' followed by a string.
239 Use the shared Topic reference resolver."
240 (let* ((token (look parser))
241 (typed (topic-reference-start-p token))
242 (type (when typed (topic-reference parser map))))
244 (unless (punctuation-p parser #\:)
245 (problem 'ctm-rejection :expected-name-type-separator
246 (token-position (look parser)) "Expected ':' after the name type."))
248 (let ((value (consume parser)))
249 (unless (eq :string (token-kind value))
250 (problem 'ctm-rejection :expected-name-value (token-position value)
251 "Expected a quoted name value after '-' or the name type separator."))
252 (let* ((scope (read-scope parser map))
254 (topic-maps.tmdm:add-name topic (token-value value) :type type :scope scope)
255 (topic-maps.tmdm:add-name topic (token-value value) :scope scope))))
256 (loop while (punctuation-p parser #\() do (read-variant parser map name))))
257 (topic-maps.tmdm:canonical-topic topic)))
259 (defun read-topic-tail (parser map topic terminator &key required)
260 "CTM 3.9: the same Tail reader ends at '.' or the caller's Embedded ']'."
261 (let ((has-tail nil) (seen-tail nil))
264 ((punctuation-p parser terminator)
265 (when (and required (not seen-tail))
266 (problem 'ctm-rejection :expected-topic-tail (token-position (look parser)) "An Embedded Topic requires a nonempty Topic Tail."))
267 (consume parser) (return (topic-maps.tmdm:canonical-topic topic)))
268 ((and (char= terminator #\]) (punctuation-p parser #\.))
269 (problem 'ctm-rejection :missing-embedded-close (token-position (look parser)) "Embedded Topics end with ']', not a period."))
270 ((punctuation-p parser #\-)
272 (problem 'ctm-rejection :expected-separator (token-position (look parser)) "Topic-tail statements need a semicolon separator."))
274 (setf topic (read-name parser map topic))
275 (setf has-tail t seen-tail t))
276 ((and has-tail (punctuation-p parser #\;))
279 ((eq :eof (token-kind (look parser)))
280 (problem 'ctm-rejection (if (char= terminator #\]) :missing-embedded-close :missing-period)
281 (token-position (look parser)) "Expected the closing Topic/Embedded Topic delimiter."))
282 ((topic-reference-start-p (look parser))
284 (problem 'ctm-rejection :expected-separator (token-position (look parser)) "Topic-tail statements need a semicolon separator."))
285 (setf topic (read-identity-tail parser map topic) has-tail t seen-tail t))
286 ((punctuation-p parser #\()
287 (problem 'ctm-rejection :unexpected-variant (token-position (look parser)) "A Variant must immediately follow a Topic Name."))
288 (t (problem 'ctm-rejection :unexpected-token (token-position (look parser)) "Unexpected token after topic or name."))))))
290 (defun read-association (parser map type)
291 "CTM 3.13, restricted to one or two role declarations; optional scope, no reifier."
292 (consume parser) ; opening parenthesis already recognized by the caller
293 (let ((roles nil) (third-position nil))
295 (when (or (punctuation-p parser #\)) (eq :eof (token-kind (look parser))))
296 (problem 'ctm-rejection :expected-role (token-position (look parser)) "Expected a nonempty Association role declaration."))
297 (when (= 2 (length roles)) (setf third-position (token-position (look parser))))
298 (let* ((role-type (topic-reference parser map))
299 (type-end (lexer-cursor (parser-lexer parser)))
300 (colon (look parser)))
301 (unless (punctuation-p parser #\:)
302 (problem 'ctm-rejection :expected-role-type-separator (token-position colon) "Expected ':' after the Role type."))
304 (let ((player-token (look parser)))
305 ;; CTM role production requires layout on at least one side of ':'.
306 ;; skip-layout handles whitespace and comments; gaps use source offsets.
307 (unless (or (> (token-position colon) type-end)
308 (> (token-position player-token) (1+ (token-position colon))))
309 (problem 'ctm-rejection :role-separator-whitespace (token-position colon)
310 "A Role separator needs whitespace or a comment on at least one side."))
311 (when (or (eq :eof (token-kind player-token))
312 (punctuation-p parser #\)) (punctuation-p parser #\,))
313 (problem 'ctm-rejection :expected-role-player (token-position player-token) "Expected a Topic as the Role player.")))
314 (push (list role-type (topic-reference parser map)) roles))
315 (cond ((punctuation-p parser #\,) (consume parser))
316 ((punctuation-p parser #\)) (consume parser) (return))
317 ((eq :eof (token-kind (look parser)))
318 (problem 'ctm-rejection :missing-association-close (token-position (look parser)) "Expected ')' after the Roles."))
319 (t (problem 'ctm-rejection :expected-role-separator (token-position (look parser)) "Expected ',' or ')' after a Role."))))
320 (when (> (length roles) 2)
321 (problem 'ctm-unsupported :association-arity third-position "Associations with more than two Role declarations are outside Slice 3."))
322 (let ((scope (read-scope parser map)))
323 (topic-maps.tmdm:make-association map type (nreverse roles) :scope scope))))
325 (defun deserialize-string (text &key document-iri source-name (wildcard-iri document-iri) (wildcard-counter 0))
326 "Read the documented CTM subset, with per-document prefixes and qualified strings.
327 Return the Map and final Wildcard Counter as two values. Wildcard IRI defaults
328 to Document IRI; local identifiers and relative IRIs still use Document IRI.
329 Source positions are zero-based character offsets; lines/columns are one-based."
330 (check-type text string)
331 (let ((*source-name* source-name) (*source-text* text))
332 (require-document-iri document-iri)
333 (require-wildcard-environment wildcard-iri wildcard-counter)
334 (let ((parser (make-parser (make-lexer text) document-iri wildcard-iri wildcard-counter))
335 (map (topic-maps.tmdm:make-topic-map)))
336 (handler-bind ((topic-maps.tmdm:variant-error
337 (lambda (c) (problem 'ctm-rejection (topic-maps.tmdm:variant-error-code c)
338 (lexer-cursor (parser-lexer parser)) (princ-to-string c)))))
339 (loop until (eq :eof (token-kind (look parser))) do
340 (if (eq :directive (token-kind (look parser)))
341 (read-prefix-directive parser)
342 (let* ((embedded (punctuation-p parser #\[)) (topic (topic-reference parser map)))
343 (if (punctuation-p parser #\()
344 (read-association parser map topic)
346 (problem 'ctm-rejection :embedded-topic-at-top-level (token-position (look parser))
347 "An Embedded Topic at top level must be an Association Type, not a standalone declaration.")
348 (read-topic-tail parser map topic #\.)))))))
349 (values map (parser-wildcard-counter parser)))))
351 (defun deserialize-file (pathname &key document-iri source-name (wildcard-iri document-iri) (wildcard-counter 0))
352 "Read a UTF-8 CTM file, with optional UTF-8 BOM, using an explicit Document IRI.
353 Other encoding directives are UNSUPPORTED. File I/O errors propagate unchanged."
354 (let ((*source-name* source-name) (*source-text* ""))
355 (require-document-iri document-iri)
356 (require-wildcard-environment wildcard-iri wildcard-counter)
357 (with-open-file (input pathname :direction :input :element-type '(unsigned-byte 8))
358 (let ((bytes (make-array (file-length input) :element-type '(unsigned-byte 8))))
359 (unless (= (length bytes) (read-sequence bytes input))
360 (error "Input file changed or was truncated during reading."))
361 (deserialize-string (decode-utf8 bytes :strip-bom t)
362 :document-iri document-iri :source-name source-name
363 :wildcard-iri wildcard-iri :wildcard-counter wildcard-counter)))))