interscript 0.1.0

Rust runtime for Interscript ISC maps, executing the parsanol .parg grammar
Documentation
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
//! `iscrs` — the interscript-rs CLI. Mirrors the Ruby runtime's
//! entry points:
//!
//!   iscrs transliterate <map_id> <string>   # Interscript.transliterate
//!   iscrs test <map_id>...                  # run a map's embedded tests
//!   iscrs test-all                          # sweep the corpus
//!   iscrs parse <file|dir>...               # parse-only check
//!   iscrs parse-all                         # parse sweep of a maps dir
//!   iscrs grammar-test                      # the .parg embedded suite

use interscript_rs::{Error, Runtime};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match run(&args) {
        Ok(()) => ExitCode::SUCCESS,
        Err(CliError::Usage(msg)) => {
            eprintln!("{msg}\n\n{}", usage());
            ExitCode::from(2)
        }
        Err(CliError::Runtime(e)) => {
            eprintln!("error: {e}");
            ExitCode::FAILURE
        }
        Err(CliError::Failures) => ExitCode::FAILURE,
    }
}

enum CliError {
    Usage(String),
    Runtime(Error),
    Failures,
}

impl From<Error> for CliError {
    fn from(e: Error) -> Self {
        CliError::Runtime(e)
    }
}

fn usage() -> String {
    r#"commands:
  transliterate <map_id> <string> [--stage NAME]
  reverse <map_id> <string> [--stage NAME]   # run the reversed document
  test <map_id>...
  test-all [--root DIR] [--limit N]
  parse <file-or-dir>...
  parse-all [--root DIR]
  grammar-test
  infer <artifact_zip_or_model_id> <string> [--max-len N]
  conformance <fixture_file_or_dir> [<artifact_dir>]

options:
  --maps DIR...    add a maps/library directory to the load path
                   (default: $ISCRS_MAPS or the sibling maps checkout)
  --json           machine-readable summary lines (test-all/parse-all)

environment (IMF commands):
  SECRYST_INDEX    models.yaml index URL or path (default: index-v12)
  SECRYST_CACHE    artifact cache dir (default: ~/.cache/secryst)"#
        .to_string()
}

fn run(args: &[String]) -> Result<(), CliError> {
    let mut maps_dirs: Vec<PathBuf> = Vec::new();
    let mut positional: Vec<String> = Vec::new();
    let mut stage = "main".to_string();
    let mut limit: Option<usize> = None;
    let mut max_len = interscript_rs::imf::infer::MAX_DECODE_STEPS;
    let mut json = false;
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "--maps" => {
                let dir = iter.next().ok_or_else(|| CliError::Usage("--maps needs a value".into()))?;
                maps_dirs.push(PathBuf::from(dir));
            }
            "--stage" => {
                stage = iter
                    .next()
                    .ok_or_else(|| CliError::Usage("--stage needs a value".into()))?
                    .clone();
            }
            "--limit" => {
                let v = iter
                    .next()
                    .ok_or_else(|| CliError::Usage("--limit needs a value".into()))?;
                limit = Some(v.parse().map_err(|_| CliError::Usage("--limit needs a number".into()))?);
            }
            "--max-len" => {
                let v = iter
                    .next()
                    .ok_or_else(|| CliError::Usage("--max-len needs a value".into()))?;
                max_len = v
                    .parse()
                    .map_err(|_| CliError::Usage("--max-len needs a number".into()))?;
            }
            "--json" => json = true,
            other if other.starts_with("--") => {
                return Err(CliError::Usage(format!("unknown option {other}")));
            }
            _ => positional.push(arg.clone()),
        }
    }

    let Some(cmd) = positional.first() else {
        return Err(CliError::Usage(usage()));
    };
    let rest = &positional[1..];

    // The IMF commands do not need a maps load path.
    match cmd.as_str() {
        "infer" => return cmd_infer(rest, max_len).map_err(CliError::from),
        "conformance" => return cmd_conformance(rest).map_err(CliError::from),
        _ => {}
    }

    let load_path = if maps_dirs.is_empty() {
        interscript_rs::locate::default_load_path()
    } else {
        maps_dirs
    };
    if load_path.is_empty() {
        return Err(CliError::Usage(
            "no maps directory found; pass --maps DIR or set ISCRS_MAPS".into(),
        ));
    }

    match cmd.as_str() {
        "transliterate" => {
            if rest.len() != 2 {
                return Err(CliError::Usage("usage: transliterate <map_id> <string>".into()));
            }
            let rt = Runtime::new(load_path);
            let out = rt.transliterate_stage(&rest[0], &stage, &rest[1])?;
            println!("{out}");
        }
        "reverse" => {
            if rest.len() != 2 {
                return Err(CliError::Usage("usage: reverse <map_id> <string>".into()));
            }
            let rt = Runtime::new(load_path);
            let doc = rt.load(&rest[0])?;
            let reversed = interscript_rs::reverse::reverse_document(&doc)?;
            let out = interscript_rs::interpreter::execute_stage_pub(
                &reversed,
                &stage,
                &rest[1],
            )?;
            println!("{out}");
        }
        "test" => {
            if rest.is_empty() {
                return Err(CliError::Usage("usage: test <map_id>...".into()));
            }
            let rt = Runtime::new(load_path);
            let mut total_pass = 0usize;
            let mut total_fail = 0usize;
            for map in rest {
                let (passed, failed, failures) = rt.run_tests(map)?;
                println!("{map}: {passed} passed, {failed} failed");
                for f in &failures {
                    println!("  {f}");
                }
                total_pass += passed;
                total_fail += failed;
            }
            println!("total: {total_pass} passed, {total_fail} failed");
            if total_fail > 0 {
                return Err(CliError::Failures);
            }
        }
        "test-all" => {
            let root = rest
                .first()
                .map(PathBuf::from)
                .unwrap_or_else(|| PathBuf::from("../maps/maps"));
            let maps = list_isc(&root);
            let rt = Runtime::new(load_path);
            let mut maps_with_tests = 0usize;
            let mut maps_run = 0usize;
            let mut total_pass = 0usize;
            let mut total_fail = 0usize;
            let mut failing_maps: Vec<String> = Vec::new();
            let mut skipped: Vec<String> = Vec::new();
            for (i, path) in maps.iter().enumerate() {
                if let Some(l) = limit {
                    if maps_run >= l {
                        break;
                    }
                }
                let map_id = path.file_stem().unwrap().to_string_lossy().to_string();
                // A map without tests still proves parse+build+load.
                let has_tests = match rt.run_tests(&map_id) {
                    Ok((passed, failed, failures)) => {
                        if passed + failed == 0 {
                            if !json {
                                println!("SKIP-NO-TESTS {map_id}");
                            }
                            skipped.push(format!("{map_id} (no tests)"));
                            continue;
                        }
                        maps_run += 1;
                        maps_with_tests += 1;
                        total_pass += passed;
                        total_fail += failed;
                        if failed > 0 {
                            println!("FAIL {map_id}: {failed} failed");
                            for f in &failures {
                                println!("  {f}");
                            }
                            failing_maps.push(map_id.clone());
                        } else if !json {
                            println!("OK   {map_id}: {passed} passed");
                        }
                        true
                    }
                    Err(e) => {
                        maps_run += 1;
                        skipped.push(format!("{map_id} ({e})"));
                        if !json {
                            println!("SKIP {map_id}: {e}");
                        }
                        false
                    }
                };
                let _ = has_tests;
                let _ = i;
            }
            if json {
                println!(
                    r#"{{"maps_run": {maps_run}, "maps_with_tests": {maps_with_tests}, "tests_passed": {total_pass}, "tests_failed": {total_fail}, "failing_maps": {:?}}}"#,
                    failing_maps
                );
            } else {
                println!(
                    "maps run: {maps_run} (with tests: {maps_with_tests}); tests: {total_pass} passed, {total_fail} failed"
                );
                println!("skipped: {}", skipped.len());
                for s in &skipped {
                    println!("  {s}");
                }
            }
            if total_fail > 0 {
                return Err(CliError::Failures);
            }
        }
        "parse" => {
            if rest.is_empty() {
                return Err(CliError::Usage("usage: parse <file-or-dir>...".into()));
            }
            let mut files = Vec::new();
            for arg in rest {
                collect_isc(Path::new(arg), &mut files);
            }
            files.sort();
            let mut ok = 0usize;
            let mut fail = 0usize;
            for file in &files {
                let source = interscript_rs::locate::read_map(file).map_err(Error::from)?;
                match interscript_rs::grammar::parse_isc(&source) {
                    Ok(_) => {
                        ok += 1;
                        if !json {
                            println!("OK   {}", file.display());
                        }
                    }
                    Err((offset, expected)) => {
                        fail += 1;
                        println!("FAIL {} (offset {offset}, expected {:?})", file.display(), expected);
                    }
                }
            }
            println!("{}/{}/{} files parsed", ok, ok + fail, ok + fail);
            if fail > 0 {
                return Err(CliError::Failures);
            }
        }
        "parse-all" => {
            let root = rest
                .first()
                .map(PathBuf::from)
                .unwrap_or_else(|| PathBuf::from("../maps/maps"));
            let mut files = Vec::new();
            collect_isc(&root, &mut files);
            files.sort();
            let mut ok = 0usize;
            let mut fail = 0usize;
            for file in &files {
                let source = interscript_rs::locate::read_map(file).map_err(Error::from)?;
                match interscript_rs::grammar::parse_isc(&source) {
                    Ok(_) => ok += 1,
                    Err((offset, expected)) => {
                        fail += 1;
                        println!("FAIL {} (offset {offset}, expected {:?})", file.display(), expected);
                    }
                }
            }
            if json {
                println!(r#"{{"parsed": {ok}, "failed": {fail}}}"#);
            } else {
                println!("{}/{}/{} files parsed", ok, ok + fail, ok + fail);
            }
            if fail > 0 {
                return Err(CliError::Failures);
            }
        }
        "grammar-test" => {
            let (passed, failed, failures) = interscript_rs::grammar::run_grammar_suite();
            println!("grammar suite: {passed} passed, {failed} failed");
            for f in &failures {
                println!("  {f}");
            }
            if failed > 0 {
                return Err(CliError::Failures);
            }
        }
        other => {
            return Err(CliError::Usage(format!("unknown command {other:?}\n\n{}", usage())));
        }
    }
    Ok(())
}

fn list_isc(root: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    collect_isc(root, &mut out);
    out.sort();
    out
}

// ----------------------------------------------------------------------
// IMF v1 commands (infer / conformance)
// ----------------------------------------------------------------------

/// `iscrs infer <artifact_zip_or_model_id> <string>`: resolve (local
/// path or models.yaml id -> verified cache), greedy single-row
/// decode, print the translated string.
fn cmd_infer(rest: &[String], max_len: usize) -> interscript_rs::Result<()> {
    if rest.len() != 2 {
        return Err(interscript_rs::Error::Io(
            "usage: infer <artifact_zip_or_model_id> <string>".into(),
        ));
    }
    let artifact = resolve_artifact_arg(&rest[0])?;
    println!(
        "# artifact: {}",
        artifact.display()
    );
    let graphs = interscript_rs::imf::loader::verify_and_read(&artifact)?;
    println!(
        "# model {} (decoder: {:?}, precision: {}, opset: {}), members sha256-verified",
        graphs.manifest.id,
        graphs.manifest.decoder,
        graphs.manifest.precision,
        graphs.manifest.opset
    );
    let mut engine = interscript_rs::imf::infer::OrtEngine::from_graphs(&graphs)?;
    let out = interscript_rs::imf::infer::translate(&mut engine, &rest[1], max_len)?;
    println!("{out}");
    Ok(())
}

fn resolve_artifact_arg(arg: &str) -> interscript_rs::Result<PathBuf> {
    let path = Path::new(arg);
    if arg.ends_with(".zip") || path.exists() {
        // Model.load parity: an existing path is used directly.
        return Ok(path.to_path_buf());
    }
    // models.yaml id: index (SECRYST_INDEX / default) + cache/download.
    let index = interscript_rs::imf::registry::load_index(None)?;
    interscript_rs::imf::registry::resolve(arg, &index)
}

/// `iscrs conformance <fixture_file_or_dir> [<artifact_dir>]`: load
/// the frozen vectors, resolve each family's artifact, run every row,
/// report byte-exact pass counts. Exit failure on any mismatch.
fn cmd_conformance(rest: &[String]) -> interscript_rs::Result<()> {
    if rest.is_empty() || rest.len() > 2 {
        return Err(interscript_rs::Error::Io(
            "usage: conformance <fixture_file_or_dir> [<artifact_dir>]".into(),
        ));
    }
    let fixture_path = Path::new(&rest[0]);
    let artifact_dir = rest.get(1).map(|d| PathBuf::from(d));

    // One index load shared across families (registry mode).
    let index = if artifact_dir.is_none() {
        Some(interscript_rs::imf::registry::load_index(None)?)
    } else {
        None
    };

    let mut fixture_files: Vec<PathBuf> = Vec::new();
    if fixture_path.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(fixture_path)
            .map_err(|e| interscript_rs::Error::Io(format!("{}: {e}", fixture_path.display())))?
            .filter_map(|e| e.ok().map(|e| e.path()))
            .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("json"))
            .collect();
        entries.sort();
        fixture_files.extend(entries);
    } else {
        fixture_files.push(fixture_path.to_path_buf());
    }

    let mut families = 0usize;
    let mut skipped = 0usize;
    let mut rows_total = 0usize;
    let mut rows_passed = 0usize;
    let mut any_mismatch = false;
    let mut any_skip = false;

    for file in &fixture_files {
        let vectors = match interscript_rs::imf::conformance::Vectors::load(file) {
            Ok(v) => v,
            Err(e) => {
                println!("SKIP {}: {e}", file.display());
                any_skip = true;
                skipped += 1;
                continue;
            }
        };
        let artifact = match interscript_rs::imf::conformance::resolve_artifact(
            &vectors.model,
            artifact_dir.as_deref(),
            index.as_ref(),
        ) {
            Ok(a) => a,
            Err(e) => {
                println!("SKIP {}: {e}", vectors.model);
                any_skip = true;
                skipped += 1;
                continue;
            }
        };
        // C2: the whole artifact is re-verified against the index
        // digest when the index knows the entry.
        if let Some(index) = &index {
            let canonical = index.canonical_id(&vectors.model);
            if let Some(entry) = index.models.get(&canonical) {
                let actual = interscript_rs::imf::loader::sha256_file(&artifact)?;
                if actual != entry.sha256 {
                    println!(
                        "FAIL {}: artifact sha256 mismatch ({} has {actual}, index says {})",
                        vectors.model,
                        artifact.display(),
                        entry.sha256
                    );
                    any_mismatch = true;
                    continue;
                }
            }
        }
        let graphs = interscript_rs::imf::loader::verify_and_read(&artifact)?;
        let mut engine = interscript_rs::imf::infer::OrtEngine::from_graphs(&graphs)?;
        let result = interscript_rs::imf::conformance::run_conformance(&vectors, &mut engine)?;

        let passed = result.checked - result.mismatches.len();
        families += 1;
        rows_total += result.checked;
        rows_passed += passed;
        println!(
            "{}: {passed}/{} byte-exact  (artifact {})",
            vectors.model,
            result.checked,
            artifact.display()
        );
        for m in &result.mismatches {
            println!(
                "  row {} src {:?}\n    expected {:?}\n    got      {:?}",
                m.index, m.src, m.expected, m.got
            );
        }
        if !result.passed() {
            any_mismatch = true;
        }
    }

    println!(
        "conformance: {families} families, {rows_passed}/{rows_total} rows byte-exact{}",
        if any_skip {
            format!(", {skipped} skipped (artifact not resolvable locally)")
        } else {
            String::new()
        }
    );
    if any_mismatch {
        return Err(interscript_rs::Error::Io(
            "conformance reported mismatches above".into(),
        ));
    }
    if any_skip {
        return Err(interscript_rs::Error::Io(
            "conformance incomplete: skipped families above (fetch their artifacts, \
             then re-run)"
                .into(),
        ));
    }
    Ok(())
}

fn collect_isc(path: &Path, out: &mut Vec<PathBuf>) {
    if path.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(path)
            .into_iter()
            .flatten()
            .flatten()
            .map(|e| e.path())
            .collect();
        entries.sort();
        for entry in entries {
            collect_isc(&entry, out);
        }
    } else if path.extension().and_then(|e| e.to_str()) == Some("isc") {
        out.push(path.to_path_buf());
    }
}