Skip to main content

sound_law/
lib.rs

1//! A small, dependency-free engine for writing and applying sound laws.
2//!
3//! [`sound_laws!`] declares both the segment classes and an ordered rule list.
4//! The same notation handles simple letter maps, contextual rewrites, deletion,
5//! insertion, assimilation, capture, and metathesis:
6//!
7//! ```
8//! use sound_law::{RuleSet, sound_laws};
9//!
10//! const LAWS: RuleSet<'static> = sound_laws! {
11//!     classes {
12//!         V = ["a", "e", "i", "o", "u"];
13//!         C = ["p", "t", "k", "s"];
14//!         K = ["k"];
15//!     }
16//!     maps {
17//!         PALATAL = ["k" => "tʲ"];
18//!     }
19//!     rules {
20//!         // A plain letter map and a contextual rewrite use the same syntax.
21//!         palatalize_k: "{c:K}" => "{c|PALATAL}" / "" _ "{V}";
22//!         // Capture a consonant and vowel, then emit them in reverse order.
23//!         metathesis: "{c:C}{v:V}" => "{v}{c}";
24//!     }
25//! };
26//!
27//! let program = LAWS.compile()?;
28//! assert_eq!(program.apply("pa"), "ap");
29//! # Ok::<(), sound_law::CompileError>(())
30//! ```
31//!
32//! # Pattern notation
33//!
34//! Patterns are strings, keeping the macro grammar compact and allowing rules
35//! to be assembled as ordinary const data.
36//!
37//! - literal text matches itself;
38//! - `{V}` matches one member of class `V`;
39//! - `{v:V}` captures one member of `V` as `v`;
40//! - `{[a|e|ai]}` matches one inline literal alternative, longest first;
41//! - `{v:[a|e|ai]}` captures an inline alternative;
42//! - `{C|V}`, `{C&SONORANT}`, and `{C-[p|t]}` form finite class unions,
43//!   intersections, and differences;
44//! - `{x:.}` captures any one Unicode scalar value;
45//! - `{cluster:C+}`, `{maybe:C?}`, and `{run:C*}` use greedy quantifiers with
46//!   backtracking and capture the complete matched span;
47//! - `{x:!V}` matches and captures one scalar value that does not begin a member
48//!   of `V`;
49//! - `{=v}` matches the exact text captured earlier as `v`;
50//! - `^` and `$` anchor a pattern to the start and end of the complete form;
51//! - `#` matches a zero-width edge of a whitespace-delimited word.
52//!
53//! Replacements contain literal text and capture references such as `{v}`.
54//! `{v|MAP}` emits a capture through a declared correspondence map. Captures
55//! may be omitted, duplicated, transformed, or emitted in any order. A
56//! backslash escapes a metacharacter in either a pattern or replacement. An
57//! empty target inserts at every boundary satisfying its context:
58//! `"" => "ə" / "{C}" _ "{C}"`.
59//!
60//! Rules apply globally and left-to-right by default, to the result of the
61//! preceding rule. `[rtl]` changes overlap selection and `[once]` selects only
62//! the first directional match. Matches made by one rule are simultaneous: its
63//! own output is not reconsidered until another pass is explicitly requested
64//! with [`Program::apply_until_stable`].
65
66#![forbid(unsafe_code)]
67
68mod compile;
69mod engine;
70
71use std::fmt;
72
73pub use engine::{
74    IterationError, MatchLimitError, Program, ProgramCompositionError, RuleRangeError, TraceStep,
75};
76
77/// The direction in which a rule selects non-overlapping matches.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
79pub enum Direction {
80    /// Select the leftmost remaining match first.
81    #[default]
82    LeftToRight,
83    /// Select the rightmost remaining match first.
84    RightToLeft,
85}
86
87/// How many matches one rule applies to in a word.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
89pub enum Application {
90    /// Apply to every non-overlapping match selected in the rule's direction.
91    #[default]
92    All,
93    /// Apply only to the first match selected in the rule's direction.
94    Once,
95}
96
97/// A named set of possible segments.
98///
99/// Members may contain more than one Unicode scalar value. When multiple
100/// members match at one position, the engine tries the longest first.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct Class<'a> {
103    name: &'a str,
104    members: &'a [&'a str],
105}
106
107impl<'a> Class<'a> {
108    /// Construct a class declaration.
109    pub const fn new(name: &'a str, members: &'a [&'a str]) -> Self {
110        Self { name, members }
111    }
112
113    /// The name used to reference this class from patterns.
114    pub const fn name(&self) -> &'a str {
115        self.name
116    }
117
118    /// The class's possible segments.
119    pub const fn members(&self) -> &'a [&'a str] {
120        self.members
121    }
122}
123
124/// A named, source-keyed correspondence used by mapped capture replacements.
125///
126/// A pattern captures a source member normally, then `{capture|MAP}` emits the
127/// corresponding output. Compilation rejects maps that do not cover every
128/// possible value of that capture.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub struct Map<'a> {
131    name: &'a str,
132    entries: &'a [(&'a str, &'a str)],
133}
134
135impl<'a> Map<'a> {
136    /// Construct a correspondence map.
137    pub const fn new(name: &'a str, entries: &'a [(&'a str, &'a str)]) -> Self {
138        Self { name, entries }
139    }
140
141    /// The name used after `|` in replacement capture references.
142    pub const fn name(&self) -> &'a str {
143        self.name
144    }
145
146    /// The source-to-output correspondence entries.
147    pub const fn entries(&self) -> &'a [(&'a str, &'a str)] {
148        self.entries
149    }
150}
151
152/// One declarative sound law.
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub struct Rule<'a> {
155    name: &'a str,
156    target: &'a str,
157    replacement: &'a str,
158    left: &'a str,
159    right: &'a str,
160    excluded_left: Option<&'a str>,
161    excluded_right: Option<&'a str>,
162    direction: Direction,
163    application: Application,
164}
165
166impl<'a> Rule<'a> {
167    /// Construct an unconditional `target → replacement` rule.
168    pub const fn new(name: &'a str, target: &'a str, replacement: &'a str) -> Self {
169        Self {
170            name,
171            target,
172            replacement,
173            left: "",
174            right: "",
175            excluded_left: None,
176            excluded_right: None,
177            direction: Direction::LeftToRight,
178            application: Application::All,
179        }
180    }
181
182    /// Restrict this rule to `left _ right`.
183    pub const fn in_context(mut self, left: &'a str, right: &'a str) -> Self {
184        self.left = left;
185        self.right = right;
186        self
187    }
188
189    /// Prevent this rule in the `left _ right` environment.
190    ///
191    /// The exclusion is checked after the positive environment. Captures from
192    /// the positive environment and target may be used as backreferences, but
193    /// exclusions cannot declare new captures.
194    pub const fn unless_context(mut self, left: &'a str, right: &'a str) -> Self {
195        self.excluded_left = Some(left);
196        self.excluded_right = Some(right);
197        self
198    }
199
200    /// Select non-overlapping matches from the right edge toward the left.
201    pub const fn right_to_left(mut self) -> Self {
202        self.direction = Direction::RightToLeft;
203        self
204    }
205
206    /// Apply only to the first match selected in this rule's direction.
207    pub const fn once(mut self) -> Self {
208        self.application = Application::Once;
209        self
210    }
211
212    /// A stable name used by traces and diagnostics.
213    pub const fn name(&self) -> &'a str {
214        self.name
215    }
216
217    /// The pattern replaced by this rule.
218    pub const fn target(&self) -> &'a str {
219        self.target
220    }
221
222    /// The replacement template emitted by this rule.
223    pub const fn replacement(&self) -> &'a str {
224        self.replacement
225    }
226
227    /// The immediately preceding context pattern, or `""` when unrestricted.
228    pub const fn left_context(&self) -> &'a str {
229        self.left
230    }
231
232    /// The immediately following context pattern, or `""` when unrestricted.
233    pub const fn right_context(&self) -> &'a str {
234        self.right
235    }
236
237    /// The excluded preceding context, if one was declared.
238    pub const fn excluded_left_context(&self) -> Option<&'a str> {
239        self.excluded_left
240    }
241
242    /// The excluded following context, if one was declared.
243    pub const fn excluded_right_context(&self) -> Option<&'a str> {
244        self.excluded_right
245    }
246
247    /// The match-selection direction.
248    pub const fn direction(&self) -> Direction {
249        self.direction
250    }
251
252    /// Whether this rule applies globally or once.
253    pub const fn application(&self) -> Application {
254        self.application
255    }
256}
257
258/// An uncompiled collection of classes and ordered rules.
259///
260/// This type is const-friendly, so a [`sound_laws!`] declaration can live in a
261/// `const` or `static`. Call [`RuleSet::compile`] once before applying it many
262/// times.
263#[derive(Debug, Clone, Copy)]
264pub struct RuleSet<'a> {
265    classes: &'a [Class<'a>],
266    maps: &'a [Map<'a>],
267    rules: &'a [Rule<'a>],
268}
269
270impl<'a> RuleSet<'a> {
271    /// Construct a rule set from declaration slices.
272    pub const fn new(classes: &'a [Class<'a>], rules: &'a [Rule<'a>]) -> Self {
273        Self {
274            classes,
275            maps: &[],
276            rules,
277        }
278    }
279
280    /// Construct a rule set with correspondence maps.
281    pub const fn new_with_maps(
282        classes: &'a [Class<'a>],
283        maps: &'a [Map<'a>],
284        rules: &'a [Rule<'a>],
285    ) -> Self {
286        Self {
287            classes,
288            maps,
289            rules,
290        }
291    }
292
293    /// Access the class declarations.
294    pub const fn classes(&self) -> &'a [Class<'a>] {
295        self.classes
296    }
297
298    /// Access the correspondence-map declarations.
299    pub const fn maps(&self) -> &'a [Map<'a>] {
300        self.maps
301    }
302
303    /// Access the ordered rule declarations.
304    pub const fn rules(&self) -> &'a [Rule<'a>] {
305        self.rules
306    }
307
308    /// Validate and compile the string notation into an executable program.
309    pub fn compile(&self) -> Result<Program, CompileError> {
310        compile::compile(self)
311    }
312
313    /// Compile and apply the complete rule set once.
314    ///
315    /// Prefer retaining a [`Program`] when applying the same laws repeatedly.
316    pub fn apply(&self, input: &str) -> Result<String, CompileError> {
317        Ok(self.compile()?.apply(input))
318    }
319}
320
321/// A problem in a class, pattern, backreference, or replacement template.
322#[derive(Debug, Clone, PartialEq, Eq)]
323pub struct CompileError {
324    rule: Option<String>,
325    message: String,
326}
327
328impl CompileError {
329    pub(crate) fn global(message: impl Into<String>) -> Self {
330        Self {
331            rule: None,
332            message: message.into(),
333        }
334    }
335
336    pub(crate) fn in_rule(rule: &str, message: impl Into<String>) -> Self {
337        Self {
338            rule: Some(rule.to_owned()),
339            message: message.into(),
340        }
341    }
342
343    /// The rule that failed to compile, when the error belongs to one rule.
344    pub fn rule(&self) -> Option<&str> {
345        self.rule.as_deref()
346    }
347
348    /// The diagnostic without its optional rule-name prefix.
349    pub fn message(&self) -> &str {
350        &self.message
351    }
352}
353
354impl fmt::Display for CompileError {
355    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356        match &self.rule {
357            Some(rule) => write!(f, "sound law `{rule}`: {}", self.message),
358            None => f.write_str(&self.message),
359        }
360    }
361}
362
363impl std::error::Error for CompileError {}
364
365/// Declare segment classes and ordered sound laws in one expression.
366///
367/// Every rule has the shape `name: "target" => "replacement";`. Add
368/// `/ "left" _ "right"` before the semicolon to constrain its environment. An
369/// empty target denotes insertion at a boundary rather than replacement. Add
370/// `unless "left" _ "right"` to exclude an environment. Rule options `[rtl]`,
371/// `[once]`, or `[rtl, once]` control match selection.
372#[macro_export]
373macro_rules! sound_laws {
374    (
375        classes {
376            $( $class:ident = [ $( $member:literal ),+ $(,)? ]; )*
377        }
378        $(
379            maps {
380                $( $map:ident = [ $( $map_from:literal => $map_to:literal ),+ $(,)? ]; )*
381            }
382        )?
383        rules {
384            $(
385                $rule:ident $( [ $( $option:ident ),+ $(,)? ] )?
386                : $target:literal => $replacement:literal
387                $( / $left:literal _ $right:literal )?
388                $( unless $excluded_left:literal _ $excluded_right:literal )? ;
389            )*
390        }
391    ) => {
392        $crate::RuleSet::new_with_maps(
393            &[
394                $(
395                    $crate::Class::new(stringify!($class), &[ $( $member ),+ ])
396                ),*
397            ],
398            &[
399                $($(
400                    $crate::Map::new(
401                        stringify!($map),
402                        &[ $( ($map_from, $map_to) ),+ ],
403                    )
404                ),*)?
405            ],
406            &[
407                $(
408                    $crate::sound_laws!(
409                        @options
410                        $crate::Rule::new(stringify!($rule), $target, $replacement)
411                            $( .in_context($left, $right) )?
412                            $( .unless_context($excluded_left, $excluded_right) )?
413                        ; $( $( $option ),+ )?
414                    )
415                ),*
416            ],
417        )
418    };
419    (@options $rule:expr; ) => { $rule };
420    (@options $rule:expr; rtl $(, $rest:ident)*) => {
421        $crate::sound_laws!(@options $rule.right_to_left(); $( $rest ),*)
422    };
423    (@options $rule:expr; once $(, $rest:ident)*) => {
424        $crate::sound_laws!(@options $rule.once(); $( $rest ),*)
425    };
426    (@options $rule:expr; $unknown:ident $(, $rest:ident)*) => {
427        compile_error!(concat!("unknown sound-law rule option `", stringify!($unknown), "`"))
428    };
429}