rusty_racer 0.2.7 → 0.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +87 -0
- data/README.md +104 -1
- data/ext/rusty_racer/Cargo.toml +1 -1
- data/ext/rusty_racer/src/lib.rs +1022 -216
- data/ext/rusty_racer/src/marshal.rs +76 -1
- data/ext/rusty_racer/src/ops.rs +403 -34
- data/lib/rusty_racer/version.rb +1 -1
- data/lib/rusty_racer.rb +137 -22
- metadata +2 -2
data/ext/rusty_racer/src/lib.rs
CHANGED
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
// OUTERMOST op cancels a stale terminate so it can't poison the next op, while a
|
|
32
32
|
// nested op's cancel never erases a termination aimed at the suspended outer JS.
|
|
33
33
|
//
|
|
34
|
-
// Attached procs and the dynamic-import
|
|
34
|
+
// Attached procs and the dynamic-import handler are kept alive by the ISOLATE'S
|
|
35
35
|
// OWN ROOTS ARRAY (Core.roots), which every wrapper marks — never by a GC root.
|
|
36
36
|
// A root would be a leak: a host fn closes over its embedder's world, and that
|
|
37
37
|
// world reaches back to this isolate's wrappers, so rooting the proc roots the
|
|
@@ -72,7 +72,9 @@ use magnus::{
|
|
|
72
72
|
mod marshal;
|
|
73
73
|
use marshal::{JsVal, js_to_jsval, jsval_to_js, jsval_to_ruby, ruby_to_jsval};
|
|
74
74
|
mod ops;
|
|
75
|
-
use ops::{
|
|
75
|
+
use ops::{
|
|
76
|
+
Compiled, Completion, Request, Settle, SyntheticExport, VmReply, run_source, service_request,
|
|
77
|
+
};
|
|
76
78
|
mod stack;
|
|
77
79
|
use stack::{STACK_DEBUG, StackScope, current_real_isolate, discover_scan_start_field};
|
|
78
80
|
mod watchdog;
|
|
@@ -85,16 +87,16 @@ use watchdog::{
|
|
|
85
87
|
// and PINS it (GC.compact must not move it: the copies living in Rust are
|
|
86
88
|
// invisible to the compactor and would go stale).
|
|
87
89
|
//
|
|
88
|
-
// Only for a proc the isolate holds TRANSIENTLY — today just the
|
|
89
|
-
//
|
|
90
|
-
// restored after it. Anything held for the isolate's LIFE goes in the roots
|
|
90
|
+
// Only for a proc the isolate holds TRANSIENTLY — today just the resolve block
|
|
91
|
+
// of Module#instantiate or DynamicImport#resolve, parked in the slot for the
|
|
92
|
+
// length of one InstantiateModule / SettleImport op and restored after it. Anything held for the isolate's LIFE goes in the roots
|
|
91
93
|
// array instead (see the module header): a lasting root is a lasting leak.
|
|
92
94
|
//
|
|
93
95
|
// SAFETY of the manual Send: the !Send contents (and BoxValue's drop, which
|
|
94
96
|
// calls rb_gc_unregister_address) only run under the GVL. Two conventions
|
|
95
97
|
// keep that true — breaking either is silent UB, so don't:
|
|
96
|
-
// - Arc<Core> lives ONLY in the
|
|
97
|
-
// Module, Script, Function). Never clone it into the V8/watchdog threads, or the
|
|
98
|
+
// - Arc<Core> lives ONLY in the six TypedData wrappers (Isolate, Context,
|
|
99
|
+
// Module, Script, Function, DynamicImport). Never clone it into the V8/watchdog threads, or the
|
|
98
100
|
// last drop could run off a Ruby thread.
|
|
99
101
|
// - the wrappers must not set free_immediately: their dfree (and so Core's
|
|
100
102
|
// drop) has to run outside the GC sweep, where Ruby APIs are forbidden.
|
|
@@ -259,13 +261,33 @@ impl ProcTable {
|
|
|
259
261
|
// long as a wrapper of it is reachable, in one place the GC can be shown without
|
|
260
262
|
// taking any Rust lock (a mark that had to lock `procs` could deadlock against
|
|
261
263
|
// the thread whose allocation triggered the GC while holding it). Slot 0 is the
|
|
262
|
-
// dynamic-import
|
|
263
|
-
const
|
|
264
|
+
// dynamic-import handler; the attached host fns follow, one per proc slot.
|
|
265
|
+
const ROOT_IMPORT_HANDLER: isize = 0;
|
|
264
266
|
const ROOT_FIRST_PROC: isize = 1;
|
|
265
267
|
fn proc_root_index(index: usize) -> isize {
|
|
266
268
|
ROOT_FIRST_PROC + index as isize
|
|
267
269
|
}
|
|
268
270
|
|
|
271
|
+
// Import attributes as a frozen Ruby Hash (String => String), in source order —
|
|
272
|
+
// none, the one frozen empty Hash (NO_ATTRIBUTES): what almost every request
|
|
273
|
+
// has, handed to a resolve block per import edge, made once.
|
|
274
|
+
fn attributes_hash(ruby: &Ruby, attributes: &[(String, String)]) -> Result<RHash, Error> {
|
|
275
|
+
if attributes.is_empty() {
|
|
276
|
+
return Ok(ruby.get_inner(&NO_ATTRIBUTES));
|
|
277
|
+
}
|
|
278
|
+
let hash = ruby.hash_new();
|
|
279
|
+
for (key, value) in attributes {
|
|
280
|
+
hash.aset(key.as_str(), value.as_str())?;
|
|
281
|
+
}
|
|
282
|
+
hash.freeze();
|
|
283
|
+
Ok(hash)
|
|
284
|
+
}
|
|
285
|
+
static NO_ATTRIBUTES: magnus::value::Lazy<RHash> = magnus::value::Lazy::new(|ruby| {
|
|
286
|
+
let hash = ruby.hash_new();
|
|
287
|
+
hash.freeze();
|
|
288
|
+
hash
|
|
289
|
+
});
|
|
290
|
+
|
|
269
291
|
// Look up a RustyRacer::<name> exception class at raise time. The classes are
|
|
270
292
|
// defined in lib/rusty_racer.rb (loaded after this extension), so they exist
|
|
271
293
|
// by the time any eval can raise. Falls back to Ruby's RuntimeError.
|
|
@@ -712,7 +734,12 @@ fn reject_with_error(
|
|
|
712
734
|
|
|
713
735
|
// A ScriptOrigin naming the script |filename|, so stack traces and parse-error
|
|
714
736
|
// locations report a meaningful resource name instead of being anonymous.
|
|
715
|
-
|
|
737
|
+
// |host_defined| its host-defined options (`host_defined_options`).
|
|
738
|
+
fn script_origin<'s>(
|
|
739
|
+
scope: &v8::PinScope<'s, '_>,
|
|
740
|
+
filename: &str,
|
|
741
|
+
host_defined: Option<v8::Local<'s, v8::Data>>,
|
|
742
|
+
) -> v8::ScriptOrigin<'s> {
|
|
716
743
|
let name = v8::String::new(scope, filename).unwrap_or_else(|| v8::String::empty(scope));
|
|
717
744
|
v8::ScriptOrigin::new(
|
|
718
745
|
scope,
|
|
@@ -725,7 +752,7 @@ fn script_origin<'s>(scope: &v8::PinScope<'s, '_>, filename: &str) -> v8::Script
|
|
|
725
752
|
false,
|
|
726
753
|
false,
|
|
727
754
|
/*is_module*/ false,
|
|
728
|
-
|
|
755
|
+
host_defined,
|
|
729
756
|
)
|
|
730
757
|
}
|
|
731
758
|
|
|
@@ -874,7 +901,11 @@ fn take_thrown<'s>(
|
|
|
874
901
|
// owning the url->Module registry and the resolve policy (ModuleReg is only the
|
|
875
902
|
// binding's id and url bookkeeping).
|
|
876
903
|
// ---------------------------------------------------------------------------
|
|
877
|
-
fn module_origin<'s>(
|
|
904
|
+
fn module_origin<'s>(
|
|
905
|
+
scope: &v8::PinScope<'s, '_>,
|
|
906
|
+
url: &str,
|
|
907
|
+
host_defined: Option<v8::Local<'s, v8::Data>>,
|
|
908
|
+
) -> v8::ScriptOrigin<'s> {
|
|
878
909
|
let name = v8::String::new(scope, url).unwrap();
|
|
879
910
|
v8::ScriptOrigin::new(
|
|
880
911
|
scope,
|
|
@@ -887,10 +918,30 @@ fn module_origin<'s>(scope: &v8::PinScope<'s, '_>, url: &str) -> v8::ScriptOrigi
|
|
|
887
918
|
false,
|
|
888
919
|
false,
|
|
889
920
|
/*is_module*/ true,
|
|
890
|
-
|
|
921
|
+
host_defined,
|
|
891
922
|
)
|
|
892
923
|
}
|
|
893
924
|
|
|
925
|
+
// File a module V8 made (compiled, or synthetic) under a new id of the realm
|
|
926
|
+
// |context_id|'s — what a Module wrapper addresses — and index its |origin| by
|
|
927
|
+
// its identity (ModuleReg.urls).
|
|
928
|
+
pub(crate) fn register_module(
|
|
929
|
+
scope: &mut v8::PinScope<'_, '_>,
|
|
930
|
+
module: v8::Local<v8::Module>,
|
|
931
|
+
context_id: i32,
|
|
932
|
+
origin: ModuleOrigin,
|
|
933
|
+
) -> i32 {
|
|
934
|
+
let hash = module.get_identity_hash().get();
|
|
935
|
+
let g = v8::Global::new(scope, module);
|
|
936
|
+
let weak = v8::Weak::new(scope, module);
|
|
937
|
+
let m = &mut istate!(scope).modules;
|
|
938
|
+
let id = m.next_id;
|
|
939
|
+
m.next_id += 1;
|
|
940
|
+
m.by_id.insert(id, (g, context_id));
|
|
941
|
+
m.add_url(hash, weak, origin);
|
|
942
|
+
id
|
|
943
|
+
}
|
|
944
|
+
|
|
894
945
|
// Registry for the thin compile_module/instantiate API.
|
|
895
946
|
#[derive(Default)]
|
|
896
947
|
struct ModuleReg {
|
|
@@ -899,13 +950,14 @@ struct ModuleReg {
|
|
|
899
950
|
// was compiled in. Strong, and gone once the wrapper is disposed or collected
|
|
900
951
|
// (Core.released).
|
|
901
952
|
by_id: HashMap<i32, (v8::Global<v8::Module>, i32)>,
|
|
902
|
-
// identity hash -> (module,
|
|
903
|
-
// (import.meta, a referrer being linked) back to the url
|
|
904
|
-
//
|
|
905
|
-
//
|
|
906
|
-
//
|
|
907
|
-
//
|
|
908
|
-
|
|
953
|
+
// identity hash -> (module, what it was compiled with): a Local<Module> V8
|
|
954
|
+
// hands a callback (import.meta, a referrer being linked) back to the url
|
|
955
|
+
// it was compiled with, and the host-defined value it was given. WEAK, so a
|
|
956
|
+
// module V8 still keeps — a dependency linked into a live graph, a function
|
|
957
|
+
// of a disposed realm's module another realm holds — answers whether its
|
|
958
|
+
// wrapper (or its realm) is still around or not, and one V8 collected is
|
|
959
|
+
// pruned instead of pinned (`add_url`).
|
|
960
|
+
urls: HashMap<i32, Vec<(v8::Weak<v8::Module>, ModuleOrigin)>>,
|
|
909
961
|
// `add_url`'s amortization: entries added since the last prune, and the
|
|
910
962
|
// entries that prune left.
|
|
911
963
|
added_since_prune: usize,
|
|
@@ -918,7 +970,7 @@ impl ModuleReg {
|
|
|
918
970
|
// as many have been added since the last prune as it left — a scan
|
|
919
971
|
// amortized O(1) per compile, keeping the index within about twice the
|
|
920
972
|
// modules alive.
|
|
921
|
-
fn add_url(&mut self, hash: i32, module: v8::Weak<v8::Module>,
|
|
973
|
+
fn add_url(&mut self, hash: i32, module: v8::Weak<v8::Module>, origin: ModuleOrigin) {
|
|
922
974
|
if self.added_since_prune > self.kept_at_prune {
|
|
923
975
|
self.urls.retain(|_, bucket| {
|
|
924
976
|
bucket.retain(|(module, _)| !module.is_empty());
|
|
@@ -928,10 +980,20 @@ impl ModuleReg {
|
|
|
928
980
|
self.added_since_prune = 0;
|
|
929
981
|
}
|
|
930
982
|
self.added_since_prune += 1;
|
|
931
|
-
self.urls.entry(hash).or_default().push((module,
|
|
983
|
+
self.urls.entry(hash).or_default().push((module, origin));
|
|
932
984
|
}
|
|
933
985
|
}
|
|
934
986
|
|
|
987
|
+
// What a module was compiled with, as a callback about it hands it on: its url
|
|
988
|
+
// (the filename), and the host-defined value (`host_defined:`) its ScriptOrigin
|
|
989
|
+
// carries, a primitive — V8 itself hands that to the dynamic-import hook of an
|
|
990
|
+
// import() the module makes, but to no hook about the module itself.
|
|
991
|
+
#[derive(Clone)]
|
|
992
|
+
pub(crate) struct ModuleOrigin {
|
|
993
|
+
pub(crate) url: String,
|
|
994
|
+
pub(crate) host_defined: Option<v8::Global<v8::Value>>,
|
|
995
|
+
}
|
|
996
|
+
|
|
935
997
|
// Classic compiled scripts: id -> (unbound script, owning context id). An
|
|
936
998
|
// UnboundScript is context-independent, but we run it in the context it was
|
|
937
999
|
// compiled in (and reset/dispose of that context drops it).
|
|
@@ -955,6 +1017,60 @@ struct ScriptReg {
|
|
|
955
1017
|
// realm it was resolved in, so it holds that other realm's function until this
|
|
956
1018
|
// one is reset or the handle is released — as any reference this realm keeps
|
|
957
1019
|
// to it would.
|
|
1020
|
+
// The import() promises waiting for their host (DynamicImport): id -> the
|
|
1021
|
+
// promise's resolver and the realm the import() fired in, whose module it is
|
|
1022
|
+
// to settle with. An entry leaves as its import is settled, as its realm is
|
|
1023
|
+
// reset or disposed (no script of it is left to see the promise), or as its
|
|
1024
|
+
// DynamicImport wrapper is let go of unsettled (nothing can settle it any more:
|
|
1025
|
+
// the promise stays pending, as a fetch no one answers does). Ids are never
|
|
1026
|
+
// reused, so a stale id can only miss.
|
|
1027
|
+
#[derive(Default)]
|
|
1028
|
+
struct ImportReg {
|
|
1029
|
+
by_id: HashMap<u64, (v8::Global<v8::PromiseResolver>, i32)>,
|
|
1030
|
+
next_id: u64,
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
// A synthetic module's default export, until its evaluation steps set it
|
|
1034
|
+
// (synthetic_evaluation_steps): by the module's identity hash, the module
|
|
1035
|
+
// (weak: one never evaluated, then collected, is pruned) and the value, and the
|
|
1036
|
+
// realm both belong to.
|
|
1037
|
+
type KeptExport = (v8::Weak<v8::Module>, v8::Global<v8::Value>, i32);
|
|
1038
|
+
#[derive(Default)]
|
|
1039
|
+
pub(crate) struct SyntheticExports {
|
|
1040
|
+
pub(crate) by_hash: HashMap<i32, Vec<KeptExport>>,
|
|
1041
|
+
// `add`'s amortization, as ModuleReg::add_url's: entries added since the last
|
|
1042
|
+
// prune, and the entries that prune left.
|
|
1043
|
+
added_since_prune: usize,
|
|
1044
|
+
kept_at_prune: usize,
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
impl SyntheticExports {
|
|
1048
|
+
// Keep |value| for |module| of realm |cid|, first letting go of the values of
|
|
1049
|
+
// modules collected unevaluated once as many were added since the last prune
|
|
1050
|
+
// as it left.
|
|
1051
|
+
pub(crate) fn add(
|
|
1052
|
+
&mut self,
|
|
1053
|
+
hash: i32,
|
|
1054
|
+
module: v8::Weak<v8::Module>,
|
|
1055
|
+
value: v8::Global<v8::Value>,
|
|
1056
|
+
cid: i32,
|
|
1057
|
+
) {
|
|
1058
|
+
if self.added_since_prune > self.kept_at_prune {
|
|
1059
|
+
self.by_hash.retain(|_, exports| {
|
|
1060
|
+
exports.retain(|(module, _, _)| !module.is_empty());
|
|
1061
|
+
!exports.is_empty()
|
|
1062
|
+
});
|
|
1063
|
+
self.kept_at_prune = self.by_hash.values().map(Vec::len).sum();
|
|
1064
|
+
self.added_since_prune = 0;
|
|
1065
|
+
}
|
|
1066
|
+
self.added_since_prune += 1;
|
|
1067
|
+
self.by_hash
|
|
1068
|
+
.entry(hash)
|
|
1069
|
+
.or_default()
|
|
1070
|
+
.push((module, value, cid));
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
|
|
958
1074
|
#[derive(Default)]
|
|
959
1075
|
struct FunctionReg {
|
|
960
1076
|
by_id: HashMap<u64, FunctionEntry>,
|
|
@@ -972,6 +1088,7 @@ enum Released {
|
|
|
972
1088
|
Function(u64),
|
|
973
1089
|
Module(i32),
|
|
974
1090
|
Script(i32),
|
|
1091
|
+
Import(u64),
|
|
975
1092
|
}
|
|
976
1093
|
|
|
977
1094
|
// The V8 thread's realm registry: the main context (id 0, swappable by reset),
|
|
@@ -1027,6 +1144,9 @@ struct V8State {
|
|
|
1027
1144
|
retiring: Vec<(v8::Global<v8::Context>, v8::UniqueRef<v8::MicrotaskQueue>)>,
|
|
1028
1145
|
next_context_id: i32,
|
|
1029
1146
|
host_namespace: Option<String>,
|
|
1147
|
+
// The private key every realm's global holds its host object under
|
|
1148
|
+
// (host_object_key), once something has asked for one.
|
|
1149
|
+
host_key: Option<v8::Global<v8::Private>>,
|
|
1030
1150
|
// One security token shared by every realm of this isolate: the
|
|
1031
1151
|
// embedder's frames are same-origin, so cross-context access (e.g.
|
|
1032
1152
|
// NS.contextGlobal) must pass V8's access checks, which compare the
|
|
@@ -1059,14 +1179,20 @@ struct IsolateState {
|
|
|
1059
1179
|
modules: ModuleReg,
|
|
1060
1180
|
scripts: ScriptReg,
|
|
1061
1181
|
functions: FunctionReg,
|
|
1182
|
+
imports: ImportReg,
|
|
1183
|
+
synthetic: SyntheticExports,
|
|
1062
1184
|
active_realms: Vec<i32>,
|
|
1063
1185
|
instantiating: bool,
|
|
1186
|
+
// Set while a dynamic import's module is linked (finish_dynamic_import), so
|
|
1187
|
+
// resolve_imported turns a raising block into the import's rejection rather
|
|
1188
|
+
// than stashing it for a Ruby frame to re-raise.
|
|
1189
|
+
settling_import: bool,
|
|
1064
1190
|
watchdog_fired: bool,
|
|
1065
1191
|
auto_microtasks: bool,
|
|
1066
1192
|
draining: bool,
|
|
1067
1193
|
// Back-pointer to the owning Core, so a V8 callback (host fn / module
|
|
1068
1194
|
// resolver) — which holds only a scope — can reach Core.procs and
|
|
1069
|
-
// Core.
|
|
1195
|
+
// Core.dynamic_import_handler. Set once, after the Arc<Core> is built;
|
|
1070
1196
|
// valid for the whole isolate life (Core outlives the slot — the slot is
|
|
1071
1197
|
// dropped during isolate disposal, which a live wrapper triggers). Null
|
|
1072
1198
|
// only in the brief window before it is wired up.
|
|
@@ -1113,8 +1239,11 @@ impl IsolateState {
|
|
|
1113
1239
|
modules: ModuleReg::default(),
|
|
1114
1240
|
scripts: ScriptReg::default(),
|
|
1115
1241
|
functions: FunctionReg::default(),
|
|
1242
|
+
imports: ImportReg::default(),
|
|
1243
|
+
synthetic: SyntheticExports::default(),
|
|
1116
1244
|
active_realms: Vec::new(),
|
|
1117
1245
|
instantiating: false,
|
|
1246
|
+
settling_import: false,
|
|
1118
1247
|
watchdog_fired: false,
|
|
1119
1248
|
auto_microtasks,
|
|
1120
1249
|
draining: false,
|
|
@@ -1284,6 +1413,12 @@ fn drop_context_artifacts(state: &mut IsolateState, context_id: i32) {
|
|
|
1284
1413
|
.functions
|
|
1285
1414
|
.by_id
|
|
1286
1415
|
.retain(|_, entry| entry.context_id != context_id);
|
|
1416
|
+
// Its import() promises are no script's to see any more.
|
|
1417
|
+
state.imports.by_id.retain(|_, (_, cid)| *cid != context_id);
|
|
1418
|
+
state.synthetic.by_hash.retain(|_, exports| {
|
|
1419
|
+
exports.retain(|(_, _, cid)| *cid != context_id);
|
|
1420
|
+
!exports.is_empty()
|
|
1421
|
+
});
|
|
1287
1422
|
// A promise-reject recorder created in this context is unusable now.
|
|
1288
1423
|
if state
|
|
1289
1424
|
.realms
|
|
@@ -1307,11 +1442,14 @@ fn script_handle(
|
|
|
1307
1442
|
.map(|(g, cid)| (g.clone(), *cid))
|
|
1308
1443
|
}
|
|
1309
1444
|
|
|
1310
|
-
//
|
|
1311
|
-
// the weak url index (ModuleReg.urls) — for
|
|
1312
|
-
// to give a referrer its url for the
|
|
1313
|
-
// import.meta.
|
|
1314
|
-
fn
|
|
1445
|
+
// What a compiled module was compiled with (its url — the filename — and its
|
|
1446
|
+
// host-defined value), by identity in the weak url index (ModuleReg.urls) — for
|
|
1447
|
+
// as long as V8 keeps the module. Used to give a referrer its url for the
|
|
1448
|
+
// resolve round-trip and to fill import.meta.
|
|
1449
|
+
fn origin_of_module(
|
|
1450
|
+
scope: &mut v8::PinScope<'_, '_>,
|
|
1451
|
+
module: v8::Local<v8::Module>,
|
|
1452
|
+
) -> Option<ModuleOrigin> {
|
|
1315
1453
|
let hash = module.get_identity_hash().get();
|
|
1316
1454
|
// A shared borrow of the slot beside the shared one to_local takes.
|
|
1317
1455
|
scope
|
|
@@ -1321,42 +1459,113 @@ fn module_url(scope: &mut v8::PinScope<'_, '_>, module: v8::Local<v8::Module>) -
|
|
|
1321
1459
|
.get(&hash)?
|
|
1322
1460
|
.iter()
|
|
1323
1461
|
.find(|(weak, _)| weak.to_local(scope) == Some(module))
|
|
1324
|
-
.map(|(_,
|
|
1462
|
+
.map(|(_, origin)| origin.clone())
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
fn module_url(scope: &mut v8::PinScope<'_, '_>, module: v8::Local<v8::Module>) -> Option<String> {
|
|
1466
|
+
origin_of_module(scope, module).map(|origin| origin.url)
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
// The host-defined options a ScriptOrigin carries for `host_defined:` — a
|
|
1470
|
+
// PrimitiveArray holding the value alone — or None for none. A value that is
|
|
1471
|
+
// no primitive is refused before it gets here (`host_defined_arg`).
|
|
1472
|
+
pub(crate) fn host_defined_options<'s>(
|
|
1473
|
+
scope: &mut v8::PinScope<'s, '_>,
|
|
1474
|
+
value: Option<&JsVal>,
|
|
1475
|
+
) -> Option<v8::Local<'s, v8::Data>> {
|
|
1476
|
+
let value = marshal::jsval_to_js(scope, value?.clone());
|
|
1477
|
+
let primitive = v8::Local::<v8::Primitive>::try_from(value).ok()?;
|
|
1478
|
+
let options = v8::PrimitiveArray::new(scope, 1);
|
|
1479
|
+
options.set(scope, 0, primitive);
|
|
1480
|
+
Some(options.into())
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
// …and back: the value the host-defined options V8 hands a hook hold — their
|
|
1484
|
+
// first element, as any embedder that sets a PrimitiveArray of its own
|
|
1485
|
+
// (rather than through `host_defined:`) puts it there — or None.
|
|
1486
|
+
fn host_defined_value<'s>(
|
|
1487
|
+
scope: &mut v8::PinScope<'s, '_>,
|
|
1488
|
+
options: v8::Local<'s, v8::Data>,
|
|
1489
|
+
) -> Option<v8::Local<'s, v8::Value>> {
|
|
1490
|
+
let options = v8::Local::<v8::FixedArray>::try_from(options).ok()?;
|
|
1491
|
+
let first = options.get(scope, 0)?;
|
|
1492
|
+
v8::Local::<v8::Value>::try_from(first).ok()
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
// The import attributes V8 hands a hook, as (key, value) pairs: `stride` 3 for
|
|
1496
|
+
// a module request's (key, value, source offset), 2 for a dynamic import's.
|
|
1497
|
+
fn import_attributes_of(
|
|
1498
|
+
scope: &mut v8::PinScope<'_, '_>,
|
|
1499
|
+
attributes: v8::Local<v8::FixedArray>,
|
|
1500
|
+
stride: usize,
|
|
1501
|
+
) -> Vec<(String, String)> {
|
|
1502
|
+
let mut pairs = Vec::with_capacity(attributes.length() / stride);
|
|
1503
|
+
for at in (0..attributes.length()).step_by(stride) {
|
|
1504
|
+
let text = |scope: &mut v8::PinScope<'_, '_>, i: usize| {
|
|
1505
|
+
attributes
|
|
1506
|
+
.get(scope, i)
|
|
1507
|
+
.and_then(|d| v8::Local::<v8::Value>::try_from(d).ok())
|
|
1508
|
+
.map(|v| v.to_rust_string_lossy(scope))
|
|
1509
|
+
};
|
|
1510
|
+
if let (Some(key), Some(value)) = (text(scope, at), text(scope, at + 1)) {
|
|
1511
|
+
pairs.push((key, value));
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
pairs
|
|
1325
1515
|
}
|
|
1326
1516
|
|
|
1327
1517
|
// V8 calls this the first time a module reads import.meta. Fills in
|
|
1328
|
-
// import.meta.url with the module's compile-time url (filename)
|
|
1329
|
-
//
|
|
1518
|
+
// import.meta.url with the module's compile-time url (filename), then hands the
|
|
1519
|
+
// object to its realm's import-meta handler (NS.setImportMetaHandler), if it has
|
|
1520
|
+
// one, as `handler(meta, url, hostDefined)` — HTML's
|
|
1521
|
+
// HostGetImportMetaProperties, whose `resolve` only the host can make. What the
|
|
1522
|
+
// handler throws is dropped: there is no script of the page's to throw it at.
|
|
1330
1523
|
unsafe extern "C" fn import_meta_cb(
|
|
1331
1524
|
context: v8::Local<v8::Context>,
|
|
1332
1525
|
module: v8::Local<v8::Module>,
|
|
1333
1526
|
meta: v8::Local<v8::Object>,
|
|
1334
1527
|
) {
|
|
1335
1528
|
v8::callback_scope!(unsafe scope, context);
|
|
1336
|
-
let Some(
|
|
1529
|
+
let Some(origin) = origin_of_module(scope, module) else {
|
|
1337
1530
|
return;
|
|
1338
1531
|
};
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
}
|
|
1532
|
+
let Some(url) = v8::String::new(scope, &origin.url) else {
|
|
1533
|
+
return;
|
|
1534
|
+
};
|
|
1535
|
+
if let Some(key) = v8::String::new(scope, "url") {
|
|
1536
|
+
meta.create_data_property(scope, key.into(), url.into());
|
|
1537
|
+
}
|
|
1538
|
+
let global = context.global(scope);
|
|
1539
|
+
let key = import_meta_key(scope);
|
|
1540
|
+
let Some(handler) = global
|
|
1541
|
+
.get_private(scope, key)
|
|
1542
|
+
.and_then(|h| v8::Local::<v8::Function>::try_from(h).ok())
|
|
1543
|
+
else {
|
|
1544
|
+
return;
|
|
1545
|
+
};
|
|
1546
|
+
let host_defined: v8::Local<v8::Value> = match origin.host_defined {
|
|
1547
|
+
Some(value) => v8::Local::new(scope, value),
|
|
1548
|
+
None => v8::undefined(scope).into(),
|
|
1549
|
+
};
|
|
1550
|
+
v8::tc_scope!(let tc, scope);
|
|
1551
|
+
let receiver = v8::undefined(tc).into();
|
|
1552
|
+
handler.call(tc, receiver, &[meta.into(), url.into(), host_defined]);
|
|
1342
1553
|
}
|
|
1343
1554
|
|
|
1344
|
-
// V8 calls this per import edge during InstantiateModule (and while
|
|
1345
|
-
//
|
|
1346
|
-
// to its url and calls the Ruby
|
|
1347
|
-
//
|
|
1348
|
-
// parked (a dynamic import's auto-link) — the Context's dynamic_import_resolver.
|
|
1555
|
+
// V8 calls this per import edge during InstantiateModule (and while a dynamic
|
|
1556
|
+
// import is settled with a module to link — DynamicImport#resolve). Maps the
|
|
1557
|
+
// referrer to its url and calls the Ruby resolve block parked in the slot for
|
|
1558
|
+
// the op INLINE (reacquiring the GVL), with the request's import attributes.
|
|
1349
1559
|
fn resolve_imported<'s>(
|
|
1350
1560
|
context: v8::Local<'s, v8::Context>,
|
|
1351
1561
|
specifier: v8::Local<'s, v8::String>,
|
|
1352
|
-
|
|
1562
|
+
import_attributes: v8::Local<'s, v8::FixedArray>,
|
|
1353
1563
|
referrer: v8::Local<'s, v8::Module>,
|
|
1354
1564
|
) -> Option<v8::Local<'s, v8::Module>> {
|
|
1355
1565
|
v8::callback_scope!(unsafe scope, context);
|
|
1356
1566
|
let spec = specifier.to_rust_string_lossy(scope);
|
|
1357
1567
|
let ref_url = module_url(scope, referrer)?;
|
|
1358
|
-
// The realm being linked (this callback's own context)
|
|
1359
|
-
// it both rides along to the dynamic_import_resolver AND backs the
|
|
1568
|
+
// The realm being linked (this callback's own context), for the
|
|
1360
1569
|
// foreign-context check below; for a real module context it is always Some.
|
|
1361
1570
|
let here = id_of_context(scope, context);
|
|
1362
1571
|
let core_ptr = istate!(scope).core_ptr;
|
|
@@ -1364,51 +1573,45 @@ fn resolve_imported<'s>(
|
|
|
1364
1573
|
return None;
|
|
1365
1574
|
}
|
|
1366
1575
|
let core = unsafe { &*core_ptr };
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
//
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
let
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
//
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
Err(exc) => {
|
|
1386
|
-
istate!(scope).instantiate_resolve_err = exc;
|
|
1387
|
-
None
|
|
1388
|
-
}
|
|
1576
|
+
let attributes = import_attributes_of(scope, import_attributes, 3);
|
|
1577
|
+
let resolve = istate!(scope).instantiate_resolve.as_ref().map(|r| r.get());
|
|
1578
|
+
// Linking for a dynamic import (DynamicImport#resolve) has no Ruby frame to
|
|
1579
|
+
// re-raise a raising block into — the failure becomes the import()'s
|
|
1580
|
+
// rejection — so the block's own message travels out as the JS error.
|
|
1581
|
+
let settling = istate!(scope).settling_import;
|
|
1582
|
+
let mut failure = None;
|
|
1583
|
+
let dep_id = match resolve {
|
|
1584
|
+
Some(resolve) if settling => match with_gvl(core, RubyCall::Resolver(&spec), || {
|
|
1585
|
+
// Rendering the message reads the Ruby exception, so it stays
|
|
1586
|
+
// inside with_gvl.
|
|
1587
|
+
resolve_module_via_ruby(core, resolve, &spec, &ref_url, &attributes)
|
|
1588
|
+
.map_err(|e| e.to_string())
|
|
1589
|
+
}) {
|
|
1590
|
+
Ok(id) => id,
|
|
1591
|
+
Err(why) => {
|
|
1592
|
+
failure = Some(why);
|
|
1593
|
+
None
|
|
1389
1594
|
}
|
|
1390
|
-
}
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
dynamic_err = Some(why);
|
|
1406
|
-
None
|
|
1407
|
-
}
|
|
1408
|
-
},
|
|
1409
|
-
None => None,
|
|
1595
|
+
},
|
|
1596
|
+
// The error conversion happens INSIDE with_gvl: error_to_exception
|
|
1597
|
+
// calls into Ruby (so it can allocate, so it can GC) and BoxValue::new
|
|
1598
|
+
// registers a GC root — neither is safe with the GVL released.
|
|
1599
|
+
Some(resolve) => match with_gvl(core, RubyCall::Resolver(&spec), || {
|
|
1600
|
+
resolve_module_via_ruby(core, resolve, &spec, &ref_url, &attributes)
|
|
1601
|
+
.map_err(|e| error_to_exception(&e).map(BoxValue::new))
|
|
1602
|
+
}) {
|
|
1603
|
+
Ok(id) => id,
|
|
1604
|
+
// Stash the resolver's own raised exception (GC-rooted) so the
|
|
1605
|
+
// InstantiateModule op can re-raise it with its original class
|
|
1606
|
+
// instead of a generic "failed to link".
|
|
1607
|
+
Err(exc) => {
|
|
1608
|
+
istate!(scope).instantiate_resolve_err = exc;
|
|
1609
|
+
None
|
|
1410
1610
|
}
|
|
1411
|
-
}
|
|
1611
|
+
},
|
|
1612
|
+
// No block: a module handed to DynamicImport#resolve unlinked, with
|
|
1613
|
+
// nothing to link its imports by.
|
|
1614
|
+
None => None,
|
|
1412
1615
|
};
|
|
1413
1616
|
// From here on, every exit that isn't a module throws first. V8 has no
|
|
1414
1617
|
// channel for "why" — it just sees an empty return, installs no error of its
|
|
@@ -1417,9 +1620,8 @@ fn resolve_imported<'s>(
|
|
|
1417
1620
|
// where it came from, which is the single most common module wiring mistake.
|
|
1418
1621
|
// (The two bails above stay silent: both are broken internal state, not
|
|
1419
1622
|
// anything the caller did.) The one path that must also stay silent is a
|
|
1420
|
-
//
|
|
1421
|
-
// for instantiate_module to re-raise, and ours would mask it.
|
|
1422
|
-
// branch has no such frame, so it carries its message in dynamic_err.
|
|
1623
|
+
// block that raised for Module#instantiate — its own Ruby exception is
|
|
1624
|
+
// already stashed for instantiate_module to re-raise, and ours would mask it.
|
|
1423
1625
|
let raised = istate!(scope).instantiate_resolve_err.is_some();
|
|
1424
1626
|
let fail = |scope: &mut v8::PinScope<'_, '_>, message: String| {
|
|
1425
1627
|
if !raised {
|
|
@@ -1429,7 +1631,7 @@ fn resolve_imported<'s>(
|
|
|
1429
1631
|
};
|
|
1430
1632
|
let import = format!("{spec:?} imported from {ref_url}");
|
|
1431
1633
|
let Some(dep_id) = dep_id else {
|
|
1432
|
-
return match
|
|
1634
|
+
return match failure {
|
|
1433
1635
|
Some(why) => fail(scope, format!("{why} (resolving {import})")),
|
|
1434
1636
|
None => fail(
|
|
1435
1637
|
scope,
|
|
@@ -1437,10 +1639,8 @@ fn resolve_imported<'s>(
|
|
|
1437
1639
|
),
|
|
1438
1640
|
};
|
|
1439
1641
|
};
|
|
1440
|
-
// The dep must live in the context actually being linked
|
|
1441
|
-
//
|
|
1442
|
-
// detach from the request that started it. A foreign-context module would
|
|
1443
|
-
// V8-CHECK-abort.
|
|
1642
|
+
// The dep must live in the context actually being linked; a foreign-context
|
|
1643
|
+
// module would V8-CHECK-abort.
|
|
1444
1644
|
let found = istate!(scope)
|
|
1445
1645
|
.modules
|
|
1446
1646
|
.by_id
|
|
@@ -1471,72 +1671,134 @@ fn resolve_imported<'s>(
|
|
|
1471
1671
|
Some(v8::Local::new(scope, &g))
|
|
1472
1672
|
}
|
|
1473
1673
|
|
|
1474
|
-
// V8 calls this for a JS `import(specifier)`. Returns a
|
|
1475
|
-
//
|
|
1476
|
-
//
|
|
1477
|
-
//
|
|
1478
|
-
// (finish_dynamic_import).
|
|
1674
|
+
// V8 calls this for a JS `import(specifier, options)`. Returns a promise the
|
|
1675
|
+
// HOST settles — now or on a later task — through the RustyRacer::DynamicImport
|
|
1676
|
+
// handed to the Isolate's dynamic_import_handler (called INLINE, reacquiring the
|
|
1677
|
+
// GVL): with a module (DynamicImport#resolve), which per V8's host contract is
|
|
1678
|
+
// linked and evaluated here (finish_dynamic_import), or with a rejection value.
|
|
1679
|
+
// The promise waits in ImportReg until then; a handler that raises rejects it
|
|
1680
|
+
// with its message, unless it settled it first.
|
|
1479
1681
|
fn dynamic_import_cb<'s>(
|
|
1480
1682
|
scope: &mut v8::PinScope<'s, '_>,
|
|
1481
|
-
|
|
1683
|
+
host_defined_options: v8::Local<'s, v8::Data>,
|
|
1482
1684
|
resource_name: v8::Local<'s, v8::Value>,
|
|
1483
1685
|
specifier: v8::Local<'s, v8::String>,
|
|
1484
|
-
|
|
1686
|
+
import_attributes: v8::Local<'s, v8::FixedArray>,
|
|
1485
1687
|
) -> Option<v8::Local<'s, v8::Promise>> {
|
|
1486
1688
|
let resolver = v8::PromiseResolver::new(scope)?;
|
|
1487
1689
|
let promise = resolver.get_promise(scope);
|
|
1488
|
-
let reject = |scope: &mut v8::PinScope<'s, '_>, msg: &str| {
|
|
1489
|
-
reject_with_error(scope, resolver, msg);
|
|
1490
|
-
};
|
|
1491
|
-
let spec = specifier.to_rust_string_lossy(scope);
|
|
1492
|
-
let referrer = resource_name.to_rust_string_lossy(scope);
|
|
1493
|
-
// The realm import() fired in — handed to the resolver as a Context so it can
|
|
1494
|
-
// resolve/compile the module in the right realm (e.g. an iframe's), not the
|
|
1495
|
-
// main one.
|
|
1496
|
-
let initiating = id_of_context(scope, scope.get_current_context()).unwrap_or(0);
|
|
1497
1690
|
let core_ptr = istate!(scope).core_ptr;
|
|
1498
|
-
|
|
1499
|
-
|
|
1691
|
+
let core = (!core_ptr.is_null()).then(|| unsafe { &*core_ptr });
|
|
1692
|
+
let Some((core, handler)) = core.and_then(|core| Some((core, core.dynamic_import_handler()?)))
|
|
1693
|
+
else {
|
|
1694
|
+
reject_with_error(
|
|
1695
|
+
scope,
|
|
1696
|
+
resolver,
|
|
1697
|
+
"import() is not supported: no dynamic_import_handler",
|
|
1698
|
+
);
|
|
1500
1699
|
return Some(promise);
|
|
1501
|
-
}
|
|
1502
|
-
let core = unsafe { &*core_ptr };
|
|
1503
|
-
let id = match core.dynamic_import_resolver() {
|
|
1504
|
-
// A raising resolver only fails the import() (it rejects generically);
|
|
1505
|
-
// it must NOT abort the surrounding eval, so swallow the Err here.
|
|
1506
|
-
Some(p) => with_gvl(core, RubyCall::Resolver(&spec), || {
|
|
1507
|
-
resolve_module_via_ruby(core, p, &spec, &referrer, Some(initiating))
|
|
1508
|
-
})
|
|
1509
|
-
.unwrap_or(None),
|
|
1510
|
-
None => None,
|
|
1511
1700
|
};
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1701
|
+
let specifier = specifier.to_rust_string_lossy(scope);
|
|
1702
|
+
// The script import() was called from, by the name it was compiled under
|
|
1703
|
+
// (none: e.g. a function made by `new Function` of no script's).
|
|
1704
|
+
let referrer = resource_name
|
|
1705
|
+
.is_string()
|
|
1706
|
+
.then(|| resource_name.to_rust_string_lossy(scope));
|
|
1707
|
+
let attributes = import_attributes_of(scope, import_attributes, 2);
|
|
1708
|
+
let host_defined = host_defined_value(scope, host_defined_options)
|
|
1709
|
+
.map(|value| marshal::js_to_jsval(scope, value));
|
|
1710
|
+
// The realm import() fired in — whose module the promise is to settle with,
|
|
1711
|
+
// and whose Context the handler is handed. Under kAuto a microtask queued by
|
|
1712
|
+
// realm B can run import() during the drain at the end of realm A's request,
|
|
1713
|
+
// so the running realm is the truth, not the request's.
|
|
1714
|
+
// (…a function of a realm reset or disposed since — another realm holds it — imports nothing: no realm is its)
|
|
1715
|
+
let current = scope.get_current_context();
|
|
1716
|
+
let Some(context_id) = id_of_context(scope, current) else {
|
|
1717
|
+
reject_with_error(scope, resolver, "import() of a realm that is gone");
|
|
1718
|
+
return Some(promise);
|
|
1719
|
+
};
|
|
1720
|
+
let kept = v8::Global::new(scope, resolver);
|
|
1721
|
+
let id = {
|
|
1722
|
+
let imports = &mut istate!(scope).imports;
|
|
1723
|
+
imports.next_id += 1;
|
|
1724
|
+
imports.by_id.insert(imports.next_id, (kept, context_id));
|
|
1725
|
+
imports.next_id
|
|
1726
|
+
};
|
|
1727
|
+
let raised = with_gvl(core, RubyCall::Resolver(&specifier), || {
|
|
1728
|
+
let Some(core) = core.me.upgrade() else {
|
|
1729
|
+
return Some("the isolate is gone".to_owned());
|
|
1730
|
+
};
|
|
1731
|
+
let import = DynamicImport {
|
|
1732
|
+
core,
|
|
1733
|
+
id,
|
|
1734
|
+
context_id,
|
|
1735
|
+
specifier: specifier.clone(),
|
|
1736
|
+
referrer,
|
|
1737
|
+
attributes,
|
|
1738
|
+
host_defined,
|
|
1739
|
+
settled: AtomicBool::new(false),
|
|
1740
|
+
};
|
|
1741
|
+
handler
|
|
1742
|
+
.call::<_, Value>((import,))
|
|
1743
|
+
.err()
|
|
1744
|
+
.map(|e| e.to_string())
|
|
1745
|
+
});
|
|
1746
|
+
if let Some(why) = raised {
|
|
1747
|
+
let pending = istate!(scope).imports.by_id.remove(&id);
|
|
1748
|
+
if let Some((resolver, _)) = pending {
|
|
1749
|
+
let resolver = v8::Local::new(scope, resolver);
|
|
1750
|
+
reject_with_error(scope, resolver, &why);
|
|
1534
1751
|
}
|
|
1535
|
-
None => reject(scope, "import() was not resolved to a module"),
|
|
1536
1752
|
}
|
|
1537
1753
|
Some(promise)
|
|
1538
1754
|
}
|
|
1539
1755
|
|
|
1756
|
+
// V8 calls this as a synthetic module (op_create_synthetic_module) evaluates:
|
|
1757
|
+
// its `default` export set to the value kept for it, which it then lets go of.
|
|
1758
|
+
// Returns a fulfilled promise, as a module's evaluation does.
|
|
1759
|
+
fn synthetic_evaluation_steps<'s>(
|
|
1760
|
+
context: v8::Local<'s, v8::Context>,
|
|
1761
|
+
module: v8::Local<'s, v8::Module>,
|
|
1762
|
+
) -> Option<v8::Local<'s, v8::Value>> {
|
|
1763
|
+
v8::callback_scope!(unsafe scope, context);
|
|
1764
|
+
let hash = module.get_identity_hash().get();
|
|
1765
|
+
// (…V8 told of every failure by an exception: an empty return with none pending is a CHECK)
|
|
1766
|
+
let at = scope.get_slot::<IsolateState>().and_then(|state| {
|
|
1767
|
+
state
|
|
1768
|
+
.synthetic
|
|
1769
|
+
.by_hash
|
|
1770
|
+
.get(&hash)?
|
|
1771
|
+
.iter()
|
|
1772
|
+
.position(|(weak, _, _)| weak.to_local(scope) == Some(module))
|
|
1773
|
+
});
|
|
1774
|
+
let kept = at.and_then(|at| {
|
|
1775
|
+
let by_hash = &mut istate!(scope).synthetic.by_hash;
|
|
1776
|
+
let exports = by_hash.get_mut(&hash)?;
|
|
1777
|
+
let (_, value, _) = exports.remove(at);
|
|
1778
|
+
if exports.is_empty() {
|
|
1779
|
+
by_hash.remove(&hash);
|
|
1780
|
+
}
|
|
1781
|
+
Some(value)
|
|
1782
|
+
});
|
|
1783
|
+
let Some(value) = kept else {
|
|
1784
|
+
throw_js_error(scope, "the synthetic module's value is gone with its realm");
|
|
1785
|
+
return None;
|
|
1786
|
+
};
|
|
1787
|
+
let value = v8::Local::new(scope, value);
|
|
1788
|
+
let Some(name) = v8::String::new(scope, "default") else {
|
|
1789
|
+
throw_js_error(scope, "out of memory");
|
|
1790
|
+
return None;
|
|
1791
|
+
};
|
|
1792
|
+
module.set_synthetic_module_export(scope, name, value)?;
|
|
1793
|
+
let Some(resolver) = v8::PromiseResolver::new(scope) else {
|
|
1794
|
+
throw_js_error(scope, "out of memory");
|
|
1795
|
+
return None;
|
|
1796
|
+
};
|
|
1797
|
+
let undefined = v8::undefined(scope).into();
|
|
1798
|
+
resolver.resolve(scope, undefined);
|
|
1799
|
+
Some(resolver.get_promise(scope).into())
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1540
1802
|
// The on-fulfilled handler for finish_dynamic_import's native then: ignores
|
|
1541
1803
|
// the evaluation promise's fulfilment value and returns the module namespace
|
|
1542
1804
|
// captured as the function's data, so the import() promise fulfils with the
|
|
@@ -1549,16 +1811,15 @@ fn dyn_import_namespace_cb(
|
|
|
1549
1811
|
rv.set(args.data());
|
|
1550
1812
|
}
|
|
1551
1813
|
|
|
1552
|
-
// Complete a dynamic import with the module the
|
|
1814
|
+
// Complete a dynamic import with the module the host settled it with. V8's
|
|
1553
1815
|
// HostImportModuleDynamicallyCallback contract makes load -> link -> evaluate
|
|
1554
|
-
// the HOST's responsibility, so a
|
|
1555
|
-
//
|
|
1556
|
-
// through the same dynamic_import_resolver (pump's ResolveModule fallback).
|
|
1816
|
+
// the HOST's responsibility, so a merely compiled module is linked (by the
|
|
1817
|
+
// block DynamicImport#resolve parked) and evaluated right here.
|
|
1557
1818
|
// The import() promise is settled FROM the evaluation promise, which handles
|
|
1558
1819
|
// sync completion, a thrown error, and top-level await uniformly — and since
|
|
1559
1820
|
// V8's Module::Evaluate is idempotent (an Evaluated module returns its
|
|
1560
|
-
// existing top-level promise),
|
|
1561
|
-
fn finish_dynamic_import(
|
|
1821
|
+
// existing top-level promise), a module evaluated already costs nothing extra.
|
|
1822
|
+
pub(crate) fn finish_dynamic_import(
|
|
1562
1823
|
scope: &mut v8::PinScope<'_, '_>,
|
|
1563
1824
|
module: v8::Local<v8::Module>,
|
|
1564
1825
|
resolver: v8::Local<v8::PromiseResolver>,
|
|
@@ -1575,8 +1836,12 @@ fn finish_dynamic_import(
|
|
|
1575
1836
|
);
|
|
1576
1837
|
return;
|
|
1577
1838
|
}
|
|
1839
|
+
// (…a block that raises failing the import: resolve_imported's `settling_import` — set for the link alone, not
|
|
1840
|
+
// for the evaluation after it, whose own Module#instantiate re-raises as it always does)
|
|
1578
1841
|
istate!(tc).instantiating = true;
|
|
1842
|
+
istate!(tc).settling_import = true;
|
|
1579
1843
|
let linked = module.instantiate_module(tc, resolve_imported);
|
|
1844
|
+
istate!(tc).settling_import = false;
|
|
1580
1845
|
istate!(tc).instantiating = false;
|
|
1581
1846
|
if linked != Some(true) {
|
|
1582
1847
|
// A watchdog/terminate that landed during linking must escalate to
|
|
@@ -1760,7 +2025,7 @@ struct Core {
|
|
|
1760
2025
|
// each `run`.
|
|
1761
2026
|
depth: std::sync::atomic::AtomicU32,
|
|
1762
2027
|
// Everything this isolate keeps alive on the Ruby side — the attached host fns
|
|
1763
|
-
// and the dynamic-import
|
|
2028
|
+
// and the dynamic-import handler — in one Array the wrappers MARK (and pin).
|
|
1764
2029
|
// See the module header for why these must not be GC roots; ROOT_* for the
|
|
1765
2030
|
// layout. Read on the V8 side without the GVL (the import hooks), which is
|
|
1766
2031
|
// sound because the entries are pinned and nothing here allocates or raises.
|
|
@@ -1778,6 +2043,10 @@ struct Core {
|
|
|
1778
2043
|
// Set with each push there, so the request boundary looks at the lock only
|
|
1779
2044
|
// when there is something under it.
|
|
1780
2045
|
handles_released: AtomicBool,
|
|
2046
|
+
// The extra realms disposed so far (ids are never reused), so any Context
|
|
2047
|
+
// wrapper of one — not only the one dispose was called on, a
|
|
2048
|
+
// DynamicImport#context's too — reads as disposed.
|
|
2049
|
+
disposed_realms: Mutex<std::collections::HashSet<i32>>,
|
|
1781
2050
|
// Default per-eval/call timeout (ms); 0 = none. eval(timeout_ms:)'s explicit
|
|
1782
2051
|
// value overrides it. Guards against an in-V8 infinite loop without a watchdog.
|
|
1783
2052
|
default_timeout_ms: u64,
|
|
@@ -1859,7 +2128,25 @@ struct JsFunction {
|
|
|
1859
2128
|
disposed: AtomicBool,
|
|
1860
2129
|
}
|
|
1861
2130
|
|
|
1862
|
-
//
|
|
2131
|
+
// An import() waiting for its host (dynamic_import_cb), handed to the
|
|
2132
|
+
// Isolate's dynamic_import_handler: what was asked — the specifier, the import
|
|
2133
|
+
// attributes, the referring script's name and host-defined value — and in
|
|
2134
|
+
// which realm, until #resolve / #reject / #reject_with settles it (ImportReg
|
|
2135
|
+
// keeps the promise). Let go of unsettled, the promise is let go of too.
|
|
2136
|
+
#[derive(TypedData)]
|
|
2137
|
+
#[magnus(class = "RustyRacer::DynamicImport", mark)]
|
|
2138
|
+
struct DynamicImport {
|
|
2139
|
+
core: Arc<Core>,
|
|
2140
|
+
id: u64,
|
|
2141
|
+
context_id: i32,
|
|
2142
|
+
specifier: String,
|
|
2143
|
+
referrer: Option<String>,
|
|
2144
|
+
attributes: Vec<(String, String)>,
|
|
2145
|
+
host_defined: Option<JsVal>,
|
|
2146
|
+
settled: AtomicBool,
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
// The six wrappers that hold an Arc<Core> all mark the isolate's roots, because any
|
|
1863
2150
|
// one of them may be the last one reachable: Ruby code is free to keep only the
|
|
1864
2151
|
// Context a `Isolate#context` handed it, or only a Module, and the host fns must
|
|
1865
2152
|
// stay callable through it. Marking the same array five times costs nothing (the GC
|
|
@@ -1878,6 +2165,7 @@ marks_core_roots!(Context);
|
|
|
1878
2165
|
marks_core_roots!(JsModule);
|
|
1879
2166
|
marks_core_roots!(Script);
|
|
1880
2167
|
marks_core_roots!(JsFunction);
|
|
2168
|
+
marks_core_roots!(DynamicImport);
|
|
1881
2169
|
|
|
1882
2170
|
// Set true once V8 is initialized; Platform.set_flags! refuses after that
|
|
1883
2171
|
// (flags must be set before V8::initialize), like mini_racer's
|
|
@@ -1998,6 +2286,30 @@ fn context_global(
|
|
|
1998
2286
|
}
|
|
1999
2287
|
}
|
|
2000
2288
|
|
|
2289
|
+
// NS.hostObjectOf(id) -> the host object of context |id| (host_object), made
|
|
2290
|
+
// there if it has none yet — for one realm's bindings to reach another's, as
|
|
2291
|
+
// contextGlobal reaches its global. Only on a namespace that is itself on the
|
|
2292
|
+
// host object (`host_namespace: '@…'`): a namespace on the global would hand
|
|
2293
|
+
// every realm's host object to any script. Throws on an unknown/disposed id.
|
|
2294
|
+
fn host_object_of(
|
|
2295
|
+
scope: &mut v8::PinScope<'_, '_>,
|
|
2296
|
+
args: v8::FunctionCallbackArguments<'_>,
|
|
2297
|
+
mut rv: v8::ReturnValue<'_, v8::Value>,
|
|
2298
|
+
) {
|
|
2299
|
+
let Some(id) = args.get(0).int32_value(scope) else {
|
|
2300
|
+
throw_js_error(scope, "hostObjectOf expects a context id");
|
|
2301
|
+
return;
|
|
2302
|
+
};
|
|
2303
|
+
match context_for(istate!(scope), id) {
|
|
2304
|
+
Some(g) => {
|
|
2305
|
+
let context = v8::Local::new(scope, &g);
|
|
2306
|
+
let scope = &mut v8::ContextScope::new(scope, context);
|
|
2307
|
+
rv.set(host_object(scope).into());
|
|
2308
|
+
}
|
|
2309
|
+
None => throw_js_error(scope, &format!("unknown context {id}")),
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
|
|
2001
2313
|
// NS.contextOf(value) -> the id of the context |value| was created in, or
|
|
2002
2314
|
// undefined for primitives and for objects whose context is no longer a live
|
|
2003
2315
|
// realm (e.g. it was reset away). Lets the embedder attribute a function or
|
|
@@ -2040,6 +2352,30 @@ fn set_promise_reject_handler(
|
|
|
2040
2352
|
}
|
|
2041
2353
|
}
|
|
2042
2354
|
|
|
2355
|
+
// NS.setImportMetaHandler(fn | null): register (or clear) the realm's handler
|
|
2356
|
+
// import_meta_cb hands each of its modules' import.meta to, as it is first
|
|
2357
|
+
// read — the realm whose namespace is called, whose global keeps it under a
|
|
2358
|
+
// private key (import_meta_key), so it goes with the realm, a reset's included,
|
|
2359
|
+
// and a realm init hook may set it before the realm is filed.
|
|
2360
|
+
fn set_import_meta_handler(
|
|
2361
|
+
scope: &mut v8::PinScope<'_, '_>,
|
|
2362
|
+
args: v8::FunctionCallbackArguments<'_>,
|
|
2363
|
+
_rv: v8::ReturnValue<'_, v8::Value>,
|
|
2364
|
+
) {
|
|
2365
|
+
let global = scope.get_current_context().global(scope);
|
|
2366
|
+
let key = import_meta_key(scope);
|
|
2367
|
+
match v8::Local::<v8::Function>::try_from(args.get(0)) {
|
|
2368
|
+
Ok(f) => global.set_private(scope, key, f.into()),
|
|
2369
|
+
Err(_) => global.delete_private(scope, key),
|
|
2370
|
+
};
|
|
2371
|
+
}
|
|
2372
|
+
|
|
2373
|
+
// The private key a realm's global keeps its import-meta handler under.
|
|
2374
|
+
fn import_meta_key<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Private> {
|
|
2375
|
+
let name = v8::String::new(scope, "rusty_racer:import_meta_handler").expect("a short string");
|
|
2376
|
+
v8::Private::for_api(scope, Some(name))
|
|
2377
|
+
}
|
|
2378
|
+
|
|
2043
2379
|
// NS.transferOut(arrayBufferOrView) -> a positive integer token, or 0 when the
|
|
2044
2380
|
// argument can't be zero-copy transferred so the caller falls back to a copy.
|
|
2045
2381
|
// Grabs the buffer's backing store, DETACHES the source (transfer semantics: its
|
|
@@ -2269,6 +2605,97 @@ pub fn set_realm_init_hook(hook: RealmInitHook) {
|
|
|
2269
2605
|
let _ = REALM_INIT_HOOK.set(hook);
|
|
2270
2606
|
}
|
|
2271
2607
|
|
|
2608
|
+
// The HOST OBJECT of the realm |scope| has entered: an object of the realm's,
|
|
2609
|
+
// with no prototype, that no property of any global holds — the realm's global
|
|
2610
|
+
// keeps it under a private key, which no script can name — so the host and the
|
|
2611
|
+
// realm's own bindings share it and a page's script neither reads, calls nor
|
|
2612
|
+
// replaces what it holds. A path that begins `@` starts from it rather than from
|
|
2613
|
+
// the global: `attach('@x.y', proc)` puts a host function there,
|
|
2614
|
+
// `Context#function('@x.y')` / `#call('@x.y')` find one there, `host_namespace:
|
|
2615
|
+
// '@NS'` installs the namespace there, `evaluate(report: '@r')` reports to one
|
|
2616
|
+
// there; and `RustyRacer::HOST_OBJECT`, as an argument crossing into JS, is this
|
|
2617
|
+
// object — how the bindings are handed it, where an embedder's realm init hook
|
|
2618
|
+
// (which calls this) does not hand it over itself. Made as it is first asked
|
|
2619
|
+
// for, so a realm that never uses it carries none.
|
|
2620
|
+
//
|
|
2621
|
+
// The private key lives with the global, so the object goes with its realm: a
|
|
2622
|
+
// reset or a disposal needs nothing of it, and no context slot is used (see
|
|
2623
|
+
// id_of_context for why realms keep none).
|
|
2624
|
+
pub fn host_object<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Object> {
|
|
2625
|
+
if let Some(object) = existing_host_object(scope) {
|
|
2626
|
+
return object;
|
|
2627
|
+
}
|
|
2628
|
+
let object = null_prototype_object(scope);
|
|
2629
|
+
let global = scope.get_current_context().global(scope);
|
|
2630
|
+
let key = host_object_key(scope);
|
|
2631
|
+
global.set_private(scope, key, object.into());
|
|
2632
|
+
object
|
|
2633
|
+
}
|
|
2634
|
+
|
|
2635
|
+
// The current realm's host object if it has made one yet, without making it.
|
|
2636
|
+
pub(crate) fn existing_host_object<'s>(
|
|
2637
|
+
scope: &mut v8::PinScope<'s, '_>,
|
|
2638
|
+
) -> Option<v8::Local<'s, v8::Object>> {
|
|
2639
|
+
let global = scope.get_current_context().global(scope);
|
|
2640
|
+
let key = host_object_key(scope);
|
|
2641
|
+
v8::Local::<v8::Object>::try_from(global.get_private(scope, key)?).ok()
|
|
2642
|
+
}
|
|
2643
|
+
|
|
2644
|
+
// The private key a global holds its host object under: an API private, so it
|
|
2645
|
+
// is one key per isolate whoever asks — the binding's own isolates keep it
|
|
2646
|
+
// (V8State::host_key) rather than looking it up by name at every use.
|
|
2647
|
+
fn host_object_key<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Private> {
|
|
2648
|
+
let kept = scope
|
|
2649
|
+
.get_slot::<IsolateState>()
|
|
2650
|
+
.and_then(|state| state.realms.host_key.clone());
|
|
2651
|
+
if let Some(key) = kept {
|
|
2652
|
+
return v8::Local::new(scope, &key);
|
|
2653
|
+
}
|
|
2654
|
+
let name = v8::String::new(scope, "rusty_racer:host_object").expect("a short string");
|
|
2655
|
+
let key = v8::Private::for_api(scope, Some(name));
|
|
2656
|
+
let kept = v8::Global::new(scope, key);
|
|
2657
|
+
if let Some(state) = scope.get_slot_mut::<IsolateState>() {
|
|
2658
|
+
state.realms.host_key = Some(kept);
|
|
2659
|
+
}
|
|
2660
|
+
key
|
|
2661
|
+
}
|
|
2662
|
+
|
|
2663
|
+
// An object of the current realm with no prototype: a read of a name it lacks
|
|
2664
|
+
// ends there, never in an Object.prototype a page may have put a getter on.
|
|
2665
|
+
fn null_prototype_object<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Object> {
|
|
2666
|
+
let null = v8::null(scope).into();
|
|
2667
|
+
v8::Object::with_prototype_and_properties(scope, null, &[], &[])
|
|
2668
|
+
}
|
|
2669
|
+
|
|
2670
|
+
// Where a path starts, and the rest of it: `@a.b` is the host object's `a.b`, any
|
|
2671
|
+
// other path the global's.
|
|
2672
|
+
pub(crate) fn path_root<'s, 'p>(
|
|
2673
|
+
scope: &mut v8::PinScope<'s, '_>,
|
|
2674
|
+
path: &'p str,
|
|
2675
|
+
) -> (v8::Local<'s, v8::Object>, &'p str, bool) {
|
|
2676
|
+
match path.strip_prefix('@') {
|
|
2677
|
+
Some(rest) => (host_object(scope), rest, true),
|
|
2678
|
+
None => (scope.get_current_context().global(scope), path, false),
|
|
2679
|
+
}
|
|
2680
|
+
}
|
|
2681
|
+
|
|
2682
|
+
// One segment of a path read off |holder|: an ordinary [[Get]] on the global's
|
|
2683
|
+
// side; on the host object's (|hidden|), its OWN property alone — undefined
|
|
2684
|
+
// where it has none, so no prototype of an object along the way (Object's, a
|
|
2685
|
+
// function's) is ever consulted, and a getter a page put there neither sees
|
|
2686
|
+
// the walk nor hands it an object of the page's. None when the read threw.
|
|
2687
|
+
pub(crate) fn path_segment<'s>(
|
|
2688
|
+
scope: &mut v8::PinScope<'s, '_>,
|
|
2689
|
+
holder: v8::Local<v8::Object>,
|
|
2690
|
+
key: v8::Local<v8::String>,
|
|
2691
|
+
hidden: bool,
|
|
2692
|
+
) -> Option<v8::Local<'s, v8::Value>> {
|
|
2693
|
+
if hidden && !holder.has_own_property(scope, key.into())? {
|
|
2694
|
+
return Some(v8::undefined(scope).into());
|
|
2695
|
+
}
|
|
2696
|
+
holder.get(scope, key.into())
|
|
2697
|
+
}
|
|
2698
|
+
|
|
2272
2699
|
fn new_realm(
|
|
2273
2700
|
scope: &mut v8::PinScope<'_, '_, ()>,
|
|
2274
2701
|
context_id: i32,
|
|
@@ -2373,9 +2800,12 @@ fn flush_retiring(scope: &mut v8::PinScope<'_, '_, ()>) {
|
|
|
2373
2800
|
drop(retiring);
|
|
2374
2801
|
}
|
|
2375
2802
|
|
|
2376
|
-
// Inject globalThis.<name> = { drainMicrotasks } into a context
|
|
2377
|
-
//
|
|
2378
|
-
//
|
|
2803
|
+
// Inject globalThis.<name> = { drainMicrotasks, ... } into a context — or, for
|
|
2804
|
+
// an `@name`, put it on the realm's host object instead, with no prototype, where
|
|
2805
|
+
// only the host and the realm's bindings reach it, and with one member more
|
|
2806
|
+
// there: hostObjectOf(id), another realm's host object. Re-run on reset_realm so the
|
|
2807
|
+
// fresh realm keeps the namespace. Takes a scope (not the isolate) so
|
|
2808
|
+
// service_request can call it from nested servicing too.
|
|
2379
2809
|
fn install_host_namespace(
|
|
2380
2810
|
scope: &mut v8::PinScope<'_, '_, ()>,
|
|
2381
2811
|
ctx: &v8::Global<v8::Context>,
|
|
@@ -2384,8 +2814,13 @@ fn install_host_namespace(
|
|
|
2384
2814
|
v8::scope!(let scope, &mut *scope);
|
|
2385
2815
|
let context = v8::Local::new(scope, ctx);
|
|
2386
2816
|
let scope = &mut v8::ContextScope::new(scope, context);
|
|
2387
|
-
let
|
|
2388
|
-
let
|
|
2817
|
+
let (holder, name, hidden) = path_root(scope, name);
|
|
2818
|
+
let ns = if hidden {
|
|
2819
|
+
null_prototype_object(scope)
|
|
2820
|
+
} else {
|
|
2821
|
+
v8::Object::new(scope)
|
|
2822
|
+
};
|
|
2823
|
+
let members: [(&str, Option<v8::Local<v8::Function>>); 10] = [
|
|
2389
2824
|
(
|
|
2390
2825
|
"drainMicrotasks",
|
|
2391
2826
|
v8::Function::new(scope, drain_microtasks),
|
|
@@ -2396,46 +2831,68 @@ fn install_host_namespace(
|
|
|
2396
2831
|
"setPromiseRejectHandler",
|
|
2397
2832
|
v8::Function::new(scope, set_promise_reject_handler),
|
|
2398
2833
|
),
|
|
2834
|
+
(
|
|
2835
|
+
"setImportMetaHandler",
|
|
2836
|
+
v8::Function::new(scope, set_import_meta_handler),
|
|
2837
|
+
),
|
|
2399
2838
|
("transferOut", v8::Function::new(scope, transfer_out)),
|
|
2400
2839
|
("transferIn", v8::Function::new(scope, transfer_in)),
|
|
2401
2840
|
("shareOut", v8::Function::new(scope, share_out)),
|
|
2402
2841
|
("shareIn", v8::Function::new(scope, share_in)),
|
|
2403
2842
|
("transferDrop", v8::Function::new(scope, transfer_drop)),
|
|
2404
2843
|
];
|
|
2405
|
-
|
|
2844
|
+
let hidden_members: &[(&str, Option<v8::Local<v8::Function>>)] = if hidden {
|
|
2845
|
+
&[("hostObjectOf", v8::Function::new(scope, host_object_of))]
|
|
2846
|
+
} else {
|
|
2847
|
+
&[]
|
|
2848
|
+
};
|
|
2849
|
+
for (member, function) in members.into_iter().chain(hidden_members.iter().copied()) {
|
|
2406
2850
|
if let (Some(f), Some(k)) = (function, v8::String::new(scope, member)) {
|
|
2407
2851
|
ns.create_data_property(scope, k.into(), f.into());
|
|
2408
2852
|
}
|
|
2409
2853
|
}
|
|
2410
2854
|
if let Some(key) = v8::String::new(scope, name) {
|
|
2411
|
-
|
|
2412
|
-
global.create_data_property(scope, key.into(), ns.into());
|
|
2855
|
+
holder.create_data_property(scope, key.into(), ns.into());
|
|
2413
2856
|
}
|
|
2414
2857
|
}
|
|
2415
2858
|
|
|
2416
2859
|
// Set |function| at the dotted property path |name| on the global, creating
|
|
2417
2860
|
// intermediate plain objects as needed — so attach("MiniRacer.foo", ...) lands
|
|
2418
2861
|
// under the namespace whether or not globalThis.MiniRacer already exists, while
|
|
2419
|
-
// a bare "foo" still attaches on the global.
|
|
2862
|
+
// a bare "foo" still attaches on the global. An `@` path lands on the realm's
|
|
2863
|
+
// host object instead: walked through own properties alone (path_segment), its
|
|
2864
|
+
// missing intermediates made with no prototype, and every property DEFINED
|
|
2865
|
+
// there — nothing a page's script left on a prototype runs or is written to.
|
|
2420
2866
|
fn attach_at_path(
|
|
2421
2867
|
scope: &mut v8::PinScope<'_, '_>,
|
|
2422
|
-
context: v8::Local<v8::Context>,
|
|
2423
2868
|
name: &str,
|
|
2424
2869
|
function: v8::Local<v8::Function>,
|
|
2425
2870
|
) -> Result<JsVal, VmError> {
|
|
2426
|
-
let mut
|
|
2871
|
+
let (mut holder, path, hidden) = path_root(scope, name);
|
|
2872
|
+
let mut parts: Vec<&str> = path.split('.').collect();
|
|
2427
2873
|
let leaf = parts
|
|
2428
2874
|
.pop()
|
|
2429
2875
|
.filter(|s| !s.is_empty())
|
|
2430
2876
|
.ok_or_else(|| VmError::Runtime(format!("invalid attach name `{name}`")))?;
|
|
2431
|
-
|
|
2877
|
+
// Make a property of |holder|: defined on the host object's side, assigned on
|
|
2878
|
+
// the global's (as attach always has, so an accessor there still sees it).
|
|
2879
|
+
let put = |scope: &mut v8::PinScope<'_, '_>,
|
|
2880
|
+
holder: v8::Local<v8::Object>,
|
|
2881
|
+
key: v8::Local<v8::String>,
|
|
2882
|
+
value: v8::Local<v8::Value>| {
|
|
2883
|
+
if hidden {
|
|
2884
|
+
holder.create_data_property(scope, key.into(), value)
|
|
2885
|
+
} else {
|
|
2886
|
+
holder.set(scope, key.into(), value)
|
|
2887
|
+
}
|
|
2888
|
+
};
|
|
2432
2889
|
for part in parts {
|
|
2433
2890
|
if part.is_empty() {
|
|
2434
2891
|
return Err(VmError::Runtime(format!("invalid attach name `{name}`")));
|
|
2435
2892
|
}
|
|
2436
2893
|
let key = v8::String::new(scope, part)
|
|
2437
2894
|
.ok_or_else(|| VmError::Runtime("name too large".into()))?;
|
|
2438
|
-
holder = match
|
|
2895
|
+
holder = match path_segment(scope, holder, key, hidden) {
|
|
2439
2896
|
Some(v) if v.is_object() => v8::Local::<v8::Object>::try_from(v).unwrap(),
|
|
2440
2897
|
// Don't clobber an existing non-object (e.g. a primitive global that
|
|
2441
2898
|
// collides with the namespace name) — fail loudly instead.
|
|
@@ -2445,8 +2902,12 @@ fn attach_at_path(
|
|
|
2445
2902
|
)));
|
|
2446
2903
|
}
|
|
2447
2904
|
_ => {
|
|
2448
|
-
let obj =
|
|
2449
|
-
|
|
2905
|
+
let obj = if hidden {
|
|
2906
|
+
null_prototype_object(scope)
|
|
2907
|
+
} else {
|
|
2908
|
+
v8::Object::new(scope)
|
|
2909
|
+
};
|
|
2910
|
+
if put(scope, holder, key, obj.into()) != Some(true) {
|
|
2450
2911
|
return Err(VmError::Runtime(format!(
|
|
2451
2912
|
"`{name}`: cannot create `{part}`"
|
|
2452
2913
|
)));
|
|
@@ -2457,7 +2918,7 @@ fn attach_at_path(
|
|
|
2457
2918
|
}
|
|
2458
2919
|
let key =
|
|
2459
2920
|
v8::String::new(scope, leaf).ok_or_else(|| VmError::Runtime("name too large".into()))?;
|
|
2460
|
-
if
|
|
2921
|
+
if put(scope, holder, key, function.into()) != Some(true) {
|
|
2461
2922
|
return Err(VmError::Runtime(format!(
|
|
2462
2923
|
"`{name}`: target is not writable/extensible"
|
|
2463
2924
|
)));
|
|
@@ -2574,7 +3035,7 @@ impl Isolate {
|
|
|
2574
3035
|
// :auto/:explicit distinction lives in auto_microtasks (read by
|
|
2575
3036
|
// auto_drain).
|
|
2576
3037
|
isolate.set_microtasks_policy(v8::MicrotasksPolicy::Explicit);
|
|
2577
|
-
// JS import() routes here; rejects unless a
|
|
3038
|
+
// JS import() routes here; rejects unless a dynamic_import_handler is set.
|
|
2578
3039
|
isolate.set_host_import_module_dynamically_callback(dynamic_import_cb);
|
|
2579
3040
|
// Fills import.meta.url (the module's compile-time filename) on first access.
|
|
2580
3041
|
isolate.set_host_initialize_import_meta_object_callback(import_meta_cb);
|
|
@@ -2627,7 +3088,7 @@ impl Isolate {
|
|
|
2627
3088
|
// owner check.
|
|
2628
3089
|
use magnus::rb_sys::{AsRawValue, FromRawValue};
|
|
2629
3090
|
let owner_thread = unsafe { Value::from_raw(rb_sys::rb_thread_current()) };
|
|
2630
|
-
// The roots array (see
|
|
3091
|
+
// The roots array (see ROOT_IMPORT_HANDLER): created empty, grown by the
|
|
2631
3092
|
// first attach. Nothing roots it — the wrappers mark it, so it lives
|
|
2632
3093
|
// exactly as long as this isolate is reachable from Ruby.
|
|
2633
3094
|
let roots = ruby.ary_new();
|
|
@@ -2648,6 +3109,7 @@ impl Isolate {
|
|
|
2648
3109
|
procs: Mutex::new(ProcTable::default()),
|
|
2649
3110
|
released: Mutex::new(Vec::new()),
|
|
2650
3111
|
handles_released: AtomicBool::new(false),
|
|
3112
|
+
disposed_realms: Mutex::new(std::collections::HashSet::new()),
|
|
2651
3113
|
default_timeout_ms: timeout_ms,
|
|
2652
3114
|
memory_limit,
|
|
2653
3115
|
watchdog,
|
|
@@ -2946,7 +3408,7 @@ impl Core {
|
|
|
2946
3408
|
.clone()
|
|
2947
3409
|
}
|
|
2948
3410
|
|
|
2949
|
-
// ── the roots array (see the module header +
|
|
3411
|
+
// ── the roots array (see the module header + ROOT_IMPORT_HANDLER) ──────
|
|
2950
3412
|
// Keep `val` alive for as long as this isolate is reachable from Ruby. On a
|
|
2951
3413
|
// Ruby thread with the GVL: storing can grow the Array, which allocates.
|
|
2952
3414
|
fn root_store<T: magnus::IntoValue>(
|
|
@@ -3307,6 +3769,7 @@ impl Core {
|
|
|
3307
3769
|
let reply = self.run(ruby, Request::DisposeContext { context_id })?;
|
|
3308
3770
|
self.reply_value(ruby, reply)?;
|
|
3309
3771
|
self.release_context_procs(ruby, context_id);
|
|
3772
|
+
self.disposed_realms.lock().unwrap().insert(context_id);
|
|
3310
3773
|
Ok(())
|
|
3311
3774
|
}
|
|
3312
3775
|
|
|
@@ -3321,6 +3784,7 @@ impl Core {
|
|
|
3321
3784
|
cached_data: Option<Vec<u8>>,
|
|
3322
3785
|
produce_cache: bool,
|
|
3323
3786
|
eager: bool,
|
|
3787
|
+
host_defined: Option<JsVal>,
|
|
3324
3788
|
) -> Result<Compiled, Error> {
|
|
3325
3789
|
let reply = self.run(
|
|
3326
3790
|
ruby,
|
|
@@ -3331,6 +3795,7 @@ impl Core {
|
|
|
3331
3795
|
cached_data,
|
|
3332
3796
|
produce_cache,
|
|
3333
3797
|
eager,
|
|
3798
|
+
host_defined,
|
|
3334
3799
|
},
|
|
3335
3800
|
)?;
|
|
3336
3801
|
match reply {
|
|
@@ -3421,6 +3886,114 @@ impl Core {
|
|
|
3421
3886
|
self.reply_value(ruby, reply)
|
|
3422
3887
|
}
|
|
3423
3888
|
|
|
3889
|
+
// [[specifier, attributes], …], each request's attributes a Hash (attributes_hash).
|
|
3890
|
+
fn module_script_id(&self, ruby: &Ruby, module_id: i32) -> Result<Value, Error> {
|
|
3891
|
+
let reply = self.run(ruby, Request::ModuleScriptId { module_id })?;
|
|
3892
|
+
self.reply_value(ruby, reply)
|
|
3893
|
+
}
|
|
3894
|
+
|
|
3895
|
+
fn module_requests(&self, ruby: &Ruby, module_id: i32) -> Result<Value, Error> {
|
|
3896
|
+
let JsVal::Array { items, .. } =
|
|
3897
|
+
(match self.run(ruby, Request::ModuleRequests { module_id })? {
|
|
3898
|
+
VmReply::Done(Ok(value)) => value,
|
|
3899
|
+
VmReply::Done(Err(e)) => return Err(vm_err(ruby, e)),
|
|
3900
|
+
_ => {
|
|
3901
|
+
return Err(Error::new(
|
|
3902
|
+
err_class(ruby, "InternalError"),
|
|
3903
|
+
"internal: unexpected requests reply",
|
|
3904
|
+
));
|
|
3905
|
+
}
|
|
3906
|
+
})
|
|
3907
|
+
else {
|
|
3908
|
+
return Err(Error::new(
|
|
3909
|
+
err_class(ruby, "InternalError"),
|
|
3910
|
+
"internal: unexpected requests reply",
|
|
3911
|
+
));
|
|
3912
|
+
};
|
|
3913
|
+
let requests = ruby.ary_new_capa(items.len());
|
|
3914
|
+
for item in items {
|
|
3915
|
+
let JsVal::Array { items: pair, .. } = item else {
|
|
3916
|
+
continue;
|
|
3917
|
+
};
|
|
3918
|
+
let (Some(JsVal::Str(specifier)), Some(JsVal::Obj { entries, .. })) =
|
|
3919
|
+
(pair.first(), pair.get(1))
|
|
3920
|
+
else {
|
|
3921
|
+
continue;
|
|
3922
|
+
};
|
|
3923
|
+
let attributes: Vec<(String, String)> = entries
|
|
3924
|
+
.iter()
|
|
3925
|
+
.filter_map(|(key, value)| match value {
|
|
3926
|
+
JsVal::Str(value) => Some((key.clone(), value.clone())),
|
|
3927
|
+
_ => None,
|
|
3928
|
+
})
|
|
3929
|
+
.collect();
|
|
3930
|
+
requests.push(ruby.ary_new_from_values(&[
|
|
3931
|
+
ruby.str_new(specifier).as_value(),
|
|
3932
|
+
attributes_hash(ruby, &attributes)?.as_value(),
|
|
3933
|
+
]))?;
|
|
3934
|
+
}
|
|
3935
|
+
Ok(requests.as_value())
|
|
3936
|
+
}
|
|
3937
|
+
|
|
3938
|
+
// A synthetic module of the realm's (Request::CreateSyntheticModule): its id.
|
|
3939
|
+
fn synthetic_module(
|
|
3940
|
+
&self,
|
|
3941
|
+
ruby: &Ruby,
|
|
3942
|
+
context_id: i32,
|
|
3943
|
+
filename: String,
|
|
3944
|
+
export: SyntheticExport,
|
|
3945
|
+
) -> Result<i32, Error> {
|
|
3946
|
+
let reply = self.run(
|
|
3947
|
+
ruby,
|
|
3948
|
+
Request::CreateSyntheticModule {
|
|
3949
|
+
context_id,
|
|
3950
|
+
filename,
|
|
3951
|
+
export,
|
|
3952
|
+
timeout_ms: self.default_timeout_ms,
|
|
3953
|
+
},
|
|
3954
|
+
)?;
|
|
3955
|
+
match reply {
|
|
3956
|
+
VmReply::Done(Ok(JsVal::Int(id))) => Ok(id as i32),
|
|
3957
|
+
VmReply::Done(Err(e)) => Err(vm_err(ruby, e)),
|
|
3958
|
+
_ => Err(Error::new(
|
|
3959
|
+
err_class(ruby, "InternalError"),
|
|
3960
|
+
"internal: unexpected synthetic module reply",
|
|
3961
|
+
)),
|
|
3962
|
+
}
|
|
3963
|
+
}
|
|
3964
|
+
|
|
3965
|
+
// Settle the waiting import() |import_id| (Request::SettleImport): whether it
|
|
3966
|
+
// was still waiting. A module is linked by |resolve| (parked as
|
|
3967
|
+
// instantiate_module parks its block, the outer op's put back after).
|
|
3968
|
+
fn settle_import(
|
|
3969
|
+
&self,
|
|
3970
|
+
ruby: &Ruby,
|
|
3971
|
+
import_id: u64,
|
|
3972
|
+
settle: Settle,
|
|
3973
|
+
resolve: Option<Proc>,
|
|
3974
|
+
) -> Result<bool, Error> {
|
|
3975
|
+
self.ensure_owner_and_live(ruby)?;
|
|
3976
|
+
let parked = resolve.map(|p| RootedProc(BoxValue::new(p)));
|
|
3977
|
+
let (saved_resolve, saved_err) = self.swap_instantiate(parked, None);
|
|
3978
|
+
let reply = self.run(
|
|
3979
|
+
ruby,
|
|
3980
|
+
Request::SettleImport {
|
|
3981
|
+
import_id,
|
|
3982
|
+
settle,
|
|
3983
|
+
timeout_ms: self.default_timeout_ms,
|
|
3984
|
+
},
|
|
3985
|
+
);
|
|
3986
|
+
self.swap_instantiate(saved_resolve, saved_err);
|
|
3987
|
+
match reply? {
|
|
3988
|
+
VmReply::Done(Ok(JsVal::Bool(settled))) => Ok(settled),
|
|
3989
|
+
VmReply::Done(Err(e)) => Err(vm_err(ruby, e)),
|
|
3990
|
+
_ => Err(Error::new(
|
|
3991
|
+
err_class(ruby, "InternalError"),
|
|
3992
|
+
"internal: unexpected import reply",
|
|
3993
|
+
)),
|
|
3994
|
+
}
|
|
3995
|
+
}
|
|
3996
|
+
|
|
3424
3997
|
// Classic script: compile, run, dispose.
|
|
3425
3998
|
#[allow(clippy::too_many_arguments)]
|
|
3426
3999
|
fn compile_script(
|
|
@@ -3432,6 +4005,7 @@ impl Core {
|
|
|
3432
4005
|
cached_data: Option<Vec<u8>>,
|
|
3433
4006
|
produce_cache: bool,
|
|
3434
4007
|
eager: bool,
|
|
4008
|
+
host_defined: Option<JsVal>,
|
|
3435
4009
|
) -> Result<Compiled, Error> {
|
|
3436
4010
|
let reply = self.run(
|
|
3437
4011
|
ruby,
|
|
@@ -3442,6 +4016,7 @@ impl Core {
|
|
|
3442
4016
|
cached_data,
|
|
3443
4017
|
produce_cache,
|
|
3444
4018
|
eager,
|
|
4019
|
+
host_defined,
|
|
3445
4020
|
},
|
|
3446
4021
|
)?;
|
|
3447
4022
|
match reply {
|
|
@@ -3474,6 +4049,11 @@ impl Core {
|
|
|
3474
4049
|
code_cache_from_reply(ruby, reply)
|
|
3475
4050
|
}
|
|
3476
4051
|
|
|
4052
|
+
fn unbound_script_id(&self, ruby: &Ruby, script_id: i32) -> Result<Value, Error> {
|
|
4053
|
+
let reply = self.run(ruby, Request::UnboundScriptId { script_id })?;
|
|
4054
|
+
self.reply_value(ruby, reply)
|
|
4055
|
+
}
|
|
4056
|
+
|
|
3477
4057
|
fn module_code_cache(&self, ruby: &Ruby, module_id: i32) -> Result<Option<Vec<u8>>, Error> {
|
|
3478
4058
|
let reply = self.run(ruby, Request::ModuleCodeCache { module_id })?;
|
|
3479
4059
|
code_cache_from_reply(ruby, reply)
|
|
@@ -3482,15 +4062,16 @@ impl Core {
|
|
|
3482
4062
|
// Owner-thread only, like every other writer of the roots array (`attach`,
|
|
3483
4063
|
// `attach_many`, `dispose`): the store can REALLOC the array's element storage, and
|
|
3484
4064
|
// the import hooks read that storage with the GVL released.
|
|
3485
|
-
|
|
4065
|
+
// (…nil clearing it: an import() rejected then)
|
|
4066
|
+
fn set_dynamic_import_handler(&self, ruby: &Ruby, proc: Option<Proc>) -> Result<(), Error> {
|
|
3486
4067
|
self.ensure_owner_and_live(ruby)?;
|
|
3487
|
-
self.root_store(ruby,
|
|
4068
|
+
self.root_store(ruby, ROOT_IMPORT_HANDLER, proc)
|
|
3488
4069
|
}
|
|
3489
4070
|
|
|
3490
|
-
// The
|
|
4071
|
+
// The handler, or None if none was set. Read on the V8 side without the GVL —
|
|
3491
4072
|
// see root_proc.
|
|
3492
|
-
fn
|
|
3493
|
-
self.root_proc(
|
|
4073
|
+
fn dynamic_import_handler(&self) -> Option<Proc> {
|
|
4074
|
+
self.root_proc(ROOT_IMPORT_HANDLER)
|
|
3494
4075
|
}
|
|
3495
4076
|
|
|
3496
4077
|
// Terminate whatever is running. IsolateHandle is Send + refcounted —
|
|
@@ -3710,9 +4291,14 @@ impl Isolate {
|
|
|
3710
4291
|
fn pump_message_loop(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
|
|
3711
4292
|
rb_self.core.pump_message_loop(ruby)
|
|
3712
4293
|
}
|
|
3713
|
-
//
|
|
3714
|
-
|
|
3715
|
-
|
|
4294
|
+
// dynamic_import_handler = ->(import) { ... } for import(): handed each one's
|
|
4295
|
+
// RustyRacer::DynamicImport.
|
|
4296
|
+
fn set_dynamic_import_handler(
|
|
4297
|
+
ruby: &Ruby,
|
|
4298
|
+
rb_self: &Self,
|
|
4299
|
+
proc: Option<Proc>,
|
|
4300
|
+
) -> Result<(), Error> {
|
|
4301
|
+
rb_self.core.set_dynamic_import_handler(ruby, proc)
|
|
3716
4302
|
}
|
|
3717
4303
|
fn dispose(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
|
|
3718
4304
|
rb_self.core.dispose(ruby)
|
|
@@ -3731,7 +4317,7 @@ impl Context {
|
|
|
3731
4317
|
}
|
|
3732
4318
|
fn check_live(&self, ruby: &Ruby) -> Result<(), Error> {
|
|
3733
4319
|
// id 0's lifetime is the isolate's; extras also track their own dispose.
|
|
3734
|
-
if self.disposed
|
|
4320
|
+
if self.disposed() {
|
|
3735
4321
|
return Err(Error::new(
|
|
3736
4322
|
err_class(ruby, "DisposedError"),
|
|
3737
4323
|
"disposed context",
|
|
@@ -3806,6 +4392,7 @@ impl Context {
|
|
|
3806
4392
|
rb_self.check_live(ruby)?;
|
|
3807
4393
|
rb_self.core.reset(ruby, rb_self.id)
|
|
3808
4394
|
}
|
|
4395
|
+
#[allow(clippy::too_many_arguments)]
|
|
3809
4396
|
fn compile_module(
|
|
3810
4397
|
ruby: &Ruby,
|
|
3811
4398
|
rb_self: &Self,
|
|
@@ -3814,9 +4401,11 @@ impl Context {
|
|
|
3814
4401
|
cached_data: Option<magnus::RString>,
|
|
3815
4402
|
produce_cache: bool,
|
|
3816
4403
|
eager: bool,
|
|
4404
|
+
host_defined: Value,
|
|
3817
4405
|
) -> Result<JsModule, Error> {
|
|
3818
4406
|
rb_self.check_live(ruby)?;
|
|
3819
4407
|
let cache_in = binary_bytes(ruby, cached_data)?;
|
|
4408
|
+
let host_defined = host_defined_arg(ruby, host_defined)?;
|
|
3820
4409
|
let cm = rb_self.core.compile_module(
|
|
3821
4410
|
ruby,
|
|
3822
4411
|
rb_self.id,
|
|
@@ -3825,17 +4414,57 @@ impl Context {
|
|
|
3825
4414
|
cache_in,
|
|
3826
4415
|
produce_cache,
|
|
3827
4416
|
eager,
|
|
4417
|
+
host_defined,
|
|
3828
4418
|
)?;
|
|
3829
|
-
Ok(
|
|
3830
|
-
|
|
3831
|
-
|
|
4419
|
+
Ok(rb_self.module(cm.id, cm.cached_data, cm.cache_rejected))
|
|
4420
|
+
}
|
|
4421
|
+
fn module(
|
|
4422
|
+
&self,
|
|
4423
|
+
module_id: i32,
|
|
4424
|
+
cached_data: Option<Vec<u8>>,
|
|
4425
|
+
cache_rejected: bool,
|
|
4426
|
+
) -> JsModule {
|
|
4427
|
+
JsModule {
|
|
4428
|
+
core: self.core.clone(),
|
|
4429
|
+
module_id,
|
|
3832
4430
|
disposed: AtomicBool::new(false),
|
|
3833
|
-
cached_data
|
|
3834
|
-
cache_rejected
|
|
3835
|
-
}
|
|
4431
|
+
cached_data,
|
|
4432
|
+
cache_rejected,
|
|
4433
|
+
}
|
|
4434
|
+
}
|
|
4435
|
+
// _synthetic_module(filename, kind, payload, args): a module exporting
|
|
4436
|
+
// `default` alone — kind 0: payload marshalled; 1: payload a JSON text,
|
|
4437
|
+
// %JSON.parse%d; 2: payload a function path, called with args.
|
|
4438
|
+
fn synthetic_module(
|
|
4439
|
+
ruby: &Ruby,
|
|
4440
|
+
rb_self: &Self,
|
|
4441
|
+
filename: String,
|
|
4442
|
+
kind: u8,
|
|
4443
|
+
payload: Value,
|
|
4444
|
+
args: RArray,
|
|
4445
|
+
) -> Result<JsModule, Error> {
|
|
4446
|
+
rb_self.check_live(ruby)?;
|
|
4447
|
+
let export = match kind {
|
|
4448
|
+
0 => SyntheticExport::Value(ruby_to_jsval(payload)?),
|
|
4449
|
+
1 => SyntheticExport::Json(String::try_convert(payload)?),
|
|
4450
|
+
_ => SyntheticExport::Call {
|
|
4451
|
+
path: String::try_convert(payload)?,
|
|
4452
|
+
args: {
|
|
4453
|
+
let args: Vec<Value> = (0..args.len())
|
|
4454
|
+
.map(|i| args.entry::<Value>(i as isize))
|
|
4455
|
+
.collect::<Result<_, _>>()?;
|
|
4456
|
+
js_args(&args)?
|
|
4457
|
+
},
|
|
4458
|
+
},
|
|
4459
|
+
};
|
|
4460
|
+
let id = rb_self
|
|
4461
|
+
.core
|
|
4462
|
+
.synthetic_module(ruby, rb_self.id, filename, export)?;
|
|
4463
|
+
Ok(rb_self.module(id, None, false))
|
|
3836
4464
|
}
|
|
3837
4465
|
// compile(source, filename:, cached_data:, produce_cache:, eager:) -> Script:
|
|
3838
4466
|
// a classic <script>. Same cache semantics as compile_module.
|
|
4467
|
+
#[allow(clippy::too_many_arguments)]
|
|
3839
4468
|
fn compile(
|
|
3840
4469
|
ruby: &Ruby,
|
|
3841
4470
|
rb_self: &Self,
|
|
@@ -3844,9 +4473,11 @@ impl Context {
|
|
|
3844
4473
|
cached_data: Option<magnus::RString>,
|
|
3845
4474
|
produce_cache: bool,
|
|
3846
4475
|
eager: bool,
|
|
4476
|
+
host_defined: Value,
|
|
3847
4477
|
) -> Result<Script, Error> {
|
|
3848
4478
|
rb_self.check_live(ruby)?;
|
|
3849
4479
|
let cache_in = binary_bytes(ruby, cached_data)?;
|
|
4480
|
+
let host_defined = host_defined_arg(ruby, host_defined)?;
|
|
3850
4481
|
let cs = rb_self.core.compile_script(
|
|
3851
4482
|
ruby,
|
|
3852
4483
|
rb_self.id,
|
|
@@ -3855,6 +4486,7 @@ impl Context {
|
|
|
3855
4486
|
cache_in,
|
|
3856
4487
|
produce_cache,
|
|
3857
4488
|
eager,
|
|
4489
|
+
host_defined,
|
|
3858
4490
|
)?;
|
|
3859
4491
|
Ok(Script {
|
|
3860
4492
|
core: rb_self.core.clone(),
|
|
@@ -3876,7 +4508,9 @@ impl Context {
|
|
|
3876
4508
|
Ok(())
|
|
3877
4509
|
}
|
|
3878
4510
|
fn disposed(&self) -> bool {
|
|
3879
|
-
self.disposed.load(Ordering::SeqCst)
|
|
4511
|
+
self.disposed.load(Ordering::SeqCst)
|
|
4512
|
+
|| self.core.is_disposed()
|
|
4513
|
+
|| self.core.disposed_realms.lock().unwrap().contains(&self.id)
|
|
3880
4514
|
}
|
|
3881
4515
|
}
|
|
3882
4516
|
|
|
@@ -3993,6 +4627,21 @@ impl JsModule {
|
|
|
3993
4627
|
rb_self.check_live(ruby)?;
|
|
3994
4628
|
rb_self.core.module_graph_async(ruby, rb_self.module_id)
|
|
3995
4629
|
}
|
|
4630
|
+
// The module's script id (V8 Module::ScriptId) — what StackFrame#script_id /
|
|
4631
|
+
// an embedder's stack walk names its code by — or nil: a synthetic module, an
|
|
4632
|
+
// errored one. Modules V8's compilation cache shares (the same source and
|
|
4633
|
+
// filename) share it.
|
|
4634
|
+
fn script_id(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
|
|
4635
|
+
rb_self.check_live(ruby)?;
|
|
4636
|
+
rb_self.core.module_script_id(ruby, rb_self.module_id)
|
|
4637
|
+
}
|
|
4638
|
+
// [[specifier, attributes], …]: the module's requests (V8 GetModuleRequests),
|
|
4639
|
+
// each with its import attributes as a Hash, in source order — what linking
|
|
4640
|
+
// it will ask its resolve block for. A synthetic module has none.
|
|
4641
|
+
fn requests(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
|
|
4642
|
+
rb_self.check_live(ruby)?;
|
|
4643
|
+
rb_self.core.module_requests(ruby, rb_self.module_id)
|
|
4644
|
+
}
|
|
3996
4645
|
// The bytecode cache produced at compile (produce_cache: true), as a binary
|
|
3997
4646
|
// String, or nil. Persist it cross-process and pass back via cached_data:.
|
|
3998
4647
|
fn cached_data(ruby: &Ruby, rb_self: &Self) -> Value {
|
|
@@ -4047,6 +4696,13 @@ impl Script {
|
|
|
4047
4696
|
rb_self.check_live(ruby)?;
|
|
4048
4697
|
rb_self.core.run_script(ruby, rb_self.script_id, true)
|
|
4049
4698
|
}
|
|
4699
|
+
// The script's V8 script id (UnboundScript::GetId), as Module#script_id: what
|
|
4700
|
+
// a stack frame of its code names it by. Scripts V8's compilation cache
|
|
4701
|
+
// shares (the same source and origin) share it.
|
|
4702
|
+
fn script_id(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
|
|
4703
|
+
rb_self.check_live(ruby)?;
|
|
4704
|
+
rb_self.core.unbound_script_id(ruby, rb_self.script_id)
|
|
4705
|
+
}
|
|
4050
4706
|
fn cached_data(ruby: &Ruby, rb_self: &Self) -> Value {
|
|
4051
4707
|
code_cache_value(ruby, rb_self.cached_data.as_ref())
|
|
4052
4708
|
}
|
|
@@ -4284,38 +4940,87 @@ fn js_runtime_error(ruby: &Ruby, message: String, backtrace: Vec<String>) -> Err
|
|
|
4284
4940
|
}
|
|
4285
4941
|
}
|
|
4286
4942
|
|
|
4287
|
-
//
|
|
4288
|
-
//
|
|
4289
|
-
|
|
4290
|
-
|
|
4291
|
-
|
|
4943
|
+
// A `host_defined:` argument: nil for none, else a primitive — an Integer, a
|
|
4944
|
+
// Float, a String, true or false — that a ScriptOrigin can carry.
|
|
4945
|
+
fn host_defined_arg(ruby: &Ruby, value: Value) -> Result<Option<JsVal>, Error> {
|
|
4946
|
+
if value.is_nil() {
|
|
4947
|
+
return Ok(None);
|
|
4948
|
+
}
|
|
4949
|
+
// (…a Symbol marshals as a String would, but names nothing a script was given: refused, as any other value is)
|
|
4950
|
+
if magnus::Symbol::from_value(value).is_some()
|
|
4951
|
+
|| magnus::value::StaticSymbol::from_value(value).is_some()
|
|
4952
|
+
{
|
|
4953
|
+
return Err(Error::new(
|
|
4954
|
+
ruby.exception_arg_error(),
|
|
4955
|
+
"host_defined: must be nil, an Integer, a Float, a String, true or false",
|
|
4956
|
+
));
|
|
4957
|
+
}
|
|
4958
|
+
match ruby_to_jsval(value)? {
|
|
4959
|
+
v @ (JsVal::Bool(_)
|
|
4960
|
+
| JsVal::Int(_)
|
|
4961
|
+
| JsVal::Num(_)
|
|
4962
|
+
| JsVal::Str(_)
|
|
4963
|
+
| JsVal::BigInt { .. }) => Ok(Some(v)),
|
|
4964
|
+
_ => Err(Error::new(
|
|
4965
|
+
ruby.exception_arg_error(),
|
|
4966
|
+
"host_defined: must be nil, an Integer, a Float, a String, true or false",
|
|
4967
|
+
)),
|
|
4968
|
+
}
|
|
4969
|
+
}
|
|
4970
|
+
|
|
4971
|
+
// A resolve block returns a RustyRacer::Module (or nil for a genuinely-
|
|
4972
|
+
// unresolved import); pull its module_id so the V8 side can look up the V8
|
|
4973
|
+
// module. Verifies the module belongs to THIS isolate (core identity), since
|
|
4974
|
+
// module ids are per-isolate and a foreign id would alias a local one. A
|
|
4975
|
+
// raised block propagates as Err (not silently swallowed into "not found").
|
|
4976
|
+
// The block is handed (specifier, referrer_url, attributes) — a lambda of two
|
|
4977
|
+
// parameters the first two alone, as it always was.
|
|
4292
4978
|
fn resolve_module_via_ruby(
|
|
4293
4979
|
core: &Core,
|
|
4294
4980
|
resolve: Proc,
|
|
4295
4981
|
specifier: &str,
|
|
4296
4982
|
referrer_url: &str,
|
|
4297
|
-
|
|
4298
|
-
// initiating realm as a 3rd Context arg so it can resolve per-realm. None for
|
|
4299
|
-
// the static instantiate block, whose (specifier, referrer_url) contract is
|
|
4300
|
-
// unchanged.
|
|
4301
|
-
initiating_context: Option<i32>,
|
|
4983
|
+
attributes: &[(String, String)],
|
|
4302
4984
|
) -> Result<Option<i32>, Error> {
|
|
4303
4985
|
let ruby = Ruby::get().unwrap();
|
|
4304
|
-
let ret: Value =
|
|
4305
|
-
|
|
4306
|
-
|
|
4307
|
-
|
|
4308
|
-
id,
|
|
4309
|
-
disposed: AtomicBool::new(false),
|
|
4310
|
-
};
|
|
4311
|
-
resolve.call((specifier, referrer_url, ctx))?
|
|
4312
|
-
}
|
|
4313
|
-
None => resolve.call((specifier, referrer_url))?,
|
|
4986
|
+
let ret: Value = if !takes_three(resolve)? {
|
|
4987
|
+
resolve.call((specifier, referrer_url))?
|
|
4988
|
+
} else {
|
|
4989
|
+
resolve.call((specifier, referrer_url, attributes_hash(&ruby, attributes)?))?
|
|
4314
4990
|
};
|
|
4315
|
-
|
|
4991
|
+
module_id_of(&ruby, core, ret)
|
|
4992
|
+
}
|
|
4993
|
+
|
|
4994
|
+
// Whether a resolve block takes a third argument: any proc does (it drops what it
|
|
4995
|
+
// has no parameter for); a lambda one with a rest parameter, or three in all.
|
|
4996
|
+
fn takes_three(resolve: Proc) -> Result<bool, Error> {
|
|
4997
|
+
if !resolve.is_lambda() {
|
|
4998
|
+
return Ok(true);
|
|
4999
|
+
}
|
|
5000
|
+
let arity = resolve.arity();
|
|
5001
|
+
if arity >= 0 {
|
|
5002
|
+
return Ok(arity >= 3);
|
|
5003
|
+
}
|
|
5004
|
+
let parameters: RArray = resolve.funcall("parameters", ())?;
|
|
5005
|
+
let mut count = 0;
|
|
5006
|
+
for parameter in parameters.into_iter() {
|
|
5007
|
+
let kind: magnus::Symbol = RArray::try_convert(parameter)?.entry(0)?;
|
|
5008
|
+
match kind.name()?.as_ref() {
|
|
5009
|
+
"rest" => return Ok(true),
|
|
5010
|
+
"req" | "opt" => count += 1,
|
|
5011
|
+
_ => {}
|
|
5012
|
+
}
|
|
5013
|
+
}
|
|
5014
|
+
Ok(count >= 3)
|
|
5015
|
+
}
|
|
5016
|
+
|
|
5017
|
+
// The id of the RustyRacer::Module |value| — None for nil, or a disposed one —
|
|
5018
|
+
// of the isolate |core|.
|
|
5019
|
+
fn module_id_of(ruby: &Ruby, core: &Core, value: Value) -> Result<Option<i32>, Error> {
|
|
5020
|
+
if value.is_nil() {
|
|
4316
5021
|
return Ok(None); // legitimately unresolved
|
|
4317
5022
|
}
|
|
4318
|
-
let obj = magnus::typed_data::Obj::<JsModule>::try_convert(
|
|
5023
|
+
let obj = magnus::typed_data::Obj::<JsModule>::try_convert(value).map_err(|_| {
|
|
4319
5024
|
Error::new(
|
|
4320
5025
|
ruby.exception_type_error(),
|
|
4321
5026
|
"module resolver must return a RustyRacer::Module or nil",
|
|
@@ -4323,8 +5028,8 @@ fn resolve_module_via_ruby(
|
|
|
4323
5028
|
})?;
|
|
4324
5029
|
if !std::ptr::eq(Arc::as_ptr(&obj.core), core as *const Core) {
|
|
4325
5030
|
return Err(Error::new(
|
|
4326
|
-
err_class(
|
|
4327
|
-
"module resolver returned a Module
|
|
5031
|
+
err_class(ruby, "Error"),
|
|
5032
|
+
"module resolver returned a Module of another isolate",
|
|
4328
5033
|
));
|
|
4329
5034
|
}
|
|
4330
5035
|
if obj.disposed.load(Ordering::SeqCst) {
|
|
@@ -4333,6 +5038,91 @@ fn resolve_module_via_ruby(
|
|
|
4333
5038
|
Ok(Some(obj.module_id))
|
|
4334
5039
|
}
|
|
4335
5040
|
|
|
5041
|
+
impl DynamicImport {
|
|
5042
|
+
fn specifier(&self) -> String {
|
|
5043
|
+
self.specifier.clone()
|
|
5044
|
+
}
|
|
5045
|
+
// The name of the script import() was called from (its filename), or nil.
|
|
5046
|
+
fn referrer(&self) -> Option<String> {
|
|
5047
|
+
self.referrer.clone()
|
|
5048
|
+
}
|
|
5049
|
+
// {key => value} of its `with` options' import attributes.
|
|
5050
|
+
fn attributes(ruby: &Ruby, rb_self: &Self) -> Result<RHash, Error> {
|
|
5051
|
+
attributes_hash(ruby, &rb_self.attributes)
|
|
5052
|
+
}
|
|
5053
|
+
// The `host_defined:` value of the script import() was called from, or nil.
|
|
5054
|
+
fn host_defined(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
|
|
5055
|
+
match &rb_self.host_defined {
|
|
5056
|
+
Some(value) => marshal::jsval_to_ruby(ruby, value),
|
|
5057
|
+
None => Ok(ruby.qnil().as_value()),
|
|
5058
|
+
}
|
|
5059
|
+
}
|
|
5060
|
+
// The realm import() was called in: a module it is resolved with is of it.
|
|
5061
|
+
fn context(&self) -> Context {
|
|
5062
|
+
Context {
|
|
5063
|
+
core: self.core.clone(),
|
|
5064
|
+
id: self.context_id,
|
|
5065
|
+
disposed: AtomicBool::new(false),
|
|
5066
|
+
}
|
|
5067
|
+
}
|
|
5068
|
+
fn is_settled(&self) -> bool {
|
|
5069
|
+
self.settled.load(Ordering::SeqCst)
|
|
5070
|
+
}
|
|
5071
|
+
fn settle(&self, ruby: &Ruby, settle: Settle, resolve: Option<Proc>) -> Result<bool, Error> {
|
|
5072
|
+
if self.settled.load(Ordering::SeqCst) || self.core.is_disposed() {
|
|
5073
|
+
return Ok(false);
|
|
5074
|
+
}
|
|
5075
|
+
// (…settled once the op has run, whatever it raised — a terminated evaluation's — as the registry let go of it)
|
|
5076
|
+
self.core.ensure_owner_and_live(ruby)?;
|
|
5077
|
+
let settled = self.core.settle_import(ruby, self.id, settle, resolve);
|
|
5078
|
+
self.settled.store(true, Ordering::SeqCst);
|
|
5079
|
+
settled
|
|
5080
|
+
}
|
|
5081
|
+
// _resolve(module, block): settle it with |module| — linked by |block| where
|
|
5082
|
+
// it is not yet (as Module#instantiate's), and evaluated — the promise then
|
|
5083
|
+
// fulfilled with its namespace, or rejected with what failed.
|
|
5084
|
+
fn resolve(
|
|
5085
|
+
ruby: &Ruby,
|
|
5086
|
+
rb_self: &Self,
|
|
5087
|
+
module: Value,
|
|
5088
|
+
block: Option<Proc>,
|
|
5089
|
+
) -> Result<bool, Error> {
|
|
5090
|
+
let Some(module_id) = module_id_of(ruby, &rb_self.core, module)? else {
|
|
5091
|
+
return Err(Error::new(
|
|
5092
|
+
ruby.exception_arg_error(),
|
|
5093
|
+
"resolve needs a RustyRacer::Module that is not disposed",
|
|
5094
|
+
));
|
|
5095
|
+
};
|
|
5096
|
+
rb_self.settle(ruby, Settle::Module(module_id), block)
|
|
5097
|
+
}
|
|
5098
|
+
// reject(value): rejected with |value|, marshalled into its realm.
|
|
5099
|
+
fn reject(ruby: &Ruby, rb_self: &Self, value: Value) -> Result<bool, Error> {
|
|
5100
|
+
let value = ruby_to_jsval(value)?;
|
|
5101
|
+
rb_self.settle(ruby, Settle::Reject(value), None)
|
|
5102
|
+
}
|
|
5103
|
+
// reject_with(path, *args): rejected with what the function at |path| (as
|
|
5104
|
+
// Context#call names one, in its realm) returns — or throws.
|
|
5105
|
+
fn reject_with(ruby: &Ruby, rb_self: &Self, args: &[Value]) -> Result<bool, Error> {
|
|
5106
|
+
let Some((path, args)) = args.split_first() else {
|
|
5107
|
+
return Err(Error::new(
|
|
5108
|
+
ruby.exception_arg_error(),
|
|
5109
|
+
"reject_with needs a function path",
|
|
5110
|
+
));
|
|
5111
|
+
};
|
|
5112
|
+
let path = String::try_convert(*path)?;
|
|
5113
|
+
let args = js_args(args)?;
|
|
5114
|
+
rb_self.settle(ruby, Settle::RejectWith { path, args }, None)
|
|
5115
|
+
}
|
|
5116
|
+
}
|
|
5117
|
+
|
|
5118
|
+
impl Drop for DynamicImport {
|
|
5119
|
+
fn drop(&mut self) {
|
|
5120
|
+
if !self.settled.swap(true, Ordering::SeqCst) {
|
|
5121
|
+
self.core.release(Released::Import(self.id));
|
|
5122
|
+
}
|
|
5123
|
+
}
|
|
5124
|
+
}
|
|
5125
|
+
|
|
4336
5126
|
#[magnus::init]
|
|
4337
5127
|
fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
4338
5128
|
install_classes(ruby)
|
|
@@ -4346,6 +5136,8 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
|
4346
5136
|
// same surface.
|
|
4347
5137
|
pub fn install_classes(ruby: &Ruby) -> Result<(), Error> {
|
|
4348
5138
|
let module = ruby.define_module("RustyRacer")?;
|
|
5139
|
+
// The argument that crosses into JS as the realm's host object (host_object).
|
|
5140
|
+
module.const_set("HOST_OBJECT", ruby.get_inner(&marshal::HOST_OBJECT))?;
|
|
4349
5141
|
|
|
4350
5142
|
// The isolate (VM) + its isolate-level ops; hands out Contexts.
|
|
4351
5143
|
let isolate = module.define_class("Isolate", ruby.class_object())?;
|
|
@@ -4360,8 +5152,8 @@ pub fn install_classes(ruby: &Ruby) -> Result<(), Error> {
|
|
|
4360
5152
|
)?;
|
|
4361
5153
|
// lib keeps the proc in an ivar (GC liveness) and calls this primitive.
|
|
4362
5154
|
isolate.define_method(
|
|
4363
|
-
"
|
|
4364
|
-
method!(Isolate::
|
|
5155
|
+
"_set_dynamic_import_handler",
|
|
5156
|
+
method!(Isolate::set_dynamic_import_handler, 1),
|
|
4365
5157
|
)?;
|
|
4366
5158
|
isolate.define_method("heap_statistics", method!(Isolate::heap_statistics, 0))?;
|
|
4367
5159
|
isolate.define_method(
|
|
@@ -4385,8 +5177,9 @@ pub fn install_classes(ruby: &Ruby) -> Result<(), Error> {
|
|
|
4385
5177
|
context.define_method("reset", method!(Context::reset, 0))?;
|
|
4386
5178
|
context.define_method("id", method!(Context::id, 0))?;
|
|
4387
5179
|
// keyword-arg wrappers Context#compile_module / #compile (source, ...) in lib.
|
|
4388
|
-
context.define_method("_compile_module", method!(Context::compile_module,
|
|
4389
|
-
context.define_method("_compile", method!(Context::compile,
|
|
5180
|
+
context.define_method("_compile_module", method!(Context::compile_module, 6))?;
|
|
5181
|
+
context.define_method("_compile", method!(Context::compile, 6))?;
|
|
5182
|
+
context.define_method("_synthetic_module", method!(Context::synthetic_module, 4))?;
|
|
4390
5183
|
context.define_method("dispose", method!(Context::dispose, 0))?;
|
|
4391
5184
|
context.define_method("disposed?", method!(Context::disposed, 0))?;
|
|
4392
5185
|
|
|
@@ -4394,6 +5187,7 @@ pub fn install_classes(ruby: &Ruby) -> Result<(), Error> {
|
|
|
4394
5187
|
let script = module.define_class("Script", ruby.class_object())?;
|
|
4395
5188
|
script.define_method("run", method!(Script::run, 0))?;
|
|
4396
5189
|
script.define_method("run_void", method!(Script::run_void, 0))?;
|
|
5190
|
+
script.define_method("script_id", method!(Script::script_id, 0))?;
|
|
4397
5191
|
script.define_method("cached_data", method!(Script::cached_data, 0))?;
|
|
4398
5192
|
script.define_method("cache_rejected?", method!(Script::cache_rejected, 0))?;
|
|
4399
5193
|
script.define_method("create_code_cache", method!(Script::create_code_cache, 0))?;
|
|
@@ -4401,6 +5195,16 @@ pub fn install_classes(ruby: &Ruby) -> Result<(), Error> {
|
|
|
4401
5195
|
script.define_method("disposed?", method!(Script::disposed, 0))?;
|
|
4402
5196
|
|
|
4403
5197
|
// A resolved function: Context#function -> #call / #call_void.
|
|
5198
|
+
let import = module.define_class("DynamicImport", ruby.class_object())?;
|
|
5199
|
+
import.define_method("specifier", method!(DynamicImport::specifier, 0))?;
|
|
5200
|
+
import.define_method("referrer", method!(DynamicImport::referrer, 0))?;
|
|
5201
|
+
import.define_method("attributes", method!(DynamicImport::attributes, 0))?;
|
|
5202
|
+
import.define_method("host_defined", method!(DynamicImport::host_defined, 0))?;
|
|
5203
|
+
import.define_method("context", method!(DynamicImport::context, 0))?;
|
|
5204
|
+
import.define_method("settled?", method!(DynamicImport::is_settled, 0))?;
|
|
5205
|
+
import.define_method("_resolve", method!(DynamicImport::resolve, 2))?;
|
|
5206
|
+
import.define_method("reject", method!(DynamicImport::reject, 1))?;
|
|
5207
|
+
import.define_method("reject_with", method!(DynamicImport::reject_with, -1))?;
|
|
4404
5208
|
let function = module.define_class("Function", ruby.class_object())?;
|
|
4405
5209
|
function.define_method("call", method!(JsFunction::call, -1))?;
|
|
4406
5210
|
function.define_method("call_void", method!(JsFunction::call_void, -1))?;
|
|
@@ -4422,6 +5226,8 @@ pub fn install_classes(ruby: &Ruby) -> Result<(), Error> {
|
|
|
4422
5226
|
jsmodule.define_method("namespace", method!(JsModule::namespace, 0))?;
|
|
4423
5227
|
jsmodule.define_method("_status", method!(JsModule::status, 0))?;
|
|
4424
5228
|
jsmodule.define_method("graph_async?", method!(JsModule::graph_async, 0))?;
|
|
5229
|
+
jsmodule.define_method("requests", method!(JsModule::requests, 0))?;
|
|
5230
|
+
jsmodule.define_method("script_id", method!(JsModule::script_id, 0))?;
|
|
4425
5231
|
jsmodule.define_method("cached_data", method!(JsModule::cached_data, 0))?;
|
|
4426
5232
|
jsmodule.define_method("cache_rejected?", method!(JsModule::cache_rejected, 0))?;
|
|
4427
5233
|
jsmodule.define_method("create_code_cache", method!(JsModule::create_code_cache, 0))?;
|