lang_interpreter/parser/
ast.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
pub mod node;

use std::fmt::{Display, Formatter, Write as _};
pub use node::{
    Node, NodeData, Visibility, StructMember, StructDefinition, ClassMember, Method,
    ConditionalNode, Constructor, ClassDefinition, Operator, OperatorType, FunctionDefinition,
    OperationExpression,
};

use crate::lexer::CodePosition;

#[derive(Debug, Clone, PartialEq)]
pub struct AST {
    nodes: Vec<Node>,
}

impl AST {
    pub fn new() -> Self {
        Self { nodes: Vec::new() }
    }

    pub fn get_pos(&self) -> CodePosition {
        if self.nodes.is_empty() {
            CodePosition::EMPTY
        }else {
            self.nodes.first().unwrap().pos().combine(&self.nodes.last().unwrap().pos())
        }
    }

    pub fn add_child(&mut self, node: Node) {
        self.nodes.push(node);
    }

    pub fn nodes(&self) -> &[Node] {
        &self.nodes
    }

    pub(in crate::parser) fn nodes_mut(&mut self) -> &mut Vec<Node> {
        &mut self.nodes
    }

    pub fn into_nodes(self) -> Vec<Node> {
        self.nodes
    }

    pub fn into_node(self) -> Node {
        if self.nodes.len() == 1 {
            self.nodes.into_iter().next().unwrap()
        }else {
            Node::new_list_node(self.nodes)
        }
    }

    pub fn optimize_ast(&mut self) {
        Node::optimize_nodes(&mut self.nodes);
    }
}

impl Default for AST {
    fn default() -> Self {
        Self::new()
    }
}

impl Display for AST {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut builder = String::new();
        builder += "AST: Children: {\n";
        for node in self.nodes.iter() {
            for token in node.to_string().split("\n") {
                let _ = writeln!(builder, "\t{token}");
            }
        }
        builder += "}";

        f.write_str(builder.as_str())
    }
}

impl From<&[Node]> for AST {
    fn from(value: &[Node]) -> Self {
        Self {
            nodes: Vec::from(value),
        }
    }
}

impl From<&mut [Node]> for AST {
    fn from(value: &mut [Node]) -> Self {
        Self {
            nodes: Vec::from(value),
        }
    }
}

impl <const N: usize> From<&[Node; N]> for AST {
    fn from(value: &[Node; N]) -> Self {
        Self {
            nodes: Vec::from(value),
        }
    }
}

impl <const N: usize> From<&mut [Node; N]> for AST {
    fn from(value: &mut [Node; N]) -> Self {
        Self {
            nodes: Vec::from(value),
        }
    }
}

impl <const N: usize> From<[Node; N]> for AST {
    fn from(value: [Node; N]) -> Self {
        Self {
            nodes: Vec::from(value),
        }
    }
}