1mod decisions;
10mod declarations;
11mod group;
12mod names;
13mod normalize;
14mod reconcile;
15mod rename;
16
17use group::{
18 Prepared, edition_alternatives, group_fingerprint, group_key, merge_group, name_label,
19 normalize_samples, prepare_sources, required_failures, source_of,
20};
21use normalize::normalize;
22pub use rename::{rename_grammar_rule, restore_source_names};
23
24use std::collections::{BTreeMap, BTreeSet};
25use std::error::Error;
26use std::fmt;
27
28use serde::Serialize;
29
30use super::{Grammar, GrammarRule};
31use crate::decorators::{DecoratorLevel, DecoratorSet, decorator_record, record_field};
32
33pub const GRAMMAR_MERGE_METHOD: &str = "recursive-structural-bisimulation";
35
36#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct GrammarMergeSource {
39 pub id: String,
41 pub language: String,
43 pub edition: String,
45 pub precedence: u32,
47 pub grammar: Grammar,
49}
50
51impl GrammarMergeSource {
52 #[must_use]
54 pub fn new(id: impl Into<String>, language: impl Into<String>, grammar: Grammar) -> Self {
55 Self {
56 id: id.into(),
57 language: language.into(),
58 edition: String::new(),
59 precedence: 0,
60 grammar,
61 }
62 }
63
64 #[must_use]
66 pub fn with_edition(mut self, edition: impl Into<String>) -> Self {
67 self.edition = edition.into();
68 self
69 }
70
71 #[must_use]
73 pub const fn with_precedence(mut self, precedence: u32) -> Self {
74 self.precedence = precedence;
75 self
76 }
77}
78
79#[derive(Clone, Debug, Default)]
81pub struct GrammarMergeOptions<'a> {
82 pub samples: BTreeMap<String, Vec<String>>,
85 pub required_equivalences: Vec<(String, String)>,
87 pub previous: Option<&'a GrammarMergeResult>,
90 pub decorators: DecoratorSet,
95 pub reconcile: bool,
102 pub global_equivalences: Vec<[String; 2]>,
104 pub concept_records: Option<serde_json::Value>,
106 pub formal_definitions: Option<serde_json::Value>,
108}
109
110#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
112#[serde(rename_all = "kebab-case")]
113pub enum GrammarMergeDecisionKind {
114 Merged,
116 Reconciled,
118 KeptUnique,
120 RenamedForCollision,
122 HomonymKeptDistinct,
124 Uncertain,
126 DeclarationConflict,
129}
130
131impl GrammarMergeDecisionKind {
132 #[must_use]
134 pub const fn as_str(self) -> &'static str {
135 match self {
136 Self::Merged => "merged",
137 Self::Reconciled => "reconciled",
138 Self::KeptUnique => "kept-unique",
139 Self::RenamedForCollision => "renamed-for-collision",
140 Self::HomonymKeptDistinct => "homonym-kept-distinct",
141 Self::Uncertain => "uncertain",
142 Self::DeclarationConflict => "declaration-conflict",
143 }
144 }
145
146 #[must_use]
148 pub fn parse(text: &str) -> Option<Self> {
149 [
150 Self::Merged,
151 Self::Reconciled,
152 Self::KeptUnique,
153 Self::RenamedForCollision,
154 Self::HomonymKeptDistinct,
155 Self::Uncertain,
156 Self::DeclarationConflict,
157 ]
158 .into_iter()
159 .find(|kind| kind.as_str() == text)
160 }
161}
162
163#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
165pub struct GrammarMergeDecision {
166 pub kind: GrammarMergeDecisionKind,
168 pub name: String,
170 pub members: Vec<String>,
172 pub basis: String,
174 pub definition: Option<String>,
176 #[serde(skip_serializing_if = "Option::is_none")]
178 pub concept: Option<String>,
179}
180
181#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
183#[serde(rename_all = "kebab-case")]
184pub enum GrammarMergeNominationBasis {
185 NameSimilarity,
187 IdenticalSamples,
189}
190
191impl GrammarMergeNominationBasis {
192 #[must_use]
194 pub const fn as_str(self) -> &'static str {
195 match self {
196 Self::NameSimilarity => "name-similarity",
197 Self::IdenticalSamples => "identical-samples",
198 }
199 }
200}
201
202#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
204#[serde(rename_all = "kebab-case")]
205pub enum GrammarMergeNominationOutcome {
206 Proven,
208 Reconciled,
210 Unproven,
212}
213
214#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
216pub struct GrammarMergeNomination {
217 pub basis: GrammarMergeNominationBasis,
219 pub members: [String; 2],
221 pub outcome: GrammarMergeNominationOutcome,
223}
224
225#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
227#[serde(rename_all = "kebab-case")]
228pub enum GrammarMergeAlternativeReason {
229 StartRule,
231 DistinctMeaning,
233 UncertainMatch,
235 Edition,
237 DeclarationConflict,
239}
240
241impl GrammarMergeAlternativeReason {
242 #[must_use]
244 pub const fn as_str(self) -> &'static str {
245 match self {
246 Self::StartRule => "start-rule",
247 Self::DistinctMeaning => "distinct-meaning",
248 Self::UncertainMatch => "uncertain-match",
249 Self::Edition => "edition",
250 Self::DeclarationConflict => "declaration-conflict",
251 }
252 }
253}
254
255#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
257pub struct GrammarMergeAlternative {
258 pub reason: GrammarMergeAlternativeReason,
260 pub name: String,
262 pub options: Vec<String>,
264}
265
266#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
268#[serde(rename_all = "kebab-case")]
269pub enum GrammarMergeFailureKind {
270 UnresolvedRequiredEquivalence,
272}
273
274#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
276#[serde(rename_all = "kebab-case")]
277pub enum GrammarMergeFailureReason {
278 UnknownRule,
280 DifferentLanguageOrEdition,
282 NotProven,
284}
285
286impl GrammarMergeFailureReason {
287 #[must_use]
289 pub const fn as_str(self) -> &'static str {
290 match self {
291 Self::UnknownRule => "unknown-rule",
292 Self::DifferentLanguageOrEdition => "different-language-or-edition",
293 Self::NotProven => "not-proven",
294 }
295 }
296}
297
298#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
300pub struct GrammarMergeFailure {
301 pub kind: GrammarMergeFailureKind,
303 pub members: [String; 2],
305 pub reason: GrammarMergeFailureReason,
307}
308
309#[derive(Clone, Debug, PartialEq, Eq)]
311pub struct MergedGrammarGroup {
312 pub key: String,
314 pub language: String,
316 pub edition: String,
318 pub fingerprint: String,
320 pub sources: Vec<String>,
322 pub grammar: Grammar,
324 pub identities: BTreeMap<String, String>,
326 pub source_productions: Vec<GrammarMergeProduction>,
328 pub decisions: Vec<GrammarMergeDecision>,
330 pub nominations: Vec<GrammarMergeNomination>,
332 pub alternatives: Vec<GrammarMergeAlternative>,
334}
335
336#[derive(Clone, Debug, PartialEq, Eq)]
338pub struct GrammarMergeProduction {
339 pub alias: String,
341 pub canonical: String,
343 pub source_format: String,
345 pub rule: GrammarRule,
347 pub renamed_rule: GrammarRule,
349}
350
351#[derive(Clone, Debug, PartialEq, Eq)]
353pub struct GrammarMergeResult {
354 pub groups: Vec<MergedGrammarGroup>,
356 pub alternatives: Vec<GrammarMergeAlternative>,
358 pub failures: Vec<GrammarMergeFailure>,
360 pub reused: Vec<String>,
362 pub recomputed: Vec<String>,
364 pub global_concept_space: serde_json::Value,
366}
367
368impl GrammarMergeResult {
369 #[must_use]
371 pub fn status(&self) -> &'static str {
372 if self.failures.is_empty()
373 && self.global_concept_space["failures"]
374 .as_array()
375 .is_none_or(Vec::is_empty)
376 {
377 "complete"
378 } else {
379 "incomplete"
380 }
381 }
382
383 #[must_use]
385 pub fn group(&self, key: &str) -> Option<&MergedGrammarGroup> {
386 self.groups.iter().find(|group| group.key == key)
387 }
388}
389
390#[derive(Clone, Debug, PartialEq, Eq)]
392pub struct GrammarMergeError {
393 message: String,
394 failures: Vec<GrammarMergeFailure>,
395 concatenated: Vec<String>,
396}
397
398impl GrammarMergeError {
399 fn new(message: impl Into<String>) -> Self {
400 Self {
401 message: message.into(),
402 failures: Vec::new(),
403 concatenated: Vec::new(),
404 }
405 }
406
407 #[must_use]
409 pub fn failures(&self) -> &[GrammarMergeFailure] {
410 &self.failures
411 }
412
413 #[must_use]
415 pub fn concatenated(&self) -> &[String] {
416 &self.concatenated
417 }
418}
419
420impl fmt::Display for GrammarMergeError {
421 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
422 formatter.write_str(&self.message)
423 }
424}
425
426impl Error for GrammarMergeError {}
427
428#[derive(Clone, Copy, Debug, PartialEq, Eq)]
430pub enum GrammarRenameErrorKind {
431 InvalidName,
433 UnknownRule,
435 Collision,
437}
438
439impl GrammarRenameErrorKind {
440 #[must_use]
442 pub const fn as_str(self) -> &'static str {
443 match self {
444 Self::InvalidName => "invalid-name",
445 Self::UnknownRule => "unknown-rule",
446 Self::Collision => "collision",
447 }
448 }
449}
450
451#[derive(Clone, Debug, PartialEq, Eq)]
453pub struct GrammarRenameError {
454 kind: GrammarRenameErrorKind,
455 message: String,
456}
457
458impl GrammarRenameError {
459 fn new(kind: GrammarRenameErrorKind, message: impl Into<String>) -> Self {
460 Self {
461 kind,
462 message: message.into(),
463 }
464 }
465
466 #[must_use]
468 pub const fn kind(&self) -> GrammarRenameErrorKind {
469 self.kind
470 }
471}
472
473impl fmt::Display for GrammarRenameError {
474 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
475 formatter.write_str(&self.message)
476 }
477}
478
479impl Error for GrammarRenameError {}
480
481#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
483pub struct RuleAlias {
484 pub canonical: String,
486 pub original: String,
488}
489
490#[derive(Clone, Debug, PartialEq, Eq)]
492pub struct RenamedGrammar {
493 pub grammar: Grammar,
495 pub aliases: Vec<RuleAlias>,
497}
498
499pub fn merge_grammars(
506 sources: &[GrammarMergeSource],
507 options: &GrammarMergeOptions<'_>,
508) -> Result<GrammarMergeResult, GrammarMergeError> {
509 let prepared = prepare_sources(sources)?;
510 let samples = normalize_samples(&options.samples);
511 let required: BTreeSet<(String, String)> = options
512 .required_equivalences
513 .iter()
514 .map(|(first, second)| {
515 if first <= second {
516 (first.clone(), second.clone())
517 } else {
518 (second.clone(), first.clone())
519 }
520 })
521 .collect();
522 let previous_groups: BTreeMap<&str, &MergedGrammarGroup> = options
523 .previous
524 .map(|previous| {
525 previous
526 .groups
527 .iter()
528 .map(|group| (group.key.as_str(), group))
529 .collect()
530 })
531 .unwrap_or_default();
532
533 let mut grouped: BTreeMap<(&str, &str), Vec<&Prepared<'_>>> = BTreeMap::new();
534 for source in &prepared {
535 grouped
536 .entry((source.language, source.edition))
537 .or_default()
538 .push(source);
539 }
540
541 let mut groups = Vec::new();
542 let mut reused = Vec::new();
543 let mut recomputed = Vec::new();
544 for ((language, edition), entry) in grouped {
545 let key = group_key(language, edition);
546 let ids: BTreeSet<&str> = entry.iter().map(|source| source.id).collect();
547 let group_required: Vec<&(String, String)> = required
548 .iter()
549 .filter(|(first, second)| {
550 ids.contains(source_of(first)) || ids.contains(source_of(second))
551 })
552 .collect();
553 let fingerprint = group_fingerprint(
554 language,
555 edition,
556 &entry,
557 &group_required,
558 &samples,
559 &options.decorators,
560 options.reconcile,
561 )?;
562 let previous = previous_groups.get(key.as_str()).copied();
563 if let Some(previous) = previous.filter(|previous| previous.fingerprint == fingerprint) {
564 groups.push(previous.clone());
565 reused.push(key);
566 continue;
567 }
568 let empty = BTreeMap::new();
569 let previous_identities = previous.map_or(&empty, |previous| &previous.identities);
570 let mut group = merge_group(
571 language,
572 edition,
573 &entry,
574 fingerprint,
575 &samples,
576 previous_identities,
577 options.reconcile,
578 )?;
579 group.decisions = decorate_decisions(group.decisions, &options.decorators)?;
580 groups.push(group);
581 recomputed.push(key);
582 }
583
584 let alternatives = edition_alternatives(&groups);
585 let failures = required_failures(&required, &groups);
586 let global_sources: Vec<crate::global_concept_space::GlobalConceptSource> = sources
587 .iter()
588 .map(|source| crate::global_concept_space::GlobalConceptSource {
589 id: source.id.clone(),
590 language: source.language.clone(),
591 edition: source.edition.clone(),
592 grammar: source.grammar.clone(),
593 })
594 .collect();
595 let global_concept_space = crate::global_concept_space::create_global_concept_space(
596 &global_sources,
597 &crate::global_concept_space::GlobalConceptOptions {
598 previous: options
599 .previous
600 .map(|result| result.global_concept_space.clone()),
601 equivalences: options.global_equivalences.clone(),
602 records: options.concept_records.clone(),
603 formal_definitions: options.formal_definitions.clone(),
604 },
605 )
606 .map_err(GrammarMergeError::new)?;
607 Ok(GrammarMergeResult {
608 groups,
609 alternatives,
610 failures,
611 reused,
612 recomputed,
613 global_concept_space,
614 })
615}
616
617fn decorate_decisions(
618 decisions: Vec<GrammarMergeDecision>,
619 decorators: &DecoratorSet,
620) -> Result<Vec<GrammarMergeDecision>, GrammarMergeError> {
621 if !decorators.has(DecoratorLevel::MergeDecision) {
622 return Ok(decisions);
623 }
624 let mut kept = Vec::with_capacity(decisions.len());
625 for mut decision in decisions {
626 let record = decorator_record([
627 ("kind", decision.kind.as_str()),
628 ("name", &decision.name),
629 ("members", &decision.members.join(" ")),
630 ("basis", &decision.basis),
631 (
632 "definition",
633 decision.definition.as_deref().unwrap_or_default(),
634 ),
635 ]);
636 let Some(decorated) = decorators.decorate(DecoratorLevel::MergeDecision, &record) else {
637 continue;
638 };
639 let kind = record_field(&decorated, "kind");
640 decision.kind = GrammarMergeDecisionKind::parse(kind).ok_or_else(|| {
641 GrammarMergeError::new(format!(
642 "a decorator set the unknown decision kind {kind:?}"
643 ))
644 })?;
645 record_field(&decorated, "basis").clone_into(&mut decision.basis);
646 kept.push(decision);
647 }
648 Ok(kept)
649}
650
651pub fn assert_merge_complete(
653 result: &GrammarMergeResult,
654) -> Result<&GrammarMergeResult, GrammarMergeError> {
655 if result.status() == "complete" {
656 return Ok(result);
657 }
658 let mut detail = result
659 .failures
660 .iter()
661 .map(|failure| {
662 format!(
663 "{} = {} ({})",
664 failure.members[0],
665 failure.members[1],
666 failure.reason.as_str()
667 )
668 })
669 .collect::<Vec<_>>()
670 .join("; ");
671 if let Some(failures) = result.global_concept_space["failures"].as_array() {
672 for failure in failures {
673 if !detail.is_empty() {
674 detail.push_str("; ");
675 }
676 detail.push_str(&failure.to_string());
677 }
678 }
679 Err(GrammarMergeError {
680 message: format!("unresolved required equivalence: {detail}"),
681 failures: result.failures.clone(),
682 concatenated: Vec::new(),
683 })
684}
685
686#[must_use]
689pub fn shared_rule_decisions(group: &MergedGrammarGroup) -> Vec<&GrammarMergeDecision> {
690 group
691 .decisions
692 .iter()
693 .filter(|decision| {
694 matches!(
695 decision.kind,
696 GrammarMergeDecisionKind::Merged | GrammarMergeDecisionKind::Reconciled
697 ) && decision
698 .members
699 .iter()
700 .map(|member| source_of(member))
701 .collect::<BTreeSet<_>>()
702 .len()
703 > 1
704 })
705 .collect()
706}
707
708pub fn assert_merge_shares(
711 result: &GrammarMergeResult,
712) -> Result<&GrammarMergeResult, GrammarMergeError> {
713 let concatenated: Vec<&MergedGrammarGroup> = result
714 .groups
715 .iter()
716 .filter(|group| group.sources.len() > 1 && shared_rule_decisions(group).is_empty())
717 .collect();
718 if concatenated.is_empty() {
719 return Ok(result);
720 }
721 let detail = concatenated
722 .iter()
723 .map(|group| {
724 format!(
725 "{} ({}: {} rules)",
726 group.key,
727 group.sources.join(", "),
728 group.grammar.rules().len()
729 )
730 })
731 .collect::<Vec<_>>()
732 .join("; ");
733 Err(GrammarMergeError {
734 message: format!("the merge only concatenates its sources, sharing no rule: {detail}"),
735 failures: Vec::new(),
736 concatenated: concatenated.iter().map(|group| group.key.clone()).collect(),
737 })
738}
739
740pub fn normalized_rule_definition(rule: &GrammarRule) -> Result<String, GrammarMergeError> {
742 Ok(format!(
743 "{}:{}",
744 rule.kind.as_str(),
745 normalize(&rule.expr, &name_label)?.text
746 ))
747}