unluac 1.1.1

Multi-dialect Lua decompiler written in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! 这个文件集中声明 AST 层的共享语法节点。
//!
//! AST 是 target-dialect-aware 的语法树:它不再做控制流恢复,但要把 HIR 已经确定
//! 的结构落成“某个目标 Lua 方言真正允许出现”的语法节点。
//!
//! 除了语法节点本身,这一层也会保留少量“readability 必须知道、但源码语法里看不见”
//! 的 provenance。这样后续 pass 在做 sugar 时可以依赖前层已经确认过的结构事实,
//! 而不是回头重新猜测。

use std::collections::BTreeSet;
use std::fmt;

use crate::hir::{HirLabelId, HirProtoRef, LocalId, ParamId, TempId, UpvalueId};

/// AST 内部物化出来的保守局部绑定。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct AstSyntheticLocalId(pub TempId);

impl AstSyntheticLocalId {
    pub const fn index(self) -> usize {
        self.0.index()
    }
}

/// AST 根对象。
#[derive(Debug, Clone, PartialEq, Default)]
pub struct AstModule {
    pub entry_function: HirProtoRef,
    pub body: AstBlock,
}

/// AST 语句块。
#[derive(Debug, Clone, PartialEq, Default)]
pub struct AstBlock {
    pub stmts: Vec<AstStmt>,
}

/// AST 语句。
#[derive(Debug, Clone, PartialEq)]
pub enum AstStmt {
    LocalDecl(Box<AstLocalDecl>),
    GlobalDecl(Box<AstGlobalDecl>),
    Assign(Box<AstAssign>),
    CallStmt(Box<AstCallStmt>),
    Return(Box<AstReturn>),
    If(Box<AstIf>),
    While(Box<AstWhile>),
    Repeat(Box<AstRepeat>),
    NumericFor(Box<AstNumericFor>),
    GenericFor(Box<AstGenericFor>),
    Break,
    Continue,
    Goto(Box<AstGoto>),
    Label(Box<AstLabel>),
    DoBlock(Box<AstBlock>),
    FunctionDecl(Box<AstFunctionDecl>),
    LocalFunctionDecl(Box<AstLocalFunctionDecl>),
    /// 反编译过程中无法恢复的语句占位符,最终会被输出为 Lua 注释。
    Error(String),
}

/// AST 表达式。
#[derive(Debug, Clone, PartialEq)]
pub enum AstExpr {
    Nil,
    Boolean(bool),
    Integer(i64),
    Number(f64),
    String(String),
    Int64(i64),
    UInt64(u64),
    Complex { real: f64, imag: f64 },
    Var(AstNameRef),
    FieldAccess(Box<AstFieldAccess>),
    IndexAccess(Box<AstIndexAccess>),
    Unary(Box<AstUnaryExpr>),
    Binary(Box<AstBinaryExpr>),
    LogicalAnd(Box<AstLogicalExpr>),
    LogicalOr(Box<AstLogicalExpr>),
    Call(Box<AstCallExpr>),
    MethodCall(Box<AstMethodCallExpr>),
    SingleValue(Box<AstExpr>),
    VarArg,
    TableConstructor(Box<AstTableConstructor>),
    FunctionExpr(Box<AstFunctionExpr>),
    /// 反编译过程中无法恢复的表达式占位符,最终会被输出为带注释的 nil。
    Error(String),
}

/// 赋值语句。
#[derive(Debug, Clone, PartialEq)]
pub struct AstAssign {
    pub targets: Vec<AstLValue>,
    pub values: Vec<AstExpr>,
}

/// 赋值左值。
#[derive(Debug, Clone, PartialEq)]
pub enum AstLValue {
    Name(AstNameRef),
    FieldAccess(Box<AstFieldAccess>),
    IndexAccess(Box<AstIndexAccess>),
}

/// 变量/绑定引用。
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum AstNameRef {
    Param(ParamId),
    Local(LocalId),
    Temp(TempId),
    SyntheticLocal(AstSyntheticLocalId),
    Upvalue(UpvalueId),
    Global(AstGlobalName),
}

/// 可在 `local` 中声明的 binding。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum AstBindingRef {
    Local(LocalId),
    Temp(TempId),
    SyntheticLocal(AstSyntheticLocalId),
}

/// 全局名。
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct AstGlobalName {
    pub text: String,
}

/// 返回语句。
#[derive(Debug, Clone, PartialEq)]
pub struct AstReturn {
    pub values: Vec<AstExpr>,
}

/// 函数表达式。
#[derive(Debug, Clone, PartialEq)]
pub struct AstFunctionExpr {
    pub function: HirProtoRef,
    pub params: Vec<ParamId>,
    pub is_vararg: bool,
    pub named_vararg: Option<AstBindingRef>,
    pub body: AstBlock,
    /// 这份集合只记录“闭包初始化时显式 capture 了哪些当前词法绑定”。
    ///
    /// 它不是源码语法的一部分,而是给 readability 提供结构事实:
    /// 如果一个函数值仍然依赖某个局部槽位,就不能把那个槽位前推消掉,
    /// 否则像递归 local function 这种形状会失去可见声明。
    pub captured_bindings: BTreeSet<AstBindingRef>,
}

/// 顶层/表字段函数声明。
#[derive(Debug, Clone, PartialEq)]
pub struct AstFunctionDecl {
    pub target: AstFunctionName,
    pub func: AstFunctionExpr,
}

/// `local function` 声明。
#[derive(Debug, Clone, PartialEq)]
pub struct AstLocalFunctionDecl {
    pub name: AstBindingRef,
    pub func: AstFunctionExpr,
}

/// 函数声明名。
#[derive(Debug, Clone, PartialEq)]
pub enum AstFunctionName {
    Plain(AstNamePath),
    Method(AstNamePath, String),
}

/// `a.b.c` 这类名字路径。
#[derive(Debug, Clone, PartialEq)]
pub struct AstNamePath {
    pub root: AstNameRef,
    pub fields: Vec<String>,
}

/// 目标语法方言。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AstTargetDialect {
    pub version: AstDialectVersion,
    pub caps: AstDialectCaps,
}

/// AST 关心的语法能力。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AstDialectCaps {
    pub goto_label: bool,
    pub continue_stmt: bool,
    pub local_const: bool,
    pub local_close: bool,
    pub global_decl: bool,
    pub global_const: bool,
}

/// AST/Generate 关心的可选语法特性。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum AstFeature {
    GotoLabel,
    ContinueStmt,
    LocalConst,
    LocalClose,
    GlobalDecl,
    GlobalConst,
}

impl AstFeature {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::GotoLabel => "goto",
            Self::ContinueStmt => "continue",
            Self::LocalConst => "local<const>",
            Self::LocalClose => "local<close>",
            Self::GlobalDecl => "global",
            Self::GlobalConst => "global<const>",
        }
    }
}

/// 当前支持的目标方言版本。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AstDialectVersion {
    Lua51,
    Lua52,
    Lua53,
    Lua54,
    Lua55,
    LuaJit,
    Luau,
}

impl AstDialectVersion {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Lua51 => "lua5.1",
            Self::Lua52 => "lua5.2",
            Self::Lua53 => "lua5.3",
            Self::Lua54 => "lua5.4",
            Self::Lua55 => "lua5.5",
            Self::LuaJit => "luajit",
            Self::Luau => "luau",
        }
    }
}

impl fmt::Display for AstDialectVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl AstTargetDialect {
    pub const fn new(version: AstDialectVersion) -> Self {
        let caps = match version {
            AstDialectVersion::Lua51 => AstDialectCaps {
                goto_label: false,
                continue_stmt: false,
                local_const: false,
                local_close: false,
                global_decl: false,
                global_const: false,
            },
            AstDialectVersion::Lua52 | AstDialectVersion::Lua53 => AstDialectCaps {
                goto_label: true,
                continue_stmt: false,
                local_const: false,
                local_close: false,
                global_decl: false,
                global_const: false,
            },
            AstDialectVersion::Lua54 => AstDialectCaps {
                goto_label: true,
                continue_stmt: false,
                local_const: true,
                local_close: true,
                global_decl: false,
                global_const: false,
            },
            AstDialectVersion::Lua55 => AstDialectCaps {
                goto_label: true,
                continue_stmt: false,
                local_const: true,
                local_close: true,
                global_decl: true,
                global_const: true,
            },
            AstDialectVersion::LuaJit => AstDialectCaps {
                goto_label: true,
                continue_stmt: false,
                local_const: false,
                local_close: false,
                global_decl: false,
                global_const: false,
            },
            AstDialectVersion::Luau => AstDialectCaps {
                goto_label: false,
                continue_stmt: true,
                local_const: false,
                local_close: false,
                global_decl: false,
                global_const: false,
            },
        };
        Self { version, caps }
    }

    pub const fn relaxed_for_lowering(version: AstDialectVersion) -> Self {
        let mut caps = Self::new(version).caps;
        caps.goto_label = true;
        caps.local_const = true;
        caps.local_close = true;
        caps.global_decl = true;
        caps.global_const = true;
        Self { version, caps }
    }

    pub const fn supports_feature(self, feature: AstFeature) -> bool {
        self.caps.supports(feature)
    }
}

impl AstDialectCaps {
    pub const fn supports(self, feature: AstFeature) -> bool {
        match feature {
            AstFeature::GotoLabel => self.goto_label,
            AstFeature::ContinueStmt => self.continue_stmt,
            AstFeature::LocalConst => self.local_const,
            AstFeature::LocalClose => self.local_close,
            AstFeature::GlobalDecl => self.global_decl,
            AstFeature::GlobalConst => self.global_decl && self.global_const,
        }
    }
}

/// `local` 声明。
#[derive(Debug, Clone, PartialEq)]
pub struct AstLocalDecl {
    pub bindings: Vec<AstLocalBinding>,
    pub values: Vec<AstExpr>,
}

/// `global` 声明。
#[derive(Debug, Clone, PartialEq)]
pub struct AstGlobalDecl {
    pub bindings: Vec<AstGlobalBinding>,
    pub values: Vec<AstExpr>,
}

/// `local` binding。
#[derive(Debug, Clone, PartialEq)]
pub struct AstLocalBinding {
    pub id: AstBindingRef,
    pub attr: AstLocalAttr,
    pub origin: AstLocalOrigin,
}

/// `global` binding。
#[derive(Debug, Clone, PartialEq)]
pub struct AstGlobalBinding {
    pub target: AstGlobalBindingTarget,
    pub attr: AstGlobalAttr,
}

/// `global` 声明的绑定目标。
///
/// 这里显式区分普通全局名和 `global *` wildcard,是为了避免把 `*` 塞成一个伪名字。
/// 后续 Generate 只需要按这个稳定结构输出,不需要再猜测当前 binding 到底是不是 wildcard。
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum AstGlobalBindingTarget {
    Name(AstGlobalName),
    Wildcard,
}

/// 局部声明属性。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AstLocalAttr {
    None,
    Const,
    Close,
}

/// 局部绑定在进入 AST 时的来源。
///
/// 这里不是为了精确复刻 parser 的原始局部声明,而是给 readability 一个稳定边界:
/// 带 parser debug 影子的 local 更接近源码语义名,机械恢复出来的 local 则可以更积极
/// 地继续收回表达式。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AstLocalOrigin {
    Recovered,
    DebugHinted,
}

/// 全局声明属性。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AstGlobalAttr {
    None,
    Const,
}

/// 字段访问。
#[derive(Debug, Clone, PartialEq)]
pub struct AstFieldAccess {
    pub base: AstExpr,
    pub field: String,
}

/// 索引访问。
#[derive(Debug, Clone, PartialEq)]
pub struct AstIndexAccess {
    pub base: AstExpr,
    pub index: AstExpr,
}

/// 一元表达式。
#[derive(Debug, Clone, PartialEq)]
pub struct AstUnaryExpr {
    pub op: AstUnaryOpKind,
    pub expr: AstExpr,
}

/// 二元表达式。
#[derive(Debug, Clone, PartialEq)]
pub struct AstBinaryExpr {
    pub op: AstBinaryOpKind,
    pub lhs: AstExpr,
    pub rhs: AstExpr,
}

/// 逻辑表达式。
#[derive(Debug, Clone, PartialEq)]
pub struct AstLogicalExpr {
    pub lhs: AstExpr,
    pub rhs: AstExpr,
}

/// 普通调用。
#[derive(Debug, Clone, PartialEq)]
pub struct AstCallExpr {
    pub callee: AstExpr,
    pub args: Vec<AstExpr>,
}

/// 方法调用。
#[derive(Debug, Clone, PartialEq)]
pub struct AstMethodCallExpr {
    pub receiver: AstExpr,
    pub method: String,
    pub args: Vec<AstExpr>,
}

/// 调用语句。
#[derive(Debug, Clone, PartialEq)]
pub struct AstCallStmt {
    pub call: AstCallKind,
}

/// 调用表达式/语句的统一承载。
#[derive(Debug, Clone, PartialEq)]
pub enum AstCallKind {
    Call(Box<AstCallExpr>),
    MethodCall(Box<AstMethodCallExpr>),
}

/// 表构造器。
#[derive(Debug, Clone, PartialEq)]
pub struct AstTableConstructor {
    pub fields: Vec<AstTableField>,
}

/// 表字段。
#[derive(Debug, Clone, PartialEq)]
pub enum AstTableField {
    Array(AstExpr),
    Record(AstRecordField),
}

/// 记录字段。
#[derive(Debug, Clone, PartialEq)]
pub struct AstRecordField {
    pub key: AstTableKey,
    pub value: AstExpr,
}

/// 记录 key。
#[derive(Debug, Clone, PartialEq)]
pub enum AstTableKey {
    Name(String),
    Expr(AstExpr),
}

/// `if` 语句。
#[derive(Debug, Clone, PartialEq)]
pub struct AstIf {
    pub cond: AstExpr,
    pub then_block: AstBlock,
    pub else_block: Option<AstBlock>,
}

/// `while` 语句。
#[derive(Debug, Clone, PartialEq)]
pub struct AstWhile {
    pub cond: AstExpr,
    pub body: AstBlock,
}

/// `repeat` 语句。
#[derive(Debug, Clone, PartialEq)]
pub struct AstRepeat {
    pub body: AstBlock,
    pub cond: AstExpr,
}

/// `numeric for` 语句。
#[derive(Debug, Clone, PartialEq)]
pub struct AstNumericFor {
    pub binding: AstBindingRef,
    pub start: AstExpr,
    pub limit: AstExpr,
    pub step: AstExpr,
    pub body: AstBlock,
}

/// `generic for` 语句。
#[derive(Debug, Clone, PartialEq)]
pub struct AstGenericFor {
    pub bindings: Vec<AstBindingRef>,
    pub iterator: Vec<AstExpr>,
    pub body: AstBlock,
}

/// `goto` 语句。
#[derive(Debug, Clone, PartialEq)]
pub struct AstGoto {
    pub target: AstLabelId,
}

/// label 语句。
#[derive(Debug, Clone, PartialEq)]
pub struct AstLabel {
    pub id: AstLabelId,
}

/// AST label 身份。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct AstLabelId(pub usize);

impl AstLabelId {
    pub const fn index(self) -> usize {
        self.0
    }
}

impl From<HirLabelId> for AstLabelId {
    fn from(value: HirLabelId) -> Self {
        Self(value.index())
    }
}

/// 一元运算。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AstUnaryOpKind {
    Not,
    Neg,
    BitNot,
    Length,
}

/// 二元运算。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AstBinaryOpKind {
    Add,
    Sub,
    Mul,
    Div,
    FloorDiv,
    Mod,
    Pow,
    BitAnd,
    BitOr,
    BitXor,
    Shl,
    Shr,
    Concat,
    Eq,
    Lt,
    Le,
}