File
Blob: src/rust/gen-compile-cache/cxx-bridge.c++
| 1 | #include "cxx-bridge.h" |
| 2 | |
| 3 | #include <workerd/jsg/compile-cache.h> |
| 4 | #include <workerd/jsg/setup.h> |
| 5 | #include <workerd/jsg/type-wrapper.h> |
| 6 | |
| 7 | #include <kj-rs/kj-rs.h> |
| 8 | |
| 9 | #include <capnp/serialize.h> |
| 10 | |
| 11 | using namespace kj_rs; |
| 12 | namespace workerd::rust::gen_compile_cache { |
| 13 | |
| 14 | namespace { |
| 15 | struct CompilerCacheContext: public jsg::Object, public jsg::ContextGlobal { |
| 16 | JSG_RESOURCE_TYPE(CompilerCacheContext) {} |
| 17 | }; |
| 18 | |
| 19 | JSG_DECLARE_ISOLATE_TYPE(CompileCacheIsolate, CompilerCacheContext); |
| 20 | |
| 21 | constexpr int resourceLineOffset = 0; |
| 22 | constexpr int resourceColumnOffset = 0; |
| 23 | constexpr bool resourceIsSharedCrossOrigin = false; |
| 24 | constexpr int scriptId = -1; |
| 25 | constexpr bool resourceIsOpaque = false; |
| 26 | constexpr bool isWasm = false; |
| 27 | constexpr bool isModule = true; |
| 28 | constexpr v8::ScriptCompiler::CompileOptions compileOptions = v8::ScriptCompiler::kNoCompileOptions; |
| 29 | |
| 30 | } // namespace |
| 31 | |
| 32 | ::rust::Vec<uint8_t> compile(::rust::Str path, ::rust::Str source) { |
| 33 | static jsg::V8System system{}; |
| 34 | static v8::Isolate::CreateParams params{}; |
| 35 | static CompileCacheIsolate ccIsolate(system, kj::heap<jsg::IsolateObserver>(), params); |
| 36 | |
| 37 | auto data = ccIsolate.runInLockScope([&](CompileCacheIsolate::Lock& isolateLock) { |
| 38 | return JSG_WITHIN_CONTEXT_SCOPE(isolateLock, |
| 39 | isolateLock.newContext<CompilerCacheContext>().getHandle(isolateLock), [&](jsg::Lock& js) { |
| 40 | return js.tryCatch([&]() { |
| 41 | auto resourceName = jsg::newExternalOneByteString(js, kj::from<Rust>(path)); |
| 42 | v8::ScriptOrigin origin(resourceName, resourceLineOffset, resourceColumnOffset, |
| 43 | resourceIsSharedCrossOrigin, scriptId, {}, resourceIsOpaque, isWasm, isModule); |
| 44 | |
| 45 | auto contentStr = jsg::newExternalOneByteString(js, kj::from<Rust>(source)); |
| 46 | auto source = v8::ScriptCompiler::Source(contentStr, origin, nullptr); |
| 47 | auto module = |
| 48 | jsg::check(v8::ScriptCompiler::CompileModule(js.v8Isolate, &source, compileOptions)); |
| 49 | |
| 50 | auto codeCache = v8::ScriptCompiler::CreateCodeCache(module->GetUnboundModuleScript()); |
| 51 | auto data = kj::arrayPtr(codeCache->data, codeCache->length).as<RustCopy>(); |
| 52 | delete codeCache; |
| 53 | return data; |
| 54 | }, [&](jsg::Value exception) -> ::rust::Vec<uint8_t> { |
| 55 | auto kjException = js.exceptionToKj(kj::mv(exception)); |
| 56 | KJ_FAIL_REQUIRE("JavaScript compilation error", path, kjException.getDescription()); |
| 57 | }); |
| 58 | }); |
| 59 | }); |
| 60 | |
| 61 | return kj::mv(data); |
| 62 | } |
| 63 | |
| 64 | } // namespace workerd::rust::gen_compile_cache |