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
6 changes: 4 additions & 2 deletions cli/src/debug/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#![allow(clippy::unnecessary_wraps)]

use boa_engine::{Context, JsObject, js_string, object::ObjectInitializer, property::Attribute};
use color_eyre::Result;

mod function;
mod gc;
Expand Down Expand Up @@ -67,13 +68,14 @@ fn create_boa_object(context: &mut Context) -> JsObject {
}

#[allow(clippy::redundant_pub_crate)]
pub(crate) fn init_boa_debug_object(context: &mut Context) {
pub(crate) fn init_boa_debug_object(context: &mut Context) -> Result<()> {
let boa_object = create_boa_object(context);
context
.register_global_property(
js_string!("$boa"),
boa_object,
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.expect("cannot fail with the default object");
.map_err(|e| color_eyre::eyre::eyre!("failed to register debug object: {e}"))?;
Ok(())
}
14 changes: 9 additions & 5 deletions cli/src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,13 @@ static KEYWORDS: Set<&'static str> = phf_set! {
};

struct LineHighlighter {
regex: Regex,
regex: Option<Regex>,
}

impl LineHighlighter {
fn new() -> Self {
// Precompiles the regex to avoid creating it again after every highlight
// Precompiles the regex to avoid creating it again after every highlight.
// If compilation fails (e.g. unsupported Unicode on some platforms), we fall back to no highlighting.
let regex = Regex::new(
r#"(?x)
(?P<identifier>\b[$_\p{ID_Start}][$_\p{ID_Continue}\u{200C}\u{200D}]*\b) |
Expand All @@ -154,7 +155,7 @@ impl LineHighlighter {
(?P<template_literal>`([^`\\]|\\.)*`) |
(?P<op>[+\-/*%~^!&|=<>;:]) |
(?P<number>0[bB][01](_?[01])*n?|0[oO][0-7](_?[0-7])*n?|0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?|(([0-9](_?[0-9])*\.([0-9](_?[0-9])*)?)|(([0-9](_?[0-9])*)?\.[0-9](_?[0-9])*)|([0-9](_?[0-9])*))([eE][+-]?[0-9](_?[0-9])*)?n?)"#,
).expect("could not compile regular expression");
).ok();

Self { regex }
}
Expand Down Expand Up @@ -200,12 +201,15 @@ impl Highlighter for LineHighlighter {
};

if let Some(colored) = colored {
write!(dst, "{colored}").expect("could not append data to dst");
let _ = write!(dst, "{colored}");
} else {
dst.push_str(&caps[0]);
}
}
}
self.regex.replace_all(line, Colorizer)
match &self.regex {
Some(regex) => regex.replace_all(line, Colorizer),
None => Borrowed(line),
}
}
}
4 changes: 2 additions & 2 deletions cli/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ impl SharedExternalPrinterLogger {
pub(crate) fn set<T: ExternalPrinter + Send + 'static>(&self, inner: T) {
self.inner
.lock()
.expect("printer lock failed")
.unwrap_or_else(|e| e.into_inner())
.replace(Box::new(inner));
}

pub(crate) fn print(&self, message: String) {
if let Some(l) = &mut *self.inner.lock().expect("printer lock failed") {
if let Some(l) = &mut *self.inner.lock().unwrap_or_else(|e| e.into_inner()) {
// Ignore errors, there's nothing we can do at this point.
drop(l.print(message));
} else {
Expand Down
35 changes: 22 additions & 13 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,9 +303,9 @@ fn dump<R: ReadChar>(src: Source<'_, R>, args: &Opt, context: &mut Context) -> R
let _timer = counters.new_timer("AST generation");
match arg {
DumpFormat::Json => serde_json::to_string(&module)
.expect("could not convert AST to a JSON string"),
.wrap_err("could not convert AST to a JSON string")?,
DumpFormat::JsonPretty => serde_json::to_string_pretty(&module)
.expect("could not convert AST to a pretty JSON string"),
.wrap_err("could not convert AST to a pretty JSON string")?,
DumpFormat::Debug => format!("{module:#?}"),
}
} else {
Expand All @@ -324,9 +324,9 @@ fn dump<R: ReadChar>(src: Source<'_, R>, args: &Opt, context: &mut Context) -> R
let _timer = counters.new_timer("AST generation");
match arg {
DumpFormat::Json => serde_json::to_string(&script)
.expect("could not convert AST to a JSON string"),
.wrap_err("could not convert AST to a JSON string")?,
DumpFormat::JsonPretty => serde_json::to_string_pretty(&script)
.expect("could not convert AST to a pretty JSON string"),
.wrap_err("could not convert AST to a pretty JSON string")?,
DumpFormat::Debug => format!("{script:#?}"),
}
};
Expand Down Expand Up @@ -431,13 +431,17 @@ fn evaluate_file(
printer: &SharedExternalPrinterLogger,
) -> Result<()> {
if args.has_dump_flag() {
return dump(Source::from_filepath(file)?, args, context);
return dump(
Source::from_filepath(file).wrap_err_with(|| format!("failed to read file '{}'", file.display()))?,
args,
context,
);
}

if let Some(flowgraph) = args.flowgraph {
let flowgraph = generate_flowgraph(
context,
Source::from_filepath(file)?,
Source::from_filepath(file).wrap_err_with(|| format!("failed to read file '{}'", file.display()))?,
flowgraph.unwrap_or(FlowgraphFormat::Graphviz),
args.flowgraph_direction,
)?;
Expand All @@ -448,7 +452,8 @@ fn evaluate_file(
}

if args.module {
let source = Source::from_filepath(file)?;
let source = Source::from_filepath(file)
.wrap_err_with(|| format!("failed to read file '{}'", file.display()))?;
let mut counters = Counters::new(args.time);
let module = {
let _timer = counters.new_timer("Parsing");
Expand Down Expand Up @@ -479,7 +484,8 @@ fn evaluate_file(
};
}

let source = Source::from_filepath(file)?;
let source = Source::from_filepath(file)
.wrap_err_with(|| format!("failed to read file '{}'", file.display()))?;
let mut counters = Counters::new(args.time);
let script = {
let _timer = counters.new_timer("Parsing");
Expand Down Expand Up @@ -545,13 +551,13 @@ fn main() -> Result<()> {
context.strict(args.strict);

// Add `console`.
add_runtime(printer.clone(), &mut context);
add_runtime(printer.clone(), &mut context)?;

// Trace Output
context.set_trace(args.trace);

if args.debug_object {
init_boa_debug_object(&mut context);
init_boa_debug_object(&mut context)?;
}

// Configure optimizer options
Expand Down Expand Up @@ -600,7 +606,9 @@ fn main() -> Result<()> {
thread::sleep(Duration::from_millis(10));
}

handle.join().expect("failed to join thread");
handle
.join()
.map_err(|_| eyre!("readline thread panicked"))?;

Ok(())
}
Expand Down Expand Up @@ -682,7 +690,7 @@ fn start_readline_thread(
}

/// Adds the CLI runtime to the context with default options.
fn add_runtime(printer: SharedExternalPrinterLogger, context: &mut Context) {
fn add_runtime(printer: SharedExternalPrinterLogger, context: &mut Context) -> Result<()> {
boa_runtime::register(
(
boa_runtime::extensions::ConsoleExtension(printer),
Expand All @@ -694,7 +702,8 @@ fn add_runtime(printer: SharedExternalPrinterLogger, context: &mut Context) {
None,
context,
)
.expect("should not fail while registering the runtime");
.map_err(|e| eyre!("failed to register runtime: {e}"))?;
Ok(())
}

#[allow(clippy::struct_field_names)]
Expand Down
Loading
Loading