1#[allow(unused_imports)]
23use crate::prelude::*;
24use crate::state::LuaState;
25use lua_types::opcode::Instruction;
26use lua_types::tagmethod::TagMethod;
27use lua_types::{CallInfoIdx, GcRef, LuaError, LuaString, LuaValue, StackIdx};
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
55#[allow(non_camel_case_types)]
56#[repr(u8)]
57pub enum OpCode {
58 Move = 0,
59 LoadI = 1,
60 LoadF = 2,
61 LoadK = 3,
62 LoadKX = 4,
63 LoadFalse = 5,
64 LFalseSkip = 6,
65 LoadTrue = 7,
66 LoadNil = 8,
67 GetUpVal = 9,
68 SetUpVal = 10,
69 GetTabUp = 11,
70 GetTable = 12,
71 GetI = 13,
72 GetField = 14,
73 SetTabUp = 15,
74 SetTable = 16,
75 SetI = 17,
76 SetField = 18,
77 NewTable = 19,
78 Self_ = 20,
79 AddI = 21,
80 AddK = 22,
81 SubK = 23,
82 MulK = 24,
83 ModK = 25,
84 PowK = 26,
85 DivK = 27,
86 IDivK = 28,
87 BAndK = 29,
88 BOrK = 30,
89 BXOrK = 31,
90 ShrI = 32,
91 ShlI = 33,
92 Add = 34,
93 Sub = 35,
94 Mul = 36,
95 Mod = 37,
96 Pow = 38,
97 Div = 39,
98 IDiv = 40,
99 BAnd = 41,
100 BOr = 42,
101 BXOr = 43,
102 Shl = 44,
103 Shr = 45,
104 MmBin = 46,
105 MmBinI = 47,
106 MmBinK = 48,
107 Unm = 49,
108 BNot = 50,
109 Not = 51,
110 Len = 52,
111 Concat = 53,
112 Close = 54,
113 Tbc = 55,
114 Jmp = 56,
115 Eq = 57,
116 Lt = 58,
117 Le = 59,
118 EqK = 60,
119 EqI = 61,
120 LtI = 62,
121 LeI = 63,
122 GtI = 64,
123 GeI = 65,
124 Test = 66,
125 TestSet = 67,
126 Call = 68,
127 TailCall = 69,
128 Return = 70,
129 Return0 = 71,
130 Return1 = 72,
131 ForLoop = 73,
132 ForPrep = 74,
133 TForPrep = 75,
134 TForCall = 76,
135 TForLoop = 77,
136 SetList = 78,
137 Closure = 79,
138 VarArg = 80,
139 VarArgPrep = 81,
140 ExtraArg = 82,
141 ErrNNil = 83,
148 VarArgPack = 84,
156 GetVArg = 85,
159}
160
161#[allow(dead_code)]
165const NUM_OPCODES: u8 = 86;
166
167impl OpCode {
168 #[allow(non_upper_case_globals)]
175 pub const LoadKx: OpCode = OpCode::LoadKX;
176
177 #[allow(non_upper_case_globals)]
179 pub const GetUpval: OpCode = OpCode::GetUpVal;
180
181 pub fn from_u32(v: u32) -> Option<Self> {
185 match v {
186 0 => Some(Self::Move),
187 1 => Some(Self::LoadI),
188 2 => Some(Self::LoadF),
189 3 => Some(Self::LoadK),
190 4 => Some(Self::LoadKX),
191 5 => Some(Self::LoadFalse),
192 6 => Some(Self::LFalseSkip),
193 7 => Some(Self::LoadTrue),
194 8 => Some(Self::LoadNil),
195 9 => Some(Self::GetUpVal),
196 10 => Some(Self::SetUpVal),
197 11 => Some(Self::GetTabUp),
198 12 => Some(Self::GetTable),
199 13 => Some(Self::GetI),
200 14 => Some(Self::GetField),
201 15 => Some(Self::SetTabUp),
202 16 => Some(Self::SetTable),
203 17 => Some(Self::SetI),
204 18 => Some(Self::SetField),
205 19 => Some(Self::NewTable),
206 20 => Some(Self::Self_),
207 21 => Some(Self::AddI),
208 22 => Some(Self::AddK),
209 23 => Some(Self::SubK),
210 24 => Some(Self::MulK),
211 25 => Some(Self::ModK),
212 26 => Some(Self::PowK),
213 27 => Some(Self::DivK),
214 28 => Some(Self::IDivK),
215 29 => Some(Self::BAndK),
216 30 => Some(Self::BOrK),
217 31 => Some(Self::BXOrK),
218 32 => Some(Self::ShrI),
219 33 => Some(Self::ShlI),
220 34 => Some(Self::Add),
221 35 => Some(Self::Sub),
222 36 => Some(Self::Mul),
223 37 => Some(Self::Mod),
224 38 => Some(Self::Pow),
225 39 => Some(Self::Div),
226 40 => Some(Self::IDiv),
227 41 => Some(Self::BAnd),
228 42 => Some(Self::BOr),
229 43 => Some(Self::BXOr),
230 44 => Some(Self::Shl),
231 45 => Some(Self::Shr),
232 46 => Some(Self::MmBin),
233 47 => Some(Self::MmBinI),
234 48 => Some(Self::MmBinK),
235 49 => Some(Self::Unm),
236 50 => Some(Self::BNot),
237 51 => Some(Self::Not),
238 52 => Some(Self::Len),
239 53 => Some(Self::Concat),
240 54 => Some(Self::Close),
241 55 => Some(Self::Tbc),
242 56 => Some(Self::Jmp),
243 57 => Some(Self::Eq),
244 58 => Some(Self::Lt),
245 59 => Some(Self::Le),
246 60 => Some(Self::EqK),
247 61 => Some(Self::EqI),
248 62 => Some(Self::LtI),
249 63 => Some(Self::LeI),
250 64 => Some(Self::GtI),
251 65 => Some(Self::GeI),
252 66 => Some(Self::Test),
253 67 => Some(Self::TestSet),
254 68 => Some(Self::Call),
255 69 => Some(Self::TailCall),
256 70 => Some(Self::Return),
257 71 => Some(Self::Return0),
258 72 => Some(Self::Return1),
259 73 => Some(Self::ForLoop),
260 74 => Some(Self::ForPrep),
261 75 => Some(Self::TForPrep),
262 76 => Some(Self::TForCall),
263 77 => Some(Self::TForLoop),
264 78 => Some(Self::SetList),
265 79 => Some(Self::Closure),
266 80 => Some(Self::VarArg),
267 81 => Some(Self::VarArgPrep),
268 82 => Some(Self::ExtraArg),
269 83 => Some(Self::ErrNNil),
270 84 => Some(Self::VarArgPack),
271 85 => Some(Self::GetVArg),
272 _ => None,
273 }
274 }
275}
276
277pub trait InstructionExt {
280 fn opcode(&self) -> OpCode;
281 fn arg_a(&self) -> i32;
282 fn arg_b(&self) -> i32;
283 fn arg_c(&self) -> i32;
284 fn arg_k(&self) -> i32;
285 fn arg_ax(&self) -> i32;
286 fn arg_bx(&self) -> i32;
287 fn arg_s_b(&self) -> i32;
288 fn arg_s_c(&self) -> i32;
289 fn arg_s_j(&self) -> i32;
290 fn arg_s_bx(&self) -> i32;
291 fn test_k(&self) -> bool;
292 fn test_a_mode(&self) -> bool;
293 fn is_mm_mode(&self) -> bool;
294 fn is_vararg_prep(&self) -> bool;
295 fn is_in_top(&self) -> bool;
296}
297
298impl InstructionExt for Instruction {
299 #[inline(always)]
307 fn opcode(&self) -> OpCode {
308 match (self.raw() & 0x7F) as u8 {
309 0 => OpCode::Move,
310 1 => OpCode::LoadI,
311 2 => OpCode::LoadF,
312 3 => OpCode::LoadK,
313 4 => OpCode::LoadKX,
314 5 => OpCode::LoadFalse,
315 6 => OpCode::LFalseSkip,
316 7 => OpCode::LoadTrue,
317 8 => OpCode::LoadNil,
318 9 => OpCode::GetUpVal,
319 10 => OpCode::SetUpVal,
320 11 => OpCode::GetTabUp,
321 12 => OpCode::GetTable,
322 13 => OpCode::GetI,
323 14 => OpCode::GetField,
324 15 => OpCode::SetTabUp,
325 16 => OpCode::SetTable,
326 17 => OpCode::SetI,
327 18 => OpCode::SetField,
328 19 => OpCode::NewTable,
329 20 => OpCode::Self_,
330 21 => OpCode::AddI,
331 22 => OpCode::AddK,
332 23 => OpCode::SubK,
333 24 => OpCode::MulK,
334 25 => OpCode::ModK,
335 26 => OpCode::PowK,
336 27 => OpCode::DivK,
337 28 => OpCode::IDivK,
338 29 => OpCode::BAndK,
339 30 => OpCode::BOrK,
340 31 => OpCode::BXOrK,
341 32 => OpCode::ShrI,
342 33 => OpCode::ShlI,
343 34 => OpCode::Add,
344 35 => OpCode::Sub,
345 36 => OpCode::Mul,
346 37 => OpCode::Mod,
347 38 => OpCode::Pow,
348 39 => OpCode::Div,
349 40 => OpCode::IDiv,
350 41 => OpCode::BAnd,
351 42 => OpCode::BOr,
352 43 => OpCode::BXOr,
353 44 => OpCode::Shl,
354 45 => OpCode::Shr,
355 46 => OpCode::MmBin,
356 47 => OpCode::MmBinI,
357 48 => OpCode::MmBinK,
358 49 => OpCode::Unm,
359 50 => OpCode::BNot,
360 51 => OpCode::Not,
361 52 => OpCode::Len,
362 53 => OpCode::Concat,
363 54 => OpCode::Close,
364 55 => OpCode::Tbc,
365 56 => OpCode::Jmp,
366 57 => OpCode::Eq,
367 58 => OpCode::Lt,
368 59 => OpCode::Le,
369 60 => OpCode::EqK,
370 61 => OpCode::EqI,
371 62 => OpCode::LtI,
372 63 => OpCode::LeI,
373 64 => OpCode::GtI,
374 65 => OpCode::GeI,
375 66 => OpCode::Test,
376 67 => OpCode::TestSet,
377 68 => OpCode::Call,
378 69 => OpCode::TailCall,
379 70 => OpCode::Return,
380 71 => OpCode::Return0,
381 72 => OpCode::Return1,
382 73 => OpCode::ForLoop,
383 74 => OpCode::ForPrep,
384 75 => OpCode::TForPrep,
385 76 => OpCode::TForCall,
386 77 => OpCode::TForLoop,
387 78 => OpCode::SetList,
388 79 => OpCode::Closure,
389 80 => OpCode::VarArg,
390 81 => OpCode::VarArgPrep,
391 82 => OpCode::ExtraArg,
392 83 => OpCode::ErrNNil,
393 84 => OpCode::VarArgPack,
394 85 => OpCode::GetVArg,
395 _ => OpCode::ExtraArg,
396 }
397 }
398 #[inline]
399 fn arg_a(&self) -> i32 {
400 ((self.raw() >> 7) & 0xFF) as i32
401 }
402 #[inline]
403 fn arg_b(&self) -> i32 {
404 ((self.raw() >> 16) & 0xFF) as i32
405 }
406 #[inline]
407 fn arg_c(&self) -> i32 {
408 ((self.raw() >> 24) & 0xFF) as i32
409 }
410 #[inline]
411 fn arg_k(&self) -> i32 {
412 ((self.raw() >> 15) & 0x1) as i32
413 }
414 #[inline]
415 fn arg_ax(&self) -> i32 {
416 (self.raw() >> 7) as i32
417 }
418 #[inline]
419 fn arg_bx(&self) -> i32 {
420 (self.raw() >> 15) as i32
421 }
422 #[inline]
423 fn arg_s_b(&self) -> i32 {
424 self.arg_b() - 0x7F
425 }
426 #[inline]
427 fn arg_s_c(&self) -> i32 {
428 self.arg_c() - 0x7F
429 }
430 #[inline]
431 fn arg_s_j(&self) -> i32 {
432 self.arg_ax() - 0xFFFFFF
433 }
434 #[inline]
435 fn arg_s_bx(&self) -> i32 {
436 self.arg_bx() - 0xFFFF
437 }
438 #[inline]
439 fn test_k(&self) -> bool {
440 (self.raw() & (1 << 15)) != 0
441 }
442 #[inline]
443 fn test_a_mode(&self) -> bool {
444 (op_mode_byte(self.opcode()) & (1 << 3)) != 0
445 }
446 #[inline]
447 fn is_mm_mode(&self) -> bool {
448 (op_mode_byte(self.opcode()) & (1 << 7)) != 0
449 }
450 #[inline]
451 fn is_vararg_prep(&self) -> bool {
452 matches!(self.opcode(), OpCode::VarArgPrep)
453 }
454 #[inline]
455 fn is_in_top(&self) -> bool {
456 (op_mode_byte(self.opcode()) & (1 << 5)) != 0 && self.arg_b() == 0
457 }
458}
459
460const OP_MODE_BYTES: [u8; NUM_OPCODES as usize] = [
474 0x08, 0x0a, 0x0a, 0x09, 0x09, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x80, 0x80, 0x80, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x04, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x18, 0x68, 0x68, 0x20, 0x00, 0x00, 0x09, 0x09, 0x01, 0x00, 0x09, 0x20, 0x09, 0x48, 0x28, 0x03, 0x01, 0x08, 0x08, ];
561
562#[inline(always)]
563fn op_mode_byte(op: OpCode) -> u8 {
564 OP_MODE_BYTES[op as usize]
565}
566
567const MAX_TAG_LOOP: i32 = 2000;
571
572const NBITS: u32 = 64;
573
574#[derive(Debug, Clone, Copy, PartialEq, Eq)]
578pub(crate) enum F2Imod {
579 Eq,
581 Floor,
583 Ceil,
585}
586
587#[inline]
590fn intop_add(a: i64, b: i64) -> i64 {
591 (a as u64).wrapping_add(b as u64) as i64
592}
593
594#[inline]
595fn intop_sub(a: i64, b: i64) -> i64 {
596 (a as u64).wrapping_sub(b as u64) as i64
597}
598
599#[inline]
600fn intop_mul(a: i64, b: i64) -> i64 {
601 (a as u64).wrapping_mul(b as u64) as i64
602}
603
604#[inline]
606fn intop_shr(x: i64, n: u32) -> i64 {
607 (x as u64 >> n) as i64
609}
610
611#[inline]
612fn intop_shl(x: i64, n: u32) -> i64 {
613 (x as u64).wrapping_shl(n) as i64
614}
615
616#[inline]
617fn intop_band(a: i64, b: i64) -> i64 {
618 ((a as u64) & (b as u64)) as i64
619}
620#[inline]
621fn intop_bor(a: i64, b: i64) -> i64 {
622 ((a as u64) | (b as u64)) as i64
623}
624#[inline]
625fn intop_bxor(a: i64, b: i64) -> i64 {
626 ((a as u64) ^ (b as u64)) as i64
627}
628
629#[inline]
634fn int_fits_float(i: i64) -> bool {
635 const MAXINTFITSF: u64 = 1u64 << f64::MANTISSA_DIGITS;
636 (MAXINTFITSF.wrapping_add(i as u64)) <= 2 * MAXINTFITSF
637}
638
639fn str_to_number(obj: &LuaValue) -> Option<LuaValue> {
645 let s = match obj {
647 LuaValue::Str(ts) => ts.as_bytes().to_vec(),
648 _ => return None,
649 };
650 let trimmed = trim_whitespace(&s);
652 if trimmed.is_empty() {
653 return None;
654 }
655 let mut result = LuaValue::Nil;
656 if crate::object::str2num(trimmed, &mut result) != 0 {
657 return Some(result);
658 }
659 None
660}
661
662fn trim_whitespace(s: &[u8]) -> &[u8] {
663 let start = s
664 .iter()
665 .position(|&b| !b.is_ascii_whitespace())
666 .unwrap_or(s.len());
667 let end = s
668 .iter()
669 .rposition(|&b| !b.is_ascii_whitespace())
670 .map(|i| i + 1)
671 .unwrap_or(0);
672 if start <= end {
673 &s[start..end]
674 } else {
675 &s[0..0]
676 }
677}
678
679pub(crate) fn tonumber_(obj: &LuaValue) -> Option<f64> {
685 if let LuaValue::Int(i) = obj {
686 return Some(*i as f64);
687 }
688 if let Some(v) = str_to_number(obj) {
689 return match v {
690 LuaValue::Float(f) => Some(f),
691 LuaValue::Int(i) => Some(i as f64),
692 _ => None,
693 };
694 }
695 None
696}
697
698fn tonumber(obj: &LuaValue) -> Option<f64> {
700 if let LuaValue::Float(f) = obj {
701 return Some(*f);
702 }
703 tonumber_(obj)
704}
705
706pub(crate) fn flt_to_integer(n: f64, mode: F2Imod) -> Option<i64> {
709 let f = n.floor();
710 if n != f {
711 match mode {
712 F2Imod::Eq => return None,
713 F2Imod::Ceil => {
714 let f = f + 1.0;
716 if f >= i64::MIN as f64 && f < (i64::MAX as f64 + 1.0) {
718 return Some(f as i64);
719 }
720 return None;
721 }
722 F2Imod::Floor => { }
723 }
724 }
725 if f >= i64::MIN as f64 && f < (i64::MAX as f64 + 1.0) {
726 Some(f as i64)
727 } else {
728 None
729 }
730}
731
732pub(crate) fn to_integer_ns(obj: &LuaValue, mode: F2Imod) -> Option<i64> {
734 if let LuaValue::Float(f) = obj {
735 return flt_to_integer(*f, mode);
736 }
737 if let LuaValue::Int(i) = obj {
738 return Some(*i);
739 }
740 None
741}
742
743pub(crate) fn to_integer(obj: &LuaValue, mode: F2Imod) -> Option<i64> {
745 let coerced;
746 let obj = if let Some(v) = str_to_number(obj) {
747 coerced = v;
748 &coerced
749 } else {
750 obj
751 };
752 to_integer_ns(obj, mode)
753}
754
755fn forlimit(
762 state: &mut LuaState,
763 init: i64,
764 lim: &LuaValue,
765 step: i64,
766) -> Result<(bool, i64), LuaError> {
767 let round = if step < 0 {
768 F2Imod::Ceil
769 } else {
770 F2Imod::Floor
771 };
772 if let Some(p) = to_integer(lim, round) {
773 let skip = if step > 0 { init > p } else { init < p };
774 return Ok((skip, p));
775 }
776 let flim = match tonumber(lim) {
777 Some(f) => f,
778 None => return Err(crate::debug::for_error(state, lim, b"limit")),
779 };
780 if 0.0_f64 < flim {
781 if step < 0 {
783 return Ok((true, 0));
784 }
785 Ok((false, i64::MAX))
786 } else {
787 if step > 0 {
789 return Ok((true, 0));
790 }
791 Ok((false, i64::MIN))
792 }
793}
794
795pub(crate) fn forprep(state: &mut LuaState, ra: StackIdx) -> Result<bool, LuaError> {
800 let pinit = state.get_at(ra);
801 let plimit = state.get_at(ra + 1);
802 let pstep = state.get_at(ra + 2);
803
804 if let (LuaValue::Int(init), LuaValue::Int(step)) = (&pinit, &pstep) {
805 let init = *init;
806 let step = *step;
807 if step == 0 {
808 return Err(LuaError::runtime(format_args!("'for' step is zero")));
809 }
810 state.set_at(ra + 3, LuaValue::Int(init));
811
812 let (skip, limit) = forlimit(state, init, &plimit, step)?;
813 if skip {
814 return Ok(true);
815 }
816 let count: u64 = if step > 0 {
817 let c = (limit as u64).wrapping_sub(init as u64);
818 if step != 1 {
819 c / (step as u64)
820 } else {
821 c
822 }
823 } else {
824 let c = (init as u64).wrapping_sub(limit as u64);
825 c / (((-(step + 1)) as u64).wrapping_add(1))
826 };
827 state.set_at(ra + 1, LuaValue::Int(count as i64));
828 Ok(false)
829 } else {
830 let limit_f = match tonumber(&plimit) {
831 Some(f) => f,
832 None => return Err(crate::debug::for_error(state, &plimit, b"limit")),
833 };
834 let step_f = match tonumber(&pstep) {
835 Some(f) => f,
836 None => return Err(crate::debug::for_error(state, &pstep, b"step")),
837 };
838 let init_f = match tonumber(&pinit) {
839 Some(f) => f,
840 None => return Err(crate::debug::for_error(state, &pinit, b"initial value")),
841 };
842 if step_f == 0.0 {
843 return Err(LuaError::runtime(format_args!("'for' step is zero")));
844 }
845 let skip = if step_f > 0.0 {
846 limit_f < init_f
847 } else {
848 init_f < limit_f
849 };
850 if skip {
851 return Ok(true);
852 }
853 state.set_at(ra + 1, LuaValue::Float(limit_f));
855 state.set_at(ra + 2, LuaValue::Float(step_f));
856 state.set_at(ra, LuaValue::Float(init_f));
857 state.set_at(ra + 3, LuaValue::Float(init_f));
858 Ok(false)
859 }
860}
861
862fn forlimit_legacy(obj: &LuaValue, step: i64) -> Option<(i64, bool)> {
868 let round = if step < 0 {
869 F2Imod::Ceil
870 } else {
871 F2Imod::Floor
872 };
873 if let Some(p) = to_integer(obj, round) {
874 return Some((p, false));
875 }
876 let n = tonumber(obj)?;
877 if 0.0 < n {
878 Some((i64::MAX, step < 0))
879 } else {
880 Some((i64::MIN, step >= 0))
881 }
882}
883
884pub(crate) fn forprep_legacy(state: &mut LuaState, ra: StackIdx) -> Result<(), LuaError> {
892 let init = state.get_at(ra);
893 let plimit = state.get_at(ra + 1);
894 let pstep = state.get_at(ra + 2);
895
896 if matches!(
902 state.global().lua_version,
903 lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
904 ) && !matches!(init, LuaValue::Int(_))
905 && tonumber(&init).is_none()
906 {
907 return Err(crate::debug::for_error(state, &init, b"initial value"));
908 }
909
910 if let (LuaValue::Int(initv), LuaValue::Int(stepv)) = (&init, &pstep) {
911 let (initv, stepv) = (*initv, *stepv);
912 if let Some((ilimit, stopnow)) = forlimit_legacy(&plimit, stepv) {
913 let base = if stopnow { 0 } else { initv };
914 state.set_at(ra + 1, LuaValue::Int(ilimit));
915 state.set_at(ra, LuaValue::Int(intop_sub(base, stepv)));
916 return Ok(());
917 }
918 }
921
922 let nlimit = match tonumber(&plimit) {
923 Some(f) => f,
924 None => return Err(crate::debug::for_error(state, &plimit, b"limit")),
925 };
926 let nstep = match tonumber(&pstep) {
927 Some(f) => f,
928 None => return Err(crate::debug::for_error(state, &pstep, b"step")),
929 };
930 let ninit = match tonumber(&init) {
931 Some(f) => f,
932 None => return Err(crate::debug::for_error(state, &init, b"initial value")),
933 };
934 state.set_at(ra + 1, LuaValue::Float(nlimit));
935 state.set_at(ra + 2, LuaValue::Float(nstep));
936 state.set_at(ra, LuaValue::Float(ninit - nstep));
937 Ok(())
938}
939
940fn forloop_legacy(state: &mut LuaState, ra: StackIdx) -> bool {
945 if let LuaValue::Int(step) = state.get_at(ra + 2) {
946 let idx = intop_add(
947 match state.get_at(ra) {
948 LuaValue::Int(x) => x,
949 _ => 0,
950 },
951 step,
952 );
953 let limit = match state.get_at(ra + 1) {
954 LuaValue::Int(l) => l,
955 _ => 0,
956 };
957 let cont = if step > 0 { idx <= limit } else { limit <= idx };
958 if cont {
959 state.set_at(ra, LuaValue::Int(idx));
960 state.set_at(ra + 3, LuaValue::Int(idx));
961 }
962 cont
963 } else {
964 let step = match state.get_at(ra + 2) {
965 LuaValue::Float(f) => f,
966 _ => return false,
967 };
968 let idx = match state.get_at(ra) {
969 LuaValue::Float(f) => f,
970 _ => return false,
971 } + step;
972 let limit = match state.get_at(ra + 1) {
973 LuaValue::Float(f) => f,
974 _ => return false,
975 };
976 let cont = if step > 0.0 {
977 idx <= limit
978 } else {
979 limit <= idx
980 };
981 if cont {
982 state.set_at(ra, LuaValue::Float(idx));
983 state.set_at(ra + 3, LuaValue::Float(idx));
984 }
985 cont
986 }
987}
988
989fn float_for_loop(state: &mut LuaState, ra: StackIdx) -> bool {
991 let step = match state.get_at(ra + 2) {
993 LuaValue::Float(f) => f,
994 _ => return false,
995 };
996 let limit = match state.get_at(ra + 1) {
997 LuaValue::Float(f) => f,
998 _ => return false,
999 };
1000 let idx = match state.get_at(ra) {
1001 LuaValue::Float(f) => f,
1002 _ => return false,
1003 };
1004 let idx = idx + step;
1005 if if step > 0.0 {
1006 idx <= limit
1007 } else {
1008 limit <= idx
1009 } {
1010 state.set_at(ra, LuaValue::Float(idx));
1011 state.set_at(ra + 3, LuaValue::Float(idx));
1012 true
1013 } else {
1014 false
1015 }
1016}
1017
1018pub(crate) fn finish_get(
1024 state: &mut LuaState,
1025 t_val: LuaValue,
1026 key: LuaValue,
1027 result_idx: StackIdx,
1028 slot_empty: bool,
1029 t_idx: Option<StackIdx>,
1030 var_hint: Option<(&[u8], &[u8])>,
1031) -> Result<(), LuaError> {
1032 let mut t = t_val;
1033 let mut t_idx = t_idx;
1034 for _loop in 0..MAX_TAG_LOOP {
1035 let tm: LuaValue;
1036 if slot_empty && !matches!(t, LuaValue::Table(_)) {
1037 tm = state.get_tm_by_obj(&t, TagMethod::Index);
1038 if matches!(tm, LuaValue::Nil) {
1039 return Err(match (t_idx, var_hint) {
1040 (Some(idx), _) => crate::debug::type_error(state, &t, idx, b"index"),
1041 (None, Some((kind, name))) => {
1042 crate::debug::type_error_with_hint(state, &t, b"index", kind, name)
1043 }
1044 (None, None) => LuaError::type_error(&t, "index"),
1045 });
1046 }
1047 } else {
1048 let mt = state.table_metatable(&t);
1049 tm = state.fast_tm_table(mt.as_ref(), TagMethod::Index);
1050 if matches!(tm, LuaValue::Nil) {
1051 state.set_at(result_idx, LuaValue::Nil);
1052 return Ok(());
1053 }
1054 }
1055 if matches!(tm, LuaValue::Function(_)) {
1056 state.call_tm_res(tm, &t, &key, result_idx)?;
1057 return Ok(());
1058 }
1059 t = tm.clone();
1060 t_idx = None;
1061 if let Some(v) = state.fast_get(&t, &key)? {
1062 state.set_at(result_idx, v);
1063 return Ok(());
1064 }
1065 }
1067 Err(LuaError::runtime(format_args!(
1068 "'__index' chain too long; possible loop"
1069 )))
1070}
1071
1072pub(crate) fn finish_set(
1081 state: &mut LuaState,
1082 t_val: LuaValue,
1083 key: LuaValue,
1084 val: LuaValue,
1085 _slot_present: bool,
1086 t_idx: Option<StackIdx>,
1087 var_hint: Option<(&[u8], &[u8])>,
1088) -> Result<(), LuaError> {
1089 let mut t = t_val;
1090 let mut t_idx = t_idx;
1091 for _loop in 0..MAX_TAG_LOOP {
1092 let tm: LuaValue;
1093 if matches!(t, LuaValue::Table(_)) {
1094 let mt = state.table_metatable(&t);
1095 tm = state.fast_tm_table(mt.as_ref(), TagMethod::NewIndex);
1096 if matches!(tm, LuaValue::Nil) {
1097 state.table_raw_set(&t, key, val.clone())?;
1098 state.gc_value_barrier_back(&t, &val);
1099 return Ok(());
1100 }
1101 } else {
1102 tm = state.get_tm_by_obj(&t, TagMethod::NewIndex);
1103 if matches!(tm, LuaValue::Nil) {
1104 return Err(match (t_idx, var_hint) {
1105 (Some(idx), _) => crate::debug::type_error(state, &t, idx, b"index"),
1106 (None, Some((kind, name))) => {
1107 crate::debug::type_error_with_hint(state, &t, b"index", kind, name)
1108 }
1109 (None, None) => LuaError::type_error(&t, "index"),
1110 });
1111 }
1112 }
1113 if matches!(tm, LuaValue::Function(_)) {
1114 state.call_tm(tm, &t, &key, &val)?;
1115 return Ok(());
1116 }
1117 t = tm.clone();
1118 t_idx = None;
1119 if state.fast_get(&t, &key)?.is_some() {
1120 state.table_raw_set(&t, key.clone(), val.clone())?;
1121 state.gc_value_barrier_back(&t, &val);
1122 return Ok(());
1123 }
1124 }
1125 Err(LuaError::runtime(format_args!(
1126 "'__newindex' chain too long; possible loop"
1127 )))
1128}
1129
1130fn str_cmp(s1: &[u8], s2: &[u8]) -> std::cmp::Ordering {
1141 let mut s1 = s1;
1142 let mut s2 = s2;
1143 loop {
1144 let z1 = s1.iter().position(|&b| b == 0).unwrap_or(s1.len());
1146 let z2 = s2.iter().position(|&b| b == 0).unwrap_or(s2.len());
1147 let seg_cmp = s1[..z1].cmp(&s2[..z2]);
1149 if seg_cmp != std::cmp::Ordering::Equal {
1150 return seg_cmp;
1151 }
1152 if z2 == s2.len() {
1154 if z1 == s1.len() {
1156 return std::cmp::Ordering::Equal;
1157 }
1158 return std::cmp::Ordering::Greater; }
1160 if z1 == s1.len() {
1161 return std::cmp::Ordering::Less; }
1163 s1 = &s1[z1 + 1..];
1165 s2 = &s2[z2 + 1..];
1166 }
1167}
1168
1169#[inline]
1172fn lt_int_float(i: i64, f: f64) -> bool {
1173 if int_fits_float(i) {
1174 (i as f64) < f
1175 } else {
1176 match flt_to_integer(f, F2Imod::Ceil) {
1177 Some(fi) => i < fi,
1178 None => f > 0.0, }
1180 }
1181}
1182
1183#[inline]
1184fn le_int_float(i: i64, f: f64) -> bool {
1185 if int_fits_float(i) {
1186 (i as f64) <= f
1187 } else {
1188 match flt_to_integer(f, F2Imod::Floor) {
1189 Some(fi) => i <= fi,
1190 None => f > 0.0,
1191 }
1192 }
1193}
1194
1195#[inline]
1196fn lt_float_int(f: f64, i: i64) -> bool {
1197 if int_fits_float(i) {
1198 f < (i as f64)
1199 } else {
1200 match flt_to_integer(f, F2Imod::Floor) {
1201 Some(fi) => fi < i,
1202 None => f < 0.0,
1203 }
1204 }
1205}
1206
1207#[inline]
1208fn le_float_int(f: f64, i: i64) -> bool {
1209 if int_fits_float(i) {
1210 f <= (i as f64)
1211 } else {
1212 match flt_to_integer(f, F2Imod::Ceil) {
1213 Some(fi) => fi <= i,
1214 None => f < 0.0,
1215 }
1216 }
1217}
1218
1219#[inline]
1220fn lt_num(l: &LuaValue, r: &LuaValue) -> bool {
1221 debug_assert!(matches!(l, LuaValue::Int(_) | LuaValue::Float(_)));
1222 debug_assert!(matches!(r, LuaValue::Int(_) | LuaValue::Float(_)));
1223 match (l, r) {
1224 (LuaValue::Int(li), LuaValue::Int(ri)) => li < ri,
1225 (LuaValue::Int(li), LuaValue::Float(rf)) => lt_int_float(*li, *rf),
1226 (LuaValue::Float(lf), LuaValue::Float(rf)) => lf < rf,
1227 (LuaValue::Float(lf), LuaValue::Int(ri)) => lt_float_int(*lf, *ri),
1228 _ => false,
1229 }
1230}
1231
1232#[inline]
1233fn le_num(l: &LuaValue, r: &LuaValue) -> bool {
1234 debug_assert!(matches!(l, LuaValue::Int(_) | LuaValue::Float(_)));
1235 debug_assert!(matches!(r, LuaValue::Int(_) | LuaValue::Float(_)));
1236 match (l, r) {
1237 (LuaValue::Int(li), LuaValue::Int(ri)) => li <= ri,
1238 (LuaValue::Int(li), LuaValue::Float(rf)) => le_int_float(*li, *rf),
1239 (LuaValue::Float(lf), LuaValue::Float(rf)) => lf <= rf,
1240 (LuaValue::Float(lf), LuaValue::Int(ri)) => le_float_int(*lf, *ri),
1241 _ => false,
1242 }
1243}
1244
1245fn less_than_others(state: &mut LuaState, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
1247 debug_assert!(
1248 !(matches!(l, LuaValue::Int(_) | LuaValue::Float(_))
1249 && matches!(r, LuaValue::Int(_) | LuaValue::Float(_)))
1250 );
1251 match (l, r) {
1252 (LuaValue::Str(ts1), LuaValue::Str(ts2)) => {
1253 Ok(str_cmp(ts1.as_bytes(), ts2.as_bytes()) == std::cmp::Ordering::Less)
1254 }
1255 _ => state.call_order_tm(l, r, TagMethod::Lt),
1256 }
1257}
1258
1259pub(crate) fn less_than(
1260 state: &mut LuaState,
1261 l: &LuaValue,
1262 r: &LuaValue,
1263) -> Result<bool, LuaError> {
1264 if matches!(l, LuaValue::Int(_) | LuaValue::Float(_))
1265 && matches!(r, LuaValue::Int(_) | LuaValue::Float(_))
1266 {
1267 Ok(lt_num(l, r))
1268 } else {
1269 less_than_others(state, l, r)
1270 }
1271}
1272
1273fn less_equal_others(state: &mut LuaState, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
1274 match (l, r) {
1275 (LuaValue::Str(ts1), LuaValue::Str(ts2)) => {
1276 Ok(str_cmp(ts1.as_bytes(), ts2.as_bytes()) != std::cmp::Ordering::Greater)
1277 }
1278 _ => state.call_order_tm(l, r, TagMethod::Le),
1279 }
1280}
1281
1282pub(crate) fn less_equal(
1283 state: &mut LuaState,
1284 l: &LuaValue,
1285 r: &LuaValue,
1286) -> Result<bool, LuaError> {
1287 if matches!(l, LuaValue::Int(_) | LuaValue::Float(_))
1288 && matches!(r, LuaValue::Int(_) | LuaValue::Float(_))
1289 {
1290 Ok(le_num(l, r))
1291 } else {
1292 less_equal_others(state, l, r)
1293 }
1294}
1295
1296pub(crate) fn raw_equal_values(t1: &LuaValue, t2: &LuaValue) -> bool {
1305 matches!(equal_obj(None, t1, t2), Ok(true))
1306}
1307
1308fn equal_tm(state: &mut LuaState, t1: &LuaValue, t2: &LuaValue) -> LuaValue {
1316 let eq = crate::tagmethods::TagMethod::Eq;
1317 if state.global().lua_version == lua_types::LuaVersion::V51 {
1318 return crate::tagmethods::get_comp_tm_51(state, t1, t2, eq);
1319 }
1320 let tm1 = crate::tagmethods::get_tm_by_obj(state, t1, eq);
1321 if tm1.is_nil() {
1322 crate::tagmethods::get_tm_by_obj(state, t2, eq)
1323 } else {
1324 tm1
1325 }
1326}
1327
1328pub(crate) fn equal_obj(
1330 state: Option<&mut LuaState>,
1331 t1: &LuaValue,
1332 t2: &LuaValue,
1333) -> Result<bool, LuaError> {
1334 let same_variant = std::mem::discriminant(t1) == std::mem::discriminant(t2);
1337 if !same_variant {
1338 let t1_is_num = matches!(t1, LuaValue::Int(_) | LuaValue::Float(_));
1339 let t2_is_num = matches!(t2, LuaValue::Int(_) | LuaValue::Float(_));
1340 if !(t1_is_num && t2_is_num) {
1341 return Ok(false);
1342 }
1343 let i1 = to_integer_ns(t1, F2Imod::Eq);
1345 let i2 = to_integer_ns(t2, F2Imod::Eq);
1346 return Ok(i1.is_some() && i2.is_some() && i1 == i2);
1347 }
1348
1349 match (t1, t2) {
1350 (LuaValue::Nil, LuaValue::Nil) => Ok(true),
1351 (LuaValue::Bool(b1), LuaValue::Bool(b2)) => Ok(b1 == b2),
1352 (LuaValue::Int(i1), LuaValue::Int(i2)) => Ok(i1 == i2),
1353 (LuaValue::Float(f1), LuaValue::Float(f2)) => Ok(f1 == f2),
1354 (LuaValue::LightUserData(p1), LuaValue::LightUserData(p2)) => Ok(p1 == p2),
1355 (LuaValue::Function(f1), LuaValue::Function(f2)) => {
1356 use lua_types::closure::LuaClosure;
1357 let same = match (f1, f2) {
1358 (LuaClosure::Lua(a), LuaClosure::Lua(b)) => GcRef::ptr_eq(a, b),
1359 (LuaClosure::C(a), LuaClosure::C(b)) => GcRef::ptr_eq(a, b),
1360 (LuaClosure::LightC(a), LuaClosure::LightC(b)) => a == b,
1361 _ => false,
1362 };
1363 Ok(same)
1364 }
1365 (LuaValue::Str(s1), LuaValue::Str(s2)) => {
1366 Ok(s1 == s2)
1369 }
1370 (LuaValue::UserData(u1), LuaValue::UserData(u2)) => {
1371 if std::ptr::eq(u1.as_ptr(), u2.as_ptr()) {
1374 return Ok(true);
1375 }
1376 let Some(state) = state else {
1377 return Ok(false);
1378 };
1379 let tm = equal_tm(state, t1, t2);
1380 if matches!(tm, LuaValue::Nil) {
1381 return Ok(false);
1382 }
1383 let result = state.call_tm_res_bool(tm, t1, t2)?;
1384 Ok(result)
1385 }
1386 (LuaValue::Table(h1), LuaValue::Table(h2)) => {
1387 if std::ptr::eq(h1.as_ptr(), h2.as_ptr()) {
1388 return Ok(true);
1389 }
1390 let Some(state) = state else {
1391 return Ok(false);
1392 };
1393 let tm = equal_tm(state, t1, t2);
1394 if matches!(tm, LuaValue::Nil) {
1395 return Ok(false);
1396 }
1397 let result = state.call_tm_res_bool(tm, t1, t2)?;
1398 Ok(result)
1399 }
1400 (LuaValue::Thread(a), LuaValue::Thread(b)) => Ok(GcRef::ptr_eq(a, b)),
1401 _ => Ok(std::ptr::eq(t1 as *const _, t2 as *const _)),
1402 }
1403}
1404
1405fn copy_to_buf(state: &LuaState, top: StackIdx, n: u32, buf: &mut Vec<u8>) {
1409 buf.clear();
1410 let mut remaining = n;
1411 loop {
1412 let idx = top - remaining as i32;
1413 let v = state.get_at(idx);
1414 if let LuaValue::Str(ts) = v {
1415 buf.extend_from_slice(ts.as_bytes());
1416 }
1417 if remaining <= 1 {
1418 break;
1419 }
1420 remaining -= 1;
1421 }
1422}
1423
1424pub(crate) fn concat(state: &mut LuaState, total: i32) -> Result<(), LuaError> {
1426 if total == 1 {
1427 return Ok(());
1428 }
1429 if total == 2 {
1430 let top = state.top_idx();
1431 let v_tm1 = state.get_at(top - 1);
1432 let v_tm2 = state.get_at(top - 2);
1433 if concat_pair_fast(state, top, v_tm2, v_tm1)? {
1434 return Ok(());
1435 }
1436 }
1437 let mut total = total;
1438 loop {
1439 let top = state.top_idx();
1440 let v_tm1 = state.get_at(top - 1); let v_tm2 = state.get_at(top - 2); let top2_coercible = matches!(v_tm2, LuaValue::Str(_))
1445 || matches!(v_tm2, LuaValue::Int(_) | LuaValue::Float(_));
1446 let top1_stringlike = matches!(v_tm1, LuaValue::Str(_))
1448 || matches!(v_tm1, LuaValue::Int(_) | LuaValue::Float(_));
1449 if !top2_coercible || !top1_stringlike {
1450 state.try_concat_tm(&v_tm1, &v_tm2)?;
1451 total -= 1;
1456 let top = state.top_idx();
1457 state.set_top(top - 1);
1458 if total <= 1 {
1459 break;
1460 }
1461 continue;
1462 }
1463
1464 let is_empty =
1465 |v: &LuaValue| -> bool { matches!(v, LuaValue::Str(s) if s.as_bytes().is_empty()) };
1466
1467 let n: u32;
1468 if is_empty(&v_tm1) {
1469 state.coerce_to_string(top - 2)?;
1470 n = 2;
1471 } else if is_empty(&v_tm2) {
1472 state.coerce_to_string(top - 1)?;
1475 let v = state.get_at(top - 1);
1476 state.set_at(top - 2, v);
1477 n = 2;
1478 } else {
1479 state.coerce_to_string(top - 1)?;
1481 let s1 = match state.get_at(top - 1) {
1482 LuaValue::Str(ts) => ts.as_bytes().len(),
1483 _ => 0,
1484 };
1485 let mut total_len = s1;
1486 let mut count: u32 = 1;
1487 let top = state.top_idx();
1488 loop {
1489 if count as i32 >= total {
1490 break;
1491 }
1492 let idx = top - (count as i32 + 1);
1493 let v = state.get_at(idx);
1494 if !matches!(v, LuaValue::Str(_) | LuaValue::Int(_) | LuaValue::Float(_)) {
1495 break;
1496 }
1497 state.coerce_to_string(idx)?;
1498 let l = match state.get_at(idx) {
1499 LuaValue::Str(ts) => ts.as_bytes().len(),
1500 _ => 0,
1501 };
1502 if l >= usize::MAX - total_len {
1503 state.set_top(top - total as i32);
1505 return Err(LuaError::runtime(format_args!("string length overflow")));
1506 }
1507 total_len += l;
1508 count += 1;
1509 }
1510 n = count;
1511
1512 if let Some(err) = state.sandbox_reserve(total_len) {
1514 return Err(err);
1515 }
1516 let mut buf: Vec<u8> = Vec::with_capacity(total_len);
1517 let top = state.top_idx();
1518 copy_to_buf(state, top, n, &mut buf);
1519 let ts = state.intern_or_create_str(&buf)?;
1520 state.set_at(top - n as i32, LuaValue::Str(ts));
1521 }
1522 total -= n as i32 - 1;
1523 let top = state.top_idx();
1524 state.set_top(top - ((n - 1) as i32));
1525
1526 if total <= 1 {
1527 break;
1528 }
1529 }
1530 Ok(())
1531}
1532
1533enum ConcatPiece {
1534 Str(GcRef<LuaString>),
1535 Num(Vec<u8>),
1536}
1537
1538impl ConcatPiece {
1539 #[inline]
1540 fn len(&self) -> usize {
1541 match self {
1542 ConcatPiece::Str(s) => s.as_bytes().len(),
1543 ConcatPiece::Num(bytes) => bytes.len(),
1544 }
1545 }
1546
1547 #[inline]
1548 fn append_to(&self, out: &mut Vec<u8>) {
1549 match self {
1550 ConcatPiece::Str(s) => out.extend_from_slice(s.as_bytes()),
1551 ConcatPiece::Num(bytes) => out.extend_from_slice(bytes),
1552 }
1553 }
1554}
1555
1556#[inline]
1557fn concat_piece(v: LuaValue, version: lua_types::LuaVersion) -> Option<ConcatPiece> {
1558 match v {
1559 LuaValue::Str(s) => Some(ConcatPiece::Str(s)),
1560 LuaValue::Int(_) | LuaValue::Float(_) => Some(ConcatPiece::Num(
1561 crate::object::number_to_str_buf(&v, version),
1562 )),
1563 _ => None,
1564 }
1565}
1566
1567#[inline]
1568fn concat_pair_fast(
1569 state: &mut LuaState,
1570 top: StackIdx,
1571 left: LuaValue,
1572 right: LuaValue,
1573) -> Result<bool, LuaError> {
1574 let version = state.global().lua_version;
1575 let Some(left) = concat_piece(left, version) else {
1576 return Ok(false);
1577 };
1578 let Some(right) = concat_piece(right, version) else {
1579 return Ok(false);
1580 };
1581 let total_len = left
1582 .len()
1583 .checked_add(right.len())
1584 .ok_or_else(|| LuaError::runtime(format_args!("string length overflow")))?;
1585 if let Some(err) = state.sandbox_reserve(total_len) {
1586 return Err(err);
1587 }
1588 let mut buf = Vec::with_capacity(total_len);
1589 left.append_to(&mut buf);
1590 right.append_to(&mut buf);
1591 let ts = state.intern_or_create_str(&buf)?;
1592 state.set_at(top - 2, LuaValue::Str(ts));
1593 state.set_top(top - 1);
1594 Ok(true)
1595}
1596
1597pub(crate) fn obj_len(
1601 state: &mut LuaState,
1602 ra: StackIdx,
1603 rb: LuaValue,
1604 rb_idx: StackIdx,
1605) -> Result<(), LuaError> {
1606 match &rb {
1607 LuaValue::Table(_) => {
1608 let consult_len_tm = !matches!(state.global().lua_version, lua_types::LuaVersion::V51);
1613 let tm = if consult_len_tm {
1614 let mt = state.table_metatable(&rb);
1615 state.fast_tm_table(mt.as_ref(), TagMethod::Len)
1616 } else {
1617 LuaValue::Nil
1618 };
1619 if matches!(tm, LuaValue::Nil) {
1620 let n = state.table_length(&rb)?;
1621 state.set_at(ra, LuaValue::Int(n as i64));
1622 return Ok(());
1623 }
1624 state.call_tm_res(tm, &rb, &rb, ra)?;
1626 }
1627 LuaValue::Str(ts) => {
1628 let n = ts.len();
1631 state.set_at(ra, LuaValue::Int(n as i64));
1632 }
1633 other => {
1634 let tm = state.get_tm_by_obj(other, TagMethod::Len);
1636 if matches!(tm, LuaValue::Nil) {
1637 return Err(crate::debug::type_error(
1638 state,
1639 other,
1640 rb_idx,
1641 b"get length of",
1642 ));
1643 }
1644 state.call_tm_res(tm, &rb, &rb, ra)?;
1645 }
1646 }
1647 Ok(())
1648}
1649
1650pub(crate) fn idiv(m: i64, n: i64) -> Result<i64, LuaError> {
1654 if (n as u64).wrapping_add(1) <= 1 {
1655 if n == 0 {
1656 return Err(LuaError::runtime(format_args!("attempt to divide by zero")));
1657 }
1658 return Ok(intop_sub(0, m));
1659 }
1660 let q = m / n;
1661 if (m ^ n) < 0 && m % n != 0 {
1663 Ok(q - 1)
1664 } else {
1665 Ok(q)
1666 }
1667}
1668
1669pub(crate) fn imod(m: i64, n: i64) -> Result<i64, LuaError> {
1671 if (n as u64).wrapping_add(1) <= 1 {
1672 if n == 0 {
1673 return Err(LuaError::runtime(format_args!("attempt to perform 'n%0'")));
1674 }
1675 return Ok(0);
1676 }
1677 let r = m % n;
1678 if r != 0 && (r ^ n) < 0 {
1679 Ok(r + n)
1680 } else {
1681 Ok(r)
1682 }
1683}
1684
1685pub(crate) fn fmodf(m: f64, n: f64) -> f64 {
1687 let r = m % n;
1688 let opposite_signs = if r > 0.0 { n < 0.0 } else { r < 0.0 && n > 0.0 };
1689 if opposite_signs {
1690 r + n
1691 } else {
1692 r
1693 }
1694}
1695
1696pub(crate) fn tagmethod_from_index(i: usize) -> TagMethod {
1699 use TagMethod::*;
1700 match i {
1701 0 => Index,
1702 1 => NewIndex,
1703 2 => Gc,
1704 3 => Mode,
1705 4 => Len,
1706 5 => Eq,
1707 6 => Add,
1708 7 => Sub,
1709 8 => Mul,
1710 9 => Mod,
1711 10 => Pow,
1712 11 => Div,
1713 12 => Idiv,
1714 13 => Band,
1715 14 => Bor,
1716 15 => Bxor,
1717 16 => Shl,
1718 17 => Shr,
1719 18 => Unm,
1720 19 => Bnot,
1721 20 => Lt,
1722 21 => Le,
1723 22 => Concat,
1724 23 => Call,
1725 24 => Close,
1726 _ => Index,
1727 }
1728}
1729
1730pub(crate) fn int_floor_mod(_state: &mut LuaState, a: i64, b: i64) -> Result<i64, LuaError> {
1733 imod(a, b)
1734}
1735
1736pub(crate) fn int_floor_div(_state: &mut LuaState, a: i64, b: i64) -> Result<i64, LuaError> {
1739 idiv(a, b)
1740}
1741
1742pub(crate) fn float_floor_mod(_state: &mut LuaState, a: f64, b: f64) -> Result<f64, LuaError> {
1745 Ok(fmodf(a, b))
1746}
1747
1748pub(crate) fn shiftl(x: i64, y: i64) -> i64 {
1750 if y < 0 {
1751 if y <= -(NBITS as i64) {
1752 0
1753 } else {
1754 intop_shr(x, (-y) as u32)
1755 }
1756 } else {
1757 if y >= NBITS as i64 {
1758 0
1759 } else {
1760 intop_shl(x, y as u32)
1761 }
1762 }
1763}
1764
1765fn push_closure(
1773 state: &mut LuaState,
1774 proto_idx: usize, ci: CallInfoIdx,
1776 base: StackIdx,
1777 ra: StackIdx,
1778) -> Result<(), LuaError> {
1779 state.push_closure(proto_idx, ci, base, ra)
1780}
1781
1782pub(crate) fn finish_op(state: &mut LuaState) -> Result<(), LuaError> {
1787 let ci = state.current_ci_idx();
1791 let base = state.ci_base(ci);
1792 let inst = state.ci_prev_instruction(ci);
1793 let op = inst.opcode();
1794
1795 match op {
1796 OpCode::MmBin | OpCode::MmBinI | OpCode::MmBinK => {
1798 let prev_inst = state.ci_prev2_instruction(ci);
1799 let a = prev_inst.arg_a();
1800 state.dec_top();
1801 let top = state.top_idx();
1802 let v = state.get_at(top);
1803 state.set_at(base + a, v);
1804 }
1805 OpCode::Unm
1807 | OpCode::BNot
1808 | OpCode::Len
1809 | OpCode::GetTabUp
1810 | OpCode::GetTable
1811 | OpCode::GetI
1812 | OpCode::GetField
1813 | OpCode::Self_ => {
1814 let a = inst.arg_a();
1815 state.dec_top();
1816 let top = state.top_idx();
1817 let v = state.get_at(top);
1818 state.set_at(base + a, v);
1819 }
1820 OpCode::Lt
1824 | OpCode::Le
1825 | OpCode::LtI
1826 | OpCode::LeI
1827 | OpCode::GtI
1828 | OpCode::GeI
1829 | OpCode::Eq => {
1830 let top_minus1 = state.top_idx() - 1;
1831 let v = state.get_at(top_minus1);
1832 let mut res = !matches!(v, LuaValue::Nil | LuaValue::Bool(false));
1833 state.dec_top();
1834 if (state.get_ci(ci).callstatus & crate::state::CIST_LEQ) != 0 {
1839 state.get_ci_mut(ci).callstatus &= !crate::state::CIST_LEQ;
1840 res = !res;
1841 }
1842 if (res as i32) != inst.arg_k() {
1843 state.ci_skip_next_instruction(ci);
1844 }
1845 }
1846 OpCode::Concat => {
1852 let top = state.top_idx() - 1; let a = inst.arg_a();
1854 let total_concat = (top - 1 - (base + a)) as i32;
1855 let v = state.get_at(top);
1856 state.set_at(top - 2, v);
1857 state.set_top(top - 1);
1858 concat(state, total_concat)?;
1859 }
1860 OpCode::Close => {
1861 state.ci_step_pc_back(ci);
1862 }
1863 OpCode::Return => {
1867 let a = inst.arg_a();
1868 let ra = base + a;
1869 let nres = state.ci_nres(ci);
1870 state.set_top(ra + nres);
1871 state.ci_step_pc_back(ci);
1872 }
1873 other => {
1874 debug_assert!(
1875 matches!(
1876 other,
1877 OpCode::TForCall
1878 | OpCode::Call
1879 | OpCode::TailCall
1880 | OpCode::SetTabUp
1881 | OpCode::SetTable
1882 | OpCode::SetI
1883 | OpCode::SetField
1884 ),
1885 "unexpected opcode in finish_op: {:?}",
1886 other
1887 );
1888 }
1889 }
1890 Ok(())
1891}
1892
1893pub(crate) fn execute(state: &mut LuaState, mut ci: CallInfoIdx) -> Result<(), LuaError> {
1905 let mut trap: bool;
1906 let legacy_for = matches!(
1913 state.global().lua_version,
1914 lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
1915 );
1916 let tfor_55 = state.global().lua_version == lua_types::LuaVersion::V55;
1917
1918 'startfunc: loop {
1920 trap = state.hook_mask() != 0;
1921
1922 'returning: loop {
1925 let ci_slot = ci.as_usize();
1926 let func_idx = state.call_info[ci_slot].func;
1927 let cl = match state.stack[func_idx.0 as usize].val {
1928 LuaValue::Function(lua_types::closure::LuaClosure::Lua(c)) => c,
1929 _ => {
1930 return Err(LuaError::runtime(format_args!(
1931 "internal: execute called on non-Lua frame"
1932 )));
1933 }
1934 };
1935 let code = &cl.proto.code;
1936 let constants = &cl.proto.k;
1937 let mut pc: u32 = state.call_info[ci_slot].saved_pc();
1939
1940 if trap {
1941 trap = state.trace_call(ci)?;
1942 }
1943 let mut base: StackIdx = state.call_info[ci.as_usize()].func + 1;
1944
1945 'dispatch: loop {
1947 if trap {
1948 trap = state.trace_exec(ci, pc)?;
1949 base = state.ci_base(ci); }
1951 let i: Instruction = code[pc as usize];
1952 pc += 1;
1953 let op = i.opcode();
1954 #[cfg(feature = "opcode-profile")]
1955 crate::opcode_profile::record(op);
1956
1957 debug_assert!(base == state.ci_base(ci));
1958
1959 #[cfg(debug_assertions)]
1963 {
1964 let op_mode = op_mode_byte(op);
1965 if (op_mode & (1 << 5)) == 0 || i.arg_b() != 0 {
1966 state.set_top(base);
1967 }
1968 }
1969
1970 match op {
1971 OpCode::Move => {
1973 let ra = base + i.arg_a();
1974 let rb = base + i.arg_b();
1975 let v = state.stack[rb.0 as usize].val;
1976 state.stack[ra.0 as usize].val = v;
1977 }
1978 OpCode::LoadI => {
1980 let ra = base + i.arg_a();
1981 let b = i.arg_s_bx() as i64;
1982 state.stack[ra.0 as usize].val = LuaValue::Int(b);
1983 }
1984 OpCode::LoadF => {
1986 let ra = base + i.arg_a();
1987 let b = i.arg_s_bx() as f64;
1988 state.stack[ra.0 as usize].val = LuaValue::Float(b);
1989 }
1990 OpCode::LoadK => {
1992 let ra = base + i.arg_a();
1993 let k_idx = i.arg_bx() as usize;
1994 state.stack[ra.0 as usize].val = constants[k_idx];
1995 }
1996 OpCode::LoadKX => {
1998 let ra = base + i.arg_a();
1999 let extra = code[pc as usize];
2000 pc += 1;
2001 let k_idx = extra.arg_ax() as usize;
2002 state.stack[ra.0 as usize].val = constants[k_idx];
2003 }
2004 OpCode::LoadFalse => {
2006 let ra = base + i.arg_a();
2007 state.stack[ra.0 as usize].val = LuaValue::Bool(false);
2008 }
2009 OpCode::LFalseSkip => {
2011 let ra = base + i.arg_a();
2012 state.stack[ra.0 as usize].val = LuaValue::Bool(false);
2013 pc += 1;
2014 }
2015 OpCode::LoadTrue => {
2017 let ra = base + i.arg_a();
2018 state.stack[ra.0 as usize].val = LuaValue::Bool(true);
2019 }
2020 OpCode::LoadNil => {
2022 let ra = base + i.arg_a();
2023 let b = i.arg_b();
2024 for k in 0..=b {
2025 state.stack[(ra + k).0 as usize].val = LuaValue::Nil;
2026 }
2027 }
2028 OpCode::GetUpVal => {
2030 let ra = base + i.arg_a();
2031 let b = i.arg_b() as usize;
2032 let uv = cl.upval(b);
2033 let v = match uv.try_open_payload() {
2034 Some((thread_id, idx))
2035 if thread_id == state.cached_thread_id =>
2036 {
2037 state.stack[idx.0 as usize].val
2038 }
2039 Some(_) => state.upvalue_get(&cl, b),
2040 None => uv.closed_value(),
2041 };
2042 state.stack[ra.0 as usize].val = v;
2043 }
2044 OpCode::SetUpVal => {
2047 let ra = base + i.arg_a();
2048 let b = i.arg_b() as usize;
2049 let v = state.stack[ra.0 as usize].val;
2050 let uv = cl.upval(b);
2051 match uv.try_open_payload() {
2052 Some((thread_id, idx))
2053 if thread_id == state.cached_thread_id =>
2054 {
2055 state.stack[idx.0 as usize].val = v;
2056 if v.is_collectable() {
2057 state.gc_barrier_upval(&uv, &v);
2058 }
2059 }
2060 None => {
2061 uv.set_closed_value(v);
2062 if v.is_collectable() {
2063 state.gc_barrier_upval(&uv, &v);
2064 }
2065 }
2066 _ => {
2067 state.upvalue_set(&cl, b, v)?;
2068 }
2069 }
2070 }
2071 OpCode::GetTabUp => {
2075 let ra = base + i.arg_a();
2076 let b = i.arg_b() as usize;
2077 let k_idx = i.arg_c() as usize;
2078 let upval = state.upvalue_get(&cl, b);
2079 let key = constants[k_idx];
2080 match state.fast_get_short_str(&upval, &key)? {
2081 Some(v) => state.set_at(ra, v),
2082 None => {
2083 state.set_ci_savedpc(ci, pc);
2084 state.set_top(state.ci_top(ci));
2085 let upval_name: Vec<u8> =
2086 cl.0.proto
2087 .upvalues
2088 .get(b)
2089 .and_then(|uv| uv.name.as_ref())
2090 .map(|s| s.as_bytes().to_vec())
2091 .unwrap_or_else(|| b"?".to_vec());
2092 let hint: Option<(&[u8], &[u8])> = Some((b"upvalue", &upval_name));
2093 finish_get(state, upval, key, ra, true, None, hint)?;
2094 trap = state.ci_trap(ci);
2095 }
2096 }
2097 }
2098 OpCode::GetTable => {
2101 let ra = base + i.arg_a();
2102 let rb_idx = base + i.arg_b();
2103 let rb_v = state.get_at(rb_idx);
2104 let rc_v = state.get_at(base + i.arg_c());
2105 let fast_result = if let LuaValue::Int(n) = &rc_v {
2106 state.fast_get_int(&rb_v, *n)?
2107 } else {
2108 state.fast_get(&rb_v, &rc_v)?
2109 };
2110 match fast_result {
2111 Some(v) => state.set_at(ra, v),
2112 None => {
2113 state.set_ci_savedpc(ci, pc);
2114 state.set_top(state.ci_top(ci));
2115 finish_get(state, rb_v, rc_v, ra, true, Some(rb_idx), None)?;
2116 trap = state.ci_trap(ci);
2117 }
2118 }
2119 }
2120 OpCode::GetI => {
2124 let ra = base + i.arg_a();
2125 let rb_idx = base + i.arg_b();
2126 let rb_v = state.get_at(rb_idx);
2127 let c = i.arg_c() as i64;
2128 match state.fast_get_int(&rb_v, c)? {
2129 Some(v) => state.set_at(ra, v),
2130 None => {
2131 let key = LuaValue::Int(c);
2132 state.set_ci_savedpc(ci, pc);
2133 state.set_top(state.ci_top(ci));
2134 finish_get(state, rb_v, key, ra, true, Some(rb_idx), None)?;
2135 trap = state.ci_trap(ci);
2136 }
2137 }
2138 }
2139 OpCode::GetField => {
2141 let ra = base + i.arg_a();
2142 let rb_idx = base + i.arg_b();
2143 let rb_v = state.get_at(rb_idx);
2144 let k_idx = i.arg_c() as usize;
2145 let key = constants[k_idx];
2146 match state.fast_get_short_str(&rb_v, &key)? {
2147 Some(v) => state.set_at(ra, v),
2148 None => {
2149 state.set_ci_savedpc(ci, pc);
2150 state.set_top(state.ci_top(ci));
2151 finish_get(state, rb_v, key, ra, true, Some(rb_idx), None)?;
2152 trap = state.ci_trap(ci);
2153 }
2154 }
2155 }
2156 OpCode::SetTabUp => {
2158 let a = i.arg_a() as usize;
2159 let b_idx = i.arg_b() as usize; let rc_v = if i.test_k() {
2161 constants[i.arg_c() as usize]
2162 } else {
2163 state.get_at(base + i.arg_c())
2164 };
2165 let upval = state.upvalue_get(&cl, a);
2166 let key = constants[b_idx];
2167 if let LuaValue::Table(tbl) = upval {
2168 if !tbl.has_metatable() {
2169 if rc_v.is_collectable() {
2170 state.gc_table_barrier_back(&tbl, &rc_v);
2171 }
2172 if let LuaValue::Str(s) = key {
2173 tbl.raw_set_short_str(state, s, rc_v)?;
2174 } else {
2175 tbl.raw_set(state, key, rc_v)?;
2176 }
2177 continue 'dispatch;
2178 }
2179 }
2180 match state.fast_get_short_str(&upval, &key)? {
2181 Some(_slot) => {
2182 state.gc_value_barrier_back(&upval, &rc_v);
2183 if let LuaValue::Table(tbl) = upval {
2184 if let LuaValue::Str(s) = key {
2185 tbl.raw_set_short_str(state, s, rc_v)?;
2186 } else {
2187 tbl.raw_set(state, key, rc_v)?;
2188 }
2189 } else {
2190 state.table_raw_set(&upval, key, rc_v)?;
2191 }
2192 }
2193 None => {
2194 state.set_ci_savedpc(ci, pc);
2195 state.set_top(state.ci_top(ci));
2196 let upval_name: Vec<u8> = cl
2197 .proto
2198 .upvalues
2199 .get(a)
2200 .and_then(|uv| uv.name.as_ref())
2201 .map(|s| s.as_bytes().to_vec())
2202 .unwrap_or_else(|| b"?".to_vec());
2203 let hint: Option<(&[u8], &[u8])> = Some((b"upvalue", &upval_name));
2204 finish_set(state, upval, key, rc_v, false, None, hint)?;
2205 trap = state.ci_trap(ci);
2206 }
2207 }
2208 }
2209 OpCode::SetTable => {
2211 let ra_idx = base + i.arg_a();
2212 let ra_v = state.get_at(ra_idx);
2213 let rb_v = state.get_at(base + i.arg_b());
2214 let rc_v = if i.test_k() {
2215 constants[i.arg_c() as usize]
2216 } else {
2217 state.get_at(base + i.arg_c())
2218 };
2219 if let LuaValue::Table(tbl) = ra_v {
2220 if !tbl.has_metatable() {
2221 if rc_v.is_collectable() {
2222 state.gc_table_barrier_back(&tbl, &rc_v);
2223 }
2224 match rb_v {
2225 LuaValue::Int(n) => tbl.raw_set_int(state, n, rc_v)?,
2226 LuaValue::Str(s) if s.is_short() => {
2227 tbl.raw_set_short_str(state, s, rc_v)?
2228 }
2229 _ => tbl.raw_set(state, rb_v, rc_v)?,
2230 }
2231 } else {
2232 let fast = if let LuaValue::Int(n) = &rb_v {
2233 state.fast_get_int(&ra_v, *n)?
2234 } else {
2235 state.fast_get(&ra_v, &rb_v)?
2236 };
2237 if fast.is_some() {
2238 state.gc_value_barrier_back(&ra_v, &rc_v);
2239 match rb_v {
2240 LuaValue::Int(n) => tbl.raw_set_int(state, n, rc_v)?,
2241 LuaValue::Str(s) if s.is_short() => {
2242 tbl.raw_set_short_str(state, s, rc_v)?
2243 }
2244 _ => tbl.raw_set(state, rb_v, rc_v)?,
2245 }
2246 } else {
2247 state.set_ci_savedpc(ci, pc);
2248 state.set_top(state.ci_top(ci));
2249 finish_set(state, ra_v, rb_v, rc_v, false, Some(ra_idx), None)?;
2250 trap = state.ci_trap(ci);
2251 }
2252 }
2253 } else {
2254 state.set_ci_savedpc(ci, pc);
2255 state.set_top(state.ci_top(ci));
2256 finish_set(state, ra_v, rb_v, rc_v, false, Some(ra_idx), None)?;
2257 trap = state.ci_trap(ci);
2258 }
2259 }
2260 OpCode::SetI => {
2262 let ra_idx = base + i.arg_a();
2263 let ra_v = state.get_at(ra_idx);
2264 let c = i.arg_b() as i64;
2265 let rc_v = if i.test_k() {
2266 constants[i.arg_c() as usize]
2267 } else {
2268 state.get_at(base + i.arg_c())
2269 };
2270 if let LuaValue::Table(tbl) = ra_v {
2271 if !tbl.has_metatable() {
2272 if rc_v.is_collectable() {
2273 state.gc_table_barrier_back(&tbl, &rc_v);
2274 }
2275 tbl.raw_set_int(state, c, rc_v)?;
2276 } else {
2277 let fast = state.fast_get_int(&ra_v, c)?;
2278 if fast.is_some() {
2279 state.gc_value_barrier_back(&ra_v, &rc_v);
2280 tbl.raw_set_int(state, c, rc_v)?;
2281 } else {
2282 state.set_ci_savedpc(ci, pc);
2283 state.set_top(state.ci_top(ci));
2284 finish_set(
2285 state,
2286 ra_v,
2287 LuaValue::Int(c),
2288 rc_v,
2289 false,
2290 Some(ra_idx),
2291 None,
2292 )?;
2293 trap = state.ci_trap(ci);
2294 }
2295 }
2296 } else {
2297 state.set_ci_savedpc(ci, pc);
2298 state.set_top(state.ci_top(ci));
2299 finish_set(
2300 state,
2301 ra_v,
2302 LuaValue::Int(c),
2303 rc_v,
2304 false,
2305 Some(ra_idx),
2306 None,
2307 )?;
2308 trap = state.ci_trap(ci);
2309 }
2310 }
2311 OpCode::SetField => {
2313 let ra_idx = base + i.arg_a();
2314 let ra_v = state.get_at(ra_idx);
2315 let b_idx = i.arg_b() as usize;
2316 let key = constants[b_idx];
2317 let rc_v = if i.test_k() {
2318 constants[i.arg_c() as usize]
2319 } else {
2320 state.get_at(base + i.arg_c())
2321 };
2322 if let LuaValue::Table(tbl) = ra_v {
2323 if !tbl.has_metatable() {
2324 if rc_v.is_collectable() {
2325 state.gc_table_barrier_back(&tbl, &rc_v);
2326 }
2327 if let LuaValue::Str(s) = key {
2328 tbl.raw_set_short_str(state, s, rc_v)?;
2329 } else {
2330 tbl.raw_set(state, key, rc_v)?;
2331 }
2332 } else {
2333 match state.fast_get_short_str(&ra_v, &key)? {
2334 Some(_) => {
2335 state.gc_value_barrier_back(&ra_v, &rc_v);
2336 if let LuaValue::Str(s) = key {
2337 tbl.raw_set_short_str(state, s, rc_v)?;
2338 } else {
2339 tbl.raw_set(state, key, rc_v)?;
2340 }
2341 }
2342 None => {
2343 state.set_ci_savedpc(ci, pc);
2344 state.set_top(state.ci_top(ci));
2345 finish_set(
2346 state,
2347 ra_v,
2348 key,
2349 rc_v,
2350 false,
2351 Some(ra_idx),
2352 None,
2353 )?;
2354 trap = state.ci_trap(ci);
2355 }
2356 }
2357 }
2358 } else {
2359 state.set_ci_savedpc(ci, pc);
2360 state.set_top(state.ci_top(ci));
2361 finish_set(state, ra_v, key, rc_v, false, Some(ra_idx), None)?;
2362 trap = state.ci_trap(ci);
2363 }
2364 }
2365 OpCode::NewTable => {
2368 let ra = base + i.arg_a();
2369 let mut b = i.arg_b();
2370 let mut c = i.arg_c();
2371 if b > 0 {
2372 b = 1 << (b - 1);
2373 }
2374 if i.test_k() {
2375 let extra = code[pc as usize];
2376 pc += 1;
2377 const MAXARG_C: i32 = (1 << 8) - 1;
2378 c += extra.arg_ax() * (MAXARG_C + 1);
2379 } else {
2380 pc += 1; }
2382 state.set_top(ra + 1);
2383 let t = if b != 0 || c != 0 {
2384 state.new_table_with_sizes(c as u32, b as u32)?
2385 } else {
2386 state.new_table()
2387 };
2388 state.set_at(ra, LuaValue::Table(t.clone()));
2389 state.set_ci_savedpc(ci, pc);
2390 state.set_top(ra + 1);
2391 state.gc_cond_step();
2392 if state.hookmask != 0 {
2393 trap = state.ci_trap(ci);
2394 }
2395 }
2396 OpCode::Self_ => {
2398 let ra = base + i.arg_a();
2399 let rb_idx = base + i.arg_b();
2400 let rb_v = state.get_at(rb_idx);
2401 let k_idx = i.arg_c() as usize; let key = if i.test_k() {
2403 constants[k_idx]
2404 } else {
2405 state.get_at(base + i.arg_c())
2406 };
2407 state.set_at(ra + 1, rb_v.clone());
2408 match state.fast_get_short_str(&rb_v, &key)? {
2409 Some(v) => state.set_at(ra, v),
2410 None => {
2411 state.set_ci_savedpc(ci, pc);
2412 state.set_top(state.ci_top(ci));
2413 finish_get(state, rb_v, key, ra, true, Some(rb_idx), None)?;
2414 trap = state.ci_trap(ci);
2415 }
2416 }
2417 }
2418 OpCode::AddI => {
2420 let ra = base + i.arg_a();
2421 let rb = base + i.arg_b();
2422 let imm = i.arg_s_c() as i64;
2423 let rb_v = state.stack[rb.0 as usize].val;
2424 match rb_v {
2425 LuaValue::Int(iv1) => {
2426 pc += 1;
2427 state.stack[ra.0 as usize].val = LuaValue::Int(intop_add(iv1, imm));
2428 }
2429 LuaValue::Float(nb) => {
2430 pc += 1;
2431 state.stack[ra.0 as usize].val = LuaValue::Float(nb + imm as f64);
2432 }
2433 _ => {}
2434 }
2435 }
2436 OpCode::AddK => {
2438 let ra = base + i.arg_a();
2439 let rb = base + i.arg_b();
2440 let kidx = i.arg_c() as usize;
2441 if let (Some(i1), Some(i2)) =
2442 (state.get_int_at(rb), state.proto_const_int(&cl, kidx))
2443 {
2444 pc += 1;
2445 state.set_at(ra, LuaValue::Int(intop_add(i1, i2)));
2446 } else if let (Some(n1), Some(n2)) =
2447 (state.get_num_at(rb), state.proto_const_num(&cl, kidx))
2448 {
2449 pc += 1;
2450 state.set_at(ra, LuaValue::Float(n1 + n2));
2451 }
2452 }
2453 OpCode::SubK => {
2454 let ra = base + i.arg_a();
2455 let rb = base + i.arg_b();
2456 let kidx = i.arg_c() as usize;
2457 if let (Some(i1), Some(i2)) =
2458 (state.get_int_at(rb), state.proto_const_int(&cl, kidx))
2459 {
2460 pc += 1;
2461 state.set_at(ra, LuaValue::Int(intop_sub(i1, i2)));
2462 } else if let (Some(n1), Some(n2)) =
2463 (state.get_num_at(rb), state.proto_const_num(&cl, kidx))
2464 {
2465 pc += 1;
2466 state.set_at(ra, LuaValue::Float(n1 - n2));
2467 }
2468 }
2469 OpCode::MulK => {
2470 let ra = base + i.arg_a();
2471 let rb = base + i.arg_b();
2472 let kidx = i.arg_c() as usize;
2473 if let (Some(i1), Some(i2)) =
2474 (state.get_int_at(rb), state.proto_const_int(&cl, kidx))
2475 {
2476 pc += 1;
2477 state.set_at(ra, LuaValue::Int(intop_mul(i1, i2)));
2478 } else if let (Some(n1), Some(n2)) =
2479 (state.get_num_at(rb), state.proto_const_num(&cl, kidx))
2480 {
2481 pc += 1;
2482 state.set_at(ra, LuaValue::Float(n1 * n2));
2483 }
2484 }
2485 OpCode::ModK => {
2486 let ra = base + i.arg_a();
2487 let v1 = state.get_at(base + i.arg_b());
2488 let v2 = constants[i.arg_c() as usize];
2489 state.set_ci_savedpc(ci, pc); state.set_top(state.ci_top(ci));
2491 arith_op_checked(state, ra, &v1, &v2, &mut pc, |a, b| imod(a, b), fmodf)?;
2492 }
2493 OpCode::PowK => {
2494 let ra = base + i.arg_a();
2495 let rb = base + i.arg_b();
2496 let kidx = i.arg_c() as usize;
2497 if let (Some(n1), Some(n2)) =
2498 (state.get_num_at(rb), state.proto_const_num(&cl, kidx))
2499 {
2500 pc += 1;
2501 let r = if n2 == 2.0 { n1 * n1 } else { n1.powf(n2) };
2502 state.set_at(ra, LuaValue::Float(r));
2503 }
2504 }
2505 OpCode::DivK => {
2506 let ra = base + i.arg_a();
2507 let rb = base + i.arg_b();
2508 let kidx = i.arg_c() as usize;
2509 if let (Some(n1), Some(n2)) =
2510 (state.get_num_at(rb), state.proto_const_num(&cl, kidx))
2511 {
2512 pc += 1;
2513 state.set_at(ra, LuaValue::Float(n1 / n2));
2514 }
2515 }
2516 OpCode::IDivK => {
2517 let ra = base + i.arg_a();
2518 let v1 = state.get_at(base + i.arg_b());
2519 let v2 = constants[i.arg_c() as usize];
2520 state.set_ci_savedpc(ci, pc);
2521 state.set_top(state.ci_top(ci));
2522 arith_op_checked(
2523 state,
2524 ra,
2525 &v1,
2526 &v2,
2527 &mut pc,
2528 |a, b| idiv(a, b),
2529 |a, b| (a / b).floor(),
2530 )?;
2531 }
2532 OpCode::BAndK => {
2533 let ra = base + i.arg_a();
2534 let v1 = state.get_at(base + i.arg_b());
2535 let v2 = constants[i.arg_c() as usize];
2536 bitwise_op_k(state, ra, &v1, &v2, &mut pc, intop_band);
2537 }
2538 OpCode::BOrK => {
2539 let ra = base + i.arg_a();
2540 let v1 = state.get_at(base + i.arg_b());
2541 let v2 = constants[i.arg_c() as usize];
2542 bitwise_op_k(state, ra, &v1, &v2, &mut pc, intop_bor);
2543 }
2544 OpCode::BXOrK => {
2545 let ra = base + i.arg_a();
2546 let v1 = state.get_at(base + i.arg_b());
2547 let v2 = constants[i.arg_c() as usize];
2548 bitwise_op_k(state, ra, &v1, &v2, &mut pc, intop_bxor);
2549 }
2550 OpCode::ShrI => {
2551 let ra = base + i.arg_a();
2552 let v = state.get_at(base + i.arg_b());
2553 let ic = i.arg_s_c() as i64;
2554 if let Some(ib) = to_integer_ns(&v, F2Imod::Eq) {
2555 pc += 1;
2556 state.set_at(ra, LuaValue::Int(shiftl(ib, -ic)));
2557 }
2558 }
2559 OpCode::ShlI => {
2560 let ra = base + i.arg_a();
2561 let v = state.get_at(base + i.arg_b());
2562 let ic = i.arg_s_c() as i64;
2563 if let Some(ib) = to_integer_ns(&v, F2Imod::Eq) {
2564 pc += 1;
2565 state.set_at(ra, LuaValue::Int(shiftl(ic, ib)));
2566 }
2567 }
2568 OpCode::Add => {
2570 let ra = base + i.arg_a();
2571 let rb = base + i.arg_b();
2572 let rc = base + i.arg_c();
2573 let ra_u = ra.0 as usize;
2574 let rb_v = state.stack[rb.0 as usize].val;
2575 let rc_v = state.stack[rc.0 as usize].val;
2576 if let (LuaValue::Int(i1), LuaValue::Int(i2)) = (rb_v, rc_v) {
2577 pc += 1;
2578 state.stack[ra_u].val = LuaValue::Int(intop_add(i1, i2));
2579 } else if let (Some(n1), Some(n2)) =
2580 (number_value(rb_v), number_value(rc_v))
2581 {
2582 pc += 1;
2583 state.stack[ra_u].val = LuaValue::Float(n1 + n2);
2584 }
2585 }
2586 OpCode::Sub => {
2587 let ra = base + i.arg_a();
2588 let rb = base + i.arg_b();
2589 let rc = base + i.arg_c();
2590 let ra_u = ra.0 as usize;
2591 let rb_v = state.stack[rb.0 as usize].val;
2592 let rc_v = state.stack[rc.0 as usize].val;
2593 if let (LuaValue::Int(i1), LuaValue::Int(i2)) = (rb_v, rc_v) {
2594 pc += 1;
2595 state.stack[ra_u].val = LuaValue::Int(intop_sub(i1, i2));
2596 } else if let (Some(n1), Some(n2)) =
2597 (number_value(rb_v), number_value(rc_v))
2598 {
2599 pc += 1;
2600 state.stack[ra_u].val = LuaValue::Float(n1 - n2);
2601 }
2602 }
2603 OpCode::Mul => {
2604 let ra = base + i.arg_a();
2605 let rb = base + i.arg_b();
2606 let rc = base + i.arg_c();
2607 if let Some((i1, i2)) = state.get_int_pair_at(rb, rc) {
2608 pc += 1;
2609 state.set_at(ra, LuaValue::Int(intop_mul(i1, i2)));
2610 } else if let Some((n1, n2)) = state.get_num_pair_at(rb, rc) {
2611 pc += 1;
2612 state.set_at(ra, LuaValue::Float(n1 * n2));
2613 }
2614 }
2615 OpCode::Mod => {
2616 let ra = base + i.arg_a();
2617 let v1 = state.get_at(base + i.arg_b());
2618 let v2 = state.get_at(base + i.arg_c());
2619 state.set_ci_savedpc(ci, pc);
2620 state.set_top(state.ci_top(ci));
2621 arith_op_checked(state, ra, &v1, &v2, &mut pc, |a, b| imod(a, b), fmodf)?;
2622 }
2623 OpCode::Pow => {
2624 let ra = base + i.arg_a();
2625 let rb = base + i.arg_b();
2626 let rc = base + i.arg_c();
2627 if let Some((n1, n2)) = state.get_num_pair_at(rb, rc) {
2628 pc += 1;
2629 let r = if n2 == 2.0 { n1 * n1 } else { n1.powf(n2) };
2630 state.set_at(ra, LuaValue::Float(r));
2631 }
2632 }
2633 OpCode::Div => {
2634 let ra = base + i.arg_a();
2635 let rb = base + i.arg_b();
2636 let rc = base + i.arg_c();
2637 if let Some((n1, n2)) = state.get_num_pair_at(rb, rc) {
2638 pc += 1;
2639 state.set_at(ra, LuaValue::Float(n1 / n2));
2640 }
2641 }
2642 OpCode::IDiv => {
2643 let ra = base + i.arg_a();
2644 let v1 = state.get_at(base + i.arg_b());
2645 let v2 = state.get_at(base + i.arg_c());
2646 state.set_ci_savedpc(ci, pc);
2647 state.set_top(state.ci_top(ci));
2648 arith_op_checked(
2649 state,
2650 ra,
2651 &v1,
2652 &v2,
2653 &mut pc,
2654 |a, b| idiv(a, b),
2655 |a, b| (a / b).floor(),
2656 )?;
2657 }
2658 OpCode::BAnd => {
2661 let ra = base + i.arg_a();
2662 let v1 = state.get_at(base + i.arg_b());
2663 let v2 = state.get_at(base + i.arg_c());
2664 bitwise_op_rr(state, ra, &v1, &v2, &mut pc, intop_band);
2665 }
2666 OpCode::BOr => {
2667 let ra = base + i.arg_a();
2668 let v1 = state.get_at(base + i.arg_b());
2669 let v2 = state.get_at(base + i.arg_c());
2670 bitwise_op_rr(state, ra, &v1, &v2, &mut pc, intop_bor);
2671 }
2672 OpCode::BXOr => {
2673 let ra = base + i.arg_a();
2674 let v1 = state.get_at(base + i.arg_b());
2675 let v2 = state.get_at(base + i.arg_c());
2676 bitwise_op_rr(state, ra, &v1, &v2, &mut pc, intop_bxor);
2677 }
2678 OpCode::Shr => {
2679 let ra = base + i.arg_a();
2680 let v1 = state.get_at(base + i.arg_b());
2681 let v2 = state.get_at(base + i.arg_c());
2682 bitwise_shift_rr(state, ra, &v1, &v2, &mut pc, true);
2683 }
2684 OpCode::Shl => {
2685 let ra = base + i.arg_a();
2686 let v1 = state.get_at(base + i.arg_b());
2687 let v2 = state.get_at(base + i.arg_c());
2688 bitwise_shift_rr(state, ra, &v1, &v2, &mut pc, false);
2689 }
2690 OpCode::MmBin => {
2695 let ra_idx = base + i.arg_a();
2696 let rb_idx = base + i.arg_b();
2697 let ra_v = state.get_at(ra_idx);
2698 let rb_v = state.get_at(rb_idx);
2699 let tm = tagmethod_from_index(i.arg_c() as usize);
2700 let prev_inst = code[(pc - 2) as usize];
2701 let result_idx = base + prev_inst.arg_a();
2702 state.set_ci_savedpc(ci, pc);
2703 state.set_top(state.ci_top(ci));
2704 state.try_bin_tm(
2705 &ra_v,
2706 Some(ra_idx),
2707 &rb_v,
2708 Some(rb_idx),
2709 result_idx,
2710 tm,
2711 )?;
2712 trap = state.ci_trap(ci);
2713 }
2714 OpCode::MmBinI => {
2715 let ra_idx = base + i.arg_a();
2716 let ra_v = state.get_at(ra_idx);
2717 let imm = i.arg_s_b() as i64;
2718 let tm = tagmethod_from_index(i.arg_c() as usize);
2719 let flip = i.arg_k() != 0;
2720 let prev_inst = code[(pc - 2) as usize];
2721 let result_idx = base + prev_inst.arg_a();
2722 state.set_ci_savedpc(ci, pc);
2723 state.set_top(state.ci_top(ci));
2724 state.try_bin_i_tm(&ra_v, Some(ra_idx), imm, flip, result_idx, tm)?;
2725 trap = state.ci_trap(ci);
2726 }
2727 OpCode::MmBinK => {
2728 let ra_idx = base + i.arg_a();
2729 let ra_v = state.get_at(ra_idx);
2730 let imm = constants[i.arg_b() as usize];
2731 let tm = tagmethod_from_index(i.arg_c() as usize);
2732 let flip = i.arg_k() != 0;
2733 let prev_inst = code[(pc - 2) as usize];
2734 let result_idx = base + prev_inst.arg_a();
2735 state.set_ci_savedpc(ci, pc);
2736 state.set_top(state.ci_top(ci));
2737 state.try_bin_assoc_tm(
2738 &ra_v,
2739 Some(ra_idx),
2740 &imm,
2741 None,
2742 flip,
2743 result_idx,
2744 tm,
2745 )?;
2746 trap = state.ci_trap(ci);
2747 }
2748 OpCode::Unm => {
2752 let ra = base + i.arg_a();
2753 let rb_idx = base + i.arg_b();
2754 let rb_v = state.get_at(rb_idx);
2755 match &rb_v {
2756 LuaValue::Int(ib) => {
2757 state.set_at(ra, LuaValue::Int(intop_sub(0, *ib)));
2758 }
2759 LuaValue::Float(nb) => {
2760 state.set_at(ra, LuaValue::Float(-nb));
2761 }
2762 _ => {
2763 state.set_ci_savedpc(ci, pc);
2764 state.set_top(state.ci_top(ci));
2765 state.try_bin_tm(
2766 &rb_v,
2767 Some(rb_idx),
2768 &rb_v,
2769 Some(rb_idx),
2770 ra,
2771 TagMethod::Unm,
2772 )?;
2773 trap = state.ci_trap(ci);
2774 }
2775 }
2776 }
2777 OpCode::BNot => {
2779 let ra = base + i.arg_a();
2780 let rb_idx = base + i.arg_b();
2781 let rb_v = state.get_at(rb_idx);
2782 if let Some(ib) = to_integer_ns(&rb_v, F2Imod::Eq) {
2783 state.set_at(ra, LuaValue::Int(!ib));
2784 } else {
2785 state.set_ci_savedpc(ci, pc);
2786 state.set_top(state.ci_top(ci));
2787 state.try_bin_tm(
2788 &rb_v,
2789 Some(rb_idx),
2790 &rb_v,
2791 Some(rb_idx),
2792 ra,
2793 TagMethod::Bnot,
2794 )?;
2795 trap = state.ci_trap(ci);
2796 }
2797 }
2798 OpCode::Not => {
2800 let ra = base + i.arg_a();
2801 let rb_v = state.get_at(base + i.arg_b());
2802 let falsy = matches!(rb_v, LuaValue::Nil | LuaValue::Bool(false));
2803 state.set_at(ra, LuaValue::Bool(falsy));
2804 }
2805 OpCode::Len => {
2807 let ra = base + i.arg_a();
2808 let rb_idx = base + i.arg_b();
2809 let rb_v = state.get_at(rb_idx);
2810 state.set_ci_savedpc(ci, pc);
2811 state.set_top(state.ci_top(ci));
2812 obj_len(state, ra, rb_v, rb_idx)?;
2813 trap = state.ci_trap(ci);
2814 }
2815 OpCode::Concat => {
2817 let ra = base + i.arg_a();
2818 let n = i.arg_b() as i32;
2819 state.set_top(ra + n as i32);
2820 state.set_ci_savedpc(ci, pc); concat(state, n)?;
2822 let top = state.top_idx();
2823 state.set_ci_savedpc(ci, pc);
2824 state.set_top(top);
2825 state.gc_cond_step();
2826 trap = state.ci_trap(ci);
2827 }
2828 OpCode::Close => {
2830 let ra = base + i.arg_a();
2831 state.set_ci_savedpc(ci, pc);
2832 state.set_top(state.ci_top(ci));
2833 crate::func::close(
2834 state,
2835 ra,
2836 lua_types::status::LuaStatus::Ok as i32,
2837 true,
2838 )?;
2839 trap = state.ci_trap(ci);
2840 }
2841 OpCode::Tbc => {
2843 let ra = base + i.arg_a();
2844 state.set_ci_savedpc(ci, pc);
2845 state.set_top(state.ci_top(ci));
2846 state.new_tbc_upval(ra)?;
2847 }
2848 OpCode::Jmp => {
2850 pc = (pc as i64 + i.arg_s_j() as i64) as u32;
2851 trap = state.ci_trap(ci);
2852 }
2853 OpCode::Eq => {
2855 let ra_v = state.get_at(base + i.arg_a());
2856 let rb_v = state.get_at(base + i.arg_b());
2857 state.set_ci_savedpc(ci, pc);
2858 state.set_top(state.ci_top(ci));
2859 let cond = equal_obj(Some(state), &ra_v, &rb_v)? as u32;
2860 trap = state.ci_trap(ci);
2861 if (cond as i32) != i.arg_k() {
2862 pc += 1;
2863 } else {
2864 let next = code[pc as usize];
2865 pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
2866 trap = state.ci_trap(ci);
2867 }
2868 }
2869 OpCode::Lt => {
2871 let ra_v = state.get_at(base + i.arg_a());
2872 let rb_v = state.get_at(base + i.arg_b());
2873 let cond = if let (LuaValue::Int(ia), LuaValue::Int(ib)) = (&ra_v, &rb_v) {
2874 *ia < *ib
2875 } else if matches!(
2876 (&ra_v, &rb_v),
2877 (
2878 LuaValue::Int(_) | LuaValue::Float(_),
2879 LuaValue::Int(_) | LuaValue::Float(_)
2880 )
2881 ) {
2882 lt_num(&ra_v, &rb_v)
2883 } else {
2884 state.set_ci_savedpc(ci, pc);
2885 state.set_top(state.ci_top(ci));
2886 let r = less_than_others(state, &ra_v, &rb_v)?;
2887 trap = state.ci_trap(ci);
2888 r
2889 };
2890 if (cond as i32) != i.arg_k() {
2891 pc += 1;
2892 } else {
2893 let next = code[pc as usize];
2894 pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
2895 trap = state.ci_trap(ci);
2896 }
2897 }
2898 OpCode::Le => {
2900 let ra_v = state.get_at(base + i.arg_a());
2901 let rb_v = state.get_at(base + i.arg_b());
2902 let cond = if let (LuaValue::Int(ia), LuaValue::Int(ib)) = (&ra_v, &rb_v) {
2903 *ia <= *ib
2904 } else if matches!(
2905 (&ra_v, &rb_v),
2906 (
2907 LuaValue::Int(_) | LuaValue::Float(_),
2908 LuaValue::Int(_) | LuaValue::Float(_)
2909 )
2910 ) {
2911 le_num(&ra_v, &rb_v)
2912 } else {
2913 state.set_ci_savedpc(ci, pc);
2914 state.set_top(state.ci_top(ci));
2915 let r = less_equal_others(state, &ra_v, &rb_v)?;
2916 trap = state.ci_trap(ci);
2917 r
2918 };
2919 if (cond as i32) != i.arg_k() {
2920 pc += 1;
2921 } else {
2922 let next = code[pc as usize];
2923 pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
2924 trap = state.ci_trap(ci);
2925 }
2926 }
2927 OpCode::EqK => {
2929 let ra_v = state.get_at(base + i.arg_a());
2930 let rb_v = constants[i.arg_b() as usize];
2931 let cond = equal_obj(None, &ra_v, &rb_v)? as u32;
2932 if (cond as i32) != i.arg_k() {
2933 pc += 1;
2934 } else {
2935 let next = code[pc as usize];
2936 pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
2937 trap = state.ci_trap(ci);
2938 }
2939 }
2940 OpCode::EqI => {
2945 let ra_v = state.get_at(base + i.arg_a());
2946 let im = i.arg_s_b() as i64;
2947 let cond: bool = match &ra_v {
2948 LuaValue::Int(iv) => *iv == im,
2949 LuaValue::Float(fv) => *fv == im as f64,
2950 _ => false,
2951 };
2952 if (cond as i32) != i.arg_k() {
2953 pc += 1;
2954 } else {
2955 let next = code[pc as usize];
2956 pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
2957 trap = state.ci_trap(ci);
2958 }
2959 }
2960 OpCode::LtI => {
2963 let ra = base + i.arg_a();
2964 let im = i.arg_s_b() as i64;
2965 let fast_cond = match &state.stack[ra.0 as usize].val {
2966 LuaValue::Int(ia) => Some(*ia < im),
2967 LuaValue::Float(fa) => Some(*fa < im as f64),
2968 _ => None,
2969 };
2970 let cond = match fast_cond {
2971 Some(cond) => cond,
2972 None => order_imm_slow(
2973 state,
2974 ra,
2975 pc,
2976 &mut trap,
2977 ci,
2978 i,
2979 im,
2980 false,
2981 TagMethod::Lt,
2982 )?,
2983 };
2984 finish_order_imm_jump(state, code, &mut pc, &mut trap, ci, i, cond);
2985 }
2986 OpCode::LeI => {
2987 let ra = base + i.arg_a();
2988 let im = i.arg_s_b() as i64;
2989 let fast_cond = match &state.stack[ra.0 as usize].val {
2990 LuaValue::Int(ia) => Some(*ia <= im),
2991 LuaValue::Float(fa) => Some(*fa <= im as f64),
2992 _ => None,
2993 };
2994 let cond = match fast_cond {
2995 Some(cond) => cond,
2996 None => order_imm_slow(
2997 state,
2998 ra,
2999 pc,
3000 &mut trap,
3001 ci,
3002 i,
3003 im,
3004 false,
3005 TagMethod::Le,
3006 )?,
3007 };
3008 finish_order_imm_jump(state, code, &mut pc, &mut trap, ci, i, cond);
3009 }
3010 OpCode::GtI => {
3011 let ra = base + i.arg_a();
3012 let im = i.arg_s_b() as i64;
3013 let fast_cond = match &state.stack[ra.0 as usize].val {
3014 LuaValue::Int(ia) => Some(*ia > im),
3015 LuaValue::Float(fa) => Some(*fa > im as f64),
3016 _ => None,
3017 };
3018 let cond = match fast_cond {
3019 Some(cond) => cond,
3020 None => order_imm_slow(
3021 state,
3022 ra,
3023 pc,
3024 &mut trap,
3025 ci,
3026 i,
3027 im,
3028 true,
3029 TagMethod::Lt,
3030 )?,
3031 };
3032 finish_order_imm_jump(state, code, &mut pc, &mut trap, ci, i, cond);
3033 }
3034 OpCode::GeI => {
3035 let ra = base + i.arg_a();
3036 let im = i.arg_s_b() as i64;
3037 let fast_cond = match &state.stack[ra.0 as usize].val {
3038 LuaValue::Int(ia) => Some(*ia >= im),
3039 LuaValue::Float(fa) => Some(*fa >= im as f64),
3040 _ => None,
3041 };
3042 let cond = match fast_cond {
3043 Some(cond) => cond,
3044 None => order_imm_slow(
3045 state,
3046 ra,
3047 pc,
3048 &mut trap,
3049 ci,
3050 i,
3051 im,
3052 true,
3053 TagMethod::Le,
3054 )?,
3055 };
3056 finish_order_imm_jump(state, code, &mut pc, &mut trap, ci, i, cond);
3057 }
3058 OpCode::Test => {
3060 let ra_v = state.get_at(base + i.arg_a());
3061 let cond = !matches!(ra_v, LuaValue::Nil | LuaValue::Bool(false));
3062 if (cond as i32) != i.arg_k() {
3063 pc += 1;
3064 } else {
3065 let next = code[pc as usize];
3066 pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
3067 trap = state.ci_trap(ci);
3068 }
3069 }
3070 OpCode::TestSet => {
3073 let ra = base + i.arg_a();
3074 let rb_v = state.get_at(base + i.arg_b());
3075 let falsy = matches!(rb_v, LuaValue::Nil | LuaValue::Bool(false));
3076 if (falsy as i32) == i.arg_k() {
3077 pc += 1;
3078 } else {
3079 state.set_at(ra, rb_v);
3080 let next = code[pc as usize];
3081 pc = (pc as i64 + next.arg_s_j() as i64 + 1) as u32;
3082 trap = state.ci_trap(ci);
3083 }
3084 }
3085 OpCode::Call => {
3089 let ra = base + i.arg_a();
3090 let b = i.arg_b();
3091 let nresults = i.arg_c() as i32 - 1;
3092 if b != 0 {
3093 state.set_top(ra + b);
3094 }
3095 state.set_ci_savedpc(ci, pc); let had_hook = state.hookmask != 0;
3097 match state.precall(ra, nresults)? {
3098 None => {
3099 if had_hook || state.hookmask != 0 {
3103 trap = state.ci_trap(ci); }
3105 }
3106 Some(new_ci) => {
3107 ci = new_ci;
3109 continue 'startfunc;
3110 }
3111 }
3112 }
3113 OpCode::TailCall => {
3118 let ra = base + i.arg_a();
3119 let b = i.arg_b();
3120 let nparams1 = i.arg_c();
3121 let delta = if nparams1 != 0 {
3122 state.ci_nextraargs(ci) + nparams1 as i32
3123 } else {
3124 0
3125 };
3126 let top_b: i32 = if b != 0 {
3127 state.set_top(ra + b);
3128 b
3129 } else {
3130 state.top_idx() - ra
3131 };
3132 state.set_ci_savedpc(ci, pc);
3133 if i.test_k() {
3134 state.close_upvals_from_base(ci)?;
3135 }
3136 let n = state.pretailcall(ci, ra, top_b, delta)?;
3137 if n < 0 {
3138 state.note_lua_tailcall(ci);
3140 continue 'startfunc;
3141 } else {
3142 state.ci_adjust_func(ci, delta);
3144 state.poscall(ci, n as u32)?;
3145 if state.hookmask != 0 {
3146 trap = state.ci_trap(ci);
3147 }
3148 break 'dispatch; }
3150 }
3151 OpCode::Return => {
3156 let ra = base + i.arg_a();
3157 let n_raw = i.arg_b() as i32 - 1;
3158 let nparams1 = i.arg_c();
3159 let n: u32 = if n_raw < 0 {
3160 (state.top_idx() - ra) as u32
3161 } else {
3162 n_raw as u32
3163 };
3164 state.set_ci_savedpc(ci, pc);
3165 if i.test_k() {
3166 state.ci_nres_set(ci, n as i32);
3167 let ci_top = state.ci_top(ci);
3168 if state.top_idx().0 < ci_top.0 {
3169 state.set_top(ci_top);
3170 }
3171 crate::func::close(state, base, crate::func::CLOSE_K_TOP, true)?;
3172 if state.hookmask != 0 {
3173 trap = state.ci_trap(ci);
3174 }
3175 base = state.ci_base(ci); }
3177 if nparams1 != 0 {
3178 let nextraargs = state.ci_nextraargs(ci) as u32;
3179 state.ci_adjust_func(ci, nextraargs as i32 + nparams1 as i32);
3180 }
3181 state.set_top(ra + n as i32);
3182 state.poscall(ci, n)?;
3183 if state.hookmask != 0 {
3184 trap = state.ci_trap(ci);
3185 }
3186 break 'dispatch; }
3188 OpCode::Return0 => {
3194 if state.hookmask == 0 {
3195 let ci_slot = ci.as_usize();
3196 let nres = state.call_info[ci_slot].nresults as i32;
3197 state.ci = state.call_info[ci_slot]
3198 .previous
3199 .expect("RETURN0: returning frame has no previous CallInfo");
3200 state.top = base - 1;
3201 for _ in 0..nres.max(0) {
3202 state.push(LuaValue::Nil);
3203 }
3204 } else {
3205 return0_hook(state, ci, base, i, pc, &mut trap)?;
3206 }
3207 break 'dispatch; }
3209 OpCode::Return1 => {
3213 if state.hookmask == 0 {
3214 let ci_slot = ci.as_usize();
3215 let nres = state.call_info[ci_slot].nresults as i32;
3216 state.ci = state.call_info[ci_slot]
3217 .previous
3218 .expect("RETURN1: returning frame has no previous CallInfo");
3219 if nres == 0 {
3220 state.top = base - 1;
3221 } else {
3222 let ra = base + i.arg_a();
3223 state.stack[(base - 1).0 as usize].val =
3224 state.stack[ra.0 as usize].val; state.top = base;
3226 for _ in 1..nres.max(0) {
3227 state.push(LuaValue::Nil);
3228 }
3229 }
3230 } else {
3231 return1_hook(state, ci, base, i, pc, &mut trap)?;
3232 }
3233 break 'dispatch; }
3235 OpCode::ForLoop => {
3239 let ra = base + i.arg_a();
3240 if legacy_for {
3241 if forloop_legacy(state, ra) {
3242 pc = (pc as i64 - i.arg_bx() as i64) as u32;
3243 }
3244 if state.hookmask != 0 {
3245 trap = state.ci_trap(ci);
3246 }
3247 } else {
3248 let ra_u = ra.0 as usize;
3249 let window: &mut [crate::state::StackValue; 4] = (&mut state.stack
3250 [ra_u..ra_u + 4])
3251 .try_into()
3252 .expect("FORLOOP register window");
3253 if let LuaValue::Int(step) = window[2].val {
3254 let count = match window[1].val {
3255 LuaValue::Int(c) => c as u64,
3256 _ => 0,
3257 };
3258 if count > 0 {
3259 let idx = match window[0].val {
3260 LuaValue::Int(x) => x,
3261 _ => 0,
3262 };
3263 window[1].val = LuaValue::Int((count - 1) as i64);
3264 let new_idx = intop_add(idx, step);
3265 window[0].val = LuaValue::Int(new_idx);
3266 window[3].val = LuaValue::Int(new_idx);
3267 pc = (pc as i64 - i.arg_bx() as i64) as u32;
3268 }
3269 } else if float_for_loop(state, ra) {
3270 pc = (pc as i64 - i.arg_bx() as i64) as u32;
3271 }
3272 if state.hookmask != 0 {
3273 trap = state.ci_trap(ci);
3274 }
3275 }
3276 }
3277 OpCode::ForPrep => {
3279 let ra = base + i.arg_a();
3280 state.set_ci_savedpc(ci, pc);
3281 state.set_top(state.ci_top(ci));
3282 if legacy_for {
3283 forprep_legacy(state, ra)?;
3286 pc = (pc as i64 + i.arg_bx() as i64) as u32;
3287 } else if forprep(state, ra)? {
3288 pc = (pc as i64 + i.arg_bx() as i64 + 1) as u32;
3289 }
3290 }
3291 OpCode::TForPrep => {
3295 let ra = base + i.arg_a();
3296 state.set_ci_savedpc(ci, pc);
3297 state.set_top(state.ci_top(ci));
3298 if tfor_55 {
3299 let closing = state.get_at(ra + 3);
3300 let control = state.get_at(ra + 2);
3301 state.set_at(ra + 2, closing);
3302 state.set_at(ra + 3, control);
3303 state.new_tbc_upval(ra + 2)?;
3304 } else {
3305 state.new_tbc_upval(ra + 3)?;
3306 }
3307 pc = (pc as i64 + i.arg_bx() as i64) as u32;
3308 let tfc_i = code[pc as usize];
3309 pc += 1;
3310 debug_assert!(tfc_i.opcode() == OpCode::TForCall);
3311 let tfc_ra = base + tfc_i.arg_a();
3313 if tfor_55 {
3314 let src = tfc_ra.0 as usize;
3315 let func = state.stack[src].val.clone();
3316 let state_val = state.stack[src + 1].val.clone();
3317 let control = state.stack[src + 3].val.clone();
3318 state.stack[src + 3].val = func;
3319 state.stack[src + 4].val = state_val;
3320 state.stack[src + 5].val = control;
3321 state.set_top(tfc_ra + 6);
3322 state.set_ci_savedpc(ci, pc);
3323 if !state.call_known_c_at(tfc_ra + 3, tfc_i.arg_c() as i32)? {
3324 state.call_at(tfc_ra + 3, tfc_i.arg_c() as i32)?;
3325 }
3326 } else {
3327 let src = tfc_ra.0 as usize;
3328 let dst = src + 4;
3329 for k in 0..3usize {
3330 state.stack[dst + k].val = state.stack[src + k].val.clone();
3331 }
3332 state.set_top(tfc_ra + 4 + 3);
3333 state.set_ci_savedpc(ci, pc);
3334 if !state.call_known_c_at(tfc_ra + 4, tfc_i.arg_c() as i32)? {
3335 state.call_at(tfc_ra + 4, tfc_i.arg_c() as i32)?;
3336 }
3337 }
3338 trap = state.ci_trap(ci);
3339 base = state.ci_base(ci); let tfl_i = code[pc as usize];
3341 pc += 1;
3342 debug_assert!(tfl_i.opcode() == OpCode::TForLoop);
3343 let tfl_ra = base + tfl_i.arg_a();
3344 if tfor_55 {
3346 if !matches!(state.get_at(tfl_ra + 3), LuaValue::Nil) {
3347 pc = (pc as i64 - tfl_i.arg_bx() as i64) as u32;
3348 }
3349 } else if !matches!(state.get_at(tfl_ra + 4), LuaValue::Nil) {
3350 let v = state.get_at(tfl_ra + 4);
3351 state.set_at(tfl_ra + 2, v);
3352 pc = (pc as i64 - tfl_i.arg_bx() as i64) as u32;
3353 }
3354 }
3355 OpCode::TForCall => {
3357 let ra = base + i.arg_a();
3358 if tfor_55 {
3359 let src = ra.0 as usize;
3360 let func = state.stack[src].val.clone();
3361 let state_val = state.stack[src + 1].val.clone();
3362 let control = state.stack[src + 3].val.clone();
3363 state.stack[src + 3].val = func;
3364 state.stack[src + 4].val = state_val;
3365 state.stack[src + 5].val = control;
3366 state.set_top(ra + 6);
3367 state.set_ci_savedpc(ci, pc);
3368 if !state.call_known_c_at(ra + 3, i.arg_c() as i32)? {
3369 state.call_at(ra + 3, i.arg_c() as i32)?;
3370 }
3371 } else {
3372 let src = ra.0 as usize;
3373 let dst = src + 4;
3374 for k in 0..3usize {
3375 state.stack[dst + k].val = state.stack[src + k].val.clone();
3376 }
3377 state.set_top(ra + 4 + 3);
3378 state.set_ci_savedpc(ci, pc);
3379 if !state.call_known_c_at(ra + 4, i.arg_c() as i32)? {
3380 state.call_at(ra + 4, i.arg_c() as i32)?;
3381 }
3382 }
3383 trap = state.ci_trap(ci);
3384 base = state.ci_base(ci); let tfl_i = code[pc as usize];
3386 pc += 1;
3387 debug_assert!(tfl_i.opcode() == OpCode::TForLoop);
3388 let tfl_ra = base + tfl_i.arg_a();
3389 if tfor_55 {
3390 if !matches!(state.get_at(tfl_ra + 3), LuaValue::Nil) {
3391 pc = (pc as i64 - tfl_i.arg_bx() as i64) as u32;
3392 }
3393 } else if !matches!(state.get_at(tfl_ra + 4), LuaValue::Nil) {
3394 let v = state.get_at(tfl_ra + 4);
3395 state.set_at(tfl_ra + 2, v);
3396 pc = (pc as i64 - tfl_i.arg_bx() as i64) as u32;
3397 }
3398 }
3399 OpCode::TForLoop => {
3401 let ra = base + i.arg_a();
3402 if tfor_55 {
3403 if !matches!(state.get_at(ra + 3), LuaValue::Nil) {
3404 pc = (pc as i64 - i.arg_bx() as i64) as u32;
3405 }
3406 } else if !matches!(state.get_at(ra + 4), LuaValue::Nil) {
3407 let v = state.get_at(ra + 4);
3408 state.set_at(ra + 2, v);
3409 pc = (pc as i64 - i.arg_bx() as i64) as u32;
3410 }
3411 }
3412 OpCode::SetList => {
3416 let ra = base + i.arg_a();
3417 let n_raw = i.arg_b();
3418 let mut last = i.arg_c();
3419 let t_val = state.get_at(ra);
3420 let n: i32 = if n_raw == 0 {
3421 state.top_idx() - ra - 1
3422 } else {
3423 state.set_top(state.ci_top(ci));
3424 n_raw
3425 };
3426 last += n;
3427 if i.test_k() {
3428 let extra = code[pc as usize];
3429 pc += 1;
3430 const MAXARG_C: i32 = (1 << 8) - 1;
3431 last += extra.arg_ax() * (MAXARG_C + 1);
3432 }
3433 state.table_ensure_array(&t_val, last as usize)?;
3434 for k in (1..=n).rev() {
3435 let val = state.get_at(ra + k as i32);
3436 state.table_array_set(&t_val, (last - 1) as usize, val.clone())?;
3437 last -= 1;
3438 state.gc_value_barrier_back(&t_val, &val);
3439 }
3440 }
3441 OpCode::Closure => {
3445 let ra = base + i.arg_a();
3446 let proto_idx = i.arg_bx() as usize;
3447 state.set_ci_savedpc(ci, pc);
3448 state.set_top(state.ci_top(ci));
3449 push_closure(state, proto_idx, ci, base, ra)?;
3450 state.set_ci_savedpc(ci, pc);
3452 state.set_top(ra + 1);
3453 state.gc_cond_step();
3454 trap = state.ci_trap(ci);
3455 }
3456 OpCode::VarArg => {
3458 let ra = base + i.arg_a();
3459 let n = i.arg_c() as i32 - 1;
3460 state.set_ci_savedpc(ci, pc);
3461 state.set_top(state.ci_top(ci));
3462 state.get_varargs(ci, ra, n)?;
3463 trap = state.ci_trap(ci);
3464 }
3465 OpCode::VarArgPrep => {
3469 let nparams = i.arg_a();
3470 state.set_ci_savedpc(ci, pc);
3471 state.adjust_varargs(ci, nparams, &cl)?;
3472 trap = state.ci_trap(ci);
3473 if trap {
3474 state.hook_call(ci)?;
3475 state.set_oldpc(1);
3476 }
3477 base = state.ci_base(ci);
3478 }
3479 OpCode::GetVArg => {
3481 let ra = base + i.arg_a();
3482 let vararg_reg = base + i.arg_b();
3483 let key = state.get_at(base + i.arg_c()).clone();
3484 let val = if let LuaValue::Table(t) = state.get_at(vararg_reg) {
3485 t.get(&key)
3486 } else {
3487 let nextra = state.ci_nextraargs(ci);
3488 match key {
3489 LuaValue::Int(n) if n >= 1 && n <= nextra as i64 => {
3490 let ci_func = state.ci_base(ci) - 1;
3491 state.get_at(ci_func - nextra + n as i32 - 1)
3492 }
3493 LuaValue::Float(f)
3494 if f.is_finite()
3495 && f.fract() == 0.0
3496 && f >= 1.0
3497 && f <= nextra as f64 =>
3498 {
3499 let ci_func = state.ci_base(ci) - 1;
3500 state.get_at(ci_func - nextra + f as i32 - 1)
3501 }
3502 LuaValue::Str(s) if s.as_bytes() == b"n" => {
3503 LuaValue::Int(nextra as i64)
3504 }
3505 _ => LuaValue::Nil,
3506 }
3507 };
3508 state.set_at(ra, val);
3509 }
3510 OpCode::ExtraArg => {
3512 debug_assert!(false, "OP_EXTRAARG executed directly");
3513 }
3514 OpCode::ErrNNil => {
3519 let ra = base + i.arg_a();
3520 if !matches!(state.get_at(ra), LuaValue::Nil) {
3521 let bx = i.arg_bx();
3522 let name: Vec<u8> = if bx == 0 {
3523 b"?".to_vec()
3524 } else {
3525 match constants[(bx - 1) as usize] {
3526 LuaValue::Str(s) => s.as_bytes().to_vec(),
3527 _ => b"?".to_vec(),
3528 }
3529 };
3530 let mut msg = Vec::with_capacity(name.len() + 24);
3531 msg.extend_from_slice(b"global '");
3532 msg.extend_from_slice(&name);
3533 msg.extend_from_slice(b"' already defined");
3534 state.set_ci_savedpc(ci, pc);
3535 return Err(crate::debug::prefixed_runtime_pub(state, msg));
3536 }
3537 }
3538 OpCode::VarArgPack => {
3546 if !cl.proto.vararg_table_needed && !i.test_k() {
3547 state.set_ci_savedpc(ci, pc);
3548 continue;
3549 }
3550 let ra = base + i.arg_a();
3551 let nextra = state.ci_nextraargs(ci);
3552 let ci_func: StackIdx = state.ci_base(ci) - 1;
3553 let t = if nextra > 0 {
3554 state.new_table_with_sizes(nextra as u32, 1)?
3555 } else {
3556 state.new_table()
3557 };
3558 for k in 0..nextra {
3559 let src: StackIdx = ci_func - nextra as i32 + k as i32;
3560 let val = state.get_at(src);
3561 t.raw_set_int(state, (k + 1) as i64, val)?;
3562 }
3563 let n_key = state.intern_str(b"n")?;
3564 t.raw_set(state, LuaValue::Str(n_key), LuaValue::Int(nextra as i64))?;
3565 state.set_at(ra, LuaValue::Table(t));
3566 state.set_ci_savedpc(ci, pc);
3567 state.set_top(ra + 1);
3568 state.gc_cond_step();
3569 if state.hookmask != 0 {
3570 trap = state.ci_trap(ci);
3571 }
3572 }
3573 } } if state.ci_is_fresh(ci) {
3578 return Ok(());
3579 } else {
3580 ci = state
3581 .ci_previous(ci)
3582 .expect("ci_previous: not fresh frame must have previous");
3583 continue 'returning;
3584 }
3585 } } }
3588
3589#[inline(always)]
3592fn number_value(v: LuaValue) -> Option<f64> {
3593 match v {
3594 LuaValue::Float(f) => Some(f),
3595 LuaValue::Int(i) => Some(i as f64),
3596 _ => None,
3597 }
3598}
3599
3600#[allow(dead_code)]
3602#[inline]
3603fn arith_op_aux_rr(
3604 state: &mut LuaState,
3605 ra: StackIdx,
3606 v1: &LuaValue,
3607 v2: &LuaValue,
3608 pc: &mut u32,
3609 iop: fn(i64, i64) -> i64,
3610 fop: fn(f64, f64) -> f64,
3611) {
3612 if let (LuaValue::Int(i1), LuaValue::Int(i2)) = (v1, v2) {
3613 *pc += 1;
3614 state.set_at(ra, LuaValue::Int(iop(*i1, *i2)));
3615 } else {
3616 arith_float_aux(state, ra, v1, v2, pc, fop);
3617 }
3618}
3619
3620#[allow(dead_code)]
3621#[inline]
3622fn arith_float_aux(
3623 state: &mut LuaState,
3624 ra: StackIdx,
3625 v1: &LuaValue,
3626 v2: &LuaValue,
3627 pc: &mut u32,
3628 fop: fn(f64, f64) -> f64,
3629) {
3630 let n1 = match v1 {
3631 LuaValue::Float(f) => Some(*f),
3632 LuaValue::Int(i) => Some(*i as f64),
3633 _ => None,
3634 };
3635 let n2 = match v2 {
3636 LuaValue::Float(f) => Some(*f),
3637 LuaValue::Int(i) => Some(*i as f64),
3638 _ => None,
3639 };
3640 if let (Some(n1), Some(n2)) = (n1, n2) {
3641 *pc += 1;
3642 state.set_at(ra, LuaValue::Float(fop(n1, n2)));
3643 }
3644}
3645
3646#[allow(dead_code)]
3647#[inline]
3648fn arith_op_checked(
3649 state: &mut LuaState,
3650 ra: StackIdx,
3651 v1: &LuaValue,
3652 v2: &LuaValue,
3653 pc: &mut u32,
3654 iop: fn(i64, i64) -> Result<i64, LuaError>,
3655 fop: fn(f64, f64) -> f64,
3656) -> Result<(), LuaError> {
3657 if let (LuaValue::Int(i1), LuaValue::Int(i2)) = (v1, v2) {
3658 *pc += 1;
3659 let result = iop(*i1, *i2).map_err(|e| match e {
3660 LuaError::Runtime(LuaValue::Str(s)) => {
3661 crate::debug::prefixed_runtime_pub(state, s.as_bytes().to_vec())
3662 }
3663 LuaError::RuntimeMsg(b) => crate::debug::prefixed_runtime_pub(state, b.into_vec()),
3664 other => other,
3665 })?;
3666 state.set_at(ra, LuaValue::Int(result));
3667 } else {
3668 arith_float_aux(state, ra, v1, v2, pc, fop);
3669 }
3670 Ok(())
3671}
3672
3673#[allow(dead_code)]
3674#[inline]
3675fn bitwise_op_k(
3676 state: &mut LuaState,
3677 ra: StackIdx,
3678 v1: &LuaValue,
3679 v2: &LuaValue, pc: &mut u32,
3681 op: fn(i64, i64) -> i64,
3682) {
3683 let i2 = match v2 {
3684 LuaValue::Int(i) => *i,
3685 _ => return,
3686 };
3687 if let Some(i1) = to_integer_ns(v1, F2Imod::Eq) {
3688 *pc += 1;
3689 state.set_at(ra, LuaValue::Int(op(i1, i2)));
3690 }
3691}
3692
3693#[allow(dead_code)]
3694#[inline]
3695fn bitwise_op_rr(
3696 state: &mut LuaState,
3697 ra: StackIdx,
3698 v1: &LuaValue,
3699 v2: &LuaValue,
3700 pc: &mut u32,
3701 op: fn(i64, i64) -> i64,
3702) {
3703 if let (Some(i1), Some(i2)) = (to_integer_ns(v1, F2Imod::Eq), to_integer_ns(v2, F2Imod::Eq)) {
3704 *pc += 1;
3705 state.set_at(ra, LuaValue::Int(op(i1, i2)));
3706 }
3707}
3708
3709#[allow(dead_code)]
3711#[inline]
3712fn bitwise_shift_rr(
3713 state: &mut LuaState,
3714 ra: StackIdx,
3715 v1: &LuaValue,
3716 v2: &LuaValue,
3717 pc: &mut u32,
3718 right: bool,
3719) {
3720 if let (Some(i1), Some(i2)) = (to_integer_ns(v1, F2Imod::Eq), to_integer_ns(v2, F2Imod::Eq)) {
3721 let y = if right { intop_sub(0, i2) } else { i2 };
3722 *pc += 1;
3723 state.set_at(ra, LuaValue::Int(shiftl(i1, y)));
3724 }
3725}
3726
3727#[cold]
3730#[inline(never)]
3731#[allow(clippy::too_many_arguments)]
3732fn order_imm_slow(
3733 state: &mut LuaState,
3734 ra: StackIdx,
3735 pc: u32,
3736 trap: &mut bool,
3737 ci: CallInfoIdx,
3738 i: Instruction,
3739 im: i64,
3740 inv: bool,
3741 tm: TagMethod,
3742) -> Result<bool, LuaError> {
3743 let ra_v = state.get_at(ra);
3744 let isf = i.arg_c() != 0;
3745 state.set_ci_savedpc(ci, pc);
3746 state.set_top(state.ci_top(ci));
3747 let r = state.call_order_i_tm(&ra_v, im, inv, isf, tm)?;
3748 *trap = state.ci_trap(ci);
3749 Ok(r)
3750}
3751
3752#[inline(always)]
3753fn finish_order_imm_jump(
3754 state: &mut LuaState,
3755 code: &[Instruction],
3756 pc: &mut u32,
3757 trap: &mut bool,
3758 ci: CallInfoIdx,
3759 i: Instruction,
3760 cond: bool,
3761) {
3762 if (cond as i32) != i.arg_k() {
3763 *pc += 1;
3764 } else {
3765 let next = code[*pc as usize];
3766 *pc = (*pc as i64 + next.arg_s_j() as i64 + 1) as u32;
3767 if state.hookmask != 0 {
3768 *trap = state.ci_trap(ci);
3769 }
3770 }
3771}
3772
3773#[cold]
3774#[inline(never)]
3775fn return0_hook(
3776 state: &mut LuaState,
3777 ci: CallInfoIdx,
3778 base: StackIdx,
3779 i: Instruction,
3780 pc: u32,
3781 trap: &mut bool,
3782) -> Result<(), LuaError> {
3783 let ra = base + i.arg_a();
3784 state.set_top(ra);
3785 state.set_ci_savedpc(ci, pc);
3786 state.poscall(ci, 0)?;
3787 *trap = true;
3788 Ok(())
3789}
3790
3791#[cold]
3792#[inline(never)]
3793fn return1_hook(
3794 state: &mut LuaState,
3795 ci: CallInfoIdx,
3796 base: StackIdx,
3797 i: Instruction,
3798 pc: u32,
3799 trap: &mut bool,
3800) -> Result<(), LuaError> {
3801 let ra = base + i.arg_a();
3802 state.set_top(ra + 1);
3803 state.set_ci_savedpc(ci, pc);
3804 state.poscall(ci, 1)?;
3805 *trap = true;
3806 Ok(())
3807}