#![forbid(unsafe_code)]
#![deny(missing_docs)]
use std::io::{IsTerminal, Read, Write};
use std::process::ExitCode;
use std::time::Duration;
use viperjs::api::{Engine, Error, Host};
use viperjs::heap::{Heap, NativeCall};
use viperjs::parser::parse_module;
use viperjs::value::{Abrupt, Completion, Value};
use viperjs::vm::Vm;
#[derive(Debug, PartialEq, Eq)]
enum Command {
File(String),
Source(String),
Stdin,
Prompt,
Help,
Version,
Bad(String),
}
#[derive(Debug, PartialEq, Eq)]
struct Asked {
command: Command,
budget: Option<Duration>,
heap: Option<usize>,
}
fn read_arguments(arguments: &[String], interactive: bool) -> Asked {
let mut command = None;
let mut budget = None;
let mut heap = None;
let mut at = 0;
while at < arguments.len() {
let argument = arguments[at].as_str();
at += 1;
match argument {
"-h" | "--help" => return Asked::of(Command::Help),
"-V" | "--version" => return Asked::of(Command::Version),
"-e" | "--eval" => match arguments.get(at) {
Some(source) => {
at += 1;
command = Some(Command::Source(source.clone()));
}
None => return Asked::of(Command::Bad("-e wants source after it".into())),
},
"--time-budget" => match arguments.get(at).map(|text| text.parse::<u64>()) {
Some(Ok(millis)) => {
at += 1;
budget = Some(Duration::from_millis(millis));
}
_ => {
return Asked::of(Command::Bad(
"--time-budget wants a whole number of milliseconds".into(),
));
}
},
"--heap-budget" => match arguments.get(at).map(|text| text.parse::<usize>()) {
Some(Ok(mib)) if mib > 0 => {
at += 1;
heap = Some(mib << 20);
}
_ => {
return Asked::of(Command::Bad(
"--heap-budget wants a whole number of mebibytes, above zero".into(),
));
}
},
"-" => command = Some(Command::Stdin),
other if other.starts_with('-') => {
return Asked::of(Command::Bad(format!("unknown option {other}")));
}
path => command = Some(Command::File(path.to_string())),
}
}
Asked {
command: command.unwrap_or(match interactive {
true => Command::Prompt,
false => Command::Stdin,
}),
budget,
heap,
}
}
impl Asked {
fn of(command: Command) -> Self {
Self {
command,
budget: None,
heap: None,
}
}
}
const USAGE: &str = "\
viper — ViperJS, an embeddable JavaScript engine, on a command line
usage:
viper <file> run a file as a Script
viper -e <source> run source given here
viper - run standard input, even from a terminal
viper run standard input, or prompt if it is a terminal
options:
-e, --eval <source> source to run
--time-budget <ms> stop a run that takes longer, uncatchably (DR-0022)
--heap-budget <MiB> how much memory a run may take before it refuses (default 64)
-h, --help this text
-V, --version the version
The host binds `print` and a `console` of six logging methods — log, info and debug to standard
output, warn, error and trace to standard error. There is no `require`, no `fs` and no module
loading: GOAL.md §3 says the host provides I/O and this host provides almost none of it.
exit status: 0 ran, 1 the script threw or would not parse, 2 the arguments made no sense.
";
const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
fn not_base64() -> Abrupt {
Abrupt::type_error("InvalidCharacterError: this is not base64")
}
fn encode_base64(bytes: &[u8]) -> String {
let mut out = String::new();
for group in bytes.chunks(3) {
let packed = u32::from(group[0]) << 16
| u32::from(group.get(1).copied().unwrap_or(0)) << 8
| u32::from(group.get(2).copied().unwrap_or(0));
out.push(char::from(BASE64[(packed >> 18) as usize & 63]));
out.push(char::from(BASE64[(packed >> 12) as usize & 63]));
out.push(match group.len() {
1 => '=',
_ => char::from(BASE64[(packed >> 6) as usize & 63]),
});
out.push(match group.len() {
3 => char::from(BASE64[packed as usize & 63]),
_ => '=',
});
}
out
}
fn decode_base64(text: &str) -> Completion<String> {
let mut trimmed: Vec<u8> = Vec::with_capacity(text.len());
for point in text.chars() {
if matches!(point, '\t' | '\n' | '\u{c}' | '\r' | ' ') {
continue;
}
match u8::try_from(point as u32) {
Ok(byte) => trimmed.push(byte),
Err(_) => return Err(not_base64()),
}
}
if trimmed.len().is_multiple_of(4) {
for _ in 0..2 {
if trimmed.last() == Some(&b'=') {
trimmed.pop();
}
}
}
if trimmed.len() % 4 == 1 {
return Err(Abrupt::type_error(
"InvalidCharacterError: this base64 has a length no number of bytes encodes to",
));
}
let mut out = String::with_capacity(trimmed.len() / 4 * 3);
let mut buffer = 0_u32;
let mut bits = 0_u32;
for byte in trimmed {
let Some(index) = BASE64.iter().position(|known| *known == byte) else {
return Err(not_base64());
};
buffer = buffer << 6 | index as u32;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push(char::from_u32(buffer >> bits & 0xff).unwrap_or('\u{0}'));
}
}
Ok(out)
}
fn btoa(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let text = Host::new(vm, heap).text(call.argument(0))?;
let mut bytes = Vec::with_capacity(text.len());
for point in text.chars() {
match u8::try_from(point as u32) {
Ok(byte) => bytes.push(byte),
Err(_) => {
return Err(Abrupt::type_error(
"InvalidCharacterError: btoa encodes bytes, and this string has a code point above U+00FF",
));
}
}
}
let encoded = encode_base64(&bytes);
Ok(Host::new(vm, heap).string(&encoded))
}
fn atob(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let text = Host::new(vm, heap).text(call.argument(0))?;
let decoded = decode_base64(&text)?;
Ok(Host::new(vm, heap).string(&decoded))
}
fn print(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let mut host = Host::new(vm, heap);
let text = host.text(call.argument(0))?;
let _ = writeln!(std::io::stdout(), "{text}");
Ok(Value::Undefined)
}
fn joined(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<String> {
let mut host = Host::new(vm, heap);
let mut out = String::new();
for (at, value) in call.arguments.iter().enumerate() {
if at > 0 {
out.push(' ');
}
out.push_str(&host.text(*value)?);
}
Ok(out)
}
fn console_out(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let text = joined(vm, heap, call)?;
let _ = writeln!(std::io::stdout(), "{text}");
Ok(Value::Undefined)
}
fn console_err(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
let text = joined(vm, heap, call)?;
let _ = writeln!(std::io::stderr(), "{text}");
Ok(Value::Undefined)
}
fn main() -> ExitCode {
let arguments: Vec<String> = std::env::args().skip(1).collect();
let asked = read_arguments(&arguments, std::io::stdin().is_terminal());
let mut engine = Engine::new();
engine.bind("print", 1, print);
engine.bind("atob", 1, atob);
engine.bind("btoa", 1, btoa);
engine.bind_namespace(
"console",
&[
("log", 0, console_out),
("info", 0, console_out),
("debug", 0, console_out),
("warn", 0, console_err),
("error", 0, console_err),
("trace", 0, console_err),
],
);
engine.set_time_budget(asked.budget);
if let Some(bytes) = asked.heap {
engine.set_heap_budget(bytes);
}
match asked.command {
Command::Help => {
print!("{USAGE}");
ExitCode::SUCCESS
}
Command::Version => {
println!("viper {}", env!("CARGO_PKG_VERSION"));
ExitCode::SUCCESS
}
Command::Bad(why) => {
eprintln!("viper: {why}");
eprint!("{USAGE}");
ExitCode::from(2)
}
Command::File(path) => match std::fs::read_to_string(&path) {
Ok(source) => run(&mut engine, &source, Show::Nothing),
Err(why) => {
eprintln!("viper: {path}: {why}");
ExitCode::from(2)
}
},
Command::Source(source) => run(&mut engine, &source, Show::Answer),
Command::Stdin => {
let mut source = String::new();
match std::io::stdin().read_to_string(&mut source) {
Ok(_) => run(&mut engine, &source, Show::Nothing),
Err(why) => {
eprintln!("viper: could not read standard input: {why}");
ExitCode::from(2)
}
}
}
Command::Prompt => prompt(&mut engine),
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Show {
Answer,
Nothing,
}
fn report_rejections(engine: &mut Engine) {
for reason in engine.unhandled_rejections() {
let said = engine
.text(reason)
.unwrap_or_else(|_| "a reason that cannot be described".to_string());
let _ = writeln!(std::io::stderr(), "viper: unhandled rejection: {said}");
}
}
fn run(engine: &mut Engine, source: &str, show: Show) -> ExitCode {
let answer = run_quietly(engine, source, show);
report_rejections(engine);
answer
}
fn run_quietly(engine: &mut Engine, source: &str, show: Show) -> ExitCode {
match engine.eval(source) {
Ok(value) if show == Show::Answer => match engine.text(value) {
Ok(text) => {
println!("{text}");
ExitCode::SUCCESS
}
Err(error) => {
eprintln!("viper: could not describe the answer: {}", describe(&error));
ExitCode::SUCCESS
}
},
Ok(_) => ExitCode::SUCCESS,
Err(Error::Syntax { message: said, .. }) if is_module(source) => {
eprintln!("viper: this is Module code — it parses under §11.2's Module goal but not");
eprintln!(" as a Script, which is what viper runs. A Module's imports need a");
eprintln!(" resolver, and GOAL.md §3 leaves that to the host: see");
eprintln!(" viperjs::api::Engine to supply one.");
eprintln!(" as a Script it said: {said}");
ExitCode::FAILURE
}
Err(Error::Syntax { message, span }) => {
eprintln!("viper: SyntaxError: {message}");
for line in point_at(source, span) {
eprintln!("{line}");
}
ExitCode::FAILURE
}
Err(error) => {
eprintln!("viper: {}", describe(&error));
ExitCode::FAILURE
}
}
}
fn point_at(source: &str, span: viperjs::span::Span) -> Vec<String> {
let at = viperjs::span::line_col(source, span.start);
let mut said = vec![format!(" at line {}, column {}", at.line, at.column)];
let Some(text) = source
.lines()
.nth(at.line as usize - 1)
.filter(|line| (at.column as usize) <= line.chars().count() + 1)
else {
return said;
};
said.push(format!(" {text}"));
let pad: String = text
.chars()
.take(at.column as usize - 1)
.map(|found| if found == '\t' { '\t' } else { ' ' })
.collect();
let width = usize::max(span.len() as usize, 1);
said.push(format!(" {pad}{}", "^".repeat(width)));
said
}
fn is_module(source: &str) -> bool {
parse_module(source).is_ok()
}
fn describe(error: &Error) -> String {
match error {
Error::Syntax { message, .. } => format!("SyntaxError: {message}"),
Error::Thrown(said) => said.clone(),
Error::Interrupted => "the run was stopped: it spent its time budget".to_string(),
Error::Collected => "a value was read after the collector had freed it".to_string(),
Error::Engine(fault) => format!("internal error, which is a bug in ViperJS: {fault:?}"),
}
}
fn prompt_line(line: &str) -> Option<&str> {
match line.trim().is_empty() {
true => None,
false => Some(line),
}
}
fn prompt(engine: &mut Engine) -> ExitCode {
println!(
"ViperJS {} — one line is one script, ^D to leave",
env!("CARGO_PKG_VERSION")
);
let input = std::io::stdin();
loop {
print!("> ");
let _ = std::io::stdout().flush();
let mut line = String::new();
match input.read_line(&mut line) {
Ok(0) => {
println!();
return ExitCode::SUCCESS;
}
Ok(_) => {}
Err(why) => {
eprintln!("viper: {why}");
return ExitCode::FAILURE;
}
}
if let Some(source) = prompt_line(&line) {
let _ = run(engine, source, Show::Answer);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_caret_lands_under_the_token_the_span_names() {
let source = "var a = 1;\nvar b = ;\nvar c = 3;";
let said = point_at(source, viperjs::span::Span::new(19, 20));
assert_eq!(
said,
vec![
" at line 2, column 9".to_string(),
" var b = ;".to_string(),
" ^".to_string(),
]
);
let source = "function f() {";
let said = point_at(source, viperjs::span::Span::new(14, 14));
assert_eq!(said.len(), 3, "the line is shown at the end of input");
assert_eq!(said[0], " at line 1, column 15");
assert_eq!(said[2], " ^");
let said = point_at("ab\n", viperjs::span::Span::new(90, 91));
assert_eq!(said, vec![" at line 2, column 1".to_string()]);
let source = "function f() {\n\tconst x = [1, 2;\n}";
let semicolon = source.find(';').expect("the source has one") as u32;
let said = point_at(source, viperjs::span::Span::new(semicolon, semicolon + 1));
assert_eq!(said[0], " at line 2, column 17");
assert_eq!(said[1], " \tconst x = [1, 2;");
assert_eq!(
said[2],
format!(" \t{}^", " ".repeat(15)),
"the padding is a tab followed by spaces, not eight spaces"
);
let source = "let value = notdefined;";
assert_eq!(
point_at(source, viperjs::span::Span::new(12, 22))[2],
" ^^^^^^^^^^"
);
assert_eq!(point_at("abc", viperjs::span::Span::new(1, 1))[2], " ^");
}
#[test]
fn base64_encodes_every_group_length_and_pads_each_the_way_the_standard_says() {
assert_eq!(encode_base64(b""), "");
assert_eq!(encode_base64(b"a"), "YQ==");
assert_eq!(encode_base64(b"ab"), "YWI=");
assert_eq!(encode_base64(b"abc"), "YWJj");
assert_eq!(encode_base64(b"hello"), "aGVsbG8=");
assert_eq!(encode_base64(&[0xff, 0xfe]), "//4=");
assert_eq!(encode_base64(&[0x00, 0x00, 0x00]), "AAAA");
assert_eq!(encode_base64(&[0xff, 0xff, 0xff]), "////");
assert_eq!(encode_base64(&[0xff, 0x00, 0x00]), "/wAA");
assert_eq!(encode_base64(&[0x00, 0xff, 0x00]), "AP8A");
assert_eq!(encode_base64(&[0x00, 0x00, 0xff]), "AAD/");
}
#[test]
fn base64_decodes_what_it_encoded_for_every_byte_there_is() {
let all: Vec<u8> = (0..=255).collect();
let encoded = encode_base64(&all);
let back = decode_base64(&encoded).expect("what we encoded decodes"); assert_eq!(
back.chars().map(|c| c as u32).collect::<Vec<_>>(),
(0..=255).collect::<Vec<u32>>()
);
assert_eq!(&encoded[..8], "AAECAwQF");
}
#[test]
fn forgiving_base64_forgives_exactly_three_things() {
assert_eq!(
decode_base64(" a G V s b G 8 = ").ok().as_deref(),
Some("hello")
);
assert_eq!(decode_base64("aGVs\nbG8=").ok().as_deref(), Some("hello"));
assert!(decode_base64("aGVs\u{b}bG8=").is_err());
assert!(decode_base64("aGVs\u{a0}bG8=").is_err());
assert_eq!(decode_base64("aGVsbG8").ok().as_deref(), Some("hello"));
assert_eq!(decode_base64("YQ==").ok().as_deref(), Some("a"));
assert!(decode_base64("YQ=").is_err());
assert!(decode_base64("a").is_err());
assert!(decode_base64("aGVsb").is_err());
for bad in ["!!!!", "a=b=", "ab-d", "ab_d", "\u{100}"] {
assert!(decode_base64(bad).is_err(), "for {bad:?}");
}
assert_eq!(decode_base64("").ok().as_deref(), Some(""));
}
use super::{Asked, Command, read_arguments};
fn read(arguments: &[&str], interactive: bool) -> Asked {
let owned: Vec<String> = arguments.iter().map(|text| (*text).to_string()).collect();
read_arguments(&owned, interactive)
}
#[test]
fn a_bare_invocation_prompts_at_a_terminal_and_reads_the_pipe_otherwise() {
assert_eq!(read(&[], true).command, Command::Prompt);
assert_eq!(read(&[], false).command, Command::Stdin);
assert_eq!(read(&["-"], true).command, Command::Stdin);
}
#[test]
fn a_path_is_a_file_and_an_unknown_option_is_a_usage_error() {
assert_eq!(
read(&["script.js"], false).command,
Command::File("script.js".to_string())
);
assert!(matches!(read(&["--nope"], false).command, Command::Bad(_)));
assert_eq!(
read(&["--time-budget", "50", "a.js"], false).command,
Command::File("a.js".to_string())
);
}
#[test]
fn eval_takes_the_argument_after_it_and_complains_when_there_is_none() {
assert_eq!(
read(&["-e", "1 + 1"], false).command,
Command::Source("1 + 1".to_string())
);
assert_eq!(
read(&["--eval", "1 + 1"], false).command,
Command::Source("1 + 1".to_string())
);
assert!(matches!(read(&["-e"], false).command, Command::Bad(_)));
assert_eq!(
read(&["-e", "-h"], false).command,
Command::Source("-h".to_string())
);
}
#[test]
fn a_time_budget_is_milliseconds_and_anything_else_is_refused() {
let asked = read(&["--time-budget", "250", "a.js"], false);
assert_eq!(asked.budget, Some(std::time::Duration::from_millis(250)));
assert_eq!(read(&["a.js"], false).budget, None);
assert!(matches!(
read(&["--time-budget", "soon"], false).command,
Command::Bad(_)
));
assert!(matches!(
read(&["--time-budget"], false).command,
Command::Bad(_)
));
assert!(matches!(
read(&["--time-budget", "-5"], false).command,
Command::Bad(_)
));
}
#[test]
fn help_and_version_win_over_everything_after_them() {
assert_eq!(read(&["-h", "script.js"], false).command, Command::Help);
assert_eq!(read(&["--help"], false).command, Command::Help);
assert_eq!(read(&["-V", "script.js"], false).command, Command::Version);
assert_eq!(read(&["--version"], false).command, Command::Version);
}
#[test]
fn a_blank_line_at_the_prompt_runs_nothing() {
assert_eq!(super::prompt_line(""), None);
assert_eq!(
super::prompt_line(
"
"
),
None
);
assert_eq!(
super::prompt_line(
"
"
),
None
);
assert_eq!(
super::prompt_line(
" 1 + 1
"
),
Some(
" 1 + 1
"
)
);
assert_eq!(super::prompt_line("0"), Some("0"));
}
#[test]
fn the_last_thing_named_is_what_runs() {
assert_eq!(
read(&["a.js", "b.js"], false).command,
Command::File("b.js".to_string())
);
assert_eq!(
read(&["a.js", "-e", "1"], false).command,
Command::Source("1".to_string())
);
}
}