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
pub use crate::generator::node::Meta;
pub use crate::generator::node::Node;
pub use crate::generator::nodes::Attrs;
use crate::generator::TestManager;
use crate::TEST;
use crate::{Error, Result};
use std::fmt;

#[macro_export]
macro_rules! push_pin_actions {
    ($pin_info:expr) => {{
        crate::TEST.push(crate::node!(PinAction, $pin_info));
    }};
}

#[macro_export]
macro_rules! text {
    ($txt:expr) => {{
        crate::node!(Text, $txt.to_string())
    }};
}

#[macro_export]
macro_rules! add_children {
    ( $parent:expr, $( $child:expr ),* ) => {{
        let mut p = $parent;
        $( p.add_child($child); )*
        p
    }};
}

#[macro_export]
macro_rules! text_line {
    ( $( $elem:expr ),* ) => {{
        let mut n = node!(TextLine);
        $( n.add_child($elem); )*
        n
    }};
}

/// An AST provides an API for constructing a node tree, when completed it can be unwrapped
/// to a node by calling the unwrap() method
#[derive(Clone)]
pub struct AST {
    nodes: Vec<Node>,
}

impl AST {
    /// Create a new AST with the given node as the top-level
    pub fn new() -> AST {
        AST { nodes: vec![] }
    }

    /// Consumes the AST, converting it to a Node
    pub fn unwrap(&mut self) -> Node {
        while self.nodes.len() > 1 {
            let n = self.nodes.pop().unwrap();
            if let Some(node) = self.nodes.last_mut() {
                node.add_child(n);
            }
        }
        self.nodes.pop().unwrap()
    }

    /// Push a new terminal node into the AST
    pub fn push(&mut self, node: Node) {
        match self.nodes.last_mut() {
            Some(n) => n.add_child(node),
            None => self.nodes.push(node),
        }
    }

    pub fn append(&mut self, nodes: &mut Vec<Node>) {
        match self.nodes.last_mut() {
            Some(n) => {
                n.add_children(nodes.to_vec());
            }
            None => self.nodes.append(nodes),
        }
    }

    /// Push a new node into the AST and leave it open, meaning that all new nodes
    /// added to the AST will be inserted as children of this node until it is closed.
    /// A reference ID is returned and the caller should save this and provide it again
    /// when calling close(). If the reference does not match the expected an error will
    /// be raised. This will catch any cases of AST application code forgetting to close
    /// a node before closing one of its parents.
    pub fn push_and_open(&mut self, node: Node) -> usize {
        self.nodes.push(node);
        self.nodes.len()
    }

    /// Close the currently open node
    pub fn close(&mut self, ref_id: usize) -> Result<()> {
        if self.nodes.len() != ref_id {
            return Err(Error::new(&format!(
                "Attempt to close a parent AST node without first closing all its children (given ID: {}, current length: {}), it looks like you have either forgotten to close an open node or given the wrong reference ID",
                ref_id, self.nodes.len()
            )));
        }
        if ref_id == 1 {
            return Err(Error::new("The top-level AST node can never be closed"));
        }
        let n = self.nodes.pop().unwrap();
        if let Some(node) = self.nodes.last_mut() {
            node.add_child(n);
        }
        Ok(())
    }

    /// Replace the node n - offset with the given node, use offset = 0 to
    /// replace the last node that was pushed.
    /// Fails if the AST has no children yet or if the offset is otherwise out
    /// of range.
    pub fn replace(&mut self, node: Node, mut offset: usize) -> Result<()> {
        let mut node_offset = 0;
        let mut child_offset = 0;
        let mut root_node = false;
        let node_len = self.nodes.len();
        while offset > 0 {
            let node = &self.nodes[node_len - 1 - node_offset];
            let num_children = node.children.len();
            // If node to be replaced lies in this node's children
            if num_children > offset {
                child_offset = offset;
                offset = 0;
            // If node to be replaced is this node itself
            } else if num_children == offset {
                root_node = true;
                offset = 0;
            // The node to be replaced lies outside this node
            } else {
                node_offset += 1;
                offset -= num_children + 1;
                child_offset = 0;
            }
        }
        let index = node_len - 1 - node_offset;
        let mut n = self.nodes.remove(index);
        if root_node {
            self.nodes.insert(index, node);
        } else {
            n.replace_child(node, child_offset)?;
            self.nodes.insert(index, n);
        }
        Ok(())
    }

    /// Insert the node at position n - offset, using offset = 0 is equivalent
    /// calling push().
    pub fn insert(&mut self, node: Node, mut offset: usize) -> Result<()> {
        let mut node_offset = 0;
        let mut child_offset = 0;
        let node_len = self.nodes.len();
        while offset > 0 {
            let node = &self.nodes[node_len - 1 - node_offset];
            let num_children = node.children.len();
            // If node is to be inserted into this node's children
            if num_children >= offset {
                child_offset = offset;
                offset = 0;
            // The parent node lies outside this node
            } else {
                node_offset += 1;
                offset -= num_children + 1;
                child_offset = 0;
            }
        }
        let index = node_len - 1 - node_offset;
        let mut n = self.nodes.remove(index);
        n.insert_child(node, child_offset)?;
        self.nodes.insert(index, n);
        Ok(())
    }

    /// Returns a copy of node n - offset, an offset of 0 means
    /// the last node pushed.
    /// Fails if the offset is out of range.
    pub fn get(&self, mut offset: usize) -> Result<Node> {
        let mut node_offset = 0;
        let mut child_offset = 0;
        let mut root_node = false;
        let node_len = self.nodes.len();
        while offset > 0 {
            let node = &self.nodes[node_len - 1 - node_offset];
            let num_children = node.children.len();
            // If node to be returned lies in this node's children
            if num_children > offset {
                child_offset = offset;
                offset = 0;
            // If node to be returned is this node itself
            } else if num_children == offset {
                root_node = true;
                offset = 0;
            // The node to be returned lies outside this node
            } else {
                node_offset += 1;
                offset -= num_children + 1;
                child_offset = 0;
            }
        }
        let index = node_len - 1 - node_offset;
        let n = &self.nodes[index];
        if root_node {
            Ok(self.nodes[index].clone())
        } else {
            Ok(n.get_child(child_offset)?)
        }
    }

    pub fn get_with_descendants(&self, offset: usize) -> Result<Node> {
        let mut cnt: usize = 0;
        for n in self.nodes.iter().rev() {
            if let Some(node) = n.get_descendant(offset, &mut cnt) {
                return Ok(node);
            }
        }
        Err(Error::new(&format!(
            "Offset {} is out of range of the current AST",
            offset
        )))
    }

    /// Clear the current AST and start a new one with the given node at the top-level
    pub fn start(&mut self, node: Node) {
        self.nodes.clear();
        self.nodes.push(node);
    }

    pub fn process(&self, process_fn: &mut dyn FnMut(&Node) -> Result<Node>) -> Result<Node> {
        if self.nodes.len() > 1 {
            let node = self.to_node();
            process_fn(&node)
        } else {
            process_fn(&self.nodes[0])
        }
    }

    /// Execute the given function which receives the a reference to the AST (as a Node) as
    /// its input, returning the result of the function
    pub fn with_node<T, F>(&self, mut process_fn: F) -> Result<T>
    where
        F: FnMut(&Node) -> Result<T>,
    {
        if self.nodes.len() > 1 {
            let node = self.to_node();
            process_fn(&node)
        } else {
            process_fn(&self.nodes[0])
        }
    }

    pub fn to_string(&self) -> String {
        if self.nodes.len() > 1 {
            let node = self.to_node();
            node.to_string()
        } else {
            self.nodes[0].to_string()
        }
    }

    /// Serializes the AST for import into Python
    pub fn to_pickle(&self) -> Vec<u8> {
        if self.nodes.len() > 1 {
            let node = self.to_node();
            node.to_pickle()
        } else {
            self.nodes[0].to_pickle()
        }
    }

    /// Clones the current state of the AST into a Node, leaving the AST unmodified
    pub fn to_node(&self) -> Node {
        let mut node = self.nodes.last().unwrap().clone();
        let num = self.nodes.len();
        if num > 1 {
            for i in 1..num {
                let n = node;
                node = self.nodes[num - i - 1].clone();
                node.add_child(n);
            }
        }
        node
    }
}

impl fmt::Display for AST {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_string())
    }
}

impl fmt::Debug for AST {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_string())
    }
}

impl PartialEq<Node> for AST {
    fn eq(&self, node: &Node) -> bool {
        self.to_node() == *node
    }
}

impl PartialEq<TEST> for AST {
    fn eq(&self, test: &TEST) -> bool {
        self.to_node() == test.to_node()
    }
}

impl PartialEq<TestManager> for AST {
    fn eq(&self, test: &TestManager) -> bool {
        self.to_node() == test.to_node()
    }
}