Skip to content

Commit

Permalink
js: Track declarations/literals in compiler
Browse files Browse the repository at this point in the history
  • Loading branch information
simonwuelker committed Aug 13, 2024
1 parent d8807fa commit 39531c9
Show file tree
Hide file tree
Showing 3 changed files with 200 additions and 63 deletions.
39 changes: 39 additions & 0 deletions crates/js/src/compiler/constant_store.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use crate::Value;

/// Contains all literals referenced inside the compiled code
///
/// Literals are automatically deduplicated, meaning
/// ```
/// let x = 1;
/// let y = 1;
/// ```
/// still only stores `1` once.
#[derive(Clone, Debug, Default)]
pub struct ConstantStore {
values: Vec<Value>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ConstantHandle(usize);

impl ConstantStore {
#[must_use]
pub fn get_or_insert_constant(&mut self, constant: Value) -> ConstantHandle {
let index = self
.values
.iter()
.position(|v| v == &constant)
.unwrap_or_else(|| {
let index = self.values.len();
self.values.push(constant);
index
});

ConstantHandle(index)
}

#[must_use]
pub fn get_constant(&self, handle: ConstantHandle) -> &Value {
&self.values[handle.0]
}
}
24 changes: 19 additions & 5 deletions crates/js/src/compiler/declarative_environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,22 @@ impl Default for DeclarativeEnvironment {
}
}

#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Binding {
/// How many environment record "jumps" have to be performend
/// to get to the environment that defines this binding
environment_index: usize,
pub environment_index: usize,

/// The index of the binding within the environment
index: usize,
pub index: usize,
}

impl DeclarativeEnvironment {
#[must_use]
pub fn len(&self) -> usize {
self.bindings.borrow().len()
}

#[must_use]
pub fn locate_binding(&self, identifier: &str) -> Option<Binding> {
self.locate_binding_inner(identifier, 0)
Expand All @@ -49,9 +54,18 @@ impl DeclarativeEnvironment {
}
}

pub fn insert_binding(&self, identifier: &str) {
/// Insert a new binding and return whether a previous
/// binding existed for this identifier.
pub fn insert_binding(&self, identifier: &str) -> (Binding, bool) {
let mut bindings = self.bindings.borrow_mut();
let index = bindings.len();
bindings.insert(identifier.to_string(), index);
let had_previous_binding = bindings.insert(identifier.to_string(), index).is_some();

let binding = Binding {
environment_index: 0,
index,
};

(binding, had_previous_binding)
}
}
Loading

0 comments on commit 39531c9

Please sign in to comment.