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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Delimiter-skeleton structural prior for positive grammar inference.

use std::collections::BTreeSet;

use super::lexical::{categorise, CharCategory};
use crate::{LinkNetwork, ParseConfiguration};

const PRIOR_LANGUAGE: &str = "grammar-prior";

/// Half-open byte span `[start, end)` into the owning example string.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ByteSpan {
    /// First byte in the span.
    pub start: usize,
    /// Byte immediately after the span.
    pub end: usize,
}

impl ByteSpan {
    /// Creates a byte span.
    ///
    /// # Panics
    ///
    /// Panics when `start` is greater than `end`.
    #[must_use]
    pub const fn new(start: usize, end: usize) -> Self {
        assert!(start <= end, "byte span start must not exceed end");
        Self { start, end }
    }

    /// Returns `true` when the span contains no bytes.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.start == self.end
    }
}

/// The kind of an opaque terminal leaf.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum LeafKind {
    /// Unquoted text.
    Text,
    /// Single-quoted text kept opaque.
    SingleQuote,
    /// Double-quoted text kept opaque.
    DoubleQuote,
    /// Backtick-quoted text kept opaque.
    Backtick,
}

/// Delimiter family for a seed-tree group.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Delimiter {
    /// Parenthesized `(...)` group.
    Paren,
    /// Curly-braced `{...}` group.
    Curly,
    /// Square-bracketed `[...]` group.
    Square,
    /// Synthetic root wrapping one whole example.
    Root,
}

/// One node of a seed parse tree over a single example string.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SeedNode {
    /// An opaque terminal slice.
    Leaf {
        /// Span of the leaf in the owning example.
        span: ByteSpan,
        /// Leaf classification.
        kind: LeafKind,
    },
    /// A bracketed or synthetic grouped constituent.
    Group {
        /// Delimiter family that produced this group.
        delimiter: Delimiter,
        /// Ordered child nodes.
        children: Vec<Self>,
        /// Span of the group in the owning example.
        span: ByteSpan,
    },
}

/// One positive example paired with its seed tree.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SeedTree {
    /// Original example string.
    pub example: String,
    /// Synthetic root group for the example.
    pub root: SeedNode,
}

/// A batch of seed trees plus the shared terminal alphabet.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StructuralPrior {
    /// One seed tree per input example, preserving input order.
    pub trees: Vec<SeedTree>,
    /// Distinct terminal slices observed across all leaves, sorted lexicographically.
    pub alphabet: Vec<String>,
}

/// Whitespace policy for text leaves.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WhitespacePolicy {
    /// Strip ASCII whitespace around text runs and split internal runs into fine leaves.
    #[default]
    Trim,
    /// Keep each text run as one verbatim leaf.
    Keep,
}

/// Configuration for structural-prior construction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PriorOptions {
    /// Merge each text run into a single leaf after whitespace handling.
    pub coalesce_runs: bool,
    /// Whitespace handling for text runs.
    pub whitespace: WhitespacePolicy,
}

impl Default for PriorOptions {
    fn default() -> Self {
        Self {
            coalesce_runs: false,
            whitespace: WhitespacePolicy::Trim,
        }
    }
}

/// Builds the delimiter-skeleton structural prior for positive examples.
#[must_use]
pub fn build_structural_prior(examples: &[String], opts: PriorOptions) -> StructuralPrior {
    let mut alphabet = BTreeSet::new();
    let trees = examples
        .iter()
        .map(|example| {
            let root = build_seed_root(example, opts);
            collect_alphabet(&root, example, &mut alphabet);
            SeedTree {
                example: example.clone(),
                root,
            }
        })
        .collect();

    StructuralPrior {
        trees,
        alphabet: alphabet.into_iter().collect(),
    }
}

fn build_seed_root(example: &str, opts: PriorOptions) -> SeedNode {
    let _skeleton = skeletonise(example);
    let children = DelimiterParser::new(example, opts)
        .parse()
        .unwrap_or_else(|()| flat_leaves(example, opts));

    SeedNode::Group {
        delimiter: Delimiter::Root,
        children,
        span: ByteSpan::new(0, example.len()),
    }
}

fn skeletonise(text: &str) -> LinkNetwork {
    LinkNetwork::parse(text, PRIOR_LANGUAGE, ParseConfiguration::default())
}

struct DelimiterParser<'input> {
    text: &'input str,
    opts: PriorOptions,
    cursor: usize,
}

impl<'input> DelimiterParser<'input> {
    const fn new(text: &'input str, opts: PriorOptions) -> Self {
        Self {
            text,
            opts,
            cursor: 0,
        }
    }

    fn parse(mut self) -> Result<Vec<SeedNode>, ()> {
        self.parse_children_until(None)
    }

    fn parse_children_until(&mut self, closing: Option<char>) -> Result<Vec<SeedNode>, ()> {
        let mut children = Vec::new();
        while self.cursor < self.text.len() {
            let character = self.current_char().expect("cursor is inside text");
            if Some(character) == closing {
                self.advance_char();
                return Ok(children);
            }

            match character {
                '(' => children.push(self.parse_group(Delimiter::Paren, ')')?),
                '{' => children.push(self.parse_group(Delimiter::Curly, '}')?),
                '[' => children.push(self.parse_group(Delimiter::Square, ']')?),
                ')' | '}' | ']' => return Err(()),
                '\'' | '"' | '`' => children.push(self.parse_quoted(character)?),
                _ => children.extend(self.parse_text_run()),
            }
        }

        if closing.is_some() {
            Err(())
        } else {
            Ok(children)
        }
    }

    fn parse_group(&mut self, delimiter: Delimiter, closing: char) -> Result<SeedNode, ()> {
        let start = self.cursor;
        self.advance_char();
        let children = self.parse_children_until(Some(closing))?;

        Ok(SeedNode::Group {
            delimiter,
            children,
            span: ByteSpan::new(start, self.cursor),
        })
    }

    fn parse_quoted(&mut self, quote: char) -> Result<SeedNode, ()> {
        let start = self.cursor;
        let end = quoted_end(self.text, start, quote).ok_or(())?;
        self.cursor = end;

        Ok(SeedNode::Leaf {
            span: ByteSpan::new(start, end),
            kind: quote_kind(quote),
        })
    }

    fn parse_text_run(&mut self) -> Vec<SeedNode> {
        let start = self.cursor;
        while self.cursor < self.text.len() {
            let character = self.current_char().expect("cursor is inside text");
            if is_structural_delimiter(character) || is_quote(character) {
                break;
            }
            self.advance_char();
        }
        text_leaves(self.text, start, self.cursor, self.opts)
    }

    fn current_char(&self) -> Option<char> {
        self.text[self.cursor..].chars().next()
    }

    fn advance_char(&mut self) {
        self.cursor += self
            .current_char()
            .expect("cursor is inside text")
            .len_utf8();
    }
}

fn flat_leaves(text: &str, opts: PriorOptions) -> Vec<SeedNode> {
    let mut leaves = Vec::new();
    let mut cursor = 0;
    let mut text_start = 0;

    while cursor < text.len() {
        let character = text[cursor..]
            .chars()
            .next()
            .expect("cursor is inside text");
        if is_quote(character) {
            if let Some(end) = quoted_end(text, cursor, character) {
                leaves.extend(text_leaves(text, text_start, cursor, opts));
                leaves.push(SeedNode::Leaf {
                    span: ByteSpan::new(cursor, end),
                    kind: quote_kind(character),
                });
                cursor = end;
                text_start = cursor;
                continue;
            }
        }

        cursor += character.len_utf8();
    }

    leaves.extend(text_leaves(text, text_start, text.len(), opts));
    leaves
}

fn text_leaves(text: &str, start: usize, end: usize, opts: PriorOptions) -> Vec<SeedNode> {
    if start == end {
        return Vec::new();
    }

    match opts.whitespace {
        WhitespacePolicy::Keep => text_leaf(start, end).into_iter().collect(),
        WhitespacePolicy::Trim if opts.coalesce_runs => trim_ascii_span(text, start, end)
            .and_then(|(trimmed_start, trimmed_end)| text_leaf(trimmed_start, trimmed_end))
            .into_iter()
            .collect(),
        WhitespacePolicy::Trim => split_trimmed_text(text, start, end),
    }
}

fn split_trimmed_text(text: &str, start: usize, end: usize) -> Vec<SeedNode> {
    let mut leaves = Vec::new();
    let mut cursor = start;

    while cursor < end {
        cursor = skip_ascii_whitespace(text, cursor, end);
        if cursor >= end {
            break;
        }

        let token_start = cursor;
        let token_category = current_category(text, cursor);
        cursor += current_char(text, cursor).len_utf8();

        if !is_atomic(token_category) {
            while cursor < end {
                let next = current_char(text, cursor);
                if next.is_ascii_whitespace() {
                    break;
                }

                let next_category = categorise(next);
                if continues_text_token(token_category, next_category) {
                    cursor += next.len_utf8();
                } else {
                    break;
                }
            }
        }

        leaves.push(SeedNode::Leaf {
            span: ByteSpan::new(token_start, cursor),
            kind: LeafKind::Text,
        });
    }

    leaves
}

fn trim_ascii_span(text: &str, start: usize, end: usize) -> Option<(usize, usize)> {
    let trimmed_start = skip_ascii_whitespace(text, start, end);
    let mut trimmed_end = end;

    while trimmed_start < trimmed_end {
        let character_start = previous_char_start(text, trimmed_start, trimmed_end);
        let character = current_char(text, character_start);
        if !character.is_ascii_whitespace() {
            break;
        }
        trimmed_end = character_start;
    }

    (trimmed_start < trimmed_end).then_some((trimmed_start, trimmed_end))
}

fn skip_ascii_whitespace(text: &str, mut cursor: usize, end: usize) -> usize {
    while cursor < end {
        let character = current_char(text, cursor);
        if !character.is_ascii_whitespace() {
            break;
        }
        cursor += character.len_utf8();
    }
    cursor
}

fn text_leaf(start: usize, end: usize) -> Option<SeedNode> {
    (start < end).then_some(SeedNode::Leaf {
        span: ByteSpan::new(start, end),
        kind: LeafKind::Text,
    })
}

fn quoted_end(text: &str, start: usize, quote: char) -> Option<usize> {
    let mut cursor = start + quote.len_utf8();
    while cursor < text.len() {
        let character = current_char(text, cursor);
        if character == '\\' {
            cursor += character.len_utf8();
            if cursor < text.len() {
                cursor += current_char(text, cursor).len_utf8();
            }
            continue;
        }

        if character == quote {
            let close_end = cursor + quote.len_utf8();
            if text[close_end..].starts_with(quote) {
                cursor = close_end + quote.len_utf8();
                continue;
            }
            return Some(close_end);
        }

        cursor += character.len_utf8();
    }

    None
}

fn collect_alphabet(node: &SeedNode, example: &str, alphabet: &mut BTreeSet<String>) {
    match node {
        SeedNode::Leaf { span, .. } => {
            alphabet.insert(example[span.start..span.end].to_string());
        }
        SeedNode::Group { children, .. } => {
            for child in children {
                collect_alphabet(child, example, alphabet);
            }
        }
    }
}

fn current_char(text: &str, cursor: usize) -> char {
    text[cursor..]
        .chars()
        .next()
        .expect("cursor is inside text")
}

fn current_category(text: &str, cursor: usize) -> CharCategory {
    categorise(current_char(text, cursor))
}

fn previous_char_start(text: &str, start: usize, end: usize) -> usize {
    text[start..end]
        .char_indices()
        .last()
        .map_or(start, |(offset, _)| start + offset)
}

fn continues_text_token(current: CharCategory, next: CharCategory) -> bool {
    if is_atomic(current) || is_atomic(next) {
        return false;
    }

    current == next || (current == CharCategory::Letter && next == CharCategory::Digit)
}

const fn is_atomic(category: CharCategory) -> bool {
    matches!(
        category,
        CharCategory::Delimiter | CharCategory::Punctuation
    )
}

const fn is_structural_delimiter(value: char) -> bool {
    matches!(value, '(' | ')' | '[' | ']' | '{' | '}')
}

const fn is_quote(value: char) -> bool {
    matches!(value, '\'' | '"' | '`')
}

const fn quote_kind(quote: char) -> LeafKind {
    match quote {
        '\'' => LeafKind::SingleQuote,
        '"' => LeafKind::DoubleQuote,
        '`' => LeafKind::Backtick,
        _ => unreachable!(),
    }
}