Skip to content

Commit

Permalink
print js error in console.log
Browse files Browse the repository at this point in the history
  • Loading branch information
ofzo committed Feb 4, 2024
1 parent 0bccc94 commit f1bc378
Show file tree
Hide file tree
Showing 8 changed files with 80 additions and 77 deletions.
66 changes: 27 additions & 39 deletions src/compile.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
use std::{path::PathBuf, sync::Arc};
use crate::{
graph::resolve,
runtime::{ModuleInstance, Runtime},
};
use anyhow::anyhow;
use std::{io::Result, path::PathBuf, sync::Arc};
use swc::{
config::{Config, JscConfig, ModuleConfig, Options, SourceMapsConfig},
Compiler,
Expand All @@ -12,11 +17,6 @@ use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax};
use swc_ecma_visit::{Visit, VisitWith};
use v8::Isolate;

use crate::{
graph::resolve,
runtime::{ModuleInstance, Runtime},
};

struct ImportParser {
sync_imports: Vec<String>,
async_imports: Vec<String>,
Expand Down Expand Up @@ -187,7 +187,7 @@ impl ModuleDependency {
}
}

pub fn compile(file_name: &str, source: &str) -> ModuleDependency {
pub fn compile(file_name: &str, source: &str) -> anyhow::Result<ModuleDependency> {
let cm = Arc::<SourceMap>::default();
let handler = Arc::new(Handler::with_tty_emitter(
ColorConfig::Auto,
Expand Down Expand Up @@ -220,61 +220,49 @@ pub fn compile(file_name: &str, source: &str) -> ModuleDependency {
let parsed = parser
.parse_module()
.map_err(|e| e.into_diagnostic(&handler).emit())
.expect(&format!("parse {file_name} fail"));
.map_err(|e| anyhow!("parse {file_name} fail"))?;
// .expect(&format!("parse {file_name} fail"));

let mut import_parser = ImportParser::new();
parsed.visit_with(&mut import_parser);

let config = Config {
jsc: JscConfig {
target: Some(EsVersion::Es2022),
syntax: Some(Syntax::Typescript(Default::default())),
..Default::default()
},
module: Some(ModuleConfig::Es6(
swc_ecma_transforms_module::EsModuleConfig {
resolve_fully: true,
},
)),
source_maps: Some(SourceMapsConfig::Bool(false)),
..Default::default()
};
let result = GLOBALS.set(&Default::default(), || {
compiler.run(|| {
compiler
.process_js_file(
fm,
&handler,
&Options {
config: Config {
jsc: JscConfig {
target: Some(EsVersion::Es2022),
syntax: Some(Syntax::Typescript(Default::default())),
..Default::default()
},
module: Some(ModuleConfig::Es6(
swc_ecma_transforms_module::EsModuleConfig {
resolve_fully: true,
},
)),
source_maps: Some(SourceMapsConfig::Bool(false)),
..Default::default()
},
config,
..Default::default()
},
)
// .map_err(|e| anyhow!("compiler error"))
.expect("compiler error")
})
});

// let filename = path.file_name().unwrap().to_str().unwrap();
// let mut file = fs::OpenOptions::new()
// .write(true)
// .truncate(true)
// .create(true)
// .open(PathBuf::from(format!("output/{filename}.js")))
// .unwrap();

// if let Some(map) = &result.map {
// fs::write(
// PathBuf::from(format!("output/{filename}.js.map")),
// map.as_bytes(),
// )
// .unwrap();
// }
ModuleDependency {
Ok(ModuleDependency {
deps: import_parser.sync_imports,
async_deps: import_parser.async_imports,
specifier: vec![],
source: result.code,
map: result.map,
filename: file_name.to_string(),
is_main: false,
}
})
}
5 changes: 2 additions & 3 deletions src/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub async fn load(filename: &String) -> anyhow::Result<ModuleDependency> {
let now = Local::now().timestamp_millis();
let data = reqwest::get(filename).await?;
let data = data.text().await?;
let data = compile(filename, &data);
let data = compile(filename, &data)?;
println!(
"{} {}",
"Downland ".green(),
Expand All @@ -50,8 +50,7 @@ pub async fn load(filename: &String) -> anyhow::Result<ModuleDependency> {
return Ok(data);
};
let data = tokio::fs::read(&filename).await?;
let data = compile(filename, &String::from_utf8_lossy(&data).to_string());
return Ok(data);
compile(filename, &String::from_utf8_lossy(&data).to_string())
}

#[derive(Debug)]
Expand Down
17 changes: 12 additions & 5 deletions src/runner/console.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,20 @@ pub fn console_format(
}
if v.is_object() {
let obj = v8::Local::<v8::Object>::try_from(*v).unwrap();

if v.is_native_error() {
let stack = v8::String::new(scope, "stack").unwrap();
let stack = obj
.get(scope, stack.into())
.unwrap()
.to_rust_string_lossy(scope);
return format!("{stack}");
}

let names = obj
.get_own_property_names(scope, Default::default())
.unwrap();
// let prototype = obj.get_prototype(scope).unwrap();

let mut fmt = (0..names.length())
.map(|index| {
let name = names.get_index(scope, index).unwrap();
Expand Down Expand Up @@ -128,8 +138,5 @@ pub fn console_log(
.collect::<Vec<_>>()
.join(" ");

println!(
"{} {result}",
format!("{}", Utc::now().format("%Y-%m-%d %H:%M:%S%.3f")).color("gray")
);
println!("{result}");
}
33 changes: 23 additions & 10 deletions src/runtime/asynchronous.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,29 @@
use anyhow::anyhow;
use std::task::Poll;

use v8::Isolate;

use super::Runtime;

#[derive(Debug, PartialEq)]
pub enum AsynchronousKind {
Operation(u32),
Import((String, v8::Global<v8::PromiseResolver>)),
Operation(u32),
}

impl AsynchronousKind {
pub fn exec(&self, isolate: &mut Isolate) -> Poll<()> {
match self {
match match self {
AsynchronousKind::Operation(id) => Self::operation(isolate, id.clone()),
AsynchronousKind::Import((specifier, resolver)) => {
Self::import(isolate, specifier, resolver)
}
} {
Ok(v) => v,
Err(e) => panic!("error {}", e),
}
}
fn operation(isolate: &mut Isolate, id: u32) -> Poll<()> {

fn operation(isolate: &mut Isolate, id: u32) -> anyhow::Result<Poll<()>> {
let state_rc = Runtime::state(isolate);

let context = {
Expand All @@ -41,15 +45,23 @@ impl AsynchronousKind {
false,
);
let source = v8::String::new(scope, &format!("globalThis.exec({id});")).unwrap();
let script = v8::Script::compile(scope, source, Some(&origin)).unwrap();
script.run(scope).unwrap();
return Poll::Ready(());
let tc_scope = &mut v8::TryCatch::new(scope);
let script = v8::Script::compile(tc_scope, source, Some(&origin))
.ok_or(anyhow!("compile script failure"))?;
script
.run(tc_scope)
.ok_or(anyhow!("run script failure {}", id))?;

if tc_scope.has_caught() {
panic!("exec error");
}
return Ok(Poll::Ready(()));
}
fn import(
isolate: &mut Isolate,
specifier: &String,
resolver: &v8::Global<v8::PromiseResolver>,
) -> Poll<()> {
) -> anyhow::Result<Poll<()>> {
let state_rc = Runtime::state(isolate);
let graph_rc = Runtime::graph(isolate);

Expand All @@ -71,7 +83,8 @@ impl AsynchronousKind {
let table = graph.table.borrow();
let dep = table
.get(specifier)
.expect(&format!("specifier `{}` not found", specifier));
.ok_or(anyhow!("specifier `{}` not found", specifier))?;
// .expect(&format!("specifier `{}` not found", specifier));

if dep.initialize(isolate).is_some() {
dep.evaluate(isolate);
Expand All @@ -90,6 +103,6 @@ impl AsynchronousKind {
};
};

return Poll::Ready(());
return Ok(Poll::Ready(()));
}
}
7 changes: 4 additions & 3 deletions src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl Runtime {
state
}

fn bootstrap(&mut self, entry: &String) {
fn bootstrap(&mut self, entry: &String) -> anyhow::Result<()> {
let isolate = self.isolate.as_mut();
let state_rc = Self::state(isolate);
let graph_rc = Self::graph(isolate);
Expand All @@ -121,7 +121,7 @@ impl Runtime {
let dependency = compile::compile(
&bootstrap_js.to_string_lossy().to_string(),
&include_str!("../../bootstrap/main.ts").to_string(),
);
)?;

dependency.initialize(isolate);
dependency.evaluate(isolate);
Expand Down Expand Up @@ -153,10 +153,11 @@ impl Runtime {

let entry = v8::String::new(tc_scope, &entry).unwrap();
fun.call(tc_scope, this.into(), &[entry.into()]);
Ok(())
}

pub async fn run(&mut self, entry: &String) -> anyhow::Result<()> {
self.bootstrap(entry);
self.bootstrap(entry)?;

let isolate = self.isolate.as_mut();
let state_rc = Self::state(isolate);
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/static_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl Runtime {
pub fn timer_send(
scope: &mut v8::HandleScope,
info: v8::FunctionCallbackArguments,
mut rv: v8::ReturnValue,
rv: v8::ReturnValue,
) {
let state_rc = Runtime::state(scope);
let id = info
Expand Down
15 changes: 6 additions & 9 deletions test/test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import "https://deno.land/[email protected]/examples/welcome.ts";
import "https://deno.land/[email protected]/examples/welcome.ts";
// import "https://deno.land/[email protected]/examples/welcome.ts";
// import "https://deno.land/[email protected]/examples/welcome.ts";

const res = await import("./test1.ts");
console.log("res", res);
try {
const text = await res.json();
console.log("🚀 text", text);
test.copy();
} catch (err) {
console.error("err => ", err);
}
const text = await res.json();
console.log("🚀 text", text);
test.copy();

12 changes: 5 additions & 7 deletions test/test1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,18 @@ setTimeout(
(...arg: number[]) => {
console.log("Hello Timeout", ...arg);
},
1000,
100,
1,
2,
3,
3
);
console.log("Welcome Timeout!");

setTimeout((...arg: number[]) => {
console.log("Timeout 2", ...arg, /^bin$/g);
}, 100);
console.log("Timeout 2", /^bin$/g);
}, 10);

export default {
copy() {
console.log("1121");
},
};

export function* x() {}

0 comments on commit f1bc378

Please sign in to comment.