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

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

use super::{expr::ExprKind, visitors::AstVisitor, AstKind, AstVisitable};

/// Represents a return node in the AST, such as `return 5`.
#[derive(Debug, Clone, Serialize, Deserialize, Eq, AstNodeTransform)]
#[convert_to(AstKind::Return)]
pub struct ReturnNode {
    /// The value to return.
    pub ret: Box<ExprKind>,
}

impl ReturnNode {
    /// Creates a new return node.
    ///
    /// # Arguments
    /// - `ret`: The value to return.
    ///
    /// # Returns
    /// The return node.
    pub fn new(ret: Box<ExprKind>) -> Self {
        Self { ret }
    }
}

impl AstVisitable for ReturnNode {
    fn accept(&self, visitor: &mut dyn AstVisitor) {
        visitor.visit_return(self);
    }
}

// == Other implementations for return ==
impl PartialEq for ReturnNode {
    fn eq(&self, other: &Self) -> bool {
        self.ret == other.ret
    }
}

#[cfg(test)]
mod tests {
    use crate::decompiler::ast::{emit, literal::LiteralNode};

    use super::*;

    #[test]
    fn test_return_node() {
        let ret = ReturnNode::new(Box::new(ExprKind::Literal(LiteralNode::new_number(5))));
        assert_eq!(
            ret.ret,
            Box::new(ExprKind::Literal(LiteralNode::new_number(5)))
        );
    }

    #[test]
    fn test_emit() {
        let ret = ReturnNode::new(Box::new(ExprKind::Literal(LiteralNode::new_number(5))));
        assert_eq!(emit(ret), "return 5;");
    }

    #[test]
    fn test_equality() {
        let ret = ReturnNode::new(Box::new(ExprKind::Literal(LiteralNode::new_number(5))));
        let ret2 = ReturnNode::new(Box::new(ExprKind::Literal(LiteralNode::new_number(5))));
        let ret3 = ReturnNode::new(Box::new(ExprKind::Literal(LiteralNode::new_number(6))));
        assert_eq!(ret, ret2);
        assert_ne!(ret, ret3);
    }
}