1use std::collections::{BTreeMap, BTreeSet};
4
5use super::{
6 Parsed, ResourceDescriptionNTriplesLinks, Result, error, graph_error, graph_schema, identity,
7 parse, profile, units,
8};
9use crate::resource_description_ntriples_rules::read_resource_description_n_triples_token;
10use crate::{
11 LinkFlags, LinkId, LinkMetadata, LinkNetwork, LinkType, ResourceDescriptionLinks,
12 decode_resource_description_graph,
13};
14use serde_json::{Value, json};
15
16fn refs(network: &LinkNetwork, id: LinkId) -> Vec<LinkId> {
17 network
18 .link(id)
19 .expect("validated linked node exists")
20 .references()
21 .to_vec()
22}
23fn owned_terms(network: &LinkNetwork, root: LinkId) -> BTreeSet<LinkId> {
24 refs(network, refs(network, root)[1])
25 .into_iter()
26 .flat_map(|id| refs(network, id))
27 .collect()
28}
29fn blank(network: &LinkNetwork, id: LinkId) -> Value {
30 let children = refs(network, id);
31 json!({"kind":"blank", "sourceIdentifier":network.link(children[0]).unwrap().metadata().definition().unwrap(),
32 "value":network.link(children[1]).unwrap().metadata().definition().unwrap()})
33}
34struct Writer<'a> {
35 network: &'a mut LinkNetwork,
36}
37impl Writer<'_> {
38 fn node(
39 &mut self,
40 kind: &str,
41 children: &[LinkId],
42 definition: Option<&str>,
43 ) -> Result<LinkId> {
44 if self.network.len() >= 100_000 {
45 return Err(error(
46 "resourceLimit",
47 0,
48 "the syntax structural node limit is exceeded",
49 ));
50 }
51 let mut data = LinkMetadata::new()
52 .with_link_type(LinkType::Semantic)
53 .with_named(true)
54 .with_language(profile()["language"].as_str().unwrap())
55 .with_term(profile()["terms"][kind].as_str().unwrap());
56 if let Some(value) = definition {
57 data = data.with_definition(value);
58 }
59 Ok(self.network.insert_dynamic_link(children, data))
60 }
61 fn text(&mut self, value: &str) -> Result<LinkId> {
62 self.node("text", &[], Some(value))
63 }
64 fn position(&mut self, value: usize) -> Result<LinkId> {
65 self.node("position", &[], Some(&value.to_string()))
66 }
67 fn sequence(&mut self, values: &[LinkId]) -> Result<LinkId> {
68 self.node("sequence", values, None)
69 }
70 fn premise(&mut self) -> Result<LinkId> {
71 let specification = self.text(profile()["specification"].as_str().unwrap())?;
72 self.node("profile", &[specification], profile()["profile"].as_str())
73 }
74}
75struct Reader<'a> {
76 network: &'a LinkNetwork,
77 visited: BTreeSet<LinkId>,
78 fields: BTreeSet<LinkId>,
79}
80impl<'a> Reader<'a> {
81 fn new(network: &'a LinkNetwork) -> Self {
82 Self {
83 network,
84 visited: BTreeSet::new(),
85 fields: network
86 .links()
87 .filter(|link| {
88 link.metadata().link_type() == Some(LinkType::Field)
89 && link.references().len() == 3
90 })
91 .map(|link| link.references()[0])
92 .collect(),
93 }
94 }
95 fn node(
96 &mut self,
97 id: LinkId,
98 kind: &str,
99 arity: Option<usize>,
100 ) -> Result<(Vec<LinkId>, Option<String>)> {
101 let link = self
102 .network
103 .link(id)
104 .ok_or_else(|| error("malformed", 0, "a syntax reference is dangling"))?;
105 self.visited.insert(id);
106 if self.visited.len() > 100_000 {
107 return Err(error(
108 "resourceLimit",
109 0,
110 "the syntax structural node limit is exceeded",
111 ));
112 }
113 let data = link.metadata();
114 if data.link_type() != Some(LinkType::Semantic)
115 || !data.is_named()
116 || data.language() != profile()["language"].as_str()
117 || data.term() != profile()["terms"][kind].as_str()
118 || data.span().is_some()
119 || data.flags() != LinkFlags::clean()
120 || self.fields.contains(&id)
121 {
122 return Err(error(
123 "malformed",
124 0,
125 "a syntax node has a foreign role or concealed fields",
126 ));
127 }
128 if arity.is_some_and(|size| link.references().len() != size) {
129 return Err(error("malformed", 0, "a syntax node has the wrong arity"));
130 }
131 if !["text", "position", "profile", "token"].contains(&kind) && data.definition().is_some()
132 {
133 return Err(error(
134 "malformed",
135 0,
136 "a syntax node has unexpected scalar data",
137 ));
138 }
139 Ok((
140 link.references().to_vec(),
141 data.definition().map(str::to_owned),
142 ))
143 }
144 fn text(&mut self, id: LinkId) -> Result<String> {
145 let value = self
146 .node(id, "text", Some(0))?
147 .1
148 .ok_or_else(|| error("malformed", 0, "a syntax text value is invalid"))?;
149 if value.encode_utf16().count() > 262_144 {
150 return Err(error("malformed", 0, "a syntax text value is invalid"));
151 }
152 Ok(value)
153 }
154 fn premise(&mut self, id: LinkId) -> Result<()> {
155 let (children, definition) = self.node(id, "profile", Some(1))?;
156 if definition.as_deref() != profile()["profile"].as_str()
157 || self.text(children[0])? != profile()["specification"]
158 {
159 return Err(error(
160 "unsupported",
161 0,
162 "the syntax profile is not supported",
163 ));
164 }
165 Ok(())
166 }
167}
168
169pub(super) fn correspondence(
170 input: Option<&ResourceDescriptionLinks>,
171) -> Result<BTreeMap<String, Value>> {
172 let Some(input) = input else {
173 return Ok(BTreeMap::new());
174 };
175 let mut read = Reader::new(&input.network);
176 let children = read.node(input.root, "correspondenceRoot", Some(3))?.0;
177 read.premise(children[2])?;
178 decode_resource_description_graph(&input.network, children[0]).map_err(graph_error)?;
179 let owned = owned_terms(&input.network, children[0]);
180 let mut mapping = BTreeMap::new();
181 let mut targets = BTreeSet::new();
182 for id in read.node(children[1], "sequence", None)?.0 {
183 let pair = read.node(id, "correspondence", Some(2))?.0;
184 let label = read.text(pair[1])?;
185 if !owned.contains(&pair[0])
186 || input.network.link(pair[0]).unwrap().metadata().term()
187 != graph_schema()["terms"]["blank"].as_str()
188 {
189 return Err(error(
190 "malformed",
191 0,
192 "a blank correspondence is not owned by its graph",
193 ));
194 }
195 let value = blank(&input.network, pair[0]);
196 let lexical = units(&format!("_:{label}"));
197 let token = read_resource_description_n_triples_token(&lexical, 0.0);
198 if super::natural(token[0]) != 2
199 || super::natural(token[1]) != lexical.len()
200 || mapping.contains_key(&label)
201 || !targets.insert(identity(&value))
202 {
203 return Err(error(
204 "malformed",
205 0,
206 "blank correspondences must be valid and one to one",
207 ));
208 }
209 mapping.insert(label, value);
210 }
211 Ok(mapping)
212}
213pub(super) fn attach(
214 mut graph: ResourceDescriptionLinks,
215 source: &str,
216 parsed: &Parsed,
217) -> Result<ResourceDescriptionNTriplesLinks> {
218 let occurrences = refs(&graph.network, refs(&graph.network, graph.root)[2]);
219 let mut output = Writer {
220 network: &mut graph.network,
221 };
222 let mut tokens = Vec::new();
223 for token in &parsed.tokens {
224 let text = output.text(&token.raw)?;
225 let start = output.position(token.start)?;
226 let end = output.position(token.end)?;
227 tokens.push(output.node("token", &[text, start, end], Some(&token.kind.to_string()))?);
228 }
229 let mut statements = Vec::new();
230 for (index, statement) in parsed.statements.iter().enumerate() {
231 let selected = statement
232 .qualifiers
233 .iter()
234 .map(|index| tokens[*index])
235 .collect::<Vec<_>>();
236 let qualifiers = output.sequence(&selected)?;
237 statements.push(output.node(
238 "statement",
239 &[
240 occurrences[index],
241 tokens[statement.tokens[0]],
242 tokens[statement.tokens[1]],
243 tokens[statement.tokens[2]],
244 qualifiers,
245 tokens[statement.period],
246 ],
247 None,
248 )?);
249 }
250 let source = output.text(source)?;
251 let tokens = output.sequence(&tokens)?;
252 let statements = output.sequence(&statements)?;
253 let premise = output.premise()?;
254 let syntax_root = output.node(
255 "syntaxRoot",
256 &[graph.root, source, tokens, statements, premise],
257 None,
258 )?;
259 Ok(ResourceDescriptionNTriplesLinks {
260 network: graph.network,
261 root: graph.root,
262 syntax_root,
263 })
264}
265fn read_tokens(read: &mut Reader<'_>, ids: &[LinkId]) -> Result<String> {
266 let mut source = String::new();
267 let mut position = 0;
268 for id in ids {
269 let (children, kind) = read.node(*id, "token", Some(3))?;
270 let start = read.node(children[1], "position", Some(0))?.1;
271 let end = read.node(children[2], "position", Some(0))?.1;
272 let raw = read.text(children[0])?;
273 let input = units(&raw);
274 if start.as_deref() != Some(position.to_string().as_str())
275 || end.as_deref() != Some((position + input.len()).to_string().as_str())
276 {
277 return Err(error(
278 "malformed",
279 position,
280 "syntax token positions are not contiguous",
281 ));
282 }
283 let token = read_resource_description_n_triples_token(&input, 0.0);
284 if super::natural(token[0]) == 0
285 || kind.as_deref() != Some(super::natural(token[0]).to_string().as_str())
286 || super::natural(token[1]) != input.len()
287 {
288 return Err(error(
289 "malformed",
290 position,
291 "a syntax token does not match its lexical role",
292 ));
293 }
294 position += input.len();
295 source.push_str(&raw);
296 if position > 262_144 {
297 return Err(error(
298 "resourceLimit",
299 position,
300 "the syntax source limit is exceeded",
301 ));
302 }
303 }
304 Ok(source)
305}
306fn verify_statements(
307 read: &mut Reader<'_>,
308 ids: &[LinkId],
309 tokens: &[LinkId],
310 occurrences: &[LinkId],
311 parsed: &Parsed,
312) -> Result<()> {
313 if ids.len() != parsed.statements.len() || occurrences.len() != ids.len() {
314 return Err(error(
315 "malformed",
316 0,
317 "syntax statements and occurrences differ",
318 ));
319 }
320 for (index, id) in ids.iter().enumerate() {
321 let children = read.node(*id, "statement", Some(6))?.0;
322 let statement = &parsed.statements[index];
323 let expected = [
324 occurrences[index],
325 tokens[statement.tokens[0]],
326 tokens[statement.tokens[1]],
327 tokens[statement.tokens[2]],
328 children[4],
329 tokens[statement.period],
330 ];
331 if children != expected {
332 return Err(error(
333 "malformed",
334 0,
335 "a syntax statement references a foreign occurrence or token",
336 ));
337 }
338 let qualifiers = read.node(children[4], "sequence", None)?.0;
339 let expected = statement
340 .qualifiers
341 .iter()
342 .map(|index| tokens[*index])
343 .collect::<Vec<_>>();
344 if qualifiers != expected {
345 return Err(error(
346 "malformed",
347 0,
348 "a syntax qualifier references a foreign token",
349 ));
350 }
351 }
352 Ok(())
353}
354
355pub fn read_resource_description_ntriples_source(
360 network: &LinkNetwork,
361 syntax_root: LinkId,
362) -> Result<String> {
363 let mut read = Reader::new(network);
364 let children = read.node(syntax_root, "syntaxRoot", Some(5))?.0;
365 read.premise(children[4])?;
366 decode_resource_description_graph(network, children[0]).map_err(graph_error)?;
367 let scope = read.text(children[1])?;
368 let tokens = read.node(children[2], "sequence", None)?.0;
369 let source = read_tokens(&mut read, &tokens)?;
370 let parsed = parse(&source, &scope, &BTreeMap::new())?;
371 let statements = read.node(children[3], "sequence", None)?.0;
372 let occurrences = refs(network, refs(network, children[0])[2]);
373 verify_statements(&mut read, &statements, &tokens, &occurrences, &parsed)?;
374 Ok(source)
375}
376fn copy(
377 source: &LinkNetwork,
378 id: LinkId,
379 target: &mut LinkNetwork,
380 mapping: &mut BTreeMap<LinkId, LinkId>,
381 active: &mut BTreeSet<LinkId>,
382) -> Result<LinkId> {
383 if let Some(mapped) = mapping.get(&id) {
384 return Ok(*mapped);
385 }
386 if target.len() >= 100_000 || active.len() > 64 {
387 return Err(error(
388 "resourceLimit",
389 0,
390 "the correspondence graph limit is exceeded",
391 ));
392 }
393 if !active.insert(id) {
394 return Err(error(
395 "malformed",
396 0,
397 "a correspondence graph has a structural cycle",
398 ));
399 }
400 let link = source.link(id).expect("validated graph link exists");
401 let children = link
402 .references()
403 .iter()
404 .map(|id| copy(source, *id, target, mapping, active))
405 .collect::<Result<Vec<_>>>()?;
406 if target.len() >= 100_000 {
407 return Err(error(
408 "resourceLimit",
409 0,
410 "the correspondence graph limit is exceeded",
411 ));
412 }
413 let mapped = target.insert_dynamic_link(&children, link.metadata().clone());
414 mapping.insert(id, mapped);
415 active.remove(&id);
416 Ok(mapped)
417}
418pub(super) fn create_correspondence(
419 network: &LinkNetwork,
420 root: LinkId,
421 labels: &BTreeMap<String, String>,
422) -> Result<ResourceDescriptionLinks> {
423 let mut target = LinkNetwork::new();
424 let mut mapping = BTreeMap::new();
425 let copied_root = copy(
426 network,
427 root,
428 &mut target,
429 &mut mapping,
430 &mut BTreeSet::new(),
431 )?;
432 let owned = owned_terms(network, root)
433 .into_iter()
434 .filter(|id| {
435 network.link(*id).unwrap().metadata().term()
436 == graph_schema()["terms"]["blank"].as_str()
437 })
438 .map(|id| (identity(&blank(network, id)), id))
439 .collect::<BTreeMap<_, _>>();
440 let mut output = Writer {
441 network: &mut target,
442 };
443 let mut pairs = Vec::new();
444 let mut ordered = labels.iter().collect::<Vec<_>>();
445 ordered.sort_by(|(left, _), (right, _)| left.encode_utf16().cmp(right.encode_utf16()));
446 for (identity, label) in ordered {
447 let text = output.text(label)?;
448 pairs.push(output.node("correspondence", &[mapping[&owned[identity]], text], None)?);
449 }
450 let pairs = output.sequence(&pairs)?;
451 let premise = output.premise()?;
452 let root = output.node("correspondenceRoot", &[copied_root, pairs, premise], None)?;
453 Ok(ResourceDescriptionLinks {
454 network: target,
455 root,
456 })
457}