1use lua_types::{AbsLineInfo, GcRef, LocalVar, LuaError, LuaProto, LuaString, LuaValue, UpvalDesc};
24
25pub type TokenKind = i32;
33pub const TK_AND: TokenKind = 257;
34pub const TK_BREAK: TokenKind = 258;
35pub const TK_DO: TokenKind = 259;
36pub const TK_ELSE: TokenKind = 260;
37pub const TK_ELSEIF: TokenKind = 261;
38pub const TK_END: TokenKind = 262;
39pub const TK_FALSE: TokenKind = 263;
40pub const TK_FOR: TokenKind = 264;
41pub const TK_FUNCTION: TokenKind = 265;
42pub const TK_GOTO: TokenKind = 266;
43pub const TK_IF: TokenKind = 267;
44pub const TK_IN: TokenKind = 268;
45pub const TK_LOCAL: TokenKind = 269;
46pub const TK_NIL: TokenKind = 270;
47pub const TK_NOT: TokenKind = 271;
48pub const TK_OR: TokenKind = 272;
49pub const TK_REPEAT: TokenKind = 273;
50pub const TK_RETURN: TokenKind = 274;
51pub const TK_THEN: TokenKind = 275;
52pub const TK_TRUE: TokenKind = 276;
53pub const TK_UNTIL: TokenKind = 277;
54pub const TK_WHILE: TokenKind = 278;
55pub const TK_IDIV: TokenKind = 279;
56pub const TK_CONCAT: TokenKind = 280;
57pub const TK_DOTS: TokenKind = 281;
58pub const TK_EQ: TokenKind = 282;
59pub const TK_GE: TokenKind = 283;
60pub const TK_LE: TokenKind = 284;
61pub const TK_NE: TokenKind = 285;
62pub const TK_SHL: TokenKind = 286;
63pub const TK_SHR: TokenKind = 287;
64pub const TK_DBCOLON: TokenKind = 288;
65pub const TK_EOS: TokenKind = 289;
66pub const TK_FLT: TokenKind = 290;
67pub const TK_INT: TokenKind = 291;
68pub const TK_NAME: TokenKind = 292;
69pub const TK_STRING: TokenKind = 293;
70
71const MAX_VARS: i32 = 200;
74
75const NO_JUMP: i32 = -1;
76
77const UNARY_PRIORITY: i32 = 12;
78
79const LUA_MULTRET: i32 = -1;
80
81const MAX_UPVAL: u8 = 255;
82
83const MAXARG_BX: i32 = (1 << 17) - 1;
85
86const LFIELDS_PER_FLUSH: i32 = 50;
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92#[repr(u8)]
93pub enum VarKind {
94 Reg = 0,
95 Const = 1,
96 ToBeClosed = 2,
97 CompileTimeConst = 3,
98 VarArg = 4,
99}
100
101impl VarKind {
102 pub fn from_u8(v: u8) -> Self {
103 match v {
104 0 => VarKind::Reg,
105 1 => VarKind::Const,
106 2 => VarKind::ToBeClosed,
107 3 => VarKind::CompileTimeConst,
108 4 => VarKind::VarArg,
109 _ => VarKind::Reg,
110 }
111 }
112 pub fn as_u8(self) -> u8 {
113 self as u8
114 }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum ExprKind {
122 Void, Nil, True, False, K, KFlt, KInt, KStr, NonReloc, Local, UpVal, Const, Indexed, IndexUp, IndexI, IndexStr, VarArgVar, VarArgIndex, Jmp, Reloc, Call, VarArg, }
145
146impl ExprKind {
147 #[inline]
148 pub fn has_mult_ret(self) -> bool {
149 matches!(self, ExprKind::Call | ExprKind::VarArg)
150 }
151
152 #[inline]
153 pub fn is_var(self) -> bool {
154 matches!(
155 self,
156 ExprKind::Local
157 | ExprKind::UpVal
158 | ExprKind::Const
159 | ExprKind::Indexed
160 | ExprKind::IndexUp
161 | ExprKind::IndexI
162 | ExprKind::IndexStr
163 | ExprKind::VarArgVar
164 | ExprKind::VarArgIndex
165 )
166 }
167
168 #[inline]
169 pub fn is_indexed(self) -> bool {
170 matches!(
171 self,
172 ExprKind::Indexed
173 | ExprKind::IndexUp
174 | ExprKind::IndexI
175 | ExprKind::IndexStr
176 | ExprKind::VarArgIndex
177 )
178 }
179}
180
181#[derive(Debug, Clone, Default)]
186pub struct ExprPayload {
187 pub ival: i64,
188 pub nval: f64,
189 pub strval: Option<GcRef<LuaString>>,
190 pub info: i32,
191 pub ind_idx: i16,
192 pub ind_t: u8,
193 pub var_ridx: u8,
194 pub var_vidx: u16,
195 pub global_const_name: Option<GcRef<LuaString>>,
200}
201
202#[derive(Debug, Clone)]
206pub struct ExprDesc {
207 pub k: ExprKind,
208 pub u: ExprPayload,
209 pub t: i32,
210 pub f: i32,
211}
212
213impl Default for ExprDesc {
214 fn default() -> Self {
215 ExprDesc {
216 k: ExprKind::Void,
217 u: ExprPayload::default(),
218 t: NO_JUMP,
219 f: NO_JUMP,
220 }
221 }
222}
223
224#[derive(Debug, Clone)]
230pub struct VarDesc {
231 pub kind: VarKind,
232 pub ridx: u8,
233 pub pidx: i16,
234 pub name: Option<GcRef<LuaString>>,
235 pub const_val: LuaValue,
236}
237
238impl Default for VarDesc {
239 fn default() -> Self {
240 VarDesc {
241 kind: VarKind::Reg,
242 ridx: 0,
243 pidx: 0,
244 name: None,
245 const_val: LuaValue::Nil,
246 }
247 }
248}
249
250#[derive(Debug, Clone)]
253pub struct LabelDesc {
254 pub name: Option<GcRef<LuaString>>,
255 pub pc: i32,
256 pub line: i32,
257 pub nactvar: u8,
258 pub close: bool,
259}
260
261#[derive(Debug, Clone)]
262pub struct ScopeBarrier {
263 pub level: u8,
264 pub name: GcRef<LuaString>,
265}
266
267#[derive(Debug, Default)]
271pub struct DynData {
272 pub actvar: Vec<VarDesc>,
273 pub gt: Vec<LabelDesc>,
274 pub label: Vec<LabelDesc>,
275}
276
277#[derive(Debug)]
282pub struct BlockCnt {
283 pub previous: Option<Box<BlockCnt>>,
284 pub firstlabel: i32,
285 pub firstgoto: i32,
286 pub nactvar: u8,
287 pub scope_level: u8,
288 pub upval: bool,
289 pub isloop: bool,
290 pub insidetbc: bool,
291 pub saved_global_strict: bool,
296 pub saved_declared_globals: usize,
297 pub saved_global_wildcard: bool,
300 pub saved_global_wildcard_const: bool,
301 pub saved_scope_barriers: usize,
302}
303
304#[derive(Debug)]
309pub struct FuncState {
310 pub f: Box<LuaProto>,
314 pub prev: Option<Box<FuncState>>,
315 pub bl: Option<Box<BlockCnt>>,
316 pub pc: i32,
317 pub lasttarget: i32,
318 pub previousline: i32,
319 pub nk: i32,
320 pub np: i32,
321 pub nabslineinfo: i32,
322 pub firstlocal: i32,
323 pub firstlabel: i32,
324 pub ndebugvars: i16,
325 pub nactvar: u8,
326 pub first_scope_barrier: usize,
327 pub nups: u8,
328 pub freereg: u8,
329 pub iwthabs: u8,
330 pub needclose: bool,
331 pub last_token_line: i32,
337}
338
339#[derive(Debug)]
345pub struct ConsControl {
346 pub v: ExprDesc,
347 pub t: ExprDesc,
348 pub nh: i32,
349 pub na: i32,
350 pub tostore: i32,
351}
352
353#[derive(Debug)]
357pub struct LhsAssign {
358 pub prev: Option<Box<LhsAssign>>,
359 pub v: ExprDesc,
360}
361
362#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366pub enum UnOpr {
367 Minus, BNot, Not, Len, NoUnOpr, }
373
374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
375pub enum BinOpr {
376 Add, Sub, Mul, Mod, Pow, Div, IDiv, BAnd, BOr, BXor, Shl, Shr, Concat, Eq, Lt, Le, Ne, Gt, Ge, And, Or, NoBinOpr, }
399
400const PRIORITY: [(u8, u8); 21] = [
402 (10, 10),
403 (10, 10), (11, 11),
405 (11, 11), (14, 13), (11, 11),
408 (11, 11), (6, 6),
410 (4, 4),
411 (5, 5), (7, 7),
413 (7, 7), (9, 8), (3, 3),
416 (3, 3),
417 (3, 3), (3, 3),
419 (3, 3),
420 (3, 3), (2, 2),
422 (1, 1), ];
424
425pub use lua_code::opcodes::OpCode;
427
428#[derive(Debug, Clone, Default)]
435pub struct TokenValue {
436 pub r: f64,
437 pub i: i64,
438 pub ts: Option<GcRef<LuaString>>,
439}
440
441#[derive(Debug, Clone, Default)]
442pub struct LexToken {
443 pub token: TokenKind,
444 pub seminfo: TokenValue,
445}
446
447pub struct LexState {
452 pub current: i32,
453 pub linenumber: i32,
454 pub lastline: i32,
455 pub t: LexToken,
456 pub lookahead: LexToken,
457 pub fs: Option<Box<FuncState>>,
458 pub dyd: DynData,
459 pub source: Option<GcRef<LuaString>>,
460 pub envn: Option<GcRef<LuaString>>,
461 pub lex: lua_lex::LexState,
466 pub recursion_depth: u32,
468 pub global_strict: bool,
476 pub global_wildcard: bool,
484 pub global_wildcard_const: bool,
488 pub declared_globals: Vec<(GcRef<LuaString>, bool)>,
492 pub scope_barriers: Vec<ScopeBarrier>,
496 pub global_function_names: Vec<GcRef<LuaString>>,
497}
498
499const PARSER_MAX_C_CALLS: u32 = 200;
500
501fn enter_level(ls: &mut LexState) -> Result<(), LuaError> {
502 ls.recursion_depth += 1;
503 if ls.recursion_depth >= PARSER_MAX_C_CALLS {
504 Err(LuaError::syntax(format_args!("C stack overflow")))
505 } else {
506 Ok(())
507 }
508}
509
510fn leave_level(ls: &mut LexState) {
511 ls.recursion_depth = ls.recursion_depth.saturating_sub(1);
512}
513
514fn lex_next(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
518 lua_lex::next(state, &mut ls.lex)?;
519 sync_from_lex(ls);
520 Ok(())
521}
522
523fn lex_lookahead(ls: &mut LexState, state: &mut LuaState) -> Result<TokenKind, LuaError> {
526 let kind = lua_lex::lookahead(state, &mut ls.lex)?;
527 sync_from_lex(ls);
528 Ok(kind)
529}
530
531fn sync_from_lex(ls: &mut LexState) {
534 ls.current = ls.lex.current;
535 ls.linenumber = ls.lex.linenumber;
536 ls.lastline = ls.lex.lastline;
537 ls.t = LexToken {
538 token: ls.lex.t.kind,
539 seminfo: local_token_value(&ls.lex.t.value),
540 };
541 ls.lookahead = LexToken {
542 token: ls.lex.lookahead.kind,
543 seminfo: local_token_value(&ls.lex.lookahead.value),
544 };
545 if let Some(fs) = ls.fs.as_mut() {
549 fs.last_token_line = ls.lastline;
550 }
551}
552
553pub use lua_vm::state::LuaState;
555
556fn emit_inst(fs: &mut FuncState, line: i32, inst: lua_code::opcodes::Instruction) -> i32 {
572 const MAX_IWTH_ABS: i32 = 128;
573 const LIM_LINE_DIFF: i32 = 0x80;
574 const ABS_LINE_INFO: i8 = -0x80i8;
575 let pc = fs.pc as usize;
576 if fs.f.code.len() <= pc {
577 fs.f.code
578 .resize(pc + 1, lua_types::opcode::Instruction::default());
579 }
580 fs.f.code[pc] = lua_types::opcode::Instruction::new(inst.0);
581 if fs.f.lineinfo.len() <= pc {
582 fs.f.lineinfo.resize(pc + 1, 0i8);
583 }
584 let linedif_raw = line - fs.previousline;
585 let need_abs = linedif_raw.abs() >= LIM_LINE_DIFF || {
586 let over = fs.iwthabs as i32 >= MAX_IWTH_ABS;
587 if !over {
588 fs.iwthabs += 1;
589 }
590 over
591 };
592 if need_abs {
593 fs.f.abslineinfo.push(AbsLineInfo {
594 pc: pc as i32,
595 line,
596 });
597 fs.nabslineinfo += 1;
598 fs.f.lineinfo[pc] = ABS_LINE_INFO;
599 fs.iwthabs = 1;
600 } else {
601 fs.f.lineinfo[pc] = linedif_raw as i8;
602 }
603 fs.previousline = line;
604 let result = fs.pc;
605 fs.pc += 1;
606 result
607}
608
609fn add_k_value(fs: &mut FuncState, v: LuaValue) -> i32 {
610 let idx = fs.nk;
611 if (fs.f.k.len() as i32) <= idx {
612 fs.f.k.resize((idx + 1) as usize, LuaValue::Nil);
613 }
614 fs.f.k[idx as usize] = v;
615 fs.nk += 1;
616 idx
617}
618
619fn add_k_string(fs: &mut FuncState, s: GcRef<LuaString>) -> i32 {
620 for (i, k) in fs.f.k.iter().take(fs.nk as usize).enumerate() {
621 if let LuaValue::Str(existing) = k {
622 if GcRef::ptr_eq(existing, &s) {
623 return i as i32;
624 }
625 }
626 }
627 add_k_value(fs, LuaValue::Str(s))
628}
629
630fn bump_maxstack(fs: &mut FuncState, n: u8) {
631 if fs.f.maxstacksize < n {
632 fs.f.maxstacksize = n;
633 }
634}
635
636fn reserve_reg(fs: &mut FuncState) -> Result<u8, LuaError> {
637 if fs.freereg == u8::MAX {
638 return Err(LuaError::syntax(format_args!(
639 "function or expression needs too many registers"
640 )));
641 }
642 let r = fs.freereg;
643 fs.freereg += 1;
644 bump_maxstack(fs, fs.freereg);
645 Ok(r)
646}
647
648fn reserve_regs(fs: &mut FuncState, n: i32) -> Result<(), LuaError> {
649 let newstack = fs.freereg as i32 + n;
650 if newstack >= 255 {
651 return Err(LuaError::syntax(format_args!(
652 "function or expression needs too many registers"
653 )));
654 }
655 fs.freereg = newstack as u8;
656 bump_maxstack(fs, fs.freereg);
657 Ok(())
658}
659
660fn cg_free_reg(fs: &mut FuncState, reg: i32) {
666 if reg >= fs.nactvar as i32 {
667 debug_assert_eq!(reg, fs.freereg as i32 - 1);
668 fs.freereg = fs.freereg.saturating_sub(1);
669 }
670}
671
672fn cg_free_exp(fs: &mut FuncState, e: &ExprDesc) {
677 if e.k == ExprKind::NonReloc {
678 cg_free_reg(fs, e.u.info);
679 }
680}
681
682fn cg_free_exps(fs: &mut FuncState, e1: &ExprDesc, e2: &ExprDesc) {
687 let r1 = if e1.k == ExprKind::NonReloc {
688 e1.u.info
689 } else {
690 -1
691 };
692 let r2 = if e2.k == ExprKind::NonReloc {
693 e2.u.info
694 } else {
695 -1
696 };
697 if r1 > r2 {
698 cg_free_reg(fs, r1);
699 cg_free_reg(fs, r2);
700 } else {
701 cg_free_reg(fs, r2);
702 cg_free_reg(fs, r1);
703 }
704}
705
706fn fold_int_mod(m: i64, n: i64) -> i64 {
720 if n == -1 {
721 return 0;
722 }
723 let r = m % n;
724 if r != 0 && (r ^ n) < 0 {
725 r + n
726 } else {
727 r
728 }
729}
730
731fn fold_int_idiv(m: i64, n: i64) -> i64 {
735 if n == -1 {
736 return m.wrapping_neg();
737 }
738 let q = m / n;
739 if (m ^ n) < 0 && m % n != 0 {
740 q - 1
741 } else {
742 q
743 }
744}
745
746fn fold_int_shiftl(x: i64, y: i64) -> i64 {
750 if y < 0 {
751 if y <= -64 {
752 0
753 } else {
754 ((x as u64) >> (-y as u32)) as i64
755 }
756 } else if y >= 64 {
757 0
758 } else {
759 ((x as u64) << (y as u32)) as i64
760 }
761}
762
763fn cg_posfix_fold(
764 fs: &mut FuncState,
765 op: BinOpr,
766 e1: &mut ExprDesc,
767 e2: &mut ExprDesc,
768 line: i32,
769) -> Result<(), LuaError> {
770 let rhs_line = fs.last_token_line;
776 cg_discharge_vars(fs, rhs_line, e2)?;
777
778 let promote = |k: ExprKind, u: &ExprPayload| -> Option<f64> {
779 match k {
780 ExprKind::KInt => Some(u.ival as f64),
781 ExprKind::KFlt => Some(u.nval),
782 _ => None,
783 }
784 };
785
786 let foldable = e1.t == NO_JUMP && e1.f == NO_JUMP && e2.t == NO_JUMP && e2.f == NO_JUMP;
787
788 if foldable {
789 if let (ExprKind::KInt, ExprKind::KInt) = (e1.k, e2.k) {
790 let a = e1.u.ival;
791 let b = e2.u.ival;
792 let r: Option<i64> = match op {
793 BinOpr::Add => Some(a.wrapping_add(b)),
794 BinOpr::Sub => Some(a.wrapping_sub(b)),
795 BinOpr::Mul => Some(a.wrapping_mul(b)),
796 BinOpr::Mod if b != 0 => Some(fold_int_mod(a, b)),
797 BinOpr::IDiv if b != 0 => Some(fold_int_idiv(a, b)),
798 BinOpr::BAnd => Some(a & b),
799 BinOpr::BOr => Some(a | b),
800 BinOpr::BXor => Some(a ^ b),
801 BinOpr::Shl => Some(fold_int_shiftl(a, b)),
802 BinOpr::Shr => Some(fold_int_shiftl(a, b.wrapping_neg())),
803 _ => None,
804 };
805 if let Some(v) = r {
806 e1.k = ExprKind::KInt;
807 e1.u.ival = v;
808 return Ok(());
809 }
810 }
811 if let (Some(a), Some(b)) = (promote(e1.k, &e1.u), promote(e2.k, &e2.u)) {
812 let r: Option<f64> = match op {
813 BinOpr::Add => Some(a + b),
814 BinOpr::Sub => Some(a - b),
815 BinOpr::Mul => Some(a * b),
816 BinOpr::Div => Some(a / b),
817 BinOpr::Pow => Some(a.powf(b)),
818 _ => None,
819 };
820 if let Some(v) = r {
821 if !v.is_nan() && v != 0.0 {
822 e1.k = ExprKind::KFlt;
823 e1.u.nval = v;
824 return Ok(());
825 }
826 }
827 }
828 }
829
830 if matches!(op, BinOpr::Lt | BinOpr::Le) {
831 return cg_emit_order(fs, op, e1, e2, line);
832 }
833
834 if matches!(op, BinOpr::Gt | BinOpr::Ge) {
835 let swap_op = if matches!(op, BinOpr::Gt) {
836 BinOpr::Lt
837 } else {
838 BinOpr::Le
839 };
840 std::mem::swap(e1, e2);
841 return cg_emit_order(fs, swap_op, e1, e2, line);
842 }
843
844 if matches!(op, BinOpr::Eq | BinOpr::Ne) {
845 return cg_emit_eq(fs, op, e1, e2, line);
846 }
847
848 if matches!(op, BinOpr::And) {
849 debug_assert_eq!(e1.t, NO_JUMP);
850 cg_concat(fs, &mut e2.f, e1.f)?;
851 *e1 = e2.clone();
852 return Ok(());
853 }
854
855 if matches!(op, BinOpr::Or) {
856 debug_assert_eq!(e1.f, NO_JUMP);
857 cg_concat(fs, &mut e2.t, e1.t)?;
858 *e1 = e2.clone();
859 return Ok(());
860 }
861
862 if matches!(op, BinOpr::Concat) {
863 return cg_emit_concat(fs, e1, e2, line);
864 }
865
866 match op {
867 BinOpr::Add | BinOpr::Mul => cg_code_commutative(fs, op, e1, e2, line),
868 BinOpr::Sub => {
869 if cg_finish_bin_exp_neg(
870 fs,
871 e1,
872 e2,
873 lua_code::opcodes::OpCode::AddI,
874 line,
875 lua_types::tagmethod::TagMethod::Sub,
876 )? {
877 Ok(())
878 } else {
879 cg_code_arith(fs, op, e1, e2, false, line)
880 }
881 }
882 BinOpr::Mod | BinOpr::Pow | BinOpr::Div | BinOpr::IDiv => {
883 cg_code_arith(fs, op, e1, e2, false, line)
884 }
885 BinOpr::BAnd | BinOpr::BOr | BinOpr::BXor => cg_code_bitwise(fs, op, e1, e2, line),
886 BinOpr::Shl => cg_code_shift_left(fs, e1, e2, line),
887 BinOpr::Shr => cg_code_shift_right(fs, e1, e2, line),
888 BinOpr::Concat
889 | BinOpr::Eq
890 | BinOpr::Lt
891 | BinOpr::Le
892 | BinOpr::Ne
893 | BinOpr::Gt
894 | BinOpr::Ge
895 | BinOpr::And
896 | BinOpr::Or
897 | BinOpr::NoBinOpr => {
898 unreachable!(
899 "cg_posfix_fold reached opcode match with non-arith op {:?}",
900 op
901 )
902 }
903 }
904}
905
906fn cg_binop_reg_opcode(op: BinOpr) -> lua_code::opcodes::OpCode {
907 match op {
908 BinOpr::Add => lua_code::opcodes::OpCode::Add,
909 BinOpr::Sub => lua_code::opcodes::OpCode::Sub,
910 BinOpr::Mul => lua_code::opcodes::OpCode::Mul,
911 BinOpr::Mod => lua_code::opcodes::OpCode::Mod,
912 BinOpr::Pow => lua_code::opcodes::OpCode::Pow,
913 BinOpr::Div => lua_code::opcodes::OpCode::Div,
914 BinOpr::IDiv => lua_code::opcodes::OpCode::IDiv,
915 BinOpr::BAnd => lua_code::opcodes::OpCode::BAnd,
916 BinOpr::BOr => lua_code::opcodes::OpCode::BOr,
917 BinOpr::BXor => lua_code::opcodes::OpCode::BXOr,
918 BinOpr::Shl => lua_code::opcodes::OpCode::Shl,
919 BinOpr::Shr => lua_code::opcodes::OpCode::Shr,
920 _ => unreachable!("non-value binary operator {:?}", op),
921 }
922}
923
924fn cg_binop_k_opcode(op: BinOpr) -> lua_code::opcodes::OpCode {
925 match op {
926 BinOpr::Add => lua_code::opcodes::OpCode::AddK,
927 BinOpr::Sub => lua_code::opcodes::OpCode::SubK,
928 BinOpr::Mul => lua_code::opcodes::OpCode::MulK,
929 BinOpr::Mod => lua_code::opcodes::OpCode::ModK,
930 BinOpr::Pow => lua_code::opcodes::OpCode::PowK,
931 BinOpr::Div => lua_code::opcodes::OpCode::DivK,
932 BinOpr::IDiv => lua_code::opcodes::OpCode::IDivK,
933 BinOpr::BAnd => lua_code::opcodes::OpCode::BAndK,
934 BinOpr::BOr => lua_code::opcodes::OpCode::BOrK,
935 BinOpr::BXor => lua_code::opcodes::OpCode::BXOrK,
936 _ => unreachable!("operator has no K opcode {:?}", op),
937 }
938}
939
940fn cg_binop_event(op: BinOpr) -> lua_types::tagmethod::TagMethod {
941 match op {
942 BinOpr::Add => lua_types::tagmethod::TagMethod::Add,
943 BinOpr::Sub => lua_types::tagmethod::TagMethod::Sub,
944 BinOpr::Mul => lua_types::tagmethod::TagMethod::Mul,
945 BinOpr::Mod => lua_types::tagmethod::TagMethod::Mod,
946 BinOpr::Pow => lua_types::tagmethod::TagMethod::Pow,
947 BinOpr::Div => lua_types::tagmethod::TagMethod::Div,
948 BinOpr::IDiv => lua_types::tagmethod::TagMethod::Idiv,
949 BinOpr::BAnd => lua_types::tagmethod::TagMethod::Band,
950 BinOpr::BOr => lua_types::tagmethod::TagMethod::Bor,
951 BinOpr::BXor => lua_types::tagmethod::TagMethod::Bxor,
952 BinOpr::Shl => lua_types::tagmethod::TagMethod::Shl,
953 BinOpr::Shr => lua_types::tagmethod::TagMethod::Shr,
954 _ => unreachable!("operator has no arithmetic metamethod {:?}", op),
955 }
956}
957
958fn cg_is_numeral(e: &ExprDesc) -> bool {
959 e.t == NO_JUMP && e.f == NO_JUMP && matches!(e.k, ExprKind::KInt | ExprKind::KFlt)
960}
961
962fn cg_is_integer(e: &ExprDesc) -> bool {
963 e.t == NO_JUMP && e.f == NO_JUMP && e.k == ExprKind::KInt
964}
965
966fn cg_find_k_value(fs: &FuncState, v: &LuaValue) -> Option<i32> {
967 fs.f.k
968 .iter()
969 .take(fs.nk as usize)
970 .position(|existing| existing == v)
971 .map(|idx| idx as i32)
972}
973
974fn cg_k_value_index_limited(fs: &mut FuncState, value: LuaValue, maxarg: u32) -> Option<i32> {
975 let idx = if let Some(idx) = cg_find_k_value(fs, &value) {
976 idx
977 } else {
978 if fs.nk as u32 > maxarg {
979 return None;
980 }
981 add_k_value(fs, value)
982 };
983 if idx as u32 > maxarg {
984 None
985 } else {
986 Some(idx)
987 }
988}
989
990fn cg_k_string_index_limited(fs: &mut FuncState, s: GcRef<LuaString>, maxarg: u32) -> Option<i32> {
991 for (i, k) in fs.f.k.iter().take(fs.nk as usize).enumerate() {
992 if let LuaValue::Str(existing) = k {
993 if GcRef::ptr_eq(existing, &s) {
994 let idx = i as i32;
995 return (idx as u32 <= maxarg).then_some(idx);
996 }
997 }
998 }
999 if fs.nk as u32 > maxarg {
1000 return None;
1001 }
1002 let idx = add_k_string(fs, s);
1003 (idx as u32 <= maxarg).then_some(idx)
1004}
1005
1006fn cg_exp_to_k(fs: &mut FuncState, e: &mut ExprDesc) -> bool {
1007 if !cg_is_numeral(e) {
1008 return false;
1009 }
1010 let value = match e.k {
1011 ExprKind::KInt => LuaValue::Int(e.u.ival),
1012 ExprKind::KFlt => LuaValue::Float(e.u.nval),
1013 _ => return false,
1014 };
1015 let Some(idx) = cg_k_value_index_limited(fs, value, lua_code::opcodes::MAXARG_C) else {
1016 return false;
1017 };
1018 e.k = ExprKind::K;
1019 e.u.info = idx;
1020 true
1021}
1022
1023fn cg_exp_to_int_k(fs: &mut FuncState, e: &mut ExprDesc) -> bool {
1024 if !cg_is_integer(e) {
1025 return false;
1026 }
1027 let Some(idx) =
1028 cg_k_value_index_limited(fs, LuaValue::Int(e.u.ival), lua_code::opcodes::MAXARG_C)
1029 else {
1030 return false;
1031 };
1032 e.k = ExprKind::K;
1033 e.u.info = idx;
1034 true
1035}
1036
1037fn cg_exp_to_const_k(fs: &mut FuncState, e: &mut ExprDesc, maxarg: u32) -> bool {
1038 if e.t != NO_JUMP || e.f != NO_JUMP {
1039 return false;
1040 }
1041 let idx = match e.k {
1042 ExprKind::Nil => cg_k_value_index_limited(fs, LuaValue::Nil, maxarg),
1043 ExprKind::False => cg_k_value_index_limited(fs, LuaValue::Bool(false), maxarg),
1044 ExprKind::True => cg_k_value_index_limited(fs, LuaValue::Bool(true), maxarg),
1045 ExprKind::KInt => cg_k_value_index_limited(fs, LuaValue::Int(e.u.ival), maxarg),
1046 ExprKind::KFlt => cg_k_value_index_limited(fs, LuaValue::Float(e.u.nval), maxarg),
1047 ExprKind::KStr => {
1048 let Some(s) = e.u.strval.clone() else {
1049 return false;
1050 };
1051 cg_k_string_index_limited(fs, s, maxarg)
1052 }
1053 ExprKind::K => {
1054 if e.u.info >= 0 && (e.u.info as u32) <= maxarg {
1055 Some(e.u.info)
1056 } else {
1057 None
1058 }
1059 }
1060 _ => None,
1061 };
1062 let Some(idx) = idx else {
1063 return false;
1064 };
1065 e.k = ExprKind::K;
1066 e.u.info = idx;
1067 true
1068}
1069
1070fn cg_finish_bin_exp_val(
1071 fs: &mut FuncState,
1072 e1: &mut ExprDesc,
1073 e2: &mut ExprDesc,
1074 opcode: lua_code::opcodes::OpCode,
1075 v2: u32,
1076 flip: bool,
1077 line: i32,
1078 mm_opcode: lua_code::opcodes::OpCode,
1079 event: lua_types::tagmethod::TagMethod,
1080) -> Result<(), LuaError> {
1081 let v1 = cg_exp_to_any_reg(fs, line, e1)?;
1082 let inst = lua_code::opcodes::Instruction::abck(opcode, 0, v1 as u32, v2, 0);
1083 let pc = emit_inst(fs, line, inst);
1084 cg_free_exps(fs, e1, e2);
1085 e1.u.info = pc;
1086 e1.k = ExprKind::Reloc;
1087
1088 let mm_inst =
1089 lua_code::opcodes::Instruction::abck(mm_opcode, v1 as u32, v2, event as u32, flip as u32);
1090 emit_inst(fs, line, mm_inst);
1091 Ok(())
1092}
1093
1094fn cg_code_bin_exp_val(
1095 fs: &mut FuncState,
1096 op: BinOpr,
1097 e1: &mut ExprDesc,
1098 e2: &mut ExprDesc,
1099 line: i32,
1100) -> Result<(), LuaError> {
1101 let opcode = cg_binop_reg_opcode(op);
1102 let v2 = cg_exp_to_any_reg(fs, line, e2)? as u32;
1103 cg_finish_bin_exp_val(
1104 fs,
1105 e1,
1106 e2,
1107 opcode,
1108 v2,
1109 false,
1110 line,
1111 lua_code::opcodes::OpCode::MmBin,
1112 cg_binop_event(op),
1113 )
1114}
1115
1116fn cg_code_bin_i(
1117 fs: &mut FuncState,
1118 opcode: lua_code::opcodes::OpCode,
1119 e1: &mut ExprDesc,
1120 e2: &mut ExprDesc,
1121 flip: bool,
1122 line: i32,
1123 event: lua_types::tagmethod::TagMethod,
1124) -> Result<(), LuaError> {
1125 let Some(v2) = cg_sc_int(e2) else {
1126 unreachable!("cg_code_bin_i called with non-small-integer operand");
1127 };
1128 cg_finish_bin_exp_val(
1129 fs,
1130 e1,
1131 e2,
1132 opcode,
1133 v2 as u32,
1134 flip,
1135 line,
1136 lua_code::opcodes::OpCode::MmBinI,
1137 event,
1138 )
1139}
1140
1141fn cg_code_bin_k(
1142 fs: &mut FuncState,
1143 op: BinOpr,
1144 e1: &mut ExprDesc,
1145 e2: &mut ExprDesc,
1146 flip: bool,
1147 line: i32,
1148) -> Result<(), LuaError> {
1149 let v2 = e2.u.info as u32;
1150 cg_finish_bin_exp_val(
1151 fs,
1152 e1,
1153 e2,
1154 cg_binop_k_opcode(op),
1155 v2,
1156 flip,
1157 line,
1158 lua_code::opcodes::OpCode::MmBinK,
1159 cg_binop_event(op),
1160 )
1161}
1162
1163fn cg_code_bin_no_k(
1164 fs: &mut FuncState,
1165 op: BinOpr,
1166 e1: &mut ExprDesc,
1167 e2: &mut ExprDesc,
1168 flip: bool,
1169 line: i32,
1170) -> Result<(), LuaError> {
1171 if flip {
1172 std::mem::swap(e1, e2);
1173 }
1174 cg_code_bin_exp_val(fs, op, e1, e2, line)
1175}
1176
1177fn cg_code_arith(
1178 fs: &mut FuncState,
1179 op: BinOpr,
1180 e1: &mut ExprDesc,
1181 e2: &mut ExprDesc,
1182 flip: bool,
1183 line: i32,
1184) -> Result<(), LuaError> {
1185 if cg_is_numeral(e2) && cg_exp_to_k(fs, e2) {
1186 cg_code_bin_k(fs, op, e1, e2, flip, line)
1187 } else {
1188 cg_code_bin_no_k(fs, op, e1, e2, flip, line)
1189 }
1190}
1191
1192fn cg_code_commutative(
1193 fs: &mut FuncState,
1194 op: BinOpr,
1195 e1: &mut ExprDesc,
1196 e2: &mut ExprDesc,
1197 line: i32,
1198) -> Result<(), LuaError> {
1199 let mut flip = false;
1200 if cg_is_numeral(e1) {
1201 std::mem::swap(e1, e2);
1202 flip = true;
1203 }
1204 if op == BinOpr::Add && cg_sc_int(e2).is_some() {
1205 cg_code_bin_i(
1206 fs,
1207 lua_code::opcodes::OpCode::AddI,
1208 e1,
1209 e2,
1210 flip,
1211 line,
1212 lua_types::tagmethod::TagMethod::Add,
1213 )
1214 } else {
1215 cg_code_arith(fs, op, e1, e2, flip, line)
1216 }
1217}
1218
1219fn cg_code_bitwise(
1220 fs: &mut FuncState,
1221 op: BinOpr,
1222 e1: &mut ExprDesc,
1223 e2: &mut ExprDesc,
1224 line: i32,
1225) -> Result<(), LuaError> {
1226 let mut flip = false;
1227 if cg_is_integer(e1) {
1228 std::mem::swap(e1, e2);
1229 flip = true;
1230 }
1231 if cg_is_integer(e2) && cg_exp_to_int_k(fs, e2) {
1232 cg_code_bin_k(fs, op, e1, e2, flip, line)
1233 } else {
1234 cg_code_bin_no_k(fs, op, e1, e2, flip, line)
1235 }
1236}
1237
1238fn cg_code_shift_left(
1239 fs: &mut FuncState,
1240 e1: &mut ExprDesc,
1241 e2: &mut ExprDesc,
1242 line: i32,
1243) -> Result<(), LuaError> {
1244 if cg_sc_int(e1).is_some() {
1245 std::mem::swap(e1, e2);
1246 cg_code_bin_i(
1247 fs,
1248 lua_code::opcodes::OpCode::ShlI,
1249 e1,
1250 e2,
1251 true,
1252 line,
1253 lua_types::tagmethod::TagMethod::Shl,
1254 )
1255 } else if cg_finish_bin_exp_neg(
1256 fs,
1257 e1,
1258 e2,
1259 lua_code::opcodes::OpCode::ShrI,
1260 line,
1261 lua_types::tagmethod::TagMethod::Shl,
1262 )? {
1263 Ok(())
1264 } else {
1265 cg_code_bin_exp_val(fs, BinOpr::Shl, e1, e2, line)
1266 }
1267}
1268
1269fn cg_code_shift_right(
1270 fs: &mut FuncState,
1271 e1: &mut ExprDesc,
1272 e2: &mut ExprDesc,
1273 line: i32,
1274) -> Result<(), LuaError> {
1275 if cg_sc_int(e2).is_some() {
1276 cg_code_bin_i(
1277 fs,
1278 lua_code::opcodes::OpCode::ShrI,
1279 e1,
1280 e2,
1281 false,
1282 line,
1283 lua_types::tagmethod::TagMethod::Shr,
1284 )
1285 } else {
1286 cg_code_bin_exp_val(fs, BinOpr::Shr, e1, e2, line)
1287 }
1288}
1289
1290fn cg_finish_bin_exp_neg(
1291 fs: &mut FuncState,
1292 e1: &mut ExprDesc,
1293 e2: &mut ExprDesc,
1294 opcode: lua_code::opcodes::OpCode,
1295 line: i32,
1296 event: lua_types::tagmethod::TagMethod,
1297) -> Result<bool, LuaError> {
1298 if e2.k != ExprKind::KInt || e2.t != NO_JUMP || e2.f != NO_JUMP {
1299 return Ok(false);
1300 }
1301 let i2 = e2.u.ival;
1302 let Some(neg_i2) = i2.checked_neg() else {
1303 return Ok(false);
1304 };
1305 let biased = (i2 as i128) + (lua_code::opcodes::OFFSET_S_C as i128);
1306 let neg_biased = (neg_i2 as i128) + (lua_code::opcodes::OFFSET_S_C as i128);
1307 if !(0..=lua_code::opcodes::MAXARG_C as i128).contains(&biased)
1308 || !(0..=lua_code::opcodes::MAXARG_C as i128).contains(&neg_biased)
1309 {
1310 return Ok(false);
1311 }
1312
1313 let v1 = cg_exp_to_any_reg(fs, line, e1)?;
1314 let inst = lua_code::opcodes::Instruction::abck(opcode, 0, v1 as u32, neg_biased as u32, 0);
1315 let pc = emit_inst(fs, line, inst);
1316 cg_free_exps(fs, e1, e2);
1317 e1.u.info = pc;
1318 e1.k = ExprKind::Reloc;
1319
1320 let mm_inst = lua_code::opcodes::Instruction::abck(
1321 lua_code::opcodes::OpCode::MmBinI,
1322 v1 as u32,
1323 biased as u32,
1324 event as u32,
1325 0,
1326 );
1327 emit_inst(fs, line, mm_inst);
1328 Ok(true)
1329}
1330
1331fn cg_emit_order(
1340 fs: &mut FuncState,
1341 op: BinOpr,
1342 e1: &mut ExprDesc,
1343 e2: &mut ExprDesc,
1344 line: i32,
1345) -> Result<(), LuaError> {
1346 debug_assert!(matches!(op, BinOpr::Lt | BinOpr::Le));
1347 let is_le = matches!(op, BinOpr::Le);
1348 let (op_imm_e2, op_imm_e1, op_reg) = if is_le {
1349 (
1350 lua_code::opcodes::OpCode::LeI,
1351 lua_code::opcodes::OpCode::GeI,
1352 lua_code::opcodes::OpCode::Le,
1353 )
1354 } else {
1355 (
1356 lua_code::opcodes::OpCode::LtI,
1357 lua_code::opcodes::OpCode::GtI,
1358 lua_code::opcodes::OpCode::Lt,
1359 )
1360 };
1361 let (r1, r2, cmp_op, isfloat) = if let Some((im, isf)) = cg_sc_number(e2) {
1362 let r1 = cg_exp_to_any_reg(fs, line, e1)?;
1363 (r1, im, op_imm_e2, isf)
1364 } else if let Some((im, isf)) = cg_sc_number(e1) {
1365 let r1 = cg_exp_to_any_reg(fs, line, e2)?;
1366 (r1, im, op_imm_e1, isf)
1367 } else {
1368 let r2 = cg_exp_to_any_reg(fs, line, e2)?;
1369 let r1 = cg_exp_to_any_reg(fs, line, e1)?;
1370 (r1, r2, op_reg, false)
1371 };
1372 cg_free_exps(fs, e1, e2);
1373 let cmp =
1374 lua_code::opcodes::Instruction::abck(cmp_op, r1 as u32, r2 as u32, isfloat as u32, 1);
1375 emit_inst(fs, line, cmp);
1376 let jmp_arg = (NO_JUMP + lua_code::opcodes::OFFSET_S_J) as u32;
1377 let jmp = lua_code::opcodes::Instruction::sj(lua_code::opcodes::OpCode::Jmp, jmp_arg, 0);
1378 let jmp_pc = emit_inst(fs, line, jmp);
1379 e1.u.info = jmp_pc;
1380 e1.k = ExprKind::Jmp;
1381 Ok(())
1382}
1383
1384fn cg_emit_eq(
1389 fs: &mut FuncState,
1390 op: BinOpr,
1391 e1: &mut ExprDesc,
1392 e2: &mut ExprDesc,
1393 line: i32,
1394) -> Result<(), LuaError> {
1395 debug_assert!(matches!(op, BinOpr::Eq | BinOpr::Ne));
1396 if e1.k != ExprKind::NonReloc {
1397 std::mem::swap(e1, e2);
1398 }
1399 let r1 = cg_exp_to_any_reg(fs, line, e1)?;
1400 let (r2, cmp_op, isfloat) = if let Some((im, isf)) = cg_sc_number(e2) {
1401 (im, lua_code::opcodes::OpCode::EqI, isf)
1402 } else if cg_exp_to_const_k(fs, e2, lua_code::opcodes::MAXARG_B) {
1403 (e2.u.info as u8, lua_code::opcodes::OpCode::EqK, false)
1404 } else {
1405 let r = cg_exp_to_any_reg(fs, line, e2)?;
1406 (r, lua_code::opcodes::OpCode::Eq, false)
1407 };
1408 cg_free_exps(fs, e1, e2);
1409 let k_bit = if matches!(op, BinOpr::Eq) { 1 } else { 0 };
1410 let cmp =
1411 lua_code::opcodes::Instruction::abck(cmp_op, r1 as u32, r2 as u32, isfloat as u32, k_bit);
1412 emit_inst(fs, line, cmp);
1413 let jmp_pc = cg_jump(fs, line);
1414 e1.u.info = jmp_pc;
1415 e1.k = ExprKind::Jmp;
1416 Ok(())
1417}
1418
1419fn previous_instruction_idx(fs: &FuncState) -> Option<usize> {
1424 if fs.pc > fs.lasttarget {
1425 Some((fs.pc - 1) as usize)
1426 } else {
1427 None
1428 }
1429}
1430
1431fn cg_emit_concat(
1440 fs: &mut FuncState,
1441 e1: &mut ExprDesc,
1442 e2: &mut ExprDesc,
1443 line: i32,
1444) -> Result<(), LuaError> {
1445 cg_exp_to_next_reg(fs, line, e2)?;
1446
1447 if let Some(prev_idx) = previous_instruction_idx(fs) {
1448 let prev = lua_code::opcodes::Instruction(fs.f.code[prev_idx].0);
1449 if prev.opcode() == Some(lua_code::opcodes::OpCode::Concat) {
1450 let n = prev.arg_b();
1451 debug_assert_eq!(e1.u.info + 1, prev.arg_a() as i32);
1452 cg_free_exp(fs, e2);
1453 let mut updated = prev;
1454 updated.set_arg_a(e1.u.info as u32);
1455 updated.set_arg_b(n + 1);
1456 fs.f.code[prev_idx] = lua_types::opcode::Instruction::new(updated.0);
1457 return Ok(());
1458 }
1459 }
1460
1461 let inst = lua_code::opcodes::Instruction::abck(
1462 lua_code::opcodes::OpCode::Concat,
1463 e1.u.info as u32,
1464 2,
1465 0,
1466 0,
1467 );
1468 emit_inst(fs, line, inst);
1469 cg_free_exp(fs, e2);
1470 Ok(())
1471}
1472
1473fn cg_fold_unary(op: UnOpr, e: &mut ExprDesc) -> bool {
1483 if e.t != NO_JUMP || e.f != NO_JUMP {
1484 return false;
1485 }
1486 match (op, e.k) {
1487 (UnOpr::Minus, ExprKind::KInt) => {
1488 e.u.ival = e.u.ival.wrapping_neg();
1489 true
1490 }
1491 (UnOpr::Minus, ExprKind::KFlt) => {
1492 let n = -e.u.nval;
1493 if n.is_nan() || n == 0.0 {
1494 false
1495 } else {
1496 e.u.nval = n;
1497 true
1498 }
1499 }
1500 (UnOpr::BNot, ExprKind::KInt) => {
1501 e.u.ival = !e.u.ival;
1502 true
1503 }
1504 (UnOpr::BNot, ExprKind::KFlt) => match flt_to_int_exact(e.u.nval) {
1505 Some(iv) => {
1506 e.k = ExprKind::KInt;
1507 e.u.ival = !iv;
1508 true
1509 }
1510 None => false,
1511 },
1512 _ => false,
1513 }
1514}
1515
1516fn cg_prefix(fs: &mut FuncState, op: UnOpr, e: &mut ExprDesc, line: i32) -> Result<(), LuaError> {
1525 cg_discharge_vars(fs, line, e)?;
1526 if matches!(op, UnOpr::Minus | UnOpr::BNot) && cg_fold_unary(op, e) {
1527 return Ok(());
1528 }
1529 let opcode = match op {
1530 UnOpr::Minus => lua_code::opcodes::OpCode::Unm,
1531 UnOpr::BNot => lua_code::opcodes::OpCode::BNot,
1532 UnOpr::Len => lua_code::opcodes::OpCode::Len,
1533 UnOpr::Not => return cg_codenot(fs, line, e),
1534 UnOpr::NoUnOpr => return Ok(()),
1535 };
1536 let r = cg_exp_to_any_reg(fs, line, e)?;
1537 cg_free_exp(fs, e);
1538 let inst = lua_code::opcodes::Instruction::abck(opcode, 0, r as u32, 0, 0);
1539 let pc = emit_inst(fs, line, inst);
1540 e.u.info = pc;
1541 e.k = ExprKind::Reloc;
1542 Ok(())
1543}
1544
1545fn cg_get_jump_control(fs: &FuncState, pc: i32) -> i32 {
1552 if pc >= 1 {
1553 let prev = cg_inst_at(fs, pc - 1);
1554 if let Some(op) = prev.opcode() {
1555 if lua_code::opcodes::test_t_mode(op) {
1556 return pc - 1;
1557 }
1558 }
1559 }
1560 pc
1561}
1562
1563fn cg_patch_test_reg(fs: &mut FuncState, node: i32, reg: u32) -> bool {
1571 let ctrl_pc = cg_get_jump_control(fs, node);
1572 let mut inst = cg_inst_at(fs, ctrl_pc);
1573 if inst.opcode() != Some(lua_code::opcodes::OpCode::TestSet) {
1574 return false;
1575 }
1576 let b = inst.arg_b();
1577 let k = inst.arg_k();
1578 if reg != lua_code::opcodes::NO_REG && reg != b {
1579 inst.set_arg_a(reg);
1580 cg_set_inst_at(fs, ctrl_pc, inst);
1581 } else {
1582 let test =
1583 lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::Test, b, 0, 0, k);
1584 cg_set_inst_at(fs, ctrl_pc, test);
1585 }
1586 true
1587}
1588
1589fn cg_remove_values(fs: &mut FuncState, list: i32) {
1596 let mut list = list;
1597 while list != NO_JUMP {
1598 let next = cg_get_jump(fs, list);
1599 cg_patch_test_reg(fs, list, lua_code::opcodes::NO_REG);
1600 list = next;
1601 }
1602}
1603
1604fn cg_codenot(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1612 match e.k {
1613 ExprKind::Nil | ExprKind::False => {
1614 e.k = ExprKind::True;
1615 }
1616 ExprKind::K | ExprKind::KFlt | ExprKind::KInt | ExprKind::KStr | ExprKind::True => {
1617 e.k = ExprKind::False;
1618 }
1619 ExprKind::Jmp => {
1620 cg_negate_condition(fs, e);
1621 }
1622 ExprKind::Reloc | ExprKind::NonReloc => {
1623 let reg = cg_exp_to_any_reg(fs, line, e)?;
1624 cg_free_exp(fs, e);
1625 let inst = lua_code::opcodes::Instruction::abck(
1626 lua_code::opcodes::OpCode::Not,
1627 0,
1628 reg as u32,
1629 0,
1630 0,
1631 );
1632 let pc = emit_inst(fs, line, inst);
1633 e.u.info = pc;
1634 e.k = ExprKind::Reloc;
1635 }
1636 _ => debug_assert!(false, "cg_codenot: unexpected ExprKind {:?}", e.k),
1637 }
1638 std::mem::swap(&mut e.f, &mut e.t);
1639 cg_remove_values(fs, e.f);
1640 cg_remove_values(fs, e.t);
1641 Ok(())
1642}
1643
1644fn cg_jump(fs: &mut FuncState, line: i32) -> i32 {
1648 let jmp_arg = (NO_JUMP + lua_code::opcodes::OFFSET_S_J) as u32;
1649 let jmp = lua_code::opcodes::Instruction::sj(lua_code::opcodes::OpCode::Jmp, jmp_arg, 0);
1650 emit_inst(fs, line, jmp)
1651}
1652
1653fn cg_inst_at(fs: &FuncState, pc: i32) -> lua_code::opcodes::Instruction {
1656 lua_code::opcodes::Instruction(fs.f.code[pc as usize].0)
1657}
1658
1659fn cg_set_inst_at(fs: &mut FuncState, pc: i32, inst: lua_code::opcodes::Instruction) {
1662 fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(inst.0);
1663}
1664
1665fn cg_get_jump(fs: &FuncState, pc: i32) -> i32 {
1670 let offset = cg_inst_at(fs, pc).arg_s_j();
1671 if offset == NO_JUMP {
1672 NO_JUMP
1673 } else {
1674 (pc + 1) + offset
1675 }
1676}
1677
1678fn cg_fix_jump(fs: &mut FuncState, pc: i32, dest: i32) -> Result<(), LuaError> {
1682 debug_assert!(dest != NO_JUMP);
1683 let offset = dest - (pc + 1);
1684 let max = lua_code::opcodes::MAXARG_S_J as i32 - lua_code::opcodes::OFFSET_S_J;
1685 let min = -lua_code::opcodes::OFFSET_S_J;
1686 if offset < min || offset > max {
1687 return Err(LuaError::syntax(format_args!("control structure too long")));
1688 }
1689 let mut inst = cg_inst_at(fs, pc);
1690 inst.set_arg_s_j(offset);
1691 cg_set_inst_at(fs, pc, inst);
1692 Ok(())
1693}
1694
1695fn cg_get_label(fs: &mut FuncState) -> i32 {
1699 fs.lasttarget = fs.pc;
1700 fs.pc
1701}
1702
1703fn cg_concat(fs: &mut FuncState, l1: &mut i32, l2: i32) -> Result<(), LuaError> {
1707 if l2 == NO_JUMP {
1708 return Ok(());
1709 }
1710 if *l1 == NO_JUMP {
1711 *l1 = l2;
1712 return Ok(());
1713 }
1714 let mut list = *l1;
1715 loop {
1716 let next = cg_get_jump(fs, list);
1717 if next == NO_JUMP {
1718 break;
1719 }
1720 list = next;
1721 }
1722 cg_fix_jump(fs, list, l2)
1723}
1724
1725fn cg_patch_list(fs: &mut FuncState, list: i32, target: i32) -> Result<(), LuaError> {
1734 cg_patch_list_aux(fs, list, target, lua_code::opcodes::NO_REG, target)
1735}
1736
1737fn cg_patch_to_here(fs: &mut FuncState, list: i32) -> Result<(), LuaError> {
1741 let target = cg_get_label(fs);
1742 cg_patch_list(fs, list, target)
1743}
1744
1745fn cg_negate_condition(fs: &mut FuncState, e: &ExprDesc) {
1751 let pc = e.u.info - 1;
1752 let mut inst = cg_inst_at(fs, pc);
1753 let k = inst.arg_k();
1754 inst.set_arg_k(k ^ 1);
1755 cg_set_inst_at(fs, pc, inst);
1756}
1757
1758fn cg_go_if_true(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1767 cg_discharge_vars(fs, line, e)?;
1768 let pc: i32 = match e.k {
1769 ExprKind::Jmp => {
1770 cg_negate_condition(fs, e);
1771 e.u.info
1772 }
1773 ExprKind::K | ExprKind::KFlt | ExprKind::KInt | ExprKind::KStr | ExprKind::True => NO_JUMP,
1774 _ => cg_jump_on_cond(fs, line, e, 0)?,
1775 };
1776 cg_concat(fs, &mut e.f, pc)?;
1777 cg_patch_to_here(fs, e.t)?;
1778 e.t = NO_JUMP;
1779 Ok(())
1780}
1781
1782fn cg_go_if_false(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1789 cg_discharge_vars(fs, line, e)?;
1790 let pc: i32 = match e.k {
1791 ExprKind::Jmp => e.u.info,
1792 ExprKind::Nil | ExprKind::False => NO_JUMP,
1793 _ => cg_jump_on_cond(fs, line, e, 1)?,
1794 };
1795 cg_concat(fs, &mut e.t, pc)?;
1796 cg_patch_to_here(fs, e.f)?;
1797 e.f = NO_JUMP;
1798 Ok(())
1799}
1800
1801fn remove_last_instruction(fs: &mut FuncState) {
1816 const ABS_LINE_INFO: i8 = -0x80i8;
1817 let pc = (fs.pc - 1) as usize;
1818 if fs.f.lineinfo[pc] != ABS_LINE_INFO {
1819 fs.previousline -= fs.f.lineinfo[pc] as i32;
1820 fs.iwthabs -= 1;
1821 } else {
1822 debug_assert_eq!(
1823 fs.f.abslineinfo[fs.nabslineinfo as usize - 1].pc,
1824 pc as i32
1825 );
1826 fs.f.abslineinfo.pop();
1827 fs.nabslineinfo -= 1;
1828 fs.iwthabs = 129;
1829 }
1830 fs.pc -= 1;
1831}
1832
1833fn cg_jump_on_cond(
1834 fs: &mut FuncState,
1835 line: i32,
1836 e: &mut ExprDesc,
1837 cond: u8,
1838) -> Result<i32, LuaError> {
1839 if e.k == ExprKind::Reloc {
1840 let ie = lua_code::opcodes::Instruction(fs.f.code[e.u.info as usize].0);
1841 if ie.opcode() == Some(lua_code::opcodes::OpCode::Not) {
1842 remove_last_instruction(fs);
1843 let test = lua_code::opcodes::Instruction::abck(
1844 lua_code::opcodes::OpCode::Test,
1845 ie.arg_b(),
1846 0,
1847 0,
1848 (cond == 0) as u32,
1849 );
1850 emit_inst(fs, line, test);
1851 return Ok(cg_jump(fs, line));
1852 }
1853 }
1854 cg_discharge_to_any_reg(fs, line, e)?;
1855 cg_free_exp(fs, e);
1856 let reg = e.u.info;
1857 let test = lua_code::opcodes::Instruction::abck(
1858 lua_code::opcodes::OpCode::TestSet,
1859 lua_code::opcodes::NO_REG,
1860 reg as u32,
1861 0,
1862 cond as u32,
1863 );
1864 emit_inst(fs, line, test);
1865 Ok(cg_jump(fs, line))
1866}
1867
1868fn cg_discharge_to_any_reg(
1876 fs: &mut FuncState,
1877 line: i32,
1878 e: &mut ExprDesc,
1879) -> Result<(), LuaError> {
1880 if e.k != ExprKind::NonReloc {
1881 let reg = reserve_reg(fs)?;
1882 cg_discharge_to_reg(fs, line, e, reg)?;
1883 }
1884 Ok(())
1885}
1886
1887fn cg_infix(fs: &mut FuncState, op: BinOpr, v: &mut ExprDesc, line: i32) -> Result<(), LuaError> {
1900 match op {
1901 BinOpr::And => cg_go_if_true(fs, line, v),
1902 BinOpr::Or => cg_go_if_false(fs, line, v),
1903 BinOpr::Concat => cg_exp_to_next_reg(fs, line, v),
1904 BinOpr::Add
1905 | BinOpr::Sub
1906 | BinOpr::Mul
1907 | BinOpr::Div
1908 | BinOpr::IDiv
1909 | BinOpr::Mod
1910 | BinOpr::Pow
1911 | BinOpr::BAnd
1912 | BinOpr::BOr
1913 | BinOpr::BXor
1914 | BinOpr::Shl
1915 | BinOpr::Shr
1916 | BinOpr::Eq
1917 | BinOpr::Ne
1918 | BinOpr::Lt
1919 | BinOpr::Le
1920 | BinOpr::Gt
1921 | BinOpr::Ge => {
1922 if matches!(v.k, ExprKind::KInt | ExprKind::KFlt) && v.t == NO_JUMP && v.f == NO_JUMP {
1923 cg_discharge_vars(fs, line, v)
1924 } else {
1925 cg_exp_to_any_reg(fs, line, v).map(|_| ())
1926 }
1927 }
1928 _ => cg_discharge_vars(fs, line, v),
1929 }
1930}
1931
1932fn cg_sc_int(e: &ExprDesc) -> Option<u8> {
1938 if !matches!(e.k, ExprKind::KInt) {
1939 return None;
1940 }
1941 if e.t != NO_JUMP || e.f != NO_JUMP {
1942 return None;
1943 }
1944 let biased = (e.u.ival as u64).wrapping_add(lua_code::opcodes::OFFSET_S_C as u64);
1945 if biased <= lua_code::opcodes::MAXARG_C as u64 {
1946 Some(biased as u8)
1947 } else {
1948 None
1949 }
1950}
1951
1952fn flt_to_int_exact(n: f64) -> Option<i64> {
1956 if n.floor() == n && n >= (i64::MIN as f64) && n < -(i64::MIN as f64) {
1957 Some(n as i64)
1958 } else {
1959 None
1960 }
1961}
1962
1963fn cg_sc_number(e: &ExprDesc) -> Option<(u8, bool)> {
1971 let (i, isfloat) = match e.k {
1972 ExprKind::KInt => (e.u.ival, false),
1973 ExprKind::KFlt => (flt_to_int_exact(e.u.nval)?, true),
1974 _ => return None,
1975 };
1976 if e.t != NO_JUMP || e.f != NO_JUMP {
1977 return None;
1978 }
1979 let biased = (i as u64).wrapping_add(lua_code::opcodes::OFFSET_S_C as u64);
1980 if biased <= lua_code::opcodes::MAXARG_C as u64 {
1981 Some((biased as u8, isfloat))
1982 } else {
1983 None
1984 }
1985}
1986
1987fn mark_vararg_table_needed(fs: &mut FuncState) {
1988 fs.f.vararg_table_needed = true;
1989 for inst in fs.f.code.iter_mut() {
1990 let mut op = lua_code::opcodes::Instruction(inst.raw());
1991 if op.opcode() == Some(lua_code::opcodes::OpCode::VarArgPack) {
1992 op.set_arg_k(1);
1993 *inst = lua_types::opcode::Instruction::new(op.0);
1994 break;
1995 }
1996 }
1997}
1998
1999fn cg_exp_to_any_reg(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<u8, LuaError> {
2003 cg_discharge_vars(fs, line, e)?;
2004 if e.k == ExprKind::NonReloc {
2005 if e.t == NO_JUMP && e.f == NO_JUMP {
2006 return Ok(e.u.info as u8);
2007 }
2008 if e.u.info >= fs.nactvar as i32 {
2009 cg_exp_to_reg(fs, line, e, e.u.info as u8)?;
2010 return Ok(e.u.info as u8);
2011 }
2012 }
2013 cg_exp_to_next_reg(fs, line, e)?;
2014 Ok(e.u.info as u8)
2015}
2016
2017fn cg_discharge_vars(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
2021 match e.k {
2022 ExprKind::VarArgVar => {
2023 mark_vararg_table_needed(fs);
2024 e.u.info = e.u.var_ridx as i32;
2025 e.k = ExprKind::NonReloc;
2026 }
2027 ExprKind::Local => {
2028 e.u.info = e.u.var_ridx as i32;
2029 e.k = ExprKind::NonReloc;
2030 }
2031 ExprKind::UpVal => {
2032 let inst = lua_code::opcodes::Instruction::abck(
2033 lua_code::opcodes::OpCode::GetUpVal,
2034 0,
2035 e.u.info as u32,
2036 0,
2037 0,
2038 );
2039 let pc = emit_inst(fs, line, inst);
2040 e.u.info = pc;
2041 e.k = ExprKind::Reloc;
2042 }
2043 ExprKind::IndexUp => {
2044 let inst = lua_code::opcodes::Instruction::abck(
2045 lua_code::opcodes::OpCode::GetTabUp,
2046 0,
2047 e.u.ind_t as u32,
2048 e.u.ind_idx as u32,
2049 0,
2050 );
2051 let pc = emit_inst(fs, line, inst);
2052 e.u.info = pc;
2053 e.k = ExprKind::Reloc;
2054 }
2055 ExprKind::IndexI => {
2056 cg_free_reg_if_temp(fs, e.u.ind_t as i32);
2057 let inst = lua_code::opcodes::Instruction::abck(
2058 lua_code::opcodes::OpCode::GetI,
2059 0,
2060 e.u.ind_t as u32,
2061 e.u.ind_idx as u32,
2062 0,
2063 );
2064 let pc = emit_inst(fs, line, inst);
2065 e.u.info = pc;
2066 e.k = ExprKind::Reloc;
2067 }
2068 ExprKind::IndexStr => {
2069 cg_free_reg_if_temp(fs, e.u.ind_t as i32);
2070 let inst = lua_code::opcodes::Instruction::abck(
2071 lua_code::opcodes::OpCode::GetField,
2072 0,
2073 e.u.ind_t as u32,
2074 e.u.ind_idx as u32,
2075 0,
2076 );
2077 let pc = emit_inst(fs, line, inst);
2078 e.u.info = pc;
2079 e.k = ExprKind::Reloc;
2080 }
2081 ExprKind::Indexed => {
2082 let t_reg = e.u.ind_t as i32;
2083 let idx_reg = e.u.ind_idx as i32;
2084 if idx_reg > t_reg {
2085 cg_free_reg_if_temp(fs, idx_reg);
2086 cg_free_reg_if_temp(fs, t_reg);
2087 } else {
2088 cg_free_reg_if_temp(fs, t_reg);
2089 cg_free_reg_if_temp(fs, idx_reg);
2090 }
2091 let inst = lua_code::opcodes::Instruction::abck(
2092 lua_code::opcodes::OpCode::GetTable,
2093 0,
2094 e.u.ind_t as u32,
2095 e.u.ind_idx as u32,
2096 0,
2097 );
2098 let pc = emit_inst(fs, line, inst);
2099 e.u.info = pc;
2100 e.k = ExprKind::Reloc;
2101 }
2102 ExprKind::VarArgIndex => {
2103 let t_reg = e.u.ind_t as i32;
2104 let idx_reg = e.u.ind_idx as i32;
2105 if idx_reg > t_reg {
2106 cg_free_reg_if_temp(fs, idx_reg);
2107 cg_free_reg_if_temp(fs, t_reg);
2108 } else {
2109 cg_free_reg_if_temp(fs, t_reg);
2110 cg_free_reg_if_temp(fs, idx_reg);
2111 }
2112 let inst = lua_code::opcodes::Instruction::abck(
2113 lua_code::opcodes::OpCode::GetVArg,
2114 0,
2115 e.u.ind_t as u32,
2116 e.u.ind_idx as u32,
2117 0,
2118 );
2119 let pc = emit_inst(fs, line, inst);
2120 e.u.info = pc;
2121 e.k = ExprKind::Reloc;
2122 }
2123 ExprKind::VarArg | ExprKind::Call => {
2124 cg_set_one_ret(fs, e);
2125 }
2126 _ => {}
2127 }
2128 Ok(())
2129}
2130
2131fn cg_set_one_ret(fs: &mut FuncState, e: &mut ExprDesc) {
2137 if e.k == ExprKind::Call {
2138 let pc_idx = e.u.info as usize;
2139 let lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
2140 debug_assert_eq!(lc.arg_c(), 2);
2141 e.u.info = lc.arg_a() as i32;
2142 e.k = ExprKind::NonReloc;
2143 } else if e.k == ExprKind::VarArg {
2144 let pc_idx = e.u.info as usize;
2145 let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
2146 lc.set_arg_c(2);
2147 fs.f.code[pc_idx] = lua_types::opcode::Instruction::new(lc.0);
2148 e.k = ExprKind::Reloc;
2149 }
2150}
2151
2152fn cg_storevar(
2155 fs: &mut FuncState,
2156 line: i32,
2157 var: &ExprDesc,
2158 ex: &mut ExprDesc,
2159) -> Result<(), LuaError> {
2160 match var.k {
2161 ExprKind::Local => {
2162 cg_free_exp(fs, ex);
2163 cg_exp_to_reg(fs, line, ex, var.u.var_ridx as u8)?;
2164 return Ok(());
2165 }
2166 ExprKind::UpVal => {
2167 let e_reg = cg_exp_to_any_reg(fs, line, ex)?;
2168 let inst = lua_code::opcodes::Instruction::abck(
2169 lua_code::opcodes::OpCode::SetUpVal,
2170 e_reg as u32,
2171 var.u.info as u32,
2172 0,
2173 0,
2174 );
2175 emit_inst(fs, line, inst);
2176 }
2177 ExprKind::IndexUp => {
2178 cg_store_abrk(
2179 fs,
2180 line,
2181 lua_code::opcodes::OpCode::SetTabUp,
2182 var.u.ind_t as u32,
2183 var.u.ind_idx as u32,
2184 ex,
2185 )?;
2186 }
2187 ExprKind::IndexI => {
2188 cg_store_abrk(
2189 fs,
2190 line,
2191 lua_code::opcodes::OpCode::SetI,
2192 var.u.ind_t as u32,
2193 var.u.ind_idx as u32,
2194 ex,
2195 )?;
2196 }
2197 ExprKind::IndexStr => {
2198 cg_store_abrk(
2199 fs,
2200 line,
2201 lua_code::opcodes::OpCode::SetField,
2202 var.u.ind_t as u32,
2203 var.u.ind_idx as u32,
2204 ex,
2205 )?;
2206 }
2207 ExprKind::Indexed => {
2208 cg_store_abrk(
2209 fs,
2210 line,
2211 lua_code::opcodes::OpCode::SetTable,
2212 var.u.ind_t as u32,
2213 var.u.ind_idx as u32,
2214 ex,
2215 )?;
2216 }
2217 ExprKind::VarArgIndex => {
2218 mark_vararg_table_needed(fs);
2219 cg_store_abrk(
2220 fs,
2221 line,
2222 lua_code::opcodes::OpCode::SetTable,
2223 var.u.ind_t as u32,
2224 var.u.ind_idx as u32,
2225 ex,
2226 )?;
2227 }
2228 _ => {
2229 return Err(LuaError::syntax(format_args!(
2230 "internal: cg_storevar: invalid var kind {:?}",
2231 var.k
2232 )));
2233 }
2234 }
2235 cg_free_exp(fs, ex);
2236 Ok(())
2237}
2238
2239fn cg_store_abrk(
2243 fs: &mut FuncState,
2244 line: i32,
2245 op: lua_code::opcodes::OpCode,
2246 a: u32,
2247 b: u32,
2248 ex: &mut ExprDesc,
2249) -> Result<(), LuaError> {
2250 if cg_exp_to_const_k(fs, ex, lua_code::opcodes::MAXARG_C) {
2251 let inst = lua_code::opcodes::Instruction::abck(op, a, b, ex.u.info as u32, 1);
2252 emit_inst(fs, line, inst);
2253 return Ok(());
2254 }
2255 let c_reg = cg_exp_to_any_reg(fs, line, ex)?;
2256 let inst = lua_code::opcodes::Instruction::abck(op, a, b, c_reg as u32, 0);
2257 emit_inst(fs, line, inst);
2258 Ok(())
2259}
2260
2261fn cg_discharge_to_reg(
2266 fs: &mut FuncState,
2267 line: i32,
2268 e: &mut ExprDesc,
2269 reg: u8,
2270) -> Result<(), LuaError> {
2271 cg_discharge_vars(fs, line, e)?;
2272 match e.k {
2273 ExprKind::Jmp => {
2274 return Ok(());
2275 }
2276 ExprKind::NonReloc => {
2277 if e.u.info as u8 != reg {
2278 let inst = lua_code::opcodes::Instruction::abck(
2279 lua_code::opcodes::OpCode::Move,
2280 reg as u32,
2281 e.u.info as u32,
2282 0,
2283 0,
2284 );
2285 emit_inst(fs, line, inst);
2286 }
2287 }
2288 ExprKind::Reloc => {
2289 let pc = e.u.info as usize;
2290 let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc].0);
2291 lc.set_arg_a(reg as u32);
2292 fs.f.code[pc] = lua_types::opcode::Instruction::new(lc.0);
2293 }
2294 ExprKind::Nil => {
2295 let inst = lua_code::opcodes::Instruction::abck(
2296 lua_code::opcodes::OpCode::LoadNil,
2297 reg as u32,
2298 0,
2299 0,
2300 0,
2301 );
2302 emit_inst(fs, line, inst);
2303 }
2304 ExprKind::True => {
2305 let inst = lua_code::opcodes::Instruction::abck(
2306 lua_code::opcodes::OpCode::LoadTrue,
2307 reg as u32,
2308 0,
2309 0,
2310 0,
2311 );
2312 emit_inst(fs, line, inst);
2313 }
2314 ExprKind::False => {
2315 let inst = lua_code::opcodes::Instruction::abck(
2316 lua_code::opcodes::OpCode::LoadFalse,
2317 reg as u32,
2318 0,
2319 0,
2320 0,
2321 );
2322 emit_inst(fs, line, inst);
2323 }
2324 ExprKind::KInt => {
2325 let i = e.u.ival;
2326 let max = lua_code::opcodes::MAXARG_BX as i64 - lua_code::opcodes::OFFSET_S_BX as i64;
2327 let min = -(lua_code::opcodes::OFFSET_S_BX as i64);
2328 if i >= min && i <= max {
2329 let bx = (i as i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
2330 let inst = lua_code::opcodes::Instruction::abx(
2331 lua_code::opcodes::OpCode::LoadI,
2332 reg as u32,
2333 bx,
2334 );
2335 emit_inst(fs, line, inst);
2336 } else {
2337 let k_idx = add_k_value(fs, LuaValue::Int(i));
2338 let inst = lua_code::opcodes::Instruction::abx(
2339 lua_code::opcodes::OpCode::LoadK,
2340 reg as u32,
2341 k_idx as u32,
2342 );
2343 emit_inst(fs, line, inst);
2344 }
2345 }
2346 ExprKind::KFlt => {
2347 let f = e.u.nval;
2348 let max = lua_code::opcodes::MAXARG_BX as i64 - lua_code::opcodes::OFFSET_S_BX as i64;
2349 let min = -(lua_code::opcodes::OFFSET_S_BX as i64);
2350 let fi_opt: Option<i64> = if f.fract() == 0.0 && f.abs() < i64::MAX as f64 {
2351 Some(f as i64)
2352 } else {
2353 None
2354 };
2355 if let Some(fi) = fi_opt.filter(|fi| *fi >= min && *fi <= max) {
2356 let bx = (fi as i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
2357 let inst = lua_code::opcodes::Instruction::abx(
2358 lua_code::opcodes::OpCode::LoadF,
2359 reg as u32,
2360 bx,
2361 );
2362 emit_inst(fs, line, inst);
2363 } else {
2364 let k_idx = add_k_value(fs, LuaValue::Float(f));
2365 let inst = lua_code::opcodes::Instruction::abx(
2366 lua_code::opcodes::OpCode::LoadK,
2367 reg as u32,
2368 k_idx as u32,
2369 );
2370 emit_inst(fs, line, inst);
2371 }
2372 }
2373 ExprKind::KStr => {
2374 let s =
2375 e.u.strval.clone().ok_or_else(|| {
2376 LuaError::syntax(format_args!("internal: VKStr with no strval"))
2377 })?;
2378 let k_idx = add_k_string(fs, s);
2379 let inst = lua_code::opcodes::Instruction::abx(
2380 lua_code::opcodes::OpCode::LoadK,
2381 reg as u32,
2382 k_idx as u32,
2383 );
2384 emit_inst(fs, line, inst);
2385 }
2386 ExprKind::K => {
2387 let inst = lua_code::opcodes::Instruction::abx(
2388 lua_code::opcodes::OpCode::LoadK,
2389 reg as u32,
2390 e.u.info as u32,
2391 );
2392 emit_inst(fs, line, inst);
2393 }
2394 _ => {
2395 return Err(LuaError::syntax(format_args!(
2396 "internal: cg_discharge_to_reg cannot discharge {:?}",
2397 e.k
2398 )));
2399 }
2400 }
2401 e.u.info = reg as i32;
2402 e.k = ExprKind::NonReloc;
2403 Ok(())
2404}
2405
2406fn cg_need_value(fs: &FuncState, list: i32) -> bool {
2411 let mut list = list;
2412 while list != NO_JUMP {
2413 let ctrl_pc = cg_get_jump_control(fs, list);
2414 let ctrl = cg_inst_at(fs, ctrl_pc);
2415 if ctrl.opcode() != Some(lua_code::opcodes::OpCode::TestSet) {
2416 return true;
2417 }
2418 list = cg_get_jump(fs, list);
2419 }
2420 false
2421}
2422
2423fn cg_code_loadbool(fs: &mut FuncState, line: i32, reg: i32, op: lua_code::opcodes::OpCode) -> i32 {
2427 cg_get_label(fs);
2428 let inst = lua_code::opcodes::Instruction::abck(op, reg as u32, 0, 0, 0);
2429 emit_inst(fs, line, inst)
2430}
2431
2432fn cg_patch_list_aux(
2436 fs: &mut FuncState,
2437 list: i32,
2438 vtarget: i32,
2439 reg: u32,
2440 dtarget: i32,
2441) -> Result<(), LuaError> {
2442 let mut list = list;
2443 while list != NO_JUMP {
2444 let next = cg_get_jump(fs, list);
2445 if cg_patch_test_reg(fs, list, reg) {
2446 cg_fix_jump(fs, list, vtarget)?;
2447 } else {
2448 cg_fix_jump(fs, list, dtarget)?;
2449 }
2450 list = next;
2451 }
2452 Ok(())
2453}
2454
2455fn cg_exp_to_reg(fs: &mut FuncState, line: i32, e: &mut ExprDesc, reg: u8) -> Result<(), LuaError> {
2462 cg_discharge_to_reg(fs, line, e, reg)?;
2463 if e.k == ExprKind::Jmp {
2464 let info = e.u.info;
2465 cg_concat(fs, &mut e.t, info)?;
2466 }
2467 if e.t != e.f {
2468 let mut p_f = NO_JUMP;
2469 let mut p_t = NO_JUMP;
2470 if cg_need_value(fs, e.t) || cg_need_value(fs, e.f) {
2471 let fj = if e.k == ExprKind::Jmp {
2472 NO_JUMP
2473 } else {
2474 cg_jump(fs, line)
2475 };
2476 p_f = cg_code_loadbool(fs, line, reg as i32, lua_code::opcodes::OpCode::LFalseSkip);
2477 p_t = cg_code_loadbool(fs, line, reg as i32, lua_code::opcodes::OpCode::LoadTrue);
2478 cg_patch_to_here(fs, fj)?;
2479 }
2480 let final_pc = cg_get_label(fs);
2481 cg_patch_list_aux(fs, e.f, final_pc, reg as u32, p_f)?;
2482 cg_patch_list_aux(fs, e.t, final_pc, reg as u32, p_t)?;
2483 }
2484 e.f = NO_JUMP;
2485 e.t = NO_JUMP;
2486 e.u.info = reg as i32;
2487 e.k = ExprKind::NonReloc;
2488 Ok(())
2489}
2490
2491fn cg_free_reg_if_temp(fs: &mut FuncState, reg: i32) {
2495 if reg >= fs.nactvar as i32 {
2496 debug_assert!(reg < fs.freereg as i32);
2497 if reg == fs.freereg as i32 - 1 {
2498 fs.freereg -= 1;
2499 }
2500 }
2501}
2502
2503fn cg_check_global(
2520 fs: &mut FuncState,
2521 line: i32,
2522 target: &ExprDesc,
2523 name: GcRef<LuaString>,
2524) -> Result<(), LuaError> {
2525 let k = add_k_string(fs, name);
2526 let bx = if (k as u32) >= lua_code::opcodes::MAXARG_BX {
2527 0
2528 } else {
2529 (k + 1) as u32
2530 };
2531 let mut probe = target.clone();
2532 cg_exp_to_next_reg(fs, line, &mut probe)?;
2533 let reg = probe.u.info;
2534 let inst =
2535 lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::ErrNNil, reg as u32, bx);
2536 emit_inst(fs, line, inst);
2537 cg_free_reg(fs, reg);
2538 Ok(())
2539}
2540
2541fn cg_exp_to_next_reg(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
2542 cg_discharge_vars(fs, line, e)?;
2543 cg_free_exp(fs, e);
2544 let reg = reserve_reg(fs)?;
2545 cg_exp_to_reg(fs, line, e, reg)
2546}
2547
2548fn cg_set_returns(fs: &mut FuncState, e: &mut ExprDesc, nresults: i32) {
2550 let pc_idx = e.u.info as usize;
2551 let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
2552 if e.k == ExprKind::Call {
2553 lc.set_arg_c((nresults + 1) as u32);
2554 } else {
2555 debug_assert_eq!(e.k, ExprKind::VarArg);
2556 lc.set_arg_c((nresults + 1) as u32);
2557 lc.set_arg_a(fs.freereg as u32);
2558 fs.freereg += 1;
2564 bump_maxstack(fs, fs.freereg);
2565 }
2566 fs.f.code[pc_idx] = lua_types::opcode::Instruction::new(lc.0);
2567}
2568
2569fn cg_final_target(fs: &FuncState, mut i: i32) -> i32 {
2572 for _ in 0..100 {
2573 let inst = cg_inst_at(fs, i);
2574 if inst.opcode() != Some(lua_code::opcodes::OpCode::Jmp) {
2575 break;
2576 }
2577 i += inst.arg_s_j() + 1;
2578 }
2579 i
2580}
2581
2582fn cg_finish(fs: &mut FuncState) {
2588 use lua_code::opcodes::OpCode;
2589 let needclose = fs.needclose;
2590 let is_vararg = fs.f.is_vararg;
2591 let numparams = fs.f.numparams as u32;
2592 let pc_end = fs.pc;
2593 for i in 0..pc_end {
2594 let mut inst = cg_inst_at(fs, i);
2595 match inst.opcode() {
2596 Some(OpCode::Return0) | Some(OpCode::Return1) => {
2597 if !(needclose || is_vararg) {
2598 continue;
2599 }
2600 inst.set_opcode(OpCode::Return);
2601 if needclose {
2602 inst.set_arg_k(1);
2603 }
2604 if is_vararg {
2605 inst.set_arg_c(numparams + 1);
2606 }
2607 cg_set_inst_at(fs, i, inst);
2608 }
2609 Some(OpCode::Return) | Some(OpCode::TailCall) => {
2610 if needclose {
2611 inst.set_arg_k(1);
2612 }
2613 if is_vararg {
2614 inst.set_arg_c(numparams + 1);
2615 }
2616 cg_set_inst_at(fs, i, inst);
2617 }
2618 Some(OpCode::Jmp) => {
2619 let target = cg_final_target(fs, i);
2620 let _ = cg_fix_jump(fs, i, target);
2621 }
2622 _ => {}
2623 }
2624 }
2625}
2626
2627fn cg_emit_return(
2630 fs: &mut FuncState,
2631 line: i32,
2632 first: i32,
2633 nret: i32,
2634 version: lua_types::LuaVersion,
2635) -> Result<(), LuaError> {
2636 let op = match nret {
2637 0 => lua_code::opcodes::OpCode::Return0,
2638 1 => lua_code::opcodes::OpCode::Return1,
2639 _ => lua_code::opcodes::OpCode::Return,
2640 };
2641 if matches!(version, lua_types::LuaVersion::V55) {
2642 check_limit(fs, nret + 1, lua_code::opcodes::MAXARG_B as i32, "returns")?;
2643 }
2644 let inst = lua_code::opcodes::Instruction::abck(op, first as u32, (nret + 1) as u32, 0, 0);
2645 emit_inst(fs, line, inst);
2646 Ok(())
2647}
2648
2649fn error_expected(ls: &mut LexState, token: TokenKind) -> LuaError {
2659 let tok_str = lua_lex::token2str(&ls.lex, token);
2660 let mut msg: Vec<u8> = Vec::with_capacity(tok_str.len() + 10);
2661 msg.extend_from_slice(&tok_str);
2662 msg.extend_from_slice(b" expected");
2663 lua_lex::syntax_error(&mut ls.lex, &msg)
2664}
2665
2666fn error_limit(fs: &FuncState, limit: i32, what: &str) -> LuaError {
2668 let line = fs.f.linedefined;
2669 if line == 0 {
2670 LuaError::syntax(format_args!(
2671 "too many {} (limit is {}) in main function",
2672 what, limit
2673 ))
2674 } else {
2675 LuaError::syntax(format_args!(
2676 "too many {} (limit is {}) in function at line {}",
2677 what, limit, line
2678 ))
2679 }
2680}
2681
2682fn check_limit(fs: &FuncState, v: i32, l: i32, what: &str) -> Result<(), LuaError> {
2683 if v > l {
2684 return Err(error_limit(fs, l, what));
2685 }
2686 Ok(())
2687}
2688
2689fn test_next(ls: &mut LexState, state: &mut LuaState, c: TokenKind) -> Result<bool, LuaError> {
2693 if ls.t.token == c {
2694 lex_next(ls, state)?;
2695 Ok(true)
2696 } else {
2697 Ok(false)
2698 }
2699}
2700
2701fn check(ls: &mut LexState, c: TokenKind) -> Result<(), LuaError> {
2702 if ls.t.token != c {
2703 return Err(error_expected(ls, c));
2704 }
2705 Ok(())
2706}
2707
2708fn check_next(ls: &mut LexState, state: &mut LuaState, c: TokenKind) -> Result<(), LuaError> {
2709 check(ls, c)?;
2710 lex_next(ls, state)?;
2711 Ok(())
2712}
2713
2714fn str_check_name(ls: &mut LexState, state: &mut LuaState) -> Result<GcRef<LuaString>, LuaError> {
2716 check(ls, TK_NAME)?;
2717 let ts =
2718 ls.t.seminfo
2719 .ts
2720 .clone()
2721 .ok_or_else(|| LuaError::syntax(format_args!("name expected")))?;
2722 lex_next(ls, state)?;
2723 Ok(ts)
2724}
2725
2726fn init_exp(e: &mut ExprDesc, k: ExprKind, i: i32) {
2727 e.f = NO_JUMP;
2728 e.t = NO_JUMP;
2729 e.k = k;
2730 e.u.info = i;
2731}
2732
2733fn codestring(e: &mut ExprDesc, s: GcRef<LuaString>) {
2734 e.f = NO_JUMP;
2735 e.t = NO_JUMP;
2736 e.k = ExprKind::KStr;
2737 e.u.strval = Some(s);
2738}
2739
2740fn codename(ls: &mut LexState, state: &mut LuaState, e: &mut ExprDesc) -> Result<(), LuaError> {
2741 let name = str_check_name(ls, state)?;
2742 codestring(e, name);
2743 Ok(())
2744}
2745
2746fn register_local_var(
2751 _ls: &mut LexState,
2752 _state: &mut LuaState,
2753 fs: &mut FuncState,
2754 varname: GcRef<LuaString>,
2755) -> Result<i32, LuaError> {
2756 let idx = fs.ndebugvars as usize;
2758 while fs.f.locvars.len() <= idx {
2759 fs.f.locvars.push(LocalVar {
2760 varname: varname.clone(), startpc: 0,
2762 endpc: 0,
2763 });
2764 }
2765 fs.f.locvars[idx].varname = varname;
2766 fs.f.locvars[idx].startpc = fs.pc;
2767 let result = fs.ndebugvars as i32;
2768 fs.ndebugvars += 1;
2769 Ok(result)
2770}
2771
2772fn new_local_var(
2775 ls: &mut LexState,
2776 _state: &mut LuaState,
2777 name: GcRef<LuaString>,
2778) -> Result<i32, LuaError> {
2779 let fs = ls.fs.as_ref().unwrap();
2780 let n = ls.dyd.actvar.len() as i32;
2781 let first_local = fs.firstlocal;
2782 check_limit(fs, n + 1 - first_local, MAX_VARS, "local variables")?;
2783
2784 let mut var = VarDesc::default();
2785 var.kind = VarKind::Reg;
2786 var.name = Some(name);
2787 ls.dyd.actvar.push(var);
2788 let result = ls.dyd.actvar.len() as i32 - 1 - first_local;
2789 Ok(result)
2790}
2791
2792fn get_local_var_desc<'a>(ls: &'a LexState, fs: &FuncState, vidx: i32) -> &'a VarDesc {
2794 &ls.dyd.actvar[(fs.firstlocal + vidx) as usize]
2795}
2796
2797fn get_local_var_desc_mut(ls: &mut LexState, first_local: i32, vidx: i32) -> &mut VarDesc {
2798 &mut ls.dyd.actvar[(first_local + vidx) as usize]
2799}
2800
2801fn reg_level(ls: &LexState, fs: &FuncState, nvar: i32) -> i32 {
2803 let mut nvar = nvar;
2804 while nvar > 0 {
2805 nvar -= 1;
2806 let vd = get_local_var_desc(ls, fs, nvar);
2807 if vd.kind != VarKind::CompileTimeConst {
2808 return vd.ridx as i32 + 1;
2809 }
2810 }
2811 0
2812}
2813
2814pub fn nvarstack(ls: &LexState, fs: &FuncState) -> i32 {
2817 reg_level(ls, fs, fs.nactvar as i32)
2818}
2819
2820fn init_var(ls: &LexState, fs: &FuncState, e: &mut ExprDesc, vidx: i32) {
2821 e.f = NO_JUMP;
2822 e.t = NO_JUMP;
2823 e.k = ExprKind::Local;
2824 e.u.var_vidx = vidx as u16;
2825 e.u.var_ridx = get_local_var_desc(ls, fs, vidx).ridx;
2826}
2827
2828fn check_readonly(ls: &mut LexState, state: &mut LuaState, e: &ExprDesc) -> Result<(), LuaError> {
2830 if let Some(name) = e.u.global_const_name.as_ref() {
2833 let msg = format!(
2834 "attempt to assign to const variable '{}'",
2835 String::from_utf8_lossy(name.as_bytes())
2836 );
2837 return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
2839 }
2840 let varname: Option<GcRef<LuaString>> = {
2841 let fs = ls.fs.as_ref().unwrap();
2842 match e.k {
2843 ExprKind::Const => ls.dyd.actvar[e.u.info as usize].name.clone(),
2844 ExprKind::Local | ExprKind::VarArgVar => {
2845 let vd = get_local_var_desc(ls, fs, e.u.var_vidx as i32);
2846 if vd.kind != VarKind::Reg {
2847 vd.name.clone()
2848 } else {
2849 None
2850 }
2851 }
2852 ExprKind::UpVal => {
2853 let up = &fs.f.upvalues[e.u.info as usize];
2854 if VarKind::from_u8(up.kind) != VarKind::Reg {
2855 up.name.clone()
2856 } else {
2857 None
2858 }
2859 }
2860 _ => None,
2861 }
2862 };
2863 if let Some(vname) = varname {
2864 let _ = state;
2869 let msg = format!(
2870 "attempt to assign to const variable '{}'",
2871 String::from_utf8_lossy(vname.as_bytes())
2872 );
2873 return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
2874 }
2875 Ok(())
2876}
2877
2878fn adjust_local_vars(ls: &mut LexState, state: &mut LuaState, nvars: i32) -> Result<(), LuaError> {
2880 let first_local = ls.fs.as_ref().unwrap().firstlocal;
2882 let nactvar_start = ls.fs.as_ref().unwrap().nactvar as i32;
2883 let mut reglevel_val = {
2884 let fs = ls.fs.as_ref().unwrap();
2885 reg_level(ls, fs, fs.nactvar as i32)
2886 };
2887
2888 for i in 0..nvars {
2889 let vidx = nactvar_start + i;
2890 ls.fs.as_mut().unwrap().nactvar += 1;
2891 let var_name = ls.dyd.actvar[(first_local + vidx) as usize].name.clone();
2892 ls.dyd.actvar[(first_local + vidx) as usize].ridx = reglevel_val as u8;
2893 reglevel_val += 1;
2894 if let Some(vn) = var_name {
2895 let mut fs_box = ls.fs.take().unwrap();
2896 let pidx_result = register_local_var(ls, state, &mut fs_box, vn);
2897 ls.fs = Some(fs_box);
2898 let pidx = pidx_result?;
2899 ls.dyd.actvar[(first_local + vidx) as usize].pidx = pidx as i16;
2900 } else {
2901 }
2903 }
2904 Ok(())
2905}
2906
2907fn remove_vars(ls: &mut LexState, fs: &mut FuncState, tolevel: i32) {
2909 let delta = fs.nactvar as i32 - tolevel;
2917 while fs.nactvar as i32 > tolevel {
2918 fs.nactvar -= 1;
2919 let nactvar = fs.nactvar as i32;
2920 let vd_kind = {
2921 let first_local = fs.firstlocal;
2922 ls.dyd
2923 .actvar
2924 .get((first_local + nactvar) as usize)
2925 .map(|v| v.kind)
2926 .unwrap_or(VarKind::Reg)
2927 };
2928 if vd_kind != VarKind::CompileTimeConst {
2929 let vd_pidx = {
2930 let first_local = fs.firstlocal;
2931 ls.dyd
2932 .actvar
2933 .get((first_local + nactvar) as usize)
2934 .map(|v| v.pidx)
2935 .unwrap_or(0)
2936 };
2937 if let Some(lv) = fs.f.locvars.get_mut(vd_pidx as usize) {
2938 lv.endpc = fs.pc;
2939 }
2940 }
2941 }
2942 if delta > 0 {
2943 let new_len = ls.dyd.actvar.len().saturating_sub(delta as usize);
2944 ls.dyd.actvar.truncate(new_len);
2945 }
2946}
2947
2948fn search_upvalue(fs: &FuncState, name: &GcRef<LuaString>) -> i32 {
2952 for (i, up) in fs.f.upvalues.iter().enumerate() {
2953 if up.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
2954 return i as i32;
2955 }
2956 }
2957 -1
2958}
2959
2960fn alloc_upvalue(fs: &mut FuncState) -> Result<usize, LuaError> {
2962 if fs.nups as i32 + 1 > MAX_UPVAL as i32 {
2963 return Err(error_limit(fs, MAX_UPVAL as i32, "upvalues"));
2964 }
2965 let idx = fs.nups as usize;
2966 while fs.f.upvalues.len() <= idx {
2967 fs.f.upvalues.push(UpvalDesc {
2968 name: None,
2969 instack: false,
2970 idx: 0,
2971 kind: 0,
2972 });
2973 }
2974 fs.nups += 1;
2975 Ok(idx)
2976}
2977
2978fn new_upvalue(
2980 ls: &LexState,
2981 fs: &mut FuncState,
2982 name: GcRef<LuaString>,
2983 v: &ExprDesc,
2984) -> Result<i32, LuaError> {
2985 let idx = alloc_upvalue(fs)?;
2986 let kind: u8 = if v.k == ExprKind::Local {
2987 let prev = fs
2988 .prev
2989 .as_deref()
2990 .expect("upvalue capture requires enclosing FuncState");
2991 get_local_var_desc(ls, prev, v.u.var_vidx as i32)
2992 .kind
2993 .as_u8()
2994 } else {
2995 let prev = fs
2996 .prev
2997 .as_deref()
2998 .expect("upvalue chain requires enclosing FuncState");
2999 prev.f.upvalues[v.u.info as usize].kind
3000 };
3001 let up = &mut fs.f.upvalues[idx];
3002 if v.k == ExprKind::Local {
3003 up.instack = true;
3004 up.idx = v.u.var_ridx;
3005 } else {
3006 up.instack = false;
3007 up.idx = v.u.info as u8;
3008 }
3009 up.kind = kind;
3010 up.name = Some(name);
3011 Ok(fs.nups as i32 - 1)
3012}
3013
3014fn searchvar(ls: &LexState, fs: &FuncState, n: &GcRef<LuaString>, var: &mut ExprDesc) -> i32 {
3016 let mut i = fs.nactvar as i32 - 1;
3017 while i >= 0 {
3018 let vd = get_local_var_desc(ls, fs, i);
3019 if vd.name.as_ref().map_or(false, |nm| GcRef::ptr_eq(nm, n)) {
3020 if vd.kind == VarKind::CompileTimeConst {
3021 init_exp(var, ExprKind::Const, fs.firstlocal + i);
3022 } else {
3023 init_var(ls, fs, var, i);
3024 if vd.kind == VarKind::VarArg {
3025 var.k = ExprKind::VarArgVar;
3026 }
3027 }
3028 return var.k as i32; }
3030 i -= 1;
3031 }
3032 -1
3033}
3034
3035fn markupval(fs: &mut FuncState, level: i32) {
3037 let mut current = fs.bl.as_deref_mut();
3038 while let Some(b) = current {
3039 if (b.nactvar as i32) <= level {
3040 b.upval = true;
3041 break;
3042 }
3043 current = b.previous.as_deref_mut();
3044 }
3045 fs.needclose = true;
3046}
3047
3048fn marktobeclosed(fs: &mut FuncState) {
3049 if let Some(bl) = fs.bl.as_mut() {
3050 bl.upval = true;
3051 bl.insidetbc = true;
3052 }
3053 fs.needclose = true;
3054}
3055
3056fn singlevaraux(
3061 ls: &LexState,
3062 fs: Option<&mut FuncState>,
3063 n: &GcRef<LuaString>,
3064 var: &mut ExprDesc,
3065 base: bool,
3066) -> Result<(), LuaError> {
3067 match fs {
3068 None => {
3069 init_exp(var, ExprKind::Void, 0);
3070 }
3071 Some(fs) => {
3072 let v = searchvar(ls, fs, n, var);
3073 if v >= 0 {
3074 if !base {
3075 if var.k == ExprKind::VarArgVar {
3076 mark_vararg_table_needed(fs);
3077 var.k = ExprKind::Local;
3078 }
3079 if var.k == ExprKind::Local {
3080 markupval(fs, var.u.var_vidx as i32);
3081 }
3082 }
3083 } else {
3084 let idx = search_upvalue(fs, n);
3085 let final_idx = if idx < 0 {
3086 singlevaraux(ls, fs.prev.as_deref_mut(), n, var, false)?;
3087 if var.k == ExprKind::Local
3088 || var.k == ExprKind::VarArgVar
3089 || var.k == ExprKind::UpVal
3090 {
3091 if var.k == ExprKind::VarArgVar {
3092 var.k = ExprKind::Local;
3093 }
3094 new_upvalue(ls, fs, n.clone(), var)?
3095 } else {
3096 return Ok(());
3097 }
3098 } else {
3099 idx
3100 };
3101 init_exp(var, ExprKind::UpVal, final_idx);
3102 }
3103 }
3104 }
3105 Ok(())
3106}
3107
3108fn singlevar(ls: &mut LexState, state: &mut LuaState, var: &mut ExprDesc) -> Result<(), LuaError> {
3110 let name_line = ls.linenumber;
3111 let varname = str_check_name(ls, state)?;
3112 let mut fs_box = ls.fs.take();
3113 let recurse_result = singlevaraux(ls, fs_box.as_deref_mut(), &varname, var, true);
3114 ls.fs = fs_box;
3115 recurse_result?;
3116 if state.global().lua_version == lua_types::LuaVersion::V55 {
3117 match var.k {
3118 ExprKind::Local | ExprKind::Const => {
3119 if let Some(global_level) = latest_matching_global_barrier_current(ls, &varname) {
3120 let local_level = scope_level_for_local_level(ls, var.u.var_vidx as u8);
3121 if global_level > local_level {
3122 init_exp(var, ExprKind::Void, 0);
3123 }
3124 }
3125 }
3126 ExprKind::UpVal => {
3127 if is_active_global_function_name(ls, &varname) {
3128 init_exp(var, ExprKind::Void, 0);
3129 }
3130 }
3131 _ => {}
3132 }
3133 }
3134 if var.k == ExprKind::Void {
3135 let mut declared_const: Option<bool> = None;
3140 for (n, c) in ls.declared_globals.iter().rev() {
3141 if GcRef::ptr_eq(n, &varname) {
3142 declared_const = Some(*c);
3143 break;
3144 }
3145 }
3146 let is_const_global = match declared_const {
3147 Some(c) => c,
3148 None if ls.global_wildcard => ls.global_wildcard_const,
3149 None if ls.global_strict => {
3150 let msg = format!(
3151 "variable '{}' not declared",
3152 String::from_utf8_lossy(varname.as_bytes())
3153 );
3154 let saved_line = ls.lex.linenumber;
3156 ls.lex.linenumber = name_line;
3157 let err = lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0);
3158 ls.lex.linenumber = saved_line;
3159 return Err(err);
3160 }
3161 None => false,
3162 };
3163 let envn = ls
3164 .envn
3165 .clone()
3166 .expect("envn must be set when resolving globals");
3167 if has_active_global_barrier(ls, &envn) {
3168 let msg = format!(
3169 "{} is global when accessing variable '{}'",
3170 lua_lex::LUA_ENV.escape_ascii(),
3171 String::from_utf8_lossy(varname.as_bytes())
3172 );
3173 return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
3174 }
3175 let mut env_var = ExprDesc::default();
3176 let mut fs_box = ls.fs.take();
3177 let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut env_var, true);
3178 ls.fs = fs_box;
3179 r?;
3180 debug_assert!(env_var.k != ExprKind::Void, "_ENV must resolve");
3181 let line = ls.lastline;
3182 let fs = ls.fs.as_mut().unwrap();
3183 cg_exp_to_any_reg_up(fs, line, &mut env_var)?;
3184 let mut key = ExprDesc::default();
3185 let const_name = if is_const_global {
3186 Some(varname.clone())
3187 } else {
3188 None
3189 };
3190 codestring(&mut key, varname);
3191 cg_indexed(fs, line, &mut env_var, &mut key)?;
3192 *var = env_var;
3193 var.u.global_const_name = const_name;
3194 }
3195 Ok(())
3196}
3197
3198fn adjust_assign(
3199 ls: &mut LexState,
3200 _state: &mut LuaState,
3201 nvars: i32,
3202 nexps: i32,
3203 e: &mut ExprDesc,
3204) -> Result<(), LuaError> {
3205 let needed = nvars - nexps;
3206 let line = ls.lastline;
3207 let fs = ls.fs.as_mut().unwrap();
3208 if e.k.has_mult_ret() {
3209 let extra = if needed + 1 < 0 { 0 } else { needed + 1 };
3210 cg_set_returns(fs, e, extra);
3211 } else {
3212 if e.k != ExprKind::Void {
3213 cg_exp_to_next_reg(fs, line, e)?;
3214 }
3215 if needed > 0 {
3216 let from = fs.freereg as i32;
3217 cg_emit_nil(fs, line, from, needed);
3218 }
3219 }
3220 if needed > 0 {
3221 for _ in 0..needed {
3222 reserve_reg(fs)?;
3223 }
3224 } else {
3225 fs.freereg = (fs.freereg as i32 + needed) as u8;
3226 }
3227 Ok(())
3228}
3229
3230fn cg_emit_newtable(fs: &mut FuncState, line: i32) -> i32 {
3234 let newtable =
3235 lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::NewTable, 0, 0, 0, 0);
3236 let pc = emit_inst(fs, line, newtable);
3237 let extra = lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, 0);
3238 emit_inst(fs, line, extra);
3239 pc
3240}
3241
3242fn cg_settablesize(fs: &mut FuncState, pc: i32, ra: i32, asize: i32, hsize: i32) {
3246 let rb = if hsize != 0 {
3247 (hsize as u32).next_power_of_two().trailing_zeros() as i32 + 1
3248 } else {
3249 0
3250 };
3251 let maxc = lua_code::opcodes::MAXARG_C as i32 + 1;
3252 let extra = asize / maxc;
3253 let rc = asize % maxc;
3254 let k = if extra > 0 { 1u32 } else { 0u32 };
3255 let newtable = lua_code::opcodes::Instruction::abck(
3256 lua_code::opcodes::OpCode::NewTable,
3257 ra as u32,
3258 rb as u32,
3259 rc as u32,
3260 k,
3261 );
3262 fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(newtable.0);
3263 let extra_inst =
3264 lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, extra as u32);
3265 fs.f.code[pc as usize + 1] = lua_types::opcode::Instruction::new(extra_inst.0);
3266}
3267
3268fn cg_setlist(fs: &mut FuncState, line: i32, base: i32, nelems: i32, tostore: i32) {
3273 let maxc = lua_code::opcodes::MAXARG_C as i32;
3274 let tostore_arg = if tostore == LUA_MULTRET { 0 } else { tostore };
3275 if nelems <= maxc {
3276 let inst = lua_code::opcodes::Instruction::abck(
3277 lua_code::opcodes::OpCode::SetList,
3278 base as u32,
3279 tostore_arg as u32,
3280 nelems as u32,
3281 0,
3282 );
3283 emit_inst(fs, line, inst);
3284 } else {
3285 let extra = nelems / (maxc + 1);
3286 let nelems_lo = nelems % (maxc + 1);
3287 let inst = lua_code::opcodes::Instruction::abck(
3288 lua_code::opcodes::OpCode::SetList,
3289 base as u32,
3290 tostore_arg as u32,
3291 nelems_lo as u32,
3292 1,
3293 );
3294 emit_inst(fs, line, inst);
3295 let extra_inst =
3296 lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, extra as u32);
3297 emit_inst(fs, line, extra_inst);
3298 }
3299 fs.freereg = (base + 1) as u8;
3300}
3301
3302fn cg_indexed(
3307 fs: &mut FuncState,
3308 line: i32,
3309 t: &mut ExprDesc,
3310 k: &mut ExprDesc,
3311) -> Result<(), LuaError> {
3312 t.u.global_const_name = None;
3313 if k.k == ExprKind::KStr {
3314 let s =
3315 k.u.strval
3316 .clone()
3317 .ok_or_else(|| LuaError::syntax(format_args!("internal: VKStr with no strval")))?;
3318 let k_idx = add_k_string(fs, s);
3319 k.u.info = k_idx;
3320 k.k = ExprKind::K;
3321 }
3322 let k_is_kstr =
3323 k.k == ExprKind::K && k.u.info >= 0 && (k.u.info as u32) <= lua_code::opcodes::MAXARG_B;
3324 if t.k == ExprKind::VarArgVar {
3325 cg_exp_to_any_reg(fs, line, k)?;
3326 t.u.ind_t = t.u.var_ridx;
3327 t.u.ind_idx = k.u.info as i16;
3328 t.k = ExprKind::VarArgIndex;
3329 return Ok(());
3330 }
3331 if t.k == ExprKind::UpVal && !k_is_kstr {
3332 cg_exp_to_any_reg(fs, line, t)?;
3333 }
3334 if t.k == ExprKind::UpVal {
3335 let temp = t.u.info as u8;
3336 t.u.ind_t = temp;
3337 t.u.ind_idx = k.u.info as i16;
3338 t.k = ExprKind::IndexUp;
3339 return Ok(());
3340 }
3341 let t_reg = match t.k {
3342 ExprKind::Local => t.u.var_ridx,
3343 ExprKind::NonReloc => t.u.info as u8,
3344 _ => {
3345 return Err(LuaError::syntax(format_args!(
3346 "internal: cg_indexed on non-register table kind {:?}",
3347 t.k
3348 )))
3349 }
3350 };
3351 t.u.ind_t = t_reg;
3352 if k.k == ExprKind::K && k_is_kstr {
3353 t.u.ind_idx = k.u.info as i16;
3354 t.k = ExprKind::IndexStr;
3355 } else if k.k == ExprKind::KInt && cg_fits_int_key(k.u.ival) {
3356 t.u.ind_idx = k.u.ival as i16;
3357 t.k = ExprKind::IndexI;
3358 } else {
3359 cg_exp_to_any_reg(fs, line, k)?;
3360 t.u.ind_idx = k.u.info as i16;
3361 t.k = ExprKind::Indexed;
3362 }
3363 Ok(())
3364}
3365
3366fn cg_fits_int_key(i: i64) -> bool {
3367 i >= 0 && (i as u32) <= lua_code::opcodes::MAXARG_C
3368}
3369
3370fn cg_self(
3374 fs: &mut FuncState,
3375 line: i32,
3376 e: &mut ExprDesc,
3377 key: &mut ExprDesc,
3378 keep_self_opcode_for_register_key: bool,
3379) -> Result<(), LuaError> {
3380 cg_exp_to_any_reg(fs, line, e)?;
3381 let ereg = e.u.info;
3382 cg_free_exp(fs, e);
3383 let base = fs.freereg as i32;
3384 e.u.info = base;
3385 e.k = ExprKind::NonReloc;
3386 reserve_regs(fs, 2)?;
3387 let key_str = key.u.strval.clone().ok_or_else(|| {
3388 LuaError::syntax(format_args!(
3389 "internal: cg_self expected VKStr key, got {:?}",
3390 key.k
3391 ))
3392 })?;
3393 let k_idx = add_k_string(fs, key_str);
3394 if (k_idx as u32) <= lua_code::opcodes::MAXINDEXRK {
3395 let inst = lua_code::opcodes::Instruction::abck(
3396 lua_code::opcodes::OpCode::Self_,
3397 base as u32,
3398 ereg as u32,
3399 k_idx as u32,
3400 1,
3401 );
3402 emit_inst(fs, line, inst);
3403 } else if keep_self_opcode_for_register_key {
3404 key.k = ExprKind::K;
3405 key.u.info = k_idx;
3406 cg_exp_to_any_reg(fs, line, key)?;
3407 let inst = lua_code::opcodes::Instruction::abck(
3408 lua_code::opcodes::OpCode::Self_,
3409 base as u32,
3410 ereg as u32,
3411 key.u.info as u32,
3412 0,
3413 );
3414 emit_inst(fs, line, inst);
3415 } else {
3416 key.k = ExprKind::K;
3417 key.u.info = k_idx;
3418 cg_exp_to_any_reg(fs, line, key)?;
3419 let move_inst = lua_code::opcodes::Instruction::abck(
3420 lua_code::opcodes::OpCode::Move,
3421 (base + 1) as u32,
3422 ereg as u32,
3423 0,
3424 0,
3425 );
3426 emit_inst(fs, line, move_inst);
3427 let get_inst = lua_code::opcodes::Instruction::abck(
3428 lua_code::opcodes::OpCode::GetTable,
3429 base as u32,
3430 ereg as u32,
3431 key.u.info as u32,
3432 0,
3433 );
3434 emit_inst(fs, line, get_inst);
3435 }
3436 cg_free_exp(fs, key);
3437 Ok(())
3438}
3439
3440fn cg_exp_to_any_reg_up(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
3443 if matches!(e.k, ExprKind::UpVal | ExprKind::K | ExprKind::VarArgVar) {
3444 return Ok(());
3445 }
3446 cg_exp_to_any_reg(fs, line, e)?;
3447 Ok(())
3448}
3449
3450fn cg_emit_nil(fs: &mut FuncState, line: i32, from: i32, n: i32) {
3454 let inst = lua_code::opcodes::Instruction::abck(
3455 lua_code::opcodes::OpCode::LoadNil,
3456 from as u32,
3457 (n - 1) as u32,
3458 0,
3459 0,
3460 );
3461 emit_inst(fs, line, inst);
3462}
3463
3464fn current_scope_level(ls: &LexState) -> u8 {
3467 let (local_count, first_barrier) = ls.fs.as_ref().map_or((0usize, 0usize), |fs| {
3468 (fs.nactvar as usize, fs.first_scope_barrier)
3469 });
3470 let barrier_count = ls.scope_barriers.len().saturating_sub(first_barrier);
3471 let level = local_count + barrier_count;
3472 level.min(u8::MAX as usize) as u8
3473}
3474
3475fn local_level_for_scope_level(ls: &LexState, scope_level: u8) -> i32 {
3476 let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3477 let barriers_before = ls.scope_barriers[first_barrier..]
3478 .iter()
3479 .filter(|b| b.level < scope_level)
3480 .count();
3481 let locals = scope_level as i32 - barriers_before as i32;
3482 let max_locals = ls.fs.as_ref().map_or(0i32, |fs| fs.nactvar as i32);
3483 locals.clamp(0, max_locals)
3484}
3485
3486fn scope_level_for_local_level(ls: &LexState, local_level: u8) -> u8 {
3487 let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3488 let target = local_level as usize;
3489 let mut locals_seen = 0usize;
3490 for level in 0..=current_scope_level(ls) {
3491 if ls.scope_barriers[first_barrier..]
3492 .iter()
3493 .any(|b| b.level == level)
3494 {
3495 continue;
3496 }
3497 if locals_seen == target {
3498 return level;
3499 }
3500 locals_seen += 1;
3501 }
3502 local_level
3503}
3504
3505fn add_scope_barrier(ls: &mut LexState, name: GcRef<LuaString>) {
3506 let level = current_scope_level(ls);
3507 ls.scope_barriers.push(ScopeBarrier { level, name });
3508}
3509
3510fn latest_matching_global_barrier_current(ls: &LexState, name: &GcRef<LuaString>) -> Option<u8> {
3511 let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3512 ls.scope_barriers[first_barrier..]
3513 .iter()
3514 .rev()
3515 .find(|b| GcRef::ptr_eq(&b.name, name))
3516 .map(|b| b.level)
3517}
3518
3519fn has_active_global_barrier(ls: &LexState, name: &GcRef<LuaString>) -> bool {
3520 ls.scope_barriers
3521 .iter()
3522 .rev()
3523 .any(|b| GcRef::ptr_eq(&b.name, name))
3524}
3525
3526fn is_active_global_function_name(ls: &LexState, name: &GcRef<LuaString>) -> bool {
3527 ls.global_function_names
3528 .iter()
3529 .rev()
3530 .any(|n| GcRef::ptr_eq(n, name))
3531}
3532
3533fn scope_name_at(ls: &LexState, level: u8, label_nactvar: u8) -> Vec<u8> {
3534 let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3535 for scope_level in level..label_nactvar {
3536 if let Some(barrier) = ls.scope_barriers[first_barrier..]
3537 .iter()
3538 .find(|b| b.level == scope_level)
3539 {
3540 return barrier.name.as_bytes().to_vec();
3541 }
3542
3543 let barriers_before = ls.scope_barriers[first_barrier..]
3544 .iter()
3545 .filter(|b| b.level < scope_level)
3546 .count();
3547 let vidx = scope_level as i32 - barriers_before as i32;
3548 if vidx < 0 {
3549 continue;
3550 }
3551 if let Some(name) = ls.fs.as_ref().and_then(|fs| {
3552 if (fs.firstlocal + vidx) >= 0
3553 && ((fs.firstlocal + vidx) as usize) < ls.dyd.actvar.len()
3554 {
3555 let vd = get_local_var_desc(ls, fs, vidx);
3556 vd.name.as_ref().map(|n| n.as_bytes().to_vec())
3557 } else {
3558 None
3559 }
3560 }) {
3561 return name;
3562 }
3563 }
3564
3565 b"*".to_vec()
3566}
3567
3568fn jumpscopeerror(
3569 ls: &LexState,
3570 version: lua_types::LuaVersion,
3571 gt_idx: usize,
3572 label_nactvar: u8,
3573) -> LuaError {
3574 let gt = &ls.dyd.gt[gt_idx];
3575 let line = gt.line;
3576 let gt_name_bytes: &[u8] = gt.name.as_ref().map(|n| n.as_bytes()).unwrap_or(b"");
3577 let gt_name = String::from_utf8_lossy(gt_name_bytes);
3578 let varname_bytes = scope_name_at(ls, gt.nactvar, label_nactvar);
3579 let varname = String::from_utf8_lossy(&varname_bytes);
3580 if version == lua_types::LuaVersion::V55 {
3581 LuaError::syntax(format_args!(
3582 "<goto {}> at line {} jumps into the scope of '{}'",
3583 gt_name, line, varname
3584 ))
3585 } else {
3586 LuaError::syntax(format_args!(
3587 "<goto {}> at line {} jumps into the scope of local '{}'",
3588 gt_name, line, varname
3589 ))
3590 }
3591}
3592
3593fn solvegoto(
3595 ls: &mut LexState,
3596 state: &mut LuaState,
3597 g: usize,
3598 label_pc: i32,
3599 label_nactvar: u8,
3600) -> Result<(), LuaError> {
3601 if ls.dyd.gt[g].nactvar < label_nactvar {
3602 let version = state.global().lua_version;
3603 return Err(jumpscopeerror(ls, version, g, label_nactvar));
3604 }
3605 let gt_pc = ls.dyd.gt[g].pc;
3606 cg_patch_list(ls.fs.as_mut().unwrap(), gt_pc, label_pc)?;
3607 ls.dyd.gt.remove(g);
3608 Ok(())
3609}
3610
3611fn findlabel_from(ls: &LexState, name: &GcRef<LuaString>, first: usize) -> Option<usize> {
3621 for i in first..ls.dyd.label.len() {
3622 let lb = &ls.dyd.label[i];
3623 if lb.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
3624 return Some(i);
3625 }
3626 }
3627 None
3628}
3629
3630fn findlabel_for_goto(ls: &LexState, state: &LuaState, name: &GcRef<LuaString>) -> Option<usize> {
3634 let block_scoped = matches!(
3635 state.global().lua_version,
3636 lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
3637 );
3638 let first = if block_scoped {
3639 ls.fs
3640 .as_ref()
3641 .unwrap()
3642 .bl
3643 .as_ref()
3644 .map_or(0, |b| b.firstlabel) as usize
3645 } else {
3646 ls.fs.as_ref().unwrap().firstlabel as usize
3647 };
3648 findlabel_from(ls, name, first)
3649}
3650
3651fn new_label_entry(
3653 ls: &mut LexState,
3654 _state: &mut LuaState,
3655 is_goto: bool,
3656 name: GcRef<LuaString>,
3657 line: i32,
3658 pc: i32,
3659) -> Result<usize, LuaError> {
3660 let nactvar = current_scope_level(ls);
3661 let entry = LabelDesc {
3662 name: Some(name),
3663 pc,
3664 line,
3665 nactvar,
3666 close: false,
3667 };
3668 let list = if is_goto {
3669 &mut ls.dyd.gt
3670 } else {
3671 &mut ls.dyd.label
3672 };
3673 let n = list.len();
3674 list.push(entry);
3675 Ok(n)
3676}
3677
3678fn new_goto_entry(
3679 ls: &mut LexState,
3680 state: &mut LuaState,
3681 name: GcRef<LuaString>,
3682 line: i32,
3683 pc: i32,
3684) -> Result<usize, LuaError> {
3685 new_label_entry(ls, state, true, name, line, pc)
3686}
3687
3688fn solvegotos(ls: &mut LexState, state: &mut LuaState, lb_idx: usize) -> Result<bool, LuaError> {
3691 let lb_name = ls.dyd.label[lb_idx].name.clone();
3692 let lb_pc = ls.dyd.label[lb_idx].pc;
3693 let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
3694 let first_goto = ls
3695 .fs
3696 .as_ref()
3697 .unwrap()
3698 .bl
3699 .as_ref()
3700 .map_or(0, |b| b.firstgoto) as usize;
3701
3702 let mut i = first_goto;
3703 let mut needs_close = false;
3704 while i < ls.dyd.gt.len() {
3705 let gt_name = ls.dyd.gt[i].name.clone();
3706 let names_match = lb_name
3707 .as_ref()
3708 .and_then(|ln| gt_name.as_ref().map(|gn| GcRef::ptr_eq(ln, gn)))
3709 .unwrap_or(false);
3710 if names_match {
3711 needs_close |= ls.dyd.gt[i].close;
3712 solvegoto(ls, state, i, lb_pc, lb_nactvar)?;
3714 } else {
3715 i += 1;
3716 }
3717 }
3718 Ok(needs_close)
3719}
3720
3721fn createlabel(
3723 ls: &mut LexState,
3724 state: &mut LuaState,
3725 name: GcRef<LuaString>,
3726 line: i32,
3727 last: bool,
3728) -> Result<bool, LuaError> {
3729 let label_pc = cg_get_label(ls.fs.as_mut().unwrap());
3730 let l = new_label_entry(ls, state, false, name, line, label_pc)?;
3731 if last {
3732 let bl_scope_level = ls
3733 .fs
3734 .as_ref()
3735 .unwrap()
3736 .bl
3737 .as_ref()
3738 .map_or(0, |b| b.scope_level);
3739 ls.dyd.label[l].nactvar = bl_scope_level;
3740 }
3741 let needs_close = solvegotos(ls, state, l)?;
3742 if needs_close {
3743 let nstack = nvarstack(ls, ls.fs.as_ref().unwrap()) as u32;
3744 let inst =
3745 lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::Close, nstack, 0, 0, 0);
3746 emit_inst(ls.fs.as_mut().unwrap(), line, inst);
3747 return Ok(true);
3748 }
3749 Ok(false)
3750}
3751
3752fn movegotosout(
3763 ls: &mut LexState,
3764 state: &mut LuaState,
3765 bl_firstgoto: usize,
3766 bl_scope_level: u8,
3767 bl_upval: bool,
3768) -> Result<(), LuaError> {
3769 let reresolve = matches!(
3770 state.global().lua_version,
3771 lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
3772 );
3773 let mut i = bl_firstgoto;
3774 while i < ls.dyd.gt.len() {
3775 if reresolve {
3776 if ls.dyd.gt[i].nactvar > bl_scope_level {
3777 if bl_upval {
3778 ls.dyd.gt[i].close = true;
3779 }
3780 ls.dyd.gt[i].nactvar = bl_scope_level;
3781 }
3782 } else {
3783 if bl_upval {
3784 ls.dyd.gt[i].close = true;
3785 }
3786 ls.dyd.gt[i].nactvar = bl_scope_level;
3787 }
3788 if reresolve {
3789 let gt_name = ls.dyd.gt[i].name.clone();
3790 let lb_idx = gt_name
3791 .as_ref()
3792 .and_then(|n| findlabel_for_goto(ls, state, n));
3793 if let Some(lb_idx) = lb_idx {
3794 let lb_pc = ls.dyd.label[lb_idx].pc;
3795 let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
3796 solvegoto(ls, state, i, lb_pc, lb_nactvar)?;
3797 continue;
3798 }
3799 }
3800 i += 1;
3801 }
3802 Ok(())
3803}
3804
3805fn enter_block(ls: &mut LexState, isloop: bool) {
3807 let firstlabel = ls.dyd.label.len() as i32;
3808 let firstgoto = ls.dyd.gt.len() as i32;
3809 let saved_global_strict = ls.global_strict;
3810 let saved_declared_globals = ls.declared_globals.len();
3811 let saved_global_wildcard = ls.global_wildcard;
3812 let saved_global_wildcard_const = ls.global_wildcard_const;
3813 let saved_scope_barriers = ls.scope_barriers.len();
3814 let scope_level = current_scope_level(ls);
3815 let insidetbc = ls
3816 .fs
3817 .as_ref()
3818 .and_then(|f| f.bl.as_ref())
3819 .map_or(false, |b| b.insidetbc);
3820 let fs = ls.fs.as_mut().unwrap();
3821 let nactvar = fs.nactvar;
3822 let new_bl = Box::new(BlockCnt {
3823 previous: fs.bl.take(),
3824 firstlabel,
3825 firstgoto,
3826 nactvar,
3827 scope_level,
3828 upval: false,
3829 isloop,
3830 insidetbc,
3831 saved_global_strict,
3832 saved_declared_globals,
3833 saved_global_wildcard,
3834 saved_global_wildcard_const,
3835 saved_scope_barriers,
3836 });
3837 fs.bl = Some(new_bl);
3838 debug_assert!(
3839 fs.freereg as i32 == {
3840 fs.freereg as i32 }
3843 );
3844}
3845
3846fn undef_goto(ls: &mut LexState, version: lua_types::LuaVersion, gt_idx: usize) -> LuaError {
3847 let (line, name_bytes): (i32, Vec<u8>) = {
3848 let gt = &ls.dyd.gt[gt_idx];
3849 (
3850 gt.line,
3851 gt.name
3852 .as_ref()
3853 .map(|n| n.as_bytes().to_vec())
3854 .unwrap_or_default(),
3855 )
3856 };
3857 let msg = if name_bytes == b"break" {
3858 if matches!(
3861 version,
3862 lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
3863 ) {
3864 format!("<break> at line {} not inside a loop", line)
3865 } else {
3866 format!("break outside loop at line {}", line)
3867 }
3868 } else {
3869 let name_str = String::from_utf8_lossy(&name_bytes);
3870 format!(
3871 "no visible label '{}' for <goto> at line {}",
3872 name_str, line
3873 )
3874 };
3875 lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0)
3876}
3877
3878fn leave_block(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
3880 let (bl_nactvar, bl_scope_level, bl_isloop, bl_upval, bl_firstgoto, bl_firstlabel) = {
3884 let bl = ls
3885 .fs
3886 .as_ref()
3887 .unwrap()
3888 .bl
3889 .as_ref()
3890 .expect("leave_block: no current block");
3891 (
3892 bl.nactvar,
3893 bl.scope_level,
3894 bl.isloop,
3895 bl.upval,
3896 bl.firstgoto,
3897 bl.firstlabel,
3898 )
3899 };
3900
3901 {
3905 let (sgs, sdg, sgw, sgwc, ssb) = {
3906 let bl = ls.fs.as_ref().unwrap().bl.as_ref().unwrap();
3907 (
3908 bl.saved_global_strict,
3909 bl.saved_declared_globals,
3910 bl.saved_global_wildcard,
3911 bl.saved_global_wildcard_const,
3912 bl.saved_scope_barriers,
3913 )
3914 };
3915 ls.global_strict = sgs;
3916 ls.declared_globals.truncate(sdg);
3917 ls.global_wildcard = sgw;
3918 ls.global_wildcard_const = sgwc;
3919 ls.scope_barriers.truncate(ssb);
3920 }
3921
3922 let stklevel = reg_level(ls, ls.fs.as_ref().unwrap(), bl_nactvar as i32);
3923 let mut fs_box = ls.fs.take().unwrap();
3924 remove_vars(ls, &mut fs_box, bl_nactvar as i32);
3925 debug_assert!(bl_nactvar == fs_box.nactvar);
3926 ls.fs = Some(fs_box);
3927
3928 let hasclose = if bl_isloop {
3929 let break_str = state.intern_str(b"break")?;
3930 createlabel(ls, state, break_str, 0, false)?
3931 } else {
3932 false
3933 };
3934
3935 let mut bl_box = ls.fs.as_mut().unwrap().bl.take().unwrap();
3937 let previous = bl_box.previous.take();
3938 ls.fs.as_mut().unwrap().bl = previous;
3939
3940 let has_prev_block = ls.fs.as_ref().unwrap().bl.is_some();
3941 if !hasclose && has_prev_block && bl_upval {
3942 let line = ls.lastline;
3946 let inst = lua_code::opcodes::Instruction::abck(
3947 lua_code::opcodes::OpCode::Close,
3948 stklevel as u32,
3949 0,
3950 0,
3951 0,
3952 );
3953 emit_inst(ls.fs.as_mut().unwrap(), line, inst);
3954 }
3955 ls.fs.as_mut().unwrap().freereg = stklevel as u8;
3956
3957 ls.dyd.label.truncate(bl_firstlabel as usize);
3958
3959 if has_prev_block {
3960 movegotosout(ls, state, bl_firstgoto as usize, bl_scope_level, bl_upval)?;
3961 } else {
3962 if (bl_firstgoto as usize) < ls.dyd.gt.len() {
3963 let version = state.global().lua_version;
3964 return Err(undef_goto(ls, version, bl_firstgoto as usize));
3965 }
3966 }
3967 Ok(())
3968}
3969
3970fn add_prototype(ls: &mut LexState, _state: &mut LuaState) -> Result<Box<LuaProto>, LuaError> {
3975 let np = ls.fs.as_ref().unwrap().np as usize;
3976 let new_proto = Box::new(LuaProto::placeholder());
3978 while ls.fs.as_ref().unwrap().f.p.len() <= np {
3979 ls.fs
3980 .as_mut()
3981 .unwrap()
3982 .f
3983 .p
3984 .push(GcRef::new(LuaProto::placeholder()));
3985 }
3986 ls.fs.as_mut().unwrap().np += 1;
3987 Ok(new_proto)
3988}
3989
3990fn codeclosure(ls: &mut LexState, _state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
3992 let line = ls.lastline;
3993 let mut child = ls.fs.take().expect("codeclosure: no current FuncState");
3994 let result = (|| -> Result<(), LuaError> {
3995 let parent = child
3996 .prev
3997 .as_mut()
3998 .expect("codeclosure: child FuncState has no parent (called outside body()?)");
3999 let bx = (parent.np - 1) as u32;
4000 let inst = lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::Closure, 0, bx);
4001 let pc = emit_inst(parent, line, inst);
4002 init_exp(v, ExprKind::Reloc, pc);
4003 cg_exp_to_next_reg(parent, line, v)
4004 })();
4005 ls.fs = Some(child);
4006 result
4007}
4008
4009fn open_func(
4011 ls: &mut LexState,
4012 _state: &mut LuaState,
4013 mut new_fs: FuncState,
4014) -> Result<(), LuaError> {
4015 new_fs.prev = ls.fs.take();
4016
4017 let f = &mut new_fs.f;
4018 new_fs.pc = 0;
4019 new_fs.previousline = f.linedefined;
4020 new_fs.iwthabs = 0;
4021 new_fs.lasttarget = 0;
4022 new_fs.freereg = 0;
4023 new_fs.nk = 0;
4024 new_fs.nabslineinfo = 0;
4025 new_fs.np = 0;
4026 new_fs.nups = 0;
4027 new_fs.ndebugvars = 0;
4028 new_fs.nactvar = 0;
4029 new_fs.needclose = false;
4030
4031 new_fs.firstlocal = ls.dyd.actvar.len() as i32;
4032 new_fs.firstlabel = ls.dyd.label.len() as i32;
4033 new_fs.bl = None;
4034
4035 new_fs.f.source = ls.source.clone();
4036 new_fs.f.maxstacksize = 2;
4037
4038 ls.fs = Some(Box::new(new_fs));
4039
4040 enter_block(ls, false);
4041 Ok(())
4042}
4043
4044fn close_func(ls: &mut LexState, state: &mut LuaState) -> Result<Box<LuaProto>, LuaError> {
4047 {
4048 let first = {
4049 let fs = ls.fs.as_ref().unwrap();
4050 nvarstack(ls, fs)
4051 };
4052 let line = ls.lastline;
4053 let fs = ls.fs.as_mut().unwrap();
4054 let inst = lua_code::opcodes::Instruction::abck(
4055 lua_code::opcodes::OpCode::Return0,
4056 first as u32,
4057 1,
4058 0,
4059 0,
4060 );
4061 emit_inst(fs, line, inst);
4062 }
4063 leave_block(ls, state)?;
4064 debug_assert!(ls.fs.as_ref().unwrap().bl.is_none());
4065
4066 cg_finish(ls.fs.as_mut().unwrap());
4068
4069 {
4070 let fs = ls.fs.as_mut().unwrap();
4071 let pc = fs.pc as usize;
4072 let nabslineinfo = fs.nabslineinfo as usize;
4073 let nk = fs.nk as usize;
4074 let np = fs.np as usize;
4075 let ndebugvars = fs.ndebugvars as usize;
4076 let nups = fs.nups as usize;
4077 fs.f.code.truncate(pc);
4078 fs.f.lineinfo.truncate(pc);
4079 fs.f.abslineinfo.truncate(nabslineinfo);
4080 fs.f.k.truncate(nk);
4081 fs.f.p.truncate(np);
4082 fs.f.locvars.truncate(ndebugvars);
4083 fs.f.upvalues.truncate(nups);
4084 }
4085
4086 let mut fs_box = ls.fs.take().unwrap();
4087 ls.fs = fs_box.prev.take();
4088
4089 Ok(fs_box.f)
4090}
4091
4092fn block_follow(ls: &LexState, withuntil: bool) -> bool {
4096 match ls.t.token {
4097 TK_ELSE | TK_ELSEIF | TK_END | TK_EOS => true,
4098 TK_UNTIL => withuntil,
4099 _ => false,
4100 }
4101}
4102
4103fn statlist(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4104 while !block_follow(ls, true) {
4105 if ls.t.token == TK_RETURN {
4106 statement(ls, state)?;
4107 return Ok(());
4108 }
4109 statement(ls, state)?;
4110 }
4111 Ok(())
4112}
4113
4114fn fieldsel(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4116 let line = ls.lastline;
4117 cg_exp_to_any_reg_up(ls.fs.as_mut().unwrap(), line, v)?;
4118 lex_next(ls, state)?; let mut key = ExprDesc::default();
4120 codename(ls, state, &mut key)?;
4121 cg_indexed(ls.fs.as_mut().unwrap(), line, v, &mut key)?;
4122 Ok(())
4123}
4124
4125fn exp_to_val(
4141 fs: &mut FuncState,
4142 line: i32,
4143 e: &mut ExprDesc,
4144 materialize_jmp: bool,
4145) -> Result<(), LuaError> {
4146 if (materialize_jmp && e.k == ExprKind::Jmp) || e.t != e.f {
4147 cg_exp_to_any_reg(fs, line, e)?;
4148 } else {
4149 cg_discharge_vars(fs, line, e)?;
4150 }
4151 Ok(())
4152}
4153
4154fn yindex(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4155 lex_next(ls, state)?;
4156 expr(ls, state, v)?;
4157 let line = ls.linenumber;
4158 let materialize_jmp = state.global().lua_version != lua_types::LuaVersion::V54;
4159 exp_to_val(ls.fs.as_mut().unwrap(), line, v, materialize_jmp)?;
4160 check_next(ls, state, b']' as TokenKind)?;
4161 Ok(())
4162}
4163
4164fn recfield(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
4167 let reg = ls.fs.as_ref().unwrap().freereg as i32;
4168 let mut key = ExprDesc::default();
4169 let mut val = ExprDesc::default();
4170 if ls.t.token == TK_NAME {
4171 let fs = ls.fs.as_ref().unwrap();
4172 check_limit(fs, cc.nh, i32::MAX, "items in a constructor")?;
4173 codename(ls, state, &mut key)?;
4174 } else {
4175 yindex(ls, state, &mut key)?;
4176 }
4177 cc.nh += 1;
4178 check_next(ls, state, b'=' as TokenKind)?;
4179 let mut tab = cc.t.clone();
4180 let line = ls.lastline;
4181 cg_indexed(ls.fs.as_mut().unwrap(), line, &mut tab, &mut key)?;
4182 expr(ls, state, &mut val)?;
4183 cg_storevar(ls.fs.as_mut().unwrap(), line, &tab, &mut val)?;
4184 ls.fs.as_mut().unwrap().freereg = reg as u8;
4185 Ok(())
4186}
4187
4188fn closelistfield(
4189 ls: &mut LexState,
4190 state: &mut LuaState,
4191 cc: &mut ConsControl,
4192) -> Result<(), LuaError> {
4193 let _ = state;
4194 if cc.v.k == ExprKind::Void {
4195 return Ok(());
4196 }
4197 let line = ls.lastline;
4198 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut cc.v)?;
4199 cc.v.k = ExprKind::Void;
4200 if cc.tostore == LFIELDS_PER_FLUSH {
4201 let t_info = cc.t.u.info;
4202 cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, cc.tostore);
4203 cc.na += cc.tostore;
4204 cc.tostore = 0;
4205 }
4206 Ok(())
4207}
4208
4209fn lastlistfield(
4210 ls: &mut LexState,
4211 state: &mut LuaState,
4212 cc: &mut ConsControl,
4213) -> Result<(), LuaError> {
4214 let _ = state;
4215 if cc.tostore == 0 {
4216 return Ok(());
4217 }
4218 let t_info = cc.t.u.info;
4219 let line = ls.lastline;
4220 if cc.v.k.has_mult_ret() {
4221 cg_set_returns(ls.fs.as_mut().unwrap(), &mut cc.v, LUA_MULTRET);
4222 cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, LUA_MULTRET);
4223 cc.na -= 1;
4224 } else {
4225 if cc.v.k != ExprKind::Void {
4226 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut cc.v)?;
4227 }
4228 cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, cc.tostore);
4229 }
4230 cc.na += cc.tostore;
4231 Ok(())
4232}
4233
4234fn listfield(
4235 ls: &mut LexState,
4236 state: &mut LuaState,
4237 cc: &mut ConsControl,
4238) -> Result<(), LuaError> {
4239 expr(ls, state, &mut cc.v)?;
4240 cc.tostore += 1;
4241 Ok(())
4242}
4243
4244fn field(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
4245 match ls.t.token {
4246 TK_NAME => {
4247 let next_is_eq = lex_lookahead(ls, state)? == b'=' as TokenKind;
4248 if !next_is_eq {
4249 listfield(ls, state, cc)?;
4250 } else {
4251 recfield(ls, state, cc)?;
4252 }
4253 }
4254 c if c == b'[' as TokenKind => {
4255 recfield(ls, state, cc)?;
4256 }
4257 _ => {
4258 listfield(ls, state, cc)?;
4259 }
4260 }
4261 Ok(())
4262}
4263
4264fn constructor(ls: &mut LexState, state: &mut LuaState, t: &mut ExprDesc) -> Result<(), LuaError> {
4265 let line = ls.lastline;
4266 let pc = cg_emit_newtable(ls.fs.as_mut().unwrap(), line);
4267
4268 let freereg = ls.fs.as_ref().unwrap().freereg as i32;
4269 init_exp(t, ExprKind::NonReloc, freereg);
4270 reserve_regs(ls.fs.as_mut().unwrap(), 1)?;
4271
4272 let mut cc = ConsControl {
4273 v: ExprDesc::default(),
4274 t: t.clone(),
4275 nh: 0,
4276 na: 0,
4277 tostore: 0,
4278 };
4279
4280 check_next(ls, state, b'{' as TokenKind)?;
4281 loop {
4282 debug_assert!(cc.v.k == ExprKind::Void || cc.tostore > 0);
4283 if ls.t.token == b'}' as TokenKind {
4284 break;
4285 }
4286 closelistfield(ls, state, &mut cc)?;
4287 field(ls, state, &mut cc)?;
4288 if !test_next(ls, state, b',' as TokenKind)? && !test_next(ls, state, b';' as TokenKind)? {
4289 break;
4290 }
4291 }
4292 check_match(ls, state, b'}' as TokenKind, b'{' as TokenKind, line)?;
4293 lastlistfield(ls, state, &mut cc)?;
4294
4295 let t_info = t.u.info;
4296 cg_settablesize(ls.fs.as_mut().unwrap(), pc, t_info, cc.na, cc.nh);
4297 Ok(())
4298}
4299
4300fn setvararg(fs: &mut FuncState, _state: &mut LuaState, nparams: i32) -> Result<(), LuaError> {
4303 fs.f.is_vararg = true;
4304 let inst = lua_code::opcodes::Instruction::abck(
4305 lua_code::opcodes::OpCode::VarArgPrep,
4306 nparams as u32,
4307 0,
4308 0,
4309 0,
4310 );
4311 let line = fs.previousline;
4312 emit_inst(fs, line, inst);
4313 Ok(())
4314}
4315
4316fn parlist(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4317 let mut nparams: i32 = 0;
4318 let mut isvararg = false;
4319 let is_v55 = state.global().lua_version == lua_types::LuaVersion::V55;
4325 let mut has_vararg_local = false;
4326 let mut has_vararg_name = false;
4327 let mut vararg_name_vidx: Option<i32> = None;
4328 if ls.t.token != b')' as TokenKind {
4329 loop {
4330 match ls.t.token {
4331 TK_NAME => {
4332 let name = str_check_name(ls, state)?;
4333 new_local_var(ls, state, name)?;
4334 nparams += 1;
4335 }
4336 TK_DOTS => {
4337 lex_next(ls, state)?;
4338 isvararg = true;
4339 if is_v55 && ls.t.token == TK_NAME {
4345 let name = str_check_name(ls, state)?;
4346 vararg_name_vidx = Some(new_local_var(ls, state, name)?);
4347 has_vararg_local = true;
4348 has_vararg_name = true;
4349 } else if is_v55 {
4350 let name = state.intern_str(b"(vararg table)")?;
4351 new_local_var(ls, state, name)?;
4352 has_vararg_local = true;
4353 }
4354 }
4355 _ => {
4356 return Err(LuaError::syntax(format_args!("<name> or '...' expected")));
4357 }
4358 }
4359 if isvararg || !test_next(ls, state, b',' as TokenKind)? {
4360 break;
4361 }
4362 }
4363 }
4364 adjust_local_vars(ls, state, nparams)?;
4365 let numparams = ls.fs.as_ref().unwrap().nactvar;
4366 ls.fs.as_mut().unwrap().f.numparams = numparams;
4367 if isvararg {
4368 setvararg(ls.fs.as_mut().unwrap(), state, numparams as i32)?;
4369 }
4370 if has_vararg_local {
4371 adjust_local_vars(ls, state, 1)?;
4372 if let Some(vidx) = vararg_name_vidx {
4373 let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
4374 get_local_var_desc_mut(ls, firstlocal, vidx).kind = VarKind::VarArg;
4375 }
4376 }
4377 let nactvar = ls.fs.as_ref().unwrap().nactvar as i32;
4380 reserve_regs(ls.fs.as_mut().unwrap(), nactvar)?;
4381 if has_vararg_name {
4385 let reg = nvarstack(ls, ls.fs.as_ref().unwrap()) - 1;
4386 let inst = lua_code::opcodes::Instruction::abck(
4387 lua_code::opcodes::OpCode::VarArgPack,
4388 reg as u32,
4389 0,
4390 0,
4391 0,
4392 );
4393 let line = ls.fs.as_ref().unwrap().previousline;
4394 emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4395 ls.fs.as_mut().unwrap().f.vararg_table_reg = Some(reg as u8);
4398 }
4399 Ok(())
4400}
4401
4402fn check_match(
4403 ls: &mut LexState,
4404 state: &mut LuaState,
4405 what: TokenKind,
4406 who: TokenKind,
4407 where_line: i32,
4408) -> Result<(), LuaError> {
4409 if !test_next(ls, state, what)? {
4410 if where_line == ls.linenumber {
4411 return Err(error_expected(ls, what));
4412 } else {
4413 let what_str = lua_lex::token2str(&ls.lex, what);
4414 let who_str = lua_lex::token2str(&ls.lex, who);
4415 let mut msg: Vec<u8> = Vec::new();
4416 msg.extend_from_slice(&what_str);
4417 msg.extend_from_slice(b" expected (to close ");
4418 msg.extend_from_slice(&who_str);
4419 use std::io::Write as _;
4420 let _ = write!(msg, " at line {})", where_line);
4421 return Err(lua_lex::syntax_error(&mut ls.lex, &msg));
4422 }
4423 }
4424 Ok(())
4425}
4426
4427fn body(
4428 ls: &mut LexState,
4429 state: &mut LuaState,
4430 e: &mut ExprDesc,
4431 ismethod: bool,
4432 line: i32,
4433) -> Result<(), LuaError> {
4434 let new_proto = add_prototype(ls, state)?;
4435 let mut new_fs = FuncState {
4436 f: new_proto,
4437 prev: None,
4438 bl: None,
4439 pc: 0,
4440 lasttarget: 0,
4441 previousline: line,
4442 nk: 0,
4443 np: 0,
4444 nabslineinfo: 0,
4445 firstlocal: 0,
4446 firstlabel: 0,
4447 ndebugvars: 0,
4448 nactvar: 0,
4449 first_scope_barrier: ls.scope_barriers.len(),
4450 nups: 0,
4451 freereg: 0,
4452 iwthabs: 0,
4453 needclose: false,
4454 last_token_line: ls.lastline,
4455 };
4456 new_fs.f.linedefined = line;
4457 open_func(ls, state, new_fs)?;
4458
4459 check_next(ls, state, b'(' as TokenKind)?;
4460 if ismethod {
4461 let self_str = state.intern_str(b"self")?;
4462 new_local_var(ls, state, self_str)?;
4463 adjust_local_vars(ls, state, 1)?;
4464 }
4465 parlist(ls, state)?;
4466 check_next(ls, state, b')' as TokenKind)?;
4467 statlist(ls, state)?;
4468 ls.fs.as_mut().unwrap().f.lastlinedefined = ls.linenumber;
4469 check_match(ls, state, TK_END, TK_FUNCTION, line)?;
4470 codeclosure(ls, state, e)?;
4471 let inner_proto = close_func(ls, state)?;
4472 let parent = ls
4473 .fs
4474 .as_mut()
4475 .expect("body: close_func left no parent FuncState");
4476 let slot = (parent.np - 1) as usize;
4477 if parent.f.p.len() <= slot {
4478 parent
4479 .f
4480 .p
4481 .resize_with(slot + 1, || GcRef::new(LuaProto::placeholder()));
4482 }
4483 let inner_ref = GcRef::new(*inner_proto);
4484 inner_ref.account_buffer(inner_ref.buffer_bytes() as isize);
4485 parent.f.p[slot] = inner_ref;
4486 Ok(())
4487}
4488
4489fn explist(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<i32, LuaError> {
4492 let mut n = 1;
4493 expr(ls, state, v)?;
4494 while test_next(ls, state, b',' as TokenKind)? {
4495 let line = ls.lastline;
4496 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, v)?;
4497 expr(ls, state, v)?;
4498 n += 1;
4499 }
4500 Ok(n)
4501}
4502
4503fn funcargs(ls: &mut LexState, state: &mut LuaState, f: &mut ExprDesc) -> Result<(), LuaError> {
4504 let mut args = ExprDesc::default();
4505 let line = ls.linenumber;
4508 match ls.t.token {
4509 c if c == b'(' as TokenKind => {
4510 lex_next(ls, state)?; if ls.t.token == b')' as TokenKind {
4512 args.k = ExprKind::Void;
4513 } else {
4514 explist(ls, state, &mut args)?;
4515 if args.k.has_mult_ret() {
4516 cg_set_returns(ls.fs.as_mut().unwrap(), &mut args, LUA_MULTRET);
4519 }
4520 }
4521 check_match(ls, state, b')' as TokenKind, b'(' as TokenKind, line)?;
4522 }
4523 c if c == b'{' as TokenKind => {
4524 constructor(ls, state, &mut args)?;
4525 }
4526 TK_STRING => {
4527 let s =
4528 ls.t.seminfo
4529 .ts
4530 .clone()
4531 .ok_or_else(|| LuaError::syntax(format_args!("string expected")))?;
4532 codestring(&mut args, s);
4533 lex_next(ls, state)?;
4534 }
4535 _ => {
4536 return Err(LuaError::syntax(format_args!(
4537 "function arguments expected"
4538 )));
4539 }
4540 }
4541 debug_assert!(f.k == ExprKind::NonReloc);
4542 let base = f.u.info;
4543 let nparams: i32 = if args.k.has_mult_ret() {
4544 LUA_MULTRET
4547 } else {
4548 if args.k != ExprKind::Void {
4549 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut args)?;
4550 }
4551 ls.fs.as_ref().unwrap().freereg as i32 - (base + 1)
4552 };
4553 let call_inst = lua_code::opcodes::Instruction::abck(
4554 lua_code::opcodes::OpCode::Call,
4555 base as u32,
4556 (nparams + 1) as u32,
4557 2,
4558 0,
4559 );
4560 let call_pc = emit_inst(ls.fs.as_mut().unwrap(), line, call_inst);
4561 init_exp(f, ExprKind::Call, call_pc);
4562 ls.fs.as_mut().unwrap().freereg = base as u8 + 1;
4563 Ok(())
4564}
4565
4566fn primaryexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4569 match ls.t.token {
4570 c if c == b'(' as TokenKind => {
4571 let line = ls.lastline;
4572 lex_next(ls, state)?;
4573 expr(ls, state, v)?;
4574 check_match(ls, state, b')' as TokenKind, b'(' as TokenKind, line)?;
4575 cg_discharge_vars(ls.fs.as_mut().unwrap(), line, v)?;
4576 }
4577 TK_NAME => {
4578 singlevar(ls, state, v)?;
4579 }
4580 _ => {
4581 return Err(lua_lex::syntax_error(&mut ls.lex, b"unexpected symbol"));
4582 }
4583 }
4584 Ok(())
4585}
4586
4587fn suffixedexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4588 primaryexp(ls, state, v)?;
4589 loop {
4590 match ls.t.token {
4591 c if c == b'.' as TokenKind => {
4592 fieldsel(ls, state, v)?;
4593 }
4594 c if c == b'[' as TokenKind => {
4595 let mut key = ExprDesc::default();
4596 let line = ls.lastline;
4597 cg_exp_to_any_reg_up(ls.fs.as_mut().unwrap(), line, v)?;
4598 yindex(ls, state, &mut key)?;
4599 cg_indexed(ls.fs.as_mut().unwrap(), line, v, &mut key)?;
4600 }
4601 c if c == b':' as TokenKind => {
4602 let mut key = ExprDesc::default();
4603 lex_next(ls, state)?;
4604 codename(ls, state, &mut key)?;
4605 let line = ls.lastline;
4606 let keep_self_opcode_for_register_key =
4607 state.global().lua_version != lua_types::LuaVersion::V55;
4608 cg_self(
4609 ls.fs.as_mut().unwrap(),
4610 line,
4611 v,
4612 &mut key,
4613 keep_self_opcode_for_register_key,
4614 )?;
4615 funcargs(ls, state, v)?;
4616 }
4617 c if c == b'(' as TokenKind || c == TK_STRING || c == b'{' as TokenKind => {
4618 let line = ls.lastline;
4619 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, v)?;
4620 funcargs(ls, state, v)?;
4621 }
4622 _ => return Ok(()),
4623 }
4624 }
4625}
4626
4627fn simpleexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4628 match ls.t.token {
4629 TK_FLT => {
4630 init_exp(v, ExprKind::KFlt, 0);
4631 v.u.nval = ls.t.seminfo.r;
4632 }
4633 TK_INT => {
4634 init_exp(v, ExprKind::KInt, 0);
4635 v.u.ival = ls.t.seminfo.i;
4636 }
4637 TK_STRING => {
4638 let s =
4639 ls.t.seminfo
4640 .ts
4641 .clone()
4642 .ok_or_else(|| LuaError::syntax(format_args!("string value missing")))?;
4643 codestring(v, s);
4644 }
4645 TK_NIL => {
4646 init_exp(v, ExprKind::Nil, 0);
4647 }
4648 TK_TRUE => {
4649 init_exp(v, ExprKind::True, 0);
4650 }
4651 TK_FALSE => {
4652 init_exp(v, ExprKind::False, 0);
4653 }
4654 TK_DOTS => {
4655 let is_vararg = ls.fs.as_ref().unwrap().f.is_vararg;
4656 if !is_vararg {
4657 return Err(LuaError::syntax(format_args!(
4658 "cannot use '...' outside a vararg function"
4659 )));
4660 }
4661 let line = ls.lastline;
4662 let inst =
4663 lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::VarArg, 0, 0, 1, 0);
4664 let pc = emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4665 init_exp(v, ExprKind::VarArg, pc);
4666 }
4667 c if c == b'{' as TokenKind => {
4668 constructor(ls, state, v)?;
4669 return Ok(());
4670 }
4671 TK_FUNCTION => {
4672 lex_next(ls, state)?;
4673 let line = ls.lastline;
4674 body(ls, state, v, false, line)?;
4675 return Ok(());
4676 }
4677 _ => {
4678 suffixedexp(ls, state, v)?;
4679 return Ok(());
4680 }
4681 }
4682 lex_next(ls, state)?;
4683 Ok(())
4684}
4685
4686fn getunopr(op: TokenKind) -> UnOpr {
4687 match op {
4688 TK_NOT => UnOpr::Not,
4689 c if c == b'-' as TokenKind => UnOpr::Minus,
4690 c if c == b'~' as TokenKind => UnOpr::BNot,
4691 c if c == b'#' as TokenKind => UnOpr::Len,
4692 _ => UnOpr::NoUnOpr,
4693 }
4694}
4695
4696fn getbinopr(op: TokenKind) -> BinOpr {
4697 match op {
4698 c if c == b'+' as TokenKind => BinOpr::Add,
4699 c if c == b'-' as TokenKind => BinOpr::Sub,
4700 c if c == b'*' as TokenKind => BinOpr::Mul,
4701 c if c == b'%' as TokenKind => BinOpr::Mod,
4702 c if c == b'^' as TokenKind => BinOpr::Pow,
4703 c if c == b'/' as TokenKind => BinOpr::Div,
4704 TK_IDIV => BinOpr::IDiv,
4705 c if c == b'&' as TokenKind => BinOpr::BAnd,
4706 c if c == b'|' as TokenKind => BinOpr::BOr,
4707 c if c == b'~' as TokenKind => BinOpr::BXor,
4708 TK_SHL => BinOpr::Shl,
4709 TK_SHR => BinOpr::Shr,
4710 TK_CONCAT => BinOpr::Concat,
4711 TK_NE => BinOpr::Ne,
4712 TK_EQ => BinOpr::Eq,
4713 c if c == b'<' as TokenKind => BinOpr::Lt,
4714 TK_LE => BinOpr::Le,
4715 c if c == b'>' as TokenKind => BinOpr::Gt,
4716 TK_GE => BinOpr::Ge,
4717 TK_AND => BinOpr::And,
4718 TK_OR => BinOpr::Or,
4719 _ => BinOpr::NoBinOpr,
4720 }
4721}
4722
4723fn parser_is_float_only(state: &LuaState) -> bool {
4726 matches!(
4727 state.global().lua_version,
4728 lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
4729 )
4730}
4731
4732fn getbinopr_versioned(op: TokenKind, state: &LuaState) -> BinOpr {
4739 let r = getbinopr(op);
4740 if parser_is_float_only(state) && matches!(r, BinOpr::BAnd | BinOpr::BOr | BinOpr::BXor) {
4741 return BinOpr::NoBinOpr;
4742 }
4743 r
4744}
4745
4746fn getunopr_versioned(op: TokenKind, state: &LuaState) -> UnOpr {
4749 let r = getunopr(op);
4750 if parser_is_float_only(state) && matches!(r, UnOpr::BNot) {
4751 return UnOpr::NoUnOpr;
4752 }
4753 r
4754}
4755
4756fn subexpr(
4759 ls: &mut LexState,
4760 state: &mut LuaState,
4761 v: &mut ExprDesc,
4762 limit: i32,
4763) -> Result<BinOpr, LuaError> {
4764 enter_level(ls)?;
4765
4766 let uop = getunopr_versioned(ls.t.token, state);
4767 if uop != UnOpr::NoUnOpr {
4768 let line = ls.linenumber;
4770 lex_next(ls, state)?; subexpr(ls, state, v, UNARY_PRIORITY)?;
4772 cg_prefix(ls.fs.as_mut().unwrap(), uop, v, line)?;
4773 } else {
4774 simpleexp(ls, state, v)?;
4775 }
4776
4777 let mut op = getbinopr_versioned(ls.t.token, state);
4778 while op != BinOpr::NoBinOpr && PRIORITY[op as usize].0 as i32 > limit {
4779 let mut v2 = ExprDesc::default();
4780 let line = ls.linenumber;
4783 lex_next(ls, state)?;
4784 cg_infix(ls.fs.as_mut().unwrap(), op, v, line)?;
4785 let nextop = subexpr(ls, state, &mut v2, PRIORITY[op as usize].1 as i32)?;
4786 cg_posfix_fold(ls.fs.as_mut().unwrap(), op, v, &mut v2, line)?;
4787 op = nextop;
4788 }
4789
4790 leave_level(ls);
4791 Ok(op)
4792}
4793
4794fn expr(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4795 subexpr(ls, state, v, 0)?;
4796 Ok(())
4797}
4798
4799fn block(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4802 enter_block(ls, false);
4803 statlist(ls, state)?;
4804 leave_block(ls, state)?;
4805 Ok(())
4806}
4807
4808fn check_conflict(
4816 ls: &mut LexState,
4817 _state: &mut LuaState,
4818 lh: &mut LhsAssign,
4819 v: &ExprDesc,
4820) -> Result<(), LuaError> {
4821 let extra = ls.fs.as_ref().unwrap().freereg as i32;
4822 let line = ls.lastline;
4823 let mut conflict = false;
4824
4825 conflict |= check_one_lhs_entry(&mut lh.v, v, extra);
4826 let mut prev = lh.prev.as_deref_mut();
4827 while let Some(node) = prev {
4828 conflict |= check_one_lhs_entry(&mut node.v, v, extra);
4829 prev = node.prev.as_deref_mut();
4830 }
4831
4832 if conflict {
4833 let fs = ls.fs.as_mut().unwrap();
4834 let inst = if v.k == ExprKind::Local {
4835 lua_code::opcodes::Instruction::abck(
4836 lua_code::opcodes::OpCode::Move,
4837 extra as u32,
4838 v.u.var_ridx as u32,
4839 0,
4840 0,
4841 )
4842 } else {
4843 lua_code::opcodes::Instruction::abck(
4844 lua_code::opcodes::OpCode::GetUpVal,
4845 extra as u32,
4846 v.u.info as u32,
4847 0,
4848 0,
4849 )
4850 };
4851 emit_inst(fs, line, inst);
4852 reserve_regs(fs, 1)?;
4853 }
4854 Ok(())
4855}
4856
4857fn check_one_lhs_entry(entry: &mut ExprDesc, v: &ExprDesc, extra: i32) -> bool {
4858 if !entry.k.is_indexed() {
4859 return false;
4860 }
4861 let mut found = false;
4862 if entry.k == ExprKind::IndexUp {
4863 if v.k == ExprKind::UpVal && entry.u.ind_t == v.u.info as u8 {
4864 found = true;
4865 entry.k = ExprKind::IndexStr;
4866 entry.u.ind_t = extra as u8;
4867 }
4868 } else {
4869 if v.k == ExprKind::Local && entry.u.ind_t == v.u.var_ridx {
4870 found = true;
4871 entry.u.ind_t = extra as u8;
4872 }
4873 if entry.k == ExprKind::Indexed
4874 && v.k == ExprKind::Local
4875 && entry.u.ind_idx == v.u.var_ridx as i16
4876 {
4877 found = true;
4878 entry.u.ind_idx = extra as i16;
4879 }
4880 }
4881 found
4882}
4883
4884fn restassign(
4885 ls: &mut LexState,
4886 state: &mut LuaState,
4887 lh: &mut LhsAssign,
4888 nvars: i32,
4889) -> Result<(), LuaError> {
4890 if !lh.v.k.is_var() {
4891 return Err(lua_lex::syntax_error(&mut ls.lex, b"syntax error"));
4892 }
4893 check_readonly(ls, state, &lh.v.clone())?;
4894
4895 if test_next(ls, state, b',' as TokenKind)? {
4896 let mut nv_assign = LhsAssign {
4897 prev: None, v: ExprDesc::default(),
4899 };
4900 suffixedexp(ls, state, &mut nv_assign.v)?;
4901 if !nv_assign.v.k.is_indexed() {
4902 check_conflict(ls, state, lh, &nv_assign.v.clone())?;
4903 }
4904 enter_level(ls)?;
4905 restassign(ls, state, &mut nv_assign, nvars + 1)?;
4906 leave_level(ls);
4907 } else {
4908 let mut e = ExprDesc::default();
4909 check_next(ls, state, b'=' as TokenKind)?;
4910 let nexps = explist(ls, state, &mut e)?;
4911 if nexps != nvars {
4912 adjust_assign(ls, state, nvars, nexps, &mut e)?;
4913 } else {
4914 let line = ls.lastline;
4915 let fs = ls.fs.as_mut().unwrap();
4916 cg_set_one_ret(fs, &mut e);
4917 cg_storevar(fs, line, &lh.v, &mut e)?;
4918 return Ok(());
4919 }
4920 }
4921 let line = ls.lastline;
4922 let fs = ls.fs.as_mut().unwrap();
4923 let freereg = fs.freereg as i32 - 1;
4924 let mut e = ExprDesc::default();
4925 init_exp(&mut e, ExprKind::NonReloc, freereg);
4926 cg_storevar(fs, line, &lh.v, &mut e)?;
4927 Ok(())
4928}
4929
4930fn cond(ls: &mut LexState, state: &mut LuaState) -> Result<i32, LuaError> {
4932 let mut v = ExprDesc::default();
4933 expr(ls, state, &mut v)?;
4934 if v.k == ExprKind::Nil {
4935 v.k = ExprKind::False;
4936 }
4937 let line = ls.lastline;
4938 cg_go_if_true(ls.fs.as_mut().unwrap(), line, &mut v)?;
4939 Ok(v.f)
4940}
4941
4942fn gotostat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4943 let line = ls.lastline;
4944 let name = str_check_name(ls, state)?;
4945 let lb = findlabel_for_goto(ls, state, &name);
4946 if lb.is_none() {
4947 let pc = cg_jump(ls.fs.as_mut().unwrap(), line);
4948 new_goto_entry(ls, state, name, line, pc)?;
4949 } else {
4950 let lb_idx = lb.unwrap();
4951 let lb_pc = ls.dyd.label[lb_idx].pc;
4952 let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
4953 let lb_local_level = local_level_for_scope_level(ls, lb_nactvar);
4954 let lblevel = reg_level(ls, ls.fs.as_ref().unwrap(), lb_local_level);
4955 let cur_nvarstack = {
4956 let fs = ls.fs.as_ref().unwrap();
4957 nvarstack(ls, fs)
4958 };
4959 if cur_nvarstack > lblevel {
4960 let inst = lua_code::opcodes::Instruction::abck(
4961 lua_code::opcodes::OpCode::Close,
4962 lblevel as u32,
4963 0,
4964 0,
4965 0,
4966 );
4967 emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4968 }
4969 let jpc = cg_jump(ls.fs.as_mut().unwrap(), line);
4970 cg_patch_list(ls.fs.as_mut().unwrap(), jpc, lb_pc)?;
4971 }
4972 Ok(())
4973}
4974
4975fn has_enclosing_loop(ls: &LexState) -> bool {
4978 let mut bl = ls.fs.as_ref().unwrap().bl.as_deref();
4979 while let Some(b) = bl {
4980 if b.isloop {
4981 return true;
4982 }
4983 bl = b.previous.as_deref();
4984 }
4985 false
4986}
4987
4988fn breakstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4989 let version = state.global().lua_version;
4990 let line = ls.lastline;
4991 if version == lua_types::LuaVersion::V55 && !has_enclosing_loop(ls) {
4999 return Err(lua_lex::syntax_error(&mut ls.lex, b"break outside loop"));
5000 }
5001 lex_next(ls, state)?;
5002 if version == lua_types::LuaVersion::V51 && !has_enclosing_loop(ls) {
5003 return Err(lua_lex::syntax_error(&mut ls.lex, b"no loop to break"));
5004 }
5005 let break_str = state.intern_str(b"break")?;
5006 let pc = cg_jump(ls.fs.as_mut().unwrap(), line);
5007 new_goto_entry(ls, state, break_str, line, pc)?;
5008 Ok(())
5009}
5010
5011fn checkrepeated(
5020 ls: &mut LexState,
5021 state: &LuaState,
5022 name: &GcRef<LuaString>,
5023) -> Result<(), LuaError> {
5024 let block_scoped = matches!(
5025 state.global().lua_version,
5026 lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
5027 );
5028 let first = if block_scoped {
5029 ls.fs
5030 .as_ref()
5031 .unwrap()
5032 .bl
5033 .as_ref()
5034 .map_or(0, |b| b.firstlabel) as usize
5035 } else {
5036 ls.fs.as_ref().unwrap().firstlabel as usize
5037 };
5038 let mut dup_line: Option<i32> = None;
5039 for i in first..ls.dyd.label.len() {
5040 let lb = &ls.dyd.label[i];
5041 if lb.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
5042 dup_line = Some(lb.line);
5043 break;
5044 }
5045 }
5046 if let Some(line) = dup_line {
5047 let name_str = String::from_utf8_lossy(name.as_bytes());
5048 let msg = format!("label '{}' already defined on line {}", name_str, line);
5049 let saved_line = ls.lex.linenumber;
5050 ls.lex.linenumber = ls.lastline;
5051 let err = lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0);
5052 ls.lex.linenumber = saved_line;
5053 return Err(err);
5054 }
5055 Ok(())
5056}
5057
5058fn labelstat(
5059 ls: &mut LexState,
5060 state: &mut LuaState,
5061 name: GcRef<LuaString>,
5062 line: i32,
5063) -> Result<(), LuaError> {
5064 check_next(ls, state, TK_DBCOLON)?;
5065 while ls.t.token == b';' as TokenKind || ls.t.token == TK_DBCOLON {
5066 statement(ls, state)?;
5067 }
5068 checkrepeated(ls, state, &name)?;
5069 let is_last = block_follow(ls, false);
5070 createlabel(ls, state, name, line, is_last)?;
5071 Ok(())
5072}
5073
5074fn whilestat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5075 lex_next(ls, state)?;
5076 let whileinit = cg_get_label(ls.fs.as_mut().unwrap());
5077 let condexit = cond(ls, state)?;
5078 enter_block(ls, true);
5079 check_next(ls, state, TK_DO)?;
5080 block(ls, state)?;
5081 let back = cg_jump(ls.fs.as_mut().unwrap(), ls.lastline);
5086 cg_patch_list(ls.fs.as_mut().unwrap(), back, whileinit)?;
5087 check_match(ls, state, TK_END, TK_WHILE, line)?;
5088 leave_block(ls, state)?;
5089 cg_patch_to_here(ls.fs.as_mut().unwrap(), condexit)?;
5090 Ok(())
5091}
5092
5093fn repeatstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5094 let repeat_init = cg_get_label(ls.fs.as_mut().unwrap());
5095 enter_block(ls, true);
5096 enter_block(ls, false);
5097 lex_next(ls, state)?;
5098 statlist(ls, state)?;
5099 check_match(ls, state, TK_UNTIL, TK_REPEAT, line)?;
5100 let condexit = cond(ls, state)?;
5101
5102 let bl2_upval = ls.fs.as_ref().unwrap().bl.as_ref().unwrap().upval;
5103 let bl2_nactvar = ls.fs.as_ref().unwrap().bl.as_ref().unwrap().nactvar as i32;
5104 leave_block(ls, state)?;
5105
5106 let mut condexit = condexit;
5107 if bl2_upval {
5108 let exit = cg_jump(ls.fs.as_mut().unwrap(), line);
5109 cg_patch_to_here(ls.fs.as_mut().unwrap(), condexit)?;
5110 let close_level = reg_level(ls, ls.fs.as_ref().unwrap(), bl2_nactvar) as u32;
5111 let close_inst = lua_code::opcodes::Instruction::abck(
5112 lua_code::opcodes::OpCode::Close,
5113 close_level,
5114 0,
5115 0,
5116 0,
5117 );
5118 emit_inst(ls.fs.as_mut().unwrap(), line, close_inst);
5119 condexit = cg_jump(ls.fs.as_mut().unwrap(), line);
5120 cg_patch_to_here(ls.fs.as_mut().unwrap(), exit)?;
5121 }
5122 cg_patch_list(ls.fs.as_mut().unwrap(), condexit, repeat_init)?;
5123 leave_block(ls, state)?;
5124 Ok(())
5125}
5126
5127fn exp1(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5129 let mut e = ExprDesc::default();
5130 expr(ls, state, &mut e)?;
5131 let line = ls.lastline;
5132 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut e)?;
5133 debug_assert!(e.k == ExprKind::NonReloc);
5134 Ok(())
5135}
5136
5137fn fixforjump(fs: &mut FuncState, pc: i32, dest: i32, back: bool) -> Result<(), LuaError> {
5138 let mut offset = dest - (pc + 1);
5139 if back {
5140 offset = -offset;
5141 }
5142 if offset > MAXARG_BX {
5143 return Err(LuaError::syntax(format_args!("control structure too long")));
5144 }
5145 let raw = fs.f.code[pc as usize].0;
5146 let mut inst = lua_code::opcodes::Instruction(raw);
5147 inst.set_arg_bx(offset as u32);
5148 fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(inst.0);
5149 Ok(())
5150}
5151
5152fn forbody(
5153 ls: &mut LexState,
5154 state: &mut LuaState,
5155 base: i32,
5156 line: i32,
5157 nvars: i32,
5158 isgen: bool,
5159) -> Result<(), LuaError> {
5160 check_next(ls, state, TK_DO)?;
5161 let prep_op = if isgen {
5162 OpCode::TForPrep
5163 } else {
5164 OpCode::ForPrep
5165 };
5166 let prep = {
5167 let fs = ls.fs.as_mut().unwrap();
5168 let inst = lua_code::opcodes::Instruction::abx(prep_op, base as u32, 0);
5169 emit_inst(fs, line, inst)
5170 };
5171 if isgen && state.global().lua_version == lua_types::LuaVersion::V55 {
5172 let fs = ls.fs.as_mut().unwrap();
5173 fs.freereg = fs.freereg.saturating_sub(1);
5174 }
5175
5176 enter_block(ls, false);
5177 adjust_local_vars(ls, state, nvars)?;
5178 reserve_regs(ls.fs.as_mut().unwrap(), nvars)?;
5179 block(ls, state)?;
5180 leave_block(ls, state)?;
5181
5182 let label_pc = ls.fs.as_ref().unwrap().pc;
5183 fixforjump(ls.fs.as_mut().unwrap(), prep, label_pc, false)?;
5184
5185 if isgen {
5186 let fs = ls.fs.as_mut().unwrap();
5187 let inst =
5188 lua_code::opcodes::Instruction::abck(OpCode::TForCall, base as u32, 0, nvars as u32, 0);
5189 emit_inst(fs, line, inst);
5190 }
5191 let loop_op = if isgen {
5192 OpCode::TForLoop
5193 } else {
5194 OpCode::ForLoop
5195 };
5196 let endfor = {
5197 let fs = ls.fs.as_mut().unwrap();
5198 let inst = lua_code::opcodes::Instruction::abx(loop_op, base as u32, 0);
5199 emit_inst(fs, line, inst)
5200 };
5201 fixforjump(ls.fs.as_mut().unwrap(), endfor, prep + 1, true)?;
5202 Ok(())
5203}
5204
5205fn fornum(
5206 ls: &mut LexState,
5207 state: &mut LuaState,
5208 varname: GcRef<LuaString>,
5209 line: i32,
5210) -> Result<(), LuaError> {
5211 let base = ls.fs.as_ref().unwrap().freereg as i32;
5212 let for_state_str = state.intern_str(b"(for state)")?;
5213 new_local_var(ls, state, for_state_str.clone())?;
5214 new_local_var(ls, state, for_state_str.clone())?;
5215 new_local_var(ls, state, for_state_str)?;
5216 let ctrl_vidx = new_local_var(ls, state, varname)?;
5217 if state.global().lua_version == lua_types::LuaVersion::V55 {
5221 let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
5222 get_local_var_desc_mut(ls, firstlocal, ctrl_vidx).kind = VarKind::Const;
5223 }
5224 check_next(ls, state, b'=' as TokenKind)?;
5225 exp1(ls, state)?; check_next(ls, state, b',' as TokenKind)?;
5227 exp1(ls, state)?; if test_next(ls, state, b',' as TokenKind)? {
5229 exp1(ls, state)?; } else {
5231 let fs = ls.fs.as_mut().unwrap();
5232 let reg = fs.freereg as u32;
5233 let bx = (1i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
5234 let inst = lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::LoadI, reg, bx);
5235 emit_inst(fs, line, inst);
5236 reserve_regs(fs, 1)?;
5237 }
5238 adjust_local_vars(ls, state, 3)?; forbody(ls, state, base, line, 1, false)?;
5240 Ok(())
5241}
5242
5243fn forlist(
5244 ls: &mut LexState,
5245 state: &mut LuaState,
5246 indexname: GcRef<LuaString>,
5247) -> Result<(), LuaError> {
5248 let is_v55 = state.global().lua_version == lua_types::LuaVersion::V55;
5249 let mut nvars: i32 = if is_v55 { 4 } else { 5 };
5250 let base = ls.fs.as_ref().unwrap().freereg as i32;
5251 let for_state_str = state.intern_str(b"(for state)")?;
5252 new_local_var(ls, state, for_state_str.clone())?;
5253 new_local_var(ls, state, for_state_str.clone())?;
5254 new_local_var(ls, state, for_state_str.clone())?;
5255 if !is_v55 {
5256 new_local_var(ls, state, for_state_str)?;
5257 }
5258 let idx_vidx = new_local_var(ls, state, indexname)?;
5259 if state.global().lua_version == lua_types::LuaVersion::V55 {
5262 let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
5263 get_local_var_desc_mut(ls, firstlocal, idx_vidx).kind = VarKind::Const;
5264 }
5265 while test_next(ls, state, b',' as TokenKind)? {
5266 let extra_name = str_check_name(ls, state)?;
5267 new_local_var(ls, state, extra_name)?;
5268 nvars += 1;
5269 }
5270 check_next(ls, state, TK_IN)?;
5271 let line = ls.linenumber;
5275 let mut e = ExprDesc::default();
5276 let nexps = explist(ls, state, &mut e)?;
5277 adjust_assign(ls, state, 4, nexps, &mut e)?;
5278 adjust_local_vars(ls, state, if is_v55 { 3 } else { 4 })?;
5279 marktobeclosed(ls.fs.as_mut().unwrap()); let internal_vars = if is_v55 { 3 } else { 4 };
5282 forbody(ls, state, base, line, nvars - internal_vars, true)?;
5283 Ok(())
5284}
5285
5286fn forstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5287 enter_block(ls, true); lex_next(ls, state)?;
5289 let varname = str_check_name(ls, state)?;
5290 match ls.t.token {
5291 c if c == b'=' as TokenKind => fornum(ls, state, varname, line)?,
5292 c if c == b',' as TokenKind || c == TK_IN => forlist(ls, state, varname)?,
5293 _ => {
5294 return Err(LuaError::syntax(format_args!("'=' or 'in' expected")));
5295 }
5296 }
5297 check_match(ls, state, TK_END, TK_FOR, line)?;
5298 leave_block(ls, state)?; Ok(())
5300}
5301
5302fn test_then_block(
5303 ls: &mut LexState,
5304 state: &mut LuaState,
5305 escapelist: &mut i32,
5306) -> Result<(), LuaError> {
5307 lex_next(ls, state)?;
5308 let mut v = ExprDesc::default();
5309 expr(ls, state, &mut v)?;
5310 let cond_line = ls.lastline;
5318 let fold_onto_cond = state.global().lua_version == lua_types::LuaVersion::V55;
5319 check_next(ls, state, TK_THEN)?;
5320
5321 let jf: i32;
5322 if ls.t.token == TK_BREAK {
5323 let line = ls.linenumber;
5324 cg_go_if_false(ls.fs.as_mut().unwrap(), line, &mut v)?;
5325 lex_next(ls, state)?; enter_block(ls, false);
5327 let break_str = state.intern_str(b"break")?;
5328 new_goto_entry(ls, state, break_str, line, v.t)?;
5329 while test_next(ls, state, b';' as TokenKind)? {}
5330 if block_follow(ls, false) {
5331 leave_block(ls, state)?;
5332 return Ok(());
5333 } else {
5334 jf = cg_jump(ls.fs.as_mut().unwrap(), ls.linenumber);
5335 }
5336 } else {
5337 let line = if fold_onto_cond {
5338 cond_line
5339 } else {
5340 ls.lastline
5341 };
5342 cg_go_if_true(ls.fs.as_mut().unwrap(), line, &mut v)?;
5343 enter_block(ls, false);
5344 jf = v.f;
5345 }
5346
5347 statlist(ls, state)?;
5348 leave_block(ls, state)?;
5349
5350 if ls.t.token == TK_ELSE || ls.t.token == TK_ELSEIF {
5351 let line = ls.lastline;
5352 let j = cg_jump(ls.fs.as_mut().unwrap(), line);
5353 cg_concat(ls.fs.as_mut().unwrap(), escapelist, j)?;
5354 }
5355 cg_patch_to_here(ls.fs.as_mut().unwrap(), jf)?;
5356 Ok(())
5357}
5358
5359fn ifstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5360 let mut escapelist = NO_JUMP;
5361 test_then_block(ls, state, &mut escapelist)?; while ls.t.token == TK_ELSEIF {
5363 test_then_block(ls, state, &mut escapelist)?;
5364 }
5365 if test_next(ls, state, TK_ELSE)? {
5366 block(ls, state)?;
5367 }
5368 check_match(ls, state, TK_END, TK_IF, line)?;
5369 cg_patch_to_here(ls.fs.as_mut().unwrap(), escapelist)?;
5370 Ok(())
5371}
5372
5373fn localfunc(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5374 let mut b = ExprDesc::default();
5375 let _fvar = ls.fs.as_ref().unwrap().nactvar as i32;
5376 let name = str_check_name(ls, state)?;
5377 new_local_var(ls, state, name)?;
5378 adjust_local_vars(ls, state, 1)?; let line = ls.lastline;
5380 body(ls, state, &mut b, false, line)?;
5381 let _pc = ls.fs.as_ref().unwrap().pc;
5382 Ok(())
5384}
5385
5386fn version_has_attributes(state: &LuaState) -> bool {
5389 use lua_types::LuaVersion;
5390 matches!(
5391 state.global().lua_version,
5392 LuaVersion::V54 | LuaVersion::V55
5393 )
5394}
5395
5396fn getlocalattribute(
5405 ls: &mut LexState,
5406 state: &mut LuaState,
5407 df: VarKind,
5408) -> Result<VarKind, LuaError> {
5409 if !version_has_attributes(state) {
5410 return Ok(df);
5411 }
5412 if test_next(ls, state, b'<' as TokenKind)? {
5413 let attr_name = str_check_name(ls, state)?;
5414 check_next(ls, state, b'>' as TokenKind)?;
5415 let bytes = attr_name.as_bytes();
5416 if bytes == b"const" {
5417 return Ok(VarKind::Const);
5418 } else if bytes == b"close" {
5419 return Ok(VarKind::ToBeClosed);
5420 } else {
5421 let msg = format!("unknown attribute '{}'", String::from_utf8_lossy(bytes));
5422 return Err(lua_lex::sem_error(&mut ls.lex, msg.as_bytes()));
5423 }
5424 }
5425 Ok(df)
5426}
5427
5428fn checktoclose(ls: &mut LexState, _state: &mut LuaState, level: i32) -> Result<(), LuaError> {
5429 if level != -1 {
5430 marktobeclosed(ls.fs.as_mut().unwrap());
5431 let rl = reg_level(ls, ls.fs.as_ref().unwrap(), level);
5432 let line = ls.lastline;
5433 let inst = lua_code::opcodes::Instruction::abck(
5434 lua_code::opcodes::OpCode::Tbc,
5435 rl as u32,
5436 0,
5437 0,
5438 0,
5439 );
5440 emit_inst(ls.fs.as_mut().unwrap(), line, inst);
5441 }
5442 Ok(())
5443}
5444
5445fn get_global_attribute(
5497 ls: &mut LexState,
5498 state: &mut LuaState,
5499 df: bool,
5500) -> Result<bool, LuaError> {
5501 if !test_next(ls, state, b'<' as TokenKind)? {
5502 return Ok(df);
5503 }
5504 let attr = str_check_name(ls, state)?;
5505 check_next(ls, state, b'>' as TokenKind)?;
5506 match attr.as_bytes() {
5507 b"const" => Ok(true),
5508 b"close" => Err(lua_lex::sem_error(
5509 &mut ls.lex,
5510 b"global variables cannot be to-be-closed",
5511 )),
5512 other => {
5513 let msg = format!("unknown attribute '{}'", String::from_utf8_lossy(other));
5514 Err(lua_lex::sem_error(&mut ls.lex, msg.as_bytes()))
5515 }
5516 }
5517}
5518
5519fn globalstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5520 lex_next(ls, state)?; if ls.t.token == TK_FUNCTION {
5527 let line = ls.linenumber;
5528 lex_next(ls, state)?; let name = str_check_name(ls, state)?;
5530 ls.declared_globals.push((name.clone(), false));
5531 add_scope_barrier(ls, name.clone());
5532 let envn = ls
5534 .envn
5535 .clone()
5536 .expect("envn must be set when resolving globals");
5537 let mut target = ExprDesc::default();
5538 let mut fs_box = ls.fs.take();
5539 let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut target, true);
5540 ls.fs = fs_box;
5541 r?;
5542 let lline = ls.lastline;
5543 {
5544 let fs = ls.fs.as_mut().unwrap();
5545 cg_exp_to_any_reg_up(fs, lline, &mut target)?;
5546 let mut key = ExprDesc::default();
5547 codestring(&mut key, name.clone());
5548 cg_indexed(fs, lline, &mut target, &mut key)?;
5549 }
5550 let mut b = ExprDesc::default();
5551 ls.global_function_names.push(name.clone());
5552 let body_result = body(ls, state, &mut b, false, line);
5553 ls.global_function_names.pop();
5554 body_result?;
5555 {
5556 let fs = ls.fs.as_mut().unwrap();
5557 cg_check_global(fs, line, &target, name)?;
5558 cg_storevar(fs, line, &target, &mut b)?;
5559 }
5560 ls.global_strict = true;
5561 return Ok(());
5562 }
5563
5564 let defkind = get_global_attribute(ls, state, false)?;
5575
5576 if test_next(ls, state, b'*' as TokenKind)? {
5582 let star = state.intern_str(b"*")?;
5583 add_scope_barrier(ls, star);
5584 ls.global_strict = false;
5585 ls.global_wildcard = true;
5586 ls.global_wildcard_const = defkind;
5587 return Ok(());
5588 }
5589
5590 let mut names: Vec<GcRef<LuaString>> = Vec::new();
5594 let mut declarations: Vec<(GcRef<LuaString>, bool)> = Vec::new();
5595 loop {
5596 let name = str_check_name(ls, state)?;
5597 let is_const = get_global_attribute(ls, state, defkind)?;
5598 names.push(name.clone());
5599 declarations.push((name, is_const));
5600 if !test_next(ls, state, b',' as TokenKind)? {
5601 break;
5602 }
5603 }
5604 if test_next(ls, state, b'=' as TokenKind)? {
5611 let init_line = ls.linenumber;
5614 let mut targets: Vec<ExprDesc> = Vec::with_capacity(names.len());
5615 for name in &names {
5616 let envn = ls
5617 .envn
5618 .clone()
5619 .expect("envn must be set when resolving globals");
5620 let mut env_var = ExprDesc::default();
5621 let mut fs_box = ls.fs.take();
5622 let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut env_var, true);
5623 ls.fs = fs_box;
5624 r?;
5625 let line = ls.lastline;
5626 let fs = ls.fs.as_mut().unwrap();
5627 cg_exp_to_any_reg_up(fs, line, &mut env_var)?;
5628 let mut key = ExprDesc::default();
5629 codestring(&mut key, name.clone());
5630 cg_indexed(fs, line, &mut env_var, &mut key)?;
5631 targets.push(env_var);
5632 }
5633 let nvars = targets.len() as i32;
5634 let mut e = ExprDesc::default();
5635 let nexps = explist(ls, state, &mut e)?;
5636 adjust_assign(ls, state, nvars, nexps, &mut e)?;
5637 for (i, target) in targets.iter().enumerate().rev() {
5643 let name = names[i].clone();
5644 {
5645 let fs = ls.fs.as_mut().unwrap();
5646 cg_check_global(fs, init_line, target, name)?;
5647 }
5648 let line = ls.lastline;
5649 let fs = ls.fs.as_mut().unwrap();
5650 let freereg = fs.freereg as i32 - 1;
5651 let mut v = ExprDesc::default();
5652 init_exp(&mut v, ExprKind::NonReloc, freereg);
5653 cg_storevar(fs, line, target, &mut v)?;
5654 }
5655 }
5656 for (name, is_const) in declarations {
5657 ls.declared_globals.push((name.clone(), is_const));
5658 add_scope_barrier(ls, name);
5659 }
5660 ls.global_strict = true;
5661 Ok(())
5662}
5663
5664fn localstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5665 let local_line = ls.lastline;
5666 let mut toclose: i32 = -1;
5667 let mut nvars: i32 = 0;
5668 let mut vidx: i32;
5669 use lua_types::LuaVersion;
5675 let defkind = if matches!(state.global().lua_version, LuaVersion::V55) {
5676 getlocalattribute(ls, state, VarKind::Reg)?
5677 } else {
5678 VarKind::Reg
5679 };
5680 loop {
5681 let name = str_check_name(ls, state)?;
5682 vidx = new_local_var(ls, state, name)?;
5683 let kind = getlocalattribute(ls, state, defkind)?;
5684 get_local_var_desc_mut(ls, ls.fs.as_ref().unwrap().firstlocal, vidx).kind = kind;
5685 if kind == VarKind::ToBeClosed {
5686 if toclose != -1 {
5687 let saved_line = ls.lex.linenumber;
5688 ls.lex.linenumber = local_line;
5689 let err = lua_lex::lex_error(
5690 &mut ls.lex,
5691 b"multiple to-be-closed variables in local list",
5692 0,
5693 );
5694 ls.lex.linenumber = saved_line;
5695 return Err(err);
5696 }
5697 toclose = ls.fs.as_ref().unwrap().nactvar as i32 + nvars;
5698 }
5699 nvars += 1;
5700 if !test_next(ls, state, b',' as TokenKind)? {
5701 break;
5702 }
5703 }
5704 let nexps: i32;
5705 let mut e = ExprDesc::default();
5706 if test_next(ls, state, b'=' as TokenKind)? {
5707 nexps = explist(ls, state, &mut e)?;
5708 } else {
5709 e.k = ExprKind::Void;
5710 nexps = 0;
5711 }
5712 let first_local = ls.fs.as_ref().unwrap().firstlocal;
5713 let last_vd_kind = ls.dyd.actvar[(first_local + vidx) as usize].kind;
5714 if nvars == nexps && last_vd_kind == VarKind::Const {
5715 let is_const = false; if is_const {
5718 ls.dyd.actvar[(first_local + vidx) as usize].kind = VarKind::CompileTimeConst;
5719 adjust_local_vars(ls, state, nvars - 1)?;
5720 ls.fs.as_mut().unwrap().nactvar += 1;
5721 } else {
5722 adjust_assign(ls, state, nvars, nexps, &mut e)?;
5723 adjust_local_vars(ls, state, nvars)?;
5724 }
5725 } else {
5726 adjust_assign(ls, state, nvars, nexps, &mut e)?;
5727 adjust_local_vars(ls, state, nvars)?;
5728 }
5729 checktoclose(ls, state, toclose)?;
5730 Ok(())
5731}
5732
5733fn funcname(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<bool, LuaError> {
5735 let mut ismethod = false;
5736 singlevar(ls, state, v)?;
5737 while ls.t.token == b'.' as TokenKind {
5738 fieldsel(ls, state, v)?;
5739 }
5740 if ls.t.token == b':' as TokenKind {
5741 ismethod = true;
5742 fieldsel(ls, state, v)?;
5743 }
5744 Ok(ismethod)
5745}
5746
5747fn funcstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5748 lex_next(ls, state)?;
5749 let mut v = ExprDesc::default();
5750 let mut b = ExprDesc::default();
5751 let ismethod = funcname(ls, state, &mut v)?;
5752 check_readonly(ls, state, &v.clone())?;
5753 body(ls, state, &mut b, ismethod, line)?;
5754 check_readonly(ls, state, &v.clone())?;
5755 let fs = ls.fs.as_mut().unwrap();
5756 cg_storevar(fs, line, &v, &mut b)?;
5757 Ok(())
5759}
5760
5761fn exprstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5762 let mut v_assign = LhsAssign {
5763 prev: None,
5764 v: ExprDesc::default(),
5765 };
5766 suffixedexp(ls, state, &mut v_assign.v)?;
5767 if ls.t.token == b'=' as TokenKind || ls.t.token == b',' as TokenKind {
5768 restassign(ls, state, &mut v_assign, 1)?;
5769 } else {
5770 if v_assign.v.k != ExprKind::Call {
5771 if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
5778 return Err(error_expected(ls, b'=' as TokenKind));
5779 }
5780 return Err(lua_lex::syntax_error(&mut ls.lex, b"syntax error"));
5781 }
5782 let info = v_assign.v.u.info as usize;
5783 let fs = ls.fs.as_mut().unwrap();
5784 let mut lc = lua_code::opcodes::Instruction(fs.f.code[info].0);
5785 lc.set_arg_c(1);
5786 fs.f.code[info] = lua_types::opcode::Instruction::new(lc.0);
5787 }
5788 Ok(())
5789}
5790
5791fn retstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5792 let mut first = {
5793 let fs = ls.fs.as_ref().unwrap();
5794 nvarstack(ls, fs)
5795 };
5796 let mut nret: i32;
5797 if block_follow(ls, true) || ls.t.token == b';' as TokenKind {
5798 nret = 0;
5799 } else {
5800 let mut e = ExprDesc::default();
5801 nret = explist(ls, state, &mut e)?;
5802 if e.k.has_mult_ret() {
5803 cg_set_returns(ls.fs.as_mut().unwrap(), &mut e, LUA_MULTRET);
5804 if e.k == ExprKind::Call && nret == 1 {
5805 let insidetbc = ls
5806 .fs
5807 .as_ref()
5808 .unwrap()
5809 .bl
5810 .as_ref()
5811 .map_or(false, |b| b.insidetbc);
5812 if !insidetbc {
5813 let fs = ls.fs.as_mut().unwrap();
5814 let info = e.u.info as usize;
5815 let mut lc = lua_code::opcodes::Instruction(fs.f.code[info].0);
5816 lc.set_opcode(lua_code::opcodes::OpCode::TailCall);
5817 fs.f.code[info] = lua_types::opcode::Instruction::new(lc.0);
5818 }
5819 }
5820 nret = LUA_MULTRET;
5821 } else {
5822 let line = ls.lastline;
5823 if nret == 1 {
5824 first = cg_exp_to_any_reg(ls.fs.as_mut().unwrap(), line, &mut e)? as i32;
5825 } else {
5826 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut e)?;
5827 }
5828 }
5829 }
5830 let line = ls.lastline;
5831 let version = state.global().lua_version;
5832 cg_emit_return(ls.fs.as_mut().unwrap(), line, first, nret, version)?;
5833 test_next(ls, state, b';' as TokenKind)?;
5834 Ok(())
5835}
5836
5837fn statement(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5839 let line = ls.linenumber;
5844 enter_level(ls)?;
5845 match ls.t.token {
5846 c if c == b';' as TokenKind => {
5847 lex_next(ls, state)?;
5848 }
5849 TK_IF => {
5850 ifstat(ls, state, line)?;
5851 }
5852 TK_WHILE => {
5853 whilestat(ls, state, line)?;
5854 }
5855 TK_DO => {
5856 lex_next(ls, state)?; block(ls, state)?;
5858 check_match(ls, state, TK_END, TK_DO, line)?;
5859 }
5860 TK_FOR => {
5861 forstat(ls, state, line)?;
5862 }
5863 TK_REPEAT => {
5864 repeatstat(ls, state, line)?;
5865 }
5866 TK_FUNCTION => {
5867 funcstat(ls, state, line)?;
5868 }
5869 TK_LOCAL => {
5870 lex_next(ls, state)?; if test_next(ls, state, TK_FUNCTION)? {
5872 localfunc(ls, state)?;
5873 } else {
5874 localstat(ls, state)?;
5875 }
5876 }
5877 TK_DBCOLON => {
5878 lex_next(ls, state)?; let name = str_check_name(ls, state)?;
5880 labelstat(ls, state, name, line)?;
5881 }
5882 TK_RETURN => {
5883 lex_next(ls, state)?; retstat(ls, state)?;
5885 }
5886 TK_BREAK => {
5887 breakstat(ls, state)?;
5888 }
5889 TK_GOTO => {
5890 lex_next(ls, state)?; gotostat(ls, state)?;
5892 }
5893 _ => {
5894 let is_global_decl = state.global().lua_version == lua_types::LuaVersion::V55
5900 && ls.t.token == TK_NAME
5901 && ls
5902 .t
5903 .seminfo
5904 .ts
5905 .as_ref()
5906 .map_or(false, |s| s.as_bytes() == b"global")
5907 && {
5908 let nxt = lex_lookahead(ls, state)?;
5909 nxt == TK_NAME
5910 || nxt == b'*' as TokenKind
5911 || nxt == b'<' as TokenKind
5912 || nxt == TK_FUNCTION
5913 };
5914 if is_global_decl {
5915 globalstat(ls, state)?;
5916 } else {
5917 exprstat(ls, state)?;
5918 }
5919 }
5920 }
5921 debug_assert!(
5922 ls.fs.as_ref().unwrap().f.maxstacksize >= ls.fs.as_ref().unwrap().freereg
5923 && ls.fs.as_ref().unwrap().freereg as i32 >= nvarstack(ls, ls.fs.as_ref().unwrap())
5924 );
5925 let nv = nvarstack(ls, ls.fs.as_ref().unwrap());
5926 ls.fs.as_mut().unwrap().freereg = nv as u8;
5927 leave_level(ls);
5928 Ok(())
5929}
5930
5931fn mainfunc(
5935 ls: &mut LexState,
5936 state: &mut LuaState,
5937 main_fs: FuncState,
5938) -> Result<Box<LuaProto>, LuaError> {
5939 open_func(ls, state, main_fs)?;
5940
5941 setvararg(ls.fs.as_mut().unwrap(), state, 0)?;
5942
5943 let env_name = ls.envn.clone();
5944 {
5945 let idx = alloc_upvalue(ls.fs.as_mut().unwrap())?;
5946 let up = &mut ls.fs.as_mut().unwrap().f.upvalues[idx];
5947 up.instack = true;
5948 up.idx = 0;
5949 up.kind = VarKind::Reg.as_u8();
5950 up.name = env_name.clone();
5951 }
5952
5953 lex_next(ls, state)?;
5954
5955 statlist(ls, state)?;
5956
5957 check(ls, TK_EOS)?;
5958
5959 close_func(ls, state)
5960}
5961
5962pub fn parse(
5969 state: &mut LuaState,
5970 dyd: DynData,
5971 source: &[u8],
5972 name: &[u8],
5973 firstchar: i32,
5974) -> Result<Box<LuaProto>, LuaError> {
5975 let source_str = state.intern_str(name)?;
5976 let envn_str = state.intern_str(lua_lex::LUA_ENV)?;
5977
5978 let rest_bytes: Vec<u8> = source.iter().skip(1).copied().collect();
5979 let z = lua_lex::ZIO::from_bytes(rest_bytes);
5980
5981 let lex_ls = lua_lex::LexState {
5982 current: firstchar,
5983 linenumber: 1,
5984 lastline: 1,
5985 t: lua_lex::Token::eos(),
5986 lookahead: lua_lex::Token::eos(),
5987 fs: None,
5988 z,
5989 buff: lua_lex::LexBuffer::new(),
5990 h: None,
5991 long_str_anchor: std::collections::HashMap::new(),
5992 dyd: None,
5993 source: source_str.clone(),
5994 envn: envn_str.clone(),
5995 version: state.global().lua_version,
5996 };
5997
5998 let mut lexstate = LexState {
5999 current: lex_ls.current,
6000 linenumber: lex_ls.linenumber,
6001 lastline: lex_ls.lastline,
6002 t: LexToken::default(),
6003 lookahead: LexToken::default(),
6004 fs: None,
6005 dyd,
6006 source: Some(source_str.clone()),
6007 envn: Some(lex_ls.envn.clone()),
6008 lex: lex_ls,
6009 recursion_depth: 0,
6010 global_strict: false,
6011 global_wildcard: false,
6012 global_wildcard_const: false,
6013 declared_globals: Vec::new(),
6014 scope_barriers: Vec::new(),
6015 global_function_names: Vec::new(),
6016 };
6017 let mut main_proto = Box::new(LuaProto::placeholder());
6022 main_proto.source = Some(source_str);
6023 main_proto.is_vararg = true;
6024 let main_fs = FuncState {
6025 f: main_proto,
6026 prev: None,
6027 bl: None,
6028 pc: 0,
6029 lasttarget: 0,
6030 previousline: 0,
6031 nk: 0,
6032 np: 0,
6033 nabslineinfo: 0,
6034 firstlocal: 0,
6035 firstlabel: 0,
6036 ndebugvars: 0,
6037 nactvar: 0,
6038 first_scope_barrier: 0,
6039 nups: 0,
6040 freereg: 0,
6041 iwthabs: 0,
6042 needclose: false,
6043 last_token_line: 0,
6044 };
6045
6046 mainfunc(&mut lexstate, state, main_fs)
6047}
6048
6049fn local_token_value(v: &lua_lex::TokenValue) -> TokenValue {
6054 match v {
6055 lua_lex::TokenValue::None => TokenValue::default(),
6056 lua_lex::TokenValue::Float(r) => TokenValue {
6057 r: *r,
6058 i: 0,
6059 ts: None,
6060 },
6061 lua_lex::TokenValue::Int(i) => TokenValue {
6062 r: 0.0,
6063 i: *i,
6064 ts: None,
6065 },
6066 lua_lex::TokenValue::Str(s) => TokenValue {
6067 r: 0.0,
6068 i: 0,
6069 ts: Some(s.clone()),
6070 },
6071 }
6072}
6073
6074