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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
//! Loaders and resolvers for loading JS modules.

use std::{ffi::CStr, ptr};

use crate::{module::ModuleData, qjs, Ctx, Module, Result};

mod builtin_resolver;
pub use builtin_resolver::BuiltinResolver;

mod file_resolver;
pub use file_resolver::FileResolver;

mod script_loader;
pub use script_loader::ScriptLoader;

mod builtin_loader;
pub use builtin_loader::BuiltinLoader;

mod module_loader;
pub use module_loader::ModuleLoader;

mod compile;
pub use compile::Compile;

#[cfg(feature = "dyn-load")]
mod native_loader;
#[cfg(feature = "dyn-load")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "dyn-load")))]
pub use native_loader::NativeLoader;

pub mod bundle;

#[cfg(feature = "phf")]
/// The type of bundle that the `embed!` macro returns
pub type Bundle = bundle::Bundle<bundle::PhfBundleData<&'static [u8]>>;

#[cfg(not(feature = "phf"))]
/// The type of bundle that the `embed!` macro returns
pub type Bundle = bundle::Bundle<bundle::ScaBundleData<&'static [u8]>>;

mod util;

/// Module resolver interface
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "loader")))]
pub trait Resolver {
    /// Normalize module name
    ///
    /// The resolving may looks like:
    ///
    /// ```no_run
    /// # use rquickjs::{Ctx, Result, Error};
    /// # fn default_resolve<'js>(_ctx: &Ctx<'js>, base: &str, name: &str) -> Result<String> {
    /// Ok(if !name.starts_with('.') {
    ///     name.into()
    /// } else {
    ///     let mut split = base.rsplitn(2, '/');
    ///     let path = match (split.next(), split.next()) {
    ///         (_, Some(path)) => path,
    ///         _ => "",
    ///     };
    ///     format!("{path}/{name}")
    /// })
    /// # }
    /// ```
    fn resolve<'js>(&mut self, ctx: &Ctx<'js>, base: &str, name: &str) -> Result<String>;
}

/// Module loader interface
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "loader")))]
pub trait Loader {
    /// Load module by name
    fn load<'js>(&mut self, ctx: &Ctx<'js>, name: &str) -> Result<ModuleData>;
}

/// The Raw Module loader interface.
///
/// When implementing a module loader prefer the to implement [`Loader`] instead.
/// All struct which implement [`Loader`] will automatically implement this trait.
///
/// # Safety
/// Implementors must ensure that all module declaration and evaluation errors are returned from
/// this function.
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "loader")))]
pub unsafe trait RawLoader {
    /// Load module by name, should return an unevaluated module.
    ///
    /// # Safety
    /// Callers must ensure that the module returned by this function is not used after an module
    /// declaration or evaluation failed.
    unsafe fn raw_load<'js>(&mut self, ctx: &Ctx<'js>, name: &str) -> Result<Module<'js>>;
}

unsafe impl<T: Loader> RawLoader for T {
    unsafe fn raw_load<'js>(&mut self, ctx: &Ctx<'js>, name: &str) -> Result<Module<'js>> {
        let res = self.load(ctx, name)?.unsafe_declare(ctx.clone())?;
        Ok(res)
    }
}

struct LoaderOpaque {
    resolver: Box<dyn Resolver>,
    loader: Box<dyn RawLoader>,
}

#[derive(Debug)]
#[repr(transparent)]
pub(crate) struct LoaderHolder(*mut LoaderOpaque);

impl Drop for LoaderHolder {
    fn drop(&mut self) {
        let _opaque = unsafe { Box::from_raw(self.0) };
    }
}

impl LoaderHolder {
    pub fn new<R, L>(resolver: R, loader: L) -> Self
    where
        R: Resolver + 'static,
        L: RawLoader + 'static,
    {
        Self(Box::into_raw(Box::new(LoaderOpaque {
            resolver: Box::new(resolver),
            loader: Box::new(loader),
        })))
    }

    pub(crate) fn set_to_runtime(&self, rt: *mut qjs::JSRuntime) {
        unsafe {
            qjs::JS_SetModuleLoaderFunc(
                rt,
                Some(Self::normalize_raw),
                Some(Self::load_raw),
                self.0 as _,
            );
        }
    }

    #[inline]
    fn normalize<'js>(
        opaque: &mut LoaderOpaque,
        ctx: &Ctx<'js>,
        base: &CStr,
        name: &CStr,
    ) -> Result<*mut qjs::c_char> {
        let base = base.to_str()?;
        let name = name.to_str()?;

        let name = opaque.resolver.resolve(ctx, base, name)?;

        // We should transfer ownership of this string to QuickJS
        Ok(
            unsafe {
                qjs::js_strndup(ctx.as_ptr(), name.as_ptr() as _, name.as_bytes().len() as _)
            },
        )
    }

    unsafe extern "C" fn normalize_raw(
        ctx: *mut qjs::JSContext,
        base: *const qjs::c_char,
        name: *const qjs::c_char,
        opaque: *mut qjs::c_void,
    ) -> *mut qjs::c_char {
        let ctx = Ctx::from_ptr(ctx);
        let base = CStr::from_ptr(base);
        let name = CStr::from_ptr(name);
        let loader = &mut *(opaque as *mut LoaderOpaque);

        Self::normalize(loader, &ctx, base, name).unwrap_or_else(|error| {
            error.throw(&ctx);
            ptr::null_mut()
        })
    }

    #[inline]
    unsafe fn load<'js>(
        opaque: &mut LoaderOpaque,
        ctx: &Ctx<'js>,
        name: &CStr,
    ) -> Result<*mut qjs::JSModuleDef> {
        let name = name.to_str()?;

        Ok(opaque.loader.raw_load(ctx, name)?.as_module_def().as_ptr())
    }

    unsafe extern "C" fn load_raw(
        ctx: *mut qjs::JSContext,
        name: *const qjs::c_char,
        opaque: *mut qjs::c_void,
    ) -> *mut qjs::JSModuleDef {
        let ctx = Ctx::from_ptr(ctx);
        let name = CStr::from_ptr(name);
        let loader = &mut *(opaque as *mut LoaderOpaque);

        Self::load(loader, &ctx, name).unwrap_or_else(|error| {
            error.throw(&ctx);
            ptr::null_mut()
        })
    }
}

macro_rules! loader_impls {
    ($($t:ident)*) => {
        loader_impls!(@sub @mark $($t)*);
    };
    (@sub $($lead:ident)* @mark $head:ident $($rest:ident)*) => {
        loader_impls!(@impl $($lead)*);
        loader_impls!(@sub $($lead)* $head @mark $($rest)*);
    };
    (@sub $($lead:ident)* @mark) => {
        loader_impls!(@impl $($lead)*);
    };
    (@impl $($t:ident)*) => {
            impl<$($t,)*> Resolver for ($($t,)*)
            where
                $($t: Resolver,)*
            {
                #[allow(non_snake_case)]
                #[allow(unused_mut)]
                fn resolve<'js>(&mut self, _ctx: &Ctx<'js>, base: &str, name: &str) -> Result<String> {
                    let mut messages = Vec::<std::string::String>::new();
                    let ($($t,)*) = self;
                    $(
                        match $t.resolve(_ctx, base, name) {
                            // Still could try the next resolver
                            Err($crate::Error::Resolving { message, .. }) => {
                                message.map(|message| messages.push(message));
                            },
                            result => return result,
                        }
                    )*
                    // Unable to resolve module name
                    Err(if messages.is_empty() {
                        $crate::Error::new_resolving(base, name)
                    } else {
                        $crate::Error::new_resolving_message(base, name, messages.join("\n"))
                    })
                }
            }

            unsafe impl< $($t,)*> $crate::loader::RawLoader for ($($t,)*)
            where
                $($t: $crate::loader::RawLoader,)*
            {
                #[allow(non_snake_case)]
                #[allow(unused_mut)]
                unsafe fn raw_load<'js>(&mut self, _ctx: &Ctx<'js>, name: &str) -> Result<Module<'js>> {
                    let mut messages = Vec::<std::string::String>::new();
                    let ($($t,)*) = self;
                    $(
                        match $t.raw_load(_ctx, name) {
                            // Still could try the next loader
                            Err($crate::Error::Loading { message, .. }) => {
                                message.map(|message| messages.push(message));
                            },
                            result => return result,
                        }
                    )*
                    // Unable to load module
                    Err(if messages.is_empty() {
                        $crate::Error::new_loading(name)
                    } else {
                        $crate::Error::new_loading_message(name, messages.join("\n"))
                    })
                }
            }
    };
}
loader_impls!(A B C D E F G H);

#[cfg(test)]
mod test {
    use crate::{module::ModuleData, Context, Ctx, Error, Result, Runtime};

    use super::{Loader, Resolver};

    struct TestResolver;

    impl Resolver for TestResolver {
        fn resolve<'js>(&mut self, _ctx: &Ctx<'js>, base: &str, name: &str) -> Result<String> {
            if base == "loader" && name == "test" {
                Ok(name.into())
            } else {
                Err(Error::new_resolving_message(
                    base,
                    name,
                    "unable to resolve",
                ))
            }
        }
    }

    struct TestLoader;

    impl Loader for TestLoader {
        fn load<'js>(&mut self, _ctx: &Ctx<'js>, name: &str) -> Result<ModuleData> {
            if name == "test" {
                Ok(ModuleData::source(
                    "test",
                    r#"
                      export const n = 123;
                      export const s = "abc";
                    "#,
                ))
            } else {
                Err(Error::new_loading_message(name, "unable to load"))
            }
        }
    }

    #[test]
    fn custom_loader() {
        let rt = Runtime::new().unwrap();
        let ctx = Context::full(&rt).unwrap();
        rt.set_loader(TestResolver, TestLoader);
        ctx.with(|ctx| {
            let _module = ctx
                .compile(
                    "loader",
                    r#"
                      import { n, s } from "test";
                      export default [n, s];
                    "#,
                )
                .unwrap();
        })
    }

    #[test]
    #[should_panic(expected = "Unable to resolve")]
    fn resolving_error() {
        let rt = Runtime::new().unwrap();
        let ctx = Context::full(&rt).unwrap();
        rt.set_loader(TestResolver, TestLoader);
        ctx.with(|ctx| {
            let _ = ctx
                .compile(
                    "loader",
                    r#"
                      import { n, s } from "test_";
                    "#,
                )
                .map_err(|error| {
                    println!("{error:?}");
                    // TODO: Error::Resolving
                    if let Error::Exception = error {
                    } else {
                        panic!();
                    }
                })
                .expect("Unable to resolve");
        })
    }
}