1use std::collections::{BTreeMap, BTreeSet};
2
3use crate::concept_records::{ConceptRecord, concept_record, concept_records};
4use crate::grammar::GRAMMAR_CONCEPTS;
5use crate::link_network::vocabulary::FORMER_CONCEPT_IDENTIFIERS;
6use crate::link_network::{Link, LinkId, LinkMetadata, LinkNetwork, LinkType};
7use crate::lino_serialization::LinoSerializationError;
8
9mod semantic_lexicon;
10mod views;
11pub use views::{ConceptViews, create_concept_views, read_concept_ontology, read_concept_taxonomy};
12
13use semantic_lexicon::{
14 SemanticLexiconConcept, is_wikidata_qid, is_wordnet_cili_id, semantic_lexicon,
15};
16
17const EXTERNAL_IDENTIFIER_VOCABULARY_PREFIX: &str = "external-identifier:";
18const FORMER_EXTERNAL_IDENTIFIER_VOCABULARY_PREFIX: &str = "external-id:";
20
21pub const FORMER_CONCEPT_ID_VOCABULARY: &str = "meta-language";
23
24pub const FORMER_CONCEPT_IDS: &[(&str, &str)] = FORMER_CONCEPT_IDENTIFIERS;
31
32#[must_use]
34pub fn current_concept_id(id: &str) -> &str {
35 concept_record(id).map_or_else(
36 || {
37 FORMER_CONCEPT_IDS
38 .iter()
39 .find(|(former, _)| *former == id)
40 .map_or(id, |(_, current)| current)
41 },
42 |record| record.id.as_str(),
43 )
44}
45
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub struct ConceptOntologyImportReport {
49 concepts: usize,
50 assigned: usize,
51 renamed: usize,
52 alias_links: usize,
53 syntax_mappings: usize,
54}
55
56impl ConceptOntologyImportReport {
57 #[must_use]
59 pub const fn concepts(self) -> usize {
60 self.concepts
61 }
62
63 #[must_use]
65 pub const fn assigned(self) -> usize {
66 self.assigned
67 }
68
69 #[must_use]
71 pub const fn renamed(self) -> usize {
72 self.renamed
73 }
74
75 #[must_use]
77 pub const fn alias_links(self) -> usize {
78 self.alias_links
79 }
80
81 #[must_use]
83 pub const fn syntax_mappings(self) -> usize {
84 self.syntax_mappings
85 }
86}
87
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
90pub struct ConceptRecordSeedReport {
91 concepts: usize,
92 links: usize,
93}
94
95impl ConceptRecordSeedReport {
96 #[must_use]
98 pub const fn concepts(self) -> usize {
99 self.concepts
100 }
101
102 #[must_use]
104 pub const fn links(self) -> usize {
105 self.links
106 }
107}
108
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
111pub struct ConceptOntologySeedReport {
112 lexicon_concepts: usize,
113 structural_concepts: usize,
114 grammar_concepts: usize,
115 formatting_concepts: usize,
116 alias_links: usize,
117 syntax_mappings: usize,
118}
119
120impl ConceptOntologySeedReport {
121 const fn new(
122 lexicon_concepts: usize,
123 structural_concepts: usize,
124 grammar_concepts: usize,
125 formatting_concepts: usize,
126 alias_links: usize,
127 syntax_mappings: usize,
128 ) -> Self {
129 Self {
130 lexicon_concepts,
131 structural_concepts,
132 grammar_concepts,
133 formatting_concepts,
134 alias_links,
135 syntax_mappings,
136 }
137 }
138
139 #[must_use]
141 pub const fn lexicon_concepts(self) -> usize {
142 self.lexicon_concepts
143 }
144
145 #[must_use]
147 pub const fn structural_concepts(self) -> usize {
148 self.structural_concepts
149 }
150
151 #[must_use]
153 pub const fn grammar_concepts(self) -> usize {
154 self.grammar_concepts
155 }
156
157 #[must_use]
159 pub const fn formatting_concepts(self) -> usize {
160 self.formatting_concepts
161 }
162
163 #[must_use]
165 pub const fn alias_links(self) -> usize {
166 self.alias_links
167 }
168
169 #[must_use]
171 pub const fn syntax_mappings(self) -> usize {
172 self.syntax_mappings
173 }
174}
175
176struct StructuralConcept {
177 id: &'static str,
178 definition: &'static str,
179 syntax: &'static [(&'static str, &'static str)],
180}
181
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183pub struct StatehoodConceptIds {
184 pub proposition: LinkId,
185 pub subject: LinkId,
186 pub object: LinkId,
187}
188
189const STATEHOOD_PROPOSITION_SYNTAX: &[(&str, &str)] = &[
190 ("English", "Hawaii is a state."),
191 ("en", "Hawaii is a state."),
192 ("Russian", "Гавайи это штат."),
193 ("ru", "Гавайи это штат."),
194];
195
196const HAWAII_ENTITY_SYNTAX: &[(&str, &str)] = &[
197 ("English", "Hawaii"),
198 ("en", "Hawaii"),
199 ("Russian", "Гавайи"),
200 ("ru", "Гавайи"),
201];
202
203const UNITED_STATES_STATE_SYNTAX: &[(&str, &str)] = &[
204 ("English", "state"),
205 ("en", "state"),
206 ("Russian", "штат"),
207 ("ru", "штат"),
208];
209
210const STRUCTURAL_CONCEPTS: &[StructuralConcept] = &[
211 StructuralConcept {
212 id: "function",
213 definition: "Reusable computation with parameters and a result boundary.",
214 syntax: &[
215 ("Rust", "fn"),
216 ("Python", "def"),
217 ("JavaScript", "function"),
218 ("C", "function"),
219 ("C++", "function"),
220 ("C#", "method"),
221 ("Java", "method"),
222 ("Visual Basic", "Function"),
223 ("R", "function"),
224 ("sql-ansi", "CREATE FUNCTION"),
225 ("Delphi/Object Pascal", "function"),
226 ],
227 },
228 StructuralConcept {
229 id: "binding",
230 definition: "Association between a name and a value or computation.",
231 syntax: &[
232 ("Rust", "let"),
233 ("Python", "="),
234 ("JavaScript", "let"),
235 ("C", "="),
236 ("C++", "="),
237 ("C#", "="),
238 ("Java", "="),
239 ("Visual Basic", "Dim"),
240 ("R", "<-"),
241 ("sql-ansi", "AS"),
242 ("Delphi/Object Pascal", ":="),
243 ],
244 },
245 StructuralConcept {
246 id: "application",
247 definition: "Application of a callable expression to arguments.",
248 syntax: &[
249 ("Rust", "call(...)"),
250 ("Python", "call(...)"),
251 ("JavaScript", "call(...)"),
252 ("C", "call(...)"),
253 ("C++", "call(...)"),
254 ("C#", "call(...)"),
255 ("Java", "call(...)"),
256 ("Visual Basic", "Call"),
257 ("R", "call(...)"),
258 ("sql-ansi", "CALL"),
259 ("Delphi/Object Pascal", "call(...)"),
260 ],
261 },
262 StructuralConcept {
263 id: "sequential-composition",
264 definition: "Ordered execution or evaluation of multiple operations.",
265 syntax: &[
266 ("Rust", ";"),
267 ("Python", "newline"),
268 ("JavaScript", ";"),
269 ("C", ";"),
270 ("C++", ";"),
271 ("C#", ";"),
272 ("Java", ";"),
273 ("Visual Basic", "newline"),
274 ("R", ";"),
275 ("sql-ansi", ";"),
276 ("Delphi/Object Pascal", "begin ... end"),
277 ],
278 },
279 StructuralConcept {
280 id: "branch",
281 definition: "Conditional selection among alternative operations.",
282 syntax: &[
283 ("Rust", "if"),
284 ("Python", "if"),
285 ("JavaScript", "if"),
286 ("C", "if"),
287 ("C++", "if"),
288 ("C#", "if"),
289 ("Java", "if"),
290 ("Visual Basic", "If"),
291 ("R", "if"),
292 ("sql-ansi", "CASE"),
293 ("Delphi/Object Pascal", "if"),
294 ],
295 },
296 StructuralConcept {
297 id: "loop",
298 definition: "Repeated execution or evaluation over a condition or iterable.",
299 syntax: &[
300 ("Rust", "loop"),
301 ("Python", "for"),
302 ("JavaScript", "for"),
303 ("C", "for"),
304 ("C++", "for"),
305 ("C#", "for"),
306 ("Java", "for"),
307 ("Visual Basic", "For"),
308 ("R", "for"),
309 ("sql-ansi", "WHILE"),
310 ("Delphi/Object Pascal", "for"),
311 ],
312 },
313 StructuralConcept {
314 id: "parameter",
315 definition: "Named input accepted by a function abstraction.",
316 syntax: &[
317 ("Rust", "parameter"),
318 ("Python", "parameter"),
319 ("JavaScript", "parameter"),
320 ("C", "parameter"),
321 ("C++", "parameter"),
322 ("C#", "parameter"),
323 ("Java", "parameter"),
324 ("Visual Basic", "parameter"),
325 ("R", "parameter"),
326 ("sql-ansi", "parameter"),
327 ("Delphi/Object Pascal", "parameter"),
328 ],
329 },
330 StructuralConcept {
331 id: "argument",
332 definition: "Concrete input supplied to a function application.",
333 syntax: &[
334 ("Rust", "argument"),
335 ("Python", "argument"),
336 ("JavaScript", "argument"),
337 ("C", "argument"),
338 ("C++", "argument"),
339 ("C#", "argument"),
340 ("Java", "argument"),
341 ("Visual Basic", "argument"),
342 ("R", "argument"),
343 ("sql-ansi", "argument"),
344 ("Delphi/Object Pascal", "argument"),
345 ],
346 },
347 StructuralConcept {
348 id: "return",
349 definition: "Transfer of a function result to its caller.",
350 syntax: &[
351 ("Rust", "return"),
352 ("Python", "return"),
353 ("JavaScript", "return"),
354 ("C", "return"),
355 ("C++", "return"),
356 ("C#", "return"),
357 ("Java", "return"),
358 ("Visual Basic", "Return"),
359 ("R", "return"),
360 ("sql-ansi", "RETURN"),
361 ("Delphi/Object Pascal", "Result"),
362 ],
363 },
364 StructuralConcept {
365 id: "assignment",
366 definition: "Update that stores a value into a named location.",
367 syntax: &[
368 ("Rust", "="),
369 ("Python", "="),
370 ("JavaScript", "="),
371 ("C", "="),
372 ("C++", "="),
373 ("C#", "="),
374 ("Java", "="),
375 ("Visual Basic", "="),
376 ("R", "<-"),
377 ("sql-ansi", "="),
378 ("Delphi/Object Pascal", ":="),
379 ],
380 },
381];
382
383impl LinkNetwork {
384 pub(crate) fn seed_statehood_worked_example(&mut self) -> StatehoodConceptIds {
385 let proposition = self.insert_typed_point(
386 "statehood",
387 LinkType::Concept,
388 Some("Statehood proposition connecting Hawaii (Q782) to U.S. state (Q35657)."),
389 );
390 let subject = self.insert_typed_point(
391 "Q782",
392 LinkType::Concept,
393 Some("Wikidata Q782; Hawaii; state of the United States."),
394 );
395 let object = self.insert_typed_point(
396 "Q35657",
397 LinkType::Concept,
398 Some("Wikidata Q35657; state of the United States."),
399 );
400
401 for (language, syntax) in STATEHOOD_PROPOSITION_SYNTAX {
402 self.insert_concept_syntax_mapping(proposition, "statehood", language, syntax, true);
403 }
404 for (language, syntax) in HAWAII_ENTITY_SYNTAX {
405 self.insert_concept_syntax_mapping(subject, "Q782", language, syntax, true);
406 }
407 for (language, syntax) in UNITED_STATES_STATE_SYNTAX {
408 self.insert_concept_syntax_mapping(object, "Q35657", language, syntax, true);
409 }
410
411 StatehoodConceptIds {
412 proposition,
413 subject,
414 object,
415 }
416 }
417
418 #[must_use]
424 pub fn seed_common_concept_ontology(&mut self) -> ConceptOntologySeedReport {
425 let lexicon = semantic_lexicon();
426 let mut alias_links = 0;
427 let mut syntax_mappings = 0;
428
429 for concept in &lexicon.concepts {
430 let definition = concept.definition();
431 let concept_link = self.intern_concept(concept.id(), Some(&definition));
432 alias_links += self.insert_external_aliases(concept_link, concept);
433
434 for entry in concept.syntax_entries() {
435 self.insert_concept_syntax_mapping(
436 concept_link,
437 concept.id(),
438 entry.language,
439 entry.syntax,
440 entry.canonical,
441 );
442 syntax_mappings += 1;
443 }
444 }
445
446 let mut structural_concepts = BTreeSet::new();
447 for concept in STRUCTURAL_CONCEPTS {
448 structural_concepts.insert(concept.id);
449 let concept_link = self.intern_concept(concept.id, Some(concept.definition));
450 alias_links += self.insert_former_concept_ids(concept_link, concept.id);
451
452 for (language, syntax) in concept.syntax {
453 self.insert_concept_syntax_mapping(
454 concept_link,
455 concept.id,
456 language,
457 syntax,
458 true,
459 );
460 syntax_mappings += 1;
461 }
462 }
463
464 let grammar_concepts = self.seed_grammar_concept_ontology();
465 syntax_mappings += GRAMMAR_CONCEPTS
466 .iter()
467 .map(|concept| concept.syntax.len())
468 .sum::<usize>();
469
470 let formatting = self.seed_document_formatting_concepts();
471 syntax_mappings += formatting.syntax_mappings();
472
473 let statehood = self.seed_statehood_worked_example();
474 for (concept_link, external_id) in
475 [(statehood.subject, "Q782"), (statehood.object, "Q35657")]
476 {
477 let (_alias, inserted) =
478 self.insert_concept_alias_link(concept_link, "Wikidata", external_id);
479 if inserted {
480 alias_links += 1;
481 }
482 }
483 syntax_mappings += STATEHOOD_PROPOSITION_SYNTAX.len()
484 + HAWAII_ENTITY_SYNTAX.len()
485 + UNITED_STATES_STATE_SYNTAX.len();
486
487 ConceptOntologySeedReport::new(
488 lexicon.concept_count,
489 structural_concepts.len(),
490 grammar_concepts,
491 formatting.concepts(),
492 alias_links,
493 syntax_mappings,
494 )
495 }
496
497 pub fn intern_concept(&mut self, exact_id: &str, definition: Option<&str>) -> LinkId {
503 self.insert_typed_point(exact_id, LinkType::Concept, definition)
504 }
505
506 pub fn insert_concept_expression(
511 &mut self,
512 concept: &str,
513 language: &str,
514 expression: &str,
515 ) -> LinkId {
516 let concept_link = self.find_term(concept).unwrap_or_else(|| {
517 self.intern_concept(
518 concept,
519 Some("A language-free concept shared by exact interlingual id."),
520 )
521 });
522 self.insert_concept_syntax_mapping(concept_link, concept, language, expression, true)
523 }
524
525 pub fn insert_concept_mapping(
527 &mut self,
528 concept: &str,
529 language: &str,
530 syntax: &str,
531 ) -> LinkId {
532 self.insert_concept_expression(concept, language, syntax)
533 }
534
535 pub fn insert_concept_alias(
537 &mut self,
538 concept_link: LinkId,
539 vocabulary: &str,
540 external_id: &str,
541 ) -> LinkId {
542 self.insert_concept_alias_link(concept_link, vocabulary, external_id)
543 .0
544 }
545
546 pub fn import_concept_ontology_lino(
552 &mut self,
553 text: &str,
554 ) -> Result<ConceptOntologyImportReport, LinoSerializationError> {
555 let source = Self::from_lino(text)?;
556 Ok(self.import_concept_ontology(&source))
557 }
558
559 pub fn import_concept_ontology(&mut self, source: &Self) -> ConceptOntologyImportReport {
567 let mut concept_links: BTreeMap<LinkId, (LinkId, String)> = BTreeMap::new();
568 let mut report = ConceptOntologyImportReport::default();
569
570 for link in source.links() {
571 if link.metadata().link_type() != Some(LinkType::Concept) {
572 continue;
573 }
574 let Some(term) = link.metadata().term() else {
575 continue;
576 };
577 let id = current_concept_id(term);
578 let concept_link = if let Some(record) = concept_record(id) {
579 report.assigned += 1;
580 self.insert_concept_record(record)
581 } else {
582 self.intern_concept(id, link.metadata().definition())
583 };
584 if id != term {
585 self.insert_concept_alias_link(concept_link, FORMER_CONCEPT_ID_VOCABULARY, term);
586 report.renamed += 1;
587 }
588 concept_links.insert(link.id(), (concept_link, id.to_string()));
589 report.concepts += 1;
590 }
591
592 for link in source.links() {
593 if link.metadata().link_type() != Some(LinkType::Semantic) {
594 continue;
595 }
596 let [source_concept, source_context] = link.references() else {
597 continue;
598 };
599 let Some((target_concept, concept_id)) = concept_links.get(source_concept) else {
600 continue;
601 };
602 let Some(context) = source.link(*source_context) else {
603 continue;
604 };
605 let Some(term) = link.metadata().term() else {
606 continue;
607 };
608
609 match context.metadata().link_type() {
610 Some(LinkType::Language) => {
611 if let Some(language) = link
612 .metadata()
613 .language()
614 .or_else(|| context.metadata().term())
615 {
616 self.insert_concept_syntax_mapping(
617 *target_concept,
618 concept_id,
619 language,
620 term,
621 false,
622 );
623 report.syntax_mappings += 1;
624 }
625 }
626 Some(LinkType::Type) => {
627 let vocabulary = link.metadata().language().or_else(|| {
628 context
629 .metadata()
630 .term()
631 .and_then(external_vocabulary_from_term)
632 });
633 if let Some(vocabulary) = vocabulary {
634 self.insert_concept_alias(*target_concept, vocabulary, term);
635 report.alias_links += 1;
636 }
637 }
638 _ => {}
639 }
640 }
641
642 report
643 }
644
645 pub fn insert_concept_record(&mut self, record: &ConceptRecord) -> LinkId {
651 let concept_link = self.intern_concept(&record.id, Some(&record.definition));
652 self.insert_concept_syntax_mapping(concept_link, &record.id, "en", &record.phrase, false);
653 for alias in &record.source_aliases {
654 self.insert_concept_alias_link(concept_link, &alias.source, &alias.name);
655 }
656 for former in &record.former_names {
657 self.insert_concept_alias_link(concept_link, FORMER_CONCEPT_ID_VOCABULARY, former);
658 }
659 concept_link
660 }
661
662 pub fn seed_concept_records(&mut self) -> ConceptRecordSeedReport {
664 let before = self.len();
665 for record in concept_records() {
666 self.insert_concept_record(record);
667 }
668 ConceptRecordSeedReport {
669 concepts: concept_records().len(),
670 links: self.len() - before,
671 }
672 }
673
674 fn insert_external_aliases(
675 &mut self,
676 concept_link: LinkId,
677 concept: &SemanticLexiconConcept,
678 ) -> usize {
679 let mut aliases = BTreeSet::new();
680 if let Some(vocabulary) = external_vocabulary_for_id(concept.id()) {
681 aliases.insert((vocabulary, concept.id()));
682 }
683 if let Some(entity_id) = concept.entity_id.as_deref()
684 && let Some(vocabulary) = external_vocabulary_for_id(entity_id)
685 {
686 aliases.insert((vocabulary, entity_id));
687 }
688
689 aliases
690 .into_iter()
691 .filter(|(vocabulary, external_id)| {
692 let (_alias, inserted) =
693 self.insert_concept_alias_link(concept_link, vocabulary, external_id);
694 inserted
695 })
696 .count()
697 }
698
699 pub(crate) fn insert_former_concept_ids(
701 &mut self,
702 concept_link: LinkId,
703 concept_id: &str,
704 ) -> usize {
705 FORMER_CONCEPT_IDS
706 .iter()
707 .filter(|(former, current)| {
708 *current == concept_id
709 && self
710 .insert_concept_alias_link(
711 concept_link,
712 FORMER_CONCEPT_ID_VOCABULARY,
713 former,
714 )
715 .1
716 })
717 .count()
718 }
719
720 fn insert_concept_alias_link(
721 &mut self,
722 concept_link: LinkId,
723 vocabulary: &str,
724 external_id: &str,
725 ) -> (LinkId, bool) {
726 let vocabulary_term = external_vocabulary_term(vocabulary);
727 let vocabulary_link = self.insert_typed_point(
728 &vocabulary_term,
729 LinkType::Type,
730 Some("External concept identifier vocabulary."),
731 );
732
733 if let Some(existing) =
734 self.find_concept_alias(concept_link, vocabulary_link, vocabulary, external_id)
735 {
736 return (existing, false);
737 }
738
739 (
740 self.insert_link(
741 [concept_link, vocabulary_link],
742 LinkMetadata::new()
743 .with_link_type(LinkType::Semantic)
744 .with_named(true)
745 .with_term(external_id)
746 .with_language(vocabulary),
747 ),
748 true,
749 )
750 }
751
752 pub(crate) fn insert_concept_syntax_mapping(
753 &mut self,
754 concept_link: LinkId,
755 concept: &str,
756 language: &str,
757 syntax: &str,
758 update_reconstruction: bool,
759 ) -> LinkId {
760 let language_link = self.insert_typed_point(language, LinkType::Language, None);
761 self.cache_concept_syntax(concept, language, syntax, update_reconstruction);
762
763 if let Some(existing) =
764 self.find_concept_syntax_mapping(concept_link, language_link, syntax, language)
765 {
766 return existing;
767 }
768
769 self.insert_link(
770 [concept_link, language_link],
771 LinkMetadata::new()
772 .with_link_type(LinkType::Semantic)
773 .with_named(true)
774 .with_term(syntax)
775 .with_language(language),
776 )
777 }
778
779 fn find_concept_syntax_mapping(
780 &self,
781 concept_link: LinkId,
782 language_link: LinkId,
783 syntax: &str,
784 language: &str,
785 ) -> Option<LinkId> {
786 self.links()
787 .find(|link| {
788 let references = link.references();
789 link.metadata().link_type() == Some(LinkType::Semantic)
790 && references.len() == 2
791 && references[0] == concept_link
792 && references[1] == language_link
793 && link.metadata().term() == Some(syntax)
794 && link.metadata().language() == Some(language)
795 })
796 .map(Link::id)
797 }
798
799 fn find_concept_alias(
800 &self,
801 concept_link: LinkId,
802 vocabulary_link: LinkId,
803 vocabulary: &str,
804 external_id: &str,
805 ) -> Option<LinkId> {
806 self.links()
807 .find(|link| {
808 let references = link.references();
809 link.metadata().link_type() == Some(LinkType::Semantic)
810 && references.len() == 2
811 && references[0] == concept_link
812 && references[1] == vocabulary_link
813 && link.metadata().term() == Some(external_id)
814 && link.metadata().language() == Some(vocabulary)
815 })
816 .map(Link::id)
817 }
818}
819
820fn external_vocabulary_for_id(value: &str) -> Option<&'static str> {
821 if is_wikidata_qid(value) {
822 Some("Wikidata")
823 } else if is_wordnet_cili_id(value) {
824 Some("WordNet CILI")
825 } else {
826 None
827 }
828}
829
830fn external_vocabulary_term(vocabulary: &str) -> String {
831 format!("{EXTERNAL_IDENTIFIER_VOCABULARY_PREFIX}{vocabulary}")
832}
833
834fn external_vocabulary_from_term(term: &str) -> Option<&str> {
835 term.strip_prefix(EXTERNAL_IDENTIFIER_VOCABULARY_PREFIX)
836 .or_else(|| term.strip_prefix(FORMER_EXTERNAL_IDENTIFIER_VOCABULARY_PREFIX))
837}