garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /programs/src/bin/frits.rs

raw

//! The command `frits`: Frits, Pinnacle's scripting language, in the
//! terminal (`jeroen/frits`).
//!
//! - `frits run <script> [words…]` runs a script's `on main()`;
//! - `frits test <script>` runs its `test` blocks;
//! - `frits check <script>` compiles it and says which effects it asks for;
//! - `frits fmt <script>` gives it the one layout every script has;
//! - `frits guide` writes what a script here can call;
//! - `frits` alone reads lines and runs each, keeping what they define.
//!
//! A script is a file (`notes/hello.frits`, on the data disk when no disk
//! is named) or one of the examples that come with it, by name (`hello`).
//! What it can call is `programs/frits/terminal.frits`: its output is
//! records like any command's, so a table is a table and a question a
//! question. Its first line names the effects it uses, and nothing else
//! compiles; that line is what `check` shows before anything runs.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::boxed::Box;
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use frits::bytecode::Module;
use frits::{Cx, HostValue, Level, Pid, Platform, Runtime, Status, Value};
use pinnacle_rt::fs;
use pinnacle_rt::output::{AskKind, Output, Record};

/// What a script run here can call.
const PLATFORM: &str = include_str!("../../frits/terminal.frits");

/// The scripts that come with the command, by name.
const EXAMPLES: &[(&str, &str, &str)] = &[
    (
        "hello",
        "Greets a name, or asks for one",
        include_str!("../../frits/hello.frits"),
    ),
    (
        "todo",
        "A to-do list in a file: add, done",
        include_str!("../../frits/todo.frits"),
    ),
    (
        "countdown",
        "Asks, then counts down with a progress bar",
        include_str!("../../frits/countdown.frits"),
    ),
];

/// Instructions a `test` block may run before it counts as stuck.
const TEST_FUEL: u64 = 10_000_000;

/// What every host function reaches: the terminal, and the words the
/// script was given. Made once and never freed, as the program ends with
/// the script.
struct Shell {
    out: Output,
    args: Vec<String>,
}

type State = &'static Shell;

/// A path without a disk is on the data disk.
fn path(name: &str) -> String {
    if name.contains(':') {
        name.into()
    } else {
        alloc::format!("data:/{}", name.trim_start_matches('/'))
    }
}

fn strings(h: HostValue) -> Vec<String> {
    match h {
        HostValue::List(items) => items
            .into_iter()
            .map(|i| match i {
                HostValue::Str(s) => s,
                _ => String::new(),
            })
            .collect(),
        _ => Vec::new(),
    }
}

fn ok(cx: &mut Cx<State>, v: HostValue) -> Value {
    cx.import(&HostValue::Variant(0, alloc::vec![v]))
}

fn err(cx: &mut Cx<State>, why: String) -> Value {
    cx.import(&HostValue::Variant(1, alloc::vec![HostValue::Str(why)]))
}

/// An answer the script waits for; the script stops when there is no one
/// to ask (started from outside a terminal, or the terminal went).
fn ask(cx: &mut Cx<State>, kind: AskKind, prompt: &str, options: &[&str]) -> Result<String, String> {
    cx.state
        .out
        .ask(kind, prompt, options)
        .ok_or_else(|| "there is no one at a terminal to answer".into())
}

fn platform() -> Platform<State> {
    let mut p: Platform<State> = Platform::new(PLATFORM).expect("the terminal's platform declaration parses");
    p.bind("Console.print", |cx, a| {
        cx.state.out.text(cx.str(a[0]));
        Ok(Value::Unit)
    });
    p.bind("Console.table", |cx, a| {
        let columns = strings(cx.export(a[0]));
        let rows = match cx.export(a[1]) {
            HostValue::List(rows) => rows.into_iter().map(strings).collect(),
            _ => Vec::new(),
        };
        cx.charge(rows.iter().map(Vec::len).sum::<usize>() as u64);
        cx.state.out.send(&Record::Table { columns, rows });
        Ok(Value::Unit)
    });
    p.bind("Console.progress", |cx, a| {
        let label = cx.str(a[2]).into();
        cx.state.out.send(&Record::Progress {
            id: 1,
            done: a[0].int().max(0) as u64,
            total: a[1].int().max(0) as u64,
            label,
        });
        Ok(Value::Unit)
    });
    p.bind("Console.ask", |cx, a| {
        let prompt = String::from(cx.str(a[0]));
        let answer = ask(cx, AskKind::Text, &prompt, &[])?;
        Ok(cx.new_str(&answer))
    });
    p.bind("Console.choose", |cx, a| {
        let prompt = String::from(cx.str(a[0]));
        let options = strings(cx.export(a[1]));
        if options.is_empty() {
            return Err("`Console.choose` was given no options".into());
        }
        let options: Vec<&str> = options.iter().map(String::as_str).collect();
        let answer = ask(cx, AskKind::Choice, &prompt, &options)?;
        Ok(cx.new_str(&answer))
    });
    p.bind("Console.confirm", |cx, a| {
        let prompt = String::from(cx.str(a[0]));
        Ok(Value::Bool(ask(cx, AskKind::YesNo, &prompt, &[])? == "Yes"))
    });
    p.bind("Console.args", |cx, _| {
        let words = cx.state.args.iter().map(|w| HostValue::Str(w.clone())).collect();
        Ok(cx.import(&HostValue::List(words)))
    });
    p.bind("Files.read", |cx, a| {
        let at = path(cx.str(a[0]));
        Ok(match fs::read(&at).map(String::from_utf8) {
            Some(Ok(text)) => {
                cx.charge(text.len() as u64 / 64);
                ok(cx, HostValue::Str(text))
            }
            Some(Err(_)) => err(cx, alloc::format!("{at} is not text")),
            None => err(cx, alloc::format!("there is no file {at}")),
        })
    });
    p.bind("Files.write", |cx, a| {
        let at = path(cx.str(a[0]));
        let written = fs::write(&at, cx.str(a[1]).as_bytes());
        Ok(if written {
            ok(cx, HostValue::Unit)
        } else {
            err(cx, alloc::format!("{at} could not be written"))
        })
    });
    p.bind("Files.append", |cx, a| {
        let at = path(cx.str(a[0]));
        let mut text = fs::read(&at).unwrap_or_default();
        text.extend_from_slice(cx.str(a[1]).as_bytes());
        Ok(if fs::write(&at, &text) {
            ok(cx, HostValue::Unit)
        } else {
            err(cx, alloc::format!("{at} could not be written"))
        })
    });
    p.bind("Files.list", |cx, a| {
        let at = path(cx.str(a[0]));
        Ok(match fs::list(&at) {
            Some(names) => ok(
                cx,
                HostValue::List(names.into_iter().map(HostValue::Str).collect()),
            ),
            None => err(cx, alloc::format!("there is no folder {at}")),
        })
    });
    p.bind("Files.exists", |cx, a| {
        Ok(Value::Bool(fs::exists(&path(cx.str(a[0])))))
    });
    p.bind("Files.remove", |cx, a| {
        let at = path(cx.str(a[0]));
        Ok(if fs::remove(&at) {
            ok(cx, HostValue::Unit)
        } else {
            err(cx, alloc::format!("{at} could not be removed"))
        })
    });
    p.bind("Clock.now", |_, _| Ok(Value::Int(pinnacle_rt::clock() as i64)));
    p.bind("Clock.uptime", |_, _| Ok(Value::Int(pinnacle_rt::time() as i64)));
    p.bind("Clock.wait", |_, a| {
        let seconds = a[0].float();
        if seconds > 0.0 {
            pinnacle_rt::sleep((seconds * 1000.0) as u64);
        }
        Ok(Value::Unit)
    });
    p.bind("Net.get", |cx, a| {
        let url = String::from(cx.str(a[0]));
        Ok(match pinnacle_rt::net::http_get(&url, 10_000) {
            Ok(body) => match String::from_utf8(body) {
                Ok(text) => ok(cx, HostValue::Str(text)),
                Err(_) => err(cx, alloc::format!("{url} did not answer with text")),
            },
            Err(e) => err(cx, alloc::format!("{url}: {e:?}")),
        })
    });
    p
}

#[unsafe(no_mangle)]
fn main(argument: u64) -> u64 {
    if argument == pinnacle_rt::abi::FRITS_CHECK {
        return self_check();
    }
    let out = Output::start(argument);
    let words: Vec<String> = out.args.iter().skip(1).cloned().collect();
    let verb = words.first().map(String::as_str);
    match verb {
        None => {
            let shell: State = Box::leak(Box::new(Shell { out, args: Vec::new() }));
            repl(shell)
        }
        Some("guide") => match frits::guide::guide("Pinnacle's terminal", PLATFORM) {
            Ok(guide) => {
                out.text(&guide);
                out.status(0, "")
            }
            Err(e) => out.status(1, &alloc::format!("the platform: {e}")),
        },
        Some("examples") => {
            out.table(
                &["Example", "What it does"],
                EXAMPLES
                    .iter()
                    .map(|(name, about, _)| alloc::vec![String::from(*name), String::from(*about)])
                    .collect(),
            );
            out.status(0, "frits run <example>, or frits show <example> for its text")
        }
        Some(verb @ ("run" | "test" | "check" | "fmt" | "show")) => {
            let Some(name) = words.get(1) else {
                return out.status(2, &alloc::format!("frits {verb} <script>: which script?"));
            };
            let Some((at, source)) = script(name) else {
                return out.status(
                    2,
                    &alloc::format!("There is no script {name}: give a file, or an example (frits examples)"),
                );
            };
            let args = words[2..].to_vec();
            let shell: State = Box::leak(Box::new(Shell { out, args }));
            match verb {
                "show" => {
                    shell.out.text(&source);
                    shell.out.status(0, "")
                }
                "fmt" => format(shell, &at, &source),
                _ => compiled(shell, verb, &at, &source),
            }
        }
        Some(other) => out.status(
            2,
            &alloc::format!("frits has no “{other}”: run, test, check, fmt, show, guide, examples, or nothing to type lines"),
        ),
    }
}

/// The script `name` names, and where it is: a bare name is an example,
/// anything else a file (so `todo` is the example even beside a file
/// `todo`, which may be what a script keeps).
fn script(name: &str) -> Option<(String, String)> {
    let example = EXAMPLES
        .iter()
        .find(|(n, _, _)| *n == name)
        .map(|(n, _, text)| (alloc::format!("{n}.frits"), String::from(*text)));
    if example.is_some() {
        return example;
    }
    let at = path(name);
    String::from_utf8(fs::read(&at)?).ok().map(|text| (at, text))
}

/// `frits fmt`: a file is formatted in place, an example only shown.
fn format(shell: State, at: &str, source: &str) -> u64 {
    let formatted = frits::fmt::format(source);
    if formatted == source {
        return shell.out.status(0, &alloc::format!("{at} was already formatted"));
    }
    if !at.contains(':') {
        shell.out.text(&formatted);
        return shell
            .out
            .status(0, "An example is not changed: this is how it would be");
    }
    if fs::write(at, formatted.as_bytes()) {
        shell.out.status(0, &alloc::format!("{at} formatted"))
    } else {
        shell.out.status(1, &alloc::format!("{at} could not be written"))
    }
}

/// Compiles `source`, or sends its errors with their lines.
fn compile(shell: State, rt: &Runtime<State>, at: &str, source: &str) -> Option<Rc<Module>> {
    match rt.platform.compile(source) {
        Ok(module) => Some(module),
        Err(errors) => {
            let rows = errors
                .iter()
                .map(|e| alloc::vec![e.line.to_string(), e.msg.clone()])
                .collect();
            shell.out.send(&Record::Table {
                columns: alloc::vec!["Line".into(), alloc::format!("What is wrong in {at}")],
                rows,
            });
            None
        }
    }
}

/// `run`, `test` and `check`: each needs the script compiled.
fn compiled(shell: State, verb: &str, at: &str, source: &str) -> u64 {
    let mut rt = Runtime::new(platform());
    let Some(module) = compile(shell, &rt, at, source) else {
        return shell.out.status(1, "It does not compile");
    };
    match verb {
        "check" => {
            let effects = if module.effects.is_empty() {
                "none: it only computes".into()
            } else {
                module.effects.join(", ")
            };
            shell.out.table(
                &["", ""],
                alloc::vec![
                    alloc::vec!["Effects".into(), effects],
                    alloc::vec!["Runs on".into(), handlers(&module)],
                    alloc::vec!["Tests".into(), module.tests.len().to_string()],
                ],
            );
            shell.out.status(0, &alloc::format!("{at} compiles"))
        }
        "test" => {
            let results = rt.test(&module, || shell, TEST_FUEL);
            let failed = results.iter().filter(|r| r.failure.is_some()).count();
            shell.out.table(
                &["Test", "How it went"],
                results
                    .iter()
                    .map(|r| {
                        let how = match &r.failure {
                            None => "passed".into(),
                            Some(why) => alloc::format!("failed: {why}"),
                        };
                        alloc::vec![r.name.clone(), how]
                    })
                    .collect(),
            );
            let summary = alloc::format!("{} passed, {failed} failed", results.len() - failed);
            shell.out.status(u64::from(failed > 0), &summary)
        }
        _ => {
            if module.handler("main").is_none() {
                return shell
                    .out
                    .status(1, &alloc::format!("{at} has no `on main()` to run"));
            }
            match run(shell, &mut rt, module) {
                Ok(_) => shell.out.status(0, ""),
                Err(why) => shell.out.status(1, &why),
            }
        }
    }
}

fn handlers(module: &Module) -> String {
    let names: Vec<String> = module
        .handlers
        .iter()
        .map(|(n, _)| alloc::format!("{n}()"))
        .collect();
    if names.is_empty() {
        "nothing".into()
    } else {
        names.join(", ")
    }
}

/// Runs `module`'s `on main()` to its end, its log lines sent as text; the
/// process stays in `rt`, for what it kept.
fn run(shell: State, rt: &mut Runtime<State>, module: Rc<Module>) -> Result<Pid, String> {
    let pid = rt.spawn(module, shell);
    rt.post(pid, "main", Vec::new());
    loop {
        let died = rt.tick();
        if let Some(p) = rt.get_mut(pid) {
            for line in p.take_log() {
                let what = if line.level == Level::Warn {
                    "warning"
                } else {
                    "log"
                };
                shell
                    .out
                    .text(&alloc::format!("line {}, {what}: {}", line.line, line.text));
            }
        }
        if let Some((_, why)) = died.into_iter().next() {
            return Err(why);
        }
        match rt.get(pid).map(|p| (&p.status, p.has_work())) {
            Some((Status::Idle, false)) | None => return Ok(pid),
            _ => {}
        }
    }
}

/// The effects a line typed at the prompt may use: all of them, as the
/// person typing it is the one it acts for.
const REPL_HEADER: &str = "script / Console, Files, Clock, Net\n";

/// The words that begin a definition, which later lines can use.
const DEFINES: &[&str] = &["fn ", "let ", "var ", "type ", "enum ", "import "];

/// `frits` alone: reads a line at a time and runs it. A definition (`fn`,
/// `let`, `type`…) is kept for the lines after it; an expression's value is
/// shown with its type; anything else runs as a statement. Each line runs
/// in a new process, so a `var` a statement changes starts from its
/// definition again on the next line.
fn repl(shell: State) -> u64 {
    shell.out.text(
        "Frits: type a line to run it. fn, let, var, type and enum lines are kept for the lines after; \
         an empty line ends.",
    );
    let mut definitions = String::new();
    let mut lines = 0;
    while let Some(line) = shell.out.ask(AskKind::Text, "frits>", &[]) {
        let line = line.trim();
        if line.is_empty() || line == "exit" {
            break;
        }
        lines += 1;
        let mut rt = Runtime::new(platform());
        if DEFINES.iter().any(|d| line.starts_with(d)) {
            let kept = alloc::format!("{definitions}{line}\n");
            match rt.platform.compile(&alloc::format!("{REPL_HEADER}{kept}")) {
                Ok(_) => definitions = kept,
                Err(errors) => wrong(shell, &errors),
            }
            continue;
        }
        // An expression first: a kept global, which the host reads back
        // with its type, whatever the type is. Then a statement.
        let shown = alloc::format!("{REPL_HEADER}{definitions}keep var it = ({line})\non main() {{}}\n");
        let statement = alloc::format!("{REPL_HEADER}{definitions}on main() {{\n{line}\n}}\n");
        let module = match rt.platform.compile(&shown) {
            Ok(m) => m,
            Err(_) => match rt.platform.compile(&statement) {
                Ok(m) => m,
                Err(errors) => {
                    wrong(shell, &errors);
                    continue;
                }
            },
        };
        match run(shell, &mut rt, module) {
            Ok(pid) => {
                let kept = rt.get(pid).map(|p| p.kept()).unwrap_or_default();
                if let Some((_, ty, value)) = kept.into_iter().next()
                    && ty != "Unit"
                {
                    shell
                        .out
                        .text(&alloc::format!("{} : {ty}", shown_value(&value, &ty, true)));
                }
            }
            Err(why) => {
                shell.out.text(&alloc::format!("It stopped: {why}"));
            }
        }
    }
    shell.out.status(0, &alloc::format!("{lines} lines run"))
}

/// A value as a line typed at the prompt shows it. Records and enums cross
/// without their names, so an `Option` or a `Result` is named from its
/// type, and other variants by number.
fn shown_value(v: &HostValue, ty: &str, top: bool) -> String {
    let all = |items: &[HostValue]| {
        items
            .iter()
            .map(|i| shown_value(i, "", false))
            .collect::<Vec<_>>()
            .join(", ")
    };
    match v {
        HostValue::Unit => "()".into(),
        HostValue::Bool(b) => b.to_string(),
        HostValue::Int(i) => i.to_string(),
        HostValue::Float(f) => alloc::format!("{f:?}"),
        HostValue::Str(s) if top => s.clone(),
        HostValue::Str(s) => alloc::format!("\"{s}\""),
        HostValue::List(items) => alloc::format!("[{}]", all(items)),
        HostValue::Record(fields) => alloc::format!("{{ {} }}", all(fields)),
        HostValue::Map(pairs) => {
            let pairs: Vec<String> = pairs
                .iter()
                .map(|(k, v)| alloc::format!("{}: {}", shown_value(k, "", false), shown_value(v, "", false)))
                .collect();
            alloc::format!("{{ {} }}", pairs.join(", "))
        }
        HostValue::Tag(0) if ty.starts_with("Option") => "None".into(),
        HostValue::Tag(t) => alloc::format!("#{t}"),
        HostValue::Variant(t, args) => {
            let name = match (ty.split('<').next(), t) {
                (Some("Option"), 1) => "Some".into(),
                (Some("Result"), 0) => "Ok".into(),
                (Some("Result"), 1) => "Err".into(),
                _ => alloc::format!("#{t}"),
            };
            alloc::format!("{name}({})", all(args))
        }
    }
}

/// A typed line's errors, without lines: there is only the one.
fn wrong(shell: State, errors: &[frits::Error]) {
    let text: Vec<&str> = errors.iter().map(|e| e.msg.as_str()).collect();
    shell.out.text(&text.join("\n"));
}

/// The kernel's self-check (`abi::FRITS_CHECK`), on the console: every
/// example compiles against the platform and passes its tests, the
/// formatter leaves them as they are, and a script runs and computes.
fn self_check() -> u64 {
    let shell: State = Box::leak(Box::new(Shell {
        out: Output::start(0),
        args: alloc::vec!["Pinnacle".into()],
    }));
    let mut rt = Runtime::new(platform());
    let mut tests = 0;
    for (name, _, source) in EXAMPLES {
        let Ok(module) = rt.platform.compile(source) else {
            pinnacle_rt::println!("frits: the example {name} does not compile");
            return 1;
        };
        for result in rt.test(&module, || shell, TEST_FUEL) {
            if let Some(why) = result.failure {
                pinnacle_rt::println!("frits: {name}'s test “{}” failed: {why}", result.name);
                return 1;
            }
            tests += 1;
        }
        if frits::fmt::format(source) != *source {
            pinnacle_rt::println!("frits: the example {name} is not formatted");
            return 1;
        }
    }
    let Some((_, hello)) = script("hello") else {
        return 1;
    };
    let module = rt.platform.compile(&hello).expect("checked above");
    if let Err(why) = run(shell, &mut rt, module) {
        pinnacle_rt::println!("frits: hello stopped: {why}");
        return 1;
    }
    pinnacle_rt::println!("frits: {} examples compile, {tests} tests pass", EXAMPLES.len());
    0
}