Skip to content

feat: repl command #323

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ resolver = "2"
members = ["nova_cli", "nova_vm", "common", "small_string", "tests"]

[workspace.dependencies]
clap = { version = "4.5.0", features = ["derive"] }
clap = { version = "4.5.9", features = ["derive"] }
cliclack = "0.3.2"
console = "0.15.8"
fast-float = "0.2.0"
miette = { version = "7.2.0", features = ["fancy"] }
num-bigint = "0.4.4"
Expand Down
2 changes: 2 additions & 0 deletions nova_cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ default-run = "nova_cli"

[dependencies]
clap = { workspace = true}
cliclack = { workspace = true }
console = { workspace = true }
miette = { workspace = true }
nova_vm = { path = "../nova_vm" }
oxc_ast = { workspace = true }
Expand Down
67 changes: 67 additions & 0 deletions nova_cli/src/helper.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
use nova_vm::ecmascript::{
builtins::{create_builtin_function, ArgumentsList, Behaviour, BuiltinFunctionArgs},
execution::{Agent, JsResult},
types::{InternalMethods, IntoValue, Object, PropertyDescriptor, PropertyKey, Value},
};
use oxc_diagnostics::{GraphicalTheme, OxcDiagnostic};

/// Initialize the global object with the built-in functions.
pub fn initialize_global_object(agent: &mut Agent, global: Object) {
// `print` function
fn print(agent: &mut Agent, _this: Value, args: ArgumentsList) -> JsResult<Value> {
if args.len() == 0 {
println!();
} else {
println!("{}", args[0].to_string(agent)?.as_str(agent));
}
Ok(Value::Undefined)
}
let function = create_builtin_function(
agent,
Behaviour::Regular(print),
BuiltinFunctionArgs::new(1, "print", agent.current_realm_id()),
);
let property_key = PropertyKey::from_static_str(agent, "print");
global
.internal_define_own_property(
agent,
property_key,
PropertyDescriptor {
value: Some(function.into_value()),
..Default::default()
},
)
.unwrap();
}

/// Exit the program with parse errors.
pub fn exit_with_parse_errors(errors: Vec<OxcDiagnostic>, source_path: &str, source: &str) -> ! {
assert!(!errors.is_empty());

// This seems to be needed for color and Unicode output.
miette::set_hook(Box::new(|_| {
use std::io::IsTerminal;
let mut handler = oxc_diagnostics::GraphicalReportHandler::new();
if !std::io::stdout().is_terminal() || std::io::stderr().is_terminal() {
// Fix for https://github.com/oxc-project/oxc/issues/3539
handler = handler.with_theme(GraphicalTheme::none());
}
Box::new(handler)
}))
.unwrap();

eprintln!("Parse errors:");

// SAFETY: This function never returns, so `source`'s lifetime must last for
// the duration of the program.
let source: &'static str = unsafe { std::mem::transmute(source) };
let named_source = miette::NamedSource::new(source_path, source);

for error in errors {
let report = error.with_source_code(named_source.clone());
eprint!("{:?}", report);
}
eprintln!();

std::process::exit(1);
}
123 changes: 59 additions & 64 deletions nova_cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
mod helper;
mod theme;

use std::{cell::RefCell, collections::VecDeque, fmt::Debug};

use clap::{Parser as ClapParser, Subcommand};
use cliclack::{input, intro, set_theme};
use helper::{exit_with_parse_errors, initialize_global_object};
use nova_vm::ecmascript::{
execution::{
agent::{HostHooks, Job, Options},
Expand All @@ -13,9 +17,9 @@ use nova_vm::ecmascript::{
scripts_and_modules::script::{parse_script, script_evaluation},
types::{Object, Value},
};
use oxc_diagnostics::{GraphicalTheme, OxcDiagnostic};
use oxc_parser::Parser;
use oxc_span::SourceType;
use theme::DefaultTheme;

/// A JavaScript engine
#[derive(Debug, ClapParser)] // requires `derive` feature
Expand Down Expand Up @@ -46,6 +50,9 @@ enum Command {
#[arg(required = true)]
paths: Vec<String>,
},

/// Runs the REPL
Repl {},
}

#[derive(Default)]
Expand Down Expand Up @@ -158,72 +165,60 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}
}
}
}

Ok(())
}

fn exit_with_parse_errors(errors: Vec<OxcDiagnostic>, source_path: &str, source: &str) -> ! {
assert!(!errors.is_empty());

// This seems to be needed for color and Unicode output.
miette::set_hook(Box::new(|_| {
use std::io::IsTerminal;
let mut handler = oxc_diagnostics::GraphicalReportHandler::new();
if !std::io::stdout().is_terminal() || std::io::stderr().is_terminal() {
// Fix for https://github.com/oxc-project/oxc/issues/3539
handler = handler.with_theme(GraphicalTheme::none());
}
Box::new(handler)
}))
.unwrap();

eprintln!("Parse errors:");

// SAFETY: This function never returns, so `source`'s lifetime must last for
// the duration of the program.
let source: &'static str = unsafe { std::mem::transmute(source) };
let named_source = miette::NamedSource::new(source_path, source);
Command::Repl {} => {
let allocator = Default::default();
let host_hooks: &CliHostHooks = &*Box::leak(Box::default());
let mut agent = Agent::new(
Options {
disable_gc: false,
print_internals: true,
},
host_hooks,
);
{
let create_global_object: Option<fn(&mut Realm) -> Object> = None;
let create_global_this_value: Option<fn(&mut Realm) -> Object> = None;
initialize_host_defined_realm(
&mut agent,
create_global_object,
create_global_this_value,
Some(initialize_global_object),
);
}
let realm = agent.current_realm_id();

for error in errors {
let report = error.with_source_code(named_source.clone());
eprint!("{:?}", report);
}
eprintln!();
set_theme(DefaultTheme);
println!("\n\n");
let mut placeholder = "Enter a line of Javascript".to_string();

std::process::exit(1);
}
loop {
intro("Nova Repl (type exit or ctrl+c to exit)")?;
let input: String = input("").placeholder(&placeholder).interact()?;

fn initialize_global_object(agent: &mut Agent, global: Object) {
use nova_vm::ecmascript::{
builtins::{create_builtin_function, ArgumentsList, Behaviour, BuiltinFunctionArgs},
execution::JsResult,
types::{InternalMethods, IntoValue, PropertyDescriptor, PropertyKey},
};

// `print` function
fn print(agent: &mut Agent, _this: Value, args: ArgumentsList) -> JsResult<Value> {
if args.len() == 0 {
println!();
} else {
println!("{}", args[0].to_string(agent)?.as_str(agent));
if input.matches("exit").count() == 1 {
std::process::exit(0);
}
placeholder = input.to_string();
let script = match parse_script(&allocator, input.into(), realm, true, None) {
Ok(script) => script,
Err((file, errors)) => {
exit_with_parse_errors(errors, "<stdin>", &file);
}
};
let result = script_evaluation(&mut agent, script);
match result {
Ok(result) => {
println!("{:?}\n", result);
}
Err(error) => {
eprintln!(
"Uncaught exception: {}",
error.value().string_repr(&mut agent).as_str(&agent)
);
}
}
}
}
Ok(Value::Undefined)
}
let function = create_builtin_function(
agent,
Behaviour::Regular(print),
BuiltinFunctionArgs::new(1, "print", agent.current_realm_id()),
);
let property_key = PropertyKey::from_static_str(agent, "print");
global
.internal_define_own_property(
agent,
property_key,
PropertyDescriptor {
value: Some(function.into_value()),
..Default::default()
},
)
.unwrap();
Ok(())
}
18 changes: 18 additions & 0 deletions nova_cli/src/theme.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use cliclack::{Theme, ThemeState};
use console::Style;

pub struct DefaultTheme;

impl Theme for DefaultTheme {
fn bar_color(&self, _: &ThemeState) -> Style {
Style::new().dim().bold()
}

fn state_symbol_color(&self, _state: &ThemeState) -> Style {
Style::new().cyan()
}

fn info_symbol(&self) -> String {
"⚙".into()
}
}