Debian Codegraph @

crates/wasm-mutate/src/mutators/codemotion/ir/parse_context.rs

raw
1 use crate::{Error, Result};
2 use std::ops::Range;
3 use wasmparser::BlockType;
4
5 #[derive(Debug, Default)]
6 pub struct Ast {
7 // Index of the root node
8 root: usize,
9 // Nodes of the tree
10 nodes: Vec<Node>,
11 // indexes of ifs nodes
12 ifs: Vec<usize>,
13 // indexeds of loop nodes
14 loops: Vec<usize>,
15 }
16
17 impl Ast {
18 /// Returns true if the Ast has if-else nodes
19 pub fn has_if(&self) -> bool {
20 !self.ifs.is_empty()
21 }
22
23 /// Returns the node indexes corresponding to if-else nodes
24 pub fn get_ifs(&self) -> &[usize] {
25 &self.ifs
26 }
27
28 /// Returns the node indexes corresponding to if-else nodes
29 pub fn get_loops(&self) -> &[usize] {
30 &self.loops
31 }
32
33 /// Returns the `Root` node index of the Ast
34 pub fn get_root(&self) -> usize {
35 self.root
36 }
37
38 /// Returns all Ast nodes
39 pub fn get_nodes(&self) -> Vec<Node> {
40 self.nodes.clone()
41 }
42 }
43
44 #[derive(Debug, Clone)]
45 pub enum Node {
46 /// `if`/`else` node.
47 IfElse {
48 /// Then branch node indices.
49 consequent: Vec<usize>,
50 /// Else branch node indices.
51 alternative: Option<Vec<usize>>,
52 /// The block type for the branches.
53 ty: BlockType,
54 },
55 /// Code node
56 Code {
57 /// Range on the instructions stream
58 range: Range<usize>,
59 },
60 /// Loop Node
61 Loop {
62 /// Children nodes
63 body: Vec<usize>,
64 /// Block type
65 ty: BlockType,
66 /// Range on the instructions stream
67 range: Range<usize>,
68 },
69 /// Block Node
70 Block {
71 /// Children nodes
72 body: Vec<usize>,
73 /// Block type
74 ty: BlockType,
75 },
76 /// Special node to wrap the root nodes of the Ast
77 Root(Vec<usize>),
78 }
79
80 #[derive(Debug)]
81 pub(crate) enum State {
82 If,
83 Else,
84 Loop,
85 Block,
86 Root,
87 }
88
89 #[derive(Debug)]
90 pub(crate) struct ParseContext {
91 current_parsing: Vec<usize>,
92 stack: Vec<Vec<usize>>,
93 frames: Vec<(State, Option<BlockType>, usize)>,
94 current_code_range: Range<usize>,
95 nodes: Vec<Node>,
96
97 ifs: Vec<usize>,
98 loops: Vec<usize>,
99 blocks: Vec<usize>,
100 }
101
102 impl Default for ParseContext {
103 fn default() -> Self {
104 ParseContext {
105 current_code_range: 0..0,
106 current_parsing: Vec::new(),
107 stack: Vec::new(),
108 frames: Vec::new(),
109 nodes: Vec::new(),
110 ifs: Vec::new(),
111 loops: Vec::new(),
112 blocks: Vec::new(),
113 }
114 }
115 }
116
117 impl ParseContext {
118 /// Saves current parsed nodes in the stack
119 pub fn push_state(&mut self) {
120 self.stack.push(self.current_parsing.clone());
121 self.current_parsing = vec![]
122 }
123
124 /// Pops nodes previously parsed, set them as the current parsing
125 /// and then returns a copy of the poped value
126 pub fn pop_state(&mut self) -> Result<Vec<usize>> {
127 match self.stack.pop() {
128 Some(new_state) => {
129 self.current_parsing = new_state.clone();
130 Ok(new_state)
131 }
132 None => Err(Error::other("`pop_state` on an empty stack")),
133 }
134 }
135
136 /// Push a node to the current parsing
137 pub fn push_node_to_current_parsing(&mut self, node: Node) -> usize {
138 let id = self.nodes.len();
139 self.nodes.push(node.clone());
140 self.current_parsing.push(id);
141
142 match node {
143 Node::IfElse {
144 consequent: _,
145 alternative: _,
146 ty: _,
147 } => self.ifs.push(id),
148 Node::Loop { .. } => self.loops.push(id),
149 Node::Block { .. } => self.blocks.push(id),
150 _ => {}
151 }
152 id
153 }
154
155 /// Push a new frame,
156 ///
157 /// * `state` - `If`, `Else`, `Block`, or `Loop` frame type
158 /// * `ty` - Returning type of the frame
159 /// * `idx` - Instruction index
160 pub fn push_frame(&mut self, state: State, ty: Option<BlockType>, idx: usize) {
161 self.frames.push((state, ty, idx))
162 }
163
164 /// Pop frame from the current parsing
165 pub fn pop_frame(&mut self) -> Result<(State, Option<BlockType>, usize)> {
166 match self.frames.pop() {
167 Some(e) => Ok(e),
168 None => Err(Error::other("`pop_frame` on an empty frame stack")),
169 }
170 }
171
172 /// Returns the nodes indexes already parsed in the current state
173 pub fn get_current_parsing(&self) -> Vec<usize> {
174 self.current_parsing.clone()
175 }
176
177 /// Checks if the corrent code parsing has at least one instruction
178 pub fn current_code_is_empty(&self) -> bool {
179 self.current_code_range.start == self.current_code_range.end
180 }
181
182 /// Pushes the current code parsing as a `Node::Code` instance
183 pub fn push_current_code_as_node(&mut self) -> usize {
184 self.push_node_to_current_parsing(Node::Code {
185 range: self.current_code_range.clone(),
186 })
187 }
188
189 /// Resets the current code parsing
190 pub fn reset_code_range_at(&mut self, idx: usize) {
191 self.current_code_range = idx..idx;
192 }
193
194 /// Augmnents current code parsing to include the next instruction
195 /// in the Wasm code
196 pub fn append_instruction_to_current_code(&mut self) {
197 self.current_code_range.end += 1;
198 }
199
200 /// Closes the parsing, creates a `Node::Root` node where the children are the current
201 /// parsed nodes in the current state.
202 ///
203 /// Returns a new Ast instance
204 pub fn finish(mut self) -> Ast {
205 let roots = self.get_current_parsing();
206 let root_id = self.push_node_to_current_parsing(Node::Root(roots));
207 Ast {
208 root: root_id,
209 nodes: self.nodes,
210 ifs: self.ifs,
211 loops: self.loops,
212 }
213 }
214 }