use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use crate::ast::CompilationUnit;
use crate::callable::NativeFunction;
use crate::class::{BridgedClassDef, BridgedEnumDef};
use crate::env::Environment;
use crate::error::InterpError;
use crate::interp::InterpreterVisitor;
use crate::permission::{FilesystemPermission, NetworkPermission, Permission, ProcessPermission};
use crate::rt::FunctionRuntimeType;
use crate::value::{Value, value_display};
type PrintHandler = Box<dyn Fn(&str)>;
pub type NativeFn = Box<
dyn Fn(
&mut InterpreterVisitor,
Vec<Value>,
HashMap<String, Value>,
) -> Result<Value, InterpError>,
>;
pub struct Context {
env: Rc<RefCell<Environment>>,
print_handler: Rc<RefCell<PrintHandler>>,
state: Rc<crate::state::ContextState>,
interpreted_instance: Option<Value>,
}
#[derive(Default, Clone, Debug)]
pub struct SandboxOptions {
pub filesystem: Option<FilesystemPermission>,
pub network: Option<NetworkPermission>,
pub process: Option<ProcessPermission>,
pub isolate: bool,
pub env: bool,
pub filesystem_modules: bool,
}
impl SandboxOptions {
pub fn allow_all() -> Self {
SandboxOptions {
filesystem: Some(FilesystemPermission::Any),
network: Some(NetworkPermission::Any),
process: Some(ProcessPermission::Any),
isolate: true,
env: true,
filesystem_modules: true,
}
}
}
pub(crate) fn catch_dart_panic<T>(
f: impl FnOnce() -> Result<T, InterpError>,
) -> Result<T, InterpError> {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(result) => result,
Err(payload) => {
let msg = payload
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| payload.downcast_ref::<&str>().copied())
.unwrap_or("unknown internal error");
Err(InterpError::runtime(format!(
"Internal interpreter error (panic caught at the Context boundary): {msg}"
)))
}
}
}
impl Context {
pub fn new_with(options: SandboxOptions) -> Self {
let mut ctx = Context::new();
if let Some(fs) = options.filesystem {
ctx.grant(Permission::Filesystem(fs));
}
if let Some(net) = options.network {
ctx.grant(Permission::Network(net));
}
if let Some(proc) = options.process {
ctx.grant(Permission::Process(proc));
}
if options.isolate {
ctx.grant(Permission::Isolate);
}
if options.env {
ctx.grant(Permission::Env);
}
if options.filesystem_modules {
ctx.grant(Permission::ModuleFiles);
}
ctx
}
pub fn new() -> Self {
let state = crate::state::ContextState::new();
let (env, print_handler) = crate::state::with_current(&state, || {
let env = Environment::new();
crate::stdlib::core::load_core(&env);
#[cfg(feature = "async")]
if let Some(async_env) = crate::stdlib::load_library("dart:async") {
Environment::import_environment(&env, &async_env, None, None).expect("async load");
}
let print_handler: Rc<RefCell<PrintHandler>> =
Rc::new(RefCell::new(Box::new(|s: &str| println!("{s}"))));
let handler = print_handler.clone();
let print_fn = NativeFunction {
name: Some("print".to_string()),
min_arity: 1,
max_arity: Some(1),
is_async: false,
is_generator: false,
closure: Box::new(move |visitor, positional, _named| {
let s = positional
.first()
.map(|v| {
visitor
.display_value(v)
.unwrap_or_else(|_| value_display(v))
})
.unwrap_or_default();
(handler.borrow())(&s);
Ok(Value::Null)
}),
callable_runtime_type: FunctionRuntimeType::untyped(),
};
Environment::define(&env, "print", Value::NativeFn(Rc::new(print_fn)));
(env, print_handler)
});
Context {
env,
print_handler,
state,
interpreted_instance: None,
}
}
pub fn eval(&mut self, source: &str) -> Result<Value, InterpError> {
match self.execute(source, "main", vec![], HashMap::new()) {
Ok(v) => self.pump_to_completion(v),
Err(e) if e.message().is_some_and(|m| m.contains("not defined")) => Ok(Value::Null),
Err(e) => Err(e),
}
}
pub fn pump_to_completion(&mut self, v: Value) -> Result<Value, InterpError> {
let mut guard: u64 = 0;
loop {
match self.drive_bounded(&v, u64::MAX, &mut guard) {
Ok(DriveVerdict::Done(res)) => return Ok(res),
Ok(DriveVerdict::Wait) => {}
Err(e) => return Err(e),
}
}
}
pub async fn execute_async_await(
&mut self,
source: &str,
name: &str,
positional: Vec<Value>,
named: HashMap<String, Value>,
) -> Result<Value, InterpError> {
let v = self.execute(source, name, positional, named)?;
let mut guard: u64 = 0;
loop {
match self.drive_bounded(&v, MAX_STEPS_PER_BATCH, &mut guard) {
Ok(DriveVerdict::Done(res)) => return Ok(res),
Ok(DriveVerdict::Wait) => yield_now().await,
Err(e) => return Err(e),
}
}
}
pub fn execute(
&mut self,
source: &str,
name: &str,
positional: Vec<Value>,
named: HashMap<String, Value>,
) -> Result<Value, InterpError> {
catch_dart_panic(|| {
crate::state::with_current(&self.state, || {
let unit = Rc::new(CompilationUnit::parse(source)?);
let mut visitor = InterpreterVisitor::new(self.env.clone());
visitor.execute_top_level(&unit)?;
let result = match Environment::get(&self.env, name) {
Ok(Value::Function(f)) => {
visitor.call_interpreted_function(&f, positional, named)
}
Ok(Value::NativeFn(n)) => visitor.call_native_function(&n, positional, named),
Ok(other) => Err(InterpError::runtime(format!(
"{name} is not a function: {}",
value_display(&other)
))),
Err(_) => Err(InterpError::runtime(format!(
"Function '{name}' is not defined"
))),
};
if let Ok(v) = &result
&& matches!(v, Value::Instance(_) | Value::Bridged(_))
{
self.interpreted_instance = Some(v.clone());
}
result
})
})
}
pub fn invoke(
&mut self,
name: &str,
positional: Vec<Value>,
named: HashMap<String, Value>,
) -> Result<Value, InterpError> {
let instance = self.interpreted_instance.clone().ok_or_else(|| {
InterpError::runtime("No interpreted instance found. Call execute() before invoke().")
})?;
catch_dart_panic(|| {
crate::state::with_current(&self.state, || {
let mut visitor = InterpreterVisitor::new(self.env.clone());
let member = match &instance {
Value::Instance(inst) => {
crate::value::instance_get(inst, name, Some(&mut visitor))?
}
Value::Bridged(b) => visitor.bridged_instance_get(b, name)?,
Value::BridgedClass(bc) => visitor.get_bridged_class_member(bc, name)?,
other => {
return Err(InterpError::runtime(format!(
"Cannot invoke '{name}' on {}",
value_display(other)
)));
}
};
if matches!(
&member,
Value::Function(_)
| Value::NativeFn(_)
| Value::BridgedSuperMethod(_)
| Value::BridgedMixinMethod(_)
| Value::BridgedEnumMixinMethod(_)
| Value::BoundBridgedSuper(_)
) {
visitor.call_value(&member, positional, named)
} else {
Ok(member)
}
})
})
}
pub fn eval_expression(&mut self, source: &str) -> Result<Value, InterpError> {
catch_dart_panic(|| {
crate::state::with_current(&self.state, || {
crate::interp::evaluate_expression_in(&self.env, source)
})
})
}
pub fn execute_async(
&mut self,
source: &str,
name: &str,
positional: Vec<Value>,
named: HashMap<String, Value>,
) -> Result<Value, InterpError> {
let v = self.execute(source, name, positional, named)?;
self.pump_to_completion(v)
}
pub fn register_function<F>(&mut self, name: &str, f: F)
where
F: Fn(
&mut InterpreterVisitor,
Vec<Value>,
HashMap<String, Value>,
) -> Result<Value, InterpError>
+ 'static,
{
let native = NativeFunction {
name: Some(name.to_string()),
min_arity: 0,
max_arity: None,
is_async: false,
is_generator: false,
closure: Box::new(f),
callable_runtime_type: FunctionRuntimeType::untyped(),
};
Environment::define(&self.env, name, Value::NativeFn(Rc::new(native)));
}
pub fn register_bridged_class(&mut self, bridged: Arc<BridgedClassDef>) {
Environment::define_bridge(&self.env, bridged);
}
pub fn register_bridged_enum(&mut self, def: Rc<BridgedEnumDef>) {
Environment::define_bridged_enum(&self.env, def);
}
pub fn get(&self, name: &str) -> Result<Value, InterpError> {
Environment::get(&self.env, name)
}
pub fn set(&mut self, name: &str, value: Value) {
Environment::define(&self.env, name, value);
}
pub fn set_print_handler<F>(&mut self, handler: F)
where
F: Fn(&str) + 'static,
{
*self.print_handler.borrow_mut() = Box::new(handler);
}
pub fn env(&self) -> Rc<RefCell<Environment>> {
self.env.clone()
}
pub fn grant(&mut self, permission: Permission) {
self.state.permissions.grant(permission);
}
pub fn revoke(&mut self, permission: &Permission) {
self.state.permissions.revoke(permission);
}
pub fn register_dart_module(&mut self, name: &str, source: &str) {
self.state
.virtual_modules
.borrow_mut()
.insert(name.to_string(), source.to_string());
}
pub fn register_module_library(&mut self, uri: &str, classes: Vec<Arc<BridgedClassDef>>) {
let mut reg = self.state.module_libraries.borrow_mut();
let entry = reg.entry(uri.to_string()).or_default();
for c in classes {
if !entry.iter().any(|e| e.name == c.name) {
entry.push(c);
}
}
}
pub fn register_package_library(&mut self, uri: &str, classes: Vec<Arc<BridgedClassDef>>) {
self.register_module_library(uri, classes);
}
pub fn has_permission(&self, permission: &Permission) -> bool {
self.state.permissions.allows(permission)
}
fn drive_bounded(
&mut self,
v: &Value,
step_limit: u64,
guard: &mut u64,
) -> Result<DriveVerdict, InterpError> {
let state = self.state.clone();
catch_dart_panic(|| {
crate::state::with_current(&state, || self.drive_bounded_inner(v, step_limit, guard))
})
}
fn drive_bounded_inner(
&mut self,
v: &Value,
step_limit: u64,
guard: &mut u64,
) -> Result<DriveVerdict, InterpError> {
let mut visitor = crate::interp::InterpreterVisitor::new(self.env.clone());
let mut steps: u64 = 0;
loop {
*guard += 1;
if std::env::var("D4RT_DEBUG_AWAIT").is_ok() && (*guard).is_multiple_of(500) {
eprintln!("PUMP iteration {guard}"); }
if *guard > 1_000_000 {
return Err(InterpError::runtime("pump runaway guard hit"));
}
match crate::async_state::unwrap_future(v) {
None => return Ok(DriveVerdict::Done(v.clone())),
Some(f) => {
let completed = {
let st = f.borrow();
st.completed
};
if completed {
let result = {
let st = f.borrow();
crate::async_state::future_result(&st)
};
return match result {
Ok(val) => Ok(DriveVerdict::Done(val)),
Err(e) => Err(InterpError::Throw(e)),
};
}
match crate::async_state::dequeue_task() {
Some(task) => {
crate::async_state::process_task(&mut visitor, task);
}
None => {
return Err(InterpError::runtime(
"Async deadlock: no pending tasks for an incomplete future",
));
}
}
}
}
steps += 1;
if steps >= step_limit {
return Ok(DriveVerdict::Wait);
}
}
}
}
const MAX_STEPS_PER_BATCH: u64 = 64;
enum DriveVerdict {
Done(Value),
Wait,
}
struct YieldNow;
impl std::future::Future for YieldNow {
type Output = ();
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
cx.waker().wake_by_ref();
std::task::Poll::Pending
}
}
fn yield_now() -> YieldNow {
YieldNow
}
#[cfg(test)]
fn block_on<F: std::future::Future>(mut fut: F) -> F::Output {
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
fn noop_clone(_: *const ()) -> RawWaker {
noop_raw_waker()
}
fn noop(_: *const ()) {}
fn noop_raw_waker() -> RawWaker {
RawWaker::new(
std::ptr::null(),
&RawWakerVTable::new(noop_clone, noop, noop, noop),
)
}
let waker = unsafe { Waker::from_raw(noop_raw_waker()) };
let mut cx = Context::from_waker(&waker);
loop {
match unsafe { std::pin::Pin::new_unchecked(&mut fut) }.poll(&mut cx) {
Poll::Ready(r) => return r,
Poll::Pending => continue,
}
}
}
impl Default for Context {
fn default() -> Self {
Self::new()
}
}
impl Drop for Context {
fn drop(&mut self) {
#[cfg(feature = "io")]
crate::stdlib::http::cleanup_context(self.state.id);
#[cfg(feature = "io")]
crate::stdlib::io::cleanup_context(self.state.id);
#[cfg(feature = "io")]
crate::stdlib::process::cleanup_context(self.state.id);
}
}
pub struct SendableContext(Context);
unsafe impl Send for SendableContext {}
impl SendableContext {
pub fn new(context: Context) -> Self {
SendableContext(context)
}
pub fn into_inner(self) -> Context {
self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn contexts_are_independent() {
let mut a = Context::new();
let mut b = Context::new();
a.eval("var shared = 10;").unwrap();
assert!(b.eval_expression("shared").is_err());
assert_eq!(a.eval_expression("shared").unwrap(), Value::Int(10));
}
#[test]
fn register_and_call() {
let mut ctx = Context::new();
ctx.register_function("double_it", |_v, args, _named| {
let n = crate::helpers::as_int(&args[0]).unwrap_or(0);
Ok(Value::Int(n * 2))
});
assert_eq!(
ctx.eval_expression("double_it(21)").unwrap(),
Value::Int(42)
);
}
#[test]
fn execute_with_args() {
let mut ctx = Context::new();
let v = ctx
.execute(
"int add(int a, int b) => a + b;",
"add",
vec![Value::Int(2), Value::Int(3)],
HashMap::new(),
)
.unwrap();
assert_eq!(v, Value::Int(5));
}
#[test]
fn print_handler_captures_output() {
let mut ctx = Context::new();
let captured = Rc::new(RefCell::new(Vec::new()));
let c = captured.clone();
ctx.set_print_handler(move |s| c.borrow_mut().push(s.to_string()));
ctx.eval("void main() { print('hello'); print('world'); }")
.unwrap();
assert_eq!(
*captured.borrow(),
vec!["hello".to_string(), "world".to_string()]
);
}
#[cfg(feature = "async")]
#[test]
fn execute_async_waits_for_future() {
let mut ctx = Context::new();
let src = "Future<int> compute(int n) async { await Future.delayed(Duration(milliseconds: 5)); return n * 2; }";
let v = ctx
.execute_async(src, "compute", vec![Value::Int(21)], HashMap::new())
.unwrap();
assert_eq!(v, Value::Int(42));
}
#[test]
fn execute_async_returns_sync_values_unchanged() {
let mut ctx = Context::new();
let v = ctx
.execute_async(
"int add(int a, int b) => a + b;",
"add",
vec![Value::Int(2), Value::Int(3)],
HashMap::new(),
)
.unwrap();
assert_eq!(v, Value::Int(5));
}
#[cfg(feature = "async")]
#[test]
fn execute_async_await_cooperative_resolves_future() {
let mut ctx = Context::new();
let src = "Future<int> compute(int n) async { for (var i = 0; i < 5; i++) { await Future.delayed(Duration(milliseconds: 1)); } return n * 3; }";
let v = block_on(async {
ctx.execute_async_await(src, "compute", vec![Value::Int(14)], HashMap::new())
.await
})
.unwrap();
assert_eq!(v, Value::Int(42));
}
#[test]
fn execute_async_await_cooperative_returns_sync_immediately() {
let mut ctx = Context::new();
let v = block_on(async {
ctx.execute_async_await(
"int add(int a, int b) => a + b;",
"add",
vec![Value::Int(2), Value::Int(3)],
HashMap::new(),
)
.await
})
.unwrap();
assert_eq!(v, Value::Int(5));
}
#[test]
fn execute_async_await_propagates_async_error() {
let mut ctx = Context::new();
let src = "Future<int> boom() async { await Future.delayed(Duration(milliseconds: 1)); throw StateError('kaboom'); }";
let res = block_on(async {
ctx.execute_async_await(src, "boom", vec![], HashMap::new())
.await
});
assert!(res.is_err());
}
}