meta-language 0.46.0

A self-describing links-network core for lossless language representation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Deterministic evaluation utilities for inferred grammars.

mod metrics;
mod recognizer;
mod sampler;

use std::error::Error;
use std::fmt;

use crate::grammar::Grammar;

/// Decides language membership for a target language.
pub trait MembershipOracle {
    /// Returns `true` when `text` belongs to the oracle's language.
    fn accepts(&self, text: &str) -> bool;
}

/// [`Grammar`] backed membership oracle.
#[derive(Clone, Copy, Debug)]
pub struct GrammarOracle<'g>(pub &'g Grammar);

impl<'g> GrammarOracle<'g> {
    /// Builds an oracle over `grammar`.
    #[must_use]
    pub const fn new(grammar: &'g Grammar) -> Self {
        Self(grammar)
    }

    /// Returns `true` when `text` is accepted by the wrapped grammar.
    #[must_use]
    pub fn accepts(&self, text: &str) -> bool {
        <Self as MembershipOracle>::accepts(self, text)
    }
}

impl MembershipOracle for GrammarOracle<'_> {
    fn accepts(&self, text: &str) -> bool {
        recognizer::accepts(self.0, text)
    }
}

/// Deterministic sampler configuration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SampleConfig {
    /// Deterministic PRNG seed.
    pub seed: u64,
    /// Number of derivations to draw before duplicate removal.
    pub count: usize,
    /// Maximum non-terminal recursion depth before shortest terminating choices are forced.
    pub max_depth: usize,
    /// Maximum generated repetitions for `*`, `+`, and unbounded counted repetition.
    pub repeat_cap: usize,
}

impl Default for SampleConfig {
    fn default() -> Self {
        Self {
            seed: 0xD1E5_EED5_17A7_E001,
            count: 256,
            max_depth: 16,
            repeat_cap: 4,
        }
    }
}

/// Primary inference-evaluation metrics.
#[derive(Clone, Debug, PartialEq)]
pub struct MetricScores {
    /// Fraction of inferred samples accepted by the golden oracle.
    pub precision: f64,
    /// Fraction of golden samples or held-out positives accepted by the inferred grammar.
    pub recall: f64,
    /// Harmonic mean of [`Self::precision`] and [`Self::recall`].
    pub f1: f64,
    /// Raw grammar size measured as rule-name symbols plus expression nodes.
    pub size_symbols: usize,
    /// Deterministic two-part MDL score in bits; lower is better.
    pub mdl_bits: f64,
}

/// Recall source used by an evaluation report.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScoringMode {
    /// Recall was measured by sampling a golden grammar.
    GoldenGrammar,
    /// Recall was measured against held-out positive corpus examples.
    Corpus,
}

/// End-to-end benchmark result for one corpus.
#[derive(Clone, Debug, PartialEq)]
pub struct BenchmarkReport {
    /// Corpus identifier.
    pub corpus: &'static str,
    /// Metric values for this corpus run.
    pub scores: MetricScores,
    /// Number of unique samples/examples considered by precision and recall.
    pub samples_drawn: usize,
    /// Sampler seed used for this run.
    pub seed: u64,
    /// Recall source used for this report.
    pub scoring_mode: ScoringMode,
}

/// Evaluation failure.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EvalError {
    /// The grammar has no start rule to sample or recognize.
    EmptyGrammar,
    /// Corpus-mode recall was requested without held-out positive examples.
    EmptyCorpus,
    /// Sampling produced no unique strings for the named source.
    EmptySample {
        /// Source that produced no samples.
        source: &'static str,
    },
    /// A reachable rule cannot produce a finite string.
    NonTerminating {
        /// Rule name that cannot terminate.
        rule: String,
    },
    /// A reachable non-terminal references a missing rule.
    UnknownRule {
        /// Missing rule name.
        rule: String,
    },
    /// A character range has its start after its end.
    InvalidCharRange {
        /// Inclusive range start.
        start: char,
        /// Inclusive range end.
        end: char,
    },
    /// A character class has no character that the sampler can emit.
    EmptyCharClass,
    /// A counted repetition has a maximum smaller than its minimum.
    InvalidRepeat {
        /// Minimum repetition count.
        min: usize,
        /// Maximum repetition count.
        max: usize,
    },
    /// A named corpus was not registered.
    CorpusNotFound {
        /// Requested corpus name.
        corpus: String,
    },
}

impl fmt::Display for EvalError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyGrammar => formatter.write_str("grammar has no start rule"),
            Self::EmptyCorpus => formatter.write_str("corpus-mode recall requires positives"),
            Self::EmptySample { source } => write!(formatter, "{source} sampling produced no text"),
            Self::NonTerminating { rule } => write!(formatter, "rule `{rule}` cannot terminate"),
            Self::UnknownRule { rule } => write!(formatter, "unknown grammar rule `{rule}`"),
            Self::InvalidCharRange { start, end } => {
                write!(formatter, "invalid character range {start:?}..={end:?}")
            }
            Self::EmptyCharClass => formatter.write_str("character class has no sampleable member"),
            Self::InvalidRepeat { min, max } => {
                write!(formatter, "invalid repetition bounds {min}..={max}")
            }
            Self::CorpusNotFound { corpus } => write!(formatter, "unknown corpus `{corpus}`"),
        }
    }
}

impl Error for EvalError {}

/// Registry entry for an in-repository golden corpus.
#[derive(Clone, Copy, Debug)]
pub struct GoldenCorpus {
    name: &'static str,
    positives: &'static [&'static str],
    golden_grammar: fn() -> Grammar,
}

impl GoldenCorpus {
    /// Builds a corpus descriptor.
    #[must_use]
    pub const fn new(
        name: &'static str,
        positives: &'static [&'static str],
        golden_grammar: fn() -> Grammar,
    ) -> Self {
        Self {
            name,
            positives,
            golden_grammar,
        }
    }

    /// Corpus identifier.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// Held-out positive examples for corpus-mode recall or MDL data.
    #[must_use]
    pub const fn positives(&self) -> &'static [&'static str] {
        self.positives
    }

    /// Builds the corpus golden grammar.
    #[must_use]
    pub fn golden_grammar(&self) -> Grammar {
        (self.golden_grammar)()
    }
}

const LIST_POSITIVES: &[&str] = &["a", "b", "a,b", "b,a"];
const ASSIGNMENT_POSITIVES: &[&str] = &["let a=1;", "let b=2;", "let x=9;"];

/// Built-in smoke corpora for exercising the harness without vendored competitors.
pub const GOLDEN_CORPORA: &[GoldenCorpus] = &[
    GoldenCorpus::new("inference-eval:list", LIST_POSITIVES, list_corpus_grammar),
    GoldenCorpus::new(
        "inference-eval:assignment",
        ASSIGNMENT_POSITIVES,
        assignment_corpus_grammar,
    ),
];

/// Generates deterministic strings from `grammar`.
///
/// The sampler uses `SplitMix64` with the exact transition implemented in this
/// module, never system entropy. Duplicate draws are removed while preserving
/// first-seen order. Reachable rules that cannot emit any finite string return
/// [`EvalError::NonTerminating`].
pub fn sample(grammar: &Grammar, config: &SampleConfig) -> Result<Vec<String>, EvalError> {
    sampler::sample(grammar, config)
}

/// Evaluates an inferred grammar against a golden oracle.
///
/// Precision is the fraction of samples drawn from `inferred` that `golden`
/// accepts. When `golden_sampler` is present, recall is the fraction of samples
/// drawn from that grammar that `inferred` accepts. When `golden_sampler` is
/// absent, recall is the fraction of `positives` accepted by `inferred`.
pub fn evaluate(
    inferred: &Grammar,
    golden: &dyn MembershipOracle,
    golden_sampler: Option<&Grammar>,
    positives: &[&str],
    config: &SampleConfig,
) -> Result<MetricScores, EvalError> {
    evaluate_outcome(inferred, golden, golden_sampler, positives, config)
        .map(|outcome| outcome.scores)
}

/// Runs one registered corpus against an inferred grammar.
pub fn run_corpus(
    corpus: &GoldenCorpus,
    inferred: &Grammar,
    config: &SampleConfig,
) -> Result<BenchmarkReport, EvalError> {
    let golden = corpus.golden_grammar();
    let oracle = GrammarOracle(&golden);
    let outcome = evaluate_outcome(inferred, &oracle, Some(&golden), corpus.positives(), config)?;

    Ok(BenchmarkReport {
        corpus: corpus.name(),
        scores: outcome.scores,
        samples_drawn: outcome.samples_drawn,
        seed: config.seed,
        scoring_mode: outcome.scoring_mode,
    })
}

/// Runs a registered corpus by name.
pub fn run_named_corpus(
    corpus: &str,
    inferred: &Grammar,
    config: &SampleConfig,
) -> Result<BenchmarkReport, EvalError> {
    let descriptor = GOLDEN_CORPORA
        .iter()
        .find(|candidate| candidate.name() == corpus)
        .ok_or_else(|| EvalError::CorpusNotFound {
            corpus: corpus.to_string(),
        })?;
    run_corpus(descriptor, inferred, config)
}

/// Counts grammar symbols as rule-name symbols plus expression nodes.
#[must_use]
pub fn size_symbols(grammar: &Grammar) -> usize {
    metrics::size_symbols(grammar)
}

/// Computes the deterministic two-part MDL score for `grammar` and `data`.
///
/// `L(G)` is `size_symbols(G) * ceil(log2(alphabet(G)))`, where the alphabet is
/// the distinct set of rule names, terminals, character primitives, and grammar
/// operators. `L(D | G)` uses a fixed deterministic code: accepted examples cost
/// one emitted-symbol bit per Unicode scalar plus a stop bit; rejected examples
/// fall back to their UTF-8 byte length plus a 64-bit escape penalty.
#[must_use]
pub fn mdl(grammar: &Grammar, data: &[&str]) -> f64 {
    metrics::mdl(grammar, data)
}

#[derive(Clone, Debug)]
struct EvaluationOutcome {
    scores: MetricScores,
    samples_drawn: usize,
    scoring_mode: ScoringMode,
}

fn evaluate_outcome(
    inferred: &Grammar,
    golden: &dyn MembershipOracle,
    golden_sampler: Option<&Grammar>,
    positives: &[&str],
    config: &SampleConfig,
) -> Result<EvaluationOutcome, EvalError> {
    let inferred_samples = sample(inferred, config)?;
    if inferred_samples.is_empty() {
        return Err(EvalError::EmptySample { source: "inferred" });
    }

    let precision_hits = inferred_samples
        .iter()
        .filter(|text| golden.accepts(text))
        .count();
    let precision = metrics::ratio(precision_hits, inferred_samples.len());
    let inferred_oracle = GrammarOracle(inferred);

    let (recall, mdl_bits, samples_drawn, scoring_mode) =
        if let Some(golden_grammar) = golden_sampler {
            let reference_samples = sample(golden_grammar, config)?;
            if reference_samples.is_empty() {
                return Err(EvalError::EmptySample { source: "golden" });
            }
            let recall_hits = reference_samples
                .iter()
                .filter(|text| inferred_oracle.accepts(text))
                .count();
            let data = reference_samples
                .iter()
                .map(String::as_str)
                .collect::<Vec<_>>();
            (
                metrics::ratio(recall_hits, reference_samples.len()),
                mdl(inferred, &data),
                inferred_samples
                    .len()
                    .saturating_add(reference_samples.len()),
                ScoringMode::GoldenGrammar,
            )
        } else {
            if positives.is_empty() {
                return Err(EvalError::EmptyCorpus);
            }
            let recall_hits = positives
                .iter()
                .filter(|text| inferred_oracle.accepts(text))
                .count();
            (
                metrics::ratio(recall_hits, positives.len()),
                mdl(inferred, positives),
                inferred_samples.len().saturating_add(positives.len()),
                ScoringMode::Corpus,
            )
        };

    let f1 = if precision + recall == 0.0 {
        0.0
    } else {
        2.0 * precision * recall / (precision + recall)
    };

    Ok(EvaluationOutcome {
        scores: MetricScores {
            precision,
            recall,
            f1,
            size_symbols: size_symbols(inferred),
            mdl_bits,
        },
        samples_drawn,
        scoring_mode,
    })
}

fn list_corpus_grammar() -> Grammar {
    let expr = Grammar::expr();
    Grammar::builder()
        .start("list")
        .rule(
            "list",
            expr.seq([
                expr.nt("item"),
                expr.rep0(expr.seq([expr.term(","), expr.nt("item")])),
            ]),
        )
        .rule(
            "item",
            expr.choice_unordered([expr.term("a"), expr.term("b")]),
        )
        .build()
}

fn assignment_corpus_grammar() -> Grammar {
    let expr = Grammar::expr();
    Grammar::builder()
        .start("assignment")
        .rule(
            "assignment",
            expr.seq([
                expr.term("let "),
                expr.nt("letter"),
                expr.term("="),
                expr.nt("digit"),
                expr.term(";"),
            ]),
        )
        .rule("letter", expr.char_range('a', 'z'))
        .rule("digit", expr.char_range('0', '9'))
        .build()
}