use std::process::ExitCode;
const STACK_SIZE: usize = 512 * 1024 * 1024;
fn main() -> ExitCode {
std::thread::Builder::new()
.stack_size(STACK_SIZE)
.spawn(run)
.and_then(|h| {
h.join()
.map_err(|_| std::io::Error::other("interpreter thread panicked"))
})
.unwrap_or_else(|e| fail(&e.to_string()))
}
fn run() -> ExitCode {
let cli = rlang::cli::parse();
if cli.lsp {
return match rlang::lsp::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e),
};
}
if cli.dap {
return match rlang::dap::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e),
};
}
if let Some(src) = cli.eval {
return run_source(&src);
}
if let Some(file) = cli.file.clone() {
if cli.dump_tokens || cli.dump_ast || cli.disasm {
return match dump(&file, &cli) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e),
};
}
if cli.tiers {
return match std::fs::read_to_string(&file)
.map_err(|e| format!("cannot read {file}: {e}"))
.and_then(|src| rlang::tiers::report(&src))
{
Ok(r) => {
println!("{r}");
ExitCode::SUCCESS
}
Err(e) => fail(&e),
};
}
if cli.aot {
let out = cli
.output
.clone()
.map(std::path::PathBuf::from)
.unwrap_or_else(|| std::path::Path::new(&file).with_extension("fvm"));
return match rlang::aot::compile_executable(&file, &out) {
Ok(p) => {
println!("{}", p.display());
ExitCode::SUCCESS
}
Err(e) => fail(&e),
};
}
if cli.build {
return match rlang::aot::build(&file) {
Ok(msg) => {
println!("{msg}");
ExitCode::SUCCESS
}
Err(e) => fail(&e),
};
}
return match std::fs::read_to_string(&file) {
Ok(src) => eval_with_cran_fallback(&src, || rlang::eval_str(&src)),
Err(e) => fail(&format!("cannot read {file}: {e}")),
};
}
if cli.repl || atty_stdin() {
rlang::repl::run();
return ExitCode::SUCCESS;
}
let src = std::io::read_to_string(std::io::stdin()).unwrap_or_default();
run_source(&src)
}
fn run_source(src: &str) -> ExitCode {
eval_with_cran_fallback(src, || rlang::eval_str(src))
}
fn eval_with_cran_fallback(
src: &str,
run: impl FnOnce() -> Result<rlang::Value, String>,
) -> ExitCode {
let (result, captured, diagnostics) = capture_stdout(run);
match result {
Ok(_) => {
replay(&captured, &diagnostics);
ExitCode::SUCCESS
}
Err(e) if e == rlang::host::RESTART_UNWIND => {
replay(&captured, &diagnostics);
rlang::host::flush_warnings(false);
ExitCode::FAILURE
}
Err(e) => {
#[cfg(not(target_arch = "wasm32"))]
if rlang::rembed::available() {
use rlang::rembed::ScriptFailure;
return match rlang::rembed::run_script(src) {
Ok(()) => ExitCode::SUCCESS,
Err(ScriptFailure::RError(msg)) => {
eprint!("{msg}");
eprintln!("Execution halted");
ExitCode::FAILURE
}
Err(ScriptFailure::Unavailable(msg)) => fail(&msg),
};
}
replay(&captured, &diagnostics);
r_error(&e);
rlang::host::flush_warnings(true);
eprintln!("Execution halted");
ExitCode::FAILURE
}
}
}
type Diagnostics = std::rc::Rc<std::cell::RefCell<Vec<(usize, String)>>>;
fn capture_stdout<R>(f: impl FnOnce() -> R) -> (R, Vec<u8>, Vec<(usize, String)>) {
use std::io::{Read, Seek, Write};
use std::os::unix::io::AsRawFd;
let path = std::env::temp_dir().join(format!("rlang-cap-{}.out", std::process::id()));
let Ok(file) = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(&path)
else {
return (f(), Vec::new(), Vec::new());
};
let diagnostics: Diagnostics = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let sink = diagnostics.clone();
rlang::host::set_stderr_hook(Box::new(move |s: &str| {
let _ = std::io::stdout().flush();
let at = unsafe { libc::lseek(1, 0, libc::SEEK_CUR) };
sink.borrow_mut().push((at.max(0) as usize, s.to_string()));
}));
let (r, mut file) = unsafe {
let saved = libc::dup(1);
libc::dup2(file.as_raw_fd(), 1);
let r = f();
let _ = std::io::stdout().flush();
libc::dup2(saved, 1);
libc::close(saved);
(r, file)
};
rlang::host::clear_stderr_hook();
let mut buf = Vec::new();
let _ = file.seek(std::io::SeekFrom::Start(0));
let _ = file.read_to_end(&mut buf);
let _ = std::fs::remove_file(&path);
let events = diagnostics.borrow().clone();
(r, buf, events)
}
fn replay(out: &[u8], diagnostics: &[(usize, String)]) {
use std::io::Write;
let mut stdout = std::io::stdout();
let mut at = 0usize;
for (offset, text) in diagnostics {
let upto = (*offset).min(out.len());
if upto > at {
let _ = stdout.write_all(&out[at..upto]);
at = upto;
}
let _ = stdout.flush();
eprint!("{text}");
}
let _ = stdout.write_all(&out[at..]);
let _ = stdout.flush();
}
fn dump(file: &str, cli: &rlang::cli::Cli) -> Result<(), String> {
let src = std::fs::read_to_string(file).map_err(|e| format!("cannot read {file}: {e}"))?;
if cli.dump_tokens {
for t in rlang::lexer::lex(&src)? {
println!("{:>5} {:?}", t.line, t.tok);
}
}
if cli.dump_ast {
for e in rlang::parser::parse(&src)? {
println!("{e:#?}");
}
}
if cli.disasm {
let prog = rlang::compile(&src)?;
print!("{}", rlang::disasm(&prog));
}
Ok(())
}
fn atty_stdin() -> bool {
unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }
}
fn fail(msg: &str) -> ExitCode {
eprintln!("Rscript: {msg}");
ExitCode::FAILURE
}
fn r_error(msg: &str) {
let (call, trace) = rlang::host::with_host(|h| {
let c = h.error_call.take();
let t = std::mem::take(&mut h.error_trace);
h.clear_error_call();
(c, t)
});
eprint!("{}", rlang::host::error_report(msg, call.as_deref()));
if let Some(tr) = call
.as_deref()
.and_then(|c| rlang::host::traceback(&trace, Some(c)))
{
eprintln!("Calls: {tr}");
}
}