Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
prozacchiwawa committed Apr 16, 2024
1 parent 0e679db commit d507b5d
Show file tree
Hide file tree
Showing 9 changed files with 646 additions and 364 deletions.
66 changes: 40 additions & 26 deletions src/compiler/fuzz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub trait FuzzTypeParams {
}

#[derive(Clone, Debug)]
pub struct FuzzChoice<Item,Tag> {
pub struct FuzzChoice<Item, Tag> {
pub tag: Tag,
pub atom: Item,
}
Expand All @@ -19,7 +19,7 @@ pub trait ExprModifier {
type Item;

/// Add identified in-progress expansions into waiters.
fn find_waiters(&self, waiters: &mut Vec<FuzzChoice<Self::Item,Self::Tag>>);
fn find_waiters(&self, waiters: &mut Vec<FuzzChoice<Self::Item, Self::Tag>>);

/// Replace a value where it appears in the structure with a new value.
fn replace_node(&self, to_replace: &Self::Item, new_value: Self::Item) -> Self::Item;
Expand All @@ -30,13 +30,20 @@ pub trait ExprModifier {
}

pub trait Rule<FT: FuzzTypeParams> {
fn check(&self, state: &mut FT::State, tag: &FT::Tag, idx: usize, terminate: bool, parents: &[FT::Expr]) -> Result<Option<FT::Expr>, FT::Error>;
fn check(
&self,
state: &mut FT::State,
tag: &FT::Tag,
idx: usize,
terminate: bool,
parents: &[FT::Expr],
) -> Result<Option<FT::Expr>, FT::Error>;
}

pub struct FuzzGenerator<FT: FuzzTypeParams> {
idx: usize,
structure: FT::Expr,
waiting: Vec<FuzzChoice<FT::Expr,FT::Tag>>,
waiting: Vec<FuzzChoice<FT::Expr, FT::Tag>>,
rules: Vec<Rc<dyn Rule<FT>>>,
}

Expand All @@ -52,16 +59,23 @@ impl<FT: FuzzTypeParams> FuzzGenerator<FT> {
}
}

pub fn result<'a>(&'a self) -> &'a FT::Expr { &self.structure }
pub fn result<'a>(&'a self) -> &'a FT::Expr {
&self.structure
}

fn remove_waiting(&mut self, waiting_atom: &FT::Expr) -> Result<(), FT::Error> {
let to_remove_waiting: Vec<usize> = self.waiting.iter().enumerate().filter_map(|(i,w)| {
if w.atom == *waiting_atom {
Some(i)
} else {
None
}
}).collect();
let to_remove_waiting: Vec<usize> = self
.waiting
.iter()
.enumerate()
.filter_map(|(i, w)| {
if w.atom == *waiting_atom {
Some(i)
} else {
None
}
})
.collect();

if to_remove_waiting.is_empty() {
return Err("remove_waiting must succeed".into());
Expand All @@ -71,7 +85,12 @@ impl<FT: FuzzTypeParams> FuzzGenerator<FT> {
Ok(())
}

pub fn expand<R: Rng + Sized>(&mut self, state: &mut FT::State, terminate: bool, rng: &mut R) -> Result<bool, FT::Error> {
pub fn expand<R: Rng + Sized>(
&mut self,
state: &mut FT::State,
terminate: bool,
rng: &mut R,
) -> Result<bool, FT::Error> {
let mut waiting = self.waiting.clone();

while !waiting.is_empty() {
Expand All @@ -81,25 +100,20 @@ impl<FT: FuzzTypeParams> FuzzGenerator<FT> {
let chosen = waiting[waiting_choice].clone();
waiting.remove(waiting_choice);

let heritage =
if let Some(heritage) = self.structure.find_in_structure(&chosen.atom) {
heritage
} else {
return Err("Parity wasn't kept between the structure and waiting list".into());
};
let heritage = if let Some(heritage) = self.structure.find_in_structure(&chosen.atom) {
heritage
} else {
return Err("Parity wasn't kept between the structure and waiting list".into());
};

while !rules.is_empty() {
let rule_choice: usize = rng.gen::<usize>() % rules.len();
let chosen_rule = rules[rule_choice].clone();
rules.remove(rule_choice);

if let Some(res) = chosen_rule.check(
state,
&chosen.tag,
self.idx,
terminate,
&heritage
)? {
if let Some(res) =
chosen_rule.check(state, &chosen.tag, self.idx, terminate, &heritage)?
{
let mut new_waiters = Vec::new();
res.find_waiters(&mut new_waiters);
for n in new_waiters.into_iter() {
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub mod debug;
pub mod dialect;
pub mod evaluate;
pub mod frontend;
#[cfg(any(test, feature="fuzz"))]
#[cfg(any(test, feature = "fuzz"))]
pub mod fuzz;
pub mod gensym;
mod inline;
Expand Down
10 changes: 8 additions & 2 deletions src/compiler/optimize/above22.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,17 @@ impl Optimization for Strategy23 {
let mut rebuilt_helpers = Vec::new();
// XXX Come up with a good way to do this.
#[deprecated]
let enable_merge_disable_for_tests = !opts.filename().starts_with("*cl23-pre-cse-merge-fix");
let enable_merge_disable_for_tests =
!opts.filename().starts_with("*cl23-pre-cse-merge-fix");
for h in p0.helpers.iter() {
if let HelperForm::Defun(inline, d) = h {
eprintln!("cse optimize helper {}", h.to_sexp());
let function_body = cse_optimize_bodyform(&h.loc(), h.name(), enable_merge_disable_for_tests, d.body.borrow())?;
let function_body = cse_optimize_bodyform(
&h.loc(),
h.name(),
enable_merge_disable_for_tests,
d.body.borrow(),
)?;
// Ok we've got a body that is now a let stack.
let new_helper = HelperForm::Defun(
*inline,
Expand Down
55 changes: 31 additions & 24 deletions src/compiler/optimize/cse.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::borrow::Borrow;
use std::cmp::min;
use std::collections::{BTreeMap, HashSet};
use std::fmt::{Error, Formatter, Debug};
use std::fmt::{Debug, Error, Formatter};
use std::rc::Rc;

use crate::compiler::clvm::sha256tree;
Expand Down Expand Up @@ -45,7 +45,15 @@ pub struct CSEDetection {

impl Debug for CSEDetection {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "CSEDetection {{ hash: {:?}, root: {:?}, saturated: {}, subexp: {}, instances: {:?} }}", self.hash, self.root, self.saturated, self.subexp.to_sexp(), self.instances)
write!(
f,
"CSEDetection {{ hash: {:?}, root: {:?}, saturated: {}, subexp: {}, instances: {:?} }}",
self.hash,
self.root,
self.saturated,
self.subexp.to_sexp(),
self.instances
)
}
}

Expand Down Expand Up @@ -516,15 +524,10 @@ impl CSEBindingInfo {
fn detect_merge_into_host_assign(
target: &[BodyformPathArc],
body: &BodyForm,
binding: Rc<Binding>
binding: Rc<Binding>,
) -> bool {
let root_expr =
if let Some(root_expr) =
retrieve_bodyform(
target,
body,
&|b: &BodyForm| { b.clone() }
) {
if let Some(root_expr) = retrieve_bodyform(target, body, &|b: &BodyForm| b.clone()) {
root_expr
} else {
return false;
Expand All @@ -541,8 +544,10 @@ fn detect_merge_into_host_assign(
return false;
}

let used_names: HashSet<Vec<u8>> =
collect_used_names_bodyform(binding.body.borrow()).iter().cloned().collect();
let used_names: HashSet<Vec<u8>> = collect_used_names_bodyform(binding.body.borrow())
.iter()
.cloned()
.collect();

let mut provided_names: Vec<Vec<u8>> = Vec::new();
for b in letdata.bindings.iter() {
Expand All @@ -569,10 +574,13 @@ fn merge_cse_binding(body: &BodyForm, binding: Rc<Binding>) -> BodyForm {
if matches!(kind, LetFormKind::Assign) {
let mut new_bindings = letdata.bindings.clone();
new_bindings.push(binding.clone());
return BodyForm::Let(kind.clone(), Box::new(LetData {
bindings: new_bindings,
.. *letdata.clone()
}));
return BodyForm::Let(
kind.clone(),
Box::new(LetData {
bindings: new_bindings,
..*letdata.clone()
}),
);
}
}

Expand Down Expand Up @@ -749,14 +757,15 @@ pub fn cse_optimize_bodyform(
// of let forms.
// (2) it uses bindings from that assign form.
let rc_binding = Rc::new(site.binding.clone());
let should_merge = allow_merge && detect_merge_into_host_assign(
target_path,
&function_body,
rc_binding.clone(),
);
let should_merge = allow_merge
&& detect_merge_into_host_assign(
target_path,
&function_body,
rc_binding.clone(),
);
BindingStackEntry {
binding: rc_binding,
merge: should_merge
merge: should_merge,
}
})
.collect();
Expand Down Expand Up @@ -837,9 +846,7 @@ pub fn cse_optimize_bodyform(
loc: function_body.loc(),
kw: None,
inline_hint: Some(LetFormInlineHint::NonInline(loc.clone())),
bindings: not_to_merge.iter().map(|b| {
b.binding.clone()
}).collect(),
bindings: not_to_merge.iter().map(|b| b.binding.clone()).collect(),
body: Rc::new(output_body.clone()),
}),
)
Expand Down
52 changes: 19 additions & 33 deletions src/compiler/sexp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use serde::Serialize;
use crate::classic::clvm::__type_compatibility__::bi_one;
use crate::classic::clvm::__type_compatibility__::{bi_zero, Bytes, BytesFromType};
use crate::classic::clvm::casts::{bigint_from_bytes, bigint_to_bytes_clvm, TConvertOption};
#[cfg(any(test,feature="fuzz"))]
#[cfg(any(test, feature = "fuzz"))]
use crate::compiler::fuzz::{ExprModifier, FuzzChoice};
use crate::compiler::prims::prims;
use crate::compiler::srcloc::Srcloc;
Expand Down Expand Up @@ -1232,18 +1232,10 @@ fn find_in_structure_inner(
) -> bool {
if let SExp::Cons(_, a, b) = structure.borrow() {
parents.push(structure.clone());
if find_in_structure_inner(
parents,
a.clone(),
target,
) {
if find_in_structure_inner(parents, a.clone(), target) {
return true;
}
if find_in_structure_inner(
parents,
b.clone(),
target,
) {
if find_in_structure_inner(parents, b.clone(), target) {
return true;
}

Expand All @@ -1253,28 +1245,33 @@ fn find_in_structure_inner(
structure == *target
}

#[cfg(any(test,feature="fuzz"))]
#[cfg(any(test, feature = "fuzz"))]
impl ExprModifier for Rc<SExp> {
type Item = Self;
type Tag = Vec<u8>;

fn find_waiters(
&self,
waiters: &mut Vec<FuzzChoice<Self::Item,Self::Tag>>,
) {
fn find_waiters(&self, waiters: &mut Vec<FuzzChoice<Self::Item, Self::Tag>>) {
match self.borrow() {
SExp::Cons(_, a, b) => {
a.find_waiters(waiters);
b.find_waiters(waiters);
}
SExp::Atom(_, a) => {
if a.starts_with(b"${") && a.ends_with(b"}") {
let mut found_colon = a.iter().enumerate().filter_map(|(i,c)| if *c == b':' { Some(i) } else { None });
let mut found_colon =
a.iter()
.enumerate()
.filter_map(|(i, c)| if *c == b':' { Some(i) } else { None });
if let Some(c_idx) = found_colon.next() {
let tag_str: Vec<u8> = a.iter().take(a.len() - 1).skip(c_idx + 1).copied().collect();
let tag_str: Vec<u8> = a
.iter()
.take(a.len() - 1)
.skip(c_idx + 1)
.copied()
.collect();
waiters.push(FuzzChoice {
tag: tag_str,
atom: self.clone()
atom: self.clone(),
});
}
}
Expand All @@ -1283,11 +1280,7 @@ impl ExprModifier for Rc<SExp> {
}
}

fn replace_node(
&self,
to_replace: &Self::Item,
new_value: Self::Item,
) -> Self::Item {
fn replace_node(&self, to_replace: &Self::Item, new_value: Self::Item) -> Self::Item {
if let SExp::Cons(l, a, b) = self.borrow() {
let new_a = a.replace_node(to_replace, new_value.clone());
let new_b = b.replace_node(to_replace, new_value.clone());
Expand All @@ -1303,16 +1296,9 @@ impl ExprModifier for Rc<SExp> {
self.clone()
}

fn find_in_structure(
&self,
target: &Self::Item,
) -> Option<Vec<Self::Item>> {
fn find_in_structure(&self, target: &Self::Item) -> Option<Vec<Self::Item>> {
let mut parents = Vec::new();
if find_in_structure_inner(
&mut parents,
self.clone(),
target,
) {
if find_in_structure_inner(&mut parents, self.clone(), target) {
Some(parents)
} else {
None
Expand Down
12 changes: 6 additions & 6 deletions src/tests/classic/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2361,8 +2361,8 @@ fn test_assign_rename_tricky() {
program.clone(),
"(11)".to_string(),
])
.trim()
.to_string();
.trim()
.to_string();
assert_eq!(run_result_11, "506");

let run_result_41 = do_basic_brun(&vec!["brun".to_string(), program, "(41)".to_string()])
Expand All @@ -2386,8 +2386,8 @@ fn test_cse_breakage_example() {
program.clone(),
"(())".to_string(),
])
.trim()
.to_string();
.trim()
.to_string();
assert_eq!(run_result_11, "((a 3) (a 3) (a 3))");
}

Expand All @@ -2406,8 +2406,8 @@ fn test_cse_breakage_example_letstar() {
program.clone(),
"(())".to_string(),
])
.trim()
.to_string();
.trim()
.to_string();
assert_eq!(run_result_11, "((a 3) (a 3) (a 3))");
}

Expand Down
Loading

0 comments on commit d507b5d

Please sign in to comment.