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 cg_posfix_fold(
717 fs: &mut FuncState,
718 op: BinOpr,
719 e1: &mut ExprDesc,
720 e2: &mut ExprDesc,
721 line: i32,
722) -> Result<(), LuaError> {
723 let rhs_line = fs.last_token_line;
729 cg_discharge_vars(fs, rhs_line, e2)?;
730
731 let promote = |k: ExprKind, u: &ExprPayload| -> Option<f64> {
732 match k {
733 ExprKind::KInt => Some(u.ival as f64),
734 ExprKind::KFlt => Some(u.nval),
735 _ => None,
736 }
737 };
738
739 let foldable = e1.t == NO_JUMP && e1.f == NO_JUMP && e2.t == NO_JUMP && e2.f == NO_JUMP;
740
741 if foldable {
742 if let (ExprKind::KInt, ExprKind::KInt) = (e1.k, e2.k) {
743 let a = e1.u.ival;
744 let b = e2.u.ival;
745 let r: Option<i64> = match op {
746 BinOpr::Add => Some(a.wrapping_add(b)),
747 BinOpr::Sub => Some(a.wrapping_sub(b)),
748 BinOpr::Mul => Some(a.wrapping_mul(b)),
749 BinOpr::Mod if b != 0 => Some(a.rem_euclid(b)),
750 BinOpr::IDiv if b != 0 => Some(a.div_euclid(b)),
751 BinOpr::BAnd => Some(a & b),
752 BinOpr::BOr => Some(a | b),
753 BinOpr::BXor => Some(a ^ b),
754 _ => None,
755 };
756 if let Some(v) = r {
757 e1.k = ExprKind::KInt;
758 e1.u.ival = v;
759 return Ok(());
760 }
761 }
762 if let (Some(a), Some(b)) = (promote(e1.k, &e1.u), promote(e2.k, &e2.u)) {
763 let r: Option<f64> = match op {
764 BinOpr::Add => Some(a + b),
765 BinOpr::Sub => Some(a - b),
766 BinOpr::Mul => Some(a * b),
767 BinOpr::Div => Some(a / b),
768 BinOpr::Pow => Some(a.powf(b)),
769 _ => None,
770 };
771 if let Some(v) = r {
772 if v.is_finite() {
773 e1.k = ExprKind::KFlt;
774 e1.u.nval = v;
775 return Ok(());
776 }
777 }
778 }
779 }
780
781 if matches!(op, BinOpr::Lt | BinOpr::Le) {
782 return cg_emit_order(fs, op, e1, e2, line);
783 }
784
785 if matches!(op, BinOpr::Gt | BinOpr::Ge) {
786 let swap_op = if matches!(op, BinOpr::Gt) {
787 BinOpr::Lt
788 } else {
789 BinOpr::Le
790 };
791 std::mem::swap(e1, e2);
792 return cg_emit_order(fs, swap_op, e1, e2, line);
793 }
794
795 if matches!(op, BinOpr::Eq | BinOpr::Ne) {
796 return cg_emit_eq(fs, op, e1, e2, line);
797 }
798
799 if matches!(op, BinOpr::And) {
800 debug_assert_eq!(e1.t, NO_JUMP);
801 cg_concat(fs, &mut e2.f, e1.f)?;
802 *e1 = e2.clone();
803 return Ok(());
804 }
805
806 if matches!(op, BinOpr::Or) {
807 debug_assert_eq!(e1.f, NO_JUMP);
808 cg_concat(fs, &mut e2.t, e1.t)?;
809 *e1 = e2.clone();
810 return Ok(());
811 }
812
813 if matches!(op, BinOpr::Concat) {
814 return cg_emit_concat(fs, e1, e2, line);
815 }
816
817 match op {
818 BinOpr::Add | BinOpr::Mul => cg_code_commutative(fs, op, e1, e2, line),
819 BinOpr::Sub => {
820 if cg_finish_bin_exp_neg(
821 fs,
822 e1,
823 e2,
824 lua_code::opcodes::OpCode::AddI,
825 line,
826 lua_types::tagmethod::TagMethod::Sub,
827 )? {
828 Ok(())
829 } else {
830 cg_code_arith(fs, op, e1, e2, false, line)
831 }
832 }
833 BinOpr::Mod | BinOpr::Pow | BinOpr::Div | BinOpr::IDiv => {
834 cg_code_arith(fs, op, e1, e2, false, line)
835 }
836 BinOpr::BAnd | BinOpr::BOr | BinOpr::BXor => cg_code_bitwise(fs, op, e1, e2, line),
837 BinOpr::Shl => cg_code_shift_left(fs, e1, e2, line),
838 BinOpr::Shr => cg_code_shift_right(fs, e1, e2, line),
839 BinOpr::Concat
840 | BinOpr::Eq
841 | BinOpr::Lt
842 | BinOpr::Le
843 | BinOpr::Ne
844 | BinOpr::Gt
845 | BinOpr::Ge
846 | BinOpr::And
847 | BinOpr::Or
848 | BinOpr::NoBinOpr => {
849 unreachable!(
850 "cg_posfix_fold reached opcode match with non-arith op {:?}",
851 op
852 )
853 }
854 }
855}
856
857fn cg_binop_reg_opcode(op: BinOpr) -> lua_code::opcodes::OpCode {
858 match op {
859 BinOpr::Add => lua_code::opcodes::OpCode::Add,
860 BinOpr::Sub => lua_code::opcodes::OpCode::Sub,
861 BinOpr::Mul => lua_code::opcodes::OpCode::Mul,
862 BinOpr::Mod => lua_code::opcodes::OpCode::Mod,
863 BinOpr::Pow => lua_code::opcodes::OpCode::Pow,
864 BinOpr::Div => lua_code::opcodes::OpCode::Div,
865 BinOpr::IDiv => lua_code::opcodes::OpCode::IDiv,
866 BinOpr::BAnd => lua_code::opcodes::OpCode::BAnd,
867 BinOpr::BOr => lua_code::opcodes::OpCode::BOr,
868 BinOpr::BXor => lua_code::opcodes::OpCode::BXOr,
869 BinOpr::Shl => lua_code::opcodes::OpCode::Shl,
870 BinOpr::Shr => lua_code::opcodes::OpCode::Shr,
871 _ => unreachable!("non-value binary operator {:?}", op),
872 }
873}
874
875fn cg_binop_k_opcode(op: BinOpr) -> lua_code::opcodes::OpCode {
876 match op {
877 BinOpr::Add => lua_code::opcodes::OpCode::AddK,
878 BinOpr::Sub => lua_code::opcodes::OpCode::SubK,
879 BinOpr::Mul => lua_code::opcodes::OpCode::MulK,
880 BinOpr::Mod => lua_code::opcodes::OpCode::ModK,
881 BinOpr::Pow => lua_code::opcodes::OpCode::PowK,
882 BinOpr::Div => lua_code::opcodes::OpCode::DivK,
883 BinOpr::IDiv => lua_code::opcodes::OpCode::IDivK,
884 BinOpr::BAnd => lua_code::opcodes::OpCode::BAndK,
885 BinOpr::BOr => lua_code::opcodes::OpCode::BOrK,
886 BinOpr::BXor => lua_code::opcodes::OpCode::BXOrK,
887 _ => unreachable!("operator has no K opcode {:?}", op),
888 }
889}
890
891fn cg_binop_event(op: BinOpr) -> lua_types::tagmethod::TagMethod {
892 match op {
893 BinOpr::Add => lua_types::tagmethod::TagMethod::Add,
894 BinOpr::Sub => lua_types::tagmethod::TagMethod::Sub,
895 BinOpr::Mul => lua_types::tagmethod::TagMethod::Mul,
896 BinOpr::Mod => lua_types::tagmethod::TagMethod::Mod,
897 BinOpr::Pow => lua_types::tagmethod::TagMethod::Pow,
898 BinOpr::Div => lua_types::tagmethod::TagMethod::Div,
899 BinOpr::IDiv => lua_types::tagmethod::TagMethod::Idiv,
900 BinOpr::BAnd => lua_types::tagmethod::TagMethod::Band,
901 BinOpr::BOr => lua_types::tagmethod::TagMethod::Bor,
902 BinOpr::BXor => lua_types::tagmethod::TagMethod::Bxor,
903 BinOpr::Shl => lua_types::tagmethod::TagMethod::Shl,
904 BinOpr::Shr => lua_types::tagmethod::TagMethod::Shr,
905 _ => unreachable!("operator has no arithmetic metamethod {:?}", op),
906 }
907}
908
909fn cg_is_numeral(e: &ExprDesc) -> bool {
910 e.t == NO_JUMP && e.f == NO_JUMP && matches!(e.k, ExprKind::KInt | ExprKind::KFlt)
911}
912
913fn cg_is_integer(e: &ExprDesc) -> bool {
914 e.t == NO_JUMP && e.f == NO_JUMP && e.k == ExprKind::KInt
915}
916
917fn cg_find_k_value(fs: &FuncState, v: &LuaValue) -> Option<i32> {
918 fs.f.k
919 .iter()
920 .take(fs.nk as usize)
921 .position(|existing| existing == v)
922 .map(|idx| idx as i32)
923}
924
925fn cg_k_value_index_limited(fs: &mut FuncState, value: LuaValue, maxarg: u32) -> Option<i32> {
926 let idx = if let Some(idx) = cg_find_k_value(fs, &value) {
927 idx
928 } else {
929 if fs.nk as u32 > maxarg {
930 return None;
931 }
932 add_k_value(fs, value)
933 };
934 if idx as u32 > maxarg {
935 None
936 } else {
937 Some(idx)
938 }
939}
940
941fn cg_k_string_index_limited(fs: &mut FuncState, s: GcRef<LuaString>, maxarg: u32) -> Option<i32> {
942 for (i, k) in fs.f.k.iter().take(fs.nk as usize).enumerate() {
943 if let LuaValue::Str(existing) = k {
944 if GcRef::ptr_eq(existing, &s) {
945 let idx = i as i32;
946 return (idx as u32 <= maxarg).then_some(idx);
947 }
948 }
949 }
950 if fs.nk as u32 > maxarg {
951 return None;
952 }
953 let idx = add_k_string(fs, s);
954 (idx as u32 <= maxarg).then_some(idx)
955}
956
957fn cg_exp_to_k(fs: &mut FuncState, e: &mut ExprDesc) -> bool {
958 if !cg_is_numeral(e) {
959 return false;
960 }
961 let value = match e.k {
962 ExprKind::KInt => LuaValue::Int(e.u.ival),
963 ExprKind::KFlt => LuaValue::Float(e.u.nval),
964 _ => return false,
965 };
966 let Some(idx) = cg_k_value_index_limited(fs, value, lua_code::opcodes::MAXARG_C) else {
967 return false;
968 };
969 e.k = ExprKind::K;
970 e.u.info = idx;
971 true
972}
973
974fn cg_exp_to_int_k(fs: &mut FuncState, e: &mut ExprDesc) -> bool {
975 if !cg_is_integer(e) {
976 return false;
977 }
978 let Some(idx) =
979 cg_k_value_index_limited(fs, LuaValue::Int(e.u.ival), lua_code::opcodes::MAXARG_C)
980 else {
981 return false;
982 };
983 e.k = ExprKind::K;
984 e.u.info = idx;
985 true
986}
987
988fn cg_exp_to_const_k(fs: &mut FuncState, e: &mut ExprDesc, maxarg: u32) -> bool {
989 if e.t != NO_JUMP || e.f != NO_JUMP {
990 return false;
991 }
992 let idx = match e.k {
993 ExprKind::Nil => cg_k_value_index_limited(fs, LuaValue::Nil, maxarg),
994 ExprKind::False => cg_k_value_index_limited(fs, LuaValue::Bool(false), maxarg),
995 ExprKind::True => cg_k_value_index_limited(fs, LuaValue::Bool(true), maxarg),
996 ExprKind::KInt => cg_k_value_index_limited(fs, LuaValue::Int(e.u.ival), maxarg),
997 ExprKind::KFlt => cg_k_value_index_limited(fs, LuaValue::Float(e.u.nval), maxarg),
998 ExprKind::KStr => {
999 let Some(s) = e.u.strval.clone() else {
1000 return false;
1001 };
1002 cg_k_string_index_limited(fs, s, maxarg)
1003 }
1004 ExprKind::K => {
1005 if e.u.info >= 0 && (e.u.info as u32) <= maxarg {
1006 Some(e.u.info)
1007 } else {
1008 None
1009 }
1010 }
1011 _ => None,
1012 };
1013 let Some(idx) = idx else {
1014 return false;
1015 };
1016 e.k = ExprKind::K;
1017 e.u.info = idx;
1018 true
1019}
1020
1021fn cg_finish_bin_exp_val(
1022 fs: &mut FuncState,
1023 e1: &mut ExprDesc,
1024 e2: &mut ExprDesc,
1025 opcode: lua_code::opcodes::OpCode,
1026 v2: u32,
1027 flip: bool,
1028 line: i32,
1029 mm_opcode: lua_code::opcodes::OpCode,
1030 event: lua_types::tagmethod::TagMethod,
1031) -> Result<(), LuaError> {
1032 let v1 = cg_exp_to_any_reg(fs, line, e1)?;
1033 let inst = lua_code::opcodes::Instruction::abck(opcode, 0, v1 as u32, v2, 0);
1034 let pc = emit_inst(fs, line, inst);
1035 cg_free_exps(fs, e1, e2);
1036 e1.u.info = pc;
1037 e1.k = ExprKind::Reloc;
1038
1039 let mm_inst =
1040 lua_code::opcodes::Instruction::abck(mm_opcode, v1 as u32, v2, event as u32, flip as u32);
1041 emit_inst(fs, line, mm_inst);
1042 Ok(())
1043}
1044
1045fn cg_code_bin_exp_val(
1046 fs: &mut FuncState,
1047 op: BinOpr,
1048 e1: &mut ExprDesc,
1049 e2: &mut ExprDesc,
1050 line: i32,
1051) -> Result<(), LuaError> {
1052 let opcode = cg_binop_reg_opcode(op);
1053 let v2 = cg_exp_to_any_reg(fs, line, e2)? as u32;
1054 cg_finish_bin_exp_val(
1055 fs,
1056 e1,
1057 e2,
1058 opcode,
1059 v2,
1060 false,
1061 line,
1062 lua_code::opcodes::OpCode::MmBin,
1063 cg_binop_event(op),
1064 )
1065}
1066
1067fn cg_code_bin_i(
1068 fs: &mut FuncState,
1069 opcode: lua_code::opcodes::OpCode,
1070 e1: &mut ExprDesc,
1071 e2: &mut ExprDesc,
1072 flip: bool,
1073 line: i32,
1074 event: lua_types::tagmethod::TagMethod,
1075) -> Result<(), LuaError> {
1076 let Some(v2) = cg_sc_int(e2) else {
1077 unreachable!("cg_code_bin_i called with non-small-integer operand");
1078 };
1079 cg_finish_bin_exp_val(
1080 fs,
1081 e1,
1082 e2,
1083 opcode,
1084 v2 as u32,
1085 flip,
1086 line,
1087 lua_code::opcodes::OpCode::MmBinI,
1088 event,
1089 )
1090}
1091
1092fn cg_code_bin_k(
1093 fs: &mut FuncState,
1094 op: BinOpr,
1095 e1: &mut ExprDesc,
1096 e2: &mut ExprDesc,
1097 flip: bool,
1098 line: i32,
1099) -> Result<(), LuaError> {
1100 let v2 = e2.u.info as u32;
1101 cg_finish_bin_exp_val(
1102 fs,
1103 e1,
1104 e2,
1105 cg_binop_k_opcode(op),
1106 v2,
1107 flip,
1108 line,
1109 lua_code::opcodes::OpCode::MmBinK,
1110 cg_binop_event(op),
1111 )
1112}
1113
1114fn cg_code_bin_no_k(
1115 fs: &mut FuncState,
1116 op: BinOpr,
1117 e1: &mut ExprDesc,
1118 e2: &mut ExprDesc,
1119 flip: bool,
1120 line: i32,
1121) -> Result<(), LuaError> {
1122 if flip {
1123 std::mem::swap(e1, e2);
1124 }
1125 cg_code_bin_exp_val(fs, op, e1, e2, line)
1126}
1127
1128fn cg_code_arith(
1129 fs: &mut FuncState,
1130 op: BinOpr,
1131 e1: &mut ExprDesc,
1132 e2: &mut ExprDesc,
1133 flip: bool,
1134 line: i32,
1135) -> Result<(), LuaError> {
1136 if cg_is_numeral(e2) && cg_exp_to_k(fs, e2) {
1137 cg_code_bin_k(fs, op, e1, e2, flip, line)
1138 } else {
1139 cg_code_bin_no_k(fs, op, e1, e2, flip, line)
1140 }
1141}
1142
1143fn cg_code_commutative(
1144 fs: &mut FuncState,
1145 op: BinOpr,
1146 e1: &mut ExprDesc,
1147 e2: &mut ExprDesc,
1148 line: i32,
1149) -> Result<(), LuaError> {
1150 let mut flip = false;
1151 if cg_is_numeral(e1) {
1152 std::mem::swap(e1, e2);
1153 flip = true;
1154 }
1155 if op == BinOpr::Add && cg_sc_int(e2).is_some() {
1156 cg_code_bin_i(
1157 fs,
1158 lua_code::opcodes::OpCode::AddI,
1159 e1,
1160 e2,
1161 flip,
1162 line,
1163 lua_types::tagmethod::TagMethod::Add,
1164 )
1165 } else {
1166 cg_code_arith(fs, op, e1, e2, flip, line)
1167 }
1168}
1169
1170fn cg_code_bitwise(
1171 fs: &mut FuncState,
1172 op: BinOpr,
1173 e1: &mut ExprDesc,
1174 e2: &mut ExprDesc,
1175 line: i32,
1176) -> Result<(), LuaError> {
1177 let mut flip = false;
1178 if cg_is_integer(e1) {
1179 std::mem::swap(e1, e2);
1180 flip = true;
1181 }
1182 if cg_is_integer(e2) && cg_exp_to_int_k(fs, e2) {
1183 cg_code_bin_k(fs, op, e1, e2, flip, line)
1184 } else {
1185 cg_code_bin_no_k(fs, op, e1, e2, flip, line)
1186 }
1187}
1188
1189fn cg_code_shift_left(
1190 fs: &mut FuncState,
1191 e1: &mut ExprDesc,
1192 e2: &mut ExprDesc,
1193 line: i32,
1194) -> Result<(), LuaError> {
1195 if cg_sc_int(e1).is_some() {
1196 std::mem::swap(e1, e2);
1197 cg_code_bin_i(
1198 fs,
1199 lua_code::opcodes::OpCode::ShlI,
1200 e1,
1201 e2,
1202 true,
1203 line,
1204 lua_types::tagmethod::TagMethod::Shl,
1205 )
1206 } else if cg_finish_bin_exp_neg(
1207 fs,
1208 e1,
1209 e2,
1210 lua_code::opcodes::OpCode::ShrI,
1211 line,
1212 lua_types::tagmethod::TagMethod::Shl,
1213 )? {
1214 Ok(())
1215 } else {
1216 cg_code_bin_exp_val(fs, BinOpr::Shl, e1, e2, line)
1217 }
1218}
1219
1220fn cg_code_shift_right(
1221 fs: &mut FuncState,
1222 e1: &mut ExprDesc,
1223 e2: &mut ExprDesc,
1224 line: i32,
1225) -> Result<(), LuaError> {
1226 if cg_sc_int(e2).is_some() {
1227 cg_code_bin_i(
1228 fs,
1229 lua_code::opcodes::OpCode::ShrI,
1230 e1,
1231 e2,
1232 false,
1233 line,
1234 lua_types::tagmethod::TagMethod::Shr,
1235 )
1236 } else {
1237 cg_code_bin_exp_val(fs, BinOpr::Shr, e1, e2, line)
1238 }
1239}
1240
1241fn cg_finish_bin_exp_neg(
1242 fs: &mut FuncState,
1243 e1: &mut ExprDesc,
1244 e2: &mut ExprDesc,
1245 opcode: lua_code::opcodes::OpCode,
1246 line: i32,
1247 event: lua_types::tagmethod::TagMethod,
1248) -> Result<bool, LuaError> {
1249 if e2.k != ExprKind::KInt || e2.t != NO_JUMP || e2.f != NO_JUMP {
1250 return Ok(false);
1251 }
1252 let i2 = e2.u.ival;
1253 let Some(neg_i2) = i2.checked_neg() else {
1254 return Ok(false);
1255 };
1256 let biased = (i2 as i128) + (lua_code::opcodes::OFFSET_S_C as i128);
1257 let neg_biased = (neg_i2 as i128) + (lua_code::opcodes::OFFSET_S_C as i128);
1258 if !(0..=lua_code::opcodes::MAXARG_C as i128).contains(&biased)
1259 || !(0..=lua_code::opcodes::MAXARG_C as i128).contains(&neg_biased)
1260 {
1261 return Ok(false);
1262 }
1263
1264 let v1 = cg_exp_to_any_reg(fs, line, e1)?;
1265 let inst = lua_code::opcodes::Instruction::abck(opcode, 0, v1 as u32, neg_biased as u32, 0);
1266 let pc = emit_inst(fs, line, inst);
1267 cg_free_exps(fs, e1, e2);
1268 e1.u.info = pc;
1269 e1.k = ExprKind::Reloc;
1270
1271 let mm_inst = lua_code::opcodes::Instruction::abck(
1272 lua_code::opcodes::OpCode::MmBinI,
1273 v1 as u32,
1274 biased as u32,
1275 event as u32,
1276 0,
1277 );
1278 emit_inst(fs, line, mm_inst);
1279 Ok(true)
1280}
1281
1282fn cg_emit_order(
1291 fs: &mut FuncState,
1292 op: BinOpr,
1293 e1: &mut ExprDesc,
1294 e2: &mut ExprDesc,
1295 line: i32,
1296) -> Result<(), LuaError> {
1297 debug_assert!(matches!(op, BinOpr::Lt | BinOpr::Le));
1298 let is_le = matches!(op, BinOpr::Le);
1299 let (op_imm_e2, op_imm_e1, op_reg) = if is_le {
1300 (
1301 lua_code::opcodes::OpCode::LeI,
1302 lua_code::opcodes::OpCode::GeI,
1303 lua_code::opcodes::OpCode::Le,
1304 )
1305 } else {
1306 (
1307 lua_code::opcodes::OpCode::LtI,
1308 lua_code::opcodes::OpCode::GtI,
1309 lua_code::opcodes::OpCode::Lt,
1310 )
1311 };
1312 let (r1, r2, cmp_op) = if let Some(im) = cg_sc_int(e2) {
1313 let r1 = cg_exp_to_any_reg(fs, line, e1)?;
1314 (r1, im, op_imm_e2)
1315 } else if let Some(im) = cg_sc_int(e1) {
1316 let r1 = cg_exp_to_any_reg(fs, line, e2)?;
1317 (r1, im, op_imm_e1)
1318 } else {
1319 let r2 = cg_exp_to_any_reg(fs, line, e2)?;
1320 let r1 = cg_exp_to_any_reg(fs, line, e1)?;
1321 (r1, r2, op_reg)
1322 };
1323 cg_free_exps(fs, e1, e2);
1324 let cmp = lua_code::opcodes::Instruction::abck(cmp_op, r1 as u32, r2 as u32, 0, 1);
1325 emit_inst(fs, line, cmp);
1326 let jmp_arg = (NO_JUMP + lua_code::opcodes::OFFSET_S_J) as u32;
1327 let jmp = lua_code::opcodes::Instruction::sj(lua_code::opcodes::OpCode::Jmp, jmp_arg, 0);
1328 let jmp_pc = emit_inst(fs, line, jmp);
1329 e1.u.info = jmp_pc;
1330 e1.k = ExprKind::Jmp;
1331 Ok(())
1332}
1333
1334fn cg_emit_eq(
1339 fs: &mut FuncState,
1340 op: BinOpr,
1341 e1: &mut ExprDesc,
1342 e2: &mut ExprDesc,
1343 line: i32,
1344) -> Result<(), LuaError> {
1345 debug_assert!(matches!(op, BinOpr::Eq | BinOpr::Ne));
1346 if e1.k != ExprKind::NonReloc {
1347 std::mem::swap(e1, e2);
1348 }
1349 let r1 = cg_exp_to_any_reg(fs, line, e1)?;
1350 let (r2, cmp_op) = if let Some(im) = cg_sc_int(e2) {
1351 (im, lua_code::opcodes::OpCode::EqI)
1352 } else if cg_exp_to_const_k(fs, e2, lua_code::opcodes::MAXARG_B) {
1353 (e2.u.info as u8, lua_code::opcodes::OpCode::EqK)
1354 } else {
1355 let r = cg_exp_to_any_reg(fs, line, e2)?;
1356 (r, lua_code::opcodes::OpCode::Eq)
1357 };
1358 cg_free_exps(fs, e1, e2);
1359 let k_bit = if matches!(op, BinOpr::Eq) { 1 } else { 0 };
1360 let cmp = lua_code::opcodes::Instruction::abck(cmp_op, r1 as u32, r2 as u32, 0, k_bit);
1361 emit_inst(fs, line, cmp);
1362 let jmp_pc = cg_jump(fs, line);
1363 e1.u.info = jmp_pc;
1364 e1.k = ExprKind::Jmp;
1365 Ok(())
1366}
1367
1368fn previous_instruction_idx(fs: &FuncState) -> Option<usize> {
1373 if fs.pc > fs.lasttarget {
1374 Some((fs.pc - 1) as usize)
1375 } else {
1376 None
1377 }
1378}
1379
1380fn cg_emit_concat(
1389 fs: &mut FuncState,
1390 e1: &mut ExprDesc,
1391 e2: &mut ExprDesc,
1392 line: i32,
1393) -> Result<(), LuaError> {
1394 cg_exp_to_next_reg(fs, line, e2)?;
1395
1396 if let Some(prev_idx) = previous_instruction_idx(fs) {
1397 let prev = lua_code::opcodes::Instruction(fs.f.code[prev_idx].0);
1398 if prev.opcode() == Some(lua_code::opcodes::OpCode::Concat) {
1399 let n = prev.arg_b();
1400 debug_assert_eq!(e1.u.info + 1, prev.arg_a() as i32);
1401 cg_free_exp(fs, e2);
1402 let mut updated = prev;
1403 updated.set_arg_a(e1.u.info as u32);
1404 updated.set_arg_b(n + 1);
1405 fs.f.code[prev_idx] = lua_types::opcode::Instruction::new(updated.0);
1406 return Ok(());
1407 }
1408 }
1409
1410 let inst = lua_code::opcodes::Instruction::abck(
1411 lua_code::opcodes::OpCode::Concat,
1412 e1.u.info as u32,
1413 2,
1414 0,
1415 0,
1416 );
1417 emit_inst(fs, line, inst);
1418 cg_free_exp(fs, e2);
1419 Ok(())
1420}
1421
1422fn cg_prefix(fs: &mut FuncState, op: UnOpr, e: &mut ExprDesc, line: i32) -> Result<(), LuaError> {
1431 cg_discharge_vars(fs, line, e)?;
1432 let opcode = match op {
1433 UnOpr::Minus => lua_code::opcodes::OpCode::Unm,
1434 UnOpr::BNot => lua_code::opcodes::OpCode::BNot,
1435 UnOpr::Len => lua_code::opcodes::OpCode::Len,
1436 UnOpr::Not => return cg_codenot(fs, line, e),
1437 UnOpr::NoUnOpr => return Ok(()),
1438 };
1439 let r = cg_exp_to_any_reg(fs, line, e)?;
1440 cg_free_exp(fs, e);
1441 let inst = lua_code::opcodes::Instruction::abck(opcode, 0, r as u32, 0, 0);
1442 let pc = emit_inst(fs, line, inst);
1443 e.u.info = pc;
1444 e.k = ExprKind::Reloc;
1445 Ok(())
1446}
1447
1448fn cg_get_jump_control(fs: &FuncState, pc: i32) -> i32 {
1455 if pc >= 1 {
1456 let prev = cg_inst_at(fs, pc - 1);
1457 if let Some(op) = prev.opcode() {
1458 if lua_code::opcodes::test_t_mode(op) {
1459 return pc - 1;
1460 }
1461 }
1462 }
1463 pc
1464}
1465
1466fn cg_patch_test_reg(fs: &mut FuncState, node: i32, reg: u32) -> bool {
1474 let ctrl_pc = cg_get_jump_control(fs, node);
1475 let mut inst = cg_inst_at(fs, ctrl_pc);
1476 if inst.opcode() != Some(lua_code::opcodes::OpCode::TestSet) {
1477 return false;
1478 }
1479 let b = inst.arg_b();
1480 let k = inst.arg_k();
1481 if reg != lua_code::opcodes::NO_REG && reg != b {
1482 inst.set_arg_a(reg);
1483 cg_set_inst_at(fs, ctrl_pc, inst);
1484 } else {
1485 let test =
1486 lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::Test, b, 0, 0, k);
1487 cg_set_inst_at(fs, ctrl_pc, test);
1488 }
1489 true
1490}
1491
1492fn cg_remove_values(fs: &mut FuncState, list: i32) {
1499 let mut list = list;
1500 while list != NO_JUMP {
1501 let next = cg_get_jump(fs, list);
1502 cg_patch_test_reg(fs, list, lua_code::opcodes::NO_REG);
1503 list = next;
1504 }
1505}
1506
1507fn cg_codenot(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1515 match e.k {
1516 ExprKind::Nil | ExprKind::False => {
1517 e.k = ExprKind::True;
1518 }
1519 ExprKind::K | ExprKind::KFlt | ExprKind::KInt | ExprKind::KStr | ExprKind::True => {
1520 e.k = ExprKind::False;
1521 }
1522 ExprKind::Jmp => {
1523 cg_negate_condition(fs, e);
1524 }
1525 ExprKind::Reloc | ExprKind::NonReloc => {
1526 let reg = cg_exp_to_any_reg(fs, line, e)?;
1527 cg_free_exp(fs, e);
1528 let inst = lua_code::opcodes::Instruction::abck(
1529 lua_code::opcodes::OpCode::Not,
1530 0,
1531 reg as u32,
1532 0,
1533 0,
1534 );
1535 let pc = emit_inst(fs, line, inst);
1536 e.u.info = pc;
1537 e.k = ExprKind::Reloc;
1538 }
1539 _ => debug_assert!(false, "cg_codenot: unexpected ExprKind {:?}", e.k),
1540 }
1541 std::mem::swap(&mut e.f, &mut e.t);
1542 cg_remove_values(fs, e.f);
1543 cg_remove_values(fs, e.t);
1544 Ok(())
1545}
1546
1547fn cg_jump(fs: &mut FuncState, line: i32) -> i32 {
1551 let jmp_arg = (NO_JUMP + lua_code::opcodes::OFFSET_S_J) as u32;
1552 let jmp = lua_code::opcodes::Instruction::sj(lua_code::opcodes::OpCode::Jmp, jmp_arg, 0);
1553 emit_inst(fs, line, jmp)
1554}
1555
1556fn cg_inst_at(fs: &FuncState, pc: i32) -> lua_code::opcodes::Instruction {
1559 lua_code::opcodes::Instruction(fs.f.code[pc as usize].0)
1560}
1561
1562fn cg_set_inst_at(fs: &mut FuncState, pc: i32, inst: lua_code::opcodes::Instruction) {
1565 fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(inst.0);
1566}
1567
1568fn cg_get_jump(fs: &FuncState, pc: i32) -> i32 {
1573 let offset = cg_inst_at(fs, pc).arg_s_j();
1574 if offset == NO_JUMP {
1575 NO_JUMP
1576 } else {
1577 (pc + 1) + offset
1578 }
1579}
1580
1581fn cg_fix_jump(fs: &mut FuncState, pc: i32, dest: i32) -> Result<(), LuaError> {
1585 debug_assert!(dest != NO_JUMP);
1586 let offset = dest - (pc + 1);
1587 let max = lua_code::opcodes::MAXARG_S_J as i32 - lua_code::opcodes::OFFSET_S_J;
1588 let min = -lua_code::opcodes::OFFSET_S_J;
1589 if offset < min || offset > max {
1590 return Err(LuaError::syntax(format_args!("control structure too long")));
1591 }
1592 let mut inst = cg_inst_at(fs, pc);
1593 inst.set_arg_s_j(offset);
1594 cg_set_inst_at(fs, pc, inst);
1595 Ok(())
1596}
1597
1598fn cg_get_label(fs: &mut FuncState) -> i32 {
1602 fs.lasttarget = fs.pc;
1603 fs.pc
1604}
1605
1606fn cg_concat(fs: &mut FuncState, l1: &mut i32, l2: i32) -> Result<(), LuaError> {
1610 if l2 == NO_JUMP {
1611 return Ok(());
1612 }
1613 if *l1 == NO_JUMP {
1614 *l1 = l2;
1615 return Ok(());
1616 }
1617 let mut list = *l1;
1618 loop {
1619 let next = cg_get_jump(fs, list);
1620 if next == NO_JUMP {
1621 break;
1622 }
1623 list = next;
1624 }
1625 cg_fix_jump(fs, list, l2)
1626}
1627
1628fn cg_patch_list(fs: &mut FuncState, list: i32, target: i32) -> Result<(), LuaError> {
1637 cg_patch_list_aux(fs, list, target, lua_code::opcodes::NO_REG, target)
1638}
1639
1640fn cg_patch_to_here(fs: &mut FuncState, list: i32) -> Result<(), LuaError> {
1644 let target = cg_get_label(fs);
1645 cg_patch_list(fs, list, target)
1646}
1647
1648fn cg_negate_condition(fs: &mut FuncState, e: &ExprDesc) {
1654 let pc = e.u.info - 1;
1655 let mut inst = cg_inst_at(fs, pc);
1656 let k = inst.arg_k();
1657 inst.set_arg_k(k ^ 1);
1658 cg_set_inst_at(fs, pc, inst);
1659}
1660
1661fn cg_go_if_true(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1670 cg_discharge_vars(fs, line, e)?;
1671 let pc: i32 = match e.k {
1672 ExprKind::Jmp => {
1673 cg_negate_condition(fs, e);
1674 e.u.info
1675 }
1676 ExprKind::K | ExprKind::KFlt | ExprKind::KInt | ExprKind::KStr | ExprKind::True => NO_JUMP,
1677 _ => cg_jump_on_cond(fs, line, e, 0)?,
1678 };
1679 cg_concat(fs, &mut e.f, pc)?;
1680 cg_patch_to_here(fs, e.t)?;
1681 e.t = NO_JUMP;
1682 Ok(())
1683}
1684
1685fn cg_go_if_false(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1692 cg_discharge_vars(fs, line, e)?;
1693 let pc: i32 = match e.k {
1694 ExprKind::Jmp => e.u.info,
1695 ExprKind::Nil | ExprKind::False => NO_JUMP,
1696 _ => cg_jump_on_cond(fs, line, e, 1)?,
1697 };
1698 cg_concat(fs, &mut e.t, pc)?;
1699 cg_patch_to_here(fs, e.f)?;
1700 e.f = NO_JUMP;
1701 Ok(())
1702}
1703
1704fn cg_jump_on_cond(
1714 fs: &mut FuncState,
1715 line: i32,
1716 e: &mut ExprDesc,
1717 cond: u8,
1718) -> Result<i32, LuaError> {
1719 let reg = cg_exp_to_any_reg(fs, line, e)?;
1720 cg_free_exp(fs, e);
1721 let test = lua_code::opcodes::Instruction::abck(
1722 lua_code::opcodes::OpCode::TestSet,
1723 lua_code::opcodes::NO_REG,
1724 reg as u32,
1725 0,
1726 cond as u32,
1727 );
1728 emit_inst(fs, line, test);
1729 Ok(cg_jump(fs, line))
1730}
1731
1732fn cg_infix(fs: &mut FuncState, op: BinOpr, v: &mut ExprDesc, line: i32) -> Result<(), LuaError> {
1745 match op {
1746 BinOpr::And => cg_go_if_true(fs, line, v),
1747 BinOpr::Or => cg_go_if_false(fs, line, v),
1748 BinOpr::Concat => cg_exp_to_next_reg(fs, line, v),
1749 BinOpr::Add
1750 | BinOpr::Sub
1751 | BinOpr::Mul
1752 | BinOpr::Div
1753 | BinOpr::IDiv
1754 | BinOpr::Mod
1755 | BinOpr::Pow
1756 | BinOpr::BAnd
1757 | BinOpr::BOr
1758 | BinOpr::BXor
1759 | BinOpr::Shl
1760 | BinOpr::Shr
1761 | BinOpr::Eq
1762 | BinOpr::Ne
1763 | BinOpr::Lt
1764 | BinOpr::Le
1765 | BinOpr::Gt
1766 | BinOpr::Ge => {
1767 if matches!(v.k, ExprKind::KInt | ExprKind::KFlt) && v.t == NO_JUMP && v.f == NO_JUMP {
1768 cg_discharge_vars(fs, line, v)
1769 } else {
1770 cg_exp_to_any_reg(fs, line, v).map(|_| ())
1771 }
1772 }
1773 _ => cg_discharge_vars(fs, line, v),
1774 }
1775}
1776
1777fn cg_sc_int(e: &ExprDesc) -> Option<u8> {
1783 if !matches!(e.k, ExprKind::KInt) {
1784 return None;
1785 }
1786 if e.t != NO_JUMP || e.f != NO_JUMP {
1787 return None;
1788 }
1789 let biased = (e.u.ival as u64).wrapping_add(lua_code::opcodes::OFFSET_S_C as u64);
1790 if biased <= lua_code::opcodes::MAXARG_C as u64 {
1791 Some(biased as u8)
1792 } else {
1793 None
1794 }
1795}
1796
1797fn mark_vararg_table_needed(fs: &mut FuncState) {
1798 fs.f.vararg_table_needed = true;
1799 for inst in fs.f.code.iter_mut() {
1800 let mut op = lua_code::opcodes::Instruction(inst.raw());
1801 if op.opcode() == Some(lua_code::opcodes::OpCode::VarArgPack) {
1802 op.set_arg_k(1);
1803 *inst = lua_types::opcode::Instruction::new(op.0);
1804 break;
1805 }
1806 }
1807}
1808
1809fn cg_exp_to_any_reg(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<u8, LuaError> {
1813 cg_discharge_vars(fs, line, e)?;
1814 if e.k == ExprKind::NonReloc {
1815 if e.t == NO_JUMP && e.f == NO_JUMP {
1816 return Ok(e.u.info as u8);
1817 }
1818 if e.u.info >= fs.nactvar as i32 {
1819 cg_exp_to_reg(fs, line, e, e.u.info as u8)?;
1820 return Ok(e.u.info as u8);
1821 }
1822 }
1823 cg_exp_to_next_reg(fs, line, e)?;
1824 Ok(e.u.info as u8)
1825}
1826
1827fn cg_discharge_vars(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
1831 match e.k {
1832 ExprKind::VarArgVar => {
1833 mark_vararg_table_needed(fs);
1834 e.u.info = e.u.var_ridx as i32;
1835 e.k = ExprKind::NonReloc;
1836 }
1837 ExprKind::Local => {
1838 e.u.info = e.u.var_ridx as i32;
1839 e.k = ExprKind::NonReloc;
1840 }
1841 ExprKind::UpVal => {
1842 let inst = lua_code::opcodes::Instruction::abck(
1843 lua_code::opcodes::OpCode::GetUpVal,
1844 0,
1845 e.u.info as u32,
1846 0,
1847 0,
1848 );
1849 let pc = emit_inst(fs, line, inst);
1850 e.u.info = pc;
1851 e.k = ExprKind::Reloc;
1852 }
1853 ExprKind::IndexUp => {
1854 let inst = lua_code::opcodes::Instruction::abck(
1855 lua_code::opcodes::OpCode::GetTabUp,
1856 0,
1857 e.u.ind_t as u32,
1858 e.u.ind_idx as u32,
1859 0,
1860 );
1861 let pc = emit_inst(fs, line, inst);
1862 e.u.info = pc;
1863 e.k = ExprKind::Reloc;
1864 }
1865 ExprKind::IndexI => {
1866 cg_free_reg_if_temp(fs, e.u.ind_t as i32);
1867 let inst = lua_code::opcodes::Instruction::abck(
1868 lua_code::opcodes::OpCode::GetI,
1869 0,
1870 e.u.ind_t as u32,
1871 e.u.ind_idx as u32,
1872 0,
1873 );
1874 let pc = emit_inst(fs, line, inst);
1875 e.u.info = pc;
1876 e.k = ExprKind::Reloc;
1877 }
1878 ExprKind::IndexStr => {
1879 cg_free_reg_if_temp(fs, e.u.ind_t as i32);
1880 let inst = lua_code::opcodes::Instruction::abck(
1881 lua_code::opcodes::OpCode::GetField,
1882 0,
1883 e.u.ind_t as u32,
1884 e.u.ind_idx as u32,
1885 0,
1886 );
1887 let pc = emit_inst(fs, line, inst);
1888 e.u.info = pc;
1889 e.k = ExprKind::Reloc;
1890 }
1891 ExprKind::Indexed => {
1892 let t_reg = e.u.ind_t as i32;
1893 let idx_reg = e.u.ind_idx as i32;
1894 if idx_reg > t_reg {
1895 cg_free_reg_if_temp(fs, idx_reg);
1896 cg_free_reg_if_temp(fs, t_reg);
1897 } else {
1898 cg_free_reg_if_temp(fs, t_reg);
1899 cg_free_reg_if_temp(fs, idx_reg);
1900 }
1901 let inst = lua_code::opcodes::Instruction::abck(
1902 lua_code::opcodes::OpCode::GetTable,
1903 0,
1904 e.u.ind_t as u32,
1905 e.u.ind_idx as u32,
1906 0,
1907 );
1908 let pc = emit_inst(fs, line, inst);
1909 e.u.info = pc;
1910 e.k = ExprKind::Reloc;
1911 }
1912 ExprKind::VarArgIndex => {
1913 let t_reg = e.u.ind_t as i32;
1914 let idx_reg = e.u.ind_idx as i32;
1915 if idx_reg > t_reg {
1916 cg_free_reg_if_temp(fs, idx_reg);
1917 cg_free_reg_if_temp(fs, t_reg);
1918 } else {
1919 cg_free_reg_if_temp(fs, t_reg);
1920 cg_free_reg_if_temp(fs, idx_reg);
1921 }
1922 let inst = lua_code::opcodes::Instruction::abck(
1923 lua_code::opcodes::OpCode::GetVArg,
1924 0,
1925 e.u.ind_t as u32,
1926 e.u.ind_idx as u32,
1927 0,
1928 );
1929 let pc = emit_inst(fs, line, inst);
1930 e.u.info = pc;
1931 e.k = ExprKind::Reloc;
1932 }
1933 ExprKind::VarArg | ExprKind::Call => {
1934 cg_set_one_ret(fs, e);
1935 }
1936 _ => {}
1937 }
1938 Ok(())
1939}
1940
1941fn cg_set_one_ret(fs: &mut FuncState, e: &mut ExprDesc) {
1947 if e.k == ExprKind::Call {
1948 let pc_idx = e.u.info as usize;
1949 let lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
1950 debug_assert_eq!(lc.arg_c(), 2);
1951 e.u.info = lc.arg_a() as i32;
1952 e.k = ExprKind::NonReloc;
1953 } else if e.k == ExprKind::VarArg {
1954 let pc_idx = e.u.info as usize;
1955 let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
1956 lc.set_arg_c(2);
1957 fs.f.code[pc_idx] = lua_types::opcode::Instruction::new(lc.0);
1958 e.k = ExprKind::Reloc;
1959 }
1960}
1961
1962fn cg_storevar(
1965 fs: &mut FuncState,
1966 line: i32,
1967 var: &ExprDesc,
1968 ex: &mut ExprDesc,
1969) -> Result<(), LuaError> {
1970 match var.k {
1971 ExprKind::Local => {
1972 cg_free_exp(fs, ex);
1973 cg_exp_to_reg(fs, line, ex, var.u.var_ridx as u8)?;
1974 return Ok(());
1975 }
1976 ExprKind::UpVal => {
1977 let e_reg = cg_exp_to_any_reg(fs, line, ex)?;
1978 let inst = lua_code::opcodes::Instruction::abck(
1979 lua_code::opcodes::OpCode::SetUpVal,
1980 e_reg as u32,
1981 var.u.info as u32,
1982 0,
1983 0,
1984 );
1985 emit_inst(fs, line, inst);
1986 }
1987 ExprKind::IndexUp => {
1988 cg_store_abrk(
1989 fs,
1990 line,
1991 lua_code::opcodes::OpCode::SetTabUp,
1992 var.u.ind_t as u32,
1993 var.u.ind_idx as u32,
1994 ex,
1995 )?;
1996 }
1997 ExprKind::IndexI => {
1998 cg_store_abrk(
1999 fs,
2000 line,
2001 lua_code::opcodes::OpCode::SetI,
2002 var.u.ind_t as u32,
2003 var.u.ind_idx as u32,
2004 ex,
2005 )?;
2006 }
2007 ExprKind::IndexStr => {
2008 cg_store_abrk(
2009 fs,
2010 line,
2011 lua_code::opcodes::OpCode::SetField,
2012 var.u.ind_t as u32,
2013 var.u.ind_idx as u32,
2014 ex,
2015 )?;
2016 }
2017 ExprKind::Indexed => {
2018 cg_store_abrk(
2019 fs,
2020 line,
2021 lua_code::opcodes::OpCode::SetTable,
2022 var.u.ind_t as u32,
2023 var.u.ind_idx as u32,
2024 ex,
2025 )?;
2026 }
2027 ExprKind::VarArgIndex => {
2028 mark_vararg_table_needed(fs);
2029 cg_store_abrk(
2030 fs,
2031 line,
2032 lua_code::opcodes::OpCode::SetTable,
2033 var.u.ind_t as u32,
2034 var.u.ind_idx as u32,
2035 ex,
2036 )?;
2037 }
2038 _ => {
2039 return Err(LuaError::syntax(format_args!(
2040 "internal: cg_storevar: invalid var kind {:?}",
2041 var.k
2042 )));
2043 }
2044 }
2045 cg_free_exp(fs, ex);
2046 Ok(())
2047}
2048
2049fn cg_store_abrk(
2053 fs: &mut FuncState,
2054 line: i32,
2055 op: lua_code::opcodes::OpCode,
2056 a: u32,
2057 b: u32,
2058 ex: &mut ExprDesc,
2059) -> Result<(), LuaError> {
2060 let c_reg = cg_exp_to_any_reg(fs, line, ex)?;
2061 let inst = lua_code::opcodes::Instruction::abck(op, a, b, c_reg as u32, 0);
2062 emit_inst(fs, line, inst);
2063 Ok(())
2064}
2065
2066fn cg_discharge_to_reg(
2071 fs: &mut FuncState,
2072 line: i32,
2073 e: &mut ExprDesc,
2074 reg: u8,
2075) -> Result<(), LuaError> {
2076 cg_discharge_vars(fs, line, e)?;
2077 match e.k {
2078 ExprKind::Jmp => {
2079 return Ok(());
2080 }
2081 ExprKind::NonReloc => {
2082 if e.u.info as u8 != reg {
2083 let inst = lua_code::opcodes::Instruction::abck(
2084 lua_code::opcodes::OpCode::Move,
2085 reg as u32,
2086 e.u.info as u32,
2087 0,
2088 0,
2089 );
2090 emit_inst(fs, line, inst);
2091 }
2092 }
2093 ExprKind::Reloc => {
2094 let pc = e.u.info as usize;
2095 let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc].0);
2096 lc.set_arg_a(reg as u32);
2097 fs.f.code[pc] = lua_types::opcode::Instruction::new(lc.0);
2098 }
2099 ExprKind::Nil => {
2100 let inst = lua_code::opcodes::Instruction::abck(
2101 lua_code::opcodes::OpCode::LoadNil,
2102 reg as u32,
2103 0,
2104 0,
2105 0,
2106 );
2107 emit_inst(fs, line, inst);
2108 }
2109 ExprKind::True => {
2110 let inst = lua_code::opcodes::Instruction::abck(
2111 lua_code::opcodes::OpCode::LoadTrue,
2112 reg as u32,
2113 0,
2114 0,
2115 0,
2116 );
2117 emit_inst(fs, line, inst);
2118 }
2119 ExprKind::False => {
2120 let inst = lua_code::opcodes::Instruction::abck(
2121 lua_code::opcodes::OpCode::LoadFalse,
2122 reg as u32,
2123 0,
2124 0,
2125 0,
2126 );
2127 emit_inst(fs, line, inst);
2128 }
2129 ExprKind::KInt => {
2130 let i = e.u.ival;
2131 let max = lua_code::opcodes::MAXARG_BX as i64 - lua_code::opcodes::OFFSET_S_BX as i64;
2132 let min = -(lua_code::opcodes::OFFSET_S_BX as i64);
2133 if i >= min && i <= max {
2134 let bx = (i as i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
2135 let inst = lua_code::opcodes::Instruction::abx(
2136 lua_code::opcodes::OpCode::LoadI,
2137 reg as u32,
2138 bx,
2139 );
2140 emit_inst(fs, line, inst);
2141 } else {
2142 let k_idx = add_k_value(fs, LuaValue::Int(i));
2143 let inst = lua_code::opcodes::Instruction::abx(
2144 lua_code::opcodes::OpCode::LoadK,
2145 reg as u32,
2146 k_idx as u32,
2147 );
2148 emit_inst(fs, line, inst);
2149 }
2150 }
2151 ExprKind::KFlt => {
2152 let f = e.u.nval;
2153 let max = lua_code::opcodes::MAXARG_BX as i64 - lua_code::opcodes::OFFSET_S_BX as i64;
2154 let min = -(lua_code::opcodes::OFFSET_S_BX as i64);
2155 let fi_opt: Option<i64> = if f.fract() == 0.0 && f.abs() < i64::MAX as f64 {
2156 Some(f as i64)
2157 } else {
2158 None
2159 };
2160 if let Some(fi) = fi_opt.filter(|fi| *fi >= min && *fi <= max) {
2161 let bx = (fi as i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
2162 let inst = lua_code::opcodes::Instruction::abx(
2163 lua_code::opcodes::OpCode::LoadF,
2164 reg as u32,
2165 bx,
2166 );
2167 emit_inst(fs, line, inst);
2168 } else {
2169 let k_idx = add_k_value(fs, LuaValue::Float(f));
2170 let inst = lua_code::opcodes::Instruction::abx(
2171 lua_code::opcodes::OpCode::LoadK,
2172 reg as u32,
2173 k_idx as u32,
2174 );
2175 emit_inst(fs, line, inst);
2176 }
2177 }
2178 ExprKind::KStr => {
2179 let s =
2180 e.u.strval.clone().ok_or_else(|| {
2181 LuaError::syntax(format_args!("internal: VKStr with no strval"))
2182 })?;
2183 let k_idx = add_k_string(fs, s);
2184 let inst = lua_code::opcodes::Instruction::abx(
2185 lua_code::opcodes::OpCode::LoadK,
2186 reg as u32,
2187 k_idx as u32,
2188 );
2189 emit_inst(fs, line, inst);
2190 }
2191 ExprKind::K => {
2192 let inst = lua_code::opcodes::Instruction::abx(
2193 lua_code::opcodes::OpCode::LoadK,
2194 reg as u32,
2195 e.u.info as u32,
2196 );
2197 emit_inst(fs, line, inst);
2198 }
2199 _ => {
2200 return Err(LuaError::syntax(format_args!(
2201 "internal: cg_discharge_to_reg cannot discharge {:?}",
2202 e.k
2203 )));
2204 }
2205 }
2206 e.u.info = reg as i32;
2207 e.k = ExprKind::NonReloc;
2208 Ok(())
2209}
2210
2211fn cg_need_value(fs: &FuncState, list: i32) -> bool {
2216 let mut list = list;
2217 while list != NO_JUMP {
2218 let ctrl_pc = cg_get_jump_control(fs, list);
2219 let ctrl = cg_inst_at(fs, ctrl_pc);
2220 if ctrl.opcode() != Some(lua_code::opcodes::OpCode::TestSet) {
2221 return true;
2222 }
2223 list = cg_get_jump(fs, list);
2224 }
2225 false
2226}
2227
2228fn cg_code_loadbool(fs: &mut FuncState, line: i32, reg: i32, op: lua_code::opcodes::OpCode) -> i32 {
2232 cg_get_label(fs);
2233 let inst = lua_code::opcodes::Instruction::abck(op, reg as u32, 0, 0, 0);
2234 emit_inst(fs, line, inst)
2235}
2236
2237fn cg_patch_list_aux(
2241 fs: &mut FuncState,
2242 list: i32,
2243 vtarget: i32,
2244 reg: u32,
2245 dtarget: i32,
2246) -> Result<(), LuaError> {
2247 let mut list = list;
2248 while list != NO_JUMP {
2249 let next = cg_get_jump(fs, list);
2250 if cg_patch_test_reg(fs, list, reg) {
2251 cg_fix_jump(fs, list, vtarget)?;
2252 } else {
2253 cg_fix_jump(fs, list, dtarget)?;
2254 }
2255 list = next;
2256 }
2257 Ok(())
2258}
2259
2260fn cg_exp_to_reg(fs: &mut FuncState, line: i32, e: &mut ExprDesc, reg: u8) -> Result<(), LuaError> {
2267 cg_discharge_to_reg(fs, line, e, reg)?;
2268 if e.k == ExprKind::Jmp {
2269 let info = e.u.info;
2270 cg_concat(fs, &mut e.t, info)?;
2271 }
2272 if e.t != e.f {
2273 let mut p_f = NO_JUMP;
2274 let mut p_t = NO_JUMP;
2275 if cg_need_value(fs, e.t) || cg_need_value(fs, e.f) {
2276 let fj = if e.k == ExprKind::Jmp {
2277 NO_JUMP
2278 } else {
2279 cg_jump(fs, line)
2280 };
2281 p_f = cg_code_loadbool(fs, line, reg as i32, lua_code::opcodes::OpCode::LFalseSkip);
2282 p_t = cg_code_loadbool(fs, line, reg as i32, lua_code::opcodes::OpCode::LoadTrue);
2283 cg_patch_to_here(fs, fj)?;
2284 }
2285 let final_pc = cg_get_label(fs);
2286 cg_patch_list_aux(fs, e.f, final_pc, reg as u32, p_f)?;
2287 cg_patch_list_aux(fs, e.t, final_pc, reg as u32, p_t)?;
2288 }
2289 e.f = NO_JUMP;
2290 e.t = NO_JUMP;
2291 e.u.info = reg as i32;
2292 e.k = ExprKind::NonReloc;
2293 Ok(())
2294}
2295
2296fn cg_free_reg_if_temp(fs: &mut FuncState, reg: i32) {
2300 if reg >= fs.nactvar as i32 {
2301 debug_assert!(reg < fs.freereg as i32);
2302 if reg == fs.freereg as i32 - 1 {
2303 fs.freereg -= 1;
2304 }
2305 }
2306}
2307
2308fn cg_check_global(
2325 fs: &mut FuncState,
2326 line: i32,
2327 target: &ExprDesc,
2328 name: GcRef<LuaString>,
2329) -> Result<(), LuaError> {
2330 let k = add_k_string(fs, name);
2331 let bx = if (k as u32) >= lua_code::opcodes::MAXARG_BX {
2332 0
2333 } else {
2334 (k + 1) as u32
2335 };
2336 let mut probe = target.clone();
2337 cg_exp_to_next_reg(fs, line, &mut probe)?;
2338 let reg = probe.u.info;
2339 let inst =
2340 lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::ErrNNil, reg as u32, bx);
2341 emit_inst(fs, line, inst);
2342 cg_free_reg(fs, reg);
2343 Ok(())
2344}
2345
2346fn cg_exp_to_next_reg(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
2347 cg_discharge_vars(fs, line, e)?;
2348 cg_free_exp(fs, e);
2349 let reg = reserve_reg(fs)?;
2350 cg_exp_to_reg(fs, line, e, reg)
2351}
2352
2353fn cg_set_returns(fs: &mut FuncState, e: &mut ExprDesc, nresults: i32) {
2355 let pc_idx = e.u.info as usize;
2356 let mut lc = lua_code::opcodes::Instruction(fs.f.code[pc_idx].0);
2357 if e.k == ExprKind::Call {
2358 lc.set_arg_c((nresults + 1) as u32);
2359 } else {
2360 debug_assert_eq!(e.k, ExprKind::VarArg);
2361 lc.set_arg_c((nresults + 1) as u32);
2362 lc.set_arg_a(fs.freereg as u32);
2363 fs.freereg += 1;
2369 bump_maxstack(fs, fs.freereg);
2370 }
2371 fs.f.code[pc_idx] = lua_types::opcode::Instruction::new(lc.0);
2372}
2373
2374fn cg_final_target(fs: &FuncState, mut i: i32) -> i32 {
2377 for _ in 0..100 {
2378 let inst = cg_inst_at(fs, i);
2379 if inst.opcode() != Some(lua_code::opcodes::OpCode::Jmp) {
2380 break;
2381 }
2382 i += inst.arg_s_j() + 1;
2383 }
2384 i
2385}
2386
2387fn cg_finish(fs: &mut FuncState) {
2393 use lua_code::opcodes::OpCode;
2394 let needclose = fs.needclose;
2395 let is_vararg = fs.f.is_vararg;
2396 let numparams = fs.f.numparams as u32;
2397 let pc_end = fs.pc;
2398 for i in 0..pc_end {
2399 let mut inst = cg_inst_at(fs, i);
2400 match inst.opcode() {
2401 Some(OpCode::Return0) | Some(OpCode::Return1) => {
2402 if !(needclose || is_vararg) {
2403 continue;
2404 }
2405 inst.set_opcode(OpCode::Return);
2406 if needclose {
2407 inst.set_arg_k(1);
2408 }
2409 if is_vararg {
2410 inst.set_arg_c(numparams + 1);
2411 }
2412 cg_set_inst_at(fs, i, inst);
2413 }
2414 Some(OpCode::Return) | Some(OpCode::TailCall) => {
2415 if needclose {
2416 inst.set_arg_k(1);
2417 }
2418 if is_vararg {
2419 inst.set_arg_c(numparams + 1);
2420 }
2421 cg_set_inst_at(fs, i, inst);
2422 }
2423 Some(OpCode::Jmp) => {
2424 let target = cg_final_target(fs, i);
2425 let _ = cg_fix_jump(fs, i, target);
2426 }
2427 _ => {}
2428 }
2429 }
2430}
2431
2432fn cg_emit_return(
2435 fs: &mut FuncState,
2436 line: i32,
2437 first: i32,
2438 nret: i32,
2439 version: lua_types::LuaVersion,
2440) -> Result<(), LuaError> {
2441 let op = match nret {
2442 0 => lua_code::opcodes::OpCode::Return0,
2443 1 => lua_code::opcodes::OpCode::Return1,
2444 _ => lua_code::opcodes::OpCode::Return,
2445 };
2446 if matches!(version, lua_types::LuaVersion::V55) {
2447 check_limit(fs, nret + 1, lua_code::opcodes::MAXARG_B as i32, "returns")?;
2448 }
2449 let inst = lua_code::opcodes::Instruction::abck(op, first as u32, (nret + 1) as u32, 0, 0);
2450 emit_inst(fs, line, inst);
2451 Ok(())
2452}
2453
2454fn error_expected(ls: &mut LexState, token: TokenKind) -> LuaError {
2464 let tok_str = lua_lex::token2str(&ls.lex, token);
2465 let mut msg: Vec<u8> = Vec::with_capacity(tok_str.len() + 10);
2466 msg.extend_from_slice(&tok_str);
2467 msg.extend_from_slice(b" expected");
2468 lua_lex::syntax_error(&mut ls.lex, &msg)
2469}
2470
2471fn error_limit(fs: &FuncState, limit: i32, what: &str) -> LuaError {
2473 let line = fs.f.linedefined;
2474 if line == 0 {
2475 LuaError::syntax(format_args!(
2476 "too many {} (limit is {}) in main function",
2477 what, limit
2478 ))
2479 } else {
2480 LuaError::syntax(format_args!(
2481 "too many {} (limit is {}) in function at line {}",
2482 what, limit, line
2483 ))
2484 }
2485}
2486
2487fn check_limit(fs: &FuncState, v: i32, l: i32, what: &str) -> Result<(), LuaError> {
2488 if v > l {
2489 return Err(error_limit(fs, l, what));
2490 }
2491 Ok(())
2492}
2493
2494fn test_next(ls: &mut LexState, state: &mut LuaState, c: TokenKind) -> Result<bool, LuaError> {
2498 if ls.t.token == c {
2499 lex_next(ls, state)?;
2500 Ok(true)
2501 } else {
2502 Ok(false)
2503 }
2504}
2505
2506fn check(ls: &mut LexState, c: TokenKind) -> Result<(), LuaError> {
2507 if ls.t.token != c {
2508 return Err(error_expected(ls, c));
2509 }
2510 Ok(())
2511}
2512
2513fn check_next(ls: &mut LexState, state: &mut LuaState, c: TokenKind) -> Result<(), LuaError> {
2514 check(ls, c)?;
2515 lex_next(ls, state)?;
2516 Ok(())
2517}
2518
2519fn str_check_name(ls: &mut LexState, state: &mut LuaState) -> Result<GcRef<LuaString>, LuaError> {
2521 check(ls, TK_NAME)?;
2522 let ts =
2523 ls.t.seminfo
2524 .ts
2525 .clone()
2526 .ok_or_else(|| LuaError::syntax(format_args!("name expected")))?;
2527 lex_next(ls, state)?;
2528 Ok(ts)
2529}
2530
2531fn init_exp(e: &mut ExprDesc, k: ExprKind, i: i32) {
2532 e.f = NO_JUMP;
2533 e.t = NO_JUMP;
2534 e.k = k;
2535 e.u.info = i;
2536}
2537
2538fn codestring(e: &mut ExprDesc, s: GcRef<LuaString>) {
2539 e.f = NO_JUMP;
2540 e.t = NO_JUMP;
2541 e.k = ExprKind::KStr;
2542 e.u.strval = Some(s);
2543}
2544
2545fn codename(ls: &mut LexState, state: &mut LuaState, e: &mut ExprDesc) -> Result<(), LuaError> {
2546 let name = str_check_name(ls, state)?;
2547 codestring(e, name);
2548 Ok(())
2549}
2550
2551fn register_local_var(
2556 _ls: &mut LexState,
2557 _state: &mut LuaState,
2558 fs: &mut FuncState,
2559 varname: GcRef<LuaString>,
2560) -> Result<i32, LuaError> {
2561 let idx = fs.ndebugvars as usize;
2563 while fs.f.locvars.len() <= idx {
2564 fs.f.locvars.push(LocalVar {
2565 varname: varname.clone(), startpc: 0,
2567 endpc: 0,
2568 });
2569 }
2570 fs.f.locvars[idx].varname = varname;
2571 fs.f.locvars[idx].startpc = fs.pc;
2572 let result = fs.ndebugvars as i32;
2573 fs.ndebugvars += 1;
2574 Ok(result)
2575}
2576
2577fn new_local_var(
2580 ls: &mut LexState,
2581 _state: &mut LuaState,
2582 name: GcRef<LuaString>,
2583) -> Result<i32, LuaError> {
2584 let fs = ls.fs.as_ref().unwrap();
2585 let n = ls.dyd.actvar.len() as i32;
2586 let first_local = fs.firstlocal;
2587 check_limit(fs, n + 1 - first_local, MAX_VARS, "local variables")?;
2588
2589 let mut var = VarDesc::default();
2590 var.kind = VarKind::Reg;
2591 var.name = Some(name);
2592 ls.dyd.actvar.push(var);
2593 let result = ls.dyd.actvar.len() as i32 - 1 - first_local;
2594 Ok(result)
2595}
2596
2597fn get_local_var_desc<'a>(ls: &'a LexState, fs: &FuncState, vidx: i32) -> &'a VarDesc {
2599 &ls.dyd.actvar[(fs.firstlocal + vidx) as usize]
2600}
2601
2602fn get_local_var_desc_mut(ls: &mut LexState, first_local: i32, vidx: i32) -> &mut VarDesc {
2603 &mut ls.dyd.actvar[(first_local + vidx) as usize]
2604}
2605
2606fn reg_level(ls: &LexState, fs: &FuncState, nvar: i32) -> i32 {
2608 let mut nvar = nvar;
2609 while nvar > 0 {
2610 nvar -= 1;
2611 let vd = get_local_var_desc(ls, fs, nvar);
2612 if vd.kind != VarKind::CompileTimeConst {
2613 return vd.ridx as i32 + 1;
2614 }
2615 }
2616 0
2617}
2618
2619pub fn nvarstack(ls: &LexState, fs: &FuncState) -> i32 {
2622 reg_level(ls, fs, fs.nactvar as i32)
2623}
2624
2625fn init_var(ls: &LexState, fs: &FuncState, e: &mut ExprDesc, vidx: i32) {
2626 e.f = NO_JUMP;
2627 e.t = NO_JUMP;
2628 e.k = ExprKind::Local;
2629 e.u.var_vidx = vidx as u16;
2630 e.u.var_ridx = get_local_var_desc(ls, fs, vidx).ridx;
2631}
2632
2633fn check_readonly(ls: &mut LexState, state: &mut LuaState, e: &ExprDesc) -> Result<(), LuaError> {
2635 if let Some(name) = e.u.global_const_name.as_ref() {
2638 let msg = format!(
2639 "attempt to assign to const variable '{}'",
2640 String::from_utf8_lossy(name.as_bytes())
2641 );
2642 return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
2644 }
2645 let varname: Option<GcRef<LuaString>> = {
2646 let fs = ls.fs.as_ref().unwrap();
2647 match e.k {
2648 ExprKind::Const => ls.dyd.actvar[e.u.info as usize].name.clone(),
2649 ExprKind::Local | ExprKind::VarArgVar => {
2650 let vd = get_local_var_desc(ls, fs, e.u.var_vidx as i32);
2651 if vd.kind != VarKind::Reg {
2652 vd.name.clone()
2653 } else {
2654 None
2655 }
2656 }
2657 ExprKind::UpVal => {
2658 let up = &fs.f.upvalues[e.u.info as usize];
2659 if VarKind::from_u8(up.kind) != VarKind::Reg {
2660 up.name.clone()
2661 } else {
2662 None
2663 }
2664 }
2665 _ => None,
2666 }
2667 };
2668 if let Some(vname) = varname {
2669 let _ = state;
2674 let msg = format!(
2675 "attempt to assign to const variable '{}'",
2676 String::from_utf8_lossy(vname.as_bytes())
2677 );
2678 return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
2679 }
2680 Ok(())
2681}
2682
2683fn adjust_local_vars(ls: &mut LexState, state: &mut LuaState, nvars: i32) -> Result<(), LuaError> {
2685 let first_local = ls.fs.as_ref().unwrap().firstlocal;
2687 let nactvar_start = ls.fs.as_ref().unwrap().nactvar as i32;
2688 let mut reglevel_val = {
2689 let fs = ls.fs.as_ref().unwrap();
2690 reg_level(ls, fs, fs.nactvar as i32)
2691 };
2692
2693 for i in 0..nvars {
2694 let vidx = nactvar_start + i;
2695 ls.fs.as_mut().unwrap().nactvar += 1;
2696 let var_name = ls.dyd.actvar[(first_local + vidx) as usize].name.clone();
2697 ls.dyd.actvar[(first_local + vidx) as usize].ridx = reglevel_val as u8;
2698 reglevel_val += 1;
2699 if let Some(vn) = var_name {
2700 let mut fs_box = ls.fs.take().unwrap();
2701 let pidx_result = register_local_var(ls, state, &mut fs_box, vn);
2702 ls.fs = Some(fs_box);
2703 let pidx = pidx_result?;
2704 ls.dyd.actvar[(first_local + vidx) as usize].pidx = pidx as i16;
2705 } else {
2706 }
2708 }
2709 Ok(())
2710}
2711
2712fn remove_vars(ls: &mut LexState, fs: &mut FuncState, tolevel: i32) {
2714 let delta = fs.nactvar as i32 - tolevel;
2722 while fs.nactvar as i32 > tolevel {
2723 fs.nactvar -= 1;
2724 let nactvar = fs.nactvar as i32;
2725 let vd_kind = {
2726 let first_local = fs.firstlocal;
2727 ls.dyd
2728 .actvar
2729 .get((first_local + nactvar) as usize)
2730 .map(|v| v.kind)
2731 .unwrap_or(VarKind::Reg)
2732 };
2733 if vd_kind != VarKind::CompileTimeConst {
2734 let vd_pidx = {
2735 let first_local = fs.firstlocal;
2736 ls.dyd
2737 .actvar
2738 .get((first_local + nactvar) as usize)
2739 .map(|v| v.pidx)
2740 .unwrap_or(0)
2741 };
2742 if let Some(lv) = fs.f.locvars.get_mut(vd_pidx as usize) {
2743 lv.endpc = fs.pc;
2744 }
2745 }
2746 }
2747 if delta > 0 {
2748 let new_len = ls.dyd.actvar.len().saturating_sub(delta as usize);
2749 ls.dyd.actvar.truncate(new_len);
2750 }
2751}
2752
2753fn search_upvalue(fs: &FuncState, name: &GcRef<LuaString>) -> i32 {
2757 for (i, up) in fs.f.upvalues.iter().enumerate() {
2758 if up.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
2759 return i as i32;
2760 }
2761 }
2762 -1
2763}
2764
2765fn alloc_upvalue(fs: &mut FuncState) -> Result<usize, LuaError> {
2767 if fs.nups as i32 + 1 > MAX_UPVAL as i32 {
2768 return Err(error_limit(fs, MAX_UPVAL as i32, "upvalues"));
2769 }
2770 let idx = fs.nups as usize;
2771 while fs.f.upvalues.len() <= idx {
2772 fs.f.upvalues.push(UpvalDesc {
2773 name: None,
2774 instack: false,
2775 idx: 0,
2776 kind: 0,
2777 });
2778 }
2779 fs.nups += 1;
2780 Ok(idx)
2781}
2782
2783fn new_upvalue(
2785 ls: &LexState,
2786 fs: &mut FuncState,
2787 name: GcRef<LuaString>,
2788 v: &ExprDesc,
2789) -> Result<i32, LuaError> {
2790 let idx = alloc_upvalue(fs)?;
2791 let kind: u8 = if v.k == ExprKind::Local {
2792 let prev = fs
2793 .prev
2794 .as_deref()
2795 .expect("upvalue capture requires enclosing FuncState");
2796 get_local_var_desc(ls, prev, v.u.var_vidx as i32)
2797 .kind
2798 .as_u8()
2799 } else {
2800 let prev = fs
2801 .prev
2802 .as_deref()
2803 .expect("upvalue chain requires enclosing FuncState");
2804 prev.f.upvalues[v.u.info as usize].kind
2805 };
2806 let up = &mut fs.f.upvalues[idx];
2807 if v.k == ExprKind::Local {
2808 up.instack = true;
2809 up.idx = v.u.var_ridx;
2810 } else {
2811 up.instack = false;
2812 up.idx = v.u.info as u8;
2813 }
2814 up.kind = kind;
2815 up.name = Some(name);
2816 Ok(fs.nups as i32 - 1)
2817}
2818
2819fn searchvar(ls: &LexState, fs: &FuncState, n: &GcRef<LuaString>, var: &mut ExprDesc) -> i32 {
2821 let mut i = fs.nactvar as i32 - 1;
2822 while i >= 0 {
2823 let vd = get_local_var_desc(ls, fs, i);
2824 if vd.name.as_ref().map_or(false, |nm| GcRef::ptr_eq(nm, n)) {
2825 if vd.kind == VarKind::CompileTimeConst {
2826 init_exp(var, ExprKind::Const, fs.firstlocal + i);
2827 } else {
2828 init_var(ls, fs, var, i);
2829 if vd.kind == VarKind::VarArg {
2830 var.k = ExprKind::VarArgVar;
2831 }
2832 }
2833 return var.k as i32; }
2835 i -= 1;
2836 }
2837 -1
2838}
2839
2840fn markupval(fs: &mut FuncState, level: i32) {
2842 let mut current = fs.bl.as_deref_mut();
2843 while let Some(b) = current {
2844 if (b.nactvar as i32) <= level {
2845 b.upval = true;
2846 break;
2847 }
2848 current = b.previous.as_deref_mut();
2849 }
2850 fs.needclose = true;
2851}
2852
2853fn marktobeclosed(fs: &mut FuncState) {
2854 if let Some(bl) = fs.bl.as_mut() {
2855 bl.upval = true;
2856 bl.insidetbc = true;
2857 }
2858 fs.needclose = true;
2859}
2860
2861fn singlevaraux(
2866 ls: &LexState,
2867 fs: Option<&mut FuncState>,
2868 n: &GcRef<LuaString>,
2869 var: &mut ExprDesc,
2870 base: bool,
2871) -> Result<(), LuaError> {
2872 match fs {
2873 None => {
2874 init_exp(var, ExprKind::Void, 0);
2875 }
2876 Some(fs) => {
2877 let v = searchvar(ls, fs, n, var);
2878 if v >= 0 {
2879 if !base {
2880 if var.k == ExprKind::VarArgVar {
2881 mark_vararg_table_needed(fs);
2882 var.k = ExprKind::Local;
2883 }
2884 if var.k == ExprKind::Local {
2885 markupval(fs, var.u.var_vidx as i32);
2886 }
2887 }
2888 } else {
2889 let idx = search_upvalue(fs, n);
2890 let final_idx = if idx < 0 {
2891 singlevaraux(ls, fs.prev.as_deref_mut(), n, var, false)?;
2892 if var.k == ExprKind::Local
2893 || var.k == ExprKind::VarArgVar
2894 || var.k == ExprKind::UpVal
2895 {
2896 if var.k == ExprKind::VarArgVar {
2897 var.k = ExprKind::Local;
2898 }
2899 new_upvalue(ls, fs, n.clone(), var)?
2900 } else {
2901 return Ok(());
2902 }
2903 } else {
2904 idx
2905 };
2906 init_exp(var, ExprKind::UpVal, final_idx);
2907 }
2908 }
2909 }
2910 Ok(())
2911}
2912
2913fn singlevar(ls: &mut LexState, state: &mut LuaState, var: &mut ExprDesc) -> Result<(), LuaError> {
2915 let name_line = ls.linenumber;
2916 let varname = str_check_name(ls, state)?;
2917 let mut fs_box = ls.fs.take();
2918 let recurse_result = singlevaraux(ls, fs_box.as_deref_mut(), &varname, var, true);
2919 ls.fs = fs_box;
2920 recurse_result?;
2921 if state.global().lua_version == lua_types::LuaVersion::V55 {
2922 match var.k {
2923 ExprKind::Local | ExprKind::Const => {
2924 if let Some(global_level) = latest_matching_global_barrier_current(ls, &varname) {
2925 let local_level = scope_level_for_local_level(ls, var.u.var_vidx as u8);
2926 if global_level > local_level {
2927 init_exp(var, ExprKind::Void, 0);
2928 }
2929 }
2930 }
2931 ExprKind::UpVal => {
2932 if is_active_global_function_name(ls, &varname) {
2933 init_exp(var, ExprKind::Void, 0);
2934 }
2935 }
2936 _ => {}
2937 }
2938 }
2939 if var.k == ExprKind::Void {
2940 let mut declared_const: Option<bool> = None;
2945 for (n, c) in ls.declared_globals.iter().rev() {
2946 if GcRef::ptr_eq(n, &varname) {
2947 declared_const = Some(*c);
2948 break;
2949 }
2950 }
2951 let is_const_global = match declared_const {
2952 Some(c) => c,
2953 None if ls.global_wildcard => ls.global_wildcard_const,
2954 None if ls.global_strict => {
2955 let msg = format!(
2956 "variable '{}' not declared",
2957 String::from_utf8_lossy(varname.as_bytes())
2958 );
2959 let saved_line = ls.lex.linenumber;
2961 ls.lex.linenumber = name_line;
2962 let err = lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0);
2963 ls.lex.linenumber = saved_line;
2964 return Err(err);
2965 }
2966 None => false,
2967 };
2968 let envn = ls
2969 .envn
2970 .clone()
2971 .expect("envn must be set when resolving globals");
2972 if has_active_global_barrier(ls, &envn) {
2973 let msg = format!(
2974 "{} is global when accessing variable '{}'",
2975 lua_lex::LUA_ENV.escape_ascii(),
2976 String::from_utf8_lossy(varname.as_bytes())
2977 );
2978 return Err(lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0));
2979 }
2980 let mut env_var = ExprDesc::default();
2981 let mut fs_box = ls.fs.take();
2982 let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut env_var, true);
2983 ls.fs = fs_box;
2984 r?;
2985 debug_assert!(env_var.k != ExprKind::Void, "_ENV must resolve");
2986 let line = ls.lastline;
2987 let fs = ls.fs.as_mut().unwrap();
2988 cg_exp_to_any_reg_up(fs, line, &mut env_var)?;
2989 let mut key = ExprDesc::default();
2990 let const_name = if is_const_global {
2991 Some(varname.clone())
2992 } else {
2993 None
2994 };
2995 codestring(&mut key, varname);
2996 cg_indexed(fs, line, &mut env_var, &mut key)?;
2997 *var = env_var;
2998 var.u.global_const_name = const_name;
2999 }
3000 Ok(())
3001}
3002
3003fn adjust_assign(
3004 ls: &mut LexState,
3005 _state: &mut LuaState,
3006 nvars: i32,
3007 nexps: i32,
3008 e: &mut ExprDesc,
3009) -> Result<(), LuaError> {
3010 let needed = nvars - nexps;
3011 let line = ls.lastline;
3012 let fs = ls.fs.as_mut().unwrap();
3013 if e.k.has_mult_ret() {
3014 let extra = if needed + 1 < 0 { 0 } else { needed + 1 };
3015 cg_set_returns(fs, e, extra);
3016 } else {
3017 if e.k != ExprKind::Void {
3018 cg_exp_to_next_reg(fs, line, e)?;
3019 }
3020 if needed > 0 {
3021 let from = fs.freereg as i32;
3022 cg_emit_nil(fs, line, from, needed);
3023 }
3024 }
3025 if needed > 0 {
3026 for _ in 0..needed {
3027 reserve_reg(fs)?;
3028 }
3029 } else {
3030 fs.freereg = (fs.freereg as i32 + needed) as u8;
3031 }
3032 Ok(())
3033}
3034
3035fn cg_emit_newtable(fs: &mut FuncState, line: i32) -> i32 {
3039 let newtable =
3040 lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::NewTable, 0, 0, 0, 0);
3041 let pc = emit_inst(fs, line, newtable);
3042 let extra = lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, 0);
3043 emit_inst(fs, line, extra);
3044 pc
3045}
3046
3047fn cg_settablesize(fs: &mut FuncState, pc: i32, ra: i32, asize: i32, hsize: i32) {
3051 let rb = if hsize != 0 {
3052 (hsize as u32).next_power_of_two().trailing_zeros() as i32 + 1
3053 } else {
3054 0
3055 };
3056 let maxc = lua_code::opcodes::MAXARG_C as i32 + 1;
3057 let extra = asize / maxc;
3058 let rc = asize % maxc;
3059 let k = if extra > 0 { 1u32 } else { 0u32 };
3060 let newtable = lua_code::opcodes::Instruction::abck(
3061 lua_code::opcodes::OpCode::NewTable,
3062 ra as u32,
3063 rb as u32,
3064 rc as u32,
3065 k,
3066 );
3067 fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(newtable.0);
3068 let extra_inst =
3069 lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, extra as u32);
3070 fs.f.code[pc as usize + 1] = lua_types::opcode::Instruction::new(extra_inst.0);
3071}
3072
3073fn cg_setlist(fs: &mut FuncState, line: i32, base: i32, nelems: i32, tostore: i32) {
3078 let maxc = lua_code::opcodes::MAXARG_C as i32;
3079 let tostore_arg = if tostore == LUA_MULTRET { 0 } else { tostore };
3080 if nelems <= maxc {
3081 let inst = lua_code::opcodes::Instruction::abck(
3082 lua_code::opcodes::OpCode::SetList,
3083 base as u32,
3084 tostore_arg as u32,
3085 nelems as u32,
3086 0,
3087 );
3088 emit_inst(fs, line, inst);
3089 } else {
3090 let extra = nelems / (maxc + 1);
3091 let nelems_lo = nelems % (maxc + 1);
3092 let inst = lua_code::opcodes::Instruction::abck(
3093 lua_code::opcodes::OpCode::SetList,
3094 base as u32,
3095 tostore_arg as u32,
3096 nelems_lo as u32,
3097 1,
3098 );
3099 emit_inst(fs, line, inst);
3100 let extra_inst =
3101 lua_code::opcodes::Instruction::ax(lua_code::opcodes::OpCode::ExtraArg, extra as u32);
3102 emit_inst(fs, line, extra_inst);
3103 }
3104 fs.freereg = (base + 1) as u8;
3105}
3106
3107fn cg_indexed(
3112 fs: &mut FuncState,
3113 line: i32,
3114 t: &mut ExprDesc,
3115 k: &mut ExprDesc,
3116) -> Result<(), LuaError> {
3117 t.u.global_const_name = None;
3118 if k.k == ExprKind::KStr {
3119 let s =
3120 k.u.strval
3121 .clone()
3122 .ok_or_else(|| LuaError::syntax(format_args!("internal: VKStr with no strval")))?;
3123 let k_idx = add_k_string(fs, s);
3124 k.u.info = k_idx;
3125 k.k = ExprKind::K;
3126 }
3127 let k_is_kstr =
3128 k.k == ExprKind::K && k.u.info >= 0 && (k.u.info as u32) <= lua_code::opcodes::MAXARG_B;
3129 if t.k == ExprKind::VarArgVar {
3130 cg_exp_to_any_reg(fs, line, k)?;
3131 t.u.ind_t = t.u.var_ridx;
3132 t.u.ind_idx = k.u.info as i16;
3133 t.k = ExprKind::VarArgIndex;
3134 return Ok(());
3135 }
3136 if t.k == ExprKind::UpVal && !k_is_kstr {
3137 cg_exp_to_any_reg(fs, line, t)?;
3138 }
3139 if t.k == ExprKind::UpVal {
3140 let temp = t.u.info as u8;
3141 t.u.ind_t = temp;
3142 t.u.ind_idx = k.u.info as i16;
3143 t.k = ExprKind::IndexUp;
3144 return Ok(());
3145 }
3146 let t_reg = match t.k {
3147 ExprKind::Local => t.u.var_ridx,
3148 ExprKind::NonReloc => t.u.info as u8,
3149 _ => {
3150 return Err(LuaError::syntax(format_args!(
3151 "internal: cg_indexed on non-register table kind {:?}",
3152 t.k
3153 )))
3154 }
3155 };
3156 t.u.ind_t = t_reg;
3157 if k.k == ExprKind::K && k_is_kstr {
3158 t.u.ind_idx = k.u.info as i16;
3159 t.k = ExprKind::IndexStr;
3160 } else if k.k == ExprKind::KInt && cg_fits_int_key(k.u.ival) {
3161 t.u.ind_idx = k.u.ival as i16;
3162 t.k = ExprKind::IndexI;
3163 } else {
3164 cg_exp_to_any_reg(fs, line, k)?;
3165 t.u.ind_idx = k.u.info as i16;
3166 t.k = ExprKind::Indexed;
3167 }
3168 Ok(())
3169}
3170
3171fn cg_fits_int_key(i: i64) -> bool {
3172 i >= 0 && (i as u32) <= lua_code::opcodes::MAXARG_C
3173}
3174
3175fn cg_self(
3179 fs: &mut FuncState,
3180 line: i32,
3181 e: &mut ExprDesc,
3182 key: &mut ExprDesc,
3183 keep_self_opcode_for_register_key: bool,
3184) -> Result<(), LuaError> {
3185 cg_exp_to_any_reg(fs, line, e)?;
3186 let ereg = e.u.info;
3187 cg_free_exp(fs, e);
3188 let base = fs.freereg as i32;
3189 e.u.info = base;
3190 e.k = ExprKind::NonReloc;
3191 reserve_regs(fs, 2)?;
3192 let key_str = key.u.strval.clone().ok_or_else(|| {
3193 LuaError::syntax(format_args!(
3194 "internal: cg_self expected VKStr key, got {:?}",
3195 key.k
3196 ))
3197 })?;
3198 let k_idx = add_k_string(fs, key_str);
3199 if (k_idx as u32) <= lua_code::opcodes::MAXINDEXRK {
3200 let inst = lua_code::opcodes::Instruction::abck(
3201 lua_code::opcodes::OpCode::Self_,
3202 base as u32,
3203 ereg as u32,
3204 k_idx as u32,
3205 1,
3206 );
3207 emit_inst(fs, line, inst);
3208 } else if keep_self_opcode_for_register_key {
3209 key.k = ExprKind::K;
3210 key.u.info = k_idx;
3211 cg_exp_to_any_reg(fs, line, key)?;
3212 let inst = lua_code::opcodes::Instruction::abck(
3213 lua_code::opcodes::OpCode::Self_,
3214 base as u32,
3215 ereg as u32,
3216 key.u.info as u32,
3217 0,
3218 );
3219 emit_inst(fs, line, inst);
3220 } else {
3221 key.k = ExprKind::K;
3222 key.u.info = k_idx;
3223 cg_exp_to_any_reg(fs, line, key)?;
3224 let move_inst = lua_code::opcodes::Instruction::abck(
3225 lua_code::opcodes::OpCode::Move,
3226 (base + 1) as u32,
3227 ereg as u32,
3228 0,
3229 0,
3230 );
3231 emit_inst(fs, line, move_inst);
3232 let get_inst = lua_code::opcodes::Instruction::abck(
3233 lua_code::opcodes::OpCode::GetTable,
3234 base as u32,
3235 ereg as u32,
3236 key.u.info as u32,
3237 0,
3238 );
3239 emit_inst(fs, line, get_inst);
3240 }
3241 cg_free_exp(fs, key);
3242 Ok(())
3243}
3244
3245fn cg_exp_to_any_reg_up(fs: &mut FuncState, line: i32, e: &mut ExprDesc) -> Result<(), LuaError> {
3248 if matches!(e.k, ExprKind::UpVal | ExprKind::K | ExprKind::VarArgVar) {
3249 return Ok(());
3250 }
3251 cg_exp_to_any_reg(fs, line, e)?;
3252 Ok(())
3253}
3254
3255fn cg_emit_nil(fs: &mut FuncState, line: i32, from: i32, n: i32) {
3259 let inst = lua_code::opcodes::Instruction::abck(
3260 lua_code::opcodes::OpCode::LoadNil,
3261 from as u32,
3262 (n - 1) as u32,
3263 0,
3264 0,
3265 );
3266 emit_inst(fs, line, inst);
3267}
3268
3269fn current_scope_level(ls: &LexState) -> u8 {
3272 let (local_count, first_barrier) = ls.fs.as_ref().map_or((0usize, 0usize), |fs| {
3273 (fs.nactvar as usize, fs.first_scope_barrier)
3274 });
3275 let barrier_count = ls.scope_barriers.len().saturating_sub(first_barrier);
3276 let level = local_count + barrier_count;
3277 level.min(u8::MAX as usize) as u8
3278}
3279
3280fn local_level_for_scope_level(ls: &LexState, scope_level: u8) -> i32 {
3281 let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3282 let barriers_before = ls.scope_barriers[first_barrier..]
3283 .iter()
3284 .filter(|b| b.level < scope_level)
3285 .count();
3286 let locals = scope_level as i32 - barriers_before as i32;
3287 let max_locals = ls.fs.as_ref().map_or(0i32, |fs| fs.nactvar as i32);
3288 locals.clamp(0, max_locals)
3289}
3290
3291fn scope_level_for_local_level(ls: &LexState, local_level: u8) -> u8 {
3292 let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3293 let target = local_level as usize;
3294 let mut locals_seen = 0usize;
3295 for level in 0..=current_scope_level(ls) {
3296 if ls.scope_barriers[first_barrier..]
3297 .iter()
3298 .any(|b| b.level == level)
3299 {
3300 continue;
3301 }
3302 if locals_seen == target {
3303 return level;
3304 }
3305 locals_seen += 1;
3306 }
3307 local_level
3308}
3309
3310fn add_scope_barrier(ls: &mut LexState, name: GcRef<LuaString>) {
3311 let level = current_scope_level(ls);
3312 ls.scope_barriers.push(ScopeBarrier { level, name });
3313}
3314
3315fn latest_matching_global_barrier_current(ls: &LexState, name: &GcRef<LuaString>) -> Option<u8> {
3316 let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3317 ls.scope_barriers[first_barrier..]
3318 .iter()
3319 .rev()
3320 .find(|b| GcRef::ptr_eq(&b.name, name))
3321 .map(|b| b.level)
3322}
3323
3324fn has_active_global_barrier(ls: &LexState, name: &GcRef<LuaString>) -> bool {
3325 ls.scope_barriers
3326 .iter()
3327 .rev()
3328 .any(|b| GcRef::ptr_eq(&b.name, name))
3329}
3330
3331fn is_active_global_function_name(ls: &LexState, name: &GcRef<LuaString>) -> bool {
3332 ls.global_function_names
3333 .iter()
3334 .rev()
3335 .any(|n| GcRef::ptr_eq(n, name))
3336}
3337
3338fn scope_name_at(ls: &LexState, level: u8, label_nactvar: u8) -> Vec<u8> {
3339 let first_barrier = ls.fs.as_ref().map_or(0usize, |fs| fs.first_scope_barrier);
3340 for scope_level in level..label_nactvar {
3341 if let Some(barrier) = ls.scope_barriers[first_barrier..]
3342 .iter()
3343 .find(|b| b.level == scope_level)
3344 {
3345 return barrier.name.as_bytes().to_vec();
3346 }
3347
3348 let barriers_before = ls.scope_barriers[first_barrier..]
3349 .iter()
3350 .filter(|b| b.level < scope_level)
3351 .count();
3352 let vidx = scope_level as i32 - barriers_before as i32;
3353 if vidx < 0 {
3354 continue;
3355 }
3356 if let Some(name) = ls.fs.as_ref().and_then(|fs| {
3357 if (fs.firstlocal + vidx) >= 0
3358 && ((fs.firstlocal + vidx) as usize) < ls.dyd.actvar.len()
3359 {
3360 let vd = get_local_var_desc(ls, fs, vidx);
3361 vd.name.as_ref().map(|n| n.as_bytes().to_vec())
3362 } else {
3363 None
3364 }
3365 }) {
3366 return name;
3367 }
3368 }
3369
3370 b"*".to_vec()
3371}
3372
3373fn jumpscopeerror(
3374 ls: &LexState,
3375 version: lua_types::LuaVersion,
3376 gt_idx: usize,
3377 label_nactvar: u8,
3378) -> LuaError {
3379 let gt = &ls.dyd.gt[gt_idx];
3380 let line = gt.line;
3381 let gt_name_bytes: &[u8] = gt.name.as_ref().map(|n| n.as_bytes()).unwrap_or(b"");
3382 let gt_name = String::from_utf8_lossy(gt_name_bytes);
3383 let varname_bytes = scope_name_at(ls, gt.nactvar, label_nactvar);
3384 let varname = String::from_utf8_lossy(&varname_bytes);
3385 if version == lua_types::LuaVersion::V55 {
3386 LuaError::syntax(format_args!(
3387 "<goto {}> at line {} jumps into the scope of '{}'",
3388 gt_name, line, varname
3389 ))
3390 } else {
3391 LuaError::syntax(format_args!(
3392 "<goto {}> at line {} jumps into the scope of local '{}'",
3393 gt_name, line, varname
3394 ))
3395 }
3396}
3397
3398fn solvegoto(
3400 ls: &mut LexState,
3401 state: &mut LuaState,
3402 g: usize,
3403 label_pc: i32,
3404 label_nactvar: u8,
3405) -> Result<(), LuaError> {
3406 if ls.dyd.gt[g].nactvar < label_nactvar {
3407 let version = state.global().lua_version;
3408 return Err(jumpscopeerror(ls, version, g, label_nactvar));
3409 }
3410 let gt_pc = ls.dyd.gt[g].pc;
3411 cg_patch_list(ls.fs.as_mut().unwrap(), gt_pc, label_pc)?;
3412 ls.dyd.gt.remove(g);
3413 Ok(())
3414}
3415
3416fn findlabel_from(ls: &LexState, name: &GcRef<LuaString>, first: usize) -> Option<usize> {
3426 for i in first..ls.dyd.label.len() {
3427 let lb = &ls.dyd.label[i];
3428 if lb.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
3429 return Some(i);
3430 }
3431 }
3432 None
3433}
3434
3435fn findlabel_for_goto(ls: &LexState, state: &LuaState, name: &GcRef<LuaString>) -> Option<usize> {
3439 let block_scoped = matches!(
3440 state.global().lua_version,
3441 lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
3442 );
3443 let first = if block_scoped {
3444 ls.fs
3445 .as_ref()
3446 .unwrap()
3447 .bl
3448 .as_ref()
3449 .map_or(0, |b| b.firstlabel) as usize
3450 } else {
3451 ls.fs.as_ref().unwrap().firstlabel as usize
3452 };
3453 findlabel_from(ls, name, first)
3454}
3455
3456fn new_label_entry(
3458 ls: &mut LexState,
3459 _state: &mut LuaState,
3460 is_goto: bool,
3461 name: GcRef<LuaString>,
3462 line: i32,
3463 pc: i32,
3464) -> Result<usize, LuaError> {
3465 let nactvar = current_scope_level(ls);
3466 let entry = LabelDesc {
3467 name: Some(name),
3468 pc,
3469 line,
3470 nactvar,
3471 close: false,
3472 };
3473 let list = if is_goto {
3474 &mut ls.dyd.gt
3475 } else {
3476 &mut ls.dyd.label
3477 };
3478 let n = list.len();
3479 list.push(entry);
3480 Ok(n)
3481}
3482
3483fn new_goto_entry(
3484 ls: &mut LexState,
3485 state: &mut LuaState,
3486 name: GcRef<LuaString>,
3487 line: i32,
3488 pc: i32,
3489) -> Result<usize, LuaError> {
3490 new_label_entry(ls, state, true, name, line, pc)
3491}
3492
3493fn solvegotos(ls: &mut LexState, state: &mut LuaState, lb_idx: usize) -> Result<bool, LuaError> {
3496 let lb_name = ls.dyd.label[lb_idx].name.clone();
3497 let lb_pc = ls.dyd.label[lb_idx].pc;
3498 let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
3499 let first_goto = ls
3500 .fs
3501 .as_ref()
3502 .unwrap()
3503 .bl
3504 .as_ref()
3505 .map_or(0, |b| b.firstgoto) as usize;
3506
3507 let mut i = first_goto;
3508 let mut needs_close = false;
3509 while i < ls.dyd.gt.len() {
3510 let gt_name = ls.dyd.gt[i].name.clone();
3511 let names_match = lb_name
3512 .as_ref()
3513 .and_then(|ln| gt_name.as_ref().map(|gn| GcRef::ptr_eq(ln, gn)))
3514 .unwrap_or(false);
3515 if names_match {
3516 needs_close |= ls.dyd.gt[i].close;
3517 solvegoto(ls, state, i, lb_pc, lb_nactvar)?;
3519 } else {
3520 i += 1;
3521 }
3522 }
3523 Ok(needs_close)
3524}
3525
3526fn createlabel(
3528 ls: &mut LexState,
3529 state: &mut LuaState,
3530 name: GcRef<LuaString>,
3531 line: i32,
3532 last: bool,
3533) -> Result<bool, LuaError> {
3534 let label_pc = cg_get_label(ls.fs.as_mut().unwrap());
3535 let l = new_label_entry(ls, state, false, name, line, label_pc)?;
3536 if last {
3537 let bl_scope_level = ls
3538 .fs
3539 .as_ref()
3540 .unwrap()
3541 .bl
3542 .as_ref()
3543 .map_or(0, |b| b.scope_level);
3544 ls.dyd.label[l].nactvar = bl_scope_level;
3545 }
3546 let needs_close = solvegotos(ls, state, l)?;
3547 if needs_close {
3548 let nstack = nvarstack(ls, ls.fs.as_ref().unwrap()) as u32;
3549 let inst =
3550 lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::Close, nstack, 0, 0, 0);
3551 emit_inst(ls.fs.as_mut().unwrap(), line, inst);
3552 return Ok(true);
3553 }
3554 Ok(false)
3555}
3556
3557fn movegotosout(
3568 ls: &mut LexState,
3569 state: &mut LuaState,
3570 bl_firstgoto: usize,
3571 bl_scope_level: u8,
3572 bl_upval: bool,
3573) -> Result<(), LuaError> {
3574 let reresolve = matches!(
3575 state.global().lua_version,
3576 lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
3577 );
3578 let mut i = bl_firstgoto;
3579 while i < ls.dyd.gt.len() {
3580 if reresolve {
3581 if ls.dyd.gt[i].nactvar > bl_scope_level {
3582 if bl_upval {
3583 ls.dyd.gt[i].close = true;
3584 }
3585 ls.dyd.gt[i].nactvar = bl_scope_level;
3586 }
3587 } else {
3588 if bl_upval {
3589 ls.dyd.gt[i].close = true;
3590 }
3591 ls.dyd.gt[i].nactvar = bl_scope_level;
3592 }
3593 if reresolve {
3594 let gt_name = ls.dyd.gt[i].name.clone();
3595 let lb_idx = gt_name
3596 .as_ref()
3597 .and_then(|n| findlabel_for_goto(ls, state, n));
3598 if let Some(lb_idx) = lb_idx {
3599 let lb_pc = ls.dyd.label[lb_idx].pc;
3600 let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
3601 solvegoto(ls, state, i, lb_pc, lb_nactvar)?;
3602 continue;
3603 }
3604 }
3605 i += 1;
3606 }
3607 Ok(())
3608}
3609
3610fn enter_block(ls: &mut LexState, isloop: bool) {
3612 let firstlabel = ls.dyd.label.len() as i32;
3613 let firstgoto = ls.dyd.gt.len() as i32;
3614 let saved_global_strict = ls.global_strict;
3615 let saved_declared_globals = ls.declared_globals.len();
3616 let saved_global_wildcard = ls.global_wildcard;
3617 let saved_global_wildcard_const = ls.global_wildcard_const;
3618 let saved_scope_barriers = ls.scope_barriers.len();
3619 let scope_level = current_scope_level(ls);
3620 let insidetbc = ls
3621 .fs
3622 .as_ref()
3623 .and_then(|f| f.bl.as_ref())
3624 .map_or(false, |b| b.insidetbc);
3625 let fs = ls.fs.as_mut().unwrap();
3626 let nactvar = fs.nactvar;
3627 let new_bl = Box::new(BlockCnt {
3628 previous: fs.bl.take(),
3629 firstlabel,
3630 firstgoto,
3631 nactvar,
3632 scope_level,
3633 upval: false,
3634 isloop,
3635 insidetbc,
3636 saved_global_strict,
3637 saved_declared_globals,
3638 saved_global_wildcard,
3639 saved_global_wildcard_const,
3640 saved_scope_barriers,
3641 });
3642 fs.bl = Some(new_bl);
3643 debug_assert!(
3644 fs.freereg as i32 == {
3645 fs.freereg as i32 }
3648 );
3649}
3650
3651fn undef_goto(ls: &mut LexState, version: lua_types::LuaVersion, gt_idx: usize) -> LuaError {
3652 let (line, name_bytes): (i32, Vec<u8>) = {
3653 let gt = &ls.dyd.gt[gt_idx];
3654 (
3655 gt.line,
3656 gt.name
3657 .as_ref()
3658 .map(|n| n.as_bytes().to_vec())
3659 .unwrap_or_default(),
3660 )
3661 };
3662 let msg = if name_bytes == b"break" {
3663 if matches!(
3666 version,
3667 lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
3668 ) {
3669 format!("<break> at line {} not inside a loop", line)
3670 } else {
3671 format!("break outside loop at line {}", line)
3672 }
3673 } else {
3674 let name_str = String::from_utf8_lossy(&name_bytes);
3675 format!(
3676 "no visible label '{}' for <goto> at line {}",
3677 name_str, line
3678 )
3679 };
3680 lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0)
3681}
3682
3683fn leave_block(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
3685 let (bl_nactvar, bl_scope_level, bl_isloop, bl_upval, bl_firstgoto, bl_firstlabel) = {
3689 let bl = ls
3690 .fs
3691 .as_ref()
3692 .unwrap()
3693 .bl
3694 .as_ref()
3695 .expect("leave_block: no current block");
3696 (
3697 bl.nactvar,
3698 bl.scope_level,
3699 bl.isloop,
3700 bl.upval,
3701 bl.firstgoto,
3702 bl.firstlabel,
3703 )
3704 };
3705
3706 {
3710 let (sgs, sdg, sgw, sgwc, ssb) = {
3711 let bl = ls.fs.as_ref().unwrap().bl.as_ref().unwrap();
3712 (
3713 bl.saved_global_strict,
3714 bl.saved_declared_globals,
3715 bl.saved_global_wildcard,
3716 bl.saved_global_wildcard_const,
3717 bl.saved_scope_barriers,
3718 )
3719 };
3720 ls.global_strict = sgs;
3721 ls.declared_globals.truncate(sdg);
3722 ls.global_wildcard = sgw;
3723 ls.global_wildcard_const = sgwc;
3724 ls.scope_barriers.truncate(ssb);
3725 }
3726
3727 let stklevel = reg_level(ls, ls.fs.as_ref().unwrap(), bl_nactvar as i32);
3728 let mut fs_box = ls.fs.take().unwrap();
3729 remove_vars(ls, &mut fs_box, bl_nactvar as i32);
3730 debug_assert!(bl_nactvar == fs_box.nactvar);
3731 ls.fs = Some(fs_box);
3732
3733 let hasclose = if bl_isloop {
3734 let break_str = state.intern_str(b"break")?;
3735 createlabel(ls, state, break_str, 0, false)?
3736 } else {
3737 false
3738 };
3739
3740 let mut bl_box = ls.fs.as_mut().unwrap().bl.take().unwrap();
3742 let previous = bl_box.previous.take();
3743 ls.fs.as_mut().unwrap().bl = previous;
3744
3745 let has_prev_block = ls.fs.as_ref().unwrap().bl.is_some();
3746 if !hasclose && has_prev_block && bl_upval {
3747 let line = ls.lastline;
3751 let inst = lua_code::opcodes::Instruction::abck(
3752 lua_code::opcodes::OpCode::Close,
3753 stklevel as u32,
3754 0,
3755 0,
3756 0,
3757 );
3758 emit_inst(ls.fs.as_mut().unwrap(), line, inst);
3759 }
3760 ls.fs.as_mut().unwrap().freereg = stklevel as u8;
3761
3762 ls.dyd.label.truncate(bl_firstlabel as usize);
3763
3764 if has_prev_block {
3765 movegotosout(ls, state, bl_firstgoto as usize, bl_scope_level, bl_upval)?;
3766 } else {
3767 if (bl_firstgoto as usize) < ls.dyd.gt.len() {
3768 let version = state.global().lua_version;
3769 return Err(undef_goto(ls, version, bl_firstgoto as usize));
3770 }
3771 }
3772 Ok(())
3773}
3774
3775fn add_prototype(ls: &mut LexState, _state: &mut LuaState) -> Result<Box<LuaProto>, LuaError> {
3780 let np = ls.fs.as_ref().unwrap().np as usize;
3781 let new_proto = Box::new(LuaProto::placeholder());
3783 while ls.fs.as_ref().unwrap().f.p.len() <= np {
3784 ls.fs
3785 .as_mut()
3786 .unwrap()
3787 .f
3788 .p
3789 .push(GcRef::new(LuaProto::placeholder()));
3790 }
3791 ls.fs.as_mut().unwrap().np += 1;
3792 Ok(new_proto)
3793}
3794
3795fn codeclosure(ls: &mut LexState, _state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
3797 let line = ls.lastline;
3798 let mut child = ls.fs.take().expect("codeclosure: no current FuncState");
3799 let result = (|| -> Result<(), LuaError> {
3800 let parent = child
3801 .prev
3802 .as_mut()
3803 .expect("codeclosure: child FuncState has no parent (called outside body()?)");
3804 let bx = (parent.np - 1) as u32;
3805 let inst = lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::Closure, 0, bx);
3806 let pc = emit_inst(parent, line, inst);
3807 init_exp(v, ExprKind::Reloc, pc);
3808 cg_exp_to_next_reg(parent, line, v)
3809 })();
3810 ls.fs = Some(child);
3811 result
3812}
3813
3814fn open_func(
3816 ls: &mut LexState,
3817 _state: &mut LuaState,
3818 mut new_fs: FuncState,
3819) -> Result<(), LuaError> {
3820 new_fs.prev = ls.fs.take();
3821
3822 let f = &mut new_fs.f;
3823 new_fs.pc = 0;
3824 new_fs.previousline = f.linedefined;
3825 new_fs.iwthabs = 0;
3826 new_fs.lasttarget = 0;
3827 new_fs.freereg = 0;
3828 new_fs.nk = 0;
3829 new_fs.nabslineinfo = 0;
3830 new_fs.np = 0;
3831 new_fs.nups = 0;
3832 new_fs.ndebugvars = 0;
3833 new_fs.nactvar = 0;
3834 new_fs.needclose = false;
3835
3836 new_fs.firstlocal = ls.dyd.actvar.len() as i32;
3837 new_fs.firstlabel = ls.dyd.label.len() as i32;
3838 new_fs.bl = None;
3839
3840 new_fs.f.source = ls.source.clone();
3841 new_fs.f.maxstacksize = 2;
3842
3843 ls.fs = Some(Box::new(new_fs));
3844
3845 enter_block(ls, false);
3846 Ok(())
3847}
3848
3849fn close_func(ls: &mut LexState, state: &mut LuaState) -> Result<Box<LuaProto>, LuaError> {
3852 {
3853 let first = {
3854 let fs = ls.fs.as_ref().unwrap();
3855 nvarstack(ls, fs)
3856 };
3857 let line = ls.lastline;
3858 let fs = ls.fs.as_mut().unwrap();
3859 let inst = lua_code::opcodes::Instruction::abck(
3860 lua_code::opcodes::OpCode::Return0,
3861 first as u32,
3862 1,
3863 0,
3864 0,
3865 );
3866 emit_inst(fs, line, inst);
3867 }
3868 leave_block(ls, state)?;
3869 debug_assert!(ls.fs.as_ref().unwrap().bl.is_none());
3870
3871 cg_finish(ls.fs.as_mut().unwrap());
3873
3874 {
3875 let fs = ls.fs.as_mut().unwrap();
3876 let pc = fs.pc as usize;
3877 let nabslineinfo = fs.nabslineinfo as usize;
3878 let nk = fs.nk as usize;
3879 let np = fs.np as usize;
3880 let ndebugvars = fs.ndebugvars as usize;
3881 let nups = fs.nups as usize;
3882 fs.f.code.truncate(pc);
3883 fs.f.lineinfo.truncate(pc);
3884 fs.f.abslineinfo.truncate(nabslineinfo);
3885 fs.f.k.truncate(nk);
3886 fs.f.p.truncate(np);
3887 fs.f.locvars.truncate(ndebugvars);
3888 fs.f.upvalues.truncate(nups);
3889 }
3890
3891 let mut fs_box = ls.fs.take().unwrap();
3892 ls.fs = fs_box.prev.take();
3893
3894 Ok(fs_box.f)
3895}
3896
3897fn block_follow(ls: &LexState, withuntil: bool) -> bool {
3901 match ls.t.token {
3902 TK_ELSE | TK_ELSEIF | TK_END | TK_EOS => true,
3903 TK_UNTIL => withuntil,
3904 _ => false,
3905 }
3906}
3907
3908fn statlist(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
3909 while !block_follow(ls, true) {
3910 if ls.t.token == TK_RETURN {
3911 statement(ls, state)?;
3912 return Ok(());
3913 }
3914 statement(ls, state)?;
3915 }
3916 Ok(())
3917}
3918
3919fn fieldsel(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
3921 let line = ls.lastline;
3922 cg_exp_to_any_reg_up(ls.fs.as_mut().unwrap(), line, v)?;
3923 lex_next(ls, state)?; let mut key = ExprDesc::default();
3925 codename(ls, state, &mut key)?;
3926 cg_indexed(ls.fs.as_mut().unwrap(), line, v, &mut key)?;
3927 Ok(())
3928}
3929
3930fn exp_to_val(
3946 fs: &mut FuncState,
3947 line: i32,
3948 e: &mut ExprDesc,
3949 materialize_jmp: bool,
3950) -> Result<(), LuaError> {
3951 if (materialize_jmp && e.k == ExprKind::Jmp) || e.t != e.f {
3952 cg_exp_to_any_reg(fs, line, e)?;
3953 } else {
3954 cg_discharge_vars(fs, line, e)?;
3955 }
3956 Ok(())
3957}
3958
3959fn yindex(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
3960 lex_next(ls, state)?;
3961 expr(ls, state, v)?;
3962 let line = ls.linenumber;
3963 let materialize_jmp = state.global().lua_version != lua_types::LuaVersion::V54;
3964 exp_to_val(ls.fs.as_mut().unwrap(), line, v, materialize_jmp)?;
3965 check_next(ls, state, b']' as TokenKind)?;
3966 Ok(())
3967}
3968
3969fn recfield(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
3972 let reg = ls.fs.as_ref().unwrap().freereg as i32;
3973 let mut key = ExprDesc::default();
3974 let mut val = ExprDesc::default();
3975 if ls.t.token == TK_NAME {
3976 let fs = ls.fs.as_ref().unwrap();
3977 check_limit(fs, cc.nh, i32::MAX, "items in a constructor")?;
3978 codename(ls, state, &mut key)?;
3979 } else {
3980 yindex(ls, state, &mut key)?;
3981 }
3982 cc.nh += 1;
3983 check_next(ls, state, b'=' as TokenKind)?;
3984 let mut tab = cc.t.clone();
3985 let line = ls.lastline;
3986 cg_indexed(ls.fs.as_mut().unwrap(), line, &mut tab, &mut key)?;
3987 expr(ls, state, &mut val)?;
3988 cg_storevar(ls.fs.as_mut().unwrap(), line, &tab, &mut val)?;
3989 ls.fs.as_mut().unwrap().freereg = reg as u8;
3990 Ok(())
3991}
3992
3993fn closelistfield(
3994 ls: &mut LexState,
3995 state: &mut LuaState,
3996 cc: &mut ConsControl,
3997) -> Result<(), LuaError> {
3998 let _ = state;
3999 if cc.v.k == ExprKind::Void {
4000 return Ok(());
4001 }
4002 let line = ls.lastline;
4003 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut cc.v)?;
4004 cc.v.k = ExprKind::Void;
4005 if cc.tostore == LFIELDS_PER_FLUSH {
4006 let t_info = cc.t.u.info;
4007 cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, cc.tostore);
4008 cc.na += cc.tostore;
4009 cc.tostore = 0;
4010 }
4011 Ok(())
4012}
4013
4014fn lastlistfield(
4015 ls: &mut LexState,
4016 state: &mut LuaState,
4017 cc: &mut ConsControl,
4018) -> Result<(), LuaError> {
4019 let _ = state;
4020 if cc.tostore == 0 {
4021 return Ok(());
4022 }
4023 let t_info = cc.t.u.info;
4024 let line = ls.lastline;
4025 if cc.v.k.has_mult_ret() {
4026 cg_set_returns(ls.fs.as_mut().unwrap(), &mut cc.v, LUA_MULTRET);
4027 cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, LUA_MULTRET);
4028 cc.na -= 1;
4029 } else {
4030 if cc.v.k != ExprKind::Void {
4031 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut cc.v)?;
4032 }
4033 cg_setlist(ls.fs.as_mut().unwrap(), line, t_info, cc.na, cc.tostore);
4034 }
4035 cc.na += cc.tostore;
4036 Ok(())
4037}
4038
4039fn listfield(
4040 ls: &mut LexState,
4041 state: &mut LuaState,
4042 cc: &mut ConsControl,
4043) -> Result<(), LuaError> {
4044 expr(ls, state, &mut cc.v)?;
4045 cc.tostore += 1;
4046 Ok(())
4047}
4048
4049fn field(ls: &mut LexState, state: &mut LuaState, cc: &mut ConsControl) -> Result<(), LuaError> {
4050 match ls.t.token {
4051 TK_NAME => {
4052 let next_is_eq = lex_lookahead(ls, state)? == b'=' as TokenKind;
4053 if !next_is_eq {
4054 listfield(ls, state, cc)?;
4055 } else {
4056 recfield(ls, state, cc)?;
4057 }
4058 }
4059 c if c == b'[' as TokenKind => {
4060 recfield(ls, state, cc)?;
4061 }
4062 _ => {
4063 listfield(ls, state, cc)?;
4064 }
4065 }
4066 Ok(())
4067}
4068
4069fn constructor(ls: &mut LexState, state: &mut LuaState, t: &mut ExprDesc) -> Result<(), LuaError> {
4070 let line = ls.lastline;
4071 let pc = cg_emit_newtable(ls.fs.as_mut().unwrap(), line);
4072
4073 let freereg = ls.fs.as_ref().unwrap().freereg as i32;
4074 init_exp(t, ExprKind::NonReloc, freereg);
4075 reserve_regs(ls.fs.as_mut().unwrap(), 1)?;
4076
4077 let mut cc = ConsControl {
4078 v: ExprDesc::default(),
4079 t: t.clone(),
4080 nh: 0,
4081 na: 0,
4082 tostore: 0,
4083 };
4084
4085 check_next(ls, state, b'{' as TokenKind)?;
4086 loop {
4087 debug_assert!(cc.v.k == ExprKind::Void || cc.tostore > 0);
4088 if ls.t.token == b'}' as TokenKind {
4089 break;
4090 }
4091 closelistfield(ls, state, &mut cc)?;
4092 field(ls, state, &mut cc)?;
4093 if !test_next(ls, state, b',' as TokenKind)? && !test_next(ls, state, b';' as TokenKind)? {
4094 break;
4095 }
4096 }
4097 check_match(ls, state, b'}' as TokenKind, b'{' as TokenKind, line)?;
4098 lastlistfield(ls, state, &mut cc)?;
4099
4100 let t_info = t.u.info;
4101 cg_settablesize(ls.fs.as_mut().unwrap(), pc, t_info, cc.na, cc.nh);
4102 Ok(())
4103}
4104
4105fn setvararg(fs: &mut FuncState, _state: &mut LuaState, nparams: i32) -> Result<(), LuaError> {
4108 fs.f.is_vararg = true;
4109 let inst = lua_code::opcodes::Instruction::abck(
4110 lua_code::opcodes::OpCode::VarArgPrep,
4111 nparams as u32,
4112 0,
4113 0,
4114 0,
4115 );
4116 let line = fs.previousline;
4117 emit_inst(fs, line, inst);
4118 Ok(())
4119}
4120
4121fn parlist(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4122 let mut nparams: i32 = 0;
4123 let mut isvararg = false;
4124 let is_v55 = state.global().lua_version == lua_types::LuaVersion::V55;
4130 let mut has_vararg_local = false;
4131 let mut has_vararg_name = false;
4132 let mut vararg_name_vidx: Option<i32> = None;
4133 if ls.t.token != b')' as TokenKind {
4134 loop {
4135 match ls.t.token {
4136 TK_NAME => {
4137 let name = str_check_name(ls, state)?;
4138 new_local_var(ls, state, name)?;
4139 nparams += 1;
4140 }
4141 TK_DOTS => {
4142 lex_next(ls, state)?;
4143 isvararg = true;
4144 if is_v55 && ls.t.token == TK_NAME {
4150 let name = str_check_name(ls, state)?;
4151 vararg_name_vidx = Some(new_local_var(ls, state, name)?);
4152 has_vararg_local = true;
4153 has_vararg_name = true;
4154 } else if is_v55 {
4155 let name = state.intern_str(b"(vararg table)")?;
4156 new_local_var(ls, state, name)?;
4157 has_vararg_local = true;
4158 }
4159 }
4160 _ => {
4161 return Err(LuaError::syntax(format_args!("<name> or '...' expected")));
4162 }
4163 }
4164 if isvararg || !test_next(ls, state, b',' as TokenKind)? {
4165 break;
4166 }
4167 }
4168 }
4169 adjust_local_vars(ls, state, nparams)?;
4170 let numparams = ls.fs.as_ref().unwrap().nactvar;
4171 ls.fs.as_mut().unwrap().f.numparams = numparams;
4172 if isvararg {
4173 setvararg(ls.fs.as_mut().unwrap(), state, numparams as i32)?;
4174 }
4175 if has_vararg_local {
4176 adjust_local_vars(ls, state, 1)?;
4177 if let Some(vidx) = vararg_name_vidx {
4178 let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
4179 get_local_var_desc_mut(ls, firstlocal, vidx).kind = VarKind::VarArg;
4180 }
4181 }
4182 let nactvar = ls.fs.as_ref().unwrap().nactvar as i32;
4185 reserve_regs(ls.fs.as_mut().unwrap(), nactvar)?;
4186 if has_vararg_name {
4190 let reg = nvarstack(ls, ls.fs.as_ref().unwrap()) - 1;
4191 let inst = lua_code::opcodes::Instruction::abck(
4192 lua_code::opcodes::OpCode::VarArgPack,
4193 reg as u32,
4194 0,
4195 0,
4196 0,
4197 );
4198 let line = ls.fs.as_ref().unwrap().previousline;
4199 emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4200 ls.fs.as_mut().unwrap().f.vararg_table_reg = Some(reg as u8);
4203 }
4204 Ok(())
4205}
4206
4207fn check_match(
4208 ls: &mut LexState,
4209 state: &mut LuaState,
4210 what: TokenKind,
4211 who: TokenKind,
4212 where_line: i32,
4213) -> Result<(), LuaError> {
4214 if !test_next(ls, state, what)? {
4215 if where_line == ls.linenumber {
4216 return Err(error_expected(ls, what));
4217 } else {
4218 let what_str = lua_lex::token2str(&ls.lex, what);
4219 let who_str = lua_lex::token2str(&ls.lex, who);
4220 let mut msg: Vec<u8> = Vec::new();
4221 msg.extend_from_slice(&what_str);
4222 msg.extend_from_slice(b" expected (to close ");
4223 msg.extend_from_slice(&who_str);
4224 use std::io::Write as _;
4225 let _ = write!(msg, " at line {})", where_line);
4226 return Err(lua_lex::syntax_error(&mut ls.lex, &msg));
4227 }
4228 }
4229 Ok(())
4230}
4231
4232fn body(
4233 ls: &mut LexState,
4234 state: &mut LuaState,
4235 e: &mut ExprDesc,
4236 ismethod: bool,
4237 line: i32,
4238) -> Result<(), LuaError> {
4239 let new_proto = add_prototype(ls, state)?;
4240 let mut new_fs = FuncState {
4241 f: new_proto,
4242 prev: None,
4243 bl: None,
4244 pc: 0,
4245 lasttarget: 0,
4246 previousline: line,
4247 nk: 0,
4248 np: 0,
4249 nabslineinfo: 0,
4250 firstlocal: 0,
4251 firstlabel: 0,
4252 ndebugvars: 0,
4253 nactvar: 0,
4254 first_scope_barrier: ls.scope_barriers.len(),
4255 nups: 0,
4256 freereg: 0,
4257 iwthabs: 0,
4258 needclose: false,
4259 last_token_line: ls.lastline,
4260 };
4261 new_fs.f.linedefined = line;
4262 open_func(ls, state, new_fs)?;
4263
4264 check_next(ls, state, b'(' as TokenKind)?;
4265 if ismethod {
4266 let self_str = state.intern_str(b"self")?;
4267 new_local_var(ls, state, self_str)?;
4268 adjust_local_vars(ls, state, 1)?;
4269 }
4270 parlist(ls, state)?;
4271 check_next(ls, state, b')' as TokenKind)?;
4272 statlist(ls, state)?;
4273 ls.fs.as_mut().unwrap().f.lastlinedefined = ls.linenumber;
4274 check_match(ls, state, TK_END, TK_FUNCTION, line)?;
4275 codeclosure(ls, state, e)?;
4276 let inner_proto = close_func(ls, state)?;
4277 let parent = ls
4278 .fs
4279 .as_mut()
4280 .expect("body: close_func left no parent FuncState");
4281 let slot = (parent.np - 1) as usize;
4282 if parent.f.p.len() <= slot {
4283 parent
4284 .f
4285 .p
4286 .resize_with(slot + 1, || GcRef::new(LuaProto::placeholder()));
4287 }
4288 let inner_ref = GcRef::new(*inner_proto);
4289 inner_ref.account_buffer(inner_ref.buffer_bytes() as isize);
4290 parent.f.p[slot] = inner_ref;
4291 Ok(())
4292}
4293
4294fn explist(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<i32, LuaError> {
4297 let mut n = 1;
4298 expr(ls, state, v)?;
4299 while test_next(ls, state, b',' as TokenKind)? {
4300 let line = ls.lastline;
4301 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, v)?;
4302 expr(ls, state, v)?;
4303 n += 1;
4304 }
4305 Ok(n)
4306}
4307
4308fn funcargs(ls: &mut LexState, state: &mut LuaState, f: &mut ExprDesc) -> Result<(), LuaError> {
4309 let mut args = ExprDesc::default();
4310 let line = ls.linenumber;
4313 match ls.t.token {
4314 c if c == b'(' as TokenKind => {
4315 lex_next(ls, state)?; if ls.t.token == b')' as TokenKind {
4317 args.k = ExprKind::Void;
4318 } else {
4319 explist(ls, state, &mut args)?;
4320 if args.k.has_mult_ret() {
4321 cg_set_returns(ls.fs.as_mut().unwrap(), &mut args, LUA_MULTRET);
4324 }
4325 }
4326 check_match(ls, state, b')' as TokenKind, b'(' as TokenKind, line)?;
4327 }
4328 c if c == b'{' as TokenKind => {
4329 constructor(ls, state, &mut args)?;
4330 }
4331 TK_STRING => {
4332 let s =
4333 ls.t.seminfo
4334 .ts
4335 .clone()
4336 .ok_or_else(|| LuaError::syntax(format_args!("string expected")))?;
4337 codestring(&mut args, s);
4338 lex_next(ls, state)?;
4339 }
4340 _ => {
4341 return Err(LuaError::syntax(format_args!(
4342 "function arguments expected"
4343 )));
4344 }
4345 }
4346 debug_assert!(f.k == ExprKind::NonReloc);
4347 let base = f.u.info;
4348 let nparams: i32 = if args.k.has_mult_ret() {
4349 LUA_MULTRET
4352 } else {
4353 if args.k != ExprKind::Void {
4354 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut args)?;
4355 }
4356 ls.fs.as_ref().unwrap().freereg as i32 - (base + 1)
4357 };
4358 let call_inst = lua_code::opcodes::Instruction::abck(
4359 lua_code::opcodes::OpCode::Call,
4360 base as u32,
4361 (nparams + 1) as u32,
4362 2,
4363 0,
4364 );
4365 let call_pc = emit_inst(ls.fs.as_mut().unwrap(), line, call_inst);
4366 init_exp(f, ExprKind::Call, call_pc);
4367 ls.fs.as_mut().unwrap().freereg = base as u8 + 1;
4368 Ok(())
4369}
4370
4371fn primaryexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4374 match ls.t.token {
4375 c if c == b'(' as TokenKind => {
4376 let line = ls.lastline;
4377 lex_next(ls, state)?;
4378 expr(ls, state, v)?;
4379 check_match(ls, state, b')' as TokenKind, b'(' as TokenKind, line)?;
4380 cg_discharge_vars(ls.fs.as_mut().unwrap(), line, v)?;
4381 }
4382 TK_NAME => {
4383 singlevar(ls, state, v)?;
4384 }
4385 _ => {
4386 return Err(lua_lex::syntax_error(&mut ls.lex, b"unexpected symbol"));
4387 }
4388 }
4389 Ok(())
4390}
4391
4392fn suffixedexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4393 primaryexp(ls, state, v)?;
4394 loop {
4395 match ls.t.token {
4396 c if c == b'.' as TokenKind => {
4397 fieldsel(ls, state, v)?;
4398 }
4399 c if c == b'[' as TokenKind => {
4400 let mut key = ExprDesc::default();
4401 let line = ls.lastline;
4402 cg_exp_to_any_reg_up(ls.fs.as_mut().unwrap(), line, v)?;
4403 yindex(ls, state, &mut key)?;
4404 cg_indexed(ls.fs.as_mut().unwrap(), line, v, &mut key)?;
4405 }
4406 c if c == b':' as TokenKind => {
4407 let mut key = ExprDesc::default();
4408 lex_next(ls, state)?;
4409 codename(ls, state, &mut key)?;
4410 let line = ls.lastline;
4411 let keep_self_opcode_for_register_key =
4412 state.global().lua_version != lua_types::LuaVersion::V55;
4413 cg_self(
4414 ls.fs.as_mut().unwrap(),
4415 line,
4416 v,
4417 &mut key,
4418 keep_self_opcode_for_register_key,
4419 )?;
4420 funcargs(ls, state, v)?;
4421 }
4422 c if c == b'(' as TokenKind || c == TK_STRING || c == b'{' as TokenKind => {
4423 let line = ls.lastline;
4424 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, v)?;
4425 funcargs(ls, state, v)?;
4426 }
4427 _ => return Ok(()),
4428 }
4429 }
4430}
4431
4432fn simpleexp(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4433 match ls.t.token {
4434 TK_FLT => {
4435 init_exp(v, ExprKind::KFlt, 0);
4436 v.u.nval = ls.t.seminfo.r;
4437 }
4438 TK_INT => {
4439 init_exp(v, ExprKind::KInt, 0);
4440 v.u.ival = ls.t.seminfo.i;
4441 }
4442 TK_STRING => {
4443 let s =
4444 ls.t.seminfo
4445 .ts
4446 .clone()
4447 .ok_or_else(|| LuaError::syntax(format_args!("string value missing")))?;
4448 codestring(v, s);
4449 }
4450 TK_NIL => {
4451 init_exp(v, ExprKind::Nil, 0);
4452 }
4453 TK_TRUE => {
4454 init_exp(v, ExprKind::True, 0);
4455 }
4456 TK_FALSE => {
4457 init_exp(v, ExprKind::False, 0);
4458 }
4459 TK_DOTS => {
4460 let is_vararg = ls.fs.as_ref().unwrap().f.is_vararg;
4461 if !is_vararg {
4462 return Err(LuaError::syntax(format_args!(
4463 "cannot use '...' outside a vararg function"
4464 )));
4465 }
4466 let line = ls.lastline;
4467 let inst =
4468 lua_code::opcodes::Instruction::abck(lua_code::opcodes::OpCode::VarArg, 0, 0, 1, 0);
4469 let pc = emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4470 init_exp(v, ExprKind::VarArg, pc);
4471 }
4472 c if c == b'{' as TokenKind => {
4473 constructor(ls, state, v)?;
4474 return Ok(());
4475 }
4476 TK_FUNCTION => {
4477 lex_next(ls, state)?;
4478 let line = ls.lastline;
4479 body(ls, state, v, false, line)?;
4480 return Ok(());
4481 }
4482 _ => {
4483 suffixedexp(ls, state, v)?;
4484 return Ok(());
4485 }
4486 }
4487 lex_next(ls, state)?;
4488 Ok(())
4489}
4490
4491fn getunopr(op: TokenKind) -> UnOpr {
4492 match op {
4493 TK_NOT => UnOpr::Not,
4494 c if c == b'-' as TokenKind => UnOpr::Minus,
4495 c if c == b'~' as TokenKind => UnOpr::BNot,
4496 c if c == b'#' as TokenKind => UnOpr::Len,
4497 _ => UnOpr::NoUnOpr,
4498 }
4499}
4500
4501fn getbinopr(op: TokenKind) -> BinOpr {
4502 match op {
4503 c if c == b'+' as TokenKind => BinOpr::Add,
4504 c if c == b'-' as TokenKind => BinOpr::Sub,
4505 c if c == b'*' as TokenKind => BinOpr::Mul,
4506 c if c == b'%' as TokenKind => BinOpr::Mod,
4507 c if c == b'^' as TokenKind => BinOpr::Pow,
4508 c if c == b'/' as TokenKind => BinOpr::Div,
4509 TK_IDIV => BinOpr::IDiv,
4510 c if c == b'&' as TokenKind => BinOpr::BAnd,
4511 c if c == b'|' as TokenKind => BinOpr::BOr,
4512 c if c == b'~' as TokenKind => BinOpr::BXor,
4513 TK_SHL => BinOpr::Shl,
4514 TK_SHR => BinOpr::Shr,
4515 TK_CONCAT => BinOpr::Concat,
4516 TK_NE => BinOpr::Ne,
4517 TK_EQ => BinOpr::Eq,
4518 c if c == b'<' as TokenKind => BinOpr::Lt,
4519 TK_LE => BinOpr::Le,
4520 c if c == b'>' as TokenKind => BinOpr::Gt,
4521 TK_GE => BinOpr::Ge,
4522 TK_AND => BinOpr::And,
4523 TK_OR => BinOpr::Or,
4524 _ => BinOpr::NoBinOpr,
4525 }
4526}
4527
4528fn parser_is_float_only(state: &LuaState) -> bool {
4531 matches!(
4532 state.global().lua_version,
4533 lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
4534 )
4535}
4536
4537fn getbinopr_versioned(op: TokenKind, state: &LuaState) -> BinOpr {
4544 let r = getbinopr(op);
4545 if parser_is_float_only(state) && matches!(r, BinOpr::BAnd | BinOpr::BOr | BinOpr::BXor) {
4546 return BinOpr::NoBinOpr;
4547 }
4548 r
4549}
4550
4551fn getunopr_versioned(op: TokenKind, state: &LuaState) -> UnOpr {
4554 let r = getunopr(op);
4555 if parser_is_float_only(state) && matches!(r, UnOpr::BNot) {
4556 return UnOpr::NoUnOpr;
4557 }
4558 r
4559}
4560
4561fn subexpr(
4564 ls: &mut LexState,
4565 state: &mut LuaState,
4566 v: &mut ExprDesc,
4567 limit: i32,
4568) -> Result<BinOpr, LuaError> {
4569 enter_level(ls)?;
4570
4571 let uop = getunopr_versioned(ls.t.token, state);
4572 if uop != UnOpr::NoUnOpr {
4573 let line = ls.linenumber;
4575 lex_next(ls, state)?; subexpr(ls, state, v, UNARY_PRIORITY)?;
4577 cg_prefix(ls.fs.as_mut().unwrap(), uop, v, line)?;
4578 } else {
4579 simpleexp(ls, state, v)?;
4580 }
4581
4582 let mut op = getbinopr_versioned(ls.t.token, state);
4583 while op != BinOpr::NoBinOpr && PRIORITY[op as usize].0 as i32 > limit {
4584 let mut v2 = ExprDesc::default();
4585 let line = ls.linenumber;
4588 lex_next(ls, state)?;
4589 cg_infix(ls.fs.as_mut().unwrap(), op, v, line)?;
4590 let nextop = subexpr(ls, state, &mut v2, PRIORITY[op as usize].1 as i32)?;
4591 cg_posfix_fold(ls.fs.as_mut().unwrap(), op, v, &mut v2, line)?;
4592 op = nextop;
4593 }
4594
4595 leave_level(ls);
4596 Ok(op)
4597}
4598
4599fn expr(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<(), LuaError> {
4600 subexpr(ls, state, v, 0)?;
4601 Ok(())
4602}
4603
4604fn block(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4607 enter_block(ls, false);
4608 statlist(ls, state)?;
4609 leave_block(ls, state)?;
4610 Ok(())
4611}
4612
4613fn check_conflict(
4621 ls: &mut LexState,
4622 _state: &mut LuaState,
4623 lh: &mut LhsAssign,
4624 v: &ExprDesc,
4625) -> Result<(), LuaError> {
4626 let extra = ls.fs.as_ref().unwrap().freereg as i32;
4627 let line = ls.lastline;
4628 let mut conflict = false;
4629
4630 conflict |= check_one_lhs_entry(&mut lh.v, v, extra);
4631 let mut prev = lh.prev.as_deref_mut();
4632 while let Some(node) = prev {
4633 conflict |= check_one_lhs_entry(&mut node.v, v, extra);
4634 prev = node.prev.as_deref_mut();
4635 }
4636
4637 if conflict {
4638 let fs = ls.fs.as_mut().unwrap();
4639 let inst = if v.k == ExprKind::Local {
4640 lua_code::opcodes::Instruction::abck(
4641 lua_code::opcodes::OpCode::Move,
4642 extra as u32,
4643 v.u.var_ridx as u32,
4644 0,
4645 0,
4646 )
4647 } else {
4648 lua_code::opcodes::Instruction::abck(
4649 lua_code::opcodes::OpCode::GetUpVal,
4650 extra as u32,
4651 v.u.info as u32,
4652 0,
4653 0,
4654 )
4655 };
4656 emit_inst(fs, line, inst);
4657 reserve_regs(fs, 1)?;
4658 }
4659 Ok(())
4660}
4661
4662fn check_one_lhs_entry(entry: &mut ExprDesc, v: &ExprDesc, extra: i32) -> bool {
4663 if !entry.k.is_indexed() {
4664 return false;
4665 }
4666 let mut found = false;
4667 if entry.k == ExprKind::IndexUp {
4668 if v.k == ExprKind::UpVal && entry.u.ind_t == v.u.info as u8 {
4669 found = true;
4670 entry.k = ExprKind::IndexStr;
4671 entry.u.ind_t = extra as u8;
4672 }
4673 } else {
4674 if v.k == ExprKind::Local && entry.u.ind_t == v.u.var_ridx {
4675 found = true;
4676 entry.u.ind_t = extra as u8;
4677 }
4678 if entry.k == ExprKind::Indexed
4679 && v.k == ExprKind::Local
4680 && entry.u.ind_idx == v.u.var_ridx as i16
4681 {
4682 found = true;
4683 entry.u.ind_idx = extra as i16;
4684 }
4685 }
4686 found
4687}
4688
4689fn restassign(
4690 ls: &mut LexState,
4691 state: &mut LuaState,
4692 lh: &mut LhsAssign,
4693 nvars: i32,
4694) -> Result<(), LuaError> {
4695 if !lh.v.k.is_var() {
4696 return Err(lua_lex::syntax_error(&mut ls.lex, b"syntax error"));
4697 }
4698 check_readonly(ls, state, &lh.v.clone())?;
4699
4700 if test_next(ls, state, b',' as TokenKind)? {
4701 let mut nv_assign = LhsAssign {
4702 prev: None, v: ExprDesc::default(),
4704 };
4705 suffixedexp(ls, state, &mut nv_assign.v)?;
4706 if !nv_assign.v.k.is_indexed() {
4707 check_conflict(ls, state, lh, &nv_assign.v.clone())?;
4708 }
4709 enter_level(ls)?;
4710 restassign(ls, state, &mut nv_assign, nvars + 1)?;
4711 leave_level(ls);
4712 } else {
4713 let mut e = ExprDesc::default();
4714 check_next(ls, state, b'=' as TokenKind)?;
4715 let nexps = explist(ls, state, &mut e)?;
4716 if nexps != nvars {
4717 adjust_assign(ls, state, nvars, nexps, &mut e)?;
4718 } else {
4719 let line = ls.lastline;
4720 let fs = ls.fs.as_mut().unwrap();
4721 cg_set_one_ret(fs, &mut e);
4722 cg_storevar(fs, line, &lh.v, &mut e)?;
4723 return Ok(());
4724 }
4725 }
4726 let line = ls.lastline;
4727 let fs = ls.fs.as_mut().unwrap();
4728 let freereg = fs.freereg as i32 - 1;
4729 let mut e = ExprDesc::default();
4730 init_exp(&mut e, ExprKind::NonReloc, freereg);
4731 cg_storevar(fs, line, &lh.v, &mut e)?;
4732 Ok(())
4733}
4734
4735fn cond(ls: &mut LexState, state: &mut LuaState) -> Result<i32, LuaError> {
4737 let mut v = ExprDesc::default();
4738 expr(ls, state, &mut v)?;
4739 if v.k == ExprKind::Nil {
4740 v.k = ExprKind::False;
4741 }
4742 let line = ls.lastline;
4743 cg_go_if_true(ls.fs.as_mut().unwrap(), line, &mut v)?;
4744 Ok(v.f)
4745}
4746
4747fn gotostat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4748 let line = ls.lastline;
4749 let name = str_check_name(ls, state)?;
4750 let lb = findlabel_for_goto(ls, state, &name);
4751 if lb.is_none() {
4752 let pc = cg_jump(ls.fs.as_mut().unwrap(), line);
4753 new_goto_entry(ls, state, name, line, pc)?;
4754 } else {
4755 let lb_idx = lb.unwrap();
4756 let lb_pc = ls.dyd.label[lb_idx].pc;
4757 let lb_nactvar = ls.dyd.label[lb_idx].nactvar;
4758 let lb_local_level = local_level_for_scope_level(ls, lb_nactvar);
4759 let lblevel = reg_level(ls, ls.fs.as_ref().unwrap(), lb_local_level);
4760 let cur_nvarstack = {
4761 let fs = ls.fs.as_ref().unwrap();
4762 nvarstack(ls, fs)
4763 };
4764 if cur_nvarstack > lblevel {
4765 let inst = lua_code::opcodes::Instruction::abck(
4766 lua_code::opcodes::OpCode::Close,
4767 lblevel as u32,
4768 0,
4769 0,
4770 0,
4771 );
4772 emit_inst(ls.fs.as_mut().unwrap(), line, inst);
4773 }
4774 let jpc = cg_jump(ls.fs.as_mut().unwrap(), line);
4775 cg_patch_list(ls.fs.as_mut().unwrap(), jpc, lb_pc)?;
4776 }
4777 Ok(())
4778}
4779
4780fn has_enclosing_loop(ls: &LexState) -> bool {
4783 let mut bl = ls.fs.as_ref().unwrap().bl.as_deref();
4784 while let Some(b) = bl {
4785 if b.isloop {
4786 return true;
4787 }
4788 bl = b.previous.as_deref();
4789 }
4790 false
4791}
4792
4793fn breakstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4794 let version = state.global().lua_version;
4795 let line = ls.lastline;
4796 if version == lua_types::LuaVersion::V55 && !has_enclosing_loop(ls) {
4804 return Err(lua_lex::syntax_error(&mut ls.lex, b"break outside loop"));
4805 }
4806 lex_next(ls, state)?;
4807 if version == lua_types::LuaVersion::V51 && !has_enclosing_loop(ls) {
4808 return Err(lua_lex::syntax_error(&mut ls.lex, b"no loop to break"));
4809 }
4810 let break_str = state.intern_str(b"break")?;
4811 let pc = cg_jump(ls.fs.as_mut().unwrap(), line);
4812 new_goto_entry(ls, state, break_str, line, pc)?;
4813 Ok(())
4814}
4815
4816fn checkrepeated(
4825 ls: &mut LexState,
4826 state: &LuaState,
4827 name: &GcRef<LuaString>,
4828) -> Result<(), LuaError> {
4829 let block_scoped = matches!(
4830 state.global().lua_version,
4831 lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
4832 );
4833 let first = if block_scoped {
4834 ls.fs
4835 .as_ref()
4836 .unwrap()
4837 .bl
4838 .as_ref()
4839 .map_or(0, |b| b.firstlabel) as usize
4840 } else {
4841 ls.fs.as_ref().unwrap().firstlabel as usize
4842 };
4843 let mut dup_line: Option<i32> = None;
4844 for i in first..ls.dyd.label.len() {
4845 let lb = &ls.dyd.label[i];
4846 if lb.name.as_ref().map_or(false, |n| GcRef::ptr_eq(n, name)) {
4847 dup_line = Some(lb.line);
4848 break;
4849 }
4850 }
4851 if let Some(line) = dup_line {
4852 let name_str = String::from_utf8_lossy(name.as_bytes());
4853 let msg = format!("label '{}' already defined on line {}", name_str, line);
4854 let saved_line = ls.lex.linenumber;
4855 ls.lex.linenumber = ls.lastline;
4856 let err = lua_lex::lex_error(&mut ls.lex, msg.as_bytes(), 0);
4857 ls.lex.linenumber = saved_line;
4858 return Err(err);
4859 }
4860 Ok(())
4861}
4862
4863fn labelstat(
4864 ls: &mut LexState,
4865 state: &mut LuaState,
4866 name: GcRef<LuaString>,
4867 line: i32,
4868) -> Result<(), LuaError> {
4869 check_next(ls, state, TK_DBCOLON)?;
4870 while ls.t.token == b';' as TokenKind || ls.t.token == TK_DBCOLON {
4871 statement(ls, state)?;
4872 }
4873 checkrepeated(ls, state, &name)?;
4874 let is_last = block_follow(ls, false);
4875 createlabel(ls, state, name, line, is_last)?;
4876 Ok(())
4877}
4878
4879fn whilestat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
4880 lex_next(ls, state)?;
4881 let whileinit = cg_get_label(ls.fs.as_mut().unwrap());
4882 let condexit = cond(ls, state)?;
4883 enter_block(ls, true);
4884 check_next(ls, state, TK_DO)?;
4885 block(ls, state)?;
4886 let back = cg_jump(ls.fs.as_mut().unwrap(), ls.lastline);
4891 cg_patch_list(ls.fs.as_mut().unwrap(), back, whileinit)?;
4892 check_match(ls, state, TK_END, TK_WHILE, line)?;
4893 leave_block(ls, state)?;
4894 cg_patch_to_here(ls.fs.as_mut().unwrap(), condexit)?;
4895 Ok(())
4896}
4897
4898fn repeatstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
4899 let repeat_init = cg_get_label(ls.fs.as_mut().unwrap());
4900 enter_block(ls, true);
4901 enter_block(ls, false);
4902 lex_next(ls, state)?;
4903 statlist(ls, state)?;
4904 check_match(ls, state, TK_UNTIL, TK_REPEAT, line)?;
4905 let condexit = cond(ls, state)?;
4906
4907 let bl2_upval = ls.fs.as_ref().unwrap().bl.as_ref().unwrap().upval;
4908 let bl2_nactvar = ls.fs.as_ref().unwrap().bl.as_ref().unwrap().nactvar as i32;
4909 leave_block(ls, state)?;
4910
4911 let mut condexit = condexit;
4912 if bl2_upval {
4913 let exit = cg_jump(ls.fs.as_mut().unwrap(), line);
4914 cg_patch_to_here(ls.fs.as_mut().unwrap(), condexit)?;
4915 let close_level = reg_level(ls, ls.fs.as_ref().unwrap(), bl2_nactvar) as u32;
4916 let close_inst = lua_code::opcodes::Instruction::abck(
4917 lua_code::opcodes::OpCode::Close,
4918 close_level,
4919 0,
4920 0,
4921 0,
4922 );
4923 emit_inst(ls.fs.as_mut().unwrap(), line, close_inst);
4924 condexit = cg_jump(ls.fs.as_mut().unwrap(), line);
4925 cg_patch_to_here(ls.fs.as_mut().unwrap(), exit)?;
4926 }
4927 cg_patch_list(ls.fs.as_mut().unwrap(), condexit, repeat_init)?;
4928 leave_block(ls, state)?;
4929 Ok(())
4930}
4931
4932fn exp1(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
4934 let mut e = ExprDesc::default();
4935 expr(ls, state, &mut e)?;
4936 let line = ls.lastline;
4937 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut e)?;
4938 debug_assert!(e.k == ExprKind::NonReloc);
4939 Ok(())
4940}
4941
4942fn fixforjump(fs: &mut FuncState, pc: i32, dest: i32, back: bool) -> Result<(), LuaError> {
4943 let mut offset = dest - (pc + 1);
4944 if back {
4945 offset = -offset;
4946 }
4947 if offset > MAXARG_BX {
4948 return Err(LuaError::syntax(format_args!("control structure too long")));
4949 }
4950 let raw = fs.f.code[pc as usize].0;
4951 let mut inst = lua_code::opcodes::Instruction(raw);
4952 inst.set_arg_bx(offset as u32);
4953 fs.f.code[pc as usize] = lua_types::opcode::Instruction::new(inst.0);
4954 Ok(())
4955}
4956
4957fn forbody(
4958 ls: &mut LexState,
4959 state: &mut LuaState,
4960 base: i32,
4961 line: i32,
4962 nvars: i32,
4963 isgen: bool,
4964) -> Result<(), LuaError> {
4965 check_next(ls, state, TK_DO)?;
4966 let prep_op = if isgen {
4967 OpCode::TForPrep
4968 } else {
4969 OpCode::ForPrep
4970 };
4971 let prep = {
4972 let fs = ls.fs.as_mut().unwrap();
4973 let inst = lua_code::opcodes::Instruction::abx(prep_op, base as u32, 0);
4974 emit_inst(fs, line, inst)
4975 };
4976 if isgen && state.global().lua_version == lua_types::LuaVersion::V55 {
4977 let fs = ls.fs.as_mut().unwrap();
4978 fs.freereg = fs.freereg.saturating_sub(1);
4979 }
4980
4981 enter_block(ls, false);
4982 adjust_local_vars(ls, state, nvars)?;
4983 reserve_regs(ls.fs.as_mut().unwrap(), nvars)?;
4984 block(ls, state)?;
4985 leave_block(ls, state)?;
4986
4987 let label_pc = ls.fs.as_ref().unwrap().pc;
4988 fixforjump(ls.fs.as_mut().unwrap(), prep, label_pc, false)?;
4989
4990 if isgen {
4991 let fs = ls.fs.as_mut().unwrap();
4992 let inst =
4993 lua_code::opcodes::Instruction::abck(OpCode::TForCall, base as u32, 0, nvars as u32, 0);
4994 emit_inst(fs, line, inst);
4995 }
4996 let loop_op = if isgen {
4997 OpCode::TForLoop
4998 } else {
4999 OpCode::ForLoop
5000 };
5001 let endfor = {
5002 let fs = ls.fs.as_mut().unwrap();
5003 let inst = lua_code::opcodes::Instruction::abx(loop_op, base as u32, 0);
5004 emit_inst(fs, line, inst)
5005 };
5006 fixforjump(ls.fs.as_mut().unwrap(), endfor, prep + 1, true)?;
5007 Ok(())
5008}
5009
5010fn fornum(
5011 ls: &mut LexState,
5012 state: &mut LuaState,
5013 varname: GcRef<LuaString>,
5014 line: i32,
5015) -> Result<(), LuaError> {
5016 let base = ls.fs.as_ref().unwrap().freereg as i32;
5017 let for_state_str = state.intern_str(b"(for state)")?;
5018 new_local_var(ls, state, for_state_str.clone())?;
5019 new_local_var(ls, state, for_state_str.clone())?;
5020 new_local_var(ls, state, for_state_str)?;
5021 let ctrl_vidx = new_local_var(ls, state, varname)?;
5022 if state.global().lua_version == lua_types::LuaVersion::V55 {
5026 let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
5027 get_local_var_desc_mut(ls, firstlocal, ctrl_vidx).kind = VarKind::Const;
5028 }
5029 check_next(ls, state, b'=' as TokenKind)?;
5030 exp1(ls, state)?; check_next(ls, state, b',' as TokenKind)?;
5032 exp1(ls, state)?; if test_next(ls, state, b',' as TokenKind)? {
5034 exp1(ls, state)?; } else {
5036 let fs = ls.fs.as_mut().unwrap();
5037 let reg = fs.freereg as u32;
5038 let bx = (1i32 + lua_code::opcodes::OFFSET_S_BX) as u32;
5039 let inst = lua_code::opcodes::Instruction::abx(lua_code::opcodes::OpCode::LoadI, reg, bx);
5040 emit_inst(fs, line, inst);
5041 reserve_regs(fs, 1)?;
5042 }
5043 adjust_local_vars(ls, state, 3)?; forbody(ls, state, base, line, 1, false)?;
5045 Ok(())
5046}
5047
5048fn forlist(
5049 ls: &mut LexState,
5050 state: &mut LuaState,
5051 indexname: GcRef<LuaString>,
5052) -> Result<(), LuaError> {
5053 let is_v55 = state.global().lua_version == lua_types::LuaVersion::V55;
5054 let mut nvars: i32 = if is_v55 { 4 } else { 5 };
5055 let base = ls.fs.as_ref().unwrap().freereg as i32;
5056 let for_state_str = state.intern_str(b"(for state)")?;
5057 new_local_var(ls, state, for_state_str.clone())?;
5058 new_local_var(ls, state, for_state_str.clone())?;
5059 new_local_var(ls, state, for_state_str.clone())?;
5060 if !is_v55 {
5061 new_local_var(ls, state, for_state_str)?;
5062 }
5063 let idx_vidx = new_local_var(ls, state, indexname)?;
5064 if state.global().lua_version == lua_types::LuaVersion::V55 {
5067 let firstlocal = ls.fs.as_ref().unwrap().firstlocal;
5068 get_local_var_desc_mut(ls, firstlocal, idx_vidx).kind = VarKind::Const;
5069 }
5070 while test_next(ls, state, b',' as TokenKind)? {
5071 let extra_name = str_check_name(ls, state)?;
5072 new_local_var(ls, state, extra_name)?;
5073 nvars += 1;
5074 }
5075 check_next(ls, state, TK_IN)?;
5076 let line = ls.linenumber;
5080 let mut e = ExprDesc::default();
5081 let nexps = explist(ls, state, &mut e)?;
5082 adjust_assign(ls, state, 4, nexps, &mut e)?;
5083 adjust_local_vars(ls, state, if is_v55 { 3 } else { 4 })?;
5084 marktobeclosed(ls.fs.as_mut().unwrap()); let internal_vars = if is_v55 { 3 } else { 4 };
5087 forbody(ls, state, base, line, nvars - internal_vars, true)?;
5088 Ok(())
5089}
5090
5091fn forstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5092 enter_block(ls, true); lex_next(ls, state)?;
5094 let varname = str_check_name(ls, state)?;
5095 match ls.t.token {
5096 c if c == b'=' as TokenKind => fornum(ls, state, varname, line)?,
5097 c if c == b',' as TokenKind || c == TK_IN => forlist(ls, state, varname)?,
5098 _ => {
5099 return Err(LuaError::syntax(format_args!("'=' or 'in' expected")));
5100 }
5101 }
5102 check_match(ls, state, TK_END, TK_FOR, line)?;
5103 leave_block(ls, state)?; Ok(())
5105}
5106
5107fn test_then_block(
5108 ls: &mut LexState,
5109 state: &mut LuaState,
5110 escapelist: &mut i32,
5111) -> Result<(), LuaError> {
5112 lex_next(ls, state)?;
5113 let mut v = ExprDesc::default();
5114 expr(ls, state, &mut v)?;
5115 let cond_line = ls.lastline;
5123 let fold_onto_cond = state.global().lua_version == lua_types::LuaVersion::V55;
5124 check_next(ls, state, TK_THEN)?;
5125
5126 let jf: i32;
5127 if ls.t.token == TK_BREAK {
5128 let line = ls.linenumber;
5129 cg_go_if_false(ls.fs.as_mut().unwrap(), line, &mut v)?;
5130 lex_next(ls, state)?; enter_block(ls, false);
5132 let break_str = state.intern_str(b"break")?;
5133 new_goto_entry(ls, state, break_str, line, v.t)?;
5134 while test_next(ls, state, b';' as TokenKind)? {}
5135 if block_follow(ls, false) {
5136 leave_block(ls, state)?;
5137 return Ok(());
5138 } else {
5139 jf = cg_jump(ls.fs.as_mut().unwrap(), ls.linenumber);
5140 }
5141 } else {
5142 let line = if fold_onto_cond {
5143 cond_line
5144 } else {
5145 ls.lastline
5146 };
5147 cg_go_if_true(ls.fs.as_mut().unwrap(), line, &mut v)?;
5148 enter_block(ls, false);
5149 jf = v.f;
5150 }
5151
5152 statlist(ls, state)?;
5153 leave_block(ls, state)?;
5154
5155 if ls.t.token == TK_ELSE || ls.t.token == TK_ELSEIF {
5156 let line = ls.lastline;
5157 let j = cg_jump(ls.fs.as_mut().unwrap(), line);
5158 cg_concat(ls.fs.as_mut().unwrap(), escapelist, j)?;
5159 }
5160 cg_patch_to_here(ls.fs.as_mut().unwrap(), jf)?;
5161 Ok(())
5162}
5163
5164fn ifstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5165 let mut escapelist = NO_JUMP;
5166 test_then_block(ls, state, &mut escapelist)?; while ls.t.token == TK_ELSEIF {
5168 test_then_block(ls, state, &mut escapelist)?;
5169 }
5170 if test_next(ls, state, TK_ELSE)? {
5171 block(ls, state)?;
5172 }
5173 check_match(ls, state, TK_END, TK_IF, line)?;
5174 cg_patch_to_here(ls.fs.as_mut().unwrap(), escapelist)?;
5175 Ok(())
5176}
5177
5178fn localfunc(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5179 let mut b = ExprDesc::default();
5180 let _fvar = ls.fs.as_ref().unwrap().nactvar as i32;
5181 let name = str_check_name(ls, state)?;
5182 new_local_var(ls, state, name)?;
5183 adjust_local_vars(ls, state, 1)?; let line = ls.lastline;
5185 body(ls, state, &mut b, false, line)?;
5186 let _pc = ls.fs.as_ref().unwrap().pc;
5187 Ok(())
5189}
5190
5191fn version_has_attributes(state: &LuaState) -> bool {
5194 use lua_types::LuaVersion;
5195 matches!(
5196 state.global().lua_version,
5197 LuaVersion::V54 | LuaVersion::V55
5198 )
5199}
5200
5201fn getlocalattribute(
5210 ls: &mut LexState,
5211 state: &mut LuaState,
5212 df: VarKind,
5213) -> Result<VarKind, LuaError> {
5214 if !version_has_attributes(state) {
5215 return Ok(df);
5216 }
5217 if test_next(ls, state, b'<' as TokenKind)? {
5218 let attr_name = str_check_name(ls, state)?;
5219 check_next(ls, state, b'>' as TokenKind)?;
5220 let bytes = attr_name.as_bytes();
5221 if bytes == b"const" {
5222 return Ok(VarKind::Const);
5223 } else if bytes == b"close" {
5224 return Ok(VarKind::ToBeClosed);
5225 } else {
5226 let msg = format!("unknown attribute '{}'", String::from_utf8_lossy(bytes));
5227 return Err(lua_lex::sem_error(&mut ls.lex, msg.as_bytes()));
5228 }
5229 }
5230 Ok(df)
5231}
5232
5233fn checktoclose(ls: &mut LexState, _state: &mut LuaState, level: i32) -> Result<(), LuaError> {
5234 if level != -1 {
5235 marktobeclosed(ls.fs.as_mut().unwrap());
5236 let rl = reg_level(ls, ls.fs.as_ref().unwrap(), level);
5237 let line = ls.lastline;
5238 let inst = lua_code::opcodes::Instruction::abck(
5239 lua_code::opcodes::OpCode::Tbc,
5240 rl as u32,
5241 0,
5242 0,
5243 0,
5244 );
5245 emit_inst(ls.fs.as_mut().unwrap(), line, inst);
5246 }
5247 Ok(())
5248}
5249
5250fn get_global_attribute(
5302 ls: &mut LexState,
5303 state: &mut LuaState,
5304 df: bool,
5305) -> Result<bool, LuaError> {
5306 if !test_next(ls, state, b'<' as TokenKind)? {
5307 return Ok(df);
5308 }
5309 let attr = str_check_name(ls, state)?;
5310 check_next(ls, state, b'>' as TokenKind)?;
5311 match attr.as_bytes() {
5312 b"const" => Ok(true),
5313 b"close" => Err(lua_lex::sem_error(
5314 &mut ls.lex,
5315 b"global variables cannot be to-be-closed",
5316 )),
5317 other => {
5318 let msg = format!("unknown attribute '{}'", String::from_utf8_lossy(other));
5319 Err(lua_lex::sem_error(&mut ls.lex, msg.as_bytes()))
5320 }
5321 }
5322}
5323
5324fn globalstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5325 lex_next(ls, state)?; if ls.t.token == TK_FUNCTION {
5332 let line = ls.linenumber;
5333 lex_next(ls, state)?; let name = str_check_name(ls, state)?;
5335 ls.declared_globals.push((name.clone(), false));
5336 add_scope_barrier(ls, name.clone());
5337 let envn = ls
5339 .envn
5340 .clone()
5341 .expect("envn must be set when resolving globals");
5342 let mut target = ExprDesc::default();
5343 let mut fs_box = ls.fs.take();
5344 let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut target, true);
5345 ls.fs = fs_box;
5346 r?;
5347 let lline = ls.lastline;
5348 {
5349 let fs = ls.fs.as_mut().unwrap();
5350 cg_exp_to_any_reg_up(fs, lline, &mut target)?;
5351 let mut key = ExprDesc::default();
5352 codestring(&mut key, name.clone());
5353 cg_indexed(fs, lline, &mut target, &mut key)?;
5354 }
5355 let mut b = ExprDesc::default();
5356 ls.global_function_names.push(name.clone());
5357 let body_result = body(ls, state, &mut b, false, line);
5358 ls.global_function_names.pop();
5359 body_result?;
5360 {
5361 let fs = ls.fs.as_mut().unwrap();
5362 cg_check_global(fs, line, &target, name)?;
5363 cg_storevar(fs, line, &target, &mut b)?;
5364 }
5365 ls.global_strict = true;
5366 return Ok(());
5367 }
5368
5369 let defkind = get_global_attribute(ls, state, false)?;
5380
5381 if test_next(ls, state, b'*' as TokenKind)? {
5387 let star = state.intern_str(b"*")?;
5388 add_scope_barrier(ls, star);
5389 ls.global_strict = false;
5390 ls.global_wildcard = true;
5391 ls.global_wildcard_const = defkind;
5392 return Ok(());
5393 }
5394
5395 let mut names: Vec<GcRef<LuaString>> = Vec::new();
5399 let mut declarations: Vec<(GcRef<LuaString>, bool)> = Vec::new();
5400 loop {
5401 let name = str_check_name(ls, state)?;
5402 let is_const = get_global_attribute(ls, state, defkind)?;
5403 names.push(name.clone());
5404 declarations.push((name, is_const));
5405 if !test_next(ls, state, b',' as TokenKind)? {
5406 break;
5407 }
5408 }
5409 if test_next(ls, state, b'=' as TokenKind)? {
5416 let init_line = ls.linenumber;
5419 let mut targets: Vec<ExprDesc> = Vec::with_capacity(names.len());
5420 for name in &names {
5421 let envn = ls
5422 .envn
5423 .clone()
5424 .expect("envn must be set when resolving globals");
5425 let mut env_var = ExprDesc::default();
5426 let mut fs_box = ls.fs.take();
5427 let r = singlevaraux(ls, fs_box.as_deref_mut(), &envn, &mut env_var, true);
5428 ls.fs = fs_box;
5429 r?;
5430 let line = ls.lastline;
5431 let fs = ls.fs.as_mut().unwrap();
5432 cg_exp_to_any_reg_up(fs, line, &mut env_var)?;
5433 let mut key = ExprDesc::default();
5434 codestring(&mut key, name.clone());
5435 cg_indexed(fs, line, &mut env_var, &mut key)?;
5436 targets.push(env_var);
5437 }
5438 let nvars = targets.len() as i32;
5439 let mut e = ExprDesc::default();
5440 let nexps = explist(ls, state, &mut e)?;
5441 adjust_assign(ls, state, nvars, nexps, &mut e)?;
5442 for (i, target) in targets.iter().enumerate().rev() {
5448 let name = names[i].clone();
5449 {
5450 let fs = ls.fs.as_mut().unwrap();
5451 cg_check_global(fs, init_line, target, name)?;
5452 }
5453 let line = ls.lastline;
5454 let fs = ls.fs.as_mut().unwrap();
5455 let freereg = fs.freereg as i32 - 1;
5456 let mut v = ExprDesc::default();
5457 init_exp(&mut v, ExprKind::NonReloc, freereg);
5458 cg_storevar(fs, line, target, &mut v)?;
5459 }
5460 }
5461 for (name, is_const) in declarations {
5462 ls.declared_globals.push((name.clone(), is_const));
5463 add_scope_barrier(ls, name);
5464 }
5465 ls.global_strict = true;
5466 Ok(())
5467}
5468
5469fn localstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5470 let local_line = ls.lastline;
5471 let mut toclose: i32 = -1;
5472 let mut nvars: i32 = 0;
5473 let mut vidx: i32;
5474 use lua_types::LuaVersion;
5480 let defkind = if matches!(state.global().lua_version, LuaVersion::V55) {
5481 getlocalattribute(ls, state, VarKind::Reg)?
5482 } else {
5483 VarKind::Reg
5484 };
5485 loop {
5486 let name = str_check_name(ls, state)?;
5487 vidx = new_local_var(ls, state, name)?;
5488 let kind = getlocalattribute(ls, state, defkind)?;
5489 get_local_var_desc_mut(ls, ls.fs.as_ref().unwrap().firstlocal, vidx).kind = kind;
5490 if kind == VarKind::ToBeClosed {
5491 if toclose != -1 {
5492 let saved_line = ls.lex.linenumber;
5493 ls.lex.linenumber = local_line;
5494 let err = lua_lex::lex_error(
5495 &mut ls.lex,
5496 b"multiple to-be-closed variables in local list",
5497 0,
5498 );
5499 ls.lex.linenumber = saved_line;
5500 return Err(err);
5501 }
5502 toclose = ls.fs.as_ref().unwrap().nactvar as i32 + nvars;
5503 }
5504 nvars += 1;
5505 if !test_next(ls, state, b',' as TokenKind)? {
5506 break;
5507 }
5508 }
5509 let nexps: i32;
5510 let mut e = ExprDesc::default();
5511 if test_next(ls, state, b'=' as TokenKind)? {
5512 nexps = explist(ls, state, &mut e)?;
5513 } else {
5514 e.k = ExprKind::Void;
5515 nexps = 0;
5516 }
5517 let first_local = ls.fs.as_ref().unwrap().firstlocal;
5518 let last_vd_kind = ls.dyd.actvar[(first_local + vidx) as usize].kind;
5519 if nvars == nexps && last_vd_kind == VarKind::Const {
5520 let is_const = false; if is_const {
5523 ls.dyd.actvar[(first_local + vidx) as usize].kind = VarKind::CompileTimeConst;
5524 adjust_local_vars(ls, state, nvars - 1)?;
5525 ls.fs.as_mut().unwrap().nactvar += 1;
5526 } else {
5527 adjust_assign(ls, state, nvars, nexps, &mut e)?;
5528 adjust_local_vars(ls, state, nvars)?;
5529 }
5530 } else {
5531 adjust_assign(ls, state, nvars, nexps, &mut e)?;
5532 adjust_local_vars(ls, state, nvars)?;
5533 }
5534 checktoclose(ls, state, toclose)?;
5535 Ok(())
5536}
5537
5538fn funcname(ls: &mut LexState, state: &mut LuaState, v: &mut ExprDesc) -> Result<bool, LuaError> {
5540 let mut ismethod = false;
5541 singlevar(ls, state, v)?;
5542 while ls.t.token == b'.' as TokenKind {
5543 fieldsel(ls, state, v)?;
5544 }
5545 if ls.t.token == b':' as TokenKind {
5546 ismethod = true;
5547 fieldsel(ls, state, v)?;
5548 }
5549 Ok(ismethod)
5550}
5551
5552fn funcstat(ls: &mut LexState, state: &mut LuaState, line: i32) -> Result<(), LuaError> {
5553 lex_next(ls, state)?;
5554 let mut v = ExprDesc::default();
5555 let mut b = ExprDesc::default();
5556 let ismethod = funcname(ls, state, &mut v)?;
5557 check_readonly(ls, state, &v.clone())?;
5558 body(ls, state, &mut b, ismethod, line)?;
5559 check_readonly(ls, state, &v.clone())?;
5560 let fs = ls.fs.as_mut().unwrap();
5561 cg_storevar(fs, line, &v, &mut b)?;
5562 Ok(())
5564}
5565
5566fn exprstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5567 let mut v_assign = LhsAssign {
5568 prev: None,
5569 v: ExprDesc::default(),
5570 };
5571 suffixedexp(ls, state, &mut v_assign.v)?;
5572 if ls.t.token == b'=' as TokenKind || ls.t.token == b',' as TokenKind {
5573 restassign(ls, state, &mut v_assign, 1)?;
5574 } else {
5575 if v_assign.v.k != ExprKind::Call {
5576 if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
5583 return Err(error_expected(ls, b'=' as TokenKind));
5584 }
5585 return Err(lua_lex::syntax_error(&mut ls.lex, b"syntax error"));
5586 }
5587 let info = v_assign.v.u.info as usize;
5588 let fs = ls.fs.as_mut().unwrap();
5589 let mut lc = lua_code::opcodes::Instruction(fs.f.code[info].0);
5590 lc.set_arg_c(1);
5591 fs.f.code[info] = lua_types::opcode::Instruction::new(lc.0);
5592 }
5593 Ok(())
5594}
5595
5596fn retstat(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5597 let mut first = {
5598 let fs = ls.fs.as_ref().unwrap();
5599 nvarstack(ls, fs)
5600 };
5601 let mut nret: i32;
5602 if block_follow(ls, true) || ls.t.token == b';' as TokenKind {
5603 nret = 0;
5604 } else {
5605 let mut e = ExprDesc::default();
5606 nret = explist(ls, state, &mut e)?;
5607 if e.k.has_mult_ret() {
5608 cg_set_returns(ls.fs.as_mut().unwrap(), &mut e, LUA_MULTRET);
5609 if e.k == ExprKind::Call && nret == 1 {
5610 let insidetbc = ls
5611 .fs
5612 .as_ref()
5613 .unwrap()
5614 .bl
5615 .as_ref()
5616 .map_or(false, |b| b.insidetbc);
5617 if !insidetbc {
5618 let fs = ls.fs.as_mut().unwrap();
5619 let info = e.u.info as usize;
5620 let mut lc = lua_code::opcodes::Instruction(fs.f.code[info].0);
5621 lc.set_opcode(lua_code::opcodes::OpCode::TailCall);
5622 fs.f.code[info] = lua_types::opcode::Instruction::new(lc.0);
5623 }
5624 }
5625 nret = LUA_MULTRET;
5626 } else {
5627 let line = ls.lastline;
5628 if nret == 1 {
5629 first = cg_exp_to_any_reg(ls.fs.as_mut().unwrap(), line, &mut e)? as i32;
5630 } else {
5631 cg_exp_to_next_reg(ls.fs.as_mut().unwrap(), line, &mut e)?;
5632 }
5633 }
5634 }
5635 let line = ls.lastline;
5636 let version = state.global().lua_version;
5637 cg_emit_return(ls.fs.as_mut().unwrap(), line, first, nret, version)?;
5638 test_next(ls, state, b';' as TokenKind)?;
5639 Ok(())
5640}
5641
5642fn statement(ls: &mut LexState, state: &mut LuaState) -> Result<(), LuaError> {
5644 let line = ls.linenumber;
5649 enter_level(ls)?;
5650 match ls.t.token {
5651 c if c == b';' as TokenKind => {
5652 lex_next(ls, state)?;
5653 }
5654 TK_IF => {
5655 ifstat(ls, state, line)?;
5656 }
5657 TK_WHILE => {
5658 whilestat(ls, state, line)?;
5659 }
5660 TK_DO => {
5661 lex_next(ls, state)?; block(ls, state)?;
5663 check_match(ls, state, TK_END, TK_DO, line)?;
5664 }
5665 TK_FOR => {
5666 forstat(ls, state, line)?;
5667 }
5668 TK_REPEAT => {
5669 repeatstat(ls, state, line)?;
5670 }
5671 TK_FUNCTION => {
5672 funcstat(ls, state, line)?;
5673 }
5674 TK_LOCAL => {
5675 lex_next(ls, state)?; if test_next(ls, state, TK_FUNCTION)? {
5677 localfunc(ls, state)?;
5678 } else {
5679 localstat(ls, state)?;
5680 }
5681 }
5682 TK_DBCOLON => {
5683 lex_next(ls, state)?; let name = str_check_name(ls, state)?;
5685 labelstat(ls, state, name, line)?;
5686 }
5687 TK_RETURN => {
5688 lex_next(ls, state)?; retstat(ls, state)?;
5690 }
5691 TK_BREAK => {
5692 breakstat(ls, state)?;
5693 }
5694 TK_GOTO => {
5695 lex_next(ls, state)?; gotostat(ls, state)?;
5697 }
5698 _ => {
5699 let is_global_decl = state.global().lua_version == lua_types::LuaVersion::V55
5705 && ls.t.token == TK_NAME
5706 && ls
5707 .t
5708 .seminfo
5709 .ts
5710 .as_ref()
5711 .map_or(false, |s| s.as_bytes() == b"global")
5712 && {
5713 let nxt = lex_lookahead(ls, state)?;
5714 nxt == TK_NAME
5715 || nxt == b'*' as TokenKind
5716 || nxt == b'<' as TokenKind
5717 || nxt == TK_FUNCTION
5718 };
5719 if is_global_decl {
5720 globalstat(ls, state)?;
5721 } else {
5722 exprstat(ls, state)?;
5723 }
5724 }
5725 }
5726 debug_assert!(
5727 ls.fs.as_ref().unwrap().f.maxstacksize >= ls.fs.as_ref().unwrap().freereg
5728 && ls.fs.as_ref().unwrap().freereg as i32 >= nvarstack(ls, ls.fs.as_ref().unwrap())
5729 );
5730 let nv = nvarstack(ls, ls.fs.as_ref().unwrap());
5731 ls.fs.as_mut().unwrap().freereg = nv as u8;
5732 leave_level(ls);
5733 Ok(())
5734}
5735
5736fn mainfunc(
5740 ls: &mut LexState,
5741 state: &mut LuaState,
5742 main_fs: FuncState,
5743) -> Result<Box<LuaProto>, LuaError> {
5744 open_func(ls, state, main_fs)?;
5745
5746 setvararg(ls.fs.as_mut().unwrap(), state, 0)?;
5747
5748 let env_name = ls.envn.clone();
5749 {
5750 let idx = alloc_upvalue(ls.fs.as_mut().unwrap())?;
5751 let up = &mut ls.fs.as_mut().unwrap().f.upvalues[idx];
5752 up.instack = true;
5753 up.idx = 0;
5754 up.kind = VarKind::Reg.as_u8();
5755 up.name = env_name.clone();
5756 }
5757
5758 lex_next(ls, state)?;
5759
5760 statlist(ls, state)?;
5761
5762 check(ls, TK_EOS)?;
5763
5764 close_func(ls, state)
5765}
5766
5767pub fn parse(
5774 state: &mut LuaState,
5775 dyd: DynData,
5776 source: &[u8],
5777 name: &[u8],
5778 firstchar: i32,
5779) -> Result<Box<LuaProto>, LuaError> {
5780 let source_str = state.intern_str(name)?;
5781 let envn_str = state.intern_str(lua_lex::LUA_ENV)?;
5782
5783 let rest_bytes: Vec<u8> = source.iter().skip(1).copied().collect();
5784 let z = lua_lex::ZIO::from_bytes(rest_bytes);
5785
5786 let lex_ls = lua_lex::LexState {
5787 current: firstchar,
5788 linenumber: 1,
5789 lastline: 1,
5790 t: lua_lex::Token::eos(),
5791 lookahead: lua_lex::Token::eos(),
5792 fs: None,
5793 z,
5794 buff: lua_lex::LexBuffer::new(),
5795 h: None,
5796 long_str_anchor: std::collections::HashMap::new(),
5797 dyd: None,
5798 source: source_str.clone(),
5799 envn: envn_str.clone(),
5800 version: state.global().lua_version,
5801 };
5802
5803 let mut lexstate = LexState {
5804 current: lex_ls.current,
5805 linenumber: lex_ls.linenumber,
5806 lastline: lex_ls.lastline,
5807 t: LexToken::default(),
5808 lookahead: LexToken::default(),
5809 fs: None,
5810 dyd,
5811 source: Some(source_str.clone()),
5812 envn: Some(lex_ls.envn.clone()),
5813 lex: lex_ls,
5814 recursion_depth: 0,
5815 global_strict: false,
5816 global_wildcard: false,
5817 global_wildcard_const: false,
5818 declared_globals: Vec::new(),
5819 scope_barriers: Vec::new(),
5820 global_function_names: Vec::new(),
5821 };
5822 let mut main_proto = Box::new(LuaProto::placeholder());
5827 main_proto.source = Some(source_str);
5828 main_proto.is_vararg = true;
5829 let main_fs = FuncState {
5830 f: main_proto,
5831 prev: None,
5832 bl: None,
5833 pc: 0,
5834 lasttarget: 0,
5835 previousline: 0,
5836 nk: 0,
5837 np: 0,
5838 nabslineinfo: 0,
5839 firstlocal: 0,
5840 firstlabel: 0,
5841 ndebugvars: 0,
5842 nactvar: 0,
5843 first_scope_barrier: 0,
5844 nups: 0,
5845 freereg: 0,
5846 iwthabs: 0,
5847 needclose: false,
5848 last_token_line: 0,
5849 };
5850
5851 mainfunc(&mut lexstate, state, main_fs)
5852}
5853
5854fn local_token_value(v: &lua_lex::TokenValue) -> TokenValue {
5859 match v {
5860 lua_lex::TokenValue::None => TokenValue::default(),
5861 lua_lex::TokenValue::Float(r) => TokenValue {
5862 r: *r,
5863 i: 0,
5864 ts: None,
5865 },
5866 lua_lex::TokenValue::Int(i) => TokenValue {
5867 r: 0.0,
5868 i: *i,
5869 ts: None,
5870 },
5871 lua_lex::TokenValue::Str(s) => TokenValue {
5872 r: 0.0,
5873 i: 0,
5874 ts: Some(s.clone()),
5875 },
5876 }
5877}
5878
5879