use std::io::Write as _;
use std::process::ExitCode;
use hexicon_compiler::pp::{Preprocessor, Severity, SourceFiles};
use hexicon_compiler::{Tok, read_project, with_preprocessor};
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()
}
fn decode(&mut self, charset: &str, bytes: &[u8]) -> Option<Vec<u8>> {
hexicon_vm::decode_text(charset, bytes).map(String::into_bytes)
}
}
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
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Output {
Text,
Tokens,
}
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;
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);
}
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)
}
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();
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
})
}
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;
}
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
}
}