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
//! 这个文件负责把 evidence/hints 组合成具体候选名字。
//!
//! 这里还不做最终冲突消解,只回答“这个槽位现在最像什么名字”。
//! 真正的唯一化和祖先作用域避让由 allocation 阶段完成。

use std::collections::BTreeSet;

use crate::ast::AstSyntheticLocalId;
use crate::hir::{HirProto, HirProtoRef, LocalId, ParamId, TempId, UpvalueId};

use super::NamingError;
use super::ast_facts::FunctionAstNamingFacts;
use super::common::{
    CandidateHint, CapturedBinding, FunctionHints, FunctionNameMap, FunctionNamingEvidence,
    NameSource, NamingMode, NamingOptions,
};
use super::lexical::{FunctionLexicalContext, VisibleBinding};
use super::support::{alphabetical_name, as_valid_name};

/// 计算函数定义点外层当前可见绑定对应的最终名字。
pub(super) fn resolve_outer_visible_names(
    function: HirProtoRef,
    lexical: &FunctionLexicalContext,
    assigned_functions: &[FunctionNameMap],
) -> Result<BTreeSet<String>, NamingError> {
    let mut names = BTreeSet::new();
    for &binding in &lexical.outer_visible_bindings {
        names.insert(resolve_visible_binding_name(
            function,
            binding,
            assigned_functions,
        )?);
    }
    Ok(names)
}

/// 选择参数候选名。
pub(super) fn choose_param_candidate(
    proto: &HirProto,
    param: ParamId,
    index: usize,
    evidence: &FunctionNamingEvidence,
    hints: &FunctionHints,
    options: NamingOptions,
) -> CandidateHint {
    if let Some(hint) = hints.param_hints.get(&param)
        && hint.source == NameSource::SelfParam
    {
        return hint.clone();
    }
    if options.mode == NamingMode::DebugLike {
        return mode_fallback_candidate(
            options,
            proto.id,
            "p",
            index,
            alphabetical_name(index).unwrap_or_else(|| format!("arg{}", index + 1)),
        );
    }
    if let Some(name) = evidence
        .param_debug_names
        .get(index)
        .and_then(as_valid_name)
    {
        return CandidateHint {
            text: name,
            source: NameSource::Debug,
        };
    }
    if let Some(hint) = hints.param_hints.get(&param) {
        return hint.clone();
    }
    mode_fallback_candidate(
        options,
        proto.id,
        "p",
        index,
        alphabetical_name(index).unwrap_or_else(|| format!("arg{}", index + 1)),
    )
}

/// 选择 local 候选名。
pub(super) fn choose_local_candidate(
    proto: &HirProto,
    local: LocalId,
    index: usize,
    evidence: &FunctionNamingEvidence,
    hints: &FunctionHints,
    ast_facts: &FunctionAstNamingFacts,
    options: NamingOptions,
) -> CandidateHint {
    if options.mode == NamingMode::DebugLike {
        let visible_count = ast_facts.debug_like_binding_order.len();
        return mode_fallback_candidate(
            options,
            proto.id,
            "r",
            debug_like_binding_index(ast_facts, crate::ast::AstBindingRef::Local(local))
                .unwrap_or(visible_count + index),
            "value".to_owned(),
        );
    }
    if let Some(name) = evidence
        .local_debug_names
        .get(index)
        .and_then(as_valid_name)
    {
        return CandidateHint {
            text: name,
            source: NameSource::Debug,
        };
    }
    if let Some(hint) = hints.local_hints.get(&local) {
        return hint.clone();
    }
    mode_fallback_candidate(options, proto.id, "l", index, "value".to_owned())
}

/// 选择 upvalue 候选名。
pub(super) fn choose_upvalue_candidate(
    proto: &HirProto,
    index: usize,
    evidence: &FunctionNamingEvidence,
    options: NamingOptions,
    assigned_functions: &[FunctionNameMap],
) -> Result<CandidateHint, NamingError> {
    if let Some(capture) = evidence
        .upvalue_capture_sources
        .get(index)
        .and_then(|capture| *capture)
    {
        // upvalue 不是一个“重新发明名字”的槽位:只要我们知道它捕获自哪个父绑定,
        // 就应该沿用那个绑定在父作用域里已经稳定下来的名字。
        return resolve_captured_name(proto.id, capture, assigned_functions);
    }
    if options.mode == NamingMode::DebugLike {
        return Ok(mode_fallback_candidate(
            options,
            proto.id,
            "u",
            index,
            "up".to_owned(),
        ));
    }
    if let Some(name) = evidence
        .upvalue_debug_names
        .get(index)
        .and_then(as_valid_name)
    {
        return Ok(CandidateHint {
            text: name,
            source: NameSource::Debug,
        });
    }
    Ok(mode_fallback_candidate(
        options,
        proto.id,
        "u",
        index,
        "up".to_owned(),
    ))
}

/// 选择 synthetic local 候选名。
pub(super) fn choose_synthetic_local_candidate(
    proto: &HirProto,
    local: AstSyntheticLocalId,
    synthetic_order: usize,
    evidence: &FunctionNamingEvidence,
    hints: &FunctionHints,
    ast_facts: &FunctionAstNamingFacts,
    options: NamingOptions,
) -> CandidateHint {
    if options.mode == NamingMode::DebugLike {
        let visible_count = ast_facts.debug_like_binding_order.len();
        return mode_fallback_candidate(
            options,
            proto.id,
            "r",
            debug_like_binding_index(ast_facts, crate::ast::AstBindingRef::SyntheticLocal(local))
                .unwrap_or(visible_count + proto.locals.len() + synthetic_order),
            "value".to_owned(),
        );
    }
    let index = local.index();
    if let Some(name) = evidence.temp_debug_names.get(index).and_then(as_valid_name) {
        return CandidateHint {
            text: name,
            source: NameSource::Debug,
        };
    }
    if ast_facts.unused_synthetic_locals.contains(&local) {
        return CandidateHint {
            text: "_".to_owned(),
            source: NameSource::Discard,
        };
    }
    if let Some(hint) = hints.synthetic_local_hints.get(&local) {
        return hint.clone();
    }
    mode_fallback_candidate(options, proto.id, "sl", index, "value".to_owned())
}

fn debug_like_binding_index(
    ast_facts: &FunctionAstNamingFacts,
    binding: crate::ast::AstBindingRef,
) -> Option<usize> {
    ast_facts.debug_like_binding_order.get(&binding).copied()
}

fn resolve_visible_binding_name(
    function: HirProtoRef,
    binding: VisibleBinding,
    assigned_functions: &[FunctionNameMap],
) -> Result<String, NamingError> {
    match binding {
        VisibleBinding::Param {
            function: parent,
            param,
        } => resolve_captured_param_name(function, parent, param, assigned_functions),
        VisibleBinding::Local {
            function: parent,
            local,
        } => resolve_captured_local_name(function, parent, local, assigned_functions),
        VisibleBinding::SyntheticLocal {
            function: parent,
            local,
        } => {
            let parent_names = assigned_functions.get(parent.index()).ok_or(
                NamingError::MissingCaptureParent {
                    function: function.index(),
                    parent: parent.index(),
                },
            )?;
            parent_names
                .synthetic_locals
                .get(&local)
                .map(|name| name.text.clone())
                .ok_or(NamingError::MissingCapturedBinding {
                    function: function.index(),
                    parent: parent.index(),
                    kind: "synthetic-local",
                    index: local.index(),
                })
        }
        VisibleBinding::Upvalue {
            function: parent,
            upvalue,
        } => resolve_captured_upvalue_name(function, parent, upvalue, assigned_functions),
    }
}

fn resolve_captured_name(
    function: HirProtoRef,
    capture: CapturedBinding,
    assigned_functions: &[FunctionNameMap],
) -> Result<CandidateHint, NamingError> {
    let text = match capture {
        CapturedBinding::Param { parent, param } => {
            resolve_captured_param_name(function, parent, param, assigned_functions)?
        }
        CapturedBinding::Local { parent, local } => {
            resolve_captured_local_name(function, parent, local, assigned_functions)?
        }
        CapturedBinding::Temp { parent, temp } => {
            resolve_captured_temp_name(function, parent, temp, assigned_functions)?
        }
        CapturedBinding::Upvalue { parent, upvalue } => {
            resolve_captured_upvalue_name(function, parent, upvalue, assigned_functions)?
        }
    };
    Ok(CandidateHint {
        text,
        source: NameSource::CaptureProvenance,
    })
}

fn resolve_captured_param_name(
    function: HirProtoRef,
    parent: HirProtoRef,
    param: ParamId,
    assigned_functions: &[FunctionNameMap],
) -> Result<String, NamingError> {
    let parent_names =
        assigned_functions
            .get(parent.index())
            .ok_or(NamingError::MissingCaptureParent {
                function: function.index(),
                parent: parent.index(),
            })?;
    parent_names
        .params
        .get(param.index())
        .map(|name| name.text.clone())
        .ok_or(NamingError::MissingCapturedBinding {
            function: function.index(),
            parent: parent.index(),
            kind: "param",
            index: param.index(),
        })
}

fn resolve_captured_local_name(
    function: HirProtoRef,
    parent: HirProtoRef,
    local: LocalId,
    assigned_functions: &[FunctionNameMap],
) -> Result<String, NamingError> {
    let parent_names =
        assigned_functions
            .get(parent.index())
            .ok_or(NamingError::MissingCaptureParent {
                function: function.index(),
                parent: parent.index(),
            })?;
    parent_names
        .locals
        .get(local.index())
        .map(|name| name.text.clone())
        .ok_or(NamingError::MissingCapturedBinding {
            function: function.index(),
            parent: parent.index(),
            kind: "local",
            index: local.index(),
        })
}

fn resolve_captured_temp_name(
    function: HirProtoRef,
    parent: HirProtoRef,
    temp: TempId,
    assigned_functions: &[FunctionNameMap],
) -> Result<String, NamingError> {
    let parent_names =
        assigned_functions
            .get(parent.index())
            .ok_or(NamingError::MissingCaptureParent {
                function: function.index(),
                parent: parent.index(),
            })?;
    parent_names
        .synthetic_locals
        .get(&AstSyntheticLocalId(temp))
        .map(|name| name.text.clone())
        .ok_or(NamingError::MissingCapturedBinding {
            function: function.index(),
            parent: parent.index(),
            kind: "synthetic-local",
            index: temp.index(),
        })
}

fn resolve_captured_upvalue_name(
    function: HirProtoRef,
    parent: HirProtoRef,
    upvalue: UpvalueId,
    assigned_functions: &[FunctionNameMap],
) -> Result<String, NamingError> {
    let parent_names =
        assigned_functions
            .get(parent.index())
            .ok_or(NamingError::MissingCaptureParent {
                function: function.index(),
                parent: parent.index(),
            })?;
    parent_names
        .upvalues
        .get(upvalue.index())
        .map(|name| name.text.clone())
        .ok_or(NamingError::MissingCapturedBinding {
            function: function.index(),
            parent: parent.index(),
            kind: "upvalue",
            index: upvalue.index(),
        })
}

fn mode_fallback_candidate(
    options: NamingOptions,
    function: HirProtoRef,
    prefix: &str,
    index: usize,
    simple_base: String,
) -> CandidateHint {
    match options.mode {
        NamingMode::DebugLike => CandidateHint {
            text: debug_like_name(options, function, prefix, index),
            source: NameSource::DebugLike,
        },
        NamingMode::Simple | NamingMode::Heuristic => CandidateHint {
            text: simple_base,
            source: NameSource::Simple,
        },
    }
}

fn debug_like_name(
    options: NamingOptions,
    function: HirProtoRef,
    prefix: &str,
    index: usize,
) -> String {
    if options.debug_like_include_function {
        format!("{prefix}{}_{}", function.index(), index)
    } else {
        format!("{prefix}{index}")
    }
}