1mod provenance;
5
6use std::collections::BTreeMap;
7use std::fmt::Write as _;
8use std::sync::OnceLock;
9
10use serde_json::{Value, json};
11
12use crate::resource_description_ntriples_rules::{
13 accept_resource_description_n_triples_final_state,
14 read_resource_description_n_triples_canonical_escape, read_resource_description_n_triples_role,
15 read_resource_description_n_triples_scalar, read_resource_description_n_triples_token,
16 read_resource_description_n_triples_transition,
17};
18use crate::resource_description_rules::{
19 accept_resource_description_identifier, accept_resource_description_language,
20};
21use crate::{
22 LinkId, LinkNetwork, ResourceDescriptionLinks, decode_resource_description_graph,
23 import_resource_description_graph, read_structured_data_lino,
24};
25
26pub use provenance::read_resource_description_ntriples_source;
27
28#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct ResourceDescriptionNTriplesLinks {
31 pub network: LinkNetwork,
33 pub root: LinkId,
35 pub syntax_root: LinkId,
37}
38
39#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct ResourceDescriptionNTriplesOutput {
42 pub source: String,
44 pub correspondence: ResourceDescriptionLinks,
46}
47
48#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct ResourceDescriptionNTriplesError {
51 pub kind: &'static str,
53 pub offset: usize,
55 pub message: String,
57}
58
59impl std::fmt::Display for ResourceDescriptionNTriplesError {
60 fn fmt(&self, output: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 write!(
62 output,
63 "resource description N-Triples: {} at UTF-16 position {}",
64 self.message, self.offset
65 )
66 }
67}
68impl std::error::Error for ResourceDescriptionNTriplesError {}
69
70type Result<T> = std::result::Result<T, ResourceDescriptionNTriplesError>;
71fn error(
72 kind: &'static str,
73 offset: usize,
74 message: impl Into<String>,
75) -> ResourceDescriptionNTriplesError {
76 ResourceDescriptionNTriplesError {
77 kind,
78 offset,
79 message: message.into(),
80 }
81}
82fn graph_error(message: String) -> ResourceDescriptionNTriplesError {
83 error(
84 if message.contains("limit") {
85 "resourceLimit"
86 } else {
87 "malformed"
88 },
89 0,
90 message,
91 )
92}
93fn profile() -> &'static Value {
94 static PROFILE: OnceLock<Value> = OnceLock::new();
95 PROFILE.get_or_init(|| {
96 read_structured_data_lino(include_str!(
97 "data/resource-description-ntriples-profile.lino"
98 ))
99 .expect("the packaged N-Triples profile is valid")
100 })
101}
102fn graph_schema() -> &'static Value {
103 static SCHEMA: OnceLock<Value> = OnceLock::new();
104 SCHEMA.get_or_init(|| {
105 read_structured_data_lino(include_str!("data/resource-description-schema.lino"))
106 .expect("the packaged RDF graph schema is valid")
107 })
108}
109fn units(source: &str) -> Vec<f64> {
110 source.encode_utf16().map(f64::from).collect()
111}
112#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
115fn natural(value: f64) -> usize {
116 assert!(
117 value.is_finite() && value.fract() == 0.0 && (0.0..=f64::from(u32::MAX)).contains(&value)
118 );
119 usize::try_from(value as u32).expect("a bounded kernel field fits native indexing")
120}
121fn number(value: usize) -> f64 {
122 f64::from(
123 u32::try_from(value).expect("a bounded syntax position fits the portable scalar profile"),
124 )
125}
126fn identity(term: &Value) -> String {
127 let parts = match term["kind"].as_str().unwrap() {
128 "blank" => json!(["blank", term["sourceIdentifier"], term["value"]]),
129 "literal" => json!(["literal", term["value"], term["datatype"], term["language"]]),
130 _ => json!(["identifier", term["value"]]),
131 };
132 serde_json::to_string(&parts).expect("resource term strings serialize")
133}
134fn identifier(value: &str, offset: usize) -> Result<Value> {
135 if value.contains(['[', ']']) {
136 return Err(error(
137 "unsupported",
138 offset,
139 "bracketed identifiers require an address grammar outside this profile",
140 ));
141 }
142 if !accept_resource_description_identifier(&units(value)) {
143 return Err(error(
144 "malformed",
145 offset,
146 "an absolute identifier is required",
147 ));
148 }
149 Ok(json!({"kind":"identifier","value":value}))
150}
151fn lexical_error(diagnostic: f64) -> &'static str {
152 match natural(diagnostic) {
153 1 => "invalid Unicode scalar",
154 2 => "empty language tag",
155 3 => "invalid blank node label",
156 4 => "invalid Unicode scalar escape",
157 5 => "unknown character escape",
158 6 => "illegal unescaped character",
159 7 => "unterminated term",
160 _ => "unexpected syntax character",
161 }
162}
163fn slice(input: &[f64], start: usize, end: usize) -> Result<String> {
164 String::from_utf16(
165 &input[start..end]
166 .iter()
167 .map(|value| u16::try_from(natural(*value)).unwrap())
168 .collect::<Vec<_>>(),
169 )
170 .map_err(|_| error("malformed", start, "invalid Unicode scalar"))
171}
172fn token_value(input: &[f64], start: usize, end: usize, kind: usize) -> Result<String> {
173 if kind == 2 || kind == 4 {
174 return slice(input, start + if kind == 2 { 2 } else { 1 }, end);
175 }
176 if kind != 1 && kind != 3 {
177 return Ok(String::new());
178 }
179 let mut result = String::new();
180 let mut index = start + 1;
181 while index < end - 1 {
182 let scalar = read_resource_description_n_triples_scalar(input, number(index), number(kind));
183 if scalar[2] != 0.0 || scalar[0] < 1.0 {
184 return Err(error("malformed", index, lexical_error(scalar[2])));
185 }
186 result.push(
187 char::from_u32(u32::try_from(natural(scalar[1])).unwrap())
188 .ok_or_else(|| error("malformed", index, "invalid Unicode scalar"))?,
189 );
190 index += natural(scalar[0]);
191 }
192 Ok(result)
193}
194struct Token {
195 kind: usize,
196 start: usize,
197 end: usize,
198 raw: String,
199}
200struct Statement {
201 tokens: Vec<usize>,
202 qualifiers: Vec<usize>,
203 period: usize,
204}
205struct Parsed {
206 triples: Vec<Value>,
207 tokens: Vec<Token>,
208 statements: Vec<Statement>,
209}
210fn parse(source: &str, scope: &str, mapping: &BTreeMap<String, Value>) -> Result<Parsed> {
211 let input = units(source);
212 if input.len() > 262_144 {
213 return Err(error(
214 "resourceLimit",
215 0,
216 "a source of at most 262144 UTF-16 units is required",
217 ));
218 }
219 let mut parsed = Parsed {
220 triples: Vec::new(),
221 tokens: Vec::new(),
222 statements: Vec::new(),
223 };
224 let mut state = 0;
225 let mut start = 0;
226 let mut triple = Vec::new();
227 let mut token_ids = Vec::new();
228 let mut qualifiers = Vec::new();
229 while start < input.len() {
230 if parsed.tokens.len() >= 10_000 {
231 return Err(error("resourceLimit", start, "the token limit is exceeded"));
232 }
233 let token = read_resource_description_n_triples_token(&input, number(start));
234 let kind = natural(token[0]);
235 let end = natural(token[1]);
236 if kind == 0 {
237 return Err(error("malformed", end, lexical_error(token[2])));
238 }
239 let next = read_resource_description_n_triples_transition(number(state), number(kind));
240 if next < 0.0 {
241 return Err(error(
242 "malformed",
243 start,
244 "a token cannot occupy this statement position",
245 ));
246 }
247 let value = token_value(&input, start, end, kind)?;
248 if value.encode_utf16().count() > 65_536 {
249 return Err(error(
250 "resourceLimit",
251 start,
252 "a term exceeds 65536 UTF-16 units",
253 ));
254 }
255 let token_index = parsed.tokens.len();
256 parsed.tokens.push(Token {
257 kind,
258 start,
259 end,
260 raw: slice(&input, start, end)?,
261 });
262 let role = natural(read_resource_description_n_triples_role(
263 number(state),
264 number(kind),
265 ));
266 match role {
267 1..=3 => {
268 if role == 1 {
269 triple.clear();
270 token_ids.clear();
271 qualifiers.clear();
272 }
273 let term = if kind == 1 {
274 identifier(&value, start)?
275 } else if kind == 2 {
276 mapping.get(&value).cloned().unwrap_or_else(
277 || json!({"kind":"blank","value":value,"sourceIdentifier":scope}),
278 )
279 } else {
280 json!({"kind":"literal","value":value})
281 };
282 triple.push(term);
283 token_ids.push(token_index);
284 }
285 4 => {
286 let lower = value.to_lowercase();
287 let grandfathered = graph_schema()["grandfatheredLanguages"]
288 .as_array()
289 .unwrap()
290 .iter()
291 .any(|tag| tag == &lower);
292 if !accept_resource_description_language(&units(&value), grandfathered) {
293 return Err(error("malformed", start, "invalid language tag"));
294 }
295 triple[2]["language"] = Value::String(value);
296 qualifiers.push(token_index);
297 }
298 5 => {
299 triple[2]["datatype"] = identifier(&value, start)?["value"].clone();
300 qualifiers.push(token_index);
301 }
302 6 => {
303 if triple[2]["datatype"] == graph_schema()["languageDatatype"]
304 && triple[2].get("language").is_none()
305 {
306 return Err(error(
307 "malformed",
308 start,
309 "a language string requires a language tag",
310 ));
311 }
312 parsed.triples.push(Value::Array(triple.clone()));
313 parsed.statements.push(Statement {
314 tokens: token_ids.clone(),
315 qualifiers: qualifiers.clone(),
316 period: token_index,
317 });
318 triple.clear();
319 }
320 _ => {
321 if kind == 6 {
322 qualifiers.push(token_index);
323 }
324 }
325 }
326 state = natural(next);
327 start = end;
328 }
329 if !accept_resource_description_n_triples_final_state(number(state)) {
330 return Err(error(
331 "malformed",
332 input.len(),
333 "an incomplete statement remains at the end of input",
334 ));
335 }
336 Ok(parsed)
337}
338
339pub fn import_resource_description_ntriples(
344 source: &str,
345 source_identifier: &str,
346 correspondence: Option<&ResourceDescriptionLinks>,
347) -> Result<ResourceDescriptionNTriplesLinks> {
348 let mapping = provenance::correspondence(correspondence)?;
349 let parsed = parse(source, source_identifier, &mapping)?;
350 let graph =
351 import_resource_description_graph(&Value::Array(parsed.triples.clone()), source_identifier)
352 .map_err(graph_error)?;
353 provenance::attach(graph, source_identifier, &parsed)
354}
355fn literal(value: &str) -> String {
356 let mut output = String::from("\"");
357 for character in value.chars() {
358 let escaped =
359 read_resource_description_n_triples_canonical_escape(f64::from(u32::from(character)));
360 if escaped < 0.0 {
361 output.push(character);
362 } else {
363 output.push('\\');
364 output.push(char::from_u32(u32::try_from(natural(escaped)).unwrap()).unwrap());
365 }
366 }
367 output.push('"');
368 output
369}
370fn canonical_term(term: &Value, labels: &BTreeMap<String, String>) -> String {
371 match term["kind"].as_str().unwrap() {
372 "identifier" => format!("<{}>", term["value"].as_str().unwrap()),
373 "blank" => format!("_:{}", labels[&identity(term)]),
374 _ => {
375 let mut result = literal(term["value"].as_str().unwrap());
376 if !term["language"].as_str().unwrap().is_empty() {
377 result.push('@');
378 result.push_str(term["language"].as_str().unwrap());
379 } else if term["datatype"] != graph_schema()["stringDatatype"] {
380 write!(result, "^^<{}>", term["datatype"].as_str().unwrap())
381 .expect("formatting a String succeeds");
382 }
383 result
384 }
385 }
386}
387
388pub fn emit_resource_description_ntriples(
393 network: &LinkNetwork,
394 root: LinkId,
395) -> Result<ResourceDescriptionNTriplesOutput> {
396 let graph = decode_resource_description_graph(network, root).map_err(graph_error)?;
397 let mut blank_keys = graph["triples"]
398 .as_array()
399 .unwrap()
400 .iter()
401 .flat_map(|triple| triple.as_array().unwrap())
402 .filter(|term| term["kind"] == "blank")
403 .map(identity)
404 .collect::<Vec<_>>();
405 blank_keys.sort_by(|left, right| left.encode_utf16().cmp(right.encode_utf16()));
406 blank_keys.dedup();
407 let labels = blank_keys
408 .into_iter()
409 .enumerate()
410 .map(|(index, key)| (key, format!("b{index}")))
411 .collect::<BTreeMap<_, _>>();
412 let mut lines = graph["triples"]
413 .as_array()
414 .unwrap()
415 .iter()
416 .map(|triple| {
417 format!(
418 "{} .\n",
419 triple
420 .as_array()
421 .unwrap()
422 .iter()
423 .map(|value| canonical_term(value, &labels))
424 .collect::<Vec<_>>()
425 .join(" ")
426 )
427 })
428 .collect::<Vec<_>>();
429 lines.sort_by(|left, right| left.encode_utf16().cmp(right.encode_utf16()));
430 Ok(ResourceDescriptionNTriplesOutput {
431 source: lines.concat(),
432 correspondence: provenance::create_correspondence(network, root, &labels)?,
433 })
434}