1use std::collections::{BTreeMap, BTreeSet};
11use std::sync::{Mutex, OnceLock};
12
13use crate::concept_records::concept_records_for_source_name;
14use crate::decorators::{
15 DecoratorError, DecoratorLevel, DecoratorSet, decorator_record, record_field,
16};
17use crate::language_catalog::{native_grammar, native_grammars};
18use crate::native_grammar_parser::{native_grammar_text, native_parser};
19use crate::{ConceptRecord, FeatureParseOptions, SyntaxTree, concept_records, parse_grammar_links};
20
21const NATIVE_SOURCE_PREFIX: &str = "native:";
22
23#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct NativeRuleConcept {
26 pub rule: String,
28 pub concept: Option<String>,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum NativeConceptProblemKind {
35 RuleWithoutConcept,
37 ConceptWithoutRecord,
39 RuleWithoutAlias,
41 AliasWithoutRule,
43 NamespaceMismatch,
45}
46
47impl NativeConceptProblemKind {
48 #[must_use]
50 pub const fn as_str(self) -> &'static str {
51 match self {
52 Self::RuleWithoutConcept => "rule-without-concept",
53 Self::ConceptWithoutRecord => "concept-without-record",
54 Self::RuleWithoutAlias => "rule-without-alias",
55 Self::AliasWithoutRule => "alias-without-rule",
56 Self::NamespaceMismatch => "namespace-mismatch",
57 }
58 }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct NativeConceptProblem {
64 pub kind: NativeConceptProblemKind,
66 pub grammar: String,
68 pub rule: String,
70 pub concept: Option<String>,
72}
73
74#[must_use]
76pub fn native_grammar_ids() -> Vec<&'static str> {
77 let mut ids: Vec<&'static str> = native_grammars()
78 .iter()
79 .map(|grammar| grammar.id.as_str())
80 .collect();
81 ids.sort_unstable();
82 ids
83}
84
85#[must_use]
88pub fn native_grammar_language(id: &str) -> Option<&'static str> {
89 let file = native_grammar(id)?.file.as_str();
90 let name = file.rsplit('/').next().unwrap_or(file);
91 Some(name.strip_suffix(".lino").unwrap_or(name))
92}
93
94#[must_use]
97pub fn native_grammar_source(id: &str) -> Option<String> {
98 native_grammar_language(id).map(|language| format!("{NATIVE_SOURCE_PREFIX}{language}"))
99}
100
101#[must_use]
104pub fn native_grammar_rule_concepts(id: &str) -> Vec<NativeRuleConcept> {
105 static RULES: OnceLock<Mutex<BTreeMap<String, Vec<NativeRuleConcept>>>> = OnceLock::new();
106 let Some(text) = native_grammar_text(id) else {
107 return Vec::new();
108 };
109 let rules = RULES.get_or_init(|| Mutex::new(BTreeMap::new()));
110 if let Some(found) = rules
111 .lock()
112 .expect("the rule summary cache is available")
113 .get(id)
114 {
115 return found.clone();
116 }
117 let found = parse_grammar_links(text)
118 .map(|grammar| {
119 grammar
120 .rules()
121 .iter()
122 .map(|rule| NativeRuleConcept {
123 rule: rule.name.clone(),
124 concept: rule.concept.clone(),
125 })
126 .collect::<Vec<_>>()
127 })
128 .unwrap_or_default();
129 rules
130 .lock()
131 .expect("the rule summary cache is available")
132 .insert(id.to_owned(), found.clone());
133 found
134}
135
136fn namespace_language<'a>(concept: &'a str, languages: &BTreeSet<&str>) -> Option<&'a str> {
139 let parts: Vec<&str> = concept.split('.').collect();
140 (parts.len() > 2 && languages.contains(parts[1])).then(|| parts[1])
141}
142
143#[must_use]
149pub fn check_native_grammar_concepts() -> Vec<NativeConceptProblem> {
150 check_native_grammar_concepts_in(
151 concept_records(),
152 &native_grammar_ids(),
153 &native_grammar_rule_concepts,
154 )
155}
156
157#[must_use]
160pub fn check_native_grammar_concepts_in(
161 records: &[ConceptRecord],
162 grammars: &[&str],
163 rule_concepts: &dyn Fn(&str) -> Vec<NativeRuleConcept>,
164) -> Vec<NativeConceptProblem> {
165 let by_id: BTreeMap<&str, &ConceptRecord> = records
166 .iter()
167 .map(|record| (record.id.as_str(), record))
168 .collect();
169 let languages: BTreeSet<&str> = grammars
170 .iter()
171 .filter_map(|id| native_grammar_language(id))
172 .collect();
173 let mut problems = Vec::new();
174 for &grammar in grammars {
175 let (Some(source), Some(language)) = (
176 native_grammar_source(grammar),
177 native_grammar_language(grammar),
178 ) else {
179 continue;
180 };
181 let problem = |kind, rule: &str, concept: Option<&str>| NativeConceptProblem {
182 kind,
183 grammar: grammar.to_owned(),
184 rule: rule.to_owned(),
185 concept: concept.map(str::to_owned),
186 };
187 let mut named = BTreeMap::new();
188 for NativeRuleConcept { rule, concept } in rule_concepts(grammar) {
189 let Some(concept) = concept else {
190 problems.push(problem(
191 NativeConceptProblemKind::RuleWithoutConcept,
192 &rule,
193 None,
194 ));
195 continue;
196 };
197 let Some(record) = by_id.get(concept.as_str()) else {
198 problems.push(problem(
199 NativeConceptProblemKind::ConceptWithoutRecord,
200 &rule,
201 Some(&concept),
202 ));
203 named.insert(rule, concept);
204 continue;
205 };
206 if !record
207 .source_aliases
208 .iter()
209 .any(|alias| alias.source == source && alias.name == rule)
210 {
211 problems.push(problem(
212 NativeConceptProblemKind::RuleWithoutAlias,
213 &rule,
214 Some(&concept),
215 ));
216 }
217 if namespace_language(&concept, &languages).is_some_and(|owner| owner != language) {
218 problems.push(problem(
219 NativeConceptProblemKind::NamespaceMismatch,
220 &rule,
221 Some(&concept),
222 ));
223 }
224 named.insert(rule, concept);
225 }
226 for record in records {
227 for alias in &record.source_aliases {
228 if alias.source == source && named.get(&alias.name) != Some(&record.id) {
229 problems.push(problem(
230 NativeConceptProblemKind::AliasWithoutRule,
231 &alias.name,
232 Some(&record.id),
233 ));
234 }
235 }
236 }
237 }
238 problems
239}
240
241#[derive(Debug, Clone, PartialEq, Eq)]
243pub struct SharedRule {
244 pub rule: String,
246 pub concept: String,
248 pub languages: Vec<String>,
250}
251
252#[derive(Debug, Clone, PartialEq, Eq)]
254pub struct SpecificRule {
255 pub rule: String,
257 pub concept: String,
259}
260
261#[derive(Debug, Clone, PartialEq, Eq)]
264pub struct GrammarConceptReuse {
265 pub grammar: String,
267 pub language: String,
269 pub rules: usize,
271 pub shared: Vec<SharedRule>,
273 pub specific: Vec<SpecificRule>,
275}
276
277#[derive(Debug, Clone, PartialEq, Eq)]
279pub struct ConceptReuse {
280 pub concept: String,
282 pub languages: Vec<String>,
284 pub shared: bool,
286}
287
288#[derive(Debug, Clone, PartialEq, Eq)]
290pub struct NativeConceptReuse {
291 pub grammars: Vec<GrammarConceptReuse>,
293 pub concepts: Vec<ConceptReuse>,
295}
296
297#[must_use]
304pub fn native_grammar_concept_reuse() -> NativeConceptReuse {
305 let grammars = native_grammar_ids();
306 let language_of: BTreeMap<String, &str> = grammars
307 .iter()
308 .filter_map(|id| Some((native_grammar_source(id)?, native_grammar_language(id)?)))
309 .collect();
310 let mut languages: BTreeMap<&str, Vec<String>> = BTreeMap::new();
311 for record in concept_records() {
312 let named: BTreeSet<&str> = record
313 .source_aliases
314 .iter()
315 .filter_map(|alias| language_of.get(&alias.source).copied())
316 .collect();
317 if !named.is_empty() {
318 languages.insert(&record.id, named.into_iter().map(str::to_owned).collect());
319 }
320 }
321 let report = grammars
322 .iter()
323 .map(|&grammar| {
324 let mut shared = Vec::new();
325 let mut specific = Vec::new();
326 for NativeRuleConcept { rule, concept } in native_grammar_rule_concepts(grammar) {
327 let concept = concept.unwrap_or_default();
328 match languages.get(concept.as_str()) {
329 Some(named) if named.len() > 1 => shared.push(SharedRule {
330 rule,
331 concept,
332 languages: named.clone(),
333 }),
334 _ => specific.push(SpecificRule { rule, concept }),
335 }
336 }
337 GrammarConceptReuse {
338 grammar: grammar.to_owned(),
339 language: native_grammar_language(grammar)
340 .unwrap_or_default()
341 .to_owned(),
342 rules: shared.len() + specific.len(),
343 shared,
344 specific,
345 }
346 })
347 .collect();
348 let concepts = languages
349 .into_iter()
350 .map(|(concept, named)| ConceptReuse {
351 concept: concept.to_owned(),
352 shared: named.len() > 1,
353 languages: named,
354 })
355 .collect();
356 NativeConceptReuse {
357 grammars: report,
358 concepts,
359 }
360}
361
362#[derive(Debug, Clone, Copy, PartialEq, Eq)]
364pub enum ConstructTranslationRelation {
365 Translated,
367 Untranslatable,
369 Ambiguous,
371 Unknown,
373}
374
375impl ConstructTranslationRelation {
376 #[must_use]
378 pub const fn as_str(self) -> &'static str {
379 match self {
380 Self::Translated => "translated",
381 Self::Untranslatable => "untranslatable",
382 Self::Ambiguous => "ambiguous",
383 Self::Unknown => "unknown",
384 }
385 }
386
387 #[must_use]
389 pub fn parse(name: &str) -> Option<Self> {
390 [
391 Self::Translated,
392 Self::Untranslatable,
393 Self::Ambiguous,
394 Self::Unknown,
395 ]
396 .into_iter()
397 .find(|relation| relation.as_str() == name)
398 }
399}
400
401#[derive(Debug, Clone, PartialEq, Eq)]
403pub struct ConstructTranslation {
404 pub relation: ConstructTranslationRelation,
406 pub concept: Option<String>,
408 pub rules: Vec<String>,
410}
411
412#[must_use]
418pub fn translate_native_construct(from: &str, rule: &str, to: &str) -> ConstructTranslation {
419 translate_native_construct_in(concept_records(), from, rule, to)
420}
421
422#[must_use]
424pub fn translate_native_construct_in(
425 records: &[ConceptRecord],
426 from: &str,
427 rule: &str,
428 to: &str,
429) -> ConstructTranslation {
430 let unknown = ConstructTranslation {
431 relation: ConstructTranslationRelation::Unknown,
432 concept: None,
433 rules: Vec::new(),
434 };
435 let (Some(source), Some(target)) = (native_grammar_source(from), native_grammar_source(to))
436 else {
437 return unknown;
438 };
439 let meanings: Vec<&ConceptRecord> = if std::ptr::eq(records, concept_records()) {
440 concept_records_for_source_name(&source, rule)
441 } else {
442 records
443 .iter()
444 .filter(|record| {
445 record
446 .source_aliases
447 .iter()
448 .any(|alias| alias.source == source && alias.name == rule)
449 })
450 .collect()
451 };
452 let record = match meanings.as_slice() {
453 [] => return unknown,
454 [record] => record,
455 _ => {
456 return ConstructTranslation {
457 relation: ConstructTranslationRelation::Ambiguous,
458 ..unknown
459 };
460 }
461 };
462 let rules: Vec<String> = record
463 .source_aliases
464 .iter()
465 .filter(|alias| alias.source == target)
466 .map(|alias| alias.name.clone())
467 .collect();
468 ConstructTranslation {
469 relation: relation_of(&rules),
470 concept: Some(record.id.clone()),
471 rules,
472 }
473}
474
475const fn relation_of(rules: &[String]) -> ConstructTranslationRelation {
476 match rules.len() {
477 1 => ConstructTranslationRelation::Translated,
478 0 => ConstructTranslationRelation::Untranslatable,
479 _ => ConstructTranslationRelation::Ambiguous,
480 }
481}
482
483pub fn translate_native_construct_decorated(
495 from: &str,
496 rule: &str,
497 to: &str,
498 decorators: &DecoratorSet,
499) -> Result<ConstructTranslation, DecoratorError> {
500 let found = translate_native_construct(from, rule, to);
501 if !decorators.has(DecoratorLevel::ConceptMapping) {
502 return Ok(found);
503 }
504 let joined = found.rules.join(" ");
505 let record = decorator_record([
506 ("from", from),
507 ("to", to),
508 ("rule", rule),
509 ("relation", found.relation.as_str()),
510 ("concept", found.concept.as_deref().unwrap_or_default()),
511 ("rules", &joined),
512 ]);
513 let Some(decorated) = decorators.decorate(DecoratorLevel::ConceptMapping, &record) else {
514 return Ok(ConstructTranslation {
515 relation: ConstructTranslationRelation::Unknown,
516 concept: None,
517 rules: Vec::new(),
518 });
519 };
520 let rules: Vec<String> = record_field(&decorated, "rules")
521 .split(' ')
522 .filter(|name| !name.is_empty())
523 .map(str::to_owned)
524 .collect();
525 let relation = record_field(&decorated, "relation");
526 let relation =
527 if relation != found.relation.as_str() || record_field(&decorated, "rules") == joined {
528 ConstructTranslationRelation::parse(relation).ok_or_else(|| {
529 DecoratorError::new(format!("a decorator set the unknown relation {relation:?}"))
530 })?
531 } else {
532 relation_of(&rules)
533 };
534 let concept = record_field(&decorated, "concept");
535 Ok(ConstructTranslation {
536 relation,
537 concept: (!concept.is_empty()).then(|| concept.to_owned()),
538 rules,
539 })
540}
541
542#[derive(Debug, Clone, PartialEq, Eq)]
545pub struct ConstructTree {
546 pub kind: String,
548 pub concept: String,
550 pub children: Vec<Self>,
552}
553
554#[must_use]
560pub fn native_construct_tree(id: &str, source: &str) -> Option<ConstructTree> {
561 let concepts: BTreeMap<String, String> = native_grammar_rule_concepts(id)
562 .into_iter()
563 .filter_map(|NativeRuleConcept { rule, concept }| Some((rule, concept?)))
564 .collect();
565 let outcome = native_parser(id)?
566 .parse_tree(source.as_bytes(), &FeatureParseOptions::default())
567 .ok()?;
568 let tree = outcome.tree?;
569 if !matches!(tree, SyntaxTree::Node { .. }) {
570 return None;
571 }
572 constructs(&tree, &concepts)?.into_iter().next()
573}
574
575fn constructs(
576 node: &SyntaxTree,
577 concepts: &BTreeMap<String, String>,
578) -> Option<Vec<ConstructTree>> {
579 let (kind, children) = match node {
580 SyntaxTree::Node { kind, children, .. } => {
581 let mut inner = Vec::new();
582 for child in children {
583 inner.extend(constructs(child, concepts)?);
584 }
585 (Some(kind), inner)
586 }
587 SyntaxTree::Token {
588 kind,
589 trivia: false,
590 ..
591 } => (kind.as_ref(), Vec::new()),
592 SyntaxTree::Token { .. } | SyntaxTree::Embed { .. } => (None, Vec::new()),
593 SyntaxTree::Error { .. } | SyntaxTree::Missing { .. } => return None,
594 };
595 match kind.and_then(|kind| Some((kind, concepts.get(kind)?))) {
596 Some((kind, concept)) => Some(vec![ConstructTree {
597 kind: kind.clone(),
598 concept: concept.clone(),
599 children,
600 }]),
601 None => Some(children),
602 }
603}
604
605#[derive(Debug, Clone, PartialEq, Eq)]
607pub struct ConstructTranslationProblem {
608 pub kind: String,
610 pub concept: Option<String>,
612 pub relation: ConstructTranslationRelation,
614}
615
616#[derive(Debug, Clone, PartialEq, Eq)]
618pub struct ConstructTreeTranslation {
619 pub tree: Option<ConstructTree>,
622 pub problems: Vec<ConstructTranslationProblem>,
624}
625
626#[must_use]
629pub fn translate_native_construct_tree(
630 tree: &ConstructTree,
631 from: &str,
632 to: &str,
633) -> ConstructTreeTranslation {
634 fn translate(
635 node: &ConstructTree,
636 from: &str,
637 to: &str,
638 problems: &mut Vec<ConstructTranslationProblem>,
639 ) -> Option<ConstructTree> {
640 let translation = translate_native_construct(from, &node.kind, to);
641 let children: Vec<Option<ConstructTree>> = node
642 .children
643 .iter()
644 .map(|child| translate(child, from, to, problems))
645 .collect();
646 if translation.relation != ConstructTranslationRelation::Translated {
647 problems.push(ConstructTranslationProblem {
648 kind: node.kind.clone(),
649 concept: translation.concept,
650 relation: translation.relation,
651 });
652 return None;
653 }
654 Some(ConstructTree {
655 kind: translation.rules[0].clone(),
656 concept: translation.concept.unwrap_or_default(),
657 children: children.into_iter().collect::<Option<Vec<_>>>()?,
658 })
659 }
660 let mut problems = Vec::new();
661 let translated = translate(tree, from, to, &mut problems);
662 ConstructTreeTranslation {
663 tree: if problems.is_empty() {
664 translated
665 } else {
666 None
667 },
668 problems,
669 }
670}