Compare commits

...

2 commits

2 changed files with 82 additions and 2 deletions

View file

@ -1,29 +1,107 @@
use rand::Rng;
use rand_distr::Distribution;
use crate::params::Params; use crate::params::Params;
use crate::ast::{ use crate::ast::{
Expr,
Statement,
Quantifier, Quantifier,
BaseType, BaseType,
GlobalBlock, GlobalBlock,
Block, Block,
Literal, Literal,
Declaration, Declaration,
DeclarationBuilder,
Variable, Variable,
VariableBuilder,
BinaryOperator, BinaryOperator,
}; };
pub struct AstBuilder { pub struct AstBuilder {
params: Params, params: Params,
ast: GlobalBlock, ast: GlobalBlock,
name_counter: u64,
rng: rand::rngs::ThreadRng,
} }
impl AstBuilder { impl AstBuilder {
pub fn from(params: Params) -> Self { pub fn from(params: Params) -> Self {
Self { Self {
params, params,
rng: rand::thread_rng(),
name_counter: 0,
ast: GlobalBlock::default(), ast: GlobalBlock::default(),
} }
} }
pub fn generate(&self) { pub fn generate(&mut self) {
let mut p: f64;
loop {
p = self.rng.gen();
if p < self.params.global_flow.end_generation {
break;
} else {
let decl = self.gen_decl();
self.ast.push(decl);
}
}
}
fn gen_decl(&mut self) -> Box<dyn Statement> {
let t = BaseType::Int;
let v = self.gen_variable_quantified(t, Quantifier::Const);
Box::new(
DeclarationBuilder::default()
.variable(v)
.assn(self.gen_literal(t))
.build()
.unwrap()
)
}
fn gen_variable(&mut self, t: BaseType) -> Variable {
VariableBuilder::default()
.type_(t)
.name(self.gen_name())
.quantifer(Quantifier::Var)
.build()
.unwrap()
}
fn gen_variable_quantified(&mut self, t: BaseType, q: Quantifier) -> Variable {
VariableBuilder::default()
.type_(t)
.name(self.gen_name())
.quantifer(q)
.build()
.unwrap()
}
fn gen_name(&mut self) -> String {
let s = format!("_{}", self.name_counter);
self.name_counter += 1;
s
}
//fn gen_expr(&mut self, type_: BaseType) -> Box<dyn Expr> {
//}
fn gen_literal(&mut self, t: BaseType) -> Literal {
match t {
BaseType::Int => {
let r = rand_distr::Beta::new(0.5, 0.5).unwrap();
let i: i32 = (r.sample(&mut self.rng) * (i32::MAX as f64)) as i32;
Literal::Int(i)
}
BaseType::Real => Literal::Real(1.0),
BaseType::Never => panic!("Attempted to generate literal of type Never"),
BaseType::Unset => panic!("Attempted to generate literal of type Unset"),
}
} }
} }

View file

@ -20,7 +20,9 @@ struct Args {
fn main() { fn main() {
let args = Args::parse(); let args = Args::parse();
let params = Params::parse(&args.config); let params = Params::parse(&args.config);
let builder = AstBuilder::from(params); let mut builder = AstBuilder::from(params);
builder.generate();
println!("{}", builder.to_string()); println!("{}", builder.to_string());
} }