gbf_core/decompiler/ast/visitors/
emitter.rs

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
#![deny(missing_docs)]

use super::{
    emit_context::{EmitContext, EmitVerbosity, IndentStyle},
    AstVisitor,
};
use crate::decompiler::ast::meta::MetaNode;
use crate::decompiler::ast::statement::StatementNode;
use crate::decompiler::ast::unary_op::UnaryOperationNode;
use crate::decompiler::ast::{assignable::AssignableKind, expr::ExprKind};
use crate::decompiler::ast::{
    bin_op::{BinOpType, BinaryOperationNode},
    func_call::FunctionCallNode,
};
use crate::decompiler::ast::{function::FunctionNode, literal::LiteralNode};
use crate::decompiler::ast::{member_access::MemberAccessNode, ret::ReturnNode};
use crate::decompiler::ast::{AstKind, AstVisitable};
use crate::{decompiler::ast::identifier::IdentifierNode, utils::escape_string};

/// An emitter for the AST.
pub struct Gs2Emitter {
    /// The output of the emitter.
    output: String,
    /// The context of the emitter.
    context: EmitContext,
}

impl Gs2Emitter {
    /// Creates a new `Gs2Emitter` with the given `context`.
    pub fn new(context: EmitContext) -> Self {
        Self {
            output: String::new(),
            context,
        }
    }

    /// Returns the output of the emitter.
    pub fn output(&self) -> &str {
        &self.output
    }
}

impl AstVisitor for Gs2Emitter {
    fn visit_node(&mut self, node: &AstKind) {
        match node {
            AstKind::Expression(expr) => expr.accept(self),
            AstKind::Meta(meta) => meta.accept(self),
            AstKind::Statement(stmt) => stmt.accept(self),
            AstKind::Function(func) => func.accept(self),
            AstKind::Return(ret) => ret.accept(self),
            AstKind::Empty => {}
        }
    }
    fn visit_statement(&mut self, stmt_node: &StatementNode) {
        // Step 0: Print the whitespace
        let indent_level = self.context.indent;
        for _ in 0..indent_level {
            self.output.push(' ');
        }
        // Step 1: Visit and emit the LHS
        stmt_node.lhs.accept(self);
        let lhs_str = self.output.clone();
        self.output.clear();

        // Step 2: Handle RHS
        if let ExprKind::BinOp(bin_op_node) = stmt_node.rhs.as_ref() {
            // Check if the binary operation directly involves the LHS
            let lhs_in_rhs =
                bin_op_node.lhs.as_ref() == &ExprKind::Assignable(*stmt_node.lhs.clone());

            if lhs_in_rhs {
                match bin_op_node.op_type {
                    BinOpType::Add => {
                        // Handle increment (++), compound assignment (+=), or fall back to addition
                        if let ExprKind::Literal(LiteralNode::Number(num)) =
                            bin_op_node.rhs.as_ref()
                        {
                            if *num == 1 {
                                // Emit increment (++)
                                self.output.push_str(&format!("{}++;", lhs_str));
                                return;
                            } else {
                                // Emit compound assignment (+=)
                                bin_op_node.rhs.accept(self); // Visit the RHS to get the formatted number
                                let rhs_str = self.output.clone();
                                self.output.clear();
                                self.output
                                    .push_str(&format!("{} += {};", lhs_str, rhs_str));
                                return;
                            }
                        }
                    }
                    BinOpType::Sub => {
                        // Handle decrement (--), compound assignment (-=), or fall back to subtraction
                        if let ExprKind::Literal(LiteralNode::Number(num)) =
                            bin_op_node.rhs.as_ref()
                        {
                            if *num == 1 {
                                // Emit decrement (--)
                                self.output.push_str(&format!("{}--;", lhs_str));
                                return;
                            } else {
                                // Emit compound assignment (-=)
                                bin_op_node.rhs.accept(self); // Visit the RHS to get the formatted number
                                let rhs_str = self.output.clone();
                                self.output.clear();
                                self.output
                                    .push_str(&format!("{} -= {};", lhs_str, rhs_str));
                                return;
                            }
                        }
                    }
                    _ => {}
                }
            }
        }

        // Step 3: Handle default assignment
        let prev_context = self.context;
        self.context = self.context.with_expr_root(true);

        stmt_node.rhs.accept(self); // Visit the RHS
        let rhs_str = self.output.clone();
        self.output.clear();

        self.context = prev_context; // Restore the context
        self.output.push_str(&format!("{} = {};", lhs_str, rhs_str));
    }

    fn visit_expr(&mut self, node: &ExprKind) {
        match node {
            ExprKind::Literal(literal) => literal.accept(self),
            ExprKind::Assignable(assignable) => self.visit_assignable_expr(assignable),
            ExprKind::BinOp(bin_op) => bin_op.accept(self),
            ExprKind::UnaryOp(unary_op) => unary_op.accept(self),
            ExprKind::FunctionCall(func_call) => func_call.accept(self),
        }
    }

    fn visit_assignable_expr(&mut self, node: &AssignableKind) {
        match node {
            AssignableKind::MemberAccess(member_access) => {
                if member_access.ssa_version.is_some() && self.context.include_ssa_versions {
                    self.output.push('{');
                }
                member_access.accept(self);
                if self.context.include_ssa_versions {
                    if let Some(ssa_version) = member_access.ssa_version {
                        self.output.push_str(&format!("}}@{}", ssa_version));
                    }
                }
            }
            AssignableKind::Identifier(identifier) => {
                identifier.accept(self);
                if self.context.include_ssa_versions {
                    if let Some(ssa_version) = identifier.ssa_version {
                        self.output.push_str(&format!("@{}", ssa_version));
                    }
                }
            }
        }
    }

    fn visit_bin_op(&mut self, node: &BinaryOperationNode) {
        // Save the current context and set expr_root to false for nested operations
        let prev_context = self.context;
        self.context = self.context.with_expr_root(false);

        // Visit and emit the left-hand side
        node.lhs.accept(self);
        let lhs_str = self.output.clone(); // Capture emitted LHS
        self.output.clear();

        // Visit and emit the right-hand side
        node.rhs.accept(self);
        let rhs_str = self.output.clone(); // Capture emitted RHS
        self.output.clear();

        // Restore the previous context
        self.context = prev_context;

        // Determine the operator string
        let op_str = node.op_type.to_string();

        // Combine the emitted parts into the final binary operation string
        if self.context.expr_root {
            // Emit without parentheses for root expressions
            self.output
                .push_str(&format!("{} {} {}", lhs_str, op_str, rhs_str));
        } else {
            // Emit with parentheses for nested expressions
            self.output
                .push_str(&format!("({} {} {})", lhs_str, op_str, rhs_str));
        }
    }

    fn visit_unary_op(&mut self, node: &UnaryOperationNode) {
        // Save the current context and set expr_root to false for the operand
        let prev_context = self.context;
        self.context = self.context.with_expr_root(false);

        // Visit and emit the operand
        node.operand.accept(self);
        let operand_str = self.output.clone(); // Capture emitted operand
        self.output.clear();

        // Restore the previous context
        self.context = prev_context;

        // Determine the operator string
        let op_str = node.op_type.to_string();

        // Combine the emitted parts into the final unary operation string
        if self.context.expr_root {
            self.output.push_str(&format!("{}{}", op_str, operand_str));
        } else {
            self.output
                .push_str(&format!("({}{})", op_str, operand_str));
        }
        // self.output.push_str(&format!("{}{}", op_str, operand_str));
    }

    fn visit_identifier(&mut self, node: &IdentifierNode) {
        // Append the identifier's ID directly to the output
        self.output.push_str(node.id());
    }

    fn visit_literal(&mut self, node: &LiteralNode) {
        let emitted_literal = match node {
            LiteralNode::String(s) => format!("\"{}\"", escape_string(s)),
            LiteralNode::Number(n) => {
                if self.context.format_number_hex {
                    format!("0x{:X}", n)
                } else {
                    n.to_string()
                }
            }
            LiteralNode::Float(f) => f.clone(),
            LiteralNode::Boolean(b) => b.to_string(),
        };

        self.output.push_str(&emitted_literal);
    }

    fn visit_member_access(&mut self, node: &MemberAccessNode) {
        // Visit and emit the LHS
        node.lhs.accept(self);
        let lhs_str = self.output.clone(); // Capture emitted LHS
        self.output.clear();

        // Visit and emit the RHS
        node.rhs.accept(self);
        let rhs_str = self.output.clone(); // Capture emitted RHS
        self.output.clear();

        // Combine the LHS and RHS with a dot for member access
        self.output.push_str(&format!("{}.{}", lhs_str, rhs_str));
    }

    fn visit_meta(&mut self, node: &MetaNode) {
        // Handle minified verbosity
        if self.context.verbosity == EmitVerbosity::Minified {
            node.node().accept(self);
            return;
        }

        let mut result = String::new();

        // Add comment if available
        if let Some(comment) = &node.comment() {
            result.push_str(&format!("// {}\n", comment));
        }

        // Visit and emit the inner node
        node.node().accept(self);
        result.push_str(&self.output);
        self.output.clear();

        // Store the result in the visitor's output
        self.output.push_str(&result);
    }

    fn visit_function_call(&mut self, node: &FunctionCallNode) {
        // Visit and emit the base
        self.output.push_str(node.name.id_string().as_str());

        // Emit the arguments
        self.output.push('(');
        for (i, arg) in node.arguments.iter().enumerate() {
            arg.accept(self);
            if i < node.arguments.len() - 1 {
                self.output.push_str(", ");
            }
        }
        self.output.push(')');
    }

    fn visit_function(&mut self, node: &FunctionNode) {
        let name = node.name().clone();
        if name.is_none() {
            // Just emit the function body if there is no name since we're
            // in the entry point function
            for stmt in node.body() {
                stmt.accept(self);
                self.output.push('\n');
            }
            return;
        }

        let name = name.unwrap();

        // Emit the function parameters
        self.output.push_str(format!("function {}(", name).as_str());
        for (i, param) in node.params().iter().enumerate() {
            param.accept(self);
            if i < node.params().len() - 1 {
                self.output.push_str(", ");
            }
        }
        self.output.push(')');

        // Check if we we are using allman or k&r style
        if self.context.indent_style == IndentStyle::Allman {
            self.output.push_str("\n{\n");
        } else {
            self.output.push_str(" {\n");
        }

        // Emit the function body, indented
        let old_context = self.context;
        self.context = self.context.with_indent();
        for stmt in node.body() {
            stmt.accept(self);
            self.output.push('\n');
        }
        self.context = old_context;
        self.output.push_str("}\n");
    }

    fn visit_return(&mut self, node: &ReturnNode) {
        // return with indentation
        for _ in 0..self.context.indent {
            self.output.push(' ');
        }

        // Emit the return keyword
        self.output.push_str("return ");

        // Emit the return value
        node.ret.accept(self);

        // Emit the semicolon
        self.output.push(';');
    }
}