]> dreyeck.freedombox.rocks Git - topic-maps.git/blob - src/ctm/reader.lisp
Implement unreified Variants with Scope and canonical merging
[topic-maps.git] / src / ctm / reader.lisp
1 (in-package #:topic-maps.ctm)
2
3 (defstruct (parser (:constructor make-parser (lexer document-iri)))
4 lexer document-iri lookahead (prefixes (make-hash-table :test #'equal)))
5 (defun look (parser)
6 (or (parser-lookahead parser)
7 (setf (parser-lookahead parser) (next-token (parser-lexer parser)))))
8 (defun consume (parser)
9 (prog1 (look parser) (setf (parser-lookahead parser) nil)))
10 (defun punctuation-p (parser character)
11 (and (eq :punctuation (token-kind (look parser)))
12 (eql character (token-value (look parser)))))
13
14 (defun resolve-qname (parser token)
15 "CTM 3.3.4: concatenate the resolved binding and local part exactly once."
16 (let* ((text (token-value token)) (colon (position #\: text))
17 (prefix (subseq text 0 colon)) (bound (gethash prefix (parser-prefixes parser))))
18 (unless bound
19 (problem 'undefined-prefix :undefined-prefix (token-position token)
20 (format nil "Prefix ~S has no binding." prefix)))
21 ;; Do not re-resolve or percent-decode an already resolved binding.
22 (validate-iri-characters (concatenate 'string bound (subseq text (1+ colon)))
23 (token-position token))))
24
25 (defun read-prefix-directive (parser)
26 "CTM 3.16.1: document-ordered, per-deserialization bindings; reference is an IRI."
27 (consume parser) ; %prefix
28 (let ((name (consume parser)) (reference (consume parser)))
29 (unless (eq :identifier (token-kind name))
30 (problem 'ctm-rejection :expected-prefix-name (token-position name) "Expected a prefix identifier."))
31 (unless (eq :iri (token-kind reference))
32 (problem 'ctm-rejection :expected-prefix-iri (token-position reference)
33 "A prefix binding requires an IRI, not a QName or Topic identifier."))
34 (let* ((iri (resolve-iri (token-value reference) (parser-document-iri parser) (token-position reference)))
35 (old (gethash (token-value name) (parser-prefixes parser))))
36 (when (and old (not (string= old iri)))
37 (problem 'prefix-collision :prefix-collision (token-position name)
38 (format nil "Prefix ~S is already bound to ~S, not ~S." (token-value name) old iri)))
39 (setf (gethash (token-value name) (parser-prefixes parser)) iri))))
40
41 (defun identity-value (parser &optional explicit-kind)
42 (let ((token (consume parser)))
43 (case (token-kind token)
44 (:identifier
45 (when explicit-kind
46 (problem 'ctm-rejection :expected-iri (token-position token) "Explicit = or ^ needs an IRI reference."))
47 (when (member (token-value token) '("def" "isa" "ako" "end") :test #'string=)
48 (problem 'ctm-unsupported :unsupported-keyword (token-position token) "This keyword is outside the implemented subset."))
49 (values :item-identifier
50 (concatenate 'string (parser-document-iri parser) "#" (token-value token))))
51 (:iri
52 (values (or explicit-kind :subject-identifier)
53 (resolve-iri (token-value token) (parser-document-iri parser) (token-position token))))
54 (:qname (values (or explicit-kind :subject-identifier) (resolve-qname parser token)))
55 (:punctuation
56 (case (token-value token)
57 (#\= (if explicit-kind
58 (problem 'ctm-rejection :expected-iri (token-position token) "Unexpected identity marker.")
59 (identity-value parser :subject-locator)))
60 (#\^ (if explicit-kind
61 (problem 'ctm-rejection :expected-iri (token-position token) "Unexpected identity marker.")
62 (identity-value parser :item-identifier)))
63 (otherwise (problem 'ctm-rejection :expected-topic-identity (token-position token) "Expected topic identity."))))
64 (otherwise (problem 'ctm-rejection :expected-topic-identity (token-position token) "Expected topic identity.")))))
65
66 (defun identity-reference (parser map)
67 (multiple-value-bind (kind iri) (identity-value parser)
68 (topic-maps.tmdm:intern-topic map kind iri)))
69
70 (defun read-scope (parser map)
71 "CTM 3.3.9: optional @ followed by a nonempty comma-separated Topic set.
72 Use the existing identity resolver; embedded/wildcard Topics remain unsupported.
73 The owning information item is not constructed until this function finishes."
74 (when (punctuation-p parser #\@)
75 (consume parser)
76 (let ((themes nil))
77 (loop
78 ;; A reifier marker where a Theme is required is malformed Scope,
79 ;; even though reification after a complete Scope remains unsupported.
80 (unless (parser-lookahead parser)
81 (skip-layout (parser-lexer parser))
82 (when (eql #\~ (peek-character (parser-lexer parser)))
83 (problem 'ctm-rejection :expected-scope-theme (lexer-cursor (parser-lexer parser))
84 "Expected a Theme, not a reifier marker.")))
85 (let ((token (look parser)))
86 (unless (or (member (token-kind token) '(:identifier :iri :qname))
87 (and (eq :punctuation (token-kind token)) (find (token-value token) "=^")))
88 (problem 'ctm-rejection :expected-scope-theme (token-position token)
89 "Expected a Topic reference after '@' or the scope comma."))
90 (push (identity-reference parser map) themes))
91 (if (punctuation-p parser #\,) (consume parser) (return (nreverse themes)))))))
92
93 (defun literal-iri-reference (parser)
94 "An IRI locator, not a Topic identity. Used for values/datatype syntax."
95 (let ((token (consume parser)))
96 (case (token-kind token)
97 (:iri (resolve-iri (token-value token) (parser-document-iri parser) (token-position token)))
98 (:qname (resolve-qname parser token))
99 (otherwise (problem 'ctm-rejection :expected-datatype-iri (token-position token)
100 "A datatype qualifier requires an IRI reference, not a Topic identifier.")))))
101
102 (defun read-literal (parser &optional (context :occurrence))
103 "Shared CTM 3.4.1 literal reader for Occurrences and Variants."
104 (let ((token (look parser)))
105 (case (token-kind token)
106 (:integer
107 (consume parser)
108 ;; Numeric-literal value policy: represent the unquoted integer value
109 ;; canonically; qualified quoted strings retain their lexical value.
110 (values (topic-maps.tmdm:canonical-integer-lexical-form (token-value token))
111 (topic-maps.tmdm:integer-datatype)))
112 (:decimal
113 (consume parser)
114 ;; Same value-representation policy as bare integers; token spelling is
115 ;; retained by the lexer, qualified strings remain lexical model data.
116 (values (topic-maps.tmdm:canonical-decimal-lexical-form (token-value token))
117 (topic-maps.tmdm:decimal-datatype)))
118 (:date
119 (consume parser)
120 (values (topic-maps.tmdm:canonical-date-lexical-form (token-value token)) (topic-maps.tmdm:date-datatype)))
121 (:datetime
122 (consume parser)
123 (multiple-value-bind (value reason) (topic-maps.tmdm:canonical-datetime-lexical-form (token-value token))
124 (unless value (problem 'ctm-unsupported
125 (if (eq reason :unsupported-bce-timezone-rollover)
126 :datetime-bce-timezone-rollover :datetime-leap-second-context)
127 (token-position token) "DateTime normalization is outside the supported BCE/leap-second calendar context."))
128 (values value (topic-maps.tmdm:datetime-datatype))))
129 (:excluded-literal
130 (problem 'ctm-unsupported (if (eq context :variant) :variant-literal-datatype :occurrence-literal-datatype) (token-position token)
131 "The separate CTM '*' literal is outside this slice."))
132 (:string
133 (consume parser)
134 (if (punctuation-p parser #\^)
135 (let ((caret (consume parser)))
136 (unless (and (punctuation-p parser #\^)
137 (= (token-position (look parser)) (1+ (token-position caret))))
138 (problem 'ctm-rejection :invalid-datatype-marker (token-position caret) "Expected contiguous '^^'."))
139 (consume parser)
140 (let ((datatype (literal-iri-reference parser)))
141 (when (and (string= datatype (topic-maps.tmdm:integer-datatype))
142 (not (topic-maps.tmdm:integer-lexical-p (token-value token))))
143 (problem 'ctm-rejection :invalid-integer-value (token-position token)
144 "Quoted value is not an xsd:integer lexical form."))
145 (when (and (string= datatype (topic-maps.tmdm:decimal-datatype))
146 (not (topic-maps.tmdm:decimal-lexical-p (token-value token))))
147 (problem 'ctm-rejection :invalid-decimal-value (token-position token)
148 "Quoted value is not an xsd:decimal lexical form."))
149 (when (and (string= datatype (topic-maps.tmdm:date-datatype))
150 (not (topic-maps.tmdm:date-lexical-p (token-value token))))
151 (problem 'ctm-rejection :invalid-date-value (token-position token)
152 "Quoted value is not a valid XSD 1.0 date lexical form."))
153 (when (and (string= datatype (topic-maps.tmdm:datetime-datatype))
154 (not (topic-maps.tmdm:datetime-lexical-p (token-value token))))
155 (problem 'ctm-rejection :invalid-datetime-value (token-position token)
156 "Quoted value is not a valid XSD 1.0 dateTime."))
157 ;; TMDM 4.4 requires absolute anyURI content; quoted content is
158 ;; lexical data, never an IRI reference to resolve against the document.
159 (when (and (string= datatype (topic-maps.tmdm:iri-datatype))
160 (not (topic-maps.tmdm::absolute-locator-p (token-value token))))
161 (problem 'ctm-rejection :relative-uri-value (token-position token)
162 "A quoted anyURI value must already be absolute (TMDM 4.4)."))
163 (values (token-value token) datatype)))
164 (values (token-value token) (topic-maps.tmdm:string-datatype))))
165 ((:iri :qname) (values (literal-iri-reference parser) (topic-maps.tmdm:iri-datatype)))
166 (otherwise (problem 'ctm-rejection (if (eq context :variant) :expected-variant-value :expected-occurrence-value)
167 (token-position token) "Expected a supported CTM literal value.")))))
168
169 (defun read-identity-tail (parser map topic)
170 (let ((start (look parser)))
171 (multiple-value-bind (kind iri) (identity-value parser)
172 (if (punctuation-p parser #\:)
173 (progn
174 (consume parser)
175 (multiple-value-bind (value datatype) (read-literal parser)
176 (let* ((type (topic-maps.tmdm:intern-topic map kind iri))
177 (scope (read-scope parser map)))
178 (topic-maps.tmdm:add-occurrence topic type value :datatype datatype :scope scope)
179 (topic-maps.tmdm:canonical-topic topic))))
180 (if (eq :identifier (token-kind start))
181 (if (punctuation-p parser #\()
182 (problem 'ctm-unsupported :topic-tail (token-position start) "Template invocations are outside this subset.")
183 (problem 'ctm-rejection :expected-occurrence-type-separator (token-position (look parser))
184 "Expected ':' after the Occurrence Type."))
185 (topic-maps.tmdm:add-topic-identifier topic kind iri))))))
186
187 (defun read-variant (parser map name)
188 "CTM 3.12: required explicit Scope, then union with the current Parent Scope."
189 (consume parser) ; (
190 (multiple-value-bind (value datatype) (read-literal parser :variant)
191 (unless (punctuation-p parser #\@)
192 (problem 'ctm-rejection :expected-variant-scope (token-position (look parser))
193 "A Variant requires an explicit '@' Scope."))
194 (let* ((scope-position (token-position (look parser))) (themes (read-scope parser map))
195 (scope (append (topic-maps.tmdm:topic-name-scope name) themes)))
196 (unless (punctuation-p parser #\))
197 (problem 'ctm-rejection :missing-variant-close (token-position (look parser))
198 "Expected ')' after the Variant Scope."))
199 (consume parser)
200 (handler-case (topic-maps.tmdm:add-variant name value :datatype datatype :scope scope)
201 (topic-maps.tmdm:variant-error (c)
202 (problem 'ctm-rejection (topic-maps.tmdm:variant-error-code c) scope-position (princ-to-string c)))))))
203
204 (defun read-name (parser map topic)
205 "CTM 3.11: optional Topic reference plus ':' followed by a string.
206 Use the existing identity resolver; embedded Topics remain unsupported."
207 (let* ((token (look parser))
208 (typed (or (member (token-kind token) '(:identifier :iri :qname))
209 (and (eq :punctuation (token-kind token))
210 (find (token-value token) "=^"))))
211 (type (when typed (identity-reference parser map))))
212 (when typed
213 (unless (punctuation-p parser #\:)
214 (problem 'ctm-rejection :expected-name-type-separator
215 (token-position (look parser)) "Expected ':' after the name type."))
216 (consume parser))
217 (let ((value (consume parser)))
218 (unless (eq :string (token-kind value))
219 (problem 'ctm-rejection :expected-name-value (token-position value)
220 "Expected a quoted name value after '-' or the name type separator."))
221 (let* ((scope (read-scope parser map))
222 (name (if typed
223 (topic-maps.tmdm:add-name topic (token-value value) :type type :scope scope)
224 (topic-maps.tmdm:add-name topic (token-value value) :scope scope))))
225 (loop while (punctuation-p parser #\() do (read-variant parser map name))))
226 (topic-maps.tmdm:canonical-topic topic)))
227
228 (defun read-topic (parser map &optional (topic (identity-reference parser map)))
229 (let ((has-tail nil))
230 (loop
231 (cond
232 ((punctuation-p parser #\.) (consume parser) (return topic))
233 ((punctuation-p parser #\-)
234 (when has-tail
235 (problem 'ctm-rejection :expected-separator (token-position (look parser)) "Topic-tail statements need a semicolon separator."))
236 (consume parser)
237 (setf topic (read-name parser map topic))
238 (setf has-tail t))
239 ((and has-tail (punctuation-p parser #\;))
240 (consume parser)
241 (setf has-tail nil)
242 (when (punctuation-p parser #\.) (consume parser) (return topic)))
243 ((eq :eof (token-kind (look parser)))
244 (problem 'ctm-rejection :missing-period (token-position (look parser)) "Topic declaration requires a final period."))
245 ((or (and (eq :punctuation (token-kind (look parser)))
246 (find (token-value (look parser)) "=^"))
247 (member (token-kind (look parser)) '(:identifier :iri :qname)))
248 (when has-tail
249 (problem 'ctm-rejection :expected-separator (token-position (look parser)) "Topic-tail statements need a semicolon separator."))
250 (setf topic (read-identity-tail parser map topic) has-tail t))
251 ((punctuation-p parser #\()
252 (problem 'ctm-rejection :unexpected-variant (token-position (look parser)) "A Variant must immediately follow a Topic Name."))
253 (t (problem 'ctm-rejection :unexpected-token (token-position (look parser)) "Unexpected token after topic or name."))))))
254
255 (defun read-association (parser map type)
256 "CTM 3.13, restricted to one or two role declarations; optional scope, no reifier."
257 (consume parser) ; opening parenthesis already recognized by the caller
258 (let ((roles nil) (third-position nil))
259 (loop
260 (when (or (punctuation-p parser #\)) (eq :eof (token-kind (look parser))))
261 (problem 'ctm-rejection :expected-role (token-position (look parser)) "Expected a nonempty Association role declaration."))
262 (when (= 2 (length roles)) (setf third-position (token-position (look parser))))
263 (let* ((role-type (identity-reference parser map))
264 (type-end (lexer-cursor (parser-lexer parser)))
265 (colon (look parser)))
266 (unless (punctuation-p parser #\:)
267 (problem 'ctm-rejection :expected-role-type-separator (token-position colon) "Expected ':' after the Role type."))
268 (consume parser)
269 (let ((player-token (look parser)))
270 ;; CTM role production requires layout on at least one side of ':'.
271 ;; skip-layout handles whitespace and comments; gaps use source offsets.
272 (unless (or (> (token-position colon) type-end)
273 (> (token-position player-token) (1+ (token-position colon))))
274 (problem 'ctm-rejection :role-separator-whitespace (token-position colon)
275 "A Role separator needs whitespace or a comment on at least one side."))
276 (when (or (eq :eof (token-kind player-token))
277 (punctuation-p parser #\)) (punctuation-p parser #\,))
278 (problem 'ctm-rejection :expected-role-player (token-position player-token) "Expected a Topic as the Role player.")))
279 (push (list role-type (identity-reference parser map)) roles))
280 (cond ((punctuation-p parser #\,) (consume parser))
281 ((punctuation-p parser #\)) (consume parser) (return))
282 ((eq :eof (token-kind (look parser)))
283 (problem 'ctm-rejection :missing-association-close (token-position (look parser)) "Expected ')' after the Roles."))
284 (t (problem 'ctm-rejection :expected-role-separator (token-position (look parser)) "Expected ',' or ')' after a Role."))))
285 (when (> (length roles) 2)
286 (problem 'ctm-unsupported :association-arity third-position "Associations with more than two Role declarations are outside Slice 3."))
287 (let ((scope (read-scope parser map)))
288 (topic-maps.tmdm:make-association map type (nreverse roles) :scope scope))))
289
290 (defun deserialize-string (text &key document-iri source-name)
291 "Read the documented CTM subset, with per-document prefixes and qualified strings.
292 Source positions are zero-based character offsets; lines/columns are one-based."
293 (check-type text string)
294 (let ((*source-name* source-name) (*source-text* text))
295 (require-document-iri document-iri)
296 (let ((parser (make-parser (make-lexer text) document-iri))
297 (map (topic-maps.tmdm:make-topic-map)))
298 (handler-bind ((topic-maps.tmdm:variant-error
299 (lambda (c) (problem 'ctm-rejection (topic-maps.tmdm:variant-error-code c)
300 (lexer-cursor (parser-lexer parser)) (princ-to-string c)))))
301 (loop until (eq :eof (token-kind (look parser))) do
302 (if (eq :directive (token-kind (look parser)))
303 (read-prefix-directive parser)
304 (let ((topic (identity-reference parser map)))
305 (if (punctuation-p parser #\()
306 (read-association parser map topic)
307 (read-topic parser map topic))))))
308 map)))
309
310 (defun deserialize-file (pathname &key document-iri source-name)
311 "Read a UTF-8 CTM file, with optional UTF-8 BOM, using an explicit Document IRI.
312 Other encoding directives are UNSUPPORTED. File I/O errors propagate unchanged."
313 (let ((*source-name* source-name) (*source-text* ""))
314 (require-document-iri document-iri)
315 (with-open-file (input pathname :direction :input :element-type '(unsigned-byte 8))
316 (let ((bytes (make-array (file-length input) :element-type '(unsigned-byte 8))))
317 (unless (= (length bytes) (read-sequence bytes input))
318 (error "Input file changed or was truncated during reading."))
319 (deserialize-string (decode-utf8 bytes :strip-bom t)
320 :document-iri document-iri :source-name source-name)))))