Skip to main content

meta_language/grammar/merge/
mod.rs

1//! Deterministic, meaning-aware merging of grammars from several sources, and
2//! binding-aware renaming of grammar rules.
3//!
4//! This mirrors `js/src/grammar-merge.js`: both runtimes normalize rule
5//! definitions the same way, prove equivalence by the same recursive structural
6//! bisimulation and print the same canonical definitions, so their decisions
7//! agree.
8
9mod 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
33/// How an accepted equivalence is justified.
34pub const GRAMMAR_MERGE_METHOD: &str = "recursive-structural-bisimulation";
35
36/// One grammar taking part in a merge.
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct GrammarMergeSource {
39    /// Source identifier, unique within one merge and free of `:`.
40    pub id: String,
41    /// Language the grammar describes.
42    pub language: String,
43    /// Language edition; different editions are never merged with each other.
44    pub edition: String,
45    /// Lower precedence wins name collisions.
46    pub precedence: u32,
47    /// The source grammar.
48    pub grammar: Grammar,
49}
50
51impl GrammarMergeSource {
52    /// Builds a source with an empty edition and precedence zero.
53    #[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    /// Sets the language edition.
65    #[must_use]
66    pub fn with_edition(mut self, edition: impl Into<String>) -> Self {
67        self.edition = edition.into();
68        self
69    }
70
71    /// Sets the precedence.
72    #[must_use]
73    pub const fn with_precedence(mut self, precedence: u32) -> Self {
74        self.precedence = precedence;
75        self
76    }
77}
78
79/// Optional inputs of [`merge_grammars`].
80#[derive(Clone, Debug, Default)]
81pub struct GrammarMergeOptions<'a> {
82    /// Sample inputs keyed by `sourceId:ruleName`; identical samples only
83    /// nominate candidates, they never decide a merge.
84    pub samples: BTreeMap<String, Vec<String>>,
85    /// Pairs of `sourceId:ruleName` aliases that must end up merged.
86    pub required_equivalences: Vec<(String, String)>,
87    /// An earlier result: unchanged groups are reused and established
88    /// canonical names are kept.
89    pub previous: Option<&'a GrammarMergeResult>,
90    /// `merge-decision` decorators, which see each decision as `{ kind,
91    /// name, members, basis, definition }` (members joined by spaces): they
92    /// may change the kind or the basis, and `drop` removes the decision.
93    /// They change the reported decisions only, never the merged grammar.
94    pub decorators: DecoratorSet,
95    /// Also unite corresponding rules of different sources that are
96    /// equivalent up to their lexical roles, or that share a name when no
97    /// correspondence matched them (see `reconcile.rs`). Each such class is a
98    /// [`GrammarMergeDecisionKind::Reconciled`] decision, kept by the
99    /// union of every source production and the concept of its first rule
100    /// that has one. Correspondence is not proof of concept equivalence.
101    pub reconcile: bool,
102    /// Cross-language aliases requiring a one-to-one global concept proof.
103    pub global_equivalences: Vec<[String; 2]>,
104    /// Optional semantic concept records for the global proof procedure.
105    pub concept_records: Option<serde_json::Value>,
106    /// Explicit supported operational Links archives, by origin or concept id.
107    pub formal_definitions: Option<serde_json::Value>,
108}
109
110/// What the merge decided about one class of rules.
111#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
112#[serde(rename_all = "kebab-case")]
113pub enum GrammarMergeDecisionKind {
114    /// Several rules were proven equivalent and merged.
115    Merged,
116    /// Corresponding rules of different sources were reconciled and merged.
117    Reconciled,
118    /// The rule has no equivalent in the group.
119    KeptUnique,
120    /// The rule was renamed because a higher-precedence rule holds its name.
121    RenamedForCollision,
122    /// Rules sharing a name have different meanings and stay distinct.
123    HomonymKeptDistinct,
124    /// A nominated match could not be proven and was not merged.
125    Uncertain,
126    /// Sources declare a different matching, macro or scanner of one name;
127    /// the declaration of the first source in precedence order is kept.
128    DeclarationConflict,
129}
130
131impl GrammarMergeDecisionKind {
132    /// Returns the stable textual form.
133    #[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    /// The kind whose textual form is `text`.
147    #[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/// One merge decision with its justification.
164#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
165pub struct GrammarMergeDecision {
166    /// Decision kind.
167    pub kind: GrammarMergeDecisionKind,
168    /// Canonical name (the raw source name for homonyms).
169    pub name: String,
170    /// Source aliases, or canonical names for homonyms.
171    pub members: Vec<String>,
172    /// Justification of the decision.
173    pub basis: String,
174    /// Canonical normalized definition of a merged or unique rule.
175    pub definition: Option<String>,
176    /// The concept record a reconciling merge gave the merged rule.
177    #[serde(skip_serializing_if = "Option::is_none")]
178    pub concept: Option<String>,
179}
180
181/// Why two rules were nominated as a possible match.
182#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
183#[serde(rename_all = "kebab-case")]
184pub enum GrammarMergeNominationBasis {
185    /// The names differ only in case, `-` or `_`.
186    NameSimilarity,
187    /// Both rules have the same caller-supplied samples.
188    IdenticalSamples,
189}
190
191impl GrammarMergeNominationBasis {
192    /// Returns the stable textual form.
193    #[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/// Whether a nomination was confirmed by the structural proof.
203#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
204#[serde(rename_all = "kebab-case")]
205pub enum GrammarMergeNominationOutcome {
206    /// The nominated rules were proven equivalent.
207    Proven,
208    /// The nominated rules were reconciled as corresponding rules.
209    Reconciled,
210    /// The nominated rules were not proven equivalent and stay separate.
211    Unproven,
212}
213
214/// A candidate match nominated by a heuristic.
215#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
216pub struct GrammarMergeNomination {
217    /// Heuristic that nominated the pair.
218    pub basis: GrammarMergeNominationBasis,
219    /// The two source aliases.
220    pub members: [String; 2],
221    /// Result of the structural proof.
222    pub outcome: GrammarMergeNominationOutcome,
223}
224
225/// Why the merge kept several options instead of choosing silently.
226#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
227#[serde(rename_all = "kebab-case")]
228pub enum GrammarMergeAlternativeReason {
229    /// Sources start from different rules.
230    StartRule,
231    /// Rules sharing a name have different meanings.
232    DistinctMeaning,
233    /// A nominated match was not proven.
234    UncertainMatch,
235    /// A language has several editions.
236    Edition,
237    /// Sources declare a different matching, macro or scanner of one name.
238    DeclarationConflict,
239}
240
241impl GrammarMergeAlternativeReason {
242    /// Returns the stable textual form.
243    #[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/// An explicit alternative kept by the merge.
256#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
257pub struct GrammarMergeAlternative {
258    /// Why the alternative exists.
259    pub reason: GrammarMergeAlternativeReason,
260    /// The chosen option, the shared name, the nomination basis or the language.
261    pub name: String,
262    /// The options kept.
263    pub options: Vec<String>,
264}
265
266/// Kind of a merge failure.
267#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
268#[serde(rename_all = "kebab-case")]
269pub enum GrammarMergeFailureKind {
270    /// A required equivalence was not established.
271    UnresolvedRequiredEquivalence,
272}
273
274/// Why a required equivalence was not established.
275#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
276#[serde(rename_all = "kebab-case")]
277pub enum GrammarMergeFailureReason {
278    /// An alias names no rule of the merged sources.
279    UnknownRule,
280    /// The rules belong to different languages or editions.
281    DifferentLanguageOrEdition,
282    /// The rules were not proven equivalent.
283    NotProven,
284}
285
286impl GrammarMergeFailureReason {
287    /// Returns the stable textual form.
288    #[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/// A required equivalence the merge could not establish.
299#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
300pub struct GrammarMergeFailure {
301    /// Failure kind.
302    pub kind: GrammarMergeFailureKind,
303    /// The two aliases, sorted.
304    pub members: [String; 2],
305    /// Why the equivalence is unresolved.
306    pub reason: GrammarMergeFailureReason,
307}
308
309/// The merged grammar of one language edition.
310#[derive(Clone, Debug, PartialEq, Eq)]
311pub struct MergedGrammarGroup {
312    /// `language@edition`.
313    pub key: String,
314    /// Language.
315    pub language: String,
316    /// Edition.
317    pub edition: String,
318    /// SHA-256 of the group's normalized inputs.
319    pub fingerprint: String,
320    /// Source ids in precedence order.
321    pub sources: Vec<String>,
322    /// The merged grammar.
323    pub grammar: Grammar,
324    /// Canonical rule name of every `sourceId:ruleName` alias.
325    pub identities: BTreeMap<String, String>,
326    /// Every original production and its bound canonical references.
327    pub source_productions: Vec<GrammarMergeProduction>,
328    /// Decisions with their justification.
329    pub decisions: Vec<GrammarMergeDecision>,
330    /// Candidate matches nominated by heuristics.
331    pub nominations: Vec<GrammarMergeNomination>,
332    /// Alternatives kept explicit.
333    pub alternatives: Vec<GrammarMergeAlternative>,
334}
335
336/// One preserved source production in a merged grammar.
337#[derive(Clone, Debug, PartialEq, Eq)]
338pub struct GrammarMergeProduction {
339    /// Qualified source rule identity.
340    pub alias: String,
341    /// Canonical rule receiving this production.
342    pub canonical: String,
343    /// Original grammar notation.
344    pub source_format: String,
345    /// Exact original rule, including actions and aliases.
346    pub rule: GrammarRule,
347    /// Original production with rule references bound to canonical names.
348    pub renamed_rule: GrammarRule,
349}
350
351/// The result of [`merge_grammars`].
352#[derive(Clone, Debug, PartialEq, Eq)]
353pub struct GrammarMergeResult {
354    /// One merged grammar per language edition, sorted by language and edition.
355    pub groups: Vec<MergedGrammarGroup>,
356    /// Languages with several editions.
357    pub alternatives: Vec<GrammarMergeAlternative>,
358    /// Unresolved required equivalences.
359    pub failures: Vec<GrammarMergeFailure>,
360    /// Keys of groups reused from the previous result.
361    pub reused: Vec<String>,
362    /// Keys of groups merged again.
363    pub recomputed: Vec<String>,
364    /// One concept space containing all input languages and their proof records.
365    pub global_concept_space: serde_json::Value,
366}
367
368impl GrammarMergeResult {
369    /// `"complete"` when every required equivalence holds, else `"incomplete"`.
370    #[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    /// Returns the group with `key`, when present.
384    #[must_use]
385    pub fn group(&self, key: &str) -> Option<&MergedGrammarGroup> {
386        self.groups.iter().find(|group| group.key == key)
387    }
388}
389
390/// Malformed merge input, or an incomplete merge in [`assert_merge_complete`].
391#[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    /// The unresolved required equivalences, if any.
408    #[must_use]
409    pub fn failures(&self) -> &[GrammarMergeFailure] {
410        &self.failures
411    }
412
413    /// The keys of the groups [`assert_merge_shares`] rejected, if any.
414    #[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/// Why a rename was refused.
429#[derive(Clone, Copy, Debug, PartialEq, Eq)]
430pub enum GrammarRenameErrorKind {
431    /// The new name is empty or contains whitespace.
432    InvalidName,
433    /// The grammar has no rule with the old name.
434    UnknownRule,
435    /// The new name would capture an existing binding.
436    Collision,
437}
438
439impl GrammarRenameErrorKind {
440    /// Returns the stable textual form.
441    #[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/// A refused rename.
452#[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    /// Why the rename was refused.
467    #[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/// Maps a canonical rule name back to its original source name.
482#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
483pub struct RuleAlias {
484    /// Current name in the grammar.
485    pub canonical: String,
486    /// Name in the source grammar.
487    pub original: String,
488}
489
490/// A renamed grammar and its source aliases.
491#[derive(Clone, Debug, PartialEq, Eq)]
492pub struct RenamedGrammar {
493    /// The grammar after the rename.
494    pub grammar: Grammar,
495    /// Aliases from canonical names to original source names.
496    pub aliases: Vec<RuleAlias>,
497}
498
499/// Merges grammars of several sources without user interaction.
500///
501/// Sources of different languages or editions are never merged with each
502/// other. Within one language edition, rules are merged only when their
503/// normalized definitions are equivalent under a recursive structural
504/// bisimulation; similar names and identical samples only nominate candidates.
505pub 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
651/// Fails when a merge left a required equivalence unresolved.
652pub 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/// The decisions of a merge group that share a rule between its sources: the
687/// merged and reconciled classes with members of more than one source.
688#[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
708/// Fails when a group of two or more sources shares no rule between them:
709/// such a merge only concatenates its sources side by side.
710pub 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
740/// The canonical text of a rule definition after meaning-aware normalization.
741pub 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}