1use std::collections::{BTreeMap, BTreeSet};
4
5use links_notation::{LiNo, ParserConfig, parse_lino_to_links_with_config};
6use serde_json::{Value, json};
7
8use super::{
9 GLOBAL_CONCEPT_PROOF_METHOD, GlobalConceptOptions, array, canonical,
10 create_global_concept_space_in, declarations, production, representative, string,
11};
12use crate::formal_concept_definition::read_formal_concept_definition;
13use crate::global_concept_rules::verify_global_concept_correspondence;
14use crate::grammar::Grammar;
15use crate::grammar::feature::{
16 check_grammar_selection_included_range_data, check_grammar_selection_included_range_grammar,
17};
18use crate::grammar::interchange::{
19 deserialize_grammar, parse_grammar_links, percent_decode_links_text, percent_encode_links_text,
20 render_declaration_links, render_links_expression, render_rule_fields, serialize_grammar,
21};
22use crate::link_network::LinkNetwork;
23
24fn definition_grammar(definition: &Value) -> Result<Grammar, String> {
25 let mut rule = definition.clone();
26 rule["name"] = json!("global_definition");
27 deserialize_grammar(
28 &json!({"schemaVersion":1,"start":"global_definition","sourceFormat":null,"rules":[rule]})
29 .to_string(),
30 )
31 .map_err(|error| error.to_string())
32}
33
34pub fn global_concept_space_to_links(space: &Value) -> Result<String, String> {
39 for source in array(&space["sources"])? {
40 check_grammar_selection_included_range_data(&source["context"])?;
41 }
42 for concept in array(&space["concepts"])? {
43 for definition in array(&concept["definitions"])? {
44 check_grammar_selection_included_range_data(&definition["definition"])?;
45 }
46 }
47 let word = |value: &Value| string(value).map(percent_encode_links_text);
48 let mut lines = vec!["(global-concept-space (schema-version 1))".to_owned()];
49 for source in array(&space["sources"])? {
50 let id = word(&source["id"])?;
51 let start = if source["start"].is_null() {
52 "(start unspecified)".to_owned()
53 } else {
54 format!("(start defined {})", word(&source["start"])?)
55 };
56 lines.push(format!(
57 "(grammar-origin {id} {} {} {start} (rule-order {}))",
58 word(&source["language"])?,
59 word(&source["edition"])?,
60 array(&source["ruleOrder"])?
61 .iter()
62 .map(word)
63 .collect::<Result<Vec<_>, _>>()?
64 .join(" ")
65 ));
66 if !source["sourceFormat"].is_null() {
67 lines.push(format!(
68 "(grammar-source-format {id} {})",
69 word(&source["sourceFormat"])?
70 ));
71 }
72 let context = &source["context"];
73 if !context["matching"].is_null() {
74 lines.push(format!(
75 "(grammar-context {id} (matching {}))",
76 word(&context["matching"])?
77 ));
78 }
79 if !context["settling"].is_null() {
80 lines.push(format!(
81 "(grammar-context {id} (settling {}))",
82 array(&context["settling"])?
83 .iter()
84 .map(word)
85 .collect::<Result<Vec<_>, _>>()?
86 .join(" ")
87 ));
88 }
89 let grammar = deserialize_grammar(&json!({"schemaVersion":1,"start":"global_context","rules":[{"name":"global_context","kind":"normal","expression":{"kind":"empty"}}],"declarations":context}).to_string()).map_err(|error| error.to_string())?;
90 for declaration in render_declaration_links(grammar.declarations()) {
91 lines.push(format!("(grammar-context {id} {declaration})"));
92 }
93 }
94 if let Some(definitions) = space["formalDefinitions"].as_object() {
95 for (alias, definition) in definitions {
96 let root = definition["root"]
97 .as_u64()
98 .ok_or("a formal origin needs a root")?;
99 let definition_text = string(&definition["links"])?;
100 lines.push(format!(
101 "(formal-origin-definition {} {root} (links {}))",
102 percent_encode_links_text(alias),
103 definition_text.trim().replace('\n', " ")
104 ));
105 }
106 }
107 for concept in array(&space["concepts"])? {
108 let id = word(&concept["id"])?;
109 lines.push(format!("(global-concept {id})"));
110 for origin in array(&concept["origins"])? {
111 let alias = word(&origin["alias"])?;
112 let meaning = if origin["concept"].is_null() {
113 String::new()
114 } else {
115 format!(" (meaning {})", word(&origin["concept"])?)
116 };
117 lines.push(format!("(concept-origin {id} {alias} (source {}) (language {}) (edition {}) (rule {}){meaning})", word(&origin["source"])?, word(&origin["language"])?, word(&origin["edition"])?, word(&origin["rule"])?));
118 for source_alias in array(&origin["sourceNames"])? {
119 lines.push(format!(
120 "(source-alias {alias} {} {})",
121 word(&source_alias["source"])?,
122 word(&source_alias["name"])?
123 ));
124 }
125 }
126 for definition in array(&concept["definitions"])? {
127 let grammar = definition_grammar(&definition["definition"])?;
128 let rule = grammar
129 .rules()
130 .first()
131 .ok_or("missing concept definition")?;
132 lines.push(format!(
133 "(concept-definition {id} {} {} {} {})",
134 word(&definition["origin"])?,
135 rule.kind.as_str(),
136 render_links_expression(&rule.expr),
137 render_rule_fields(&rule.attributes).join(" ")
138 ));
139 }
140 }
141 for proof in array(&space["proofs"])? {
142 let pairs = array(&proof["correspondence"])?
143 .iter()
144 .map(|pair| Ok(format!("({} {})", word(&pair[0])?, word(&pair[1])?)))
145 .collect::<Result<Vec<_>, String>>()?;
146 lines.push(format!(
147 "(concept-proof {} {} {} (correspondence {}))",
148 word(&proof["method"])?,
149 word(&proof["first"])?,
150 word(&proof["second"])?,
151 pairs.join(" ")
152 ));
153 }
154 for failure in array(&space["failures"])? {
155 lines.push(format!(
156 "(unproved-equivalence {} {})",
157 array(&failure["members"])?
158 .iter()
159 .map(word)
160 .collect::<Result<Vec<_>, _>>()?
161 .join(" "),
162 word(&failure["reason"])?
163 ));
164 }
165 for ambiguity in array(&space["ambiguities"])? {
166 lines.push(format!(
167 "(ambiguous-origin {} {})",
168 word(&ambiguity["alias"])?,
169 array(&ambiguity["meanings"])?
170 .iter()
171 .map(word)
172 .collect::<Result<Vec<_>, _>>()?
173 .join(" ")
174 ));
175 }
176 for (old, current) in space["redirects"]
177 .as_object()
178 .ok_or("invalid concept redirects")?
179 {
180 lines.push(format!(
181 "(concept-redirect {} {})",
182 percent_encode_links_text(old),
183 word(current)?
184 ));
185 }
186 Ok(format!("{}\n", lines.join("\n")))
187}
188
189fn link_atom(node: &LiNo<String>) -> Result<&str, String> {
190 match node {
191 LiNo::Ref(word) => Ok(word),
192 LiNo::Link {
193 id: Some(word),
194 values,
195 } if values.is_empty() => Ok(word),
196 LiNo::Link { .. } => Err("expected a global concept word".to_owned()),
197 }
198}
199
200fn link_word(node: &LiNo<String>) -> Result<String, String> {
201 percent_decode_links_text(link_atom(node)?).map_err(|error| error.to_string())
202}
203
204fn link_parts(node: &LiNo<String>) -> Result<(&str, &[LiNo<String>]), String> {
205 match node {
206 LiNo::Link { id: None, values } if !values.is_empty() => {
207 Ok((link_atom(&values[0])?, &values[1..]))
208 }
209 _ => Err("expected a structured global concept link".to_owned()),
210 }
211}
212
213fn print_link(node: &LiNo<String>) -> Result<String, String> {
214 match node {
215 LiNo::Link { id: None, values } if !values.is_empty() => Ok(format!(
216 "({})",
217 values
218 .iter()
219 .map(print_link)
220 .collect::<Result<Vec<_>, _>>()?
221 .join(" ")
222 )),
223 _ => link_atom(node).map(str::to_owned),
224 }
225}
226
227fn print_network_link(node: &LiNo<String>) -> String {
228 match node {
229 LiNo::Link { id, values } if !values.is_empty() => {
230 let prefix = id.as_ref().map_or(String::new(), |id| format!("{id}: "));
231 format!(
232 "({prefix}{})",
233 values
234 .iter()
235 .map(print_network_link)
236 .collect::<Vec<_>>()
237 .join(" ")
238 )
239 }
240 LiNo::Link { id, .. } => id.clone().unwrap_or_default(),
241 LiNo::Ref(value) => value.clone(),
242 }
243}
244
245pub fn read_global_concept_space_links(
251 source: &str,
252 options: &GlobalConceptOptions,
253) -> Result<Value, String> {
254 read_validated_global_concept_archive(source, options).map(|archive| archive.space)
255}
256
257pub(super) struct ValidatedGlobalConceptArchive {
258 pub(super) space: Value,
259 pub(super) imported: Vec<Value>,
260}
261
262pub(super) fn read_validated_global_concept_archive(
263 source: &str,
264 options: &GlobalConceptOptions,
265) -> Result<ValidatedGlobalConceptArchive, String> {
266 let statements = parse_lino_to_links_with_config(source, &ParserConfig::without_comments())
267 .map_err(|error| error.to_string())?;
268 if statements.is_empty() {
269 return Err("missing global concept space header".to_owned());
270 }
271 let mut space = json!({"schemaVersion":1,"sources":[],"concepts":[],"mappings":{},"proofs":[],"failures":[],"ambiguities":[],"redirects":{},"formalDefinitions":{}});
272 let mut sources = BTreeMap::new();
273 let mut concepts = BTreeMap::new();
274 let mut origins: BTreeMap<String, (usize, usize)> = BTreeMap::new();
275 let mut contexts: BTreeMap<String, Vec<LiNo<String>>> = BTreeMap::new();
276 for (at, statement) in statements.iter().enumerate() {
277 let (head, args) = link_parts(statement)?;
278 if at == 0 {
279 if head != "global-concept-space"
280 || args.len() != 1
281 || print_link(&args[0])? != "(schema-version 1)"
282 {
283 return Err("unsupported global concept space header".to_owned());
284 }
285 continue;
286 }
287 match head {
288 "formal-origin-definition" => {
289 if args.len() != 3 {
290 return Err("invalid or duplicated formal origin definition".to_owned());
291 }
292 let alias = link_word(&args[0])?;
293 if space["formalDefinitions"].get(&alias).is_some() {
294 return Err("invalid or duplicated formal origin definition".to_owned());
295 }
296 let root = link_word(&args[1])?
297 .parse::<u64>()
298 .map_err(|_| "a formal origin needs a root".to_owned())?;
299 let (tag, links) = link_parts(&args[2])?;
300 if tag != "links" {
301 return Err("a formal origin needs actual linked definitions".to_owned());
302 }
303 let text = format!(
304 "{}\n",
305 links
306 .iter()
307 .map(print_network_link)
308 .collect::<Vec<_>>()
309 .join("\n")
310 );
311 let network = LinkNetwork::from_lino(&text).map_err(|error| error.to_string())?;
312 let definition = json!({"root":root,"links":network.to_lino()});
313 read_formal_concept_definition(&definition)?;
314 space["formalDefinitions"][alias] = definition;
315 }
316 "grammar-origin" => {
317 if args.len() != 5 {
318 return Err(
319 "a grammar origin has source, language, edition, start and rule order"
320 .to_owned(),
321 );
322 }
323 let (start_tag, start_values) = link_parts(&args[3])?;
324 if start_tag != "start" {
325 return Err("missing grammar start".to_owned());
326 }
327 let start = match start_values {
328 [policy] if link_atom(policy)? == "unspecified" => Value::Null,
329 [policy, rule] if link_atom(policy)? == "defined" => json!(link_word(rule)?),
330 _ => return Err("invalid grammar start".to_owned()),
331 };
332 let (order_tag, order_values) = link_parts(&args[4])?;
333 if order_tag != "rule-order" {
334 return Err("missing grammar rule order".to_owned());
335 }
336 let rule_order = order_values
337 .iter()
338 .map(link_word)
339 .collect::<Result<Vec<_>, _>>()?;
340 if rule_order.iter().collect::<BTreeSet<_>>().len() != rule_order.len() {
341 return Err("duplicated grammar rule order".to_owned());
342 }
343 let id = link_word(&args[0])?;
344 if sources.contains_key(&id) {
345 return Err(format!("duplicate grammar origin {id}"));
346 }
347 let entries = space["sources"]
348 .as_array_mut()
349 .ok_or("invalid grammar sources")?;
350 sources.insert(id.clone(), entries.len());
351 contexts.insert(id.clone(), Vec::new());
352 entries.push(json!({"id":id,"language":link_word(&args[1])?,"edition":link_word(&args[2])?,"start":start,"ruleOrder":rule_order,"context":null}));
353 }
354 "grammar-source-format" => {
355 if args.len() != 2 {
356 return Err("a grammar source format has an origin and one format".to_owned());
357 }
358 let id = link_word(&args[0])?;
359 let index = *sources
360 .get(&id)
361 .ok_or("unknown or duplicate grammar source format origin")?;
362 if space["sources"][index].get("sourceFormat").is_some() {
363 return Err("unknown or duplicate grammar source format origin".to_owned());
364 }
365 space["sources"][index]["sourceFormat"] = json!(link_word(&args[1])?);
366 }
367 "grammar-context" => {
368 if args.len() != 2 {
369 return Err("unknown grammar context origin".to_owned());
370 }
371 contexts
372 .get_mut(&link_word(&args[0])?)
373 .ok_or("unknown grammar context origin")?
374 .push(args[1].clone());
375 }
376 "global-concept" => {
377 if args.len() != 1 {
378 return Err("a global concept has one identity".to_owned());
379 }
380 let id = link_word(&args[0])?;
381 if concepts.contains_key(&id) {
382 return Err(format!("duplicate global concept {id}"));
383 }
384 let entries = space["concepts"]
385 .as_array_mut()
386 .ok_or("invalid global concepts")?;
387 concepts.insert(id.clone(), entries.len());
388 entries.push(
389 json!({"id":id,"origins":[],"definition":null,"definitions":[],"proofs":[]}),
390 );
391 }
392 "concept-origin" => {
393 if !(6..=7).contains(&args.len()) {
394 return Err(
395 "a concept origin has identity, alias and qualification fields".to_owned(),
396 );
397 }
398 let id = link_word(&args[0])?;
399 let alias = link_word(&args[1])?;
400 let index = *concepts
401 .get(&id)
402 .ok_or("unknown concept or duplicate origin")?;
403 if origins.contains_key(&alias) {
404 return Err("unknown concept or duplicate origin".to_owned());
405 }
406 let mut fields = BTreeMap::new();
407 for field in &args[2..] {
408 let (key, values) = link_parts(field)?;
409 if !["source", "language", "edition", "rule", "meaning"].contains(&key)
410 || values.len() != 1
411 || fields.contains_key(key)
412 {
413 return Err(format!("invalid concept origin field {key}"));
414 }
415 fields.insert(key.to_owned(), link_word(&values[0])?);
416 }
417 for key in ["source", "language", "edition", "rule"] {
418 if !fields.contains_key(key) {
419 return Err("incomplete concept origin qualification".to_owned());
420 }
421 }
422 let grammar = &space["sources"][*sources
423 .get(&fields["source"])
424 .ok_or("inconsistent concept origin qualification")?];
425 if grammar["language"] != fields["language"]
426 || grammar["edition"] != fields["edition"]
427 || alias != format!("{}:{}", fields["source"], fields["rule"])
428 {
429 return Err("inconsistent concept origin qualification".to_owned());
430 }
431 let entries = space["concepts"][index]["origins"]
432 .as_array_mut()
433 .ok_or("invalid concept origins")?;
434 origins.insert(alias.clone(), (index, entries.len()));
435 entries.push(json!({"alias":alias,"source":fields["source"],"language":fields["language"],"edition":fields["edition"],"rule":fields["rule"],"concept":fields.get("meaning"),"sourceNames":[]}));
436 space["mappings"][alias] = json!(id);
437 }
438 "source-alias" => {
439 if args.len() != 3 {
440 return Err("unknown source alias origin".to_owned());
441 }
442 let (concept, origin) = *origins
443 .get(&link_word(&args[0])?)
444 .ok_or("unknown source alias origin")?;
445 space["concepts"][concept]["origins"][origin]["sourceNames"]
446 .as_array_mut()
447 .ok_or("invalid source aliases")?
448 .push(json!({"source":link_word(&args[1])?,"name":link_word(&args[2])?}));
449 }
450 "concept-definition" => {
451 if args.len() < 4 {
452 return Err("incomplete concept definition".to_owned());
453 }
454 let id = link_word(&args[0])?;
455 let alias = link_word(&args[1])?;
456 let index = *concepts
457 .get(&id)
458 .ok_or("unknown or duplicated concept definition origin")?;
459 if space["mappings"][&alias] != id
460 || array(&space["concepts"][index]["definitions"])?
461 .iter()
462 .any(|entry| entry["origin"] == alias)
463 {
464 return Err("unknown or duplicated concept definition origin".to_owned());
465 }
466 let word = percent_encode_links_text(&alias);
467 let grammar = parse_grammar_links(&format!(
468 "(grammar (start {word}))\n(rule {word} {} {})\n",
469 print_link(&args[2])?,
470 args[3..]
471 .iter()
472 .map(print_link)
473 .collect::<Result<Vec<_>, _>>()?
474 .join(" ")
475 ))
476 .map_err(|error| error.to_string())?;
477 check_grammar_selection_included_range_grammar(&grammar)?;
478 let serialized: Value = serde_json::from_str(&serialize_grammar(&grammar))
479 .map_err(|error| error.to_string())?;
480 let definition = production(&serialized["rules"][0]);
481 space["concepts"][index]["definitions"]
482 .as_array_mut()
483 .ok_or("invalid concept definitions")?
484 .push(json!({"origin":alias,"definition":definition}));
485 if space["concepts"][index]["definition"].is_null() {
486 space["concepts"][index]["definition"] = definition;
487 }
488 }
489 "concept-proof" => {
490 if args.len() != 4 {
491 return Err("incomplete concept proof".to_owned());
492 }
493 let (tag, pairs) = link_parts(&args[3])?;
494 if tag != "correspondence" {
495 return Err("missing proof correspondence".to_owned());
496 }
497 let pairs = pairs
498 .iter()
499 .map(|pair| match pair {
500 LiNo::Link { id: None, values } if values.len() == 2 => {
501 Ok(json!([link_word(&values[0])?, link_word(&values[1])?]))
502 }
503 _ => Err("invalid proof correspondence pair".to_owned()),
504 })
505 .collect::<Result<Vec<_>, String>>()?;
506 space["proofs"].as_array_mut().ok_or("invalid concept proofs")?.push(json!({"method":link_word(&args[0])?,"first":link_word(&args[1])?,"second":link_word(&args[2])?,"correspondence":pairs}));
507 }
508 "unproved-equivalence" => {
509 if args.len() != 3 {
510 return Err("invalid unproved equivalence".to_owned());
511 }
512 space["failures"].as_array_mut().ok_or("invalid equivalence failures")?.push(json!({"members":[link_word(&args[0])?,link_word(&args[1])?],"reason":link_word(&args[2])?}));
513 }
514 "ambiguous-origin" => {
515 if args.len() < 3 {
516 return Err("invalid ambiguous origin".to_owned());
517 }
518 space["ambiguities"].as_array_mut().ok_or("invalid concept ambiguities")?.push(json!({"alias":link_word(&args[0])?,"meanings":args[1..].iter().map(link_word).collect::<Result<Vec<_>,_>>()?}));
519 }
520 "concept-redirect" => {
521 if args.len() != 2 {
522 return Err("invalid concept redirect".to_owned());
523 }
524 let old = link_word(&args[0])?;
525 if space["redirects"].get(&old).is_some() {
526 return Err("duplicate concept redirect".to_owned());
527 }
528 space["redirects"][old] = json!(link_word(&args[1])?);
529 }
530 _ => return Err(format!("unknown global concept link {head}")),
531 }
532 }
533 let mut imported = Vec::new();
534 for index in 0..array(&space["sources"])?.len() {
535 let source = space["sources"][index].clone();
536 let id = string(&source["id"])?;
537 let context = contexts.get(id).ok_or("missing grammar context")?;
538 let mut header = Vec::new();
539 let mut declared = Vec::new();
540 for field in context {
541 if ["matching", "settling"].contains(&link_parts(field)?.0) {
542 header.push(print_link(field)?);
543 } else {
544 declared.push(print_link(field)?);
545 }
546 }
547 let format = source
548 .get("sourceFormat")
549 .map(|format| {
550 string(format)
551 .map(|format| format!("(format {})", percent_encode_links_text(format)))
552 })
553 .transpose()?
554 .unwrap_or_default();
555 let placeholder = parse_grammar_links(&format!(
556 "(grammar (start placeholder) {format} {})\n{}\n(rule placeholder normal empty)\n",
557 header.join(" "),
558 declared.join("\n")
559 ))
560 .map_err(|error| error.to_string())?;
561 check_grammar_selection_included_range_grammar(&placeholder)?;
562 let serialized: Value = serde_json::from_str(&serialize_grammar(&placeholder))
563 .map_err(|error| error.to_string())?;
564 let context = declarations(serialized.get("declarations"));
565 space["sources"][index]["context"] = context.clone();
566 let mut rules = Vec::new();
567 for concept in array(&space["concepts"])? {
568 if array(&concept["origins"])?.is_empty()
569 || array(&concept["definitions"])?.len() != array(&concept["origins"])?.len()
570 {
571 return Err("a copied global origin needs exactly one production".to_owned());
572 }
573 for definition in array(&concept["definitions"])? {
574 let alias = string(&definition["origin"])?;
575 let (concept_index, origin_index) =
576 *origins.get(alias).ok_or("missing production origin")?;
577 let origin = &space["concepts"][concept_index]["origins"][origin_index];
578 if origin["source"] != id {
579 continue;
580 }
581 let mut rule = definition["definition"].clone();
582 rule["name"] = origin["rule"].clone();
583 rule["sourceNames"] = origin["sourceNames"].clone();
584 if !origin["concept"].is_null() {
585 rule["concept"] = origin["concept"].clone();
586 }
587 rules.push(rule);
588 }
589 }
590 let order = array(&source["ruleOrder"])?;
591 if order.len() != rules.len()
592 || order
593 .iter()
594 .any(|name| !rules.iter().any(|rule| rule["name"] == *name))
595 {
596 return Err("grammar rule order disagrees with copied productions".to_owned());
597 }
598 if !source["start"].is_null() && !order.contains(&source["start"]) {
599 return Err("grammar start names no copied production".to_owned());
600 }
601 rules.sort_by_key(|rule| {
602 order
603 .iter()
604 .position(|name| *name == rule["name"])
605 .unwrap_or(order.len())
606 });
607 imported.push(json!({"id":source["id"],"language":source["language"],"edition":source["edition"],"grammar":{"schemaVersion":serialized["schemaVersion"],"start":source["start"],"sourceFormat":source["sourceFormat"],"rules":rules,"declarations":context}}));
608 }
609 let mut required = Vec::new();
610 for failure in array(&space["failures"])? {
611 required.push([
612 string(&failure["members"][0])?.to_owned(),
613 string(&failure["members"][1])?.to_owned(),
614 ]);
615 }
616 let settings = GlobalConceptOptions {
617 records: options.records.clone(),
618 formal_definitions: Some(space["formalDefinitions"].clone()),
619 previous: Some(space.clone()),
620 equivalences: required,
621 };
622 let (checked, graph, aliases) = create_global_concept_space_in(&imported, &settings)?;
623 if space["formalDefinitions"]
624 .as_object()
625 .ok_or("invalid formal definitions")?
626 .keys()
627 .any(|alias| !aliases.contains_key(alias))
628 {
629 return Err("unknown formal definition origin".to_owned());
630 }
631 let mut witnessed: Vec<_> = (0..aliases.len()).collect();
632 for proof in array(&space["proofs"])? {
633 let pairs = array(&proof["correspondence"])?;
634 if proof["method"] != GLOBAL_CONCEPT_PROOF_METHOD
635 || pairs.is_empty()
636 || pairs[0][0] != proof["first"]
637 || pairs[0][1] != proof["second"]
638 {
639 return Err("invalid global concept proof witness".to_owned());
640 }
641 let mut first = Vec::new();
642 let mut second = Vec::new();
643 for pair in pairs {
644 let one = string(&pair[0])?;
645 let other = string(&pair[1])?;
646 first.push(
647 *aliases
648 .get(one)
649 .ok_or("invalid global concept proof witness")?,
650 );
651 second.push(
652 *aliases
653 .get(other)
654 .ok_or("invalid global concept proof witness")?,
655 );
656 }
657 let number = |index: usize| serde_json::Number::from(index).as_f64().unwrap();
658 let to_numbers = |values: &[usize]| values.iter().map(|index| number(*index)).collect();
659 if !verify_global_concept_correspondence(
660 graph.shapes.clone(),
661 graph.meanings.clone(),
662 to_numbers(&graph.offsets),
663 to_numbers(&graph.edges),
664 to_numbers(&first),
665 to_numbers(&second),
666 ) {
667 return Err("unproved global concept correspondence".to_owned());
668 }
669 for (index, pair) in pairs.iter().enumerate() {
670 if space["mappings"][string(&pair[0])?] != space["mappings"][string(&pair[1])?] {
671 return Err("a proof correspondence has different global identities".to_owned());
672 }
673 let one = representative(&witnessed, first[index]);
674 let other = representative(&witnessed, second[index]);
675 witnessed[one.max(other)] = one.min(other);
676 }
677 }
678 if canonical(&checked["mappings"]) != canonical(&space["mappings"]) {
679 return Err("shared global identity lacks a current one-to-one proof".to_owned());
680 }
681 if canonical(&checked["failures"]) != canonical(&space["failures"])
682 || canonical(&checked["ambiguities"]) != canonical(&space["ambiguities"])
683 {
684 return Err("global concept uncertainty disagrees with current definitions".to_owned());
685 }
686 for index in 0..array(&space["concepts"])?.len() {
687 let concept = &space["concepts"][index];
688 let members = array(&concept["origins"])?;
689 if members.is_empty() {
690 return Err("a copied global origin needs exactly one production".to_owned());
691 }
692 let root = representative(
693 &witnessed,
694 *aliases
695 .get(string(&members[0]["alias"])?)
696 .ok_or("unknown concept origin")?,
697 );
698 let present: BTreeSet<_> = members
699 .iter()
700 .map(|origin| string(&origin["alias"]))
701 .collect::<Result<_, _>>()?;
702 for alias in &present {
703 if representative(
704 &witnessed,
705 *aliases.get(*alias).ok_or("unknown concept origin")?,
706 ) != root
707 {
708 return Err("a shared global concept lacks its proof witnesses".to_owned());
709 }
710 }
711 let proofs: Vec<_> = array(&space["proofs"])?
712 .iter()
713 .enumerate()
714 .filter_map(|(index, proof)| {
715 proof["correspondence"]
716 .as_array()
717 .is_some_and(|pairs| {
718 pairs.iter().any(|pair| {
719 present.contains(pair[0].as_str().unwrap_or_default())
720 && present.contains(pair[1].as_str().unwrap_or_default())
721 })
722 })
723 .then_some(index)
724 })
725 .collect();
726 space["concepts"][index]["proofs"] = json!(proofs);
727 }
728 for (old, current) in space["redirects"]
729 .as_object()
730 .ok_or("invalid concept redirects")?
731 {
732 let current = string(current)?;
733 if concepts.contains_key(old) || !concepts.contains_key(current) || old == current {
734 return Err("invalid global concept identity redirect".to_owned());
735 }
736 }
737 Ok(ValidatedGlobalConceptArchive { space, imported })
738}