Skip to content

Instantly share code, notes, and snippets.

@gwpl
Last active January 8, 2024 12:38
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 gwpl/7ec106933a0024d9daf4b24b9d054b38 to your computer and use it in GitHub Desktop.
Save gwpl/7ec106933a0024d9daf4b24b9d054b38 to your computer and use it in GitHub Desktop.
Micro example of proptest for micro AST | as reading https://proptest-rs.github.io/proptest/proptest/tutorial/index.html "Proptest from the Bottom Up"
Maybe some inspiration (proptesting , not fuzzing, per say, still maybe helpful/inspiring):
Micro example of proptest for micro AST | as reading https://proptest-rs.github.io/proptest/proptest/tutorial/index.html "Proptest from the Bottom Up"
```rust
use std::fmt;
use proptest::prelude::*;
// Definition of Micro Language AST Grammar
#[derive(Debug)]
enum Expr {
Add(Box<Expr>, Box<Expr>),
Int(i32),
}
// Definiotions as `proptest-derive` failed on stable...
impl Arbitrary for Expr {
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
let leaf = any::<i32>().prop_map(Expr::Int).boxed();
leaf.prop_recursive(8, 256, 10, |inner| {
(inner.clone(), inner)
.prop_map(|(lhs, rhs)| Expr::Add(Box::new(lhs), Box::new(rhs)))
.boxed()
}).boxed()
}
}
// probably could be for bigger grammar solved with some nice "derive".
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Expr::Add(lhs, rhs) => write!(f, "({} + {})", lhs, rhs),
Expr::Int(i) => write!(f, "{}", i),
}
}
}
// Let's generate example bunch of ASTs and print them:
fn main() {
proptest!(|(expr in any::<Expr>())| {
println!("{}", expr);
});
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment