-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathstate.rs
More file actions
1808 lines (1679 loc) · 70.5 KB
/
state.rs
File metadata and controls
1808 lines (1679 loc) · 70.5 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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
array,
borrow::Cow,
collections::{BTreeMap, HashMap},
hash::BuildHasherDefault,
mem, ops,
};
use ahash::AHasher;
use aiscript_arena::{
Collect, Collection, Gc, Mutation,
lock::{GcRefLock, RefLock},
};
use sqlx::{PgPool, SqlitePool};
use crate::{
NativeFn, OpCode, ReturnValue, Value,
ai::{self, AiConfig, PromptConfig},
ast::{ChunkId, Visibility},
builtins::BuiltinMethods,
module::{ModuleKind, ModuleManager, ModuleSource},
object::{
BoundMethod, Class, Closure, EnumVariant, Function, Instance, List, ListKind, Object,
Upvalue, UpvalueObj,
},
string::{InternedString, InternedStringSet},
};
use super::{Context, VmError, fuel::Fuel};
type Table<'gc> = HashMap<InternedString<'gc>, Value<'gc>, BuildHasherDefault<AHasher>>;
const FRAME_MAX_SIZE: usize = 64;
// const STACK_MAX_SIZE: usize = FRAME_MAX_SIZE * (u8::MAX as usize + 1);
#[cfg(not(test))]
const STACK_MAX_SIZE: usize = 4096; // Temporary reduce the stack size due to tokio thread stack size limit
#[cfg(test)]
const STACK_MAX_SIZE: usize = 128;
static NUMBER_OPERATOR_ERROR: &str = "Operands must be numbers.";
macro_rules! binary_op {
($self:expr, $op:tt) => {{
debug_assert!($self.stack_top >= 2, "Stack underflow in binary op");
let b = unsafe { $self.stack.get_unchecked($self.stack_top - 1) }
.as_number()
.map_err(|_| $self.runtime_error(NUMBER_OPERATOR_ERROR.into()))?;
let a = unsafe { $self.stack.get_unchecked($self.stack_top - 2) }
.as_number()
.map_err(|_| $self.runtime_error(NUMBER_OPERATOR_ERROR.into()))?;
$self.stack_top -= 2;
$self.push_stack((a $op b).into());
}};
}
enum CheckArgsResult<'gc> {
Args(Vec<Value<'gc>>),
ValidationError(Value<'gc>),
}
#[derive(Collect)]
#[collect(no_drop)]
struct CallFrame<'gc> {
closure: Gc<'gc, Closure<'gc>>,
// When we return from a function, the VM will
// jump to the ip of the caller’s CallFrame and resume from there.
ip: usize,
// slot_start field points into the VM’s value stack
// at the first slot that this function can use
slot_start: usize,
}
impl<'gc> CallFrame<'gc> {
fn next_opcode(&mut self) -> OpCode {
let byte = self.closure.function[self.ip];
self.ip += 1;
byte
}
fn read_constant(&mut self, byte: u8) -> Value<'gc> {
self.closure.function.read_constant(byte)
}
#[allow(unused)]
fn disassemble(&self) {
self.closure
.function
.disassemble(self.closure.function.name.unwrap().display_lossy());
}
#[allow(unused)]
fn disassemble_instruction(&self, offset: usize) {
self.closure.function.disassemble_instruction(offset);
}
}
pub struct State<'gc> {
pub(super) mc: &'gc Mutation<'gc>,
pub(super) chunks: BTreeMap<ChunkId, Gc<'gc, Function<'gc>>>,
frames: Vec<CallFrame<'gc>>,
frame_count: usize,
stack: [Value<'gc>; STACK_MAX_SIZE],
stack_top: usize,
pub(super) strings: InternedStringSet<'gc>,
pub(super) globals: Table<'gc>,
open_upvalues: Option<GcRefLock<'gc, UpvalueObj<'gc>>>,
pub module_manager: ModuleManager<'gc>,
pub(super) builtin_methods: BuiltinMethods<'gc>,
current_module: Option<InternedString<'gc>>,
pub pg_connection: Option<PgPool>,
pub sqlite_connection: Option<SqlitePool>,
pub redis_connection: Option<redis::aio::MultiplexedConnection>,
pub ai_config: AiConfig,
}
unsafe impl Collect for State<'_> {
fn needs_trace() -> bool
where
Self: Sized,
{
true
}
fn trace(&self, cc: &Collection) {
self.frames.trace(cc);
self.frame_count.trace(cc);
self.stack.trace(cc);
self.stack_top.trace(cc);
self.strings.trace(cc);
self.globals.trace(cc);
self.open_upvalues.trace(cc);
self.module_manager.trace(cc);
self.builtin_methods.trace(cc);
self.current_module.trace(cc);
}
}
impl<'gc> State<'gc> {
pub(super) fn new(mc: &'gc Mutation<'gc>) -> Self {
State {
mc,
chunks: BTreeMap::new(),
frames: Vec::with_capacity(FRAME_MAX_SIZE),
frame_count: 0,
stack: array::from_fn(|_| Value::Nil),
stack_top: 0,
strings: InternedStringSet::new(mc),
globals: HashMap::default(),
open_upvalues: None,
module_manager: ModuleManager::new(),
builtin_methods: BuiltinMethods::new(),
current_module: None,
pg_connection: None,
sqlite_connection: None,
redis_connection: None,
ai_config: AiConfig::default(),
}
}
pub fn get_context(&mut self) -> Context<'gc> {
Context {
mutation: self.mc,
strings: self.strings,
}
}
pub fn import_module(&mut self, path: InternedString<'gc>) -> Result<(), VmError> {
// Get the simple name (last component) from the path
let simple_name = path.to_str().unwrap().split('.').last().unwrap();
let simple_name = self.intern(simple_name.as_bytes());
// Check if simple name is already used
if self.globals.contains_key(&simple_name) {
return Err(VmError::RuntimeError(format!(
"Name '{}' is already in use",
simple_name
)));
}
// Get module source
let module_source = self.module_manager.get_or_load_module(path)?;
match module_source {
ModuleSource::Cached => {
// For any module (std or script), just bind it to its simple name
self.globals.insert(simple_name, Value::Module(path));
Ok(())
}
ModuleSource::New {
source,
path: module_path,
} => {
let prev_module = self.current_module.replace(path);
let prev_globals = mem::take(&mut self.globals);
let module = ModuleKind::Script {
name: path,
exports: HashMap::default(),
globals: HashMap::default(),
path: module_path,
};
self.module_manager.register_script_module(path, module);
let source: &'static str = Box::leak(source.into_boxed_str());
let chunks = crate::compiler::compile(self.get_context(), source)?;
let imported_script_chunk_id = chunks.keys().last().copied().unwrap();
self.chunks.extend(chunks);
let function = self.get_chunk(imported_script_chunk_id)?;
self.eval_function(function, &[])?;
if let Some(ModuleKind::Script { globals, .. }) =
self.module_manager.modules.get_mut(&path)
{
*globals = mem::replace(&mut self.globals, prev_globals);
}
// Add the module to globals with its simple name
self.globals.insert(simple_name, Value::Module(path));
self.current_module = prev_module;
Ok(())
}
}
}
pub fn get_global(&self, name: InternedString<'gc>) -> Option<Value<'gc>> {
// First check if it's a module name
if let Some(module) = self.module_manager.get_module(name) {
return Some(Value::Module(module.name()));
}
// Then check current globals scope
if let Some(value) = self.globals.get(&name).copied() {
return Some(value);
}
// Finally check current module's globals if we're in a module
if let Some(current_module) = self.current_module {
if let Some(ModuleKind::Script { globals, .. }) =
self.module_manager.modules.get(¤t_module)
{
if let Some(value) = globals.get(&name).copied() {
return Some(value);
}
}
}
None
}
pub fn gc_ref<T: Collect>(&mut self, value: T) -> GcRefLock<'gc, T> {
Gc::new(self.mc, RefLock::new(value))
}
pub fn intern(&mut self, s: &[u8]) -> InternedString<'gc> {
self.strings.intern(self.mc, s)
}
pub fn intern_static(&mut self, s: &'static str) -> InternedString<'gc> {
self.strings.intern_static(self.mc, s.as_bytes())
}
pub fn get_chunk(&mut self, chunk_id: ChunkId) -> Result<Gc<'gc, Function<'gc>>, VmError> {
self.chunks.get(&chunk_id).copied().ok_or_else(|| {
VmError::RuntimeError(format!("Failed to find chunk with id {}", chunk_id))
})
}
// Call function with params
pub fn call_function(
&mut self,
function: Gc<'gc, Function<'gc>>,
params: &[Value<'gc>],
) -> Result<(), VmError> {
let closure = Gc::new(self.mc, Closure::new(self.mc, function));
self.push_stack(Value::from(closure));
for param in params {
self.push_stack(*param);
}
self.call(closure, function.arity, 0)
}
}
impl<'gc> State<'gc> {
fn runtime_error(&mut self, message: Cow<'static, str>) -> VmError {
let mut error_message = String::from(message);
for i in (0..self.frame_count).rev() {
let frame = &self.frames[i];
// Break loop if reach the un-initialized callframe.
// Call Vm::eval_function directly will reach this case,
// since it never init the root script.
if frame.ip == 0 {
break;
}
let function = &frame.closure.function;
error_message.push_str(&format!(
"\n[line {}] in ",
function.chunk.line(frame.ip - 1)
));
let name = if let Some(name) = function.name {
name.to_str().unwrap()
} else {
"script"
};
error_message.push_str(name);
error_message.push('\n');
}
VmError::RuntimeError(error_message)
}
fn current_frame(&mut self) -> &mut CallFrame<'gc> {
&mut self.frames[self.frame_count - 1]
}
// Dispatch the next opcode, stop at the given frame count.
// When dispatch in step() function, the stop_at_frame_count is 0.
// When dispatch in eval_function(), the stop_at_frame_count is the frame count before to call eval_function().
// This is used to exit the frame call after the chunks of that function is finished.
pub fn dispatch_next(
&mut self,
stop_at_frame_count: usize,
) -> Result<Option<Value<'gc>>, VmError> {
// Debug stack info
#[cfg(feature = "debug")]
self.print_stack();
let frame = self.current_frame();
// Disassemble instruction for debug
#[cfg(feature = "debug")]
frame.disassemble_instruction(frame.ip);
match frame.next_opcode() {
OpCode::Constant(byte) => {
let constant = frame.read_constant(byte);
self.push_stack(constant);
}
OpCode::Add => match (self.peek(0), self.peek(1)) {
(Value::Number(_), Value::Number(_)) => {
binary_op!(self, +);
}
(Value::String(_), Value::String(_))
| (Value::IoString(_), Value::IoString(_))
| (Value::String(_), Value::IoString(_))
| (Value::IoString(_), Value::String(_)) => {
let b = self.pop_stack().as_string()?;
let a = self.pop_stack().as_string()?;
let s = self.intern(format!("{a}{b}").as_bytes());
self.push_stack(s.into());
}
_ => {
return Err(
self.runtime_error("Operands must be two numbers or two strings.".into())
);
}
},
OpCode::Subtract => {
binary_op!(self, -);
}
OpCode::Multiply => {
binary_op!(self, *);
}
OpCode::Divide => {
binary_op!(self, /);
}
OpCode::Modulo => {
binary_op!(self, %);
}
OpCode::Power => {
let b = self
.pop_stack()
.as_number()
.map_err(|_| self.runtime_error(NUMBER_OPERATOR_ERROR.into()))?;
let a = self
.pop_stack()
.as_number()
.map_err(|_| self.runtime_error(NUMBER_OPERATOR_ERROR.into()))?;
// Use f64's powf method for power operation
self.push_stack(a.powf(b).into());
}
OpCode::Negate => {
let v = self
.pop_stack()
.as_number()
.map_err(|_| self.runtime_error("Operand must be a number.".into()))?;
self.push_stack((-v).into());
}
OpCode::Return => {
let frame_slot_start = frame.slot_start;
let return_value = self.pop_stack();
self.close_upvalues(frame_slot_start);
// Must pop the frame from vec when returning
self.frames.pop();
self.frame_count -= 1;
if self.frame_count == stop_at_frame_count {
self.pop_stack();
return Ok(Some(return_value));
}
self.stack_top = frame_slot_start;
self.push_stack(return_value);
}
OpCode::Nil => self.push_stack(Value::Nil),
OpCode::Bool(b) => self.push_stack(Value::Boolean(b)),
OpCode::Not => {
let v = self.pop_stack().is_falsy();
self.push_stack((v).into())
}
OpCode::Equal => {
let b = self.pop_stack();
let a = self.pop_stack();
self.push_stack(a.equals(&b).into());
}
OpCode::EqualInplace => {
let b = self.peek(0);
let a = self.peek(1);
self.stack[self.stack_top - 1] = a.equals(b).into();
}
OpCode::NotEqual => {
let b = self.pop_stack();
let a = self.pop_stack();
self.push_stack((!a.equals(&b)).into());
}
OpCode::Greater => {
binary_op!(self, >);
}
OpCode::GreaterEqual => {
binary_op!(self, >=);
}
OpCode::Less => {
binary_op!(self, <);
}
OpCode::LessEqual => {
binary_op!(self, <=);
}
OpCode::BuildString(count) => {
let count = count as usize;
if count == 0 {
// Empty string case
let empty = self.intern(b"");
self.push_stack(Value::String(empty));
} else {
// We have 'count' values on the stack to combine
let mut total_len = 0;
let mut string_parts = Vec::with_capacity(count);
// First, convert all values to strings and estimate total length
for i in 0..count {
let value = *self.peek(count - i - 1);
let string_repr = match value {
Value::String(s) => {
let s_str = s.to_str().unwrap_or("");
total_len += s_str.len();
s_str.to_string()
}
Value::IoString(s) => {
total_len += s.len();
s.to_string()
}
Value::Number(n) => {
let s = format!("{}", n);
total_len += s.len();
s
}
Value::Boolean(b) => {
let s = format!("{}", b);
total_len += s.len();
s
}
Value::Nil => {
let s = "nil".to_string();
total_len += s.len();
s
}
Value::List(list) => {
// Format arrays and tuples nicely
let arr = list.borrow();
let s = match arr.kind {
ListKind::Array => {
let elements: Vec<String> =
arr.data.iter().map(|v| format!("{}", v)).collect();
format!("[{}]", elements.join(", "))
}
ListKind::Tuple => {
let elements: Vec<String> =
arr.data.iter().map(|v| format!("{}", v)).collect();
format!("({})", elements.join(", "))
}
};
total_len += s.len();
s
}
Value::Object(obj) => {
let mut result = String::from("{");
let mut first = true;
for (key, value) in &obj.borrow().fields {
if !first {
result.push_str(", ");
}
result.push_str(&format!("{}: {}", key, value));
first = false;
}
result.push('}');
total_len += result.len();
result
}
Value::Instance(instance) => {
let name = instance.borrow().class.borrow().name.to_string();
let s = format!("<instance of {}>", name);
total_len += s.len();
s
}
Value::EnumVariant(variant) => {
let enum_name = variant.enum_.borrow().name.to_string();
let variant_name = variant.name.to_string();
let s = if variant.value.is_nil() {
format!("{}::{}", enum_name, variant_name)
} else {
format!("{}::{}({})", enum_name, variant_name, variant.value)
};
total_len += s.len();
s
}
// Handle other value types with their string representation
_ => {
let s = format!("{}", value);
total_len += s.len();
s
}
};
string_parts.push(string_repr);
}
// Build the final string
let mut result = String::with_capacity(total_len);
for part in string_parts {
result.push_str(&part);
}
// Pop the string parts from the stack
self.stack_top -= count;
// Push the combined string
let interned = self.intern(result.as_bytes());
self.push_stack(Value::String(interned));
}
}
OpCode::Dup => {
let value = *self.peek(0);
self.push_stack(value);
}
OpCode::Pop(count) => {
self.stack_top = self.stack_top.saturating_sub(count as usize);
}
OpCode::DefineGlobal {
name_constant,
visibility,
} => {
let variable_name = frame.read_constant(name_constant).as_string()?;
let value = *self.peek(0);
// Define in global scope with visibility
self.define_global(variable_name, value, visibility);
self.pop_stack(); // Pop the value after defining
}
OpCode::GetGlobal(byte) => {
let variable_name = frame.read_constant(byte).as_string()?;
if let Some(value) = self.get_global(variable_name) {
self.push_stack(value);
} else {
return Err(self
.runtime_error(format!("Undefined variable '{}'.", variable_name).into()));
}
}
OpCode::SetGlobal(byte) => {
let varible_name = frame.read_constant(byte).as_string()?;
#[allow(clippy::map_entry)]
if self.globals.contains_key(&varible_name) {
self.globals.insert(varible_name, *self.peek(0));
} else {
return Err(self
.runtime_error(format!("Undefined variable '{}'.", varible_name).into()));
}
}
OpCode::GetLocal(slot) => {
let value = self.stack[frame.slot_start + slot as usize];
self.push_stack(value);
}
OpCode::SetLocal(slot) => {
let slot_start = frame.slot_start;
self.stack[slot_start + slot as usize] = *self.peek(0);
}
OpCode::JumpIfFalse(offset) => {
let is_falsy = self.peek(0).is_falsy();
// Alwasy jump to the next instruction, do not move this line into if block
if is_falsy {
let frame = self.current_frame();
frame.ip += offset as usize;
}
}
OpCode::JumpPopIfFalse(offset) => {
let is_falsy = self.pop_stack().is_falsy();
// Alwasy jump to the next instruction, do not move this line into if block
if is_falsy {
let frame = self.current_frame();
frame.ip += offset as usize;
}
}
OpCode::JumpIfError(offset) => {
let value = *self.peek(0);
if value.is_error() {
// Jump to error handler
self.current_frame().ip += offset as usize;
}
}
OpCode::Jump(offset) => {
frame.ip += offset as usize;
}
OpCode::Loop(offset) => {
frame.ip -= offset as usize;
}
OpCode::Constructor {
positional_count,
keyword_count,
validate,
} => {
// *2 because each keyword arg has name and value
// Get the actual function from the correct stack position
// Need to peek past all args (both positional and keyword) to get to the function
let arg_slot_count = positional_count + keyword_count * 2;
let callee = *self.peek(arg_slot_count as usize);
self.call_constructor(callee, positional_count, keyword_count, validate)?;
}
OpCode::Call {
positional_count,
keyword_count,
} => {
// *2 because each keyword arg has name and value
// Get the actual function from the correct stack position
// Need to peek past all args (both positional and keyword) to get to the function
let arg_slot_count = positional_count + keyword_count * 2;
let callee = *self.peek(arg_slot_count as usize);
self.call_value(callee, positional_count, keyword_count)?;
}
OpCode::Closure { chunk_id } => {
let function = self.get_chunk(chunk_id)?;
let mut closure = Closure::new(self.mc, function);
closure
.function
.upvalues
.iter()
.enumerate()
.for_each(|(i, upvalue)| {
let frame = self.current_frame();
let Upvalue { is_local, index } = *upvalue;
if is_local {
let slot = frame.slot_start + index;
let upvalue = self.capture_upvalue(slot);
// println!("function {} capture local: {slot}, {:?}", fn_name, upvalue);
closure.upvalues[i] = upvalue;
} else {
// println!(
// "function {} capture upvalue: {index} {:?}",
// fn_name, &frame.closure.upvalues[index]
// );
closure.upvalues[i] = frame.closure.upvalues[index];
}
});
self.push_stack(Value::from(Gc::new(self.mc, closure)));
}
OpCode::GetUpvalue(slot) => {
let slot = slot as usize;
let upvalue = frame.closure.upvalues[slot];
if let Some(closed) = upvalue.borrow().closed {
self.push_stack(closed);
} else {
let location = frame.closure.upvalues[slot].borrow().location;
let upvalue = self.stack[location];
self.push_stack(upvalue);
}
}
OpCode::SetUpvalue(slot) => {
let slot = slot as usize;
let mut upvalue = frame.closure.upvalues[slot].borrow_mut(self.mc);
let stack_position = upvalue.location;
upvalue.location = slot;
let value = *self.peek(slot);
upvalue.closed = Some(value);
// Also update the stack value
self.stack[stack_position] = value;
}
OpCode::CloseUpvalue => {
self.close_upvalues(self.stack_top - 1);
self.pop_stack();
}
OpCode::Enum(constant) => {
let enum_ = frame.read_constant(constant);
if enum_.is_enum() {
self.push_stack(enum_);
} else {
unreachable!();
}
}
OpCode::Class(byte) => {
let name = frame.read_constant(byte).as_string().unwrap();
self.push_stack(Value::from(Gc::new(
self.mc,
RefLock::new(Class::new(name)),
)));
}
OpCode::EnumVariant {
name_constant,
evaluate,
} => {
if evaluate {
match self.pop_stack() {
Value::Enum(enum_) => {
let frame = self.current_frame();
let name = frame.read_constant(name_constant).as_string().unwrap();
if let Some(value) = enum_.borrow().variants.get(&name) {
self.push_stack(*value);
}
}
Value::EnumVariant(variant) => {
self.push_stack(variant.value);
}
_ => {
return Err(self.runtime_error(
"The variable is not an enum variant and is not evaluable. To declare a single-element array, use [element,] syntax instead of [element].".into(),
));
}
}
return Ok(None);
}
let name = frame.read_constant(name_constant).as_string().unwrap();
if let Value::Enum(enum_) = *self.peek(0) {
// Check if it's a variant access
if let Some(value) = enum_.borrow().variants.get(&name) {
self.pop_stack(); // Pop enum
self.push_stack(Value::EnumVariant(Gc::new(
self.mc,
EnumVariant {
enum_,
name,
value: *value,
},
)));
}
}
}
OpCode::GetProperty(byte) => {
let name = frame.read_constant(byte).as_string().unwrap();
match *self.peek(0) {
Value::Enum(enum_) => {
// Check if it's a variant access
if let Some(value) = enum_.borrow().variants.get(&name) {
self.pop_stack(); // Pop enum
self.push_stack(*value);
} else {
return Err(
self.runtime_error(format!("Undefined property '{}'", name).into())
);
}
}
Value::Object(obj) => {
// Pop the target object first
self.pop_stack();
// Default is nil if no key found
let value = obj.borrow().fields.get(&name).copied().unwrap_or_default();
self.push_stack(value);
}
Value::Instance(instance) => {
if let Some(property) = instance.borrow().fields.get(&name) {
self.pop_stack(); // Instance
self.push_stack(*property);
} else {
self.bind_method(instance.borrow().class, name)?;
}
}
Value::Module(module_name) => {
if let Some(value) = self.module_manager.get_export(module_name, name) {
self.pop_stack(); // Pop module
self.push_stack(value);
} else {
return Err(self.runtime_error(
format!(
"Undefined property '{}' in module '{}'",
name, module_name
)
.into(),
));
}
}
_ => {
// Only instances and modules have properties.
return Err(self.runtime_error("Only instances have properties.".into()));
}
}
}
OpCode::SetProperty(byte) => {
let value = *self.peek(0);
match *self.peek(1) {
Value::Instance(instantce) => {
let frame = self.current_frame();
let name = frame.read_constant(byte).as_string().unwrap();
instantce.borrow_mut(self.mc).fields.insert(name, value);
let value = self.pop_stack(); // Value
self.pop_stack(); // Instance
self.push_stack(value);
}
Value::Object(obj) => {
let frame = self.current_frame();
let name = frame.read_constant(byte).as_string().unwrap();
obj.borrow_mut(self.mc).fields.insert(name, value);
let value = self.pop_stack(); // Value
self.pop_stack(); // Object
self.push_stack(value);
}
_ => return Err(self.runtime_error("Only instances have fields.".into())),
}
}
OpCode::Method {
name_constant,
is_static,
} => {
let name = frame.read_constant(name_constant).as_string().unwrap();
self.define_method(name, is_static)?;
}
OpCode::Invoke {
method_constant,
positional_count,
keyword_count,
} => {
let method_name = frame.read_constant(method_constant).as_string().unwrap();
self.invoke(method_name, positional_count, keyword_count)?;
}
OpCode::Inherit => {
if let Value::Class(superclass) = self.peek(1) {
let subclass = self.peek(0).as_class()?;
subclass
.borrow_mut(self.mc)
.methods
.extend(&superclass.borrow().methods);
self.pop_stack(); // Subclass
} else {
return Err(self.runtime_error("Superclass must be a class.".into()));
}
}
OpCode::GetSuper(byte) => {
let name = frame.read_constant(byte).as_string().unwrap();
let superclass = self.pop_stack().as_class()?;
self.bind_method(superclass, name)?
}
OpCode::SuperInvoke {
method_constant,
positional_count,
keyword_count,
} => {
let method_name = frame.read_constant(method_constant).as_string().unwrap();
let superclass = self.pop_stack().as_class()?;
self.invoke_from_class(superclass, method_name, positional_count, keyword_count)?;
}
OpCode::MakeObject(count) => {
let mut object = Object::default();
let count = count as usize;
// Stack has pairs of [key1, value1, key2, value2, ...]
// Process from last to first pair
for _ in (0..count).rev() {
let value = self.pop_stack();
let key = self
.pop_stack()
.as_string()
.map_err(|_| self.runtime_error("Object key must be a string.".into()))?;
object.fields.insert(key, value);
}
let object = Gc::new(self.mc, RefLock::new(object));
self.push_stack(Value::Object(object));
}
OpCode::MakeList {
size_constant,
kind,
} => {
let count = size_constant as usize;
let mut list = List::with_capacity(kind, count);
let elements = self.pop_stack_n(count);
list.data = elements;
let list = Value::List(Gc::new(self.mc, RefLock::new(list)));
self.push_stack(list);
}
OpCode::GetIndex => {
// Stack: [object] [key]
let key = self.pop_stack();
let target = self.pop_stack();
match target {
Value::Object(obj) => {
// Convert key to string
let key = key.as_string().map_err(|_| {
self.runtime_error("Index key must be a string.".into())
})?;
// Get value from object's fields, default is nil if not key found.
let value = obj.borrow().fields.get(&key).copied().unwrap_or_default();
self.push_stack(value);
}
Value::List(list) => {
let index = key.as_number().map_err(|_| {
self.runtime_error("Array index must be a number.".into())
})?;
let vec = &list.borrow().data;
let value = vec.get(index as usize).copied().unwrap_or(Value::Nil);
self.push_stack(value);
}
Value::Instance(_) => {
return Err(self.runtime_error(
"Use dot notation for accessing instance properties.".into(),
));
}
_ => {
return Err(
self.runtime_error("Only object and array support indexing.".into())
);
}
}
}
OpCode::SetIndex => {
// Stack: [object] [key] [value]
let value = self.pop_stack();
let index = self.pop_stack();
let target = self.pop_stack();
match target {
Value::Object(obj) => {
// Pop remaining operands now that we know they're valid
// Set the field
let key = index.as_string().unwrap();
obj.borrow_mut(self.mc).fields.insert(key, value);
// Push value back for assignment expressions
self.push_stack(value);
}
Value::List(list) => {
// TODO: don't support tuple set index
let index = index.as_number().unwrap();
let index = index as usize;
let vec = &mut list.borrow_mut(self.mc).data;
// Grow array if needed
if index >= vec.len() {
vec.resize(index + 1, Value::Nil);
}
vec[index] = value;
self.push_stack(value);
}
Value::Instance(_) => {
return Err(self.runtime_error(
"Use dot notation for accessing instance properties.".into(),
));
}
_ => {
return Err(
self.runtime_error("Only object and array support indexing.".into())
);
}
}
}
OpCode::In => {
let target = self.pop_stack();
let value = self.pop_stack();
let result = match target {
Value::List(list) => {
let vec = &list.borrow().data;
vec.contains(&value)
}
Value::Object(obj) => {
let key = value.as_string().map_err(|_| {
self.runtime_error(
"Object key must be a string in 'in' operator.".into(),
)
})?;
obj.borrow().fields.contains_key(&key)
}
_ => {
return Err(self.runtime_error(
"Right operand of 'in' operator must be array or object.".into(),
));
}
};
self.push_stack(Value::Boolean(result));
}
OpCode::EnvLookup => {