miruscriptx 1.12.0

MiruScriptX: a complete, general-purpose scripting language written from scratch in Rust.
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
//! The `miru` command line interface: run a file or start the REPL.

mod keyboard;
mod repl;
mod screen;

use std::process::ExitCode;

const USAGE: &str = "\
Usage:
  miru run <file.miru>      Run a MiruScriptX program from a file
  miru -e <program>         Evaluate a program supplied on the command line
  miru --eval <program>     Evaluate a program supplied on the command line
  miru fmt <file.miru>      Format a program and print it to standard output
  miru fmt -w <file.miru>   Format a program and rewrite the file in place
  miru migrate <file.miru>  Report what version 2.0 changes about a program
  miru migrate -w <file>    Rename what it can, and report the rest
  miru disasm <file.miru>   Show the bytecode a program compiles to
  miru                      Start the interactive REPL
  miru repl                 Start the interactive REPL
  miru --version            Print the version and exit
  miru --help               Show this help and exit";

/// The stack the interpreter runs on.
///
/// The interpreter walks its own structures by recursion. The parser descends
/// through nested source, and the compiler, the formatter, and the destructor
/// each walk the tree it built. So how deeply a program may nest is decided by
/// how much stack this program has, and the default is not the same everywhere:
/// a main thread usually gets 8 MiB, a spawned thread 2 MiB, and neither number
/// is promised.
///
/// Choosing the stack here turns that around. The limit in [`miruscriptx::
/// parser::Parser::MAX_NESTING`] is then set from a figure this program
/// controls, rather than inherited from whatever the operating system happened
/// to hand out. A language should not have a different grammar on a thread.
const STACK_SIZE: usize = 64 * 1024 * 1024;

fn main() -> ExitCode {
    match std::thread::Builder::new()
        .name("miru".to_string())
        .stack_size(STACK_SIZE)
        .spawn(dispatch)
    {
        Ok(handle) => match handle.join() {
            Ok(code) => code,
            // The thread panicked. Its message has already gone to stderr
            // through the default hook, so there is nothing to add here.
            Err(_) => ExitCode::FAILURE,
        },
        // A system that refuses to start a thread can still run a program, with
        // whatever stack the main thread has. Less room is a better answer than
        // not running at all.
        Err(_) => dispatch(),
    }
}

fn dispatch() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match args.split_first() {
        None => repl::run(),
        Some((command, rest)) => match command.as_str() {
            "run" => run_file(rest),
            "-e" | "--eval" => eval_source(rest),
            "fmt" => fmt_file(rest),
            "migrate" => migrate_file(rest),
            "disasm" => disasm_file(rest),
            "repl" => {
                if rest.is_empty() {
                    repl::run()
                } else {
                    usage_error("the 'repl' command takes no arguments")
                }
            }
            "--version" | "-v" => {
                println!("miru {}", miruscriptx::VERSION);
                ExitCode::SUCCESS
            }
            "--help" | "-h" => {
                println!("MiruScriptX {}", miruscriptx::VERSION);
                println!();
                println!("{USAGE}");
                ExitCode::SUCCESS
            }
            other => usage_error(&format!("unknown command '{other}'")),
        },
    }
}

/// The real file system, which only this program hands out.
///
/// The library grants nothing by default, so a program run through
/// `miruscriptx` as a crate, or in the playground, cannot touch a file unless
/// its host says so. This is that host saying so.
///
/// A relative path resolves against the working directory, which is what
/// `std::fs` already does and what every other command line tool does.
/// `import` is the exception rather than this: a module is part of the program
/// and is found beside it, while a data file is wherever the person running the
/// program is standing. Section 8 of the specification states both rules
/// together, because meeting the second one by surprise is the way to be
/// confused by it.
struct RealSystem {
    /// What the program was given, which is everything after its own path.
    arguments: Vec<String>,
}

impl miruscriptx::value::System for RealSystem {
    fn read_file(&mut self, path: &str) -> Result<String, String> {
        std::fs::read_to_string(path).map_err(|err| format!("cannot read '{path}': {err}"))
    }

    fn write_file(&mut self, path: &str, contents: &str) -> Result<(), String> {
        std::fs::write(path, contents).map_err(|err| format!("cannot write '{path}': {err}"))
    }

    fn file_exists(&mut self, path: &str) -> bool {
        std::path::Path::new(path).is_file()
    }

    fn arguments(&self) -> Vec<String> {
        self.arguments.clone()
    }
}

/// The clock `miru` gives a program, which `now` reads.
///
/// `SystemTime` rather than `Instant`, because a program that asks for the time
/// wants the time and not an interval from an unnamed origin. The conversion
/// cannot lose a millisecond that matters: `as i64` from the `u128` of
/// milliseconds since the epoch is exact until the year 292278994.
///
/// A clock before the epoch gives an error rather than a negative number. It
/// means the host is set to a date in the 1960s, which a program cannot do
/// anything sensible with, and saying so is better than handing back a time
/// that arithmetic will quietly turn into nonsense.
struct RealClock;

impl miruscriptx::value::Clock for RealClock {
    fn now_millis(&mut self) -> Result<i64, String> {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|since| since.as_millis() as i64)
            .map_err(|_| "the host's clock is set before 1970".to_string())
    }

    /// The whole thread, because the whole program is this one thread. There is
    /// nothing else waiting to run, so there is nothing to yield to.
    fn sleep_millis(&mut self, millis: u64) -> Result<(), String> {
        std::thread::sleep(std::time::Duration::from_millis(millis));
        Ok(())
    }
}

/// Everything `miru` gives a program: the file system it was asked for, plus
/// the clock and the keyboard, which are the same for every run.
fn host(system: Box<RealSystem>) -> miruscriptx::Host {
    miruscriptx::Host {
        system,
        clock: Box::new(RealClock),
        keyboard: Box::new(keyboard::RealKeyboard::new()),
        screen: Box::new(screen::RealScreen::new()),
    }
}

fn eval_source(args: &[String]) -> ExitCode {
    let Some((source, rest)) = args.split_first() else {
        return usage_error("the '-e' command needs a program");
    };
    // As with `run`, everything after the program is the program's own.
    let system = Box::new(RealSystem {
        arguments: rest.to_vec(),
    });

    match miruscriptx::run_source(source, Box::new(std::io::stdout()), host(system)) {
        // `ExitCode` rather than `std::process::exit`, so the code still
        // travels back through the join from the interpreter's own thread and
        // every destructor on the way still runs. The cast is exact: `exit`
        // refuses anything outside 0 through 255.
        Ok(code) => ExitCode::from(code as u8),
        Err(errors) => report(&errors, source),
    }
}

/// Print every error a run produced, and give back the failing code.
///
/// One error prints exactly as it always did. Several print the same way, one
/// after another, with a count at the end so the reader knows the list is
/// complete rather than cut off by their terminal. Only a syntax error can be
/// more than one: a run stops at the first thing that goes wrong.
fn report(errors: &[miruscriptx::MiruError], source: &str) -> ExitCode {
    for error in errors {
        eprintln!("miru: {}", error.render(source));
    }
    if errors.len() > 1 {
        eprintln!("miru: {} errors", errors.len());
    }
    ExitCode::FAILURE
}

fn run_file(args: &[String]) -> ExitCode {
    // Everything up to the file path belongs to `miru`. Everything after it
    // belongs to the program, verbatim, including anything that looks like an
    // option: `miru run tool.miru --verbose` gives `--verbose` to `tool.miru`.
    // That is the usual convention, and without it a program could never be
    // given a flag of its own.
    //
    // Refusing an unknown option is therefore only possible before the path is
    // seen. After it there is nothing to refuse, because nothing after it is
    // addressed to `miru`.
    let mut path: Option<&str> = None;
    let mut arguments: Vec<String> = Vec::new();
    for arg in args {
        if path.is_some() {
            arguments.push(arg.clone());
            continue;
        }
        match arg.as_str() {
            // Accepted and ignored: v0.4 offered --vm to opt into the bytecode
            // engine, which is now the only one, so commands written then keep
            // working rather than failing on an unknown option.
            "--vm" => {}
            other if other.starts_with("--") => {
                return usage_error(&format!("unknown option '{other}' for 'run'"));
            }
            other => path = Some(other),
        }
    }

    let Some(path) = path else {
        return usage_error("the 'run' command needs a file path");
    };

    let source = match std::fs::read_to_string(path) {
        Ok(source) => source,
        Err(err) => {
            eprintln!("miru: cannot read '{path}': {err}");
            return ExitCode::FAILURE;
        }
    };

    let out = Box::new(std::io::stdout());
    let system = Box::new(RealSystem { arguments });
    match miruscriptx::run_source_from(&source, Some(std::path::Path::new(path)), out, host(system))
    {
        Ok(code) => ExitCode::from(code as u8),
        Err(errors) => report(&errors, &source),
    }
}

fn fmt_file(args: &[String]) -> ExitCode {
    let mut write = false;
    let mut path: Option<&str> = None;
    for arg in args {
        match arg.as_str() {
            "--write" | "-w" => write = true,
            other if other.starts_with('-') => {
                return usage_error(&format!("unknown option '{other}' for 'fmt'"));
            }
            other => {
                if path.is_some() {
                    return usage_error("the 'fmt' command takes a single file path");
                }
                path = Some(other);
            }
        }
    }

    let Some(path) = path else {
        return usage_error("the 'fmt' command needs a file path");
    };

    let source = match std::fs::read_to_string(path) {
        Ok(source) => source,
        Err(err) => {
            eprintln!("miru: cannot read '{path}': {err}");
            return ExitCode::FAILURE;
        }
    };

    let formatted = match miruscriptx::format_source(&source) {
        Ok(formatted) => formatted,
        Err(err) => {
            eprintln!("miru: {}", err.render(&source));
            return ExitCode::FAILURE;
        }
    };

    if write {
        match std::fs::write(path, &formatted) {
            Ok(()) => ExitCode::SUCCESS,
            Err(err) => {
                eprintln!("miru: cannot write '{path}': {err}");
                ExitCode::FAILURE
            }
        }
    } else {
        print!("{formatted}");
        ExitCode::SUCCESS
    }
}

/// `miru migrate`, the off-ramp to version 2.0.
///
/// Reports by default and rewrites only with `-w`, the same way `fmt` does.
/// The report is the part that matters: a rename is something the tool can
/// finish, and the notes are the part it deliberately will not touch.
fn migrate_file(args: &[String]) -> ExitCode {
    let mut write = false;
    let mut path: Option<&str> = None;
    for arg in args {
        match arg.as_str() {
            "--write" | "-w" => write = true,
            other if other.starts_with('-') => {
                return usage_error(&format!("unknown option '{other}' for 'migrate'"));
            }
            other => {
                if path.is_some() {
                    return usage_error("the 'migrate' command takes a single file path");
                }
                path = Some(other);
            }
        }
    }

    let Some(path) = path else {
        return usage_error("the 'migrate' command needs a file path");
    };

    let source = match std::fs::read_to_string(path) {
        Ok(source) => source,
        Err(err) => {
            eprintln!("miru: cannot read '{path}': {err}");
            return ExitCode::FAILURE;
        }
    };

    let migration = match miruscriptx::migrate::migrate(&source) {
        Ok(migration) => migration,
        Err(err) => {
            eprintln!("miru: {}", err.render(&source));
            return ExitCode::FAILURE;
        }
    };

    if migration.is_empty() {
        println!("{path}: nothing to change for version 2.0");
        return ExitCode::SUCCESS;
    }

    if !migration.renames.is_empty() {
        let count = migration.renames.len();
        if write {
            if let Err(err) = std::fs::write(path, &migration.source) {
                eprintln!("miru: cannot write '{path}': {err}");
                return ExitCode::FAILURE;
            }
            println!("{path}: renamed {}", plural(count, "name", "names"));
        } else {
            println!(
                "{path}: {} version 2.0 reserves. Run 'miru migrate -w {path}' to rename them.",
                plural(count, "name that", "names that")
            );
        }
        for rename in &migration.renames {
            println!(
                "  {} -> {}   {}",
                rename.from,
                rename.to,
                lines_phrase(&rename.lines)
            );
        }
    }

    if !migration.notes.is_empty() {
        if !migration.renames.is_empty() {
            println!();
        }
        println!(
            "{path}: {} version 2.0 gives a different meaning. No tool can decide these.",
            plural(migration.notes.len(), "place where", "places where")
        );
        for note in &migration.notes {
            println!("  line {}: {}", note.line, note.message);
        }
    }

    ExitCode::SUCCESS
}

/// "1 name" or "3 names", with the caller supplying both spellings so the rule
/// lives in one place rather than in every message that counts something.
fn plural(count: usize, one: &str, many: &str) -> String {
    if count == 1 {
        format!("{count} {one}")
    } else {
        format!("{count} {many}")
    }
}

/// "line 4" or "lines 4, 9, 17".
fn lines_phrase(lines: &[usize]) -> String {
    let numbers: Vec<String> = lines.iter().map(|line| line.to_string()).collect();
    if lines.len() == 1 {
        format!("line {}", numbers[0])
    } else {
        format!("lines {}", numbers.join(", "))
    }
}

fn disasm_file(args: &[String]) -> ExitCode {
    let path = match args {
        [path] if !path.starts_with('-') => path,
        [] => return usage_error("the 'disasm' command needs a file path"),
        [other] => return usage_error(&format!("unknown option '{other}' for 'disasm'")),
        _ => return usage_error("the 'disasm' command takes a single file path"),
    };

    let source = match std::fs::read_to_string(path) {
        Ok(source) => source,
        Err(err) => {
            eprintln!("miru: cannot read '{path}': {err}");
            return ExitCode::FAILURE;
        }
    };

    match miruscriptx::disassemble_source(&source) {
        Ok(listing) => {
            print!("{listing}");
            ExitCode::SUCCESS
        }
        Err(err) => {
            eprintln!("miru: {}", err.render(&source));
            ExitCode::FAILURE
        }
    }
}

fn usage_error(message: &str) -> ExitCode {
    eprintln!("miru: {message}");
    eprintln!();
    eprintln!("{USAGE}");
    ExitCode::FAILURE
}