File
Blob: src/rust/jsg-test/ffi.h
| 1 | // Copyright (c) 2026 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | |
| 5 | #pragma once |
| 6 | |
| 7 | #include <workerd/jsg/jsg.h> |
| 8 | #include <workerd/rust/jsg/ffi.h> |
| 9 | #include <workerd/rust/jsg/v8.rs.h> |
| 10 | |
| 11 | #include <kj-rs/kj-rs.h> |
| 12 | #include <rust/cxx.h> |
| 13 | #include <v8.h> |
| 14 | |
| 15 | #include <kj/function.h> |
| 16 | #include <kj/memory.h> |
| 17 | |
| 18 | namespace workerd { |
| 19 | class TestIsolate; |
| 20 | |
| 21 | namespace rust::jsg_test { |
| 22 | |
| 23 | using Isolate = v8::Isolate; |
| 24 | |
| 25 | struct EvalResult; |
| 26 | |
| 27 | class EvalContext { |
| 28 | public: |
| 29 | EvalContext(v8::Isolate* isolate, v8::Local<v8::Context> context); |
| 30 | |
| 31 | EvalResult eval(::rust::Str code) const; |
| 32 | void set_global(::rust::Str name, ::workerd::rust::jsg::Local value) const; |
| 33 | |
| 34 | v8::Isolate* v8Isolate; |
| 35 | v8::Global<v8::Context> v8Context; |
| 36 | }; |
| 37 | |
| 38 | // Testing harness that provides a simple V8 isolate for Rust JSG testing |
| 39 | class TestHarness { |
| 40 | public: |
| 41 | // Use create_test_harness() instead - it ensures proper V8 stack scope |
| 42 | TestHarness(::workerd::jsg::V8StackScope& stackScope); |
| 43 | |
| 44 | // Runs a callback within a proper V8 context and stack scope |
| 45 | // The callback receives the data pointer, isolate and a context |
| 46 | void run_in_context(size_t data, ::rust::Fn<void(size_t, Isolate*, EvalContext&)> callback) const; |
| 47 | |
| 48 | private: |
| 49 | mutable kj::Own<TestIsolate> isolate; |
| 50 | mutable v8::Locker locker; |
| 51 | mutable v8::Isolate::Scope isolateScope; |
| 52 | mutable ::rust::Box<::workerd::rust::jsg::Realm> realm; |
| 53 | }; |
| 54 | |
| 55 | kj::Own<TestHarness> create_test_harness(); |
| 56 | |
| 57 | // Forward-declared; defined by the CXX-generated lib.rs.h header. |
| 58 | enum class GcType : uint8_t; |
| 59 | |
| 60 | // Triggers garbage collection for testing purposes. |
| 61 | void request_gc(Isolate* isolate, GcType gc_type); |
| 62 | |
| 63 | // Creates a V8 object with the C++ WORKERD_WRAPPABLE_TAG set in its internal fields. |
| 64 | // Used to test that Rust unwrap correctly rejects non-Rust wrappable objects. |
| 65 | ::workerd::rust::jsg::Local create_cpp_tagged_object(Isolate* isolate); |
| 66 | |
| 67 | } // namespace rust::jsg_test |
| 68 | |
| 69 | } // namespace workerd |