-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathexecutable.rs
More file actions
500 lines (443 loc) · 15.1 KB
/
executable.rs
File metadata and controls
500 lines (443 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use crate::{
ecmascript::{
Agent, CompileFunctionBodyData, ObjectShape, PropertyKey, PropertyLookupCache, Script,
SourceCode, SourceTextModule, String, Value,
},
engine::{
Bindable, NoGcScope, Scoped, bindable_handle,
bytecode::{CompileContext, NamedEvaluationParameter, instructions::Instr},
},
heap::{
ArenaAccess, CompactionLists, CreateHeapData, Heap, HeapMarkAndSweep, WorkQueues,
arena_vec_access, {BaseIndex, HeapIndexHandle, index_handle},
},
};
use oxc_ast::ast;
use super::bytecode_compiler::GeneratorKind;
#[derive(Debug)]
/// A `Send` and `Sync` wrapper over a `&'static T` where `T` might not itself
/// be `Sync`. This is safe because the reference can only be obtained from the
/// same thread in which the `SendableRef` was created.
pub(crate) struct SendableRef<T: ?Sized + 'static> {
reference: &'static T,
thread_id: std::thread::ThreadId,
}
impl<T: ?Sized + 'static> Clone for SendableRef<T> {
fn clone(&self) -> Self {
Self {
reference: self.reference,
thread_id: self.thread_id,
}
}
}
impl<T: ?Sized> SendableRef<T> {
/// Creates a new [`SendableRef`] from a reference with a static lifetime.
pub(crate) fn new(reference: &'static T) -> Self {
Self {
reference,
thread_id: std::thread::current().id(),
}
}
pub(crate) fn get(&self) -> &'static T {
assert_eq!(std::thread::current().id(), self.thread_id);
self.reference
}
}
// SAFETY: The reference will only be dereferenced in a thread in which the
// reference is valid, so it's fine to send or use this type from other threads.
unsafe impl<T: ?Sized> Send for SendableRef<T> {}
unsafe impl<T: ?Sized> Sync for SendableRef<T> {}
#[derive(Debug, Clone)]
pub(crate) struct FunctionExpression<'a> {
pub(crate) expression: SendableRef<ast::Function<'static>>,
pub(crate) identifier: Option<NamedEvaluationParameter>,
/// Optionally eagerly compile the FunctionExpression into bytecode.
pub(crate) compiled_bytecode: Option<Executable<'a>>,
}
bindable_handle!(FunctionExpression);
impl HeapMarkAndSweep for FunctionExpression<'static> {
fn mark_values(&self, queues: &mut WorkQueues) {
let Self {
expression: _,
identifier: _,
compiled_bytecode,
} = self;
compiled_bytecode.mark_values(queues);
}
fn sweep_values(&mut self, compactions: &CompactionLists) {
let Self {
expression: _,
identifier: _,
compiled_bytecode,
} = self;
compiled_bytecode.sweep_values(compactions);
}
}
#[derive(Debug, Clone)]
pub(crate) struct ArrowFunctionExpression {
pub(crate) expression: SendableRef<ast::ArrowFunctionExpression<'static>>,
pub(crate) identifier: Option<NamedEvaluationParameter>,
}
/// Reference to a heap-allocated executable VM bytecode.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub(crate) struct Executable<'a>(BaseIndex<'a, ExecutableHeapData<'static>>);
index_handle!(Executable);
arena_vec_access!(Executable, 'a, ExecutableHeapData, executables);
impl core::fmt::Debug for Executable<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Executable({:?})", self.get_index())
}
}
#[expect(dead_code)]
const EXECUTABLE_OPTION_SIZE_IS_U32: () =
assert!(size_of::<Executable<'_>>() == size_of::<Option<Executable<'_>>>());
/// ## Notes
///
/// - This is inspired by and/or copied from Kiesel engine:
/// Copyright (c) 2023-2024 Linus Groh
#[derive(Debug, Clone)]
pub(crate) struct ExecutableHeapData<'a> {
pub(crate) instructions: Box<[u8]>,
pub(crate) caches: Box<[PropertyLookupCache<'a>]>,
pub(crate) constants: Box<[Value<'a>]>,
pub(crate) shapes: Box<[ObjectShape<'a>]>,
pub(crate) function_expressions: Box<[FunctionExpression<'a>]>,
pub(crate) arrow_function_expressions: Box<[ArrowFunctionExpression]>,
pub(crate) class_initializer_bytecodes: Box<[(Option<Executable<'a>>, bool)]>,
}
impl<'gc> Executable<'gc> {
pub(crate) fn compile_script(
agent: &mut Agent,
script: Script,
gc: NoGcScope<'gc, '_>,
) -> Self {
if agent.options.print_internals {
eprintln!();
eprintln!("=== Compiling Script ===");
eprintln!();
}
let source_code = script.get_source_code(agent, gc);
let body = script.get_statements(agent, gc);
let mut ctx = CompileContext::new(agent, source_code, gc);
ctx.compile_statements(body);
ctx.do_implicit_return();
ctx.finish()
}
pub(crate) fn compile_module(
agent: &mut Agent,
module: SourceTextModule,
gc: NoGcScope<'gc, '_>,
) -> Self {
if agent.options.print_internals {
eprintln!();
eprintln!("=== Compiling Module ===");
eprintln!();
}
let source_code = module.get_source_code(agent, gc);
let body = module.get_statements(agent, gc);
let mut ctx = CompileContext::new(agent, source_code, gc);
ctx.compile_statements(body);
ctx.do_implicit_return();
ctx.finish()
}
pub(crate) fn compile_function_body(
agent: &mut Agent,
data: CompileFunctionBodyData<'gc>,
gc: NoGcScope<'gc, '_>,
) -> Self {
let mut ctx = CompileContext::new(agent, data.source_code, gc);
if data.ast.is_generator() {
ctx.set_generator_kind(if data.ast.is_async() {
GeneratorKind::Async
} else {
GeneratorKind::Sync
});
}
let is_concise = data.ast.is_concise_body();
ctx.compile_function_body(data);
if is_concise {
ctx.do_implicit_return();
}
ctx.finish()
}
pub(crate) fn compile_eval_body(
agent: &mut Agent,
body: &[ast::Statement],
source_code: SourceCode<'gc>,
gc: NoGcScope<'gc, '_>,
) -> Self {
if agent.options.print_internals {
eprintln!();
eprintln!("=== Compiling Eval Body ===");
eprintln!();
}
let mut ctx = CompileContext::new(agent, source_code, gc);
ctx.compile_statements(body);
ctx.do_implicit_return();
ctx.finish()
}
/// Drops the Executable's heap-allocated data if possible.
///
/// ## Safety
///
/// Any attempt to use the Executable after this call will lead to a crash
/// if the drop was performed.
pub(crate) unsafe fn try_drop(self, agent: &mut Agent) {
debug_assert!(!agent.heap.executables.is_empty());
let index = self.get_index();
let last_index = agent.heap.executables.len() - 1;
if last_index == index {
// This bytecode was the last-allocated bytecode, and we can drop
// it from the Heap without affecting any other indexes. The caller
// guarantees that the Executable will not be used anymore.
agent.heap.alloc_counter = agent
.heap
.alloc_counter
.saturating_sub(core::mem::size_of::<ExecutableHeapData>());
let _ = agent.heap.executables.pop().unwrap();
}
}
/// SAFETY: The returned reference is valid until the Executable is garbage
/// collected.
#[inline]
fn get_instructions(self, agent: &Agent) -> &'static [u8] {
// SAFETY: As long as we're alive the instructions Box lives, and it is
// never accessed mutably.
unsafe { core::mem::transmute(&self.get(agent).instructions[..]) }
}
#[inline]
fn get_instruction<'a>(self, agent: &'a Agent, ip: &mut usize) -> Option<Instr<'a>> {
Instr::consume_instruction(&self.unbind().get(agent).instructions, ip)
}
#[inline]
fn get_constants<'a>(self, agent: &'a Agent, _: NoGcScope<'gc, '_>) -> &'a [Value<'gc>] {
&self.get(agent).constants[..]
}
#[inline]
fn fetch_cache(
self,
agent: &Agent,
index: usize,
gc: NoGcScope<'gc, '_>,
) -> PropertyLookupCache<'gc> {
self.get(agent).caches[index].bind(gc)
}
#[inline]
fn fetch_constant(self, agent: &Agent, index: usize, gc: NoGcScope<'gc, '_>) -> Value<'gc> {
self.get(agent).constants[index].bind(gc)
}
#[inline]
fn fetch_identifier(self, agent: &Agent, index: usize, gc: NoGcScope<'gc, '_>) -> String<'gc> {
let value = self.get(agent).constants[index];
let Ok(value) = String::try_from(value) else {
handle_identifier_failure()
};
value.bind(gc)
}
#[inline]
fn fetch_property_key(
self,
agent: &Agent,
index: usize,
gc: NoGcScope<'gc, '_>,
) -> PropertyKey<'gc> {
let value = self.get(agent).constants[index];
// SAFETY: caller wants a PropertyKey.
unsafe { PropertyKey::from_value_unchecked(value).bind(gc) }
}
fn fetch_function_expression<'a>(
self,
agent: &'a Agent,
index: usize,
_: NoGcScope<'gc, '_>,
) -> &'a FunctionExpression<'gc> {
&self.get(agent).function_expressions[index]
}
fn fetch_arrow_function_expression<'a>(
self,
agent: &'a Agent,
index: usize,
) -> &'a ArrowFunctionExpression
where
'gc: 'a,
{
&self.get(agent).arrow_function_expressions[index]
}
fn fetch_class_initializer_bytecode(
self,
agent: &Agent,
index: usize,
_: NoGcScope<'gc, '_>,
) -> (Option<Executable<'gc>>, bool) {
self.get(agent).class_initializer_bytecodes[index]
}
fn fetch_object_shape(
self,
agent: &Agent,
index: usize,
gc: NoGcScope<'gc, '_>,
) -> ObjectShape<'gc> {
self.get(agent).shapes[index].bind(gc)
}
}
impl Scoped<'_, Executable<'static>> {
#[inline]
pub(super) fn get_instructions(&self, agent: &Agent) -> &[u8] {
// SAFETY: Executable is scoped, the instructions reference is bound to
// the Scoped.
self.get(agent).get_instructions(agent)
}
#[inline]
pub(super) fn get_instruction<'a>(
&'a self,
agent: &Agent,
ip: &mut usize,
) -> Option<Instr<'a>> {
// SAFETY: Instructions are owned by Agent but Agent does not touch the
// buffer except during dropping. Dropping only happens during GC, and
// GC can only drop the executable if Scoped<Executable> no longer
// exists. Therefore, binding the lifetime to &self is valid.
unsafe { core::mem::transmute(self.get(agent).get_instruction(agent, ip)) }
}
#[inline]
pub(super) fn get_constants<'a, 'gc>(
&self,
agent: &'a Agent,
gc: NoGcScope<'gc, '_>,
) -> &'a [Value<'gc>] {
self.get(agent).get_constants(agent, gc)
}
#[inline]
pub(super) fn fetch_cache<'gc>(
&self,
agent: &Agent,
index: usize,
gc: NoGcScope<'gc, '_>,
) -> PropertyLookupCache<'gc> {
self.get(agent).fetch_cache(agent, index, gc)
}
#[inline]
pub(super) fn fetch_identifier<'gc>(
&self,
agent: &Agent,
index: usize,
gc: NoGcScope<'gc, '_>,
) -> String<'gc> {
self.get(agent).fetch_identifier(agent, index, gc)
}
#[inline]
pub(super) fn fetch_property_key<'gc>(
&self,
agent: &Agent,
index: usize,
gc: NoGcScope<'gc, '_>,
) -> PropertyKey<'gc> {
self.get(agent).fetch_property_key(agent, index, gc)
}
#[inline]
pub(super) fn fetch_constant<'gc>(
&self,
agent: &Agent,
index: usize,
gc: NoGcScope<'gc, '_>,
) -> Value<'gc> {
self.get(agent).fetch_constant(agent, index, gc)
}
#[inline]
pub(super) fn fetch_function_expression<'a, 'gc>(
&self,
agent: &'a Agent,
index: usize,
gc: NoGcScope<'gc, '_>,
) -> &'a FunctionExpression<'gc> {
self.get(agent).fetch_function_expression(agent, index, gc)
}
#[inline]
pub(super) fn fetch_arrow_function_expression<'a>(
&self,
agent: &'a Agent,
index: usize,
) -> &'a ArrowFunctionExpression {
self.get(agent)
.fetch_arrow_function_expression(agent, index)
}
#[inline]
pub(super) fn fetch_class_initializer_bytecode<'gc>(
&self,
agent: &Agent,
index: usize,
gc: NoGcScope<'gc, '_>,
) -> (Option<Executable<'gc>>, bool) {
self.get(agent)
.fetch_class_initializer_bytecode(agent, index, gc)
}
#[inline]
pub(super) fn fetch_object_shape<'gc>(
&self,
agent: &Agent,
index: usize,
gc: NoGcScope<'gc, '_>,
) -> ObjectShape<'gc> {
self.get(agent).fetch_object_shape(agent, index, gc)
}
}
impl<'a> CreateHeapData<ExecutableHeapData<'a>, Executable<'a>> for Heap {
fn create(&mut self, data: ExecutableHeapData<'a>) -> Executable<'a> {
let index = u32::try_from(self.executables.len()).expect("Executables overflowed");
self.executables.push(data.unbind());
self.alloc_counter += core::mem::size_of::<ExecutableHeapData<'static>>();
// SAFETY: After pushing to executables, the vector cannot be empty.
Executable(BaseIndex::from_index_u32(index))
}
}
bindable_handle!(ExecutableHeapData);
impl HeapMarkAndSweep for Executable<'static> {
fn mark_values(&self, queues: &mut WorkQueues) {
queues.executables.push(*self);
}
fn sweep_values(&mut self, compactions: &CompactionLists) {
compactions.executables.shift_index(&mut self.0);
}
}
impl HeapMarkAndSweep for ExecutableHeapData<'static> {
fn mark_values(&self, queues: &mut WorkQueues) {
let Self {
instructions: _,
caches,
constants,
shapes,
function_expressions,
arrow_function_expressions: _,
class_initializer_bytecodes,
} = self;
constants.mark_values(queues);
caches.mark_values(queues);
shapes.mark_values(queues);
function_expressions.mark_values(queues);
class_initializer_bytecodes.mark_values(queues);
}
fn sweep_values(&mut self, compactions: &CompactionLists) {
let Self {
instructions: _,
caches,
constants,
shapes,
function_expressions,
arrow_function_expressions: _,
class_initializer_bytecodes,
} = self;
constants.sweep_values(compactions);
caches.sweep_values(compactions);
shapes.sweep_values(compactions);
function_expressions.sweep_values(compactions);
class_initializer_bytecodes.sweep_values(compactions);
}
}
#[cold]
fn handle_identifier_failure() -> ! {
panic!("Invalid identifier index: Value was not a String")
}