Skip to content

Commit e9bb684

Browse files
authored
Merge pull request #3 from CppCXY/refactor
Refactor
2 parents 9eaefe6 + 6633207 commit e9bb684

29 files changed

+1328
-1875
lines changed

crates/luars/src/compiler/expr.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1609,21 +1609,21 @@ fn compile_binary_expr_to(
16091609
BinaryOperator::OpConcat => {
16101610
// CONCAT has special instruction format: CONCAT A B
16111611
// Concatenates R[A] through R[A+B] (B+1 values), result in R[A]
1612-
1612+
16131613
// LUA 5.4 OPTIMIZATION: Merge consecutive CONCAT operations
16141614
// When compiling "e1 .. e2", if e2's code just generated a CONCAT instruction,
16151615
// we can merge them into a single CONCAT that concatenates all values at once.
16161616
// This is critical for performance with chains like "a" .. "b" .. "c"
1617-
1617+
16181618
let code = &c.chunk.code;
16191619
if !code.is_empty() {
16201620
let prev_instr = code[code.len() - 1];
16211621
let prev_opcode = Instruction::get_opcode(prev_instr);
1622-
1622+
16231623
if prev_opcode == OpCode::Concat {
16241624
let prev_a = Instruction::get_a(prev_instr);
16251625
let prev_b = Instruction::get_b(prev_instr);
1626-
1626+
16271627
// Check if right_reg is the result of previous CONCAT
16281628
// Previous CONCAT: R[prev_a] = R[prev_a]..R[prev_a+1]..R[prev_a+prev_b]
16291629
// If right_reg == prev_a and left_reg == prev_a - 1, we can merge
@@ -1633,11 +1633,11 @@ fn compile_binary_expr_to(
16331633
let last_idx = code.len() - 1;
16341634
c.chunk.code[last_idx] = Instruction::encode_abc(
16351635
OpCode::Concat,
1636-
left_reg, // Start from left_reg instead
1637-
prev_b + 1, // Increase count by 1
1638-
0
1636+
left_reg, // Start from left_reg instead
1637+
prev_b + 1, // Increase count by 1
1638+
0,
16391639
);
1640-
1640+
16411641
// BUGFIX: Respect dest parameter
16421642
if let Some(d) = dest {
16431643
if d != left_reg {

crates/luars/src/gc.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ impl GC {
139139
allocations_since_minor_gc: 0,
140140
minor_gc_count: 0,
141141
check_counter: 0,
142-
check_interval: 1000, // Run GC every 1000 checks when debt > 0 (reduce overhead)
142+
check_interval: 10000, // Run GC every 10000 checks when debt > 0 (massive overhead reduction)
143143
finalize_queue: Vec::new(), // __gc finalizer queue
144144
collection_count: 0,
145145
stats: GCStats::default(),

crates/luars/src/lib_registry.rs

Lines changed: 14 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Provides a clean way to register Rust functions as Lua libraries
33

44
use crate::lua_value::{CFunction, LuaValue};
5-
use crate::lua_vm::{LuaError, LuaResult, LuaVM};
5+
use crate::lua_vm::{LuaResult, LuaVM};
66
use crate::stdlib;
77

88
/// Type for value initializers - functions that create values when the module loads
@@ -189,7 +189,7 @@ pub fn create_standard_registry() -> LibraryRegistry {
189189
registry.register(stdlib::string::create_string_lib());
190190
registry.register(stdlib::table::create_table_lib());
191191
registry.register(stdlib::math::create_math_lib());
192-
registry.register(stdlib::io::create_io_lib());
192+
// registry.register(stdlib::io::create_io_lib());
193193
registry.register(stdlib::os::create_os_lib());
194194
registry.register(stdlib::utf8::create_utf8_lib());
195195
registry.register(stdlib::coroutine::create_coroutine_lib());
@@ -213,17 +213,18 @@ pub fn get_args(vm: &LuaVM) -> Vec<LuaValue> {
213213
}
214214

215215
/// Helper to get a specific argument
216+
/// 1 based index
216217
#[inline(always)]
217218
pub fn get_arg(vm: &LuaVM, index: usize) -> Option<LuaValue> {
218219
let frame = vm.frames.last().unwrap();
219220
let base_ptr = frame.base_ptr;
220221
let top = frame.top;
221222

222-
// Arguments are 0-indexed from caller's perspective
223-
// But register 0 is the function, so arg 0 is at register 1
224-
// get_arg(0) should return register[base_ptr + 1]
225-
// get_arg(1) should return register[base_ptr + 2]
226-
let reg_offset = index + 1; // +1 to skip the function at register 0
223+
// Arguments use 1-based indexing (Lua convention)
224+
// Register 0 is the function itself
225+
// get_arg(1) returns register[base_ptr + 1] (first argument)
226+
// get_arg(2) returns register[base_ptr + 2] (second argument)
227+
let reg_offset = index;
227228
if reg_offset < top {
228229
let reg_index = base_ptr + reg_offset;
229230
if reg_index < vm.register_stack.len() {
@@ -237,11 +238,13 @@ pub fn get_arg(vm: &LuaVM, index: usize) -> Option<LuaValue> {
237238
}
238239

239240
/// Helper to require an argument
241+
/// 1 based index
240242
#[inline]
241-
pub fn require_arg(vm: &LuaVM, index: usize, func_name: &str) -> LuaResult<LuaValue> {
242-
get_arg(vm, index).ok_or_else(|| {
243-
LuaError::RuntimeError(format!("{}() requires argument {}", func_name, index + 1))
244-
})
243+
pub fn require_arg(vm: &mut LuaVM, index: usize, func_name: &str) -> LuaResult<LuaValue> {
244+
let Some(arg) = get_arg(vm, index) else {
245+
return Err(vm.error(format!("{}() requires argument {}", func_name, index + 1)));
246+
};
247+
Ok(arg)
245248
}
246249

247250
/// Helper to get argument count
@@ -251,19 +254,3 @@ pub fn arg_count(vm: &LuaVM) -> usize {
251254
// Subtract 1 for the function itself
252255
frame.top.saturating_sub(1)
253256
}
254-
255-
/// Helper to get string argument
256-
pub fn get_string(vm: &LuaVM, index: usize, func_name: &str) -> LuaResult<String> {
257-
let arg = require_arg(vm, index, func_name)?;
258-
unsafe {
259-
arg.as_string()
260-
.map(|s| s.as_str().to_string())
261-
.ok_or_else(|| {
262-
LuaError::RuntimeError(format!(
263-
"{}() requires string argument {}",
264-
func_name,
265-
index + 1
266-
))
267-
})
268-
}
269-
}

crates/luars/src/lua_value/lua_table.rs

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
// High-performance Lua table implementation following Lua 5.4 design
22
// - Array part for integer keys [1..n]
33
// - Hash part using open addressing (same as Lua 5.4)
4-
use crate::LuaVM;
5-
use crate::lua_vm::{LuaError, LuaResult};
6-
74
use super::LuaValue;
5+
use crate::LuaVM;
86

97
/// Hash node - mimics Lua 5.4's Node structure
108
/// Contains key+value pair and next index for collision chaining
@@ -61,7 +59,7 @@ impl LuaTable {
6159
} else {
6260
0
6361
};
64-
62+
6563
LuaTable {
6664
array: if array_size > 0 {
6765
Some(Vec::with_capacity(array_size))
@@ -162,7 +160,7 @@ impl LuaTable {
162160
if self.nodes.is_none() {
163161
panic!("insert_node_simple called with uninitialized nodes - this is a bug");
164162
}
165-
163+
166164
let nodes = self.nodes.as_mut().unwrap();
167165
let size = nodes.len();
168166
let mut idx = Self::hash_key(&key, size);
@@ -291,15 +289,15 @@ impl LuaTable {
291289

292290
if key > 0 {
293291
let idx = (key - 1) as usize;
294-
292+
295293
// Initialize array if needed
296294
if self.array.is_none() {
297295
self.array = Some(Vec::new());
298296
}
299-
297+
300298
let array = self.array.as_mut().unwrap();
301299
let array_len = array.len();
302-
300+
303301
// Limit array growth to reasonable size (64K elements)
304302
if idx < array_len {
305303
array[idx] = value;
@@ -410,19 +408,17 @@ impl LuaTable {
410408

411409
/// Insert value at position in array part, shifting elements to the right
412410
/// Position is 0-indexed internally but Lua uses 1-indexed
413-
pub fn insert_array_at(&mut self, pos: usize, value: LuaValue) -> LuaResult<()> {
411+
pub fn insert_array_at(&mut self, pos: usize, value: LuaValue) -> Result<(), String> {
414412
let len = self.len();
415413
if pos > len {
416-
return Err(LuaError::RuntimeError(
417-
"insert position out of bounds".to_string(),
418-
));
414+
return Err("insert position out of bounds".to_string());
419415
}
420416

421417
// Initialize array if needed
422418
if self.array.is_none() {
423419
self.array = Some(Vec::new());
424420
}
425-
421+
426422
let array = self.array.as_mut().unwrap();
427423

428424
// CRITICAL OPTIMIZATION: Fast path for appending at end (no shift needed!)
@@ -439,12 +435,10 @@ impl LuaTable {
439435

440436
/// Remove value at position in array part, shifting elements to the left
441437
/// Position is 0-indexed internally but Lua uses 1-indexed
442-
pub fn remove_array_at(&mut self, pos: usize) -> LuaResult<LuaValue> {
438+
pub fn remove_array_at(&mut self, pos: usize) -> Result<LuaValue, String> {
443439
let len = self.len();
444440
if pos >= len {
445-
return Err(LuaError::RuntimeError(
446-
"remove position out of bounds".to_string(),
447-
));
441+
return Err("remove position out of bounds".to_string());
448442
}
449443

450444
let array = self.array.as_mut().expect("array should exist");

crates/luars/src/lua_value/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ pub use lua_table::LuaTable;
1919
pub use lua_thread::*;
2020
pub use lua_value::{
2121
LuaValue, LuaValueKind, NAN_BASE, TAG_BOOLEAN, TAG_CFUNCTION, TAG_FLOAT, TAG_FUNCTION,
22-
TAG_INTEGER, TAG_NIL, TAG_STRING, TAG_TABLE, TAG_USERDATA, TYPE_MASK,
23-
VALUE_TRUE, VALUE_FALSE, VALUE_NIL,
22+
TAG_INTEGER, TAG_NIL, TAG_STRING, TAG_TABLE, TAG_USERDATA, TYPE_MASK, VALUE_FALSE, VALUE_NIL,
23+
VALUE_TRUE,
2424
};
2525

2626
/// Multi-return values from Lua functions

0 commit comments

Comments
 (0)