Skip to content

Commit

Permalink
Merge branch 'main' into source_map_getter
Browse files Browse the repository at this point in the history
  • Loading branch information
bartlomieju committed Jul 12, 2024
2 parents ec8e4f1 + b5218a5 commit 333c579
Show file tree
Hide file tree
Showing 11 changed files with 36 additions and 65 deletions.
5 changes: 2 additions & 3 deletions core/extension_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ use crate::ModuleCodeString;
use crate::OpDecl;
use crate::OpMetricsFactoryFn;
use crate::OpState;
use crate::SourceMapGetter;

/// Contribute to the `OpState` from each extension.
pub fn setup_op_state(op_state: &mut OpState, extensions: &mut [Extension]) {
Expand Down Expand Up @@ -242,7 +241,7 @@ impl<'a> IntoIterator for &'a mut LoadedSources {
fn load(
transpiler: Option<&ExtensionTranspiler>,
source: &ExtensionFileSource,
source_mapper: &mut SourceMapper<Rc<dyn SourceMapGetter>>,
source_mapper: &mut SourceMapper,
load_callback: &mut impl FnMut(&ExtensionFileSource),
) -> Result<ModuleCodeString, AnyError> {
load_callback(source);
Expand All @@ -263,7 +262,7 @@ fn load(
pub fn into_sources(
transpiler: Option<&ExtensionTranspiler>,
extensions: &[Extension],
source_mapper: &mut SourceMapper<Rc<dyn SourceMapGetter>>,
source_mapper: &mut SourceMapper,
mut load_callback: impl FnMut(&ExtensionFileSource),
) -> Result<LoadedSources, AnyError> {
let mut sources = LoadedSources::default();
Expand Down
2 changes: 1 addition & 1 deletion core/fast_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,7 @@ macro_rules! ascii_str {
($str:expr) => {{
const C: $crate::v8::OneByteConst =
$crate::FastStaticString::create_external_onebyte_const($str.as_bytes());
unsafe { std::mem::transmute::<_, $crate::FastStaticString>(&C) }
$crate::FastStaticString::new(&C)
}};
}

Expand Down
5 changes: 4 additions & 1 deletion core/runtime/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,10 @@ pub(crate) fn externalize_sources(
let offset = snapshot_sources.len();
for (index, source) in sources.into_iter().enumerate() {
externals[index + offset] =
FastStaticString::create_external_onebyte_const(std::mem::transmute(
FastStaticString::create_external_onebyte_const(std::mem::transmute::<
&[u8],
&[u8],
>(
source.code.as_bytes(),
));
let ptr = &externals[index + offset] as *const v8::OneByteConst;
Expand Down
5 changes: 0 additions & 5 deletions core/runtime/jsrealm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ use std::hash::BuildHasherDefault;
use std::hash::Hasher;
use std::rc::Rc;
use std::sync::Arc;
use v8::Handle;

pub const CONTEXT_STATE_SLOT_INDEX: i32 = 1;
pub const MODULE_MAP_SLOT_INDEX: i32 = 2;
Expand Down Expand Up @@ -291,10 +290,6 @@ impl JsRealm {
self.0.context()
}

pub(crate) fn context_ptr(&self) -> *mut v8::Context {
unsafe { self.0.context.get_unchecked() as *const _ as _ }
}

/// Executes traditional JavaScript code (traditional = not ES modules) in the
/// realm's context.
///
Expand Down
39 changes: 11 additions & 28 deletions core/runtime/jsruntime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ pub type CompiledWasmModuleStore = CrossIsolateStore<v8::CompiledWasmModule>;
/// Internal state for JsRuntime which is stored in one of v8::Isolate's
/// embedder slots.
pub struct JsRuntimeState {
pub(crate) source_mapper: RefCell<SourceMapper<Rc<dyn SourceMapGetter>>>,
pub(crate) source_mapper: RefCell<SourceMapper>,
pub(crate) op_state: Rc<RefCell<OpState>>,
pub(crate) shared_array_buffer_store: Option<SharedArrayBufferStore>,
pub(crate) compiled_wasm_module_store: Option<CompiledWasmModuleStore>,
Expand Down Expand Up @@ -672,8 +672,7 @@ impl JsRuntime {

// Load the sources and source maps
let mut files_loaded = Vec::with_capacity(128);
let mut source_mapper: SourceMapper<Rc<dyn SourceMapGetter>> =
SourceMapper::new(options.source_map_getter);
let mut source_mapper = SourceMapper::new(options.source_map_getter);
let mut sources = extension_set::into_sources(
options.extension_transpiler.as_deref(),
&extensions,
Expand Down Expand Up @@ -775,9 +774,9 @@ impl JsRuntime {
)));

let external_refs: &v8::ExternalReferences =
isolate_allocations.external_refs.as_ref().unwrap().as_ref();
isolate_allocations.external_refs.as_ref().unwrap();
// SAFETY: We attach external_refs to IsolateAllocations which will live as long as the isolate
let external_refs_static = unsafe { std::mem::transmute(external_refs) };
let external_refs_static = unsafe { &*(external_refs as *const _) };

let has_snapshot = maybe_startup_snapshot.is_some();
let mut isolate = setup::create_isolate(
Expand Down Expand Up @@ -1073,23 +1072,6 @@ impl JsRuntime {
self.inner.main_realm.handle_scope(isolate)
}

#[inline(always)]
/// Create a scope on the stack with the given context
fn with_context_scope<'s, T>(
isolate: *mut v8::Isolate,
context: *mut v8::Context,
f: impl FnOnce(&mut v8::HandleScope<'s>) -> T,
) -> T {
// SAFETY: We know this isolate is valid and non-null at this time
let mut isolate_scope =
v8::HandleScope::new(unsafe { isolate.as_mut().unwrap_unchecked() });
// SAFETY: We know the context is valid and non-null at this time, and that a Local and pointer share the
// same representation
let context = unsafe { std::mem::transmute(context) };
let mut scope = v8::ContextScope::new(&mut isolate_scope, context);
f(&mut scope)
}

/// Create a synthetic module - `ext:core/ops` - that exports all ops registered
/// with the runtime.
fn execute_virtual_ops_module(
Expand Down Expand Up @@ -1731,12 +1713,13 @@ impl JsRuntime {
cx: &mut Context,
poll_options: PollEventLoopOptions,
) -> Poll<Result<(), Error>> {
let isolate = self.v8_isolate_ptr();
Self::with_context_scope(
isolate,
self.inner.main_realm.context_ptr(),
move |scope| self.poll_event_loop_inner(cx, scope, poll_options),
)
// SAFETY: We know this isolate is valid and non-null at this time
let mut isolate_scope =
v8::HandleScope::new(unsafe { &mut *self.v8_isolate_ptr() });
let context =
v8::Local::new(&mut isolate_scope, self.inner.main_realm.context());
let mut scope = v8::ContextScope::new(&mut isolate_scope, context);
self.poll_event_loop_inner(cx, &mut scope, poll_options)
}

fn poll_event_loop_inner(
Expand Down
5 changes: 4 additions & 1 deletion core/runtime/op_driver/erased_future.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,10 @@ impl<const MAX_SIZE: usize, Output> ErasedFuture<MAX_SIZE, Output> {
where
F: Future<Output = Output>,
{
F::poll(std::mem::transmute(pin), cx)
F::poll(
std::mem::transmute::<Pin<&mut TypeErased<MAX_SIZE>>, Pin<&mut F>>(pin),
cx,
)
}

#[allow(dead_code)]
Expand Down
4 changes: 3 additions & 1 deletion core/runtime/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ impl SnapshotStoreDataStore {
// TODO(mmastrac): v8::Global needs From/Into
// SAFETY: Because we've tested that Local<Data>: From<Local<T>>, we can assume this is safe.
unsafe {
self.data.push(std::mem::transmute(global));
self.data.push(
std::mem::transmute::<v8::Global<T>, v8::Global<v8::Data>>(global),
);
}
id as _
}
Expand Down
27 changes: 5 additions & 22 deletions core/source_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,6 @@ pub trait SourceMapGetter {
) -> Option<String>;
}

impl<T> SourceMapGetter for Rc<T>
where
T: SourceMapGetter + ?Sized,
{
fn get_source_map(&self, file_name: &str) -> Option<Vec<u8>> {
(**self).get_source_map(file_name)
}

fn get_source_line(
&self,
file_name: &str,
line_number: usize,
) -> Option<String> {
(**self).get_source_line(file_name, line_number)
}
}

#[derive(Debug)]
pub enum SourceMapApplication {
/// No mapping was applied, the location is unchanged.
Expand All @@ -61,19 +44,19 @@ pub enum SourceMapApplication {

pub type SourceMapData = Cow<'static, [u8]>;

pub struct SourceMapper<G: SourceMapGetter> {
pub struct SourceMapper {
maps: HashMap<String, Option<SourceMap>>,
source_lines: HashMap<(String, i64), Option<String>>,
getter: Option<G>,
getter: Option<Rc<dyn SourceMapGetter>>,
pub(crate) ext_source_maps: HashMap<String, SourceMapData>,
// This is not the right place for this, but it's the easiest way to make
// op_apply_source_map a fast op. This stashing should happen in #[op2].
pub(crate) stashed_file_name: Option<String>,
pub(crate) maybe_module_map: Option<Rc<ModuleMap>>,
}

impl<G: SourceMapGetter> SourceMapper<G> {
pub fn new(getter: Option<G>) -> Self {
impl SourceMapper {
pub fn new(getter: Option<Rc<dyn SourceMapGetter>>) -> Self {
Self {
maps: Default::default(),
source_lines: Default::default(),
Expand All @@ -88,7 +71,7 @@ impl<G: SourceMapGetter> SourceMapper<G> {
assert!(self.maybe_module_map.replace(module_map).is_none());
}

pub fn has_user_sources(&self) -> bool {
pub(crate) fn has_user_sources(&self) -> bool {
self.getter.is_some()
}

Expand Down
3 changes: 2 additions & 1 deletion core/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ impl V8TaskSpawnerFactory {

// SAFETY: we are removing the Send trait as we return the tasks here to prevent
// these tasks from accidentally leaking to another thread.
let tasks = unsafe { std::mem::transmute(tasks) };
let tasks =
unsafe { std::mem::transmute::<Vec<SendTask>, Vec<UnsendTask>>(tasks) };
Poll::Ready(tasks)
}

Expand Down
2 changes: 1 addition & 1 deletion rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[toolchain]
channel = "1.78.0"
channel = "1.79.0"
components = ["rustfmt", "clippy"]
4 changes: 3 additions & 1 deletion serde_v8/magic/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ impl ToV8 for Value<'_> {
_scope: &mut v8::HandleScope<'a>,
) -> Result<v8::Local<'a, v8::Value>, crate::Error> {
// SAFETY: not fully safe, since lifetimes are detached from original scope
Ok(unsafe { transmute(self.v8_value) })
Ok(unsafe {
transmute::<v8::Local<v8::Value>, v8::Local<v8::Value>>(self.v8_value)
})
}
}

Expand Down

0 comments on commit 333c579

Please sign in to comment.