Skip to content
Open
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
8 changes: 8 additions & 0 deletions nova_cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ readme.workspace = true
keywords.workspace = true
categories = ["development-tools", "command-line-utilities"]

[lib]
name = "nova_cli"
path = "src/lib/lib.rs"

[[bin]]
name = "nova_cli"
path = "src/main.rs"

[dependencies]
clap = { workspace = true }
cliclack = { workspace = true }
Expand Down
111 changes: 111 additions & 0 deletions nova_cli/src/lib/child_hooks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// 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/.

//! The [`HostHooks`] implementation for macrotasks and promise jobs, i.e.
//! everything but the main thread.

use std::{
cell::RefCell,
collections::VecDeque,
sync::{atomic::AtomicBool, mpsc},
thread,
time::Duration,
};

use nova_vm::ecmascript::execution::agent::{HostHooks, Job};

use crate::{ChildToHostMessage, HostToChildMessage};

pub struct CliChildHooks {
promise_job_queue: RefCell<VecDeque<Job>>,
macrotask_queue: RefCell<Vec<Job>>,
pub(crate) receiver: mpsc::Receiver<HostToChildMessage>,
pub(crate) host_sender: mpsc::SyncSender<ChildToHostMessage>,
ready_to_leave: AtomicBool,
}

// RefCell doesn't implement Debug
impl std::fmt::Debug for CliChildHooks {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CliHostHooks")
//.field("promise_job_queue", &*self.promise_job_queue.borrow())
.finish()
}
}

impl CliChildHooks {
pub fn new(
host_sender: mpsc::SyncSender<ChildToHostMessage>,
) -> (Self, mpsc::SyncSender<HostToChildMessage>) {
let (sender, receiver) = mpsc::sync_channel(1);
(
Self {
promise_job_queue: Default::default(),
macrotask_queue: Default::default(),
receiver,
host_sender,
ready_to_leave: Default::default(),
},
sender,
)
}

pub fn is_ready_to_leave(&self) -> bool {
self.ready_to_leave
.load(std::sync::atomic::Ordering::Relaxed)
}

pub fn mark_ready_to_leave(&self) {
self.ready_to_leave
.store(true, std::sync::atomic::Ordering::Relaxed)
}

pub fn has_promise_jobs(&self) -> bool {
!self.promise_job_queue.borrow().is_empty()
}

pub fn pop_promise_job(&self) -> Option<Job> {
self.promise_job_queue.borrow_mut().pop_front()
}

pub fn has_macrotasks(&self) -> bool {
!self.macrotask_queue.borrow().is_empty()
}

pub fn pop_macrotask(&self) -> Option<Job> {
let mut off_thread_job_queue = self.macrotask_queue.borrow_mut();
let mut counter = 0u8;
while !off_thread_job_queue.is_empty() {
counter = counter.wrapping_add(1);
for (i, job) in off_thread_job_queue.iter().enumerate() {
if job.is_finished() {
let job = off_thread_job_queue.swap_remove(i);
return Some(job);
}
}
if counter == 0 {
thread::sleep(Duration::from_millis(5));
} else {
core::hint::spin_loop();
}
}
None
}
}

impl HostHooks for CliChildHooks {
fn enqueue_generic_job(&self, job: Job) {
self.macrotask_queue.borrow_mut().push(job);
}

fn enqueue_promise_job(&self, job: Job) {
self.promise_job_queue.borrow_mut().push_back(job);
}

fn enqueue_timeout_job(&self, _timeout_job: Job, _milliseconds: u64) {}

fn get_host_data(&self) -> &dyn std::any::Any {
self
}
}
62 changes: 62 additions & 0 deletions nova_cli/src/lib/fmt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// 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/.

//! Formatting values and errors.

use nova_vm::{
ecmascript::{
execution::{Agent, JsResult},
types::Value,
},
engine::context::{Bindable, GcScope},
};
use oxc_diagnostics::OxcDiagnostic;

pub fn print_result(agent: &mut Agent, result: JsResult<Value>, verbose: bool, gc: GcScope) {
match result {
Ok(result) => {
if verbose {
println!("{result:?}");
}
}
Err(error) => {
eprintln!(
"Uncaught exception: {}",
error
.value()
.unbind()
.string_repr(agent, gc)
.as_wtf8(agent)
.to_string_lossy()
);
std::process::exit(1);
}
}
}

/// 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(|_| {
Box::new(oxc_diagnostics::GraphicalReportHandler::new())
}))
.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);
}
134 changes: 6 additions & 128 deletions nova_cli/src/helper.rs → nova_cli/src/lib/globals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,9 @@
// 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/.

use std::{
cell::RefCell,
collections::VecDeque,
ops::Deref,
sync::{LazyLock, atomic::AtomicBool, mpsc},
thread,
time::Duration,
};
//! Initializing the global object with builtin functions.

use std::{ops::Deref, sync::LazyLock, thread, time::Duration};

// Record the start time of the program.
// To be used for the `now` function for time measurement.
Expand All @@ -23,7 +18,7 @@ use nova_vm::{
},
execution::{
Agent, JsResult,
agent::{ExceptionType, GcAgent, HostHooks, Job, Options, unwrap_try},
agent::{ExceptionType, GcAgent, Options, unwrap_try},
},
scripts_and_modules::script::{parse_script, script_evaluation},
types::{
Expand All @@ -36,97 +31,8 @@ use nova_vm::{
rootable::Scopable,
},
};
use oxc_diagnostics::OxcDiagnostic;

use crate::{ChildToHostMessage, CliHostHooks, HostToChildMessage};

struct CliChildHooks {
promise_job_queue: RefCell<VecDeque<Job>>,
macrotask_queue: RefCell<Vec<Job>>,
receiver: mpsc::Receiver<HostToChildMessage>,
host_sender: mpsc::SyncSender<ChildToHostMessage>,
ready_to_leave: AtomicBool,
}

// RefCell doesn't implement Debug
impl std::fmt::Debug for CliChildHooks {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CliHostHooks")
//.field("promise_job_queue", &*self.promise_job_queue.borrow())
.finish()
}
}

impl CliChildHooks {
fn new(
host_sender: mpsc::SyncSender<ChildToHostMessage>,
) -> (Self, mpsc::SyncSender<HostToChildMessage>) {
let (sender, receiver) = mpsc::sync_channel(1);
(
Self {
promise_job_queue: Default::default(),
macrotask_queue: Default::default(),
receiver,
host_sender,
ready_to_leave: Default::default(),
},
sender,
)
}

fn is_ready_to_leave(&self) -> bool {
self.ready_to_leave
.load(std::sync::atomic::Ordering::Relaxed)
}

fn has_promise_jobs(&self) -> bool {
!self.promise_job_queue.borrow().is_empty()
}

fn pop_promise_job(&self) -> Option<Job> {
self.promise_job_queue.borrow_mut().pop_front()
}

fn has_macrotasks(&self) -> bool {
!self.macrotask_queue.borrow().is_empty()
}

fn pop_macrotask(&self) -> Option<Job> {
let mut off_thread_job_queue = self.macrotask_queue.borrow_mut();
let mut counter = 0u8;
while !off_thread_job_queue.is_empty() {
counter = counter.wrapping_add(1);
for (i, job) in off_thread_job_queue.iter().enumerate() {
if job.is_finished() {
let job = off_thread_job_queue.swap_remove(i);
return Some(job);
}
}
if counter == 0 {
thread::sleep(Duration::from_millis(5));
} else {
core::hint::spin_loop();
}
}
None
}
}

impl HostHooks for CliChildHooks {
fn enqueue_generic_job(&self, job: Job) {
self.macrotask_queue.borrow_mut().push(job);
}

fn enqueue_promise_job(&self, job: Job) {
self.promise_job_queue.borrow_mut().push_back(job);
}

fn enqueue_timeout_job(&self, _timeout_job: Job, _milliseconds: u64) {}

fn get_host_data(&self) -> &dyn std::any::Any {
self
}
}
use crate::{ChildToHostMessage, CliChildHooks, CliHostHooks, HostToChildMessage};

/// Initialize the global object with the built-in functions.
pub fn initialize_global_object(agent: &mut Agent, global: Object, gc: GcScope) {
Expand Down Expand Up @@ -714,9 +620,7 @@ fn initialize_child_global_object(agent: &mut Agent, global: Object, mut gc: GcS
.get_host_data()
.downcast_ref::<CliChildHooks>()
.unwrap();
hooks
.ready_to_leave
.store(true, std::sync::atomic::Ordering::Relaxed);
hooks.mark_ready_to_leave();
Ok(Value::Undefined)
}

Expand Down Expand Up @@ -765,29 +669,3 @@ fn initialize_child_global_object(agent: &mut Agent, global: Object, mut gc: GcS
create_obj_func(agent, agent_obj, "sleep", sleep, 1, gc);
create_obj_func(agent, agent_obj, "monotonicNow", monotonic_now, 0, gc);
}

/// 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(|_| {
Box::new(oxc_diagnostics::GraphicalReportHandler::new())
}))
.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);
}
Loading