1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
//! Crabzilla provides a _simple_ interface for running JavaScript modules alongside Rust code.
//! <br>
//! # Example
//! ```
//! use crabzilla::*;
//! use std::io::stdin;
//! 
//! #[import_fn]
//! fn read_from_stdin() -> Value {
//!     let mut buffer = String::new();
//!     println!("Type your name: ");
//!     stdin().read_line(&mut buffer)?;
//!     buffer.pop();
//!     Value::String(buffer)
//! }
//! 
//! #[import_fn]
//! fn say_hello(args: Vec<Value>) {
//!     if let Some(string) = args.get(0) {
//!         if let Value::String(string) = string {
//!             println!("Hello, {}", string);
//!         }
//!     }
//! }
//! 
//! #[tokio::main]
//! async fn main() {
//!     let mut runtime = runtime! {
//!         read_from_stdin,
//!         say_hello,
//!     };
//!     if let Err(error) = runtime.load_module("./module.js").await {
//!         eprintln!("{}", error);
//!     }
//! }
//! ```
//! In `module.js`:
//! ```
//! const user = read_from_stdin();
//! say_hello(user);
//! ```
use deno_core::{
    FsModuleLoader,
    JsRuntime,
    ModuleSpecifier,
    OpState,
    OpFn,
    ZeroCopyBuf,
    // json_op_async,
    json_op_sync,
    // BufVec,
};
use std::rc::Rc;
// use std::cell::RefCell;
// use futures::Future;
pub use deno_core::serde_json::value::Value;
pub use deno_core::error::AnyError;
pub use import_fn::import_fn;

fn get_args(value: &Value) -> Vec<Value> {
    if let Value::Object(map) = &value {
        if let Some(Value::Array(args)) = &map.get("args") {
            return args.to_owned();
        }
    }
    unreachable!();
}

/// Represents an imported Rust function.
pub enum ImportedFn {
    Sync(Box<OpFn>, String),
    Async(Box<OpFn>, String),
}

/// Receives a Rust function and returns a structure that can be imported in to a runtime.
pub fn create_sync_fn<F>(imported_fn: F, name: String) -> ImportedFn where
    F: Fn(Vec<Value>) -> Result<Value, AnyError> + 'static,
{
    let op_fn = json_op_sync(
        move |_state: &mut OpState, value: Value, _buffer: &mut [ZeroCopyBuf]| -> Result<Value, AnyError> {
            imported_fn(get_args(&value))
        }
    );
    ImportedFn::Sync(
        op_fn,
        name,
    )
}

// pub fn create_async_fn<F, R>(imported_fn: F, name: String) -> ImportedFn where
//     F: Fn(Vec<Value>) -> R + 'static,
//     R: Future<Output = Result<Value, AnyError>> + 'static,
// {
//     let op_fn = json_op_async(
//         move |_state: Rc<RefCell<OpState>>, value: Value, _buffer: BufVec| -> R {
//             imported_fn(get_args(&value))
//         }
//     );
//     ImportedFn::Async(
//         op_fn,
//         name,
//     )
// }

enum ImportedName {
    Sync(String),
    Async(String),
}

/// Represents a JavaScript runtime instance.
pub struct Runtime {
    runtime: JsRuntime,
    imported_names: Vec<ImportedName>,
}

impl Runtime {
    pub fn new() -> Self {
        let runtime = JsRuntime::new(deno_core::RuntimeOptions{
            module_loader: Some(Rc::new(FsModuleLoader)),
            ..Default::default()
        });
        let imported_names = vec![];
        Runtime {
            runtime,
            imported_names,
        }
    }

    pub fn import<F>(&mut self, imported_fn: F) where F: Fn() -> ImportedFn {
        match imported_fn() {
            ImportedFn::Sync(op_fn, name) => {
                self.runtime.register_op(&name, op_fn);
                self.imported_names.push(ImportedName::Sync(name));
            },
            ImportedFn::Async(op_fn, name) => {
                self.runtime.register_op(&name, op_fn);
                self.imported_names.push(ImportedName::Async(name));
            },
        }
    }

    pub fn importing_finished(&mut self) {
        let mut definitions = String::new();
        for import in self.imported_names.iter() {
            match import {
                ImportedName::Sync(name) => definitions.push_str(&format!("window[{:?}]=(...args)=>Deno.core.jsonOpSync({0:?}, {{args}});", name)),
                ImportedName::Async(name) => definitions.push_str(&format!("window[{:?}]=(...args)=>Deno.core.jsonOpAsync({0:?}, {{args}});", name)),
            }
        }
        let js_source = format!("\"use strict\";((window)=>{{Deno.core.ops();{}}})(this);", definitions);
        self.runtime.execute("rust:core.js", &js_source).expect("runtime exporting");
    }

    pub async fn load_module(&mut self, path_str: &str) -> Result<(), AnyError> {
        let specifier = ModuleSpecifier::resolve_path(path_str)?;
        let id = self.runtime.load_module(&specifier, None).await?;
        self.runtime.mod_evaluate(id).await
    }
}

/// Creates a runtime object and imports a list of functions.
///
/// # Example
/// ```
/// #[import_fn]
/// fn foo() {
///   // Do something
/// }
///
/// #[import_fn]
/// fn bar() {
///   // Do something else
/// }
///
/// let mut runtime = runtime! {
///    foo,
///    bar,
///  };
/// ```
#[macro_export]
macro_rules! runtime {
    ($($fn:ident),* $(,)?) => {
        {
            let mut runtime = crabzilla::Runtime::new();
            $(
                runtime.import($fn);
            )*
            runtime.importing_finished();
            runtime
        }
    }
}