unluac 1.3.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
//! 这个文件实现共享分支候选提取。
//!
//! 它依赖 CFG/GraphFacts 已经提供好的 branch 边和后支配信息,负责回答
//! “这个 block 更像哪种 branch 形态”,以及后续多个 pass 共用的 branch-region 事实。
//! 它不会越权做短路、scope 或最终 HIR 结构决策。
//!
//! 例子:
//! - `if cond then ... end` 会产出 `BranchKind::IfThen`
//! - `if cond then ... else ... end` 会产出 `BranchKind::IfElse`
//! - `if not cond then return end; ...` 这种守卫形状会被标成 `BranchKind::Guard`

use std::collections::{BTreeMap, BTreeSet};

use crate::structure::{BlockRef, Cfg, DominatorTree, GraphFacts};

use super::common::{BranchCandidate, BranchKind, BranchRegionFact, LoopCandidate};
use super::helpers::{collect_forward_region_blocks, collect_merge_arm_preds};

pub(super) fn analyze_branches(
    cfg: &Cfg,
    graph_facts: &GraphFacts,
    loop_candidates: &[LoopCandidate],
) -> Vec<BranchCandidate> {
    let mut reachability = ReachabilityCache::new(cfg, loop_candidates);
    let mut branch_candidates: Vec<_> = cfg
        .block_order
        .iter()
        .copied()
        .filter(|header| cfg.reachable_blocks.contains(header))
        .filter_map(|header| {
            let (then_edge_ref, else_edge_ref) = cfg.branch_edges(header)?;
            let then_entry = cfg.edges[then_edge_ref.index()].to;
            let else_entry = cfg.edges[else_edge_ref.index()].to;
            if then_entry == else_entry {
                return None;
            }
            classify_one_arm_branch(&mut reachability, header, then_entry, else_entry)
                .or_else(|| {
                    classify_if_else_branch(
                        cfg,
                        graph_facts,
                        &mut reachability,
                        header,
                        then_entry,
                        else_entry,
                    )
                })
                .or_else(|| {
                    classify_loop_bounded_one_arm_branch(
                        &mut reachability,
                        header,
                        then_entry,
                        else_entry,
                    )
                })
                .or_else(|| {
                    classify_guard_branch(cfg, &mut reachability, header, then_entry, else_entry)
                })
        })
        .collect();
    branch_candidates.sort_by_key(|candidate| candidate.header);
    branch_candidates
}

pub(super) fn analyze_branch_regions(
    cfg: &Cfg,
    graph_facts: &GraphFacts,
    branch_candidates: &[BranchCandidate],
) -> Vec<BranchRegionFact> {
    let mut branch_regions = Vec::new();

    for candidate in branch_candidates {
        let Some(merge) = candidate.merge else {
            continue;
        };

        branch_regions.push(BranchRegionFact {
            header: candidate.header,
            merge,
            kind: candidate.kind,
            flow_blocks: collect_branch_region_blocks(cfg, candidate, merge, None),
            structured_blocks: collect_branch_region_blocks(
                cfg,
                candidate,
                merge,
                Some(&graph_facts.dominator_tree),
            ),
            then_merge_preds: collect_merge_arm_preds(cfg, candidate.then_entry, merge),
            else_merge_preds: candidate
                .else_entry
                .map(|else_entry| collect_merge_arm_preds(cfg, else_entry, merge))
                .unwrap_or_default(),
        });
    }

    branch_regions.sort_by_key(|fact| (fact.header, fact.merge));
    branch_regions
}

fn collect_branch_region_blocks(
    cfg: &Cfg,
    candidate: &BranchCandidate,
    merge: BlockRef,
    dom_tree: Option<&DominatorTree>,
) -> BTreeSet<BlockRef> {
    let mut blocks = BTreeSet::from([candidate.header]);
    blocks.extend(collect_forward_region_blocks(
        cfg,
        std::iter::once(candidate.then_entry).chain(candidate.else_entry),
        Some(merge),
        dom_tree.map(|tree| (candidate.header, tree)),
    ));

    blocks
}

struct ReachabilityCache<'a> {
    cfg: &'a Cfg,
    memo: BTreeMap<(BlockRef, BlockRef), bool>,
    loop_bounded_memo: BTreeMap<(BlockRef, BlockRef), bool>,
    loop_exits_by_header: BTreeMap<BlockRef, BTreeSet<BlockRef>>,
}

impl<'a> ReachabilityCache<'a> {
    fn new(cfg: &'a Cfg, loop_candidates: &[LoopCandidate]) -> Self {
        let loop_exits_by_header = loop_candidates
            .iter()
            .filter(|candidate| candidate.reducible)
            .map(|candidate| (candidate.header, candidate.exits.clone()))
            .collect();
        Self {
            cfg,
            memo: BTreeMap::new(),
            loop_bounded_memo: BTreeMap::new(),
            loop_exits_by_header,
        }
    }

    fn can_reach(&mut self, from: BlockRef, to: BlockRef) -> bool {
        *self
            .memo
            .entry((from, to))
            .or_insert_with(|| self.cfg.can_reach(from, to))
    }

    fn can_reach_without_entering_loop_header(&mut self, from: BlockRef, to: BlockRef) -> bool {
        *self.loop_bounded_memo.entry((from, to)).or_insert_with(|| {
            can_reach_without_entering_loop_body(self.cfg, from, to, &self.loop_exits_by_header)
        })
    }
}

fn can_reach_without_entering_loop_body(
    cfg: &Cfg,
    from: BlockRef,
    to: BlockRef,
    loop_exits_by_header: &BTreeMap<BlockRef, BTreeSet<BlockRef>>,
) -> bool {
    if from == to {
        return true;
    }
    if loop_exits_by_header.contains_key(&from) {
        return false;
    }

    let mut visited = BTreeSet::new();
    let mut stack = vec![from];
    while let Some(block) = stack.pop() {
        if block == to {
            return true;
        }
        if !visited.insert(block) {
            continue;
        }
        if let Some(exits) = loop_exits_by_header.get(&block) {
            stack.extend(exits.iter().copied());
            continue;
        }
        for edge_ref in &cfg.succs[block.index()] {
            stack.push(cfg.edges[edge_ref.index()].to);
        }
    }

    false
}

fn classify_one_arm_branch(
    reachability: &mut ReachabilityCache<'_>,
    header: BlockRef,
    then_entry: BlockRef,
    else_entry: BlockRef,
) -> Option<BranchCandidate> {
    let then_reaches_else = reachability.can_reach(then_entry, else_entry);
    let else_reaches_then = reachability.can_reach(else_entry, then_entry);

    match (then_reaches_else, else_reaches_then) {
        (true, false) => Some(BranchCandidate {
            header,
            then_entry,
            else_entry: None,
            merge: Some(else_entry),
            kind: BranchKind::IfThen,
            invert_hint: false,
        }),
        (false, true) => Some(BranchCandidate {
            header,
            then_entry: else_entry,
            else_entry: None,
            merge: Some(then_entry),
            kind: BranchKind::IfThen,
            invert_hint: true,
        }),
        _ => None,
    }
}

fn classify_loop_bounded_one_arm_branch(
    reachability: &mut ReachabilityCache<'_>,
    header: BlockRef,
    then_entry: BlockRef,
    else_entry: BlockRef,
) -> Option<BranchCandidate> {
    // 普通可达性在无出口或嵌套 loop 里会被回边污染:两个分支臂可能都能绕一整圈
    // 回到对方,看起来不像 if-then。这里把 reducible nested loop 当成“只通向 exits
    // 的结构化节点”,既保留 `if ... then skip nested-for end` 这种正常出口,又避免沿
    // loop body/backedge 绕回另一条臂。
    let then_reaches_else =
        reachability.can_reach_without_entering_loop_header(then_entry, else_entry);
    let else_reaches_then =
        reachability.can_reach_without_entering_loop_header(else_entry, then_entry);

    match (then_reaches_else, else_reaches_then) {
        (true, false) => Some(BranchCandidate {
            header,
            then_entry,
            else_entry: None,
            merge: Some(else_entry),
            kind: BranchKind::IfThen,
            invert_hint: false,
        }),
        (false, true) => Some(BranchCandidate {
            header,
            then_entry: else_entry,
            else_entry: None,
            merge: Some(then_entry),
            kind: BranchKind::IfThen,
            invert_hint: true,
        }),
        _ => None,
    }
}

fn classify_if_else_branch(
    cfg: &Cfg,
    graph_facts: &GraphFacts,
    reachability: &mut ReachabilityCache<'_>,
    header: BlockRef,
    then_entry: BlockRef,
    else_entry: BlockRef,
) -> Option<BranchCandidate> {
    let merge = graph_facts.nearest_common_postdom(then_entry, else_entry)?;
    if merge == cfg.exit_block {
        // 严格后支配合流是 exit block,说明两侧都有提前 return 的路径。
        // 但如果一侧的 ipostdom 是非 exit 块且从另一侧可达,那它仍然是
        // 合法的 if-else merge:提前 return 只是 body 内的 early exit,
        // 不影响外层的 merge 恢复。
        let soft = find_soft_merge(cfg, graph_facts, reachability, then_entry, else_entry);
        return Some(BranchCandidate {
            header,
            then_entry,
            else_entry: Some(else_entry),
            merge: soft,
            kind: BranchKind::IfElse,
            invert_hint: false,
        });
    }

    if merge == then_entry {
        return Some(BranchCandidate {
            header,
            then_entry: else_entry,
            else_entry: None,
            merge: Some(then_entry),
            kind: BranchKind::IfThen,
            invert_hint: true,
        });
    }

    if merge == else_entry {
        return Some(BranchCandidate {
            header,
            then_entry,
            else_entry: None,
            merge: Some(else_entry),
            kind: BranchKind::IfThen,
            invert_hint: false,
        });
    }

    Some(BranchCandidate {
        header,
        then_entry,
        else_entry: Some(else_entry),
        merge: Some(merge),
        kind: BranchKind::IfElse,
        invert_hint: false,
    })
}

fn classify_guard_branch(
    cfg: &Cfg,
    reachability: &mut ReachabilityCache<'_>,
    header: BlockRef,
    then_entry: BlockRef,
    else_entry: BlockRef,
) -> Option<BranchCandidate> {
    if reachability.can_reach(then_entry, else_entry)
        || reachability.can_reach(else_entry, then_entry)
    {
        return None;
    }

    let then_score = branch_continuation_score(cfg, then_entry);
    let else_score = branch_continuation_score(cfg, else_entry);
    if then_score == else_score {
        return None;
    }

    let (continuation, side, invert_hint) = if then_score > else_score {
        (then_entry, else_entry, true)
    } else {
        (else_entry, then_entry, false)
    };

    Some(BranchCandidate {
        header,
        then_entry: side,
        else_entry: None,
        merge: Some(continuation),
        kind: BranchKind::Guard,
        invert_hint,
    })
}

fn branch_continuation_score(cfg: &Cfg, start: BlockRef) -> usize {
    let mut visited = BTreeSet::new();
    let mut stack = vec![start];

    while let Some(block) = stack.pop() {
        if !cfg.reachable_blocks.contains(&block)
            || block == cfg.exit_block
            || !visited.insert(block)
        {
            continue;
        }

        for edge_ref in &cfg.succs[block.index()] {
            stack.push(cfg.edges[edge_ref.index()].to);
        }
    }

    visited.len()
}

/// 当严格后支配合流 = exit block 时,沿各分支的 ipostdom 链向上找一个
/// "软合流":它不是 exit block,且从另一侧可达。
///
/// 典型触发形状:
/// ```text
/// if A then        ← header
///     if B then return end   ← then 侧提前 return,导致 postdom(then)=exit
///     C
/// else
///     D
/// end
/// E                ← 软合流 = ipostdom(else),且从 then 侧也可达
/// ```
fn find_soft_merge(
    cfg: &Cfg,
    graph_facts: &GraphFacts,
    reachability: &mut ReachabilityCache<'_>,
    then_entry: BlockRef,
    else_entry: BlockRef,
) -> Option<BlockRef> {
    let pdom_parent = &graph_facts.post_dominator_tree.parent;

    // 沿 ipostdom 链向上搜索,找到第一个非 exit 且从 `other` 可达的祖先。
    let mut walk_chain = |start: BlockRef, other: BlockRef| -> Option<BlockRef> {
        let mut cursor = start;
        loop {
            let parent = (*pdom_parent.get(cursor.index())?)?;
            if parent == cfg.exit_block {
                return None;
            }
            if reachability.can_reach(other, parent) {
                return Some(parent);
            }
            cursor = parent;
        }
    };

    let else_candidate = walk_chain(else_entry, then_entry);
    let then_candidate = walk_chain(then_entry, else_entry);

    match (else_candidate, then_candidate) {
        (Some(e), Some(t)) => {
            // 两侧都找到候选,取离分支更近的(被另一侧后支配的那个)
            if graph_facts.post_dominates(t, e) {
                Some(e)
            } else {
                Some(t)
            }
        }
        (Some(e), None) => Some(e),
        (None, Some(t)) => Some(t),
        (None, None) => None,
    }
}