Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add finally return support #60

Draft
wants to merge 3 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion crates/starlight/src/bin/sl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ const SNAPSHOT_FILENAME: &str = ".startup-snapshot";
fn main() {
Platform::initialize();
let options = Options::from_args();

let mut deserialized = false;
let mut rt = if Path::new(SNAPSHOT_FILENAME).exists() {
let mut src = std::fs::read(SNAPSHOT_FILENAME);
Expand Down
3 changes: 3 additions & 0 deletions crates/starlight/src/bytecode/opcodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,4 +280,7 @@ pub enum Opcode {
OP_YIELD_STAR,
OP_AWAIT,
OP_NEWGENERATOR,

OP_FAST_CALL,
OP_FAST_RET
}
173 changes: 74 additions & 99 deletions crates/starlight/src/bytecompiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,31 @@ pub struct ByteCompiler {
pub variable_freelist: Vec<u32>,

pub info: Option<Vec<(Range<usize>, FileLocation)>>,

pub in_try_stmt: bool,
pub fast_calls: Vec<Box<dyn FnOnce(&mut ByteCompiler)>>
}

impl ByteCompiler {
pub fn new( rt: RuntimeRef, builtins: bool,code:GcPointer<CodeBlock>,scope: Rc<RefCell<Scope>>)-> Self {
Self {
lci: Vec::new(),
builtins,
variable_freelist: Vec::with_capacity(4),
code,
tail_pos: false,
info: None,
fmap: HashMap::new(),
val_map: HashMap::new(),
name_map: HashMap::new(),
top_level: false,
scope,
rt: rt,
in_try_stmt: false,
fast_calls: Vec::new()
}
}

pub fn get_val(&mut self, vm: &mut Runtime, val: Val) -> u32 {
if let Some(ix) = self.val_map.get(&val) {
return *ix;
Expand Down Expand Up @@ -472,20 +494,7 @@ impl ByteCompiler {
depth: 0,
}));
let mut code = CodeBlock::new(vm, "<anonymous>".intern(), false, rel_path.into());
let mut compiler = ByteCompiler {
lci: Vec::new(),
builtins,
variable_freelist: Vec::with_capacity(4),
code,
tail_pos: false,
info: None,
fmap: HashMap::new(),
val_map: HashMap::new(),
name_map: HashMap::new(),
top_level: false,
scope,
rt: RuntimeRef(&mut *vm),
};
let mut compiler = ByteCompiler::new(RuntimeRef(vm),builtins,code,scope);
let mut p = 0;
for x in params_.iter() {
params.push(x.intern());
Expand Down Expand Up @@ -573,20 +582,7 @@ impl ByteCompiler {
depth: self.scope.borrow().depth + 1,
}));

let mut compiler = ByteCompiler {
lci: Vec::new(),
builtins: self.builtins,
variable_freelist: Vec::with_capacity(4),
code,
info: None,
tail_pos: false,
fmap: HashMap::new(),
val_map: HashMap::new(),
name_map: HashMap::new(),
top_level: false,
scope,
rt: RuntimeRef(&mut *self.rt),
};
let mut compiler = ByteCompiler::new(self.rt,self.builtins,code,scope);
let mut p = 0;
for x in function.params.iter() {
match x.pat {
Expand Down Expand Up @@ -667,24 +663,11 @@ impl ByteCompiler {

let mut code = CodeBlock::new(&mut vm, name, false, path.into());
code.file_name = file.to_string();
let mut compiler = ByteCompiler {
lci: Vec::new(),
top_level: true,
info: None,
tail_pos: false,
builtins: false,
scope: Rc::new(RefCell::new(Scope {
parent: None,
variables: Default::default(),
depth: 0,
})),
variable_freelist: vec![],
code,
val_map: Default::default(),
name_map: Default::default(),
fmap: Default::default(),
rt: RuntimeRef(vm),
};
let mut compiler = ByteCompiler::new(RuntimeRef(vm),false,code,Rc::new(RefCell::new(Scope {
parent: None,
variables: Default::default(),
depth: 0
})));
code.var_count = 1;
code.param_count = 1;
compiler.scope.borrow_mut().add_var("@module".intern(), 0);
Expand Down Expand Up @@ -857,24 +840,13 @@ impl ByteCompiler {
let name = "<script>".intern();
let mut code = CodeBlock::new(&mut vm, name, false, path.into());
code.file_name = fname;
let mut compiler = ByteCompiler {
lci: Vec::new(),
top_level: true,
info: None,
tail_pos: false,
builtins,
scope: Rc::new(RefCell::new(Scope {
let mut compiler = ByteCompiler::new(
RuntimeRef(vm),builtins,code,Rc::new(RefCell::new(Scope {
parent: None,
variables: Default::default(),
depth: 0,
})),
variable_freelist: vec![],
code,
val_map: Default::default(),
name_map: Default::default(),
fmap: Default::default(),
rt: RuntimeRef(vm),
};
}))
);

let is_strict = match p.body.get(0) {
Some(body) => body.is_use_strict(),
Expand Down Expand Up @@ -903,24 +875,11 @@ impl ByteCompiler {
let name = "<script>".intern();
let mut code = CodeBlock::new(&mut vm, name, false, path.into());
code.file_name = fname;
let mut compiler = ByteCompiler {
lci: Vec::new(),
top_level: true,
info: None,
tail_pos: false,
builtins,
scope: Rc::new(RefCell::new(Scope {
parent: None,
variables: Default::default(),
depth: 0,
})),
variable_freelist: vec![],
code,
val_map: Default::default(),
name_map: Default::default(),
fmap: Default::default(),
rt: RuntimeRef(vm),
};
let mut compiler = ByteCompiler::new(RuntimeRef(vm),builtins,code,Rc::new(RefCell::new(Scope {
parent: None,
variables: Default::default(),
depth: 0,
})));

let is_strict = match p.body.get(0) {
Some(body) => body.is_use_strict(),
Expand Down Expand Up @@ -1122,6 +1081,10 @@ impl ByteCompiler {
None => self.emit(Opcode::OP_PUSH_UNDEF, &[], false),
};
self.tail_pos = false;
if self.in_try_stmt {
let fast_call = self.fast_call();
self.fast_calls.push(Box::new(fast_call));
}
self.emit(Opcode::OP_RET, &[], false);
}
Stmt::Break(_) => {
Expand Down Expand Up @@ -1303,7 +1266,8 @@ impl ByteCompiler {
}
Stmt::Try(try_stmt) => {
let try_push = self.try_();


self.in_try_stmt = true;
for stmt in try_stmt.block.stmts.iter() {
self.stmt(stmt)?;
}
Expand Down Expand Up @@ -1337,6 +1301,13 @@ impl ByteCompiler {

jfinally(self);
jcatch_finally(self);
while self.fast_calls.len() >0 {
let call = self.fast_calls.pop();
if let Some(c) = call {
c(self);
}
}
self.in_try_stmt = false;
match try_stmt.finalizer {
Some(ref block) => {
self.push_scope();
Expand All @@ -1349,8 +1320,8 @@ impl ByteCompiler {
}
None => {}
}
self.emit(Opcode::OP_FAST_RET,&[], false);
}

x => {
return Err(JsValue::new(
self.rt.new_syntax_error(format!("NYI: {:?}", x)),
Expand Down Expand Up @@ -1929,24 +1900,11 @@ impl ByteCompiler {
let p = self.code.path.clone();
let mut code = CodeBlock::new(&mut self.rt, name, false, p);
code.file_name = self.code.file_name.clone();
let mut compiler = ByteCompiler {
lci: Vec::new(),
top_level: false,
tail_pos: false,
builtins: self.builtins,
code,
variable_freelist: vec![],
val_map: Default::default(),
name_map: Default::default(),
info: None,
fmap: Default::default(),
rt: RuntimeRef(&mut *self.rt),
scope: Rc::new(RefCell::new(Scope {
parent: Some(self.scope.clone()),
depth: self.scope.borrow().depth + 1,
variables: HashMap::new(),
})),
};
let mut compiler = ByteCompiler::new(self.rt,self.builtins,code, Rc::new(RefCell::new(Scope {
parent: Some(self.scope.clone()),
depth: self.scope.borrow().depth + 1,
variables: HashMap::new(),
})));
code.strict = is_strict;
let mut params = vec![];
let mut rest_at = None;
Expand Down Expand Up @@ -2107,6 +2065,23 @@ impl ByteCompiler {
}
}

pub fn fast_call(&mut self) -> impl FnOnce(&mut Self) {
let p = self.code.code.len();
self.emit(Opcode::OP_FAST_CALL, &[0], false);

move |this: &mut Self| {
// this.emit(Opcode::OP_NOP, &[], false);
let to = this.code.code.len() - (p + 5);
let bytes = (to as u32).to_le_bytes();
this.code.code[p] = Opcode::OP_FAST_CALL as u8;
this.code.code[p + 1] = bytes[0];
this.code.code[p + 2] = bytes[1];
this.code.code[p + 3] = bytes[2];
this.code.code[p + 4] = bytes[3];
//this.code.code[p] = ins as u8;
}
}

pub fn jmp_custom(&mut self, op: Opcode) -> impl FnOnce(&mut Self) {
let p = self.code.code.len();
self.emit(op, &[0], false);
Expand Down
13 changes: 6 additions & 7 deletions crates/starlight/src/gc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::{
serializer::{Serializable, SnapshotSerializer},
},
};
use std::usize;
use std::{any::TypeId, cmp::Ordering, fmt, marker::PhantomData};
use std::{
mem::size_of,
Expand Down Expand Up @@ -639,16 +640,13 @@ impl Heap {
}

fn collect_internal(&mut self) {
fn current_stack_pointer() -> usize {
let mut sp: usize = 0;
sp = &sp as *const usize as usize;
sp
}
// Capture all the registers to scan them conservatively. Note that this also captures
// FPU registers too because JS values is NaN boxed and exist in FPU registers.

// Get stack pointer for scanning thread stack.
self.sp = current_stack_pointer();
let sp : usize = 0;
let sp = &sp as *const usize;
self.sp = sp as usize;
if self.defers > 0 {
return;
}
Expand All @@ -662,7 +660,7 @@ impl Heap {
visitor.add_conservative(thread.bounds.origin as _, sp as usize);
});
self.process_roots(&mut visitor);

if let Some(ref mut pool) = self.threadpool {
crate::gc::pmarking::start(
&visitor.queue,
Expand All @@ -673,6 +671,7 @@ impl Heap {
} else {
self.process_worklist(&mut visitor);
}

self.update_weak_references();
self.reset_weak_references();
let alloc = self.allocated;
Expand Down
3 changes: 3 additions & 0 deletions crates/starlight/src/gc/space_bitmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ impl<const ALIGNMENT: usize> SpaceBitmap<ALIGNMENT> {
let offset = object as isize - self.heap_begin as isize;
let index = Self::offset_to_index(offset as _);
let mask = Self::offset_to_mask(offset as _);
if index >= self.bitmap_size / size_of::<usize>() {
return false;
}
let atomic_entry = unsafe { *self.bitmap_begin.add(index) };
(atomic_entry & mask) != 0
}
Expand Down
18 changes: 17 additions & 1 deletion crates/starlight/src/tracingjit/tracing_interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use crate::{
use crate::{bytecode::*, gc::cell::Tracer};
use profile::{ArithProfile, ByValProfile};
use std::intrinsics::{likely, unlikely};
use std::ptr::null_mut;
use wtf_rs::unwrap_unchecked;

pub enum RecordResult {
Expand Down Expand Up @@ -88,6 +89,7 @@ pub unsafe fn eval(
let stack = &mut rt.stack as *mut Stack;
let stack = &mut *stack;
let gcstack = rt.shadowstack();
let mut last_fast_call_ip = null_mut();
loop {
// if trace is too large we do not want to compile it. Just return to interpreting.
if trace.len() > MAX_TRACE_SIZE {
Expand Down Expand Up @@ -172,7 +174,13 @@ pub unsafe fn eval(

frame.push(JsValue::new(env));
}

Opcode::OP_FAST_CALL => {
rt.heap().collect_if_necessary();
let offset = ip.cast::<i32>().read();
ip = ip.add(4);
last_fast_call_ip = ip;
ip = ip.offset(offset as isize);
}
Opcode::OP_JMP => {
// XXX: we do not need to record jumps?
rt.heap().collect_if_necessary();
Expand Down Expand Up @@ -237,6 +245,14 @@ pub unsafe fn eval(
trace.push((sip, Ir::PushN));
frame.push(JsValue::encode_null_value());
}
Opcode::OP_FAST_RET => {
if last_fast_call_ip.is_null(){
continue;
} else {
ip = last_fast_call_ip;
last_fast_call_ip = null_mut();
}
}
Opcode::OP_RET => {
trace.push((sip, Ir::LeaveFrame));
let mut value = if frame.sp <= frame.limit {
Expand Down
Loading