Skip to content

Commit 4de7ada

Browse files
committed
feat: do not add duplicate string constants
This means the string_equality benchmark does not crash rlox anymore (but it crashes clox).
1 parent 7ca9de7 commit 4de7ada

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

lib/compiler/src/compiler.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::{fmt::Display, iter::Peekable, mem::size_of, unreachable};
1+
use std::{fmt::Display, iter::Peekable, mem::size_of, ops::Deref, unreachable};
22

33
use cursor::Line;
44
use gc::{Chunk, Closure, ClosureRef, Function, Heap, Object, ObjectRef, Value};
@@ -1327,7 +1327,10 @@ impl<'a, 'b> Compiler<'a, 'b> {
13271327

13281328
fn add_identifier_constant(&mut self, token: &Token<'a>) -> Result<u8> {
13291329
let name = self.interner.intern(token.lexeme());
1330-
self.add_object_constant(name, token)
1330+
match self.current_chunk().constants().iter().position(|v| v.equals_string(&name)) {
1331+
Some(index) => Ok(index.try_into().unwrap()),
1332+
None => self.add_object_constant(name, token),
1333+
}
13311334
}
13321335

13331336
fn add_object_constant(&mut self, obj: impl Into<Object>, token: &Token<'a>) -> Result<u8> {

lib/gc/src/value.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ mod closure;
1212
pub use closure::*;
1313

1414
mod upvalue;
15-
use strings::string_interner::StringInterner;
15+
use strings::string_interner::{StringInterner, InternedString};
1616
pub use upvalue::*;
1717

1818
mod class;
@@ -66,6 +66,16 @@ impl Value {
6666
}
6767
}
6868

69+
pub fn equals_string(&self, s: &InternedString) -> bool {
70+
match self {
71+
Value::Object(o) => match o.deref() {
72+
Object::String(string) => string == s,
73+
_ => false,
74+
},
75+
_ => false,
76+
}
77+
}
78+
6979
pub fn less_than(&self, other: &Value) -> Option<Value> {
7080
match (self, other) {
7181
(Value::Number(a), Value::Number(b)) => Some(Value::Boolean(a < b)),

0 commit comments

Comments
 (0)