gbf_core/decompiler/ast/
bin_op.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
#![deny(missing_docs)]

use gbf_macros::AstNodeTransform;
use serde::{Deserialize, Serialize};

use super::AstKind;
use super::{expr::ExprKind, AstNodeError};
use crate::decompiler::ast::literal::LiteralNode;
use crate::decompiler::ast::AstVisitable;
use crate::define_ast_enum_type;

define_ast_enum_type! {
    BinOpType {
        Add => "+",
        Sub => "-",
        Mul => "*",
        Div => "/",
        Mod => "%",
        And => "&",
        Or => "|",
        Xor => "xor",
        LogicalAnd => "&&",
        LogicalOr => "||",
        Equal => "==",
        NotEqual => "!=",
        Greater => ">",
        Less => "<",
        GreaterOrEqual => ">=",
        LessOrEqual => "<=",
        ShiftLeft => "<<",
        ShiftRight => ">>",
        In => "in",
        Join => "@",
    }
}

/// Represents a binary operation node in the AST, such as `a + b`.
#[derive(Debug, Clone, Serialize, Deserialize, Eq, AstNodeTransform)]
#[convert_to(ExprKind::BinOp, AstKind::Expression)]
pub struct BinaryOperationNode {
    /// The left-hand side of the binary operation.
    pub lhs: Box<ExprKind>,
    /// The right-hand side of the binary operation.
    pub rhs: Box<ExprKind>,
    /// The binary operation type.
    pub op_type: BinOpType,
}

impl BinaryOperationNode {
    /// Creates a new `BinaryOperationNode` after validating `lhs` and `rhs`.
    ///
    /// # Arguments
    /// - `lhs` - The left-hand side expression.
    /// - `rhs` - The right-hand side expression.
    /// - `op_type` - The binary operation type.
    ///
    /// # Returns
    /// A new `BinaryOperationNode`.
    ///
    /// # Errors
    /// Returns an `AstNodeError` if `lhs` or `rhs` is of an unsupported type.
    pub fn new(
        lhs: Box<ExprKind>,
        rhs: Box<ExprKind>,
        op_type: BinOpType,
    ) -> Result<Self, AstNodeError> {
        Self::validate_operand(&lhs)?;
        Self::validate_operand(&rhs)?;

        Ok(Self { lhs, rhs, op_type })
    }

    fn validate_operand(expr: &ExprKind) -> Result<(), AstNodeError> {
        // Most expressions are ok except for string literals.
        if let ExprKind::Literal(LiteralNode::String(_)) = expr {
            return Err(AstNodeError::InvalidOperand(
                "BinaryOperationNode".to_string(),
                "Unsupported operand type".to_string(),
                vec!["LiteralNode".to_string()],
                format!("{:?}", expr),
            ));
        }
        Ok(())
    }
}

// == Other implementations for binary operations ==
impl PartialEq for BinaryOperationNode {
    fn eq(&self, other: &Self) -> bool {
        self.lhs == other.lhs && self.rhs == other.rhs && self.op_type == other.op_type
    }
}

impl AstVisitable for BinaryOperationNode {
    fn accept(&self, visitor: &mut dyn super::visitors::AstVisitor) {
        visitor.visit_bin_op(self);
    }
}

#[cfg(test)]
mod tests {
    use crate::decompiler::ast::{emit, new_bin_op, new_id, new_str};

    use super::*;

    #[test]
    fn test_bin_op_emit() -> Result<(), AstNodeError> {
        for op_type in BinOpType::all_variants() {
            let expr = new_bin_op(new_id("a"), new_id("b"), op_type.clone())?;
            assert_eq!(emit(expr), format!("a {} b", op_type.as_str()));
        }
        Ok(())
    }

    #[test]
    fn test_nested_bin_op_emit() -> Result<(), AstNodeError> {
        let expr = new_bin_op(
            new_bin_op(new_id("a"), new_id("b"), BinOpType::Add)?,
            new_id("c"),
            BinOpType::Mul,
        )?;
        assert_eq!(emit(expr), "(a + b) * c");
        Ok(())
    }

    #[test]
    fn test_bin_op_eq() -> Result<(), AstNodeError> {
        let a = new_bin_op(new_id("a"), new_id("b"), BinOpType::Add)?;
        let b = new_bin_op(new_id("a"), new_id("b"), BinOpType::Add)?;
        let c = new_bin_op(new_id("a"), new_id("b"), BinOpType::Sub)?;
        let d = new_bin_op(new_id("a"), new_id("c"), BinOpType::Add)?;

        assert_eq!(a, b);
        assert_ne!(a, c);
        assert_ne!(a, d);
        Ok(())
    }

    #[test]
    fn test_bin_op_validate_operand() -> Result<(), AstNodeError> {
        let a = new_bin_op(new_id("a"), new_id("b"), BinOpType::Add);
        let b = new_bin_op(new_id("a"), new_str("string"), BinOpType::Add);
        let c = new_bin_op(new_str("string"), new_id("b"), BinOpType::Add);

        assert!(a.is_ok());
        assert!(b.is_err());
        assert!(c.is_err());

        Ok(())
    }
}