servo/rust-mozjs

Question: How to compile a module?

s-panferov opened this issue · 2 comments

Hello, I'm trying to implement my own toy JS runtime like deno on top of mozjs, but I got stuck. I cannot compile a module and extract a function from it:

let rt = Runtime::new().unwrap();
      let cx = rt.cx();

      let h_option = js::OnNewGlobalHookOption::FireOnNewGlobalHook;
      let c_option = js::CompartmentOptions::default();

      let global = js::JS_NewGlobalObject(
         cx,
         &SIMPLE_GLOBAL_CLASS,
         ptr::null_mut(),
         h_option,
         &c_option,
      );

      rooted!(in(cx) let global_root = global);
      let global = global_root.handle();

      let _ac = js::JSAutoCompartment::new(cx, global.get());
      assert!(js::JS_InitStandardClasses(cx, global.into()));

      let code: Vec<u16> = "export default () => 2".encode_utf16().collect();

      rooted!(in(cx) let mut script = ptr::null_mut::<js::JSObject>());

      let filename = CString::new("script.js").unwrap();
      let options = mozjs::rust::CompileOptionsWrapper::new(cx, filename.as_ptr(), 1);
      let mut source = mozjs::jsapi::SourceBufferHolder {
         data_: code.as_ptr(),
         length_: code.len() as libc::size_t,
         ownsChars_: false,
      };

      let res =
         mozjs::rust::wrappers::CompileModule(cx, options.ptr, &mut source, script.handle_mut());

      mozjs::rust::wrappers::ModuleInstantiate(cx, script.handle());
      mozjs::rust::wrappers::ModuleEvaluate(cx, script.handle());

      let ids = mozjs::rust::IdVector::new(cx);
      mozjs::rust::wrappers::GetPropertyKeys(
         cx,
         script.handle(),
         mozjs::jsapi::JSITER_OWNONLY | mozjs::jsapi::JSITER_HIDDEN | mozjs::jsapi::JSITER_SYMBOLS,
         ids.get(),
      );

      println!("{:?}", ids.len());

After running this code ids len is 0. I expect it to contain at least "default" property. Could you please point to what I do wrong?

jdm commented

We have not experimented with modules at all. You should probably ask the folks in #jsapi on irc.mozilla.org.

@jdm I'm not sure I can ask in terms of С++ :-( Ok, thanks