hexicon 0.2.0

Hexicon, for writing interactive fiction: builds a game, plays it in a terminal, tests it, documents it, and serves editors
//! `hexicon preprocess` and `hexicon tokens`: what the first stages of
//! the compiler make of a source file.
//!
//! The output of each is in a form the reference compiler can be made to
//! write too, so that the two can be compared. Preprocessed text is as
//! the reference's preprocess-only mode writes it: a `#line` directive
//! wherever the text stops following on from the line before, and
//! otherwise one line of output for each line of source. Tokens are
//! listed one to a line.

use std::io::Write as _;
use std::process::ExitCode;

use hexicon_compiler::pp::{Preprocessor, Severity, SourceFiles};
use hexicon_compiler::{Tok, read_project, with_preprocessor};

/// Source files on disk.
pub(crate) struct DiskFiles;

impl SourceFiles for DiskFiles {
    fn read(&mut self, name: &str) -> Option<Vec<u8>> {
        std::fs::read(name).ok()
    }

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

    // The character sets are the ones programs have, from the VM.
    fn decode(&mut self, charset: &str, bytes: &[u8]) -> Option<Vec<u8>> {
        hexicon_vm::decode_text(charset, bytes).map(String::into_bytes)
    }
}

/// A file name as a string in double quotes.
fn quoted(name: &str) -> String {
    let mut out = String::from('"');
    for c in name.chars() {
        if c == '\\' || c == '"' {
            out.push('\\');
        }
        out.push(c);
    }
    out.push('"');
    out
}

/// What to write.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Output {
    /// The preprocessed text.
    Text,
    /// The tokens.
    Tokens,
}

/// Write the problems found since the last time, in with the output,
/// where they were found, as the reference's test programs do. Returns
/// whether any was an error.
fn report(pp: &mut Preprocessor<'_>, out: &mut impl std::io::Write) -> bool {
    let mut failed = false;
    for problem in pp.take_diagnostics() {
        let kind = match problem.severity {
            Severity::Error => {
                failed = true;
                "error"
            }
            Severity::Fatal => {
                failed = true;
                "fatal error"
            }
            Severity::Internal => {
                failed = true;
                "internal error"
            }
            Severity::Warning => "warning",
            Severity::Message => {
                let _ = writeln!(out, "{}", problem.message);
                continue;
            }
        };
        let _ = writeln!(
            out,
            "{}({}): {kind}: {}",
            problem.file, problem.line, problem.message
        );
    }
    failed
}

pub(crate) fn run(args: &[&str], usage: &str, output: Output) -> ExitCode {
    let mut manifest: Option<&str> = None;
    let mut debug = false;
    let mut test = false;
    // The options, as `hexicon build` takes them too.
    let mut options: Vec<(&str, &str)> = Vec::new();
    let mut rest = args;
    let source = loop {
        match rest {
            ["-f", path, tail @ ..] if manifest.is_none() => {
                manifest = Some(path);
                rest = tail;
            }
            [
                option @ ("-I" | "-D" | "-U" | "--charset"),
                value,
                tail @ ..,
            ] => {
                options.push((option, value));
                rest = tail;
            }
            ["-d", tail @ ..] => {
                debug = true;
                rest = tail;
            }
            ["--test", tail @ ..] => {
                test = true;
                rest = tail;
            }
            [source] if !source.starts_with('-') => break *source,
            _ => {
                eprint!("{usage}");
                return ExitCode::from(2);
            }
        }
    };
    if let Some(manifest) = manifest {
        return run_in_game(manifest, debug, &options, test, source, usage, output);
    }
    // `-d` is for a game's build.
    if debug {
        eprint!("{usage}");
        return ExitCode::from(2);
    }
    let mut files = DiskFiles;
    let mut pp = Preprocessor::new(&mut files);
    for (option, value) in options {
        match option {
            "-I" => pp.add_include_path(value),
            "-D" => match value.split_once('=') {
                Some((name, text)) => pp.define(name, text),
                None => pp.define(value, "1"),
            },
            "-U" => pp.undefine(value),
            _ => pp.set_default_charset(value),
        }
    }
    pp.set_test_report_mode(test);
    if !pp.set_source(source) {
        eprintln!("hexicon: {source}: unable to open source file");
        return ExitCode::FAILURE;
    }
    write(&mut pp, output)
}

/// Preprocess a source as a game's build reads it: with the macros,
/// include paths, character set, and libraries its manifest gives, and
/// the options as `hexicon build` takes them.
fn run_in_game(
    manifest: &str,
    debug: bool,
    options: &[(&str, &str)],
    test: bool,
    source: &str,
    usage: &str,
    output: Output,
) -> ExitCode {
    let mut args: Vec<String> = Vec::new();
    if debug {
        args.push("-d".to_owned());
    }
    for (option, value) in options {
        args.push((*option).to_owned());
        args.push((*value).to_owned());
    }
    args.push("-f".to_owned());
    args.push(manifest.to_owned());
    let project = match read_project(&mut DiskFiles, &args, &crate::build::default_paths()) {
        Ok(project) => project,
        Err(error) => return crate::doc::said(error, usage),
    };
    let sources: Vec<&str> = project.sources.iter().map(String::as_str).collect();
    // The source as the build names it, if it is one of the game's, so
    // that it is not read twice (as an English source would be).
    let canonical = |path: &str| std::fs::canonicalize(path).ok();
    let source = sources
        .iter()
        .find(|s| canonical(s).is_some() && canonical(s) == canonical(source))
        .copied()
        .unwrap_or(source);
    let written = with_preprocessor(&mut DiskFiles, &sources, source, &project.options, |pp| {
        pp.set_test_report_mode(test);
        write(pp, output)
    });
    written.unwrap_or_else(|problem| {
        eprintln!("hexicon: {source}: {}", problem.message);
        ExitCode::FAILURE
    })
}

/// Write what the preprocessor reads, as text or as tokens.
fn write(pp: &mut Preprocessor<'_>, output: Output) -> ExitCode {
    let mut out = std::io::BufWriter::new(std::io::stdout().lock());
    let mut failed = false;
    match output {
        Output::Text => {
            let mut last: Option<(usize, u32)> = None;
            loop {
                let line = pp.next_line();
                failed |= report(pp, &mut out);
                let Some(line) = line else {
                    break;
                };
                let follows =
                    last.is_some_and(|(file, number)| file == line.file && number + 1 == line.line);
                if !follows {
                    let _ = writeln!(
                        out,
                        "#line {} {}",
                        line.line,
                        quoted(pp.file_name(line.file))
                    );
                }
                last = Some((line.file, line.line));
                let _ = out.write_all(&line.text);
                let _ = out.write_all(b"\n");
            }
        }
        Output::Tokens => {
            pp.set_compile_mode();
            loop {
                let typ = pp.next_token();
                failed |= report(pp, &mut out);
                if typ == Tok::Eof {
                    break;
                }
                // The kind's number, a tab, and the text, with anything
                // that is not printable ASCII given as its code.
                let _ = write!(out, "{}\t", typ as u32);
                for &c in &pp.cur_token().text {
                    let _ = match c {
                        b'\\' => out.write_all(b"\\\\"),
                        32..=126 => out.write_all(&[c]),
                        _ => write!(out, "\\x{c:02x}"),
                    };
                }
                let _ = out.write_all(b"\n");
            }
        }
    }
    let _ = out.flush();
    if failed {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}