Skip to content
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

feat: import #8

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
3 changes: 1 addition & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ clap = { version = "4.5.9", features = ["derive"] }
cliclack = "0.3.2"
console = "0.15.8"
miette = { version = "7.2.0", features = ["fancy"] }
nova_vm = { git = "https://github.com/marc2332/nova", branch = "feat/hold-global-values-across-gc-calls", features = ["typescript"] }
nova_vm = { path = "../nova/nova_vm", features = ["typescript"] }
oxc_ast = "0.20.0"
oxc_parser = "0.20.0"
oxc_span = "0.20.0"
Expand Down
1 change: 1 addition & 0 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ edition = "2021"
[dependencies]
nova_vm = { workspace = true }
oxc_allocator = { workspace = true }
oxc_ast = { workspace = true }
anymap = { workspace = true }
tokio = { workspace = true }
miette = { workspace = true }
Expand Down
71 changes: 58 additions & 13 deletions core/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::{
any::Any,
cell::RefCell,
collections::VecDeque,
path::PathBuf,
sync::{atomic::Ordering, mpsc::Receiver},
};

Expand All @@ -11,17 +12,22 @@ use nova_vm::ecmascript::{
agent::{HostHooks, Job, Options},
initialize_host_defined_realm, Agent, JsResult, Realm,
},
scripts_and_modules::script::{parse_script, script_evaluation},
scripts_and_modules::{
script::{parse_script, script_evaluation},
ScriptOrModule,
},
types::{Object, Value},
};
use oxc_allocator::Allocator;
use oxc_ast::ast;

use crate::{
exit_with_parse_errors, initialize_recommended_builtins, initialize_recommended_extensions,
HostData, MacroTask,
};

pub struct RuntimeHostHooks {
allocator: Allocator,
promise_job_queue: RefCell<VecDeque<Job>>,
host_data: HostData,
}
Expand All @@ -33,10 +39,11 @@ impl std::fmt::Debug for RuntimeHostHooks {
}

impl RuntimeHostHooks {
pub fn new(host_data: HostData) -> Self {
pub fn new(host_data: HostData, allocator: Allocator) -> Self {
Self {
promise_job_queue: RefCell::default(),
host_data,
allocator,
}
}

Expand All @@ -57,6 +64,43 @@ impl HostHooks for RuntimeHostHooks {
fn get_host_data(&self) -> &dyn Any {
&self.host_data
}

// TODO: Implement a transport abstraction.
fn import_module(&self, import: &ast::ImportDeclaration<'_>, agent: &mut Agent) {
let realm_id = agent.current_realm_id();

let script_or_module = agent.running_execution_context().script_or_module.unwrap();
let script_id = match script_or_module {
ScriptOrModule::Script(script_id) => script_id,
_ => todo!(),
};
let script = &agent[script_id];

let current_host_path = script.host_defined.as_ref().unwrap();
let mut current_host_path = current_host_path
.downcast_ref::<PathBuf>()
.unwrap()
.to_path_buf();
current_host_path.pop(); // Use the parent folder
let current_host_path = std::fs::canonicalize(&current_host_path).unwrap();

let import_path = import.source.value.as_str();
let host_path = current_host_path.join(import_path);
let host_path = std::fs::canonicalize(host_path).unwrap();

let file = std::fs::read_to_string(&host_path).unwrap();
let script = match parse_script(
&self.allocator,
file.into(),
realm_id,
false,
Some(Box::leak(Box::new(host_path))),
) {
Ok(script) => script,
Err((file, errors)) => exit_with_parse_errors(errors, import_path, &file),
};
script_evaluation(agent, script).unwrap();
}
}

pub struct RuntimeConfig {
Expand All @@ -68,16 +112,16 @@ pub struct RuntimeConfig {
pub struct Runtime {
pub config: RuntimeConfig,
pub agent: Agent,
pub allocator: Allocator,
pub host_hooks: &'static RuntimeHostHooks,
pub macro_task_rx: Receiver<MacroTask>,
}

impl Runtime {
/// Create a new [Runtime] given a [RuntimeConfig]. Use [Runtime::run] to run it.
pub fn new(config: RuntimeConfig) -> Self {
let allocator = Allocator::default();
let (host_data, macro_task_rx) = HostData::new();
let host_hooks = RuntimeHostHooks::new(host_data);
let host_hooks = RuntimeHostHooks::new(host_data, allocator);

let host_hooks: &RuntimeHostHooks = &*Box::leak(Box::new(host_hooks));
let mut agent = Agent::new(
Expand All @@ -97,11 +141,9 @@ impl Runtime {
Some(initialize_recommended_extensions),
);
}
let allocator = Allocator::default();

Self {
config,
allocator,
agent,
host_hooks,
macro_task_rx,
Expand All @@ -113,34 +155,37 @@ impl Runtime {
let realm = self.agent.current_realm_id();

// LOad the builtins js sources
initialize_recommended_builtins(&self.allocator, &mut self.agent, self.config.no_strict);
initialize_recommended_builtins(
&self.host_hooks.allocator,
&mut self.agent,
self.config.no_strict,
);

let mut final_result = Value::Null;

// Fetch the runtime mod.ts file using a macro and add it to the paths
for path in &self.config.paths {
let file = std::fs::read_to_string(path).unwrap();
let host_path = PathBuf::from(path);
let script = match parse_script(
&self.allocator,
&self.host_hooks.allocator,
file.into(),
realm,
!self.config.no_strict,
None,
Some(Box::leak(Box::new(host_path))),
) {
Ok(script) => script,
Err((file, errors)) => exit_with_parse_errors(errors, path, &file),
};
final_result = match script_evaluation(&mut self.agent, script) {
Ok(v) => v,
err @ _ => return err,
err => return err,
}
}

loop {
while let Some(job) = self.host_hooks.pop_promise_job() {
if let Err(err) = job.run(&mut self.agent) {
return Err(err);
}
job.run(&mut self.agent)?;
}

// If both the microtasks and macrotasks queues are empty we can end the event loop
Expand Down
1 change: 1 addition & 0 deletions examples/b.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("b.ts")
7 changes: 2 additions & 5 deletions examples/main.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
/// <reference path="../runtime/global.d.ts" />

const name = prompt("what is your name?");
Andromeda.sleep(1000)
.then(() => {
console.log(`Hello, ${name}`);
})
import './sleep.ts'

console.log("main.ts")
6 changes: 3 additions & 3 deletions examples/sleep.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[1,2,3,4].forEach((i) => {
Andromeda.sleep(i * 1000).then(() => console.log(`${i}s`))
})
import "./b.ts"

console.log("sleep.ts")