unluac 1.2.2

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
//! 这个文件实现主反编译 pipeline 的统一入口。
//!
//! 当前只真正接上 parser,但入口已经先按完整阶段序列搭好;
//! 这样后续补层时只需要往这个骨架里填实现,不需要重写调用约定。

use crate::ast::lower_ast;
use crate::cfg::{analyze_dataflow, analyze_graph_facts, build_cfg_proto};
use crate::generate::{
    GenerateChunkCommentMetadata, GenerateCommentMetadata, GenerateFunctionCommentMetadata,
    generate_chunk,
};
use crate::hir::{PassDumpConfig, analyze_hir};
use crate::naming::{assign_names_with_evidence, collect_naming_evidence};
use crate::structure::analyze_structure;
use crate::timing::{TimingCollector, TimingReport};
use crate::transformer::lower_chunk;

use super::debug::{StageDebugOutput, collect_stage_dump};
use super::error::DecompileError;
use super::options::DecompileOptions;
use super::output_plan::{ast_lowering_target, resolve_output_plan};
use super::state::{DecompileStage, DecompileState};

/// 一次主 pipeline 调用的返回值。
#[derive(Debug, Clone, PartialEq)]
pub struct DecompileResult {
    pub state: DecompileState,
    pub debug_output: Vec<StageDebugOutput>,
    pub timing_report: Option<TimingReport>,
}

/// 对外暴露唯一的主入口,统一完成默认值补齐和阶段调度。
pub fn decompile(
    bytes: &[u8],
    options: DecompileOptions,
) -> Result<DecompileResult, DecompileError> {
    DecompilerPipeline.run(bytes, options)
}

struct DecompilerPipeline;

impl DecompilerPipeline {
    fn run(
        self,
        bytes: &[u8],
        options: DecompileOptions,
    ) -> Result<DecompileResult, DecompileError> {
        let options = options.normalized();

        let mut state = DecompileState::new(options.dialect, options.target_stage);
        let mut debug_output = Vec::new();
        let timings = TimingCollector::new(options.debug.enable && options.debug.timing);
        let requested_target = crate::ast::AstTargetDialect::new(options.dialect.into());

        state.raw_chunk = Some({
            let _timing = timings.scope(DecompileStage::Parse.as_str());
            options.dialect.parse_chunk(bytes, options.parse)?
        });
        state.mark_completed(DecompileStage::Parse);

        if let Some(output) = collect_stage_dump(&state, DecompileStage::Parse, &options.debug)? {
            debug_output.push(output);
        }

        if options.target_stage == DecompileStage::Parse {
            return Ok(finish_result(state, debug_output, &timings));
        }

        let raw_chunk = state
            .raw_chunk
            .as_ref()
            .expect("parse stage completed must leave raw_chunk in state");
        state.lowered = Some({
            let _timing = timings.scope(DecompileStage::Transform.as_str());
            lower_chunk(raw_chunk)?
        });
        state.mark_completed(DecompileStage::Transform);

        if let Some(output) = collect_stage_dump(&state, DecompileStage::Transform, &options.debug)?
        {
            debug_output.push(output);
        }

        if options.target_stage == DecompileStage::Transform {
            return Ok(finish_result(state, debug_output, &timings));
        }

        state.cfg = Some({
            let _timing = timings.scope(DecompileStage::Cfg.as_str());
            let lowered = state
                .lowered
                .as_ref()
                .expect("transform stage completed must leave lowered in state");
            build_cfg_proto(&lowered.main)
        });
        state.mark_completed(DecompileStage::Cfg);

        if let Some(output) = collect_stage_dump(&state, DecompileStage::Cfg, &options.debug)? {
            debug_output.push(output);
        }

        if options.target_stage == DecompileStage::Cfg {
            return Ok(finish_result(state, debug_output, &timings));
        }

        state.graph_facts = Some({
            let _timing = timings.scope(DecompileStage::GraphFacts.as_str());
            let cfg_graph = state
                .cfg
                .as_ref()
                .expect("cfg stage completed must leave cfg graph in state");
            analyze_graph_facts(cfg_graph)
        });
        state.mark_completed(DecompileStage::GraphFacts);

        if let Some(output) =
            collect_stage_dump(&state, DecompileStage::GraphFacts, &options.debug)?
        {
            debug_output.push(output);
        }

        if options.target_stage == DecompileStage::GraphFacts {
            return Ok(finish_result(state, debug_output, &timings));
        }

        state.dataflow = Some({
            let _timing = timings.scope(DecompileStage::Dataflow.as_str());
            let lowered = state
                .lowered
                .as_ref()
                .expect("transform stage completed must leave lowered in state");
            let cfg_graph = state
                .cfg
                .as_ref()
                .expect("cfg stage completed must leave cfg graph in state");
            let graph_facts = state
                .graph_facts
                .as_ref()
                .expect("graph facts stage completed must leave graph facts in state");
            analyze_dataflow(
                &lowered.main,
                &cfg_graph.cfg,
                graph_facts,
                &cfg_graph.children,
            )
        });
        state.mark_completed(DecompileStage::Dataflow);

        if let Some(output) = collect_stage_dump(&state, DecompileStage::Dataflow, &options.debug)?
        {
            debug_output.push(output);
        }

        if options.target_stage == DecompileStage::Dataflow {
            return Ok(finish_result(state, debug_output, &timings));
        }

        state.structure_facts = Some({
            let _timing = timings.scope(DecompileStage::StructureFacts.as_str());
            let lowered = state
                .lowered
                .as_ref()
                .expect("transform stage completed must leave lowered in state");
            let cfg_graph = state
                .cfg
                .as_ref()
                .expect("cfg stage completed must leave cfg graph in state");
            let graph_facts = state
                .graph_facts
                .as_ref()
                .expect("graph facts stage completed must leave graph facts in state");
            let dataflow = state
                .dataflow
                .as_ref()
                .expect("dataflow stage completed must leave dataflow in state");
            analyze_structure(
                &lowered.main,
                &cfg_graph.cfg,
                graph_facts,
                dataflow,
                &cfg_graph.children,
            )
        });
        state.mark_completed(DecompileStage::StructureFacts);

        if let Some(output) =
            collect_stage_dump(&state, DecompileStage::StructureFacts, &options.debug)?
        {
            debug_output.push(output);
        }

        if options.target_stage == DecompileStage::StructureFacts {
            return Ok(finish_result(state, debug_output, &timings));
        }

        state.hir = Some({
            let _timing = timings.scope(DecompileStage::Hir.as_str());
            let lowered = state
                .lowered
                .as_ref()
                .expect("transform stage completed must leave lowered in state");
            let cfg_graph = state
                .cfg
                .as_ref()
                .expect("cfg stage completed must leave cfg graph in state");
            let graph_facts = state
                .graph_facts
                .as_ref()
                .expect("graph facts stage completed must leave graph facts in state");
            let dataflow = state
                .dataflow
                .as_ref()
                .expect("dataflow stage completed must leave dataflow in state");
            let structure_facts = state
                .structure_facts
                .as_ref()
                .expect("structure stage completed must leave structure facts in state");
            let dump_config = PassDumpConfig {
                pass_names: options.debug.dump_passes.clone(),
                filters: options.debug.filters,
            };
            analyze_hir(
                lowered,
                cfg_graph,
                graph_facts,
                dataflow,
                structure_facts,
                &timings,
                options.readability,
                options.generate.mode,
                requested_target.version,
                &dump_config,
            )
        });
        state.mark_completed(DecompileStage::Hir);

        if let Some(output) = collect_stage_dump(&state, DecompileStage::Hir, &options.debug)? {
            debug_output.push(output);
        }

        if options.target_stage == DecompileStage::Hir {
            return Ok(finish_result(state, debug_output, &timings));
        }

        state.ast = Some({
            let _timing = timings.scope(DecompileStage::Ast.as_str());
            let hir = state
                .hir
                .as_ref()
                .expect("hir stage completed must leave hir module in state");
            lower_ast(
                hir,
                ast_lowering_target(requested_target, options.generate.mode),
                options.generate.mode,
            )
        }?);
        state.mark_completed(DecompileStage::Ast);

        if let Some(output) = collect_stage_dump(&state, DecompileStage::Ast, &options.debug)? {
            debug_output.push(output);
        }

        if options.target_stage == DecompileStage::Ast {
            return Ok(finish_result(state, debug_output, &timings));
        }

        let output_plan = {
            let _timing = timings.scope(DecompileStage::Readability.as_str());
            let ast = state
                .ast
                .as_ref()
                .expect("ast stage completed must leave ast module in state");
            resolve_output_plan(
                ast,
                requested_target,
                options.readability,
                options.generate.mode,
                &timings,
                &options.debug.dump_passes,
            )
        };
        let output_target = output_plan.target;
        let output_generate_mode = output_plan.generate_mode;
        let output_warnings = output_plan.warnings;
        state.readability = Some(output_plan.readability);
        state.mark_completed(DecompileStage::Readability);

        if let Some(output) =
            collect_stage_dump(&state, DecompileStage::Readability, &options.debug)?
        {
            debug_output.push(output);
        }

        if options.target_stage == DecompileStage::Readability {
            return Ok(finish_result(state, debug_output, &timings));
        }

        state.naming = Some({
            let _timing = timings.scope(DecompileStage::Naming.as_str());
            let ast = state
                .readability
                .as_ref()
                .expect("readability stage completed must leave readability result in state");
            let hir = state
                .hir
                .as_ref()
                .expect("hir stage completed must leave hir module in state");
            let evidence = {
                let _timing = timings.scope("collect-evidence");
                collect_naming_evidence(hir)
            }?;
            assign_names_with_evidence(ast, hir, &evidence, options.naming)
        }?);
        state.mark_completed(DecompileStage::Naming);

        if let Some(output) = collect_stage_dump(&state, DecompileStage::Naming, &options.debug)? {
            debug_output.push(output);
        }

        if options.target_stage == DecompileStage::Naming {
            return Ok(finish_result(state, debug_output, &timings));
        }

        state.generated = Some({
            let _timing = timings.scope(DecompileStage::Generate.as_str());
            let ast = state
                .readability
                .as_ref()
                .expect("readability stage completed must leave readability result in state");
            let names = state
                .naming
                .as_ref()
                .expect("naming stage completed must leave name map in state");
            let mut generate_options = options.generate;
            generate_options.mode = output_generate_mode;
            let comment_metadata = if generate_options.comment {
                let hir = state
                    .hir
                    .as_ref()
                    .expect("hir stage completed must leave hir module in state");
                Some(build_generate_comment_metadata(
                    hir,
                    options.parse.string_encoding.as_str(),
                ))
            } else {
                None
            };
            let mut generated = generate_chunk(
                ast,
                names,
                output_target,
                comment_metadata.as_ref(),
                generate_options,
            )?;
            generated.warnings = output_warnings;
            Ok::<_, crate::generate::GenerateError>(generated)
        }?);
        state.mark_completed(DecompileStage::Generate);

        if let Some(output) = collect_stage_dump(&state, DecompileStage::Generate, &options.debug)?
        {
            debug_output.push(output);
        }

        Ok(finish_result(state, debug_output, &timings))
    }
}

fn finish_result(
    state: DecompileState,
    debug_output: Vec<StageDebugOutput>,
    timings: &TimingCollector,
) -> DecompileResult {
    DecompileResult {
        state,
        debug_output,
        timing_report: timings.finish(),
    }
}

fn build_generate_comment_metadata(
    hir: &crate::hir::HirModule,
    encoding: &str,
) -> GenerateCommentMetadata {
    let entry_source = hir
        .protos
        .get(hir.entry.index())
        .and_then(|proto| proto.source.clone());
    GenerateCommentMetadata {
        chunk: GenerateChunkCommentMetadata {
            file_name: entry_source,
            encoding: encoding.to_owned(),
        },
        functions: hir
            .protos
            .iter()
            .map(|proto| GenerateFunctionCommentMetadata {
                function: proto.id,
                source: proto.source.clone(),
                line_range: proto.line_range,
                signature: proto.signature,
                local_count: proto.locals.len(),
                upvalue_count: proto.upvalues.len(),
            })
            .collect(),
    }
}