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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use clap::{Parser, Subcommand, ValueEnum};

use meta_language::{
    emit_abnf, emit_bnf, emit_ebnf, emit_gbnf, emit_pest, emit_tree_sitter_grammar_js, evaluate,
    grammar_concept_translation_rules, grammar_from_lino, grammar_to_lino, import_abnf,
    import_antlr, import_bnf, import_ebnf, import_gbnf, import_lark, import_pest,
    import_tree_sitter_json, infer_cfg, parse_grammar_surface, translate_grammar_surface,
    write_grammar_surface, Grammar, InferenceOptions, LinkNetwork, MembershipOracle,
    ParseConfiguration, PositiveOnlyOracle, SampleConfig,
};

#[derive(Parser, Debug)]
#[command(
    name = "meta-language",
    about = "Build and verify self-describing links networks"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Print the built-in self-description roots.
    Describe,
    /// Parse text into a lossless token network and verify it is clean.
    Verify {
        /// Language label for the parsed region.
        #[arg(long)]
        language: String,
        /// Source text to parse.
        #[arg(long)]
        text: String,
    },
    /// Infer a grammar from example texts.
    Infer {
        /// One or more files or directories of example texts.
        #[arg(required = true)]
        examples: Vec<PathBuf>,
        /// Output grammar notation.
        #[arg(long, value_enum, default_value = "lino")]
        format: GrammarFormatArg,
        /// Inference strategy / pipeline depth.
        #[arg(long, value_enum, default_value = "auto")]
        strategy: StrategyArg,
        /// Also print precision/recall/F1/runtime to stderr.
        #[arg(long)]
        metrics: bool,
        /// Write the grammar here instead of stdout.
        #[arg(long)]
        out: Option<PathBuf>,
    },
    /// Import a grammar in another notation into the IR / `LiNo`.
    ImportGrammar {
        /// Source notation of the input file.
        #[arg(long, value_enum)]
        format: ImportFormatArg,
        /// Grammar file to import.
        #[arg(required = true)]
        input: PathBuf,
        /// Output notation for the imported grammar.
        #[arg(long, value_enum, default_value = "lino")]
        to: GrammarFormatArg,
        /// Write the grammar here instead of stdout.
        #[arg(long)]
        out: Option<PathBuf>,
    },
    /// Emit an IR/LiNo grammar to another notation.
    EmitGrammar {
        /// Target notation.
        #[arg(long, value_enum)]
        format: EmitFormatArg,
        /// Grammar file (IR/LiNo or native grammar surface) to emit from.
        #[arg(required = true)]
        input: PathBuf,
        /// Write the grammar here instead of stdout.
        #[arg(long)]
        out: Option<PathBuf>,
    },
    /// Translate a grammar's human-facing surface across languages.
    TranslateGrammar {
        /// Grammar file (IR/LiNo or native grammar surface) to translate.
        #[arg(required = true)]
        input: PathBuf,
        /// Source natural language, for example en.
        #[arg(long)]
        from_language: String,
        /// Target natural language, for example ru.
        #[arg(long)]
        to_language: String,
        /// Write the grammar here instead of stdout.
        #[arg(long)]
        out: Option<PathBuf>,
    },
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum GrammarFormatArg {
    /// Canonical links-network `LiNo` encoding.
    Lino,
    /// Native grammar authoring surface.
    MetaLanguage,
    /// Backus-Naur Form.
    Bnf,
    /// Extended Backus-Naur Form.
    Ebnf,
    /// Augmented Backus-Naur Form.
    Abnf,
    /// Parsing Expression Grammar surface.
    Peg,
    /// ANTLR grammar.
    Antlr,
    /// Lark grammar.
    Lark,
    /// GBNF grammar.
    Gbnf,
    /// Tree-sitter grammar.js.
    TreeSitter,
    /// Inferred grammar source tag.
    Inferred,
}

impl GrammarFormatArg {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Lino => "lino",
            Self::MetaLanguage => "meta-language",
            Self::Bnf => "bnf",
            Self::Ebnf => "ebnf",
            Self::Abnf => "abnf",
            Self::Peg => "peg",
            Self::Antlr => "antlr",
            Self::Lark => "lark",
            Self::Gbnf => "gbnf",
            Self::TreeSitter => "tree-sitter",
            Self::Inferred => "inferred",
        }
    }
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum ImportFormatArg {
    /// Backus-Naur Form.
    Bnf,
    /// Extended Backus-Naur Form.
    Ebnf,
    /// Augmented Backus-Naur Form.
    Abnf,
    /// Parsing Expression Grammar surface.
    Peg,
    /// ANTLR grammar.
    Antlr,
    /// Lark grammar.
    Lark,
    /// GBNF grammar.
    Gbnf,
    /// Tree-sitter JSON grammar.
    TreeSitter,
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum EmitFormatArg {
    /// Backus-Naur Form.
    Bnf,
    /// Extended Backus-Naur Form.
    Ebnf,
    /// Augmented Backus-Naur Form.
    Abnf,
    /// Parsing Expression Grammar surface.
    Peg,
    /// GBNF grammar.
    Gbnf,
    /// Tree-sitter grammar.js.
    TreeSitter,
    /// ANTLR grammar.
    Antlr,
    /// Lark grammar.
    Lark,
}

impl EmitFormatArg {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Bnf => "bnf",
            Self::Ebnf => "ebnf",
            Self::Abnf => "abnf",
            Self::Peg => "peg",
            Self::Gbnf => "gbnf",
            Self::TreeSitter => "tree-sitter",
            Self::Antlr => "antlr",
            Self::Lark => "lark",
        }
    }
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum StrategyArg {
    /// Use the default deterministic structural pipeline.
    Auto,
    /// Enable the incremental inference option.
    Incremental,
}

impl StrategyArg {
    fn options(self) -> InferenceOptions {
        let mut options = InferenceOptions::default();
        if matches!(self, Self::Incremental) {
            options.incremental = true;
        }
        options
    }
}

fn main() {
    let cli = Cli::parse();

    match cli.command {
        Command::Describe => describe(),
        Command::Verify { language, text } => verify(&language, &text),
        Command::Infer {
            examples,
            format,
            strategy,
            metrics,
            out,
        } => infer(&examples, format, strategy, metrics, out.as_deref()),
        Command::ImportGrammar {
            format,
            input,
            to,
            out,
        } => import_grammar(format, &input, to, out.as_deref()),
        Command::EmitGrammar { format, input, out } => {
            emit_grammar(format, &input, out.as_deref());
        }
        Command::TranslateGrammar {
            input,
            from_language,
            to_language,
            out,
        } => translate_grammar(&input, &from_language, &to_language, out.as_deref()),
    }
}

fn describe() {
    let network = LinkNetwork::self_describing();
    print!("{}", network.self_description_text());
}

fn verify(language: &str, text: &str) {
    let network = LinkNetwork::parse(text, language, ParseConfiguration::default());
    let report = network.verify_full_match(None);

    if report.is_clean() {
        println!("clean");
    } else {
        for issue in report.issues() {
            eprintln!("{}: {:?}", issue.link_id(), issue.kind());
        }
        std::process::exit(1);
    }
}

fn infer(
    paths: &[PathBuf],
    format: GrammarFormatArg,
    strategy: StrategyArg,
    metrics: bool,
    out: Option<&Path>,
) {
    let started_at = Instant::now();
    let examples = read_examples(paths).unwrap_or_else(|error| fail(error));
    if examples.is_empty() {
        fail("no example texts were found");
    }

    let result = infer_cfg(&examples, &PositiveOnlyOracle::new(), strategy.options());
    let rendered = render_grammar(&result.grammar, format).unwrap_or_else(|error| fail(error));
    write_output(&rendered, out).unwrap_or_else(|error| fail(error));

    if metrics {
        print_metrics(
            &result.grammar,
            &examples,
            result.report.rules,
            result.report.bubbles_proposed,
            result.report.merges_accepted,
            result.report.merges_rejected,
            started_at.elapsed(),
        )
        .unwrap_or_else(|error| fail(error));
    }
}

fn import_grammar(format: ImportFormatArg, input: &Path, to: GrammarFormatArg, out: Option<&Path>) {
    let text = read_file(input, "grammar").unwrap_or_else(|error| fail(error));
    let grammar = import_with_format(format, &text).unwrap_or_else(|error| fail(error));
    let rendered = render_grammar(&grammar, to).unwrap_or_else(|error| fail(error));
    write_output(&rendered, out).unwrap_or_else(|error| fail(error));
}

fn emit_grammar(format: EmitFormatArg, input: &Path, out: Option<&Path>) {
    let grammar = read_ir_grammar(input).unwrap_or_else(|error| fail(error));
    let rendered = render_emit_format(&grammar, format).unwrap_or_else(|error| fail(error));
    write_output(&rendered, out).unwrap_or_else(|error| fail(error));
}

fn translate_grammar(input: &Path, from_language: &str, to_language: &str, out: Option<&Path>) {
    if from_language.trim().is_empty() {
        fail("from language must not be empty");
    }
    if to_language.trim().is_empty() {
        fail("to language must not be empty");
    }

    let grammar = read_ir_grammar(input).unwrap_or_else(|error| fail(error));
    let rules = grammar_concept_translation_rules();
    let translated = translate_grammar_surface(&grammar, to_language, &rules)
        .unwrap_or_else(|error| fail(error.to_string()));
    let rendered = grammar_to_lino(&translated);
    write_output(&rendered, out).unwrap_or_else(|error| fail(error));
}

fn read_examples(paths: &[PathBuf]) -> Result<Vec<String>, String> {
    let mut files = Vec::new();
    for path in paths {
        collect_example_files(path, &mut files)?;
    }

    files.sort();
    files.dedup();
    files
        .iter()
        .map(|path| read_file(path, "example"))
        .collect()
}

fn collect_example_files(path: &Path, files: &mut Vec<PathBuf>) -> Result<(), String> {
    let metadata = fs::metadata(path)
        .map_err(|error| format!("failed to inspect {}: {error}", path.display()))?;

    if metadata.is_file() {
        files.push(path.to_path_buf());
        return Ok(());
    }

    if metadata.is_dir() {
        let mut entries = fs::read_dir(path)
            .map_err(|error| format!("failed to read directory {}: {error}", path.display()))?
            .collect::<Result<Vec<_>, _>>()
            .map_err(|error| {
                format!(
                    "failed to read directory entry in {}: {error}",
                    path.display()
                )
            })?;
        entries.sort_by_key(std::fs::DirEntry::path);
        for entry in entries {
            collect_example_files(&entry.path(), files)?;
        }
        return Ok(());
    }

    Err(format!(
        "example path is not a regular file or directory: {}",
        path.display()
    ))
}

fn import_with_format(format: ImportFormatArg, text: &str) -> Result<Grammar, String> {
    match format {
        ImportFormatArg::Bnf => import_bnf(text),
        ImportFormatArg::Ebnf => import_ebnf(text),
        ImportFormatArg::Abnf => import_abnf(text),
        ImportFormatArg::Peg => import_pest(text),
        ImportFormatArg::Antlr => import_antlr(text),
        ImportFormatArg::Lark => import_lark(text),
        ImportFormatArg::Gbnf => import_gbnf(text),
        ImportFormatArg::TreeSitter => import_tree_sitter_json(text),
    }
    .map_err(|error| error.to_string())
}

fn render_grammar(grammar: &Grammar, format: GrammarFormatArg) -> Result<String, String> {
    match format {
        GrammarFormatArg::Lino => Ok(grammar_to_lino(grammar)),
        GrammarFormatArg::MetaLanguage => Ok(write_grammar_surface(grammar)),
        GrammarFormatArg::Bnf => emit_bnf(grammar)
            .map(|(text, _report)| text)
            .map_err(|error| error.to_string()),
        GrammarFormatArg::Ebnf => emit_ebnf(grammar)
            .map(|(text, _report)| text)
            .map_err(|error| error.to_string()),
        GrammarFormatArg::Abnf => emit_abnf(grammar)
            .map(|(text, _report)| text)
            .map_err(|error| error.to_string()),
        GrammarFormatArg::Peg => emit_pest(grammar)
            .map(|(text, _report)| text)
            .map_err(|error| error.to_string()),
        GrammarFormatArg::Gbnf => emit_gbnf(grammar)
            .map(|(text, _report)| text)
            .map_err(|error| error.to_string()),
        GrammarFormatArg::TreeSitter => {
            emit_tree_sitter_grammar_js(grammar).map_err(|error| error.to_string())
        }
        GrammarFormatArg::Antlr | GrammarFormatArg::Lark | GrammarFormatArg::Inferred => {
            Err(format!("unsupported output format: {}", format.as_str()))
        }
    }
}

fn render_emit_format(grammar: &Grammar, format: EmitFormatArg) -> Result<String, String> {
    match format {
        EmitFormatArg::Bnf => emit_bnf(grammar)
            .map(|(text, _report)| text)
            .map_err(|error| error.to_string()),
        EmitFormatArg::Ebnf => emit_ebnf(grammar)
            .map(|(text, _report)| text)
            .map_err(|error| error.to_string()),
        EmitFormatArg::Abnf => emit_abnf(grammar)
            .map(|(text, _report)| text)
            .map_err(|error| error.to_string()),
        EmitFormatArg::Peg => emit_pest(grammar)
            .map(|(text, _report)| text)
            .map_err(|error| error.to_string()),
        EmitFormatArg::Gbnf => emit_gbnf(grammar)
            .map(|(text, _report)| text)
            .map_err(|error| error.to_string()),
        EmitFormatArg::TreeSitter => {
            emit_tree_sitter_grammar_js(grammar).map_err(|error| error.to_string())
        }
        EmitFormatArg::Antlr | EmitFormatArg::Lark => {
            Err(format!("unsupported output format: {}", format.as_str()))
        }
    }
}

fn read_ir_grammar(input: &Path) -> Result<Grammar, String> {
    let text = read_file(input, "grammar")?;
    grammar_from_lino(&text).or_else(|lino_error| {
        parse_grammar_surface(&text).map_err(|surface_error| {
            format!(
                "failed to parse {} as LiNo ({lino_error}) or grammar surface ({surface_error})",
                input.display()
            )
        })
    })
}

fn print_metrics(
    grammar: &Grammar,
    examples: &[String],
    rules: usize,
    bubbles_proposed: usize,
    merges_accepted: usize,
    merges_rejected: usize,
    runtime: Duration,
) -> Result<(), String> {
    let positives = examples.iter().map(String::as_str).collect::<Vec<_>>();
    let scores = evaluate(
        grammar,
        &PositiveSetOracle::new(examples),
        None,
        &positives,
        &SampleConfig {
            seed: 9,
            count: 64,
            max_depth: 8,
            repeat_cap: 4,
        },
    )
    .map_err(|error| error.to_string())?;

    eprintln!(
        "precision={:.3} recall={:.3} f1={:.3} runtime_ms={} rules={rules} bubbles={bubbles_proposed} merges_accepted={merges_accepted} merges_rejected={merges_rejected}",
        scores.precision,
        scores.recall,
        scores.f1,
        runtime.as_millis()
    );
    Ok(())
}

fn read_file(path: &Path, label: &str) -> Result<String, String> {
    fs::read_to_string(path)
        .map_err(|error| format!("failed to read {label} {}: {error}", path.display()))
}

fn write_output(text: &str, out: Option<&Path>) -> Result<(), String> {
    if let Some(path) = out {
        fs::write(path, text)
            .map_err(|error| format!("failed to write output {}: {error}", path.display()))?;
    } else {
        print!("{text}");
    }
    Ok(())
}

fn fail(message: impl AsRef<str>) -> ! {
    eprintln!("error: {}", message.as_ref());
    std::process::exit(1);
}

#[derive(Clone, Debug)]
struct PositiveSetOracle {
    examples: BTreeSet<String>,
}

impl PositiveSetOracle {
    fn new(examples: &[String]) -> Self {
        Self {
            examples: examples.iter().cloned().collect(),
        }
    }
}

impl MembershipOracle for PositiveSetOracle {
    fn accepts(&self, text: &str) -> bool {
        self.examples.contains(text)
    }
}