Skip to content

Instantly share code, notes, and snippets.

@jackmott
Created May 17, 2018 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackmott/1834a947b226f0bb20f0f63408d8745f to your computer and use it in GitHub Desktop.
Save jackmott/1834a947b226f0bb20f0f63408d8745f to your computer and use it in GitHub Desktop.
how to ast in rust
//represents an AST - such as Plus(Sin(x),y)
pub enum Op {
Plus ( Vec<Op> ),
Sin ( Vec<Op> ),
X,
Y,
Constant (f32),
Empty
}
// returns the child nodes, if it is an op with children
fn op_has_children(op : Op) -> Option<Vec<Op>> {
match op {
&Op::Plus (c) => Some(c),
&Op::Sin (c) => Some(c),
_ => None
}
}
//adds a random Op to the op we pass in
pub fn add_random_op (op : Op) {
match op_has_children(op) {
Some (mut children) => {
let r = rand::random::<usize>() % children.len();
match children[r] {
Op::Empty => children[r] = get_random_op(),
_ => add_random_op(children[r])
}
}
None => debug_assert!(false)
}
}
//Results in Error:
error[E0507]: cannot move out of indexed content
--> src/apt.rs:30:36
|
30 | _ => add_random_op(children[r])
| ^^^^^^^^^^^ cannot move out of indexed content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment